diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html deleted file mode 100644 index e488cbb..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html +++ /dev/null @@ -1,52 +0,0 @@ -

Desarrollo del modelo

-@let l = lectura(); -@switch (l.tipo) { - @case ('cargando') {

Cargando el desarrollo del modelo…

} - @case ('no-disponible') { -

La versión en producción no trae el desarrollo del modelo. Entrena una nueva versión en Gobernanza para generarlo.

- } - @case ('error') {

No se pudo cargar el desarrollo del modelo. Intenta nuevamente más tarde.

} - @case ('listo') { -

- 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 }}). -

- @if (l.datos.desarrollo.variables_no_disponibles.length) { -

- El hospital todavía no reporta: {{ l.datos.desarrollo.variables_no_disponibles.join(', ') }}. Entran como «Desconocido» - y no explican nada hasta que existan. -

- } - - @for (error of errores(l.datos); track error[0]) { - - } - @for (t of tablas(l.datos); track t.id) { -
- {{ t.titulo }} ({{ t.filas.length }}) -
- - @for (c of t.columnas; track c) { } - - @for (fila of t.filas; track $index) { - @for (c of t.columnas; track c) { } - } - -
{{ c }}
{{ celda(fila[c]) }}
-
-
- } - @if (figuras(l.datos).length) { -

Figuras

-
- @for (f of figuras(l.datos); track f.id) { -
{{ f.id.replaceAll('_', ' ') }}
- } -
- } - } -} diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss deleted file mode 100644 index f1b291e..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss +++ /dev/null @@ -1,14 +0,0 @@ -: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; } diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts deleted file mode 100644 index 49f1f62..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts +++ /dev/null @@ -1,61 +0,0 @@ -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; -export interface TablaDesarrollo { columnas: string[]; filas: FilaDeTabla[]; } -export interface RegistroDesarrollo { - n: number; - etapas: { etapa: string; estado: string; segundos: number }[]; - errores: Record; - variables_no_disponibles: string[]; - tablas: Record; - figuras: Record; -} -export interface RespuestaDesarrollo { - simulado: boolean; - modelo: { nombre: string; version: string; mlflow_run_id: string }; - desarrollo: RegistroDesarrollo; -} - -const record = (v: unknown): v is Record => !!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, d = v['desarrollo'] as Record; - 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 t of Object.values(d['tablas'] as Record)) { - if (!record(t) || !Array.isArray(t['columnas']) || !t['columnas'].every(text) || !Array.isArray(t['filas']) || !t['filas'].every(record)) invalid(); - } - for (const png of Object.values(d['figuras'] as Record)) 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 { - return this.http.get('/cama/modelo/desarrollo').pipe( - map(respuestaDesarrollo), - catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), - ); - } -} diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts deleted file mode 100644 index 3e83872..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -// 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: { columnas: ['indice', 'OR', 'p'], filas: [{ indice: 'Grado_G3', OR: 2.5, p: 0.0123456 }] }, hbn_arcos: { columnas: [], filas: [] } }, - 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 = { columnas: ['a'], filas: '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) => (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([...el.querySelectorAll('th')].map(th => th.textContent!.trim())).toEqual(['indice', 'OR', 'p']); - 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'); - }); -}); diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts deleted file mode 100644 index 9bc7e4b..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts +++ /dev/null @@ -1,73 +0,0 @@ -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({ 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]?.filas.length) - .map(([id, titulo]) => { - const { columnas, filas } = datos.desarrollo.tablas[id]; - return { id, titulo, columnas, 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); - } -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts deleted file mode 100644 index e9f088d..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { PlotlyFigure, Tema } from '../indicadores.models'; -import { CurvasSupervivencia, SerieDeSupervivencia } from './cama-supervivencia.service'; - -/** The clinicians' wording of the chart: what the model's run published (`[config.etiquetas]`), and these defaults for - * a label it leaves out. The labels are settings, not code, so they can be defined with the clinicians. */ -export const ETIQUETAS_PREDETERMINADAS: Readonly> = { - titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor', - eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia', - km_crudo: 'Kaplan-Meier (observada)', km_ajustada: 'Kaplan-Meier ajustada por covariables', - weibull: 'Weibull ajustada', weibull_fraccional: 'Weibull fraccional ajustada', - puntos: 'Modelo (LR + red bayesiana) con IC 95 %', LR: 'Regresión logística', HBN: 'Red bayesiana', COMB: 'Modelo combinado', -}; - -export const COLORES = { km_crudo: '#9aa5b1', km_ajustada: '#3d4852', weibull: '#e0a060', fraccional: '#d1495b', modelo: '#6a3d9a', lr: '#1f77b4', hbn: '#2a9d8f' } as const; - -export const etiquetaDe = (curvas: CurvasSupervivencia, clave: string) => curvas.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave; - -function puntos(curvas: CurvasSupervivencia, serie: SerieDeSupervivencia, nombre: string, color: string, visible: true | 'legendonly', tamano: number): Record { - const h = curvas.horizons_months; - return { - type: 'scatter', mode: 'markers', name: nombre, x: h, y: serie.S, visible, legendgroup: nombre, - marker: { symbol: 'diamond', size: tamano, color, line: { color: 'white', width: 1 } }, - error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 1.8, width: 5, - array: serie.high.map((hi, i) => hi - serie.S[i]), arrayminus: serie.S.map((s, i) => s - serie.low[i]) }, - customdata: serie.low.map((lo, i) => [lo, serie.high[i]]), - hovertemplate: `${nombre}
%{x} meses: %{y:.1%}
IC 95 %: %{customdata[0]:.1%} a %{customdata[1]:.1%}`, - }; -} - -/** The figure of the model's results: the cohort's Kaplan-Meier with its band, the covariate-adjusted curve, the fitted - * Weibull curves, and the model's survival at each horizon as diamonds with their bootstrap interval. */ -export function figuraSupervivencia(curvas: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure { - const km = curvas.km, ajustada = curvas.km_adjusted, t = (clave: string) => etiquetaDe(curvas, clave); - const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)'; - const todos = [...km.low, ...ajustada.S, ...curvas.weibull_fractional.S, ...curvas.points.COMB.low]; - const minimo = Math.max(0, Math.min(...todos) - 0.03); - const data: Record[] = [ - { type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' }, - { type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: 'rgba(154,165,177,.35)', line: { width: 0, shape: 'hv' }, - name: `${t('km_crudo')}, IC 95 %`, hoverinfo: 'skip', legendgroup: 'km' }, - { type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km_crudo, width: 1.4, dash: 'dot', shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km', - hovertemplate: '%{x} meses: %{y:.1%}' + t('km_crudo') + '' }, - { type: 'scatter', mode: 'lines', x: ajustada.months, y: ajustada.S, line: { color: COLORES.km_ajustada, width: 2, shape: 'hv' }, name: t('km_ajustada'), - hovertemplate: '%{x} meses: %{y:.1%}' + t('km_ajustada') + '' }, - { type: 'scatter', mode: 'lines', x: curvas.weibull.t, y: curvas.weibull.S, line: { color: COLORES.weibull, width: 2, dash: 'dash' }, name: t('weibull'), visible: 'legendonly' }, - { type: 'scatter', mode: 'lines', x: curvas.weibull_fractional.t, y: curvas.weibull_fractional.S, line: { color: COLORES.fraccional, width: 2.6 }, name: t('weibull_fraccional'), - hovertemplate: '%{x:.1f} meses: %{y:.1%}' + t('weibull_fraccional') + '' }, - puntos(curvas, curvas.points.LR, t('LR'), COLORES.lr, 'legendonly', 9), - puntos(curvas, curvas.points.HBN, t('HBN'), COLORES.hbn, 'legendonly', 9), - puntos(curvas, curvas.points.COMB, t('puntos'), COLORES.modelo, true, 12), - ]; - const layout: Record = { - title: { text: `${t('titulo')} (n = ${curvas.n.toLocaleString('es-MX')})`, x: 0, xanchor: 'left', font: { size: 16, color: texto } }, - paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto }, - xaxis: { title: { text: t('eje_x') }, range: [0, curvas.months_max + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false }, - yaxis: { title: { text: t('eje_y') }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false }, - legend: { orientation: 'h', y: -0.22, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 110 }, hovermode: 'closest', - }; - return { data, layout, config: { responsive: true, displaylogo: false } }; -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html deleted file mode 100644 index c15de72..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html +++ /dev/null @@ -1,39 +0,0 @@ -

Supervivencia

-@let l = lectura(); -@switch (l.tipo) { - @case ('cargando') {

Cargando resultados del modelo…

} - @case ('no-disponible') { -

Todavía no hay un modelo de supervivencia en producción. Cuando se entrene y se promueva en Gobernanza, sus resultados aparecerán aquí.

- } - @case ('error') {

No se pudieron cargar los resultados del modelo. Intenta nuevamente más tarde.

} - @case ('listo') { - @let c = l.datos.curvas; - @if (l.datos.simulado) {

Información simulada · Entorno DEV · Sin evaluación clínica

} - - @if (figura(); as figure) { - - } -
- - - - - @for (fila of filas(l.datos); track fila.meses) { - - - - - - } - -
{{ etiquetaDe(c, 'puntos') }}
Meses desde el reporteSupervivencia (%)IC 95 % (%)
{{ fila.meses }}{{ fila.S | number:'1.1-1' }} %{{ fila.low | number:'1.1-1' }} % – {{ fila.high | number:'1.1-1' }} %
-
- @if (c.etiquetas['nota']; as nota) {

{{ nota }}

} - } -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss deleted file mode 100644 index 18fafb7..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss +++ /dev/null @@ -1,11 +0,0 @@ -:host { display: block; padding: 1rem 0; } -h2 { font-size: 1.25rem; margin: 0 0 .75rem; } -.simulated-label { font-weight: 600; margin: 0 0 .75rem; } -.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: .5rem 1.25rem; margin: 0 0 1rem; - div { display: flex; flex-direction: column; } dt { font-size: .8rem; opacity: .8; } dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; } } -.points-scroll { overflow-x: auto; margin-top: 1rem; &:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } } -table { border-collapse: collapse; min-width: 22rem; } -caption { text-align: left; font-weight: 600; padding-bottom: .4rem; } -th, td { padding: .4rem .75rem; border-bottom: 1px solid rgba(128, 128, 128, .35); text-align: left; } -.percentage, .interval { font-variant-numeric: tabular-nums; } -.note { margin-top: 1rem; font-size: .85rem; opacity: .85; } diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts deleted file mode 100644 index 6613465..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { HttpClient, HttpErrorResponse } from '@angular/common/http'; -import { inject, Injectable } from '@angular/core'; -import { catchError, map, Observable, of, throwError } from 'rxjs'; - -// The survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the -// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the -// version they come from and says when the data are simulated. A 404 is "no model in production yet". -export interface SerieDeSupervivencia { S: number[]; low: number[]; high: number[]; } -export interface CurvasSupervivencia { - n: number; events: number; median_follow_up_months: number; - horizons_months: number[]; months_max: number; bootstrap_replicas: number; - km: { months: number[]; S: number[]; low: number[]; high: number[] }; - km_adjusted: { months: number[]; S: number[] }; - weibull: { t: number[]; S: number[] }; - weibull_fractional: { t: number[]; S: number[] }; - points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia }; - etiquetas: Record; -} -export interface RespuestaCurvas { - simulado: boolean; - modelo: { nombre: string; version: string; mlflow_run_id: string }; - curvas: CurvasSupervivencia; -} - -const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); -const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); -const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length); -const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1); -const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; - -function invalid(): never { - throw new Error('Respuesta de curvas de supervivencia inválida'); -} - -function serie(v: unknown, horizons: number): SerieDeSupervivencia { - if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid(); - const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[]; - if (low.some((l, i) => l > high[i])) invalid(); - return { S: s, low, high }; -} - -/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */ -export function respuestaCurvas(v: unknown): RespuestaCurvas { - if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid(); - const m = v['modelo'] as Record, c = v['curvas'] as Record; - if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid(); - const horizons = c['horizons_months']; - if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events']) - || !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid(); - const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points']; - if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length) - || !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid(); - if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid(); - for (const curve of [weibull, fractional]) { - if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid(); - } - if (!record(points)) invalid(); - const p = points as Record, h = (horizons as number[]).length; - const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record : {}; - 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 }, - curvas: { - n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number, - horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number, - km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'], - weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'], - points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas, - }, - }; -} - -@Injectable({ providedIn: 'root' }) -export class CamaSupervivenciaService { - private readonly http = inject(HttpClient); - - /** The production version's curves, or `null` when there is none (a 404). */ - curvas(): Observable { - return this.http.get('/cama/modelo/curvas').pipe( - map(respuestaCurvas), - catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), - ); - } -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts deleted file mode 100644 index 539f2c8..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts +++ /dev/null @@ -1,157 +0,0 @@ -// Covers CaMa's survival tab: the boundary validation of `GET /cama/modelo/curvas` (a malformed record never draws a partial -// curve), the figure built from the record (the model's diamonds at 6, 12 and 18 months with their interval, the curves, -// the labels from the model's settings), and the component's states and table. Fixtures: `curvasEjemplo`, a record like a -// training run publishes; a stub Plotly runtime, so the chart is not drawn for real. -import { provideHttpClient } from '@angular/common/http'; -import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { TestBed } from '@angular/core/testing'; -import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; -import { CamaSupervivencia } from './cama-supervivencia'; -import { respuestaCurvas } from './cama-supervivencia.service'; -import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivencia } from './cama-supervivencia-figura'; - -const meses = Array.from({ length: 25 }, (_, i) => i); -const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24)); - -function curvasEjemplo(): any { - const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) }); - return { - simulado: true, - modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' }, - curvas: { - version: 1, n: 245, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200, - km: { months: meses, S: decreciente(0.7), low: decreciente(0.6), high: decreciente(0.8) }, - km_adjusted: { months: meses, S: decreciente(0.72) }, - weibull: { t: [0, 12, 24], S: [1, 0.85, 0.72] }, weibull_fractional: { t: [0, 12, 24], S: [1, 0.84, 0.71] }, - points: { LR: serie([0.93, 0.85, 0.78]), HBN: serie([0.92, 0.84, 0.77]), COMB: serie([0.925, 0.845, 0.775]) }, - etiquetas: { eje_x: 'Meses desde la biopsia', nota: 'Datos simulados. Sin validación clínica.' }, - }, - }; -} - -describe('Supervivencia CaMa: respuesta', () => { - // Fails if a record with an impossible value is accepted and drawn. - it('accepts a record as published and keeps it', () => { - const r = respuestaCurvas(curvasEjemplo()); - expect(r.modelo.version).toBe('3'); - expect(r.curvas.points.COMB.S).toEqual([0.925, 0.845, 0.775]); - }); - - it.each([ - ['a probability above 1', (d: any) => { d.curvas.km.S[3] = 1.2; }], - ['a curve shorter than its months', (d: any) => { d.curvas.km_adjusted.S.pop(); }], - ['an inverted interval', (d: any) => { d.curvas.points.COMB.low[0] = 0.99; }], - ['a series with another number of horizons', (d: any) => { d.curvas.points.LR.S.pop(); }], - ['no model version', (d: any) => { delete d.modelo.version; }], - ['a missing curve', (d: any) => { delete d.curvas.weibull_fractional; }], - ])('rejects %s', (_, estropear) => { - const d = curvasEjemplo(); - estropear(d); - expect(() => respuestaCurvas(d)).toThrow('Respuesta de curvas de supervivencia inválida'); - }); -}); - -describe('Supervivencia CaMa: figura', () => { - const figura = () => figuraSupervivencia(respuestaCurvas(curvasEjemplo()).curvas); - const traza = (nombre: string) => figura().data.find(t => t['name'] === nombre) as any; - - // Fails if the diamonds move off 6, 12 and 18 months, or their interval bars stop being the record's interval. - it('draws the combined model as diamonds at the horizons with its interval', () => { - const rombos = traza(ETIQUETAS_PREDETERMINADAS['puntos']); - expect(rombos.x).toEqual([6, 12, 18]); - expect(rombos.y).toEqual([0.925, 0.845, 0.775]); - expect(rombos.marker).toMatchObject({ symbol: 'diamond', color: COLORES.modelo }); - expect(rombos.error_y.array.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]); - expect(rombos.error_y.arrayminus.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]); - }); - - // Fails if the observed and adjusted curves, the band and the fractional Weibull are not all there, or LR and HBN start visible. - it('draws the Kaplan-Meier with its band, the adjusted curve and the fractional Weibull; LR and HBN start hidden', () => { - const f = figura(), nombres = f.data.map(t => t['name']); - expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_crudo']); - expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_ajustada']); - expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['weibull_fraccional']); - expect(f.data.some(t => t['fill'] === 'tonexty')).toBe(true); - expect(traza(ETIQUETAS_PREDETERMINADAS['LR']).visible).toBe('legendonly'); - expect(traza(ETIQUETAS_PREDETERMINADAS['HBN']).visible).toBe('legendonly'); - }); - - // Fails if the axis titles stop coming from the model's settings, or a label it leaves out stops falling back. - it('takes the labels from the record and falls back for the ones it leaves out', () => { - const l = figura().layout as any; - expect(l.xaxis.title.text).toBe('Meses desde la biopsia'); - expect(l.yaxis.title.text).toBe(ETIQUETAS_PREDETERMINADAS['eje_y']); - expect(l.title.text).toContain('(n = 245)'); - }); - - // Fails if the y axis hides a curve or an interval below its range, or leaves survival above 100 %. - it('fits the y range to the lowest curve or interval and stops at 100 %', () => { - const [bajo, alto] = (figura().layout as any).yaxis.range; - expect(bajo).toBeLessThan(0.6); - expect(bajo).toBeGreaterThanOrEqual(0); - expect(alto).toBeCloseTo(1.005); - }); -}); - -describe('Supervivencia CaMa: componente', () => { - let http: HttpTestingController; - beforeEach(() => { - vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); }); - const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) }, - addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) }; - TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - http = TestBed.inject(HttpTestingController); - }); - afterEach(() => { http.verify(); vi.unstubAllGlobals(); }); - const montar = (active: boolean) => { - const f = TestBed.createComponent(CamaSupervivencia); - f.componentRef.setInput('active', active); - f.detectChanges(); - return f; - }; - const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - - // Fails if the tab asks for the results before it is shown, or asks again when it is shown again. - it('asks once, the first time the tab is shown', () => { - const f = montar(false); - http.expectNone('/cama/modelo/curvas'); - f.componentRef.setInput('active', true); - f.detectChanges(); - http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo()); - f.componentRef.setInput('active', false); - f.detectChanges(); - f.componentRef.setInput('active', true); - f.detectChanges(); - http.expectNone('/cama/modelo/curvas'); - }); - - // Fails if the model, its version, the counts, the simulated label, the table of the diamonds or the note are not shown. - it('shows the model, the counts, the simulated label, the table of the horizons and the note', () => { - const f = montar(true); - http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo()); - f.detectChanges(); - - const t = texto(f); - expect(t).toContain('cama-survival, versión 3'); - expect(t).toContain('245'); - expect(t).toContain('Información simulada'); - expect(t).toContain('92.5 %'); - expect(t).toContain('88.5 % – 96.5 %'); - expect(t).toContain('Datos simulados. Sin validación clínica.'); - expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['6', '12', '18']); - }); - - // Fails if no model in production is shown as an error, or a failed or malformed answer as a chart. - it('says there is no model yet on a 404 and fails closed on an error or a malformed record', () => { - const sinModelo = montar(true); - http.expectOne('/cama/modelo/curvas').flush({ error: 'sin curvas' }, { status: 404, statusText: 'Not Found' }); - sinModelo.detectChanges(); - expect(texto(sinModelo)).toContain('Todavía no hay un modelo de supervivencia en producción'); - - const roto = montar(true); - http.expectOne('/cama/modelo/curvas').flush({ curvas: {} }); - roto.detectChanges(); - expect(texto(roto)).toContain('No se pudieron cargar los resultados del modelo'); - expect((roto.nativeElement as HTMLElement).querySelector('app-plotly-chart')).toBeNull(); - }); -}); diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts deleted file mode 100644 index 6b887bb..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { DecimalPipe } from '@angular/common'; -import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; -import { Tema } from '../indicadores.models'; -import { CamaSupervivenciaService, RespuestaCurvas } from './cama-supervivencia.service'; -import { etiquetaDe, figuraSupervivencia } from './cama-supervivencia-figura'; - -type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaCurvas }; - -/** - * CaMa's survival results: the cohort's survival curves and the model's survival at 6, 12 and 18 months with its - * interval, as the production version of the model published them. Population results, never a patient's: a patient's own - * risk is in her record. Loads once, the first time the tab is shown. - */ -@Component({ - selector: 'app-cama-supervivencia', - imports: [PlotlyChart, DecimalPipe], - templateUrl: './cama-supervivencia.html', - styleUrl: './cama-supervivencia.scss', -}) -export class CamaSupervivencia { - readonly active = input(false); - readonly tema = input('claro'); - private readonly service = inject(CamaSupervivenciaService); - private readonly destroy = inject(DestroyRef); - readonly lectura = signal({ tipo: 'cargando' }); - private pedido = false; - readonly figura = computed(() => { - const l = this.lectura(); - return l.tipo === 'listo' ? figuraSupervivencia(l.datos.curvas, this.tema()) : null; - }); - readonly etiquetaDe = etiquetaDe; - - constructor() { - effect(() => { - if (!this.active() || this.pedido) return; - this.pedido = true; - this.service.curvas().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 combined model's survival at each horizon, for the table that says what the figure's diamonds say. */ - filas(datos: RespuestaCurvas) { - const c = datos.curvas, p = c.points.COMB; - return c.horizons_months.map((meses, i) => ({ meses, S: p.S[i] * 100, low: p.low[i] * 100, high: p.high[i] * 100 })); - } -} diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index e06b388..0a7f3c5 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => { http.match(() => true); } - it('CaMa oculta Análisis y conserva Histórico, Supervivencia y Análisis de Riesgos', () => { + it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => { abrir('cama', [item('cama_eu38a', 'C3r')]); - expect(tabs()).toEqual(['Resumen', 'Histórico', 'Supervivencia', 'Análisis de Riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); fixture.componentInstance.changeSection('analisis'); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index a1fd68e..55283b3 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -138,13 +138,6 @@ } - @if (conSupervivencia) { -
- - -
- } -
('resumen'); readonly fichaPacienteAbierta = signal(false); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index e0c2ad1..c441f5e 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); - // TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos and adds Supervivencia; CaCu keeps its three. - const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Supervivencia', 'Análisis de Riesgos', 'Datos y definiciones'] + // TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three. + const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones'] : domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 02394df..d31d610 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -76,11 +76,11 @@ describe('Ficha CaMa: componente', () => { }); // Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model. - it('has placeholders, with no figures, for recurrence, survival and prognostic factors', () => { + it('has placeholders, with no figures, for recurrence and prognostic factors', () => { montar(toCamaPatientSummary(complete(), '2026-10-20')!); const items = [...root().querySelectorAll('[data-pronostico]')]; - expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'survival', 'factors']); - expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']); + expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'factors']); + expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Factores pronóstico']); for (const item of items) { expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE); expect(item.textContent).not.toMatch(/\d/); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index 26c4e59..f45587e 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -9,8 +9,8 @@ import { } from './cama-patient.models'; /** - * Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence, - * survival and prognostic factors are placeholders until a validated model supplies them. + * Individual record of a CaMa follow-up patient. It shows what the follow-up list carries and the patient's risk with her + * survival figure; recurrence and prognostic factors are placeholders until a validated model supplies them. */ @Component({ selector: 'app-cama-patient-card', diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts index fc49e84..1c75e67 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts @@ -1,5 +1,5 @@ // Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only -// the fields of the record, shows placeholders (no figures) for recurrence, survival and prognostic factors, and +// the fields of the record, shows placeholders (no figures) for recurrence and prognostic factors (survival is drawn in the record from the risk evaluation), and // renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test // because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser. import fixtureData from '../../fixtures/cama_seguimiento.json'; @@ -46,10 +46,10 @@ describe('Ficha CaMa: PDF individual', () => { }); // Fails if a placeholder gains a figure or an explanation other than "unavailable". - it('has placeholders, with no figures, for recurrence, survival, prognostic factors and recommendations', () => { + it('has placeholders, with no figures, for recurrence, prognostic factors and recommendations', () => { const found = texts(definition()['content']); - for (const t of ['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t); - expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(3); + for (const t of ['Probabilidad de recurrencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t); + expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(2); }); // Fails if the document carries a platform identifier field. diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index 192bef5..879d65c 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -27,10 +27,10 @@ export interface CamaPatientSummary { daysMammographyToDiagnosis: number | null; } -/** Placeholders for results that exist only once a validated model and its clinical definition do. */ +/** Placeholders for results that exist only once a validated model and its clinical definition do (survival is drawn from + * the patient's risk evaluation, not a placeholder). */ export const PROGNOSIS_PLACEHOLDERS = [ { key: 'recurrence', label: 'Probabilidad de recurrencia' }, - { key: 'survival', label: 'Supervivencia' }, { key: 'factors', label: 'Factores pronóstico' }, ] as const; export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.'; diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts new file mode 100644 index 0000000..2f33227 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts @@ -0,0 +1,65 @@ +import { PlotlyFigure, Tema } from '../../indicadores.models'; +import { HorizonteRiesgoCacu } from '../paciente-riesgo.models'; +import { tieneIntervalo } from '../paciente-riesgo.validation'; + +/** The clinicians' wording of the chart. */ +export const ETIQUETAS_PACIENTE = { + titulo: 'Supervivencia de la paciente desde el primer reporte de biopsia con carcinoma invasor', + eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia', + curva: 'Supervivencia estimada', puntos: 'Modelo (LR + red bayesiana) con IC 95 %', +} as const; +export const COLOR_MODELO = '#6a3d9a'; +/** The curve runs to this many months, as the cohort's does. */ +export const MESES_MAXIMOS = 24; + +export interface PuntoDeSupervivencia { meses: number; S: number; bajo: number | null; alto: number | null; } + +/** The model's survival at each horizon: one minus the mortality of the `RiskAssessment`, its interval turned around. */ +export function puntosDeSupervivencia(horizontes: readonly HorizonteRiesgoCacu[]): PuntoDeSupervivencia[] { + return horizontes.filter(h => h.horizonte_anios > 0).map(h => ({ + meses: Math.round(h.horizonte_anios * 12), S: 1 - h.probabilidad, + bajo: tieneIntervalo(h) ? 1 - h.ic_alto! : null, alto: tieneIntervalo(h) ? 1 - h.ic_bajo! : null, + })).sort((a, b) => a.meses - b.meses); +} + +/** The survival month by month: log-linear between 0 and the horizons (a constant hazard in each interval), and past the + * last one at the last interval's rate. It passes through every point and never rises. */ +export function curvaMensual(puntos: readonly PuntoDeSupervivencia[], hasta = MESES_MAXIMOS): { meses: number[]; S: number[] } { + const bordes = [0, ...puntos.map(p => p.meses)], log = [0, ...puntos.map(p => Math.log(Math.max(p.S, 1e-12)))]; + const ultimo = bordes.length - 1, pendiente = ultimo > 0 ? (log[ultimo] - log[ultimo - 1]) / (bordes[ultimo] - bordes[ultimo - 1]) : 0; + const meses = Array.from({ length: Math.max(hasta, bordes[ultimo]) + 1 }, (_, m) => m); + const S = meses.map(m => { + if (m >= bordes[ultimo]) return Math.exp(log[ultimo] + pendiente * (m - bordes[ultimo])); + let i = 0; + while (bordes[i + 1] < m) i++; + return Math.exp(log[i] + (log[i + 1] - log[i]) * (m - bordes[i]) / (bordes[i + 1] - bordes[i])); + }); + return { meses, S: S.reduce((acc, v) => [...acc, Math.min(v, acc.length ? acc[acc.length - 1] : 1)], []) }; +} + +/** The figure of one patient's survival: the model's curve and its survival at each horizon as diamonds, with the interval + * when the evaluation carries one. */ +export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgoCacu[], tema: Tema = 'claro'): PlotlyFigure | null { + const puntos = puntosDeSupervivencia(horizontes); + if (puntos.length === 0) return null; + const curva = curvaMensual(puntos), conIntervalo = puntos.every(p => p.bajo !== null); + const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)'; + const minimo = Math.max(0, Math.min(...curva.S, ...puntos.map(p => p.bajo ?? 1)) - 0.05); + const data: Record[] = [ + { type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: ETIQUETAS_PACIENTE.curva, line: { color: COLOR_MODELO, width: 2.6 }, + hovertemplate: '%{x} meses: %{y:.1%}' }, + { type: 'scatter', mode: 'markers', name: ETIQUETAS_PACIENTE.puntos, x: puntos.map(p => p.meses), y: puntos.map(p => p.S), + marker: { symbol: 'diamond', size: 12, color: COLOR_MODELO, line: { color: 'white', width: 1 } }, + ...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLOR_MODELO, thickness: 1.8, width: 5, + array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}), + hovertemplate: '%{x} meses: %{y:.1%}' }, + ]; + const layout: Record = { + title: { text: ETIQUETAS_PACIENTE.titulo, x: 0, xanchor: 'left', font: { size: 15, color: texto } }, + paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto }, + xaxis: { title: { text: ETIQUETAS_PACIENTE.eje_x }, range: [0, curva.meses[curva.meses.length - 1] + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false }, + yaxis: { title: { text: ETIQUETAS_PACIENTE.eje_y }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false }, + legend: { orientation: 'h', y: -0.25, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 100 }, hovermode: 'closest', + }; + return { data, layout, config: { responsive: true, displaylogo: false } }; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 553ce66..70a95ab 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -9,6 +9,7 @@ import { CamaPatientSummary } from './cama/cama-patient.models'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { INTERVALO, prediccion } from './paciente-riesgo.testing'; +import { curvaMensual, figuraSupervivenciaPaciente, puntosDeSupervivencia } from './cama/cama-supervivencia-paciente'; const CS = 'https://isssteleon.org/fhir/CodeSystem'; @@ -41,6 +42,46 @@ const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({ daysMammographyToDiagnosis: null, clinicalScenario: null, }); +describe('Supervivencia individual de la paciente CaMa', () => { + // Fails if a point of the figure is not one minus the mortality of its horizon, or its interval is not turned around. + it('turns each horizon of the evaluation into survival with its interval', () => { + const puntos = puntosDeSupervivencia([ + { horizonte_anios: 0.5, probabilidad: 0.07, ic_bajo: 0.05, ic_alto: 0.1 }, + { horizonte_anios: 1.5, probabilidad: 0.25 }, { horizonte_anios: 1, probabilidad: 0.18 }]); + + expect(puntos.map(p => p.meses)).toEqual([6, 12, 18]); + expect(puntos.map(p => +p.S.toFixed(2))).toEqual([0.93, 0.82, 0.75]); + expect(puntos[0].bajo).toBeCloseTo(0.9); + expect(puntos[0].alto).toBeCloseTo(0.95); + expect(puntos[1].bajo).toBeNull(); + }); + + // Fails if the curve misses a point, rises, or stops at the last horizon. + it('draws a curve through every point that never rises and goes on to 24 months', () => { + const puntos = puntosDeSupervivencia([{ horizonte_anios: 0.5, probabilidad: 0.1 }, { horizonte_anios: 1, probabilidad: 0.2 }, { horizonte_anios: 1.5, probabilidad: 0.4 }]); + const { meses, S } = curvaMensual(puntos); + + expect(S[0]).toBe(1); + expect(S[6]).toBeCloseTo(0.9); expect(S[12]).toBeCloseTo(0.8); expect(S[18]).toBeCloseTo(0.6); + expect(meses[meses.length - 1]).toBe(24); + expect(S.every((v, i) => i === 0 || v <= S[i - 1] + 1e-12)).toBe(true); + expect(S[24]).toBeLessThan(S[18]); + }); + + // Fails if the figure keeps no diamonds at the horizons, or draws their interval when the evaluation has none. + it('puts the diamonds at the horizons, with bars only when there is an interval', () => { + const con = figuraSupervivenciaPaciente([{ horizonte_anios: 0.5, probabilidad: 0.07, ic_bajo: 0.05, ic_alto: 0.1 }])!; + const sin = figuraSupervivenciaPaciente([{ horizonte_anios: 0.5, probabilidad: 0.07 }])!; + const rombos = (f: typeof con) => f.data.find(t => (t as any).mode === 'markers') as any; + + expect(rombos(con).x).toEqual([6]); + expect(rombos(con).marker.symbol).toBe('diamond'); + expect(rombos(con).error_y).toBeDefined(); + expect(rombos(sin).error_y).toBeUndefined(); + expect(figuraSupervivenciaPaciente([])).toBeNull(); + }); +}); + describe('Riesgo individual de la paciente CaMa', () => { const obtener = vi.fn(); beforeEach(() => { @@ -72,12 +113,14 @@ describe('Riesgo individual de la paciente CaMa', () => { f.detectChanges(); const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); expect(text).toContain('cama-survival'); expect(text).toContain('2025-06-19'); expect(text).toContain('Muerte por cualquier causa'); expect(text).toContain('7 %'); expect(text).toContain('17.8 %'); expect(text).toContain('25.1 %'); + expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/); expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 69612d0..c2a131d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -7,7 +7,6 @@ } @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') { -

Información simulada · Entorno DEV · Sin evaluación clínica

@let riesgo = lectura.datos.riesgo;
Modelo y evaluación
@if (riesgo.horizontes.length) {
- - +
Probabilidades simuladas por horizonte desde la fecha índice
+ @@ -39,6 +38,9 @@
Probabilidades por horizonte desde la fecha índice
Horizonte (años) Probabilidad (%)
} @else {

Sin horizontes evaluados en el lote vigente.

} + @if (figura(); as figure) { + + } } }

Recomendaciones no disponibles.

diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 7d9f119..e59798d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,12 +1,14 @@ import { Component, computed, effect, inject, input } from '@angular/core'; import { DecimalPipe } from '@angular/common'; +import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; +import { figuraSupervivenciaPaciente } from './cama/cama-supervivencia-paciente'; import { DominioRiesgo } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @Component({ selector: 'app-paciente-riesgo-tabla', - imports: [DecimalPipe], + imports: [DecimalPipe, PlotlyChart], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -20,6 +22,11 @@ export class PacienteRiesgoTabla { private readonly state = inject(PacienteRiesgoState); readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; + /** CaMa's survival figure of this patient, from the horizons of her current evaluation; CaCu's has none. */ + readonly figura = computed(() => { + const lectura = this.estado(); + return this.dominio() === 'cama' && lectura.tipo === 'disponible' ? figuraSupervivenciaPaciente(lectura.datos.riesgo.horizontes) : null; + }); constructor() { effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 76caafc..51c685d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -55,8 +55,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { } // The record no longer shows the cohort's internals (its definition, version or model variables). expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/); - expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado'); - expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV'); + // The record never says its data are test data: with real information it makes real predictions. + expect(root.textContent).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica|simuladas/); expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); // The resource id (batch and patient) stays in the contract, never in a UI label. expect(root.textContent).not.toMatch(/lote_id|12-42/);