Gobernanza: Analizar EEG leads to Estudios EEG, which hosts the single-study evaluation; the timeline is only a dotted line; the probability curve and the age-norm bands are drawn from the model and the centiles

This commit is contained in:
2026-12-01 18:25:08 -06:00
parent f7eb170e15
commit 98eda5bc28
14 changed files with 187 additions and 141 deletions
+5 -10
View File
@@ -225,7 +225,7 @@ test('tea complete child: every screen has data', async ({ page }) => {
.filter({ hasText: /^tea\./ })
.first(),
).toBeVisible();
await models.getByRole('button', { name: 'Evaluar un solo estudio' }).click();
await studies.getByRole('button', { name: 'Evaluar un solo estudio' }).click();
const preview = page.locator('app-eeg-preview');
await expect(preview.getByLabel('EDF')).toBeAttached();
await expect(preview.getByLabel('ADOS-2 (PDF)')).toBeAttached();
@@ -319,13 +319,9 @@ test('tea gobernanza: every section in sync mode, and the preview saved as PDF',
await expect(folder).toBeHidden();
await expect(line).toBeHidden();
const monitor = page.locator('app-governance-models app-run-monitor');
await expect(page.getByRole('button', { name: 'Calcular riesgos' })).toHaveCount(0);
await page.getByRole('button', { name: 'Analizar EEG' }).click();
await expect(page.getByRole('heading', { name: 'Análisis de EEG' })).toBeVisible();
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
await page.getByRole('button', { name: 'Calcular riesgos' }).click();
await expect(page.getByRole('heading', { name: 'Cálculo de riesgos' })).toBeVisible();
await expect(monitor.getByRole('status')).toHaveText('SUCCESS', { timeout: 10 * 60_000 });
await expect(page.getByRole('heading', { name: 'Estudios EEG', level: 2 })).toBeFocused();
await page.getByRole('button', { name: 'Promover candidatas' }).click();
await expect(page.getByText('No hay candidatas que se puedan promover.')).toBeVisible();
@@ -340,9 +336,8 @@ test('tea gobernanza: every section in sync mode, and the preview saved as PDF',
{ timeout: 10 * 60_000 },
);
const models = page.getByRole('region', { name: 'Modelos' });
const toggle = models.getByRole('button', { name: 'Evaluar un solo estudio' });
const preview = models.locator('.button-row + app-eeg-preview');
const toggle = studies.getByRole('button', { name: 'Evaluar un solo estudio' });
const preview = studies.locator('app-eeg-preview');
const edf = preview.getByRole('button', { name: 'EDF', exact: true });
const ados = preview.getByRole('button', { name: 'ADOS-2 (PDF)', exact: true });
const birth = preview.getByLabel('Fecha de nacimiento');
+28 -12
View File
@@ -10,6 +10,31 @@ interface Band {
high?: (number | null)[];
}
export function bandFill(
x: number[],
low: (number | null)[],
high: (number | null)[],
colour: string,
alpha: string,
): Partial<Plotly.Data> {
const rows = x.flatMap((age, i) =>
low[i] != null && high[i] != null
? [{ age, low: low[i] as number, high: high[i] as number }]
: [],
);
return {
type: 'scatter',
mode: 'lines',
x: [...rows.map((r) => r.age), ...rows.map((r) => r.age).reverse()],
y: [...rows.map((r) => r.high), ...rows.map((r) => r.low).reverse()],
fill: 'toself',
fillcolor: `${colour}${alpha}`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
};
}
export function banded(
name: string,
b: Band,
@@ -17,18 +42,7 @@ export function banded(
dash?: 'dot',
): Partial<Plotly.Data>[] {
const lines: Partial<Plotly.Data>[] = [];
if (b.low && b.high) {
lines.push({
x: [...b.x, ...[...b.x].reverse()],
y: [...b.high, ...[...b.low].reverse()] as number[],
fill: 'toself',
fillcolor: `${colour}33`,
line: { width: 0 },
hoverinfo: 'skip',
showlegend: false,
type: 'scatter',
});
}
if (b.low && b.high) lines.push(bandFill(b.x, b.low, b.high, colour, '33'));
lines.push({
x: b.x,
y: b.y,
@@ -43,7 +57,9 @@ export function banded(
export interface Centile {
age_months: number;
p5: number | null;
p25?: number | null;
median: number | null;
p75?: number | null;
p95: number | null;
}
+1 -1
View File
@@ -14,8 +14,8 @@
<app-governance-models
#models
[domain]="domainKey()"
[execution]="execution.execution()"
(trainingRequested)="training.focus()"
(analysisRequested)="studies()?.focus()"
/>
<app-governance-training
#training
+2 -1
View File
@@ -1,4 +1,4 @@
import { Component, computed, inject, input, resource } from '@angular/core';
import { Component, computed, inject, input, resource, viewChild } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { RouterLink } from '@angular/router';
import { Api } from '../api/api';
@@ -23,4 +23,5 @@ export class Gobernanza {
protected readonly domainKey = computed(() => this.domain() as Domain);
protected readonly labels = DOMAINS as Record<string, string>;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
protected readonly studies = viewChild(EegStudies);
}
+5 -20
View File
@@ -2,30 +2,18 @@
<h2 id="models-heading">Modelos</h2>
<div class="button-row">
<button mat-flat-button type="button" (click)="selectTraining('all')">Entrenar modelos</button>
<button
mat-stroked-button
type="button"
[disabled]="starting() || running()"
(click)="start('score')"
>
Calcular riesgos
</button>
@if (domain() === 'tea') {
<button
mat-stroked-button
type="button"
[disabled]="starting() || running() || !execution()"
(click)="start('analyze')"
>
<button mat-stroked-button type="button" (click)="analysisRequested.emit()">
Analizar EEG
</button>
} @else {
<button
mat-stroked-button
type="button"
[attr.aria-pressed]="showPreview()"
(click)="showPreview.set(!showPreview())"
[disabled]="starting() || running()"
(click)="scoreRisks()"
>
Evaluar un solo estudio
Calcular riesgos
</button>
}
<button
@@ -37,9 +25,6 @@
Promover candidatas
</button>
</div>
@if (domain() === 'tea') {
<app-eeg-preview [active]="showPreview()" />
}
@if (run(); as current) {
<section>
<h3>{{ current.label }}</h3>
+1 -30
View File
@@ -1,6 +1,4 @@
import { TestBed } from '@angular/core/testing';
import { Api } from '../api/api';
import { checkActions, Models } from './models';
import { checkActions } from './models';
describe('version checks', () => {
it('enables promotion only when the API says the version is promotable', () => {
@@ -16,30 +14,3 @@ describe('version checks', () => {
expect(checkActions({ status: 'candidate', promotable: true, checks: [] }).retire).toBe(true);
});
});
describe('single study evaluation', () => {
it('toggles the preview form below the Modelos button row', async () => {
TestBed.overrideProvider(Api, { useValue: { invoke: vi.fn().mockResolvedValue([]) } });
const fixture = TestBed.createComponent(Models);
fixture.componentRef.setInput('domain', 'tea');
fixture.detectChanges();
await fixture.whenStable();
const host: HTMLElement = fixture.nativeElement;
const toggle = host.querySelector<HTMLButtonElement>('button[aria-pressed]')!;
const form = host.querySelector<HTMLFormElement>('.button-row + app-eeg-preview > form')!;
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(form.hidden).toBe(true);
toggle.click();
fixture.detectChanges();
expect(toggle.getAttribute('aria-pressed')).toBe('true');
expect(form.hidden).toBe(false);
expect(form.querySelectorAll('input')).toHaveLength(3);
toggle.click();
fixture.detectChanges();
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(form.hidden).toBe(true);
});
});
+4 -14
View File
@@ -5,7 +5,6 @@ import {
effect,
inject,
input,
linkedSignal,
output,
resource,
signal,
@@ -19,7 +18,6 @@ import { Api } from '../api/api';
import { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study';
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
import { analyze } from '../api/fn/models/analyze';
import { curve } from '../api/fn/models/curve';
import { lineage } from '../api/fn/models/lineage';
import { models } from '../api/fn/models/models';
@@ -31,13 +29,11 @@ import { score } from '../api/fn/models/score';
import { versionChecks } from '../api/fn/models/version-checks';
import { versions } from '../api/fn/models/versions';
import type { Domain } from '../api/models/domain';
import type { Execution as Choice } from '../api/models/execution';
import type { Run } from '../api/models/run';
import { Plot } from '../plot';
import { download } from '../export';
import { interpretabilityFigures, studyPoints, type Centile } from './figures';
import { errorText, RunMonitor } from './run-monitor';
import { EegPreview } from './tea/preview';
const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica',
@@ -80,7 +76,6 @@ export function checkActions(checks: Checks) {
MatSelectModule,
Plot,
RunMonitor,
EegPreview,
],
templateUrl: './models.html',
styleUrl: './models.scss',
@@ -88,9 +83,8 @@ export function checkActions(checks: Checks) {
export class Models {
private readonly api = inject(Api);
readonly domain = input.required<Domain>();
readonly execution = input<Choice>();
readonly trainingRequested = output<void>();
protected readonly showPreview = linkedSignal({ source: this.domain, computation: () => false });
readonly analysisRequested = output<void>();
protected readonly reportNames = REPORTS;
protected readonly errorText = errorText;
readonly refreshed = signal(0);
@@ -341,17 +335,13 @@ export class Models {
this.running.set(true);
}
protected async start(kind: 'score' | 'analyze'): Promise<void> {
protected async scoreRisks(): Promise<void> {
const domain = this.domain();
this.starting.set(true);
this.message.set('');
try {
const { run_id } =
kind === 'score'
? await this.api.invoke(score, { domain })
: await this.api.invoke(analyze, { domain, body: { execution: this.execution() } });
if (domain === this.domain())
this.follow(run_id, kind === 'score' ? 'Cálculo de riesgos' : 'Análisis de EEG');
const { run_id } = await this.api.invoke(score, { domain });
if (domain === this.domain()) this.follow(run_id, 'Cálculo de riesgos');
} catch (error) {
this.message.set(errorText(error));
} finally {
+10 -1
View File
@@ -1,5 +1,5 @@
<section class="card" aria-labelledby="studies-heading">
<h2 id="studies-heading">Estudios EEG</h2>
<h2 #heading id="studies-heading" tabindex="-1">Estudios EEG</h2>
<form class="button-row" (ngSubmit)="analyze()">
<mat-form-field appearance="outline">
<mat-label>Alcance</mat-label>
@@ -22,7 +22,16 @@
</mat-form-field>
}
<button mat-flat-button type="submit" [disabled]="busy() || !execution()">Analizar</button>
<button
mat-stroked-button
type="button"
[attr.aria-pressed]="showPreview()"
(click)="showPreview.set(!showPreview())"
>
Evaluar un solo estudio
</button>
</form>
<app-eeg-preview [active]="showPreview()" />
@if (error()) {
<p role="alert">{{ error() }}</p>
}
+29
View File
@@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { Api } from '../../api/api';
import { EegStudies } from './studies';
describe('single study evaluation', () => {
it('toggles the preview form below the Estudios EEG button row', async () => {
TestBed.overrideProvider(Api, { useValue: { invoke: vi.fn().mockResolvedValue([]) } });
const fixture = TestBed.createComponent(EegStudies);
fixture.detectChanges();
await fixture.whenStable();
const host: HTMLElement = fixture.nativeElement;
const toggle = host.querySelector<HTMLButtonElement>('button[aria-pressed]')!;
const form = host.querySelector<HTMLFormElement>('form.button-row + app-eeg-preview > form')!;
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(form.hidden).toBe(true);
toggle.click();
fixture.detectChanges();
expect(toggle.getAttribute('aria-pressed')).toBe('true');
expect(form.hidden).toBe(false);
expect(form.querySelectorAll('input')).toHaveLength(3);
toggle.click();
fixture.detectChanges();
expect(toggle.getAttribute('aria-pressed')).toBe('false');
expect(form.hidden).toBe(true);
});
});
+19 -1
View File
@@ -1,5 +1,14 @@
import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { Component, inject, input, output, resource, signal } from '@angular/core';
import {
Component,
ElementRef,
inject,
input,
output,
resource,
signal,
viewChild,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
@@ -14,6 +23,7 @@ import { runHistory } from '../../api/fn/runs/run-history';
import type { Execution } from '../../api/models/execution';
import type { Scope } from '../../api/models/scope';
import { errorText, RunMonitor } from '../run-monitor';
import { EegPreview } from './preview';
@Component({
selector: 'app-eeg-studies',
@@ -27,14 +37,22 @@ import { errorText, RunMonitor } from '../run-monitor';
MatInputModule,
MatSelectModule,
RunMonitor,
EegPreview,
],
templateUrl: './studies.html',
})
export class EegStudies {
private readonly api = inject(Api);
private readonly heading = viewChild.required<ElementRef<HTMLHeadingElement>>('heading');
protected readonly showPreview = signal(false);
readonly execution = input<Execution>();
readonly refresh = input(0);
readonly changed = output<void>();
focus(): void {
this.heading().nativeElement.focus();
}
protected readonly eegs = resource({
params: () => this.refresh(),
loader: () => this.api.invoke(studies),
+3 -2
View File
@@ -5,6 +5,7 @@ import type { Catalog, Category, HistoryPanel } from './pages';
const OLIVE = '#A8C243';
const ROSE = '#C24269';
export const SHORT = '.1~f';
const SIGNIFICANT = '.2~r';
export const percentAxis = {
type: 'linear' as const,
ticksuffix: ' %',
@@ -443,8 +444,8 @@ export function valueAxis(values: Iterable<number | null | undefined>) {
const narrow = found.length > 0 && Math.max(...found) - Math.min(0, ...found) <= 5;
return {
type: 'linear' as const,
tickformat: counts ? 'd' : SHORT,
hoverformat: counts ? 'd' : SHORT,
tickformat: counts ? 'd' : SIGNIFICANT,
hoverformat: counts ? 'd' : '.3~r',
...(counts && narrow ? { dtick: 1 } : {}),
};
}
+2 -2
View File
@@ -30,7 +30,7 @@ import {
patientName,
resources,
} from '../fhir';
import { scenarioFigure } from '../gobernanza/figures';
import { type Centile, scenarioFigure } from '../gobernanza/figures';
import { ageGroup, CAMA_AGE_GROUPS, camaRows } from '../indicadores/follow-up';
import { SHORT } from '../indicadores/figures';
import { LABELS, name, PRIORITY } from '../indicadores/measures';
@@ -38,7 +38,7 @@ import { Figure, PALETTE, Plot } from '../plot';
import { Loading } from '../loading';
import { Factores, ScenarioFactors } from './factores';
import { identityRows, loadTeaPatient, Study } from './tea-data';
import { ageNorm, Centile } from './tea-figures';
import { ageNorm } from './tea-figures';
import { TeaSection } from './tea-section';
import {
exportTeaPdf,
+59 -37
View File
@@ -1,4 +1,4 @@
import { banded } from '../gobernanza/figures';
import { bandFill, type Centile } from '../gobernanza/figures';
import { valueAxis } from '../indicadores/figures';
import { Figure, PALETTE } from '../plot';
import { Metric, Pair, Site, Study, TeaStep, zoneLabel } from './tea-data';
@@ -17,24 +17,12 @@ export function timeline(steps: TeaStep[]): Figure | null {
if (!done.length) return null;
const spans = done.slice(1).map((step, i) => ({ from: done[i], to: step }));
const last = done.at(-1)!.date;
const bars = {
type: 'bar',
orientation: 'h',
base: spans.map(({ from }) => from.date),
x: spans.map(({ from, to }) => Date.parse(to.date) - Date.parse(from.date)),
y: spans.map(({ to }) => to.label),
width: 0.24,
marker: { color: PALETTE[6] },
hoverinfo: 'skip',
showlegend: false,
} satisfies Figure['data'][number] & { base: string[] };
return {
data: [
bars,
{
type: 'scatter',
mode: 'lines+markers',
line: { dash: 'dot', color: PALETTE[0] },
line: { dash: 'dot', color: PALETTE[6], width: 1.5 },
x: done.map((step) => step.date),
y: done.map((step) => step.label),
marker: {
@@ -219,26 +207,32 @@ export function headMap(sites: Site[]): Figure {
};
}
export type Centile = {
age_months: number;
p5: number | null;
median: number | null;
p95: number | null;
};
export function ageNorm(rows: Centile[], metric: Metric, age: number): Figure {
const x = rows.map((row) => row.age_months);
return {
data: [
...banded(
'Mediana',
{
x: rows.map((row) => row.age_months),
y: rows.map((row) => row.median) as number[],
low: rows.map((row) => row.p5),
high: rows.map((row) => row.p95),
},
bandFill(
x,
rows.map((row) => row.p5),
rows.map((row) => row.p95),
PALETTE[4],
'29',
),
bandFill(
x,
rows.map((row) => row.p25 ?? null),
rows.map((row) => row.p75 ?? null),
PALETTE[4],
'52',
),
{
type: 'scatter',
mode: 'lines',
name: 'Mediana',
x,
y: rows.map((row) => row.median),
line: { color: PALETTE[4] },
},
{
type: 'scatter',
mode: 'markers',
@@ -351,20 +345,31 @@ export function zBars(eeg: Study): SingleTrace {
};
}
export function probabilityCurve(
pair: Pair,
logistic?: { intercept: number; slope: number },
): Figure {
const ALTERED_Z = 2;
const expit = (x: number) => 1 / (1 + Math.exp(-x));
export function probabilityCurve(pair: Pair): Figure {
const data: Figure['data'] = [];
if (logistic) {
const extent = Math.max(4, Math.abs(pair.z ?? 0));
const extent = Math.max(4, Math.ceil(Math.abs(pair.z ?? 0)) + 1);
const modelled =
pair.reference != null &&
pair.reference > 0 &&
pair.reference < 1 &&
pair.odds &&
pair.odds > 0;
if (modelled) {
const intercept = Math.log(pair.reference! / (1 - pair.reference!));
const slope = Math.log(pair.odds!);
const x = Array.from({ length: 81 }, (_, i) => (extent * (i - 40)) / 40);
data.push({
type: 'scatter',
mode: 'lines',
name: 'Modelo',
x,
y: x.map((z) => 100 / (1 + Math.exp(-(logistic.intercept + logistic.slope * z)))),
y: x.map((z) => 100 * expit(intercept + slope * z)),
line: { color: PALETTE[4], width: 2.5 },
hovertemplate: 'z = %{x:.1~f}: %{y:.1~f} %<extra></extra>',
});
}
if (pair.z != null && pair.probability != null) {
@@ -387,11 +392,28 @@ export function probabilityCurve(
marker: { size: 10, color: PALETTE[4], symbol: 'diamond-open' },
});
}
const zone = (x0: number, x1: number) => ({
type: 'rect' as const,
xref: 'x' as const,
yref: 'paper' as const,
x0,
x1,
y0: 0,
y1: 1,
fillcolor: 'rgba(194,66,105,0.10)',
line: { width: 0 },
layer: 'below' as const,
});
return {
data,
layout: {
xaxis: { title: { text: 'Puntuación z' }, ...valueAxis([pair.z, 0]) },
xaxis: {
title: { text: 'Puntuación z' },
...valueAxis([-extent, extent]),
range: [-extent, extent],
},
yaxis: { title: { text: 'Probabilidad (%)' }, ...valueAxis([0, 100]), range: [0, 100] },
...(modelled ? { shapes: [zone(-extent, -ALTERED_Z), zone(ALTERED_Z, extent)] } : {}),
},
};
}
+19 -10
View File
@@ -150,7 +150,7 @@ describe('Figuras del paciente TEA', () => {
it('dibuja los centiles del campeón y el valor observado a la edad del paciente', () => {
const figure = ageNorm(centiles, metric, 20.5);
expect(figure.data[0]).toMatchObject({ fill: 'toself', y: [2, 2.2, 0.2, 0] });
expect(figure.data[2]).toMatchObject({ mode: 'markers', x: [20.5], y: [1.7] });
expect(figure.data[3]).toMatchObject({ mode: 'markers', x: [20.5], y: [1.7] });
});
it('usa escala logarítmica y conserva solo zonas alteradas al activar el filtro', () => {
@@ -173,11 +173,26 @@ describe('Figuras del paciente TEA', () => {
expect(figure.layout?.shapes?.[0]).toMatchObject({ type: 'rect', x0: -2, x1: 2 });
});
it('dibuja solo los puntos de paciente y referencia cuando faltan parámetros', () => {
expect(probabilityCurve(pair).data).toMatchObject([
it('dibuja la curva del modelo con las zonas alteradas sombreadas', () => {
const figure = probabilityCurve(pair);
expect(figure.data).toMatchObject([
{ mode: 'lines', name: 'Modelo' },
{ mode: 'markers', x: [2.4], y: [70] },
{ mode: 'markers', x: [0], y: [20] },
]);
expect(figure.layout?.shapes).toMatchObject([
{ type: 'rect', x0: -4, x1: -2 },
{ type: 'rect', x0: 2, x1: 4 },
]);
});
it('dibuja solo los puntos de paciente y referencia cuando faltan parámetros', () => {
const figure = probabilityCurve({ ...pair, odds: undefined });
expect(figure.data).toMatchObject([
{ mode: 'markers', x: [2.4], y: [70] },
{ mode: 'markers', x: [0], y: [20] },
]);
expect(figure.layout?.shapes).toBeUndefined();
});
it('marca con un rombo cada etapa completada en su fecha', () => {
@@ -190,13 +205,7 @@ describe('Figuras del paciente TEA', () => {
x: ['2025-11-01', '2025-11-22'],
y: ['M-CHAT', 'Psicología'],
});
expect(figure.data[0]).toMatchObject({
type: 'bar',
orientation: 'h',
base: ['2025-11-01'],
x: [21 * 24 * 60 * 60 * 1000],
y: ['Psicología'],
});
expect(figure.data).toHaveLength(1);
});
it('anota los días entre etapas y deja pendientes las que faltan', () => {