CaMa development view on the survival tab; governance trains any scenario in the background

This commit is contained in:
rockdrigo
2026-11-21 03:28:13 -06:00
parent cc802cbb57
commit c5cbaaab13
13 changed files with 544 additions and 20 deletions
@@ -0,0 +1,52 @@
<h2 id="desarrollo-titulo">Desarrollo del modelo</h2>
@let l = lectura();
@switch (l.tipo) {
@case ('cargando') { <p role="status">Cargando el desarrollo del modelo…</p> }
@case ('no-disponible') {
<p role="status">La versión en producción no trae el desarrollo del modelo. Entrena una nueva versión en Gobernanza para generarlo.</p>
}
@case ('error') { <p role="alert">No se pudo cargar el desarrollo del modelo. Intenta nuevamente más tarde.</p> }
@case ('listo') {
<p class="lead">
Depuración de variables, balanceo, regresión logística y red bayesiana, bootstrap, curvas por subgrupo y factores de
riesgo, calculados sobre las {{ l.datos.desarrollo.n }} pacientes de la cohorte (versión {{ l.datos.modelo.version }}).
</p>
@if (l.datos.desarrollo.variables_no_disponibles.length) {
<p class="note">
El hospital todavía no reporta: {{ l.datos.desarrollo.variables_no_disponibles.join(', ') }}. Entran como «Desconocido»
y no explican nada hasta que existan.
</p>
}
<ul class="stages" aria-label="Etapas del desarrollo">
@for (e of l.datos.desarrollo.etapas; track e.etapa) {
<li [class.failed]="e.estado === 'error'">Etapa {{ e.etapa }}: {{ e.estado === 'error' ? 'con error' : 'completa' }}</li>
}
</ul>
@for (error of errores(l.datos); track error[0]) {
<p class="note" role="alert">Etapa {{ error[0] }} no pudo calcularse con esta cohorte: {{ error[1] }}</p>
}
@for (t of tablas(l.datos); track t.id) {
<details>
<summary>{{ t.titulo }} ({{ t.filas.length }})</summary>
<div class="scroll" role="region" [attr.aria-label]="t.titulo + ', tabla desplazable'" tabindex="0">
<table>
<thead><tr>@for (c of t.columnas; track c) { <th scope="col">{{ c }}</th> }</tr></thead>
<tbody>
@for (fila of t.filas; track $index) {
<tr>@for (c of t.columnas; track c) { <td>{{ celda(fila[c]) }}</td> }</tr>
}
</tbody>
</table>
</div>
</details>
}
@if (figuras(l.datos).length) {
<h3>Figuras</h3>
<div class="figures">
@for (f of figuras(l.datos); track f.id) {
<figure><img [src]="f.src" [alt]="f.id.replaceAll('_', ' ')" loading="lazy" /><figcaption>{{ f.id.replaceAll('_', ' ') }}</figcaption></figure>
}
</div>
}
}
}
@@ -0,0 +1,14 @@
:host { display: block; margin-top: 2rem; }
.lead, .note { max-width: 70ch; }
.note { color: var(--mat-sys-on-surface-variant, #444); }
.stages { display: flex; flex-wrap: wrap; gap: 0.5rem 1.5rem; padding: 0; list-style: none; }
.stages .failed { font-weight: 600; }
details { margin: 0.5rem 0; }
summary { cursor: pointer; font-weight: 600; }
.scroll { overflow-x: auto; max-height: 26rem; }
table { border-collapse: collapse; font-size: 0.85rem; }
th, td { padding: 0.25rem 0.6rem; text-align: left; border-bottom: 1px solid var(--mat-sys-outline-variant, #ccc); white-space: nowrap; }
.figures { display: grid; grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr)); gap: 1rem; }
figure { margin: 0; }
img { max-width: 100%; height: auto; background: #fff; }
figcaption { font-size: 0.8rem; text-transform: capitalize; }
@@ -0,0 +1,58 @@
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, map, Observable, of, throwError } from 'rxjs';
// The development results of CaMa's model in production, `GET /cama/modelo/desarrollo`: what the SEER stages found over
// the cohort (variables kept, odds ratios, Bayesian network arcs, risk factors, subgroup curves) as tables, and their
// figures. They describe the cohort, never a patient. A 404 is "no version with a development record yet".
export type FilaDeTabla = Record<string, string | number | boolean | null>;
export interface RegistroDesarrollo {
n: number;
etapas: { etapa: string; estado: string; segundos: number }[];
errores: Record<string, string>;
variables_no_disponibles: string[];
tablas: Record<string, FilaDeTabla[]>;
figuras: Record<string, string>;
}
export interface RespuestaDesarrollo {
simulado: boolean;
modelo: { nombre: string; version: string; mlflow_run_id: string };
desarrollo: RegistroDesarrollo;
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
function invalid(): never {
throw new Error('Respuesta de desarrollo del modelo inválida');
}
/** Validate at the boundary: the record's shapes, so a partial answer never reaches the page. */
export function respuestaDesarrollo(v: unknown): RespuestaDesarrollo {
if (!record(v) || !record(v['modelo']) || !record(v['desarrollo'])) invalid();
const m = v['modelo'] as Record<string, unknown>, d = v['desarrollo'] as Record<string, unknown>;
if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid();
if (typeof d['n'] !== 'number' || !Array.isArray(d['etapas']) || !record(d['errores']) || !Array.isArray(d['variables_no_disponibles'])
|| !record(d['tablas']) || !record(d['figuras'])) invalid();
for (const e of d['etapas'] as unknown[]) if (!record(e) || !text(e['etapa']) || !text(e['estado'])) invalid();
for (const rows of Object.values(d['tablas'] as Record<string, unknown>)) if (!Array.isArray(rows) || !rows.every(record)) invalid();
for (const png of Object.values(d['figuras'] as Record<string, unknown>)) if (!text(png) || !/^[A-Za-z0-9+/=]+$/.test(png)) invalid();
return {
simulado: v['simulado'] === true,
modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string },
desarrollo: d as unknown as RegistroDesarrollo,
};
}
@Injectable({ providedIn: 'root' })
export class CamaDesarrolloService {
private readonly http = inject(HttpClient);
/** The production version's development record, or `null` when there is none (a 404). */
desarrollo(): Observable<RespuestaDesarrollo | null> {
return this.http.get<unknown>('/cama/modelo/desarrollo').pipe(
map(respuestaDesarrollo),
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
);
}
}
@@ -0,0 +1,97 @@
// Covers CaMa's development view: the boundary validation of `GET /cama/modelo/desarrollo` (a malformed record never
// reaches the page) and the component's states, its tables, its figures and the notice of what the hospital does not
// report yet. Fixtures: `registroEjemplo`, a record like a training run publishes.
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { CamaDesarrollo } from './cama-desarrollo';
import { respuestaDesarrollo } from './cama-desarrollo.service';
function registroEjemplo(): any {
return {
simulado: true,
modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' },
desarrollo: {
n: 500, etapas: [{ etapa: '01', estado: 'ok', segundos: 0 }, { etapa: '05', estado: 'error', segundos: 0 }],
errores: { '05': 'ValueError: sin subgrupos' }, variables_no_disponibles: ['Estadio_cat', 'Radioterapia_cat'],
tablas: { or_lr_balanceada: [{ indice: 'Grado_G3', OR: 2.5, p: 0.0123456 }], hbn_arcos: [] },
figuras: { sens_esp_edad: 'iVBORw0KGgo=' },
},
};
}
describe('Desarrollo CaMa: respuesta', () => {
it('accepts a record as published', () => {
expect(respuestaDesarrollo(registroEjemplo()).desarrollo.n).toBe(500);
});
// Fails if a record that would break the page (or inject markup through a figure) is accepted.
it.each([
['no model version', (d: any) => { delete d.modelo.version; }],
['a table that is not rows', (d: any) => { d.desarrollo.tablas.hbn_arcos = 'x'; }],
['a figure that is not base64', (d: any) => { d.desarrollo.figuras.sens_esp_edad = '" onerror="x'; }],
['no stages', (d: any) => { delete d.desarrollo.etapas; }],
])('rejects %s', (_, estropear) => {
const d = registroEjemplo();
estropear(d);
expect(() => respuestaDesarrollo(d)).toThrow('Respuesta de desarrollo del modelo inválida');
});
});
describe('Desarrollo CaMa: componente', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
const montar = (active: boolean) => {
const f = TestBed.createComponent(CamaDesarrollo);
f.componentRef.setInput('active', active);
f.detectChanges();
return f;
};
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
// Fails if the view asks before it is shown or asks again.
it('asks once, the first time it is shown', () => {
const f = montar(false);
http.expectNone('/cama/modelo/desarrollo');
f.componentRef.setInput('active', true);
f.detectChanges();
http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo());
f.componentRef.setInput('active', false);
f.detectChanges();
f.componentRef.setInput('active', true);
f.detectChanges();
http.expectNone('/cama/modelo/desarrollo');
});
// Fails if a table, a figure, a failed stage or the missing-variables notice stops being shown.
it('shows the tables that have rows, the figures, the failed stage and what the hospital does not report', () => {
const f = montar(true);
http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo());
f.detectChanges();
const el = f.nativeElement as HTMLElement, t = texto(f);
expect(t).toContain('Razones de momios de la regresión logística (1)');
expect(t).not.toContain('Arcos de la red bayesiana');
expect(t).toContain('0.01235');
expect(t).toContain('Estadio_cat, Radioterapia_cat');
expect(t).toContain('Etapa 05 no pudo calcularse');
expect(el.querySelector('img')!.getAttribute('src')).toBe('data:image/png;base64,iVBORw0KGgo=');
});
// Fails if no version with a record is shown as an error, or a failure as a page.
it('says there is no record on a 404 and fails closed on an error', () => {
const sin = montar(true);
http.expectOne('/cama/modelo/desarrollo').flush({ error: 'x' }, { status: 404, statusText: 'Not Found' });
sin.detectChanges();
expect(texto(sin)).toContain('no trae el desarrollo del modelo');
const roto = montar(true);
http.expectOne('/cama/modelo/desarrollo').flush({ desarrollo: {} });
roto.detectChanges();
expect(texto(roto)).toContain('No se pudo cargar el desarrollo del modelo');
});
});
@@ -0,0 +1,73 @@
import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { CamaDesarrolloService, FilaDeTabla, RespuestaDesarrollo } from './cama-desarrollo.service';
type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaDesarrollo };
/** Names the tables are shown under, in the order they are shown. */
export const TABLAS: [string, string][] = [
['factores_riesgo', 'Factores de riesgo (cuatro criterios)'],
['factores_riesgo_variables', 'Resumen de factores de riesgo por variable'],
['or_lr_balanceada', 'Razones de momios de la regresión logística'],
['hbn_arcos', 'Arcos de la red bayesiana'],
['metricas_diferenciacion', 'Métricas de diferenciación (LR y HBN)'],
['auc_validacion_interna', 'AUC de validación interna'],
['auc_bootstrap', 'AUC por réplica bootstrap'],
['seleccion_bootstrap', 'Frecuencia de selección en el bootstrap'],
['subgrupos_weibull', 'Subgrupos: Kaplan-Meier y Weibull fraccional'],
['subgrupos_puntos', 'Subgrupos: supervivencia de LR y HBN'],
['prueba_edad', 'Prueba de la edad continua contra la categorizada'],
['cortes_edad', 'Comparación de cortes de edad'],
['cortes_tumor', 'Comparación de cortes de tamaño tumoral'],
['pesos_combinacion', 'Pesos de la combinación LR y HBN'],
];
/**
* How CaMa's model was developed, from the production version's record: the SEER stages' tables and figures over the
* cohort. Population results, never a patient's. Loads once, the first time the tab is shown.
*/
@Component({
selector: 'app-cama-desarrollo',
templateUrl: './cama-desarrollo.html',
styleUrl: './cama-desarrollo.scss',
})
export class CamaDesarrollo {
readonly active = input(false);
private readonly service = inject(CamaDesarrolloService);
private readonly destroy = inject(DestroyRef);
readonly lectura = signal<Lectura>({ tipo: 'cargando' });
private pedido = false;
constructor() {
effect(() => {
if (!this.active() || this.pedido) return;
this.pedido = true;
this.service.desarrollo().pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }),
error: () => this.lectura.set({ tipo: 'error' }),
});
});
}
/** The tables the record holds, in display order, with their rows' columns. */
tablas(datos: RespuestaDesarrollo): { id: string; titulo: string; columnas: string[]; filas: FilaDeTabla[] }[] {
return TABLAS.filter(([id]) => datos.desarrollo.tablas[id]?.length)
.map(([id, titulo]) => {
const filas = datos.desarrollo.tablas[id];
return { id, titulo, columnas: Object.keys(filas[0]), filas };
});
}
figuras(datos: RespuestaDesarrollo): { id: string; src: string }[] {
return Object.entries(datos.desarrollo.figuras).map(([id, png]) => ({ id, src: `data:image/png;base64,${png}` }));
}
errores(datos: RespuestaDesarrollo): [string, string][] {
return Object.entries(datos.desarrollo.errores);
}
celda(valor: string | number | boolean | null): string {
if (valor === null) return '';
return typeof valor === 'number' && !Number.isInteger(valor) ? valor.toPrecision(4) : String(valor);
}
}
@@ -141,6 +141,7 @@
@if (conSupervivencia) {
<section id="panel-supervivencia" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-supervivencia" tabindex="0" [hidden]="activeSection() !== 'supervivencia'">
<app-cama-supervivencia [active]="activeSection() === 'supervivencia'" [tema]="tema" />
<app-cama-desarrollo [active]="activeSection() === 'supervivencia'" />
</section>
}
@@ -32,6 +32,7 @@ import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { CamaSupervivencia } from './cama-supervivencia/cama-supervivencia';
import { CamaDesarrollo } from './cama-desarrollo/cama-desarrollo';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
@@ -54,7 +55,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia, CamaDesarrollo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})