import { type Figure, PALETTE } from '../plot';
import { name, type Reading } from './measures';
import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
export const SHORT = '.1~f';
const SIGNIFICANT = '.2~r';
export const percentAxis = {
type: 'linear' as const,
ticksuffix: ' %',
tickformat: '.0f',
hoverformat: SHORT,
range: [0, 110] as [number, number],
dtick: 20,
};
const count = (n: number) => n.toLocaleString('es-MX');
const percent = (n: number) => (Math.round(n * 10) / 10).toLocaleString('es-MX');
function rgba(hex: string, alpha: number): string {
const v = parseInt(hex.slice(1), 16);
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
}
export function routeFigure(steps: { label: string; r: Reading | undefined }[]): Figure {
const shown = steps.filter((s) => s.r?.score !== undefined);
return {
data: [
{
type: 'bar',
orientation: 'h',
y: shown.map(
(s) => `${s.label}
n = ${count(s.r!.populations['measure-observation'] ?? 0)}`,
),
x: shown.map((s) => s.r!.score!),
marker: { color: OLIVE },
error_x: {
type: 'data',
symmetric: false,
thickness: 1.5,
width: 6,
array: shown.map((s) => (s.r!.high ?? s.r!.score!) - s.r!.score!),
arrayminus: shown.map((s) => s.r!.score! - (s.r!.low ?? s.r!.score!)),
},
hovertemplate: `%{y}
mediana %{x:${SHORT}} días`,
} as Partial,
],
layout: {
showlegend: false,
xaxis: {
title: { text: 'Días' },
rangemode: 'tozero',
zeroline: false,
...valueAxis(shown.flatMap((s) => [s.r!.score, s.r!.high])),
},
yaxis: { autorange: 'reversed', type: 'category', automargin: true },
},
};
}
function counted(r: Reading, code: string): number {
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
}
export function nestedDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
const groups = catalog.groups.map((g) =>
catalog.categories.reduce((n, c, i) => n + (c.group === g.id ? values[i] : 0), 0),
);
const faded = new Set(catalog.faded ?? []);
const share = (n: number) => (total ? `${percent((100 * n) / total)} %` : '');
const common = {
type: 'pie',
sort: false,
direction: 'clockwise',
rotation: 0,
showlegend: false,
textinfo: 'text',
textposition: 'inside',
insidetextorientation: 'horizontal',
};
return {
data: [
{
...common,
name: 'centro',
values: [1],
labels: ['centro'],
domain: { x: [0.32, 0.68], y: [0.32, 0.68] },
text: [`${count(total)}
${center}`],
marker: { colors: ['#FFFFFF'] },
hoverinfo: 'skip',
},
{
...common,
name: 'grupos',
values: groups,
labels: catalog.groups.map((g) => g.label),
hole: 0.62,
domain: { x: [0.16, 0.84], y: [0.16, 0.84] },
text: groups.map((n, i) =>
total && n / total >= 0.05 ? `${catalog.groups[i].label}
${share(n)}` : '',
),
marker: {
colors: catalog.groups.map((g) =>
rgba(
g.color,
catalog.categories.some((c) => c.group === g.id && !faded.has(c.code)) ? 1 : 0.3,
),
),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}
%{value:d} (%{percent:.1~%})',
},
{
...common,
name: 'categorias',
values,
labels: catalog.categories.map((c) => c.label),
hole: 0.74,
domain: { x: [0, 1], y: [0, 1] },
insidetextorientation: 'tangential',
text: values.map((n, i) => (total && n / total >= 0.05 ? catalog.categories[i].label : '')),
marker: {
colors: catalog.categories.map((c) => rgba(c.color, faded.has(c.code) ? 0.3 : 1)),
line: { color: '#FFFFFF', width: 2 },
},
hovertemplate: '%{label}
%{value:d} (%{percent:.1~%})',
},
] as Partial[],
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
};
}
export function scenarioBars(
r: Reading,
catalog: Catalog,
stratum: string,
label: (code: string) => string,
): Figure {
const cells = r.strata[`${stratum}-category`] ?? {};
const scenarios = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))].sort((a, b) =>
label(a).localeCompare(label(b), 'es'),
);
const n = (s: string, c: string) => cells[`${s}|${c}`]?.['initial-population'] ?? 0;
const totals = scenarios.map((s) => catalog.categories.reduce((t, c) => t + n(s, c.code), 0));
const y = scenarios.map(label);
return {
data: catalog.categories.map((c) => ({
type: 'bar',
orientation: 'h',
name: c.label,
y,
x: scenarios.map((s, i) => (totals[i] ? (100 * n(s, c.code)) / totals[i] : 0)),
customdata: scenarios.map((s) => n(s, c.code)),
marker: { color: c.color },
hovertemplate: `${c.label}
%{y}: %{customdata} (%{x:.1~f} %)`,
})) as Partial[],
layout: {
barmode: 'stack',
xaxis: {
title: { text: '% de pacientes del escenario con resultado' },
...percentAxis,
range: [0, 100.5],
dtick: 20,
},
yaxis: {
type: 'category',
autorange: 'reversed',
categoryorder: 'array',
categoryarray: y,
automargin: true,
},
},
};
}
function wilson(k: number, n: number): [number, number] {
const z = 1.959963984540054;
const p = k / n;
const d = 1 + (z * z) / n;
const c = (p + (z * z) / (2 * n)) / d;
const h = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / d;
return [100 * (c - h), 100 * (c + h)];
}
export function rateDots(
r: Reading,
spec: { stratum: string; rows: Category[]; positive: string[]; axis: string; colored?: boolean },
): Figure {
const cells = r.strata[`${spec.stratum}-category`] ?? {};
const rows = spec.rows.map((row) => {
const of = Object.entries(cells).filter(([k]) => k.split('|')[0] === row.code);
const biopsied = of.filter(([k]) => !['no_biopsy', 'no_data'].includes(k.split('|')[1]));
const den = biopsied.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const k = biopsied
.filter(([key]) => spec.positive.includes(key.split('|')[1]))
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0);
const rate = den ? (100 * k) / den : null;
const [low, high] = den ? wilson(k, den) : [null, null];
return { row, k, den, rate, low, high };
});
const y = rows.map((x) => x.row.label);
return {
data: [
{
type: 'scatter',
mode: 'markers',
name: 'tasas',
y,
x: rows.map((x) => x.rate),
marker: { size: 12, color: spec.colored ? rows.map((x) => x.row.color) : ROSE },
cliponaxis: false,
error_x: {
type: 'data',
symmetric: false,
color: ROSE,
thickness: 2,
width: 6,
array: rows.map((x) => (x.rate === null ? 0 : x.high! - x.rate)),
arrayminus: rows.map((x) => (x.rate === null ? 0 : x.rate - x.low!)),
},
hovertemplate: '%{y}: %{x:.1~f} %',
} as Partial,
],
layout: {
showlegend: false,
margin: { t: 24, r: 110, b: 56, l: 56 },
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: [...y].reverse(),
automargin: true,
},
xaxis: { ...percentAxis, range: [0, 100], zeroline: false, title: { text: spec.axis } },
annotations: rows.map((x) => ({
x: 1,
xref: 'paper',
xanchor: 'left',
xshift: 8,
y: x.row.label,
yref: 'y',
showarrow: false,
align: 'left',
text: x.den
? `${percent(x.rate!)} %
${x.k}/${x.den}`
: spec.colored
? 'Sin pacientes'
: 'Sin biopsias',
})),
},
};
}
const decimal = (n: number, options: Intl.NumberFormatOptions = { maximumFractionDigits: 2 }) =>
n.toLocaleString('es-MX', options);
export function fill(template: string, r: Reading): string {
const p = r.populations;
const values: Record = {
n: count(p['initial-population'] ?? 0),
obs: count(p['measure-observation'] ?? 0),
median: r.score === undefined ? '' : decimal(r.score),
q1: decimal(r.low ?? r.score ?? 0),
q3: decimal(r.high ?? r.score ?? 0),
num: count(p['numerator'] ?? 0),
den: count(p['denominator'] ?? 0),
pct: r.score === undefined ? '' : percent(r.score * 100),
};
return template.replace(/\{(\w+)\}/g, (_, k) => values[k] ?? '');
}
export function boxFigure(r: Reading, period: string): Figure {
const q1 = r.low ?? r.score!;
const q3 = r.high ?? r.score!;
return {
data: [
{
type: 'box',
name: 'Total',
x: [period],
q1: [q1],
median: [r.score!],
q3: [q3],
lowerfence: [q1],
upperfence: [q3],
marker: { color: '#4269C2' },
fillcolor: 'rgba(66,105,194,0.55)',
hoverinfo: 'skip',
} as Partial,
{
type: 'scatter',
mode: 'markers',
x: [period],
y: [r.score!],
customdata: [[q3, r.score!, q1]],
marker: { size: 40, opacity: 0 },
hovertemplate: `Q3: %{customdata[0]:${SHORT}}
Mediana: %{customdata[1]:${SHORT}}
Q1: %{customdata[2]:${SHORT}}`,
},
],
layout: {
showlegend: false,
yaxis: { title: { text: 'días' }, rangemode: 'tozero', ...valueAxis([q1, r.score!, q3]) },
},
};
}
export function shareDonut(r: Reading, catalog: Catalog, center: string): Figure {
const values = catalog.categories.map((c) => counted(r, c.code));
const total = values.reduce((a, b) => a + b, 0);
return {
data: [
{
type: 'pie',
hole: 0.54,
sort: false,
direction: 'clockwise',
labels: catalog.categories.map((c) => c.label),
values,
marker: {
colors: catalog.categories.map((c) => c.color),
line: { color: '#FFFFFF', width: 2 },
},
texttemplate: values.map((v) => (v ? '%{label}
%{percent:.1~%}' : '')),
textposition: 'outside',
hovertemplate: '%{label}
%{value:d} (%{percent:.1~%})',
} as Partial,
],
layout: {
showlegend: false,
margin: { t: 30, l: 60, r: 60, b: 30 },
annotations: [
{
text: `${count(total)}
${center}`,
showarrow: false,
x: 0.5,
y: 0.5,
xref: 'paper',
yref: 'paper',
},
],
},
};
}
export function countBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const y = catalog.categories.map((c) => c.label);
return {
data: [
{
type: 'bar',
orientation: 'h',
name: period,
y,
x: catalog.categories.map((c) => counted(r, c.code)),
marker: { color: catalog.categories.map((c) => c.color) },
texttemplate: '%{x:d}',
textposition: 'outside',
hovertemplate: '%{y}: %{x:d}',
} as Partial,
],
layout: {
showlegend: false,
xaxis: {
title: { text: axis },
rangemode: 'tozero',
...valueAxis(catalog.categories.map((c) => counted(r, c.code))),
},
yaxis: { type: 'category', autorange: 'reversed', automargin: true },
},
};
}
const TEA_SEXES = [
{ code: 'male', color: '#4269C2' },
{ code: 'female', color: ROSE },
];
const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
function ageBands(cells: Reading['strata'][string]): string[] {
const bands = Object.keys(cells)
.map((key) => key.split('|'))
.filter(([, code]) => TEA_SEXES.some((sex) => sex.code === code))
.map(([band]) => band);
return [...new Set(bands)].sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
}
export function ageStack(r: Reading, names: [string, string]): Figure {
const cells = r.strata['age_sex'] ?? {};
const bands = ageBands(cells);
const x = bands.map(ageLabel);
return {
data: TEA_SEXES.flatMap(({ code, color }) => {
const rows = bands.map((band) => cells[`${band}|${code}`]);
const totals = rows.map((row) => row?.['denominator'] ?? 0);
const confirmed = rows.map((row, j) =>
totals[j] ? (100 * (row?.['numerator'] ?? 0)) / totals[j] : 0,
);
return [confirmed, totals.map((total, j) => (total ? 100 - confirmed[j] : 0))].map(
(y, i) => ({
type: 'bar',
name: `${name(code)} · ${names[i]}`,
offsetgroup: code,
x,
y,
marker: { color: i ? rgba(color, 0.25) : color },
text: y.map((share) => (share ? `${percent(share)} %` : '')),
textposition: 'inside',
hovertemplate: `%{x}
%{fullData.name}: %{y:${SHORT}} %`,
}),
) as Partial[];
}),
layout: {
barmode: 'stack',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: '% de pacientes' }, ...percentAxis },
},
};
}
export function ageShare(r: Reading, axis: string): Figure {
const cells = r.strata['age_sex'] ?? {};
const bands = ageBands(cells);
const x = bands.map(ageLabel);
return {
data: TEA_SEXES.map(({ code, color }) => {
const rows = bands.map((band) => cells[`${band}|${code}`]);
const shares = rows.map((row) =>
row?.['denominator'] ? (100 * (row['numerator'] ?? 0)) / row['denominator'] : null,
);
return {
type: 'bar',
name: name(code),
x,
y: shares,
marker: { color },
text: shares.map((share) => (share === null ? '' : `${percent(share)} %`)),
textposition: 'outside',
hovertemplate: '%{x}: %{text}%{fullData.name}',
};
}),
layout: {
barmode: 'group',
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
yaxis: { title: { text: axis }, ...percentAxis },
},
};
}
export function valueAxis(values: Iterable) {
const found = [...values].filter((v): v is number => v != null && Number.isFinite(v));
const counts = found.every(Number.isInteger);
const narrow = found.length > 0 && Math.max(...found) - Math.min(0, ...found) <= 5;
return {
type: 'linear' as const,
tickformat: counts ? 'd' : SIGNIFICANT,
hoverformat: counts ? 'd' : '.3~r',
...(counts && narrow ? { dtick: 1 } : {}),
};
}
export function logAxis(values: Iterable) {
const found = [...values].filter((v): v is number => v != null && Number.isFinite(v) && v > 0);
const tickvals: number[] = [];
if (found.length) {
const first = Math.floor(Math.log10(Math.min(...found)));
const last = Math.ceil(Math.log10(Math.max(...found)));
for (let decade = first; decade <= last; decade++) {
for (const multiplier of [1, 2, 3, 5, 7]) {
if (decade === last && multiplier > 1) continue;
const value = Number(`${multiplier}e${decade}`);
if (value > 0 && Number.isFinite(value)) tickvals.push(value);
}
}
}
return {
type: 'log' as const,
tickmode: 'array' as const,
tickvals,
ticktext: tickvals.map((v) => decimal(v, { maximumSignificantDigits: 1, useGrouping: false })),
hoverformat: SHORT,
};
}
export function historyFigure(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
line: string,
xTitle: string,
): Figure {
const x = series.map((s) => s.label);
const layout = (y: string, values: (number | null)[]) => ({
xaxis: {
title: { text: xTitle },
type: 'category' as const,
categoryorder: 'array' as const,
categoryarray: x,
},
yaxis: { title: { text: y }, ...valueAxis(values) },
});
if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
const declared = panel.series ?? [];
const named = [
...declared,
...found
.filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
];
const data = named.map((c) => ({
type: 'bar' as const,
name: c.label,
x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color },
}));
const totals = x.map((_, i) => data.reduce((sum, trace) => sum + trace.y[i], 0));
return {
data,
layout: { ...layout(panel.axis ?? 'Pacientes', [0, ...totals]), barmode: 'stack' },
};
}
if (panel.kind === 'rate') {
const lines = [
{ name: 'Total', color: line, at: (r?: Reading) => r?.score },
...TEA_SEXES.map(({ code, color }) => ({
name: name(code),
color,
at: (r?: Reading) => r?.rates?.['sex']?.[code],
})),
];
const data = lines.map(({ name: label, color, at }) => ({
x,
y: series.map((s) => at(s.r) ?? null),
mode: 'lines+markers' as const,
name: label,
line: { color },
marker: { color },
}));
return {
data,
layout: layout(
panel.axis ?? '',
data.flatMap((d) => d.y),
),
};
}
const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k);
const highs = series.map((s) => at(s.r?.high));
const lows = series.map((s) => at(s.r?.low));
const scores = series.map((s) => at(s.r?.score));
const bandName = panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil';
return {
data: [
...bandRuns(highs, lows).map((run, i) => ({
x: [...run.map((j) => x[j]), ...[...run].reverse().map((j) => x[j])],
y: [...run.map((j) => highs[j]), ...[...run].reverse().map((j) => lows[j])],
mode: 'lines' as const,
fill: 'toself' as const,
fillcolor: line + '33',
line: { width: 0 },
name: bandName,
legendgroup: 'band',
showlegend: i === 0,
hoverinfo: 'skip' as const,
})),
{
x,
y: scores,
mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line },
marker: { color: line },
},
],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días', [
...highs,
...lows,
...scores,
]),
};
}
export function bandRuns(highs: (number | null)[], lows: (number | null)[]): number[][] {
const runs: number[][] = [];
let run: number[] = [];
highs.forEach((high, i) => {
if (high != null && lows[i] != null) run.push(i);
else if (run.length) {
runs.push(run);
run = [];
}
});
if (run.length) runs.push(run);
return runs;
}
export function sexCountBars(r: Reading, catalog: Catalog, axis: string, period: string): Figure {
const base = countBars(r, catalog, axis, period);
const cells = r.strata['sex-category'] ?? {};
return {
data: TEA_SEXES.map(({ code, color }) => ({
...base.data[0],
name: name(code),
marker: { color },
x: catalog.categories.map((c) => cells[`${code}|${c.code}`]?.['initial-population'] ?? 0),
hovertemplate: '%{y}: %{x:d}%{fullData.name}',
})) as Partial[],
layout: { ...base.layout, barmode: 'group', showlegend: true },
};
}
const STOPPED = '#888888';
export function teaSankey(r: Reading): Figure {
const [mchat, psychology, neuro, eeg] = [
'mchat_only',
'psychology',
'neuropediatrics',
'eeg',
].map((code) => counted(r, code));
const nodes = [
{ label: 'M-CHAT', color: '#B8433A', value: mchat + psychology + neuro + eeg },
{ label: 'Evaluación
psicológica', color: '#D0B778', value: psychology + neuro + eeg },
{ label: 'Evaluación
neuropediátrica', color: '#7184A2', value: neuro + eeg },
{ label: 'EEG de
buena calidad', color: OLIVE, value: eeg },
{ label: 'Se quedó en evaluación
neuropediátrica', color: STOPPED, value: neuro },
{ label: 'Se quedó en evaluación
psicológica', color: STOPPED, value: psychology },
{ label: 'Se quedó en M-CHAT', color: STOPPED, value: mchat },
];
const shown = nodes.flatMap((node, index) => (node.value > 0 ? [index] : []));
const position = new Map(shown.map((index, place) => [index, place]));
const flows: [number, number][] = [
[0, 1],
[0, 6],
[1, 2],
[1, 5],
[2, 3],
[2, 4],
];
const links = flows.flatMap(([source, target]) =>
nodes[target].value > 0
? [{ source: position.get(source)!, target: position.get(target)!, index: target }]
: [],
);
const hovertemplate = '%{label}
%{value} pacientes';
return {
data: [
{
type: 'sankey',
arrangement: 'fixed',
node: {
label: shown.map((index) => `${nodes[index].label} · ${count(nodes[index].value)}`),
color: shown.map((index) => nodes[index].color),
pad: 36,
hovertemplate,
},
link: {
source: links.map(({ source }) => source),
target: links.map(({ target }) => target),
value: links.map(({ index }) => nodes[index].value),
color: links.map(({ index }) => rgba(nodes[index].color, 0.45)),
label: links.map(({ index }) => nodes[index].label.replace('
', ' ')),
hovertemplate,
},
} as Partial,
],
layout: { font: { size: 12 }, margin: { l: 20, r: 20, t: 24, b: 24 } },
};
}
const RATE_UNIT = 'por 10 000 niños';
const perTenThousand = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 1 });
function prevalenceCounts(r: Reading, sex?: string): { confirmed: number; total: number } {
if (!sex) {
return { confirmed: counted(r, 'confirmed'), total: r.populations['initial-population'] ?? 0 };
}
return {
confirmed: r.strata['sex-category']?.[`${sex}|confirmed`]?.['initial-population'] ?? 0,
total: r.strata['sex']?.[sex]?.['initial-population'] ?? 0,
};
}
export function prevalenceHeadline(r: Reading) {
if (r.score === undefined) return undefined;
const { confirmed, total } = prevalenceCounts(r);
return {
value: perTenThousand(r.score),
detail: `${RATE_UNIT} · ${count(confirmed)} confirmados de ${count(total)} niños`,
};
}
export function teaSexBars(r: Reading): Figure {
const x = TEA_SEXES.map(({ code }) => name(code));
const y = TEA_SEXES.map(({ code }) => r.rates?.['sex']?.[code] ?? 0);
return {
data: [
{
type: 'bar',
name: 'Prevalencia registrada',
x,
y,
marker: { color: TEA_SEXES.map(({ color }) => color) },
text: y.map((value) => perTenThousand(value)),
textposition: 'outside',
customdata: TEA_SEXES.map(({ code }) => {
const { confirmed, total } = prevalenceCounts(r, code);
return [confirmed, total];
}),
hovertemplate: `%{x}
%{text} ${RATE_UNIT}
%{customdata[0]} confirmados de %{customdata[1]} niños`,
},
],
layout: {
showlegend: false,
xaxis: { title: { text: 'Sexo' }, type: 'category' },
yaxis: {
title: { text: 'Casos por 10 000 niños' },
rangemode: 'tozero',
...valueAxis(y),
},
},
};
}
export function teaAlterations(r: Reading): Figure {
const rows = [['', r.populations] as const, ...Object.entries(r.strata['alteration'] ?? {})];
const customdata = rows.map(([, c]) => [c['numerator'], c['denominator']]);
const rates = customdata.map(([n, total]) => (total ? (100 * n) / total : 0));
return {
data: [
{
type: 'bar',
x: rows.map(([code]) => (code ? name(code) : 'Alguna alteración')),
y: rates,
marker: { color: rows.map((_, i) => PALETTE[(i + 1) % PALETTE.length]) },
text: rates.map((rate) => `${percent(rate)} %`),
textposition: 'outside',
customdata,
hovertemplate:
'%{x}
%{text} (%{customdata[0]} de %{customdata[1]} niños)',
} as Partial,
],
layout: {
xaxis: { type: 'category', title: { text: 'Alteración del EEG' } },
yaxis: {
...percentAxis,
title: { text: '% de niños con EEG de buena calidad' },
},
},
};
}