From ad4edbe2a11a84dc0d137e82ec84e78928c60e25 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 07:48:42 -0600 Subject: [PATCH] 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 6039e6b741266f112b6a6a950fabfe15426ae30d) --- .../paciente-riesgo-estimando.spec.ts | 73 +++++++++++++++++++ .../paciente-riesgo-figura.ts | 46 ++++++++++++ .../paciente-riesgo-tabla.html | 22 +++++- .../paciente-riesgo-tabla.scss | 1 + .../paciente-detalle/paciente-riesgo-tabla.ts | 18 ++++- .../paciente-riesgo.models.ts | 14 ++++ .../paciente-riesgo.testing.ts | 18 +++++ .../paciente-riesgo.validation.ts | 23 +++++- 8 files changed, 206 insertions(+), 9 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts new file mode 100644 index 0000000..30ad7ab --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -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); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts new file mode 100644 index 0000000..79797e4 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts @@ -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[] = []; + 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} %
IC: %{customdata}`, + }); + 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 }, + }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index f04c835..40b2e6a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -16,14 +16,21 @@
Desenlace
{{ riesgo.desenlace_texto ?? riesgo.desenlace }}
Evaluado en
Estado del lote
{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}
+ @if (riesgo.estimando; as e) { + @if (e.quantity) {
Qué se estima
{{ e.quantity }}@if (e.description) {: {{ e.description }}}
} + @if (e.outcome) {
Desenlace del modelo
{{ e.outcome }}
} + @if (e.index_date) {
Desde
{{ e.index_date }}
} + @if (e.horizons_unit) {
Horizontes en
{{ e.horizons_unit }}
} + @if (e.interval) {
Intervalo
{{ e.interval }}
} + } @if (riesgo.horizontes.length) {
- + - - + + @@ -37,6 +44,15 @@
Probabilidades por horizonte desde la fecha índice{{ riesgo.estimando?.quantity ?? 'Probabilidades' }} por horizonte desde la fecha índice
Horizonte (años)Probabilidad (%)Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ riesgo.estimando?.quantity ?? 'Probabilidad' }} (%) Intervalo de confianza (%)
+ @if (riesgo.horizontes.length > 1) { +
+ Curva de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo + @if (curvaAbierta()) { + + } +
+ } } @else {

Sin horizontes evaluados en el lote vigente.

} } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss index 90a76f3..99d1396 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -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; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 4342680..2d4c6d6 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -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()); }); } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 4acb7cc..c140a2b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -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/`). */ export interface LoteRiesgoCacu { /** The resource's 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`. */ diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index 2344b80..f4332af 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -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; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index dbbade0..446263c 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -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 => !!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): { 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): 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), }; }