feat(cama): «Análisis» in three parts: survival, subgroup explorer and cohort diagnostics

The tab held every figure and table in one long page. It now has three parts
under one set of controls (scenario, estimator, stratum and filters), each
answering one question.

How:
- Supervivencia: the cumulative incidence curves with their risk table, then
  the comparison of the groups (log-rank with Holm pairs beside the RMST).
- Explorador de subgrupos: a new BI-RADS by age-group grid of the incidence
  at the horizon (GET /<domain>/analisis/subgrupos, guarded by
  analisisSubgrupos: no published cell under the threshold), drawn by
  subgruposFigura with suppressed cells grey and named; and the Cox forest
  plot of the chosen stratum. A cell click filters both dimensions and opens
  its curves in Supervivencia (celdaDelClic reads only coloured cells).
- Diagnóstico de la cohorte: the cohort's statistical status (patients,
  events, median follow-up, events per parameter, suppression threshold),
  the C13 validation report and what the cohort cannot answer yet
  (blocked analyses and strata).
- The parts are a keyboard tab list; the grid is requested only when its
  part opens and again only when the scenario or estimator changes.

Implications:
- One more endpoint for the backend to implement, aggregate-only like the
  others; until then the explorer shows its error with a retry.
- The stratum and filters stay hidden in the explorer, where the grid
  ignores them; the forest plot follows the ones chosen in Supervivencia.
This commit is contained in:
rockdrigo
2026-11-12 13:49:20 -06:00
parent e803c38acf
commit 05a55a673e
4 changed files with 357 additions and 97 deletions
@@ -1,6 +1,6 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { AnalisisResultados } from './indicadores-analisis.service';
import { AnalisisResultados, AnalisisSubgrupos } from './indicadores-analisis.service';
const DIAS_POR_MES = 30.4375;
const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -77,4 +77,48 @@ export function forestFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
};
}
/**
* Incidence at the horizon by BI-RADS (rows) and age group (columns). A suppressed cell is drawn grey with its
* reason, never as a colour; each cell carries its pair of codes, so a click only changes the filters.
*/
export function subgruposFigura(s: AnalisisSubgrupos, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), horizonte = Math.round(s.horizonte_dias / DIAS_POR_MES);
const celda = (f: string, c: string) => s.celdas.find(x => x.birads === f && x.grupo_edad === c);
const z = s.filas.map(f => s.columnas.map(c => { const x = celda(f.codigo, c.codigo); return x && !x.suprimido ? x.valor : null; }));
const texto = s.filas.map(f => s.columnas.map(c => {
const x = celda(f.codigo, c.codigo);
if (!x || x.suprimido) return '<span style="opacity:.75">Suprimido</span>';
const meses = Math.round(x.t_dias! / DIAS_POR_MES);
return `<b>${pct(x.valor!)} %</b><br>${miles(x.eventos!)} de ${miles(x.n!)}${meses < horizonte ? `<br>a ${meses} meses` : ''}`;
}));
const ayuda = s.filas.map(f => s.columnas.map(c => {
const x = celda(f.codigo, c.codigo);
if (!x || x.suprimido) return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}: suprimido (${(x?.motivo ?? 'sin datos').toLowerCase()})`;
return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}<br>${pct(x.valor!)} % (IC 95 %: ${pct(x.ic_bajo!)} a ${pct(x.ic_alto!)})<br>${miles(x.eventos!)} eventos en ${miles(x.n!)} pacientes`;
}));
const maximo = Math.max(1, ...z.flat().filter((v): v is number => v !== null));
return {
data: [
// The grey layer under the colour: the cells the answer suppressed.
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z: z.map(r => r.map(v => v === null ? 1 : null)),
colorscale: [[0, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9'], [1, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9']], showscale: false, hoverinfo: 'skip', xgap: 3, ygap: 3 },
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z, zmin: 0, zmax: maximo, xgap: 3, ygap: 3,
customdata: s.filas.map(f => s.columnas.map(c => [f.codigo, c.codigo])), text: ayuda, hovertemplate: '%{text}<extra></extra>',
colorscale: [[0, tema === 'oscuro' ? '#1B3A5B' : '#EAF1F8'], [1, tema === 'oscuro' ? '#9DBFE3' : '#1F5F8B']],
colorbar: { title: { text: 'Incidencia (%)' }, ticksuffix: ' %', thickness: 12 } },
],
layout: {
autosize: true, height: 80 + 64 * s.filas.length, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 16, l: 16, r: 16, b: 56 },
xaxis: { title: { text: 'Grupo de edad' }, side: 'bottom', fixedrange: true, automargin: true },
yaxis: { autorange: 'reversed', fixedrange: true, automargin: true },
annotations: s.filas.flatMap((f, i) => s.columnas.map((c, j) => {
const v = z[i][j];
return { x: c.etiqueta, y: f.etiqueta, xref: 'x', yref: 'y', showarrow: false, text: texto[i][j], font: { size: 12, color: v !== null && v > maximo * .55 ? '#FFFFFF' : p.text } };
})),
},
config: { displayModeBar: false },
};
}
export const mesesDe = (dias: number) => Math.round(dias / DIAS_POR_MES);
@@ -41,6 +41,16 @@ export interface AnalisisResultados {
efectos: Efectos; validacion: FilaValidacion[]; avisos: string[];
}
// The BI-RADS by age-group grid: the incidence at the horizon in each cell, or the reason it is suppressed.
export interface CeldaSubgrupo {
birads: string; grupo_edad: string; suprimido: boolean; motivo: string | null;
n: number | null; eventos: number | null; t_dias: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
}
export interface AnalisisSubgrupos {
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; escenario: string; estimador: string;
filas: { codigo: string; etiqueta: string }[]; columnas: { codigo: string; etiqueta: string }[]; celdas: CeldaSubgrupo[];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
@@ -89,6 +99,20 @@ export function analisisResultados(v: unknown): AnalisisResultados {
return v as unknown as AnalisisResultados;
}
export function analisisSubgrupos(v: unknown): AnalisisSubgrupos {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
const eje = (x: unknown) => lista(x, o => record(o) && text(o['codigo']) && text(o['etiqueta']));
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador'])
|| !eje(v['filas']) || !eje(v['columnas'])
|| !lista(v['celdas'], c => record(c) && text(c['birads']) && text(c['grupo_edad']) && typeof c['suprimido'] === 'boolean'
&& (c['suprimido'] ? c['n'] === null && c['eventos'] === null && c['valor'] === null
: num(c['n']) && num(c['eventos']) && num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['t_dias'])))) invalido();
// A published cell never has fewer patients or events than the threshold.
const umbral = v['umbral_supresion'] as number;
if ((v['celdas'] as CeldaSubgrupo[]).some(c => !c.suprimido && (c.n! < umbral || c.eventos! < umbral))) invalido();
return v as unknown as AnalisisSubgrupos;
}
@Injectable({ providedIn: 'root' })
export class AnalisisService {
private readonly http = inject(HttpClient);
@@ -100,4 +124,8 @@ export class AnalisisService {
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/resultados`, { params }).pipe(map(analisisResultados));
}
subgrupos(dominio: Dominio, escenario: string, estimador: string) {
const params = new HttpParams().set('escenario', escenario).set('estimador', estimador);
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/subgrupos`, { params }).pipe(map(analisisSubgrupos));
}
}
@@ -3,14 +3,16 @@ import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresAnalisis, grupoDelClic, pedidoAlElegir } from './indicadores-analisis';
import { curvasFigura, forestFigura } from './indicadores-analisis-figuras';
import { AnalisisCatalogo, AnalisisResultados, analisisCatalogo, analisisResultados } from './indicadores-analisis.service';
import { IndicadoresAnalisis, celdaDelClic, grupoDelClic, pedidoAlElegir } from './indicadores-analisis';
import { curvasFigura, forestFigura, subgruposFigura } from './indicadores-analisis-figuras';
import { AnalisisCatalogo, AnalisisResultados, AnalisisSubgrupos, analisisCatalogo, analisisResultados, analisisSubgrupos } from './indicadores-analisis.service';
// Covers the «Análisis» tab of breast cancer: the answer's guard (aggregates only, nothing under the threshold),
// the figures built from it, the click that only changes the request, and the tab's requests and states.
// The tab has three parts (survival, subgroup explorer, cohort diagnostics) under one set of controls.
// Fixtures: `catalogo` (two scenarios, two estimators, two available strata and one that isn't, one blocked
// analysis) and `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model), both built below.
// analysis), `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model) and `subgrupos`
// (a two-by-two BI-RADS and age grid with one suppressed cell), all built below.
const catalogo = (): AnalisisCatalogo => ({
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5,
@@ -49,6 +51,18 @@ const resultados = (): AnalisisResultados => ({
avisos: ['Análisis descriptivo, no causal.', 'Horizonte de 2 años (730 días).', 'Requiere el estado vital.'],
});
const subgrupos = (): AnalisisSubgrupos => ({
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif',
filas: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }],
columnas: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }],
celdas: [
{ birads: 'B4A', grupo_edad: '40-49', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, t_dias: null, valor: null, ic_bajo: null, ic_alto: null },
{ birads: 'B4A', grupo_edad: '50-59', suprimido: false, motivo: null, n: 60, eventos: 6, t_dias: 730, valor: 10, ic_bajo: 4, ic_alto: 20 },
{ birads: 'B5', grupo_edad: '40-49', suprimido: false, motivo: null, n: 40, eventos: 36, t_dias: 120, valor: 90, ic_bajo: 78, ic_alto: 96 },
{ birads: 'B5', grupo_edad: '50-59', suprimido: false, motivo: null, n: 50, eventos: 45, t_dias: 730, valor: 92, ic_bajo: 81, ic_alto: 97 },
],
});
describe('Respuesta del análisis', () => {
it('admite solo agregados de demostración', () => {
// Fails if the guard stops rejecting real records or anything shaped like a patient row, at any depth.
@@ -66,6 +80,26 @@ describe('Respuesta del análisis', () => {
});
});
describe('Explorador de subgrupos', () => {
it('admite celdas publicadas solo desde el umbral y dibuja gris lo suprimido', () => {
// Fails if a cell under the threshold reaches the grid, or a suppressed cell is drawn as a colour.
expect(analisisSubgrupos(subgrupos()).celdas).toHaveLength(4);
expect(() => analisisSubgrupos({ ...subgrupos(), celdas: subgrupos().celdas.map(c => c.suprimido ? c : { ...c, eventos: 3 }) })).toThrow();
const fig = subgruposFigura(subgrupos(), 'claro');
expect((fig.data[1]['z'] as (number | null)[][])[0]).toEqual([null, 10]);
expect((fig.data[0]['z'] as (number | null)[][])[0]).toEqual([1, null]);
const textos = (fig.layout['annotations'] as { text: string }[]).map(a => a.text);
expect(textos[0]).toContain('Suprimido');
expect(textos[2]).toContain('a 4 meses');
});
it('un clic en una celda con color da su BI-RADS y edad; en una gris, nada', () => {
// Fails if a click on a suppressed cell could open a subgroup the answer hid.
expect(celdaDelClic({ points: [{ customdata: ['B5', '40-49'], z: 90 }] })).toEqual({ birads: 'B5', grupo_edad: '40-49' });
expect(celdaDelClic({ points: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
expect(celdaDelClic({ points: [{ z: 1 }] })).toBeUndefined();
});
});
describe('Figuras del análisis', () => {
it('dibuja una curva con su banda por grupo publicado y la corta donde la respuesta la suprime', () => {
// Fails if a suppressed group gets a trace, the curve runs past its suppressed tail, or a line loses its group.
@@ -147,6 +181,41 @@ describe('Pestaña Análisis', () => {
fixture.detectChanges();
expect(text()).toContain('Eventos insuficientes. 12 eventos para 4 parámetros.');
});
it('el explorador pide su cuadrícula solo al abrirse, y una celda abre sus curvas en Supervivencia', () => {
// Fails if the grid loads with the tab, is asked for again without a change of scenario, or a cell keeps a stratum.
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
const req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
expect([req.request.params.get('escenario'), req.request.params.get('estimador')]).toEqual(['diagnostico', 'cif']);
req.flush(subgrupos()); fixture.detectChanges();
fixture.componentInstance.elegirVista('diagnostico'); fixture.detectChanges();
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B5', '50-59'], z: 92 }] }); fixture.detectChanges();
const curvas = http.expectOne(r => r.url === '/cama/analisis/resultados');
expect(['estrato', 'birads', 'grupo_edad'].map(k => curvas.request.params.get(k))).toEqual(['ninguno', 'B5', '50-59']);
curvas.flush(resultados()); fixture.detectChanges();
expect(fixture.componentInstance.vista()).toBe('supervivencia');
expect(text()).toContain('BI-RADS 5, 50-59 años');
});
it('el diagnóstico muestra el estado de la cohorte, la validación y lo bloqueado', () => {
// Fails if the cohort's status loses a figure, or a hidden total is shown as a number.
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados()); fixture.detectChanges();
const diagnostico = fixture.nativeElement.querySelector('#analisis-diagnostico') as HTMLElement;
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
expect(diagnostico.querySelector('.dato .cifra')?.textContent).toBe('Oculto');
expect(diagnostico.textContent).toContain('Subtipo molecular');
});
it('las flechas mueven entre las tres partes', () => {
// Fails if the parts stop behaving as a keyboard tab list.
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados()); fixture.detectChanges();
const lista = fixture.nativeElement.querySelector('.subsecciones') as HTMLElement;
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'End' })); fixture.detectChanges();
expect(fixture.componentInstance.vista()).toBe('diagnostico');
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); fixture.detectChanges();
expect(fixture.componentInstance.vista()).toBe('supervivencia');
});
it('sin análisis publicado queda pendiente', () => {
// Fails if a 404 on the catalog is shown as an error instead of a feature not yet published.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
@@ -8,8 +8,8 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSelectModule } from '@angular/material/select';
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { curvasFigura, forestFigura, mesesDe } from './indicadores-analisis-figuras';
import { AnalisisCatalogo, AnalisisPedido, AnalisisResultados, AnalisisService } from './indicadores-analisis.service';
import { curvasFigura, forestFigura, mesesDe, subgruposFigura } from './indicadores-analisis-figuras';
import { AnalisisCatalogo, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos } from './indicadores-analisis.service';
import { httpMessage } from './indicadores-http';
import { Dominio, Tema } from './indicadores.models';
@@ -17,6 +17,19 @@ type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estad
export const formatoP = (p: number | null) => p === null ? '—' : p < .001 ? '< 0.001' : p.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
const DIMENSIONES = ['birads', 'grupo_edad'];
export type VistaAnalisis = 'supervivencia' | 'subgrupos' | 'diagnostico';
export const VISTAS: readonly { id: VistaAnalisis; etiqueta: string }[] = [
{ id: 'supervivencia', etiqueta: 'Supervivencia' },
{ id: 'subgrupos', etiqueta: 'Explorador de subgrupos' },
{ id: 'diagnostico', etiqueta: 'Diagnóstico de la cohorte' },
];
/** The cell of the subgroup grid: its BI-RADS and age group, from the coloured layer only (grey cells are suppressed). */
export function celdaDelClic(evento: unknown): { birads: string; grupo_edad: string } | undefined {
const punto = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
const c = punto?.customdata;
return Array.isArray(c) && typeof c[0] === 'string' && typeof c[1] === 'string' && typeof punto?.z === 'number' ? { birads: c[0], grupo_edad: c[1] } : undefined;
}
/** The group of the clicked curve, from the line's `meta`; bands and empty clicks give nothing. */
export function grupoDelClic(evento: unknown): string | undefined {
@@ -35,9 +48,10 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
return { ...pedido, filtros, estrato: libre?.clave ?? 'ninguno' };
}
// Exploratory outcomes of the BI-RADS 4+ cohort: cumulative incidence by a pre-specified stratum, the tests that
// compare the groups, hazard ratios when there are enough events, and the checks behind them. Nothing is requested
// until the tab is first opened.
// Exploratory outcomes of the BI-RADS 4+ cohort, in three parts under one set of controls: survival (cumulative
// incidence by a pre-specified stratum and the tests that compare the groups), a subgroup explorer (the BI-RADS by
// age grid and the hazard ratios) and the cohort's diagnostics (its statistical status and the checks behind every
// figure). Nothing is requested until the tab is first opened, and the grid only once its part is.
@Component({
selector: 'app-indicadores-analisis',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
@@ -59,101 +73,148 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
<mat-button-toggle-group aria-labelledby="analisis-estimador" hideSingleSelectionIndicator [value]="pedido()!.estimador" (change)="cambiar({ estimador: $event.value })">
@for (e of c.estimadores; track e.clave) { <mat-button-toggle [value]="e.clave" [attr.title]="e.nota">{{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }}</mat-button-toggle> }
</mat-button-toggle-group>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Estratificar por</mat-label>
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
@for (e of c.estratos; track e.clave) {
<mat-option [value]="e.clave" [disabled]="!e.disponible">{{ e.etiqueta }}@if (!e.disponible) { <span class="motivo"> · no disponible</span> }</mat-option>
}
</mat-select>
</mat-form-field>
@for (f of c.filtros; track f.clave) {
@if (vista() !== 'subgrupos') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ f.etiqueta }}</mat-label>
<mat-select [value]="pedido()!.filtros[f.clave] ?? ''" (selectionChange)="filtrar(f.clave, $event.value)">
<mat-option value="">Todos</mat-option>
@for (o of f.opciones; track o.codigo) { <mat-option [value]="o.codigo">{{ o.etiqueta }}</mat-option> }
<mat-label>Estratificar por</mat-label>
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
@for (e of c.estratos; track e.clave) {
<mat-option [value]="e.clave" [disabled]="!e.disponible">{{ e.etiqueta }}@if (!e.disponible) { <span class="motivo"> · no disponible</span> }</mat-option>
}
</mat-select>
</mat-form-field>
@for (f of c.filtros; track f.clave) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{ f.etiqueta }}</mat-label>
<mat-select [value]="pedido()!.filtros[f.clave] ?? ''" (selectionChange)="filtrar(f.clave, $event.value)">
<mat-option value="">Todos</mat-option>
@for (o of f.opciones; track o.codigo) { <mat-option [value]="o.codigo">{{ o.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
}
@if (hayFiltros()) { <button type="button" mat-stroked-button (click)="limpiar()">Quitar filtros</button> }
}
@if (hayFiltros()) { <button type="button" mat-stroked-button (click)="limpiar()">Quitar filtros</button> }
</div>
@if (escenario(); as e) {
<p class="contexto"><strong>{{ e.poblacion }}.</strong> Origen: {{ e.origen }}. Evento: {{ e.evento }}.
@for (b of bloqueadosEstrato(); track b.clave) { <br><span class="motivo">{{ b.etiqueta }}: {{ b.motivo }}</span> }</p>
<p class="contexto"><strong>{{ e.poblacion }}.</strong> Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.</p>
}
@switch (resultados().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el análisis" /> }
@case ('error') { <div role="alert" class="panel"><p>{{ $any(resultados()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div> }
}
@if (res(); as r) {
<p class="resumen" role="status">
@if (r.poblacion.n !== null) { {{ miles(r.poblacion.n) }} pacientes · {{ miles(r.poblacion.eventos ?? 0) }} eventos · }
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido · }
@if (r.poblacion.seguimiento_mediano_dias) { seguimiento mediano {{ meses(r.poblacion.seguimiento_mediano_dias) }} meses · }
horizonte {{ meses(r.horizonte_dias) }} meses · descriptivo, no causal
</p>
<div class="subsecciones" role="tablist" aria-label="Partes del análisis" (keydown)="teclaVista($event)">
@for (v of VISTAS; track v.id) {
<button type="button" role="tab" [id]="'analisis-tab-' + v.id" [attr.aria-controls]="'analisis-' + v.id" [attr.aria-selected]="vista() === v.id"
[tabIndex]="vista() === v.id ? 0 : -1" (click)="elegirVista(v.id)">{{ v.etiqueta }}</button>
}
</div>
<!-- Survival: the curves of each group, how they compare, and who is still at risk. -->
<section id="analisis-supervivencia" role="tabpanel" aria-labelledby="analisis-tab-supervivencia" [hidden]="vista() !== 'supervivencia'">
@switch (resultados().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el análisis" /> }
@case ('error') { <div role="alert" class="panel"><p>{{ $any(resultados()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div> }
}
@if (res(); as r) {
<p class="resumen" role="status">
@if (r.poblacion.n !== null) { {{ miles(r.poblacion.n) }} pacientes · {{ miles(r.poblacion.eventos ?? 0) }} eventos }
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido }
@if (hayFiltros()) { · {{ textoFiltros() }} }
</p>
<div class="paneles">
<article class="panel ancho">
<h2>Incidencia acumulada a {{ meses(r.horizonte_dias) }} meses</h2>
<p class="nota">{{ estimadorElegido()?.etiqueta }}. @if (puedeElegir()) { Haga clic en una curva para analizar solo ese grupo. }</p>
@if (figuraCurvas().data.length) {
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
[label]="'Incidencia acumulada por ' + (estratoElegido()?.etiqueta ?? 'grupo')" />
<table class="riesgo">
<caption>Pacientes en riesgo</caption>
<thead><tr><th scope="col">Grupo</th>@for (d of r.tabla_riesgo.cortes_dias; track d) { <th scope="col">Mes {{ meses(d) }}</th> }</tr></thead>
<tbody>
@for (f of r.tabla_riesgo.filas; track f.grupo) {
<tr><th scope="row">{{ etiqueta(f.grupo) }}</th>@for (v of f.cortes; track $index) { <td>{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}</td> }</tr>
}
</tbody>
</table>
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con estos filtros.</p> }
@if (suprimidos().length) { <p class="nota">Grupos suprimidos: {{ textoSuprimidos() }}.</p> }
<p class="nota">La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.</p>
@for (a of r.avisos.slice(2); track a) { <p class="nota">{{ a }}</p> }
</article>
<article class="panel ancho">
<h2>Comparación entre grupos</h2>
<div class="comparacion">
<div>
@if (r.pruebas.logrank; as lr) {
<p>Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.</p>
@if (r.pruebas.pares.length > 1) {
<table><caption>Comparaciones por pares (corrección de Holm)</caption>
<thead><tr><th scope="col">Grupos</th><th scope="col">p</th><th scope="col">p ajustada</th></tr></thead>
<tbody>@for (par of r.pruebas.pares; track par.a + par.b) { <tr><td>{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}</td><td>{{ formatoP(par.p) }}</td><td>{{ formatoP(par.p_holm) }}</td></tr> }</tbody>
</table>
}
} @else { <p role="status">Se necesitan al menos dos grupos publicados para comparar.</p> }
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
</div>
@if (r.pruebas.rmst.length) {
<table><caption>Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)</caption>
<thead><tr><th scope="col">Grupo</th><th scope="col">Días</th><th scope="col">Diferencia (IC 95 %)</th></tr></thead>
<tbody>@for (f of r.pruebas.rmst; track f.grupo) {
<tr><td>{{ etiqueta(f.grupo) }}</td><td>{{ f.rmst.toLocaleString('es-MX') }}</td>
<td>{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}</td></tr>
}</tbody>
</table>
}
</div>
</article>
</div>
}
</section>
<!-- Subgroups: every BI-RADS and age-group cell at once, and the hazard ratios of the chosen stratum. -->
<section id="analisis-subgrupos" role="tabpanel" aria-labelledby="analisis-tab-subgrupos" [hidden]="vista() !== 'subgrupos'">
<div class="paneles">
<article class="panel ancho">
<h2>Incidencia acumulada a {{ meses(r.horizonte_dias) }} meses</h2>
<p class="nota">{{ estimadorElegido()?.etiqueta }}. @if (puedeElegir()) { Haga clic en una curva para analizar solo ese grupo. }</p>
@if (figuraCurvas().data.length) {
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
[label]="'Incidencia acumulada por ' + (estratoElegido()?.etiqueta ?? 'grupo')" />
<table class="riesgo">
<caption>Pacientes en riesgo</caption>
<thead><tr><th scope="col">Grupo</th>@for (d of r.tabla_riesgo.cortes_dias; track d) { <th scope="col">Mes {{ meses(d) }}</th> }</tr></thead>
<tbody>
@for (f of r.tabla_riesgo.filas; track f.grupo) {
<tr><th scope="row">{{ etiqueta(f.grupo) }}</th>@for (v of f.cortes; track $index) { <td>{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}</td> }</tr>
}
</tbody>
</table>
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con estos filtros.</p> }
@if (suprimidos().length) {
<p class="nota">Grupos suprimidos: {{ textoSuprimidos() }}.</p>
<h2>Incidencia a {{ meses(c.horizonte_dias) }} meses por BI-RADS y grupo de edad</h2>
@switch (subgrupos().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los subgrupos" /> }
@case ('error') { <div role="alert"><p>{{ $any(subgrupos()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarSubgrupos(true)">Reintentar consulta</button></div> }
}
<p class="nota">La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.</p>
@for (a of r.avisos.slice(2); track a) { <p class="nota">{{ a }}</p> }
</article>
<article class="panel">
<h2>Comparación entre grupos</h2>
@if (r.pruebas.logrank; as lr) {
<p>Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.</p>
@if (r.pruebas.pares.length > 1) {
<table><caption>Comparaciones por pares (corrección de Holm)</caption>
<thead><tr><th scope="col">Grupos</th><th scope="col">p</th><th scope="col">p ajustada</th></tr></thead>
<tbody>@for (par of r.pruebas.pares; track par.a + par.b) { <tr><td>{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}</td><td>{{ formatoP(par.p) }}</td><td>{{ formatoP(par.p_holm) }}</td></tr> }</tbody>
</table>
}
} @else { <p role="status">Se necesitan al menos dos grupos publicados para comparar.</p> }
@if (r.pruebas.rmst.length) {
<table><caption>Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)</caption>
<thead><tr><th scope="col">Grupo</th><th scope="col">Días</th><th scope="col">Diferencia (IC 95 %)</th></tr></thead>
<tbody>@for (f of r.pruebas.rmst; track f.grupo) {
<tr><td>{{ etiqueta(f.grupo) }}</td><td>{{ f.rmst.toLocaleString('es-MX') }}</td>
<td>{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}</td></tr>
}</tbody>
</table>
}
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
</article>
<article class="panel">
<h2>Razón de riesgos (Cox)</h2>
@if (r.efectos.estado === 'listo') {
<app-plotly-chart [style.--plot-height]="figuraForest().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraForest()" label="Razones de riesgos con intervalo al 95 %" />
<p class="nota">Modelo de Cox de una variable, contra {{ r.efectos.etiqueta_referencia }}. Un cuadro vacío marca riesgos no proporcionales. Describe diferencias; no estima un efecto causal.</p>
} @else {
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
@if (sub(); as s) {
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus curvas en Supervivencia.</p>
<app-plotly-chart [style.--plot-height]="figuraSubgrupos().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraSubgrupos()" (plotClick)="clicCelda($event)"
label="Incidencia acumulada por categoría BI-RADS y grupo de edad" />
<p class="nota">Cada celda dice el porcentaje, los eventos y las pacientes. Una celda gris tiene menos de {{ s.umbral_supresion }} pacientes o eventos. «A N meses» marca una celda cuya curva termina antes del horizonte.</p>
}
</article>
<article class="panel ancho">
<h2>Razón de riesgos (Cox)</h2>
@if (res(); as r) {
@if (r.efectos.estado === 'listo') {
<app-plotly-chart [style.--plot-height]="figuraForest().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraForest()" label="Razones de riesgos con intervalo al 95 %" />
<p class="nota">Modelo de Cox de una variable ({{ estratoElegido()?.etiqueta?.toLowerCase() }}), contra {{ r.efectos.etiqueta_referencia }}. Un cuadro vacío marca riesgos no proporcionales. Describe diferencias; no estima un efecto causal.</p>
} @else {
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
}
<p class="nota">El estrato y los filtros se eligen en Supervivencia.</p>
}
</article>
</div>
</section>
<!-- Diagnostics: the statistical status of the cohort and the checks behind every figure. -->
<section id="analisis-diagnostico" role="tabpanel" aria-labelledby="analisis-tab-diagnostico" [hidden]="vista() !== 'diagnostico'">
@if (res(); as r) {
<div class="estado-cohorte">
<div class="dato"><span class="cifra">{{ r.poblacion.n === null ? 'Oculto' : miles(r.poblacion.n) }}</span><span>pacientes en la población</span></div>
<div class="dato"><span class="cifra">{{ r.poblacion.eventos === null ? 'Oculto' : miles(r.poblacion.eventos) }}</span><span>eventos en {{ meses(r.horizonte_dias) }} meses</span></div>
<div class="dato"><span class="cifra">{{ r.poblacion.seguimiento_mediano_dias === null ? 'Sin dato' : meses(r.poblacion.seguimiento_mediano_dias) + ' meses' }}</span><span>seguimiento mediano</span></div>
<div class="dato"><span class="cifra">{{ eventosPorParametro() ?? '—' }}</span><span>eventos por parámetro (mínimo 10)</span></div>
<div class="dato"><span class="cifra">{{ r.umbral_supresion }}</span><span>umbral de supresión</span></div>
</div>
@if (r.poblacion.totales_ocultos) { <p class="nota">Los totales se ocultan porque un grupo está suprimido y se podría deducir.</p> }
<article class="panel">
<h2>Reporte de validación</h2>
<p class="nota">De {{ escenario()?.etiqueta?.toLowerCase() }}, {{ estratoElegido()?.etiqueta?.toLowerCase() }}@if (hayFiltros()) {, {{ textoFiltros() }}}.</p>
<table class="validacion">
<thead><tr><th scope="col">Chequeo</th><th scope="col">Alcance</th><th scope="col">Valor</th><th scope="col">Umbral</th><th scope="col">Resultado</th><th scope="col">Nota</th></tr></thead>
<tbody>@for (v of r.validacion; track $index) {
@@ -168,17 +229,15 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
</table>
<p class="nota">Versión del modelo: {{ r.validacion[0]?.version_modelo }}.</p>
</article>
</div>
}
@if (c.bloqueados.length) {
}
<section class="pendientes" aria-labelledby="analisis-pendientes">
<h2 id="analisis-pendientes">Análisis que aún no se pueden calcular</h2>
<h2 id="analisis-pendientes">Lo que la cohorte aún no permite</h2>
<div class="tarjetas">
@for (b of c.bloqueados; track b.clave) { <article class="bloqueado"><h3>{{ b.titulo }}</h3><p>{{ b.motivo }}</p></article> }
@for (e of bloqueadosEstrato(); track e.clave) { <article class="bloqueado"><h3>Estrato: {{ e.etiqueta }}</h3><p>{{ e.motivo }}</p></article> }
</div>
</section>
}
</section>
}
`,
styles: `
@@ -188,7 +247,7 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
.controles mat-form-field { min-width: 12rem; }
.controles mat-form-field:first-child { min-width: 20rem; }
.contexto, .resumen { margin: var(--issste-space-3) 0 0; font: var(--mat-sys-body-medium); color: var(--issste-text); }
.resumen { margin-bottom: var(--issste-space-6); color: var(--issste-text-secondary); }
.resumen { margin: 0 0 var(--issste-space-4); color: var(--issste-text-secondary); }
.motivo, .nota, .etiqueta { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@@ -209,6 +268,17 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
.tarjetas { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
.bloqueado { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); background: transparent; }
.bloqueado h3 { margin: 0; font: var(--mat-sys-title-small); }
.subsecciones { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin: var(--issste-space-4) 0; border-bottom: 1px solid var(--issste-border); }
.subsecciones button { padding: var(--issste-space-2) var(--issste-space-4); border: 0; border-bottom: 3px solid transparent; background: none; color: var(--issste-text-secondary);
font: var(--mat-sys-title-small); cursor: pointer; min-height: 44px; }
.subsecciones button[aria-selected='true'] { color: var(--issste-text); border-bottom-color: var(--issste-accent); }
.subsecciones button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
.comparacion { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 960px) { .comparacion { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.estado-cohorte { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: var(--issste-space-4); margin-bottom: var(--issste-space-4); }
.dato { display: flex; flex-direction: column; gap: var(--issste-space-1); padding: var(--issste-space-4); background: var(--issste-surface);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.dato .cifra { color: var(--issste-text); font-size: 1.5rem; font-weight: 500; line-height: 1.2; }
@media (max-width: 600px) { .controles { padding: var(--issste-space-3); } .controles mat-form-field, .controles mat-form-field:first-child { min-width: 100%; } }
`,
})
@@ -239,6 +309,22 @@ export class IndicadoresAnalisis {
readonly textoSuprimidos = computed(() => this.suprimidos().map(g => `${g.etiqueta} (${(g.motivo ?? 'suprimido').toLowerCase()})`).join('; '));
readonly figuraCurvas = computed(() => { const r = this.res(); return r ? curvasFigura(r, this.tema()) : { data: [], layout: {} }; });
readonly figuraForest = computed(() => { const r = this.res(); return r ? forestFigura(r, this.tema()) : { data: [], layout: {} }; });
readonly VISTAS = VISTAS;
readonly vista = signal<VistaAnalisis>('supervivencia');
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
readonly sub = computed(() => { const s = this.subgrupos(); return s.estado === 'listo' ? s.datos : undefined; });
readonly figuraSubgrupos = computed(() => { const s = this.sub(); return s ? subgruposFigura(s, this.tema()) : { data: [], layout: {} }; });
readonly eventosPorParametro = computed(() => {
const fila = this.res()?.validacion.find(v => v.chequeo === 'Eventos por parámetro');
return fila?.estadistico == null ? null : fila.estadistico.toLocaleString('es-MX');
});
readonly textoFiltros = computed(() => {
const cat = this.cat(), filtros = this.pedido()?.filtros ?? {};
return Object.entries(filtros).filter(([, v]) => v)
.map(([k, v]) => cat?.filtros.find(f => f.clave === k)?.opciones.find(o => o.codigo === v)?.etiqueta ?? v).join(', ');
});
private readonly pedidosSubgrupos = new Subject<{ escenario: string; estimador: string }>();
private subgruposDe?: string;
constructor() {
const destroy = inject(DestroyRef);
@@ -257,6 +343,15 @@ export class IndicadoresAnalisis {
map((datos): Carga<AnalisisResultados> => ({ estado: 'listo', datos })),
catchError(error => of<Carga<AnalisisResultados>>({ estado: 'error', mensaje: httpMessage(error) })),
startWith<Carga<AnalisisResultados>>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => this.resultados.set(carga));
this.pedidosSubgrupos.pipe(switchMap(({ escenario, estimador }) => this.service.subgrupos(this.dominio(), escenario, estimador).pipe(
map((datos): Carga<AnalisisSubgrupos> => ({ estado: 'listo', datos })),
catchError(error => of<Carga<AnalisisSubgrupos>>({ estado: 'error', mensaje: httpMessage(error) })),
startWith<Carga<AnalisisSubgrupos>>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => this.subgrupos.set(carga));
// The grid depends only on the scenario and the estimator; it is asked for when its part is open.
effect(() => {
const vista = this.vista(), pedido = this.pedido();
if (vista === 'subgrupos' && pedido) untracked(() => this.cargarSubgrupos());
});
effect(() => {
if (!this.active() || this.abierto) return;
untracked(() => { this.abierto = true; this.catalogos.next(); });
@@ -289,6 +384,30 @@ export class IndicadoresAnalisis {
const siguiente = pedidoAlElegir(pedido, grupo, cat);
if (siguiente !== pedido) this.cambiar(siguiente);
}
elegirVista(vista: VistaAnalisis) { this.vista.set(vista); }
teclaVista(event: KeyboardEvent) {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
event.preventDefault();
const i = VISTAS.findIndex(v => v.id === this.vista());
const j = event.key === 'Home' ? 0 : event.key === 'End' ? VISTAS.length - 1 : (i + (event.key === 'ArrowRight' ? 1 : -1) + VISTAS.length) % VISTAS.length;
this.vista.set(VISTAS[j].id);
(event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>('[role="tab"]')[j]?.focus();
}
cargarSubgrupos(forzar = false) {
const p = this.pedido();
if (!p) return;
const clave = p.escenario + '|' + p.estimador;
if (!forzar && clave === this.subgruposDe) return;
this.subgruposDe = clave;
this.pedidosSubgrupos.next({ escenario: p.escenario, estimador: p.estimador });
}
// A cell opens its curves: both dimensions filtered, nothing left to stratify.
clicCelda(evento: unknown) {
const celda = celdaDelClic(evento);
if (!celda) return;
this.cambiar({ filtros: { birads: celda.birads, grupo_edad: celda.grupo_edad }, estrato: 'ninguno' });
this.vista.set('supervivencia');
}
etiqueta(grupo: string) { return this.res()?.grupos.find(g => g.grupo === grupo)?.etiqueta ?? grupo; }
reintentar() { const p = this.pedido(); if (p) this.pedidos.next(p); }
reintentarCatalogo() { this.catalogos.next(); }