Compare commits

...

10 Commits

16 changed files with 499 additions and 194 deletions
+1 -1
View File
@@ -84,7 +84,7 @@ test("indicators: the KPIs are the API's MeasureReports, every tab and the patie
).not.toContainText('Sin estudios'); ).not.toContainText('Sin estudios');
await page.goto('/indicadores/cama'); await page.goto('/indicadores/cama');
await expect(page.getByRole('tab', { name: 'Indicadores' })).toBeVisible(); await expect(page.getByRole('tab', { name: 'Resumen' })).toBeVisible();
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
await page.locator('mat-form-field', { hasText: 'Ventana' }).click(); await page.locator('mat-form-field', { hasText: 'Ventana' }).click();
await page.getByRole('option', { name: '12 meses' }).click(); await page.getByRole('option', { name: '12 meses' }).click();
+21
View File
@@ -54,6 +54,8 @@ export type Mode = {
hidden?: Hidden; hidden?: Hidden;
} }
| { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint } | { kind: 'days'; steps: { label: string; measure: string }[]; tint?: Tint }
/** A proportion as one bar of 0 to 100 %, its 95 % interval as the two marks on it */
| { kind: 'ratio'; measure: string; colors?: Colors }
| { kind: 'days-by'; measure: string; stratum: string; tint?: Tint } | { kind: 'days-by'; measure: string; stratum: string; tint?: Tint }
/** A proportion as its two parts (what counted and what did not), in units, with the shares */ /** A proportion as its two parts (what counted and what did not), in units, with the shares */
| { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] } | { kind: 'split'; measure: string; yes: string; no: string; colors?: [string, string] }
@@ -204,6 +206,25 @@ const days = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
/** The bars of a mode; none when the period has nothing to draw. */ /** The bars of a mode; none when the period has nothing to draw. */
export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined { export function bars(mode: Mode, of: (measure: string) => Reading | undefined): Bars | undefined {
switch (mode.kind) { switch (mode.kind) {
case 'ratio': {
const r = of(mode.measure);
const n = r?.populations['numerator'] ?? 0;
const total = r?.populations['denominator'] ?? 0;
if (r?.score === undefined || !total) return undefined;
const ends = r.low !== undefined && r.high !== undefined ? [r.low, r.high] : [];
return {
head: ['n/N', '%', 'IC 95 %'],
rows: [
{
label: 'Total',
color: mode.colors?.['numerator'],
width: 100 * r.score,
marks: ends.map((v) => 100 * v),
cells: [`${n}/${total}`, pct(n, total), ends.map((v) => pct(v, 1)).join('–') || '—'],
},
],
};
}
case 'counts': { case 'counts': {
const cells = of(mode.measure)?.strata['category'] ?? {}; const cells = of(mode.measure)?.strata['category'] ?? {};
const total = Object.values(cells).reduce((n, c) => n + size(c), 0); const total = Object.values(cells).reduce((n, c) => n + size(c), 0);
+1 -1
View File
@@ -36,7 +36,7 @@ import { Loading } from '../loading';
<p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p> <p class="muted empty">Este dominio todavía no tiene indicadores publicados.</p>
} @else { } @else {
<mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms"> <mat-tab-group mat-stretch-tabs="false" mat-align-tabs="center" animationDuration="0ms">
<mat-tab [label]="domain() === 'tea' ? 'Resumen' : 'Indicadores'"> <mat-tab label="Resumen">
<app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" /> <app-tab-indicadores [domain]="domain()" [measures]="measures.value()!" />
</mat-tab> </mat-tab>
<mat-tab label="Histórico"> <mat-tab label="Histórico">
+2 -6
View File
@@ -116,9 +116,10 @@ const ppv = (measure: string, title: string, note: string, ...more: Mode[]): Rea
kind: 'readings', kind: 'readings',
title, title,
headline: measure, headline: measure,
footnote: true,
note: `${note} Confirma la histología LIEBG o mayor.`, note: `${note} Confirma la histología LIEBG o mayor.`,
modes: [ modes: [
{ kind: 'figure', label: 'Total', measure, figure: 'donut', colors: PPV_DONUT }, { kind: 'ratio', label: 'Total', measure, colors: PPV_DONUT },
{ {
kind: 'shares', kind: 'shares',
label: 'Citología previa', label: 'Citología previa',
@@ -177,11 +178,6 @@ export const CACU: Page = {
title: 'Días de toma de citología a resultado', title: 'Días de toma de citología a resultado',
...CACU_DAYS, ...CACU_DAYS,
}, },
{
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO',
title: 'Días de tamizaje a primer diagnóstico',
...CACU_DAYS,
},
{ {
measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA', measure: 'CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA',
title: 'Días de tamizaje a diagnóstico tras biopsia', title: 'Días de tamizaje a diagnóstico tras biopsia',
+2
View File
@@ -26,6 +26,8 @@ export interface ReadingsCard {
kind: 'readings'; kind: 'readings';
title: string; title: string;
headline?: string; headline?: string;
/** say the headline under the figure instead of above it */
footnote?: boolean;
/** what the headline proportion counts, in the plural (default: pacientes) */ /** what the headline proportion counts, in the plural (default: pacientes) */
unit?: string; unit?: string;
note?: string; note?: string;
+5
View File
@@ -146,6 +146,9 @@ import { Reading } from './measures';
} @else { } @else {
<p class="state">Sin datos en el periodo.</p> <p class="state">Sin datos en el periodo.</p>
} }
@if (foot()) {
<p class="state">{{ foot() }}</p>
}
`, `,
styles: ` styles: `
:host { :host {
@@ -347,6 +350,8 @@ export class Readings {
readonly title = input.required<string>(); readonly title = input.required<string>();
readonly headline = input(''); readonly headline = input('');
readonly note = input(''); readonly note = input('');
/** a line under the figure */
readonly foot = input('');
/** the card around it names it already (tabs inside one card) */ /** the card around it names it already (tabs inside one card) */
readonly hideTitle = input(false); readonly hideTitle = input(false);
readonly camaStyle = input(false); readonly camaStyle = input(false);
+10 -2
View File
@@ -28,7 +28,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
<app-readings <app-readings
[title]="s.title" [title]="s.title"
[camaStyle]="hasCamaHeading(s)" [camaStyle]="hasCamaHeading(s)"
[headline]="headlineOf(s)" [headline]="s.footnote ? '' : headlineOf(s)"
[foot]="footOf(s)"
[note]="s.note ?? ''" [note]="s.note ?? ''"
[modes]="s.modes" [modes]="s.modes"
[view]="view()" [view]="view()"
@@ -58,7 +59,8 @@ type Shown = Extract<Section, { kind: 'readings' | 'columns' | 'choice' }>;
[title]="c.section.title" [title]="c.section.title"
[hideTitle]="true" [hideTitle]="true"
[camaStyle]="true" [camaStyle]="true"
[headline]="headlineOf(c.section)" [headline]="c.section.footnote ? '' : headlineOf(c.section)"
[foot]="footOf(c.section)"
[note]="c.section.note ?? ''" [note]="c.section.note ?? ''"
[modes]="c.section.modes" [modes]="c.section.modes"
[loading]="of().loading" [loading]="of().loading"
@@ -162,6 +164,12 @@ export class ReadingsSection {
const words = detail(measure, r, s.unit); const words = detail(measure, r, s.unit);
return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`; return scoring(measure) === 'cohort' ? words : `${formatScore(measure, r)} · ${words}`;
} }
/** The headline of a card that says it under its figure, as one line separated by commas. */
protected footOf(s: ReadingsCard): string {
return s.footnote
? this.headlineOf(s).replace(' · ', ', ').replace('. IC 95 %', ', IC 95 %')
: '';
}
protected readonly draw = computed(() => (mode: Mode) => { protected readonly draw = computed(() => (mode: Mode) => {
if (mode.kind !== 'figure') return undefined; if (mode.kind !== 'figure') return undefined;
const r = this.of().reading(mode.measure); const r = this.of().reading(mode.measure);
+132 -82
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" [toolbar]="false" />
<app-plot [figure]="curve()" [height]="300" /> }
} </details>
</details> }
} @if (!riskModels().length && !riskExclusion()) {
@if (!riskModels().length && !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>
@@ -557,19 +559,72 @@
<mat-card appearance="outlined" class="wide" data-section="supervivencia"> <mat-card appearance="outlined" class="wide" data-section="supervivencia">
<mat-card-header> <mat-card-header>
<mat-card-title>{{ <mat-card-title>{{
domain() === 'cacu' ? 'Supervivencia por escenario clínico' : 'Riesgo de muerte' domain() === 'cacu' ? 'Supervivencia' : 'Riesgo de muerte'
}}</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 (domain() === 'cacu') { <h3>Análisis de supervivencia</h3>
<p class="muted" data-note="grupo">
Las curvas son estimaciones del grupo de pacientes del escenario clínico
correspondiente (S(t), probabilidad de supervivencia); no son predicciones
individuales.
</p>
} }
@if (survival.isLoading()) { @if (domain() === 'cacu') {
<app-risk-scales [groups]="survivalScales()" />
@for (g of survivalScales(); track $index) {
<details data-section="valores-supervivencia">
<summary>Modelos y valores</summary>
<table class="plain">
<thead>
<tr>
<th>Modelo</th>
<th>Fecha índice</th>
<th>Horizonte</th>
<th>Supervivencia</th>
<th>IC 95 %</th>
</tr>
</thead>
<tbody>
@for (v of g.scales; track v.label) {
<tr>
<td>{{ $first ? g.model : '' }}</td>
<td>{{ $first ? g.index : '' }}</td>
<td>{{ v.risk!.years }} {{ v.risk!.years === 1 ? 'año' : 'años' }}</td>
<td>{{ v.risk!.p * 100 | number: '1.1-2' }} %</td>
<td>
@if (v.risk!.low !== undefined && v.risk!.high !== undefined) {
{{ v.risk!.low! * 100 | number: '1.1-2' }}–{{
v.risk!.high! * 100 | number: '1.1-2'
}}
%
} @else {
—
}
</td>
</tr>
}
</tbody>
</table>
</details>
}
<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" [toolbar]="false" />
} @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 (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>
@@ -579,12 +634,14 @@
} }
</ul> </ul>
@if (s.methods.length) { @if (s.methods.length) {
<h3>Métodos</h3> <details>
<ul class="scenarios methods"> <summary>Métodos</summary>
@for (name of s.methods; track name) { <ul class="scenarios methods">
<li>{{ name }}</li> @for (name of s.methods; track name) {
} <li>{{ name }}</li>
</ul> }
</ul>
</details>
} }
@for (f of s.figures; track f.title) { @for (f of s.figures; track f.title) {
<h4>{{ f.title }}</h4> <h4>{{ f.title }}</h4>
@@ -608,14 +665,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>
+55 -4
View File
@@ -32,7 +32,8 @@ import { eligibilityFailure, eligibilityView, type EligibilityState } from './el
import { ineligibility } from './ineligibility'; 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 { isRiskModel, riskGroups, riskScales, RiskScales } 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,6 +80,25 @@ 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 {
if (!value) return undefined;
try {
const parsed: unknown = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [ imports: [
@@ -183,14 +203,42 @@ export class Paciente {
return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined; return this.domain() === 'cacu' ? route(shown, this.cutoff()) : undefined;
}); });
/** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */ /** The models whose estimate is a risk (scales, curves, PDF): not survival or recurrence. */
protected readonly riskModels = computed(() => this.models().filter((m) => isRiskModel(m.model))); protected readonly riskModels = computed(() => this.models().filter((m) => m.measure === 'risk'));
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' ? riskGroups(this.riskModels()) : [], 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<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: () =>
@@ -341,6 +389,9 @@ export class Paciente {
text: r.method?.text ?? '', text: r.method?.text ?? '',
version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0), version: Number(/v(\d+)$/.exec(r.method?.text ?? '')?.[1] ?? 0),
index: r.occurrenceDateTime ?? '', 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 // 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')
+19 -1
View File
@@ -1,4 +1,4 @@
import { horizon, isRiskModel, riskGroups, riskScales } from './risk-scales'; import { horizon, isRiskModel, riskGroups, riskScales, survivalGroups } from './risk-scales';
const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high }); const at = (years: number, p: number, low?: number, high?: number) => ({ years, p, low, high });
@@ -84,3 +84,21 @@ describe('which models feed the risk scales', () => {
]); ]);
}); });
}); });
describe('survival scales', () => {
it('complements mortality and reverses interval bounds at every published horizon', () => {
const [g] = survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2, 0.1, 0.3)] }]);
expect(g.survival).toBe(true);
expect(g.index).toBe('2026-01-01');
expect(g.scales[0].risk?.p).toBeCloseTo(0.8);
expect(g.scales[0].risk?.low).toBeCloseTo(0.7);
expect(g.scales[0].risk?.high).toBeCloseTo(0.9);
});
it('keeps the inputs attached to the estimate and leaves old estimates without them', () => {
const inputs = { age_group: '45-54', cytology: 'HSIL+', hpv: 'positive' };
expect(survivalGroups([{ index: '2026-01-01', predictions: [at(1, 0.2)], inputs }])[0].inputs)
.toEqual(inputs);
expect(riskGroups([{ text: 'Riesgo', index: '2026-01-01', predictions: [at(5, 0.2)] }])[0].inputs)
.toBeUndefined();
});
});
+134 -8
View File
@@ -48,9 +48,54 @@ export interface RiskGroup {
title?: string; title?: string;
scenario?: string; scenario?: string;
index?: string; index?: string;
survival?: boolean;
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). */
export function survivalGroups(
models: {
index: string;
predictions: Prediction[];
scenarios?: string[];
inputs?: Record<string, unknown>;
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][] = [ const HORIZONS: [number, string][] = [
[0, 'Riesgo inmediato (al índice)'], [0, 'Riesgo inmediato (al índice)'],
[5, 'Riesgo a 5 años'], [5, 'Riesgo a 5 años'],
@@ -65,7 +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: {
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) }));
@@ -73,6 +124,9 @@ export function riskGroups(
? models.map((m) => ({ ? models.map((m) => ({
...titleParts(m.text), ...titleParts(m.text),
index: m.index, index: m.index,
inputs: m.inputs,
model: m.text,
evaluated: m.evaluated,
scales: scales(m.predictions), scales: scales(m.predictions),
})) }))
: [{ scales: scales([]) }]; : [{ scales: scales([]) }];
@@ -85,9 +139,6 @@ export function riskGroups(
selector: 'app-risk-scales', selector: 'app-risk-scales',
imports: [DecimalPipe], imports: [DecimalPipe],
template: ` template: `
@if (groups().length) {
<p class="muted note">Divisiones numéricas descriptivas; no representan umbrales clínicos.</p>
}
@for (g of groups(); track $index) { @for (g of groups(); track $index) {
@if (g.title) { @if (g.title) {
<h3>{{ g.title }}</h3> <h3>{{ g.title }}</h3>
@@ -105,7 +156,7 @@ export function riskGroups(
· No disponible · No disponible
} }
</p> </p>
<div class="risk-plot" [class.unavailable]="!s.risk"> <div class="risk-plot" [class.unavailable]="!s.risk" [class.survival]="g.survival">
<div class="risk-line" aria-hidden="true"></div> <div class="risk-line" aria-hidden="true"></div>
@if (s.risk; as r) { @if (s.risk; as r) {
@if (r.low !== undefined && r.high !== undefined) { @if (r.low !== undefined && r.high !== undefined) {
@@ -134,12 +185,55 @@ 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 && !g.survival) {
<section>
<h4>Factores de riesgo considerados</h4>
@if (g.inputs) {
<dl>
@for (item of entries(g.inputs); track item[0]) {
<div>
<dt>{{ inputName(item[0]) }}</dt>
<dd>{{ inputValue(item[0], item[1]) }}</dd>
</div>
}
</dl>
} @else {
<p class="muted">Los valores utilizados no están disponibles para esta estimación.</p>
}
</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: `
.note {
margin: 0 0 8px;
}
.risk-scale { .risk-scale {
margin: 8px 0 14px; margin: 8px 0 14px;
max-width: 740px; max-width: 740px;
@@ -170,6 +264,15 @@ export function riskGroups(
#fff 25% #fff 25%
); );
} }
.survival .risk-line {
background: linear-gradient(
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;
border-right: 2px solid #17324d; border-right: 2px solid #17324d;
@@ -216,4 +319,27 @@ 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 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<string, string>
)[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'))
return value ? 'Positivo' : 'Negativo';
if (name.startsWith('hpv') && value === 'positive') return 'Positivo';
if (name.startsWith('hpv') && value === 'negative') return 'Negativo';
return String(value);
};
} }
+4 -1
View File
@@ -24,6 +24,9 @@ describe('risk series', () => {
], ],
}); });
expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]); expect(series.points).toEqual([{ years: 0, p: 0, low: undefined, high: undefined }]);
expect(seriesName(series)).toBe('Institucional · LIEAG+ (CIN2+)'); expect(seriesName(series)).toBe('ISSSTELEON, LIEAG+');
expect(seriesName({ ...series, source: 'NCI (tabla de ingreso)' })).toBe(
'NCI, ingreso a LIEAG+',
);
}); });
}); });
+21 -87
View File
@@ -1,12 +1,8 @@
import { DecimalPipe } from '@angular/common';
import { Component, computed, input, signal } from '@angular/core'; import { Component, computed, input, signal } from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
import type { Parameters, ParametersParameter } from 'fhir/r4'; import type { Parameters, ParametersParameter } from 'fhir/r4';
import { Plot } from '../plot'; import { Plot } from '../plot';
import { curveFigure } from './risk-curve'; import { curveFigure } from './risk-curve';
import { REASON_TEXT } from './reference-risk';
export interface SeriesPoint { export interface SeriesPoint {
years: number; years: number;
@@ -32,12 +28,16 @@ const OUTCOME_TEXT: Record<string, string> = {
'CIN3+': 'CIN3+', 'CIN3+': 'CIN3+',
cancer: 'Cáncer', cancer: 'Cáncer',
}; };
const REASONS: Record<string, string> = {
...REASON_TEXT,
history_is_registered: 'Tiene antecedentes registrados: no corresponde la tabla de ingreso.',
};
export const seriesName = (s: Series) => `${s.source} · ${OUTCOME_TEXT[s.outcome] ?? s.outcome}`; export const seriesName = (s: Series) => {
const outcome = OUTCOME_TEXT[s.outcome] ?? s.outcome;
if (s.source === 'NCI (tabla de ingreso)')
return `NCI, ingreso a ${outcome.replace(' (CIN2+)', '').replace(/^Cáncer$/, 'cáncer')}`;
// the platform's own models are the hospital's: its name, and the outcome without its synonym
return s.source === 'Institucional'
? `ISSSTELEON, ${outcome.replace(' (CIN2+)', '')}`
: `${s.source} · ${outcome}`;
};
/** The series of the answer. A value absent from it stays absent. */ /** The series of the answer. A value absent from it stays absent. */
export function parseSeries(answer: Parameters): Series[] { export function parseSeries(answer: Parameters): Series[] {
@@ -61,11 +61,10 @@ export function parseSeries(answer: Parameters): Series[] {
})); }));
} }
/** The chosen series as bars at one horizon and as curves. Series are shown side by side; no /** The chosen series as curves. Series are shown side by side; no difference is computed. */
* difference between them is computed. */
@Component({ @Component({
selector: 'app-risk-series', selector: 'app-risk-series',
imports: [DecimalPipe, MatCheckboxModule, MatFormFieldModule, MatSelectModule, Plot], imports: [MatCheckboxModule, Plot],
template: ` template: `
<p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p> <p class="muted">Cada serie tiene su propio desenlace y población: no se restan entre sí.</p>
<div class="choices"> <div class="choices">
@@ -76,44 +75,13 @@ export function parseSeries(answer: Parameters): Series[] {
} }
</div> </div>
@if (selected().length) { @if (selected().length) {
<mat-form-field appearance="outline" subscriptSizing="dynamic"> @for (assumption of assumptions(); track assumption) {
<mat-label>Horizonte</mat-label> <p class="muted">{{ assumption }}</p>
<mat-select [value]="horizon()" (selectionChange)="picked.set($event.value)"> }
@for (h of horizons(); track h) { <app-plot [figure]="figure()" [height]="340" [toolbar]="false" />
<mat-option [value]="h">{{ h === 0 ? 'Al índice' : h + ' años' }}</mat-option>
}
</mat-select>
</mat-form-field>
<ul class="bars">
@for (b of bars(); track b.series.id) {
<li>
<span>{{ name(b.series) }}</span>
<small class="muted">{{ b.series.label }}</small>
@if (b.point; as p) {
<span class="track"><span class="fill" [style.width.%]="p.p * 100"></span></span>
<span>
{{ p.p * 100 | number: '1.1-2' }} %
@if (p.low !== undefined && p.high !== undefined) {
(IC 95 %: {{ p.low * 100 | number: '1.1-2' }}–{{
p.high * 100 | number: '1.1-2'
}})
} @else {
(IC 95 % no publicado)
}
</span>
} @else {
<span class="muted">No disponible en este horizonte.</span>
}
@for (a of b.series.assumptions; track a) {
<small class="muted">{{ a }}</small>
}
</li>
}
</ul>
<app-plot [figure]="figure()" [height]="340" />
} }
@for (s of unavailable(); track s.id) { @if (!available().length) {
<p class="muted">{{ name(s) }}: no disponible. {{ why(s) }}</p> <p class="muted">No disponible: datos insuficientes.</p>
} }
`, `,
styles: ` styles: `
@@ -126,31 +94,12 @@ export function parseSeries(answer: Parameters): Series[] {
gap: 0 16px; gap: 0 16px;
margin-bottom: 8px; margin-bottom: 8px;
} }
.bars {
list-style: none;
padding: 0;
}
.bars li {
display: flex;
flex-direction: column;
margin-bottom: 10px;
}
.track {
background: var(--color-action-hover, #f1f6f6);
height: 10px;
}
.fill {
background: #4269a0;
display: block;
height: 100%;
}
`, `,
}) })
export class RiskSeries { export class RiskSeries {
readonly series = input.required<Series[]>(); readonly series = input.required<Series[]>();
protected readonly name = seriesName; protected readonly name = seriesName;
protected readonly available = computed(() => this.series().filter((s) => s.points.length)); protected readonly available = computed(() => this.series().filter((s) => s.points.length));
protected readonly unavailable = computed(() => this.series().filter((s) => !s.points.length));
/** what the user toggled away from the default (the institutional series) */ /** what the user toggled away from the default (the institutional series) */
private readonly toggled = signal(new Set<string>()); private readonly toggled = signal(new Set<string>());
protected readonly chosen = computed( protected readonly chosen = computed(
@@ -164,21 +113,10 @@ export class RiskSeries {
protected readonly selected = computed(() => protected readonly selected = computed(() =>
this.available().filter((s) => this.chosen().has(s.id)), this.available().filter((s) => this.chosen().has(s.id)),
); );
protected readonly horizons = computed(() => /** what the chosen series assume, each said once */
[...new Set(this.selected().flatMap((s) => s.points.map((p) => p.years)))].sort( protected readonly assumptions = computed(() => [
(a, b) => a - b, ...new Set(this.selected().flatMap((s) => s.assumptions)),
), ]);
);
protected readonly picked = signal(5);
protected readonly horizon = computed(() =>
this.horizons().includes(this.picked()) ? this.picked() : this.horizons().at(-1)!,
);
protected readonly bars = computed(() =>
this.selected().map((series) => ({
series,
point: series.points.find((p) => p.years === this.horizon()),
})),
);
protected readonly figure = computed(() => { protected readonly figure = computed(() => {
const shown = this.selected().map((s) => ({ const shown = this.selected().map((s) => ({
model: s.id, model: s.id,
@@ -198,8 +136,4 @@ export class RiskSeries {
if (!next.delete(id)) next.add(id); if (!next.delete(id)) next.add(id);
this.toggled.set(next); this.toggled.set(next);
} }
protected why(s: Series) {
return s.reasons.map((r) => REASONS[r] ?? r).join(' ');
}
} }
@@ -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;
}
+6 -1
View File
@@ -75,12 +75,17 @@ const CONFIG: Partial<Plotly.Config> = {
export class Plot implements OnDestroy { export class Plot implements OnDestroy {
readonly figure = input.required<Figure>(); readonly figure = input.required<Figure>();
readonly height = input(320); readonly height = input(320);
/** Plotly's buttons over the chart; a record's curves go without them */
readonly toolbar = input(true);
private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host'); private readonly host = viewChild.required<ElementRef<HTMLDivElement>>('host');
constructor() { constructor() {
effect(() => { effect(() => {
const { data, layout } = this.figure(); const { data, layout } = this.figure();
void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), CONFIG); void Plotly.react(this.host().nativeElement, withRoom(data), layoutOf(layout), {
...CONFIG,
...(this.toolbar() ? {} : { displayModeBar: false }),
});
}); });
} }