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)[]; } function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial[] { const lines: Partial[] = []; if (b.low && b.high) { lines.push({ x: [...b.x, ...[...b.x].reverse()], y: [...b.high, ...[...b.low].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, 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, ): { 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}%{y}', 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%' }, }, }, }; } function points( name: string, x: number[], p: { S: number[]; low: number[]; high: number[] }, ): Partial { 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 }, }; }