Files
WebApp/src/app/features/indicadores/indicadores-analisis-figuras.ts
T
rockdrigo d16804d416 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.
2026-11-12 14:04:58 -06:00

130 lines
9.1 KiB
TypeScript

import { PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { AnalisisResultados, AnalisisSubgrupos } from './indicadores-analisis.service';
const DIAS_POR_MES = 30.4375;
const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const miles = (v: number) => v.toLocaleString('es-MX');
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
function transparente(hex: string, alfa: number) {
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(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';
/**
* 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<string, unknown>[] = [];
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!)); 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) });
data.push({
type: 'scatter', mode: 'lines', x, y: puntos.map(c => c.valor), name: `${escapar(g.etiqueta)} (n = ${miles(g.n!)}, ${miles(g.eventos!)} eventos)`,
legendgroup: g.grupo, meta: g.grupo, line: { shape: 'hv', width: 2.5, color: g.color },
customdata: puntos.map(c => [pct(c.valor!), pct(c.ic_bajo!), pct(c.ic_alto!), miles(c.n_riesgo!), miles(c.n_eventos!)]),
hovertemplate: `<b>${escapar(g.etiqueta)}</b><br>Mes %{x:.1f}: %{customdata[0]} % (IC 95 %: %{customdata[1]} a %{customdata[2]})<br>En riesgo: %{customdata[3]} · eventos acumulados: %{customdata[4]}<extra></extra>`,
});
}
return {
data,
layout: {
autosize: true, height: 460, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
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: 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 },
};
}
/** Hazard ratio of each group against the reference, on a log axis; an open marker flags a failed proportional-hazards check. */
export function forestFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), e = r.efectos;
if (e.estado !== 'listo' || !e.filas.length) return { data: [], layout: {} };
const etiquetas = [`${escapar(e.etiqueta_referencia ?? e.referencia ?? '')} (referencia)`, ...e.filas.map(f => escapar(f.etiqueta))];
const falla = (ph: number | null) => ph !== null && ph < .05;
const minimo = Math.min(1, ...e.filas.map(f => f.ic_bajo)), maximo = Math.max(1, ...e.filas.map(f => f.ic_alto));
return {
data: [
{ type: 'scatter', mode: 'markers', x: [1], y: [etiquetas[0]], marker: { symbol: 'diamond', size: 10, color: p.outline }, hoverinfo: 'skip', showlegend: false },
{
type: 'scatter', mode: 'markers', x: e.filas.map(f => f.hr), y: etiquetas.slice(1), showlegend: false,
error_x: { type: 'data', symmetric: false, array: e.filas.map(f => f.ic_alto - f.hr), arrayminus: e.filas.map(f => f.hr - f.ic_bajo), color: p.text, thickness: 1.5, width: 6 },
marker: { size: 11, color: e.filas.map(f => falla(f.ph_p) ? p.background : p.text), line: { color: p.text, width: 2 }, symbol: 'square' },
customdata: e.filas.map(f => [f.ic_bajo.toLocaleString('es-MX'), f.ic_alto.toLocaleString('es-MX'), miles(f.n_eventos), falla(f.ph_p) ? '<br>Riesgos no proporcionales: el HR promedia un efecto que cambia.' : '']),
hovertemplate: '%{y}<br>HR %{x:.2f} (IC 95 %: %{customdata[0]} a %{customdata[1]})<br>%{customdata[2]} eventos%{customdata[3]}<extra></extra>',
},
],
layout: {
autosize: true, height: Math.max(220, 70 + 44 * etiquetas.length), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 16, l: 16, r: 24, b: 56 },
xaxis: { type: 'log', title: { text: 'Razón de riesgos (HR), escala logarítmica' }, range: [Math.log10(minimo * .7), Math.log10(maximo * 1.4)], gridcolor: p.grid, zeroline: false, fixedrange: true },
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
shapes: [{ type: 'line', xref: 'x', yref: 'paper', x0: 1, x1: 1, y0: 0, y1: 1, line: { color: p.outline, dash: 'dot', width: 1.5 } }],
},
config: { displayModeBar: false },
};
}
/**
* 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.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);
if (!x || x.suprimido) return '<span style="opacity:.75">Suprimido</span>';
const meses = Math.round(x.t_dias! / DIAS_POR_MES);
return `<b>${pct(x.valor!)} %</b><br>${miles(x.eventos!)} de ${miles(x.n!)}${meses < horizonte ? `<br>a ${meses} meses` : ''}`;
}));
const ayuda = s.filas.map(f => s.columnas.map(c => {
const x = celda(f.codigo, c.codigo);
if (!x || x.suprimido) return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}: suprimido (${(x?.motivo ?? 'sin datos').toLowerCase()})`;
return `${escapar(f.etiqueta)}, ${escapar(c.etiqueta)}<br>${pct(x.valor!)} % (IC 95 %: ${pct(x.ic_bajo!)} a ${pct(x.ic_alto!)})<br>${miles(x.eventos!)} eventos en ${miles(x.n!)} pacientes`;
}));
const maximo = Math.max(1, ...z.flat().filter((v): v is number => v !== null));
return {
data: [
// The grey layer under the colour: the cells the answer suppressed.
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z: z.map(r => r.map(v => v === null ? 1 : null)),
colorscale: [[0, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9'], [1, tema === 'oscuro' ? '#3A4A63' : '#E4E7E9']], showscale: false, hoverinfo: 'skip', xgap: 3, ygap: 3 },
{ type: 'heatmap', x: s.columnas.map(c => c.etiqueta), y: s.filas.map(f => f.etiqueta), z, zmin: 0, zmax: maximo, xgap: 3, ygap: 3,
customdata: s.filas.map(f => s.columnas.map(c => [f.codigo, c.codigo])), text: ayuda, hovertemplate: '%{text}<extra></extra>',
colorscale: [[0, tema === 'oscuro' ? '#1B3A5B' : '#EAF1F8'], [1, tema === 'oscuro' ? '#9DBFE3' : '#1F5F8B']],
colorbar: { title: { text: 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: 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 } };
})),
},
config: { displayModeBar: false },
};
}
export const mesesDe = (dias: number) => Math.round(dias / DIAS_POR_MES);