Files
WebApp/src/app/gobernanza/figures.ts
T
alberto e345d45c60 F7c: one spindle metric over all NREM sleep
Spindles are measured once, over every window the state classifier labels
sleep, and each child's detection thresholds come from all NREM sleep
samples. The 75 uV slow-wave rule labelled 89 % of the epochs after N2
onset in Helsinki toddlers (16-36 months) as N3 and was never validated
against technician-scored stages (biomarcadores-tea E13, usar_n3 = false).

spindles_n2 and spindles_n3 become spindles; the four N2/N3 age scenarios
become eeg-spindles and eeg-spindle-topography. The director's flag for a
posterior rhythm near the sigma band is kept as the rhythm_near_sigma
feature. Reasons: no-sleep under one minute of sleep, else no-spindles.
2026-12-03 20:47:28 -06:00

460 lines
13 KiB
TypeScript

import type { Analysis } from '../api/models/analysis';
import type { Figure } from '../plot';
import { PALETTE } from '../plot';
import { BIOMARKER_NAMES, OUTCOME_NAMES, ZONE_NAMES } from '../eeg-labels';
import { logAxis } from '../indicadores/figures';
interface Band {
x: number[];
y: (number | null)[];
low?: (number | null)[];
high?: (number | null)[];
}
export function bandFill(
x: number[],
low: (number | null)[],
high: (number | null)[],
colour: string,
alpha: string,
name?: string,
): Partial<Plotly.Data> {
const rows = x.flatMap((age, i) =>
low[i] != null && high[i] != null
? [{ age, low: low[i] as number, high: high[i] as number }]
: [],
);
return {
type: 'scatter',
mode: 'lines',
x: [...rows.map((r) => r.age), ...rows.map((r) => r.age).reverse()],
y: [...rows.map((r) => r.high), ...rows.map((r) => r.low).reverse()],
fill: 'toself',
fillcolor: `${colour}${alpha}`,
line: { width: 0 },
hoverinfo: 'skip',
name,
showlegend: name != null,
};
}
export function banded(
name: string,
b: Band,
colour: string,
dash?: 'dot',
): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) lines.push(bandFill(b.x, b.low, b.high, colour, '33'));
lines.push({
x: b.x,
y: b.y,
name,
type: 'scatter',
mode: 'lines',
line: { color: colour, dash },
});
return lines;
}
export interface Centile {
age_months: number;
p5: number | null;
p25?: number | null;
median: number | null;
p75?: number | null;
p95: number | null;
}
interface StudyPoint {
age: number;
value: number;
}
interface AgeCurveOptions {
feature?: string;
centiles?: Centile[];
points?: StudyPoint[];
waitForCentiles?: boolean;
}
const EEG_METRICS: Record<string, string> = {
'eeg-posterior-rhythm': 'posterior_rhythm',
'eeg-spindles': 'spindles',
'eeg-spindle-topography': 'spindles',
'eeg-spikes': 'paroxysmal_spikes',
'eeg-gradient': 'anteroposterior_gradient',
};
export function studyPoints(analyses: Analysis[], model: string, feature: string): StudyPoint[] {
const code = EEG_METRICS[model];
return analyses.flatMap((analysis) => {
const age = analysis.age_months;
if (age == null || !Number.isFinite(age) || age <= 0) return [];
const value =
feature === 'value'
? analysis.metrics.find((metric) => metric.code === code)?.value
: analysis.regions.find(
(region) =>
region['code'] === code && feature === region['kind'] + '_' + region['site'],
)?.['value'];
return typeof value === 'number' && Number.isFinite(value) ? [{ age, value }] : [];
});
}
interface AssociationRow {
biomarker: string;
zone: string;
outcome_code: string;
odds_ratio: number | null;
ci_low: number | null;
ci_high: number | null;
q: number | null;
}
export function interpretabilityFigures(
report: Record<string, any>,
ageCurve: AgeCurveOptions = {},
): { 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)' } },
},
},
},
];
}
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':
return [];
case 'forest':
return [
{
title: 'Asociaciones ADOS-2',
figure: {
data: (report['rows'] as AssociationRow[]).map((row) => {
const label = [row.biomarker, row.zone, row.outcome_code].filter(Boolean).join(' · ');
const odds = row.odds_ratio;
return {
x: [odds],
y: [label],
name: label,
showlegend: false,
type: 'scatter',
mode: 'markers',
marker: { color: PALETTE[4] },
error_x:
odds == null || row.ci_low == null || row.ci_high == null
? undefined
: {
type: 'data',
symmetric: false,
array: [row.ci_high - odds],
arrayminus: [odds - row.ci_low],
},
hovertemplate: '%{y}<br>OR: %{x}<br>q: ' + (row.q ?? '—') + '<extra></extra>',
};
}),
layout: {
xaxis: {
...logAxis(
(report['rows'] as AssociationRow[]).flatMap((row) => [
row.odds_ratio,
row.ci_low,
row.ci_high,
]),
),
title: { text: 'OR (IC 95 %)' },
},
yaxis: { type: 'category', automargin: true },
},
},
},
];
case 'age_curves': {
const curves = report['curves'];
const feature = ageCurve.feature ?? (curves.value ? 'value' : Object.keys(curves)[0]);
const value = curves[feature];
if (!value) return [];
const label = feature === 'value' ? '' : ` · ${feature}`;
const overlay: Partial<Plotly.Data>[] = ageCurve.points?.length
? [
{
x: ageCurve.points.map((point) => point.age),
y: ageCurve.points.map((point) => point.value),
name: 'Estudios analizados',
type: 'scatter',
mode: 'markers',
},
]
: [];
if (value.kind === 'count_rate') {
const rate = Number.isFinite(value.rate) ? value.rate : null;
return [
{
title: `Tasa de referencia: ${rate?.toFixed(3) ?? '—'} por minuto (${value.reference} estudios)${label}`,
figure: {
data: [
{
x: value.ages,
y: [rate, rate],
name: 'Tasa',
type: 'scatter',
mode: 'lines',
},
...overlay,
],
layout: {
xaxis: { title: { text: 'Edad (meses)' } },
yaxis: { title: { text: 'Eventos por minuto' } },
},
},
},
];
}
const centiles = ageCurve.centiles;
if (!centiles && ageCurve.waitForCentiles) return [];
const c = centiles
? {
age_months: centiles.map((point) => point.age_months),
median: centiles.map((point) => point.median),
p5: centiles.map((point) => point.p5),
p95: centiles.map((point) => point.p95),
}
: value.curve;
return [
{
title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
figure: {
data: [
...banded(
'Mediana',
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
PALETTE[4],
),
...overlay,
],
layout: {
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
yaxis: { title: { text: 'Valor' } },
},
},
},
];
}
case 'associations': {
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: {
...logAxis([1, ...rows.flatMap((r) => [r.odds_ratio, r.ci_low, r.ci_high])]),
title: { text: 'Razón de momios (escala 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 [];
}
}
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: {
hovermode: 'x unified',
xaxis: { title: { text: 'Meses desde el diagnóstico' }, hoverformat: '.0f' },
yaxis: { title: { text: yTitle }, tickformat: '.1~%', hoverformat: '.1%' },
},
},
};
}
function points(
name: string,
x: number[],
p: { S: number[]; low: number[]; high: number[] },
): Partial<Plotly.Data> {
return {
x,
y: p.S,
error_y: {
type: 'data',
symmetric: false,
array: p.high.map((h, i) => h - p.S[i]),
arrayminus: p.S.map((v, i) => v - p.low[i]),
},
name,
type: 'scatter',
mode: 'markers',
marker: { color: PALETTE[4], size: 9 },
};
}