From 4929def121241cc7dc7318c4e6c01e5e082b62f6 Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 1 Dec 2026 13:42:54 -0600 Subject: [PATCH] F1g: whole-number axes, risk list link, dotted timeline, head map Share the integer tick rule between Trazabilidad and TEA record figures. Use the plotted extent, including stacked totals or interval bounds, to target four divisions. Round spacing up to a 1/2/5 step with a minimum of one, anchor ticks at zero, ignore nonfinite values, and include integer bounds when a fractional extent contains no integer. Point the existing patient link at the TEA risk route and remove the details accordion and separate risk action. Exercise the link from the risk list in the existing patient page case. Connect completed diamonds in step order on the existing marker trace, using its color for the dotted line and retaining the duration bars and annotations. The scalp figure used the ear electrodes as markers outside the circle, omitted the ears, and masked sample centers without clipping Plotly's rendered contour cells at the scalp boundary. Its interpolation also colored distant areas with no adjacent sample. Use the reference's 19 scalp positions, nose and ear paths, and reverse-wound mask painted in the card's white surface color beneath the outline. Derive the mask and the existing 41-point grid in headMapGeometry. Use the reference's 0.45 interpolation reach with inverse squared distance, taking a coincident sample directly and preserving the existing zone inputs and z color scale. Test mirror positions, scalp bounds, and plotted contour values. Prettier, Ruff check, Ruff format check, and git diff --check passed. Angular and Playwright execution are reserved for the test machines. --- e2e/pages.spec.ts | 11 ++ src/app/indicadores/figures.ts | 55 ++++++-- src/app/indicadores/tab-riesgos-tea.html | 49 +------ src/app/indicadores/tab-riesgos-tea.scss | 7 - src/app/indicadores/tab-riesgos-tea.ts | 5 - src/app/indicadores/tea-indicators.spec.ts | 33 +++++ src/app/paciente/tea-figures.ts | 152 ++++++++++++--------- src/app/paciente/tea-patient.spec.ts | 28 +++- 8 files changed, 203 insertions(+), 137 deletions(-) diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index 5d83f68..2044ec5 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -120,6 +120,17 @@ test('tea patient: the record and the risk page load and export to PDF', async ( expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch( /^tea-riesgos-/, ); + await page.goto('/indicadores/tea'); + await page.getByRole('tab', { name: 'Análisis de riesgo' }).click(); + const riskList = page.locator('app-tab-riesgos-tea table.worklist'); + const patientLink = riskList.getByRole('row').nth(1).getByRole('link'); + await expect(patientLink).toHaveAttribute( + 'href', + /\/indicadores\/tea\/pacientes\/[^/]+\/riesgo$/, + ); + await patientLink.click(); + await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+\/riesgo$/); + await expect(page.getByRole('heading', { name: 'Análisis de riesgo TEA' })).toBeVisible(); expect(problems).toEqual([]); }); diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts index 3b7ea5d..2db9d60 100644 --- a/src/app/indicadores/figures.ts +++ b/src/app/indicadores/figures.ts @@ -409,6 +409,28 @@ export function ageShare(r: Reading, axis: string): Figure { }; } +export function wholeNumberAxis(values: Iterable) { + let min = Infinity; + let max = -Infinity; + for (const value of values) { + if (value == null || !Number.isFinite(value)) continue; + min = Math.min(min, value); + max = Math.max(max, value); + } + const target = Math.max(1, (max - min) / 4); + const magnitude = 10 ** Math.floor(Math.log10(target)); + const step = [1, 2, 5, 10].find((step) => step * magnitude >= target) ?? 1; + return { + tickmode: 'linear' as const, + tick0: 0, + dtick: step * magnitude, + tickformat: '.0f', + ...(Math.ceil(min) > Math.floor(max) && min <= max + ? { range: [Math.floor(min), Math.ceil(max)] } + : {}), + }; +} + export function historyFigure( panel: HistoryPanel, series: { label: string; r: Reading | undefined }[], @@ -416,9 +438,9 @@ export function historyFigure( xTitle: string, ): Figure { const x = series.map((s) => s.label); - const layout = (y: string) => ({ + const layout = (y: string, values: (number | null)[]) => ({ xaxis: { title: { text: xTitle }, type: 'category' as const }, - yaxis: { title: { text: y } }, + yaxis: { title: { text: y }, ...wholeNumberAxis(values) }, }); if (panel.kind === 'stack') { const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))]; @@ -429,24 +451,31 @@ export function historyFigure( .filter((c) => !declared.some((d) => d.code === c)) .map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })), ]; + const data = named.map((c) => ({ + type: 'bar' as const, + name: c.label, + x, + y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0), + marker: { color: c.color }, + })); + const totals = x.map((_, i) => data.reduce((sum, trace) => sum + trace.y[i], 0)); return { - data: named.map((c) => ({ - type: 'bar', - name: c.label, - x, - y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0), - marker: { color: c.color }, - })), - layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' }, + data, + layout: { ...layout(panel.axis ?? 'Pacientes', [0, ...totals]), barmode: 'stack' }, }; } const k = panel.kind === 'percent' ? 100 : 1; const at = (v?: number) => (v === undefined ? null : v * k); + const band = [ + ...series.map((s) => at(s.r?.high)), + ...[...series].reverse().map((s) => at(s.r?.low)), + ]; + const scores = series.map((s) => at(s.r?.score)); return { data: [ { x: [...x, ...[...x].reverse()], - y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))], + y: band, mode: 'lines', fill: 'toself', fillcolor: line + '33', @@ -456,14 +485,14 @@ export function historyFigure( }, { x, - y: series.map((s) => at(s.r?.score)), + y: scores, mode: 'lines+markers', name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana', line: { color: line }, marker: { color: line }, }, ], - layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'), + layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días', [...band, ...scores]), }; } diff --git a/src/app/indicadores/tab-riesgos-tea.html b/src/app/indicadores/tab-riesgos-tea.html index 2446657..9d7b476 100644 --- a/src/app/indicadores/tab-riesgos-tea.html +++ b/src/app/indicadores/tab-riesgos-tea.html @@ -161,22 +161,9 @@ {{ row.recordNumbers.join(', ') || '—' }} - + {{ row.name || '—' }} -
- @if (row.pairs.length) { - - } - Riesgo -
{{ row.patient.gender ? name(row.patient.gender) : '—' }} {{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }} @@ -187,40 +174,6 @@ {{ formatProbability(row.headline?.probability) }} {{ formatProbability(row.headline?.reference) }} - @if (expanded()[id] && row.pairs.length) { - - - - - - - - - - - - - - - - @for (pair of row.pairs; track pair.pair) { - - - - - - - - - - } - -
ParRazón de momiosIC 95 %qProbabilidadProbabilidad de referenciaMismo sentido
{{ pair.title }}{{ formatOr(pair.or) }}{{ formatIc(pair.low, pair.high) }}{{ formatQ(pair.q) }}{{ formatProbability(pair.probability) }}{{ formatProbability(pair.reference) }} - {{ pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' }} -
- - - } } @empty { No hay registros para los filtros aplicados. diff --git a/src/app/indicadores/tab-riesgos-tea.scss b/src/app/indicadores/tab-riesgos-tea.scss index 9258d38..f6a74d2 100644 --- a/src/app/indicadores/tab-riesgos-tea.scss +++ b/src/app/indicadores/tab-riesgos-tea.scss @@ -18,10 +18,3 @@ margin-bottom: 0; list-style: none; } - -.row-actions { - display: flex; - flex-wrap: wrap; - align-items: center; - gap: var(--space-3); -} diff --git a/src/app/indicadores/tab-riesgos-tea.ts b/src/app/indicadores/tab-riesgos-tea.ts index 0d11fe0..1c03a24 100644 --- a/src/app/indicadores/tab-riesgos-tea.ts +++ b/src/app/indicadores/tab-riesgos-tea.ts @@ -71,7 +71,6 @@ export class TabRiesgosTea { protected readonly associationOptions = ['all', 'with', 'without'] as const; protected readonly size = signal(20); protected readonly index = signal(0); - protected readonly expanded = signal>({}); protected readonly exporting = signal(false); protected readonly actionError = signal(''); @@ -136,10 +135,6 @@ export class TabRiesgosTea { this.filters.update((filters) => ({ ...filters, [key]: value })); } - protected toggle(id: string): void { - this.expanded.update((open) => ({ ...open, [id]: !open[id] })); - } - protected async export(): Promise { this.exporting.set(true); this.actionError.set(''); diff --git a/src/app/indicadores/tea-indicators.spec.ts b/src/app/indicadores/tea-indicators.spec.ts index e92e31b..ed84f29 100644 --- a/src/app/indicadores/tea-indicators.spec.ts +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -3,6 +3,7 @@ import { EXT } from '../fhir'; import { teaSteps } from '../paciente/tea-data'; import { ageStack, + historyFigure, nestedDonut, sexCountBars, shareDonut, @@ -129,6 +130,38 @@ function fixture(): Bundle { } describe('TEA indicators', () => { + it('uses integer ticks and spaces them using the stacked totals', () => { + const panel = { title: 'Pacientes', measure: 'M23', kind: 'stack' } as const; + const figure = (count: number) => + historyFigure( + panel, + [ + { + label: 'Enero', + r: { + populations: {}, + strata: { + category: { + confirmed: { 'initial-population': count }, + in_process: { 'initial-population': count }, + }, + }, + }, + }, + ], + '#123456', + 'Mes', + ); + + expect(figure(1).layout?.yaxis).toMatchObject({ + tickmode: 'linear', + tick0: 0, + dtick: 1, + tickformat: '.0f', + }); + expect(figure(100).layout?.yaxis?.dtick).toBe(50); + }); + it('builds the category and group rings from the supplied counts', () => { const catalog: Catalog = { groups: [{ id: 'female', label: 'Femenino', color: '#123456' }], diff --git a/src/app/paciente/tea-figures.ts b/src/app/paciente/tea-figures.ts index cfb672f..4a10276 100644 --- a/src/app/paciente/tea-figures.ts +++ b/src/app/paciente/tea-figures.ts @@ -1,4 +1,5 @@ import { banded } from '../gobernanza/figures'; +import { wholeNumberAxis } from '../indicadores/figures'; import { Figure, PALETTE } from '../plot'; import { Metric, Pair, Site, Study, TeaStep, zoneLabel } from './tea-data'; @@ -32,7 +33,8 @@ export function timeline(steps: TeaStep[]): Figure | null { bars, { type: 'scatter', - mode: 'markers', + mode: 'lines+markers', + line: { dash: 'dot', color: PALETTE[0] }, x: done.map((step) => step.date), y: done.map((step) => step.label), marker: { @@ -94,63 +96,83 @@ export function timeline(steps: TeaStep[]): Figure | null { }; } -const electrodes: Record = { - Fp1: [-0.3, 0.87], - Fpz: [0, 0.93], - Fp2: [0.3, 0.87], - F7: [-0.78, 0.49], - F3: [-0.42, 0.51], - Fz: [0, 0.53], - F4: [0.42, 0.51], - F8: [0.78, 0.49], - T3: [-0.93, 0], - C3: [-0.49, 0], - Cz: [0, 0], - C4: [0.49, 0], - T4: [0.93, 0], - T5: [-0.78, -0.49], - P3: [-0.42, -0.51], - Pz: [0, -0.53], - P4: [0.42, -0.51], - T6: [0.78, -0.49], - O1: [-0.3, -0.87], - Oz: [0, -0.93], - O2: [0.3, -0.87], - A1: [-1.08, 0], - A2: [1.08, 0], -}; - -const zones: Record = { - global: [0, 0], - posterior: [0, -0.72], - frontal_left: [-0.5, 0.62], - frontal_right: [0.5, 0.62], - frontal_midline: electrodes['Fz'], - central: electrodes['Cz'], - parietal: electrodes['Pz'], - temporal_left: [-0.82, -0.25], - temporal_right: [0.82, -0.25], - occipital: [0, -0.86], -}; +export function headMapGeometry() { + const electrodes: Record = { + Fp1: [-0.25, 0.77], + Fp2: [0.25, 0.77], + F7: [-0.65, 0.47], + F3: [-0.33, 0.4], + Fz: [0, 0.38], + F4: [0.33, 0.4], + F8: [0.65, 0.47], + T3: [-0.8, 0], + C3: [-0.4, 0], + Cz: [0, 0], + C4: [0.4, 0], + T4: [0.8, 0], + T5: [-0.65, -0.47], + P3: [-0.33, -0.4], + Pz: [0, -0.38], + P4: [0.33, -0.4], + T6: [0.65, -0.47], + O1: [-0.25, -0.77], + O2: [0.25, -0.77], + }; + const grid = Array.from({ length: 41 }, (_, i) => (i - 20) / 20); + const inside = grid.map((y) => grid.map((x) => x * x + y * y <= 1)); + const boundary = Array.from({ length: 96 }, (_, i) => { + const angle = (-2 * Math.PI * i) / 96; + return `${i ? 'L' : 'M'} ${Math.cos(angle).toFixed(4)} ${Math.sin(angle).toFixed(4)}`; + }).join(' '); + const line = { color: '#17324d', width: 2 }; + const shapes: NonNullable['shapes']> = [ + { + type: 'path', + path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${boundary} Z`, + fillcolor: '#ffffff', + line: { width: 0 }, + }, + { type: 'circle', x0: -1, x1: 1, y0: -1, y1: 1, line }, + { type: 'path', path: 'M -0.13 0.99 L 0 1.13 L 0.13 0.99', line }, + { type: 'path', path: 'M -0.99 0.14 Q -1.1 0.12 -1.08 0 Q -1.1 -0.12 -0.99 -0.14', line }, + { type: 'path', path: 'M 0.99 0.14 Q 1.1 0.12 1.08 0 Q 1.1 -0.12 0.99 -0.14', line }, + ]; + return { electrodes, grid, inside, shapes }; +} export function headMap(sites: Site[]): Figure { + const { electrodes, grid, inside, shapes } = headMapGeometry(); + const zones: Record = { + global: [0, 0], + posterior: [0, -0.72], + frontal_left: [-0.5, 0.62], + frontal_right: [0.5, 0.62], + frontal_midline: electrodes['Fz'], + central: electrodes['Cz'], + parietal: electrodes['Pz'], + temporal_left: [-0.82, -0.25], + temporal_right: [0.82, -0.25], + occipital: [0, -0.86], + }; const samples = sites.flatMap((site) => { const point = (site.kind === 'electrode' ? electrodes : zones)[site.name]; return point && site.z != null && Number.isFinite(site.z) ? [{ point, z: site.z }] : []; }); - const grid = Array.from({ length: 41 }, (_, i) => (i - 20) / 20); const data: Figure['data'] = []; if (samples.length) { - const surface = grid.map((y) => - grid.map((x) => { - if (x * x + y * y > 1) return null; - const weights = samples.map( - ({ point }) => 1 / Math.max(1e-6, (x - point[0]) ** 2 + (y - point[1]) ** 2), - ); - return ( - samples.reduce((sum, site, i) => sum + site.z * weights[i], 0) / - weights.reduce((sum, weight) => sum + weight, 0) - ); + const surface = grid.map((y, row) => + grid.map((x, col) => { + if (!inside[row][col]) return null; + let total = 0; + let weights = 0; + for (const { point, z } of samples) { + const distanceSquared = (x - point[0]) ** 2 + (y - point[1]) ** 2; + if (distanceSquared < 1e-9) return z; + if (distanceSquared > 0.45 ** 2) continue; + total += z / distanceSquared; + weights += 1 / distanceSquared; + } + return weights ? total / weights : null; }), ); const limit = Math.max(2, ...samples.map((site) => Math.abs(site.z))); @@ -166,7 +188,9 @@ export function headMap(sites: Site[]): Figure { [0.5, '#f7f7f7'], [1, '#c24269'], ], - contours: { coloring: 'heatmap', showlines: false }, + connectgaps: false, + contours: { coloring: 'heatmap', showlines: true }, + line: { width: 0.5, color: 'rgba(8,24,57,.3)' }, hoverinfo: 'skip', colorbar: { title: { text: 'z' } }, }); @@ -180,6 +204,7 @@ export function headMap(sites: Site[]): Figure { y: markers.map(([, point]) => point[1]), text: markers.map(([name]) => name), textposition: 'top center', + textfont: { size: 9, color: '#17324d' }, marker: { color: '#17324d', size: 5 }, hovertemplate: '%{text}', }); @@ -189,14 +214,7 @@ export function headMap(sites: Site[]): Figure { showlegend: false, xaxis: { visible: false, range: [-1.25, 1.25], constrain: 'domain' }, yaxis: { visible: false, range: [-1.13, 1.18], scaleanchor: 'x', scaleratio: 1 }, - shapes: [ - { type: 'circle', x0: -1, x1: 1, y0: -1, y1: 1, line: { color: '#17324d', width: 2 } }, - { - type: 'path', - path: 'M -0.13,0.99 L 0,1.12 L 0.13,0.99', - line: { color: '#17324d', width: 2 }, - }, - ], + shapes, }, }; } @@ -232,7 +250,13 @@ export function ageNorm(rows: Centile[], metric: Metric, age: number): Figure { ], layout: { xaxis: { title: { text: 'Edad (meses)' } }, - yaxis: { title: { text: metric.unit ?? 'Valor' } }, + yaxis: { + title: { text: metric.unit ?? 'Valor' }, + ...wholeNumberAxis([ + metric.value, + ...rows.flatMap(({ p5, median, p95 }) => [p5, median, p95]), + ]), + }, }, }; } @@ -307,7 +331,11 @@ export function zBars(eeg: Study): SingleTrace { }, ], layout: { - xaxis: { title: { text: 'Puntuación z' }, range: [-limit, limit] }, + xaxis: { + title: { text: 'Puntuación z' }, + range: [-limit, limit], + ...wholeNumberAxis([-limit, limit]), + }, yaxis: { autorange: 'reversed', automargin: true }, shapes: [ { @@ -366,7 +394,7 @@ export function probabilityCurve( data, layout: { xaxis: { title: { text: 'Puntuación z' } }, - yaxis: { title: { text: 'Probabilidad (%)' }, range: [0, 100] }, + yaxis: { title: { text: 'Probabilidad (%)' }, range: [0, 100], ...wholeNumberAxis([0, 100]) }, }, }; } diff --git a/src/app/paciente/tea-patient.spec.ts b/src/app/paciente/tea-patient.spec.ts index 9677359..726bbb3 100644 --- a/src/app/paciente/tea-patient.spec.ts +++ b/src/app/paciente/tea-patient.spec.ts @@ -2,7 +2,15 @@ import type { Observation, Patient } from 'fhir/r4'; import { describe, expect, it } from 'vitest'; import { EXT } from '../fhir'; import { identityRows, Metric, Pair, pairTitle, TeaStep, zoneLabel } from './tea-data'; -import { ageNorm, forest, headMap, probabilityCurve, timeline, zBars } from './tea-figures'; +import { + ageNorm, + forest, + headMap, + headMapGeometry, + probabilityCurve, + timeline, + zBars, +} from './tea-figures'; import { forestTitle, probabilityTitle, @@ -122,7 +130,21 @@ describe('Figuras del paciente TEA', () => { mode: 'text+markers', text: expect.arrayContaining(['O1', 'Cz']), }); - expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'circle' }); + const { electrodes, shapes } = headMapGeometry(); + expect(figure.layout?.shapes).toEqual(shapes); + expect(shapes.map((shape) => shape.type)).toEqual(['path', 'circle', 'path', 'path', 'path']); + expect(shapes[1]).toMatchObject({ x0: -1, x1: 1, y0: -1, y1: 1 }); + for (const [x, y] of Object.values(electrodes)) { + expect(Math.hypot(x, y)).toBeLessThan(1); + if (x !== 0) expect(Object.values(electrodes)).toContainEqual([-x, y]); + } + + const contour = figure.data[0] as { x: number[]; y: number[] }; + grid.forEach((row, j) => + row.forEach((z, i) => { + if (z !== null) expect(Math.hypot(contour.x[i], contour.y[j])).toBeLessThanOrEqual(1); + }), + ); }); it('dibuja los centiles del campeón y el valor observado a la edad del paciente', () => { @@ -162,6 +184,8 @@ describe('Figuras del paciente TEA', () => { const figure = timeline(steps)!; const markers = figure.data.find((trace) => trace.type === 'scatter')!; expect(markers).toMatchObject({ + mode: 'lines+markers', + line: { dash: 'dot' }, marker: expect.objectContaining({ symbol: 'diamond' }), x: ['2025-11-01', '2025-11-22'], y: ['M-CHAT', 'Psicología'],