Gobernanza: execution, models (training, run monitor, checks, lineage, bundles, interpretability), EEG studies
Share one execution selection across training and analysis. Use the first configured scheduler for a remote default and let the API validate typed addresses. Suspend health polling when the document is hidden. Poll each run serially, retry status reads on transient errors, and compute ETA from completed items and elapsed seconds. Reuse the Conectar Formly types with nullable fields and inlined references. Omit the optional cohort when its name is blank, and offer the declared input sets in a datalist with filename validation before upload. Identify the versions created by a training run from its version log lines, then check each exact version before promotion. Use native dialogs for checks, lineage, bulk confirmation and preview. Recheck promotion eligibility before submitting changes, and list results per version. Verify bundle hashes using SubtleCrypto before upload. Use blob downloads for bundles and reports. Read age centiles from the curve endpoint and keep the count-rate reference line from the report. Join study metrics by code and regional values by feature, skipping absent ages and values. Use one Plotly trace per association pair and scale the forest plot height by row count. Preflight the TEA pipeline before staging EDFs, then start the pipeline once for the batch. Refresh studies, their overlays and summary on completed runs. Page through analyze history to compare its end times against the latest tea_eeg result. The branch base lacks export/pdf.ts, so the preview uses the specified TODO and omits the PDF action. Added Vitest coverage for execution and run polling, ETA and cancellation, training schema, version actions, bundle digest verification, study overlays and the association forest. Ruff check, Ruff format --check, Prettier, strict Angular and TypeScript diagnostics for Gobernanza and git diff --check passed. npm ci, ng build and vitest run are assigned to the test machines.
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user