From c076e1e7a99c5937866560b0bb832578b4fa56b7 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Thu, 12 Nov 2026 19:19:37 -0600 Subject: [PATCH] feat(indicadores): breakdown by CaMa's stratifiers, in counts or as each category's share of its stratum MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CaMa stratifiers (age, BRCA1/2, molecular classification, stage, tumour size, early or advanced) now break down quantities of interest (BI-RADS results, histological diagnosis) instead of being distributions of their own. How: - DimensionEstrato and DIMENSIONES_ESTRATO add brca, clasificacion, estadio, tamano and etapa; stratifiedCapabilities offers, in a fixed order, every one the indicator declares in `filtros`. - etiquetaDimension names a dimension's button from the catalog's label; CaCu's two keep their wording. - stratifiedBars takes a measure: counts, or each category's share of its stratum over the published stratum total (or the sum of its cells when all are published); a suppressed or unknown total leaves the stratum without percentages. The hover gives n of total; the values table adds the share. - The bars panel has a «Conteos | Porcentaje en cada estrato» toggle; an indicator can open with the share (`medida_estrato: 'porcentaje'`). Implications: - Shares are derived in the browser from published counts; the server's suppression of small strata and totals is what keeps them safe. - Other domains are unchanged: their dimensions, labels and counts stay. --- .../indicadores/indicador-figure-panel.ts | 28 +++++++++-- .../indicadores-stratified-panel.spec.ts | 4 +- .../indicadores-stratified.spec.ts | 32 ++++++++++++- .../indicadores/indicadores-stratified.ts | 46 +++++++++++++++---- .../indicadores/indicadores.models.ts | 7 ++- 5 files changed, 99 insertions(+), 18 deletions(-) diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 8699c75..7ab6229 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -15,7 +15,7 @@ import { IndicadoresSnapshots } from './indicadores-snapshots'; import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2'; import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; -import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; +import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; import { MatTooltipModule } from '@angular/material/tooltip'; @@ -48,10 +48,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@for (d of capabilities; track d) { + (click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }} }
} + @if (dimension) { +
+ + +
+ } @if (!singlePeriod) {

Selecciona un periodo para consultar la distribución estratificada.

} } @@ -70,8 +76,8 @@ import { MatTooltipModule } from '@angular/material/tooltip'; @if (hasSuppressedCells) {

Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.

} @if (hasMissingCells) {

Hay datos no disponibles; los espacios sin barra no representan un cero observado.

}
Valores publicados -
- @for (cell of cells; track $index) { } +
CategoríaEstratoConteo
{{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}
+ @for (cell of cells; track $index) { }
CategoríaEstratoConteoPorcentaje del estrato
{{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}{{ cell.percent === null ? '—' : cell.percent + ' %' }}
@if (!cells.length) {

No hay categorías publicadas para esta selección.

} @@ -164,6 +170,18 @@ export class IndicadorFigurePanel implements OnChanges { return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state; } dimension: DimensionEstrato | '' = ''; + readonly etiquetaDimension = etiquetaDimension; + // Counts or each category's share of its stratum; an indicator can ask to open with the share. + private medidaElegida?: MedidaEstrato; + get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; } + changeMedida(medida: MedidaEstrato) { + if (medida === this.medida) return; + this.medidaElegida = medida; + if (this.dimension && this.stratifiedData && this.result().status === 'ready') { + try { this.result.set(this.presentStratified(this.stratifiedData)); } + catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); } + } + } cells: StratifiedCell[] = []; get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); } get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); } @@ -183,7 +201,7 @@ export class IndicadorFigurePanel implements OnChanges { } private presentStratified(data: IndicadorDatos): FigureState { const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {}; - const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local); + const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida); this.cells = adapted.cells; return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id, tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }), diff --git a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts index 39f831c..9ccf517 100644 --- a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts +++ b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts @@ -48,7 +48,9 @@ describe('Barras estratificadas: activación y caché',()=>{ toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges(); expect(fixture.componentInstance.dimension).toBe('grupo_edad'); expect(toggle[1].getAttribute('aria-checked')).toBe('true'); - expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2); + // The dimensions, apart from the counts or percentage toggle that follows them. + expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2); + expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2); for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); } }); it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{ diff --git a/src/app/features/indicadores/indicadores-stratified.spec.ts b/src/app/features/indicadores/indicadores-stratified.spec.ts index 9a1b389..3b6d8ad 100644 --- a/src/app/features/indicadores/indicadores-stratified.spec.ts +++ b/src/app/features/indicadores/indicadores-stratified.spec.ts @@ -1,6 +1,6 @@ import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json'; import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json'; -import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified'; +import { etiquetaDimension, stratifiedBars, stratifiedCapabilities } from './indicadores-stratified'; import { DimensionEstrato, Indicador } from './indicadores.models'; const age = { ...ageJson, tipo_periodo: 'semestre' as const }; @@ -61,3 +61,33 @@ describe('Contratos simulados de estratificación de los analistas', () => { expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow(); }); }); + +// A CaMa quantity of interest broken down by a stratifier: two strata of different size, one with a suppressed total. +const porEtapa = () => ({ + id: 'cama_birads_cancer_invasor', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], estrato: 'etapa', + valores_estrato: ['TEMPRANA', 'AVANZADA', 'SIN'], etiquetas_estrato: { TEMPRANA: 'Temprana', AVANZADA: 'Avanzada', SIN: 'Sin dato' }, + grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, categorias: { B4A: { etiqueta: 'BI-RADS 4A' }, B5: { etiqueta: 'BI-RADS 5' } }, + totales_estrato: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'TEMPRANA', n: 40, suprimido: 0 }, { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'AVANZADA', n: 10, suprimido: 0 }, + { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'SIN', n: null, suprimido: 1 }], + filas: [['TEMPRANA', 'B4A', 10], ['TEMPRANA', 'B5', 30], ['AVANZADA', 'B4A', 1], ['AVANZADA', 'B5', 9], ['SIN', 'B4A', null], ['SIN', 'B5', null]] + .map(([estrato, categoria, n], i) => ({ periodo: '2025-S1', grupo: 'TOTAL', estrato, categoria, n, orden: i % 2, suprimido: n === null ? 1 : 0 })), +}); +describe('Porcentaje en cada estrato', () => { + it('cada categoría es la parte de su estrato, y un estrato con total suprimido no tiene porcentaje', () => { + // Fails if the share is taken over the whole period instead of the stratum, or drawn over an unknown total. + const { figure, cells } = stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro', {}, 'porcentaje'); + expect(cells.filter(c => c.stratum !== 'Sin dato').map(c => c.percent)).toEqual([25, 75, 10, 90]); + expect(cells.filter(c => c.stratum === 'Sin dato').map(c => c.percent)).toEqual([null, null]); + expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje del estrato'); + expect(stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro').figure.data[0]['x']).toEqual([10, 30]); + }); + it('las dimensiones de CaMa toman su etiqueta del catálogo, y CaCu conserva la suya', () => { + // Fails if a new stratifier is offered without its published label, or CaCu's wording changes. + const item = { id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] as ['semestre'], + filtros: [{ estrato: 'etapa', etiqueta: 'Etapa (temprana o avanzada)', valores: [{ valor: 'TEMPRANA', etiqueta: 'Temprana' }] }, + { estrato: 'grupo_edad', etiqueta: 'Grupo de edad', valores: [{ valor: '40-49', etiqueta: '40-49' }] }] }; + expect(stratifiedCapabilities(item)).toEqual(['grupo_edad', 'etapa']); + expect(etiquetaDimension(item, 'etapa')).toBe('Por etapa (temprana o avanzada)'); + expect(etiquetaDimension(item, 'grupo_edad')).toBe('Por grupo de edad'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-stratified.ts b/src/app/features/indicadores/indicadores-stratified.ts index a538df2..296dafd 100644 --- a/src/app/features/indicadores/indicadores-stratified.ts +++ b/src/app/features/indicadores/indicadores-stratified.ts @@ -4,14 +4,25 @@ import { c2Color, c2Theme } from './indicadores-c2-palette'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +// The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut. +const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'clasificacion', 'estadio', 'tamano', 'etapa']; +/** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */ +export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string { + if (d === 'grupo_edad') return 'Por grupo de edad'; + if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento'; + const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta; + return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d); +} +export type MedidaEstrato = 'conteo' | 'porcentaje'; export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] { return item.contrato === 'C2' && Array.isArray(item.filtros) - ? (['grupo_edad', 'estatus_seguimiento', 'birads'] as const).filter(d => item.filtros!.some(f => f?.estrato === d + ? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; } -export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } -export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } { +// `percent`: the cell's share of its stratum, when the stratum's total is known. +export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } +export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo'): { figure: PlotlyFigure; cells: StratifiedCell[] } { if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos']) || Object.keys(data['grupos']).length !== 1 @@ -43,21 +54,38 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas'); const cells: StratifiedCell[] = []; const theme = c2Theme(tema); + // The stratum's total: the one published, or else the sum of its cells when every one is published. A share is + // only drawn over a known total; a suppressed or missing total leaves the stratum without percentages. + const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record[] : []; + const totalDe = (s: string): number | null => { + const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup); + if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null; + const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s]))); + if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null; + const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0); + return suma > 0 ? suma : null; + }; + const porcentaje = medida === 'porcentaje'; const figure: PlotlyFigure = { data: strata.map((s, series) => { const selected = categories.map(([id, c]) => { const row = rows.get(JSON.stringify([id, s])); const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible'; const value = status === 'Publicado' ? row!['n'] as number : null; - cells.push({ category: c.label, stratum: labels[s] as string, value, status }); - return value; + const total = totalDe(s); + const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null; + cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status }); + return { value, percent, total }; }); - return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)), + const x = selected.map(v => porcentaje ? v.percent : v.value); + return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)), + customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']), marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, - hovertemplate: '%{y}
%{x}%{fullData.name}' }; - }), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true, + hovertemplate: porcentaje ? '%{y}
%{x:.1f} % (%{customdata[0]} de %{customdata[1]})%{fullData.name}' : '%{y}
%{x}%{fullData.name}' }; + }), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true, height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 }, - xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, + xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid } + : { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true }, legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } }; return { figure, cells }; diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 8459b37..681de79 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -20,9 +20,12 @@ export interface Indicador { vistas?: string[]; // Interactive donut and bars by one stratum, like CaCu's EU7. escenario?: VistaEscenario; + // How the breakdown by stratum opens: counts, or each category's share of its stratum. + medida_estrato?: 'conteo' | 'porcentaje'; } -export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads'; -export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads']; +// CaMa's stratifiers (brca, clasificacion, estadio, tamano, etapa) break down its quantities of interest. +export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads' | 'brca' | 'clasificacion' | 'estadio' | 'tamano' | 'etapa'; +export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads', 'brca', 'clasificacion', 'estadio', 'tamano', 'etapa']; // `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico». export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; } export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }