Merge P5.3-tea-patient into P5-combined

This commit is contained in:
2026-11-30 14:20:07 -06:00
13 changed files with 1567 additions and 144 deletions
+4
View File
@@ -6,6 +6,10 @@ export const routes: Routes = [
path: 'indicadores/:domain', path: 'indicadores/:domain',
loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores), loadComponent: () => import('./indicadores/indicadores').then((m) => m.Indicadores),
}, },
{
path: 'indicadores/tea/pacientes/:id/riesgo',
loadComponent: () => import('./paciente/tea-patient').then((m) => m.TeaRisk),
},
{ {
path: 'indicadores/:domain/pacientes/:id', path: 'indicadores/:domain/pacientes/:id',
loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente), loadComponent: () => import('./paciente/paciente').then((m) => m.Paciente),
+1 -1
View File
@@ -9,7 +9,7 @@ interface Band {
high?: (number | null)[]; high?: (number | null)[];
} }
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] { export function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = []; const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) { if (b.low && b.high) {
lines.push({ lines.push({
+12 -4
View File
@@ -1,4 +1,7 @@
<section class="page"> @if (domain() === 'tea') {
<app-tea-record [id]="id()" />
} @else {
<section class="page">
<a mat-button [routerLink]="['/indicadores', domain()]" <a mat-button [routerLink]="['/indicadores', domain()]"
><mat-icon>arrow_back</mat-icon> Regresar</a ><mat-icon>arrow_back</mat-icon> Regresar</a
> >
@@ -24,7 +27,9 @@
<div> <div>
<dt>Sexo</dt> <dt>Sexo</dt>
<dd> <dd>
{{ p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato' }} {{
p.gender === 'female' ? 'Femenino' : p.gender === 'male' ? 'Masculino' : 'Sin dato'
}}
</dd> </dd>
</div> </div>
<div> <div>
@@ -129,7 +134,9 @@
<td>{{ p.p * 100 | number: '1.1-2' }} %</td> <td>{{ p.p * 100 | number: '1.1-2' }} %</td>
<td> <td>
@if (p.low !== undefined) { @if (p.low !== undefined) {
{{ p.low * 100 | number: '1.1-2' }}–{{ p.high! * 100 | number: '1.1-2' }} {{ p.low * 100 | number: '1.1-2' }}–{{
p.high! * 100 | number: '1.1-2'
}}
% %
} @else { } @else {
— —
@@ -150,4 +157,5 @@
} @else if (loading()) { } @else if (loading()) {
<p class="muted">Cargando…</p> <p class="muted">Cargando…</p>
} }
</section> </section>
}
+11 -2
View File
@@ -16,6 +16,7 @@ import { code, ext, Fhir, label, resources } from '../fhir';
import { CURP } from '../indicadores/follow-up'; import { CURP } from '../indicadores/follow-up';
import { name } from '../indicadores/measures'; import { name } from '../indicadores/measures';
import { Figure, PALETTE, Plot } from '../plot'; import { Figure, PALETTE, Plot } from '../plot';
import { TeaRecord } from './tea-patient';
/** An Observation's value as the screens say it, whatever its type. */ /** An Observation's value as the screens say it, whatever its type. */
function shown(o: Observation): string { function shown(o: Observation): string {
@@ -30,7 +31,15 @@ function shown(o: Observation): string {
* champion models' risks with their curves. Everything read from the FHIR API. */ * champion models' risks with their curves. Everything read from the FHIR API. */
@Component({ @Component({
selector: 'app-paciente', selector: 'app-paciente',
imports: [DecimalPipe, MatButtonModule, MatCardModule, MatIconModule, RouterLink, Plot], imports: [
DecimalPipe,
MatButtonModule,
MatCardModule,
MatIconModule,
RouterLink,
Plot,
TeaRecord,
],
templateUrl: './paciente.html', templateUrl: './paciente.html',
styleUrl: './paciente.scss', styleUrl: './paciente.scss',
}) })
@@ -40,7 +49,7 @@ export class Paciente {
readonly id = input.required<string>(); readonly id = input.required<string>();
private readonly data = resource({ private readonly data = resource({
params: () => ({ domain: this.domain(), id: this.id() }), params: () => (this.domain() === 'tea' ? undefined : { domain: this.domain(), id: this.id() }),
loader: async ({ params: { domain, id } }) => { loader: async ({ params: { domain, id } }) => {
const subject = { subject: `Patient/${id}`, _count: 200 }; const subject = { subject: `Patient/${id}`, _count: 200 };
const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([ const [patient, conditions, procedures, reports, observations, risks] = await Promise.all([
+323
View File
@@ -0,0 +1,323 @@
import type {
DiagnosticReport,
Observation,
ObservationComponent,
Patient,
RiskAssessment,
} from 'fhir/r4';
import { code, ext, Fhir, label, resources } from '../fhir';
const steps: Record<string, string> = {
mchat_only: 'Solo M-CHAT',
psychology: 'Psicología',
neurology: 'Neurología',
eeg: 'EEG',
};
const metrics: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior',
spindles_n2: 'Husos N2',
spindles_n3: 'Husos N3',
paroxysmal_spikes: 'Puntas paroxísticas',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
const regions: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
frontal_midline: 'Frontal medial',
central: 'Central',
parietal: 'Parietal',
temporal_left: 'Temporal izquierda',
temporal_right: 'Temporal derecha',
occipital: 'Occipital',
posterior: 'Posterior',
global: 'Global',
};
const biomarkers: Record<string, string> = {
spikes: 'paroxysmal_spikes',
spindles: 'spindles_n2',
posterior_rhythm: 'posterior_rhythm',
gradient: 'anteroposterior_gradient',
};
const repetitive = new Set([
'ados2.intonation',
'ados2.stereotyped_language',
'ados2.unusual_sensory_interest',
'ados2.hand_finger_mannerisms',
'ados2.repetitive_interests',
]);
const classifications: Record<string, string> = {
non_spectrum: 'Fuera del espectro',
autism_spectrum: 'Espectro autista',
autism: 'Autismo',
mild_to_moderate_concern: 'Preocupación leve a moderada',
severe_concern: 'Preocupación grave',
};
const quality: Record<string, string> = {
good: 'Buena',
bad: 'Mala',
not_analyzed: 'Sin analizar',
valid: 'Válido',
not_valid: 'No válido',
};
const number = new Intl.NumberFormat('es-MX', { maximumFractionDigits: 3 });
const percentage = new Intl.NumberFormat('es-MX', { style: 'percent', maximumFractionDigits: 1 });
export function shown(value: string | number | undefined): string {
return typeof value === 'number' ? number.format(value) : value || '—';
}
export function percent(value: number | undefined): string {
return value == null ? '—' : percentage.format(value);
}
function answer(value: boolean | undefined): string {
return value === undefined ? '—' : value ? 'Sí' : 'No';
}
function observationValue(o: Observation | ObservationComponent): string {
if (o.valueQuantity?.value != null) {
return [shown(o.valueQuantity.value), o.valueQuantity.unit].filter(Boolean).join(' ');
}
return shown(label(o.valueCodeableConcept) || o.valueString || o.valueInteger);
}
export function identity(patient: Patient): string[][] {
const group = ext(patient, 'tea-age-group')?.valueCode;
const step = ext(patient, 'tea-step')?.valueCode;
const sex = { female: 'Femenino', male: 'Masculino', other: 'Otro', unknown: '—' };
return [
['Nombre', shown(patient.name?.[0]?.text)],
...(patient.identifier ?? []).map((id) => [id.type?.text || 'Identificador', shown(id.value)]),
['Sexo', patient.gender ? sex[patient.gender] : '—'],
['Fecha de nacimiento', shown(patient.birthDate)],
['Grupo de edad', group && group !== 'no_data' ? `${group} meses` : '—'],
['Paso', shown(steps[step ?? ''] ?? step)],
];
}
export function adosItems(observation: Observation): string[][] {
return (observation.component ?? [])
.filter((item) => code(item.code) !== 'ados2.module')
.map((item) => [
shown(label(item.code)),
repetitive.has(code(item.code) ?? '') ? 'RRB' : 'SA',
observationValue(item),
]);
}
export function adosSummary(observation: Observation): string[][] {
const module = observation.component?.find((item) => code(item.code) === 'ados2.module');
return [
['Módulo', module ? observationValue(module) : '—'],
['CSS', shown(observation.valueInteger)],
[
'Clasificación',
shown(
classifications[code(observation.interpretation?.[0]) ?? ''] ??
label(observation.interpretation?.[0]),
),
],
];
}
function timeline(observations: Observation[], ados: Observation[], reports: DiagnosticReport[]) {
const events = [
...ados.map((o) => [o.effectiveDateTime ?? '', 'ADOS-2', adosSummary(o)[2][1]]),
...reports.map((r) => [
r.effectiveDateTime ?? '',
'EEG',
shown(quality[code(r.conclusionCode?.[0]) ?? '']),
]),
];
const notes = new Map<string, Observation[]>();
for (const o of observations) {
const field = code(o.code);
const date = o.effectiveDateTime ?? '';
if (field === 'mchat.score') {
events.push([date, 'M-CHAT', observationValue(o)]);
}
if (field === 'eeg.lab_record_id' && !reports.some((r) => r.effectiveDateTime === date)) {
events.push([date, 'EEG', observationValue(o)]);
}
if (field?.startsWith('clinical_note.') && o.encounter?.reference) {
const group = notes.get(o.encounter.reference) ?? [];
group.push(o);
notes.set(o.encounter.reference, group);
}
}
for (const group of notes.values()) {
const specialty = group.find((o) => code(o.code) === 'clinical_note.specialty');
if (code(specialty?.valueCodeableConcept) === 'pediatric_neurology') {
const detail = group
.filter((o) => o !== specialty)
.map(observationValue)
.join(' · ');
events.push([specialty?.effectiveDateTime ?? '', 'Nota de neurología', shown(detail)]);
}
}
return events
.sort((a, b) => b[0].localeCompare(a[0]))
.map(([date, kind, detail]) => [shown(date), kind, detail]);
}
function checkRow(o: Observation): string[] {
const range = o.referenceRange?.[0];
const abnormal = code(o.interpretation?.[0]);
return [
[label(o.code), label(o.component?.[0]?.code)].filter(Boolean).join(' · '),
observationValue(o),
range ? `${shown(range.low?.value)} a ${shown(range.high?.value)}` : '—',
answer(abnormal ? abnormal === 'A' : undefined),
answer(ext(o, 'eeg-check-decisive')?.valueBoolean),
];
}
export type Site = {
name: string;
kind: 'zone' | 'electrode';
z?: number;
outside?: number;
};
function metric(o: Observation) {
const key = code(o.code) ?? '';
return {
key,
title: metrics[key] ?? shown(label(o.code)),
value: o.valueQuantity?.value,
unit: o.valueQuantity?.unit,
z: ext(o, 'eeg-z')?.valueDecimal,
outside: ext(o, 'eeg-outside')?.valueInteger,
model: ext(o, 'eeg-model')?.valueString,
sites: (o.component ?? []).map((site): Site => ({
name: code(site.code) ?? '',
kind: site.code.coding?.[0]?.system?.endsWith('eeg-electrode-10-20') ? 'electrode' : 'zone',
z: ext(site, 'eeg-z')?.valueDecimal,
outside: ext(site, 'eeg-outside')?.valueInteger,
})),
};
}
export type Metric = ReturnType<typeof metric>;
function study(report: DiagnosticReport, observations: Map<string | undefined, Observation>) {
const results = (report.result ?? [])
.map((r) => observations.get(r.reference?.split('/').pop()))
.filter((o): o is Observation => !!o);
return {
id: report.id,
date: shown(report.effectiveDateTime),
age: ext(report, 'eeg-age-months')?.valueDecimal,
summary: [
['Calidad', shown(quality[code(report.conclusionCode?.[0]) ?? ''])],
['Validez', shown(quality[code(report.conclusionCode?.[1]) ?? ''])],
['Duración (min)', shown(ext(report, 'eeg-duration-min')?.valueDecimal)],
['Canales', shown(ext(report, 'eeg-channels')?.valueInteger)],
],
checks: results
.filter((o) => o.code.coding?.[0]?.system?.endsWith('tea-eeg-check'))
.map(checkRow),
metrics: results
.filter((o) => o.code.coding?.[0]?.system?.endsWith('tea-eeg-metric'))
.map(metric),
};
}
export type Pair = {
key: string;
title: string;
headline: boolean;
altered: boolean;
z?: number;
odds?: number;
low?: number;
high?: number;
probability?: number;
reference?: number;
};
export type Study = ReturnType<typeof study>;
export function zoneLabel(zone: string): string {
return regions[zone] ?? zone;
}
export function alteration(outside: number | undefined): string {
return outside == null ? '—' : outside < 0 ? 'Bajo' : outside > 0 ? 'Alto' : 'En rango';
}
function associations(
risk: RiskAssessment | undefined,
eeg: Study | undefined,
ados: Observation[],
) {
const items = ados[0] ? adosItems(ados[0]) : [];
return (risk?.prediction ?? [])
.map((p): Pair => {
const key = code(p.outcome) ?? '';
const [biomarker, zone = '', outcome = ''] = key.split('|');
const metric = eeg?.metrics.find((m) => m.key === biomarkers[biomarker]);
const site =
zone === 'global' || biomarker === 'posterior_rhythm'
? metric
: metric?.sites.find((s) => s.kind === 'zone' && s.name === zone);
const item = /^ados2_item_(\d+)$/.exec(outcome);
return {
key,
title: [
metric?.title ?? metrics[biomarkers[biomarker]] ?? biomarker,
zoneLabel(zone),
item ? (items[Number(item[1]) - 1]?.[0] ?? outcome) : outcome,
].join(' · '),
headline: ext(p, 'association-headline')?.valueBoolean === true,
altered: site?.outside != null && site.outside !== 0,
z: site?.z,
odds: ext(p, 'association-odds-ratio')?.valueDecimal,
low: ext(p, 'association-ci-low')?.valueDecimal,
high: ext(p, 'association-ci-high')?.valueDecimal,
probability: p.probabilityDecimal,
reference: ext(p, 'association-reference-probability')?.valueDecimal,
};
})
.sort((a, b) => Number(b.headline) - Number(a.headline));
}
export async function loadTeaPatient(fhir: Fhir, id: string) {
const bundle = await fhir.search('tea', 'Patient', {
_id: id,
_revinclude: ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject'],
});
const patient = resources<Patient>(bundle, 'Patient', 'match').find((p) => p.id === id);
if (!patient) throw new Error('No se encontró el paciente.');
const observations = resources<Observation>(bundle, 'Observation', 'include');
const ados = observations
.filter((o) => code(o.code) === 'ados2')
.sort((a, b) => (b.effectiveDateTime ?? '').localeCompare(a.effectiveDateTime ?? ''));
const reports = resources<DiagnosticReport>(bundle, 'DiagnosticReport', 'include')
.filter((r) => code(r.code) === 'eeg')
.reverse();
const byId = new Map(observations.map((o) => [o.id, o]));
const studies = reports.map((r) => study(r, byId));
const risk = resources<RiskAssessment>(bundle, 'RiskAssessment', 'include')[0];
const basis = risk?.basis?.find((r) => r.reference?.startsWith('DiagnosticReport/'));
const riskStudy = studies.find(
(eeg) => eeg.id && basis?.reference === `DiagnosticReport/${eeg.id}`,
);
return {
patient,
ados,
studies,
timeline: timeline(observations, ados, reports),
riskStudy,
pairs: associations(risk, riskStudy, ados),
};
}
export type TeaPatient = Awaited<ReturnType<typeof loadTeaPatient>>;
+280
View File
@@ -0,0 +1,280 @@
import { banded } from '../gobernanza/figures';
import { Figure, PALETTE } from '../plot';
import { Metric, Pair, Site, Study, zoneLabel } from './tea-data';
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 headMap(sites: Site[]): Figure {
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 limit = Math.max(2, ...samples.map((site) => Math.abs(site.z)));
data.push({
type: 'contour',
x: grid,
y: grid,
z: surface,
zmin: -limit,
zmax: limit,
colorscale: [
[0, '#4269c2'],
[0.5, '#f7f7f7'],
[1, '#c24269'],
],
contours: { coloring: 'heatmap', showlines: false },
hoverinfo: 'skip',
colorbar: { title: { text: 'z' } },
});
}
const markers = Object.entries(electrodes);
data.push({
type: 'scatter',
mode: 'text+markers',
name: 'Electrodos',
x: markers.map(([, point]) => point[0]),
y: markers.map(([, point]) => point[1]),
text: markers.map(([name]) => name),
textposition: 'top center',
marker: { color: '#17324d', size: 5 },
hovertemplate: '%{text}<extra></extra>',
});
return {
data,
layout: {
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 },
},
],
},
};
}
export type Centile = {
age_months: number;
p5: number | null;
median: number | null;
p95: number | null;
};
export function ageNorm(rows: Centile[], metric: Metric, age: number): Figure {
return {
data: [
...banded(
'Mediana',
{
x: rows.map((row) => row.age_months),
y: rows.map((row) => row.median) as number[],
low: rows.map((row) => row.p5),
high: rows.map((row) => row.p95),
},
PALETTE[4],
),
{
type: 'scatter',
mode: 'markers',
name: 'Paciente',
x: [age],
y: [metric.value ?? null],
marker: { size: 10, color: PALETTE[2] },
},
],
layout: {
xaxis: { title: { text: 'Edad (meses)' } },
yaxis: { title: { text: metric.unit ?? 'Valor' } },
},
};
}
type SingleTrace = Figure & { data: [Partial<Plotly.Data> & { x: number[] }] };
export function forest(pairs: Pair[], alteredOnly: boolean): SingleTrace {
const visible = pairs.filter(
(p): p is Pair & { odds: number } =>
(!alteredOnly || p.altered) && p.odds != null && p.odds > 0,
);
const intervals = (bound: 'low' | 'high') =>
visible.map((p) => {
const value = p[bound];
return value != null && value > 0 ? Math.abs(value - p.odds) : 0;
});
return {
data: [
{
type: 'scatter',
mode: 'markers',
x: visible.map((p) => p.odds),
y: visible.map((p) => p.title),
error_x: {
type: 'data',
symmetric: false,
array: intervals('high'),
arrayminus: intervals('low'),
},
marker: { color: PALETTE[4], size: 8 },
},
],
layout: {
xaxis: { type: 'log', title: { text: 'Razón de momios (OR) · IC 95 %' } },
yaxis: { autorange: 'reversed', automargin: true },
shapes: [
{
type: 'line',
x0: 1,
x1: 1,
y0: 0,
y1: 1,
yref: 'paper',
line: { dash: 'dot', color: PALETTE[6] },
},
],
},
};
}
export function zBars(eeg: Study): SingleTrace {
const rows = eeg.metrics
.flatMap((metric) => [
{ title: `${metric.title} · Global`, z: metric.z },
...metric.sites
.filter((s) => s.kind === 'zone')
.map((s) => ({
title: `${metric.title} · ${zoneLabel(s.name)}`,
z: s.z,
})),
])
.filter((s): s is { title: string; z: number } => s.z != null);
const limit = Math.max(2.2, ...rows.map((s) => Math.abs(s.z) * 1.1));
return {
data: [
{
type: 'bar',
orientation: 'h',
x: rows.map((s) => s.z),
y: rows.map((s) => s.title),
marker: { color: rows.map((s) => (Math.abs(s.z) < 2 ? PALETTE[4] : PALETTE[2])) },
},
],
layout: {
xaxis: { title: { text: 'Puntuación z' }, range: [-limit, limit] },
yaxis: { autorange: 'reversed', automargin: true },
shapes: [
{
type: 'rect',
x0: -2,
x1: 2,
y0: 0,
y1: 1,
yref: 'paper',
layer: 'below',
line: { width: 0 },
fillcolor: '#42c29c33',
},
],
},
};
}
export function probabilityCurve(
pair: Pair,
logistic?: { intercept: number; slope: number },
): Figure {
const data: Figure['data'] = [];
if (logistic) {
const extent = Math.max(4, Math.abs(pair.z ?? 0));
const x = Array.from({ length: 81 }, (_, i) => (extent * (i - 40)) / 40);
data.push({
type: 'scatter',
mode: 'lines',
name: 'Modelo',
x,
y: x.map((z) => 100 / (1 + Math.exp(-(logistic.intercept + logistic.slope * z)))),
});
}
if (pair.z != null && pair.probability != null) {
data.push({
type: 'scatter',
mode: 'markers',
name: 'Paciente',
x: [pair.z],
y: [100 * pair.probability],
marker: { size: 10, color: PALETTE[2] },
});
}
if (pair.reference != null) {
data.push({
type: 'scatter',
mode: 'markers',
name: 'Referencia',
x: [0],
y: [100 * pair.reference],
marker: { size: 10, color: PALETTE[4], symbol: 'diamond-open' },
});
}
return {
data,
layout: {
xaxis: { title: { text: 'Puntuación z' } },
yaxis: { title: { text: 'Probabilidad (%)' }, range: [0, 100] },
},
};
}
+247
View File
@@ -0,0 +1,247 @@
import { Component, input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import type { Observation } from 'fhir/r4';
import { describe, expect, it, vi } from 'vitest';
import { EXT, Fhir } from '../fhir';
import { Paciente } from './paciente';
import { loadTeaPatient, Metric, Pair } from './tea-data';
import { ageNorm, forest, headMap, probabilityCurve, zBars } from './tea-figures';
import { TeaRecord, TeaSection } from './tea-patient';
import { recordSections, teaPdfContent, teaPdfName } from './tea-sections';
const metric: Metric = {
key: 'spindles_n2',
title: 'Husos N2',
value: 1.7,
unit: undefined,
model: 'tea.eeg-spindles-n2/1',
z: 0.3,
outside: 0,
sites: [
{ kind: 'zone', name: 'central', z: 2.4, outside: 1 },
{ kind: 'electrode', name: 'O1', z: -1.2, outside: 0 },
],
};
const pair: Pair = {
key: 'spindles|central|CSS',
title: 'Husos N2 · Central · CSS',
headline: true,
altered: true,
z: 2.4,
odds: 3,
low: 1.2,
high: 4.5,
probability: 0.7,
reference: 0.2,
};
const ados: Observation = {
resourceType: 'Observation',
id: 'ados2-child-2025-11-22',
status: 'final',
code: { coding: [{ code: 'ados2' }] },
effectiveDateTime: '2025-11-22',
valueInteger: 0,
component: [
{ code: { coding: [{ code: 'ados2.module' }] }, valueCodeableConcept: { text: 'Módulo 1' } },
...Array.from({ length: 21 }, (_, i) => ({
code: { coding: [{ code: `ados2.item${i}` }], text: `Ítem ${i + 1}` },
valueQuantity: i === 0 ? { value: 0 } : undefined,
})),
{
code: { coding: [{ code: 'ados2.intonation' }], text: 'Entonación' },
valueQuantity: { value: 2 },
},
],
};
const record = {
patient: {
resourceType: 'Patient' as const,
id: 'child',
name: [{ text: 'Paciente de prueba' }],
},
timeline: [['2025-11-22', 'ADOS-2', '—']],
ados: [ados],
studies: [],
riskStudy: undefined,
pairs: [pair],
};
describe('Figuras del paciente TEA', () => {
it('interpola los sitios puntuados y dibuja los electrodos y el contorno', () => {
const figure = headMap(metric.sites);
expect(figure.data[0]).toMatchObject({ type: 'contour' });
const grid = (figure.data[0] as { z?: unknown }).z as (number | null)[][];
expect(grid[20][20]).toBeCloseTo(2.4);
expect(grid[0][0]).toBeNull();
expect(figure.data[1]).toMatchObject({
mode: 'text+markers',
text: expect.arrayContaining(['O1', 'Cz']),
});
expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'circle' });
});
it('dibuja los centiles del campeón y el valor observado a la edad del paciente', () => {
const figure = ageNorm(
[
{ age_months: 20, p5: 0, median: 1, p95: 2 },
{ age_months: 21, p5: 0.2, median: 1.2, p95: 2.2 },
],
metric,
20.5,
);
expect(figure.data[0]).toMatchObject({ fill: 'toself', y: [2, 2.2, 0.2, 0] });
expect(figure.data[2]).toMatchObject({ mode: 'markers', x: [20.5], y: [1.7] });
});
it('usa escala logarítmica y conserva solo zonas alteradas al activar el filtro', () => {
const pairs = [pair, { ...pair, title: 'Zona normal', altered: false, odds: 2 }];
expect(forest(pairs, false).data[0].x).toEqual([3, 2]);
const filtered = forest(pairs, true);
expect(filtered.layout?.xaxis?.type).toBe('log');
expect(filtered.data[0]).toMatchObject({
x: [3],
error_x: { array: [1.5], arrayminus: [1.8] },
});
});
it('marca la banda de z entre −2 y 2', () => {
const figure = zBars({
id: 'eeg-1',
date: '2025-11-22',
age: 20.5,
checks: [],
summary: [],
metrics: [metric],
});
expect(figure.data[0]).toMatchObject({
x: [0.3, 2.4],
y: ['Husos N2 · Global', 'Husos N2 · Central'],
});
expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'rect', x0: -2, x1: 2 });
});
it('dibuja solo los puntos de paciente y referencia cuando faltan parámetros', () => {
expect(probabilityCurve(pair).data).toMatchObject([
{ mode: 'markers', x: [2.4], y: [70] },
{ mode: 'markers', x: [0], y: [20] },
]);
});
});
describe('Expediente TEA', () => {
it('muestra los 22 ítems del ADOS-2 y sus dominios sin incluir el módulo', async () => {
const fixture = TestBed.createComponent(TeaSection);
fixture.componentRef.setInput(
'section',
recordSections(record, new Map()).find((section) => section.title === 'ADOS-2'),
);
await fixture.whenStable();
const rows = fixture.nativeElement.querySelectorAll('tbody tr');
expect(rows).toHaveLength(22);
expect(rows[0].textContent).toContain('SA');
expect(rows[0].cells[2].textContent.trim()).toBe('0');
expect(rows[21].textContent).toContain('RRB');
});
it('exporta las secciones, tablas y figuras con un nombre sin identificador', async () => {
const table = recordSections(record, new Map());
const sections = [
...table,
{
title: 'Normas',
blocks: [{ chart: { title: 'Mapa', figure: headMap(metric.sites) } }],
},
];
const filename = teaPdfName('seguimiento');
const content = teaPdfContent('Expediente TEA', sections, ['data:image/png;base64,YQ==']);
expect(filename).toMatch(/^tea-seguimiento-\d{4}-\d{2}-\d{2}$/);
expect(content).toEqual(
expect.arrayContaining([
expect.objectContaining({ text: 'Datos' }),
expect.objectContaining({ text: 'Relación con el ADOS-2' }),
expect.objectContaining({
table: expect.objectContaining({
body: expect.arrayContaining([['Entonación', 'RRB', '2']]),
}),
}),
expect.objectContaining({ image: 'data:image/png;base64,YQ==' }),
]),
);
});
it('usa los eventos visibles de la búsqueda y ordena primero el par principal', async () => {
const entry = [
{ resource: record.patient, search: { mode: 'match' } },
{ resource: ados, search: { mode: 'include' } },
{
resource: {
resourceType: 'Observation',
code: { coding: [{ code: 'eeg.lab_record_id' }] },
effectiveDateTime: '2025-11-30',
valueString: 'LAB-01',
},
search: { mode: 'include' },
},
{
resource: {
resourceType: 'RiskAssessment',
prediction: [
{ outcome: { coding: [{ code: 'spikes|occipital|CSS' }] } },
{
outcome: { coding: [{ code: pair.key }] },
extension: [{ url: EXT + 'association-headline', valueBoolean: true }],
},
],
},
search: { mode: 'include' },
},
];
const search = vi.fn(async () => ({ entry }));
const data = await loadTeaPatient({ search } as unknown as Fhir, 'child');
expect(search).toHaveBeenCalledWith('tea', 'Patient', {
_id: 'child',
_revinclude: ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject'],
});
expect(data.timeline[0]).toEqual(['2025-11-30', 'EEG', 'LAB-01']);
expect(data.studies).toHaveLength(0);
expect(data.pairs[0].key).toBe(pair.key);
});
});
@Component({ selector: 'app-tea-record', template: '<h2>Datos</h2><h2>Línea del tiempo</h2>' })
class RecordStub {
readonly id = input.required<string>();
}
describe('Secciones por dominio', () => {
it('elige las secciones TEA y sigue mostrando las secciones de CaCu y CaMa', async () => {
const read = vi.fn(async () => record.patient);
TestBed.configureTestingModule({
providers: [provideRouter([]), { provide: Fhir, useValue: { read, all: async () => [] } }],
}).overrideComponent(Paciente, {
remove: { imports: [TeaRecord] },
add: { imports: [RecordStub] },
});
const fixture = TestBed.createComponent(Paciente);
fixture.componentRef.setInput('id', 'child');
fixture.componentRef.setInput('domain', 'tea');
await fixture.whenStable();
expect(fixture.nativeElement.querySelector('app-tea-record')?.textContent).toContain(
'Línea del tiempo',
);
expect(read).not.toHaveBeenCalled();
for (const domain of ['cacu', 'cama']) {
fixture.componentRef.setInput('domain', domain);
await fixture.whenStable();
expect(fixture.nativeElement.querySelector('app-tea-record')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Historial médico');
expect(read).toHaveBeenCalledWith(domain, 'Patient', 'child');
}
});
});
+207
View File
@@ -0,0 +1,207 @@
import { Component, computed, ElementRef, inject, input, resource, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api';
import { curve } from '../api/fn/models/curve';
import { Fhir } from '../fhir';
import { Plot } from '../plot';
import { loadTeaPatient, Study } from './tea-data';
import { ageNorm, Centile, forest, probabilityCurve, zBars } from './tea-figures';
import {
calculation,
exportTeaPdf,
forestTitle,
limitations,
probabilityRows,
probabilityTitle,
recordSections,
Section,
} from './tea-sections';
@Component({
selector: 'app-tea-section',
imports: [MatCardModule, Plot],
templateUrl: './tea-section.html',
styleUrl: './tea-section.scss',
})
export class TeaSection {
readonly section = input.required<Section>();
}
@Component({
selector: 'app-tea-record',
imports: [TeaSection, RouterLink, MatButtonModule],
templateUrl: './tea-record.html',
})
export class TeaRecord {
private readonly fhir = inject(Fhir);
private readonly api = inject(Api);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
readonly id = input.required<string>();
protected readonly patient = resource({
params: () => this.id(),
loader: ({ params }) => loadTeaPatient(this.fhir, params),
});
protected readonly norms = resource({
params: () => (this.patient.hasValue() ? this.patient.value().studies : undefined),
loader: ({ params }) => this.loadNorms(params),
});
protected readonly sections = computed(() => {
const patient = this.patient.hasValue() ? this.patient.value() : undefined;
return patient
? recordSections(patient, this.norms.hasValue() ? this.norms.value() : new Map())
: [];
});
protected readonly exporting = signal(false);
protected readonly exportError = signal(false);
private async loadNorms(studies: Study[]) {
const curves = new Map<string, Promise<Centile[]>>();
const charts = await Promise.all(
studies.flatMap((eeg) =>
eeg.metrics.map(async (metric) => {
const model = /^tea\.([^/]+)\/([1-9]\d*)$/.exec(metric.model ?? '');
if (
!model ||
metric.key === 'paroxysmal_spikes' ||
metric.value == null ||
eeg.age == null
) {
return undefined;
}
const [, name, version] = model;
const key = model[0];
if (!curves.has(key)) {
curves.set(
key,
this.api
.invoke(curve, { domain: 'tea', name, version: Number(version) })
.then((rows) => rows as Centile[])
.catch(() => []),
);
}
const rows = await curves.get(key)!;
if (!rows.some((row) => row.median != null)) return undefined;
return [
`${eeg.id}|${metric.key}`,
{
title: 'Norma por edad · p5–p95',
figure: ageNorm(rows, metric, eeg.age),
},
] as const;
}),
),
);
return new Map(charts.filter((chart) => chart !== undefined));
}
protected async download(): Promise<void> {
this.exportError.set(false);
this.exporting.set(true);
try {
await exportTeaPdf(
'seguimiento',
'Expediente TEA',
this.sections(),
this.host.nativeElement.querySelectorAll<HTMLDivElement>('app-plot .plot'),
);
} catch {
this.exportError.set(true);
} finally {
this.exporting.set(false);
}
}
}
@Component({
selector: 'app-tea-risk',
imports: [TeaSection, RouterLink, MatButtonModule],
templateUrl: './tea-risk.html',
})
export class TeaRisk {
private readonly fhir = inject(Fhir);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
readonly id = input.required<string>();
protected readonly patient = resource({
params: () => this.id(),
loader: ({ params }) => loadTeaPatient(this.fhir, params),
});
protected readonly onlyAltered = signal(false);
protected readonly selectedKey = signal('');
protected readonly selectedPair = computed(() => {
const pairs = this.patient.hasValue() ? this.patient.value().pairs : [];
return pairs.find((pair) => pair.key === this.selectedKey()) ?? pairs[0];
});
protected readonly forestTitle = forestTitle;
protected readonly probabilityTitle = probabilityTitle;
protected readonly sections = computed<Section[]>(() => {
if (!this.patient.hasValue()) return [];
const patient = this.patient.value();
const studies = patient.riskStudy ? [patient.riskStudy] : patient.studies;
const scores = studies
.map((eeg) => ({ date: eeg.date, figure: zBars(eeg) }))
.find(({ figure }) => figure.data[0].x?.length);
const effects = forest(patient.pairs, this.onlyAltered());
const pair = this.selectedPair();
return [
{ title: 'Qué calcula', blocks: [{ text: calculation }] },
{
title: 'Puntuaciones z por métrica y zona',
blocks: scores
? [
{
chart: {
title: scores.date,
figure: scores.figure,
height: Math.max(340, 24 * (scores.figure.data[0].x?.length ?? 0) + 80),
},
},
]
: [],
},
{
title: forestTitle,
blocks: [
effects.data[0].x?.length
? {
chart: {
title: 'OR e IC 95 %',
figure: effects,
height: Math.max(340, 26 * effects.data[0].x.length + 80),
},
}
: { text: '—' },
],
},
{
title: 'Probabilidad frente a la referencia',
blocks: [{ table: probabilityRows(patient.pairs) }],
},
{
title: probabilityTitle,
blocks: pair ? [{ chart: { title: pair.title, figure: probabilityCurve(pair) } }] : [],
},
{ title: 'Limitaciones', blocks: [{ text: limitations }] },
];
});
protected readonly exporting = signal(false);
protected readonly exportError = signal(false);
protected async download(): Promise<void> {
this.exportError.set(false);
this.exporting.set(true);
try {
await exportTeaPdf(
'riesgos',
'Análisis de riesgo TEA',
this.sections(),
this.host.nativeElement.querySelectorAll<HTMLDivElement>('app-plot .plot'),
);
} catch {
this.exportError.set(true);
} finally {
this.exporting.set(false);
}
}
}
+31
View File
@@ -0,0 +1,31 @@
<section class="page">
<nav aria-label="Paciente">
<a mat-button [routerLink]="['/indicadores', 'tea']" [queryParams]="{ seguimiento: id() }"
>Regresar a Seguimiento</a
>
<a mat-button [routerLink]="['/indicadores', 'tea', 'pacientes', id(), 'riesgo']"
>Análisis de riesgo</a
>
</nav>
@if (patient.error()) {
<p role="alert">No se encontró el paciente.</p>
} @else if (patient.value(); as data) {
<h1>{{ data.patient.name?.[0]?.text ?? 'Expediente TEA' }}</h1>
<button
mat-stroked-button
type="button"
[disabled]="exporting() || norms.isLoading()"
(click)="download()"
>
Exportar PDF
</button>
@if (exportError()) {
<p role="alert">No se pudo exportar el PDF.</p>
}
@for (section of sections(); track section.title) {
<app-tea-section [section]="section" />
}
} @else if (patient.isLoading()) {
<p class="muted">Cargando…</p>
}
</section>
+51
View File
@@ -0,0 +1,51 @@
<section class="page">
<nav aria-label="Paciente">
<a mat-button [routerLink]="['/indicadores', 'tea']" [queryParams]="{ seguimiento: id() }"
>Regresar a Seguimiento</a
>
<a mat-button [routerLink]="['/indicadores', 'tea', 'pacientes', id()]">Expediente</a>
</nav>
<h1>Análisis de riesgo TEA</h1>
@if (patient.error()) {
<p role="alert">No se encontró el paciente.</p>
} @else if (patient.value(); as data) {
@if (data.patient.name?.[0]?.text; as name) {
<p class="subtitle">{{ name }}</p>
}
<button mat-stroked-button type="button" [disabled]="exporting()" (click)="download()">
Exportar PDF
</button>
@if (exportError()) {
<p role="alert">No se pudo exportar el PDF.</p>
}
@for (section of sections(); track section.title) {
<app-tea-section [section]="section">
@if (section.title === forestTitle) {
<label>
<input
type="checkbox"
#altered
[checked]="onlyAltered()"
(change)="onlyAltered.set(altered.checked)"
/>
Solo zonas alteradas
</label>
}
@if (section.title === probabilityTitle && data.pairs.length) {
<label>
Par
<select #pairs (change)="selectedKey.set(pairs.value)">
@for (pair of data.pairs; track pair.key) {
<option [value]="pair.key" [selected]="pair.key === selectedPair()?.key">
{{ pair.title }}
</option>
}
</select>
</label>
}
</app-tea-section>
}
} @else if (patient.isLoading()) {
<p class="muted">Cargando…</p>
}
</section>
+56
View File
@@ -0,0 +1,56 @@
<mat-card appearance="outlined">
<mat-card-header
><h2>{{ section().title }}</h2></mat-card-header
>
<mat-card-content>
<ng-content />
@for (block of section().blocks; track $index) {
@if (block.title) {
<h3>{{ block.title }}</h3>
}
@if (block.text) {
<p>{{ block.text }}</p>
}
@if (block.fields; as fields) {
<dl>
@for (field of fields; track $index) {
<div>
<dt>{{ field[0] }}</dt>
<dd>{{ field[1] }}</dd>
</div>
}
</dl>
}
@if (block.table; as table) {
@if (table.rows.length) {
<table class="plain">
<thead>
<tr>
@for (header of table.headers; track $index) {
<th scope="col">{{ header }}</th>
}
</tr>
</thead>
<tbody>
@for (row of table.rows; track $index) {
<tr>
@for (cell of row; track $index) {
<td>{{ cell }}</td>
}
</tr>
}
</tbody>
</table>
} @else {
<p class="muted">—</p>
}
}
@if (block.chart; as chart) {
<h3>{{ chart.title }}</h3>
<app-plot [figure]="chart.figure" [height]="chart.height ?? 340" />
}
} @empty {
<p class="muted">—</p>
}
</mat-card-content>
</mat-card>
+28
View File
@@ -0,0 +1,28 @@
:host {
display: block;
margin-block: var(--space-4);
}
mat-card-content {
overflow-x: auto;
}
h2 {
margin: 0 0 var(--space-3);
}
dl {
display: flex;
flex-wrap: wrap;
gap: var(--space-4);
margin-block: var(--space-3);
}
dt {
color: var(--color-text-secondary);
}
dd {
margin: 0;
font-weight: 500;
}
+179
View File
@@ -0,0 +1,179 @@
import type { PdfContent } from '../export/pdf';
import { downloadPdf } from '../export/pdf';
import { safeName } from '../export/safe-name';
import type { Figure } from '../plot';
import plotly from '../plotly-bundle';
import {
adosItems,
adosSummary,
alteration,
identity,
Pair,
percent,
shown,
TeaPatient,
} from './tea-data';
import { headMap } from './tea-figures';
type Table = { headers: string[]; rows: string[][] };
type Chart = { title: string; figure: Figure; height?: number };
export type Block = {
title?: string;
fields?: string[][];
table?: Table;
chart?: Chart;
text?: string;
};
export type Section = { title: string; blocks: Block[] };
export const forestTitle = 'Razones de momios por par';
export const probabilityTitle = 'Probabilidad según z';
export const calculation =
'El modelo estima, para cada par de métrica o zona del EEG y resultado del ADOS-2, la probabilidad de un puntaje elevado de severidad calibrada (CSS) o de un ítem alterado. La razón de momios corresponde al cambio asociado con una unidad de z. La probabilidad de referencia corresponde a z = 0, la edad media y el módulo más frecuente de la cohorte.';
export const limitations =
'Las estimaciones dependen de la cohorte de referencia, de la calidad del EEG y de la disponibilidad de mediciones y pares. Las asociaciones no establecen causalidad. Las probabilidades no sustituyen la evaluación clínica ni establecen un diagnóstico.';
function associationRows(pairs: Pair[]): string[][] {
return pairs.map((p) => [
p.headline ? `${p.title} (principal)` : p.title,
shown(p.odds),
p.low == null && p.high == null ? '—' : `${shown(p.low)} a ${shown(p.high)}`,
percent(p.probability),
percent(p.reference),
]);
}
export function recordSections(patient: TeaPatient, norms: ReadonlyMap<string, Chart>): Section[] {
return [
{ title: 'Datos', blocks: [{ fields: identity(patient.patient) }] },
{
title: 'Línea del tiempo',
blocks: [
{
table: {
headers: ['Fecha', 'Evento', 'Detalle'],
rows: patient.timeline,
},
},
],
},
{
title: 'ADOS-2',
blocks: patient.ados.map((o) => ({
title: shown(o.effectiveDateTime),
fields: adosSummary(o),
table: { headers: ['Ítem', 'Dominio', 'Puntaje'], rows: adosItems(o) },
})),
},
{
title: 'Calidad del EEG',
blocks: patient.studies.map((eeg) => ({
title: eeg.date,
fields: eeg.summary,
table: { headers: ['Control', 'Valor', 'Rango', 'Anormal', 'Decisivo'], rows: eeg.checks },
})),
},
{
title: 'Alteraciones',
blocks: patient.studies.flatMap((eeg) =>
eeg.metrics.flatMap((m) => {
const norm = norms.get(`${eeg.id}|${m.key}`);
return [
{
title: `${eeg.date} · ${m.title}`,
fields: [
['z', shown(m.z)],
['Resultado', alteration(m.outside)],
],
chart: m.sites.length
? { title: 'Mapa de la cabeza', figure: headMap(m.sites) }
: undefined,
},
...(norm ? [{ chart: norm }] : []),
];
}),
),
},
{
title: 'Relación con el ADOS-2',
blocks: [
{
table: {
headers: ['Par', 'OR', 'IC 95 %', 'Probabilidad', 'Referencia'],
rows: associationRows(patient.pairs),
},
},
],
},
];
}
export function probabilityRows(pairs: Pair[]): Table {
return {
headers: ['Par', 'Probabilidad', 'Referencia'],
rows: pairs.map((p) => [
p.headline ? `${p.title} (principal)` : p.title,
percent(p.probability),
percent(p.reference),
]),
};
}
export function teaPdfName(page: 'seguimiento' | 'riesgos', day = new Date()): string {
return safeName(['tea', page, day.toISOString().slice(0, 10)]);
}
export function teaPdfContent(title: string, sections: Section[], images: (string | undefined)[]): PdfContent[] {
const charts = images[Symbol.iterator]();
const content: PdfContent[] = [{ text: title, fontSize: 18, bold: true }];
for (const section of sections) {
content.push({ text: section.title, bold: true, fontSize: 14, margin: [0, 12, 0, 5] });
if (!section.blocks.length) content.push('—');
for (const block of section.blocks) {
if (block.title) content.push({ text: block.title, bold: true, margin: [0, 8, 0, 3] });
if (block.text) content.push(block.text);
if (block.fields) content.push(...block.fields.map(([key, value]) => `${key} · ${value}`));
if (block.table) {
const { headers, rows } = block.table;
content.push(
rows.length
? {
layout: 'lightHorizontalLines',
table: {
headerRows: 1,
widths: ['*', ...headers.slice(1).map(() => 'auto' as const)],
body: [headers, ...rows],
},
}
: '—',
);
}
if (block.chart) {
const image = charts.next().value;
content.push({ text: block.chart.title, bold: true });
if (image) content.push({ image, fit: [510, 620] });
}
}
}
return content;
}
export async function exportTeaPdf(
page: 'seguimiento' | 'riesgos',
title: string,
sections: Section[],
plots: Iterable<HTMLDivElement>,
): Promise<void> {
const images: string[] = [];
for (const plot of plots) {
images.push(
await plotly.toImage(plot, {
format: 'png',
width: Math.max(780, plot.clientWidth),
height: plot.clientHeight,
}),
);
}
await downloadPdf(teaPdfName(page), teaPdfContent(title, sections, images));
}