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