From d16804d41675bee17ec8ae15ce2cc4a1dc4a7853 Mon Sep 17 00:00:00 2001
From: rockdrigo
Date: Thu, 12 Nov 2026 14:04:58 -0600
Subject: [PATCH] =?UTF-8?q?feat(cama):=20=C2=ABAn=C3=A1lisis=C2=BB=20by=20?=
=?UTF-8?q?stage:=20development,=20recurrence=20and=20survival,=20each=20w?=
=?UTF-8?q?ith=20its=20two=20NOM=20variables?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The curves part held a single question. It now answers one per stage of the
disease: who reaches a cancer (development), who recurs after an invasive
cancer (recurrence) and who is alive two years after it (survival). Each
stage is stratified, filtered, tested (log-rank, Cox) and validated by its
own two variables.
How:
- The catalog now publishes stages (question, scenarios, estimators,
measure, two variables, the NOM variables it needs with their status) and
variables (NOM numeral, recorded or assumed, source, options). The
answers add their stage, measure and `supuestos`; the subgroup grid is
generic (fila, columna, dimension_filas, dimension_columnas).
- A stage selector leads the controls; choosing a stage starts from its
first scenario and variable and keeps the estimator if the stage admits
it (pedidoDeEtapa). Scenario and estimator choices show only when the
stage has more than one. Strata and filters are the stage's variables,
an assumed one marked «supuesto»; a curve click and a grid cell filter by
them (pedidoAlElegir, celdaDelClic).
- The survival stage is drawn as survival from 100 % (nombreMedida); the
others as cumulative incidence. What rests on assumed data is announced
above the curves and in the grid.
- Diagnóstico lists the NOM variables of the stage and whether the schema
records them; the validation table adds the source of each variable used.
- The curves part is now «Curvas (Kaplan-Meier)».
Implications:
- Recurrence and survival need data the schema does not record yet (stage,
receptors, recurrence date, vital status); the mock assumes them and the
page says so wherever they are used.
---
.../indicadores-analisis-figuras.ts | 23 ++-
.../indicadores-analisis.service.ts | 40 +++--
.../indicadores/indicadores-analisis.spec.ts | 78 ++++++---
.../indicadores/indicadores-analisis.ts | 154 ++++++++++++------
4 files changed, 204 insertions(+), 91 deletions(-)
diff --git a/src/app/features/indicadores/indicadores-analisis-figuras.ts b/src/app/features/indicadores/indicadores-analisis-figuras.ts
index ccd3c42..9147a54 100644
--- a/src/app/features/indicadores/indicadores-analisis-figuras.ts
+++ b/src/app/features/indicadores/indicadores-analisis-figuras.ts
@@ -11,20 +11,24 @@ function transparente(hex: string, alfa: number) {
return m ? `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alfa})` : hex;
}
+// What the stage measures: the cumulative incidence of its event, or the survival (alive at t).
+export const nombreMedida = (medida: 'incidencia' | 'supervivencia') => medida === 'supervivencia' ? 'Supervivencia' : 'Incidencia acumulada';
+
/**
- * Cumulative incidence per published group: a step line with its 95 % band. The curve ends where the
+ * The stage's measure per published group (cumulative incidence, or survival in the survival stage): a step line with its 95 % band. The curve ends where the
* answer suppressed it (fewer at risk than the threshold); each line carries its group in `meta`, so a click
* can only change the filters, never read rows.
*/
export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), meses = r.horizonte_dias / DIAS_POR_MES;
const data: Record[] = [];
- let maximo = 1;
+ const supervivencia = r.medida === 'supervivencia';
+ let maximo = 1, minimo = 100;
for (const g of r.grupos.filter(x => !x.suprimido)) {
const puntos = r.curvas.filter(c => c.grupo === g.grupo && c.suprimido === 0);
if (!puntos.length) continue;
const x = puntos.map(c => +(c.t / DIAS_POR_MES).toFixed(2));
- maximo = Math.max(maximo, ...puntos.map(c => c.ic_alto!));
+ maximo = Math.max(maximo, ...puntos.map(c => c.ic_alto!)); minimo = Math.min(minimo, ...puntos.map(c => c.ic_bajo!));
const comun = { type: 'scatter', mode: 'lines', x, legendgroup: g.grupo, line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false };
data.push({ ...comun, y: puntos.map(c => c.ic_bajo) });
data.push({ ...comun, y: puntos.map(c => c.ic_alto), fill: 'tonexty', fillcolor: transparente(g.color, tema === 'oscuro' ? .28 : .16) });
@@ -42,7 +46,8 @@ export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
margin: { t: 16, l: 64, r: 16, b: 96 }, hovermode: 'closest',
legend: { orientation: 'h', y: -0.22, itemclick: false, itemdoubleclick: false },
xaxis: { title: { text: 'Meses desde el origen' }, range: [0, meses], dtick: 6, gridcolor: p.grid, zeroline: false, fixedrange: true },
- yaxis: { title: { text: 'Incidencia acumulada (%)' }, range: [0, Math.min(100, maximo * 1.1)], gridcolor: p.grid, zeroline: false, fixedrange: true, ticksuffix: ' %' },
+ yaxis: { title: { text: nombreMedida(r.medida) + ' (%)' }, range: supervivencia ? [Math.max(0, minimo - 10), 100] : [0, Math.min(100, maximo * 1.1)],
+ gridcolor: p.grid, zeroline: false, fixedrange: true, ticksuffix: ' %' },
},
config: { displayModeBar: false },
};
@@ -78,12 +83,12 @@ 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
+ * The stage's measure at the horizon by its two variables (rows and 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 celda = (f: string, c: string) => s.celdas.find(x => x.fila === f && x.columna === 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);
@@ -105,13 +110,13 @@ export function subgruposFigura(s: AnalisisSubgrupos, tema: Tema): PlotlyFigure
{ 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 } },
+ colorbar: { title: { text: nombreMedida(s.medida) + ' (%)' }, 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 },
+ xaxis: { title: { text: escapar(s.dimension_columnas.etiqueta) }, side: 'bottom', fixedrange: true, automargin: true },
+ yaxis: { title: { text: escapar(s.dimension_filas.etiqueta) }, 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 } };
diff --git a/src/app/features/indicadores/indicadores-analisis.service.ts b/src/app/features/indicadores/indicadores-analisis.service.ts
index e9133c7..103398b 100644
--- a/src/app/features/indicadores/indicadores-analisis.service.ts
+++ b/src/app/features/indicadores/indicadores-analisis.service.ts
@@ -5,16 +5,25 @@ import { Dominio, requireDominio } from './indicadores.models';
// Exploratory outcomes of a domain's cohort: what can be asked (`/analisis`) and its aggregate answer
// (`/analisis/resultados`). The answer is curves (C9b), tests, effects (C12) and checks (C13), never patient rows.
+// The analysis goes by stages (development, recurrence, survival). Each stage has its scenarios, its estimators
+// and the two variables it is stratified and filtered by; each variable says its NOM numeral and whether the schema
+// records it or the answer assumes it.
export interface AnalisisOpcion { clave: string; etiqueta: string; }
-export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; }
+export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; etapa: string; }
export interface AnalisisEstimador extends AnalisisOpcion { nota: string; }
-export interface AnalisisEstrato extends AnalisisOpcion { disponible: boolean; motivo?: string; }
-export interface AnalisisFiltro { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
+export type EstadoVariable = 'registrado' | 'supuesto';
+export interface AnalisisVariable extends AnalisisOpcion { nom: string; estado: EstadoVariable; fuente: string; opciones: { codigo: string; etiqueta: string }[]; }
+export interface AnalisisEtapa extends AnalisisOpcion {
+ pregunta: string; escenarios: string[]; estimadores: string[]; medida: 'incidencia' | 'supervivencia';
+ estratos: [string, string]; evento_supuesto: string | null;
+ // Every variable the NOM asks for at this stage, and whether the schema has it.
+ requeridas: { variable: string; nom: string; estado: string }[];
+}
export interface AnalisisBloqueado { clave: string; titulo: string; motivo: string; }
export interface AnalisisCatalogo {
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
- escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[]; estratos: AnalisisEstrato[];
- filtros: AnalisisFiltro[]; bloqueados: AnalisisBloqueado[];
+ etapas: AnalisisEtapa[]; escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[];
+ variables: AnalisisVariable[]; bloqueados: AnalisisBloqueado[];
}
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; filtros: Record; }
@@ -28,7 +37,10 @@ export interface Efectos { estado: 'listo' | 'insuficiente' | 'no_aplica'; motiv
export interface FilaValidacion { chequeo: string; escopo: string; estadistico: number | null; p: number | null; umbral: number | null; aprobado: boolean | null; nota: string | null; version_modelo: string; sql_sha: string | null; }
export interface AnalisisResultados {
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
+ etapa: string; medida: 'incidencia' | 'supervivencia';
escenario: string; estimador: string; estrato: string; filtros: Record;
+ // What of this answer rests on data the schema does not record.
+ supuestos: string[];
poblacion: { n: number | null; eventos: number | null; totales_ocultos: boolean; seguimiento_mediano_dias: number | null };
grupos: GrupoAnalisis[]; curvas: PuntoCurva[];
tabla_riesgo: { cortes_dias: number[]; filas: { grupo: string; cortes: (number | null)[] }[] };
@@ -43,11 +55,13 @@ export interface AnalisisResultados {
// 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;
+ fila: string; columna: 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;
+ etapa: string; medida: 'incidencia' | 'supervivencia'; supuestos: string[];
+ dimension_filas: AnalisisOpcion; dimension_columnas: AnalisisOpcion;
filas: { codigo: string; etiqueta: string }[]; columnas: { codigo: string; etiqueta: string }[]; celdas: CeldaSubgrupo[];
}
@@ -69,10 +83,13 @@ const invalido = (): never => { throw new Error('Respuesta de análisis inválid
export function analisisCatalogo(v: unknown): AnalisisCatalogo {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
if (!text(v['corte']) || !num(v['horizonte_dias']) || !num(v['umbral_supresion'])
- || !lista(v['escenarios'], e => opcion(e) && record(e) && text(e['evento']) && text(e['origen']) && text(e['poblacion'])) || !(v['escenarios'] as unknown[]).length
+ || !lista(v['escenarios'], e => opcion(e) && record(e) && text(e['evento']) && text(e['origen']) && text(e['poblacion']) && text(e['etapa'])) || !(v['escenarios'] as unknown[]).length
|| !lista(v['estimadores'], e => opcion(e) && record(e) && text(e['nota'])) || !(v['estimadores'] as unknown[]).length
- || !lista(v['estratos'], e => opcion(e) && record(e) && typeof e['disponible'] === 'boolean')
- || !lista(v['filtros'], f => record(f) && text(f['clave']) && text(f['etiqueta']) && lista(f['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
+ || !lista(v['variables'], x => opcion(x) && record(x) && text(x['nom']) && ['registrado', 'supuesto'].includes(x['estado'] as string)
+ && text(x['fuente']) && lista(x['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
+ || !lista(v['etapas'], e => opcion(e) && record(e) && text(e['pregunta']) && ['incidencia', 'supervivencia'].includes(e['medida'] as string)
+ && lista(e['escenarios'], text) && (e['escenarios'] as unknown[]).length > 0 && lista(e['estimadores'], text) && (e['estimadores'] as unknown[]).length > 0
+ && lista(e['estratos'], text) && (e['estratos'] as unknown[]).length === 2 && lista(e['requeridas'], record)) || !(v['etapas'] as unknown[]).length
|| !lista(v['bloqueados'], b => record(b) && text(b['clave']) && text(b['titulo']) && text(b['motivo']))
|| !sinFilasDePaciente(v)) invalido();
return v as unknown as AnalisisCatalogo;
@@ -80,6 +97,7 @@ export function analisisCatalogo(v: unknown): AnalisisCatalogo {
export function analisisResultados(v: unknown): AnalisisResultados {
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
+ if (!['incidencia', 'supervivencia'].includes(v['medida'] as string) || !lista(v['supuestos'], text)) invalido();
const pob = v['poblacion'], tabla = v['tabla_riesgo'], pruebas = v['pruebas'], efectos = v['efectos'];
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador']) || !text(v['estrato'])
|| !record(v['filtros']) || !record(pob) || !numONulo(pob['n']) || !numONulo(pob['eventos'])
@@ -103,8 +121,8 @@ 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'
+ || !eje(v['filas']) || !eje(v['columnas']) || !opcion(v['dimension_filas']) || !opcion(v['dimension_columnas']) || !lista(v['supuestos'], text)
+ || !lista(v['celdas'], c => record(c) && text(c['fila']) && text(c['columna']) && 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.
diff --git a/src/app/features/indicadores/indicadores-analisis.spec.ts b/src/app/features/indicadores/indicadores-analisis.spec.ts
index a3fde72..0902f1f 100644
--- a/src/app/features/indicadores/indicadores-analisis.spec.ts
+++ b/src/app/features/indicadores/indicadores-analisis.spec.ts
@@ -10,27 +10,40 @@ import { AnalisisCatalogo, AnalisisResultados, AnalisisSubgrupos, analisisCatalo
// 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), `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.
+// Fixtures: `catalogo` (two stages, development and survival, with their scenarios, estimators and two variables
+// each, one of them assumed; one blocked 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,
+ etapas: [
+ { clave: 'desarrollo', etiqueta: 'Desarrollo', pregunta: '¿Quién llega a cáncer?', escenarios: ['diagnostico', 'incidencia'], estimadores: ['cif', 'km'],
+ medida: 'incidencia', estratos: ['birads', 'grupo_edad'], evento_supuesto: null, requeridas: [{ variable: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado' }] },
+ { clave: 'supervivencia', etiqueta: 'Supervivencia', pregunta: '¿Quién sigue viva?', escenarios: ['supervivencia'], estimadores: ['km'],
+ medida: 'supervivencia', estratos: ['etapa_clinica', 'grupo_edad'], evento_supuesto: 'Estado vital supuesto.',
+ requeridas: [{ variable: 'Estado vital y causa de muerte', nom: '16.8', estado: 'supuesto' }] },
+ ],
escenarios: [
- { clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más' },
- { clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna' },
+ { clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más', etapa: 'desarrollo' },
+ { clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna', etapa: 'desarrollo' },
+ { clave: 'supervivencia', etiqueta: 'Supervivencia', evento: 'Muerte', origen: 'Diagnóstico', poblacion: 'Cáncer invasor', etapa: 'supervivencia' },
],
estimadores: [{ clave: 'km', etiqueta: '1 − Kaplan-Meier', nota: 'Censura la muerte.' }, { clave: 'cif', etiqueta: 'Aalen-Johansen', nota: 'Muerte competitiva.' }],
- estratos: [{ clave: 'ninguno', etiqueta: 'Sin estratificar', disponible: true }, { clave: 'birads', etiqueta: 'Categoría BI-RADS', disponible: true },
- { clave: 'grupo_edad', etiqueta: 'Grupo de edad', disponible: true }, { clave: 'subtipo', etiqueta: 'Subtipo molecular', disponible: false, motivo: 'Sin IHC.' }],
- filtros: [{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }] },
- { clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: [{ codigo: '50-59', etiqueta: '50-59 años' }] }],
+ variables: [
+ { clave: 'birads', etiqueta: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado', fuente: 'mastografia.birads',
+ opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }] },
+ { clave: 'grupo_edad', etiqueta: 'Grupo de edad', nom: '16.5', estado: 'registrado', fuente: 'paciente.fecha_nacimiento',
+ opciones: [{ codigo: '50-59', etiqueta: '50-59 años' }] },
+ { clave: 'etapa_clinica', etiqueta: 'Etapa clínica', nom: '10.3.2', estado: 'supuesto', fuente: 'Nota de oncología.',
+ opciones: [{ codigo: 'I', etiqueta: 'Etapa I' }, { codigo: 'IV', etiqueta: 'Etapa IV' }] },
+ ],
bloqueados: [{ clave: 'sobrevida', titulo: 'Sobrevida por etapa clínica', motivo: 'No hay etapa clínica ni estado vital.' }],
});
const punto = (grupo: string, t: number, valor: number, n_riesgo: number, n_eventos: number) =>
({ grupo, t, estimador: 'CIF' as const, valor, ic_bajo: valor * .8, ic_alto: valor * 1.2, n_riesgo, n_eventos, suprimido: 0 as const });
const resultados = (): AnalisisResultados => ({
- simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {},
+ simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
+ escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {},
poblacion: { n: null, eventos: null, totales_ocultos: true, seguimiento_mediano_dias: 700 },
grupos: [
{ grupo: 'B4A', etiqueta: 'BI-RADS 4A', color: '#1F5F8B', suprimido: false, motivo: null, n: 180, eventos: 11, competitivos: null },
@@ -53,13 +66,15 @@ const resultados = (): AnalisisResultados => ({
const subgrupos = (): AnalisisSubgrupos => ({
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif',
+ etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
+ dimension_filas: { clave: 'birads', etiqueta: 'Categoría BI-RADS' }, dimension_columnas: { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
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 },
+ { fila: 'B4A', columna: '40-49', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, t_dias: null, valor: null, ic_bajo: null, ic_alto: null },
+ { fila: 'B4A', columna: '50-59', suprimido: false, motivo: null, n: 60, eventos: 6, t_dias: 730, valor: 10, ic_bajo: 4, ic_alto: 20 },
+ { fila: 'B5', columna: '40-49', suprimido: false, motivo: null, n: 40, eventos: 36, t_dias: 120, valor: 90, ic_bajo: 78, ic_alto: 96 },
+ { fila: 'B5', columna: '50-59', suprimido: false, motivo: null, n: 50, eventos: 45, t_dias: 730, valor: 92, ic_bajo: 81, ic_alto: 97 },
],
});
@@ -94,13 +109,20 @@ describe('Explorador de subgrupos', () => {
});
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: ['B5', '40-49'], z: 90 }] })).toEqual({ fila: 'B5', columna: '40-49' });
expect(celdaDelClic({ points: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
expect(celdaDelClic({ points: [{ z: 1 }] })).toBeUndefined();
});
});
describe('Figuras del análisis', () => {
+ it('en la etapa de supervivencia la curva baja desde 100 % y el eje dice Supervivencia', () => {
+ // Fails if the survival stage is drawn on the incidence axis.
+ const r = resultados();
+ const fig = curvasFigura({ ...r, medida: 'supervivencia', curvas: r.curvas.map(c => c.valor === null ? c : { ...c, valor: 100 - c.valor, ic_bajo: 100 - c.ic_alto!, ic_alto: 100 - c.ic_bajo! }) }, 'claro');
+ expect(((fig.layout['yaxis'] as { title: { text: string } }).title.text)).toBe('Supervivencia (%)');
+ expect((fig.data.find(t => t['meta'] === 'B4A')!['y'] as number[])[0]).toBe(100);
+ });
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.
const fig = curvasFigura(resultados(), 'claro');
@@ -181,7 +203,7 @@ 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', () => {
+ it('el explorador pide su cuadrícula solo al abrirse, y una celda abre sus curvas', () => {
// 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');
@@ -196,7 +218,7 @@ describe('Pestaña Análisis', () => {
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(fixture.componentInstance.vista()).toBe('curvas');
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', () => {
@@ -205,7 +227,9 @@ describe('Pestaña Análisis', () => {
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');
+ // The NOM variables of the stage, and whether the schema records them.
+ expect(diagnostico.querySelector('.requeridas')?.textContent).toContain('Categoría BI-RADS');
+ expect(diagnostico.textContent).toContain('Sobrevida por etapa clínica');
});
it('las flechas mueven entre las tres partes', () => {
// Fails if the parts stop behaving as a keyboard tab list.
@@ -214,7 +238,23 @@ describe('Pestaña Análisis', () => {
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');
+ expect(fixture.componentInstance.vista()).toBe('curvas');
+ });
+ it('cambiar de etapa pide su primer escenario, estimador y variable, y anuncia lo supuesto', () => {
+ // Fails if a stage keeps another stage's stratum or an estimator it does not admit, or hides its assumptions.
+ abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
+ fixture.componentInstance.filtrar('birads', 'B5');
+ http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
+ fixture.componentInstance.elegirEtapa('supervivencia'); fixture.detectChanges();
+ const req = http.expectOne(r => r.url === '/cama/analisis/resultados');
+ expect(['escenario', 'estimador', 'estrato', 'birads'].map(k => req.request.params.get(k))).toEqual(['supervivencia', 'km', 'etapa_clinica', null]);
+ req.flush({ ...resultados(), etapa: 'supervivencia', medida: 'supervivencia', escenario: 'supervivencia', estimador: 'km', estrato: 'etapa_clinica',
+ supuestos: ['Estado vital supuesto.'] });
+ fixture.detectChanges();
+ expect(text()).toContain('¿Quién sigue viva?');
+ expect(fixture.nativeElement.querySelector('.supuestos')?.textContent).toContain('Estado vital supuesto.');
+ expect(fixture.nativeElement.querySelector('#analisis-curvas h2')?.textContent).toContain('Supervivencia a 24 meses');
+ expect(fixture.componentInstance.estratosEtapa().map(e => e.estado)).toEqual([null, 'supuesto', 'registrado']);
});
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.
diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts
index 0703e1c..8e4d4ad 100644
--- a/src/app/features/indicadores/indicadores-analisis.ts
+++ b/src/app/features/indicadores/indicadores-analisis.ts
@@ -8,27 +8,37 @@ 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, subgruposFigura } from './indicadores-analisis-figuras';
-import { AnalisisCatalogo, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos } from './indicadores-analisis.service';
+import { curvasFigura, forestFigura, mesesDe, nombreMedida, subgruposFigura } from './indicadores-analisis-figuras';
+import { AnalisisCatalogo, AnalisisEtapa, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos, AnalisisVariable } from './indicadores-analisis.service';
import { httpMessage } from './indicadores-http';
import { Dominio, Tema } from './indicadores.models';
type Carga = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' };
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 type VistaAnalisis = 'curvas' | 'subgrupos' | 'diagnostico';
export const VISTAS: readonly { id: VistaAnalisis; etiqueta: string }[] = [
- { id: 'supervivencia', etiqueta: 'Supervivencia' },
+ { id: 'curvas', etiqueta: 'Curvas (Kaplan-Meier)' },
{ 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 {
+/** The cell of the subgroup grid: its row and column codes, from the coloured layer only (grey cells are suppressed). */
+export function celdaDelClic(evento: unknown): { fila: string; columna: 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;
+ return Array.isArray(c) && typeof c[0] === 'string' && typeof c[1] === 'string' && typeof punto?.z === 'number' ? { fila: c[0], columna: c[1] } : undefined;
+}
+
+/** The stage a scenario belongs to. */
+export const etapaDe = (catalogo: AnalisisCatalogo, escenario: string | undefined): AnalisisEtapa | undefined =>
+ catalogo.etapas.find(e => e.escenarios.includes(escenario ?? ''));
+
+/** The request a stage opens with: its first scenario and variable, the current estimator if the stage admits it, no filters. */
+export function pedidoDeEtapa(catalogo: AnalisisCatalogo, clave: string, actual?: AnalisisPedido): AnalisisPedido {
+ const etapa = catalogo.etapas.find(e => e.clave === clave) ?? catalogo.etapas[0];
+ const estimador = actual && etapa.estimadores.includes(actual.estimador) ? actual.estimador : etapa.estimadores[0];
+ return { escenario: etapa.escenarios[0], estimador, estrato: etapa.estratos[0], filtros: {} };
}
/** The group of the clicked curve, from the line's `meta`; bands and empty clicks give nothing. */
@@ -42,16 +52,17 @@ export function grupoDelClic(evento: unknown): string | undefined {
* It only changes the request: the server answers with new aggregates.
*/
export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo: AnalisisCatalogo): AnalisisPedido {
- if (!DIMENSIONES.includes(pedido.estrato)) return pedido;
+ const dimensiones: readonly string[] = etapaDe(catalogo, pedido.escenario)?.estratos ?? [];
+ if (!dimensiones.includes(pedido.estrato)) return pedido;
const filtros = { ...pedido.filtros, [pedido.estrato]: grupo };
- const libre = catalogo.estratos.find(e => e.disponible && DIMENSIONES.includes(e.clave) && !filtros[e.clave]);
- return { ...pedido, filtros, estrato: libre?.clave ?? 'ninguno' };
+ return { ...pedido, filtros, estrato: dimensiones.find(d => !filtros[d]) ?? 'ninguno' };
}
-// 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.
+// Exploratory outcomes of the BI-RADS 4+ cohort by stage (development, recurrence, survival), in three parts under
+// one set of controls: the curves (the stage's measure by one of its two variables and the tests that compare the
+// groups), a subgroup explorer (the grid of the stage's two variables and the hazard ratios) and the cohort's
+// diagnostics (its statistical status, the checks behind every figure and the NOM variables the stage needs).
+// 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],
@@ -63,26 +74,34 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
}
@if (cat(); as c) {
-
- Escenario
-
- @for (e of c.escenarios; track e.clave) { {{ e.etiqueta }} }
-
-
- Estimador
-
- @for (e of c.estimadores; track e.clave) { {{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }} }
+ Etapa
+
+ @for (e of c.etapas; track e.clave) { {{ e.etiqueta }} }
+ @if (escenariosEtapa().length > 1) {
+
+ Escenario
+
+ @for (e of escenariosEtapa(); track e.clave) { {{ e.etiqueta }} }
+
+
+ }
+ @if (estimadoresEtapa().length > 1) {
+ Estimador
+
+ @for (e of estimadoresEtapa(); track e.clave) { {{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }} }
+
+ } @else { Kaplan-Meier }
@if (vista() !== 'subgrupos') {
Estratificar por
- @for (e of c.estratos; track e.clave) {
- {{ e.etiqueta }}@if (!e.disponible) { · no disponible }
+ @for (e of estratosEtapa(); track e.clave) {
+ {{ e.etiqueta }}@if (e.estado === 'supuesto') { · supuesto }
}
- @for (f of c.filtros; track f.clave) {
+ @for (f of variablesEtapa(); track f.clave) {
{{ f.etiqueta }}
@@ -95,7 +114,7 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
}
@if (escenario(); as e) {
- {{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.
+ @if (etapa(); as et) { {{ et.pregunta }} }{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.
}
@@ -105,8 +124,8 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
}
-
-
+
+
@switch (resultados().estado) {
@case ('cargando') { }
@case ('error') { {{ $any(resultados()).mensaje }}
Reintentar consulta }
@@ -117,13 +136,17 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido }
@if (hayFiltros()) { · {{ textoFiltros() }} }
+ @if (r.supuestos.length) {
+ Datos supuestos en el mock.
+
@for (t of r.supuestos; track t) { {{ t }} }
+ }
- Incidencia acumulada a {{ meses(r.horizonte_dias) }} meses
+ {{ nombreMedida() }} a {{ meses(r.horizonte_dias) }} meses
{{ estimadorElegido()?.etiqueta }}. @if (puedeElegir()) { Haga clic en una curva para analizar solo ese grupo. }
@if (figuraCurvas().data.length) {
+ [label]="nombreMedida() + ' por ' + (estratoElegido()?.etiqueta ?? 'grupo')" />
Pacientes en riesgo
Grupo @for (d of r.tabla_riesgo.cortes_dias; track d) { Mes {{ meses(d) }} }
@@ -173,15 +196,16 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
- Incidencia a {{ meses(c.horizonte_dias) }} meses por BI-RADS y grupo de edad
+ {{ nombreMedida() }} a {{ meses(c.horizonte_dias) }} meses@if (sub(); as s) { por {{ s.dimension_filas.etiqueta.toLowerCase() }} y {{ s.dimension_columnas.etiqueta.toLowerCase() }} }
@switch (subgrupos().estado) {
@case ('cargando') { }
@case ('error') { {{ $any(subgrupos()).mensaje }}
Reintentar consulta }
}
@if (sub(); as s) {
- {{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus curvas en Supervivencia.
+ {{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus curvas.
+ @if (s.supuestos.length) { Supuesto en el mock: {{ s.supuestos.join(' ') }}
}
+ [label]="nombreMedida() + ' por ' + s.dimension_filas.etiqueta + ' y ' + s.dimension_columnas.etiqueta" />
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.
}
@@ -195,7 +219,7 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}
}
-
El estrato y los filtros se eligen en Supervivencia.
+
El estrato y los filtros se eligen en Curvas.
}
@@ -230,11 +254,23 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
Versión del modelo: {{ r.validacion[0]?.version_modelo }}.
}
+ @if (etapa(); as et) {
+
+ Variables de la NOM para la etapa de {{ et.etiqueta.toLowerCase() }}
+ Lo que hay que registrar para estratificar estas curvas, ajustar Cox y aplicar el log-rank. Las dos en uso:
+ @for (v of variablesEtapa(); track v.clave) { {{ v.etiqueta }} ({{ v.estado === 'registrado' ? 'registrada' : 'supuesta' }}){{ $last ? '.' : ';' }} }
+
+ Variable NOM En el esquema
+ @for (v of et.requeridas; track v.variable) {
+ {{ v.variable }} {{ v.nom }} {{ v.estado }}
+ }
+
+
+ }
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 }}
}
@@ -273,6 +309,11 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
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; }
+ .supuestos { margin: 0 0 var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border-left: 4px solid var(--issste-accent);
+ background: var(--issste-surface); color: var(--issste-text); font: var(--mat-sys-body-medium); }
+ .supuestos ul { margin: var(--issste-space-1) 0 0; padding-left: var(--issste-space-6); }
+ .requeridas { margin-top: var(--issste-space-6); }
+ .requeridas tr.falta td:last-child { font-weight: 600; }
.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); }
@@ -301,16 +342,24 @@ export class IndicadoresAnalisis {
readonly res = computed(() => { const r = this.resultados(); return r.estado === 'listo' ? r.datos : undefined; });
readonly escenario = computed(() => this.cat()?.escenarios.find(e => e.clave === this.pedido()?.escenario));
readonly estimadorElegido = computed(() => this.cat()?.estimadores.find(e => e.clave === this.pedido()?.estimador));
- readonly estratoElegido = computed(() => this.cat()?.estratos.find(e => e.clave === this.pedido()?.estrato));
- readonly bloqueadosEstrato = computed(() => this.cat()?.estratos.filter(e => !e.disponible) ?? []);
+ readonly etapa = computed(() => { const c = this.cat(); return c ? etapaDe(c, this.pedido()?.escenario) : undefined; });
+ readonly nombreMedida = computed(() => nombreMedida(this.etapa()?.medida ?? 'incidencia'));
+ private variable(clave: string): AnalisisVariable | undefined { return this.cat()?.variables.find(v => v.clave === clave); }
+ // The stage's two variables, each with its source; the stratum adds «Sin estratificar».
+ readonly variablesEtapa = computed(() => (this.etapa()?.estratos ?? [] as readonly string[]).map(k => this.variable(k)).filter((v): v is AnalisisVariable => !!v));
+ readonly estratosEtapa = computed(() => [{ clave: 'ninguno', etiqueta: 'Sin estratificar', estado: null as string | null },
+ ...this.variablesEtapa().map(v => ({ clave: v.clave, etiqueta: v.etiqueta, estado: v.estado as string | null }))]);
+ readonly escenariosEtapa = computed(() => this.cat()?.escenarios.filter(e => this.etapa()?.escenarios.includes(e.clave)) ?? []);
+ readonly estimadoresEtapa = computed(() => this.cat()?.estimadores.filter(e => this.etapa()?.estimadores.includes(e.clave)) ?? []);
+ readonly estratoElegido = computed(() => this.estratosEtapa().find(e => e.clave === this.pedido()?.estrato));
readonly hayFiltros = computed(() => Object.values(this.pedido()?.filtros ?? {}).some(Boolean));
- readonly puedeElegir = computed(() => DIMENSIONES.includes(this.pedido()?.estrato ?? '') && (this.res()?.grupos.filter(g => !g.suprimido).length ?? 0) > 1);
+ readonly puedeElegir = computed(() => (this.etapa()?.estratos ?? [] as readonly string[]).includes(this.pedido()?.estrato ?? '') && (this.res()?.grupos.filter(g => !g.suprimido).length ?? 0) > 1);
readonly suprimidos = computed(() => this.res()?.grupos.filter(g => g.suprimido) ?? []);
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 vista = signal('curvas');
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: {} }; });
@@ -321,7 +370,7 @@ export class IndicadoresAnalisis {
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(', ');
+ .map(([k, v]) => cat?.variables.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;
@@ -333,11 +382,7 @@ export class IndicadoresAnalisis {
catchError(error => of>(error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
startWith>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => {
this.catalogo.set(carga);
- if (carga.estado === 'listo' && !this.pedido()) {
- const c = carga.datos;
- this.cambiar({ escenario: c.escenarios[0].clave, estimador: c.estimadores.at(-1)!.clave,
- estrato: c.estratos.find(e => e.disponible && e.clave !== 'ninguno')?.clave ?? 'ninguno', filtros: {} });
- }
+ if (carga.estado === 'listo' && !this.pedido()) this.cambiar(pedidoDeEtapa(carga.datos, carga.datos.etapas[0].clave));
});
this.pedidos.pipe(switchMap(pedido => this.service.resultados(this.dominio(), pedido).pipe(
map((datos): Carga => ({ estado: 'listo', datos })),
@@ -363,6 +408,11 @@ export class IndicadoresAnalisis {
this.pedido.set(pedido);
this.pedidos.next(pedido);
}
+ // A stage keeps the estimator when it admits it, and starts from its first scenario and variable.
+ elegirEtapa(clave: string) {
+ const c = this.cat();
+ if (c && clave !== this.etapa()?.clave) this.cambiar(pedidoDeEtapa(c, clave, this.pedido()));
+ }
estratificar(estrato: string) {
// A stratum can't also be a single-value filter: choosing it lifts that filter.
const { [estrato]: _, ...filtros } = this.pedido()?.filtros ?? {};
@@ -373,7 +423,7 @@ export class IndicadoresAnalisis {
const filtros = valor ? { ...resto, [clave]: valor } : resto;
// Filtering the stratified dimension to one value moves the stratification to another one.
const estrato = valor && this.pedido()?.estrato === clave
- ? this.cat()?.estratos.find(e => e.disponible && DIMENSIONES.includes(e.clave) && !filtros[e.clave])?.clave ?? 'ninguno'
+ ? (this.etapa()?.estratos ?? [] as readonly string[]).find(d => !filtros[d]) ?? 'ninguno'
: this.pedido()?.estrato;
this.cambiar({ filtros, estrato });
}
@@ -403,10 +453,10 @@ export class IndicadoresAnalisis {
}
// 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');
+ const celda = celdaDelClic(evento), s = this.sub();
+ if (!celda || !s) return;
+ this.cambiar({ filtros: { [s.dimension_filas.clave]: celda.fila, [s.dimension_columnas.clave]: celda.columna }, estrato: 'ninguno' });
+ this.vista.set('curvas');
}
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); }