Merge parity/F1g

This commit is contained in:
2026-12-01 13:45:25 -06:00
8 changed files with 203 additions and 137 deletions
+11
View File
@@ -126,6 +126,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( expect(await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf')).toMatch(
/^tea-riesgos-/, /^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([]); expect(problems).toEqual([]);
}); });
+39 -10
View File
@@ -410,6 +410,28 @@ export function ageShare(r: Reading, axis: string): Figure {
}; };
} }
export function wholeNumberAxis(values: Iterable<number | null | undefined>) {
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( export function historyFigure(
panel: HistoryPanel, panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[], series: { label: string; r: Reading | undefined }[],
@@ -417,9 +439,9 @@ export function historyFigure(
xTitle: string, xTitle: string,
): Figure { ): Figure {
const x = series.map((s) => s.label); 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 }, xaxis: { title: { text: xTitle }, type: 'category' as const },
yaxis: { title: { text: y } }, yaxis: { title: { text: y }, ...wholeNumberAxis(values) },
}); });
if (panel.kind === 'stack') { if (panel.kind === 'stack') {
const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))]; const found = [...new Set(series.flatMap((s) => Object.keys(s.r?.strata['category'] ?? {})))];
@@ -430,24 +452,31 @@ export function historyFigure(
.filter((c) => !declared.some((d) => d.code === c)) .filter((c) => !declared.some((d) => d.code === c))
.map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })), .map((c, i) => ({ code: c, label: name(c), color: PALETTE[i % PALETTE.length] })),
]; ];
return { const data = named.map((c) => ({
data: named.map((c) => ({ type: 'bar' as const,
type: 'bar',
name: c.label, name: c.label,
x, x,
y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0), y: series.map((s) => s.r?.strata['category']?.[c.code]?.['initial-population'] ?? 0),
marker: { color: c.color }, marker: { color: c.color },
})), }));
layout: { ...layout(panel.axis ?? 'Pacientes'), barmode: 'stack' }, const totals = x.map((_, i) => data.reduce((sum, trace) => sum + trace.y[i], 0));
return {
data,
layout: { ...layout(panel.axis ?? 'Pacientes', [0, ...totals]), barmode: 'stack' },
}; };
} }
const k = panel.kind === 'percent' ? 100 : 1; const k = panel.kind === 'percent' ? 100 : 1;
const at = (v?: number) => (v === undefined ? null : v * k); 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 { return {
data: [ data: [
{ {
x: [...x, ...[...x].reverse()], x: [...x, ...[...x].reverse()],
y: [...series.map((s) => at(s.r?.high)), ...[...series].reverse().map((s) => at(s.r?.low))], y: band,
mode: 'lines', mode: 'lines',
fill: 'toself', fill: 'toself',
fillcolor: line + '33', fillcolor: line + '33',
@@ -457,14 +486,14 @@ export function historyFigure(
}, },
{ {
x, x,
y: series.map((s) => at(s.r?.score)), y: scores,
mode: 'lines+markers', mode: 'lines+markers',
name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana', name: panel.kind === 'percent' ? 'Porcentaje' : 'Mediana',
line: { color: line }, line: { color: line },
marker: { color: line }, marker: { color: line },
}, },
], ],
layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días'), layout: layout(panel.kind === 'percent' ? 'Porcentaje' : 'Días', [...band, ...scores]),
}; };
} }
+1 -48
View File
@@ -161,22 +161,9 @@
<tr> <tr>
<td>{{ row.recordNumbers.join(', ') || '—' }}</td> <td>{{ row.recordNumbers.join(', ') || '—' }}</td>
<td> <td>
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id]"> <a [routerLink]="['/indicadores', 'tea', 'pacientes', id, 'riesgo']">
{{ row.name || '—' }} {{ row.name || '—' }}
</a> </a>
<div class="row-actions">
@if (row.pairs.length) {
<button
mat-button
type="button"
(click)="toggle(id)"
[attr.aria-expanded]="expanded()[id] ?? false"
>
{{ expanded()[id] ? 'Ocultar' : 'Ver detalles' }}
</button>
}
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id, 'riesgo']">Riesgo</a>
</div>
</td> </td>
<td>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td> <td>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td>
<td>{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }}</td> <td>{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }}</td>
@@ -187,40 +174,6 @@
<td>{{ formatProbability(row.headline?.probability) }}</td> <td>{{ formatProbability(row.headline?.probability) }}</td>
<td>{{ formatProbability(row.headline?.reference) }}</td> <td>{{ formatProbability(row.headline?.reference) }}</td>
</tr> </tr>
@if (expanded()[id] && row.pairs.length) {
<tr>
<td colspan="10">
<table class="plain pairs">
<thead>
<tr>
<th>Par</th>
<th>Razón de momios</th>
<th>IC 95 %</th>
<th>q</th>
<th>Probabilidad</th>
<th>Probabilidad de referencia</th>
<th>Mismo sentido</th>
</tr>
</thead>
<tbody>
@for (pair of row.pairs; track pair.pair) {
<tr>
<td>{{ pair.title }}</td>
<td>{{ formatOr(pair.or) }}</td>
<td>{{ formatIc(pair.low, pair.high) }}</td>
<td>{{ formatQ(pair.q) }}</td>
<td>{{ formatProbability(pair.probability) }}</td>
<td>{{ formatProbability(pair.reference) }}</td>
<td>
{{ pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' }}
</td>
</tr>
}
</tbody>
</table>
</td>
</tr>
}
} @empty { } @empty {
<tr> <tr>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td> <td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
-7
View File
@@ -18,10 +18,3 @@
margin-bottom: 0; margin-bottom: 0;
list-style: none; list-style: none;
} }
.row-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
}
-5
View File
@@ -71,7 +71,6 @@ export class TabRiesgosTea {
protected readonly associationOptions = ['all', 'with', 'without'] as const; protected readonly associationOptions = ['all', 'with', 'without'] as const;
protected readonly size = signal(20); protected readonly size = signal(20);
protected readonly index = signal(0); protected readonly index = signal(0);
protected readonly expanded = signal<Record<string, boolean>>({});
protected readonly exporting = signal(false); protected readonly exporting = signal(false);
protected readonly actionError = signal(''); protected readonly actionError = signal('');
@@ -136,10 +135,6 @@ export class TabRiesgosTea {
this.filters.update((filters) => ({ ...filters, [key]: value })); this.filters.update((filters) => ({ ...filters, [key]: value }));
} }
protected toggle(id: string): void {
this.expanded.update((open) => ({ ...open, [id]: !open[id] }));
}
protected async export(): Promise<void> { protected async export(): Promise<void> {
this.exporting.set(true); this.exporting.set(true);
this.actionError.set(''); this.actionError.set('');
@@ -4,6 +4,7 @@ import { teaSteps } from '../paciente/tea-data';
import { import {
ageShare, ageShare,
ageStack, ageStack,
historyFigure,
nestedDonut, nestedDonut,
sexCountBars, sexCountBars,
shareDonut, shareDonut,
@@ -130,6 +131,38 @@ function fixture(): Bundle {
} }
describe('TEA indicators', () => { 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', () => { it('builds the category and group rings from the supplied counts', () => {
const catalog: Catalog = { const catalog: Catalog = {
groups: [{ id: 'female', label: 'Femenino', color: '#123456' }], groups: [{ id: 'female', label: 'Femenino', color: '#123456' }],
+80 -52
View File
@@ -1,4 +1,5 @@
import { banded } from '../gobernanza/figures'; import { banded } from '../gobernanza/figures';
import { wholeNumberAxis } from '../indicadores/figures';
import { Figure, PALETTE } from '../plot'; import { Figure, PALETTE } from '../plot';
import { Metric, Pair, Site, Study, TeaStep, zoneLabel } from './tea-data'; import { Metric, Pair, Site, Study, TeaStep, zoneLabel } from './tea-data';
@@ -32,7 +33,8 @@ export function timeline(steps: TeaStep[]): Figure | null {
bars, bars,
{ {
type: 'scatter', type: 'scatter',
mode: 'markers', mode: 'lines+markers',
line: { dash: 'dot', color: PALETTE[0] },
x: done.map((step) => step.date), x: done.map((step) => step.date),
y: done.map((step) => step.label), y: done.map((step) => step.label),
marker: { marker: {
@@ -94,33 +96,53 @@ export function timeline(steps: TeaStep[]): Figure | null {
}; };
} }
const electrodes: Record<string, [number, number]> = { export function headMapGeometry() {
Fp1: [-0.3, 0.87], const electrodes: Record<string, [number, number]> = {
Fpz: [0, 0.93], Fp1: [-0.25, 0.77],
Fp2: [0.3, 0.87], Fp2: [0.25, 0.77],
F7: [-0.78, 0.49], F7: [-0.65, 0.47],
F3: [-0.42, 0.51], F3: [-0.33, 0.4],
Fz: [0, 0.53], Fz: [0, 0.38],
F4: [0.42, 0.51], F4: [0.33, 0.4],
F8: [0.78, 0.49], F8: [0.65, 0.47],
T3: [-0.93, 0], T3: [-0.8, 0],
C3: [-0.49, 0], C3: [-0.4, 0],
Cz: [0, 0], Cz: [0, 0],
C4: [0.49, 0], C4: [0.4, 0],
T4: [0.93, 0], T4: [0.8, 0],
T5: [-0.78, -0.49], T5: [-0.65, -0.47],
P3: [-0.42, -0.51], P3: [-0.33, -0.4],
Pz: [0, -0.53], Pz: [0, -0.38],
P4: [0.42, -0.51], P4: [0.33, -0.4],
T6: [0.78, -0.49], T6: [0.65, -0.47],
O1: [-0.3, -0.87], O1: [-0.25, -0.77],
Oz: [0, -0.93], O2: [0.25, -0.77],
O2: [0.3, -0.87], };
A1: [-1.08, 0], const grid = Array.from({ length: 41 }, (_, i) => (i - 20) / 20);
A2: [1.08, 0], 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<NonNullable<Figure['layout']>['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 };
}
const zones: Record<string, [number, number]> = { export function headMap(sites: Site[]): Figure {
const { electrodes, grid, inside, shapes } = headMapGeometry();
const zones: Record<string, [number, number]> = {
global: [0, 0], global: [0, 0],
posterior: [0, -0.72], posterior: [0, -0.72],
frontal_left: [-0.5, 0.62], frontal_left: [-0.5, 0.62],
@@ -131,26 +153,26 @@ const zones: Record<string, [number, number]> = {
temporal_left: [-0.82, -0.25], temporal_left: [-0.82, -0.25],
temporal_right: [0.82, -0.25], temporal_right: [0.82, -0.25],
occipital: [0, -0.86], occipital: [0, -0.86],
}; };
export function headMap(sites: Site[]): Figure {
const samples = sites.flatMap((site) => { const samples = sites.flatMap((site) => {
const point = (site.kind === 'electrode' ? electrodes : zones)[site.name]; const point = (site.kind === 'electrode' ? electrodes : zones)[site.name];
return point && site.z != null && Number.isFinite(site.z) ? [{ point, z: site.z }] : []; 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'] = []; const data: Figure['data'] = [];
if (samples.length) { if (samples.length) {
const surface = grid.map((y) => const surface = grid.map((y, row) =>
grid.map((x) => { grid.map((x, col) => {
if (x * x + y * y > 1) return null; if (!inside[row][col]) return null;
const weights = samples.map( let total = 0;
({ point }) => 1 / Math.max(1e-6, (x - point[0]) ** 2 + (y - point[1]) ** 2), let weights = 0;
); for (const { point, z } of samples) {
return ( const distanceSquared = (x - point[0]) ** 2 + (y - point[1]) ** 2;
samples.reduce((sum, site, i) => sum + site.z * weights[i], 0) / if (distanceSquared < 1e-9) return z;
weights.reduce((sum, weight) => sum + weight, 0) 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))); 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'], [0.5, '#f7f7f7'],
[1, '#c24269'], [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', hoverinfo: 'skip',
colorbar: { title: { text: 'z' } }, colorbar: { title: { text: 'z' } },
}); });
@@ -180,6 +204,7 @@ export function headMap(sites: Site[]): Figure {
y: markers.map(([, point]) => point[1]), y: markers.map(([, point]) => point[1]),
text: markers.map(([name]) => name), text: markers.map(([name]) => name),
textposition: 'top center', textposition: 'top center',
textfont: { size: 9, color: '#17324d' },
marker: { color: '#17324d', size: 5 }, marker: { color: '#17324d', size: 5 },
hovertemplate: '%{text}<extra></extra>', hovertemplate: '%{text}<extra></extra>',
}); });
@@ -189,14 +214,7 @@ export function headMap(sites: Site[]): Figure {
showlegend: false, showlegend: false,
xaxis: { visible: false, range: [-1.25, 1.25], constrain: 'domain' }, xaxis: { visible: false, range: [-1.25, 1.25], constrain: 'domain' },
yaxis: { visible: false, range: [-1.13, 1.18], scaleanchor: 'x', scaleratio: 1 }, yaxis: { visible: false, range: [-1.13, 1.18], scaleanchor: 'x', scaleratio: 1 },
shapes: [ 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 },
},
],
}, },
}; };
} }
@@ -232,7 +250,13 @@ export function ageNorm(rows: Centile[], metric: Metric, age: number): Figure {
], ],
layout: { layout: {
xaxis: { title: { text: 'Edad (meses)' } }, 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: { 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 }, yaxis: { autorange: 'reversed', automargin: true },
shapes: [ shapes: [
{ {
@@ -366,7 +394,7 @@ export function probabilityCurve(
data, data,
layout: { layout: {
xaxis: { title: { text: 'Puntuación z' } }, xaxis: { title: { text: 'Puntuación z' } },
yaxis: { title: { text: 'Probabilidad (%)' }, range: [0, 100] }, yaxis: { title: { text: 'Probabilidad (%)' }, range: [0, 100], ...wholeNumberAxis([0, 100]) },
}, },
}; };
} }
+26 -2
View File
@@ -2,7 +2,15 @@ import type { Observation, Patient } from 'fhir/r4';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { EXT } from '../fhir'; import { EXT } from '../fhir';
import { identityRows, Metric, Pair, pairTitle, TeaStep, zoneLabel } from './tea-data'; 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 { import {
forestTitle, forestTitle,
probabilityTitle, probabilityTitle,
@@ -122,7 +130,21 @@ describe('Figuras del paciente TEA', () => {
mode: 'text+markers', mode: 'text+markers',
text: expect.arrayContaining(['O1', 'Cz']), 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', () => { 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 figure = timeline(steps)!;
const markers = figure.data.find((trace) => trace.type === 'scatter')!; const markers = figure.data.find((trace) => trace.type === 'scatter')!;
expect(markers).toMatchObject({ expect(markers).toMatchObject({
mode: 'lines+markers',
line: { dash: 'dot' },
marker: expect.objectContaining({ symbol: 'diamond' }), marker: expect.objectContaining({ symbol: 'diamond' }),
x: ['2025-11-01', '2025-11-22'], x: ['2025-11-01', '2025-11-22'],
y: ['M-CHAT', 'Psicología'], y: ['M-CHAT', 'Psicología'],