CaMa patient card: the SEER model's survival by clinical scenario beside the production model's
This commit is contained in:
@@ -48,6 +48,12 @@
|
||||
<mat-card-header><h3 id="riesgo-individual-title">Riesgo de muerte</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
@if (p.idField === 'pac_id') { <app-cama-analisis-supervivencia [pacId]="p.patientId" /> }
|
||||
@if (p.idField === 'pac_id') {
|
||||
<section aria-labelledby="supervivencia-seer-title">
|
||||
<h5 id="supervivencia-seer-title">Supervivencia por escenario clínico (modelo SEER)</h5>
|
||||
<app-cama-supervivencia [pacId]="+p.patientId" />
|
||||
</section>
|
||||
}
|
||||
<section aria-labelledby="recomendaciones-riesgo-title">
|
||||
<h5 id="recomendaciones-riesgo-title">Recomendaciones</h5>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
|
||||
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
|
||||
import { CamaSupervivencia } from './cama-supervivencia';
|
||||
import {
|
||||
CamaPatientSummary, NOT_AVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
} from './cama-patient.models';
|
||||
@@ -16,7 +17,7 @@ import {
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-patient-card',
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia],
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia, CamaSupervivencia],
|
||||
templateUrl: './cama-patient-card.html',
|
||||
styleUrl: './cama-patient-card.scss',
|
||||
})
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { SupervivenciaFigura } from './cama-supervivencia.models';
|
||||
|
||||
const decimales = new Intl.NumberFormat('es-MX');
|
||||
|
||||
/**
|
||||
* The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the
|
||||
* LR + HBN combined survival at each horizon with its bootstrap interval.
|
||||
*/
|
||||
export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure {
|
||||
const meses = figura.months ?? [];
|
||||
const km = figura.km!;
|
||||
const curvas = figura.curve_months ?? [];
|
||||
const combinados = figura.points.filter(p => p.model === 'COMB');
|
||||
const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1];
|
||||
const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])]
|
||||
.filter(v => Number.isFinite(v));
|
||||
const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06;
|
||||
return {
|
||||
data: [
|
||||
{ x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false },
|
||||
{ x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)',
|
||||
hoverinfo: 'skip', showlegend: false },
|
||||
{ x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' },
|
||||
name: 'Kaplan-Meier (IC 95 % Greenwood)' },
|
||||
{ x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' },
|
||||
{ x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' },
|
||||
name: 'Weibull fraccional' },
|
||||
{ x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers',
|
||||
marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } },
|
||||
error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low),
|
||||
color: '#6a3d9a', thickness: 2, width: 5 },
|
||||
name: 'LR + HBN combinado (IC 95 % bootstrap)' },
|
||||
],
|
||||
layout: {
|
||||
title: { text: `${figura.scenario}<br>n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } },
|
||||
xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false },
|
||||
yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] },
|
||||
legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 },
|
||||
hovermode: 'x unified',
|
||||
},
|
||||
config: { responsive: true, displaylogo: false },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
@switch (estado()) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando escenarios de supervivencia" /> }
|
||||
@case ('sin-modelo') { <p class="availability">No hay un modelo de supervivencia en producción.</p> }
|
||||
@case ('error') { <p class="availability" role="alert">No se pudieron cargar los escenarios de supervivencia.</p> }
|
||||
@case ('sin-escenarios') { <p class="availability">La paciente no pertenece a ninguno de los escenarios clínicos del modelo.</p> }
|
||||
@default {
|
||||
@if (escenarios().length > 1) {
|
||||
<mat-button-toggle-group class="scenarios" aria-label="Escenario clínico" [value]="elegido()" (change)="elegir($event.value)">
|
||||
@for (nombre of escenarios(); track nombre) { <mat-button-toggle [value]="nombre">{{ nombre }}</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
}
|
||||
@if (cargandoFigura()) { <mat-progress-bar mode="indeterminate" aria-label="Calculando figura" /> }
|
||||
@if (figura(); as f) { <app-plotly-chart [figure]="f" [showNotes]="false" label="Curva de supervivencia del escenario clínico" /> }
|
||||
@if (sinDibujo(); as mensaje) { <p class="availability" role="status">{{ mensaje }}</p> }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */
|
||||
export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number }
|
||||
|
||||
export interface SupervivenciaFigura {
|
||||
scenario: string;
|
||||
members: number;
|
||||
deaths: number;
|
||||
drawable: boolean;
|
||||
horizons: number[];
|
||||
months?: number[];
|
||||
km?: { S: number[]; lo: number[]; hi: number[] };
|
||||
curve_months?: number[];
|
||||
weibull?: { k: number; S: number[] };
|
||||
fractional?: { k: number; alpha: number; beta: number; S: number[] };
|
||||
points: SupervivenciaPunto[];
|
||||
}
|
||||
|
||||
export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] }
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number');
|
||||
|
||||
export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios {
|
||||
if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string')
|
||||
|| typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') {
|
||||
throw new Error('Respuesta de escenarios de supervivencia inválida');
|
||||
}
|
||||
return v as unknown as SupervivenciaEscenarios;
|
||||
}
|
||||
|
||||
export function supervivenciaFigura(v: unknown): SupervivenciaFigura {
|
||||
if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number'
|
||||
|| typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) {
|
||||
throw new Error('Respuesta de figura de supervivencia inválida');
|
||||
}
|
||||
if (v['drawable']) {
|
||||
const km = v['km'], w = v['weibull'], f = v['fractional'];
|
||||
if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi'])
|
||||
|| !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta');
|
||||
}
|
||||
return v as unknown as SupervivenciaFigura;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
:host { display: block; min-width: 0; --plot-height: 420px; }
|
||||
.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; }
|
||||
.availability { margin: 0; }
|
||||
@@ -0,0 +1,20 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaSupervivenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios a patient belongs to, from her variables over the timeline. */
|
||||
escenarios(pacId: number) {
|
||||
return this.http.get<unknown>(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios));
|
||||
}
|
||||
|
||||
/** The figure of one scenario over the production model and the live cohort. */
|
||||
figura(escenario: string) {
|
||||
const params = new HttpParams().set('escenario', escenario);
|
||||
return this.http.get<unknown>('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { Subscription } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from '../../indicadores.models';
|
||||
import { figuraSupervivencia } from './cama-supervivencia-seer-figura';
|
||||
import { CamaSupervivenciaService } from './cama-supervivencia.service';
|
||||
|
||||
/**
|
||||
* A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in
|
||||
* production and the live cohort.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-supervivencia',
|
||||
imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './cama-supervivencia.html',
|
||||
styleUrl: './cama-supervivencia.scss',
|
||||
})
|
||||
export class CamaSupervivencia {
|
||||
readonly pacId = input.required<number>();
|
||||
readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando');
|
||||
readonly escenarios = signal<string[]>([]);
|
||||
readonly elegido = signal<string | null>(null);
|
||||
readonly figura = signal<PlotlyFigure | null>(null);
|
||||
readonly cargandoFigura = signal(false);
|
||||
readonly sinDibujo = signal<string | null>(null);
|
||||
private readonly servicio = inject(CamaSupervivenciaService);
|
||||
private readonly destroy = inject(DestroyRef);
|
||||
private pedido?: Subscription;
|
||||
|
||||
constructor() {
|
||||
effect(() => this.cargar(this.pacId()));
|
||||
}
|
||||
|
||||
private cargar(pacId: number) {
|
||||
this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null);
|
||||
this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||||
next: respuesta => {
|
||||
this.escenarios.set(respuesta.scenarios);
|
||||
if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; }
|
||||
this.estado.set('listo');
|
||||
this.elegir(respuesta.scenarios[0]);
|
||||
},
|
||||
error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'),
|
||||
});
|
||||
}
|
||||
|
||||
elegir(escenario: string) {
|
||||
this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true);
|
||||
this.pedido?.unsubscribe();
|
||||
this.pedido = this.servicio.figura(escenario).subscribe({
|
||||
next: f => {
|
||||
this.cargandoFigura.set(false);
|
||||
if (this.elegido() !== escenario) return;
|
||||
if (f.drawable) this.figura.set(figuraSupervivencia(f));
|
||||
else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`);
|
||||
},
|
||||
error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); },
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user