Mostrar supervivencia con su curva de combinación y métodos por estimación

This commit is contained in:
2026-12-02 23:20:51 -06:00
parent a92515eb4d
commit a3a100450b
5 changed files with 318 additions and 107 deletions
+88 -75
View File
@@ -246,66 +246,68 @@
</mat-card> </mat-card>
} }
<mat-card appearance="outlined" class="wide" data-section="riesgos"> @if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) {
<mat-card-content> <mat-card appearance="outlined" class="wide" data-section="riesgos">
@if (riskExclusion(); as reason) { <mat-card-content>
<p role="status">{{ reason }}</p> @if (riskExclusion(); as reason) {
} @else { <p role="status">{{ reason }}</p>
<app-risk-scales [groups]="groups()" /> } @else {
} <app-risk-scales [groups]="groups()" />
@if (riskModels().length) { }
<details data-section="modelos"> @if (riskModels().length) {
<summary>Modelos y valores</summary> <details data-section="modelos">
<table class="plain"> <summary>Modelos y valores</summary>
<thead> <table class="plain">
<tr> <thead>
<th>Modelo</th> <tr>
<th>Fecha índice</th> <th>Modelo</th>
<th>Horizonte</th> <th>Fecha índice</th>
<th>Probabilidad</th> <th>Horizonte</th>
<th>IC 95 %</th> <th>Probabilidad</th>
</tr> <th>IC 95 %</th>
</thead> </tr>
<tbody> </thead>
@for (m of riskModels(); track m.model) { <tbody>
@for (p of m.predictions; track p.years) { @for (m of riskModels(); track m.model) {
<tr> @for (p of m.predictions; track p.years) {
<td>{{ $first ? m.text : '' }}</td> <tr>
<td>{{ $first ? m.index : '' }}</td> <td>{{ $first ? m.text : '' }}</td>
<td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td> <td>{{ $first ? m.index : '' }}</td>
<td>{{ p.p * 100 | number: '1.1-2' }} %</td> <td>{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}</td>
<td> <td>{{ p.p * 100 | number: '1.1-2' }} %</td>
@if (p.low !== undefined) { <td>
{{ p.low * 100 | number: '1.1-2' }}–{{ @if (p.low !== undefined) {
p.high! * 100 | number: '1.1-2' {{ p.low * 100 | number: '1.1-2' }}–{{
}} p.high! * 100 | number: '1.1-2'
% }}
} @else { %
— } @else {
} —
</td> }
</tr> </td>
</tr>
}
} }
} </tbody>
</tbody> </table>
</table> </details>
</details> }
} @if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) {
@if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) { <details class="curves" open data-section="curvas">
<details class="curves" open data-section="curvas"> <summary>Curvas de probabilidad con su intervalo</summary>
<summary>Curvas de probabilidad con su intervalo</summary> @if (riskSeries.value()?.length) {
@if (riskSeries.value()?.length) { <app-risk-series [series]="riskSeries.value()!" />
<app-risk-series [series]="riskSeries.value()!" /> } @else {
} @else { <app-plot [figure]="curve()" [height]="300" />
<app-plot [figure]="curve()" [height]="300" /> }
} </details>
</details> }
} @if (!riskModels().length && !riskExclusion()) {
@if (!riskModels().length && !groups()[0]?.survival && !riskExclusion()) { <p class="muted">Sin evaluación de un modelo en producción.</p>
<p class="muted">Sin evaluación de un modelo en producción.</p> }
} </mat-card-content>
</mat-card-content> </mat-card>
</mat-card> }
@if (domain() === 'tea') { @if (domain() === 'tea') {
<mat-card appearance="outlined" class="wide" data-section="tea"> <mat-card appearance="outlined" class="wide" data-section="tea">
<mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header> <mat-card-header><mat-card-title>ADOS-2</mat-card-title></mat-card-header>
@@ -561,15 +563,33 @@
}}</mat-card-title> }}</mat-card-title>
</mat-card-header> </mat-card-header>
<mat-card-content> <mat-card-content>
<h3>Análisis de supervivencia</h3> @if (domain() !== 'cacu') {
@if (survival.isLoading()) { <h3>Análisis de supervivencia</h3>
}
@if (domain() === 'cacu') {
<app-risk-scales [groups]="survivalScales()" />
<h3>Curva de supervivencia</h3>
@if (combination.isLoading()) {
<app-loading what="la curva de supervivencia" [figure]="true" />
} @else if (combination.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else if (combination.value(); as c) {
@if (c.figure) {
<p class="muted">
Kaplan-Meier de pacientes con sus mismos valores (IC 95 % Greenwood log-log; n =
{{ c.n }}, fallecidos = {{ c.fallecidos }}).
</p>
<app-plot [figure]="c.figure" [height]="340" />
} @else {
<p class="muted">{{ c.missing }}</p>
}
} @else {
<p class="muted">
No disponible: la estimación no conserva los valores usados para elegir la curva.
</p>
}
} @else if (survival.isLoading()) {
<app-loading what="las curvas de supervivencia" [figure]="true" /> <app-loading what="las curvas de supervivencia" [figure]="true" />
} @else if (domain() === 'cacu') {
<p class="muted">No disponible: el informe no contiene la curva para esta combinación.</p>
<details>
<summary>Métodos</summary>
<p class="muted">No hay un método publicado para esta combinación.</p>
</details>
} @else if (survival.value(); as s) { } @else if (survival.value(); as s) {
<h3>Escenario clínico de la paciente</h3> <h3>Escenario clínico de la paciente</h3>
<ul class="scenarios"> <ul class="scenarios">
@@ -609,14 +629,7 @@
} @else if (survival.error()) { } @else if (survival.error()) {
<p class="muted" role="alert">No se pudo leer el informe del modelo.</p> <p class="muted" role="alert">No se pudo leer el informe del modelo.</p>
} @else { } @else {
<p class="muted" data-state="sin-informe"> <p class="muted" data-state="sin-informe">No disponible: datos insuficientes.</p>
@if (domain() === 'cacu') {
No disponible: no hay un informe de supervivencia para los escenarios de la
paciente.
} @else {
No disponible: datos insuficientes.
}
</p>
} }
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
+40 -8
View File
@@ -33,6 +33,7 @@ import { ineligibility } from './ineligibility';
import { parseSeries, RiskSeries, Series } from './risk-series'; import { parseSeries, RiskSeries, Series } from './risk-series';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales'; import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales';
import { combinationFigure, combinationOf, noCurveText } from './survival-combination';
import { route, Stages } from './stages'; import { route, Stages } from './stages';
import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up';
import { LABELS, name, PRIORITY } from '../indicadores/measures'; import { LABELS, name, PRIORITY } from '../indicadores/measures';
@@ -79,12 +80,20 @@ function methods(figures: { figure: { data: unknown[] } }[]): string[] {
return [...new Set(names.filter((n): n is string => !!n))]; return [...new Set(names.filter((n): n is string => !!n))];
} }
/** The day of an instant in the hospital's time zone (America/Monterrey). */
function localDay(instant: string | undefined): string | undefined {
return instant
? new Date(instant).toLocaleDateString('en-CA', { timeZone: 'America/Monterrey' })
: undefined;
}
function modelInputs(value: string | undefined): Record<string, unknown> | undefined { function modelInputs(value: string | undefined): Record<string, unknown> | undefined {
if (!value) return undefined; if (!value) return undefined;
try { try {
const parsed: unknown = JSON.parse(value); const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as Record<string, unknown> : undefined; ? (parsed as Record<string, unknown>)
: undefined;
} catch { } catch {
return undefined; return undefined;
} }
@@ -198,16 +207,38 @@ export class Paciente {
protected readonly scales = computed(() => protected readonly scales = computed(() =>
this.domain() === 'cacu' ? riskScales(this.riskModels()) : [], this.domain() === 'cacu' ? riskScales(this.riskModels()) : [],
); );
/** CaCu: both horizons of every model, or both unavailable (the PDF keeps `scales`). */ /** CaCu: both horizons of every risk model, or both unavailable (the PDF keeps `scales`). With
* survival only there is nothing to draw here: its scales are in the survival section. */
protected readonly groups = computed(() => protected readonly groups = computed(() =>
this.domain() === 'cacu' this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length)
? (() => { ? riskGroups(this.riskModels())
const survival = survivalGroups(this.models().filter((m) => m.measure === 'mortality'));
return this.riskModels().length ? [...riskGroups(this.riskModels()), ...survival]
: survival.length ? survival : riskGroups([]);
})()
: [], : [],
); );
protected readonly survivalScales = computed(() =>
this.domain() === 'cacu'
? survivalGroups(this.models().filter((m) => m.measure === 'mortality'))
: [],
);
/** CaCu: the one Kaplan-Meier curve of the patients who share all her values, from the report of
* the model version that scored her. */
protected readonly combination = resource({
params: () => {
const m = this.models().find((x) => x.model === 'cacu.survival' && x.version && x.inputs);
return this.domain() === 'cacu' && m ? { version: m.version, inputs: m.inputs! } : undefined;
},
loader: async ({ params: { version, inputs } }) => {
const report = await this.api.invoke(readReport$Json, {
domain: 'cacu' as Domain,
name: 'survival',
version,
report: 'interpretability',
});
const found = combinationOf(report as Record<string, unknown>, inputs);
return found?.km
? { n: found.n, fallecidos: found.fallecidos, figure: combinationFigure(found.km) }
: { missing: noCurveText(report as Record<string, unknown>, found) };
},
});
/** CaCu, experimental: the series her record can compare; none while the API has it off. */ /** CaCu, experimental: the series her record can compare; none while the API has it off. */
protected readonly riskSeries = resource({ protected readonly riskSeries = resource({
params: () => params: () =>
@@ -360,6 +391,7 @@ export class Paciente {
index: r.occurrenceDateTime ?? '', index: r.occurrenceDateTime ?? '',
measure: ext(r, 'prediction-measure')?.valueCode, measure: ext(r, 'prediction-measure')?.valueCode,
inputs: modelInputs(ext(r, 'model-inputs')?.valueString), inputs: modelInputs(ext(r, 'model-inputs')?.valueString),
evaluated: localDay(r.meta?.lastUpdated),
// the clinical scenarios of the model's report she falls in // the clinical scenarios of the model's report she falls in
scenarios: (r.extension ?? []) scenarios: (r.extension ?? [])
.filter((e) => e.url === EXT + 'escenario-clinico') .filter((e) => e.url === EXT + 'escenario-clinico')
+104 -24
View File
@@ -50,23 +50,50 @@ export interface RiskGroup {
index?: string; index?: string;
survival?: boolean; survival?: boolean;
inputs?: Record<string, unknown>; inputs?: Record<string, unknown>;
/** the model and version that scored her, and the day it did */
model?: string;
evaluated?: string;
scales: { label: string; risk?: Prediction }[]; scales: { label: string; risk?: Prediction }[];
} }
/** Stored survival-model probabilities are mortality: complement them to obtain S(t). */ /** Stored survival-model probabilities are mortality: complement them to obtain S(t). */
export function survivalGroups(models: { index: string; predictions: Prediction[]; export function survivalGroups(
scenarios?: string[]; inputs?: Record<string, unknown> }[]): RiskGroup[] { models: {
return models.map((m) => ({ index: string;
title: 'Supervivencia', index: m.index, survival: true, inputs: m.inputs, predictions: Prediction[];
scenario: m.scenarios?.join(' · '), scenarios?: string[];
scales: m.predictions.flatMap((p) => { inputs?: Record<string, unknown>;
const v = horizon(m.predictions, p.years); text?: string;
return v ? [{ label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`, evaluated?: string;
risk: { years: p.years, p: 1 - v.p, }[],
low: v.high === undefined ? undefined : 1 - v.high, ): RiskGroup[] {
high: v.low === undefined ? undefined : 1 - v.low } }] : []; return models
}), .map((m) => ({
})).filter((g) => g.scales.length); title: 'Supervivencia',
index: m.index,
survival: true,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scenario: m.scenarios?.join(' · '),
scales: m.predictions.flatMap((p) => {
const v = horizon(m.predictions, p.years);
return v
? [
{
label: `Supervivencia a ${p.years} ${p.years === 1 ? 'año' : 'años'}`,
risk: {
years: p.years,
p: 1 - v.p,
low: v.high === undefined ? undefined : 1 - v.high,
high: v.low === undefined ? undefined : 1 - v.low,
},
},
]
: [];
}),
}))
.filter((g) => g.scales.length);
} }
const HORIZONS: [number, string][] = [ const HORIZONS: [number, string][] = [
@@ -83,8 +110,13 @@ export function titleParts(text: string): { title: string; scenario?: string } {
/** The scales the page draws: both horizons of every model, or, with no model, both horizons /** The scales the page draws: both horizons of every model, or, with no model, both horizons
* unavailable. */ * unavailable. */
export function riskGroups( export function riskGroups(
models: { text: string; index: string; predictions: Prediction[]; models: {
inputs?: Record<string, unknown> }[], text: string;
index: string;
predictions: Prediction[];
inputs?: Record<string, unknown>;
evaluated?: string;
}[],
): RiskGroup[] { ): RiskGroup[] {
const scales = (predictions: Prediction[]) => const scales = (predictions: Prediction[]) =>
HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) })); HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) }));
@@ -93,6 +125,8 @@ export function riskGroups(
...titleParts(m.text), ...titleParts(m.text),
index: m.index, index: m.index,
inputs: m.inputs, inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions), scales: scales(m.predictions),
})) }))
: [{ scales: scales([]) }]; : [{ scales: scales([]) }];
@@ -154,13 +188,16 @@ export function riskGroups(
{{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }} {{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}
</p> </p>
} }
@if (g.title) { @if (g.title && !g.survival) {
<section> <section>
<h4>Factores de riesgo considerados</h4> <h4>Factores de riesgo considerados</h4>
@if (g.inputs) { @if (g.inputs) {
<dl> <dl>
@for (item of entries(g.inputs); track item[0]) { @for (item of entries(g.inputs); track item[0]) {
<div><dt>{{ inputName(item[0]) }}</dt><dd>{{ inputValue(item[0], item[1]) }}</dd></div> <div>
<dt>{{ inputName(item[0]) }}</dt>
<dd>{{ inputValue(item[0], item[1]) }}</dd>
</div>
} }
</dl> </dl>
} @else { } @else {
@@ -168,6 +205,35 @@ export function riskGroups(
} }
</section> </section>
} }
@if (g.model) {
<details data-section="metodos">
<summary>Métodos</summary>
<dl>
<div>
<dt>Modelo y versión</dt>
<dd>{{ g.model }}</dd>
</div>
<div>
<dt>Fecha índice</dt>
<dd>{{ g.index }}</dd>
</div>
<div>
<dt>Fecha de evaluación</dt>
<dd>{{ g.evaluated ?? 'No disponible' }}</dd>
</div>
<div>
<dt>Covariables</dt>
<dd>
@for (item of entries(g.inputs ?? {}); track item[0]) {
<div>{{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}</div>
} @empty {
No disponibles para esta estimación.
}
</dd>
</div>
</dl>
</details>
}
} }
`, `,
styles: ` styles: `
@@ -205,8 +271,13 @@ export function riskGroups(
); );
} }
.survival .risk-line { .survival .risk-line {
background: linear-gradient(to right, #c24269 0 25%, #df8640 25% 50%, background: linear-gradient(
#a8c243 50% 75%, #42a77e 75% 100%); to right,
#c24269 0 25%,
#df8640 25% 50%,
#a8c243 50% 75%,
#42a77e 75% 100%
);
} }
.risk-interval { .risk-interval {
border-left: 2px solid #17324d; border-left: 2px solid #17324d;
@@ -255,11 +326,20 @@ export function riskGroups(
export class RiskScales { export class RiskScales {
readonly groups = input.required<RiskGroup[]>(); readonly groups = input.required<RiskGroup[]>();
protected readonly entries = Object.entries; protected readonly entries = Object.entries;
protected readonly inputName = (name: string) => ({ protected readonly inputName = (name: string) =>
age_group: 'Edad al diagnóstico', cytology: 'Citología', hpv: 'VPH', (
hpv_positive: 'VPH', hpv_16_18: 'VPH 16/18', referral_grade: 'Referencia', ({
bethesda: 'Citología', hpv_16: 'VPH 16', hpv_18: 'VPH 18', age_group: 'Edad al diagnóstico',
} as Record<string, string>)[name] ?? name; cytology: 'Citología',
hpv: 'VPH',
hpv_positive: 'VPH',
hpv_16_18: 'VPH 16/18',
referral_grade: 'Referencia',
bethesda: 'Citología',
hpv_16: 'VPH 16',
hpv_18: 'VPH 18',
}) as Record<string, string>
)[name] ?? name;
protected readonly inputValue = (name: string, value: unknown) => { protected readonly inputValue = (name: string, value: unknown) => {
if (value === null || value === undefined) return 'No documentado'; if (value === null || value === undefined) return 'No documentado';
if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean')) if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean'))
@@ -0,0 +1,25 @@
import { combinationOf, noCurveText } from './survival-combination';
describe('combinationOf', () => {
const values = { age_group: '<30', cytology: 'NA', hpv: 'positive' };
const report = { km_combinaciones: [{ valores: values, n: 9, fallecidos: 6 }] };
it('takes only the entry with all her values, a missing one as NA', () => {
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'positive' })?.n).toBe(9);
expect(combinationOf(report, { age_group: '<30', cytology: null, hpv: 'negative' })).toBe(
undefined,
);
expect(combinationOf(report, { age_group: '<30' })).toBe(undefined);
expect(combinationOf({}, values)).toBe(undefined);
});
it('tells an old report apart from a combination with too few deaths', () => {
expect(noCurveText({}, undefined)).toContain('no publica esta curva');
expect(
noCurveText(
{ ...report, min_fallecidos_escenario: 5 },
{ valores: values, n: 9, fallecidos: 2 },
),
).toContain('n = 9, fallecidos = 2; mínimo requerido: 5');
});
});
+61
View File
@@ -0,0 +1,61 @@
import { Figure, PALETTE } from '../plot';
/** One entry of the survival report's `km_combinaciones`: the patients who share every value. */
export interface Combination {
valores: Record<string, string>;
n: number;
fallecidos: number;
km?: { months: number[]; S: number[]; low: number[]; high: number[] };
}
/** The entry with exactly her values (a missing one is the report's "NA"); never a partial match. */
export function combinationOf(
report: Record<string, unknown> | null | undefined,
inputs: Record<string, unknown>,
): Combination | undefined {
const all = report?.['km_combinaciones'];
return (Array.isArray(all) ? (all as Combination[]) : []).find((c) => {
const keys = Object.keys(c.valores);
return (
keys.length === Object.keys(inputs).length &&
keys.every((k) => k in inputs && c.valores[k] === String(inputs[k] ?? 'NA'))
);
});
}
/** Why there is no curve for her: these are not the same thing, so each is said apart. (A patient
* outside the survival scenario has no survival section at all.) */
export function noCurveText(
report: Record<string, unknown> | null | undefined,
found: Combination | undefined,
): string {
if (!Array.isArray(report?.['km_combinaciones']))
return 'No disponible: la versión del modelo que la evaluó no publica esta curva.';
const minimum = report['min_fallecidos_escenario'];
const counts = `n = ${found?.n ?? 0}, fallecidos = ${found?.fallecidos ?? 0}`;
return `No disponible: datos insuficientes para su combinación de valores (${counts}${
typeof minimum === 'number' ? `; mínimo requerido: ${minimum} fallecidos` : ''
}).`;
}
export function combinationFigure(km: NonNullable<Combination['km']>): Figure {
const line = (y: number[], more: object) => ({
type: 'scatter',
mode: 'lines',
x: km.months,
y,
line: { shape: 'hv', color: PALETTE[0], width: 0 },
...more,
});
return {
data: [
line(km.low, { showlegend: false, hoverinfo: 'skip' }),
line(km.high, { name: 'IC 95 %', fill: 'tonexty', fillcolor: 'rgba(23, 50, 77, 0.15)' }),
line(km.S, { name: 'Kaplan-Meier', line: { shape: 'hv', color: PALETTE[0], width: 2 } }),
],
layout: {
xaxis: { title: { text: 'Meses desde el índice' } },
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [0, 1.02], tickformat: '.0%' },
},
} as Figure;
}