Files
WebApp/src/app/gobernanza/figures.ts
T
2026-12-02 19:26:50 -06:00

352 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Figure } from '../plot';
import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
/** A curve with its band, as the reports give them. */
interface Band {
x: number[];
y: number[];
low?: (number | null)[];
high?: (number | null)[];
}
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
/** The stretches of x where the curve has both limits: a band is drawn only there, never from a
* limit that is absent (an absent limit is not zero). */
function bandRuns(b: Band): number[][] {
const runs: number[][] = [];
let run: number[] = [];
b.x.forEach((x, i) => {
if (finite(x) && finite(b.low?.[i]) && finite(b.high?.[i])) run.push(i);
else {
if (run.length > 1) runs.push(run);
run = [];
}
});
if (run.length > 1) runs.push(run);
return runs;
}
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) {
for (const run of bandRuns(b)) {
const x = run.map((i) => b.x[i]);
lines.push({
x: [...x, ...[...x].reverse()],
y: [...run.map((i) => b.high![i]), ...run.map((i) => b.low![i]).reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
}
}
lines.push({
x: b.x,
y: b.y.map((v) => (finite(v) ? v : null)) as number[],
name,
type: 'scatter',
mode: 'lines',
line: { color: colour, dash },
});
return lines;
}
/** What a model's interpretability report draws, by its kind: survival curves, the mixture's
* observed and predicted risk per subgroup, or the logistic regression's calibration. */
export function interpretabilityFigures(
report: Record<string, any>,
): { title: string; figure: Figure }[] {
switch (report['kind']) {
case 'curves': {
const data = (report['curves'] as any[]).flatMap((c, i) =>
banded(c.name, { x: c.months, y: c.survival, low: c.low, high: c.high }, PALETTE[i]),
);
const p = report['predicted'];
data.push({
x: p.months,
y: p.survival,
error_y: {
type: 'data',
symmetric: false,
array: p.high.map((h: number, i: number) => h - p.survival[i]),
arrayminus: p.survival.map((s: number, i: number) => s - p.low[i]),
},
name: p.name,
type: 'scatter',
mode: 'markers',
marker: { color: PALETTE[4], size: 9 },
});
return [
{
title: 'Supervivencia observada y del modelo',
figure: {
data,
layout: {
xaxis: { title: { text: 'Meses desde el índice' } },
yaxis: { title: { text: 'Supervivencia S(t)' } },
},
},
},
// Its clinical scenarios are drawn in the patient record (Análisis de supervivencia).
];
}
case 'subgroups':
return (report['groups'] as any[]).slice(0, 6).map((g) => ({
title: `${Object.values(g.combination).join(' · ')} (n = ${g.n})`,
figure: {
data: [
...banded(
'Observado (Turnbull)',
{
x: g.observed.years,
y: g.observed.risk,
low: g.observed.low,
high: g.observed.high,
},
PALETTE[0],
),
...(g.predicted
? banded(
'Modelo',
{
x: g.predicted.years,
y: g.predicted.risk,
low: g.predicted.low,
high: g.predicted.high,
},
PALETTE[4],
'dot',
)
: []),
],
layout: {
xaxis: { title: { text: 'Años desde el índice' } },
yaxis: { title: { text: 'Riesgo acumulado' } },
},
},
}));
case 'coefficients': {
const bins = report['calibration']['bins'] as any[];
return [
{
title: `Calibración por decil de riesgo (Brier ${report['calibration']['brier'].toFixed(3)})`,
figure: {
data: [
{
x: bins.map((b) => b.predicted),
y: bins.map((b) => b.observed),
name: 'Deciles',
type: 'scatter',
mode: 'markers',
},
{
x: [0, 1],
y: [0, 1],
name: 'Calibración perfecta',
type: 'scatter',
mode: 'lines',
line: { dash: 'dot', color: PALETTE[6] },
},
],
layout: {
xaxis: { title: { text: 'Predicho' } },
yaxis: { title: { text: 'Observado' } },
},
},
},
];
}
case 'scenarios': // recurrence: its scenarios are drawn in the patient record
return [];
case 'age_curves': {
// The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
if (!value) return [];
const label = report['curves']['value'] ? '' : ` · ${Object.keys(report['curves'])[0]}`;
if (value.kind === 'count_rate') {
return [
{
title: `Tasa de referencia: ${value.rate.toFixed(3)} por minuto (${value.reference} estudios)`,
figure: {
data: [
{
x: value.ages,
y: [value.rate, value.rate],
name: 'Tasa',
type: 'scatter',
mode: 'lines',
},
],
layout: {
xaxis: { title: { text: 'Edad (meses)' } },
yaxis: { title: { text: 'Eventos por minuto' } },
},
},
},
];
}
const c = value.curve;
return [
{
title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
figure: {
data: [
...banded(
'p5–p95',
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
PALETTE[4],
),
].map((d, i) => (i === 1 ? { ...d, name: 'Mediana' } : d)),
layout: {
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
yaxis: { title: { text: 'Valor' } },
},
},
},
];
}
case 'associations': {
// Each estimated pair's odds ratio with its 95 % interval, clearest first.
const rows = (report['rows'] as any[])
.filter((r) => r.odds_ratio !== null)
.sort((a, b) => (a.q ?? 1) - (b.q ?? 1));
const label = (r: any) =>
`${BIOMARKER_NAMES[r.biomarker] ?? r.biomarker} · ${ZONE_NAMES[r.zone] ?? r.zone} → ${
OUTCOME_NAMES[r.outcome_code] ?? r.outcome_code
}`;
return [
{
title: `Asociaciones con el ADOS-2 (${report['children']} niños, nivel ${
report['level'] === 'item' ? 'reactivo' : 'dominio'
})`,
figure: {
data: [
{
type: 'scatter',
mode: 'markers',
x: rows.map((r) => r.odds_ratio),
y: rows.map(label),
error_x: {
type: 'data',
symmetric: false,
array: rows.map((r) => (r.ci_high ?? r.odds_ratio) - r.odds_ratio),
arrayminus: rows.map((r) => r.odds_ratio - (r.ci_low ?? r.odds_ratio)),
},
marker: {
color: rows.map((r) => ((r.q ?? 1) < 0.05 ? PALETTE[2] : '#9aa0a6')),
size: 9,
},
customdata: rows.map((r) => r.q),
hovertemplate: 'OR %{x:.2f} · q %{customdata:.3f}<extra>%{y}</extra>',
showlegend: false,
},
],
layout: {
xaxis: { title: { text: 'Razón de momios (escala log)' }, type: 'log' },
yaxis: { automargin: true, autorange: 'reversed' },
shapes: [
{
type: 'line',
x0: 1,
x1: 1,
yref: 'paper',
y0: 0,
y1: 1,
line: { color: '#9aa0a6', dash: 'dot' },
},
],
height: Math.max(320, 22 * rows.length + 80),
},
},
},
];
}
default:
return [];
}
}
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
* and the model's points with their bootstrap band (also a patient's, in her record). */
export function scenarioFigure(
title: string,
e: any,
horizons: number[],
yTitle: string,
): { title: string; figure: Figure } {
return {
title,
figure: {
data: [
...banded(
'Kaplan-Meier (IC 95 % Greenwood)',
{ x: e.km.months, y: e.km.S, low: e.km.low, high: e.km.high },
PALETTE[0],
),
{
x: e.weibull.t,
y: e.weibull.S,
name: 'Weibull',
type: 'scatter',
mode: 'lines',
line: { color: PALETTE[1] },
},
{
x: e.weibull_fractional.t,
y: e.weibull_fractional.S,
name: 'Weibull fraccional',
type: 'scatter',
mode: 'lines',
line: { color: PALETTE[2], dash: 'dash' },
},
points('LR + HBN combinado (IC 95 % bootstrap)', horizons, e.points.COMB),
],
layout: {
// One label per month with every curve's survival there, as percentages.
hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
},
},
};
}
/** The model's points: a value that is absent is not drawn (zero is a value and is drawn), and a
* point without both limits has no bar. */
function points(
name: string,
x: number[],
p: { S: (number | null)[]; low?: (number | null)[]; high?: (number | null)[] },
): Partial<Plotly.Data> {
const errors = p.S.map((value, i) => {
const low = p.low?.[i];
const high = p.high?.[i];
return finite(value) && finite(low) && finite(high)
? { up: high - value, down: value - low }
: null;
});
return {
x,
y: p.S.map((v) => (finite(v) ? v : null)) as number[],
...(errors.some((error) => error !== null)
? {
error_y: {
type: 'data' as const,
symmetric: false,
array: errors.map((error) => error?.up ?? null) as number[],
arrayminus: errors.map((error) => error?.down ?? null) as number[],
},
}
: {}),
name,
type: 'scatter',
mode: 'markers',
marker: { color: PALETTE[4], size: 9 },
};
}