Merge P5.4-gobernanza into P5-combined

This commit is contained in:
2026-11-30 14:20:07 -06:00
17 changed files with 2202 additions and 265 deletions
+28
View File
@@ -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);
});
});
+127
View File
@@ -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<T>(
file: Blob,
expected: string,
upload: (sha256: string) => Promise<T>,
): Promise<T> {
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: `
<section class="card">
<h3>Bundles</h3>
<form (ngSubmit)="export()">
<label
>Versiones
<select name="versions" [(ngModel)]="selection">
<option value="champion">En producción</option>
<option value="latest">Últimas</option>
<option value="all">Todas</option>
</select>
</label>
<button mat-stroked-button type="submit" [disabled]="exporting()">Exportar bundle</button>
</form>
@if (exportedHash()) {
<p>
SHA-256 <code>{{ exportedHash() }}</code>
</p>
}
<form (ngSubmit)="import(file)">
<label>Archivo ZIP <input #file type="file" accept=".zip" required /></label>
<label>SHA-256 esperado <input name="hash" [(ngModel)]="hash" required /></label>
<button mat-stroked-button type="submit" [disabled]="importing() || disabled()">
Importar bundle
</button>
</form>
@if (message()) {
<p role="alert">{{ message() }}</p>
}
</section>
`,
})
export class Bundles {
private readonly api = inject(Api);
readonly domain = input.required<Domain>();
readonly disabled = input(false);
readonly started = output<string>();
protected readonly selection = signal<NonNullable<ExportModels$Params['versions']>>('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<void> {
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<void> {
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);
}
}
}
+71
View File
@@ -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();
}
});
});
+117
View File
@@ -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: `
<section class="card">
<h2>Ejecución</h2>
@if (options.hasValue()) {
<label
>Modo
<select #mode [value]="choice().mode ?? ''" (change)="select($any(mode.value))">
<option value="sync">Sync</option>
<option value="local">Local</option>
<option value="remote">Remoto</option>
</select>
</label>
@if (choice().mode === 'remote') {
<label
>Scheduler
<input
#scheduler
list="execution-schedulers"
[value]="choice().scheduler ?? ''"
(change)="address.set(scheduler.value)"
/>
</label>
<datalist id="execution-schedulers">
@for (host of options.value().schedulers; track host) {
<option [value]="host"></option>
}
</datalist>
}
}
@if (health.hasValue()) {
@let h = health.value();
<p role="status">
{{ 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 }}
}
</p>
@if (h.dashboard_url && h.dashboard_ok !== false) {
<a [href]="h.dashboard_url" target="_blank" rel="noopener">Panel de Dask</a>
}
} @else if (health.error() || options.error()) {
<p role="alert">No se pudo consultar la ejecución.</p>
}
</section>
`,
})
export class Execution {
private readonly api = inject(Api);
private readonly document = inject(DOCUMENT);
private readonly visible = signal(!this.document.hidden);
readonly execution = model<Choice | undefined>(undefined);
protected readonly options = resource({ loader: () => this.api.invoke(executionOptions) });
protected readonly mode = signal<Choice['mode']>(undefined);
protected readonly address = signal<string | undefined>(undefined);
protected readonly choice = computed<Choice>(() => {
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<Choice['mode']>): void {
this.mode.set(mode);
if (mode === 'remote' && this.address() === undefined && this.options.hasValue()) {
this.address.set(this.options.value().schedulers[0] ?? '');
}
}
}
+82 -4
View File
@@ -1,4 +1,4 @@
import { interpretabilityFigures } from './figures'; import { interpretabilityFigures, studyPoints } from './figures';
describe('governance figures', () => { describe('governance figures', () => {
it('draws a survival report as curves with bands and the model points', () => { 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] }, 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); 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.length).toBe(2);
expect(found[1].title).toContain('fallecidos = 308'); 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]); 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', () => { it('draws an age curve with its centile band', () => {
@@ -71,6 +71,84 @@ describe('governance figures', () => {
expect(found.figure.data.length).toBe(2); 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', () => { it('draws nothing for a report it does not know', () => {
expect(interpretabilityFigures({ kind: 'other' })).toEqual([]); expect(interpretabilityFigures({ kind: 'other' })).toEqual([]);
}); });
+128 -18
View File
@@ -1,10 +1,10 @@
import type { Analysis } from '../api/models/analysis';
import type { Figure } from '../plot'; import type { Figure } from '../plot';
import { PALETTE } from '../plot'; import { PALETTE } from '../plot';
/** A curve with its band, as the reports give them. */
interface Band { interface Band {
x: number[]; x: number[];
y: number[]; y: (number | null)[];
low?: (number | null)[]; low?: (number | null)[];
high?: (number | null)[]; high?: (number | null)[];
} }
@@ -34,10 +34,64 @@ function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Pl
return lines; return lines;
} }
/** What a model's interpretability report draws, by its kind: survival curves, the mixture's export interface Centile {
* observed and predicted risk per subgroup, or the logistic regression's calibration. */ age_months: number;
p5: number | null;
median: number | null;
p95: number | null;
}
interface StudyPoint {
age: number;
value: number;
}
interface AgeCurveOptions {
feature?: string;
centiles?: Centile[];
points?: StudyPoint[];
waitForCentiles?: boolean;
}
const EEG_METRICS: Record<string, string> = {
'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( export function interpretabilityFigures(
report: Record<string, any>, report: Record<string, any>,
ageCurve: AgeCurveOptions = {},
): { title: string; figure: Figure }[] { ): { title: string; figure: Figure }[] {
switch (report['kind']) { switch (report['kind']) {
case 'curves': { case 'curves': {
@@ -70,7 +124,6 @@ export function interpretabilityFigures(
}, },
}, },
}, },
// Its clinical scenarios, those with enough deaths to draw.
...((report['escenarios'] ?? []) as any[]).map((e) => ...((report['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure( scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`, `${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', 'Supervivencia libre de recaída',
), ),
); );
case 'age_curves': { case 'forest':
// The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
if (!value) return [];
const label = report['curves']['value'] ? '' : ` · ${Object.keys(report['curves'])[0]}`;
if (value.kind === 'count_rate') {
return [ return [
{ {
title: `Tasa de referencia: ${value.rate.toFixed(3)} por minuto (${value.reference} estudios)`, 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}<br>OR: %{x}<br>q: ' + (row.q ?? '—') + '<extra></extra>',
};
}),
layout: {
xaxis: { type: 'log', title: { text: 'OR (IC 95 %)' } },
yaxis: { type: 'category', automargin: true },
},
},
},
];
case 'age_curves': {
const curves = report['curves'];
const feature = ageCurve.feature ?? (curves.value ? 'value' : Object.keys(curves)[0]);
const value = curves[feature];
if (!value) return [];
const label = feature === 'value' ? '' : ` · ${feature}`;
const overlay: Partial<Plotly.Data>[] = 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: ${rate?.toFixed(3) ?? '—'} por minuto (${value.reference} estudios)${label}`,
figure: { figure: {
data: [ data: [
{ {
x: value.ages, x: value.ages,
y: [value.rate, value.rate], y: [rate, rate],
name: 'Tasa', name: 'Tasa',
type: 'scatter', type: 'scatter',
mode: 'lines', mode: 'lines',
}, },
...overlay,
], ],
layout: { layout: {
xaxis: { title: { text: 'Edad (meses)' } }, 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 [ return [
{ {
title: `Curva de referencia por edad (p5, mediana, p95)${label}`, title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
figure: { figure: {
data: [ data: [
...banded( ...banded(
'p5–p95', 'Mediana',
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 }, { x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
PALETTE[4], PALETTE[4],
), ),
].map((d, i) => (i === 1 ? { ...d, name: 'Mediana' } : d)), ...overlay,
],
layout: { layout: {
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' }, xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
yaxis: { title: { text: 'Valor' } }, 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( function scenarioFigure(
title: string, title: string,
e: any, e: any,
+227 -101
View File
@@ -1,43 +1,81 @@
<section class="page"> <section class="page">
<h1>Gobernanza de modelos</h1> <h1>Gobernanza de modelos</h1>
<nav class="domains" aria-label="Dominios"> <nav class="domains" aria-label="Dominios">
@for (d of domains.value() ?? []; track d) { @for (d of domains.hasValue() ? domains.value() : []; track d) {
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a> <a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
} }
</nav> </nav>
<form class="card actions" (submit)="$event.preventDefault()"> <app-execution [(execution)]="execution" />
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Datos hasta</mat-label> <section>
<input <h2>Modelos</h2>
matInput <div class="card actions">
type="date" <button mat-flat-button type="button" (click)="training.set('all')">Entrenar modelos</button>
[ngModel]="asOf()" <button
(ngModelChange)="asOf.set($event)" mat-stroked-button
name="asOf" type="button"
/> [disabled]="starting() || running()"
</mat-form-field> (click)="start('score')"
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button> >
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button> Calcular riesgos
</button>
@if (domain() === 'tea') { @if (domain() === 'tea') {
<button mat-stroked-button type="button" (click)="analyzeEegs()">Analizar EEG</button> <button
mat-stroked-button
type="button"
[disabled]="starting() || running() || !execution()"
(click)="start('analyze')"
>
Analizar EEG
</button>
} }
@if (run(); as r) { <button
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span> mat-stroked-button
type="button"
[disabled]="editing() || !models.hasValue()"
(click)="prepareCandidates(bulkDialog)"
>
Promover candidatas
</button>
</div>
@if (training(); as name) {
<app-governance-training
[domain]="domainKey()"
[name]="name"
[execution]="execution()"
[(busy)]="starting"
[disabled]="running() || !execution()"
(started)="follow($event.id, 'Entrenamiento', $event.autoPromote)"
/>
}
<app-governance-bundles
[domain]="domainKey()"
[(importing)]="starting"
[disabled]="running()"
(started)="follow($event, 'Importación')"
/>
@if (run(); as current) {
<section class="card">
<h3>{{ current.label }}</h3>
<app-run-monitor [runId]="current.id" (finished)="finish($event)" />
</section>
} }
</form>
@if (message()) { @if (message()) {
<p class="muted" role="status">{{ message() }}</p> <p class="message" role="status">{{ message() }}</p>
} }
@if (models.isLoading()) { @if (models.isLoading()) {
<p class="muted">Cargando modelos…</p> <p class="muted">Cargando modelos…</p>
} @else if (!models.value()?.length) { } @else if (models.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
} @else if (!models.hasValue() || !models.value().length) {
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p> <p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
} }
@for (m of models.value() ?? []; track m.name) { @for (m of models.hasValue() ? models.value() : []; track m.name) {
<div class="card model"> <section class="card model">
<h2>{{ m.name }}</h2> <h3>{{ m.name }}</h3>
<button mat-stroked-button type="button" (click)="training.set(m.name)">Reentrenar</button>
<table class="plain"> <table class="plain">
<thead> <thead>
<tr> <tr>
@@ -46,33 +84,34 @@
<th>Entrenamiento / prueba</th> <th>Entrenamiento / prueba</th>
<th>Informes</th> <th>Informes</th>
<th>Validación clínica</th> <th>Validación clínica</th>
<th></th> <th>Comprobaciones y linaje</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@for (v of m.versions; track v.version) { @for (v of m.versions; track v.version) {
<tr> <tr>
<td> <td>
v{{ v.version }} v{{ v.version }} <span class="badge">{{ v.status }}</span>
@if (champion(v)) {
<span class="badge">en producción</span>
}
</td> </td>
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td> <td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
<td class="num"> <td class="num">
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }} {{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
</td> </td>
<td> <td>
@for (r of v.reports; track r) { @for (report of v.reports; track report) {
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{ <button
reportNames[r] ?? r mat-button
}}</a> type="button"
(click)="reportDownload(m.name, v.version, report)"
>
{{ reportNames[report] ?? report }}
</button>
} }
@if (v.reports.includes('interpretability')) { @if (v.reports.includes('interpretability')) {
<button <button
mat-button mat-button
type="button" type="button"
(click)="chosen.set({ name: m.name, version: v.version })" (click)="chooseReport({ name: m.name, version: v.version })"
> >
Ver gráficas Ver gráficas
</button> </button>
@@ -90,90 +129,177 @@
} }
</td> </td>
<td> <td>
@if (!champion(v)) { <button
<button mat-stroked-button type="button" (click)="promote(m.name, v.version)"> mat-stroked-button
Promover type="button"
(click)="
showVersion('checks', { name: m.name, version: v.version }, checksDialog)
"
>
Comprobaciones
</button>
<button
mat-stroked-button
type="button"
(click)="
showVersion('lineage', { name: m.name, version: v.version }, lineageDialog)
"
>
Linaje
</button> </button>
}
</td> </td>
</tr> </tr>
} }
</tbody> </tbody>
</table> </table>
</div> </section>
} }
@if (chosen(); as c) { @if (chosen(); as version) {
<div class="card"> <section class="card">
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2> <h3>Interpretabilidad · {{ version.name }} v{{ version.version }}</h3>
@if (feature(); as current) {
@if (ageFeatures().length > 1) {
<label
>Característica
<select [ngModel]="current" (ngModelChange)="selectedFeature.set($event)">
@for (feature of ageFeatures(); track feature) {
<option [value]="feature">{{ feature }}</option>
}
</select>
</label>
}
<label><input type="checkbox" [(ngModel)]="overlay" /> Superponer estudios</label>
}
@if (report.error() || band.error() || analysed.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@for (f of figures(); track f.title) { @for (f of figures(); track f.title) {
<h3>{{ f.title }}</h3> <h4>{{ f.title }}</h4>
<app-plot [figure]="f.figure" [height]="360" /> <app-plot
[figure]="f.figure"
[height]="
report.hasValue() && report.value()['kind'] === 'forest'
? forestHeight(f.figure.data.length)
: 360
"
/>
} @empty { } @empty {
<p class="muted"> @if (report.isLoading() || band.isLoading()) {
{{ report.isLoading() ? 'Cargando…' : 'Este informe no tiene gráficas.' }} <p class="muted">Cargando…</p>
</p> } @else if (!report.error() && !band.error()) {
<p class="muted">Este informe no tiene gráficas.</p>
} }
</div>
} }
</section>
}
</section>
@if (domain() === 'tea') { @if (domain() === 'tea') {
<div class="card model"> <app-eeg-studies [execution]="execution()" [refresh]="refreshed()" (changed)="refresh()" />
<h2>Electroencefalogramas</h2>
<table class="plain eegs">
<thead>
<tr>
<th>Fecha</th>
<th>Registro</th>
<th>Análisis</th>
</tr>
</thead>
<tbody>
@for (e of eegs.value() ?? []; track e.id) {
<tr>
<td>
<button mat-button type="button" (click)="eeg.set(e.id)">{{ e.study_date }}</button>
</td>
<td>{{ e.lab_record_id ?? '—' }}</td>
<td>
{{ !e.analysed ? 'Sin analizar' : e.valid ? 'Válido' : 'No válido' }}
{{ e.level ? '(' + e.level + ')' : '' }}
</td>
</tr>
} @empty {
<tr>
<td colspan="3" class="muted">Sin EEG cargados.</td>
</tr>
} }
</tbody>
</table> <dialog #checksDialog aria-label="Comprobaciones" (close)="checksFor.set(undefined)">
@if (eegMetrics.value(); as m) { @if (checksFor(); as key) {
<h3>EEG {{ m.id }} · {{ m.age_months ?? '—' }} meses</h3> <h3>Comprobaciones · {{ key.name }} v{{ key.version }}</h3>
<table class="plain"> @if (checks.hasValue()) {
<thead> @let details = checks.value();
<tr> @let actions = checkActions(details);
<th>Métrica</th> <ul>
<th>Valor</th> @for (check of details.checks; track check.report) {
<th>z</th> <li>
<th>Curva</th> {{ reportNames[check.report] ?? check.report }} ·
</tr> {{ check.present ? 'Presente' : 'Falta' }}
</thead> </li>
<tbody>
@for (x of m.metrics; track x.code) {
<tr>
<td>{{ metricNames[x.code] ?? x.code }}</td>
<td class="num">{{ x.value | number: '1.2-2' }}</td>
<td class="num">{{ x.z === null ? '—' : (x.z | number: '1.2-2') }}</td>
<td>{{ x.model ?? 'sin curva en producción' }}</td>
</tr>
} @empty {
<tr>
<td colspan="4" class="muted">Sin métricas (EEG no válido).</td>
</tr>
} }
</tbody> </ul>
</table> <button
mat-stroked-button
type="button"
[disabled]="editing() || !actions.promote"
(click)="changeVersion(key, 'promote')"
>
Promover
</button>
<button
mat-stroked-button
type="button"
[disabled]="editing() || !actions.retire"
(click)="changeVersion(key, 'retire')"
>
Retirar
</button>
} @else if (checks.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
} @else {
<p>Cargando…</p>
} }
</div> @if (message()) {
<p role="status">{{ message() }}</p>
} }
}
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
</dialog>
<dialog #lineageDialog aria-label="Linaje" (close)="lineageFor.set(undefined)">
@if (lineageFor(); as key) {
<h3>Linaje · {{ key.name }} v{{ key.version }}</h3>
@if (lineage.hasValue()) {
@let details = lineage.value();
<h4>Parámetros</h4>
<dl>
@for (entry of details.params | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
<h4>Métricas</h4>
<dl>
@for (entry of details.metrics | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
<h4>Etiquetas</h4>
<dl>
@for (entry of details.tags | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
@if (details.imported; as imported) {
<h4>Importado de</h4>
<dl>
@for (entry of imported | keyvalue; track entry.key) {
<dt>{{ entry.key }}</dt>
<dd>{{ entry.value }}</dd>
}
</dl>
}
} @else if (lineage.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
} @else {
<p>Cargando…</p>
}
}
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
</dialog>
<dialog #bulkDialog aria-label="Promover candidatas">
<h3>Promover candidatas</h3>
<ul>
@for (candidate of candidates(); track candidate.name) {
<li>{{ candidate.name }} v{{ candidate.version }}</li>
}
</ul>
<button
mat-flat-button
type="button"
[disabled]="editing()"
(click)="promoteCandidates(bulkDialog)"
>
Promover
</button>
<form method="dialog"><button mat-stroked-button>Cancelar</button></form>
</dialog>
</section> </section>
+9
View File
@@ -45,3 +45,12 @@ td a {
padding: 48px 0; padding: 48px 0;
text-align: center; text-align: center;
} }
.message {
white-space: pre-line;
}
dialog {
max-width: min(90vw, 64rem);
}
dialog form {
margin-top: var(--space-3);
}
+16
View File
@@ -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);
});
});
+322 -81
View File
@@ -1,30 +1,35 @@
import { HttpErrorResponse } from '@angular/common/http'; import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common';
import { DatePipe, DecimalPipe } from '@angular/common'; import { Component, computed, effect, inject, input, resource, signal } from '@angular/core';
import { Component, computed, inject, input, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; 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 { RouterLink } from '@angular/router';
import { Api } from '../api/api'; 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 { studies } from '../api/fn/eeg/studies';
import { study } from '../api/fn/eeg/study'; 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 { 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 { DOMAINS } from '../app';
import { Plot } from '../plot'; 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<string, string> = { const REPORTS: Record<string, string> = {
technical_validation: 'Validación técnica', technical_validation: 'Validación técnica',
@@ -32,35 +37,63 @@ const REPORTS: Record<string, string> = {
clinical_validation: 'Validación clínica', clinical_validation: 'Validación clínica',
}; };
/** Model governance for a domain: every model's versions with their metrics and reports, interface VersionKey {
* the clinical validation the clinical team uploads, promotion (refused without the three name: string;
* reports), and the training and scoring runs. */ version: number;
}
interface Checks {
status: 'candidate' | 'champion' | 'retired';
promotable: boolean;
checks: { report: string; present: boolean }[];
}
interface Lineage {
params: Record<string, string>;
metrics: Record<string, number>;
tags: Record<string, string>;
imported: Record<string, string> | null;
}
export function checkActions(checks: Checks) {
return { promote: checks.promotable, retire: checks.status !== 'champion' };
}
@Component({ @Component({
selector: 'app-gobernanza', selector: 'app-gobernanza',
imports: [ imports: [
DatePipe, DatePipe,
DecimalPipe, DecimalPipe,
KeyValuePipe,
FormsModule, FormsModule,
MatButtonModule, MatButtonModule,
MatFormFieldModule,
MatInputModule,
RouterLink, RouterLink,
Plot, Plot,
Bundles,
Execution,
RunMonitor,
EegStudies,
Training,
], ],
templateUrl: './gobernanza.html', templateUrl: './gobernanza.html',
styleUrl: './gobernanza.scss', styleUrl: './gobernanza.scss',
}) })
export class Gobernanza { export class Gobernanza {
private readonly api = inject(Api); private readonly api = inject(Api);
private readonly root = inject(ApiConfiguration).rootUrl;
readonly domain = input.required<string>(); readonly domain = input.required<string>();
protected readonly domainKey = computed(() => this.domain() as Domain);
protected readonly execution = signal<Choice | undefined>(undefined);
protected readonly labels = DOMAINS as Record<string, string>; protected readonly labels = DOMAINS as Record<string, string>;
protected readonly reportNames = REPORTS; protected readonly reportNames = REPORTS;
protected readonly errorText = errorText;
protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); 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({ protected readonly models = resource({
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }), params: () => ({ domain: this.domainKey(), at: this.refreshed() }),
loader: async ({ params: { domain } }) => { loader: async ({ params: { domain } }) => {
const names = await this.api.invoke(models, { domain }); const names = await this.api.invoke(models, { domain });
return Promise.all( 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<VersionKey | undefined>(undefined);
protected readonly checksFor = signal<VersionKey | undefined>(undefined);
protected readonly lineageFor = signal<VersionKey | undefined>(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<VersionKey[]>([]);
protected readonly report = resource({ 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 }) => loader: ({ params }) =>
this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }), this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }),
}); });
protected readonly ageFeatures = computed<string[]>(() => {
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(() => { protected readonly figures = computed(() => {
const found = this.report.value(); if (!this.report.hasValue()) return [];
return found ? interpretabilityFigures(found as Record<string, unknown>) : []; 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<string | undefined>(undefined);
protected readonly eegMetrics = resource({
params: () => this.eeg(),
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
});
protected readonly metricNames: Record<string, string> = {
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 { constructor() {
return v.aliases.includes('champion'); 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 { protected async reportDownload(name: string, version: number, report: string): Promise<void> {
return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`; 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<void> { protected async upload(name: string, version: number, event: Event): Promise<void> {
const file = (event.target as HTMLInputElement).files?.[0]; const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return; if (!file) return;
const domain = this.domainKey();
try {
await this.api.invoke(addClinicalValidation, { await this.api.invoke(addClinicalValidation, {
domain: this.domain() as Domain, domain,
name, name,
version, version,
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
body: { file: file as unknown as string }, 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.message.set(`Validación clínica agregada a ${name} v${version}.`);
this.refreshed.update((n) => n + 1); this.refresh();
} catch (error) {
this.message.set(errorText(error));
}
} }
protected async promote(name: string, version: number): Promise<void> { protected showVersion(
kind: 'checks' | 'lineage',
key: VersionKey,
dialog: HTMLDialogElement,
): void {
(kind === 'checks' ? this.checksFor : this.lineageFor).set(key);
dialog.showModal();
}
protected async changeVersion(key: VersionKey, action: 'promote' | 'retire'): Promise<void> {
const domain = this.domainKey();
this.editing.set(true);
this.message.set('');
try { try {
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version }); if (action === 'promote') await this.api.invoke(promote, { domain, ...key });
this.message.set(`${name} v${version} es ahora la versión en producción.`); else await this.api.invoke(retire, { domain, ...key });
this.refreshed.update((n) => n + 1); this.message.set(
} catch (e) { `${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`,
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined; );
this.message.set(`No se promovió: ${detail ?? 'error'}`); this.refresh();
} catch (error) {
this.message.set(errorText(error));
} finally {
this.editing.set(false);
} }
} }
protected async analyzeEegs(): Promise<void> { protected async prepareCandidates(dialog: HTMLDialogElement): Promise<void> {
const { run_id } = await this.api.invoke(analyze, { domain: this.domain() as Domain }); if (!this.models.hasValue()) return;
await this.follow(run_id, 'Análisis de EEG'); 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);
}
} }
private async follow(run_id: string, label: string): Promise<void> { protected async promoteCandidates(dialog: HTMLDialogElement): Promise<void> {
for (;;) { this.editing.set(true);
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string; this.message.set('');
this.run.set({ kind: label, status }); try {
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break; await this.promoteVersions(this.domainKey(), this.candidates());
await new Promise((r) => setTimeout(r, 2000)); dialog.close();
} finally {
this.editing.set(false);
} }
this.refreshed.update((n) => n + 1);
} }
protected async start(kind: 'train' | 'score'): Promise<void> { protected forestHeight(rows: number): number {
const domain = this.domain() as Domain; 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<void> {
const domain = this.domainKey();
this.starting.set(true);
this.message.set('');
try {
const { run_id } = const { run_id } =
kind === 'train' kind === 'score'
? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} }) ? await this.api.invoke(score, { domain })
: await this.api.invoke(score, { domain }); : await this.api.invoke(analyze, { domain, body: { execution: this.execution() } });
await this.follow(run_id, kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos'); 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<void> {
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<Checks> {
return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks;
}
private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise<void> {
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();
} }
} }
+101
View File
@@ -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<RunMonitor>): Promise<void> {
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');
});
});
+164
View File
@@ -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: `
<section aria-label="Monitor de ejecución">
@if (run(); as r) {
<p role="status">{{ r.status }}</p>
@for (step of r.steps; track step.key) {
<div>{{ step.key }} · {{ step.status }}</div>
}
@if (r.progress; as p) {
<div>
{{ p.phase }} · {{ p.done }} / {{ p.total }}
@if (p.total > 0) {
({{ (100 * p.done) / p.total | number: '1.0-0' }} %)
<progress [value]="p.done" [max]="p.total"></progress>
}
@if (eta(p) !== null) {
· ETA {{ eta(p) | number: '1.0-0' }} s
}
</div>
@for (worker of p.workers ?? []; track worker.name) {
<div>
{{ 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 }}
</div>
}
@for (task of p.tasks | keyvalue; track task.key) {
<div>{{ task.key }}: {{ task.value }}</div>
}
}
@if (r.info.length) {
<h4>Información</h4>
<ul>
@for (line of r.info; track $index) {
<li>{{ line }}</li>
}
</ul>
}
@if (r.warnings.length) {
<h4>Advertencias</h4>
<ul>
@for (line of r.warnings; track $index) {
<li>{{ line }}</li>
}
</ul>
}
@if (r.error) {
<p role="alert">{{ r.error }}</p>
}
@if (!terminal.has(r.state)) {
<button
mat-stroked-button
type="button"
[disabled]="cancelling() || r.state === 'cancelling'"
(click)="cancel()"
>
Cancelar
</button>
}
} @else {
<p role="status">Consultando ejecución…</p>
}
@if (pollError()) {
<p role="alert">{{ pollError() }}</p>
}
@if (cancelError()) {
<p role="alert">{{ cancelError() }}</p>
}
</section>
`,
})
export class RunMonitor {
private readonly api = inject(Api);
readonly runId = input.required<string>();
readonly finished = output<Run>();
protected readonly run = signal<Run | undefined>(undefined);
protected readonly pollError = signal('');
protected readonly cancelError = signal('');
protected readonly cancelling = signal(false);
protected readonly terminal = new Set<Run['state']>(['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<typeof setTimeout>;
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<void> {
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);
}
}
}
+177
View File
@@ -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: `
<section>
<h3>Vista previa</h3>
<form (ngSubmit)="start(edf.files?.[0], ados.files?.[0], birth.value)">
<label>EDF <input #edf type="file" accept=".edf" required /></label>
<label>ADOS-2 (PDF) <input #ados type="file" accept=".pdf" /></label>
<label>Fecha de nacimiento <input #birth type="date" /></label>
<button mat-stroked-button type="submit" [disabled]="busy()">Vista previa</button>
</form>
@if (error()) {
<p role="alert">{{ error() }}</p>
}
@if (runId(); as id) {
<app-run-monitor [runId]="id" (finished)="finish($event, dialog)" />
}
<dialog #dialog aria-label="Vista previa del estudio">
@if (result(); as r) {
<h3>Resultado de la vista previa</h3>
<p>
{{ r.eeg.level }} ·
{{ r.eeg.valid === true ? 'Válido' : r.eeg.valid === false ? 'No válido' : '—' }}
</p>
@if (r.eeg.error) {
<p role="alert">{{ r.eeg.error }}</p>
}
<h4>Comprobaciones</h4>
<table class="plain">
<thead>
<tr>
<th>Comprobación</th>
<th>Electrodo</th>
<th>Resultado</th>
<th>Rango</th>
<th>Anormal</th>
</tr>
</thead>
<tbody>
@for (check of r.eeg.checks; track $index) {
<tr>
<td>{{ check['code'] }}</td>
<td>{{ check['electrode'] ?? '—' }}</td>
<td>{{ check['value'] ?? check['text'] ?? '—' }} {{ check['unit'] }}</td>
<td>{{ check['low'] ?? '—' }} / {{ check['high'] ?? '—' }}</td>
<td>
{{
check['abnormal'] === true ? 'Sí' : check['abnormal'] === false ? 'No' : '—'
}}
</td>
</tr>
}
</tbody>
</table>
<h4>Métricas</h4>
<table class="plain">
<thead>
<tr>
<th>Métrica</th>
<th>Valor</th>
<th>z</th>
<th>p5 / mediana / p95</th>
<th>Fuera de rango</th>
</tr>
</thead>
<tbody>
@for (metric of r.eeg.metrics; track metric.code) {
<tr>
<th>{{ metric.code }}</th>
<td>{{ metric.value ?? '—' }}</td>
<td>{{ metric.score?.z ?? '—' }}</td>
<td>
{{ metric.score?.p5 ?? '—' }} / {{ metric.score?.median ?? '—' }} /
{{ metric.score?.p95 ?? '—' }}
</td>
<td>{{ metric.score?.outside ?? '—' }}</td>
</tr>
@for (site of metric.electrodes | keyvalue; track site.key) {
<tr>
<td>{{ site.key }}</td>
<td>{{ site.value.value ?? '—' }}</td>
<td>{{ site.value.score?.z ?? '—' }}</td>
<td>
{{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} /
{{ site.value.score?.p95 ?? '—' }}
</td>
<td>{{ site.value.score?.outside ?? '—' }}</td>
</tr>
}
@for (site of metric.zones | keyvalue; track site.key) {
<tr>
<td>{{ site.key }}</td>
<td>{{ site.value.value ?? '—' }}</td>
<td>{{ site.value.score?.z ?? '—' }}</td>
<td>
{{ site.value.score?.p5 ?? '—' }} / {{ site.value.score?.median ?? '—' }} /
{{ site.value.score?.p95 ?? '—' }}
</td>
<td>{{ site.value.score?.outside ?? '—' }}</td>
</tr>
}
}
</tbody>
</table>
@if (r.ados2; as ados2) {
<h4>ADOS-2</h4>
<p>{{ ados2.classification }} · CSS {{ ados2.css ?? '—' }}</p>
<dl>
@for (item of ados2.items | keyvalue; track item.key) {
<dt>{{ item.key }}</dt>
<dd>{{ item.value ?? '—' }}</dd>
}
</dl>
}
@if (r.warnings.length) {
<h4>Advertencias</h4>
<ul>
@for (warning of r.warnings; track $index) {
<li>{{ warning }}</li>
}
</ul>
}
}
<form method="dialog"><button mat-stroked-button>Cerrar</button></form>
</dialog>
</section>
`,
})
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<PreviewResult | null>(null);
protected async start(edf?: File, ados2?: File, birth_date?: string): Promise<void> {
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<void> {
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);
}
}
}
+129
View File
@@ -0,0 +1,129 @@
<section class="card model">
<h2>Estudios EEG</h2>
<form (ngSubmit)="analyze()">
<label
>Alcance
<select name="scope" [(ngModel)]="mode">
<option value="pending">Pendientes</option>
<option value="first_n">Primeros N</option>
<option value="ids">Por ID</option>
</select>
</label>
@if (mode() === 'first_n') {
<label
>Número de estudios <input type="number" name="count" min="1" required [(ngModel)]="count"
/></label>
}
@if (mode() === 'ids') {
<label
>ID de estudios (uno por línea) <textarea name="ids" required [(ngModel)]="ids"></textarea>
</label>
}
<button mat-flat-button type="submit" [disabled]="busy() || !execution()">Analizar</button>
</form>
<form (ngSubmit)="upload(files)">
<label>Archivos EDF <input #files type="file" accept=".edf" multiple required /></label>
<button mat-stroked-button type="submit" [disabled]="busy()">Subir EDF</button>
</form>
@if (error()) {
<p role="alert">{{ error() }}</p>
}
@if (runId(); as id) {
<app-run-monitor [runId]="id" (finished)="finish()" />
}
<app-eeg-preview />
<h3>Resumen</h3>
@if (summary.hasValue()) {
<dl>
@for (count of summary.value() | keyvalue; track count.key) {
<dt>{{ labels[count.key] ?? count.key }}</dt>
<dd>{{ count.value }}</dd>
}
</dl>
} @else if (summary.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (history.hasValue()) {
@if (history.value().last; as last) {
<p>
Última ejecución TEA: {{ last.status }}
@if (last.ended != null) {
· {{ last.ended * 1000 | date: 'short' }}
}
</p>
}
<p>
{{
history.value().current
? 'Indicadores al día'
: 'Indicadores pendientes: corre el análisis TEA'
}}
</p>
} @else if (history.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (eegs.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (eegMetrics.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
<div class="model">
<table class="plain eegs">
<thead>
<tr>
<th>Fecha</th>
<th>Registro</th>
<th>Análisis</th>
</tr>
</thead>
<tbody>
@for (e of eegs.hasValue() ? eegs.value() : []; track e.id) {
<tr>
<td>
<button mat-button type="button" [disabled]="!e.analysed" (click)="eeg.set(e.id)">
{{ e.study_date }}
</button>
</td>
<td>{{ e.lab_record_id ?? '—' }}</td>
<td>
{{ !e.analysed ? 'Sin analizar' : e.valid ? 'Válido' : 'No válido' }}
{{ e.level ? '(' + e.level + ')' : '' }}
</td>
</tr>
} @empty {
<tr>
<td colspan="3" class="muted">Sin EEG cargados.</td>
</tr>
}
</tbody>
</table>
@if (eegMetrics.hasValue() && eegMetrics.value(); as m) {
<h3>EEG {{ m.id }} · {{ m.age_months ?? '—' }} meses</h3>
<table class="plain">
<thead>
<tr>
<th>Métrica</th>
<th>Valor</th>
<th>z</th>
<th>Curva</th>
</tr>
</thead>
<tbody>
@for (x of m.metrics; track x.code) {
<tr>
<td>{{ metricNames[x.code] ?? x.code }}</td>
<td class="num">{{ x.value | number: '1.2-2' }}</td>
<td class="num">{{ x.z === null ? '—' : (x.z | number: '1.2-2') }}</td>
<td>{{ x.model ?? 'sin curva en producción' }}</td>
</tr>
} @empty {
<tr>
<td colspan="4" class="muted">Sin métricas (EEG no válido).</td>
</tr>
}
</tbody>
</table>
}
</div>
</section>
+160
View File
@@ -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<Execution>();
readonly refresh = input(0);
readonly changed = output<void>();
protected readonly eegs = resource({
params: () => this.refresh(),
loader: () => this.api.invoke(studies),
});
protected readonly eeg = signal<string | undefined>(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<string, string> = {
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<string, string> = {
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<NonNullable<Scope['mode']>>('pending');
protected readonly count = signal<number | null>(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<void> {
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<void> {
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<void> {
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);
}
}
}
+40
View File
@@ -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 } });
});
});
+243
View File
@@ -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<string, Schema> };
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: `
<section class="card">
<h3>{{ name() === 'all' ? 'Entrenar modelos' : 'Reentrenar ' + name() }}</h3>
@if (config.hasValue()) {
@let form = config.value();
<form (ngSubmit)="start(form.model)">
<formly-form [form]="form.form" [fields]="form.fields" [model]="form.model" />
@if (domain() === 'tea') {
<label
><input type="checkbox" name="promote" [(ngModel)]="autoPromote" /> Promover al
terminar</label
>
}
<button
mat-flat-button
type="submit"
[disabled]="busy() || disabled() || form.form.invalid"
>
Entrenar
</button>
</form>
} @else if (config.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (inputs.hasValue() && inputs.value(); as sets) {
<h4>Archivos de entrenamiento</h4>
<p>{{ sets.description }}</p>
<ul>
@for (set of sets.sets; track set.name) {
<li>
{{ set.name }} · {{ set.edf_files }} EDF ·
{{ set.has_ages ? 'Con edades' : 'Sin edades' }}
</li>
}
</ul>
<form (ngSubmit)="upload(setName.value, files)">
<label
>Conjunto
<input #setName list="training-input-sets" required />
</label>
<datalist id="training-input-sets">
@for (set of sets.sets; track set.name) {
<option [value]="set.name"></option>
}
</datalist>
<label
>Archivos
<input #files type="file" multiple required [accept]="accept(sets.allowed)" />
</label>
<button mat-stroked-button type="submit" [disabled]="uploading()">Subir archivos</button>
</form>
} @else if (inputs.error(); as error) {
<p role="alert">{{ errorText(error) }}</p>
}
@if (message()) {
<p role="status">{{ message() }}</p>
}
</section>
`,
})
export class Training {
private readonly api = inject(Api);
private readonly jsonschema = inject(FormlyJsonschema);
readonly domain = input.required<Domain>();
readonly name = input.required<string>();
readonly execution = input<Execution>();
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<void> {
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<void> {
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);
}
}
}