feat(indicadores): add the screening route chart to CaCu
Horizontal bars of the days from the sample to each event of the route (cytology result, colposcopy, biopsy result and diagnosis), cumulative with the Q1 to Q3 interval or step by step with each step starting where the previous one ends. It reads the seven duration measures of the route and shows up in CaCu's page once the catalog publishes all of them; the measures only it draws get no card of their own.
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
import { Caja, caja } from './indicadores-tiempos-pareados';
|
||||
|
||||
/**
|
||||
* The screening route as a chain of events timed from the sample: the cytology result, the colposcopy, the biopsy
|
||||
* result and the diagnosis. Each event has two C3r measures: the days from the sample and the days from the previous
|
||||
* event. The cytology's step is its own days from the sample.
|
||||
*/
|
||||
export interface RouteStep {
|
||||
id: 'cytology' | 'colposcopy' | 'biopsy' | 'diagnosis';
|
||||
label: string;
|
||||
stepLabel: string;
|
||||
sinceSample: string;
|
||||
sinceStep: string;
|
||||
}
|
||||
export const ROUTE_STEPS: readonly RouteStep[] = [
|
||||
{ id: 'cytology', label: 'Resultado de citología', stepLabel: 'Toma a resultado de citología',
|
||||
sinceSample: 'cacu_eu_tiempo_reporte', sinceStep: 'cacu_eu_tiempo_reporte' },
|
||||
{ id: 'colposcopy', label: 'Resultado de colposcopía', stepLabel: 'Del resultado de citología a la colposcopía',
|
||||
sinceSample: 'cacu_dias_toma_colposcopia', sinceStep: 'cacu_dias_resultado_colposcopia' },
|
||||
{ id: 'biopsy', label: 'Resultado de biopsia', stepLabel: 'De la colposcopía al resultado de biopsia',
|
||||
sinceSample: 'cacu_dias_toma_biopsia', sinceStep: 'cacu_dias_colposcopia_biopsia' },
|
||||
{ id: 'diagnosis', label: 'Diagnóstico', stepLabel: 'Del resultado de biopsia al diagnóstico',
|
||||
sinceSample: 'cacu_dias_toma_diagnostico', sinceStep: 'cacu_dias_biopsia_diagnostico' },
|
||||
];
|
||||
/** Every measure the chart reads, once each. */
|
||||
export const ROUTE_IDS: readonly string[] = [...new Set(ROUTE_STEPS.flatMap(s => [s.sinceSample, s.sinceStep]))];
|
||||
|
||||
/** The measures only this chart draws: the cytology's and the diagnosis' keep their own cards. */
|
||||
export const ROUTE_ONLY_IDS: readonly string[] = ROUTE_IDS.filter(id => id !== 'cacu_eu_tiempo_reporte' && id !== 'cacu_dias_toma_diagnostico');
|
||||
|
||||
export type RouteView = 'cumulative' | 'steps';
|
||||
export interface RouteRow {
|
||||
step: RouteStep;
|
||||
fromSample: Caja;
|
||||
fromPrevious: Caja;
|
||||
/** Where the step starts and ends on the days axis, when chained one after another; null without a published box. */
|
||||
start: number | null;
|
||||
end: number | null;
|
||||
}
|
||||
export interface RouteModel { period: string | undefined; periods: string[]; rows: RouteRow[]; }
|
||||
export class RouteIncompatible extends Error {}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const fail = (message: string): never => { throw new RouteIncompatible(message); };
|
||||
const NOT_AVAILABLE: Caja = { estado: 'No disponible' };
|
||||
|
||||
/** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */
|
||||
export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPeriodo, requested?: string): RouteModel {
|
||||
const boxes: Record<string, Record<string, Caja>> = {};
|
||||
for (const id of ROUTE_IDS) {
|
||||
const d = data[id];
|
||||
if (!d || d.id !== id || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
|| new Set(d.periodos).size !== d.periodos.length) {
|
||||
fail('Los datos de tiempos no corresponden a los indicadores de la ruta del tamizaje.');
|
||||
}
|
||||
boxes[id] = {};
|
||||
for (const row of d.filas) {
|
||||
if (!record(row) || typeof row['periodo'] !== 'string' || !d.periodos.includes(row['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
|
||||
if (row['grupo'] !== 'TOTAL' || row['estrato'] != null) continue;
|
||||
if (row['unidad'] !== undefined && row['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
|
||||
const period = row['periodo'] as string;
|
||||
if (boxes[id][period]) fail('Más de una fila total por periodo.');
|
||||
boxes[id][period] = caja(row);
|
||||
}
|
||||
}
|
||||
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
|
||||
const period = requested && periods.includes(requested) ? requested : periods[0];
|
||||
let cursor = 0;
|
||||
const rows = ROUTE_STEPS.map((step): RouteRow => {
|
||||
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
const fromPrevious = period ? boxes[step.sinceStep][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
if (fromPrevious.estado !== 'Publicado') return { step, fromSample, fromPrevious, start: null, end: null };
|
||||
const start = cursor;
|
||||
cursor += fromPrevious.mediana!;
|
||||
return { step, fromSample, fromPrevious, start, end: cursor };
|
||||
});
|
||||
return { period, periods, rows };
|
||||
}
|
||||
|
||||
/** The rows with a published box for the view. */
|
||||
export function drawnRows(model: RouteModel, view: RouteView): RouteRow[] {
|
||||
return model.rows.filter(row => (view === 'cumulative' ? row.fromSample : row.fromPrevious).estado === 'Publicado');
|
||||
}
|
||||
export const routeHasData = (model: RouteModel) => drawnRows(model, 'cumulative').length > 0 || drawnRows(model, 'steps').length > 0;
|
||||
|
||||
const days = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
|
||||
const count = (v: number) => v.toLocaleString('es-MX');
|
||||
|
||||
/**
|
||||
* Horizontal bars of days. Cumulative: from the sample to each event, with the Q1 to Q3 range as the interval. Steps:
|
||||
* each step floats from where the previous one ends, and the slowest is the one in colour.
|
||||
*/
|
||||
export function routeFigure(model: RouteModel, view: RouteView, tema: Tema): PlotlyFigure {
|
||||
const t = c2Theme(tema);
|
||||
const rows = drawnRows(model, view);
|
||||
if (!rows.length) return { data: [], layout: {} };
|
||||
const base = { autosize: true, height: 360, showlegend: false, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text },
|
||||
margin: { t: 24, l: 150, r: 32, b: 56 } };
|
||||
const axes = {
|
||||
xaxis: { title: { text: 'Días' }, rangemode: 'tozero', gridcolor: t.grid, zeroline: false, fixedrange: true },
|
||||
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true },
|
||||
};
|
||||
if (view === 'cumulative') {
|
||||
const boxes = rows.map(row => row.fromSample);
|
||||
return { data: [{
|
||||
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.label}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
|
||||
marker: { color: C2_PALETTE.series[0] },
|
||||
error_x: { type: 'data', symmetric: false, color: t.text, thickness: 1.5, width: 6,
|
||||
array: boxes.map(b => b.q3! - b.mediana!), arrayminus: boxes.map(b => b.mediana! - b.q1!) },
|
||||
customdata: boxes.map(b => [count(b.n!), days(b.q1!), days(b.mediana!), days(b.q3!)]),
|
||||
hovertemplate: '%{y}<br>Mediana: %{customdata[2]} días<br>Q1 a Q3: %{customdata[1]} a %{customdata[3]} días<extra></extra>',
|
||||
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
|
||||
}
|
||||
const slowest = rows.reduce((best, row, i) => (row.fromPrevious.mediana! > rows[best].fromPrevious.mediana! ? i : best), 0);
|
||||
const boxes = rows.map(row => row.fromPrevious);
|
||||
return { data: [{
|
||||
type: 'bar', orientation: 'h', y: rows.map((row, i) => `${row.step.stepLabel}<br>n = ${count(boxes[i].n!)}`), x: boxes.map(b => b.mediana),
|
||||
base: rows.map(row => row.start),
|
||||
marker: { color: rows.map((_, i) => (i === slowest ? C2_PALETTE.series[0] : C2_PALETTE.states.noData)) },
|
||||
text: boxes.map(b => `+${days(b.mediana!)} d`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
|
||||
customdata: rows.map((row, i) => [count(boxes[i].n!), days(boxes[i].q1!), days(boxes[i].mediana!), days(boxes[i].q3!), days(row.end!)]),
|
||||
hovertemplate: '%{y}<br>Tramo: %{customdata[2]} días (Q1 a Q3: %{customdata[1]} a %{customdata[3]})<br>Hasta el día %{customdata[4]}<extra></extra>',
|
||||
}], layout: { ...base, ...axes }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
export function routeCellText(box: Caja): string {
|
||||
return box.estado !== 'Publicado' ? box.estado : `n = ${count(box.n!)}, Q1 ${days(box.q1!)}, mediana ${days(box.mediana!)}, Q3 ${days(box.q3!)} días`;
|
||||
}
|
||||
Reference in New Issue
Block a user