bd897baa2d
rebuild's shell, auth and non-TEA pages; tea/parity's TEA pages on tea/parity's API. - Routes: rebuild's signed-in tree; the TEA risk page joins it (domainAllowed reads the route's data domain when the path has no :domain). - Indicadores: rebuild's header and its generic Resumen/Trazabilidad/Definiciones tabs (TEA as the reference page, fed by tea/parity's measures); TEA Seguimiento and Análisis de riesgo render tea/parity's tea-list inside rebuild's tab-seguimiento/tab-riesgos, which keep rebuild's CaCu/CaMa lists and patient search. rebuild's tab-riesgos-tea read rebuild's TEA Patient extensions, which are gone with its backend; tea-list already shows that list from tea/parity's FHIR search, so it is deleted rather than ported (its look is the base for T8/T9). - Paciente: rebuild's record for CaCu/CaMa; TEA delegates to tea/parity's TeaRecord. rebuild's inline TEA sections read its EEG detail endpoint and are removed. - Gobernanza: tea/parity's page (execution, models with checks/lineage, bundles, training, studies, preview) until T13; model headings use rebuild's model titles. figures.ts: rebuild's scenarios (drawn in the record) plus tea/parity's association forest. - plot.ts: rebuild's layout helpers on tea/parity's partial Plotly bundle. - Conectar: rebuild's KINDS/HELP with an entry for tea/parity's edf node. - Dead code removed: measures boxes/sankey (tea/parity's old TEA tab), eeg-labels headMap/byDeviation/LEVEL_NAMES/METRIC_NAMES (rebuild's TEA record), e2e/layout.ts. - e2e: tea/parity's TEA cases, signed in; rebuild's CaCu/CaMa/site cases need their hospitals loaded and come back with the page suite (T16). - openapi.json and src/app/api: regenerated in the next commit.
428 lines
13 KiB
TypeScript
428 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';
|
|
|
|
interface Band {
|
|
x: number[];
|
|
y: (number | null)[];
|
|
low?: (number | null)[];
|
|
high?: (number | 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({
|
|
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;
|
|
}
|
|
|
|
export interface Centile {
|
|
age_months: number;
|
|
p5: number | null;
|
|
median: 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-n2': 'spindles_n2',
|
|
'eeg-spindle-topography-n2': 'spindles_n2',
|
|
'eeg-spindles-n3': 'spindles_n3',
|
|
'eeg-spindle-topography-n3': 'spindles_n3',
|
|
'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: { type: 'log', 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': {
|
|
// 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 [];
|
|
}
|
|
}
|
|
|
|
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<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 },
|
|
};
|
|
}
|