feat(cama): «Análisis» by stage: development, recurrence and survival, each with its two NOM variables
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.
This commit is contained in:
@@ -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;
|
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
|
* 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.
|
* can only change the filters, never read rows.
|
||||||
*/
|
*/
|
||||||
export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
||||||
const p = c2Theme(tema), meses = r.horizonte_dias / DIAS_POR_MES;
|
const p = c2Theme(tema), meses = r.horizonte_dias / DIAS_POR_MES;
|
||||||
const data: Record<string, unknown>[] = [];
|
const data: Record<string, unknown>[] = [];
|
||||||
let maximo = 1;
|
const supervivencia = r.medida === 'supervivencia';
|
||||||
|
let maximo = 1, minimo = 100;
|
||||||
for (const g of r.grupos.filter(x => !x.suprimido)) {
|
for (const g of r.grupos.filter(x => !x.suprimido)) {
|
||||||
const puntos = r.curvas.filter(c => c.grupo === g.grupo && c.suprimido === 0);
|
const puntos = r.curvas.filter(c => c.grupo === g.grupo && c.suprimido === 0);
|
||||||
if (!puntos.length) continue;
|
if (!puntos.length) continue;
|
||||||
const x = puntos.map(c => +(c.t / DIAS_POR_MES).toFixed(2));
|
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 };
|
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_bajo) });
|
||||||
data.push({ ...comun, y: puntos.map(c => c.ic_alto), fill: 'tonexty', fillcolor: transparente(g.color, tema === 'oscuro' ? .28 : .16) });
|
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',
|
margin: { t: 16, l: 64, r: 16, b: 96 }, hovermode: 'closest',
|
||||||
legend: { orientation: 'h', y: -0.22, itemclick: false, itemdoubleclick: false },
|
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 },
|
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 },
|
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.
|
* 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 {
|
export function subgruposFigura(s: AnalisisSubgrupos, tema: Tema): PlotlyFigure {
|
||||||
const p = c2Theme(tema), horizonte = Math.round(s.horizonte_dias / DIAS_POR_MES);
|
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 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 texto = s.filas.map(f => s.columnas.map(c => {
|
||||||
const x = celda(f.codigo, c.codigo);
|
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,
|
{ 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>',
|
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']],
|
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: {
|
layout: {
|
||||||
autosize: true, height: 80 + 64 * s.filas.length, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
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 },
|
margin: { t: 16, l: 16, r: 16, b: 56 },
|
||||||
xaxis: { title: { text: 'Grupo de edad' }, side: 'bottom', fixedrange: true, automargin: true },
|
xaxis: { title: { text: escapar(s.dimension_columnas.etiqueta) }, side: 'bottom', fixedrange: true, automargin: true },
|
||||||
yaxis: { autorange: 'reversed', 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) => {
|
annotations: s.filas.flatMap((f, i) => s.columnas.map((c, j) => {
|
||||||
const v = z[i][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 } };
|
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 } };
|
||||||
|
|||||||
@@ -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
|
// 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.
|
// (`/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 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 AnalisisEstimador extends AnalisisOpcion { nota: string; }
|
||||||
export interface AnalisisEstrato extends AnalisisOpcion { disponible: boolean; motivo?: string; }
|
export type EstadoVariable = 'registrado' | 'supuesto';
|
||||||
export interface AnalisisFiltro { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
|
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 AnalisisBloqueado { clave: string; titulo: string; motivo: string; }
|
||||||
export interface AnalisisCatalogo {
|
export interface AnalisisCatalogo {
|
||||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||||
escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[]; estratos: AnalisisEstrato[];
|
etapas: AnalisisEtapa[]; escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[];
|
||||||
filtros: AnalisisFiltro[]; bloqueados: AnalisisBloqueado[];
|
variables: AnalisisVariable[]; bloqueados: AnalisisBloqueado[];
|
||||||
}
|
}
|
||||||
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; }
|
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; }
|
||||||
|
|
||||||
@@ -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 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 {
|
export interface AnalisisResultados {
|
||||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||||
|
etapa: string; medida: 'incidencia' | 'supervivencia';
|
||||||
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>;
|
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>;
|
||||||
|
// 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 };
|
poblacion: { n: number | null; eventos: number | null; totales_ocultos: boolean; seguimiento_mediano_dias: number | null };
|
||||||
grupos: GrupoAnalisis[]; curvas: PuntoCurva[];
|
grupos: GrupoAnalisis[]; curvas: PuntoCurva[];
|
||||||
tabla_riesgo: { cortes_dias: number[]; filas: { grupo: string; cortes: (number | null)[] }[] };
|
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.
|
// The BI-RADS by age-group grid: the incidence at the horizon in each cell, or the reason it is suppressed.
|
||||||
export interface CeldaSubgrupo {
|
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;
|
n: number | null; eventos: number | null; t_dias: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
|
||||||
}
|
}
|
||||||
export interface AnalisisSubgrupos {
|
export interface AnalisisSubgrupos {
|
||||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; escenario: string; estimador: string;
|
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[];
|
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 {
|
export function analisisCatalogo(v: unknown): AnalisisCatalogo {
|
||||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
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'])
|
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['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['variables'], x => opcion(x) && record(x) && text(x['nom']) && ['registrado', 'supuesto'].includes(x['estado'] as string)
|
||||||
|| !lista(v['filtros'], f => record(f) && text(f['clave']) && text(f['etiqueta']) && lista(f['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
|
&& 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']))
|
|| !lista(v['bloqueados'], b => record(b) && text(b['clave']) && text(b['titulo']) && text(b['motivo']))
|
||||||
|| !sinFilasDePaciente(v)) invalido();
|
|| !sinFilasDePaciente(v)) invalido();
|
||||||
return v as unknown as AnalisisCatalogo;
|
return v as unknown as AnalisisCatalogo;
|
||||||
@@ -80,6 +97,7 @@ export function analisisCatalogo(v: unknown): AnalisisCatalogo {
|
|||||||
|
|
||||||
export function analisisResultados(v: unknown): AnalisisResultados {
|
export function analisisResultados(v: unknown): AnalisisResultados {
|
||||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
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'];
|
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'])
|
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'])
|
|| !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.');
|
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']));
|
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'])
|
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador'])
|
||||||
|| !eje(v['filas']) || !eje(v['columnas'])
|
|| !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['birads']) && text(c['grupo_edad']) && typeof c['suprimido'] === 'boolean'
|
|| !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
|
&& (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();
|
: 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.
|
// A published cell never has fewer patients or events than the threshold.
|
||||||
|
|||||||
@@ -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),
|
// 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 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.
|
// 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
|
// Fixtures: `catalogo` (two stages, development and survival, with their scenarios, estimators and two variables
|
||||||
// analysis), `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model) and `subgrupos`
|
// each, one of them assumed; one blocked analysis), `resultados` (two published BI-RADS groups, one suppressed, a
|
||||||
// (a two-by-two BI-RADS and age grid with one suppressed cell), all built below.
|
// ready Cox model) and `subgrupos` (a two-by-two BI-RADS and age grid with one suppressed cell), all built below.
|
||||||
|
|
||||||
const catalogo = (): AnalisisCatalogo => ({
|
const catalogo = (): AnalisisCatalogo => ({
|
||||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5,
|
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: [
|
escenarios: [
|
||||||
{ clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más' },
|
{ 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' },
|
{ 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.' }],
|
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 },
|
variables: [
|
||||||
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', disponible: true }, { clave: 'subtipo', etiqueta: 'Subtipo molecular', disponible: false, motivo: 'Sin IHC.' }],
|
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado', fuente: 'mastografia.birads',
|
||||||
filtros: [{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }] },
|
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' }] }],
|
{ 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.' }],
|
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) =>
|
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 });
|
({ 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 => ({
|
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 },
|
poblacion: { n: null, eventos: null, totales_ocultos: true, seguimiento_mediano_dias: 700 },
|
||||||
grupos: [
|
grupos: [
|
||||||
{ grupo: 'B4A', etiqueta: 'BI-RADS 4A', color: '#1F5F8B', suprimido: false, motivo: null, n: 180, eventos: 11, competitivos: null },
|
{ 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 => ({
|
const subgrupos = (): AnalisisSubgrupos => ({
|
||||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif',
|
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' }],
|
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' }],
|
columnas: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }],
|
||||||
celdas: [
|
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 },
|
{ 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 },
|
||||||
{ 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 },
|
{ fila: 'B4A', columna: '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 },
|
{ fila: 'B5', columna: '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: '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', () => {
|
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.
|
// 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: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
|
||||||
expect(celdaDelClic({ points: [{ z: 1 }] })).toBeUndefined();
|
expect(celdaDelClic({ points: [{ z: 1 }] })).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Figuras del análisis', () => {
|
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', () => {
|
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.
|
// 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');
|
const fig = curvasFigura(resultados(), 'claro');
|
||||||
@@ -181,7 +203,7 @@ describe('Pestaña Análisis', () => {
|
|||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(text()).toContain('Eventos insuficientes. 12 eventos para 4 parámetros.');
|
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.
|
// 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());
|
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
|
||||||
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
|
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');
|
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']);
|
expect(['estrato', 'birads', 'grupo_edad'].map(k => curvas.request.params.get(k))).toEqual(['ninguno', 'B5', '50-59']);
|
||||||
curvas.flush(resultados()); fixture.detectChanges();
|
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');
|
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', () => {
|
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;
|
const diagnostico = fixture.nativeElement.querySelector('#analisis-diagnostico') as HTMLElement;
|
||||||
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
|
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
|
||||||
expect(diagnostico.querySelector('.dato .cifra')?.textContent).toBe('Oculto');
|
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', () => {
|
it('las flechas mueven entre las tres partes', () => {
|
||||||
// Fails if the parts stop behaving as a keyboard tab list.
|
// 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();
|
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'End' })); fixture.detectChanges();
|
||||||
expect(fixture.componentInstance.vista()).toBe('diagnostico');
|
expect(fixture.componentInstance.vista()).toBe('diagnostico');
|
||||||
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); fixture.detectChanges();
|
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', () => {
|
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.
|
// Fails if a 404 on the catalog is shown as an error instead of a feature not yet published.
|
||||||
|
|||||||
@@ -8,27 +8,37 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
|||||||
import { MatSelectModule } from '@angular/material/select';
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { curvasFigura, forestFigura, mesesDe, subgruposFigura } from './indicadores-analisis-figuras';
|
import { curvasFigura, forestFigura, mesesDe, nombreMedida, subgruposFigura } from './indicadores-analisis-figuras';
|
||||||
import { AnalisisCatalogo, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos } from './indicadores-analisis.service';
|
import { AnalisisCatalogo, AnalisisEtapa, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos, AnalisisVariable } from './indicadores-analisis.service';
|
||||||
import { httpMessage } from './indicadores-http';
|
import { httpMessage } from './indicadores-http';
|
||||||
import { Dominio, Tema } from './indicadores.models';
|
import { Dominio, Tema } from './indicadores.models';
|
||||||
|
|
||||||
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' };
|
type Carga<T> = { 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 });
|
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 = 'curvas' | 'subgrupos' | 'diagnostico';
|
||||||
export type VistaAnalisis = 'supervivencia' | 'subgrupos' | 'diagnostico';
|
|
||||||
export const VISTAS: readonly { id: VistaAnalisis; etiqueta: string }[] = [
|
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: 'subgrupos', etiqueta: 'Explorador de subgrupos' },
|
||||||
{ id: 'diagnostico', etiqueta: 'Diagnóstico de la cohorte' },
|
{ 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). */
|
/** 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): { birads: string; grupo_edad: string } | undefined {
|
export function celdaDelClic(evento: unknown): { fila: string; columna: string } | undefined {
|
||||||
const punto = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
const punto = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
||||||
const c = punto?.customdata;
|
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. */
|
/** 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.
|
* It only changes the request: the server answers with new aggregates.
|
||||||
*/
|
*/
|
||||||
export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo: AnalisisCatalogo): AnalisisPedido {
|
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 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: dimensiones.find(d => !filtros[d]) ?? 'ninguno' };
|
||||||
return { ...pedido, filtros, estrato: libre?.clave ?? 'ninguno' };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exploratory outcomes of the BI-RADS 4+ cohort, in three parts under one set of controls: survival (cumulative
|
// Exploratory outcomes of the BI-RADS 4+ cohort by stage (development, recurrence, survival), in three parts under
|
||||||
// incidence by a pre-specified stratum and the tests that compare the groups), a subgroup explorer (the BI-RADS by
|
// one set of controls: the curves (the stage's measure by one of its two variables and the tests that compare the
|
||||||
// age grid and the hazard ratios) and the cohort's diagnostics (its statistical status and the checks behind every
|
// groups), a subgroup explorer (the grid of the stage's two variables and the hazard ratios) and the cohort's
|
||||||
// figure). Nothing is requested until the tab is first opened, and the grid only once its part is.
|
// 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({
|
@Component({
|
||||||
selector: 'app-indicadores-analisis',
|
selector: 'app-indicadores-analisis',
|
||||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||||
@@ -63,26 +74,34 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
|||||||
}
|
}
|
||||||
@if (cat(); as c) {
|
@if (cat(); as c) {
|
||||||
<div class="controles">
|
<div class="controles">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
<span id="analisis-etapa" class="etiqueta">Etapa</span>
|
||||||
<mat-label>Escenario</mat-label>
|
<mat-button-toggle-group class="etapas" aria-labelledby="analisis-etapa" hideSingleSelectionIndicator [value]="etapa()?.clave" (change)="elegirEtapa($event.value)">
|
||||||
<mat-select [value]="pedido()!.escenario" (selectionChange)="cambiar({ escenario: $event.value })">
|
@for (e of c.etapas; track e.clave) { <mat-button-toggle [value]="e.clave">{{ e.etiqueta }}</mat-button-toggle> }
|
||||||
@for (e of c.escenarios; track e.clave) { <mat-option [value]="e.clave">{{ e.etiqueta }}</mat-option> }
|
|
||||||
</mat-select>
|
|
||||||
</mat-form-field>
|
|
||||||
<span id="analisis-estimador" class="etiqueta">Estimador</span>
|
|
||||||
<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-button-toggle-group>
|
||||||
|
@if (escenariosEtapa().length > 1) {
|
||||||
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
|
<mat-label>Escenario</mat-label>
|
||||||
|
<mat-select [value]="pedido()!.escenario" (selectionChange)="cambiar({ escenario: $event.value })">
|
||||||
|
@for (e of escenariosEtapa(); track e.clave) { <mat-option [value]="e.clave">{{ e.etiqueta }}</mat-option> }
|
||||||
|
</mat-select>
|
||||||
|
</mat-form-field>
|
||||||
|
}
|
||||||
|
@if (estimadoresEtapa().length > 1) {
|
||||||
|
<span id="analisis-estimador" class="etiqueta">Estimador</span>
|
||||||
|
<mat-button-toggle-group aria-labelledby="analisis-estimador" hideSingleSelectionIndicator [value]="pedido()!.estimador" (change)="cambiar({ estimador: $event.value })">
|
||||||
|
@for (e of estimadoresEtapa(); 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>
|
||||||
|
} @else { <span class="etiqueta">Kaplan-Meier</span> }
|
||||||
@if (vista() !== 'subgrupos') {
|
@if (vista() !== 'subgrupos') {
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
<mat-label>Estratificar por</mat-label>
|
<mat-label>Estratificar por</mat-label>
|
||||||
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
|
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
|
||||||
@for (e of c.estratos; track e.clave) {
|
@for (e of estratosEtapa(); 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-option [value]="e.clave">{{ e.etiqueta }}@if (e.estado === 'supuesto') { <span class="motivo"> · supuesto</span> }</mat-option>
|
||||||
}
|
}
|
||||||
</mat-select>
|
</mat-select>
|
||||||
</mat-form-field>
|
</mat-form-field>
|
||||||
@for (f of c.filtros; track f.clave) {
|
@for (f of variablesEtapa(); track f.clave) {
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
<mat-label>{{ f.etiqueta }}</mat-label>
|
<mat-label>{{ f.etiqueta }}</mat-label>
|
||||||
<mat-select [value]="pedido()!.filtros[f.clave] ?? ''" (selectionChange)="filtrar(f.clave, $event.value)">
|
<mat-select [value]="pedido()!.filtros[f.clave] ?? ''" (selectionChange)="filtrar(f.clave, $event.value)">
|
||||||
@@ -95,7 +114,7 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
@if (escenario(); as e) {
|
@if (escenario(); as e) {
|
||||||
<p class="contexto"><strong>{{ e.poblacion }}.</strong> Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.</p>
|
<p class="contexto">@if (etapa(); as et) { <strong>{{ et.pregunta }}</strong><br> }{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.</p>
|
||||||
}
|
}
|
||||||
|
|
||||||
<div class="subsecciones" role="tablist" aria-label="Partes del análisis" (keydown)="teclaVista($event)">
|
<div class="subsecciones" role="tablist" aria-label="Partes del análisis" (keydown)="teclaVista($event)">
|
||||||
@@ -105,8 +124,8 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
|||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Survival: the curves of each group, how they compare, and who is still at risk. -->
|
<!-- Curves: the stage's measure for each group, how the groups compare, and who is still at risk. -->
|
||||||
<section id="analisis-supervivencia" role="tabpanel" aria-labelledby="analisis-tab-supervivencia" [hidden]="vista() !== 'supervivencia'">
|
<section id="analisis-curvas" role="tabpanel" aria-labelledby="analisis-tab-curvas" [hidden]="vista() !== 'curvas'">
|
||||||
@switch (resultados().estado) {
|
@switch (resultados().estado) {
|
||||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el análisis" /> }
|
@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> }
|
@case ('error') { <div role="alert" class="panel"><p>{{ $any(resultados()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div> }
|
||||||
@@ -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 }
|
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido }
|
||||||
@if (hayFiltros()) { · {{ textoFiltros() }} }
|
@if (hayFiltros()) { · {{ textoFiltros() }} }
|
||||||
</p>
|
</p>
|
||||||
|
@if (r.supuestos.length) {
|
||||||
|
<div class="supuestos" role="note"><strong>Datos supuestos en el mock.</strong>
|
||||||
|
<ul>@for (t of r.supuestos; track t) { <li>{{ t }}</li> }</ul></div>
|
||||||
|
}
|
||||||
<div class="paneles">
|
<div class="paneles">
|
||||||
<article class="panel ancho">
|
<article class="panel ancho">
|
||||||
<h2>Incidencia acumulada a {{ meses(r.horizonte_dias) }} meses</h2>
|
<h2>{{ nombreMedida() }} 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>
|
<p class="nota">{{ estimadorElegido()?.etiqueta }}. @if (puedeElegir()) { Haga clic en una curva para analizar solo ese grupo. }</p>
|
||||||
@if (figuraCurvas().data.length) {
|
@if (figuraCurvas().data.length) {
|
||||||
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
|
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
|
||||||
[label]="'Incidencia acumulada por ' + (estratoElegido()?.etiqueta ?? 'grupo')" />
|
[label]="nombreMedida() + ' por ' + (estratoElegido()?.etiqueta ?? 'grupo')" />
|
||||||
<table class="riesgo">
|
<table class="riesgo">
|
||||||
<caption>Pacientes en riesgo</caption>
|
<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>
|
<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>
|
||||||
@@ -173,15 +196,16 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
|||||||
<section id="analisis-subgrupos" role="tabpanel" aria-labelledby="analisis-tab-subgrupos" [hidden]="vista() !== 'subgrupos'">
|
<section id="analisis-subgrupos" role="tabpanel" aria-labelledby="analisis-tab-subgrupos" [hidden]="vista() !== 'subgrupos'">
|
||||||
<div class="paneles">
|
<div class="paneles">
|
||||||
<article class="panel ancho">
|
<article class="panel ancho">
|
||||||
<h2>Incidencia a {{ meses(c.horizonte_dias) }} meses por BI-RADS y grupo de edad</h2>
|
<h2>{{ nombreMedida() }} a {{ meses(c.horizonte_dias) }} meses@if (sub(); as s) { por {{ s.dimension_filas.etiqueta.toLowerCase() }} y {{ s.dimension_columnas.etiqueta.toLowerCase() }} }</h2>
|
||||||
@switch (subgrupos().estado) {
|
@switch (subgrupos().estado) {
|
||||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los subgrupos" /> }
|
@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> }
|
@case ('error') { <div role="alert"><p>{{ $any(subgrupos()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarSubgrupos(true)">Reintentar consulta</button></div> }
|
||||||
}
|
}
|
||||||
@if (sub(); as s) {
|
@if (sub(); as s) {
|
||||||
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus curvas en Supervivencia.</p>
|
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus curvas.</p>
|
||||||
|
@if (s.supuestos.length) { <p class="nota">Supuesto en el mock: {{ s.supuestos.join(' ') }}</p> }
|
||||||
<app-plotly-chart [style.--plot-height]="figuraSubgrupos().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraSubgrupos()" (plotClick)="clicCelda($event)"
|
<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" />
|
[label]="nombreMedida() + ' por ' + s.dimension_filas.etiqueta + ' y ' + s.dimension_columnas.etiqueta" />
|
||||||
<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>
|
<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>
|
||||||
@@ -195,7 +219,7 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
|||||||
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
|
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
|
||||||
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
|
{{ 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>
|
<p class="nota">El estrato y los filtros se eligen en Curvas.</p>
|
||||||
}
|
}
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
@@ -230,11 +254,23 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
|||||||
<p class="nota">Versión del modelo: {{ r.validacion[0]?.version_modelo }}.</p>
|
<p class="nota">Versión del modelo: {{ r.validacion[0]?.version_modelo }}.</p>
|
||||||
</article>
|
</article>
|
||||||
}
|
}
|
||||||
|
@if (etapa(); as et) {
|
||||||
|
<article class="panel requeridas">
|
||||||
|
<h2>Variables de la NOM para la etapa de {{ et.etiqueta.toLowerCase() }}</h2>
|
||||||
|
<p class="nota">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 ? '.' : ';' }} }</p>
|
||||||
|
<table>
|
||||||
|
<thead><tr><th scope="col">Variable</th><th scope="col">NOM</th><th scope="col">En el esquema</th></tr></thead>
|
||||||
|
<tbody>@for (v of et.requeridas; track v.variable) {
|
||||||
|
<tr [class.falta]="v.estado !== 'registrado'"><td>{{ v.variable }}</td><td>{{ v.nom }}</td><td>{{ v.estado }}</td></tr>
|
||||||
|
}</tbody>
|
||||||
|
</table>
|
||||||
|
</article>
|
||||||
|
}
|
||||||
<section class="pendientes" aria-labelledby="analisis-pendientes">
|
<section class="pendientes" aria-labelledby="analisis-pendientes">
|
||||||
<h2 id="analisis-pendientes">Lo que la cohorte aún no permite</h2>
|
<h2 id="analisis-pendientes">Lo que la cohorte aún no permite</h2>
|
||||||
<div class="tarjetas">
|
<div class="tarjetas">
|
||||||
@for (b of c.bloqueados; track b.clave) { <article class="bloqueado"><h3>{{ b.titulo }}</h3><p>{{ b.motivo }}</p></article> }
|
@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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</section>
|
</section>
|
||||||
@@ -273,6 +309,11 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
|||||||
font: var(--mat-sys-title-small); cursor: pointer; min-height: 44px; }
|
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[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; }
|
.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); }
|
.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)); } }
|
@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); }
|
.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 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 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 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 etapa = computed(() => { const c = this.cat(); return c ? etapaDe(c, this.pedido()?.escenario) : undefined; });
|
||||||
readonly bloqueadosEstrato = computed(() => this.cat()?.estratos.filter(e => !e.disponible) ?? []);
|
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 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 suprimidos = computed(() => this.res()?.grupos.filter(g => g.suprimido) ?? []);
|
||||||
readonly textoSuprimidos = computed(() => this.suprimidos().map(g => `${g.etiqueta} (${(g.motivo ?? 'suprimido').toLowerCase()})`).join('; '));
|
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 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 figuraForest = computed(() => { const r = this.res(); return r ? forestFigura(r, this.tema()) : { data: [], layout: {} }; });
|
||||||
readonly VISTAS = VISTAS;
|
readonly VISTAS = VISTAS;
|
||||||
readonly vista = signal<VistaAnalisis>('supervivencia');
|
readonly vista = signal<VistaAnalisis>('curvas');
|
||||||
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
|
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
|
||||||
readonly sub = computed(() => { const s = this.subgrupos(); return s.estado === 'listo' ? s.datos : undefined; });
|
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 figuraSubgrupos = computed(() => { const s = this.sub(); return s ? subgruposFigura(s, this.tema()) : { data: [], layout: {} }; });
|
||||||
@@ -321,7 +370,7 @@ export class IndicadoresAnalisis {
|
|||||||
readonly textoFiltros = computed(() => {
|
readonly textoFiltros = computed(() => {
|
||||||
const cat = this.cat(), filtros = this.pedido()?.filtros ?? {};
|
const cat = this.cat(), filtros = this.pedido()?.filtros ?? {};
|
||||||
return Object.entries(filtros).filter(([, v]) => v)
|
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 readonly pedidosSubgrupos = new Subject<{ escenario: string; estimador: string }>();
|
||||||
private subgruposDe?: string;
|
private subgruposDe?: string;
|
||||||
@@ -333,11 +382,7 @@ export class IndicadoresAnalisis {
|
|||||||
catchError(error => of<Carga<AnalisisCatalogo>>(error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
|
catchError(error => of<Carga<AnalisisCatalogo>>(error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
|
||||||
startWith<Carga<AnalisisCatalogo>>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => {
|
startWith<Carga<AnalisisCatalogo>>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => {
|
||||||
this.catalogo.set(carga);
|
this.catalogo.set(carga);
|
||||||
if (carga.estado === 'listo' && !this.pedido()) {
|
if (carga.estado === 'listo' && !this.pedido()) this.cambiar(pedidoDeEtapa(carga.datos, carga.datos.etapas[0].clave));
|
||||||
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: {} });
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
this.pedidos.pipe(switchMap(pedido => this.service.resultados(this.dominio(), pedido).pipe(
|
this.pedidos.pipe(switchMap(pedido => this.service.resultados(this.dominio(), pedido).pipe(
|
||||||
map((datos): Carga<AnalisisResultados> => ({ estado: 'listo', datos })),
|
map((datos): Carga<AnalisisResultados> => ({ estado: 'listo', datos })),
|
||||||
@@ -363,6 +408,11 @@ export class IndicadoresAnalisis {
|
|||||||
this.pedido.set(pedido);
|
this.pedido.set(pedido);
|
||||||
this.pedidos.next(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) {
|
estratificar(estrato: string) {
|
||||||
// A stratum can't also be a single-value filter: choosing it lifts that filter.
|
// A stratum can't also be a single-value filter: choosing it lifts that filter.
|
||||||
const { [estrato]: _, ...filtros } = this.pedido()?.filtros ?? {};
|
const { [estrato]: _, ...filtros } = this.pedido()?.filtros ?? {};
|
||||||
@@ -373,7 +423,7 @@ export class IndicadoresAnalisis {
|
|||||||
const filtros = valor ? { ...resto, [clave]: valor } : resto;
|
const filtros = valor ? { ...resto, [clave]: valor } : resto;
|
||||||
// Filtering the stratified dimension to one value moves the stratification to another one.
|
// Filtering the stratified dimension to one value moves the stratification to another one.
|
||||||
const estrato = valor && this.pedido()?.estrato === clave
|
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.pedido()?.estrato;
|
||||||
this.cambiar({ filtros, estrato });
|
this.cambiar({ filtros, estrato });
|
||||||
}
|
}
|
||||||
@@ -403,10 +453,10 @@ export class IndicadoresAnalisis {
|
|||||||
}
|
}
|
||||||
// A cell opens its curves: both dimensions filtered, nothing left to stratify.
|
// A cell opens its curves: both dimensions filtered, nothing left to stratify.
|
||||||
clicCelda(evento: unknown) {
|
clicCelda(evento: unknown) {
|
||||||
const celda = celdaDelClic(evento);
|
const celda = celdaDelClic(evento), s = this.sub();
|
||||||
if (!celda) return;
|
if (!celda || !s) return;
|
||||||
this.cambiar({ filtros: { birads: celda.birads, grupo_edad: celda.grupo_edad }, estrato: 'ninguno' });
|
this.cambiar({ filtros: { [s.dimension_filas.clave]: celda.fila, [s.dimension_columnas.clave]: celda.columna }, estrato: 'ninguno' });
|
||||||
this.vista.set('supervivencia');
|
this.vista.set('curvas');
|
||||||
}
|
}
|
||||||
etiqueta(grupo: string) { return this.res()?.grupos.find(g => g.grupo === grupo)?.etiqueta ?? grupo; }
|
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); }
|
reintentar() { const p = this.pedido(); if (p) this.pedidos.next(p); }
|
||||||
|
|||||||
Reference in New Issue
Block a user