Compare commits

...

3 Commits

Author SHA1 Message Date
ulises efe4404c4e Seguimiento TEA: gráfica de la norma por edad con el paciente
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 <noreply@anthropic.com>
2026-11-21 00:27:16 -06:00
ulises 54b3e50ca5 TEA: el panel de relación con el ADOS-2 muestra solo las zonas alteradas del paciente
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:35:24 -06:00
ulises 680cc0adc6 TEA: panel «Relación con el ADOS-2» en la ficha del paciente (prototipo) y modo simulado local
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 <noreply@anthropic.com>
2026-11-20 20:06:15 -06:00
10 changed files with 512 additions and 19 deletions
+15
View File
@@ -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"
+38
View File
@@ -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.
+47
View File
@@ -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
}
}
+110
View File
@@ -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/<id>`: 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()
+21
View File
@@ -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
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
{ provide: IndicadoresService, useClass: FhirIndicadoresService },
{ provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos },
]
};
@@ -59,16 +59,16 @@
</section>
@if (d.eeg; as e) {
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
<div class="alteraciones-zona" [class.abierta]="abierto(e)">
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">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.</p>
<p class="meta">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.</p>
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
<ul class="metricas">
@for (m of e.alteraciones; track m.codigo) {
<li [attr.data-estado]="m.estado">
<div class="metrica">
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : mapaActual(e)?.codigo === m.codigo"
<button type="button" class="nombre" [disabled]="m.estado === 'no_evaluable'" [attr.aria-expanded]="m.estado === 'no_evaluable' ? null : abierto(e) && mapaElegido === m.codigo"
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
<span class="estado">{{ estado[m.estado] }}</span>
</div>
@@ -88,8 +88,24 @@
</ul>
</section>
@if (mapaActual(e); as mapa) {
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Mapa de zonas afectadas">
@if (abierto(e)) {
<div class="marco-mapa"><section class="mapa" [id]="'zonas-' + d.id_seudonimo" aria-label="Detalle de la alteración">
@if (mapaActual(e) && normaActual(e)) {
<div class="vistas" role="group" aria-label="Qué mostrar">
<button type="button" [attr.aria-pressed]="vista === 'zonas'" (click)="verVista('zonas')">Zonas de la cabeza</button>
<button type="button" [attr.aria-pressed]="vista === 'norma'" (click)="verVista('norma')">Norma por edad</button>
</div>
}
@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>
@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" />
}
<p class="leyenda-norma">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 }}).</p>
} @else if (mapaActual(e); as mapa) {
<h3>Zonas más afectadas</h3>
<p class="meta">{{ mapa.metrica }} · mapa ilustrativo</p>
<p class="leyenda-mapa"><span class="azul" aria-hidden="true"></span>Azul: menos actividad <span class="rojo" aria-hidden="true"></span>Rojo: más actividad</p>
@@ -102,9 +118,54 @@
<li [class.destacada]="r.valor_z >= 2 || r.valor_z <= -2"><span>{{ r.etiqueta }}</span><span>z = {{ r.valor_z }}</span></li>
}
</ol>
}
</section></div>
}
</div>
}
@if (d.relacion_ados2; as rel) {
<section class="panel relacion" aria-label="Relación de las alteraciones del EEG con el ADOS-2">
<h3>Relación con el ADOS-2 <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">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.}</p>
@if (!filasRelacion(rel).length) {
<p class="sin-alteraciones">Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.</p>
} @else {
<div class="tabla-relacion" role="region" aria-label="Asociaciones por zona" tabindex="0">
<table>
<thead>
<tr>
<th scope="col">Zona del EEG</th><th scope="col">Aspecto del ADOS-2</th><th scope="col">Asociación en la cohorte</th>
<th scope="col">Probabilidad para este paciente</th><th scope="col">Lo que muestra su ADOS-2</th>
</tr>
</thead>
<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>{{ 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>
<span class="prob">{{ porcentaje(f.probabilidad) }} %</span>
<span class="barra" aria-hidden="true">
<span class="paciente" [style.width.%]="porcentaje(f.probabilidad)"></span>
<span class="referencia" [style.left.%]="porcentaje(f.probabilidad_referencia)"></span>
</span>
<small>{{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} %</small>
</td>
<td>{{ observado(f) }}@if (coincide(f) !== null) { <small>{{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }}</small> }</td>
</tr>
}
</tbody>
</table>
</div>
<p class="nota">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 zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q &lt; 0.05). Versión del modelo: {{ rel.version }}.</p>
}
</section>
}
</div>
}
@@ -73,3 +73,24 @@ 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); }
// 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); }
@@ -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<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;
// ADOS-2 calibrated severity score ranges.
const NIVEL_CSS: Record<TeaAdos2['nivel_css'], string> = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' };
const CALIDAD: Record<TeaEeg['calidad'], string> = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' };
@@ -45,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}<extra></extra>` },
{ 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})<extra></extra>` },
],
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],
@@ -58,7 +94,7 @@ export class TeaPacienteResumen implements OnInit {
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
figura?: PlotlyFigure;
private mapaElegido?: string;
mapaElegido?: string;
private readonly elemento = inject<ElementRef<HTMLElement>>(ElementRef);
// The first solid background around this component: the map has no box of its own.
private fondo() {
@@ -68,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;
@@ -84,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'),
@@ -106,4 +160,25 @@ 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: 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) {
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);
}
}
@@ -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[];
@@ -67,7 +74,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<ClasificacionAdos2, string> = {
autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro',
@@ -141,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);
@@ -157,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'
@@ -172,9 +205,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;
}
@@ -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<HTMLButtonElement>('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<HTMLButtonElement>('.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<HTMLButtonElement>('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;
@@ -342,4 +377,29 @@ 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 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 };
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<HTMLButtonElement>('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.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();
});
});