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
+42 -13
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(
panel: HistoryPanel,
series: { label: string; r: Reading | undefined }[],
@@ -417,9 +439,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'] ?? {})))];
@@ -430,24 +452,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',
@@ -457,14 +486,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]),
};
}
+1 -48
View File
@@ -161,22 +161,9 @@
<tr>
<td>{{ row.recordNumbers.join(', ') || '—' }}</td>
<td>
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id]">
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id, 'riesgo']">
{{ row.name || '—' }}
</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>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td>
<td>{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }}</td>
@@ -187,40 +174,6 @@
<td>{{ formatProbability(row.headline?.probability) }}</td>
<td>{{ formatProbability(row.headline?.reference) }}</td>
</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 {
<tr>
<td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
-7
View File
@@ -18,10 +18,3 @@
margin-bottom: 0;
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 size = signal(20);
protected readonly index = signal(0);
protected readonly expanded = signal<Record<string, boolean>>({});
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<void> {
this.exporting.set(true);
this.actionError.set('');
@@ -4,6 +4,7 @@ import { teaSteps } from '../paciente/tea-data';
import {
ageShare,
ageStack,
historyFigure,
nestedDonut,
sexCountBars,
shareDonut,
@@ -130,6 +131,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' }],
+90 -62
View File
@@ -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<string, [number, number]> = {
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<string, [number, number]> = {
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<string, [number, number]> = {
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<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 };
}
export function headMap(sites: Site[]): Figure {
const { electrodes, grid, inside, shapes } = headMapGeometry();
const zones: Record<string, [number, number]> = {
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}<extra></extra>',
});
@@ -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]) },
},
};
}
+26 -2
View File
@@ -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'],