From 98eda5bc28d2dfb9b37d28cb3b1aed7ba411978a Mon Sep 17 00:00:00 2001 From: alberto Date: Tue, 1 Dec 2026 18:25:08 -0600 Subject: [PATCH] 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 --- e2e/pages.spec.ts | 15 ++-- src/app/gobernanza/figures.ts | 40 +++++++---- src/app/gobernanza/gobernanza.html | 2 +- src/app/gobernanza/gobernanza.ts | 3 +- src/app/gobernanza/models.html | 25 ++----- src/app/gobernanza/models.spec.ts | 31 +-------- src/app/gobernanza/models.ts | 18 ++--- src/app/gobernanza/tea/studies.html | 11 ++- src/app/gobernanza/tea/studies.spec.ts | 29 ++++++++ src/app/gobernanza/tea/studies.ts | 20 +++++- src/app/indicadores/figures.ts | 5 +- src/app/paciente/paciente.ts | 4 +- src/app/paciente/tea-figures.ts | 96 ++++++++++++++++---------- src/app/paciente/tea-patient.spec.ts | 29 +++++--- 14 files changed, 187 insertions(+), 141 deletions(-) create mode 100644 src/app/gobernanza/tea/studies.spec.ts diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index dd34e84..f9fa564 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -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'); diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts index 440445c..8c3fdec 100644 --- a/src/app/gobernanza/figures.ts +++ b/src/app/gobernanza/figures.ts @@ -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 { + 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[] { const lines: Partial[] = []; - 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; } diff --git a/src/app/gobernanza/gobernanza.html b/src/app/gobernanza/gobernanza.html index 7a39d85..23af27d 100644 --- a/src/app/gobernanza/gobernanza.html +++ b/src/app/gobernanza/gobernanza.html @@ -14,8 +14,8 @@ this.domain() as Domain); protected readonly labels = DOMAINS as Record; protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); + protected readonly studies = viewChild(EegStudies); } diff --git a/src/app/gobernanza/models.html b/src/app/gobernanza/models.html index 8105d23..38934d4 100644 --- a/src/app/gobernanza/models.html +++ b/src/app/gobernanza/models.html @@ -2,30 +2,18 @@

Modelos

- @if (domain() === 'tea') { - + } @else { }
- @if (domain() === 'tea') { - - } @if (run(); as current) {

{{ current.label }}

diff --git a/src/app/gobernanza/models.spec.ts b/src/app/gobernanza/models.spec.ts index acbd102..a7e01ab 100644 --- a/src/app/gobernanza/models.spec.ts +++ b/src/app/gobernanza/models.spec.ts @@ -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('button[aria-pressed]')!; - const form = host.querySelector('.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); - }); -}); diff --git a/src/app/gobernanza/models.ts b/src/app/gobernanza/models.ts index 6d3cc8c..bac1c51 100644 --- a/src/app/gobernanza/models.ts +++ b/src/app/gobernanza/models.ts @@ -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 = { 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(); - readonly execution = input(); readonly trainingRequested = output(); - protected readonly showPreview = linkedSignal({ source: this.domain, computation: () => false }); + readonly analysisRequested = output(); 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 { + protected async scoreRisks(): Promise { 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 { diff --git a/src/app/gobernanza/tea/studies.html b/src/app/gobernanza/tea/studies.html index 9143306..64b8dcf 100644 --- a/src/app/gobernanza/tea/studies.html +++ b/src/app/gobernanza/tea/studies.html @@ -1,5 +1,5 @@
-

Estudios EEG

+

Estudios EEG

Alcance @@ -22,7 +22,16 @@ } +
+ @if (error()) {

{{ error() }}

} diff --git a/src/app/gobernanza/tea/studies.spec.ts b/src/app/gobernanza/tea/studies.spec.ts new file mode 100644 index 0000000..7f6cc40 --- /dev/null +++ b/src/app/gobernanza/tea/studies.spec.ts @@ -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('button[aria-pressed]')!; + const form = host.querySelector('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); + }); +}); diff --git a/src/app/gobernanza/tea/studies.ts b/src/app/gobernanza/tea/studies.ts index 0ad7f74..f44b77a 100644 --- a/src/app/gobernanza/tea/studies.ts +++ b/src/app/gobernanza/tea/studies.ts @@ -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>('heading'); + protected readonly showPreview = signal(false); readonly execution = input(); readonly refresh = input(0); readonly changed = output(); + + focus(): void { + this.heading().nativeElement.focus(); + } + protected readonly eegs = resource({ params: () => this.refresh(), loader: () => this.api.invoke(studies), diff --git a/src/app/indicadores/figures.ts b/src/app/indicadores/figures.ts index 5725479..4c846c4 100644 --- a/src/app/indicadores/figures.ts +++ b/src/app/indicadores/figures.ts @@ -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) { 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 } : {}), }; } diff --git a/src/app/paciente/paciente.ts b/src/app/paciente/paciente.ts index cbeb6b6..d107ec9 100644 --- a/src/app/paciente/paciente.ts +++ b/src/app/paciente/paciente.ts @@ -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, diff --git a/src/app/paciente/tea-figures.ts b/src/app/paciente/tea-figures.ts index ae33455..08296c8 100644 --- a/src/app/paciente/tea-figures.ts +++ b/src/app/paciente/tea-figures.ts @@ -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} %', }); } 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)] } : {}), }, }; } diff --git a/src/app/paciente/tea-patient.spec.ts b/src/app/paciente/tea-patient.spec.ts index 0f2cbf6..2a933f3 100644 --- a/src/app/paciente/tea-patient.spec.ts +++ b/src/app/paciente/tea-patient.spec.ts @@ -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', () => {