478 lines
16 KiB
TypeScript
478 lines
16 KiB
TypeScript
import { type Figure, PALETTE } from '../plot';
|
|
import { reconciles } from './bars';
|
|
import { name, type Reading } from './measures';
|
|
import type { Catalog, Category, HistoryPanel } from './pages';
|
|
|
|
const OLIVE = '#A8C243';
|
|
const ROSE = '#C24269';
|
|
|
|
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})`;
|
|
}
|
|
|
|
/** A category's count in the report (the composition's `category` stratum). */
|
|
function counted(r: Reading, code: string): number {
|
|
return r.strata['category']?.[code]?.['initial-population'] ?? 0;
|
|
}
|
|
|
|
/** Groups inside, their categories outside, the total in the centre. */
|
|
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: [`<b>${count(total)}</b><br>${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}<br>${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}<br>%{value} (%{percent})<extra></extra>',
|
|
},
|
|
{
|
|
...common,
|
|
name: 'categorias',
|
|
values,
|
|
labels: catalog.categories.map((c) => c.label),
|
|
hole: 0.74,
|
|
domain: { x: [0, 1], y: [0, 1] },
|
|
// along the thin ring, so a label fits its slice
|
|
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}<br>%{value} (%{percent})<extra></extra>',
|
|
},
|
|
] as Partial<Plotly.Data>[],
|
|
layout: { margin: { t: 10, l: 10, r: 10, b: 10 } },
|
|
};
|
|
}
|
|
|
|
/** Each clinical scenario's results as shares of its patients, one stacked bar each. */
|
|
export function scenarioBars(
|
|
r: Reading,
|
|
catalog: Catalog,
|
|
stratum: string,
|
|
label: (code: string) => string,
|
|
/** the groups in this order (the ones the report lists, then any other) */
|
|
order?: string[],
|
|
options: {
|
|
/** draw an empty group of `order` when the counts reconcile (see `reconciles`) */
|
|
fill?: boolean;
|
|
/** a bar is the share of all the group's records, not only of those the catalog draws */
|
|
ofAll?: boolean;
|
|
} = {},
|
|
): Figure {
|
|
const cells = r.strata[`${stratum}-category`] ?? {};
|
|
const found = [...new Set(Object.keys(cells).map((k) => k.split('|')[0]))];
|
|
const listed = Object.values(cells).map((c) => c['initial-population']);
|
|
const empty = reconciles(listed, r.populations['initial-population'] ?? 0);
|
|
const scenarios = order
|
|
? [
|
|
...order.filter((s) => found.includes(s) || (options.fill && empty)),
|
|
...found.filter((s) => !order.includes(s)),
|
|
]
|
|
: found.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) =>
|
|
options.ofAll
|
|
? Object.entries(cells)
|
|
.filter(([k]) => k.split('|')[0] === s)
|
|
.reduce((t, [, c]) => t + (c['initial-population'] ?? 0), 0)
|
|
: catalog.categories.reduce((t, c) => t + n(s, c.code), 0),
|
|
);
|
|
const y = order
|
|
? scenarios.map((s, i) => `${label(s)}<br>n = ${totals[i]}`)
|
|
: 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}<br>%{y}: %{customdata} (%{x:.1f} %)<extra></extra>`,
|
|
})) as Partial<Plotly.Data>[],
|
|
layout: {
|
|
barmode: 'stack',
|
|
xaxis: {
|
|
title: {
|
|
text: order
|
|
? options.ofAll
|
|
? '% de los reportes del grupo'
|
|
: '% de pacientes con resultado'
|
|
: '% de pacientes del escenario con resultado',
|
|
},
|
|
ticksuffix: ' %',
|
|
range: [0, 100.5],
|
|
dtick: 20,
|
|
},
|
|
yaxis: {
|
|
type: 'category',
|
|
autorange: 'reversed',
|
|
categoryorder: 'array',
|
|
categoryarray: y,
|
|
automargin: true,
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
/** Wilson score interval at 95 %, in percent. */
|
|
export 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)];
|
|
}
|
|
|
|
/** Per cytology result: of the women with a biopsy, the share whose biopsy is a positive,
|
|
* with its 95 % interval; a result nobody had a biopsy for is named, not drawn. */
|
|
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:.1f} %<extra></extra>',
|
|
} as Partial<Plotly.Data>,
|
|
],
|
|
layout: {
|
|
showlegend: false,
|
|
margin: { t: 24, r: 110, b: 56, l: 56 },
|
|
yaxis: {
|
|
type: 'category',
|
|
categoryorder: 'array',
|
|
categoryarray: [...y].reverse(),
|
|
automargin: true,
|
|
},
|
|
xaxis: { range: [0, 100], ticksuffix: ' %', 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
|
|
? `<b>${percent(x.rate!)} %</b><br>${x.k}/${x.den}`
|
|
: spec.colored
|
|
? 'Sin pacientes'
|
|
: 'Sin biopsias',
|
|
})),
|
|
},
|
|
};
|
|
}
|
|
|
|
const decimal = (n: number) => n.toLocaleString('es-MX', { maximumFractionDigits: 2 });
|
|
|
|
/** A card's template filled from its measure's reading in the period: {n} counted, {obs}
|
|
* measured, {median} {q1} {q3} days, {num} {den} {pct}. */
|
|
export function fill(template: string, r: Reading): string {
|
|
const p = r.populations;
|
|
const values: Record<string, string> = {
|
|
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] ?? '');
|
|
}
|
|
|
|
/** A duration's quartile box in the period. */
|
|
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)',
|
|
hovertemplate: `Q1 ${decimal(q1)} · mediana ${decimal(r.score!)} · Q3 ${decimal(q3)} días<extra></extra>`,
|
|
} as Partial<Plotly.Data>,
|
|
],
|
|
layout: { showlegend: false, yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
|
|
};
|
|
}
|
|
|
|
/** One ring: the categories' shares, the total in the centre. */
|
|
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 },
|
|
},
|
|
// an empty slice says nothing (its label would sit on its neighbours')
|
|
texttemplate: values.map((v) => (v ? '%{label}<br>%{percent}' : '')),
|
|
textposition: 'outside',
|
|
hovertemplate: '%{label}<br>%{value} (%{percent})<extra></extra>',
|
|
} as Partial<Plotly.Data>,
|
|
],
|
|
layout: {
|
|
showlegend: false,
|
|
margin: { t: 30, l: 60, r: 60, b: 30 },
|
|
annotations: [
|
|
{
|
|
text: `<b>${count(total)}</b><br>${center}`,
|
|
showarrow: false,
|
|
x: 0.5,
|
|
y: 0.5,
|
|
xref: 'paper',
|
|
yref: 'paper',
|
|
},
|
|
],
|
|
},
|
|
};
|
|
}
|
|
|
|
/** A category's count per bar, one bar each, in the period. */
|
|
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}',
|
|
textposition: 'outside',
|
|
hovertemplate: '%{y}: %{x}<extra></extra>',
|
|
} as Partial<Plotly.Data>,
|
|
],
|
|
layout: {
|
|
showlegend: false,
|
|
xaxis: { title: { text: axis }, rangemode: 'tozero' },
|
|
yaxis: { type: 'category', autorange: 'reversed', automargin: true },
|
|
},
|
|
};
|
|
}
|
|
|
|
const AGE_COLORS = ['#A8C243', '#42C29C', '#9C42C2', '#4269C2'];
|
|
/** "16-23" as the screens say it: "16 a 23 meses". */
|
|
export const ageLabel = (band: string) => band.replace(/^(\d+)-(\d+)$/, '$1 a $2 meses');
|
|
|
|
function ages(r: Reading): [string, Record<string, number>][] {
|
|
return Object.entries(r.strata['age_group'] ?? {}).sort(
|
|
([a], [b]) => parseInt(a, 10) - parseInt(b, 10),
|
|
);
|
|
}
|
|
|
|
/** By age group: the numerator and the rest of the denominator, stacked. */
|
|
export function ageStack(r: Reading, names: [string, string]): Figure {
|
|
const rows = ages(r);
|
|
const x = rows.map(([a]) => ageLabel(a));
|
|
return {
|
|
data: [
|
|
{
|
|
type: 'bar',
|
|
name: names[0],
|
|
x,
|
|
y: rows.map(([, c]) => c['numerator'] ?? 0),
|
|
marker: { color: AGE_COLORS[0] },
|
|
},
|
|
{
|
|
type: 'bar',
|
|
name: names[1],
|
|
x,
|
|
y: rows.map(([, c]) => (c['denominator'] ?? 0) - (c['numerator'] ?? 0)),
|
|
marker: { color: AGE_COLORS[1] },
|
|
},
|
|
] as Partial<Plotly.Data>[],
|
|
layout: {
|
|
barmode: 'stack',
|
|
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
|
|
yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' },
|
|
},
|
|
};
|
|
}
|
|
|
|
/** By age group: the numerator's share of the denominator, one bar each. */
|
|
export function ageShare(r: Reading, axis: string): Figure {
|
|
const rows = ages(r);
|
|
return {
|
|
data: [
|
|
{
|
|
type: 'bar',
|
|
x: rows.map(([a]) => ageLabel(a)),
|
|
y: rows.map(([, c]) =>
|
|
c['denominator'] ? (100 * (c['numerator'] ?? 0)) / c['denominator'] : 0,
|
|
),
|
|
marker: { color: rows.map((_, i) => AGE_COLORS[i % AGE_COLORS.length]) },
|
|
texttemplate: '%{y:.1f} %',
|
|
textposition: 'outside',
|
|
hovertemplate: '%{x}: %{y:.1f} %<extra></extra>',
|
|
} as Partial<Plotly.Data>,
|
|
],
|
|
layout: {
|
|
showlegend: false,
|
|
xaxis: { title: { text: 'Grupo de edad' }, type: 'category' },
|
|
yaxis: { title: { text: axis }, range: [0, 100], ticksuffix: ' %' },
|
|
},
|
|
};
|
|
}
|
|
|
|
/** A Trazabilidad panel's figure (pages.HISTORY), as the old tab drew it: stacked bars by
|
|
* category, or a line with its band (95 % interval, or first to third quartile) drawn as one
|
|
* closed shape. */
|
|
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) => ({
|
|
xaxis: { title: { text: xTitle }, type: 'category' as const },
|
|
yaxis: { title: { text: y } },
|
|
});
|
|
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] })),
|
|
];
|
|
return {
|
|
data: named.map((c) => ({
|
|
type: 'bar',
|
|
name: c.label,
|
|
x,
|
|
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
|
|
marker: { color: c.color },
|
|
})),
|
|
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' },
|
|
};
|
|
}
|
|
const k = panel.kind === 'percent' ? 100 : 1;
|
|
const at = (v?: number) => (v === undefined ? null : v * k);
|
|
return {
|
|
data: [
|
|
{
|
|
x: [...x, ...[...x].reverse()],
|
|
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))],
|
|
mode: 'lines',
|
|
fill: 'toself',
|
|
fillcolor: line + '33',
|
|
line: { width: 0 },
|
|
name: panel.kind === 'percent' ? 'Intervalo de confianza' : 'Primer a tercer cuartil',
|
|
hoverinfo: 'skip',
|
|
},
|
|
{
|
|
x,
|
|
y: series.map((s) => at(s.r?.score)),
|
|
mode: 'lines+markers',
|
|
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
|
|
line: { color: line },
|
|
marker: { color: line },
|
|
},
|
|
],
|
|
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'),
|
|
};
|
|
}
|