352 lines
11 KiB
TypeScript
352 lines
11 KiB
TypeScript
import type { Measure, MeasureReport, MeasureReportGroup } from 'fhir/r4';
|
||
import { code, ext } from '../fhir';
|
||
import { Figure, PALETTE } from '../plot';
|
||
|
||
export type PeriodType = 'semester' | 'month';
|
||
export type Scoring = 'proportion' | 'continuous-variable' | 'cohort';
|
||
|
||
/** The periods back from today, most recent first: semesters (`2025-S1`) or months. */
|
||
export function periods(type: PeriodType, years = 6, today = new Date()): string[] {
|
||
const found: string[] = [];
|
||
const year = today.getFullYear();
|
||
if (type === 'semester') {
|
||
for (let y = year; y > year - years; y--) {
|
||
if (y < year || today.getMonth() >= 6) found.push(`${y}-S2`);
|
||
found.push(`${y}-S1`);
|
||
}
|
||
} else {
|
||
for (let i = 0; i < years * 12; i++) {
|
||
const d = new Date(year, today.getMonth() - i, 1);
|
||
found.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
|
||
}
|
||
}
|
||
return found;
|
||
}
|
||
|
||
export function periodLabel(period: string): string {
|
||
const [year, part] = period.split('-');
|
||
if (part.startsWith('S')) return `${part === 'S1' ? 'Ene–Jun' : 'Jul–Dic'} ${year}`;
|
||
const month = new Date(Number(year), Number(part) - 1, 1).toLocaleString('es-MX', {
|
||
month: 'short',
|
||
});
|
||
return `${month} ${year}`;
|
||
}
|
||
|
||
export function scoring(measure: Measure): Scoring {
|
||
return code(measure.scoring) as Scoring;
|
||
}
|
||
|
||
export function periodTypes(measure: Measure): PeriodType[] {
|
||
return (measure.extension ?? [])
|
||
.filter((e) => e.url.endsWith('/period-type'))
|
||
.map((e) => e.valueCode as PeriodType);
|
||
}
|
||
|
||
/** What one report says: its counts, its score and interval, and its strata. */
|
||
export interface Reading {
|
||
populations: Record<string, number>;
|
||
score?: number;
|
||
low?: number;
|
||
high?: number;
|
||
unit?: string;
|
||
strata: Record<string, Record<string, Record<string, number>>>;
|
||
/** A stratum value's own score (a median and its quartiles). */
|
||
scores?: Record<string, Record<string, { score?: number; low?: number; high?: number }>>;
|
||
}
|
||
|
||
function counts(group: {
|
||
population?: { code?: { coding?: { code?: string }[] }; count?: number }[];
|
||
}) {
|
||
return Object.fromEntries(
|
||
(group.population ?? []).map((p) => [p.code?.coding?.[0]?.code ?? '', p.count ?? 0]),
|
||
);
|
||
}
|
||
|
||
export function reading(report: MeasureReport | undefined): Reading | undefined {
|
||
const group: MeasureReportGroup | undefined = report?.group?.[0];
|
||
if (!group) return undefined;
|
||
const score = group.measureScore;
|
||
const strata: Reading['strata'] = {};
|
||
const scores: NonNullable<Reading['scores']> = {};
|
||
for (const s of group.stratifier ?? []) {
|
||
// A crossed stratifier (several codes) is keyed `a-b`, its strata `valueA|valueB`.
|
||
const name = (s.code ?? []).map((c) => code(c) ?? c.text ?? '').join('-');
|
||
strata[name] = Object.fromEntries(
|
||
(s.stratum ?? []).map((x) => [
|
||
x.component?.length
|
||
? x.component.map((c) => c.value?.text ?? '').join('|')
|
||
: (x.value?.text ?? ''),
|
||
counts(x),
|
||
]),
|
||
);
|
||
for (const { value, measureScore: own } of s.stratum ?? [])
|
||
if (own)
|
||
(scores[name] ??= {})[value?.text ?? ''] = {
|
||
score: own.value,
|
||
low: ext(own, 'q1')?.valueDecimal,
|
||
high: ext(own, 'q3')?.valueDecimal,
|
||
};
|
||
}
|
||
return {
|
||
populations: counts(group),
|
||
score: score?.value,
|
||
low: (ext(score, 'ic-bajo') ?? ext(score, 'q1'))?.valueDecimal,
|
||
high: (ext(score, 'ic-alto') ?? ext(score, 'q3'))?.valueDecimal,
|
||
unit: score?.unit,
|
||
strata,
|
||
scores,
|
||
};
|
||
}
|
||
|
||
/** Codes as the screens name them. */
|
||
export const LABELS: Record<string, string> = {
|
||
NILM: 'Normal (NILM)',
|
||
LSIL: 'LIEBG',
|
||
HSIL: 'LIEAG',
|
||
normal: 'Normal',
|
||
carcinoma: 'Carcinoma',
|
||
no_data: 'Sin dato',
|
||
no_biopsy: 'Sin biopsia',
|
||
pre_colposcopy: 'Pre colposcopia',
|
||
post_colposcopy: 'Post colposcopia',
|
||
post_treatment: 'Post tratamiento',
|
||
case: 'Caso (cáncer)',
|
||
low: 'Bajo',
|
||
intermediate: 'Intermedio',
|
||
high: 'Alto',
|
||
satisfactory: 'satisfactoria',
|
||
unsatisfactory: 'insatisfactoria',
|
||
benign: 'Benigno',
|
||
in_situ: 'Carcinoma in situ',
|
||
invasive: 'Carcinoma invasor',
|
||
cancer: 'Diagnóstico confirmado',
|
||
pending_biopsy: 'Pendiente de biopsia',
|
||
biopsy_no_result: 'Biopsia sin resultado',
|
||
benign_biopsy: 'Biopsia benigna',
|
||
confirmed: 'Diagnóstico confirmado',
|
||
in_process: 'En proceso',
|
||
not_confirmed: 'Sin TEA',
|
||
mchat_only: 'Solo M-CHAT',
|
||
psychology: 'Psicología (ADOS-2)',
|
||
neuropediatrics: 'Neuropediatría',
|
||
eeg: 'EEG',
|
||
good: 'Bueno',
|
||
bad: 'Malo',
|
||
not_analyzed: 'Sin analizar',
|
||
initial: 'Detección inicial',
|
||
subsequent: 'Detección subsecuente',
|
||
positive: 'Positivo',
|
||
negative: 'Negativo',
|
||
hpv_16: 'VPH 16',
|
||
hpv_18: 'VPH 18',
|
||
ascus_plus: 'ASC-US o mayor',
|
||
lsil_plus: 'LIEBG o mayor',
|
||
hsil_plus: 'LIEAG o mayor',
|
||
cin1_plus: 'Histología LIEBG o mayor',
|
||
cin2_plus: 'Histología LIEAG o mayor',
|
||
several: 'Varios códigos',
|
||
no_result: 'Sin resultado de VPH',
|
||
positive_incomplete: 'Positivo con genotipificación incompleta',
|
||
inconsistent: 'Inconsistente',
|
||
no_grade: 'Sin grado',
|
||
...Object.fromEntries(
|
||
['0', '1', '2', '3', '4', '4A', '4B', '4C', '5', '6'].map((c) => [c, `BI-RADS ${c}`]),
|
||
),
|
||
};
|
||
/** A follow-up priority's label. */
|
||
export const PRIORITY: Record<string, string> = { high: 'Alta', medium: 'Media', low: 'Baja' };
|
||
export const STRATA: Record<string, string> = {
|
||
category: 'Categoría',
|
||
age_group: 'Grupo de edad',
|
||
follow_up_status: 'Estatus de seguimiento',
|
||
result: 'Citología de alto grado',
|
||
birads: 'BI-RADS de la mastografía',
|
||
diagnosis_code: 'Diagnóstico CIE-10',
|
||
cytology: 'Citología previa',
|
||
hpv: 'VPH de la citología previa',
|
||
level: 'Histología confirmada',
|
||
round: 'Tamizaje inicial o subsecuente',
|
||
hpv_16: 'VPH 16',
|
||
hpv_18: 'VPH 18',
|
||
};
|
||
export const name = (value: string) => LABELS[value] ?? value;
|
||
|
||
export function formatScore(measure: Measure, r: Reading | undefined): string {
|
||
if (!r || r.score === undefined) return 'Sin dato';
|
||
switch (scoring(measure)) {
|
||
case 'proportion':
|
||
return `${(r.score * 100).toFixed(1)} %`;
|
||
case 'continuous-variable':
|
||
return `${Math.round(r.score * 10) / 10} días`;
|
||
default:
|
||
return `${r.score}`;
|
||
}
|
||
}
|
||
|
||
export function detail(measure: Measure, r: Reading | undefined, unit = 'pacientes'): string {
|
||
if (!r) return '';
|
||
const p = r.populations;
|
||
switch (scoring(measure)) {
|
||
case 'proportion':
|
||
return r.score === undefined
|
||
? `Sin ${unit} en el periodo.`
|
||
: `${p['numerator']} de ${p['denominator']} ${unit}. IC 95 %: ${pct(r.low)}–${pct(r.high)}.`;
|
||
case 'continuous-variable':
|
||
return r.score === undefined
|
||
? `${p['initial-population'] ?? 0} sin medición en el periodo.`
|
||
: `Mediana de ${p['measure-observation']} mediciones; cuartiles ${r.low}–${r.high} días.`;
|
||
default:
|
||
return `${p['initial-population'] ?? 0} pacientes.`;
|
||
}
|
||
}
|
||
|
||
const pct = (v?: number) => (v === undefined ? '—' : `${(v * 100).toFixed(1)} %`);
|
||
|
||
/** A donut of one stratifier's counts (initial population), or of numerator vs the rest. */
|
||
export function donut(
|
||
measure: Measure,
|
||
r: Reading,
|
||
stratifier = 'category',
|
||
/** a colour by category code (a proportion: `numerator` and `rest`); a part without one takes the palette's */
|
||
colors?: Record<string, string>,
|
||
): Figure {
|
||
let labels: string[], values: number[], codes: string[];
|
||
if (scoring(measure) === 'proportion') {
|
||
const { numerator = 0, denominator = 0 } = r.populations;
|
||
labels = ['Numerador', 'Resto'];
|
||
codes = ['numerator', 'rest'];
|
||
values = [numerator, denominator - numerator];
|
||
} else {
|
||
const cells = Object.entries(r.strata[stratifier] ?? {});
|
||
labels = cells.map(([v]) => name(v));
|
||
codes = cells.map(([v]) => v);
|
||
values = cells.map(([, c]) => c['initial-population'] ?? 0);
|
||
}
|
||
return {
|
||
data: [
|
||
{
|
||
type: 'pie',
|
||
hole: 0.62,
|
||
labels,
|
||
values,
|
||
sort: false,
|
||
textinfo: 'value+percent',
|
||
marker: { colors: codes.map((c, i) => colors?.[c] ?? PALETTE[i % PALETTE.length]) },
|
||
},
|
||
],
|
||
layout: { showlegend: true, margin: { t: 32, r: 8, b: 32, l: 8 } },
|
||
};
|
||
}
|
||
|
||
/** Bars per stratum: the rate (proportion) or the count (others). */
|
||
export function strataBars(measure: Measure, r: Reading, stratifier: string): Figure {
|
||
const cells = Object.entries(r.strata[stratifier] ?? {});
|
||
const proportion = scoring(measure) === 'proportion';
|
||
const values = cells.map(([, c]) =>
|
||
proportion
|
||
? c['denominator']
|
||
? (100 * (c['numerator'] ?? 0)) / c['denominator']
|
||
: 0
|
||
: (c['initial-population'] ?? 0),
|
||
);
|
||
return {
|
||
data: [
|
||
{
|
||
type: 'bar',
|
||
orientation: 'h',
|
||
y: cells.map(([v]) => name(v)),
|
||
x: values,
|
||
marker: { color: PALETTE[0] },
|
||
},
|
||
],
|
||
layout: {
|
||
xaxis: { title: { text: proportion ? '%' : 'Pacientes' } },
|
||
yaxis: { automargin: true },
|
||
margin: { t: 8, r: 16, b: 48, l: 8 },
|
||
},
|
||
};
|
||
}
|
||
|
||
/** Horizontal median bars with their interquartile range, one per measure. */
|
||
export function medians(rows: { label: string; r: Reading | undefined }[]): Figure {
|
||
const shown = rows.filter((x) => x.r?.score !== undefined);
|
||
return {
|
||
data: [
|
||
{
|
||
type: 'bar',
|
||
orientation: 'h',
|
||
y: shown.map((x) => x.label),
|
||
x: shown.map((x) => x.r!.score!),
|
||
error_x: {
|
||
type: 'data',
|
||
symmetric: false,
|
||
array: shown.map((x) => (x.r!.high ?? x.r!.score!) - x.r!.score!),
|
||
arrayminus: shown.map((x) => x.r!.score! - (x.r!.low ?? x.r!.score!)),
|
||
color: '#17324d',
|
||
},
|
||
marker: { color: PALETTE[0] },
|
||
hovertemplate: '%{y}: %{x} días<extra></extra>',
|
||
},
|
||
],
|
||
layout: {
|
||
xaxis: { title: { text: 'Días (mediana, Q1–Q3)' } },
|
||
yaxis: { automargin: true, autorange: 'reversed' },
|
||
},
|
||
};
|
||
}
|
||
|
||
/** A measure over time: % with its interval, median with its quartiles, or counts by category. */
|
||
export function history(
|
||
measure: Measure,
|
||
series: { period: string; r: Reading | undefined }[],
|
||
): Figure {
|
||
const x = series.map((s) => periodLabel(s.period));
|
||
const kind = scoring(measure);
|
||
if (kind === 'cohort') {
|
||
const categories = [
|
||
...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {}))),
|
||
];
|
||
return {
|
||
data: categories.map((c, i) => ({
|
||
type: 'bar',
|
||
name: name(c),
|
||
x,
|
||
y: series.map((s) => s.r?.strata['category']?.[c]?.['initial-population'] ?? 0),
|
||
marker: { color: PALETTE[i % PALETTE.length] },
|
||
})),
|
||
layout: { barmode: 'stack', yaxis: { title: { text: 'Pacientes' } } },
|
||
};
|
||
}
|
||
const k = kind === 'proportion' ? 100 : 1;
|
||
const value = (v?: number) => (v === undefined ? null : v * k);
|
||
return {
|
||
data: [
|
||
{
|
||
x,
|
||
y: series.map((s) => value(s.r?.high)),
|
||
mode: 'lines',
|
||
line: { width: 0 },
|
||
showlegend: false,
|
||
hoverinfo: 'skip',
|
||
},
|
||
{
|
||
x,
|
||
y: series.map((s) => value(s.r?.low)),
|
||
mode: 'lines',
|
||
line: { width: 0 },
|
||
fill: 'tonexty',
|
||
fillcolor: 'rgba(168,194,67,0.25)',
|
||
name: kind === 'proportion' ? 'IC 95 %' : 'Q1–Q3',
|
||
},
|
||
{
|
||
x,
|
||
y: series.map((s) => value(s.r?.score)),
|
||
mode: 'lines+markers',
|
||
name: kind === 'proportion' ? '%' : 'Mediana',
|
||
line: { color: PALETTE[0] },
|
||
},
|
||
],
|
||
layout: { yaxis: { title: { text: kind === 'proportion' ? '%' : 'Días' } } },
|
||
};
|
||
}
|