import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette'; import { sortedPeriods } from './indicadores-periodos'; export interface HistoricoFigura { contrato: string; figure: PlotlyFigure; comoLeer: string; notaMetodologica?: string; suprimidos: string[]; sinDato: string[]; } const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); // CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue. const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const; const FONDO_AZUL = '#9DBFE380'; const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); // sortedPeriods lists the newest first, for selectors; time here runs left to right. export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); const MESES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic']; // «mar 2024» and «2024 S1»: a bare 2024-03 was read as a mix of months and years. export function etiquetaPeriodo(periodo: string): string { const [anio, resto] = periodo.split('-'); return resto.startsWith('S') ? `${anio} ${resto}` : `${MESES[Number(resto) - 1]} ${anio}`; } export interface HistoricoOpciones { // Same vertical scale across small charts, so their heights compare. yMax?: number; pequena?: boolean; // The unit a measure publishes, named as the domain calls it; falls back to the defaults below (CaMa's). unidades?: Readonly>; // A composition whose categories do not add up to the report's units (`unidades_periodo`) is an error. conciliarC2?: boolean; // A composition period with no units is «sin dato», not a bar of zeros. c2SinPoblacionSinDato?: boolean; } // What the unit a measure publishes is called in the charts' texts. const UNIDADES: Readonly> = { paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' }, }; const unidadDe = (data: IndicadorDatos, propias?: HistoricoOpciones['unidades']) => propias?.[String(data['unidad'])] ?? UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' }; function validar(data: IndicadorDatos) { for (const row of data.filas) { if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida'); } return cronologico(data.periodos); } function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string, pequena = false) { const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo); const cada = pequena && periodos.length > 12 ? 6 : 3; return { autosize: true, height: pequena ? 340 : 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false }, // A label for every month does not fit: one per quarter is still readable with the full period on hover. xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0, title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % cada === 0) }, yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false }, // Shaded, because an empty space alone reads as zero. Text below the figure says the same. shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 }, x0: periodos.indexOf(periodo) - .5, x1: periodos.indexOf(periodo) + .5, fillcolor: C2_PALETTE.states.suppressed, opacity: .18 })), }; } // One polygon per run of consecutive values: a band must not bridge a gap in the line. function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string, fillcolor = color + '40') { const x: (string | null)[] = [], y: (number | null)[] = []; let run: number[] = []; const cerrar = () => { if (run.length) { if (x.length) { x.push(null); y.push(null); } x.push(...run.map(i => periodos[i]), ...[...run].reverse().map(i => periodos[i])); y.push(...run.map(i => alto[i]), ...[...run].reverse().map(i => bajo[i])); } run = []; }; periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); }); cerrar(); return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor, line: { width: 0 }, hoverinfo: 'skip' }; } // Separate rows from what is missing or suppressed; a period is judged by its only row. function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record) => boolean) { const delTotal = filasDelGrupo(data, 'TOTAL'); const filas = new Map(delTotal.map(row => [row['periodo'] as string, row])); if (filas.size !== delTotal.length) throw new Error('Filas ambiguas'); const suprimidos: string[] = [], sinDato: string[] = []; const validas = periodos.map(periodo => { const row = filas.get(periodo); if (row?.['suprimido'] === 1) { suprimidos.push(periodo); return null; } if (!row || !valor(row)) { sinDato.push(periodo); return null; } return row; }); return { validas, suprimidos, sinDato }; } const campo = (filas: (Record | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null); // CaMa's line charts (and TEA's, which follow them) share the purple mark. A band, when the series has one, is blue; a line alone stays purple. function colorDeLinea(id: string, tema: Tema) { if (id.startsWith('cama_') || /^M\d+_/.test(id)) return { linea: MORADO[tema], relleno: FONDO_AZUL }; const linea = c2Theme(tema).line; return { linea, relleno: linea + '40' }; } export const M30_RESULTADO_EEG = 'M30_resultado_eeg'; // Normal takes the cool side of the palette and abnormal the warm one, as in the other domains' compositions. const NORMAL_EEG = C2_PALETTE.frios[3], ANORMAL_EEG = C2_PALETTE.calidos[0]; const PIE_PORCENTAJE: Readonly> = { cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.', [M30_RESULTADO_EEG]: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.', }; const PIE_MEDIANA: Readonly> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id, 'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.'])); const PIE_CATEGORIAS: Readonly> = Object.fromEntries(['cama_histopatologia_birads', 'cama_birads_456_mastografia'].map(id => [id, 'Cada barra indica el total de pacientes por periodo en cada categoría'])); type Trazo = Omit; function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { const periodos = validar(data); // A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here. const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0); const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'); const trazo = data.id === M30_RESULTADO_EEG ? { linea: ANORMAL_EEG, relleno: ANORMAL_EEG + '40' } : colorDeLinea(data.id, tema); const resultadoEeg = data.id === M30_RESULTADO_EEG; const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje'; const complemento = (llave: string) => campo(validas, llave).map(v => v === null ? null : Math.round(10 * (100 - v)) / 10); // EEG results are two complementary lines; the normal one mirrors the abnormal share and its interval. const normal = data.id === M30_RESULTADO_EEG ? [ banda(periodos.map(etiquetaPeriodo), complemento('ic_alto'), complemento('ic_bajo'), 'Intervalo de confianza (normal)', NORMAL_EEG, NORMAL_EEG + '40'), { type: 'scatter', mode: 'lines+markers', name: 'EEG normal', x: periodos.map(etiquetaPeriodo), y: complemento('valor'), connectgaps: false, line: { color: NORMAL_EEG, width: 2 }, marker: { color: NORMAL_EEG }, text: validas.map(row => row ? `${(row['denominador'] as number) - (row['numerador'] as number)} de ${row['denominador']}` : ''), hovertemplate: '%{x}
%{y} %
%{text}' }, ] : []; return { figure: { data: [ banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno), { type: 'scatter', mode: 'lines+markers', name: nombre, x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea }, text: validas.map(row => { if (!row) return ''; const intervalo = numero(row['ic_bajo']) && numero(row['ic_alto']) ? `
IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''; return `${row['valor']} %
${row['numerador']} de ${row['denominador']}${intervalo}`; }), hovertemplate: '%{x}
%{text}' }, ...normal, ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.', ...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}), suprimidos, sinDato, }; } function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo { const periodos = validar(data), unidad = unidadDe(data, opciones.unidades); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); const trazo = colorDeLinea(data.id, tema); return { figure: { data: [ banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', trazo.linea, trazo.relleno), { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea }, text: validas.map(row => row ? `Mediana: ${row['mediana']} días
Q1 a Q3: ${row['q1']} a ${row['q3']} días
${row['n']} ${unidad.plural}` : ''), hovertemplate: '%{x}
%{text}' }, ], layout: (() => { const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena); return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout; })() }, comoLeer: PIE_MEDIANA[data.id] ?? `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`, suprimidos, sinDato, }; } // What each count means, for the indicators that don't count patients in the period. const CONTEOS: Readonly> = { M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' }, M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' }, }; function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): Trazo { const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data, opciones.unidades); const celdas = new Map>(), categorias = new Map(); for (const row of data.filas) { const id = row['categoria'], key = JSON.stringify([id, row['periodo']]); if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de histórico inválida'); celdas.set(key, row); categorias.set(id, row['orden']); } // A category the catalog announces but no row carries is still a category: its absence is shown as a gap and // named under the figure, not dropped as if it did not exist, nor drawn as zero. const orden = [...[...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id), ...Object.keys(catalogo).filter(id => !categorias.has(id))]; const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo]))); const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1)); // The units each report says it has, when the adapter kept them: what the categories of a period must add up to. const unidades = record(data['unidades_periodo']) ? data['unidades_periodo'] : undefined; const suma = (p: string) => { const valores = estadoDe(p).map(row => row?.['n']); return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null; }; if (opciones.conciliarC2 && unidades) { for (const p of periodos) { const total = unidades[p], contado = suma(p); if (numero(total) && contado !== null && contado !== total) throw new Error('Los conteos por categoría no suman las unidades del periodo'); } } // A period with no units is not a period of zeros: it is drawn as a gap and listed. const sinPoblacion = new Set(opciones.c2SinPoblacionSinDato ? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []); const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])))); const curso = { frio: 0, calido: 0, neutro: 0 }; return { figure: { data: orden.map((id, i) => { const meta = record(catalogo[id]) ? catalogo[id] : {}; const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined; const tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id); const slot = tono === 'neutro' ? i : curso[tono]++; const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; }); return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores, marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}%{fullData.name}' }; }), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, comoLeer: data.id === 'cama_birads_456_paciente' ? '' : CONTEOS[data.id]?.comoLeer ?? PIE_CATEGORIAS[data.id] ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`, suprimidos, sinDato, }; } // A BI-RADS 4 without subcategory is published as «B4», with no colour. function etiquetaCategoria(meta: Record, id: string) { const publicada = typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : ''; return publicada && publicada !== id ? publicada : id === 'B4' ? 'BI-RADS 4 (sin subcategoría)' : id; } // The plot follows from what the contract's numbers mean: counts add up to a total, percentages // and medians do not, so those two are never stacked. export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura { const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema) : data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined; if (!figura) throw new Error('Representación no soportada'); return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) }; }