diff --git a/src/app/gobernanza/bundles.spec.ts b/src/app/gobernanza/bundles.spec.ts new file mode 100644 index 0000000..4b8ce54 --- /dev/null +++ b/src/app/gobernanza/bundles.spec.ts @@ -0,0 +1,28 @@ +import { verifiedImport } from './bundles'; + +const hash = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'; + +describe('bundle import', () => { + beforeEach(() => { + const bytes = Uint8Array.from(hash.match(/../g)!, (hex) => parseInt(hex, 16)); + vi.stubGlobal('crypto', { subtle: { digest: vi.fn().mockResolvedValue(bytes.buffer) } }); + }); + + afterEach(() => vi.unstubAllGlobals()); + + it('refuses to upload a file with a different SHA-256', async () => { + const file = new Blob([new Uint8Array([97, 98, 99])]); + const upload = vi.fn(); + await expect(verifiedImport(file, '0'.repeat(64), upload)).rejects.toThrow('no coincide'); + expect(upload).not.toHaveBeenCalled(); + }); + + it('submits the verified digest', async () => { + const file = new Blob([new Uint8Array([97, 98, 99])]); + const upload = vi.fn().mockResolvedValue({ run_id: 'run-1' }); + await expect(verifiedImport(file, hash.toUpperCase(), upload)).resolves.toEqual({ + run_id: 'run-1', + }); + expect(upload).toHaveBeenCalledExactlyOnceWith(hash); + }); +}); diff --git a/src/app/gobernanza/bundles.ts b/src/app/gobernanza/bundles.ts new file mode 100644 index 0000000..b312940 --- /dev/null +++ b/src/app/gobernanza/bundles.ts @@ -0,0 +1,127 @@ +import { Component, inject, input, model, output, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { Api } from '../api/api'; +import { exportModels, type ExportModels$Params } from '../api/fn/models/export-models'; +import { importModels } from '../api/fn/models/import-models'; +import type { Domain } from '../api/models/domain'; +import { errorText } from './run-monitor'; + +export async function verifiedImport( + file: Blob, + expected: string, + upload: (sha256: string) => Promise, +): Promise { + const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer()); + const sha256 = Array.from(new Uint8Array(digest), (byte) => + byte.toString(16).padStart(2, '0'), + ).join(''); + if (expected.trim().toLowerCase() !== sha256) { + throw new Error('El SHA-256 del archivo no coincide con el esperado.'); + } + return upload(sha256); +} + +export function download(blob: Blob, filename: string): void { + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = filename; + link.click(); + setTimeout(() => URL.revokeObjectURL(url), 0); +} + +@Component({ + selector: 'app-governance-bundles', + imports: [FormsModule, MatButtonModule], + template: ` +
+

Bundles

+
+ + +
+ @if (exportedHash()) { +

+ SHA-256 {{ exportedHash() }} +

+ } +
+ + + +
+ @if (message()) { +

{{ message() }}

+ } +
+ `, +}) +export class Bundles { + private readonly api = inject(Api); + readonly domain = input.required(); + readonly disabled = input(false); + readonly started = output(); + protected readonly selection = signal>('champion'); + protected readonly exportedHash = signal(''); + protected readonly hash = signal(''); + protected readonly message = signal(''); + protected readonly exporting = signal(false); + readonly importing = model(false); + + protected async export(): Promise { + this.exporting.set(true); + this.message.set(''); + this.exportedHash.set(''); + const domain = this.domain(); + try { + const response = await this.api.invoke$Response(exportModels, { + domain, + versions: this.selection(), + }); + const sha256 = response.headers.get('X-Bundle-Sha256') ?? ''; + this.exportedHash.set(sha256); + download(response.body, `${domain}-models-${sha256.slice(0, 12)}.zip`); + } catch (error) { + if (error instanceof Error && 'error' in error && error.error instanceof Blob) { + this.message.set(await error.error.text()); + } else { + this.message.set(errorText(error)); + } + } finally { + this.exporting.set(false); + } + } + + protected async import(input: HTMLInputElement): Promise { + const file = input.files?.[0]; + if (!file || this.importing() || this.disabled()) return; + this.importing.set(true); + this.message.set(''); + const domain = this.domain(); + try { + const { run_id } = await verifiedImport(file, this.hash(), (sha256) => + this.api.invoke(importModels, { + domain, + sha256, + body: { file: file as unknown as string }, + }), + ); + input.value = ''; + if (domain === this.domain()) this.started.emit(run_id); + } catch (error) { + this.message.set(errorText(error)); + } finally { + this.importing.set(false); + } + } +} diff --git a/src/app/gobernanza/execution.spec.ts b/src/app/gobernanza/execution.spec.ts new file mode 100644 index 0000000..d762293 --- /dev/null +++ b/src/app/gobernanza/execution.spec.ts @@ -0,0 +1,71 @@ +import { TestBed } from '@angular/core/testing'; +import { Api } from '../api/api'; +import { executionHealth } from '../api/fn/execution/execution-health'; +import { executionOptions } from '../api/fn/execution/execution-options'; +import { Execution } from './execution'; + +describe('execution', () => { + afterEach(() => { + TestBed.resetTestingModule(); + vi.useRealTimers(); + }); + + it('publishes the deployment default and the selected scheduler, and refreshes only when visible', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const doc = document; + const hidden = vi.spyOn(doc, 'hidden', 'get').mockReturnValue(false); + const invoke = vi.fn(async (operation: unknown) => + operation === executionOptions + ? { default_mode: 'local', schedulers: ['tcp://scheduler:8786'] } + : { mode: 'remote', reachable: true, workers: 2 }, + ); + try { + TestBed.overrideProvider(Api, { useValue: { invoke } }); + const fixture = TestBed.createComponent(Execution); + fixture.detectChanges(); + await fixture.whenStable(); + fixture.detectChanges(); + + expect(fixture.componentInstance.execution()).toEqual({ mode: 'local', scheduler: null }); + expect(invoke).toHaveBeenCalledWith(executionHealth, { mode: 'local', scheduler: null }); + + const mode: HTMLSelectElement = fixture.nativeElement.querySelector('select'); + mode.value = 'remote'; + mode.dispatchEvent(new Event('change')); + fixture.detectChanges(); + await fixture.whenStable(); + fixture.detectChanges(); + expect(fixture.componentInstance.execution()).toEqual({ + mode: 'remote', + scheduler: 'tcp://scheduler:8786', + }); + + const scheduler: HTMLInputElement = fixture.nativeElement.querySelector('input'); + scheduler.value = 'other:8786'; + scheduler.dispatchEvent(new Event('change')); + fixture.detectChanges(); + await fixture.whenStable(); + expect(fixture.componentInstance.execution()).toEqual({ + mode: 'remote', + scheduler: 'other:8786', + }); + + invoke.mockClear(); + await vi.advanceTimersByTimeAsync(30_000); + fixture.detectChanges(); + await fixture.whenStable(); + expect(invoke).toHaveBeenCalledExactlyOnceWith(executionHealth, { + mode: 'remote', + scheduler: 'other:8786', + }); + + invoke.mockClear(); + hidden.mockReturnValue(true); + await vi.advanceTimersByTimeAsync(30_000); + fixture.detectChanges(); + expect(invoke).not.toHaveBeenCalled(); + } finally { + hidden.mockRestore(); + } + }); +}); diff --git a/src/app/gobernanza/execution.ts b/src/app/gobernanza/execution.ts new file mode 100644 index 0000000..716fdd6 --- /dev/null +++ b/src/app/gobernanza/execution.ts @@ -0,0 +1,117 @@ +import { DOCUMENT } from '@angular/common'; +import { Component, computed, effect, inject, model, resource, signal } from '@angular/core'; +import { Api } from '../api/api'; +import { executionHealth } from '../api/fn/execution/execution-health'; +import { executionOptions } from '../api/fn/execution/execution-options'; +import type { Execution as Choice } from '../api/models/execution'; +import type { Health } from '../api/models/health'; + +@Component({ + selector: 'app-execution', + template: ` +
+

Ejecución

+ @if (options.hasValue()) { + + @if (choice().mode === 'remote') { + + + @for (host of options.value().schedulers; track host) { + + } + + } + } + @if (health.hasValue()) { + @let h = health.value(); +

+ {{ h.reachable ? 'Disponible' : 'No disponible' }} + @if (h.workers != null) { + · Trabajadores: {{ h.workers }} + } + @if (h.memory_per_worker != null) { + · Memoria por trabajador: {{ h.memory_per_worker }} + } + @if (h.error) { + · {{ h.error }} + } +

+ @if (h.dashboard_url && h.dashboard_ok !== false) { + Panel de Dask + } + } @else if (health.error() || options.error()) { +

No se pudo consultar la ejecución.

+ } +
+ `, +}) +export class Execution { + private readonly api = inject(Api); + private readonly document = inject(DOCUMENT); + private readonly visible = signal(!this.document.hidden); + readonly execution = model(undefined); + protected readonly options = resource({ loader: () => this.api.invoke(executionOptions) }); + protected readonly mode = signal(undefined); + protected readonly address = signal(undefined); + protected readonly choice = computed(() => { + const options = this.options.hasValue() ? this.options.value() : undefined; + const mode = this.mode() ?? options?.default_mode; + return { + mode, + scheduler: + mode === 'remote' ? (this.address() ?? options?.schedulers[0] ?? '').trim() || null : null, + }; + }); + + protected readonly health = resource({ + params: () => (this.visible() && this.choice().mode ? this.choice() : undefined), + loader: async ({ params }) => { + const health: Health & { memory_per_worker?: string | number } = await this.api.invoke( + executionHealth, + params, + ); + return health; + }, + }); + + constructor() { + effect(() => { + const choice = this.choice(); + this.execution.set(choice.mode ? choice : undefined); + }); + effect((cleanup) => { + const refresh = () => { + if (!this.document.hidden) this.health.reload(); + }; + const visibilityChanged = () => this.visible.set(!this.document.hidden); + const timer = setInterval(refresh, 30_000); + this.document.addEventListener('visibilitychange', visibilityChanged); + cleanup(() => { + clearInterval(timer); + this.document.removeEventListener('visibilitychange', visibilityChanged); + }); + }); + } + + protected select(mode: NonNullable): void { + this.mode.set(mode); + if (mode === 'remote' && this.address() === undefined && this.options.hasValue()) { + this.address.set(this.options.value().schedulers[0] ?? ''); + } + } +} diff --git a/src/app/gobernanza/figures.spec.ts b/src/app/gobernanza/figures.spec.ts index 76bfc70..b02690b 100644 --- a/src/app/gobernanza/figures.spec.ts +++ b/src/app/gobernanza/figures.spec.ts @@ -1,4 +1,4 @@ -import { interpretabilityFigures } from './figures'; +import { interpretabilityFigures, studyPoints } from './figures'; describe('governance figures', () => { it('draws a survival report as curves with bands and the model points', () => { @@ -9,7 +9,7 @@ describe('governance figures', () => { ], predicted: { name: 'Modelo', months: [6], survival: [0.92], low: [0.85], high: [0.97] }, }); - expect(found.figure.data.length).toBe(3); // band, curve, model points + expect(found.figure.data.length).toBe(3); expect((found.figure.data[2] as any).error_y.array[0]).toBeCloseTo(0.05); }); @@ -32,7 +32,7 @@ describe('governance figures', () => { }); expect(found.length).toBe(2); expect(found[1].title).toContain('fallecidos = 308'); - expect(found[1].figure.data.length).toBe(5); // band, KM, Weibull, fractional, points + expect(found[1].figure.data.length).toBe(5); expect((found[1].figure.data[4] as any).x).toEqual([6, 12, 18]); }); @@ -55,7 +55,7 @@ describe('governance figures', () => { ], }, }); - expect(found.figure.data.length).toBe(5); // band, KM, Weibull, fractional, points + expect(found.figure.data.length).toBe(5); }); it('draws an age curve with its centile band', () => { @@ -71,6 +71,84 @@ describe('governance figures', () => { expect(found.figure.data.length).toBe(2); }); + it('overlays the matching analysed metric at each study age on the API centiles', () => { + const points = studyPoints( + [ + { + id: 'one', + valid: true, + level: null, + age_months: 21, + checks: [], + regions: [], + metrics: [{ code: 'posterior_rhythm', value: 7, z: null, outside: null, model: null }], + }, + { + id: 'two', + valid: true, + level: null, + age_months: null, + checks: [], + regions: [], + metrics: [{ code: 'posterior_rhythm', value: 9, z: null, outside: null, model: null }], + }, + ], + 'eeg-posterior-rhythm', + 'value', + ); + const [found] = interpretabilityFigures( + { + kind: 'age_curves', + curves: { value: { kind: 'curves' } }, + }, + { + points, + centiles: [ + { age_months: 16, p5: 4, median: 6, p95: 8 }, + { age_months: 36, p5: 5, median: 7, p95: 9 }, + ], + }, + ); + + expect(found.figure.data[1]).toMatchObject({ x: [16, 36], y: [6, 7] }); + expect(found.figure.data[2]).toMatchObject({ mode: 'markers', x: [21], y: [7] }); + }); + + it('plots one row per association pair on the log odds-ratio axis', () => { + const [found] = interpretabilityFigures({ + kind: 'forest', + rows: [ + { + biomarker: 'Spindles', + zone: 'F', + outcome_code: 'A1', + odds_ratio: 2, + ci_low: 1.5, + ci_high: 3, + q: 0.04, + }, + { + biomarker: 'Spindles', + zone: 'O', + outcome_code: 'A1', + odds_ratio: 0.5, + ci_low: 0.25, + ci_high: 1, + q: 0.1, + }, + ], + }); + + expect(found.figure.layout?.xaxis?.type).toBe('log'); + expect(found.figure.data).toHaveLength(2); + expect(found.figure.data[0]).toMatchObject({ + x: [2], + y: ['Spindles · F · A1'], + error_x: { array: [1], arrayminus: [0.5] }, + hovertemplate: expect.stringContaining('q: 0.04'), + }); + }); + it('draws nothing for a report it does not know', () => { expect(interpretabilityFigures({ kind: 'other' })).toEqual([]); }); diff --git a/src/app/gobernanza/figures.ts b/src/app/gobernanza/figures.ts index ae8741c..638b13e 100644 --- a/src/app/gobernanza/figures.ts +++ b/src/app/gobernanza/figures.ts @@ -1,10 +1,10 @@ +import type { Analysis } from '../api/models/analysis'; import type { Figure } from '../plot'; import { PALETTE } from '../plot'; -/** A curve with its band, as the reports give them. */ interface Band { x: number[]; - y: number[]; + y: (number | null)[]; low?: (number | null)[]; high?: (number | null)[]; } @@ -34,10 +34,64 @@ function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial = { + 'eeg-posterior-rhythm': 'posterior_rhythm', + 'eeg-spindles-n2': 'spindles_n2', + 'eeg-spindle-topography-n2': 'spindles_n2', + 'eeg-spindles-n3': 'spindles_n3', + 'eeg-spindle-topography-n3': 'spindles_n3', + 'eeg-spikes': 'paroxysmal_spikes', + 'eeg-gradient': 'anteroposterior_gradient', +}; + +export function studyPoints(analyses: Analysis[], model: string, feature: string): StudyPoint[] { + const code = EEG_METRICS[model]; + return analyses.flatMap((analysis) => { + const age = analysis.age_months; + if (age == null || !Number.isFinite(age) || age <= 0) return []; + const value = + feature === 'value' + ? analysis.metrics.find((metric) => metric.code === code)?.value + : analysis.regions.find( + (region) => + region['code'] === code && feature === region['kind'] + '_' + region['site'], + )?.['value']; + return typeof value === 'number' && Number.isFinite(value) ? [{ age, value }] : []; + }); +} + +interface AssociationRow { + biomarker: string; + zone: string; + outcome_code: string; + odds_ratio: number | null; + ci_low: number | null; + ci_high: number | null; + q: number | null; +} + export function interpretabilityFigures( report: Record, + ageCurve: AgeCurveOptions = {}, ): { title: string; figure: Figure }[] { switch (report['kind']) { case 'curves': { @@ -70,7 +124,6 @@ export function interpretabilityFigures( }, }, }, - // Its clinical scenarios, those with enough deaths to draw. ...((report['escenarios'] ?? []) as any[]).map((e) => scenarioFigure( `${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, @@ -158,24 +211,73 @@ export function interpretabilityFigures( 'Supervivencia libre de recaída', ), ); + case 'forest': + return [ + { + title: 'Asociaciones ADOS-2', + figure: { + data: (report['rows'] as AssociationRow[]).map((row) => { + const label = [row.biomarker, row.zone, row.outcome_code].filter(Boolean).join(' · '); + const odds = row.odds_ratio; + return { + x: [odds], + y: [label], + name: label, + showlegend: false, + type: 'scatter', + mode: 'markers', + marker: { color: PALETTE[4] }, + error_x: + odds == null || row.ci_low == null || row.ci_high == null + ? undefined + : { + type: 'data', + symmetric: false, + array: [row.ci_high - odds], + arrayminus: [odds - row.ci_low], + }, + hovertemplate: '%{y}
OR: %{x}
q: ' + (row.q ?? '—') + '', + }; + }), + layout: { + xaxis: { type: 'log', title: { text: 'OR (IC 95 %)' } }, + yaxis: { type: 'category', automargin: true }, + }, + }, + }, + ]; case 'age_curves': { - // The metric's own curve; a topography has only electrodes: its first one. - const value = report['curves']['value'] ?? Object.values(report['curves'])[0]; + const curves = report['curves']; + const feature = ageCurve.feature ?? (curves.value ? 'value' : Object.keys(curves)[0]); + const value = curves[feature]; if (!value) return []; - const label = report['curves']['value'] ? '' : ` · ${Object.keys(report['curves'])[0]}`; + const label = feature === 'value' ? '' : ` · ${feature}`; + const overlay: Partial[] = ageCurve.points?.length + ? [ + { + x: ageCurve.points.map((point) => point.age), + y: ageCurve.points.map((point) => point.value), + name: 'Estudios analizados', + type: 'scatter', + mode: 'markers', + }, + ] + : []; if (value.kind === 'count_rate') { + const rate = Number.isFinite(value.rate) ? value.rate : null; return [ { - title: `Tasa de referencia: ${value.rate.toFixed(3)} por minuto (${value.reference} estudios)`, + title: `Tasa de referencia: ${rate?.toFixed(3) ?? '—'} por minuto (${value.reference} estudios)${label}`, figure: { data: [ { x: value.ages, - y: [value.rate, value.rate], + y: [rate, rate], name: 'Tasa', type: 'scatter', mode: 'lines', }, + ...overlay, ], layout: { xaxis: { title: { text: 'Edad (meses)' } }, @@ -185,18 +287,28 @@ export function interpretabilityFigures( }, ]; } - const c = value.curve; + const centiles = ageCurve.centiles; + if (!centiles && ageCurve.waitForCentiles) return []; + const c = centiles + ? { + age_months: centiles.map((point) => point.age_months), + median: centiles.map((point) => point.median), + p5: centiles.map((point) => point.p5), + p95: centiles.map((point) => point.p95), + } + : value.curve; return [ { title: `Curva de referencia por edad (p5, mediana, p95)${label}`, figure: { data: [ ...banded( - 'p5–p95', + 'Mediana', { x: c.age_months, y: c.median, low: c.p5, high: c.p95 }, PALETTE[4], ), - ].map((d, i) => (i === 1 ? { ...d, name: 'Mediana' } : d)), + ...overlay, + ], layout: { xaxis: { title: { text: 'Edad (meses)' }, type: 'log' }, yaxis: { title: { text: 'Valor' } }, @@ -210,8 +322,6 @@ export function interpretabilityFigures( } } -/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull, - * and the model's points with their bootstrap band. */ function scenarioFigure( title: string, e: any, diff --git a/src/app/gobernanza/gobernanza.html b/src/app/gobernanza/gobernanza.html index fcd4cd7..97de969 100644 --- a/src/app/gobernanza/gobernanza.html +++ b/src/app/gobernanza/gobernanza.html @@ -1,179 +1,305 @@

Gobernanza de modelos

-
- - Datos hasta - - - - - @if (domain() === 'tea') { - - } - @if (run(); as r) { - {{ r.kind }}: {{ r.status }} - } -
- @if (message()) { -

{{ message() }}

- } + - @if (models.isLoading()) { -

Cargando modelos…

- } @else if (!models.value()?.length) { -

Este dominio todavía no tiene modelos entrenados.

- } - @for (m of models.value() ?? []; track m.name) { -
-

{{ m.name }}

- - - - - - - - - - - - - @for (v of m.versions; track v.version) { - - - - - - - - - } - -
VersiónCreadaEntrenamiento / pruebaInformesValidación clínica
- v{{ v.version }} - @if (champion(v)) { - en producción - } - {{ v.created | date: 'yyyy-MM-dd HH:mm' }} - {{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }} - - @for (r of v.reports; track r) { - {{ - reportNames[r] ?? r - }} - } - @if (v.reports.includes('interpretability')) { - - } - - @if (!v.reports.includes('clinical_validation')) { - - } @else { - Agregada - } - - @if (!champion(v)) { - - } -
-
- } - - @if (chosen(); as c) { -
-

Interpretabilidad · {{ c.name }} v{{ c.version }}

- @for (f of figures(); track f.title) { -

{{ f.title }}

- - } @empty { -

- {{ report.isLoading() ? 'Cargando…' : 'Este informe no tiene gráficas.' }} -

+
+

Modelos

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

{{ current.label }}

+ +
+ } + @if (message()) { +

{{ message() }}

+ } - @if (domain() === 'tea') { -
-

Electroencefalogramas

- - - - - - - - - - @for (e of eegs.value() ?? []; track e.id) { - - - - - - } @empty { - - - - } - -
FechaRegistroAnálisis
- - {{ e.lab_record_id ?? '—' }} - {{ !e.analysed ? 'Sin analizar' : e.valid ? 'Válido' : 'No válido' }} - {{ e.level ? '(' + e.level + ')' : '' }} -
Sin EEG cargados.
- @if (eegMetrics.value(); as m) { -

EEG {{ m.id }} · {{ m.age_months ?? '—' }} meses

+ @if (models.isLoading()) { +

Cargando modelos…

+ } @else if (models.error(); as error) { +

{{ errorText(error) }}

+ } @else if (!models.hasValue() || !models.value().length) { +

Este dominio todavía no tiene modelos entrenados.

+ } + @for (m of models.hasValue() ? models.value() : []; track m.name) { +
+

{{ m.name }}

+ - - - - + + + + + + - @for (x of m.metrics; track x.code) { + @for (v of m.versions; track v.version) { - - - - - - } @empty { - - + + + + + + }
MétricaValorzCurvaVersiónCreadaEntrenamiento / pruebaInformesValidación clínicaComprobaciones y linaje
{{ metricNames[x.code] ?? x.code }}{{ x.value | number: '1.2-2' }}{{ x.z === null ? '—' : (x.z | number: '1.2-2') }}{{ x.model ?? 'sin curva en producción' }}
Sin métricas (EEG no válido). + v{{ v.version }} {{ v.status }} + {{ v.created | date: 'yyyy-MM-dd HH:mm' }} + {{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }} + + @for (report of v.reports; track report) { + + } + @if (v.reports.includes('interpretability')) { + + } + + @if (!v.reports.includes('clinical_validation')) { + + } @else { + Agregada + } + + + +
- } -
+
+ } + + @if (chosen(); as version) { +
+

Interpretabilidad · {{ version.name }} v{{ version.version }}

+ @if (feature(); as current) { + @if (ageFeatures().length > 1) { + + } + + } + @if (report.error() || band.error() || analysed.error(); as error) { +

{{ errorText(error) }}

+ } + @for (f of figures(); track f.title) { +

{{ f.title }}

+ + } @empty { + @if (report.isLoading() || band.isLoading()) { +

Cargando…

+ } @else if (!report.error() && !band.error()) { +

Este informe no tiene gráficas.

+ } + } +
+ } +
+ + @if (domain() === 'tea') { + } + + + @if (checksFor(); as key) { +

Comprobaciones · {{ key.name }} v{{ key.version }}

+ @if (checks.hasValue()) { + @let details = checks.value(); + @let actions = checkActions(details); +
    + @for (check of details.checks; track check.report) { +
  • + {{ reportNames[check.report] ?? check.report }} · + {{ check.present ? 'Presente' : 'Falta' }} +
  • + } +
+ + + } @else if (checks.error(); as error) { +

{{ errorText(error) }}

+ } @else { +

Cargando…

+ } + @if (message()) { +

{{ message() }}

+ } + } +
+
+ + + @if (lineageFor(); as key) { +

Linaje · {{ key.name }} v{{ key.version }}

+ @if (lineage.hasValue()) { + @let details = lineage.value(); +

Parámetros

+
+ @for (entry of details.params | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+

Métricas

+
+ @for (entry of details.metrics | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+

Etiquetas

+
+ @for (entry of details.tags | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+ @if (details.imported; as imported) { +

Importado de

+
+ @for (entry of imported | keyvalue; track entry.key) { +
{{ entry.key }}
+
{{ entry.value }}
+ } +
+ } + } @else if (lineage.error(); as error) { +

{{ errorText(error) }}

+ } @else { +

Cargando…

+ } + } +
+
+ + +

Promover candidatas

+
    + @for (candidate of candidates(); track candidate.name) { +
  • {{ candidate.name }} v{{ candidate.version }}
  • + } +
+ +
+
diff --git a/src/app/gobernanza/gobernanza.scss b/src/app/gobernanza/gobernanza.scss index e974ad7..03405bc 100644 --- a/src/app/gobernanza/gobernanza.scss +++ b/src/app/gobernanza/gobernanza.scss @@ -45,3 +45,12 @@ td a { padding: 48px 0; text-align: center; } +.message { + white-space: pre-line; +} +dialog { + max-width: min(90vw, 64rem); +} +dialog form { + margin-top: var(--space-3); +} diff --git a/src/app/gobernanza/gobernanza.spec.ts b/src/app/gobernanza/gobernanza.spec.ts new file mode 100644 index 0000000..c801c48 --- /dev/null +++ b/src/app/gobernanza/gobernanza.spec.ts @@ -0,0 +1,16 @@ +import { checkActions } from './gobernanza'; + +describe('version checks', () => { + it('enables promotion only when the API says the version is promotable', () => { + expect(checkActions({ status: 'candidate', promotable: false, checks: [] }).promote).toBe( + false, + ); + expect(checkActions({ status: 'candidate', promotable: true, checks: [] }).promote).toBe(true); + expect(checkActions({ status: 'retired', promotable: false, checks: [] }).promote).toBe(false); + }); + + it('disables retirement for the champion', () => { + expect(checkActions({ status: 'champion', promotable: true, checks: [] }).retire).toBe(false); + expect(checkActions({ status: 'candidate', promotable: true, checks: [] }).retire).toBe(true); + }); +}); diff --git a/src/app/gobernanza/gobernanza.ts b/src/app/gobernanza/gobernanza.ts index 3e0289f..4ff96c6 100644 --- a/src/app/gobernanza/gobernanza.ts +++ b/src/app/gobernanza/gobernanza.ts @@ -1,30 +1,35 @@ -import { HttpErrorResponse } from '@angular/common/http'; -import { DatePipe, DecimalPipe } from '@angular/common'; -import { Component, computed, inject, input, resource, signal } from '@angular/core'; +import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common'; +import { Component, computed, effect, inject, input, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatInputModule } from '@angular/material/input'; import { RouterLink } from '@angular/router'; import { Api } from '../api/api'; -import { ApiConfiguration } from '../api/api-configuration'; -import { addClinicalValidation } from '../api/fn/models/add-clinical-validation'; -import { analyze } from '../api/fn/models/analyze'; -import { models } from '../api/fn/models/models'; -import { promote } from '../api/fn/models/promote'; -import { readReport$Json } from '../api/fn/models/read-report-json'; -import { score } from '../api/fn/models/score'; -import { train } from '../api/fn/models/train'; -import { versions } from '../api/fn/models/versions'; -import { domains } from '../api/fn/operations/domains'; import { studies } from '../api/fn/eeg/studies'; import { study } from '../api/fn/eeg/study'; -import { runStatus } from '../api/fn/runs/run-status'; +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'; +import { promote } from '../api/fn/models/promote'; +import { readReport$Any } from '../api/fn/models/read-report-any'; +import { readReport$Json } from '../api/fn/models/read-report-json'; +import { retire } from '../api/fn/models/retire'; +import { score } from '../api/fn/models/score'; +import { versionChecks } from '../api/fn/models/version-checks'; +import { versions } from '../api/fn/models/versions'; +import { domains } from '../api/fn/operations/domains'; import type { Domain } from '../api/models/domain'; -import type { Version } from '../api/models/version'; +import type { Execution as Choice } from '../api/models/execution'; +import type { Run } from '../api/models/run'; import { DOMAINS } from '../app'; import { Plot } from '../plot'; -import { interpretabilityFigures } from './figures'; +import { Bundles, download } from './bundles'; +import { Execution } from './execution'; +import { interpretabilityFigures, studyPoints, type Centile } from './figures'; +import { errorText, RunMonitor } from './run-monitor'; +import { EegStudies } from './tea/studies'; +import { Training } from './training'; const REPORTS: Record = { technical_validation: 'Validación técnica', @@ -32,35 +37,63 @@ const REPORTS: Record = { clinical_validation: 'Validación clínica', }; -/** Model governance for a domain: every model's versions with their metrics and reports, - * the clinical validation the clinical team uploads, promotion (refused without the three - * reports), and the training and scoring runs. */ +interface VersionKey { + name: string; + version: number; +} + +interface Checks { + status: 'candidate' | 'champion' | 'retired'; + promotable: boolean; + checks: { report: string; present: boolean }[]; +} + +interface Lineage { + params: Record; + metrics: Record; + tags: Record; + imported: Record | null; +} + +export function checkActions(checks: Checks) { + return { promote: checks.promotable, retire: checks.status !== 'champion' }; +} + @Component({ selector: 'app-gobernanza', imports: [ DatePipe, DecimalPipe, + KeyValuePipe, FormsModule, MatButtonModule, - MatFormFieldModule, - MatInputModule, RouterLink, Plot, + Bundles, + Execution, + RunMonitor, + EegStudies, + Training, ], templateUrl: './gobernanza.html', styleUrl: './gobernanza.scss', }) export class Gobernanza { private readonly api = inject(Api); - private readonly root = inject(ApiConfiguration).rootUrl; readonly domain = input.required(); - + protected readonly domainKey = computed(() => this.domain() as Domain); + protected readonly execution = signal(undefined); protected readonly labels = DOMAINS as Record; protected readonly reportNames = REPORTS; + protected readonly errorText = errorText; protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); - private readonly refreshed = signal(0); + protected readonly refreshed = signal(0); + + protected refresh(): void { + this.refreshed.update((value) => value + 1); + } protected readonly models = resource({ - params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }), + params: () => ({ domain: this.domainKey(), at: this.refreshed() }), loader: async ({ params: { domain } }) => { const names = await this.api.invoke(models, { domain }); return Promise.all( @@ -71,91 +104,299 @@ export class Gobernanza { ); }, }); - protected readonly chosen = signal<{ name: string; version: number } | undefined>(undefined); + protected readonly training = signal(''); + protected readonly run = signal<{ id: string; label: string; autoPromote?: boolean } | undefined>( + undefined, + ); + protected readonly starting = signal(false); + protected readonly running = signal(false); + protected readonly editing = signal(false); + protected readonly message = signal(''); + protected readonly chosen = signal(undefined); + protected readonly checksFor = signal(undefined); + protected readonly lineageFor = signal(undefined); + protected readonly checks = resource({ + params: () => { + const key = this.checksFor(); + return key ? { ...key, domain: this.domainKey(), at: this.refreshed() } : undefined; + }, + loader: async ({ params: { at, ...params } }) => this.getChecks(params.domain, params), + }); + protected readonly checkActions = checkActions; + protected readonly lineage = resource({ + params: () => { + const key = this.lineageFor(); + return key ? { ...key, domain: this.domainKey() } : undefined; + }, + loader: async ({ params }) => (await this.api.invoke(lineage, params)) as Lineage, + }); + protected readonly candidates = signal([]); protected readonly report = resource({ - params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain }, + params: () => { + const key = this.chosen(); + return key ? { ...key, domain: this.domainKey() } : undefined; + }, loader: ({ params }) => this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }), }); + protected readonly ageFeatures = computed(() => { + const report = this.report.hasValue() ? this.report.value() : undefined; + return report?.kind === 'age_curves' ? Object.keys(report['curves']) : []; + }); + protected readonly selectedFeature = signal(''); + protected readonly feature = computed(() => { + const keys = this.ageFeatures(); + return keys.includes(this.selectedFeature()) + ? this.selectedFeature() + : keys.includes('value') + ? 'value' + : keys[0]; + }); + protected readonly band = resource({ + params: () => { + const key = this.chosen(); + const feature = this.feature(); + if (!key || !feature || !this.report.hasValue()) return undefined; + if (this.report.value()['curves'][feature].kind === 'count_rate') return undefined; + return { ...key, domain: this.domainKey(), feature }; + }, + loader: async ({ params }) => (await this.api.invoke(curve, params)) as Centile[], + }); + protected readonly overlay = signal(false); + protected readonly analysed = resource({ + params: () => + this.overlay() && this.domainKey() === 'tea' && this.feature() + ? this.refreshed() + 1 + : undefined, + loader: async () => { + const found = await this.api.invoke(studies); + return Promise.all( + found + .filter((entry) => entry.analysed) + .map(({ id }) => this.api.invoke(study, { eeg_id: id })), + ); + }, + }); protected readonly figures = computed(() => { - const found = this.report.value(); - return found ? interpretabilityFigures(found as Record) : []; + if (!this.report.hasValue()) return []; + const report = this.report.value(); + const feature = this.feature(); + const points = + this.analysed.hasValue() && feature + ? studyPoints(this.analysed.value(), report['model'], feature) + : []; + return interpretabilityFigures(report, { + feature, + centiles: this.band.hasValue() ? this.band.value() : undefined, + points, + waitForCentiles: report['kind'] === 'age_curves', + }); }); - /** TEA: its EEGs and their analysis. */ - protected readonly eegs = resource({ - params: () => (this.domain() === 'tea' ? this.refreshed() + 1 : undefined), - loader: () => this.api.invoke(studies), - }); - protected readonly eeg = signal(undefined); - protected readonly eegMetrics = resource({ - params: () => this.eeg(), - loader: ({ params }) => this.api.invoke(study, { eeg_id: params }), - }); - protected readonly metricNames: Record = { - posterior_rhythm: 'Ritmo posterior (Hz)', - spindles_n2: 'Husos de sueño N2 (por min)', - spindles_n3: 'Husos de sueño N3 (por min)', - paroxysmal_spikes: 'Picos paroxísticos (por min)', - anteroposterior_gradient: 'Gradiente anteroposterior', - }; - protected readonly asOf = signal(''); - protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined); - protected readonly message = signal(''); - protected champion(v: Version): boolean { - return v.aliases.includes('champion'); + constructor() { + effect(() => { + this.domain(); + this.training.set(''); + this.run.set(undefined); + this.running.set(false); + this.starting.set(false); + this.editing.set(false); + this.message.set(''); + this.chosen.set(undefined); + this.checksFor.set(undefined); + this.lineageFor.set(undefined); + this.overlay.set(false); + }); } - protected reportUrl(name: string, version: number, report: string): string { - return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`; + protected async reportDownload(name: string, version: number, report: string): Promise { + try { + const response = await this.api.invoke$Response(readReport$Any, { + domain: this.domainKey(), + name, + version, + report, + }); + const filename = /filename="([^"]+)"/.exec( + response.headers.get('Content-Disposition') ?? '', + )?.[1]; + download(response.body, filename ?? report); + } catch (error) { + this.message.set(errorText(error)); + } } protected async upload(name: string, version: number, event: Event): Promise { - const file = (event.target as HTMLInputElement).files?.[0]; + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; if (!file) return; - await this.api.invoke(addClinicalValidation, { - domain: this.domain() as Domain, - name, - version, - // OpenAPI's binary is typed as a string; the request builder sends the File as is. - body: { file: file as unknown as string }, - }); - this.message.set(`Validación clínica agregada a ${name} v${version}.`); - this.refreshed.update((n) => n + 1); - } - - protected async promote(name: string, version: number): Promise { + const domain = this.domainKey(); try { - await this.api.invoke(promote, { domain: this.domain() as Domain, name, version }); - this.message.set(`${name} v${version} es ahora la versión en producción.`); - this.refreshed.update((n) => n + 1); - } catch (e) { - const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined; - this.message.set(`No se promovió: ${detail ?? 'error'}`); + await this.api.invoke(addClinicalValidation, { + domain, + name, + version, + body: { file: file as unknown as string }, + }); + input.value = ''; + if (domain !== this.domainKey()) return; + this.message.set(`Validación clínica agregada a ${name} v${version}.`); + this.refresh(); + } catch (error) { + this.message.set(errorText(error)); } } - protected async analyzeEegs(): Promise { - const { run_id } = await this.api.invoke(analyze, { domain: this.domain() as Domain }); - await this.follow(run_id, 'Análisis de EEG'); + protected showVersion( + kind: 'checks' | 'lineage', + key: VersionKey, + dialog: HTMLDialogElement, + ): void { + (kind === 'checks' ? this.checksFor : this.lineageFor).set(key); + dialog.showModal(); } - private async follow(run_id: string, label: string): Promise { - for (;;) { - const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string; - this.run.set({ kind: label, status }); - if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break; - await new Promise((r) => setTimeout(r, 2000)); + protected async changeVersion(key: VersionKey, action: 'promote' | 'retire'): Promise { + const domain = this.domainKey(); + this.editing.set(true); + this.message.set(''); + try { + if (action === 'promote') await this.api.invoke(promote, { domain, ...key }); + else await this.api.invoke(retire, { domain, ...key }); + this.message.set( + `${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`, + ); + this.refresh(); + } catch (error) { + this.message.set(errorText(error)); + } finally { + this.editing.set(false); } - this.refreshed.update((n) => n + 1); } - protected async start(kind: 'train' | 'score'): Promise { - const domain = this.domain() as Domain; - const { run_id } = - kind === 'train' - ? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} }) - : await this.api.invoke(score, { domain }); - await this.follow(run_id, kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos'); + protected async prepareCandidates(dialog: HTMLDialogElement): Promise { + if (!this.models.hasValue()) return; + const domain = this.domainKey(); + this.editing.set(true); + this.message.set(''); + try { + const latest = this.models.value().flatMap(({ name, versions }) => { + const newest = versions.reduce<(typeof versions)[number] | undefined>( + (current, version) => (!current || version.version > current.version ? version : current), + undefined, + ); + return newest?.status === 'candidate' ? [{ name, version: newest.version }] : []; + }); + const allowed = await Promise.all( + latest.map(async (key) => (await this.getChecks(domain, key)).promotable), + ); + if (domain !== this.domainKey()) return; + const found = latest.filter((_, index) => allowed[index]); + this.candidates.set(found); + if (found.length) dialog.showModal(); + else this.message.set('No hay candidatas que se puedan promover.'); + } catch (error) { + this.message.set(errorText(error)); + } finally { + this.editing.set(false); + } + } + + protected async promoteCandidates(dialog: HTMLDialogElement): Promise { + this.editing.set(true); + this.message.set(''); + try { + await this.promoteVersions(this.domainKey(), this.candidates()); + dialog.close(); + } finally { + this.editing.set(false); + } + } + + protected forestHeight(rows: number): number { + return Math.max(360, rows * 24 + 72); + } + + protected chooseReport(key: VersionKey): void { + this.overlay.set(false); + this.selectedFeature.set(''); + this.chosen.set(key); + } + + protected follow(id: string, label: string, autoPromote = false): void { + this.message.set(''); + this.run.set({ id, label, autoPromote }); + this.running.set(true); + } + + protected async start(kind: 'score' | 'analyze'): Promise { + const domain = this.domainKey(); + 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.domainKey()) + this.follow(run_id, kind === 'score' ? 'Cálculo de riesgos' : 'Análisis de EEG'); + } catch (error) { + this.message.set(errorText(error)); + } finally { + this.starting.set(false); + } + } + + protected async finish(run: Run): Promise { + const domain = this.domainKey(); + const active = this.run(); + if (active?.id !== run.id) return; + try { + if (!active.autoPromote) return; + if (run.state !== 'succeeded') { + this.message.set('No se promovió: el entrenamiento no terminó correctamente.'); + return; + } + const newVersions = run.info.flatMap((line) => { + const match = /^train_models: tea\.(.+): version (\d+)$/.exec(line); + return match ? [{ name: match[1], version: Number(match[2]) }] : []; + }); + if (newVersions.length) await this.promoteVersions(domain, newVersions); + else this.message.set('No se promovió: el entrenamiento no registró versiones nuevas.'); + } finally { + if (domain === this.domainKey() && this.run()?.id === run.id) { + this.refresh(); + this.running.set(false); + } + } + } + + private async getChecks(domain: Domain, key: VersionKey): Promise { + return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks; + } + + private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise { + const messages = await Promise.all( + keys.map(async (key) => { + const label = `${key.name} v${key.version}`; + try { + const checks = await this.getChecks(domain, key); + if (!checks.promotable) { + const missing = checks.checks + .filter((check) => !check.present) + .map((check) => REPORTS[check.report] ?? check.report); + const reason = missing.length ? `faltan ${missing.join(', ')}` : checks.status; + return `No se promovió ${label}: ${reason}.`; + } + await this.api.invoke(promote, { domain, ...key }); + return `${label}: en producción.`; + } catch (error) { + return `No se promovió ${label}: ${errorText(error)}`; + } + }), + ); + if (domain !== this.domainKey()) return; + this.message.set(messages.join('\n')); + this.refresh(); } } diff --git a/src/app/gobernanza/run-monitor.spec.ts b/src/app/gobernanza/run-monitor.spec.ts new file mode 100644 index 0000000..d21b33c --- /dev/null +++ b/src/app/gobernanza/run-monitor.spec.ts @@ -0,0 +1,101 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { Api } from '../api/api'; +import { cancelRun } from '../api/fn/runs/cancel-run'; +import { runStatus } from '../api/fn/runs/run-status'; +import type { Progress } from '../api/models/progress'; +import type { Run } from '../api/models/run'; +import { eta, RunMonitor } from './run-monitor'; + +const progress: Progress = { + done: 4, + total: 10, + mode: 'local', + phase: 'training', + elapsed_s: 20, + eta_s: null, + scheduler: null, + updated_at: '2026-11-30T12:00:00Z', +}; + +function run(state: Run['state']): Run { + return { + id: 'run-1', + domain: 'tea', + job: 'train', + status: state, + state, + info: [], + warnings: [], + steps: [], + error: null, + progress, + started: null, + ended: null, + }; +} + +async function render(fixture: ComponentFixture): Promise { + fixture.detectChanges(); + await Promise.resolve(); + fixture.detectChanges(); +} + +describe('run monitor', () => { + afterEach(() => { + TestBed.resetTestingModule(); + vi.useRealTimers(); + }); + + for (const state of ['succeeded', 'failed', 'cancelled'] as const) { + it('stops polling after ' + state, async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + const invoke = vi + .fn() + .mockResolvedValueOnce(run('running')) + .mockResolvedValueOnce(run(state)); + TestBed.configureTestingModule({ providers: [{ provide: Api, useValue: { invoke } }] }); + const fixture = TestBed.createComponent(RunMonitor); + fixture.componentRef.setInput('runId', 'run-1'); + const finished = vi.fn(); + fixture.componentInstance.finished.subscribe(finished); + + await render(fixture); + expect(invoke).toHaveBeenCalledExactlyOnceWith(runStatus, { run_id: 'run-1' }); + await vi.advanceTimersByTimeAsync(1999); + expect(invoke).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + expect(finished).toHaveBeenCalledExactlyOnceWith(run(state)); + await vi.advanceTimersByTimeAsync(6000); + expect(invoke).toHaveBeenCalledTimes(2); + }); + } + + it('estimates seconds remaining from observed throughput', () => { + expect(eta(progress)).toBe(30); + expect(eta({ ...progress, done: 0 })).toBeNull(); + expect(eta({ ...progress, done: 10 })).toBe(0); + }); + + it('requests cancellation and displays the conflict detail', async () => { + const invoke = vi.fn(async (endpoint: unknown) => { + if (endpoint === cancelRun) { + throw new HttpErrorResponse({ + status: 409, + error: { detail: 'the run is still starting; try again' }, + }); + } + return run('running'); + }); + TestBed.configureTestingModule({ providers: [{ provide: Api, useValue: { invoke } }] }); + const fixture = TestBed.createComponent(RunMonitor); + fixture.componentRef.setInput('runId', 'run-1'); + await render(fixture); + + const cancel: HTMLButtonElement = fixture.nativeElement.querySelector('button'); + cancel.click(); + await render(fixture); + expect(invoke).toHaveBeenCalledWith(cancelRun, { run_id: 'run-1' }); + expect(fixture.nativeElement.textContent).toContain('the run is still starting; try again'); + }); +}); diff --git a/src/app/gobernanza/run-monitor.ts b/src/app/gobernanza/run-monitor.ts new file mode 100644 index 0000000..404c79c --- /dev/null +++ b/src/app/gobernanza/run-monitor.ts @@ -0,0 +1,164 @@ +import { DecimalPipe, KeyValuePipe } from '@angular/common'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, effect, inject, input, output, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { Api } from '../api/api'; +import { cancelRun } from '../api/fn/runs/cancel-run'; +import { runStatus } from '../api/fn/runs/run-status'; +import type { Progress } from '../api/models/progress'; +import type { Run } from '../api/models/run'; + +export function errorText(error: unknown): string { + if (error instanceof HttpErrorResponse) { + const detail = error.error?.detail ?? error.error; + return typeof detail === 'string' ? detail : detail ? JSON.stringify(detail) : error.message; + } + return error instanceof Error ? error.message : String(error); +} + +export function eta(progress: Progress): number | null { + return progress.done > 0 && progress.total > 0 + ? (Math.max(0, progress.total - progress.done) * progress.elapsed_s) / progress.done + : null; +} + +@Component({ + selector: 'app-run-monitor', + imports: [DecimalPipe, KeyValuePipe, MatButtonModule], + template: ` +
+ @if (run(); as r) { +

{{ r.status }}

+ @for (step of r.steps; track step.key) { +
{{ step.key }} · {{ step.status }}
+ } + @if (r.progress; as p) { +
+ {{ p.phase }} · {{ p.done }} / {{ p.total }} + @if (p.total > 0) { + ({{ (100 * p.done) / p.total | number: '1.0-0' }} %) + + } + @if (eta(p) !== null) { + · ETA {{ eta(p) | number: '1.0-0' }} s + } +
+ @for (worker of p.workers ?? []; track worker.name) { +
+ {{ worker.name }} · CPU {{ worker.cpu_pct | number: '1.0-1' }} % · RAM + {{ worker.memory_bytes / 1048576 | number: '1.0-1' }} MiB + @if (worker.memory_limit != null) { + / {{ worker.memory_limit / 1048576 | number: '1.0-1' }} MiB + } + · Tareas activas: {{ worker.executing }} +
+ } + @for (task of p.tasks | keyvalue; track task.key) { +
{{ task.key }}: {{ task.value }}
+ } + } + @if (r.info.length) { +

Información

+
    + @for (line of r.info; track $index) { +
  • {{ line }}
  • + } +
+ } + @if (r.warnings.length) { +

Advertencias

+
    + @for (line of r.warnings; track $index) { +
  • {{ line }}
  • + } +
+ } + @if (r.error) { +

{{ r.error }}

+ } + @if (!terminal.has(r.state)) { + + } + } @else { +

Consultando ejecución…

+ } + @if (pollError()) { +

{{ pollError() }}

+ } + @if (cancelError()) { +

{{ cancelError() }}

+ } +
+ `, +}) +export class RunMonitor { + private readonly api = inject(Api); + readonly runId = input.required(); + readonly finished = output(); + protected readonly run = signal(undefined); + protected readonly pollError = signal(''); + protected readonly cancelError = signal(''); + protected readonly cancelling = signal(false); + protected readonly terminal = new Set(['succeeded', 'failed', 'cancelled']); + protected readonly eta = eta; + + constructor() { + effect((cleanup) => { + const run_id = this.runId(); + this.run.set(undefined); + this.pollError.set(''); + this.cancelError.set(''); + this.cancelling.set(false); + let active = true; + let timer: ReturnType; + const poll = async () => { + try { + const run = await this.api.invoke(runStatus, { run_id }); + if (!active) return; + this.run.set(run); + this.pollError.set(''); + if (this.terminal.has(run.state)) { + this.finished.emit(run); + return; + } + } catch (error) { + if (!active) return; + this.pollError.set(errorText(error)); + } + timer = setTimeout(poll, 2000); + }; + void poll(); + cleanup(() => { + active = false; + clearTimeout(timer); + }); + }); + } + + protected async cancel(): Promise { + const run_id = this.runId(); + this.cancelling.set(true); + this.cancelError.set(''); + try { + const { state, status } = await this.api.invoke(cancelRun, { run_id }); + if (this.runId() === run_id) { + this.run.update((run) => + run && !this.terminal.has(run.state) && !this.terminal.has(state) + ? { ...run, state, status } + : run, + ); + } + } catch (error) { + if (this.runId() === run_id) this.cancelError.set(errorText(error)); + } finally { + if (this.runId() === run_id) this.cancelling.set(false); + } + } +} diff --git a/src/app/gobernanza/tea/preview.ts b/src/app/gobernanza/tea/preview.ts new file mode 100644 index 0000000..8d437a8 --- /dev/null +++ b/src/app/gobernanza/tea/preview.ts @@ -0,0 +1,177 @@ +import { KeyValuePipe } from '@angular/common'; +import { Component, inject, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { Api } from '../../api/api'; +import { previewStatus } from '../../api/fn/preview/preview-status'; +import { startPreview } from '../../api/fn/preview/start-preview'; +import type { PreviewResult } from '../../api/models/preview-result'; +import type { Run } from '../../api/models/run'; +import { RunMonitor, errorText } from '../run-monitor'; + +@Component({ + selector: 'app-eeg-preview', + imports: [FormsModule, KeyValuePipe, MatButtonModule, RunMonitor], + template: ` +
+

Vista previa

+
+ + + + +
+ @if (error()) { +

{{ error() }}

+ } + @if (runId(); as id) { + + } + + @if (result(); as r) { +

Resultado de la vista previa

+

+ {{ r.eeg.level }} · + {{ r.eeg.valid === true ? 'Válido' : r.eeg.valid === false ? 'No válido' : '—' }} +

+ @if (r.eeg.error) { +

{{ r.eeg.error }}

+ } +

Comprobaciones

+ + + + + + + + + + + + @for (check of r.eeg.checks; track $index) { + + + + + + + + } + +
ComprobaciónElectrodoResultadoRangoAnormal
{{ check['code'] }}{{ check['electrode'] ?? '—' }}{{ check['value'] ?? check['text'] ?? '—' }} {{ check['unit'] }}{{ check['low'] ?? '—' }} / {{ check['high'] ?? '—' }} + {{ + check['abnormal'] === true ? 'Sí' : check['abnormal'] === false ? 'No' : '—' + }} +
+

Métricas

+ + + + + + + + + + + + @for (metric of r.eeg.metrics; track metric.code) { + + + + + + + + @for (site of metric.electrodes | keyvalue; track site.key) { + + + + + + + + } + @for (site of metric.zones | keyvalue; track site.key) { + + + + + + + + } + } + +
MétricaValorzp5 / mediana / p95Fuera de rango
{{ metric.code }}{{ metric.value ?? '—' }}{{ metric.score?.z ?? '—' }} + {{ metric.score?.p5 ?? '—' }} / {{ metric.score?.median ?? '—' }} / + {{ metric.score?.p95 ?? '—' }} + {{ metric.score?.outside ?? '—' }}
{{ site.key }}{{ site.value.value ?? '—' }}{{ site.value.score?.z ?? '—' }} + {{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} / + {{ site.value.score?.p95 ?? '—' }} + {{ site.value.score?.outside ?? '—' }}
{{ site.key }}{{ site.value.value ?? '—' }}{{ site.value.score?.z ?? '—' }} + {{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} / + {{ site.value.score?.p95 ?? '—' }} + {{ site.value.score?.outside ?? '—' }}
+ @if (r.ados2; as ados2) { +

ADOS-2

+

{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}

+
+ @for (item of ados2.items | keyvalue; track item.key) { +
{{ item.key }}
+
{{ item.value ?? '—' }}
+ } +
+ } + @if (r.warnings.length) { +

Advertencias

+
    + @for (warning of r.warnings; track $index) { +
  • {{ warning }}
  • + } +
+ } + } +
+
+
+ `, +}) +export class EegPreview { + private readonly api = inject(Api); + protected readonly busy = signal(false); + protected readonly error = signal(''); + protected readonly runId = signal(''); + protected readonly result = signal(null); + + protected async start(edf?: File, ados2?: File, birth_date?: string): Promise { + if (!edf) return; + this.busy.set(true); + this.error.set(''); + this.result.set(null); + try { + const { run_id } = await this.api.invoke(startPreview, { + body: { edf, ados2, birth_date: birth_date || undefined }, + }); + this.runId.set(run_id); + } catch (error) { + this.error.set(errorText(error)); + this.busy.set(false); + } + } + + protected async finish(run: Run, dialog: HTMLDialogElement): Promise { + try { + if (run.state !== 'succeeded') return; + const { result } = await this.api.invoke(previewStatus, { run_id: run.id }); + this.result.set(result); + if (result) dialog.showModal(); + else this.error.set('La vista previa no devolvió un resultado.'); + } catch (error) { + this.error.set(errorText(error)); + } finally { + this.busy.set(false); + } + } +} diff --git a/src/app/gobernanza/tea/studies.html b/src/app/gobernanza/tea/studies.html new file mode 100644 index 0000000..ce0881f --- /dev/null +++ b/src/app/gobernanza/tea/studies.html @@ -0,0 +1,129 @@ +
+

Estudios EEG

+
+ + @if (mode() === 'first_n') { + + } + @if (mode() === 'ids') { + + } + +
+
+ + +
+ @if (error()) { +

{{ error() }}

+ } + @if (runId(); as id) { + + } + +

Resumen

+ @if (summary.hasValue()) { +
+ @for (count of summary.value() | keyvalue; track count.key) { +
{{ labels[count.key] ?? count.key }}
+
{{ count.value }}
+ } +
+ } @else if (summary.error(); as error) { +

{{ errorText(error) }}

+ } + @if (history.hasValue()) { + @if (history.value().last; as last) { +

+ Última ejecución TEA: {{ last.status }} + @if (last.ended != null) { + · {{ last.ended * 1000 | date: 'short' }} + } +

+ } +

+ {{ + history.value().current + ? 'Indicadores al día' + : 'Indicadores pendientes: corre el análisis TEA' + }} +

+ } @else if (history.error(); as error) { +

{{ errorText(error) }}

+ } + @if (eegs.error(); as error) { +

{{ errorText(error) }}

+ } + @if (eegMetrics.error(); as error) { +

{{ errorText(error) }}

+ } +
+ + + + + + + + + + @for (e of eegs.hasValue() ? eegs.value() : []; track e.id) { + + + + + + } @empty { + + + + } + +
FechaRegistroAnálisis
+ + {{ e.lab_record_id ?? '—' }} + {{ !e.analysed ? 'Sin analizar' : e.valid ? 'Válido' : 'No válido' }} + {{ e.level ? '(' + e.level + ')' : '' }} +
Sin EEG cargados.
+ @if (eegMetrics.hasValue() && eegMetrics.value(); as m) { +

EEG {{ m.id }} · {{ m.age_months ?? '—' }} meses

+ + + + + + + + + + + @for (x of m.metrics; track x.code) { + + + + + + + } @empty { + + + + } + +
MétricaValorzCurva
{{ metricNames[x.code] ?? x.code }}{{ x.value | number: '1.2-2' }}{{ x.z === null ? '—' : (x.z | number: '1.2-2') }}{{ x.model ?? 'sin curva en producción' }}
Sin métricas (EEG no válido).
+ } +
+
diff --git a/src/app/gobernanza/tea/studies.ts b/src/app/gobernanza/tea/studies.ts new file mode 100644 index 0000000..8555777 --- /dev/null +++ b/src/app/gobernanza/tea/studies.ts @@ -0,0 +1,160 @@ +import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, inject, input, output, resource, signal } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { Api } from '../../api/api'; +import { analyzeEegs } from '../../api/fn/eeg/analyze-eegs'; +import { eegStudiesSummary } from '../../api/fn/eeg/eeg-studies-summary'; +import { studies } from '../../api/fn/eeg/studies'; +import { study } from '../../api/fn/eeg/study'; +import { pipeline } from '../../api/fn/ingest/pipeline'; +import { startRun } from '../../api/fn/ingest/start-run'; +import { upload } from '../../api/fn/ingest/upload'; +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', + imports: [ + DatePipe, + DecimalPipe, + KeyValuePipe, + FormsModule, + MatButtonModule, + RunMonitor, + EegPreview, + ], + templateUrl: './studies.html', +}) +export class EegStudies { + private readonly api = inject(Api); + readonly execution = input(); + readonly refresh = input(0); + readonly changed = output(); + protected readonly eegs = resource({ + params: () => this.refresh(), + loader: () => this.api.invoke(studies), + }); + protected readonly eeg = signal(undefined); + protected readonly eegMetrics = resource({ + params: () => { + const eeg_id = this.eeg(); + return eeg_id ? { eeg_id, refresh: this.refresh() } : undefined; + }, + loader: ({ params: { eeg_id } }) => this.api.invoke(study, { eeg_id }), + }); + protected readonly summary = resource({ + params: () => this.refresh(), + loader: () => this.api.invoke(eegStudiesSummary), + }); + protected readonly history = resource({ + params: () => this.refresh(), + loader: async () => { + const [last] = await this.api.invoke(runHistory, { job: 'tea_eeg', domain: 'tea', limit: 1 }); + if (last?.state !== 'succeeded' || last.ended == null) return { last, current: false }; + const ended = last.ended; + const limit = 200; + let before: string | undefined; + for (;;) { + const runs = await this.api.invoke(runHistory, { + job: 'analyze', + domain: 'tea', + limit, + before, + }); + if (runs.some((run) => run.ended != null && run.ended > ended)) + return { last, current: false }; + if (runs.length < limit) return { last, current: true }; + before = runs[runs.length - 1].id; + } + }, + }); + protected readonly labels: Record = { + eegs: 'Estudios', + analysed: 'Analizados', + valid: 'Válidos', + not_valid: 'No válidos', + failed: 'Fallidos', + metrics: 'Métricas', + metrics_with_z: 'Métricas con z', + high: 'Altas', + low: 'Bajas', + }; + protected readonly metricNames: Record = { + posterior_rhythm: 'Ritmo posterior (Hz)', + spindles_n2: 'Husos de sueño N2 (por min)', + spindles_n3: 'Husos de sueño N3 (por min)', + paroxysmal_spikes: 'Picos paroxísticos (por min)', + anteroposterior_gradient: 'Gradiente anteroposterior', + }; + protected readonly mode = signal>('pending'); + protected readonly count = signal(null); + protected readonly ids = signal(''); + protected readonly busy = signal(false); + protected readonly error = signal(''); + protected readonly runId = signal(''); + protected readonly errorText = errorText; + + protected async analyze(): Promise { + const execution = this.execution(); + if (!execution) return; + const mode = this.mode(); + const scope: Scope = { mode }; + if (mode === 'first_n') { + const count = this.count(); + if (count == null || !Number.isInteger(count) || count < 1) return; + scope.n = count; + } + if (mode === 'ids') { + scope.ids = this.ids().split(/\s+/).filter(Boolean); + if (!scope.ids.length) return; + } + await this.start(() => this.api.invoke(analyzeEegs, { body: { scope, execution } })); + } + + protected async upload(input: HTMLInputElement): Promise { + const files = Array.from(input.files ?? []); + if (!files.length) return; + if (files.some((file) => !file.name.toLowerCase().endsWith('.edf'))) { + this.error.set('Selecciona archivos EDF.'); + return; + } + await this.start(async () => { + try { + await this.api.invoke(pipeline, { pipeline_id: 'tea' }); + for (const file of files) { + await this.api.invoke(upload, { body: { file: file as unknown as string } }); + } + const run = await this.api.invoke(startRun, { pipeline_id: 'tea', body: {} }); + input.value = ''; + return run; + } catch (error) { + if (error instanceof HttpErrorResponse && error.status === 404) { + throw new Error('No hay un pipeline TEA configurado'); + } + throw error; + } + }); + } + + protected finish(): void { + this.busy.set(false); + this.changed.emit(); + } + + private async start(submit: () => Promise<{ [key: string]: string }>): Promise { + this.busy.set(true); + this.error.set(''); + try { + const { run_id } = await submit(); + this.runId.set(run_id); + } catch (error) { + this.error.set(errorText(error)); + this.busy.set(false); + } + } +} diff --git a/src/app/gobernanza/training.spec.ts b/src/app/gobernanza/training.spec.ts new file mode 100644 index 0000000..9a316e1 --- /dev/null +++ b/src/app/gobernanza/training.spec.ts @@ -0,0 +1,40 @@ +import { trainingForm } from './training'; + +describe('training form', () => { + it('removes execution and resolves the TEA reference fields with their defaults', () => { + const { schema, model } = trainingForm({ + name: 'all', + domain: 'tea', + defaults: { execution: { mode: 'local', scheduler: null }, reference: { line_hz: 50 } }, + json_schema: { + type: 'object', + properties: { + execution: { type: 'object' }, + as_of: { anyOf: [{ type: 'string', format: 'date' }, { type: 'null' }] }, + reference: { anyOf: [{ $ref: '#/$defs/Reference' }, { type: 'null' }] }, + }, + $defs: { + Reference: { + type: 'object', + required: ['name'], + properties: { + name: { type: 'string' }, + line_hz: { type: 'integer', enum: [50, 60], default: 50 }, + }, + }, + }, + }, + }); + + expect(schema.properties).not.toHaveProperty('execution'); + expect(schema.properties?.['as_of']).toMatchObject({ + type: ['string', 'null'], + format: 'date', + }); + expect(schema.properties?.['reference']).toMatchObject({ + type: ['object', 'null'], + properties: { name: { type: 'string' }, line_hz: { enum: [50, 60] } }, + }); + expect(model).toEqual({ reference: { line_hz: 50 } }); + }); +}); diff --git a/src/app/gobernanza/training.ts b/src/app/gobernanza/training.ts new file mode 100644 index 0000000..dc71c1b --- /dev/null +++ b/src/app/gobernanza/training.ts @@ -0,0 +1,243 @@ +import { HttpErrorResponse } from '@angular/common/http'; +import { Component, inject, input, model, output, resource, signal } from '@angular/core'; +import { FormsModule, ReactiveFormsModule, UntypedFormGroup } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { FormlyForm, provideFormlyCore } from '@ngx-formly/core'; +import { FormlyJsonschema } from '@ngx-formly/core/json-schema'; +import { withFormlyMaterial } from '@ngx-formly/material'; +import type { JSONSchema7, JSONSchema7TypeName } from 'json-schema'; +import { Api } from '../api/api'; +import { train } from '../api/fn/models/train'; +import { trainingConfig } from '../api/fn/models/training-config'; +import { trainingInputs } from '../api/fn/models/training-inputs'; +import { uploadTrainingInputs } from '../api/fn/models/upload-training-inputs'; +import type { Domain } from '../api/models/domain'; +import type { Execution } from '../api/models/execution'; +import type { TrainingConfig } from '../api/models/training-config'; +import { FORMLY_TYPES } from '../conectar/schema-form'; +import { errorText } from './run-monitor'; + +type Schema = JSONSchema7 & { $defs?: Record }; + +interface InputSets { + allowed: string[]; + description: string; + sets: { name: string; edf_files: number; has_ages: boolean }[]; +} + +export function trainingForm(config: TrainingConfig) { + const raw = structuredClone(config.json_schema) as Schema; + const model = structuredClone(config.defaults); + delete model['execution']; + delete raw.properties?.['execution']; + raw.required = raw.required?.filter((key) => key !== 'execution'); + const normalize = (schema: Schema): Schema => { + if (schema.$ref) return normalize(raw.$defs![schema.$ref.split('/').pop()!]); + if (schema.anyOf) { + const { anyOf, ...rest } = schema; + const selected = normalize( + anyOf.find((entry) => typeof entry === 'object' && entry.type !== 'null') as Schema, + ); + return { ...selected, ...rest, type: [selected.type as JSONSchema7TypeName, 'null'] }; + } + if (schema.properties) { + return { + ...schema, + properties: Object.fromEntries( + Object.entries(schema.properties).map(([key, value]) => [ + key, + normalize(value as Schema), + ]), + ), + }; + } + return schema; + }; + const schema = normalize(raw); + const reference = schema.properties?.['reference'] as Schema | undefined; + if (reference) reference.required = reference.required?.filter((key) => key !== 'name'); + return { schema, model }; +} + +function allowedFile(file: File, allowed: string[]): boolean { + return allowed.some((pattern) => { + if (pattern === '*.edf') return file.name.toLowerCase().endsWith('.edf'); + return file.name === pattern; + }); +} + +@Component({ + selector: 'app-governance-training', + imports: [FormsModule, ReactiveFormsModule, FormlyForm, MatButtonModule], + providers: [provideFormlyCore([...withFormlyMaterial(), FORMLY_TYPES])], + template: ` +
+

{{ name() === 'all' ? 'Entrenar modelos' : 'Reentrenar ' + name() }}

+ @if (config.hasValue()) { + @let form = config.value(); +
+ + @if (domain() === 'tea') { + + } + + + } @else if (config.error(); as error) { +

{{ errorText(error) }}

+ } + @if (inputs.hasValue() && inputs.value(); as sets) { +

Archivos de entrenamiento

+

{{ sets.description }}

+
    + @for (set of sets.sets; track set.name) { +
  • + {{ set.name }} · {{ set.edf_files }} EDF · + {{ set.has_ages ? 'Con edades' : 'Sin edades' }} +
  • + } +
+
+ + + @for (set of sets.sets; track set.name) { + + } + + + +
+ } @else if (inputs.error(); as error) { +

{{ errorText(error) }}

+ } + @if (message()) { +

{{ message() }}

+ } +
+ `, +}) +export class Training { + private readonly api = inject(Api); + private readonly jsonschema = inject(FormlyJsonschema); + readonly domain = input.required(); + readonly name = input.required(); + readonly execution = input(); + readonly disabled = input(false); + readonly started = output<{ id: string; autoPromote: boolean }>(); + protected readonly config = resource({ + params: () => ({ domain: this.domain(), name: this.name() }), + loader: async ({ params }) => { + const { schema, model } = trainingForm(await this.api.invoke(trainingConfig, params)); + const fields = [ + this.jsonschema.toFieldConfig(schema, { + map: (field, source) => { + if (source.format === 'date') { + field.props = { ...field.props, type: 'date' }; + } + if (field.key === 'line_hz') { + field.type = 'select'; + field.props = { + ...field.props, + options: [ + { value: 50, label: '50 Hz' }, + { value: 60, label: '60 Hz' }, + ], + }; + } + return field; + }, + }), + ]; + return { fields, model, form: new UntypedFormGroup({}) }; + }, + }); + protected readonly inputs = resource({ + params: () => ({ domain: this.domain(), name: this.name() }), + loader: async ({ params }) => { + try { + return (await this.api.invoke(trainingInputs, params)) as InputSets; + } catch (error) { + if (error instanceof HttpErrorResponse && error.status === 404) return undefined; + throw error; + } + }, + }); + readonly busy = model(false); + protected readonly uploading = signal(false); + protected readonly message = signal(''); + protected readonly autoPromote = signal(false); + protected readonly errorText = errorText; + + protected async start(model: TrainingConfig['defaults']): Promise { + if (this.busy() || this.disabled()) return; + this.busy.set(true); + this.message.set(''); + const domain = this.domain(); + const name = this.name(); + const autoPromote = domain === 'tea' && this.autoPromote(); + const reference = model['reference']; + try { + const { run_id } = await this.api.invoke(train, { + domain, + body: { + as_of: model['as_of'] || undefined, + reference: reference?.name ? reference : undefined, + execution: this.execution(), + ...(name === 'all' ? {} : { models: [name] }), + }, + }); + this.started.emit({ id: run_id, autoPromote }); + } catch (error) { + this.message.set(errorText(error)); + } finally { + this.busy.set(false); + } + } + + protected accept(allowed: string[]): string { + return allowed + .map((pattern) => + pattern.startsWith('*.') ? pattern.slice(1) : '.' + pattern.split('.').pop(), + ) + .join(','); + } + + protected async upload(set: string, input: HTMLInputElement): Promise { + const files = Array.from(input.files ?? []); + const allowed = this.inputs.hasValue() ? (this.inputs.value()?.allowed ?? []) : []; + if (!files.length || files.some((file) => !allowedFile(file, allowed))) { + this.message.set('Archivos permitidos: ' + allowed.join(', ')); + return; + } + this.uploading.set(true); + this.message.set(''); + try { + await this.api.invoke(uploadTrainingInputs, { + domain: this.domain(), + name: this.name(), + set: set.trim(), + body: { files }, + }); + input.value = ''; + this.inputs.reload(); + } catch (error) { + this.message.set(errorText(error)); + } finally { + this.uploading.set(false); + } + } +}