187 lines
11 KiB
TypeScript
187 lines
11 KiB
TypeScript
import { Component, DestroyRef, ElementRef, inject, Input, OnInit, output, signal } from '@angular/core';
|
||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||
import { PlotlyFigure } from './indicadores.models';
|
||
import {
|
||
CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle,
|
||
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' };
|
||
const ESTADO: Record<TeaAlteracionEstado, string> = { normal: 'Dentro de referencia', aumentado: 'Aumentado', disminuido: 'Disminuido', no_evaluable: 'No evaluable' };
|
||
const INK = '#081839';
|
||
|
||
// Shape paths have no arcs: the hole is a polygon, wound against the frame so it stays empty under either fill rule.
|
||
const HOLE = Array.from({ length: 96 }, (_, i) => -2 * Math.PI * i / 96)
|
||
.map((a, i) => `${i ? 'L' : 'M'} ${Math.cos(a).toFixed(4)} ${Math.sin(a).toFixed(4)}`).join(' ');
|
||
// A frame with a round hole hides the map outside the head, in the colour behind the map; then the head outline, nose and ears.
|
||
const headShapes = (fondo: string) => [
|
||
{ type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${HOLE} Z`, fillrule: 'evenodd', fillcolor: fondo, line: { width: 0 } },
|
||
{ type: 'circle', xref: 'x', yref: 'y', x0: -1, y0: -1, x1: 1, y1: 1, line: { color: INK, width: 2 } },
|
||
{ type: 'path', path: 'M -0.13 0.99 L 0 1.13 L 0.13 0.99', line: { color: INK, width: 2 } },
|
||
{ type: 'path', path: 'M -0.99 0.14 Q -1.1 0.12 -1.08 0 Q -1.1 -0.12 -0.99 -0.14', line: { color: INK, width: 2 } },
|
||
{ type: 'path', path: 'M 0.99 0.14 Q 1.1 0.12 1.08 0 Q 1.1 -0.12 0.99 -0.14', line: { color: INK, width: 2 } },
|
||
];
|
||
|
||
export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): PlotlyFigure {
|
||
const m = { ...eeg.ejes_mapa, z: mapa.z };
|
||
return {
|
||
data: [
|
||
{ type: 'contour', x: m.x, y: m.y, z: m.z, zmin: -3, zmax: 3, zmid: 0, colorscale: 'RdBu', connectgaps: false,
|
||
contours: { coloring: 'heatmap', showlines: true }, line: { width: .5, color: 'rgba(8,24,57,.3)' },
|
||
colorbar: { title: { text: 'z', side: 'top' }, thickness: 12, len: .8 }, hovertemplate: 'z = %{z:.2f}<extra></extra>' },
|
||
{ type: 'scatter', mode: 'markers+text', x: m.electrodos.map(e => e.x), y: m.electrodos.map(e => e.y), text: m.electrodos.map(e => e.nombre),
|
||
textposition: 'top center', textfont: { size: 9, color: INK }, marker: { size: 5, color: INK }, hoverinfo: 'text', showlegend: false },
|
||
],
|
||
layout: {
|
||
margin: { l: 8, r: 8, t: 8, b: 8 }, showlegend: false, shapes: headShapes(fondo),
|
||
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)',
|
||
xaxis: { visible: false, range: [-1.2, 1.2], fixedrange: true },
|
||
yaxis: { visible: false, range: [-1.15, 1.2], scaleanchor: 'x', fixedrange: true },
|
||
},
|
||
config: { displayModeBar: false },
|
||
};
|
||
}
|
||
|
||
// 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],
|
||
templateUrl: './tea-paciente-resumen.html',
|
||
styleUrl: './tea-paciente-resumen.scss',
|
||
})
|
||
export class TeaPacienteResumen implements OnInit {
|
||
@Input({ required: true }) id = '';
|
||
/** `tarjetas`: four summary cards for a table row. `resumen`: the whole record as a summary with collapsible headers. */
|
||
@Input() modo: 'tarjetas' | 'resumen' = 'tarjetas';
|
||
/** The cards' button: the host shows the whole record in its own section. */
|
||
readonly completo = output<string>();
|
||
private readonly service = inject(TeaSeguimientoService);
|
||
private readonly destroy = inject(DestroyRef);
|
||
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
|
||
readonly detalle = signal<TeaPacienteDetalle | undefined>(undefined);
|
||
figura?: PlotlyFigure;
|
||
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() {
|
||
for (let e: HTMLElement | null = this.elemento.nativeElement; e; e = e.parentElement) {
|
||
const color = getComputedStyle(e).backgroundColor;
|
||
if (/^rgb\(/.test(color)) return color;
|
||
}
|
||
return '#FFFFFF';
|
||
}
|
||
// The chosen metric's head map and its age norm, whichever it has.
|
||
figuraNorma?: PlotlyFigure;
|
||
mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); }
|
||
// 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.figura = mapa && mapaFigure(eeg, mapa, this.fondo());
|
||
this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number);
|
||
}
|
||
elegirMapa(eeg: TeaEeg, codigo: string) {
|
||
// In the cards' accordion the chosen metric closes its panel again; in the full summary the plots stay in view.
|
||
this.mostrar(eeg, this.modo === 'tarjetas' && codigo === this.mapaElegido ? undefined : codigo);
|
||
}
|
||
readonly clasificacion = CLASIFICACIONES_ADOS2;
|
||
readonly nivelCss = NIVEL_CSS;
|
||
readonly calidad = CALIDAD;
|
||
readonly estado = ESTADO;
|
||
ngOnInit() { this.load(); }
|
||
load() {
|
||
this.status.set('loading');
|
||
this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({
|
||
next: d => {
|
||
// 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'),
|
||
});
|
||
}
|
||
// The study-wide checks, then each bad channel.
|
||
delEstudio(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo === null); }
|
||
// Three significant digits, without trailing zeros.
|
||
cifras(n: number | null | undefined) { return typeof n === 'number' ? String(Number(n.toPrecision(3))) : ''; }
|
||
canalesMalos(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo !== null); }
|
||
valorDe(c: TeaCriterioCalidad) {
|
||
return c.valor === null ? '' : typeof c.valor === 'number' ? `${Math.round(c.valor * 100) / 100}${c.unidad ? ' ' + c.unidad : ''}` : c.valor;
|
||
}
|
||
// Why a metric couldn't be evaluated, in the reader's terms.
|
||
sinEvaluar(m: TeaEegAlteracion) {
|
||
return m.sin_evaluar === 'sin_valor' ? 'No se pudo medir en el estudio.' : 'Sin referencia para la edad del niño.';
|
||
}
|
||
clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; }
|
||
// How many of the study-wide checks are out of range, and how many metrics could be judged against the age norm.
|
||
reglasFuera(eeg: TeaEeg) { return this.delEstudio(eeg).filter(c => c.nivel === 'malo').length; }
|
||
evaluables(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado !== 'no_evaluable').length; }
|
||
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' : `= ${this.cifras(q)}`; }
|
||
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);
|
||
}
|
||
}
|