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:
2026-11-30 13:53:24 -06:00
parent 5d03f333f7
commit e2d1c9f277
17 changed files with 2202 additions and 265 deletions
+125 -15
View File
@@ -1,10 +1,10 @@
import type { Analysis } from '../api/models/analysis';
import type { Figure } from '../plot';
import { PALETTE } from '../plot';
/** A curve with its band, as the reports give them. */
interface Band {
x: number[];
y: number[];
y: (number | null)[];
low?: (number | null)[];
high?: (number | null)[];
}
@@ -34,10 +34,64 @@ function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Pl
return lines;
}
/** What a model's interpretability report draws, by its kind: survival curves, the mixture's
* observed and predicted risk per subgroup, or the logistic regression's calibration. */
export interface Centile {
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(
report: Record<string, any>,
ageCurve: AgeCurveOptions = {},
): { title: string; figure: Figure }[] {
switch (report['kind']) {
case 'curves': {
@@ -70,7 +124,6 @@ export function interpretabilityFigures(
},
},
},
// Its clinical scenarios, those with enough deaths to draw.
...((report['escenarios'] ?? []) as any[]).map((e) =>
scenarioFigure(
`${e.escenario} (n = ${e.n.toLocaleString('es-MX')}, fallecidos = ${e.fallecidos.toLocaleString('es-MX')})`,
@@ -158,24 +211,73 @@ export function interpretabilityFigures(
'Supervivencia libre de recaída',
),
);
case 'forest':
return [
{
title: 'Asociaciones ADOS-2',
figure: {
data: (report['rows'] as AssociationRow[]).map((row) => {
const label = [row.biomarker, row.zone, row.outcome_code].filter(Boolean).join(' · ');
const odds = row.odds_ratio;
return {
x: [odds],
y: [label],
name: label,
showlegend: false,
type: 'scatter',
mode: 'markers',
marker: { color: PALETTE[4] },
error_x:
odds == null || row.ci_low == null || row.ci_high == null
? undefined
: {
type: 'data',
symmetric: false,
array: [row.ci_high - odds],
arrayminus: [odds - row.ci_low],
},
hovertemplate: '%{y}<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': {
// The metric's own curve; a topography has only electrodes: its first one.
const value = report['curves']['value'] ?? Object.values(report['curves'])[0];
const curves = report['curves'];
const feature = ageCurve.feature ?? (curves.value ? 'value' : Object.keys(curves)[0]);
const value = curves[feature];
if (!value) return [];
const label = report['curves']['value'] ? '' : ` · ${Object.keys(report['curves'])[0]}`;
const label = feature === 'value' ? '' : ` · ${feature}`;
const overlay: Partial<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: ${value.rate.toFixed(3)} por minuto (${value.reference} estudios)`,
title: `Tasa de referencia: ${rate?.toFixed(3) ?? '—'} por minuto (${value.reference} estudios)${label}`,
figure: {
data: [
{
x: value.ages,
y: [value.rate, value.rate],
y: [rate, rate],
name: 'Tasa',
type: 'scatter',
mode: 'lines',
},
...overlay,
],
layout: {
xaxis: { title: { text: 'Edad (meses)' } },
@@ -185,18 +287,28 @@ export function interpretabilityFigures(
},
];
}
const c = value.curve;
const centiles = ageCurve.centiles;
if (!centiles && ageCurve.waitForCentiles) return [];
const c = centiles
? {
age_months: centiles.map((point) => point.age_months),
median: centiles.map((point) => point.median),
p5: centiles.map((point) => point.p5),
p95: centiles.map((point) => point.p95),
}
: value.curve;
return [
{
title: `Curva de referencia por edad (p5, mediana, p95)${label}`,
figure: {
data: [
...banded(
'p5–p95',
'Mediana',
{ x: c.age_months, y: c.median, low: c.p5, high: c.p95 },
PALETTE[4],
),
].map((d, i) => (i === 1 ? { ...d, name: 'Mediana' } : d)),
...overlay,
],
layout: {
xaxis: { title: { text: 'Edad (meses)' }, type: 'log' },
yaxis: { title: { text: 'Valor' } },
@@ -210,8 +322,6 @@ export function interpretabilityFigures(
}
}
/** One clinical scenario: Kaplan-Meier with its band, the classic and fractional Weibull,
* and the model's points with their bootstrap band. */
function scenarioFigure(
title: string,
e: any,