From a3a100450bbe800e5c6a07f09922904c398b328b Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 2 Dec 2026 23:20:51 -0600 Subject: [PATCH] =?UTF-8?q?Mostrar=20supervivencia=20con=20su=20curva=20de?= =?UTF-8?q?=20combinaci=C3=B3n=20y=20m=C3=A9todos=20por=20estimaci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/paciente/paciente.html | 163 ++++++++++-------- src/app/paciente/paciente.ts | 48 +++++- src/app/paciente/risk-scales.ts | 128 +++++++++++--- src/app/paciente/survival-combination.spec.ts | 25 +++ src/app/paciente/survival-combination.ts | 61 +++++++ 5 files changed, 318 insertions(+), 107 deletions(-) create mode 100644 src/app/paciente/survival-combination.spec.ts create mode 100644 src/app/paciente/survival-combination.ts diff --git a/src/app/paciente/paciente.html b/src/app/paciente/paciente.html index 1c5a653..d9d9d7d 100644 --- a/src/app/paciente/paciente.html +++ b/src/app/paciente/paciente.html @@ -246,66 +246,68 @@ } - - - @if (riskExclusion(); as reason) { -

{{ reason }}

- } @else { - - } - @if (riskModels().length) { -
- Modelos y valores - - - - - - - - - - - - @for (m of riskModels(); track m.model) { - @for (p of m.predictions; track p.years) { - - - - - - - + @if (riskExclusion() || groups().length || domain() !== 'cacu' || riskModels().length) { + + + @if (riskExclusion(); as reason) { +

{{ reason }}

+ } @else { + + } + @if (riskModels().length) { +
+ Modelos y valores +
ModeloFecha índiceHorizonteProbabilidadIC 95 %
{{ $first ? m.text : '' }}{{ $first ? m.index : '' }}{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-2' }} % - @if (p.low !== undefined) { - {{ p.low * 100 | number: '1.1-2' }}–{{ - p.high! * 100 | number: '1.1-2' - }} - % - } @else { - — - } -
+ + + + + + + + + + + @for (m of riskModels(); track m.model) { + @for (p of m.predictions; track p.years) { + + + + + + + + } } - } - -
ModeloFecha índiceHorizonteProbabilidadIC 95 %
{{ $first ? m.text : '' }}{{ $first ? m.index : '' }}{{ p.years }} {{ p.years === 1 ? 'año' : 'años' }}{{ p.p * 100 | number: '1.1-2' }} % + @if (p.low !== undefined) { + {{ p.low * 100 | number: '1.1-2' }}–{{ + p.high! * 100 | number: '1.1-2' + }} + % + } @else { + — + } +
-
- } - @if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) { -
- Curvas de probabilidad con su intervalo - @if (riskSeries.value()?.length) { - - } @else { - - } -
- } - @if (!riskModels().length && !groups()[0]?.survival && !riskExclusion()) { -

Sin evaluación de un modelo en producción.

- } -
-
+ + + + } + @if (!riskExclusion() && (riskModels().length || riskSeries.value()?.length)) { +
+ Curvas de probabilidad con su intervalo + @if (riskSeries.value()?.length) { + + } @else { + + } +
+ } + @if (!riskModels().length && !riskExclusion()) { +

Sin evaluación de un modelo en producción.

+ } + + + } @if (domain() === 'tea') { ADOS-2 @@ -561,15 +563,33 @@ }} -

Análisis de supervivencia

- @if (survival.isLoading()) { + @if (domain() !== 'cacu') { +

Análisis de supervivencia

+ } + @if (domain() === 'cacu') { + +

Curva de supervivencia

+ @if (combination.isLoading()) { + + } @else if (combination.error()) { + + } @else if (combination.value(); as c) { + @if (c.figure) { +

+ Kaplan-Meier de pacientes con sus mismos valores (IC 95 % Greenwood log-log; n = + {{ c.n }}, fallecidos = {{ c.fallecidos }}). +

+ + } @else { +

{{ c.missing }}

+ } + } @else { +

+ No disponible: la estimación no conserva los valores usados para elegir la curva. +

+ } + } @else if (survival.isLoading()) { - } @else if (domain() === 'cacu') { -

No disponible: el informe no contiene la curva para esta combinación.

-
- Métodos -

No hay un método publicado para esta combinación.

-
} @else if (survival.value(); as s) {

Escenario clínico de la paciente

    @@ -609,14 +629,7 @@ } @else if (survival.error()) { } @else { -

    - @if (domain() === 'cacu') { - No disponible: no hay un informe de supervivencia para los escenarios de la - paciente. - } @else { - No disponible: datos insuficientes. - } -

    +

    No disponible: datos insuficientes.

    } diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index dbb0199..ff9f40d 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -33,6 +33,7 @@ import { ineligibility } from './ineligibility'; import { parseSeries, RiskSeries, Series } from './risk-series'; import { curveFigure } from './risk-curve'; import { riskGroups, riskScales, RiskScales, survivalGroups } from './risk-scales'; +import { combinationFigure, combinationOf, noCurveText } from './survival-combination'; import { route, Stages } from './stages'; import { ageAt, ageGroup, CAMA_AGE_GROUPS, camaRows, CURP } from '../indicadores/follow-up'; 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))]; } +/** 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 | undefined { if (!value) return undefined; try { const parsed: unknown = JSON.parse(value); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) - ? parsed as Record : undefined; + ? (parsed as Record) + : undefined; } catch { return undefined; } @@ -198,16 +207,38 @@ export class Paciente { protected readonly scales = computed(() => 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(() => - this.domain() === 'cacu' - ? (() => { - const survival = survivalGroups(this.models().filter((m) => m.measure === 'mortality')); - return this.riskModels().length ? [...riskGroups(this.riskModels()), ...survival] - : survival.length ? survival : riskGroups([]); - })() + this.domain() === 'cacu' && (this.riskModels().length || !this.survivalScales().length) + ? riskGroups(this.riskModels()) : [], ); + 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, inputs); + return found?.km + ? { n: found.n, fallecidos: found.fallecidos, figure: combinationFigure(found.km) } + : { missing: noCurveText(report as Record, found) }; + }, + }); /** CaCu, experimental: the series her record can compare; none while the API has it off. */ protected readonly riskSeries = resource({ params: () => @@ -360,6 +391,7 @@ export class Paciente { index: r.occurrenceDateTime ?? '', measure: ext(r, 'prediction-measure')?.valueCode, inputs: modelInputs(ext(r, 'model-inputs')?.valueString), + evaluated: localDay(r.meta?.lastUpdated), // the clinical scenarios of the model's report she falls in scenarios: (r.extension ?? []) .filter((e) => e.url === EXT + 'escenario-clinico') diff --git a/src/app/paciente/risk-scales.ts b/src/app/paciente/risk-scales.ts index f500bd7..4c19c86 100644 --- a/src/app/paciente/risk-scales.ts +++ b/src/app/paciente/risk-scales.ts @@ -50,23 +50,50 @@ export interface RiskGroup { index?: string; survival?: boolean; inputs?: Record; + /** the model and version that scored her, and the day it did */ + model?: string; + evaluated?: string; scales: { label: string; risk?: Prediction }[]; } /** Stored survival-model probabilities are mortality: complement them to obtain S(t). */ -export function survivalGroups(models: { index: string; predictions: Prediction[]; - scenarios?: string[]; inputs?: Record }[]): RiskGroup[] { - return models.map((m) => ({ - title: 'Supervivencia', index: m.index, survival: true, inputs: m.inputs, - 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); +export function survivalGroups( + models: { + index: string; + predictions: Prediction[]; + scenarios?: string[]; + inputs?: Record; + text?: string; + evaluated?: string; + }[], +): RiskGroup[] { + return models + .map((m) => ({ + 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][] = [ @@ -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 * unavailable. */ export function riskGroups( - models: { text: string; index: string; predictions: Prediction[]; - inputs?: Record }[], + models: { + text: string; + index: string; + predictions: Prediction[]; + inputs?: Record; + evaluated?: string; + }[], ): RiskGroup[] { const scales = (predictions: Prediction[]) => HORIZONS.map(([years, label]) => ({ label, risk: horizon(predictions, years) })); @@ -93,6 +125,8 @@ export function riskGroups( ...titleParts(m.text), index: m.index, inputs: m.inputs, + model: m.text, + evaluated: m.evaluated, scales: scales(m.predictions), })) : [{ scales: scales([]) }]; @@ -154,13 +188,16 @@ export function riskGroups( {{ g.scenario ? 'Escenario: ' + g.scenario + ' · ' : '' }}Fecha índice {{ g.index }}

    } - @if (g.title) { + @if (g.title && !g.survival) {

    Factores de riesgo considerados

    @if (g.inputs) {
    @for (item of entries(g.inputs); track item[0]) { -
    {{ inputName(item[0]) }}
    {{ inputValue(item[0], item[1]) }}
    +
    +
    {{ inputName(item[0]) }}
    +
    {{ inputValue(item[0], item[1]) }}
    +
    }
    } @else { @@ -168,6 +205,35 @@ export function riskGroups( }
    } + @if (g.model) { +
    + Métodos +
    +
    +
    Modelo y versión
    +
    {{ g.model }}
    +
    +
    +
    Fecha índice
    +
    {{ g.index }}
    +
    +
    +
    Fecha de evaluación
    +
    {{ g.evaluated ?? 'No disponible' }}
    +
    +
    +
    Covariables
    +
    + @for (item of entries(g.inputs ?? {}); track item[0]) { +
    {{ inputName(item[0]) }}: {{ inputValue(item[0], item[1]) }}
    + } @empty { + No disponibles para esta estimación. + } +
    +
    +
    +
    + } } `, styles: ` @@ -205,8 +271,13 @@ export function riskGroups( ); } .survival .risk-line { - background: linear-gradient(to right, #c24269 0 25%, #df8640 25% 50%, - #a8c243 50% 75%, #42a77e 75% 100%); + background: linear-gradient( + to right, + #c24269 0 25%, + #df8640 25% 50%, + #a8c243 50% 75%, + #42a77e 75% 100% + ); } .risk-interval { border-left: 2px solid #17324d; @@ -255,11 +326,20 @@ export function riskGroups( export class RiskScales { readonly groups = input.required(); protected readonly entries = Object.entries; - 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', - } as Record)[name] ?? name; + 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', + }) as Record + )[name] ?? name; protected readonly inputValue = (name: string, value: unknown) => { if (value === null || value === undefined) return 'No documentado'; if (name.startsWith('hpv') && (value === 0 || value === 1 || typeof value === 'boolean')) diff --git a/src/app/paciente/survival-combination.spec.ts b/src/app/paciente/survival-combination.spec.ts new file mode 100644 index 0000000..f1e099b --- /dev/null +++ b/src/app/paciente/survival-combination.spec.ts @@ -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'); + }); +}); diff --git a/src/app/paciente/survival-combination.ts b/src/app/paciente/survival-combination.ts new file mode 100644 index 0000000..14ba0c5 --- /dev/null +++ b/src/app/paciente/survival-combination.ts @@ -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; + 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 | null | undefined, + inputs: Record, +): 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 | 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): 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; +}