CaMa indicators and follow-up list, model governance page
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import { interpretabilityFigures } from './figures';
|
||||
|
||||
describe('governance figures', () => {
|
||||
it('draws a survival report as curves with bands and the model points', () => {
|
||||
const [found] = interpretabilityFigures({
|
||||
kind: 'curves',
|
||||
curves: [
|
||||
{ name: 'Kaplan-Meier', months: [0, 6], survival: [1, 0.9], low: [1, 0.8], high: [1, 1] },
|
||||
],
|
||||
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[2] as any).error_y.array[0]).toBeCloseTo(0.05);
|
||||
});
|
||||
|
||||
it('draws nothing for a report it does not know', () => {
|
||||
expect(interpretabilityFigures({ kind: 'other' })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
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[];
|
||||
low?: (number | null)[];
|
||||
high?: (number | null)[];
|
||||
}
|
||||
|
||||
function banded(name: string, b: Band, colour: string, dash?: 'dot'): Partial<Plotly.Data>[] {
|
||||
const lines: Partial<Plotly.Data>[] = [];
|
||||
if (b.low && b.high) {
|
||||
lines.push({
|
||||
x: [...b.x, ...[...b.x].reverse()],
|
||||
y: [...b.high, ...[...b.low].reverse()] as number[],
|
||||
fill: 'toself',
|
||||
fillcolor: `${colour}33`,
|
||||
line: { width: 0 },
|
||||
hoverinfo: 'skip',
|
||||
showlegend: false,
|
||||
type: 'scatter',
|
||||
});
|
||||
}
|
||||
lines.push({
|
||||
x: b.x,
|
||||
y: b.y,
|
||||
name,
|
||||
type: 'scatter',
|
||||
mode: 'lines',
|
||||
line: { color: colour, dash },
|
||||
});
|
||||
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 function interpretabilityFigures(
|
||||
report: Record<string, any>,
|
||||
): { title: string; figure: Figure }[] {
|
||||
switch (report['kind']) {
|
||||
case 'curves': {
|
||||
const data = (report['curves'] as any[]).flatMap((c, i) =>
|
||||
banded(c.name, { x: c.months, y: c.survival, low: c.low, high: c.high }, PALETTE[i]),
|
||||
);
|
||||
const p = report['predicted'];
|
||||
data.push({
|
||||
x: p.months,
|
||||
y: p.survival,
|
||||
error_y: {
|
||||
type: 'data',
|
||||
symmetric: false,
|
||||
array: p.high.map((h: number, i: number) => h - p.survival[i]),
|
||||
arrayminus: p.survival.map((s: number, i: number) => s - p.low[i]),
|
||||
},
|
||||
name: p.name,
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
marker: { color: PALETTE[4], size: 9 },
|
||||
});
|
||||
return [
|
||||
{
|
||||
title: 'Supervivencia observada y del modelo',
|
||||
figure: {
|
||||
data,
|
||||
layout: {
|
||||
xaxis: { title: { text: 'Meses desde el índice' } },
|
||||
yaxis: { title: { text: 'Supervivencia S(t)' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
case 'subgroups':
|
||||
return (report['groups'] as any[]).slice(0, 6).map((g) => ({
|
||||
title: `${Object.values(g.combination).join(' · ')} (n = ${g.n})`,
|
||||
figure: {
|
||||
data: [
|
||||
...banded(
|
||||
'Observado (Turnbull)',
|
||||
{
|
||||
x: g.observed.years,
|
||||
y: g.observed.risk,
|
||||
low: g.observed.low,
|
||||
high: g.observed.high,
|
||||
},
|
||||
PALETTE[0],
|
||||
),
|
||||
...(g.predicted
|
||||
? banded(
|
||||
'Modelo',
|
||||
{
|
||||
x: g.predicted.years,
|
||||
y: g.predicted.risk,
|
||||
low: g.predicted.low,
|
||||
high: g.predicted.high,
|
||||
},
|
||||
PALETTE[4],
|
||||
'dot',
|
||||
)
|
||||
: []),
|
||||
],
|
||||
layout: {
|
||||
xaxis: { title: { text: 'Años desde el índice' } },
|
||||
yaxis: { title: { text: 'Riesgo acumulado' } },
|
||||
},
|
||||
},
|
||||
}));
|
||||
case 'coefficients': {
|
||||
const bins = report['calibration']['bins'] as any[];
|
||||
return [
|
||||
{
|
||||
title: `Calibración por decil de riesgo (Brier ${report['calibration']['brier'].toFixed(3)})`,
|
||||
figure: {
|
||||
data: [
|
||||
{
|
||||
x: bins.map((b) => b.predicted),
|
||||
y: bins.map((b) => b.observed),
|
||||
name: 'Deciles',
|
||||
type: 'scatter',
|
||||
mode: 'markers',
|
||||
},
|
||||
{
|
||||
x: [0, 1],
|
||||
y: [0, 1],
|
||||
name: 'Calibración perfecta',
|
||||
type: 'scatter',
|
||||
mode: 'lines',
|
||||
line: { dash: 'dot', color: PALETTE[6] },
|
||||
},
|
||||
],
|
||||
layout: {
|
||||
xaxis: { title: { text: 'Predicho' } },
|
||||
yaxis: { title: { text: 'Observado' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<section class="page">
|
||||
<h1>Gobernanza de modelos</h1>
|
||||
<nav class="domains" aria-label="Dominios">
|
||||
@for (d of domains.value() ?? []; track d) {
|
||||
<a [routerLink]="['/gobernanza', d]" [class.active]="d === domain()">{{ labels[d] ?? d }}</a>
|
||||
}
|
||||
</nav>
|
||||
|
||||
<form class="card actions" (submit)="$event.preventDefault()">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Datos hasta</mat-label>
|
||||
<input
|
||||
matInput
|
||||
type="date"
|
||||
[ngModel]="asOf()"
|
||||
(ngModelChange)="asOf.set($event)"
|
||||
name="asOf"
|
||||
/>
|
||||
</mat-form-field>
|
||||
<button mat-flat-button type="button" (click)="start('train')">Entrenar</button>
|
||||
<button mat-stroked-button type="button" (click)="start('score')">Calcular riesgos</button>
|
||||
@if (run(); as r) {
|
||||
<span class="muted" role="status">{{ r.kind }}: {{ r.status }}</span>
|
||||
}
|
||||
</form>
|
||||
@if (message()) {
|
||||
<p class="muted" role="status">{{ message() }}</p>
|
||||
}
|
||||
|
||||
@if (models.isLoading()) {
|
||||
<p class="muted">Cargando modelos…</p>
|
||||
} @else if (!models.value()?.length) {
|
||||
<p class="muted empty">Este dominio todavía no tiene modelos entrenados.</p>
|
||||
}
|
||||
@for (m of models.value() ?? []; track m.name) {
|
||||
<div class="card model">
|
||||
<h2>{{ m.name }}</h2>
|
||||
<table class="plain">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Versión</th>
|
||||
<th>Creada</th>
|
||||
<th>Entrenamiento / prueba</th>
|
||||
<th>Informes</th>
|
||||
<th>Validación clínica</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (v of m.versions; track v.version) {
|
||||
<tr>
|
||||
<td>
|
||||
v{{ v.version }}
|
||||
@if (champion(v)) {
|
||||
<span class="badge">en producción</span>
|
||||
}
|
||||
</td>
|
||||
<td>{{ v.created | date: 'yyyy-MM-dd HH:mm' }}</td>
|
||||
<td class="num">
|
||||
{{ v.metrics['n_train'] | number }} / {{ v.metrics['n_test'] | number }}
|
||||
</td>
|
||||
<td>
|
||||
@for (r of v.reports; track r) {
|
||||
<a [href]="reportUrl(m.name, v.version, r)" target="_blank" rel="noopener">{{
|
||||
reportNames[r] ?? r
|
||||
}}</a>
|
||||
}
|
||||
@if (v.reports.includes('interpretability')) {
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
(click)="chosen.set({ name: m.name, version: v.version })"
|
||||
>
|
||||
Ver gráficas
|
||||
</button>
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@if (!v.reports.includes('clinical_validation')) {
|
||||
<input
|
||||
type="file"
|
||||
[attr.aria-label]="'Validación clínica de ' + m.name + ' v' + v.version"
|
||||
(change)="upload(m.name, v.version, $event)"
|
||||
/>
|
||||
} @else {
|
||||
Agregada
|
||||
}
|
||||
</td>
|
||||
<td>
|
||||
@if (!champion(v)) {
|
||||
<button mat-stroked-button type="button" (click)="promote(m.name, v.version)">
|
||||
Promover
|
||||
</button>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (chosen(); as c) {
|
||||
<div class="card">
|
||||
<h2>Interpretabilidad · {{ c.name }} v{{ c.version }}</h2>
|
||||
@for (f of figures(); track f.title) {
|
||||
<h3>{{ f.title }}</h3>
|
||||
<app-plot [figure]="f.figure" [height]="360" />
|
||||
} @empty {
|
||||
<p class="muted">
|
||||
{{ report.isLoading() ? 'Cargando…' : 'Este informe no tiene gráficas.' }}
|
||||
</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,47 @@
|
||||
:host {
|
||||
display: block;
|
||||
}
|
||||
h1 {
|
||||
text-align: center;
|
||||
}
|
||||
.domains {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: var(--space-4);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
.domains a.active {
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
.model {
|
||||
margin-bottom: var(--space-4);
|
||||
overflow-x: auto;
|
||||
}
|
||||
.num {
|
||||
text-align: right;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge {
|
||||
margin-left: var(--space-2);
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
font-size: 12px;
|
||||
}
|
||||
td a {
|
||||
margin-right: var(--space-3);
|
||||
color: var(--color-action);
|
||||
}
|
||||
.empty {
|
||||
padding: 48px 0;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { DatePipe, DecimalPipe } from '@angular/common';
|
||||
import { Component, computed, inject, input, resource, signal } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { RouterLink } from '@angular/router';
|
||||
import { Api } from '../api/api';
|
||||
import { ApiConfiguration } from '../api/api-configuration';
|
||||
import { addClinicalValidation } from '../api/fn/models/add-clinical-validation';
|
||||
import { 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 { runStatus } from '../api/fn/runs/run-status';
|
||||
import type { Domain } from '../api/models/domain';
|
||||
import type { Version } from '../api/models/version';
|
||||
import { DOMAINS } from '../app';
|
||||
import { Plot } from '../plot';
|
||||
import { interpretabilityFigures } from './figures';
|
||||
|
||||
const REPORTS: Record<string, string> = {
|
||||
technical_validation: 'Validación técnica',
|
||||
interpretability: 'Interpretabilidad',
|
||||
clinical_validation: 'Validación clínica',
|
||||
};
|
||||
|
||||
/** Model governance for a domain: every model's versions with their metrics and reports,
|
||||
* the clinical validation the clinical team uploads, promotion (refused without the three
|
||||
* reports), and the training and scoring runs. */
|
||||
@Component({
|
||||
selector: 'app-gobernanza',
|
||||
imports: [
|
||||
DatePipe,
|
||||
DecimalPipe,
|
||||
FormsModule,
|
||||
MatButtonModule,
|
||||
MatFormFieldModule,
|
||||
MatInputModule,
|
||||
RouterLink,
|
||||
Plot,
|
||||
],
|
||||
templateUrl: './gobernanza.html',
|
||||
styleUrl: './gobernanza.scss',
|
||||
})
|
||||
export class Gobernanza {
|
||||
private readonly api = inject(Api);
|
||||
private readonly root = inject(ApiConfiguration).rootUrl;
|
||||
readonly domain = input.required<string>();
|
||||
|
||||
protected readonly labels = DOMAINS as Record<string, string>;
|
||||
protected readonly reportNames = REPORTS;
|
||||
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
||||
private readonly refreshed = signal(0);
|
||||
protected readonly models = resource({
|
||||
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
|
||||
loader: async ({ params: { domain } }) => {
|
||||
const names = await this.api.invoke(models, { domain });
|
||||
return Promise.all(
|
||||
names.map(async (name) => ({
|
||||
name,
|
||||
versions: await this.api.invoke(versions, { domain, name }),
|
||||
})),
|
||||
);
|
||||
},
|
||||
});
|
||||
protected readonly chosen = signal<{ name: string; version: number } | undefined>(undefined);
|
||||
protected readonly report = resource({
|
||||
params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain },
|
||||
loader: ({ params }) =>
|
||||
this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }),
|
||||
});
|
||||
protected readonly figures = computed(() => {
|
||||
const found = this.report.value();
|
||||
return found ? interpretabilityFigures(found as Record<string, unknown>) : [];
|
||||
});
|
||||
protected readonly asOf = signal('');
|
||||
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined);
|
||||
protected readonly message = signal('');
|
||||
|
||||
protected champion(v: Version): boolean {
|
||||
return v.aliases.includes('champion');
|
||||
}
|
||||
|
||||
protected reportUrl(name: string, version: number, report: string): string {
|
||||
return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`;
|
||||
}
|
||||
|
||||
protected async upload(name: string, version: number, event: Event): Promise<void> {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
await this.api.invoke(addClinicalValidation, {
|
||||
domain: this.domain() as Domain,
|
||||
name,
|
||||
version,
|
||||
// OpenAPI's binary is typed as a string; the request builder sends the File as is.
|
||||
body: { file: file as unknown as string },
|
||||
});
|
||||
this.message.set(`Validación clínica agregada a ${name} v${version}.`);
|
||||
this.refreshed.update((n) => n + 1);
|
||||
}
|
||||
|
||||
protected async promote(name: string, version: number): Promise<void> {
|
||||
try {
|
||||
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
|
||||
this.message.set(`${name} v${version} es ahora la versión en producción.`);
|
||||
this.refreshed.update((n) => n + 1);
|
||||
} catch (e) {
|
||||
const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined;
|
||||
this.message.set(`No se promovió: ${detail ?? 'error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
protected async start(kind: 'train' | 'score'): Promise<void> {
|
||||
const domain = this.domain() as Domain;
|
||||
const { run_id } =
|
||||
kind === 'train'
|
||||
? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} })
|
||||
: await this.api.invoke(score, { domain });
|
||||
const label = kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos';
|
||||
for (;;) {
|
||||
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
|
||||
this.run.set({ kind: label, status });
|
||||
if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break;
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
}
|
||||
this.refreshed.update((n) => n + 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user