Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bf04fa9a04 | |||
| 49b94b8f18 |
@@ -126,7 +126,7 @@ describe('Ficha y archivos de una fila con biopsia reportada y resultado descono
|
||||
const t = (card.nativeElement.textContent as string).replace(/\s+/g, ' ');
|
||||
expect(t).toContain('Resultado: No disponible'); expect(t).toContain('Fecha de reporte: 2025-02-15');
|
||||
expect(t).toContain('Categoría BI-RADS: BI-RADS 5'); expect(t).toContain('50 a 59 años');
|
||||
expect(t).toMatch(/Estatus de seguimiento\s*No disponible/); expect(t).toMatch(/Prioridad\s*No disponible/); expect(t).toMatch(/Días de mastografía a diagnóstico\s*No disponible/);
|
||||
expect(t).toMatch(/Estatus de seguimiento\s*No disponible/); expect(t).not.toMatch(/Prioridad|Días de mastografía a diagnóstico/);
|
||||
expect(t).not.toContain('Fecha de biopsia');
|
||||
const pdf = textos(camaPatientDocument(resumen, NOW, 'data:image/png;base64,AAAA'));
|
||||
expect(pdf).toContain('Fecha de reporte'); expect(pdf).not.toContain('Fecha de biopsia');
|
||||
|
||||
@@ -11,10 +11,7 @@
|
||||
<dl class="summary">
|
||||
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
|
||||
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
|
||||
<div><dt>Escenario clínico</dt><dd>{{ p.clinicalScenario ?? notAvailable }}</dd></div>
|
||||
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
|
||||
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
|
||||
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
|
||||
<div><dt>Estatus de seguimiento</dt><dd>{{ p.clinicalScenario ?? notAvailable }}</dd></div>
|
||||
</dl>
|
||||
</header>
|
||||
<div class="detail-grid">
|
||||
|
||||
@@ -68,8 +68,18 @@ describe('Ficha CaMa: componente', () => {
|
||||
const row = complete();
|
||||
montar(toCamaPatientSummary(row, '2026-10-20')!);
|
||||
const text = root().textContent!.replace(/\s+/g, ' ');
|
||||
for (const value of [`Paciente ${row['id_seudonimo']}`, 'Fecha de corte: 2026-10-20', String(row['estatus']), String(row['prioridad']), String(row['birads']),
|
||||
String(row['mastografia_fecha']), String(row['biopsia']), String(row['biopsia_fecha']), String(row['dias_mastografia_diagnostico'])]) expect(text).toContain(value);
|
||||
for (const value of [`Paciente ${row['id_seudonimo']}`, 'Fecha de corte: 2026-10-20', String(row['birads']),
|
||||
String(row['mastografia_fecha']), String(row['biopsia']), String(row['biopsia_fecha'])]) expect(text).toContain(value);
|
||||
});
|
||||
|
||||
// Fails if the "Estatus de seguimiento" label carries the row's follow-up status instead of the clinical scenario, or if the priority or the days to diagnosis come back.
|
||||
it('shows the clinical scenario as "Estatus de seguimiento" and not the status, priority or days to diagnosis', () => {
|
||||
montar({ ...toCamaPatientSummary(complete(), '2026-10-20')!, clinicalScenario: 'En observación', status: 'ESTATUS_DE_LA_FILA' });
|
||||
const labels = [...root().querySelectorAll('header dt')].map(dt => dt.textContent!.trim());
|
||||
expect(labels).toEqual(['Identificador seudónimo', 'Grupo de edad', 'Estatus de seguimiento']);
|
||||
expect(root().querySelector('header')!.textContent).toContain('En observación');
|
||||
expect(root().textContent).not.toContain('ESTATUS_DE_LA_FILA');
|
||||
for (const label of ['Escenario clínico', 'Prioridad', 'Días de mastografía a diagnóstico']) expect(root().textContent).not.toContain(label);
|
||||
});
|
||||
|
||||
// Fails if a missing value is left blank or invented instead of reading "No disponible".
|
||||
@@ -78,7 +88,6 @@ describe('Ficha CaMa: componente', () => {
|
||||
const text = root().textContent!;
|
||||
expect(text).toContain('Resultado: No disponible');
|
||||
expect(text).toContain('Fecha de biopsia: No disponible');
|
||||
expect(text).toContain('Días de mastografía a diagnóstico');
|
||||
});
|
||||
|
||||
// Fails if the cards or their subsections leave the order and the names of the specification: recurrence first, then death, each with
|
||||
|
||||
@@ -35,8 +35,10 @@ describe('Ficha CaMa: PDF individual', () => {
|
||||
it('prints each field of the record under its label', () => {
|
||||
const p = complete();
|
||||
const found = texts(definition(p)['content']);
|
||||
for (const t of [`Paciente ${p.patientId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis),
|
||||
'Categoría BI-RADS', 'Fecha de la mastografía', 'Resultado histopatológico', 'Fecha de biopsia', 'Días de mastografía a diagnóstico']) expect(found).toContain(t);
|
||||
for (const t of [`Paciente ${p.patientId}`, 'Fecha de corte: 2026-10-20', p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!,
|
||||
'Estatus de seguimiento', 'Categoría BI-RADS', 'Fecha de la mastografía', 'Resultado histopatológico', 'Fecha de biopsia']) expect(found).toContain(t);
|
||||
// The summary prints the clinical scenario under "Estatus de seguimiento" and leaves out the priority and the days to diagnosis.
|
||||
for (const t of ['Escenario clínico', 'Prioridad', 'Días de mastografía a diagnóstico']) expect(found).not.toContain(t);
|
||||
});
|
||||
|
||||
// Fails if a missing value is printed as something other than "No disponible".
|
||||
|
||||
@@ -21,10 +21,7 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo
|
||||
...section('Resumen', [
|
||||
[patient.idLabel, patient.patientId],
|
||||
['Grupo de edad', patient.ageGroup],
|
||||
['Escenario clínico', patient.clinicalScenario],
|
||||
['Estatus de seguimiento', patient.status],
|
||||
['Prioridad', patient.priority],
|
||||
['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis],
|
||||
['Estatus de seguimiento', patient.clinicalScenario],
|
||||
]),
|
||||
...section('Mastografía', [['Categoría BI-RADS', patient.birads], ['Fecha de la mastografía', patient.mammographyDate]]),
|
||||
...section('Histopatología', [['Resultado histopatológico', patient.histopathology], [patient.biopsyDateLabel ?? 'Fecha de biopsia', patient.biopsyDate]]),
|
||||
|
||||
@@ -8,15 +8,17 @@
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
@let riesgo = lectura.datos.riesgo;
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@if (dominio() === 'cama') {
|
||||
<h5>Modelo y evaluación</h5>
|
||||
<dl class="metadata">
|
||||
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
}
|
||||
@if (riesgo.horizontes.length) {
|
||||
<div class="risk-scroll" role="region" aria-label="Probabilidades por horizonte, tabla desplazable" tabindex="0">
|
||||
<table>
|
||||
|
||||
@@ -49,9 +49,9 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
// The model and evaluation block (model, version, index date, outcome, evaluation time, batch state) is not shown.
|
||||
for (const value of ['Modelo y evaluación', 'Versión del modelo', 'Desenlace', 'Evaluado en', 'Estado del lote', 'modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).not.toContain(value);
|
||||
}
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/);
|
||||
@@ -87,7 +87,6 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']);
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']);
|
||||
expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']);
|
||||
expect(root.textContent).toContain('Preliminar (preliminary)');
|
||||
});
|
||||
|
||||
it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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/<dominio>/<escenario>/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);
|
||||
|
||||
Reference in New Issue
Block a user