import { bandFill, type Centile } from '../gobernanza/figures'; import { valueAxis } from '../indicadores/figures'; import { Figure, PALETTE } from '../plot'; import { Metric, Pair, Site, Study, TeaStep, zoneLabel } from './tea-data'; const DAY = 24 * 60 * 60 * 1000; const day = (iso: string): string => { const [y, m, d] = iso.slice(0, 10).split('-'); return `${d}/${m}/${y}`; }; export function timeline(steps: TeaStep[]): Figure | null { const done = steps.filter((step): step is TeaStep & { date: string } => Boolean(step.completed && step.date), ); if (!done.length) return null; const spans = done.slice(1).map((step, i) => ({ from: done[i], to: step })); const last = done.at(-1)!.date; return { data: [ { type: 'scatter', mode: 'lines+markers', line: { dash: 'dot', color: PALETTE[6], width: 1.5 }, x: done.map((step) => step.date), y: done.map((step) => step.label), marker: { symbol: 'diamond', size: 16, color: PALETTE[0], line: { color: '#17324d', width: 1 }, }, customdata: done.map((step) => day(step.date)), hovertemplate: '%{y} · %{customdata}', showlegend: false, }, ], layout: { showlegend: false, margin: { l: 140, r: 90, t: 16, b: 40 }, xaxis: { type: 'date', tickformat: '%d/%m/%Y', ...(done.every((step) => step.date === last) ? { range: [ new Date(Date.parse(last) - 30 * DAY).toISOString().slice(0, 10), new Date(Date.parse(last) + 30 * DAY).toISOString().slice(0, 10), ], } : {}), }, yaxis: { type: 'category', categoryorder: 'array', categoryarray: steps.map((step) => step.label).reverse(), range: [-0.5, steps.length - 0.5], fixedrange: true, }, annotations: [ ...spans.map((span) => ({ x: new Date((Date.parse(span.from.date) + Date.parse(span.to.date)) / 2) .toISOString() .slice(0, 10), y: span.to.label, yshift: 14, showarrow: false, text: `${Math.round((Date.parse(span.to.date) - Date.parse(span.from.date)) / DAY)} días`, })), ...steps .filter((step) => !step.completed) .map((step) => ({ x: 1, xref: 'paper' as const, xanchor: 'right' as const, y: step.label, showarrow: false, font: { color: PALETTE[6] }, text: 'Pendiente', })), ], }, }; } export function headMapGeometry() { const electrodes: Record = { Fp1: [-0.25, 0.77], Fp2: [0.25, 0.77], F7: [-0.65, 0.47], F3: [-0.33, 0.4], Fz: [0, 0.38], F4: [0.33, 0.4], F8: [0.65, 0.47], T3: [-0.8, 0], C3: [-0.4, 0], Cz: [0, 0], C4: [0.4, 0], T4: [0.8, 0], T5: [-0.65, -0.47], P3: [-0.33, -0.4], Pz: [0, -0.38], P4: [0.33, -0.4], T6: [0.65, -0.47], O1: [-0.25, -0.77], O2: [0.25, -0.77], }; const grid = Array.from({ length: 41 }, (_, i) => (i - 20) / 20); const inside = grid.map((y) => grid.map((x) => x * x + y * y <= 1)); const boundary = Array.from({ length: 96 }, (_, i) => { const angle = (-2 * Math.PI * i) / 96; return `${i ? 'L' : 'M'} ${Math.cos(angle).toFixed(4)} ${Math.sin(angle).toFixed(4)}`; }).join(' '); const line = { color: '#17324d', width: 2 }; const shapes: NonNullable['shapes']> = [ { type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${boundary} Z`, fillcolor: '#ffffff', line: { width: 0 }, }, { type: 'circle', x0: -1, x1: 1, y0: -1, y1: 1, line }, { type: 'path', path: 'M -0.13 0.99 L 0 1.13 L 0.13 0.99', line }, { type: 'path', path: 'M -0.99 0.14 Q -1.1 0.12 -1.08 0 Q -1.1 -0.12 -0.99 -0.14', line }, { type: 'path', path: 'M 0.99 0.14 Q 1.1 0.12 1.08 0 Q 1.1 -0.12 0.99 -0.14', line }, ]; return { electrodes, grid, inside, shapes }; } export function headMap(sites: Site[]): Figure { const { electrodes, grid, inside, shapes } = headMapGeometry(); const zones: Record = { global: [0, 0], posterior: [0, -0.72], frontal_left: [-0.5, 0.62], frontal_right: [0.5, 0.62], frontal_midline: electrodes['Fz'], central: electrodes['Cz'], parietal: electrodes['Pz'], temporal_left: [-0.82, -0.25], temporal_right: [0.82, -0.25], occipital: [0, -0.86], }; const samples = sites.flatMap((site) => { const point = (site.kind === 'electrode' ? electrodes : zones)[site.name]; return point && site.z != null && Number.isFinite(site.z) ? [{ point, z: site.z }] : []; }); const data: Figure['data'] = []; if (samples.length) { const surface = grid.map((y, row) => grid.map((x, col) => { if (!inside[row][col]) return null; let total = 0; let weights = 0; for (const { point, z } of samples) { const distanceSquared = (x - point[0]) ** 2 + (y - point[1]) ** 2; if (distanceSquared < 1e-9) return z; if (distanceSquared > 0.45 ** 2) continue; total += z / distanceSquared; weights += 1 / distanceSquared; } return weights ? total / weights : null; }), ); const limit = Math.max(2, ...samples.map((site) => Math.abs(site.z))); data.push({ type: 'contour', x: grid, y: grid, z: surface, zmin: -limit, zmax: limit, colorscale: [ [0, '#4269c2'], [0.5, '#f7f7f7'], [1, '#c24269'], ], connectgaps: false, contours: { coloring: 'heatmap', showlines: true }, line: { width: 0.5, color: 'rgba(8,24,57,.3)' }, hoverinfo: 'skip', colorbar: { title: { text: 'z' } }, }); } const markers = Object.entries(electrodes); data.push({ type: 'scatter', mode: 'text+markers', name: 'Electrodos', x: markers.map(([, point]) => point[0]), y: markers.map(([, point]) => point[1]), text: markers.map(([name]) => name), textposition: 'top center', textfont: { size: 9, color: '#17324d' }, marker: { color: '#17324d', size: 5 }, hovertemplate: '%{text}', }); return { data, layout: { showlegend: false, xaxis: { visible: false, range: [-1.25, 1.25], constrain: 'domain' }, yaxis: { visible: false, range: [-1.13, 1.18], scaleanchor: 'x', scaleratio: 1 }, shapes, }, }; } export function ageNorm(rows: Centile[], metric: Metric, age: number): Figure { const x = rows.map((row) => row.age_months); return { data: [ bandFill( x, rows.map((row) => row.p5), rows.map((row) => row.p95), PALETTE[4], '29', ), bandFill( x, rows.map((row) => row.p25 ?? null), rows.map((row) => row.p75 ?? null), PALETTE[4], '52', ), { type: 'scatter', mode: 'lines', name: 'Mediana', x, y: rows.map((row) => row.median), line: { color: PALETTE[4] }, }, { type: 'scatter', mode: 'markers', name: 'Paciente', x: [age], y: [metric.value ?? null], marker: { size: 10, color: PALETTE[2] }, }, ], layout: { xaxis: { title: { text: 'Edad (meses)' }, ...valueAxis([age]) }, yaxis: { title: { text: metric.unit ?? 'Valor' }, ...valueAxis([metric.value, ...rows.flatMap(({ p5, median, p95 }) => [p5, median, p95])]), }, }, }; } type SingleTrace = Figure & { data: [Partial & { x: number[] }] }; export function forest(pairs: Pair[], alteredOnly: boolean): SingleTrace { const visible = pairs.filter( (p): p is Pair & { odds: number } => (!alteredOnly || p.altered) && p.odds != null && p.odds > 0, ); const intervals = (bound: 'low' | 'high') => visible.map((p) => { const value = p[bound]; return value != null && value > 0 ? Math.abs(value - p.odds) : 0; }); return { data: [ { type: 'scatter', mode: 'markers', x: visible.map((p) => p.odds), y: visible.map((p) => p.title), error_x: { type: 'data', symmetric: false, array: intervals('high'), arrayminus: intervals('low'), }, marker: { color: PALETTE[4], size: 8 }, }, ], layout: { xaxis: { type: 'log', title: { text: 'Razón de momios (OR) · IC 95 %' } }, yaxis: { autorange: 'reversed', automargin: true }, shapes: [ { type: 'line', x0: 1, x1: 1, y0: 0, y1: 1, yref: 'paper', line: { dash: 'dot', color: PALETTE[6] }, }, ], }, }; } export function zBars(eeg: Study): SingleTrace { const rows = eeg.metrics .flatMap((metric) => [ { title: `${metric.title} · Global`, z: metric.z }, ...metric.sites .filter((s) => s.kind === 'zone') .map((s) => ({ title: `${metric.title} · ${zoneLabel(s.name)}`, z: s.z, })), ]) .filter((s): s is { title: string; z: number } => s.z != null); const limit = Math.max(2.2, ...rows.map((s) => Math.abs(s.z) * 1.1)); return { data: [ { type: 'bar', orientation: 'h', x: rows.map((s) => s.z), y: rows.map((s) => s.title), marker: { color: rows.map((s) => (Math.abs(s.z) < 2 ? PALETTE[4] : PALETTE[2])) }, }, ], layout: { xaxis: { title: { text: 'Puntuación z' }, ...valueAxis([-limit, limit]), range: [-limit, limit], }, yaxis: { autorange: 'reversed', automargin: true }, shapes: [ { type: 'rect', x0: -2, x1: 2, y0: 0, y1: 1, yref: 'paper', layer: 'below', line: { width: 0 }, fillcolor: '#42c29c33', }, ], }, }; } const ALTERED_Z = 2; const expit = (x: number) => 1 / (1 + Math.exp(-x)); export function probabilityCurve(pair: Pair): Figure { const data: Figure['data'] = []; const extent = Math.max(4, Math.ceil(Math.abs(pair.z ?? 0)) + 1); const modelled = pair.reference != null && pair.reference > 0 && pair.reference < 1 && pair.odds && pair.odds > 0; if (modelled) { const intercept = Math.log(pair.reference! / (1 - pair.reference!)); const slope = Math.log(pair.odds!); const x = Array.from({ length: 81 }, (_, i) => (extent * (i - 40)) / 40); data.push({ type: 'scatter', mode: 'lines', name: 'Modelo', x, y: x.map((z) => 100 * expit(intercept + slope * z)), line: { color: PALETTE[4], width: 2.5 }, hovertemplate: 'z = %{x:.1~f}: %{y:.1~f} %', }); } if (pair.z != null && pair.probability != null) { data.push({ type: 'scatter', mode: 'markers', name: 'Paciente', x: [pair.z], y: [100 * pair.probability], marker: { size: 10, color: PALETTE[2] }, }); } if (pair.reference != null) { data.push({ type: 'scatter', mode: 'markers', name: 'Referencia', x: [0], y: [100 * pair.reference], marker: { size: 10, color: PALETTE[4], symbol: 'diamond-open' }, }); } const zone = (x0: number, x1: number) => ({ type: 'rect' as const, xref: 'x' as const, yref: 'paper' as const, x0, x1, y0: 0, y1: 1, fillcolor: 'rgba(194,66,105,0.10)', line: { width: 0 }, layer: 'below' as const, }); return { data, layout: { xaxis: { title: { text: 'Puntuación z' }, ...valueAxis([-extent, extent]), range: [-extent, extent], }, yaxis: { title: { text: 'Probabilidad (%)' }, ...valueAxis([0, 100]), range: [0, 100] }, ...(modelled ? { shapes: [zone(-extent, -ALTERED_Z), zone(ALTERED_Z, extent)] } : {}), }, }; }