From 7adceb86bf0b5811a7b0a64cb3f1dfbb08dfcbfc Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 12:07:21 -0600 Subject: [PATCH] CaMa patient record: the pipeline's survival figure with her curve, computed live and comparable with her subgroup --- .../cama/cama-curvas.service.ts | 105 +++++++++++++ ...cama-supervivencia-paciente.component.html | 18 +++ ...cama-supervivencia-paciente.component.scss | 3 + ...a-supervivencia-paciente.component.spec.ts | 141 ++++++++++++++++++ .../cama-supervivencia-paciente.component.ts | 62 ++++++++ .../cama/cama-supervivencia-paciente.ts | 83 ++++++++--- .../paciente-riesgo-cama.spec.ts | 18 +-- .../paciente-riesgo-tabla.html | 4 +- .../paciente-detalle/paciente-riesgo-tabla.ts | 11 +- 9 files changed, 393 insertions(+), 52 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.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 new file mode 100644 index 0000000..ef17d37 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts @@ -0,0 +1,105 @@ +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { inject, Injectable } from '@angular/core'; +import { catchError, map, Observable, of, throwError } from 'rxjs'; + +// The cohort's 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 { + modelo: { nombre: string; version: 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'])) 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 { + modelo: { nombre: m['nombre'] as string, version: m['version'] 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, + }, + }; +} + +/** What can be selected, and the patient's own value of each covariate (`GET /cama/modelo/curvas/opciones?paciente=`). */ +export interface OpcionesCurvas { + n: number; events: number; + covariables: Record; + periodo: { desde: string; hasta: string }; + limites: { miembros_min: number; muertes_min: number }; + paciente: Record | null; +} +export interface ConsultaCurvas { filtros?: Record; periodo?: { desde?: string; hasta?: string }; } +/** The selection was refused with a reason (a 422): too few patients, or invalid. */ +export class SeleccionRechazada extends Error {} + +@Injectable({ providedIn: 'root' }) +export class CamaCurvasService { + private readonly http = inject(HttpClient); + + /** The values that can be selected, and `pacId`'s own; `null` when there is no model in production or no cohort yet. */ + opciones(pacId: string): Observable { + return this.http.get<{ opciones: OpcionesCurvas }>('/cama/modelo/curvas/opciones', { params: { paciente: pacId } }).pipe( + map(r => r.opciones), + catchError(() => of(null)), + ); + } + + /** 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( + 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(() => error)), + ); + } +} 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 new file mode 100644 index 0000000..b5299c5 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html @@ -0,0 +1,18 @@ +
+
Supervivencia de la paciente
+ @if (cruzables().length) { +
+ Comparar con las pacientes que comparten + @for (c of cruzables(); track c.clave) { + + } +
+ } + @let l = lectura(); + @if (l.tipo === 'cargando') {

Calculando con los datos más recientes…

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

{{ l.motivo }} Quita algún criterio para comparar con más pacientes.

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

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

} + @if (figura(); as figure) { + + } +
diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss new file mode 100644 index 0000000..6ce8457 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss @@ -0,0 +1,3 @@ +.compare { border: 1px solid var(--mat-sys-outline-variant, #ccc); margin: 0 0 1rem; padding: .5rem .75rem; display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; } +.compare legend { font-weight: 600; padding: 0 .25rem; } +label { display: inline-flex; align-items: center; gap: .35rem; } 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 new file mode 100644 index 0000000..f3e779b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts @@ -0,0 +1,141 @@ +// 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. +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'; + +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 { + 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, + 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 }]; +const opciones = { n: 500, events: 133, covariables: {}, periodo: { desde: '2024-01-01', hasta: '2026-01-01' }, limites: { miembros_min: 30, muertes_min: 5 }, + paciente: { grade: 'G2', er: 'POSITIVO', her2: 'NA', age_group: '60-74' } }; + +describe('Figura de supervivencia de la paciente', () => { + const figura = (c: any = cohorte().curvas) => figuraSupervivenciaPaciente(horizontes, respuestaCurvas(c === null ? cohorte() : { ...cohorte(), curvas: c }).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', () => { + const f = figura(); + + expect(f.data.some((t: any) => t.fill === 'tonexty')).toBe(true); + expect(traza(f, ETIQUETAS_PREDETERMINADAS['km_crudo']).line).toMatchObject({ color: COLORES.km, shape: 'hv' }); + expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull']).line.color).toBe(COLORES.weibull); + expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull_fraccional']).line).toMatchObject({ color: COLORES.fraccional, dash: 'dash' }); + const rombos = traza(f, ETIQUETAS_PREDETERMINADAS['puntos']); + expect(rombos.x).toEqual([6, 12, 18]); + 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]); + }); + + // 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 = traza(f, ETIQUETAS_PREDETERMINADAS['paciente_puntos']); + + 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(traza(f, ETIQUETAS_PREDETERMINADAS['paciente']).line.color).toBe(COLORES.paciente); + }); + + // 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', () => { + const l = figura().layout as any; + + 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 the subgroup the reader chose is not what the title says. + it('names the subgroup in the title', () => { + const f = figuraSupervivenciaPaciente(horizontes, cohorte().curvas, 'claro', 'Pacientes con Grado de Nottingham G2')!; + + expect((f.layout as any).title.text).toContain('Pacientes con Grado de Nottingham G2'); + }); +}); + +describe('Supervivencia de la paciente: componente', () => { + let consulta: 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()))); + TestBed.configureTestingModule({ providers: [ + { provide: CamaCurvasService, useValue: { opciones: () => of(opciones), 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 for everyone first, or the covariates she has no value for are offered. + it('asks the cohort live, for everyone, and offers the covariates she has a value for', () => { + const f = montar(); + + expect(consulta).toHaveBeenCalledWith({ filtros: {} }); + expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); + const t = texto(f); + expect(t).toContain('Grado de Nottingham: G2'); + expect(t).toContain('Receptor de estrógeno: POSITIVO'); + expect(t).not.toContain('HER2:'); + }); + + // Fails if ticking a covariate does not ask the cohort for the patients who share it, or unticking does not go back. + it('asks for her subgroup when a covariate is ticked, and for everyone when it is unticked', () => { + const f = montar(); + + f.componentInstance.alternar('grade'); + f.detectChanges(); + expect(consulta).toHaveBeenLastCalledWith({ filtros: { grade: ['G2'] } }); + f.componentInstance.alternar('grade'); + f.detectChanges(); + expect(consulta).toHaveBeenLastCalledWith({ filtros: {} }); + }); + + // 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.'))); + const f = montar(); + + expect(texto(f)).toContain('La selección 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'))); + const f = montar(); + + expect(texto(f)).toContain('se muestra solo la de la paciente'); + expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); + }); +}); 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 new file mode 100644 index 0000000..b4080ae --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts @@ -0,0 +1,62 @@ +import { Component, computed, inject, input, signal } from '@angular/core'; +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, ConsultaCurvas, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service'; +import { figuraSupervivenciaPaciente } from './cama-supervivencia-paciente'; + +/** What the reader calls each covariate of the model. */ +export const COVARIABLES: Record = { + age_group: 'Grupo de edad', histologic_type: 'Tipo histológico', grade: 'Grado de Nottingham', er: 'Receptor de estrógeno', + pr: 'Receptor de progesterona', her2: 'HER2', ki67_group: 'Ki-67 (%)', size_group: 'Tamaño de la lesión (mm)', +}; + +type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas }; + +/** + * 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, for everyone or for the patients who share the covariates the + * reader ticks with her (her subgroup, as the pipeline draws its subgroups). Hers is her own prediction on top of them. + */ +@Component({ + selector: 'app-cama-supervivencia-paciente', + imports: [PlotlyChart], + 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); + /** The covariates she is compared on. */ + readonly cruces = signal([]); + readonly opciones = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.opciones(id)))); + /** The covariates she has a value for, to offer. */ + readonly cruzables = computed(() => { + const suyas = this.opciones()?.paciente; + return suyas ? Object.keys(COVARIABLES).filter(c => suyas[c] && suyas[c] !== 'NA').map(c => ({ clave: c, etiqueta: COVARIABLES[c], valor: suyas[c] })) : []; + }); + private readonly consulta = computed(() => { + const suyas = this.opciones()?.paciente; + return { filtros: Object.fromEntries(this.cruces().filter(c => suyas?.[c]).map(c => [c, [suyas![c]]])) }; + }); + readonly lectura = toSignal(toObservable(this.consulta).pipe(switchMap(q => this.service.consulta(q).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 }); + private readonly descripcion = computed(() => { + const suyas = this.opciones()?.paciente; + const partes = this.cruces().filter(c => suyas?.[c]).map(c => `${COVARIABLES[c]} ${suyas![c]}`); + return partes.length ? `Pacientes con ${partes.join(' · ')}` : null; + }); + /** 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, 'claro', this.descripcion()); + }); + alternar(clave: string): void { + this.cruces.update(actuales => actuales.includes(clave) ? actuales.filter(c => c !== clave) : [...actuales, clave]); + } +} 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 index fac1ee3..761687e 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts @@ -1,14 +1,18 @@ 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 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)', puntosConIntervalo: 'Modelo (LR + red bayesiana) con IC 95 %', -} as const; -export const COLOR_MODELO = '#6a3d9a'; +/** 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: supervivencia estimada', + paciente_puntos: 'Paciente: modelo en cada horizonte', +}; +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; @@ -37,29 +41,60 @@ export function curvaMensual(puntos: readonly PuntoDeSupervivencia[], hasta = ME 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 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); + 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 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: conIntervalo ? ETIQUETAS_PACIENTE.puntosConIntervalo : 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, + 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'), line: { color: COLORES.paciente, width: 3 }, + hovertemplate: '%{x} meses: %{y:.3f}' + t('paciente') + '' }, + { type: 'scatter', mode: 'markers', name: t('paciente_puntos'), 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:.1%}' }, - ]; + hovertemplate: '%{x} meses: %{y:.3f}' + t('paciente_puntos') + '' }); + 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: ETIQUETAS_PACIENTE.titulo, x: 0, xanchor: 'left', font: { size: 15, color: texto } }, + 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: { 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', + 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 187c2ce..895a996 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 @@ -67,22 +67,6 @@ describe('Supervivencia individual de la paciente CaMa', () => { 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(); - // The legend claims an interval only when one is drawn. - expect(rombos(con).name).toContain('IC 95 %'); - expect(rombos(sin).name).not.toContain('IC'); - expect(figuraSupervivenciaPaciente([])).toBeNull(); - }); }); describe('Riesgo individual de la paciente CaMa', () => { @@ -116,7 +100,7 @@ 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(f.nativeElement.querySelector('app-cama-supervivencia-paciente')).not.toBeNull(); expect(text).toContain('cama-survival'); expect(text).toContain('2025-06-19'); expect(text).toContain('Muerte por cualquier causa'); 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 c2a131d..474b7c5 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -38,8 +38,8 @@ } @else {

Sin horizontes evaluados en el lote vigente.

} - @if (figura(); as figure) { - + @if (dominio() === 'cama' && pacId(); as id) { + } } } 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 e59798d..d7af53f 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,14 +1,13 @@ 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 { CamaSupervivenciaPaciente } from './cama/cama-supervivencia-paciente.component'; 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, PlotlyChart], + imports: [DecimalPipe, CamaSupervivenciaPaciente], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -22,12 +21,6 @@ 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()); }); }