feat(indicadores): breakdown by CaMa's stratifiers, in counts or as each category's share of its stratum

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.
This commit is contained in:
rockdrigo
2026-11-12 19:19:37 -06:00
parent 710790b98e
commit c076e1e7a9
5 changed files with 99 additions and 18 deletions
@@ -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';
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
}
@if (dimension) {
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
}
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
}
@@ -70,8 +76,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
<details><summary>Valores publicados</summary>
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
</tbody></table></div>
</details>
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
@@ -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 }),
@@ -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',()=>{
@@ -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');
});
});
@@ -4,14 +4,25 @@ import { c2Color, c2Theme } from './indicadores-c2-palette';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// 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<string, unknown>[] : [];
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}<br>%{x}<extra>%{fullData.name}</extra>' };
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
}), 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 };
@@ -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 }[]; }