CaMa patient record: the recurrence figures of the scenarios she meets
This commit is contained in:
@@ -40,6 +40,12 @@
|
||||
<app-paciente-riesgo-tabla [pacId]="p.idField === 'pac_id' ? p.patientId : null" dominio="cama" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
@if (p.idField === 'pac_id') {
|
||||
<mat-card class="recurrence-card" appearance="outlined" aria-labelledby="recurrencia-title">
|
||||
<mat-card-header><h3 id="recurrencia-title">Recurrencia</h3></mat-card-header>
|
||||
<mat-card-content><app-cama-recurrencia-paciente [pacId]="p.patientId" /></mat-card-content>
|
||||
</mat-card>
|
||||
}
|
||||
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
|
||||
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
|
||||
@@ -76,11 +76,11 @@ describe('Ficha CaMa: componente', () => {
|
||||
});
|
||||
|
||||
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
|
||||
it('has placeholders, with no figures, for recurrence and prognostic factors', () => {
|
||||
it('has a placeholder, with no figures, for the prognostic factors', () => {
|
||||
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
|
||||
const items = [...root().querySelectorAll('[data-pronostico]')];
|
||||
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'factors']);
|
||||
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Factores pronóstico']);
|
||||
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['factors']);
|
||||
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Factores pronóstico']);
|
||||
for (const item of items) {
|
||||
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
|
||||
expect(item.textContent).not.toMatch(/\d/);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { downloadBlob, exportFilename } from '../../export/download-file';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component';
|
||||
import { PacienteRiesgoTabla } from '../paciente-riesgo-tabla';
|
||||
import {
|
||||
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
@@ -14,7 +15,7 @@ import {
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-patient-card',
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla],
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla, CamaRecurrenciaPaciente],
|
||||
templateUrl: './cama-patient-card.html',
|
||||
styleUrl: './cama-patient-card.scss',
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only
|
||||
// the fields of the record, shows placeholders (no figures) for recurrence and prognostic factors (survival is drawn in the record from the risk evaluation), and
|
||||
// the fields of the record, shows placeholders (no figures) for the prognostic factors (survival and recurrence are drawn in the record from the models' figures), and
|
||||
// renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test
|
||||
// because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser.
|
||||
import fixtureData from '../../fixtures/cama_seguimiento.json';
|
||||
@@ -46,10 +46,10 @@ describe('Ficha CaMa: PDF individual', () => {
|
||||
});
|
||||
|
||||
// Fails if a placeholder gains a figure or an explanation other than "unavailable".
|
||||
it('has placeholders, with no figures, for recurrence, prognostic factors and recommendations', () => {
|
||||
it('has placeholders, with no figures, for the prognostic factors and recommendations', () => {
|
||||
const found = texts(definition()['content']);
|
||||
for (const t of ['Probabilidad de recurrencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
|
||||
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(2);
|
||||
for (const t of ['Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
|
||||
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(1);
|
||||
});
|
||||
|
||||
// Fails if the document carries a platform identifier field.
|
||||
|
||||
@@ -27,10 +27,9 @@ export interface CamaPatientSummary {
|
||||
daysMammographyToDiagnosis: number | null;
|
||||
}
|
||||
|
||||
/** Placeholders for results that exist only once a validated model and its clinical definition do (survival is drawn from
|
||||
* the patient's risk evaluation, not a placeholder). */
|
||||
/** Placeholders for results that exist only once a validated model and its clinical definition do (survival and recurrence are drawn
|
||||
* from the models' figures, not placeholders). */
|
||||
export const PROGNOSIS_PLACEHOLDERS = [
|
||||
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
|
||||
{ key: 'factors', label: 'Factores pronóstico' },
|
||||
] as const;
|
||||
export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.';
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { PlotlyFigure, Tema } from '../../indicadores.models';
|
||||
import { FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
|
||||
export const ETIQUETAS_RECURRENCIA = {
|
||||
eje_x: 'Meses desde el diagnóstico', eje_y: 'Libre de recaída S(t)', km: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull',
|
||||
weibull_fraccional: 'Weibull fraccional', puntos: 'LR + HBN combinado (IC 95 % bootstrap)',
|
||||
} as const;
|
||||
export const COLORES_RECURRENCIA = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const;
|
||||
|
||||
/** A curve in two parts: solid up to the follow-up the cohort has, dotted after it (the extrapolation). */
|
||||
function curva(t: number[], S: number[], hasta: number, color: string, nombre: string, dash?: string): Record<string, unknown>[] {
|
||||
const dentro = t.map((x, i) => i).filter(i => t[i] <= hasta), fuera = t.map((x, i) => i).filter(i => t[i] >= hasta);
|
||||
return [
|
||||
{ type: 'scatter', mode: 'lines', x: dentro.map(i => t[i]), y: dentro.map(i => S[i]), line: { color, width: 3, ...(dash ? { dash } : {}) }, name: nombre, legendgroup: nombre,
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + nombre + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: fuera.map(i => t[i]), y: fuera.map(i => S[i]), line: { color, width: 1.8, dash: 'dot' }, showlegend: false, legendgroup: nombre, hoverinfo: 'skip' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The recurrence analysis' figure of one scenario of one cohort, as the pipeline draws it: the Kaplan-Meier curve of the scenario's
|
||||
* patients with its Greenwood band, the classic and the fractional Weibull (dotted past the follow-up), and the recurrence-free
|
||||
* probability at each horizon by the combination of the LR and the HBN, as diamonds with their bootstrap interval.
|
||||
*/
|
||||
export function figuraRecurrencia(f: FiguraRecurrencia, tema: Tema = 'claro'): PlotlyFigure {
|
||||
const L = ETIQUETAS_RECURRENCIA, d = f.points.COMB, km = f.km;
|
||||
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
|
||||
const visibles = (t: number[], S: number[]) => S.filter((_, i) => t[i] <= f.months_max);
|
||||
const minimo = Math.max(0, Math.floor((Math.min(...km.low, ...visibles(f.weibull.t, f.weibull.S), ...visibles(f.weibull_fractional.t, f.weibull_fractional.S), ...d.low) - 0.02) * 20) / 20);
|
||||
const data: Record<string, unknown>[] = [
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES_RECURRENCIA.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES_RECURRENCIA.km, width: 2, shape: 'hv' }, name: L.km, legendgroup: 'km',
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.km + '</extra>' },
|
||||
...curva(f.weibull.t, f.weibull.S, f.observado_hasta, COLORES_RECURRENCIA.weibull, L.weibull),
|
||||
...curva(f.weibull_fractional.t, f.weibull_fractional.S, f.observado_hasta, COLORES_RECURRENCIA.fraccional, L.weibull_fraccional, 'dash'),
|
||||
{ type: 'scatter', mode: 'markers', name: L.puntos, x: f.horizons_months, y: d.S,
|
||||
marker: { symbol: 'diamond', size: 15, color: COLORES_RECURRENCIA.modelo, line: { color: 'white', width: 1.5 } },
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES_RECURRENCIA.modelo, thickness: 2, width: 6,
|
||||
array: d.high.map((hi, i) => Math.max(0, hi - d.S[i])), arrayminus: d.S.map((s, i) => Math.max(0, s - d.low[i])) },
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.puntos + '</extra>' },
|
||||
];
|
||||
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
|
||||
const layout: Record<string, unknown> = {
|
||||
title: { text: `${f.escenario}<br>${f.cohorte_nombre} · n=${f.n.toLocaleString('es-MX')}, recaídas=${f.recaidas.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
|
||||
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
|
||||
xaxis: { ...eje, title: { text: L.eje_x }, range: [0, f.months_max + 0.8], dtick: 12 },
|
||||
yaxis: { ...eje, title: { text: L.eje_y }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
|
||||
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
|
||||
};
|
||||
return { data, layout, config: { responsive: true, displaylogo: false } };
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<section aria-labelledby="recurrencia-paciente-titulo">
|
||||
<h5 id="recurrencia-paciente-titulo">Probabilidad de recurrencia</h5>
|
||||
@let r = respuesta();
|
||||
@if (r === undefined) { <p role="status">Buscando los escenarios clínicos de recurrencia de la paciente…</p> }
|
||||
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
|
||||
@if (r) {
|
||||
@if (r.escenarios.length === 0) { <p role="status">La paciente no cumple ninguno de los escenarios clínicos del análisis de recurrencia.</p> }
|
||||
@for (f of r.escenarios; track f.cohorte + f.escenario) { <app-cama-figura-recurrencia [datos]="f" /> }
|
||||
}
|
||||
</section>
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
// Covers CaMa's recurrence figures in a patient's record: the boundary validation of `GET /cama/modelo/recurrencia` (a malformed
|
||||
// answer never draws a partial curve), the figure of a scenario in the pipeline's style (the Greenwood band, the Kaplan-Meier steps,
|
||||
// the solid and dotted Weibull, the diamonds with their interval, "Libre de recaída S(t)"), and the component's states. Fixtures: a
|
||||
// figure like the recurrence version publishes, and a stub of `CamaRecurrenciaService`.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
|
||||
import { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component';
|
||||
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
|
||||
import { COLORES_RECURRENCIA, ETIQUETAS_RECURRENCIA, figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
|
||||
const meses = Array.from({ length: 61 }, (_, i) => i);
|
||||
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 60));
|
||||
const grilla = Array.from({ length: 289 }, (_, i) => i * 0.25);
|
||||
function figura(escenario = 'RE− · grado 3', cohorte = 'metabric'): any {
|
||||
return {
|
||||
cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, condiciones: { Grado_histologico: ['3'] }, n: 300, recaidas: 180,
|
||||
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
|
||||
km: { months: meses, S: decreciente(0.5), low: decreciente(0.45), high: decreciente(0.55) },
|
||||
weibull: { t: grilla, S: grilla.map(t => Math.exp(-t / 90)) }, weibull_fractional: { t: grilla, S: grilla.map(t => Math.exp(-t / 85)) },
|
||||
points: { COMB: { S: [0.9, 0.7, 0.55], low: [0.88, 0.67, 0.5], high: [0.92, 0.73, 0.6] } }, bootstrap_replicas: 200,
|
||||
};
|
||||
}
|
||||
const respuesta = (escenarios = [figura()]): any => ({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios });
|
||||
|
||||
describe('Recurrencia CaMa: respuesta', () => {
|
||||
// Fails if a record with an impossible value is accepted and drawn.
|
||||
it('accepts an answer as published', () => {
|
||||
expect(respuestaRecurrencia(respuesta()).escenarios[0].escenario).toBe('RE− · grado 3');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a probability above 1', (d: any) => { d.escenarios[0].km.S[3] = 1.2; }],
|
||||
['an inverted interval', (d: any) => { d.escenarios[0].points.COMB.low[0] = 0.99; }],
|
||||
['a series with another number of horizons', (d: any) => { d.escenarios[0].points.COMB.S.pop(); }],
|
||||
['a missing curve', (d: any) => { delete d.escenarios[0].weibull_fractional; }],
|
||||
['no model version', (d: any) => { delete d.modelo.version; }],
|
||||
])('rejects %s', (_, estropear) => {
|
||||
const d = respuesta();
|
||||
estropear(d);
|
||||
expect(() => respuestaRecurrencia(d)).toThrow('Respuesta de recurrencia inválida');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Recurrencia CaMa: figura', () => {
|
||||
const f = () => figuraRecurrencia(respuestaRecurrencia(respuesta()).escenarios[0]);
|
||||
const traza = (nombre: string) => f().data.find((t: any) => t.name === nombre) as any;
|
||||
|
||||
// Fails if the figure loses a piece of the pipeline's chart.
|
||||
it('has the Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => {
|
||||
expect(f().data.some((t: any) => t.fill === 'tonexty')).toBe(true);
|
||||
expect(traza(ETIQUETAS_RECURRENCIA.km).line).toMatchObject({ color: COLORES_RECURRENCIA.km, shape: 'hv' });
|
||||
expect(traza(ETIQUETAS_RECURRENCIA.weibull).line.color).toBe(COLORES_RECURRENCIA.weibull);
|
||||
expect(traza(ETIQUETAS_RECURRENCIA.weibull_fraccional).line).toMatchObject({ color: COLORES_RECURRENCIA.fraccional, dash: 'dash' });
|
||||
const rombos = traza(ETIQUETAS_RECURRENCIA.puntos);
|
||||
expect(rombos.x).toEqual([12, 36, 60]);
|
||||
expect(rombos.error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.02, 0.03, 0.05]);
|
||||
});
|
||||
|
||||
// Fails if the Weibull stops being dotted past the follow-up the cohort has, which would present an extrapolation as observed.
|
||||
it('draws the Weibull dotted past the follow-up', () => {
|
||||
const punteadas = f().data.filter((t: any) => t.line?.dash === 'dot') as any[];
|
||||
|
||||
expect(punteadas).toHaveLength(2);
|
||||
expect(punteadas.every(t => Math.min(...t.x) >= 60)).toBe(true);
|
||||
});
|
||||
|
||||
// Fails if the labels or the title leave the pipeline's: recurrence-free S(t), the scenario, the cohort, n and recurrences.
|
||||
it('is titled with the scenario, the cohort, its patients and recurrences', () => {
|
||||
const l = f().layout as any;
|
||||
|
||||
expect(l.title.text).toBe('RE− · grado 3<br>METABRIC · n=300, recaídas=180');
|
||||
expect(l.yaxis.title.text).toBe('Libre de recaída S(t)');
|
||||
expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Recurrencia de la paciente: componente', () => {
|
||||
let recurrencia: ReturnType<typeof vi.fn>;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) },
|
||||
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
|
||||
recurrencia = vi.fn(() => of(respuestaRecurrencia(respuesta([figura(), figura('Grado 3', 'scanb')]))));
|
||||
TestBed.configureTestingModule({ providers: [{ provide: CamaRecurrenciaService, useValue: { recurrencia } },
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
const f = TestBed.createComponent(CamaRecurrenciaPaciente);
|
||||
f.componentRef.setInput('pacId', '7');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
return f;
|
||||
};
|
||||
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
||||
|
||||
// Fails if a scenario she meets in either cohort has no figure.
|
||||
it('draws a figure for each scenario she meets, in each cohort', () => {
|
||||
const f = montar();
|
||||
|
||||
expect(recurrencia).toHaveBeenCalledWith('7');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2);
|
||||
});
|
||||
|
||||
// Fails if a patient in no scenario sees nothing, or an error.
|
||||
it('says so when she meets none of the scenarios', () => {
|
||||
recurrencia.mockReturnValue(of(respuestaRecurrencia(respuesta([]))));
|
||||
const f = montar();
|
||||
|
||||
expect(texto(f)).toContain('no cumple ninguno de los escenarios clínicos');
|
||||
expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull();
|
||||
});
|
||||
|
||||
// Fails if no model in production is shown as an error or a blank.
|
||||
it('says there is no recurrence model yet', () => {
|
||||
recurrencia.mockReturnValue(of(null));
|
||||
|
||||
expect(texto(montar())).toContain('Todavía no hay un modelo de recurrencia en producción');
|
||||
});
|
||||
});
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { Component, computed, inject, input } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaRecurrenciaService, FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
|
||||
/** One scenario's recurrence figure. */
|
||||
@Component({
|
||||
selector: 'app-cama-figura-recurrencia',
|
||||
imports: [PlotlyChart],
|
||||
template: `@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + datos().escenario + ', ' + datos().cohorte_nombre" /> }`,
|
||||
})
|
||||
export class CamaFiguraRecurrencia {
|
||||
readonly datos = input.required<FiguraRecurrencia>();
|
||||
readonly figura = computed(() => figuraRecurrencia(this.datos()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The patient's probability of recurrence: the figure of each clinical scenario of the recurrence analysis that her covariates meet,
|
||||
* in each external cohort (METABRIC and SCAN-B). Patients in one scenario share its figure; it describes that scenario's patients in
|
||||
* the cohort the analysis was made on.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-recurrencia-paciente',
|
||||
imports: [CamaFiguraRecurrencia],
|
||||
templateUrl: './cama-recurrencia-paciente.component.html',
|
||||
})
|
||||
export class CamaRecurrenciaPaciente {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaRecurrenciaService);
|
||||
/** The answer; `undefined` while it loads, `null` when there is no recurrence model in production. */
|
||||
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { catchError, map, Observable, of } from 'rxjs';
|
||||
|
||||
// CaMa's recurrence figures of a patient, `GET /cama/modelo/recurrencia?paciente=`: the clinical scenarios her covariates meet,
|
||||
// each as the recurrence analysis of an external cohort (METABRIC or SCAN-B) drew it. They describe the scenario's patients in
|
||||
// that cohort, not her; the answer names the version that published them. A 404 or a failure is "none to show".
|
||||
export interface FiguraRecurrencia {
|
||||
cohorte: string; cohorte_nombre: string; escenario: string; n: number; recaidas: number;
|
||||
horizons_months: number[]; observado_hasta: number; months_max: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { COMB: { S: number[]; low: number[]; high: number[] } };
|
||||
}
|
||||
export interface RespuestaRecurrencia { modelo: { nombre: string; version: string }; horizontes: number[]; escenarios: FiguraRecurrencia[]; }
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number' && Number.isFinite(x)) && (length === undefined || v.length === length);
|
||||
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
|
||||
|
||||
function invalid(): never { throw new Error('Respuesta de recurrencia inválida'); }
|
||||
|
||||
function figura(v: unknown, horizons: number): FiguraRecurrencia {
|
||||
if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte_nombre'] !== 'string' || typeof v['cohorte'] !== 'string') invalid();
|
||||
const f = v as Record<string, any>;
|
||||
if (!numbers(f['horizons_months'], horizons) || !Number.isFinite(f['n']) || !Number.isFinite(f['recaidas']) || !Number.isFinite(f['observado_hasta']) || !Number.isFinite(f['months_max'])) invalid();
|
||||
const km = f['km'], w = f['weibull'], k = f['weibull_fractional'], p = f['points']?.['COMB'];
|
||||
const n = Array.isArray(km?.months) ? km.months.length : -1;
|
||||
if (!numbers(km?.months) || !probabilities(km?.S, n) || !probabilities(km?.low, n) || !probabilities(km?.high, n)) invalid();
|
||||
for (const c of [w, k]) if (!numbers(c?.t) || !probabilities(c?.S, c.t.length)) invalid();
|
||||
if (!probabilities(p?.S, horizons) || !probabilities(p?.low, horizons) || !probabilities(p?.high, horizons)) invalid();
|
||||
if ((p.low as number[]).some((l, i) => l > p.high[i])) invalid();
|
||||
return f as FiguraRecurrencia;
|
||||
}
|
||||
|
||||
/** Validate at the boundary: the shapes and ranges, so the chart never draws a partial or impossible curve. */
|
||||
export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
|
||||
if (!record(v) || !record(v['modelo']) || !Array.isArray(v['escenarios']) || !numbers(v['horizontes'])) invalid();
|
||||
const m = v['modelo'] as Record<string, unknown>, h = (v['horizontes'] as number[]).length;
|
||||
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
|
||||
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
|
||||
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)) };
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaRecurrenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The figures of the scenarios the patient meets, or `null` when there is no recurrence model in production or it fails. */
|
||||
recurrencia(pacId: string): Observable<RespuestaRecurrencia | null> {
|
||||
return this.http.get<unknown>('/cama/modelo/recurrencia', { params: { paciente: pacId } }).pipe(
|
||||
map(respuestaRecurrencia), catchError(() => of(null)));
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,8 @@ describe('Tabla de seguimiento con pac_id', () => {
|
||||
// Opening a CaMa record asks for the patient's risk; in these tests nobody has one.
|
||||
afterEach(() => {
|
||||
http.match(r => r.url === '/cama/fhir/RiskAssessment').forEach(r => { if (!r.cancelled) r.flush({ resourceType: 'Bundle', type: 'searchset', total: 0 }); });
|
||||
// The record also asks for the recurrence figures of the patient; there is no model for them here.
|
||||
http.match(r => r.url === '/cama/modelo/recurrencia').forEach(r => { if (!r.cancelled) r.flush({ error: 'sin recurrencia' }, { status: 404, statusText: 'Not Found' }); });
|
||||
fixture.destroy(); http.verify();
|
||||
});
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
|
||||
Reference in New Issue
Block a user