From fb5a4ed5ccab68845cb9199a9b644da9e1807a6a Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:14:06 -0600 Subject: [PATCH] CaMa patient record: the pipeline's figure of each clinical scenario she belongs to, without a curve of her own --- .../cama/cama-curvas.service.ts | 24 ++-- .../cama/cama-supervivencia-figura.ts | 49 ++++++++ ...cama-supervivencia-paciente.component.html | 13 +- ...a-supervivencia-paciente.component.spec.ts | 112 ++++++++++-------- .../cama-supervivencia-paciente.component.ts | 49 +++++--- .../cama/cama-supervivencia-paciente.ts | 99 ---------------- .../paciente-riesgo-cama.spec.ts | 28 ----- .../paciente-riesgo-tabla.html | 2 +- 8 files changed, 166 insertions(+), 210 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts index 07f7a7b..3867f52 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts @@ -7,6 +7,7 @@ import { catchError, map, Observable, of, throwError } from 'rxjs'; // 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 { + escenario?: string; 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[] }; @@ -59,6 +60,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas { return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, curvas: { + escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined, 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'], @@ -68,21 +70,29 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas { }; } -export interface ConsultaCurvas { filtros?: Record; periodo?: { desde?: string; hasta?: string }; } -/** The selection was refused with a reason (a 422): too few patients, or invalid. */ +/** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */ export class SeleccionRechazada extends Error {} @Injectable({ providedIn: 'root' }) export class CamaCurvasService { private readonly http = inject(HttpClient); - /** The figure's record for the selection, scored with the production version over the data ingested so far. A refused - * selection fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */ - consulta(consulta: ConsultaCurvas): Observable { - return this.http.post('/cama/modelo/curvas/consulta', consulta).pipe( + /** The clinical scenarios the patient belongs to (the whole cohort when she is in none), or `null` when there is no model in + * production or no cohort yet. */ + escenarios(pacId: string): Observable { + return this.http.get<{ escenarios: string[] }>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe( + map(r => Array.isArray(r.escenarios) ? r.escenarios.filter(e => typeof e === 'string') : null), + catchError(() => of(null)), + ); + } + + /** The figure's record of one scenario (`null`: the whole cohort), scored with the production version over the data + * ingested so far. A refused scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */ + consulta(escenario: string | null): Observable { + return this.http.post('/cama/modelo/curvas/consulta', { escenario }).pipe( map(respuestaCurvas), catchError(error => error instanceof HttpErrorResponse && error.status === 422 - ? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'La selección no se puede calcular.'))) + ? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'El escenario no se puede calcular.'))) : throwError(() => error)), ); } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts new file mode 100644 index 0000000..ebca7a3 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts @@ -0,0 +1,49 @@ +import { PlotlyFigure, Tema } from '../../indicadores.models'; +import { CurvasSupervivencia } from './cama-curvas.service'; + +/** The wording of the chart, as the SEER pipeline's own figure has it. The model's run can publish another wording for any + * of these (`[config.etiquetas]`), so the clinicians define it, not the code. */ +export const ETIQUETAS_PREDETERMINADAS: Readonly> = { + eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)', + km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional', + puntos: 'LR + HBN combinado (IC 95 % bootstrap)', +}; +export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const; + +const etiqueta = (c: CurvasSupervivencia, clave: string) => c.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave; + +/** + * The SEER pipeline's survival figure of one clinical scenario: the Kaplan-Meier curve of its patients with its Greenwood band, + * the classic and the fractional Weibull, and the model's survival at each horizon as diamonds with their bootstrap interval. + * Titled with the scenario, its patients and its deaths. + */ +export function figuraSupervivencia(c: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure { + const km = c.km, diamantes = c.points.COMB, t = (clave: string) => etiqueta(c, clave); + 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.floor((Math.min(...km.low, ...c.weibull_fractional.S, ...diamantes.low) - 0.02) * 20) / 20); + 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: COLORES.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' }, + { type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km, width: 2, shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km', + hovertemplate: '%{x} meses: %{y:.3f}' + t('km_crudo') + '' }, + { type: 'scatter', mode: 'lines', x: c.weibull.t, y: c.weibull.S, line: { color: COLORES.weibull, width: 3 }, name: t('weibull'), + hovertemplate: '%{x:.1f} meses: %{y:.3f}' + t('weibull') + '' }, + { type: 'scatter', mode: 'lines', x: c.weibull_fractional.t, y: c.weibull_fractional.S, line: { color: COLORES.fraccional, width: 3, dash: 'dash' }, name: t('weibull_fraccional'), + hovertemplate: '%{x:.1f} meses: %{y:.3f}' + t('weibull_fraccional') + '' }, + { type: 'scatter', mode: 'markers', name: t('puntos'), x: c.horizons_months, y: diamantes.S, + marker: { symbol: 'diamond', size: 15, color: COLORES.modelo, line: { color: 'white', width: 1.5 } }, + error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.modelo, thickness: 2, width: 6, + array: diamantes.high.map((hi, i) => hi - diamantes.S[i]), arrayminus: diamantes.S.map((s, i) => s - diamantes.low[i]) }, + hovertemplate: '%{x} meses: %{y:.3f}' + t('puntos') + '' }, + ]; + const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' }; + const layout: Record = { + title: { text: `${c.escenario ?? 'Toda la cohorte'}
n=${c.n.toLocaleString('es-MX')}, fallecidos=${c.events.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } }, + paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto }, + xaxis: { ...eje, title: { text: t('eje_x') }, range: [0, c.months_max + 0.8], dtick: 5 }, + yaxis: { ...eje, title: { text: t('eje_y') }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' }, + legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } }, + margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest', + }; + return { data, layout, config: { responsive: true, displaylogo: false } }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html index 0499581..3276551 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html @@ -1,10 +1,9 @@
-
Supervivencia de la paciente
- @let l = lectura(); - @if (l.tipo === 'cargando') {

Calculando con los datos más recientes…

} - @if (l.tipo === 'rechazada') {

{{ l.motivo }}

} - @if (l.tipo === 'error') {

No se pudo calcular la curva de la cohorte; se muestra solo la de la paciente.

} - @if (figura(); as figure) { - +
Supervivencia
+ @let lista = escenarios(); + @if (lista === undefined) {

Buscando los escenarios clínicos de la paciente…

} + @if (lista === null) {

Todavía no hay un modelo de supervivencia en producción.

} + @if (lista) { + @for (nombre of lista; track nombre) { } }
diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts index df91518..37334ef 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts @@ -1,37 +1,36 @@ -// Covers the patient's survival in her CaMa record: the cohort's curves are asked live (for everyone, then for the covariates -// she is compared on), a refused selection says why, a failure leaves her own curve, and the figure has the SEER pipeline's -// look (the Greenwood band, the Kaplan-Meier steps, the two Weibull, the diamonds) with hers over it. Fixtures: a stub of -// `CamaCurvasService` that records each selection, and a cohort record like `POST /cama/modelo/curvas/consulta` answers. +// Covers the patient's survival in her CaMa record: the figure of each clinical scenario she belongs to is computed live (one +// request per scenario, none for her own curve), a refused scenario says why, no model in production says so, and the figure +// has the SEER pipeline's look (the Greenwood band, the Kaplan-Meier steps, the two Weibull, the diamonds). Fixtures: a stub of +// `CamaCurvasService` that records each scenario asked, and a record like `POST /cama/modelo/curvas/consulta` answers. import { TestBed } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; import { vi } from 'vitest'; import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime'; import { CamaCurvasService, respuestaCurvas, SeleccionRechazada } from './cama-curvas.service'; import { CamaSupervivenciaPaciente } from './cama-supervivencia-paciente.component'; -import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivenciaPaciente } from './cama-supervivencia-paciente'; +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)); const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) }); -function cohorte(n = 245): any { +function respuesta(escenario = '< 45 años', n = 245): any { return { modelo: { nombre: 'cama-survival', version: '3' }, curvas: { - version: 1, n, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200, + version: 1, escenario, n, 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: {}, }, }; } -const horizontes = [{ horizonte_anios: 0.5, probabilidad: 0.07 }, { horizonte_anios: 1, probabilidad: 0.18 }, { horizonte_anios: 1.5, probabilidad: 0.25 }]; -describe('Figura de supervivencia de la paciente', () => { - const figura = (c: any = cohorte().curvas) => figuraSupervivenciaPaciente(horizontes, respuestaCurvas(c === null ? cohorte() : { ...cohorte(), curvas: c }).curvas)!; +describe('Figura de supervivencia de un escenario', () => { + const figura = (r: any = respuesta()) => figuraSupervivencia(respuestaCurvas(r).curvas); const traza = (f: any, nombre: string) => f.data.find((t: any) => t.name === nombre) as any; - // Fails if the figure loses a piece of the pipeline's chart: the band, the steps, the two Weibull or the cohort's diamonds. - it('has the cohort\'s Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => { + // Fails if the figure loses a piece of the pipeline's chart: the band, the steps, the two Weibull or the diamonds with their bars. + it('has the Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => { const f = figura(); expect(f.data.some((t: any) => t.fill === 'tonexty')).toBe(true); @@ -44,85 +43,100 @@ describe('Figura de supervivencia de la paciente', () => { expect(rombos.error_y.array.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]); }); - // Fails if her curve is not on the figure, or sits at other horizons than her evaluation's. - it('draws hers over the cohort\'s: a curve and her diamonds at her horizons', () => { - const f = figura(); - const suya = f.data.find((t: any) => t.legendgroup === 'paciente' && t.mode === 'markers') as any; - - expect(suya.x).toEqual([6, 12, 18]); - expect(suya.y.map((v: number) => +v.toFixed(2))).toEqual([0.93, 0.82, 0.75]); - expect(suya.error_y).toBeUndefined(); - expect((f.data.find((t: any) => t.legendgroup === 'paciente' && t.mode === 'lines') as any).line.color).toBe(COLORES.paciente); + // Fails if anything but the pipeline's own curves is drawn: the patient's own curve is not part of the figure. + it('draws only the pipeline\'s curves, none of the patient\'s own', () => { + expect(figura().data.map((t: any) => t.name).filter(Boolean).sort()).toEqual( + ['Kaplan-Meier (IC 95 % Greenwood)', 'LR + HBN combinado (IC 95 % bootstrap)', 'Weibull', 'Weibull fraccional'].sort()); }); - // Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, n and deaths. - it('is labelled and scaled as the pipeline\'s figure', () => { + // Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, the scenario, n and deaths. + it('is titled with the scenario, its patients and deaths, and scaled as the pipeline\'s figure', () => { const l = figura().layout as any; + expect(l.title.text).toBe('< 45 años
n=245, fallecidos=67'); expect(l.yaxis.title.text).toBe('Supervivencia S(t)'); expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico'); expect(l.yaxis.tickformat).toBe('.2f'); - expect(l.title.text).toContain('n=245, fallecidos=67'); expect(l.legend.yanchor).toBe('bottom'); }); - // Fails if her curve and her diamonds take two legend entries, which says nothing the curve does not. - it('has one legend entry for her curve and her diamonds', () => { - const f = figura(); - const suyas = f.data.filter((t: any) => t.legendgroup === 'paciente') as any[]; + // Fails if a label the model's run publishes is ignored, which would take the wording out of the clinicians' hands. + it('takes the wording from the record when the model publishes it', () => { + const r = respuesta(); + r.curvas.etiquetas = { eje_y: 'Probabilidad de sobrevivir' }; - expect(suyas).toHaveLength(2); - expect(suyas.filter(t => t.showlegend !== false)).toHaveLength(1); - expect(f.data.some((t: any) => t.name === 'Paciente: modelo en cada horizonte')).toBe(false); + expect((figura(r).layout as any).yaxis.title.text).toBe('Probabilidad de sobrevivir'); }); }); describe('Supervivencia de la paciente: componente', () => { let consulta: ReturnType; + let escenarios: ReturnType; 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()) }; - consulta = vi.fn(() => of(respuestaCurvas(cohorte()))); + consulta = vi.fn((nombre: string | null) => of(respuesta(nombre ?? 'Toda la cohorte'))); + escenarios = vi.fn(() => of(['< 45 años', 'Jóvenes (<45) · HER2−'])); TestBed.configureTestingModule({ providers: [ - { provide: CamaCurvasService, useValue: { consulta } }, + { provide: CamaCurvasService, useValue: { escenarios, consulta } }, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); }); afterEach(() => vi.unstubAllGlobals()); const montar = () => { const f = TestBed.createComponent(CamaSupervivenciaPaciente); f.componentRef.setInput('pacId', '7'); - f.componentRef.setInput('horizontes', horizontes); f.detectChanges(); return f; }; const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - // Fails if the cohort's curves are not asked live for everyone, or the record offers choices the reader did not ask for. - it('asks the cohort live, for everyone, and offers no choices', () => { + // Fails if the patient's scenarios are not asked for her, or a scenario she is in has no figure. + it('draws the figure of each scenario the patient belongs to, asked live', () => { const f = montar(); + f.detectChanges(); - expect(consulta).toHaveBeenCalledWith({ filtros: {} }); - expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); - expect(f.nativeElement.querySelector('input, fieldset')).toBeNull(); - expect(texto(f)).not.toContain('Comparar con'); + expect(escenarios).toHaveBeenCalledWith('7'); + expect(consulta.mock.calls.map(c => c[0])).toEqual(['< 45 años', 'Jóvenes (<45) · HER2−']); + expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2); }); - // Fails if a refused selection draws a figure, or does not say why. - it('says why when the selection is refused and draws nothing', () => { - consulta.mockReturnValue(throwError(() => new SeleccionRechazada('La selección tiene 3 pacientes y 0 defunciones.'))); + // Fails if a patient in no scenario is left without a figure, or the whole cohort is asked as a named scenario. + it('asks for the whole cohort when the patient is in no scenario', () => { + escenarios.mockReturnValue(of(['Toda la cohorte'])); const f = montar(); + f.detectChanges(); - expect(texto(f)).toContain('La selección tiene 3 pacientes'); + expect(consulta).toHaveBeenCalledExactlyOnceWith(null); + expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1); + }); + + // Fails if the record offers choices the reader did not ask for. + it('offers no choices', () => { + const f = montar(); + f.detectChanges(); + + expect(f.nativeElement.querySelector('input, fieldset, select')).toBeNull(); + }); + + // Fails if a refused scenario draws a figure, or does not say why. + it('says why when a scenario is refused and draws nothing for it', () => { + escenarios.mockReturnValue(of(['Estadio IV'])); + consulta.mockReturnValue(throwError(() => new SeleccionRechazada('El escenario tiene 3 pacientes y 0 defunciones.'))); + const f = montar(); + f.detectChanges(); + + expect(texto(f)).toContain('Estadio IV: El escenario tiene 3 pacientes'); expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull(); }); - // Fails if a failed cohort computation leaves her without a figure. - it('draws only her own curve when the cohort\'s cannot be had', () => { - consulta.mockReturnValue(throwError(() => new Error('boom'))); + // Fails if no model in production is shown as an error or a blank. + it('says there is no model yet', () => { + escenarios.mockReturnValue(of(null)); const f = montar(); + f.detectChanges(); - expect(texto(f)).toContain('se muestra solo la de la paciente'); - expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); + expect(texto(f)).toContain('Todavía no hay un modelo de supervivencia en producción'); + expect(consulta).not.toHaveBeenCalled(); }); }); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts index ece40d4..2fa52e7 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts @@ -1,36 +1,47 @@ import { Component, computed, inject, input } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { catchError, map, of, startWith } from 'rxjs'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { catchError, map, of, startWith, switchMap } from 'rxjs'; import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; -import { HorizonteRiesgoCacu } from '../paciente-riesgo.models'; import { CamaCurvasService, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service'; -import { figuraSupervivenciaPaciente } from './cama-supervivencia-paciente'; +import { figuraSupervivencia } from './cama-supervivencia-figura'; -/** What the reader calls each covariate of the model. */ type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas }; +/** One clinical scenario's figure, computed when it is shown. */ +@Component({ + selector: 'app-cama-figura-escenario', + imports: [PlotlyChart], + template: ` + @let l = lectura(); + @if (l.tipo === 'cargando') {

Calculando {{ escenario() }} con los datos más recientes…

} + @if (l.tipo === 'rechazada') {

{{ escenario() }}: {{ l.motivo }}

} + @if (l.tipo === 'error') {

No se pudo calcular la supervivencia de {{ escenario() }}.

} + @if (figura(); as figure) { }`, +}) +export class CamaFiguraEscenario { + readonly escenario = input.required(); + private readonly service = inject(CamaCurvasService); + readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => this.service.consulta(nombre === 'Toda la cohorte' ? null : nombre).pipe( + map((datos): Lectura => ({ tipo: 'lista', datos })), + catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), + startWith({ tipo: 'cargando' })))), { initialValue: { tipo: 'cargando' } as Lectura }); + readonly figura = computed(() => { const l = this.lectura(); return l.tipo === 'lista' ? figuraSupervivencia(l.datos.curvas) : null; }); +} + /** - * One patient's survival, on the SEER pipeline's figure of the cohort. The cohort's curves are computed when the record opens, - * from the data ingested so far and the model in production; hers is her own prediction on top of them. + * The patient's survival: the figure of each clinical scenario she belongs to (the whole cohort when she is in none), as the SEER + * pipeline draws them. Patients of one scenario share its figure; it is computed from the data ingested so far with the model + * in production. */ @Component({ selector: 'app-cama-supervivencia-paciente', - imports: [PlotlyChart], + imports: [CamaFiguraEscenario], templateUrl: './cama-supervivencia-paciente.component.html', styleUrl: './cama-supervivencia-paciente.component.scss', }) export class CamaSupervivenciaPaciente { readonly pacId = input.required(); - readonly horizontes = input.required(); private readonly service = inject(CamaCurvasService); - readonly lectura = toSignal(this.service.consulta({ filtros: {} }).pipe( - map((datos): Lectura => ({ tipo: 'lista', datos })), - catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), - startWith({ tipo: 'cargando' })), { initialValue: { tipo: 'cargando' } as Lectura }); - /** The figure: hers over the cohort's, or hers alone when the cohort's cannot be had. */ - readonly figura = computed(() => { - const l = this.lectura(); - if (l.tipo === 'cargando' || l.tipo === 'rechazada') return null; - return figuraSupervivenciaPaciente(this.horizontes(), l.tipo === 'lista' ? l.datos.curvas : null); - }); + /** Her scenarios; `undefined` while they load, `null` when there is no model in production yet. */ + readonly escenarios = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id)))); } 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 deleted file mode 100644 index f2c1251..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { PlotlyFigure, Tema } from '../../indicadores.models'; -import { HorizonteRiesgoCacu } from '../paciente-riesgo.models'; -import { tieneIntervalo } from '../paciente-riesgo.validation'; -import { CurvasSupervivencia } from './cama-curvas.service'; - -/** The wording of the chart, as the SEER pipeline's own figure has it. The model's run can publish another wording for any - * of these (`[config.etiquetas]`), so the clinicians define it, not the code. */ -export const ETIQUETAS_PREDETERMINADAS: Readonly> = { - titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor', - eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)', - km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional', - puntos: 'LR + HBN combinado (IC 95 % bootstrap)', paciente: 'Paciente', -}; -export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a', paciente: '#e08a00' } as const; -/** 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)], []) }; -} - -const etiqueta = (cohorte: CurvasSupervivencia | null, clave: string) => cohorte?.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave; - -/** - * The SEER pipeline's survival figure, with the patient on it. The cohort's (when the model's run published it): the - * Kaplan-Meier curve with its Greenwood band, the classic and the fractional Weibull, and the model's survival at each - * horizon as diamonds with their bootstrap interval. The patient's: her survival by the model, a curve through her value at each - * horizon (and its interval, when her evaluation has one). - */ -export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgoCacu[], cohorte: CurvasSupervivencia | null = null, tema: Tema = 'claro', descripcion: string | null = null): PlotlyFigure | null { - const puntos = puntosDeSupervivencia(horizontes); - if (puntos.length === 0) return null; - const curva = curvaMensual(puntos), conIntervalo = puntos.every(p => p.bajo !== null), t = (clave: string) => etiqueta(cohorte, clave); - const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)'; - const data: Record[] = []; - const bajos: number[] = [...curva.S, ...puntos.map(p => p.bajo ?? p.S)]; - let hasta = curva.meses[curva.meses.length - 1]; - if (cohorte) { - const km = cohorte.km, diamantes = cohorte.points.COMB; - hasta = Math.max(hasta, km.months[km.months.length - 1]); - bajos.push(...km.low, ...cohorte.weibull_fractional.S, ...diamantes.low); - data.push( - { 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: COLORES.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' }, - { type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km, width: 2, shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km', - hovertemplate: '%{x} meses: %{y:.3f}' + t('km_crudo') + '' }, - { type: 'scatter', mode: 'lines', x: cohorte.weibull.t, y: cohorte.weibull.S, line: { color: COLORES.weibull, width: 3 }, name: t('weibull'), - hovertemplate: '%{x:.1f} meses: %{y:.3f}' + t('weibull') + '' }, - { type: 'scatter', mode: 'lines', x: cohorte.weibull_fractional.t, y: cohorte.weibull_fractional.S, line: { color: COLORES.fraccional, width: 3, dash: 'dash' }, name: t('weibull_fraccional'), - hovertemplate: '%{x:.1f} meses: %{y:.3f}' + t('weibull_fraccional') + '' }, - { type: 'scatter', mode: 'markers', name: t('puntos'), x: cohorte.horizons_months, y: diamantes.S, - marker: { symbol: 'diamond', size: 15, color: COLORES.modelo, line: { color: 'white', width: 1.5 } }, - error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.modelo, thickness: 2, width: 6, - array: diamantes.high.map((hi, i) => hi - diamantes.S[i]), arrayminus: diamantes.S.map((s, i) => s - diamantes.low[i]) }, - hovertemplate: '%{x} meses: %{y:.3f}' + t('puntos') + '' }); - } - data.push( - { type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: t('paciente'), legendgroup: 'paciente', line: { color: COLORES.paciente, width: 3 }, - hovertemplate: '%{x} meses: %{y:.3f}' + t('paciente') + '' }, - { type: 'scatter', mode: 'markers', name: t('paciente'), legendgroup: 'paciente', showlegend: false, x: puntos.map(p => p.meses), y: puntos.map(p => p.S), - marker: { symbol: 'diamond', size: 14, color: COLORES.paciente, line: { color: 'white', width: 1.5 } }, - ...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.paciente, thickness: 2, width: 6, - array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}), - hovertemplate: '%{x} meses: %{y:.3f}' + t('paciente') + '' }); - const minimo = Math.max(0, Math.floor((Math.min(...bajos) - 0.02) * 20) / 20); - const base = descripcion ?? t('titulo'); - const titulo = cohorte ? `${base}
n=${cohorte.n.toLocaleString('es-MX')}, fallecidos=${cohorte.events.toLocaleString('es-MX')}` : base; - const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' }; - const layout: Record = { - title: { text: titulo, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } }, - paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto }, - xaxis: { ...eje, title: { text: t('eje_x') }, range: [0, hasta + 0.6], dtick: 5 }, - yaxis: { ...eje, title: { text: t('eje_y') }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' }, - legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } }, - margin: { l: 70, r: 20, t: 70, b: 60 }, 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 895a996..19ca9ee 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,7 +9,6 @@ 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'; @@ -42,33 +41,6 @@ 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]); - }); -}); - describe('Riesgo individual de la paciente CaMa', () => { const obtener = vi.fn(); beforeEach(() => { 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 474b7c5..10a704c 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -39,7 +39,7 @@ } @else {

Sin horizontes evaluados en el lote vigente.

} @if (dominio() === 'cama' && pacId(); as id) { - + } } }