20261118 Color Fix

This commit is contained in:
Manuel Aurrecoechea Castillo
2026-11-18 16:10:11 -06:00
parent 97fcb37761
commit a217ddae38
12 changed files with 92 additions and 43 deletions
@@ -1,6 +1,6 @@
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
import { DonutHierarchy } from './indicadores-donut-drilldown';
import { c2Theme, groupBase, seriesColors } from './indicadores-c2-palette';
import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette';
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
// Normalized presentation nodes and a selection path are independent of Plotly.
@@ -81,7 +81,8 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
const colors = seriesColors(categories.map(c => c.color));
const colors = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
const bases = basesPorGrupo(parentIds);
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
@@ -109,7 +110,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
marker: { colors: parents.map((_, i) => groupBase(i)), line: { color: theme.outline, width: 0.7 } },
marker: { colors: parents.map(p => bases.get(p.id.replace(/^group:/, '')) ?? C2_PALETTE.series[0]), line: { color: theme.outline, width: 0.7 } },
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
}
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
@@ -22,7 +22,8 @@ describe('paleta del logo ISSSTELEON', () => {
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
expect(new Set(colors.slice(0, 3)).size).toBe(3);
expect(colors[3]).toBe(groupBase(1));
expect(colors[3]).toBe(C2_PALETTE.calidos[0]);
expect(colors[0]).not.toBe(C2_PALETTE.calidos[0]);
expect(colors[0]).not.toBe(colors[3]);
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
});
@@ -1,13 +1,16 @@
import { PlotlyFigure, Tema } from './indicadores.models';
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal.
// Logo lime plus the analogous and complementary hues chosen for the charts.
// Cool greens, teal and blue are the normal side. Rose, violet and purple are the abnormal side.
// Neutrals stay neutral. Sequential fills run from pale lime to deep teal.
const OWNED = new Set<string>();
function own(hex: string): string { OWNED.add(hex.toLowerCase()); return hex; }
export const C2_PALETTE = Object.freeze({
frios: Object.freeze([own('#A8C243'), own('#69C242'), own('#42C25C'), own('#42C29C'), own('#4269C2')]),
calidos: Object.freeze([own('#C24269'), own('#9C42C2'), own('#5C42C2'), own('#C2429C'), own('#8E2F62'), own('#7A3496')]),
series: Object.freeze([
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
'#A8C243', '#42C29C', '#C24269', '#9C42C2',
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
]),
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
@@ -31,20 +34,48 @@ function isCoffeeParsed(item: Parsed | undefined): boolean {
export function isCoffeeColor(color: string): boolean {
return isCoffeeParsed(parseColor(color));
}
export function c2Color(published: string | undefined, index: number): string {
// Coffee and orange-brown published swatches take the shared series. Other published colours stay.
export type Tono = 'frio' | 'calido' | 'neutro';
/** Metadata id: cool for normal groups, warm for abnormal ones. Unknown ids stay neutral. */
export function tonoDe(clave: string | undefined | null): Tono {
if (!clave) return 'neutro';
const id = clave.toUpperCase();
if (id.includes('SIN_DATO') || id.includes('SIN_BIOPSIA')) return 'neutro';
if (id.includes('NO_ANORMAL') || id.includes('NO_MALIG') || id.includes('BENIGN') || id.includes('NO_ALTER')) return 'frio';
if (id.includes('ANORMAL') || id.includes('MALIG') || id.includes('INVAS') || id.includes('IN_SITU') || id.includes('LIEAG') || id.includes('ALTER')) return 'calido';
if (/^(B4|B4A|B4B|B4C|B5|B6)$/.test(id) || /^BIRADS_[456]/.test(id)) return 'calido';
return 'neutro';
}
function poolDe(tono: Tono): readonly string[] {
if (tono === 'calido') return C2_PALETTE.calidos;
if (tono === 'frio') return C2_PALETTE.frios;
return C2_PALETTE.series;
}
export function c2Color(published: string | undefined, index: number, tono: Tono = 'neutro'): string {
// Coffee takes the cool or warm pool when the category metadata says which. Other published colours stay.
if (published && isAgeColor(published)) return published;
if (published && isNeutralColor(published)) return published;
if (published && isCoffeeColor(published)) return C2_PALETTE.series[index % C2_PALETTE.series.length];
const pool = poolDe(tono);
if (published && isCoffeeColor(published)) return pool[index % pool.length];
if (published && /^#[0-9a-f]{6}$/i.test(published)) return published;
return C2_PALETTE.series[index % C2_PALETTE.series.length];
return pool[index % pool.length];
}
/** One base hue per group, then lighter and darker steps so siblings stay related but distinct. */
/** One base per group: cool if the id is normal, warm if it is abnormal, then steps so siblings differ. */
export function basesPorGrupo(groups: readonly string[]): ReadonlyMap<string, string> {
const seen = { frio: 0, calido: 0, neutro: 0 };
const base = new Map<string, string>();
for (const id of [...new Set(groups)]) {
const tono = tonoDe(id);
const pool = poolDe(tono);
base.set(id, pool[seen[tono] % pool.length]);
seen[tono] += 1;
}
return base;
}
export function paintByGroup(groups: readonly string[]): string[] {
const order = [...new Set(groups)];
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)]));
const bases = basesPorGrupo(groups);
const counts = new Map([...bases.keys()].map(id => [id, groups.filter(g => g === id).length]));
const stairs = new Map([...bases].map(([id, color]) => [id, steps(color, counts.get(id)!)]));
const cursor = new Map<string, number>();
return groups.map(id => {
const index = cursor.get(id) ?? 0;
@@ -74,9 +105,14 @@ export function institutionalize(colors: readonly string[]): string[] {
});
}
/** Coffee published colours take the series; other published colours stay. */
export function seriesColors(published: readonly (string | undefined)[]): string[] {
return published.map((color, index) => c2Color(color, index));
/** Coffee published colours take the cool or warm pool of their metadata id. */
export function seriesColors(published: readonly (string | undefined)[], claves?: readonly (string | undefined)[]): string[] {
const seen = { frio: 0, calido: 0, neutro: 0 };
return published.map((color, index) => {
const tono = tonoDe(claves?.[index]);
const slot = tono === 'neutro' ? index : seen[tono]++;
return c2Color(color, slot, tono);
});
}
const NAMED: Record<string, [number, number, number]> = {
@@ -112,10 +148,13 @@ function parseColor(input: string): Parsed | undefined {
}
const lum = luminance({ r, g, b });
const neutral = sat < 0.18;
const harmonious = !neutral && (
(hue >= 64 && hue <= 188 && sat >= 0.22)
const swatch = '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
const harmonious = OWNED.has(swatch) || (!neutral && (
(hue >= 64 && hue <= 175 && sat >= 0.22)
|| (hue >= 200 && hue <= 320 && sat >= 0.22)
|| (hue >= 320 && hue < 356 && sat >= 0.28 && sat <= 0.78)
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|| (hue >= 40 && hue < 64 && sat <= 0.42));
|| (hue >= 40 && hue < 64 && sat <= 0.42)));
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
}
function steps(base: string, count: number): string[] {
@@ -87,7 +87,7 @@ describe('CAM-01, CAM-02 y CAM-03: histórico con las respuestas reales', () =>
expect(f.contrato).toBe('C2'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]);
expect(f.figure.data.map(t => [t['name'], (t['y'] as number[])[0]])).toEqual([
['Benigno', 7], ['Lesión de riesgo (B3)', 5], ['Carcinoma in situ', 6], ['Carcinoma invasor', 7], ['Sin biopsia reportada', 6], ['Sin dato', 6]]);
expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.series[2], C2_PALETTE.series[3], '#C9CDD2', '#C9CDD2']);
expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.calidos[0], C2_PALETTE.calidos[1], '#C9CDD2', '#C9CDD2']);
expect(f.figure.layout['barmode']).toBe('stack');
expect(f.comoLeer).toContain('pacientes');
});
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
@@ -106,12 +106,11 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
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 ordenGrupos = [...new Set(conColor.map(g => g.grupo))];
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);
const indice = ordenGrupos.indexOf(id);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice),
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.
@@ -1,5 +1,5 @@
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme } from './indicadores-c2-palette';
import { c2Color, c2Theme, tonoDe } from './indicadores-c2-palette';
import { percentNumber } from './indicadores-format';
// Two C2 indicators of the same finding: the exams by BI-RADS category and the patients by their most severe one.
@@ -82,7 +82,7 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
};
const color = (id: string, index: number) => {
const publicado = registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
return c2Color(publicado, index);
return c2Color(publicado, index, tonoDe(id));
};
const todas = par.grupos.flatMap(g => g.categorias);
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
@@ -125,9 +125,11 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
// Missing rows remain unavailable. Catalog order is used only for the accessible
// list of missing categories; a partial distribution is never drawn as a donut.
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const colores = paintByGroup(baseCategorias.map(c => c.grupo));
const claves = baseCategorias.map(c => c.grupo);
const bases = basesPorGrupo(claves);
const colores = paintByGroup(claves);
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
const grupos = [...new Set(categorias.map(c => c.grupo))].map((id, i) => ({ id, etiqueta: nombres[id], color: groupBase(i) }));
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! }));
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
const totals = porEscenario['totales_estrato'];
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
@@ -35,7 +35,7 @@ describe('Histopatología por BI-RADS: modelo', () => {
expect(m.filas.map(f => f.id)).toEqual(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']);
expect(m.filas.map(f => f.etiqueta)).toEqual(['BI-RADS 4 sin subtipo', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR']);
expect(m.categorias.map(c => c.color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.series[2], C2_PALETTE.series[3]]);
expect(m.categorias.map(c => c.color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.calidos[0], C2_PALETTE.calidos[1]]);
expect(m.grupos.map(g => [g.id, g.etiqueta, g.categorias])).toEqual([
['NO_MALIGNO', 'No maligno', ['BENIGNO', 'RIESGO_B3']], ['MALIGNO', 'Maligno', ['IN_SITU', 'INVASOR']]]);
expect(m.base).toBe('MALIGNO');
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme } from './indicadores-c2-palette';
import { C2_PALETTE, c2Color, c2Theme, tonoDe } from './indicadores-c2-palette';
import { Celda, wilson } from './indicadores-confirmacion-citologia';
import { percentNumber, shareText } from './indicadores-format';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
@@ -105,16 +105,20 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
if (Object.keys(cats).some(id => !conocidas.includes(id)) || OBLIGATORIAS.some(id => !Object.hasOwn(cats, id))) {
return fail('El catálogo no publica las categorías esperadas de la biopsia.');
}
const categorias: Categoria[] = CON_RESULTADO.filter(id => Object.hasOwn(cats, id)).map((id, index) => {
const curso = { frio: 0, calido: 0, neutro: 0 };
const categorias: Categoria[] = CON_RESULTADO.filter(id => Object.hasOwn(cats, id)).map(id => {
const c = cats[id];
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && c['color'] !== undefined && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Categorías de biopsia incompatibles.');
const publicado = (c['color'] as string | null | undefined) ?? COLOR_RESPALDO;
return { id, etiqueta: c['etiqueta'], color: c2Color(publicado, index), grupo: c['grupo'] };
const tono = tonoDe(c['grupo']);
return { id, etiqueta: c['etiqueta'], color: c2Color(publicado, curso[tono]++, tono), grupo: c['grupo'] };
});
const grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => {
const propias = categorias.filter(c => c.grupo === id);
return { id, etiqueta: id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!, color: promedio(propias.map(c => c.color)), categorias: propias.map(c => c.id) };
const tono = tonoDe(id);
const color = tono === 'calido' ? C2_PALETTE.calidos[0] : tono === 'frio' ? C2_PALETTE.frios[0] : promedio(propias.map(c => c.color));
return { id, etiqueta: id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!, color, categorias: propias.map(c => c.id) };
});
if (grupos.length !== 2) return fail('Se esperaban dos grupos de resultados.');
const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo;
@@ -77,7 +77,7 @@ describe('Histórico: C2 (conteos por categoría)', () => {
it('apila las categorías en el orden que publica el indicador, con sus colores y etiquetas', () => {
const f = fig(d(completo));
expect(f.data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
expect((f.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
expect((f.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.calidos[0]);
expect(f.data[0]['y']).toEqual([4, 4, 4, 4]);
expect(f.layout['barmode']).toBe('stack');
expect((f.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
@@ -1,5 +1,5 @@
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
import { sortedPeriods } from './indicadores-periodos';
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
@@ -141,13 +141,16 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
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));
const sinDato = periodos.filter(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) ? n : null; });
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
marker: { color: c2Color(color, i) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
comoLeer: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
suprimidos, sinDato,
@@ -43,7 +43,7 @@ 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);
const palette = seriesColors(categories.map(([, c]) => c.color));
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
const figure: PlotlyFigure = { data: strata.map((s, series) => {
const selected = categories.map(([id, c]) => {
const row = rows.get(JSON.stringify([id, s]));