From 05a55a673e88adb967fc2daed837005c94f1cd11 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Thu, 12 Nov 2026 13:49:20 -0600 Subject: [PATCH] =?UTF-8?q?feat(cama):=20=C2=ABAn=C3=A1lisis=C2=BB=20in=20?= =?UTF-8?q?three=20parts:=20survival,=20subgroup=20explorer=20and=20cohort?= =?UTF-8?q?=20diagnostics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 //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. --- .../indicadores-analisis-figuras.ts | 46 ++- .../indicadores-analisis.service.ts | 28 ++ .../indicadores/indicadores-analisis.spec.ts | 77 ++++- .../indicadores/indicadores-analisis.ts | 303 ++++++++++++------ 4 files changed, 357 insertions(+), 97 deletions(-) diff --git a/src/app/features/indicadores/indicadores-analisis-figuras.ts b/src/app/features/indicadores/indicadores-analisis-figuras.ts index 3ad060a..ccd3c42 100644 --- a/src/app/features/indicadores/indicadores-analisis-figuras.ts +++ b/src/app/features/indicadores/indicadores-analisis-figuras.ts @@ -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, '&').replace(//g, '>'); @@ -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 'Suprimido'; + const meses = Math.round(x.t_dias! / DIAS_POR_MES); + return `${pct(x.valor!)} %
${miles(x.eventos!)} de ${miles(x.n!)}${meses < horizonte ? `
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)}
${pct(x.valor!)} % (IC 95 %: ${pct(x.ic_bajo!)} a ${pct(x.ic_alto!)})
${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}', + 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); diff --git a/src/app/features/indicadores/indicadores-analisis.service.ts b/src/app/features/indicadores/indicadores-analisis.service.ts index 1f3ad53..e9133c7 100644 --- a/src/app/features/indicadores/indicadores-analisis.service.ts +++ b/src/app/features/indicadores/indicadores-analisis.service.ts @@ -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 => !!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(`/${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(`/${requireDominio(dominio)}/analisis/subgrupos`, { params }).pipe(map(analisisSubgrupos)); + } } diff --git a/src/app/features/indicadores/indicadores-analisis.spec.ts b/src/app/features/indicadores/indicadores-analisis.spec.ts index 567e5ef..a3fde72 100644 --- a/src/app/features/indicadores/indicadores-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-analisis.spec.ts @@ -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(); diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts index 39d25d5..0703e1c 100644 --- a/src/app/features/indicadores/indicadores-analisis.ts +++ b/src/app/features/indicadores/indicadores-analisis.ts @@ -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 = { 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: @for (e of c.estimadores; track e.clave) { {{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }} } - - Estratificar por - - @for (e of c.estratos; track e.clave) { - {{ e.etiqueta }}@if (!e.disponible) { · no disponible } - } - - - @for (f of c.filtros; track f.clave) { + @if (vista() !== 'subgrupos') { - {{ f.etiqueta }} - - Todos - @for (o of f.opciones; track o.codigo) { {{ o.etiqueta }} } + Estratificar por + + @for (e of c.estratos; track e.clave) { + {{ e.etiqueta }}@if (!e.disponible) { · no disponible } + } + @for (f of c.filtros; track f.clave) { + + {{ f.etiqueta }} + + Todos + @for (o of f.opciones; track o.codigo) { {{ o.etiqueta }} } + + + } + @if (hayFiltros()) { } } - @if (hayFiltros()) { } @if (escenario(); as e) { -

{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. - @for (b of bloqueadosEstrato(); track b.clave) {
{{ b.etiqueta }}: {{ b.motivo }} }

+

{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.

} - @switch (resultados().estado) { - @case ('cargando') { } - @case ('error') { } - } - @if (res(); as r) { -

- @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 -

+
+ @for (v of VISTAS; track v.id) { + + } +
+ + +
+ @switch (resultados().estado) { + @case ('cargando') { } + @case ('error') { } + } + @if (res(); as r) { +

+ @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() }} } +

+
+
+

Incidencia acumulada a {{ meses(r.horizonte_dias) }} meses

+

{{ estimadorElegido()?.etiqueta }}. @if (puedeElegir()) { Haga clic en una curva para analizar solo ese grupo. }

+ @if (figuraCurvas().data.length) { + + + + @for (d of r.tabla_riesgo.cortes_dias; track d) { } + + @for (f of r.tabla_riesgo.filas; track f.grupo) { + @for (v of f.cortes; track $index) { } + } + +
Pacientes en riesgo
GrupoMes {{ meses(d) }}
{{ etiqueta(f.grupo) }}{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}
+ } @else {

Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con estos filtros.

} + @if (suprimidos().length) {

Grupos suprimidos: {{ textoSuprimidos() }}.

} +

La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.

+ @for (a of r.avisos.slice(2); track a) {

{{ a }}

} +
+ +
+

Comparación entre grupos

+
+
+ @if (r.pruebas.logrank; as lr) { +

Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.

+ @if (r.pruebas.pares.length > 1) { + + + @for (par of r.pruebas.pares; track par.a + par.b) { } +
Comparaciones por pares (corrección de Holm)
Grupospp ajustada
{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}{{ formatoP(par.p) }}{{ formatoP(par.p_holm) }}
+ } + } @else {

Se necesitan al menos dos grupos publicados para comparar.

} + @if (r.pruebas.nota) {

{{ r.pruebas.nota }}

} +
+ @if (r.pruebas.rmst.length) { + + + @for (f of r.pruebas.rmst; track f.grupo) { + + + } +
Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)
GrupoDíasDiferencia (IC 95 %)
{{ etiqueta(f.grupo) }}{{ f.rmst.toLocaleString('es-MX') }}{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}
+ } +
+
+
+ } +
+ + +
-

Incidencia acumulada a {{ meses(r.horizonte_dias) }} meses

-

{{ estimadorElegido()?.etiqueta }}. @if (puedeElegir()) { Haga clic en una curva para analizar solo ese grupo. }

- @if (figuraCurvas().data.length) { - - - - @for (d of r.tabla_riesgo.cortes_dias; track d) { } - - @for (f of r.tabla_riesgo.filas; track f.grupo) { - @for (v of f.cortes; track $index) { } - } - -
Pacientes en riesgo
GrupoMes {{ meses(d) }}
{{ etiqueta(f.grupo) }}{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}
- } @else {

Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con estos filtros.

} - @if (suprimidos().length) { -

Grupos suprimidos: {{ textoSuprimidos() }}.

+

Incidencia a {{ meses(c.horizonte_dias) }} meses por BI-RADS y grupo de edad

+ @switch (subgrupos().estado) { + @case ('cargando') { } + @case ('error') {

{{ $any(subgrupos()).mensaje }}

} } -

La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.

- @for (a of r.avisos.slice(2); track a) {

{{ a }}

} -
- -
-

Comparación entre grupos

- @if (r.pruebas.logrank; as lr) { -

Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.

- @if (r.pruebas.pares.length > 1) { - - - @for (par of r.pruebas.pares; track par.a + par.b) { } -
Comparaciones por pares (corrección de Holm)
Grupospp ajustada
{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}{{ formatoP(par.p) }}{{ formatoP(par.p_holm) }}
- } - } @else {

Se necesitan al menos dos grupos publicados para comparar.

} - @if (r.pruebas.rmst.length) { - - - @for (f of r.pruebas.rmst; track f.grupo) { - - - } -
Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)
GrupoDíasDiferencia (IC 95 %)
{{ etiqueta(f.grupo) }}{{ f.rmst.toLocaleString('es-MX') }}{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}
- } - @if (r.pruebas.nota) {

{{ r.pruebas.nota }}

} -
- -
-

Razón de riesgos (Cox)

- @if (r.efectos.estado === 'listo') { - -

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.

- } @else { -

- {{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}

+ @if (sub(); as s) { +

{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus curvas en Supervivencia.

+ +

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.

}
-
+

Razón de riesgos (Cox)

+ @if (res(); as r) { + @if (r.efectos.estado === 'listo') { + +

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.

+ } @else { +

+ {{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}

+ } +

El estrato y los filtros se eligen en Supervivencia.

+ } +
+
+
+ + +
+ @if (res(); as r) { +
+
{{ r.poblacion.n === null ? 'Oculto' : miles(r.poblacion.n) }}pacientes en la población
+
{{ r.poblacion.eventos === null ? 'Oculto' : miles(r.poblacion.eventos) }}eventos en {{ meses(r.horizonte_dias) }} meses
+
{{ r.poblacion.seguimiento_mediano_dias === null ? 'Sin dato' : meses(r.poblacion.seguimiento_mediano_dias) + ' meses' }}seguimiento mediano
+
{{ eventosPorParametro() ?? '—' }}eventos por parámetro (mínimo 10)
+
{{ r.umbral_supresion }}umbral de supresión
+
+ @if (r.poblacion.totales_ocultos) {

Los totales se ocultan porque un grupo está suprimido y se podría deducir.

} +

Reporte de validación

+

De {{ escenario()?.etiqueta?.toLowerCase() }}, {{ estratoElegido()?.etiqueta?.toLowerCase() }}@if (hayFiltros()) {, {{ textoFiltros() }}}.

@for (v of r.validacion; track $index) { @@ -168,17 +229,15 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
ChequeoAlcanceValorUmbralResultadoNota

Versión del modelo: {{ r.validacion[0]?.version_modelo }}.

- - } - - @if (c.bloqueados.length) { + }
-

Análisis que aún no se pueden calcular

+

Lo que la cohorte aún no permite

@for (b of c.bloqueados; track b.clave) {

{{ b.titulo }}

{{ b.motivo }}

} + @for (e of bloqueadosEstrato(); track e.clave) {

Estrato: {{ e.etiqueta }}

{{ e.motivo }}

}
- } +
} `, 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('supervivencia'); + readonly subgrupos = signal>({ 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 => ({ estado: 'listo', datos })), catchError(error => of>({ estado: 'error', mensaje: httpMessage(error) })), startWith>({ 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 => ({ estado: 'listo', datos })), + catchError(error => of>({ estado: 'error', mensaje: httpMessage(error) })), + startWith>({ 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('[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(); }