Patient risk: what the model's number is, and its curve with the interval

The record reads the RiskAssessment's `estimando` extension and shows the quantity, the outcome, the index date and
the interval's method, and names the table's columns with the quantity and the horizons' unit. Below the table, a
collapsible curve of the risk at each horizon, with its interval as a band (or as error bars when a horizon lacks
one); Plotly is loaded only when it's opened.

(cherry picked from commit 6039e6b741)
This commit is contained in:
2026-11-22 07:48:42 -06:00
parent 1af0c21291
commit ad4edbe2a1
8 changed files with 206 additions and 9 deletions
@@ -0,0 +1,73 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { of } from 'rxjs';
import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime';
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
import { riesgoCacuConEstimando, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing';
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
// What the patient's risk says about its number (the model's `[estimand]`) and the curve of its horizons.
describe('Riesgo individual: qué se estima y su curva', () => {
function setup(data: unknown) {
const react = vi.fn(() => Promise.resolve());
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(data) } },
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve({ react, purge: vi.fn(), Plots: { resize: vi.fn() },
addFrames: vi.fn(), deleteFrames: vi.fn() }) }] });
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
fixture.componentRef.setInput('pacId', '42');
fixture.detectChanges();
fixture.detectChanges();
return { fixture, root: fixture.nativeElement as HTMLElement };
}
it('lee el estimando conocido e ignora claves que no conoce; sin extensión queda en null', () => {
expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({
quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.',
outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años', interval: 'IC 95 % por método delta' });
expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista());
});
it('rechaza un estimando mal formado', () => {
const data = riesgoCacuConEstimando();
data.entry[0].resource.extension[0].extension = 'texto';
expect(() => riesgoPacienteResponse(data, '42')).toThrow();
});
it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => {
const { root } = setup(riesgoCacuConEstimando());
expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim()))
.toEqual(['Horizonte (años)', 'Riesgo acumulado (%)', 'Intervalo de confianza (%)']);
for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma', 'IC 95 % por método delta']) {
expect(root.textContent).toContain(value);
}
});
it('dibuja la curva solo al abrir su sección', async () => {
const { fixture, root } = setup(riesgoCacuConEstimando());
const details = root.querySelector('details.risk-curve') as HTMLDetailsElement;
expect(details.querySelector('summary')!.textContent).toContain('Curva de riesgo acumulado');
expect(root.querySelector('app-plotly-chart')).toBeNull();
details.open = true;
details.dispatchEvent(new Event('toggle'));
fixture.detectChanges();
expect(root.querySelector('app-plotly-chart')).not.toBeNull();
});
it('la figura une los horizontes y pone el intervalo como banda, o como barras si falta en alguno', () => {
const riesgo = riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo;
const banda = figuraRiesgoPaciente(riesgo);
expect(banda.data).toHaveLength(3);
expect(banda.data[2]['y']).toEqual([8, 21, 34]);
expect(banda.data[1]['y']).toEqual([5, 15, 26]);
expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)');
const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) };
const barras = figuraRiesgoPaciente(parcial);
expect(barras.data).toHaveLength(1);
expect((barras.data[0]['error_y'] as any).array[0]).toBe(0);
});
});
@@ -0,0 +1,46 @@
import { PlotlyFigure } from '../indicadores.models';
import { tieneIntervalo } from './paciente-riesgo.validation';
import { LoteRiesgoCacu } from './paciente-riesgo.models';
const COLOR = '#6a3d9a';
const BANDA = 'rgba(106,61,154,.18)';
/**
* The patient's risk at the model's horizons as a small curve: the points joined by a line, with the interval as a
* band where every horizon has one and as error bars otherwise. In percent; the axis names follow the estimand.
*/
export function figuraRiesgoPaciente(riesgo: LoteRiesgoCacu): PlotlyFigure {
const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100);
const cantidad = riesgo.estimando?.quantity ?? 'Probabilidad';
const unidad = riesgo.estimando?.horizons_unit ?? 'años';
const conIntervalo = h.map(tieneIntervalo);
const banda = conIntervalo.length > 1 && conIntervalo.every(Boolean);
const data: Record<string, unknown>[] = [];
if (banda) {
data.push(
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false, hoverinfo: 'skip' },
{ type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty', fillcolor: BANDA, line: { width: 0 },
name: 'Intervalo de confianza', hoverinfo: 'skip' },
);
}
const barras = !banda && conIntervalo.some(Boolean) ? {
error_y: { type: 'data', symmetric: false, visible: true, color: COLOR, thickness: 2, width: 6,
array: h.map((p, i) => conIntervalo[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0),
arrayminus: h.map((p, i) => conIntervalo[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) },
} : {};
data.push({
type: 'scatter', mode: 'lines+markers', x, y, name: cantidad, line: { color: COLOR, width: 2 },
marker: { color: COLOR, size: 9, line: { color: 'white', width: 2 } }, ...barras,
customdata: h.map(p => tieneIntervalo(p) ? `${(p.ic_bajo! * 100).toFixed(2)} % – ${(p.ic_alto! * 100).toFixed(2)} %` : 'sin intervalo'),
hovertemplate: `%{x} ${unidad}: %{y:.2f} %<br>IC: %{customdata}<extra></extra>`,
});
const maximo = Math.max(...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100));
return {
data,
layout: {
margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: banda, legend: { orientation: 'h', y: -0.25 },
xaxis: { title: { text: `Horizonte (${unidad} desde la fecha índice)` }, tickvals: x, zeroline: false },
yaxis: { title: { text: `${cantidad} (%)` }, rangemode: 'tozero', range: [0, Math.max(maximo * 1.15, 1)], zeroline: false },
},
};
}
@@ -16,14 +16,21 @@
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
<div><dt>Evaluado en</dt><dd><time [attr.datetime]="riesgo.evaluado_en">{{ instante(riesgo.evaluado_en) }}</time></dd></div>
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
@if (riesgo.estimando; as e) {
@if (e.quantity) { <div><dt>Qué se estima</dt><dd>{{ e.quantity }}@if (e.description) {: {{ e.description }}}</dd></div> }
@if (e.outcome) { <div><dt>Desenlace del modelo</dt><dd>{{ e.outcome }}</dd></div> }
@if (e.index_date) { <div><dt>Desde</dt><dd>{{ e.index_date }}</dd></div> }
@if (e.horizons_unit) { <div><dt>Horizontes en</dt><dd>{{ e.horizons_unit }}</dd></div> }
@if (e.interval) { <div><dt>Intervalo</dt><dd>{{ e.interval }}</dd></div> }
}
</dl>
@if (riesgo.horizontes.length) {
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
<table>
<caption>Probabilidades por horizonte desde la fecha índice</caption>
<caption>{{ riesgo.estimando?.quantity ?? 'Probabilidades' }} por horizonte desde la fecha índice</caption>
<thead><tr>
<th scope="col">Horizonte (años)</th>
<th scope="col">Probabilidad (%)</th>
<th scope="col">Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }})</th>
<th scope="col">{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} (%)</th>
<th scope="col">Intervalo de confianza (%)</th>
</tr></thead>
<tbody>
@@ -37,6 +44,15 @@
</tbody>
</table>
</div>
@if (riesgo.horizontes.length > 1) {
<details class="risk-curve" (toggle)="curvaAbierta.set($any($event.target).open)">
<summary>Curva de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo</summary>
@if (curvaAbierta()) {
<app-plotly-chart [style.--plot-height]="'300px'" [showNotes]="false" [figure]="figura(riesgo)"
[label]="'Curva de riesgo individual ' + rotulo() + ' por horizonte'" />
}
</details>
}
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
}
}
@@ -18,3 +18,4 @@ thead th { position: sticky; top: 0; background: var(--issste-background, var(--
tbody th, td { background: var(--issste-surface); }
tbody tr:last-child > * { border-bottom: 0; }
.percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; }
.risk-curve { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; }
@@ -1,6 +1,9 @@
import { Component, computed, effect, inject, input } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { DominioRiesgo } from './paciente-riesgo.models';
import { Component, computed, effect, inject, input, signal } from '@angular/core';
import { DecimalPipe, LowerCasePipe } from '@angular/common';
import { PlotlyChart } from '../../../shared/plotly/plotly-chart';
import { PlotlyFigure } from '../indicadores.models';
import { figuraRiesgoPaciente } from './paciente-riesgo-figura';
import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models';
import { PacienteRiesgoState } from './paciente-riesgo.state';
import { tieneIntervalo } from './paciente-riesgo.validation';
@@ -12,7 +15,7 @@ export const instanteUtc = (iso: string) => {
@Component({
selector: 'app-paciente-riesgo-tabla',
imports: [DecimalPipe],
imports: [DecimalPipe, LowerCasePipe, PlotlyChart],
providers: [PacienteRiesgoState],
templateUrl: './paciente-riesgo-tabla.html',
styleUrl: './paciente-riesgo-tabla.scss',
@@ -27,6 +30,13 @@ export class PacienteRiesgoTabla {
readonly estado = this.state.estado;
readonly tieneIntervalo = tieneIntervalo;
readonly instante = instanteUtc;
/** The curve is drawn only while its section is open, so Plotly isn't loaded for a closed one. */
readonly curvaAbierta = signal(false);
private figuraDe?: { riesgo: LoteRiesgoCacu; figura: PlotlyFigure };
figura(riesgo: LoteRiesgoCacu): PlotlyFigure {
if (this.figuraDe?.riesgo !== riesgo) this.figuraDe = { riesgo, figura: figuraRiesgoPaciente(riesgo) };
return this.figuraDe.figura;
}
constructor() {
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); });
}
@@ -14,6 +14,18 @@ export interface HorizonteRiesgoCacu {
ic_alto?: number | null;
}
/** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */
export interface EstimandoRiesgo {
/** e.g. "Riesgo acumulado"; also `method.text`. */
quantity?: string;
description?: string;
outcome?: string;
index_date?: string;
/** The unit the horizons are counted in, e.g. "años". */
horizons_unit?: string;
interval?: string;
}
/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>`). */
export interface LoteRiesgoCacu {
/** The resource's id, `<lote_id>-<pac_id>`. */
@@ -28,6 +40,8 @@ export interface LoteRiesgoCacu {
desenlace: string;
desenlace_texto: string | null;
horizontes: HorizonteRiesgoCacu[];
/** `null` for a model whose scenario doesn't say. */
estimando: EstimandoRiesgo | null;
}
/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */
@@ -2,6 +2,7 @@ import { RiesgoPacienteCacu } from './paciente-riesgo.models';
const CS = 'https://isssteleon.org/fhir/CodeSystem';
export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
export const ESTIMANDO = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */
export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any {
@@ -47,6 +48,23 @@ export function riesgoCacuVista(): RiesgoPacienteCacu {
{ horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 },
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 },
],
estimando: null,
},
};
}
/** TEST ONLY. `riesgoCacuEjemplo()` from a model whose scenario says what its number is (extension `estimando`). */
export function riesgoCacuConEstimando(): any {
const data = riesgoCacuEjemplo();
const resource = data.entry[0].resource;
resource.method.text = 'Riesgo acumulado';
resource.extension = [{ url: ESTIMANDO, extension: [
{ url: 'quantity', valueString: 'Riesgo acumulado' },
{ url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' },
{ url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' },
{ url: 'horizons_unit', valueString: 'años' },
{ url: 'interval', valueString: 'IC 95 % por método delta' },
{ url: 'otra', valueString: 'se ignora' },
] }];
return data;
}
@@ -1,5 +1,5 @@
import { isoDate } from '../cacu-seguimiento.models';
import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
@@ -9,6 +9,8 @@ const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1;
const DAYS_PER_YEAR = 365.25;
const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza';
const SIMULATED = 'simulado';
const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando';
const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'interval'];
function utcTimestamp(v: unknown): v is string {
return typeof v === 'string'
@@ -39,6 +41,23 @@ function interval(prediction: Record<string, unknown>): { ic_bajo: number | null
return { ic_bajo: low, ic_alto: high };
}
/** The resource's `estimando` extension: its known keys with a text value; `null` without one. */
function estimand(resource: Record<string, unknown>): EstimandoRiesgo | null {
const extensions = resource['extension'];
if (extensions === undefined) return null;
if (!Array.isArray(extensions)) invalid();
const found = extensions.find(e => record(e) && e['url'] === ESTIMAND);
if (found === undefined) return null;
if (!Array.isArray(found['extension'])) invalid();
const result: EstimandoRiesgo = {};
for (const item of found['extension']) {
if (!record(item) || !text(item['url'])) invalid();
const key = item['url'] as keyof EstimandoRiesgo;
if (ESTIMAND_KEYS.includes(key) && text(item['valueString'])) result[key] = item['valueString'];
}
return result;
}
function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } {
if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid();
const period = prediction['whenPeriod'];
@@ -80,7 +99,7 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu {
id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string,
fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final',
desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null,
horizontes,
horizontes, estimando: estimand(v),
};
}