From b53322ed72303bd09253acab28d6f7c1b1217616 Mon Sep 17 00:00:00 2001 From: AlbertoPMDM Date: Fri, 20 Nov 2026 19:52:10 -0600 Subject: [PATCH 1/6] fix(tea): one card per EEG metric and the electrode map within its column --- .../features/indicadores/indicadores-fhir.spec.ts | 12 ++++++++++++ .../features/indicadores/tea-paciente-resumen.scss | 4 ++-- src/app/features/indicadores/tea-seguimiento-fhir.ts | 3 ++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index b483f24..1f62fc4 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -198,6 +198,18 @@ describe('Seguimiento de TEA sobre FHIR', () => { expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']); }); + it('el mapa de electrodos del reporte no da una segunda tarjeta a su métrica', async () => { + // Pins down: the report's result lists each metric's observation and its electrode-map one, both coded under the + // metric's code, and only the metric observation becomes a card. Fails if the alteraciones filter stops skipping + // `electrodos-*` observations and the metric shows up twice. + 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; + const codigos = detalle.eeg!.alteraciones.map(a => a.codigo); + expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1); + }); + 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. diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 886fdbf..4da5d8c 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -1,4 +1,4 @@ -:host { display: block; container-type: inline-size; } +:host { display: block; container: host / inline-size; } .resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; } .panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); } h3 { margin: 0 0 .15rem; font-size: 1rem; } @@ -55,7 +55,7 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re .mapa h3 { margin-top: 0; } @keyframes aparecer { from { opacity: 0; } } @container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } } -@container zona (max-width: 42rem) { .mapa { width: 100cqw; } } +@container host (max-width: 42rem) { .mapa { width: 100cqw; } } @container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } } @media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } } .metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; } diff --git a/src/app/features/indicadores/tea-seguimiento-fhir.ts b/src/app/features/indicadores/tea-seguimiento-fhir.ts index 4c937ef..8e293a3 100644 --- a/src/app/features/indicadores/tea-seguimiento-fhir.ts +++ b/src/app/features/indicadores/tea-seguimiento-fhir.ts @@ -152,7 +152,8 @@ 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 alteraciones = listed.filter(o => codeIn(o.code, METRICAS)).map(o => alteracion(o, metricas)); + // 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-`. const mapas = observations.filter(o => o.id?.startsWith('electrodos-') && ids.has(o.id.slice('electrodos-'.length))) .map(o => { -- 2.53.0 From 304c56384511e97037635440032f78f1cfc23bb5 Mon Sep 17 00:00:00 2001 From: UlisesPG Date: Fri, 20 Nov 2026 20:06:15 -0600 Subject: [PATCH 2/6] =?UTF-8?q?TEA:=20panel=20=C2=ABRelaci=C3=B3n=20con=20?= =?UTF-8?q?el=20ADOS-2=C2=BB=20en=20la=20ficha=20del=20paciente=20(prototi?= =?UTF-8?q?po)=20y=20modo=20simulado=20local?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado. El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración «simulado» de Angular) es solo para trabajar en local. Co-Authored-By: Claude Opus 5.5 --- angular.json | 15 +++ simulado/README.md | 38 ++++++ simulado/proxy.simulado.json | 47 ++++++++ simulado/servidor.py | 110 ++++++++++++++++++ src/app/app.config.simulado.ts | 21 ++++ .../indicadores/tea-paciente-resumen.html | 45 +++++++ .../indicadores/tea-paciente-resumen.scss | 15 +++ .../indicadores/tea-paciente-resumen.ts | 32 ++++- .../indicadores/tea-seguimiento.service.ts | 29 ++++- .../indicadores/tea-seguimiento.spec.ts | 24 ++++ 10 files changed, 373 insertions(+), 3 deletions(-) create mode 100644 simulado/README.md create mode 100644 simulado/proxy.simulado.json create mode 100644 simulado/servidor.py create mode 100644 src/app/app.config.simulado.ts diff --git a/angular.json b/angular.json index e5cb6a7..aabfce8 100644 --- a/angular.json +++ b/angular.json @@ -62,6 +62,17 @@ "optimization": false, "extractLicenses": false, "sourceMap": true + }, + "simulado": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true, + "fileReplacements": [ + { + "replace": "src/app/app.config.ts", + "with": "src/app/app.config.simulado.ts" + } + ] } }, "defaultConfiguration": "production" @@ -77,6 +88,10 @@ }, "development": { "buildTarget": "WebApp:build:development" + }, + "simulado": { + "buildTarget": "WebApp:build:simulado", + "proxyConfig": "simulado/proxy.simulado.json" } }, "defaultConfiguration": "development" diff --git a/simulado/README.md b/simulado/README.md new file mode 100644 index 0000000..61bb005 --- /dev/null +++ b/simulado/README.md @@ -0,0 +1,38 @@ +# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`) + +Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso. +Todo es **inventado**. No forma parte de la WebApp que se entrega. + +| Archivo | Qué es | +|---|---| +| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona | +| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` | +| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba | +| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) | + +## Cómo se usa + +1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`: + ``` + python experimentos/E27_modelo_or/simulado_plataforma.py + ``` +2. Levantar el servidor de prueba, desde `webapp-tea/`: + ``` + python simulado/servidor.py + ``` +3. En otra terminal, la página, desde `webapp-tea/`: + ``` + npx ng serve --configuration simulado --port 4300 + ``` +4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente. + +## El panel nuevo: «Relación con el ADOS-2» + +En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05): +- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2); +- el aspecto del ADOS-2 (reactivo o dominio); +- el OR de la cohorte con su intervalo y su q; +- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0; +- lo que muestra su ADOS-2. + +El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece. diff --git a/simulado/proxy.simulado.json b/simulado/proxy.simulado.json new file mode 100644 index 0000000..ea18ef7 --- /dev/null +++ b/simulado/proxy.simulado.json @@ -0,0 +1,47 @@ +{ + "/api": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/imports": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/data": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/health": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/cacu": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/cama": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/tea": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/governance": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/reportes": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + } +} diff --git a/simulado/servidor.py b/simulado/servidor.py new file mode 100644 index 0000000..53b96a8 --- /dev/null +++ b/simulado/servidor.py @@ -0,0 +1,110 @@ +""" +servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa. + +Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega. +Responde lo que pide la sección de seguimiento de TEA en su contrato JSON: +- `/tea/seguimiento`: la lista, con filtros y páginas; +- `/tea/seguimiento/`: la ficha, incluido el campo nuevo `relacion_ados2`. + +A lo demás de `/tea/...` contesta vacío, para que la página cargue. + +Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`. + + python simulado/servidor.py # http://localhost:5051 + npx ng serve --configuration simulado --port 4300 +""" + +from __future__ import annotations + +import json +import math +import sys +from datetime import date, timedelta +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, unquote, urlparse + +PUERTO = 5051 +DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8")) +VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []} + + +def _num(q, k): + v = q.get(k, [None])[0] + try: + return float(v) if v is not None else None + except ValueError: + return None + + +def lista(q: dict) -> dict: + meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12 + corte = q.get("corte", [date.today().isoformat()])[0] + page = max(1, int(q.get("page", ["1"])[0])) + size = min(200, max(1, int(q.get("page_size", ["25"])[0]))) + filtro = q.get("alteraciones_eeg", [None])[0] + ps = DATOS["pacientes"] + if filtro in ("normal", "anormal"): + ps = [p for p in ps if p["alteraciones_eeg"] == filtro] + elif filtro == "sin_eeg_valido": + ps = [p for p in ps if p["ultimo_eeg"] is None] + if q.get("grupo_edad"): + ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))] + for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")): + a, b = _num(q, lo), _num(q, hi) + if a is not None: + ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)] + if q.get("estado_caso"): + ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]] + if q.get("alteracion"): + ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]] + total = len(ps) + por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)} + for t in DATOS["tipos_alteracion"]] + hasta = date.fromisoformat(corte) + return { + "simulado": True, "corte": corte, + "ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte}, + "filtros": {"alteraciones_eeg": filtro}, + "paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))}, + "items": ps[(page - 1) * size: page * size], + "tipos_alteracion": DATOS["tipos_alteracion"], + "resumen_eeg": {"validadas": True, "con_eeg_valido": total, + "normales": sum(p["alteraciones_eeg"] == "normal" for p in ps), + "anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0, + "por_alteracion": por_alt}, + } + + +class Manejador(BaseHTTPRequestHandler): + def _json(self, cuerpo, codigo=200): + datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8") + self.send_response(codigo) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(datos))) + self.end_headers() + self.wfile.write(datos) + + def do_GET(self): # noqa: N802 + u = urlparse(self.path) + ruta, q = u.path.rstrip("/"), parse_qs(u.query) + if ruta == "/tea/seguimiento": + return self._json(lista(q)) + if ruta.startswith("/tea/seguimiento/"): + d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1])) + return self._json(d) if d else self._json({"error": "no encontrado"}, 404) + if "/fhir/" in ruta: + return self._json(VACIO_FHIR) + if ruta.endswith("/indicadores"): + return self._json([]) + if ruta == "/health": + return self._json({"status": "ok", "simulado": True}) + return self._json({"error": "sin datos simulados para esta ruta"}, 404) + + def log_message(self, fmt, *args): + sys.stderr.write(" " + fmt % args + "\n") + + +if __name__ == "__main__": + print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)") + ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever() diff --git a/src/app/app.config.simulado.ts b/src/app/app.config.simulado.ts new file mode 100644 index 0000000..31b9c77 --- /dev/null +++ b/src/app/app.config.simulado.ts @@ -0,0 +1,21 @@ +import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; +import { provideRouter } from '@angular/router'; +import { routes } from './app.routes'; +import { IndicadoresService } from './features/indicadores/indicadores.service'; +import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos'; +import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir'; + +// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento +// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`). +export const appConfig: ApplicationConfig = { + providers: [ + provideBrowserGlobalErrorListeners(), + provideRouter(routes), + provideHttpClient(), + // The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract + // (`//indicadores//datos`, `/tea/seguimiento`). + { provide: IndicadoresService, useClass: FhirIndicadoresService }, + { provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos }, + ] +}; diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index 2c77e3e..e827e9d 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -106,5 +106,50 @@ } } + + @if (d.relacion_ados2; as rel) { +
+

Relación con el ADOS-2 Datos de ejemplo

+

Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se + asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2. + No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}

+ @if (!rel.filas.length) { +

La cohorte no muestra asociaciones claras para las zonas de este paciente.

+ } @else { + @if (!conZonaAlterada(rel)) {

Ninguna zona de este paciente está alterada (|z| ≥ 2); se muestran las asociaciones de la cohorte como referencia.

} +
+ + + + + + + + + @for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) { + + + + + + + + } + +
Zona del EEGAspecto del ADOS-2Asociación en la cohorteProbabilidad para este pacienteLo que muestra su ADOS-2
{{ biomarcador[f.biomarcador] ?? f.biomarcador }}{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · alterada}{{ f.resultado_etiqueta }}{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}OR {{ f.or }}IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}{{ direccion(f) }} + {{ porcentaje(f.probabilidad) }} % + + {{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} % + {{ observado(f) }}@if (coincide(f) !== null) { {{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }} }
+
+

OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La + probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0. + Solo se muestran las asociaciones claras en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.

+ } +
+ } } diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 4da5d8c..0f199d0 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -73,3 +73,18 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; } .canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; } + +// Relation with the ADOS-2 (association model): full width, a scrollable table on narrow screens. +.relacion { grid-column: 1 / -1; } +.tabla-relacion { overflow-x: auto; } +.tabla-relacion table { width: 100%; min-width: 44rem; border-collapse: collapse; font-size: .85rem; } +.tabla-relacion th, .tabla-relacion td { padding: .45rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; vertical-align: top; } +.tabla-relacion thead th { font-size: .8rem; color: var(--issste-text-secondary); font-weight: 600; } +.tabla-relacion small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); font-size: .75rem; } +.tabla-relacion tr.alterada td:first-child { box-shadow: inset 4px 0 0 #B3261E; } +.tabla-relacion .marca { color: #B3261E; font-weight: 600; } +.or, .prob { font-weight: 700; font-variant-numeric: tabular-nums; } +.barra { position: relative; display: block; height: .45rem; margin-top: .25rem; border-radius: 999px; background: var(--issste-border); } +.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); } +.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); } +.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 3abc899..223d026 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -4,9 +4,15 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyFigure } from './indicadores.models'; import { CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle, - TeaSeguimientoService, TeaAdos2, + TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2, } from './tea-seguimiento.service'; +const BIOMARCADOR: Record = { + 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; + // ADOS-2 calibrated severity score ranges. const NIVEL_CSS: Record = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' }; const CALIDAD: Record = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' }; @@ -106,4 +112,28 @@ export class TeaPacienteResumen implements OnInit { clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; } alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); } pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; } + + // Relation with the ADOS-2: the patient's altered zones first, then the clearest cohort associations. + readonly biomarcador = BIOMARCADOR; + zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; } + filasRelacion(rel: TeaRelacionModelo) { + return [...rel.filas].sort((a, b) => Number(this.zonaAlterada(b)) - Number(this.zonaAlterada(a)) || a.q - b.q); + } + conZonaAlterada(rel: TeaRelacionModelo) { return rel.filas.some(f => this.zonaAlterada(f)); } + direccion(f: TeaRelacionAdos2) { + return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad'; + } + porcentaje(p: number) { return Math.round(100 * p); } + qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; } + observado(f: TeaRelacionAdos2) { + if (f.observado === null) return 'Sin dato'; + if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)'; + return `CSS ${f.observado}`; + } + // Whether what the patient shows matches what the model leans to (above or below one half). + coincide(f: TeaRelacionAdos2) { + if (f.observado === null) return null; + const presente = f.tipo === 'item' ? f.observado >= 1 : f.observado >= 8; + return presente === (f.probabilidad >= .5); + } } diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts index 06534c3..83ad8fd 100644 --- a/src/app/features/indicadores/tea-seguimiento.service.ts +++ b/src/app/features/indicadores/tea-seguimiento.service.ts @@ -67,7 +67,20 @@ export interface TeaEeg { mapas: TeaEegMapa[]; ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] }; } -export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null } +// The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for +// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation. +export interface TeaRelacionAdos2 { + biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number; + tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string; + or: number; ic_inf: number; ic_sup: number; q: number; + probabilidad: number; probabilidad_referencia: number; observado: number | null; +} +export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] } +export interface TeaPacienteDetalle { + simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null; + // Absent until the WebApi serves the model. + relacion_ados2?: TeaRelacionModelo | null; +} // TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape. export const CLASIFICACIONES_ADOS2: Record = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro', @@ -172,9 +185,21 @@ function validEeg(e: unknown): boolean { && m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v))) && Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))); } +const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1; +function validRelacion(r: unknown): boolean { + if (r === undefined || r === null) return true; + return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string) + && integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas']) + && r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z']) + && ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento']) + && finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number) + && probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia']) + && (f['observado'] === null || finite(f['observado']))); +} export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle { if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); - if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])) + if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']) + || !validRelacion(v['relacion_ados2'])) throw new Error('Resumen del paciente inválido'); return v as unknown as TeaPacienteDetalle; } diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 1fd9156..507244c 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -342,4 +342,28 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow(); }); + // The association model's panel (prototype, simulated data): the field is optional and checked when present. + it('valida la relación con el ADOS-2 y la muestra con la zona alterada primero', () => { + const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa', + resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002, + probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 }; + const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 }; + const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } }); + expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow(); + expect(() => teaPacienteDetalle({ ...detalle, relacion_ados2: null }, 'T-0001')).not.toThrow(); + expect(() => teaPacienteDetalle(rel([fila]), 'T-0001')).not.toThrow(); + expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow(); + expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow(); + expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow(); + const fixture = open(); + request().flush(tres); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + root.querySelectorAll('button.row-toggle')[0].click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges(); + const filas = Array.from(root.querySelectorAll('section.relacion tbody tr')); + expect(filas.map(f => f.classList.contains('alterada'))).toEqual([true, false]); + expect(filas[0].textContent).toContain('q < 0.001'); + expect(filas[0].textContent).toContain('93 %'); + http.verify(); + }); }); -- 2.53.0 From 67ae7f482f5fe35c10cd547d72933288792f6721 Mon Sep 17 00:00:00 2001 From: UlisesPG Date: Fri, 20 Nov 2026 20:35:24 -0600 Subject: [PATCH 3/6] =?UTF-8?q?TEA:=20el=20panel=20de=20relaci=C3=B3n=20co?= =?UTF-8?q?n=20el=20ADOS-2=20muestra=20solo=20las=20zonas=20alteradas=20de?= =?UTF-8?q?l=20paciente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- src/app/features/indicadores/tea-paciente-resumen.html | 7 +++---- src/app/features/indicadores/tea-paciente-resumen.ts | 7 ++----- src/app/features/indicadores/tea-seguimiento.spec.ts | 5 +++-- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index e827e9d..e960920 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -113,10 +113,9 @@

Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2. No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}

- @if (!rel.filas.length) { -

La cohorte no muestra asociaciones claras para las zonas de este paciente.

+ @if (!filasRelacion(rel).length) { +

Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.

} @else { - @if (!conZonaAlterada(rel)) {

Ninguna zona de este paciente está alterada (|z| ≥ 2); se muestran las asociaciones de la cohorte como referencia.

}
@@ -147,7 +146,7 @@

OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0. - Solo se muestran las asociaciones claras en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.

+ Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.

} } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 223d026..c3c960a 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -113,13 +113,10 @@ export class TeaPacienteResumen implements OnInit { alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); } pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; } - // Relation with the ADOS-2: the patient's altered zones first, then the clearest cohort associations. + // 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].sort((a, b) => Number(this.zonaAlterada(b)) - Number(this.zonaAlterada(a)) || a.q - b.q); - } - conZonaAlterada(rel: TeaRelacionModelo) { return rel.filas.some(f => this.zonaAlterada(f)); } + filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); } direccion(f: TeaRelacionAdos2) { return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad'; } diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 507244c..a58e589 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -343,7 +343,7 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow(); }); // The association model's panel (prototype, simulated data): the field is optional and checked when present. - it('valida la relación con el ADOS-2 y la muestra con la zona alterada primero', () => { + it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => { const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa', resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002, probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 }; @@ -361,7 +361,8 @@ describe('Seguimiento TEA', () => { root.querySelectorAll('button.row-toggle')[0].click(); fixture.detectChanges(); http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges(); const filas = Array.from(root.querySelectorAll('section.relacion tbody tr')); - expect(filas.map(f => f.classList.contains('alterada'))).toEqual([true, false]); + expect(filas.length).toBe(1); + expect(filas[0].classList.contains('alterada')).toBe(true); expect(filas[0].textContent).toContain('q < 0.001'); expect(filas[0].textContent).toContain('93 %'); http.verify(); -- 2.53.0 From fa029d69b8eba39be7048c9516686c9516c1f36c Mon Sep 17 00:00:00 2001 From: UlisesPG Date: Sat, 21 Nov 2026 00:27:16 -0600 Subject: [PATCH 4/6] =?UTF-8?q?Seguimiento=20TEA:=20gr=C3=A1fica=20de=20la?= =?UTF-8?q?=20norma=20por=20edad=20con=20el=20paciente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas 5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo. Co-Authored-By: Claude Opus 5.5 --- .../indicadores/tea-paciente-resumen.html | 27 ++++++-- .../indicadores/tea-paciente-resumen.scss | 6 ++ .../indicadores/tea-paciente-resumen.ts | 68 ++++++++++++++++--- .../indicadores/tea-seguimiento.service.ts | 22 +++++- .../indicadores/tea-seguimiento.spec.ts | 35 ++++++++++ 5 files changed, 142 insertions(+), 16 deletions(-) diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index e960920..3d8c515 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -59,16 +59,16 @@ @if (d.eeg; as e) { -
+

Alteraciones del EEG Datos de ejemplo

-

Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.

+

Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.

@if (!alteradas(e).length) {

Sin alteraciones en las métricas evaluadas.

}
    @for (m of e.alteraciones; track m.codigo) {
  • - {{ estado[m.estado] }}
    @@ -88,8 +88,24 @@
- @if (mapaActual(e); as mapa) { -
+ @if (abierto(e)) { +
+ @if (mapaActual(e) && normaActual(e)) { +
+ + +
+ } + @if (vista === 'norma' && normaActual(e); as m) { +

Norma por edad

+

{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}

+ @if (figuraNorma) { + + } +

La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura). + El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).

+ } @else if (mapaActual(e); as mapa) {

Zonas más afectadas

{{ mapa.metrica }} · mapa ilustrativo

Azul: menos actividad Rojo: más actividad

@@ -102,6 +118,7 @@
  • {{ r.etiqueta }}z = {{ r.valor_z }}
  • } + }
    }
    diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 0f199d0..f81cf4d 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -88,3 +88,9 @@ button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border .barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); } .barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); } .nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); } +// The switch between the head map and the age norm, when the metric has both. +.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; } +.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; } +.vistas button + button { border-inline-start: 1px solid var(--issste-border); } +.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; } +.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index c3c960a..2f073cd 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -51,6 +51,36 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl }; } +// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point. +const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E'; +export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure { + const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse(); + const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({ + type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color, + line: { width: 0 }, name: nombre, hoverinfo: 'skip', + }); + const unidad = m.unidad ? ` ${m.unidad}` : ''; + const alterado = m.estado === 'aumentado' || m.estado === 'disminuido'; + return { + data: [ + banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'), + banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'), + { type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 }, + hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}` }, + { type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente', + marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } }, + hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})` }, + ], + layout: { + margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', + showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK }, + xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true }, + yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true }, + }, + config: { displayModeBar: false }, + }; +} + @Component({ selector: 'app-tea-paciente-resumen', imports: [PlotlyChart], @@ -64,7 +94,7 @@ export class TeaPacienteResumen implements OnInit { readonly status = signal<'loading' | 'ready' | 'error'>('loading'); readonly detalle = signal(undefined); figura?: PlotlyFigure; - private mapaElegido?: string; + mapaElegido?: string; private readonly elemento = inject>(ElementRef); // The first solid background around this component: the map has no box of its own. private fondo() { @@ -74,13 +104,29 @@ export class TeaPacienteResumen implements OnInit { } return '#FFFFFF'; } + // The side panel shows the chosen metric's head map, its age norm, or both with a switch between them. + vista: 'zonas' | 'norma' = 'zonas'; + figuraNorma?: PlotlyFigure; mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); } - elegirMapa(eeg: TeaEeg, codigo: string) { - // The chosen card closes the map again, and the cards take the whole space back. - const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo); - this.mapaElegido = mapa?.codigo; - this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); + // The age norm can only be drawn with the curve, the patient's value and their age. + private conNorma(eeg: TeaEeg, codigo?: string) { + const m = eeg.alteraciones.find(a => a.codigo === codigo); + return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined; } + normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); } + abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); } + private mostrar(eeg: TeaEeg, codigo: string | undefined) { + const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo); + this.mapaElegido = mapa || norma ? codigo : undefined; + this.vista = mapa ? 'zonas' : 'norma'; + this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); + this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number); + } + elegirMapa(eeg: TeaEeg, codigo: string) { + // The chosen card closes the panel again, and the cards take the whole space back. + this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo); + } + verVista(vista: 'zonas' | 'norma') { this.vista = vista; } readonly clasificacion = CLASIFICACIONES_ADOS2; readonly nivelCss = NIVEL_CSS; readonly calidad = CALIDAD; @@ -90,10 +136,12 @@ export class TeaPacienteResumen implements OnInit { this.status.set('loading'); this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({ next: d => { - // Opens on the first altered metric, or on the first one if none is altered. - const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0]; - this.mapaElegido = inicial?.codigo; - this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined; + // Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered. + const e = d.eeg; + if (e) { + const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo)); + this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo); + } else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; } this.detalle.set(d); this.status.set('ready'); }, error: () => this.status.set('error'), diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts index 83ad8fd..74ed6f4 100644 --- a/src/app/features/indicadores/tea-seguimiento.service.ts +++ b/src/app/features/indicadores/tea-seguimiento.service.ts @@ -56,10 +56,17 @@ export interface TeaEegAlteracion { valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[]; // Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age. sin_evaluar: 'sin_valor' | 'sin_referencia' | null; + // The age norm the reference comes from (percentiles by month), when the analysis sends it. + curva_referencia?: TeaCurvaReferencia | null; +} +export interface TeaCurvaReferencia { + fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[]; } export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] } export interface TeaEeg { fecha: string; duracion_min: number | null; canales: number | null; + // Age at the EEG, to place the patient on the age norms. + edad_meses?: number | null; // The overall rating is the EEG analysis's verdict; its checks say why. calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[]; alteraciones: TeaEegAlteracion[]; @@ -154,13 +161,24 @@ function validAdos(a: unknown): boolean { return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0) && a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0); } +// An age norm: ages in increasing order and, at each one, percentiles that never cross. +const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const; +function validCurva(c: unknown): boolean { + if (c === undefined || c === null) return true; + if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false; + const edades = c['edad_meses'] as unknown[], n = edades.length; + if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false; + const series = PERCENTILES.map(k => c[k]); + return series.every(s => Array.isArray(s) && s.length === n && s.every(finite)) + && edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i])); +} // A metric that can't be evaluated says why and has no z; one that can has its value, z and reference. function validAlteracion(a: unknown): boolean { const ref = a !== null && record(a) ? a['referencia'] : undefined; if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number) && (ref['mediana'] === null || finite(ref['mediana']))) - || !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false; + || !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false; const estado = a['estado']; if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string) && (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null); @@ -170,7 +188,9 @@ function validAlteracion(a: unknown): boolean { function validEeg(e: unknown): boolean { if (e === null) return true; const optional = (v: unknown) => v === null || integer(v); + const edad = record(e) ? e['edad_meses'] : undefined; if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales']) + || !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0) || !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string) || !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean' diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index a58e589..9e91ad6 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -172,6 +172,41 @@ describe('Seguimiento TEA', () => { expect(root.querySelector('section.mapa')).not.toBeNull(); http.verify(); }); + it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => { + const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48], + p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] }; + const conCurva = detalle.eeg.alteraciones.map(m => + m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m); + const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } }; + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges(); + const panel = () => root.querySelector('section.mapa')!; + const vistas = () => panel().querySelectorAll('.vistas button'); + // Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age. + expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']); + expect(panel().textContent).toContain('Zonas más afectadas'); + vistas()[1].click(); fixture.detectChanges(); + expect(vistas()[1].getAttribute('aria-pressed')).toBe('true'); + expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad'); + expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)'); + expect(panel().querySelector('.regiones')).toBeNull(); + // Gradiente has no map: its card opens the norm alone, without the switch. + const tarjetas = root.querySelectorAll('button.nombre'); + tarjetas[4].click(); fixture.detectChanges(); + expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true'); + expect(vistas().length).toBe(0); + expect(panel().textContent).toContain('Gradiente anteroposterior'); + const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance; + const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[]; + expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']); + expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]); + const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m); + expect(() => teaPacienteDetalle({ ...conNorma, eeg: { ...conNorma.eeg, alteraciones: cruzada } }, 'T-0001')).toThrow(); + http.verify(); + }); it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => { const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo); const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor; -- 2.53.0 From 68e2930e65132f37f6eaa9863e6d6bc4cb5a24df Mon Sep 17 00:00:00 2001 From: alberto Date: Sat, 21 Nov 2026 01:30:45 -0600 Subject: [PATCH 5/6] chore(tea): drop the local simulated-server mode; TEA follow-up reads only the WebApi --- angular.json | 15 ----- simulado/README.md | 38 ------------ simulado/proxy.simulado.json | 47 -------------- simulado/servidor.py | 110 --------------------------------- src/app/app.config.simulado.ts | 21 ------- 5 files changed, 231 deletions(-) delete mode 100644 simulado/README.md delete mode 100644 simulado/proxy.simulado.json delete mode 100644 simulado/servidor.py delete mode 100644 src/app/app.config.simulado.ts diff --git a/angular.json b/angular.json index aabfce8..e5cb6a7 100644 --- a/angular.json +++ b/angular.json @@ -62,17 +62,6 @@ "optimization": false, "extractLicenses": false, "sourceMap": true - }, - "simulado": { - "optimization": false, - "extractLicenses": false, - "sourceMap": true, - "fileReplacements": [ - { - "replace": "src/app/app.config.ts", - "with": "src/app/app.config.simulado.ts" - } - ] } }, "defaultConfiguration": "production" @@ -88,10 +77,6 @@ }, "development": { "buildTarget": "WebApp:build:development" - }, - "simulado": { - "buildTarget": "WebApp:build:simulado", - "proxyConfig": "simulado/proxy.simulado.json" } }, "defaultConfiguration": "development" diff --git a/simulado/README.md b/simulado/README.md deleted file mode 100644 index 61bb005..0000000 --- a/simulado/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`) - -Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso. -Todo es **inventado**. No forma parte de la WebApp que se entrega. - -| Archivo | Qué es | -|---|---| -| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona | -| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` | -| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba | -| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) | - -## Cómo se usa - -1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`: - ``` - python experimentos/E27_modelo_or/simulado_plataforma.py - ``` -2. Levantar el servidor de prueba, desde `webapp-tea/`: - ``` - python simulado/servidor.py - ``` -3. En otra terminal, la página, desde `webapp-tea/`: - ``` - npx ng serve --configuration simulado --port 4300 - ``` -4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente. - -## El panel nuevo: «Relación con el ADOS-2» - -En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05): -- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2); -- el aspecto del ADOS-2 (reactivo o dominio); -- el OR de la cohorte con su intervalo y su q; -- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0; -- lo que muestra su ADOS-2. - -El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece. diff --git a/simulado/proxy.simulado.json b/simulado/proxy.simulado.json deleted file mode 100644 index ea18ef7..0000000 --- a/simulado/proxy.simulado.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "/api": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/imports": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/data": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/health": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/cacu": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/cama": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/tea": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/governance": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - }, - "/reportes": { - "target": "http://localhost:5051", - "secure": false, - "changeOrigin": true - } -} diff --git a/simulado/servidor.py b/simulado/servidor.py deleted file mode 100644 index 53b96a8..0000000 --- a/simulado/servidor.py +++ /dev/null @@ -1,110 +0,0 @@ -""" -servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa. - -Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega. -Responde lo que pide la sección de seguimiento de TEA en su contrato JSON: -- `/tea/seguimiento`: la lista, con filtros y páginas; -- `/tea/seguimiento/`: la ficha, incluido el campo nuevo `relacion_ados2`. - -A lo demás de `/tea/...` contesta vacío, para que la página cargue. - -Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`. - - python simulado/servidor.py # http://localhost:5051 - npx ng serve --configuration simulado --port 4300 -""" - -from __future__ import annotations - -import json -import math -import sys -from datetime import date, timedelta -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import parse_qs, unquote, urlparse - -PUERTO = 5051 -DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8")) -VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []} - - -def _num(q, k): - v = q.get(k, [None])[0] - try: - return float(v) if v is not None else None - except ValueError: - return None - - -def lista(q: dict) -> dict: - meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12 - corte = q.get("corte", [date.today().isoformat()])[0] - page = max(1, int(q.get("page", ["1"])[0])) - size = min(200, max(1, int(q.get("page_size", ["25"])[0]))) - filtro = q.get("alteraciones_eeg", [None])[0] - ps = DATOS["pacientes"] - if filtro in ("normal", "anormal"): - ps = [p for p in ps if p["alteraciones_eeg"] == filtro] - elif filtro == "sin_eeg_valido": - ps = [p for p in ps if p["ultimo_eeg"] is None] - if q.get("grupo_edad"): - ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))] - for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")): - a, b = _num(q, lo), _num(q, hi) - if a is not None: - ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)] - if q.get("estado_caso"): - ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]] - if q.get("alteracion"): - ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]] - total = len(ps) - por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)} - for t in DATOS["tipos_alteracion"]] - hasta = date.fromisoformat(corte) - return { - "simulado": True, "corte": corte, - "ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte}, - "filtros": {"alteraciones_eeg": filtro}, - "paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))}, - "items": ps[(page - 1) * size: page * size], - "tipos_alteracion": DATOS["tipos_alteracion"], - "resumen_eeg": {"validadas": True, "con_eeg_valido": total, - "normales": sum(p["alteraciones_eeg"] == "normal" for p in ps), - "anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0, - "por_alteracion": por_alt}, - } - - -class Manejador(BaseHTTPRequestHandler): - def _json(self, cuerpo, codigo=200): - datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8") - self.send_response(codigo) - self.send_header("Content-Type", "application/json; charset=utf-8") - self.send_header("Content-Length", str(len(datos))) - self.end_headers() - self.wfile.write(datos) - - def do_GET(self): # noqa: N802 - u = urlparse(self.path) - ruta, q = u.path.rstrip("/"), parse_qs(u.query) - if ruta == "/tea/seguimiento": - return self._json(lista(q)) - if ruta.startswith("/tea/seguimiento/"): - d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1])) - return self._json(d) if d else self._json({"error": "no encontrado"}, 404) - if "/fhir/" in ruta: - return self._json(VACIO_FHIR) - if ruta.endswith("/indicadores"): - return self._json([]) - if ruta == "/health": - return self._json({"status": "ok", "simulado": True}) - return self._json({"error": "sin datos simulados para esta ruta"}, 404) - - def log_message(self, fmt, *args): - sys.stderr.write(" " + fmt % args + "\n") - - -if __name__ == "__main__": - print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)") - ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever() diff --git a/src/app/app.config.simulado.ts b/src/app/app.config.simulado.ts deleted file mode 100644 index 31b9c77..0000000 --- a/src/app/app.config.simulado.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; -import { provideHttpClient } from '@angular/common/http'; -import { provideRouter } from '@angular/router'; -import { routes } from './app.routes'; -import { IndicadoresService } from './features/indicadores/indicadores.service'; -import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos'; -import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir'; - -// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento -// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`). -export const appConfig: ApplicationConfig = { - providers: [ - provideBrowserGlobalErrorListeners(), - provideRouter(routes), - provideHttpClient(), - // The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract - // (`//indicadores//datos`, `/tea/seguimiento`). - { provide: IndicadoresService, useClass: FhirIndicadoresService }, - { provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos }, - ] -}; -- 2.53.0 From 4e9b25bd8fc4a6e4d8b79bc43c87c45a636c49a0 Mon Sep 17 00:00:00 2001 From: alberto Date: Sat, 21 Nov 2026 11:17:59 -0600 Subject: [PATCH 6/6] feat(tea): read the age-norm curve, the age at the EEG and the ADOS-2 relation from the WebApi's FHIR answer --- src/app/features/indicadores/fhir.ts | 2 +- .../indicadores/indicadores-fhir.spec.ts | 92 ++++++++++++++++++- .../indicadores/tea-paciente-resumen.html | 4 +- .../indicadores/tea-paciente-resumen.ts | 4 - .../indicadores/tea-seguimiento-fhir.ts | 55 ++++++++++- 5 files changed, 144 insertions(+), 13 deletions(-) diff --git a/src/app/features/indicadores/fhir.ts b/src/app/features/indicadores/fhir.ts index e184f26..71d0754 100644 --- a/src/app/features/indicadores/fhir.ts +++ b/src/app/features/indicadores/fhir.ts @@ -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[]; } diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index 1f62fc4..ddf545f 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -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. diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index 3d8c515..94862ac 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -98,7 +98,7 @@ } @if (vista === 'norma' && normaActual(e); as m) {

    Norma por edad

    -

    {{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}

    +

    {{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}

    @if (figuraNorma) { @@ -144,7 +144,7 @@
    @for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) { - +
    {{ biomarcador[f.biomarcador] ?? f.biomarcador }}{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · alterada}{{ f.biomarcador }}{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · alterada} {{ f.resultado_etiqueta }}{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }} OR {{ f.or }}IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}{{ direccion(f) }} diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 2f073cd..1f99f7a 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -7,9 +7,6 @@ import { TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2, } from './tea-seguimiento.service'; -const BIOMARCADOR: Record = { - 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) { diff --git a/src/app/features/indicadores/tea-seguimiento-fhir.ts b/src/app/features/indicadores/tea-seguimiento-fhir.ts index 8e293a3..4c3c61f 100644 --- a/src/app/features/indicadores/tea-seguimiento-fhir.ts +++ b/src/app/features/indicadores/tea-seguimiento-fhir.ts @@ -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-`. @@ -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); })); } -- 2.53.0