Compare commits

..

4 Commits

Author SHA1 Message Date
edgar eae325768d Governance: choose a notebook kept in the code or upload one
The "Correr un notebook" dialog offers "Del código" (the domain's templates from /governance/notebook-templates, each
with the scenarios it can run for) or "Subir archivo". Choosing a template fills its scenario; a scenario it doesn't
serve keeps "Correr" disabled. The request sends the template's id and no file. A domain without templates opens on
the upload, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 22:30:39 -06:00
roberto 1fef7812b4 Merge pull request 'CaMa recurrence figure: the y axis follows the months it draws' (#17) from fix/cama-recurrence-axis into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/17
2026-11-21 15:37:58 -06:00
angel 6465165e34 CaMa recurrence figure: the y axis follows the months it draws 2026-11-21 15:36:00 -06:00
angel a26df55214 Merge pull request 'CaMa patient record: survival and recurrence figures; governance trains any scenario' (#16) from feature/cama-roundtrip into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/16
2026-11-21 15:03:15 -06:00
7 changed files with 158 additions and 22 deletions
@@ -12,6 +12,7 @@ import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.compone
import { CamaCurvasService, respuestaCurvas } from './cama-curvas.service';
import { CamaFactoresRiesgo, entradasDe } from './cama-factores-riesgo.component';
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
import { figuraRecurrencia } from './cama-recurrencia-figura';
const meses = Array.from({ length: 25 }, (_, i) => i);
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
@@ -112,6 +113,14 @@ describe('Análisis de supervivencia', () => {
});
describe('Análisis de recurrencia', () => {
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
it('scales the y axis to the months it draws', () => {
const largo = { ...figura('metabric', 'Largo'), observado_hasta: 300, months_max: 72,
km: { months: Array.from({ length: 301 }, (_, i) => i), S: Array.from({ length: 301 }, (_, i) => 1 - i / 400), low: Array.from({ length: 301 }, (_, i) => (i <= 72 ? 0.85 : 0.2)), high: Array.from({ length: 301 }, () => 1) } };
expect((figuraRecurrencia(respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios: [largo], resumen: [], predeterminado: null }).escenarios[0]).layout as any).yaxis.range[0]).toBeGreaterThan(0.5);
});
const figura = (cohorte: string, escenario: string) => ({ cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, n: 300, recaidas: 180,
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
km: { months: Array.from({ length: 61 }, (_, i) => i), S: Array.from({ length: 61 }, (_, i) => 1 - i / 200), low: Array.from({ length: 61 }, (_, i) => 1 - i / 190), high: Array.from({ length: 61 }, () => 1) },
@@ -26,7 +26,7 @@ export function figuraRecurrencia(f: FiguraRecurrencia, tema: Tema = 'claro'): P
const L = ETIQUETAS_RECURRENCIA, d = f.points.COMB, km = f.km;
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
const visibles = (t: number[], S: number[]) => S.filter((_, i) => t[i] <= f.months_max);
const minimo = Math.max(0, Math.floor((Math.min(...km.low, ...visibles(f.weibull.t, f.weibull.S), ...visibles(f.weibull_fractional.t, f.weibull_fractional.S), ...d.low) - 0.02) * 20) / 20);
const minimo = Math.max(0, Math.floor((Math.min(...visibles(km.months, km.low), ...visibles(f.weibull.t, f.weibull.S), ...visibles(f.weibull_fractional.t, f.weibull_fractional.S), ...d.low) - 0.02) * 20) / 20);
const data: Record<string, unknown>[] = [
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES_RECURRENCIA.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
+10 -2
View File
@@ -6,6 +6,7 @@ import {
Experiment,
ExperimentDetail,
ExperimentRequest,
NotebookTemplate,
ModelLineage,
ModelVersion,
PromotionCheck,
@@ -85,10 +86,17 @@ export class GovernanceApi {
return this.http.get<{ experiments: Experiment[] }>('/governance/experiments', { params: toParams(filters) });
}
/** Starts the notebook on the build in the background; answers with the run while it is still `en_curso`. */
/** The domain's notebooks kept in the code, each with the scenarios it can run for. */
notebookTemplates(domain: string): Observable<{ templates: NotebookTemplate[] }> {
return this.http.get<{ templates: NotebookTemplate[] }>('/governance/notebook-templates', { params: toParams({ domain }) });
}
/** Starts the notebook (an upload, or a template the API reads from the code) on the build in the background;
* answers with the run while it is still `en_curso`. */
runExperiment(request: ExperimentRequest): Observable<ExperimentDetail> {
const form = new FormData();
form.append('file', request.file);
if (request.template) form.append('template', request.template);
else if (request.file) form.append('file', request.file);
form.append('domain', request.domain);
form.append('scenario', request.scenario);
form.append('url', request.build.url);
+13 -1
View File
@@ -79,8 +79,20 @@ export interface ExperimentDetail extends Experiment {
error: string | null;
}
/** A notebook kept in the code (`models/<domain>/<scenario>/notebooks/`), and the scenarios it can run for. */
export interface NotebookTemplate {
id: string;
domain: Domain;
scenario: string;
name: string;
scenarios: string[];
title: string;
}
/** One of `file` (an upload) or `template` (a notebook kept in the code, by its id). */
export interface ExperimentRequest {
file: File;
file?: File | null;
template?: string | null;
domain: Domain;
scenario: string;
build: CohortBuildFile;
@@ -2,19 +2,39 @@
<mat-dialog-content class="content">
<p class="hint">
El notebook corre aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no
Elija un notebook del código (<code>models/&lt;dominio&gt;/&lt;escenario&gt;/notebooks/</code>) o suba uno. Corre
aislado en el servidor, sin red y con los datos de la cohorte que elija como única información: no
ve las bases de datos ni los demás archivos. Dentro usa <code>from models.notebook import experiment</code> para leer
la cohorte, cargar la versión elegida o entrenar; lo que entrene se registra como versión de desarrollo al terminar.
La corrida guarda el notebook, la página con sus resultados y con qué datos se corrió.
</p>
<div class="file">
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
</button>
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
</div>
<mat-button-toggle-group [value]="source()" (change)="source.set($event.value)" aria-label="Origen del notebook">
<mat-button-toggle value="plantilla" [disabled]="!templates().length">Del código</mat-button-toggle>
<mat-button-toggle value="archivo">Subir archivo</mat-button-toggle>
</mat-button-toggle-group>
@if (source() === 'plantilla') {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Notebook del código</mat-label>
<mat-select [ngModel]="template()" (ngModelChange)="setTemplate($event)" [compareWith]="sameTemplate">
@for (option of templates(); track option.id) {
<mat-option [value]="option">{{ templateLabel(option) }}</mat-option>
}
</mat-select>
@if (template(); as chosen) {
<mat-hint>Corre para: {{ chosen.scenarios.join(', ') }}</mat-hint>
}
</mat-form-field>
} @else {
<div class="file">
<button mat-stroked-button type="button" [disabled]="busy()" (click)="fileInput.click()">
<mat-icon aria-hidden="true">upload_file</mat-icon>Elegir notebook
</button>
<span class="file__name">{{ file()?.name ?? 'Ningún archivo (.ipynb)' }}</span>
<input #fileInput type="file" accept=".ipynb,application/x-ipynb+json" hidden (change)="pick($event)" />
</div>
}
<div class="grid">
<mat-form-field appearance="outline" subscriptSizing="dynamic">
@@ -31,6 +51,8 @@
<input matInput [ngModel]="scenario()" (ngModelChange)="setScenario($event)" placeholder="cin2_logistic" />
@if (scenario() && !scenarioValid()) {
<mat-error>Solo letras, números, guion y guion bajo.</mat-error>
} @else if (source() === 'plantilla' && template() && !notebookReady()) {
<mat-hint>Esta plantilla no corre para ese escenario.</mat-hint>
} @else {
<mat-hint>El de un modelo existente o uno nuevo para el experimento.</mat-hint>
}
@@ -2,18 +2,28 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotebookTemplate } from '../../api/governance.types';
import { NotebookRunDialog } from './notebook-run-dialog';
/**
* The dialog that uploads a notebook and runs it on a cohort build: it starts
* from a version's defaults, offers the domain's exported builds, and sends
* the build the person chose. The API is `HttpTestingController`; the dialog
* The dialog that runs a notebook on a cohort build, one kept in the code or an
* upload: it starts from a version's defaults, offers the domain's templates and
* exported builds, and sends the notebook and build the person chose. The API is `HttpTestingController`; the dialog
* reference is a stub that records how it closed.
*/
describe('NotebookRunDialog', () => {
let http: HttpTestingController;
const close = vi.fn();
const build = { url: 'cacu/cohorte_vigilancia', source: 'dbt', build: 4, datos_as_of: '2025-12-31', n_members: '10' };
const pim: NotebookTemplate = {
id: 'cacu/cin2_pim/reporte_subgrupos', domain: 'cacu', scenario: 'cin2_pim', name: 'reporte_subgrupos',
scenarios: ['cin2_pim', 'cin2_pim_post_colposcopy'], title: 'Riesgo acumulado de CIN2+ por combinación',
};
function templates(found: object[] = []) {
http.expectOne((r) => r.url === '/governance/notebook-templates' && r.params.get('domain') === 'cacu')
.flush({ templates: found });
}
function open(data: object) {
TestBed.configureTestingModule({
@@ -39,10 +49,12 @@ describe('NotebookRunDialog', () => {
it('sends the chosen build and version with the notebook, and closes with the run', () => {
// Fails if the form stops carrying the build's url, source and number, or drops the version it was opened with.
const fixture = open({ domain: 'cacu', scenario: 'cin2_logistic', version: '3' });
templates();
http.expectOne((r) => r.url === '/governance/cohort-files' && r.params.get('domain') === 'cacu').flush({ builds: [build] });
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
const dialog = fixture.componentInstance;
expect(dialog.ready()).toBe(false);
expect(dialog.source()).toBe('archivo'); // no templates in the domain: the upload is the only source
dialog.file.set(new File(['{}'], 'analisis.ipynb'));
expect(dialog.ready()).toBe(true);
@@ -60,6 +72,7 @@ describe('NotebookRunDialog', () => {
it('refuses a scenario that the API would reject', () => {
// Fails if `ready` stops checking the scenario's characters before uploading.
const fixture = open({});
templates();
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
const dialog = fixture.componentInstance;
dialog.file.set(new File(['{}'], 'a.ipynb'));
@@ -69,4 +82,33 @@ describe('NotebookRunDialog', () => {
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.ready()).toBe(true);
});
it('runs a template from the code for a scenario it serves, sending its id and no file', () => {
// Fails if choosing a template stops filling its scenario, the form sends a file with it, or a scenario the
// template doesn't serve is let through.
const fixture = open({});
templates([pim]);
http.expectOne((r) => r.url === '/governance/cohort-files').flush({ builds: [build] });
const dialog = fixture.componentInstance;
expect(dialog.source()).toBe('plantilla');
dialog.setTemplate(pim);
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.scenario()).toBe('cin2_pim');
expect(dialog.ready()).toBe(true);
dialog.setScenario('survival');
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
expect(dialog.ready()).toBe(false);
dialog.setScenario('cin2_pim_post_colposcopy');
http.expectOne((r) => r.url === '/governance/model-versions').flush({ model_versions: [] });
dialog.run();
const request = http.expectOne('/governance/experiments');
const form = request.request.body as FormData;
expect([form.get('template'), form.get('file'), form.get('scenario')]).toEqual([
'cacu/cin2_pim/reporte_subgrupos', null, 'cin2_pim_post_colposcopy',
]);
request.flush({ run_id: 'r2', status: 'en_curso' });
expect(close).toHaveBeenCalledWith(expect.objectContaining({ run_id: 'r2' }));
});
});
@@ -1,6 +1,7 @@
import { Component, computed, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
@@ -10,7 +11,7 @@ import { MatSelectModule } from '@angular/material/select';
import { Domain, apiErrorMessage } from '../../../connect/api/api.types';
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
import { GovernanceApi } from '../../api/governance.api';
import { CohortBuildFile, ExperimentDetail, ModelVersion } from '../../api/governance.types';
import { CohortBuildFile, ExperimentDetail, ModelVersion, NotebookTemplate } from '../../api/governance.types';
/** What the dialog starts with: a version's dialog passes its own domain, scenario and version. */
export interface NotebookRunDefaults {
@@ -21,15 +22,20 @@ export interface NotebookRunDefaults {
const SCENARIO = /^[\w-]{1,100}$/;
/** Where the notebook comes from: one kept in the code (a template) or an upload. */
export type NotebookSource = 'plantilla' | 'archivo';
/**
* Uploads a Jupyter notebook and runs it on a cohort build's file, optionally
* with a registered version to try. Closes with the run once it has started.
* Runs a Jupyter notebook on a cohort build's file, optionally with a registered
* version to try: one kept in the code (`models/<domain>/<scenario>/notebooks/`,
* for the scenarios it serves) or an upload. Closes with the run once it has started.
*/
@Component({
selector: 'app-notebook-run-dialog',
imports: [
FormsModule,
MatButtonModule,
MatButtonToggleModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -49,7 +55,10 @@ export class NotebookRunDialog {
readonly domain = signal<Domain>(this.defaults.domain ?? 'cacu');
readonly scenario = signal(this.defaults.scenario ?? '');
readonly version = signal<string>(this.defaults.version ?? '');
readonly source = signal<NotebookSource>('plantilla');
readonly file = signal<File | null>(null);
readonly templates = signal<NotebookTemplate[]>([]);
readonly template = signal<NotebookTemplate | null>(null);
readonly builds = signal<CohortBuildFile[]>([]);
readonly build = signal<CohortBuildFile | null>(null);
readonly versions = signal<ModelVersion[]>([]);
@@ -57,13 +66,34 @@ export class NotebookRunDialog {
readonly error = signal<string | null>(null);
readonly scenarioValid = computed(() => SCENARIO.test(this.scenario()));
readonly ready = computed(() => !!this.file() && !!this.build() && this.scenarioValid() && !this.busy());
/** The template serves the scenario typed, or the upload is chosen. */
readonly notebookReady = computed(() => {
if (this.source() === 'archivo') return !!this.file();
const template = this.template();
return !!template && template.scenarios.includes(this.scenario());
});
readonly ready = computed(() => this.notebookReady() && !!this.build() && this.scenarioValid() && !this.busy());
constructor() {
this.loadTemplates();
this.loadBuilds();
this.loadVersions();
}
templateLabel(template: NotebookTemplate): string {
return `${template.scenario}/${template.name} · ${template.title}`;
}
sameTemplate(a: NotebookTemplate | null, b: NotebookTemplate | null): boolean {
return !!a && !!b && a.id === b.id;
}
/** Choosing a template puts its scenario when the one typed isn't one it serves. */
setTemplate(template: NotebookTemplate | null): void {
this.template.set(template);
if (template && !template.scenarios.includes(this.scenario())) this.setScenario(template.scenario);
}
buildLabel(build: CohortBuildFile): string {
const members = build.n_members ? ` · ${build.n_members} miembros` : '';
const asOf = build.datos_as_of ? ` · datos al ${build.datos_as_of}` : '';
@@ -77,6 +107,7 @@ export class NotebookRunDialog {
setDomain(domain: Domain): void {
this.domain.set(domain);
this.version.set('');
this.loadTemplates();
this.loadBuilds();
this.loadVersions();
}
@@ -94,13 +125,13 @@ export class NotebookRunDialog {
}
run(): void {
const file = this.file();
const build = this.build();
if (!file || !build || !this.ready()) return;
if (!build || !this.ready()) return;
const notebook = this.source() === 'plantilla' ? { template: this.template()!.id } : { file: this.file() };
this.busy.set(true);
this.error.set(null);
this.api
.runExperiment({ file, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.runExperiment({ ...notebook, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.subscribe({
next: (run) => this.dialogRef.close(run),
error: (error) => {
@@ -110,6 +141,18 @@ export class NotebookRunDialog {
});
}
private loadTemplates(): void {
this.templates.set([]);
this.template.set(null);
this.api.notebookTemplates(this.domain()).subscribe({
next: ({ templates }) => {
this.templates.set(templates);
if (!templates.length) this.source.set('archivo');
},
error: () => this.templates.set([]),
});
}
private loadBuilds(): void {
this.builds.set([]);
this.build.set(null);