Compare commits

..

1 Commits

7 changed files with 36 additions and 149 deletions
@@ -7,10 +7,12 @@
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
@else {
<label class="selector">Escenario clínico
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
<select [value]="escenario() ?? ''" (change)="elegir($any($event.target).value)">
@if (escenario() === null) { <option value="" selected disabled>Elige un escenario…</option> }
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
</select>
</label>
@if (escenario() === null) { <p role="status">La paciente no pertenece a ningún escenario clínico con pacientes suficientes; elige uno para ver su curva.</p> }
@let l = lectura();
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
@@ -99,6 +99,18 @@ describe('Análisis de supervivencia', () => {
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
});
// Fails if a patient in no drawable scenario gets another subgroup's curve instead of a prompt to choose one.
it('draws nothing and asks to choose when the patient belongs to no scenario', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }], predeterminado: null }), consulta } }] });
const f = montar();
expect(consulta).not.toHaveBeenCalled();
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(0);
expect(texto(f)).toContain('no pertenece a ningún escenario clínico');
});
// Fails if choosing a scenario changes only the curve or only the label: the selector decides both at once, one scenario at a time.
it('changes the curve and the label together when another scenario is chosen, and never draws two', () => {
const f = montar();
+2 -10
View File
@@ -6,7 +6,6 @@ import {
Experiment,
ExperimentDetail,
ExperimentRequest,
NotebookTemplate,
ModelLineage,
ModelVersion,
PromotionCheck,
@@ -86,17 +85,10 @@ export class GovernanceApi {
return this.http.get<{ experiments: Experiment[] }>('/governance/experiments', { params: toParams(filters) });
}
/** 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`. */
/** Starts the notebook 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();
if (request.template) form.append('template', request.template);
else if (request.file) form.append('file', request.file);
form.append('file', request.file);
form.append('domain', request.domain);
form.append('scenario', request.scenario);
form.append('url', request.build.url);
+1 -13
View File
@@ -79,20 +79,8 @@ 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 | null;
template?: string | null;
file: File;
domain: Domain;
scenario: string;
build: CohortBuildFile;
@@ -2,39 +2,19 @@
<mat-dialog-content class="content">
<p class="hint">
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
El notebook 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>
<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="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">
@@ -51,8 +31,6 @@
<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,28 +2,18 @@ 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 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
* 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
* 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({
@@ -49,12 +39,10 @@ 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);
@@ -72,7 +60,6 @@ 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'));
@@ -82,33 +69,4 @@ 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,7 +1,6 @@
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';
@@ -11,7 +10,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, NotebookTemplate } from '../../api/governance.types';
import { CohortBuildFile, ExperimentDetail, ModelVersion } from '../../api/governance.types';
/** What the dialog starts with: a version's dialog passes its own domain, scenario and version. */
export interface NotebookRunDefaults {
@@ -22,20 +21,15 @@ 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';
/**
* 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.
* 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.
*/
@Component({
selector: 'app-notebook-run-dialog',
imports: [
FormsModule,
MatButtonModule,
MatButtonToggleModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
@@ -55,10 +49,7 @@ 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[]>([]);
@@ -66,34 +57,13 @@ export class NotebookRunDialog {
readonly error = signal<string | null>(null);
readonly scenarioValid = computed(() => SCENARIO.test(this.scenario()));
/** 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());
readonly ready = computed(() => !!this.file() && !!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}` : '';
@@ -107,7 +77,6 @@ export class NotebookRunDialog {
setDomain(domain: Domain): void {
this.domain.set(domain);
this.version.set('');
this.loadTemplates();
this.loadBuilds();
this.loadVersions();
}
@@ -125,13 +94,13 @@ export class NotebookRunDialog {
}
run(): void {
const file = this.file();
const build = this.build();
if (!build || !this.ready()) return;
const notebook = this.source() === 'plantilla' ? { template: this.template()!.id } : { file: this.file() };
if (!file || !build || !this.ready()) return;
this.busy.set(true);
this.error.set(null);
this.api
.runExperiment({ ...notebook, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.runExperiment({ file, domain: this.domain(), scenario: this.scenario(), build, version: this.version() || null })
.subscribe({
next: (run) => this.dialogRef.close(run),
error: (error) => {
@@ -141,18 +110,6 @@ 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);