CaMa survival figure in the patient's risk evaluation instead of a tab; no test-data tags on the risk record

This commit is contained in:
rockdrigo
2026-11-21 10:13:47 -06:00
parent 4fba4fa861
commit 4d159ae0d0
24 changed files with 140 additions and 734 deletions
@@ -76,11 +76,11 @@ describe('Ficha CaMa: componente', () => {
});
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
it('has placeholders, with no figures, for recurrence, survival and prognostic factors', () => {
it('has placeholders, with no figures, for recurrence and prognostic factors', () => {
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
const items = [...root().querySelectorAll('[data-pronostico]')];
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'survival', 'factors']);
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']);
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'factors']);
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Factores pronóstico']);
for (const item of items) {
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
expect(item.textContent).not.toMatch(/\d/);
@@ -9,8 +9,8 @@ import {
} from './cama-patient.models';
/**
* Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence,
* survival and prognostic factors are placeholders until a validated model supplies them.
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries and the patient's risk with her
* survival figure; recurrence and prognostic factors are placeholders until a validated model supplies them.
*/
@Component({
selector: 'app-cama-patient-card',
@@ -1,5 +1,5 @@
// Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only
// the fields of the record, shows placeholders (no figures) for recurrence, survival and prognostic factors, and
// the fields of the record, shows placeholders (no figures) for recurrence and prognostic factors (survival is drawn in the record from the risk evaluation), and
// renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test
// because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser.
import fixtureData from '../../fixtures/cama_seguimiento.json';
@@ -46,10 +46,10 @@ describe('Ficha CaMa: PDF individual', () => {
});
// Fails if a placeholder gains a figure or an explanation other than "unavailable".
it('has placeholders, with no figures, for recurrence, survival, prognostic factors and recommendations', () => {
it('has placeholders, with no figures, for recurrence, prognostic factors and recommendations', () => {
const found = texts(definition()['content']);
for (const t of ['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(3);
for (const t of ['Probabilidad de recurrencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(2);
});
// Fails if the document carries a platform identifier field.
@@ -27,10 +27,10 @@ export interface CamaPatientSummary {
daysMammographyToDiagnosis: number | null;
}
/** Placeholders for results that exist only once a validated model and its clinical definition do. */
/** Placeholders for results that exist only once a validated model and its clinical definition do (survival is drawn from
* the patient's risk evaluation, not a placeholder). */
export const PROGNOSIS_PLACEHOLDERS = [
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
{ key: 'survival', label: 'Supervivencia' },
{ key: 'factors', label: 'Factores pronóstico' },
] as const;
export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.';
@@ -0,0 +1,65 @@
import { PlotlyFigure, Tema } from '../../indicadores.models';
import { HorizonteRiesgoCacu } from '../paciente-riesgo.models';
import { tieneIntervalo } from '../paciente-riesgo.validation';
/** The clinicians' wording of the chart. */
export const ETIQUETAS_PACIENTE = {
titulo: 'Supervivencia de la paciente desde el primer reporte de biopsia con carcinoma invasor',
eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia',
curva: 'Supervivencia estimada', puntos: 'Modelo (LR + red bayesiana) con IC 95 %',
} as const;
export const COLOR_MODELO = '#6a3d9a';
/** The curve runs to this many months, as the cohort's does. */
export const MESES_MAXIMOS = 24;
export interface PuntoDeSupervivencia { meses: number; S: number; bajo: number | null; alto: number | null; }
/** The model's survival at each horizon: one minus the mortality of the `RiskAssessment`, its interval turned around. */
export function puntosDeSupervivencia(horizontes: readonly HorizonteRiesgoCacu[]): PuntoDeSupervivencia[] {
return horizontes.filter(h => h.horizonte_anios > 0).map(h => ({
meses: Math.round(h.horizonte_anios * 12), S: 1 - h.probabilidad,
bajo: tieneIntervalo(h) ? 1 - h.ic_alto! : null, alto: tieneIntervalo(h) ? 1 - h.ic_bajo! : null,
})).sort((a, b) => a.meses - b.meses);
}
/** The survival month by month: log-linear between 0 and the horizons (a constant hazard in each interval), and past the
* last one at the last interval's rate. It passes through every point and never rises. */
export function curvaMensual(puntos: readonly PuntoDeSupervivencia[], hasta = MESES_MAXIMOS): { meses: number[]; S: number[] } {
const bordes = [0, ...puntos.map(p => p.meses)], log = [0, ...puntos.map(p => Math.log(Math.max(p.S, 1e-12)))];
const ultimo = bordes.length - 1, pendiente = ultimo > 0 ? (log[ultimo] - log[ultimo - 1]) / (bordes[ultimo] - bordes[ultimo - 1]) : 0;
const meses = Array.from({ length: Math.max(hasta, bordes[ultimo]) + 1 }, (_, m) => m);
const S = meses.map(m => {
if (m >= bordes[ultimo]) return Math.exp(log[ultimo] + pendiente * (m - bordes[ultimo]));
let i = 0;
while (bordes[i + 1] < m) i++;
return Math.exp(log[i] + (log[i + 1] - log[i]) * (m - bordes[i]) / (bordes[i + 1] - bordes[i]));
});
return { meses, S: S.reduce<number[]>((acc, v) => [...acc, Math.min(v, acc.length ? acc[acc.length - 1] : 1)], []) };
}
/** The figure of one patient's survival: the model's curve and its survival at each horizon as diamonds, with the interval
* when the evaluation carries one. */
export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgoCacu[], tema: Tema = 'claro'): PlotlyFigure | null {
const puntos = puntosDeSupervivencia(horizontes);
if (puntos.length === 0) return null;
const curva = curvaMensual(puntos), conIntervalo = puntos.every(p => p.bajo !== null);
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
const minimo = Math.max(0, Math.min(...curva.S, ...puntos.map(p => p.bajo ?? 1)) - 0.05);
const data: Record<string, unknown>[] = [
{ 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%}<extra></extra>' },
{ type: 'scatter', mode: 'markers', name: ETIQUETAS_PACIENTE.puntos, x: puntos.map(p => p.meses), y: puntos.map(p => p.S),
marker: { symbol: 'diamond', size: 12, color: COLOR_MODELO, line: { color: 'white', width: 1 } },
...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLOR_MODELO, thickness: 1.8, width: 5,
array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}),
hovertemplate: '%{x} meses: %{y:.1%}<extra></extra>' },
];
const layout: Record<string, unknown> = {
title: { text: ETIQUETAS_PACIENTE.titulo, x: 0, xanchor: 'left', font: { size: 15, color: texto } },
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
xaxis: { title: { text: ETIQUETAS_PACIENTE.eje_x }, range: [0, curva.meses[curva.meses.length - 1] + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false },
yaxis: { title: { text: ETIQUETAS_PACIENTE.eje_y }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false },
legend: { orientation: 'h', y: -0.25, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 100 }, hovermode: 'closest',
};
return { data, layout, config: { responsive: true, displaylogo: false } };
}