feat(tea): read the age-norm curve, the age at the EEG and the ADOS-2 relation from the WebApi's FHIR answer

This commit is contained in:
2026-11-21 11:17:59 -06:00
parent 68e2930e65
commit 4e9b25bd8f
5 changed files with 144 additions and 13 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
export interface Quantity { value?: number; unit?: string }
export interface Extension {
url: string;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
extension?: Extension[];
}
@@ -2,12 +2,14 @@
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
// the shapes the page reads and passed through the same checks.
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database; `conModelo`
// below adds to its patient summary the age at the EEG, a metric's age-norm curve and the ADOS-2 association model,
// in the shape `webapi/fhir/tea.py` emits them.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import { Bundle, Resource, resources } from './fhir';
import {
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
periodosDesde, Report,
@@ -20,6 +22,49 @@ import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-f
import { IndicadorDatos } from './indicadores.models';
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
const CS = 'https://isssteleon.org/fhir/CodeSystem';
const CURVA = `${SD}/curva-referencia`;
const curva = {
url: CURVA, extension: [
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
],
};
const prediccion = (zona: string, z: number | null) => ({
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
probabilityDecimal: 0.41,
extension: [
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
],
});
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
function conModelo(): Bundle {
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
for (const r of resources(bundle)) {
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
r.extension = [...(r.extension ?? []), curva];
}
const riesgo: Resource = {
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
meta: { tag: resources(bundle)[0].meta?.tag },
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
};
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
return bundle;
}
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
describe('Indicadores sobre FHIR', () => {
@@ -210,6 +255,49 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
});
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect(detalle.eeg!.edad_meses).toBe(23.6);
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
});
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const relacion = (await answer).relacion_ados2!;
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
expect(relacion.filas).toEqual([{
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
});
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
// the chart and the panel. Fails if the adapter fills them with defaults.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
expect('edad_meses' in detalle.eeg!).toBe(false);
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
expect('relacion_ados2' in detalle).toBe(false);
});
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
@@ -98,7 +98,7 @@
}
@if (vista === 'norma' && normaActual(e); as m) {
<h3>Norma por edad</h3>
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}</p>
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
@if (figuraNorma) {
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
@@ -144,7 +144,7 @@
<tbody>
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
<tr [class.alterada]="zonaAlterada(f)">
<td><strong>{{ biomarcador[f.biomarcador] ?? f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
<td>
@@ -7,9 +7,6 @@ import {
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
} from './tea-seguimiento.service';
const BIOMARCADOR: Record<string, string> = {
picos: 'Picos paroxísticos', husos: 'Husos de sueño', ritmo_posterior: 'Ritmo posterior', gradiente: 'Gradiente anteroposterior',
};
// A zone counts as altered from |z| ≥ 2, as the alteration cards do.
const Z_ALTERADO = 2;
@@ -162,7 +159,6 @@ export class TeaPacienteResumen implements OnInit {
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
readonly biomarcador = BIOMARCADOR;
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
direccion(f: TeaRelacionAdos2) {
@@ -1,14 +1,14 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
import { Bundle, code, codeIn, Concept, display, extension, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
import { estratoValor } from './indicadores-fhir';
import { SeguimientoQuery } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
import {
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg,
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse,
TeaSeguimientoService,
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad,
TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2,
TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
} from './tea-seguimiento.service';
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
@@ -26,6 +26,7 @@ interface Report extends Resource {
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
}
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
interface Prediction { outcome?: Concept; probabilityDecimal?: number; extension?: Resource['extension'] }
const MAX_COUNT = 200;
const METRICAS = 'tea-eeg-metrica';
@@ -111,6 +112,18 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
};
}
// The age norm a metric observation carries: one sub-extension per point, read back in order, because a FHIR
// extension holds scalars, not arrays.
function curvaDe(o: Observation): TeaCurvaReferencia | null {
const curva = extension(o, 'curva-referencia');
if (!curva) return null;
const serie = (nombre: string) => extensions(curva, nombre).map(e => e.valueDecimal).filter((v): v is number => typeof v === 'number');
return {
fuente: extension(curva, 'fuente')?.valueString ?? '', estado: extension(curva, 'estado')?.valueString ?? '',
edad_meses: serie('edad-meses'), p5: serie('p5'), p25: serie('p25'), mediana: serie('mediana'), p75: serie('p75'), p95: serie('p95'),
};
}
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
// cover the child's age (or none is in production yet).
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
@@ -123,6 +136,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
const referencia = typeof low === 'number' && typeof high === 'number'
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
const curva = evaluable ? curvaDe(o) : null;
return {
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
@@ -130,6 +144,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
...(curva ? { curva_referencia: curva } : {}),
};
}
@@ -152,6 +167,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
const listed = observations.filter(o => ids.has(o.id));
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
const duracion = extension(report, 'duracion-min')?.valueDecimal;
const edad = extension(report, 'edad-meses')?.valueDecimal;
// The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards.
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas));
// A metric's electrode values are `electrodos-<the metric observation's id>`.
@@ -166,6 +182,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
fecha: report.effectiveDateTime.slice(0, 10),
duracion_min: duracion === undefined ? null : Math.round(duracion),
canales: extension(report, 'canales')?.valueInteger ?? null,
...(typeof edad === 'number' ? { edad_meses: edad } : {}),
calidad: calidad(report.conclusionCode?.[0]),
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
alteraciones, mapas,
@@ -173,6 +190,34 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
};
}
// The ADOS-2 association model: one `RiskAssessment`, a prediction per association row with the patient's z and
// probabilities. A row missing a number the panel needs is left out; without rows there is no panel.
export function relacionDeRiesgo(riesgo: Resource | undefined): TeaRelacionModelo | null {
if (!riesgo) return null;
const nivel = extension(riesgo, 'modelo-nivel')?.valueString;
const filas = ((riesgo['prediction'] ?? []) as Prediction[]).map((p): TeaRelacionAdos2 | null => {
const numero = (nombre: string) => extension(p, nombre)?.valueDecimal;
const biomarcador = extension(p, 'biomarcador')?.valueCoding, zona = extension(p, 'zona')?.valueCoding;
const tipo = extension(p, 'tipo')?.valueString, evento = extension(p, 'evento')?.valueString;
const valores = [numero('valor-z'), numero('odds-ratio'), numero('ic-inf'), numero('ic-sup'), numero('q'), p.probabilityDecimal,
numero('probabilidad-referencia')];
if (!biomarcador?.code || !zona?.code || (tipo !== 'item' && tipo !== 'dominio') || !evento || !code(p.outcome)
|| !valores.every(v => typeof v === 'number')) return null;
const [valor_z, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia] = valores as number[];
return {
biomarcador: biomarcador.display ?? biomarcador.code, zona: zona.code, zona_etiqueta: zona.display ?? zona.code, valor_z,
tipo, resultado: code(p.outcome)!, resultado_etiqueta: display(p.outcome) ?? code(p.outcome)!, evento,
or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia, observado: extension(p, 'observado')?.valueInteger ?? null,
};
}).filter((f): f is TeaRelacionAdos2 => f !== null);
if ((nivel !== 'item' && nivel !== 'dominio') || !filas.length) return null;
return {
validado: extension(riesgo, 'modelo-validado')?.valueBoolean === true, nivel,
n_cohorte: extension(riesgo, 'modelo-n-cohorte')?.valueInteger ?? 0,
version: extension(riesgo, 'modelo-version')?.valueString ?? '', filas,
};
}
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
@@ -288,12 +333,14 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
const all = resources(bundle);
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
const episode = resources(bundle, 'EpisodeOfCare')[0];
const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
return teaPacienteDetalle({
simulado: all.length > 0 && all.every(isSimulated),
id_seudonimo: id,
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
...(relacion ? { relacion_ados2: relacion } : {}),
}, id);
}));
}