From 4c181af291b5ffa1931c6e20f0d663d529a57184 Mon Sep 17 00:00:00 2001 From: ulises Date: Sun, 22 Nov 2026 08:46:39 -0600 Subject: [PATCH] CaMa patient card: the recurrence figure of the scenarios the patient meets, and a menu of both cohorts' scenarios MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shown only for patients after treatment, in the recurrence slot of "Pronóstico y recomendaciones". Includes the survival figure this builds on. Co-Authored-By: Claude Sonnet 5.5 --- .../cama/cama-patient-card.html | 8 +- .../cama/cama-patient-card.ts | 8 +- .../cama/cama-recurrencia-figura.ts | 55 +++++++++++ .../cama/cama-recurrencia.html | 38 ++++++++ .../cama/cama-recurrencia.models.ts | 49 ++++++++++ .../cama/cama-recurrencia.scss | 4 + .../cama/cama-recurrencia.service.ts | 29 ++++++ .../paciente-detalle/cama/cama-recurrencia.ts | 95 +++++++++++++++++++ .../cama/cama-supervivencia-figura.ts | 45 +++++++++ .../cama/cama-supervivencia.html | 16 ++++ .../cama/cama-supervivencia.models.ts | 42 ++++++++ .../cama/cama-supervivencia.scss | 3 + .../cama/cama-supervivencia.service.ts | 20 ++++ .../cama/cama-supervivencia.ts | 63 ++++++++++++ 14 files changed, 471 insertions(+), 4 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 1fef561..28df1cf 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -38,7 +38,13 @@
    @for (item of placeholders; track item.key) { -
  • {{ item.label }}{{ prognosisUnavailable }}
  • + @if (item.key === 'recurrence' && p.idField === 'pac_id') { +
  • {{ item.label }}
  • + } @else if (item.key === 'survival' && p.idField === 'pac_id') { +
  • {{ item.label }}
  • + } @else { +
  • {{ item.label }}{{ prognosisUnavailable }}
  • + } }

{{ recommendationsUnavailable }}

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 a59872c..d7117ef 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 @@ -3,17 +3,19 @@ import { downloadBlob, exportFilename } from '../../export/download-file'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; +import { CamaRecurrencia } from './cama-recurrencia'; +import { CamaSupervivencia } from './cama-supervivencia'; import { CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, } 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: what the follow-up list carries and, in its prognosis card, the recurrence and + * survival figures of the clinical scenarios the patient belongs to. */ @Component({ selector: 'app-cama-patient-card', - imports: [MatButtonModule, MatCardModule, MatIconModule], + imports: [CamaRecurrencia, CamaSupervivencia, MatButtonModule, MatCardModule, MatIconModule], templateUrl: './cama-patient-card.html', styleUrl: './cama-patient-card.scss', }) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts new file mode 100644 index 0000000..aac3bd9 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts @@ -0,0 +1,55 @@ +import { PlotlyFigure } from '../../indicadores.models'; +import { RecurrenciaFigura } from './cama-recurrencia.models'; + +const decimales = new Intl.NumberFormat('es-MX'); +const finitos = (valores: (number | null)[]) => valores.filter((v): v is number => v !== null && Number.isFinite(v)); + +/** + * The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull (dotted past the + * follow-up), and the combined estimate at each horizon with its bootstrap interval. + */ +export function figuraRecurrencia(figura: RecurrenciaFigura): PlotlyFigure { + const km = figura.km; + const seguimiento = km.months[km.months.length - 1]; + const combinado = figura.points.COMB; + const tiempos = figura.weibull.t; + const dentro = tiempos.map(t => t <= seguimiento); + const trazo = (S: (number | null)[], dentroDelSeguimiento: boolean) => + S.map((v, i) => (dentro[i] === dentroDelSeguimiento || (!dentroDelSeguimiento && tiempos[i] === seguimiento) ? v : null)); + const todos = [...finitos(km.low), ...finitos(km.high), ...finitos(combinado.low), ...finitos(combinado.high), + ...finitos(figura.weibull.S), ...finitos(figura.weibull_fractional.S)]; + const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06; + const horizontes = figura.horizons_months; + const S = combinado.S.map(v => v ?? NaN); + return { + data: [ + { x: km.months, y: km.low, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false }, + { x: km.months, y: km.high, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', + fillcolor: 'rgba(154,165,177,0.3)', hoverinfo: 'skip', showlegend: false }, + { x: km.months, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' }, + name: 'Kaplan-Meier (IC 95 % Greenwood)' }, + { x: tiempos, y: trazo(figura.weibull.S, true), type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' }, + { x: tiempos, y: trazo(figura.weibull.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#1f77b4', dash: 'dot' }, + hoverinfo: 'skip', showlegend: false }, + { x: tiempos, y: trazo(figura.weibull_fractional.S, true), type: 'scatter', mode: 'lines', + line: { width: 3, color: '#d1495b', dash: 'dash' }, name: 'Weibull fraccional' }, + { x: tiempos, y: trazo(figura.weibull_fractional.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#d1495b', dash: 'dot' }, + hoverinfo: 'skip', showlegend: false }, + { x: horizontes, y: S, type: 'scatter', mode: 'markers', + marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } }, + error_y: { type: 'data', symmetric: false, array: combinado.high.map((v, i) => (v ?? NaN) - S[i]), + arrayminus: combinado.low.map((v, i) => S[i] - (v ?? NaN)), color: '#6a3d9a', thickness: 2, width: 5 }, + name: 'LR + HBN combinado (IC 95 % bootstrap)' }, + ], + layout: { + title: { text: `${figura.escenario}
${figura.cohorte_nombre} · n=${decimales.format(figura.n)}, recaídas=${decimales.format(figura.recaidas)}`, + font: { size: 15 } }, + xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, figura.months_max + 0.8], dtick: 12, zeroline: false }, + yaxis: { title: { text: 'Libre de recaída S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] }, + legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' }, + margin: { l: 70, r: 20, t: 70, b: 60 }, + hovermode: 'x unified', + }, + config: { responsive: true, displaylogo: false }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html new file mode 100644 index 0000000..b518b4e --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html @@ -0,0 +1,38 @@ +@switch (estado()) { + @case ('cargando') { } + @case ('sin-modelo') {

No hay una cohorte armada para el análisis de recurrencia.

} + @case ('error') { } + @default { + @if (!postratamiento()) { +

El análisis de recurrencia es para pacientes que ya terminaron su tratamiento.

+ } @else { + @if (deLaPaciente().length) { + + @for (e of deLaPaciente(); track e.cohorte + e.escenario) { + {{ nombreCohorte(e.cohorte) }} · {{ e.escenario }} + } + + } @else { +

La paciente no pertenece a ninguno de los escenarios clínicos del modelo. Elige uno del menú.

+ } + + } + @if (calculando()) { } + @if (figura(); as f) { } + @if (mensaje(); as texto) {

{{ texto }}

} + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts new file mode 100644 index 0000000..659eee5 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts @@ -0,0 +1,49 @@ +/** The recurrence analysis as `/cama/recurrencia` gives it: the scenarios of each cohort, a scenario's figure and a patient's scenarios. */ +export interface RecurrenciaEscenario { nombre: string; condiciones: Record; n: number; recaidas: number; dibujable: boolean } +export interface RecurrenciaCohorte { id: string; nombre: string; estado: 'calculando' | 'listo' | 'error'; error: string | null; escenarios: RecurrenciaEscenario[] } +export interface RecurrenciaEscenarios { build: number; horizontes: number[]; cohortes: RecurrenciaCohorte[] } +export interface RecurrenciaDePaciente { build: number; pac_id: number; postratamiento: boolean; escenarios: { cohorte: string; escenario: string }[] } + +export interface RecurrenciaFigura { + cohorte: string; + cohorte_nombre: string; + escenario: string; + n: number; + recaidas: number; + horizons_months: number[]; + months_max: number; + bootstrap_replicas: number; + km: { months: number[]; S: number[]; low: number[]; high: number[] }; + weibull: { t: number[]; S: (number | null)[] }; + weibull_fractional: { t: number[]; S: (number | null)[] }; + points: { COMB: { S: (number | null)[]; low: (number | null)[]; high: (number | null)[] } }; +} +export type RecurrenciaRespuestaFigura = { estado: 'calculando' } | { estado: 'listo'; figura: RecurrenciaFigura }; + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number'); + +export function recurrenciaEscenarios(v: unknown): RecurrenciaEscenarios { + if (!record(v) || typeof v['build'] !== 'number' || !numbers(v['horizontes']) || !Array.isArray(v['cohortes']) + || !v['cohortes'].every(c => record(c) && typeof c['id'] === 'string' && typeof c['nombre'] === 'string' && Array.isArray(c['escenarios']))) { + throw new Error('Respuesta de escenarios de recurrencia inválida'); + } + return v as unknown as RecurrenciaEscenarios; +} + +export function recurrenciaDePaciente(v: unknown): RecurrenciaDePaciente { + if (!record(v) || typeof v['postratamiento'] !== 'boolean' || !Array.isArray(v['escenarios']) + || !v['escenarios'].every(e => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')) { + throw new Error('Respuesta de recurrencia de la paciente inválida'); + } + return v as unknown as RecurrenciaDePaciente; +} + +export function recurrenciaFigura(v: unknown): RecurrenciaFigura { + if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte'] !== 'string' || typeof v['n'] !== 'number' + || typeof v['recaidas'] !== 'number' || !numbers(v['horizons_months']) || !record(v['km']) || !numbers(v['km']['months']) + || !numbers(v['km']['S']) || !record(v['weibull']) || !record(v['weibull_fractional']) || !record(v['points'])) { + throw new Error('Respuesta de figura de recurrencia inválida'); + } + return v as unknown as RecurrenciaFigura; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss new file mode 100644 index 0000000..fbd6238 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss @@ -0,0 +1,4 @@ +:host { display: block; min-width: 0; --plot-height: 420px; } +.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; } +.menu { display: flex; flex-wrap: wrap; gap: 0.75rem; margin: 0.75rem 0; } +.availability { margin: 0; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts new file mode 100644 index 0000000..980c059 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts @@ -0,0 +1,29 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http'; +import { map } from 'rxjs'; +import { + recurrenciaDePaciente, recurrenciaEscenarios, recurrenciaFigura, RecurrenciaRespuestaFigura, +} from './cama-recurrencia.models'; + +@Injectable({ providedIn: 'root' }) +export class CamaRecurrenciaService { + private readonly http = inject(HttpClient); + + /** The scenarios of each cohort, with their size and whether they have enough recurrences to be drawn. */ + escenarios() { + return this.http.get('/cama/recurrencia/escenarios').pipe(map(recurrenciaEscenarios)); + } + + /** The scenarios a patient's covariates meet, in each cohort; empty for a patient who is not after treatment. */ + deLaPaciente(pacId: number) { + return this.http.get(`/cama/recurrencia/pacientes/${pacId}`).pipe(map(recurrenciaDePaciente)); + } + + /** The figure of one scenario; `calculando` while the cohort's models are being computed. */ + figura(cohorte: string, escenario: string) { + const params = new HttpParams().set('cohorte', cohorte).set('escenario', escenario); + return this.http.get('/cama/recurrencia/figura', { params, observe: 'response' }).pipe( + map((r: HttpResponse): RecurrenciaRespuestaFigura => + r.status === 202 ? { estado: 'calculando' } : { estado: 'listo', figura: recurrenciaFigura(r.body) })); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts new file mode 100644 index 0000000..48b5943 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts @@ -0,0 +1,95 @@ +import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { forkJoin, Subscription, timer } from 'rxjs'; +import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from '../../indicadores.models'; +import { figuraRecurrencia } from './cama-recurrencia-figura'; +import { RecurrenciaCohorte } from './cama-recurrencia.models'; +import { CamaRecurrenciaService } from './cama-recurrencia.service'; + +const ESPERA_CALCULO_MS = 5000; + +/** + * A patient's recurrence: the clinical scenarios her covariates meet and, from a menu, any scenario of either cohort, with the + * figure of the one chosen, computed over the live cohort. + */ +@Component({ + selector: 'app-cama-recurrencia', + imports: [MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], + templateUrl: './cama-recurrencia.html', + styleUrl: './cama-recurrencia.scss', +}) +export class CamaRecurrencia { + readonly pacId = input.required(); + readonly estado = signal<'cargando' | 'listo' | 'sin-modelo' | 'error'>('cargando'); + readonly postratamiento = signal(false); + readonly cohortes = signal([]); + readonly deLaPaciente = signal<{ cohorte: string; escenario: string }[]>([]); + readonly elegido = signal<{ cohorte: string; escenario: string } | null>(null); + readonly figura = signal(null); + readonly calculando = signal(false); + readonly mensaje = signal(null); + private readonly menuCohorte = signal(null); + readonly cohorteDelMenu = computed(() => this.menuCohorte() ?? this.elegido()?.cohorte ?? this.cohortes()[0]?.id ?? ''); + readonly escenariosDelMenu = computed(() => + this.cohortes().find(c => c.id === this.cohorteDelMenu())?.escenarios.filter(e => e.dibujable) ?? []); + private readonly servicio = inject(CamaRecurrenciaService); + private readonly destroy = inject(DestroyRef); + private pedido?: Subscription; + + constructor() { + effect(() => this.cargar(this.pacId())); + } + + nombreCohorte(id: string) { return this.cohortes().find(c => c.id === id)?.nombre ?? id; } + + private cargar(pacId: number) { + this.estado.set('cargando'); this.limpiar(); this.elegido.set(null); this.menuCohorte.set(null); + forkJoin({ menu: this.servicio.escenarios(), paciente: this.servicio.deLaPaciente(pacId) }) + .pipe(takeUntilDestroyed(this.destroy)).subscribe({ + next: ({ menu, paciente }) => { + this.cohortes.set(menu.cohortes); + this.postratamiento.set(paciente.postratamiento); + this.deLaPaciente.set(paciente.escenarios); + this.estado.set('listo'); + if (paciente.postratamiento && paciente.escenarios.length) this.elegir(paciente.escenarios[0].cohorte, paciente.escenarios[0].escenario); + }, + error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'), + }); + } + + private limpiar() { this.figura.set(null); this.mensaje.set(null); this.calculando.set(false); this.pedido?.unsubscribe(); } + + elegirDePaciente(clave: string) { const [cohorte, ...resto] = clave.split('|'); this.elegir(cohorte, resto.join('|')); } + + elegirCohorte(cohorte: string) { this.menuCohorte.set(cohorte); this.elegido.set(null); this.limpiar(); } + + elegir(cohorte: string, escenario: string) { + this.limpiar(); + this.elegido.set({ cohorte, escenario }); this.menuCohorte.set(cohorte); this.calculando.set(true); + const vigente = () => this.elegido()?.cohorte === cohorte && this.elegido()?.escenario === escenario; + const pedir = () => { + this.pedido = this.servicio.figura(cohorte, escenario).subscribe({ + next: r => { + if (!vigente()) return; + if (r.estado === 'calculando') { + this.mensaje.set('Calculando los modelos de la cohorte; la figura aparecerá en cuanto estén listos.'); + this.pedido = timer(ESPERA_CALCULO_MS).subscribe(() => { if (vigente()) pedir(); }); + return; + } + this.calculando.set(false); this.mensaje.set(null); this.figura.set(figuraRecurrencia(r.figura)); + }, + error: (e: { status?: number }) => { + if (!vigente()) return; + this.calculando.set(false); + this.mensaje.set(e?.status === 404 ? 'El escenario tiene pocas recaídas para dibujar su curva.' : 'No se pudo calcular la figura. Intenta nuevamente.'); + }, + }); + }; + pedir(); + } +} 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..f914101 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts @@ -0,0 +1,45 @@ +import { PlotlyFigure } from '../../indicadores.models'; +import { SupervivenciaFigura } from './cama-supervivencia.models'; + +const decimales = new Intl.NumberFormat('es-MX'); + +/** + * The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the + * LR + HBN combined survival at each horizon with its bootstrap interval. + */ +export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure { + const meses = figura.months ?? []; + const km = figura.km!; + const curvas = figura.curve_months ?? []; + const combinados = figura.points.filter(p => p.model === 'COMB'); + const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1]; + const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])] + .filter(v => Number.isFinite(v)); + const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06; + return { + data: [ + { x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false }, + { x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)', + hoverinfo: 'skip', showlegend: false }, + { x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' }, + name: 'Kaplan-Meier (IC 95 % Greenwood)' }, + { x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' }, + { x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' }, + name: 'Weibull fraccional' }, + { x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers', + marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } }, + error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low), + color: '#6a3d9a', thickness: 2, width: 5 }, + name: 'LR + HBN combinado (IC 95 % bootstrap)' }, + ], + layout: { + title: { text: `${figura.scenario}
n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } }, + xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false }, + yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] }, + legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' }, + margin: { l: 70, r: 20, t: 70, b: 60 }, + hovermode: 'x unified', + }, + config: { responsive: true, displaylogo: false }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html new file mode 100644 index 0000000..a516010 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html @@ -0,0 +1,16 @@ +@switch (estado()) { + @case ('cargando') { } + @case ('sin-modelo') {

No hay un modelo de supervivencia en producción.

} + @case ('error') { } + @case ('sin-escenarios') {

La paciente no pertenece a ninguno de los escenarios clínicos del modelo.

} + @default { + @if (escenarios().length > 1) { + + @for (nombre of escenarios(); track nombre) { {{ nombre }} } + + } + @if (cargandoFigura()) { } + @if (figura(); as f) { } + @if (sinDibujo(); as mensaje) {

{{ mensaje }}

} + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts new file mode 100644 index 0000000..00c744b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts @@ -0,0 +1,42 @@ +/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */ +export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number } + +export interface SupervivenciaFigura { + scenario: string; + members: number; + deaths: number; + drawable: boolean; + horizons: number[]; + months?: number[]; + km?: { S: number[]; lo: number[]; hi: number[] }; + curve_months?: number[]; + weibull?: { k: number; S: number[] }; + fractional?: { k: number; alpha: number; beta: number; S: number[] }; + points: SupervivenciaPunto[]; +} + +export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] } + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number'); + +export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios { + if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string') + || typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') { + throw new Error('Respuesta de escenarios de supervivencia inválida'); + } + return v as unknown as SupervivenciaEscenarios; +} + +export function supervivenciaFigura(v: unknown): SupervivenciaFigura { + if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number' + || typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) { + throw new Error('Respuesta de figura de supervivencia inválida'); + } + if (v['drawable']) { + const km = v['km'], w = v['weibull'], f = v['fractional']; + if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi']) + || !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta'); + } + return v as unknown as SupervivenciaFigura; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss new file mode 100644 index 0000000..d2249ae --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss @@ -0,0 +1,3 @@ +:host { display: block; min-width: 0; --plot-height: 420px; } +.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; } +.availability { margin: 0; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts new file mode 100644 index 0000000..a85c12b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts @@ -0,0 +1,20 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { map } from 'rxjs'; +import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models'; + +@Injectable({ providedIn: 'root' }) +export class CamaSupervivenciaService { + private readonly http = inject(HttpClient); + + /** The scenarios a patient belongs to, from her variables over the timeline. */ + escenarios(pacId: number) { + return this.http.get(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios)); + } + + /** The figure of one scenario over the production model and the live cohort. */ + figura(escenario: string) { + const params = new HttpParams().set('escenario', escenario); + return this.http.get('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura)); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts new file mode 100644 index 0000000..b90f182 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts @@ -0,0 +1,63 @@ +import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { Subscription } from 'rxjs'; +import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from '../../indicadores.models'; +import { figuraSupervivencia } from './cama-supervivencia-figura'; +import { CamaSupervivenciaService } from './cama-supervivencia.service'; + +/** + * A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in + * production and the live cohort. + */ +@Component({ + selector: 'app-cama-supervivencia', + imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart], + templateUrl: './cama-supervivencia.html', + styleUrl: './cama-supervivencia.scss', +}) +export class CamaSupervivencia { + readonly pacId = input.required(); + readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando'); + readonly escenarios = signal([]); + readonly elegido = signal(null); + readonly figura = signal(null); + readonly cargandoFigura = signal(false); + readonly sinDibujo = signal(null); + private readonly servicio = inject(CamaSupervivenciaService); + private readonly destroy = inject(DestroyRef); + private pedido?: Subscription; + + constructor() { + effect(() => this.cargar(this.pacId())); + } + + private cargar(pacId: number) { + this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null); + this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({ + next: respuesta => { + this.escenarios.set(respuesta.scenarios); + if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; } + this.estado.set('listo'); + this.elegir(respuesta.scenarios[0]); + }, + error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'), + }); + } + + elegir(escenario: string) { + this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true); + this.pedido?.unsubscribe(); + this.pedido = this.servicio.figura(escenario).subscribe({ + next: f => { + this.cargandoFigura.set(false); + if (this.elegido() !== escenario) return; + if (f.drawable) this.figura.set(figuraSupervivencia(f)); + else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`); + }, + error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); }, + }); + } +}