import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette'; import { percentNumber, shareText } from './indicadores-format'; // Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia): // a C2 stratified by the last valid cytology of the period; the category is the grade // of the biopsy it originated. Unknown or suppressed cells never become zero. export const ID_CONFIRMACION = 'cacu_confirmacion_citologia'; export const ESTRATO_CITOLOGIA = 'citologia_alto_grado'; // Outside the denominator and the donut, reported apart in the table: // SIN_BIOPSIA = no biopsy reported at the cut-off; SIN_DATO = biopsy reported without a grade. export const APARTE = [ { id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' }, { id: 'SIN_DATO', etiqueta: 'Biopsia sin grado' }, ] as const; const APARTE_IDS: readonly string[] = APARTE.map(a => a.id); // Grades outside the published catalog (CIN2, DESCONOCIDO…) arrive without a colour. const COLOR_RESPALDO = '#8A9199'; // Fixed vertical axis, most severe cytology on top. export const FILAS_CITOLOGIA = [ { id: 'CIS', etiqueta: 'Carcinoma in situ' }, { id: 'LIEAG', etiqueta: 'LIEAG' }, { id: 'ASC-H', etiqueta: 'ASC-H' }, ] as const; export const Z95 = 1.959963984540054; export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; } export interface Grado { id: string; etiqueta: string; color: string; grupo: string; } export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; } export interface FilaCitologia { id: string; etiqueta: string; celdas: Record; // SIN_BIOPSIA and SIN_DATO cells, when the response publishes those categories. aparte: Record; // Women of the row with a biopsy: the denominator. Null when any of its cells is unknown. den: number | null; estado: Celda['estado']; } export interface ModeloConfirmacion { periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string; filas: FilaCitologia[]; totales: Record; conBiopsia: number | null; aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; } export interface SeleccionConfirmacion { grupo: string; categoria?: string; } export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; } export class ConfirmacionIncompatible extends Error {} const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0; const fail = (message: string): never => { throw new ConfirmacionIncompatible(message); }; const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); const miles = (v: number) => v.toLocaleString('es-MX'); const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL'; /** Wilson score interval at 95 %, in percent; same formula as the kit (oro/calculo.py:wilson). */ export function wilson(k: number, n: number): [number, number] { const p = k / n, z2 = Z95 * Z95, base = 1 + z2 / n; const centro = (p + z2 / (2 * n)) / base; const mitad = Z95 * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / base; return [100 * Math.max(0, Math.min(p, centro - mitad)), 100 * Math.min(1, Math.max(p, centro + mitad))]; } function celda(fila?: Record): Celda { if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' }; return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0 ? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' }; } function suma(celdas: Celda[]): number | null { return celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0); } function estado(celdas: Celda[]): Celda['estado'] { return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado'; } function rgba(hex: string, alfa: number): string { const v = parseInt(hex.slice(1), 16); return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; } // grupos_de_categoria publishes a label, or an object with `etiqueta`. const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined; /** Validated periods of one stratified response, in request order or sorted. */ export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] { if (datos.id !== ID_CONFIRMACION || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_CITOLOGIA || !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length || datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p)) || (solicitados && datos.periodos.some(p => !solicitados.includes(p))) || datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) { return fail('Los datos no corresponden a la confirmación histopatológica o al periodo aplicado.'); } return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort(); } /** One /datos payload -> the contingency table of a single period. */ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): ModeloConfirmacion { periodosConfirmacion(datos, datos.tipo_periodo); const cats = datos['categorias'], nombres = datos['grupos_de_categoria']; if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.'); const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => { const c = cats[a.id]; return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta }; }); const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => { if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']))) || typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.'); return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] }; }); const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO); const colores = paintByGroup(conColor.map(g => g.grupo)); const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]])); const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color })); const bases = basesPorGrupo(conColor.map(g => g.grupo)); const grupos = [...new Set(grados.map(g => g.grupo))].map(id => { // Off-catalogue grades keep the neutral fallback and do not take the group hue. const propios = grados.filter(g => g.grupo === id); return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO, grados: propios.map(g => g.id) }; }); // The base view is the group of LIEAG ("LIEAG o más"): the true positives. const base = grados.find(g => g.id === 'LIEAG')?.grupo ?? fail('El catálogo no publica el grado LIEAG.'); if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.'); const index = new Map>(); for (const row of datos.filas.filter(f => f['periodo'] === periodo)) { const c = row['categoria'], e = row['estrato']; if (!esTotal(row['grupo']) || typeof e !== 'string' || typeof c !== 'string' || (!grados.some(g => g.id === c) && !aparte.some(a => a.id === c)) || ![0, 1].includes(row['suprimido'] as number)) { return fail('Fila de confirmación inválida.'); } const key = JSON.stringify([e, c]); if (index.has(key)) return fail('Filas de confirmación duplicadas.'); index.set(key, row); } // valores_estrato may list only the strata with data; a fixed row absent from it has no women. const publicados = Array.isArray(datos['valores_estrato']) ? (datos['valores_estrato'] as unknown[]) : undefined; if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos de citología inválidos.'); const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {}; const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : []; if (!totales.every(registro)) fail('Totales de citología inválidos.'); const filas = FILAS_CITOLOGIA.map(({ id, etiqueta }) => { const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta; const tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id); const ausente = !tieneFilas && (!publicados || !publicados.includes(id)); const cero = (): Celda => ({ n: 0, estado: 'Publicado' }); const celdas = Object.fromEntries(grados.map(g => [g.id, ausente ? cero() : celda(index.get(JSON.stringify([id, g.id])))])); const otras = Object.fromEntries(aparte.map(a => [a.id, ausente ? cero() : celda(index.get(JSON.stringify([id, a.id])))])); // A suppressed published total suppresses the row, whatever its cells say. const suprimida = (totales as Record[]).some(t => t['periodo'] === periodo && t['estrato'] === id && t['suprimido'] === 1); const valores = Object.values(celdas); return { id, etiqueta: rotulo, celdas, aparte: otras, den: suprimida ? null : suma(valores), estado: suprimida ? 'Suprimido' as const : estado(valores) }; }); const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))])); return { periodo, grados, grupos, base, filas, totales: porGrado, conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))), aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])] }; } export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; } export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] { return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.grados ?? []; } export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string { return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta; } /** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */ export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion { if (traza === 'centro') return seleccionBase(m); if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; } if (traza !== 'categorias') return sel; const c = m.grados[indice]; if (!c) return sel; return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id }; } /** The axis title says what the rate reads. */ export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string { if (!sel.categoria && sel.grupo === m.base) return 'Verdaderos positivos (valor predictivo positivo)'; if (sel.categoria === 'NORMAL') return 'Falsos positivos: la biopsia no confirmó lesión'; if (!sel.categoria) return 'Sin confirmación de alto grado'; return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel); } /** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */ export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[] { const cats = seleccionados(m, sel); return m.filas.map(fila => { if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null }; const k = cats.reduce((s, c) => s + fila.celdas[c].n!, 0); const [bajo, alto] = wilson(k, fila.den); return { fila, k, valor: 100 * k / fila.den, bajo, alto }; }); } export function estadoTasa(t: Tasa): string { return t.fila.den === 0 ? 'Sin mujeres con biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado; } /** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */ export function rangoTasas(valores: Tasa[]): [number, number] { const visibles = valores.filter(t => t.bajo !== null && t.alto !== null); if (!visibles.length) return [0, 100]; const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!)); return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)]; } /** Rates on the left: one point and horizontal Wilson interval per cytology, one trace always. */ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure { const p = c2Theme(tema); const valores = tasas(m, sel); const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color; const y = valores.map(t => t.fila.etiqueta); return { data: [{ type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), marker: { size: 12, color }, cliponaxis: false, error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6, array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) }, customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]), hovertemplate: '%{y}
%{customdata[0]} (%{customdata[1]}/%{customdata[2]})
IC 95 %: %{customdata[3]}–%{customdata[4]} %', }], layout: { autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, margin: { l: 130, r: 96, t: 16, b: 64 }, yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true }, xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } }, annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left', font: { size: 12, color: p.text }, text: t.k === null ? estadoTasa(t) : `${shareText(t.k, t.fila.den!)}
${t.k}/${t.fila.den}` })), }, config: { displayModeBar: false } }; } /** Donut on the right: groups inside, grades outside; selection dims, values stay. */ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure { if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} }; const p = c2Theme(tema), activos = new Set(seleccionados(m, sel)), total = m.conBiopsia; const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0); const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0)); const exterior = m.grados.map(g => m.totales[g.id]!); const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' }; // A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead. const hover = { hovertemplate: '%{label}
%{hovertext}' }; const hoverText = (values: number[]) => values.map(n => `${miles(n)} mujeres con biopsia, ${shareText(n, total)}`); return { data: [ { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside', text: [`${miles(k)}
de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text }, marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '' }, { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior), marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } }, { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior), marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } }, ], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; }