CaMa patient record: no subgroup panel, one legend entry for the patient

This commit is contained in:
rockdrigo
2026-11-21 13:03:19 -06:00
parent 7adceb86bf
commit e8ce7a487b
6 changed files with 28 additions and 94 deletions
@@ -68,14 +68,6 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
};
}
/** What can be selected, and the patient's own value of each covariate (`GET /cama/modelo/curvas/opciones?paciente=`). */
export interface OpcionesCurvas {
n: number; events: number;
covariables: Record<string, { valor: string; n: number }[]>;
periodo: { desde: string; hasta: string };
limites: { miembros_min: number; muertes_min: number };
paciente: Record<string, string> | null;
}
export interface ConsultaCurvas { filtros?: Record<string, string[]>; periodo?: { desde?: string; hasta?: string }; }
/** The selection was refused with a reason (a 422): too few patients, or invalid. */
export class SeleccionRechazada extends Error {}
@@ -84,14 +76,6 @@ export class SeleccionRechazada extends Error {}
export class CamaCurvasService {
private readonly http = inject(HttpClient);
/** The values that can be selected, and `pacId`'s own; `null` when there is no model in production or no cohort yet. */
opciones(pacId: string): Observable<OpcionesCurvas | null> {
return this.http.get<{ opciones: OpcionesCurvas }>('/cama/modelo/curvas/opciones', { params: { paciente: pacId } }).pipe(
map(r => r.opciones),
catchError(() => of(null)),
);
}
/** The figure's record for the selection, scored with the production version over the data ingested so far. A refused
* selection fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
consulta(consulta: ConsultaCurvas): Observable<RespuestaCurvas> {
@@ -1,16 +1,8 @@
<section class="survival" aria-labelledby="supervivencia-paciente-titulo">
<h5 id="supervivencia-paciente-titulo">Supervivencia de la paciente</h5>
@if (cruzables().length) {
<fieldset class="compare">
<legend>Comparar con las pacientes que comparten</legend>
@for (c of cruzables(); track c.clave) {
<label><input type="checkbox" [checked]="cruces().includes(c.clave)" (change)="alternar(c.clave)" /> {{ c.etiqueta }}: {{ c.valor }}</label>
}
</fieldset>
}
@let l = lectura();
@if (l.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
@if (l.tipo === 'rechazada') { <p role="status">{{ l.motivo }} Quita algún criterio para comparar con más pacientes.</p> }
@if (l.tipo === 'rechazada') { <p role="status">{{ l.motivo }}</p> }
@if (l.tipo === 'error') { <p role="status">No se pudo calcular la curva de la cohorte; se muestra solo la de la paciente.</p> }
@if (figura(); as figure) {
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Supervivencia de la paciente" />
@@ -1,3 +1 @@
.compare { border: 1px solid var(--mat-sys-outline-variant, #ccc); margin: 0 0 1rem; padding: .5rem .75rem; display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; }
.compare legend { font-weight: 600; padding: 0 .25rem; }
label { display: inline-flex; align-items: center; gap: .35rem; }
:host { display: block; }
@@ -25,8 +25,6 @@ function cohorte(n = 245): any {
};
}
const horizontes = [{ horizonte_anios: 0.5, probabilidad: 0.07 }, { horizonte_anios: 1, probabilidad: 0.18 }, { horizonte_anios: 1.5, probabilidad: 0.25 }];
const opciones = { n: 500, events: 133, covariables: {}, periodo: { desde: '2024-01-01', hasta: '2026-01-01' }, limites: { miembros_min: 30, muertes_min: 5 },
paciente: { grade: 'G2', er: 'POSITIVO', her2: 'NA', age_group: '60-74' } };
describe('Figura de supervivencia de la paciente', () => {
const figura = (c: any = cohorte().curvas) => figuraSupervivenciaPaciente(horizontes, respuestaCurvas(c === null ? cohorte() : { ...cohorte(), curvas: c }).curvas)!;
@@ -49,12 +47,12 @@ describe('Figura de supervivencia de la paciente', () => {
// Fails if her curve is not on the figure, or sits at other horizons than her evaluation's.
it('draws hers over the cohort\'s: a curve and her diamonds at her horizons', () => {
const f = figura();
const suya = traza(f, ETIQUETAS_PREDETERMINADAS['paciente_puntos']);
const suya = f.data.find((t: any) => t.legendgroup === 'paciente' && t.mode === 'markers') as any;
expect(suya.x).toEqual([6, 12, 18]);
expect(suya.y.map((v: number) => +v.toFixed(2))).toEqual([0.93, 0.82, 0.75]);
expect(suya.error_y).toBeUndefined();
expect(traza(f, ETIQUETAS_PREDETERMINADAS['paciente']).line.color).toBe(COLORES.paciente);
expect((f.data.find((t: any) => t.legendgroup === 'paciente' && t.mode === 'lines') as any).line.color).toBe(COLORES.paciente);
});
// Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, n and deaths.
@@ -68,11 +66,14 @@ describe('Figura de supervivencia de la paciente', () => {
expect(l.legend.yanchor).toBe('bottom');
});
// Fails if the subgroup the reader chose is not what the title says.
it('names the subgroup in the title', () => {
const f = figuraSupervivenciaPaciente(horizontes, cohorte().curvas, 'claro', 'Pacientes con Grado de Nottingham G2')!;
// Fails if her curve and her diamonds take two legend entries, which says nothing the curve does not.
it('has one legend entry for her curve and her diamonds', () => {
const f = figura();
const suyas = f.data.filter((t: any) => t.legendgroup === 'paciente') as any[];
expect((f.layout as any).title.text).toContain('Pacientes con Grado de Nottingham G2');
expect(suyas).toHaveLength(2);
expect(suyas.filter(t => t.showlegend !== false)).toHaveLength(1);
expect(f.data.some((t: any) => t.name === 'Paciente: modelo en cada horizonte')).toBe(false);
});
});
@@ -84,7 +85,7 @@ describe('Supervivencia de la paciente: componente', () => {
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
consulta = vi.fn(() => of(respuestaCurvas(cohorte())));
TestBed.configureTestingModule({ providers: [
{ provide: CamaCurvasService, useValue: { opciones: () => of(opciones), consulta } },
{ provide: CamaCurvasService, useValue: { consulta } },
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
});
afterEach(() => vi.unstubAllGlobals());
@@ -97,28 +98,14 @@ describe('Supervivencia de la paciente: componente', () => {
};
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
// Fails if the cohort's curves are not asked for everyone first, or the covariates she has no value for are offered.
it('asks the cohort live, for everyone, and offers the covariates she has a value for', () => {
// Fails if the cohort's curves are not asked live for everyone, or the record offers choices the reader did not ask for.
it('asks the cohort live, for everyone, and offers no choices', () => {
const f = montar();
expect(consulta).toHaveBeenCalledWith({ filtros: {} });
expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
const t = texto(f);
expect(t).toContain('Grado de Nottingham: G2');
expect(t).toContain('Receptor de estrógeno: POSITIVO');
expect(t).not.toContain('HER2:');
});
// Fails if ticking a covariate does not ask the cohort for the patients who share it, or unticking does not go back.
it('asks for her subgroup when a covariate is ticked, and for everyone when it is unticked', () => {
const f = montar();
f.componentInstance.alternar('grade');
f.detectChanges();
expect(consulta).toHaveBeenLastCalledWith({ filtros: { grade: ['G2'] } });
f.componentInstance.alternar('grade');
f.detectChanges();
expect(consulta).toHaveBeenLastCalledWith({ filtros: {} });
expect(f.nativeElement.querySelector('input, fieldset')).toBeNull();
expect(texto(f)).not.toContain('Comparar con');
});
// Fails if a refused selection draws a figure, or does not say why.
@@ -1,23 +1,17 @@
import { Component, computed, inject, input, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of, startWith, switchMap } from 'rxjs';
import { Component, computed, inject, input } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of, startWith } from 'rxjs';
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
import { HorizonteRiesgoCacu } from '../paciente-riesgo.models';
import { CamaCurvasService, ConsultaCurvas, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
import { CamaCurvasService, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
import { figuraSupervivenciaPaciente } from './cama-supervivencia-paciente';
/** What the reader calls each covariate of the model. */
export const COVARIABLES: Record<string, string> = {
age_group: 'Grupo de edad', histologic_type: 'Tipo histológico', grade: 'Grado de Nottingham', er: 'Receptor de estrógeno',
pr: 'Receptor de progesterona', her2: 'HER2', ki67_group: 'Ki-67 (%)', size_group: 'Tamaño de la lesión (mm)',
};
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas };
/**
* One patient's survival, on the SEER pipeline's figure of the cohort. The cohort's curves are computed when the record opens,
* from the data ingested so far and the model in production, for everyone or for the patients who share the covariates the
* reader ticks with her (her subgroup, as the pipeline draws its subgroups). Hers is her own prediction on top of them.
* from the data ingested so far and the model in production; hers is her own prediction on top of them.
*/
@Component({
selector: 'app-cama-supervivencia-paciente',
@@ -29,34 +23,14 @@ export class CamaSupervivenciaPaciente {
readonly pacId = input.required<string>();
readonly horizontes = input.required<readonly HorizonteRiesgoCacu[]>();
private readonly service = inject(CamaCurvasService);
/** The covariates she is compared on. */
readonly cruces = signal<readonly string[]>([]);
readonly opciones = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.opciones(id))));
/** The covariates she has a value for, to offer. */
readonly cruzables = computed(() => {
const suyas = this.opciones()?.paciente;
return suyas ? Object.keys(COVARIABLES).filter(c => suyas[c] && suyas[c] !== 'NA').map(c => ({ clave: c, etiqueta: COVARIABLES[c], valor: suyas[c] })) : [];
});
private readonly consulta = computed<ConsultaCurvas>(() => {
const suyas = this.opciones()?.paciente;
return { filtros: Object.fromEntries(this.cruces().filter(c => suyas?.[c]).map(c => [c, [suyas![c]]])) };
});
readonly lectura = toSignal(toObservable(this.consulta).pipe(switchMap(q => this.service.consulta(q).pipe(
readonly lectura = toSignal(this.service.consulta({ filtros: {} }).pipe(
map((datos): Lectura => ({ tipo: 'lista', datos })),
catchError(error => of<Lectura>(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })),
startWith<Lectura>({ tipo: 'cargando' })))), { initialValue: { tipo: 'cargando' } as Lectura });
private readonly descripcion = computed(() => {
const suyas = this.opciones()?.paciente;
const partes = this.cruces().filter(c => suyas?.[c]).map(c => `${COVARIABLES[c]} ${suyas![c]}`);
return partes.length ? `Pacientes con ${partes.join(' · ')}` : null;
});
startWith<Lectura>({ tipo: 'cargando' })), { initialValue: { tipo: 'cargando' } as Lectura });
/** The figure: hers over the cohort's, or hers alone when the cohort's cannot be had. */
readonly figura = computed(() => {
const l = this.lectura();
if (l.tipo === 'cargando' || l.tipo === 'rechazada') return null;
return figuraSupervivenciaPaciente(this.horizontes(), l.tipo === 'lista' ? l.datos.curvas : null, 'claro', this.descripcion());
return figuraSupervivenciaPaciente(this.horizontes(), l.tipo === 'lista' ? l.datos.curvas : null);
});
alternar(clave: string): void {
this.cruces.update(actuales => actuales.includes(clave) ? actuales.filter(c => c !== clave) : [...actuales, clave]);
}
}
@@ -9,8 +9,7 @@ export const ETIQUETAS_PREDETERMINADAS: Readonly<Record<string, string>> = {
titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor',
eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)',
km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional',
puntos: 'LR + HBN combinado (IC 95 % bootstrap)', paciente: 'Paciente: supervivencia estimada',
paciente_puntos: 'Paciente: modelo en cada horizonte',
puntos: 'LR + HBN combinado (IC 95 % bootstrap)', paciente: 'Paciente',
};
export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a', paciente: '#e08a00' } as const;
/** The curve runs to this many months, as the cohort's does. */
@@ -77,13 +76,13 @@ export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgo
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('puntos') + '</extra>' });
}
data.push(
{ type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: t('paciente'), line: { color: COLORES.paciente, width: 3 },
{ type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: t('paciente'), legendgroup: 'paciente', line: { color: COLORES.paciente, width: 3 },
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('paciente') + '</extra>' },
{ type: 'scatter', mode: 'markers', name: t('paciente_puntos'), x: puntos.map(p => p.meses), y: puntos.map(p => p.S),
{ type: 'scatter', mode: 'markers', name: t('paciente'), legendgroup: 'paciente', showlegend: false, x: puntos.map(p => p.meses), y: puntos.map(p => p.S),
marker: { symbol: 'diamond', size: 14, color: COLORES.paciente, line: { color: 'white', width: 1.5 } },
...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.paciente, thickness: 2, width: 6,
array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}),
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('paciente_puntos') + '</extra>' });
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('paciente') + '</extra>' });
const minimo = Math.max(0, Math.floor((Math.min(...bajos) - 0.02) * 20) / 20);
const base = descripcion ?? t('titulo');
const titulo = cohorte ? `${base}<br>n=${cohorte.n.toLocaleString('es-MX')}, fallecidos=${cohorte.events.toLocaleString('es-MX')}` : base;