Compare commits
69 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 941ae15a3e | |||
| 410de1d3b7 | |||
| 0880181219 | |||
| ea6db36b23 | |||
| 06829a4498 | |||
| 7d50786ac2 | |||
| bde02109ab | |||
| 3e72063e3f | |||
| 200cb106e1 | |||
| 70646e64b6 | |||
| 8eac071778 | |||
| 7b8a4e8499 | |||
| 01e4406838 | |||
| dce29670a4 | |||
| 6fbf573999 | |||
| fe7f881ade | |||
| 3669aa9eae | |||
| 25c460f80e | |||
| 7b2eae2782 | |||
| fc77fd625e | |||
| 55f036b53a | |||
| 572b7561fa | |||
| bd3d6fb199 | |||
| 9ba7bdddb6 | |||
| 11e768893e | |||
| 1b45bc61d7 | |||
| c50c3a081e | |||
| 0be622c12d | |||
| c9eb68ee42 | |||
| ae2310754f | |||
| a4ddad5c8e | |||
| 55dd971a1f | |||
| a8bbdc88af | |||
| 5d65730b98 | |||
| 71e77f0c7e | |||
| 15ffeb3efe | |||
| 761b5b03bc | |||
| 22d1fda0f3 | |||
| f070d9f037 | |||
| 3853cc5522 | |||
| 9808701c46 | |||
| 0fdab3651c | |||
| 37fb292a4f | |||
| 1f6e2df051 | |||
| 122f71105a | |||
| 27e29804aa | |||
| 34de6e9348 | |||
| 29fa8def2a | |||
| 2d22409e1f | |||
| ec85cae5aa | |||
| b06ff5ce52 | |||
| f08b249eae | |||
| 0489475b86 | |||
| ec36df6a2c | |||
| dd94aba1eb | |||
| 449c67b19d | |||
| d6f7acc1fa | |||
| 5fa931d92d | |||
| bc15cc3e04 | |||
| c8bca59334 | |||
| c11575f656 | |||
| 28ff4605f3 | |||
| 2b855be12d | |||
| 92c5c69c2d | |||
| ee1c307d57 | |||
| e5526b9ec3 | |||
| 86b508cba8 | |||
| 04c8cbafd1 | |||
| 4c5bccb805 |
@@ -12,3 +12,6 @@ uv.lock
|
||||
mlflow.db
|
||||
mlruns/
|
||||
mlartifacts/
|
||||
|
||||
# Jupyter
|
||||
.ipynb_checkpoints/
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[submodule "tea"]
|
||||
path = libs/tea
|
||||
url = ssh://git@10.0.10.41:2222/alberto/tea.git
|
||||
@@ -2,20 +2,48 @@
|
||||
|
||||
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
|
||||
versiones en MLflow con requisitos de promoción, registro de predicciones y
|
||||
los trabajos de OCR de reportes. Las cohortes con que se entrena son los
|
||||
armados del kit de indicadores (`cohorte_armado`, en la base de cada
|
||||
dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa
|
||||
los trabajos de OCR de reportes. Las cohortes se definen solo en dbt
|
||||
(`Transformation/models/<dominio>/cohorts/`); el ciclo de la WebApi guarda un
|
||||
armado de ellas (`cohorte_armado`, en la base de cada dominio, por
|
||||
`models/cohorts/build.py`), y con ese armado se entrena y se estima. Las reglas
|
||||
que no caben en SQL son del modelo, sobre `cacu/cohorte_total`. Lee y escribe por los mismos repositorios de `Persistance` que usa
|
||||
WebApi.
|
||||
|
||||
| Módulo | Qué hace |
|
||||
|---|---|
|
||||
| `base.py` | `ScreeningModel`: la interfaz `train()`/`predict()` y `dataset()` para leer una tabla del dominio. |
|
||||
| `cacu.py`, `cama.py`, `tea.py` | Un modelo por dominio. Aún sin entrenar: `train` y `predict` lanzan `NotImplementedError`. |
|
||||
| `training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04). |
|
||||
| `registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
|
||||
| `prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
|
||||
| `__main__.py` | La línea de comandos: `python -m models <comando>`. Cada área agrega ahí sus subcomandos. |
|
||||
| `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). |
|
||||
| `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`) and their hashes (`file_sha256`, `table_sha256`, `cohort_reference`), dbt's manifest (`read_queries`), Persistance repositories, the risk batches, and the cohort sources a model trains and estimates on: `KitBuild`, a kit build read now from the domain's database (nothing written), or `CohortFile`, an exported file, behind one contract (`frame`, `lineage`, `reference`). |
|
||||
| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the code's version (the installed `models` package, `code_version`), a model's hash (`model_sha`), and `matches`, the one rule for "already done". |
|
||||
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `run_files`/`run_file` list and download a run's files (a folder as a zip). |
|
||||
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03, y ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias `produccion`. `artifacts`/`artifact` listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). |
|
||||
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
||||
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||
| `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. |
|
||||
| `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. |
|
||||
| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/<n>.parquet` and writes only when its rows change. The timeline comes from dbt's view `<domain>_linea_de_tiempo`. |
|
||||
| `cohorts list`, `cohorts show` | `python -m models cohorts list cacu cohorte_vigilancia [--source kit\|dbt]` lists the builds of both sources, newest first, and whether each has its file (dbt's from their files alone); `cohorts show … --source kit\|dbt --build N` prints one build's file, hash, parameters, rules and attrition as JSON (`io/storage.py`: `list_builds`, `describe_build`). |
|
||||
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member and horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
|
||||
| `reports/` (`rendering.py`, `eda.py`) | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `<scenario>/notebooks/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). Rendering: Runs a notebook and renders its page. Renderers are classes (`RENDERERS`, `register_renderer`): `quarto` and `jupyter` (`nbclient` + `nbconvert`, the `notebooks` extra). `NOTEBOOK_RENDERER` picks one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT` limits each cell (1800 s). |
|
||||
| `reports/experiment.py` | A notebook uploaded to the platform, run on one exported cohort build as a run of `<domain>-<scenario>/experimentos`: the notebook, its page, what was imported from it (`importado.json`), `error.txt` if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (`sandbox`). `start` and `execute` are separate so the WebApi runs it in the background. |
|
||||
| `reports/notebook_jobs.py` | Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: `contenedor` leaves the job in `NOTEBOOK_JOBS_DIR` for the runner (`python -m models notebooks serve`, the `notebooks` container: no network, read-only, unprivileged, only that folder); `local` runs it in this process, unisolated, for development. |
|
||||
| `reports/notebook_import.py` | Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed `modelo_sha`, never with an alias; refuses symbolic links and anything outside the job folder. |
|
||||
| `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `<domain>-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. |
|
||||
| `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
|
||||
| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. |
|
||||
| `annotations.py` | Validators a dataflow puts on its nodes, with no I/O: `@checked_frame(schema)`, a pandera check whose failure names columns and counts, never values. |
|
||||
| `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. |
|
||||
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit and its metrics. |
|
||||
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (`horizons_years`, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. `model.toml` (names, `modules`: its `model.py` and `steps/model_fitting.py`, and `[config]`) and `model.py` (the dataflow to `labelled_members`, and `fitted_model`: a scikit-learn `Pipeline` that takes the long frame). Its routines' records (ML-01a: `sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`) are nodes too, and the saver writes them; `train.py` only delegates to `dags/training.py`. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--read db|file] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]`, by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
|
||||
| `cacu/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull or I-spline incidence, `likelihood.py`), one mixture per HPV stratum, fitted to each member's code and interval; the clinical settings (windows, known-negative results, KPNC's cytology categories, the incidence family) in `model.toml`. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
|
||||
| `cacu/cin2_pim_post_colposcopy/`, `cacu/cin2_pim_post_treatment/` | `cin2_pim`'s dataflow on the post-colposcopy and post-treatment cohorts (KPNC's scenarios 4 and 5): only a `model.toml`, with KPNC's three post-colposcopy cytology groups and, after colposcopy, the referral grade (`history`). |
|
||||
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `<escenario>/notebooks/`, fuera del paquete instalado. |
|
||||
| `tea/eeg/` | TEA's EEG analysis on one EDF, with the `tea` library (`libs/tea`, a submodule installed editable): `model.toml` maps each `MetricaEeg` code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); `analyze.measure` runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; `baselines.Baselines` compares a value with its age baseline in production (`tea-eeg-<biomarker>[-<stage>]`): z, -1/0/+1 and the curve's p5/median/p95 at the age. |
|
||||
| `tea/eeg/train.py`, `tea/eeg/model.py` | TEA's age baselines: `python -m models run tea eeg --train [--promote] [--environment prod]` lists the reference cohort (`[reference]` of `model.toml`: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the `eeg-reference` extra), measures each study with the analysis's own unit of work (`analyze.reference`), and trains each scenario (biomarker and sleep stage) with the library, registered as `tea-eeg-<biomarker>[-<stage>]` through `tea.serving.log_biomarker` and tagged with what promotion checks: environment, the reference cohort (`cohort.source = referencia`, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI`); with a remote scheduler (`DASK_SCHEDULER_ADDRESS`), the workers need `models` and `tea` installed. |
|
||||
| `tea/eeg/reference.py`, `tea/eeg/bundle.py` | Training the baselines where the EEGs live and shipping only the result. `models run tea eeg --train --reference-dir DIR [--reference-ages edades.csv] [--reference-name NAME] [--line-hz 60]` trains on a folder of EDFs on this machine (ages from the table's `archivo` and `edad_meses` or `edad_anos`, or from each EDF header); file names stay in the listing, keyed by position. `models tea export-baselines --out baselines.zip [--environment prod] [--production]` writes every scenario's trained module, plan, routine records, metrics and promotion tags, with a SHA-256 manifest, after the library's privacy guard; `models tea import-baselines baselines.zip` checks the manifest, accepts only the module class the platform runs for each scenario, requires the trained module's hash, and registers new versions with the same tags (an already-registered module is kept). Promotion still waits for the three reports. |
|
||||
| `eeg_analysis.py` | The EEG analysis against TEA's database: the pending EEGs (an EDF never analysed, or analysed with another plan, other module versions or other baselines), the batch (`cluster`: this process, a LocalCluster or `DASK_SCHEDULER_ADDRESS`), each result written to `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo` with ids that survive a re-analysis, and one governance `ExtractionRun` per EEG. `python -m models tea analyze [--all] [--limit N] [--cluster auto\|local\|remote\|sync]`. |
|
||||
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
||||
| `export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
|
||||
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
||||
|
||||
MLflow se configura con sus propias variables (`MLFLOW_TRACKING_URI`).
|
||||
`MLFLOW_ARTIFACT_ROOT`, si existe, es la carpeta donde los experimentos nuevos
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
# Codificación de la línea de tiempo para el modelo prevalencia–incidencia
|
||||
|
||||
Cómo la historia de cada paciente se resume en un código $C$ y un intervalo $(L, R]$, qué factor aporta a la
|
||||
verosimilitud y en qué columnas del *Enrollment table* de KPNC cae. La codificación la hace
|
||||
`models.cacu.cin2_pim.model.interval_coded_members`; cada ejemplo de abajo tiene su prueba unitaria en
|
||||
`tests/cacu/test_cin2_pim.py` (`test_patient_1_…` a `test_patient_6_…`, más VPH−/ASC-US como negativo y
|
||||
VPH+/NILM como desconocido).
|
||||
|
||||
## Modelo
|
||||
|
||||
- $\pi(x) = \operatorname{expit}(x^\top\theta)$: probabilidad de NIC2+ en la visita índice (prevalencia, logística).
|
||||
- $S(t \mid z) = \exp\{-\Lambda_0(t)\, e^{z^\top\beta}\}$: supervivencia libre de NIC2+ incidente (riesgos
|
||||
proporcionales), con $\Lambda_0$ Weibull, $(t/\lambda)^k$, o los I-splines de PIMixture, $\sum_j e^{\gamma_j} I_j(t)$
|
||||
(`incidence` en `model.toml`). Una mezcla por estrato (`strata`: VPH en el tamizaje,
|
||||
grado de la referencia después de colposcopía, ninguno después de tratamiento), con la citología índice en las
|
||||
categorías de KPNC.
|
||||
- Riesgo acumulado: $CR(t) = \pi + (1-\pi)\,[1 - S(t)]$.
|
||||
|
||||
El tiempo se cuenta en años desde la visita índice $T_0$.
|
||||
|
||||
## Reglas de codificación
|
||||
|
||||
- $R$: fecha de la **primera biopsia NIC2+** (o $\infty$ si no hay).
|
||||
- $L$: fecha del **último hallazgo libre de NIC2+ antes de $R$**: una biopsia menor a NIC2+, o una visita con
|
||||
visita con VPH negativo y citología NILM o ASC-US (el negativo sin histología de KPNC; `known_negative` en
|
||||
`model.toml`). Una prueba positiva sin histología (VPH+, o LSIL o peor) deja el estado desconocido. Si cae dentro
|
||||
de la ventana basal (`prevalent_window_months`), $L = 0$.
|
||||
- $C = 1$ si $R$ cae dentro de la ventana basal; $C = 0$ si hubo al menos un hallazgo libre; si no, $C = -999$.
|
||||
- El seguimiento sin prueba no cuenta: nadie se considera libre hasta el corte de datos, solo hasta su último negativo.
|
||||
|
||||
## Factor de verosimilitud por paciente
|
||||
|
||||
| $C$ | $(L, R]$ | Factor $\mathcal{L}_i$ | Logística | Incidencia |
|
||||
|---|---|---|---|---|
|
||||
| 1 | $(0, 0]$ | $\pi$ | caso | — |
|
||||
| 0 | $(L, R]$, $R<\infty$ | $(1-\pi)\,[S(L) - S(R)]$ | control | censura por intervalo |
|
||||
| 0 | $(L, \infty)$ | $(1-\pi)\,S(L)$ | control | censura derecha en $L$ ($L=0$: nada) |
|
||||
| −999 | $(0, R]$ | $\pi + (1-\pi)\,[1 - S(R)]$ | latente | latente |
|
||||
| −999 | $(0, \infty)$ | $1$ | — | — |
|
||||
|
||||
Con $C$ conocido el logaritmo se separa en una logística y un modelo de supervivencia con censura por intervalo:
|
||||
|
||||
$$
|
||||
\ell = \underbrace{\sum_{C=1}\log\pi + \sum_{C=0}\log(1-\pi)}_{\text{logística}}
|
||||
+ \underbrace{\sum_{C=0}\log[S(L)-S(R)]}_{\text{incidencia}}
|
||||
+ \sum_{C=-999}\log\{\pi + (1-\pi)[1-S(R)]\}.
|
||||
$$
|
||||
|
||||
Solo los desconocidos acoplan las dos partes. La probabilidad posterior de que un desconocido diagnosticado en $R$
|
||||
fuera prevalente es $w = \pi / \{\pi + (1-\pi)[1-S(R)]\}$.
|
||||
|
||||
### Por qué varias visitas dan un solo factor
|
||||
|
||||
Con enfermedad absorbente (no regresa), negativos verdaderos (sensibilidad 1) y calendario de visitas no informativo,
|
||||
para negativos en $t_1 < \dots < L$ y NIC2+ en $R$:
|
||||
|
||||
$$
|
||||
P(\text{neg } t_1,\dots,\text{neg } L,\ \text{pos } R) = P(T > L,\ T \le R) = S(L) - S(R).
|
||||
$$
|
||||
|
||||
El último negativo implica todos los anteriores. Si la sensibilidad es menor que 1 o la lesión puede regresar, cada
|
||||
visita aporta su propio factor (verosimilitud con filtro hacia adelante, como en el modelo generativo de `bayes-pim`).
|
||||
|
||||
## Ejemplos
|
||||
|
||||
Todas las pacientes tienen ASC-US/VPH+ en $T_0$, así que entran en la celda **VPH+ / ASC-US** del Enrollment table
|
||||
(la celda la define el resultado índice; visitas posteriores no crean otra fila en esta tabla).
|
||||
|
||||
| Paciente | Historia | $(C, L, R]$ | Factor | Logística | Incidencia | Columnas del Excel |
|
||||
|---|---|---|---|---|---|---|
|
||||
| 1 | $T_1$ (1 mes): colposcopía, NIC3 | $(1, 0, 0]$ | $\pi$ | caso | — | n, informativa, caso, prevalente |
|
||||
| 2 | $T_1$: biopsias normales; $T_2$ (1 año): cotest negativo; $T_3$: ASC-US/VPH+; $T_4$: NIC3 | $(0, T_2, T_4]$ | $(1-\pi)[S(T_2)-S(T_4)]$ | control | intervalo $(T_2, T_4]$ | n, informativa, caso, incidente |
|
||||
| 3 | Colposcopía omitida; $T_1$: ASC-US/VPH+; $T_2$: NIC3 | $(-999, 0, T_2]$ | $\pi + (1-\pi)[1-S(T_2)]$ | latente (peso $w$) | latente (peso $1-w$) | n, informativa, caso, desconocido |
|
||||
| 4 | Colposcopía omitida; $T_1$ (1 año): cotest negativo | $(0, T_1, \infty)$ | $(1-\pi)\,S(T_1)$ | control | censura derecha en $T_1$ | n, informativa |
|
||||
| 5 | $T_1$ (1 mes): biopsias normales; sin más visitas | $(0, 0, \infty)$ | $1-\pi$ | control | — | n, informativa |
|
||||
| 6 | Colposcopía omitida; no regresa | $(-999, 0, \infty)$ | $1$ | — | — | n |
|
||||
|
||||
Prevalente, incidente y desconocido reparten solo a los **casos**; las no-caso informativas (4 y 5) no tienen
|
||||
columna propia.
|
||||
|
||||
Notas:
|
||||
|
||||
- **Paciente 2.** El ASC-US/VPH+ de $T_3$ no es un negativo: la lesión pudo existir desde $T_3$. La biopsia normal de
|
||||
$T_1$ queda implicada por el negativo de $T_2$.
|
||||
- **Paciente 3.** No es $L = R = T_2$ (eso diría que la lesión apareció justo en $T_2$). Es censura izquierda en
|
||||
$T_2$: $T \le T_2$, incluida la masa en cero (prevalente).
|
||||
- **Paciente 4.** Depende de que la lesión no regrese: razonable para NIC3+, discutible para NIC2 (que regresa con
|
||||
frecuencia), y de que el cotest negativo sea verdadero. $R = \infty$; el $-999$ es el código de $C$, no de $R$.
|
||||
- **Paciente 5.** El negativo cae en la ventana basal, $L = 0$ y $S(0) = 1$: solo informa la prevalencia.
|
||||
- **Paciente 6.** No aporta, siempre que la pérdida de seguimiento sea no informativa (MAR); si quienes omiten la
|
||||
colposcopía tienen otro riesgo, el modelo no lo detecta.
|
||||
|
||||
## Protocolo clínico de KPNC y definiciones de la tabla
|
||||
|
||||
Cheung LC, Egemen D, Chen X, et al. *2019 ASCCP Risk-Based Management Consensus Guidelines: Methods for Risk
|
||||
Estimation, Recommended Management, and Validation*. J Low Genit Tract Dis 2020;24(2):90–101.
|
||||
doi:10.1097/LGT.0000000000000528 (PMC7147416). Las tablas de riesgo están en Egemen D, et al., J Low Genit Tract Dis
|
||||
2020;24(2):132–143, doi:10.1097/LGT.0000000000000529, y las de genotipificación (VPH16/18) en Demarco M, et al., J Low
|
||||
Genit Tract Dis 2020;24(2):144–147, doi:10.1097/LGT.0000000000000530.
|
||||
|
||||
**Protocolo** (sección *Screening Tests and Clinical Management in the KPNC*):
|
||||
|
||||
> "Patients with cytologic abnormalities were referred to colposcopy per Kaiser guidelines, which closely resembled US
|
||||
> consensus recommendations. However, those without abnormalities, specifically patients who tested HPV negative/NILM
|
||||
> (cotest negative) were asked to return for testing in 3 years. […] Patients with HPV-negative/ASC-US or
|
||||
> HPV-positive/NILM results were monitored annually and referred to colposcopy for either a subsequent abnormal
|
||||
> cytology result or HPV positivity (after 2005)."
|
||||
|
||||
Cotest (HC2 + citología) desde 2003 en ≥ 30 años, desde 2013 en 25–29; tratamiento de NIC2+ con LEEP.
|
||||
|
||||
**Qué mide el riesgo** (sección *Risk Estimation and Definition of Intervals…*):
|
||||
|
||||
> "The CIN 2+ and CIN 3+ risks represent precancers and cancers that are detectable through colposcopy with multiple
|
||||
> biopsies (not just targeted to the single worst appearing region)."
|
||||
|
||||
**Definiciones de prevalente, incidente y desconocido** (misma sección):
|
||||
|
||||
> "We define prevalent CIN 3+ as CIN 3+ detected after colposcopic referral because of the baseline (current) test
|
||||
> results. We define a patient as having <CIN 3 at a visit if the diagnosis was either (1) directly confirmed through
|
||||
> histopathology or, in the absence of histopathologic outcomes, (2) if neither HPV nor cytology tests were positive
|
||||
> (i.e., HPV negative/NILM or HPV negative/ASC-US). […] patients with positive test results (HPV-positive or ≥LSIL
|
||||
> cytology results), but without histopathologic outcomes or a future <CIN 3 to rule out CIN 3+, are considered to
|
||||
> have unknown (in statistical terms, "latent") histologic status at that screen."
|
||||
|
||||
> "(1) prevalent (left-censored at the current test), (2) incident (interval-censored between the last result <CIN 3
|
||||
> and the time of CIN 3+ detection), or (3) unknown prevalent or incident (CIN 3+ detected in follow-up but cannot rule
|
||||
> out disease prevalence). Patients who never had CIN 3+ detected were considered right censored at the time of the
|
||||
> last <CIN 3 visit. Individuals who were never defined as <CIN 3 or CIN 3+ at any time points did not contribute to
|
||||
> risk estimation."
|
||||
|
||||
Ejemplos de historias codificadas: apéndice C (material suplementario) del mismo artículo.
|
||||
|
||||
**Supuestos declarados** (Discusión): (1) VPH−/NILM y VPH−/ASC-US son <NIC3; (2) la histopatología es correcta;
|
||||
(3) el NIC3+ diagnosticado no regresa; (4) censura independiente y no informativa; (5) que un caso de seguimiento sea
|
||||
prevalente o incidente depende solo de covariables conocidas (MAR).
|
||||
|
||||
**Genotipificación.** VPH16/18 solo se midió en una submuestra en dos fases (estudio PaP); se ponderó cada paciente
|
||||
por el inverso de su fracción de muestreo ("survey weights") para reconstituir la cohorte.
|
||||
|
||||
### Diferencias con nuestro protocolo
|
||||
|
||||
- **Biopsia.** KPNC define el riesgo respecto a colposcopía con biopsias múltiples. Aquí solo se biopsia si la
|
||||
impresión colposcópica es LIEBG+. Una colposcopía con impresión normal y sin biopsia no es "<CIN 3 confirmado por
|
||||
histopatología": bajo las definiciones de KPNC la visita queda **desconocida**, no negativa. Tratarla como negativa
|
||||
exige modelar la sensibilidad de la impresión colposcópica (modelo por visita). Además, el riesgo "inmediato" que
|
||||
estimemos es el detectable con biopsia dirigida, menor que el de KPNC: una razón O/E < 1 frente a sus tablas no
|
||||
significa por sí sola menor riesgo.
|
||||
- **Negativo sin histología.** Alineado con KPNC (2026-11-13): VPH−/NILM y VPH−/ASC-US, en la basal y en el
|
||||
seguimiento, en `models-pim` (`known_negative`) y en la simulación de `bayes-pim` (`cells.NEGATIVE_CYTOLOGY`,
|
||||
`generative.pim_codes`). Antes solo NILM/VPH−; la simulación además contaba como negativo un resultado "leve"
|
||||
del seguimiento (VPH+/NILM, VPH−/LSIL), que ahora deja el estado desconocido.
|
||||
- **Genotipificación.** Nuestras submuestras con VPH16/18 no vienen de un diseño con fracciones conocidas: la
|
||||
probabilidad de estar tipificada (por unidad, periodo, laboratorio, resultado) tendría que estimarse, y el IPW con
|
||||
pesos estimados (que Hyun et al. 2017 contemplan) solo corrige si la tipificación es MAR dadas esas variables.
|
||||
|
||||
## Referencia y estimación
|
||||
|
||||
Hyun N, Cheung LC, Pan Q, Schiffman M, Katki HA. *Flexible risk prediction models for left or interval-censored data
|
||||
from electronic health records*. Ann Appl Stat 2017;11(2):1063–1084. doi:10.1214/17-AOAS1036.
|
||||
|
||||
- Los desconocidos se tratan **dentro de la verosimilitud** como $C$ faltante bajo MAR: su factor es la mezcla de la
|
||||
tabla y el mecanismo de faltante es ignorable. No se imputan ni se ponderan.
|
||||
- El **IPW** del artículo es para otra cosa: la tipificación de VPH se hizo solo en una submuestra estratificada en dos
|
||||
fases (9,258 de 33,295 mujeres), y cada mujer de la submuestra se pondera por el inverso de su probabilidad de
|
||||
inclusión para representar a la cohorte. Sin submuestreo, todos los pesos valen 1 y se recupera la verosimilitud de
|
||||
arriba.
|
||||
- El **algoritmo iterativo** es el del estimador semiparamétrico (logística-Cox con $\Lambda$ no paramétrica): alterna
|
||||
(i) $\Lambda$ con el *iterative convex minorant* (ICM) dados los coeficientes y (ii) los coeficientes
|
||||
$(\theta, \beta)$ con IRLS dado $\Lambda$, hasta converger. El modelo débilmente paramétrico ($\Lambda$ con B-splines
|
||||
integrados) se ajusta con Newton–Raphson. Nuestro Weibull maximiza la misma verosimilitud directamente.
|
||||
- Supuestos que el propio artículo declara: enfermedad progresiva (sin regresión) y verificación perfecta del
|
||||
desenlace; ambos se relajan solo con un modelo por visita.
|
||||
File diff suppressed because one or more lines are too long
Submodule
+1
Submodule libs/tea added at 05ee02990c
@@ -0,0 +1,552 @@
|
||||
"""The package's command line: `python -m models <command>`.
|
||||
|
||||
Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit) belong inside the
|
||||
command that needs them, so `--help` stays immediate.
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
|
||||
|
||||
def _show_help(parser: argparse.ArgumentParser) -> int:
|
||||
"""A command without actions yet shows its help and fails, rather than appearing to have run."""
|
||||
parser.print_help()
|
||||
return 2
|
||||
|
||||
|
||||
def _scenario(args: argparse.Namespace):
|
||||
"""The scenario's `model.toml`; `None` and a message on stderr if there's no such model."""
|
||||
from models.dags.training import Scenario
|
||||
|
||||
try:
|
||||
return Scenario.load(args.domain, args.scenario)
|
||||
except LookupError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _own_steps(args: argparse.Namespace):
|
||||
"""A scenario that isn't trained on a cohort build runs its own steps: its `model.run_steps`, or `None`."""
|
||||
from importlib import import_module
|
||||
|
||||
try:
|
||||
model = import_module(f"models.{args.domain}.{args.scenario}.model")
|
||||
except ModuleNotFoundError:
|
||||
return None
|
||||
return getattr(model, "run_steps", None)
|
||||
|
||||
|
||||
def _cohort_file(args: argparse.Namespace, scenario):
|
||||
"""The build's exported file; `None` and a message on stderr if it's missing."""
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.storage import cohorts_root, dbt_build_path, find_cohort_file, latest_dbt_build
|
||||
|
||||
url = scenario.cohort
|
||||
command = f"python -m models cohorts export {url.replace('/', ' ')}" + (" --source dbt" if args.source == "dbt" else "")
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
if args.source == "kit":
|
||||
return find_cohort_file(root, url, args.armado)
|
||||
if args.armado is not None:
|
||||
if not (path := dbt_build_path(root, url, args.armado)).exists():
|
||||
raise FileNotFoundError(f"dbt build {args.armado} of {url} isn't exported: no {path}")
|
||||
return path
|
||||
if not (latest := latest_dbt_build(root, url)):
|
||||
raise FileNotFoundError(f"no exported dbt builds of {url} under {root}")
|
||||
return latest[1]
|
||||
except (FileNotFoundError, ValueError) as error:
|
||||
print(f"{error}: export it with `{command}`", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def _cohort_source(args: argparse.Namespace, scenario):
|
||||
"""Where the build's rows come from: a kit build from the database (`--read db`, the default), or an exported
|
||||
file (`--read file`, and always for dbt's builds, which only exist as files). `None` and a message if missing."""
|
||||
from models.io.storage import CohortFile, KitBuild
|
||||
|
||||
if args.source == "kit" and getattr(args, "read", "file") == "db":
|
||||
from importlib import import_module
|
||||
|
||||
cohorts = import_module(f"persistance.{args.domain}").cohort_repository
|
||||
build_id = args.armado if args.armado is not None else cohorts.latest_build(scenario.cohort)
|
||||
if build_id is None:
|
||||
print(f"no kit builds of {scenario.cohort}", file=sys.stderr)
|
||||
return None
|
||||
return KitBuild(args.domain, build_id, cohorts=cohorts)
|
||||
path = _cohort_file(args, scenario)
|
||||
return CohortFile(path) if path else None
|
||||
|
||||
|
||||
def _describe(source) -> str:
|
||||
return str(getattr(source, "path", None) or f"kit build {source.build_id}")
|
||||
|
||||
|
||||
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
"""Trains the model on the build, always as a new version."""
|
||||
if args.environment == "prod" and args.armado is None:
|
||||
parser.error("a prod run names its cohort build: --build (ML-03)")
|
||||
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
|
||||
return 1
|
||||
from models.dags.training import train
|
||||
|
||||
print(f"{args.domain}/{args.scenario} version {train(scenario, source, args.environment.upper())}, "
|
||||
f"from {_describe(source)}")
|
||||
return 0
|
||||
|
||||
|
||||
def _estimate_step(args: argparse.Namespace, scenario, source) -> int:
|
||||
from models.dags.estimation import estimate
|
||||
|
||||
try:
|
||||
resolved, written = estimate(scenario, source, args.output, args.version)
|
||||
except LookupError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {_describe(source)}, "
|
||||
f"to {args.output}")
|
||||
return 0
|
||||
|
||||
|
||||
def _store_step(args: argparse.Namespace, estimate_path) -> int:
|
||||
from models.pipelines.store_risks import store_estimate
|
||||
|
||||
try:
|
||||
batch, written = store_estimate(estimate_path, args.domain)
|
||||
except (LookupError, ValueError, FileNotFoundError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'stored' if written else 'already stored'}: batch {batch}, from {estimate_path}")
|
||||
return 0
|
||||
|
||||
|
||||
def _store(args: argparse.Namespace) -> int:
|
||||
"""Stores an estimate file as a batch of risks in the domain's database."""
|
||||
return _store_step(args, args.input)
|
||||
|
||||
|
||||
def _report_eda(args: argparse.Namespace) -> int:
|
||||
"""Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report."""
|
||||
from pathlib import Path
|
||||
|
||||
from models.reports.eda import report_eda
|
||||
from models.reports.rendering import RenderError
|
||||
|
||||
if not (scenario := _scenario(args)) or not (path := _cohort_file(args, scenario)):
|
||||
return 1
|
||||
notebook = Path(args.notebook) if args.notebook else scenario.folder / "notebooks" / "01_eda.ipynb"
|
||||
if not notebook.exists():
|
||||
print(f"no notebook at {notebook}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
run_id, written = report_eda(notebook, path, args.domain, args.scenario, kernel=args.kernel)
|
||||
except RenderError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'reported' if written else 'already reported'}: run {run_id}, {notebook.name} on {path}")
|
||||
return 0
|
||||
|
||||
|
||||
def _serve_notebooks(args: argparse.Namespace) -> int:
|
||||
"""The runner container's loop (`models.reports.notebook_jobs.serve`)."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from models.reports.notebook_jobs import JOBS_DIR_ENV, serve
|
||||
|
||||
folder = args.jobs or os.environ.get(JOBS_DIR_ENV)
|
||||
if not folder:
|
||||
print(f"no jobs folder: pass --jobs or set {JOBS_DIR_ENV}", file=sys.stderr)
|
||||
return 2
|
||||
serve(Path(folder), once=args.once)
|
||||
return 0
|
||||
|
||||
|
||||
def _tea_analyze(args: argparse.Namespace) -> int:
|
||||
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
|
||||
from models.eeg_analysis import analyze_pending
|
||||
|
||||
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster)
|
||||
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
|
||||
return 1 if s.failed else 0
|
||||
|
||||
|
||||
def _tea_export_baselines(args: argparse.Namespace) -> int:
|
||||
"""The trained age baselines as one bundle (`models.tea.eeg.bundle`)."""
|
||||
from models.tea.eeg.bundle import BundleError, export
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
try:
|
||||
done = export(settings(), args.out, environment=args.environment.upper(), production=args.production)
|
||||
except BundleError as error:
|
||||
print(f"not exported: {error}", file=sys.stderr)
|
||||
return 1
|
||||
for scenario, version in done.versions.items():
|
||||
print(f"{scenario}: version {version}")
|
||||
print(f"written: {done.path} (sha256 {done.sha256})")
|
||||
return 0
|
||||
|
||||
|
||||
def _tea_import_baselines(args: argparse.Namespace) -> int:
|
||||
"""The age baselines of a bundle, registered (`models.tea.eeg.bundle`)."""
|
||||
from models.tea.eeg.bundle import BundleError, import_
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
try:
|
||||
done = import_(settings(), args.bundle)
|
||||
except BundleError as error:
|
||||
print(f"not imported: {error}", file=sys.stderr)
|
||||
return 1
|
||||
for scenario, (version, new) in done.items():
|
||||
print(f"{scenario}: {'imported as' if new else 'already registered as'} version {version}")
|
||||
return 0
|
||||
|
||||
|
||||
def _estimate(args: argparse.Namespace) -> int:
|
||||
"""Scores the build with a registered version and writes the output file."""
|
||||
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
|
||||
return 1
|
||||
return _estimate_step(args, scenario, source)
|
||||
|
||||
|
||||
def _promote_step(args: argparse.Namespace, version: str) -> int:
|
||||
"""Promotes through the same gate the WebApi's promote route uses (MLD-01/01b):
|
||||
a version missing its checklist (validation reports, routine records, a saved
|
||||
model) is rejected here exactly as it would be there, rather than set directly."""
|
||||
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
|
||||
from mlflow import MlflowException
|
||||
|
||||
name = registered_name(args.domain, args.scenario)
|
||||
try:
|
||||
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
|
||||
except MlflowException:
|
||||
current = None
|
||||
if str(current) == str(version):
|
||||
print(f"already in production: version {version}")
|
||||
return 0
|
||||
try:
|
||||
registry.promote(args.domain, args.scenario, version)
|
||||
except PromotionBlocked as blocked:
|
||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
|
||||
print(f"not promoted, missing: {failed}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"in production: version {version}")
|
||||
return 0
|
||||
|
||||
|
||||
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
|
||||
if not (args.export or args.train or args.promote or args.estimate or args.store):
|
||||
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
|
||||
if (own := _own_steps(args)) is not None:
|
||||
return own(args)
|
||||
if (args.estimate or args.store) and not args.output:
|
||||
parser.error("--estimate and --store need --output")
|
||||
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
|
||||
parser.error("a prod run names its cohort build: --build (ML-03)")
|
||||
if args.export and args.source == "dbt" and not args.manifest:
|
||||
parser.error("--export with --source dbt needs --manifest")
|
||||
if args.export and args.source == "dbt" and args.armado is not None:
|
||||
parser.error("a dbt build is numbered when it's exported: --build can't go with --export --source dbt")
|
||||
if args.train and args.version:
|
||||
parser.error("--version names an existing version: it can't go with --train")
|
||||
if not (scenario := _scenario(args)):
|
||||
return 1
|
||||
|
||||
if args.export:
|
||||
args.read = "file"
|
||||
cohort = scenario.cohort.split("/", 1)[1]
|
||||
export = argparse.Namespace(domain=args.domain, cohort=cohort, source=args.source, build=args.armado,
|
||||
manifest=args.manifest)
|
||||
if args.source == "dbt":
|
||||
export.build = None
|
||||
if code := _cohort_export(export):
|
||||
return code
|
||||
if not (args.train or args.promote or args.estimate):
|
||||
return _store_step(args, args.output) if args.store else 0
|
||||
|
||||
if not (source := _cohort_source(args, scenario)):
|
||||
return 1
|
||||
version = args.version
|
||||
if args.train or (args.promote and not version):
|
||||
from models.dags.training import find_trained, train
|
||||
|
||||
environment = args.environment.upper()
|
||||
version = find_trained(scenario, source, environment)
|
||||
if args.train and version:
|
||||
print(f"already trained: version {version}, from {_describe(source)}")
|
||||
elif args.train:
|
||||
version = train(scenario, source, environment)
|
||||
print(f"trained: version {version}, from {_describe(source)}")
|
||||
elif not version:
|
||||
print(f"no {environment} version trained on {_describe(source)}: use --train or --version", file=sys.stderr)
|
||||
return 1
|
||||
if args.promote and (code := _promote_step(args, version)):
|
||||
return code
|
||||
if args.estimate and (code := _estimate_step(args, scenario, source)):
|
||||
return code
|
||||
return _store_step(args, args.output) if args.store else 0
|
||||
|
||||
|
||||
def _cohort_build(args: argparse.Namespace) -> int:
|
||||
"""Runs the cohort's rules and shows its attrition, or only its graph. Stores nothing."""
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
from models.io.contracts import CohortDefinitionError
|
||||
from models.io.storage import read_queries
|
||||
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
try:
|
||||
queries = read_queries(args.manifest, url)
|
||||
if args.graph:
|
||||
print(mermaid(build_driver(queries).graph))
|
||||
return 0
|
||||
built = build_cohort(queries, import_module(f"persistance.{args.domain}").dbt_query_repository)
|
||||
except (FileNotFoundError, CohortDefinitionError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
except DBAPIError as error:
|
||||
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
|
||||
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
|
||||
return 1
|
||||
print(built.attrition.to_string(index=False))
|
||||
print(f"{url}: {len(built.study_population)} members, not stored")
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_export(args: argparse.Namespace) -> int:
|
||||
"""Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules."""
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.edges.dbt import DbtRelationError
|
||||
from persistance.settings import settings
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from models.io.contracts import CohortDefinitionError
|
||||
from models.io.storage import read_queries
|
||||
from models.io.storage import cohorts_root
|
||||
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
repositories = import_module(f"persistance.{args.domain}")
|
||||
timeline = repositories.timeline_repository
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
if args.source == "dbt":
|
||||
queries = read_queries(args.manifest, url)
|
||||
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
|
||||
else:
|
||||
path, outcome = export_kit_build(repositories.cohort_repository, timeline, root, args.domain, url, args.build)
|
||||
except PermissionError as error:
|
||||
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
|
||||
return 1
|
||||
except DBAPIError as error:
|
||||
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
|
||||
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
|
||||
return 1
|
||||
except (FileNotFoundError, LookupError, ValueError, DbtRelationError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(f"{outcome}: {path}")
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_list(args: argparse.Namespace) -> int:
|
||||
"""Prints the cohort's builds: dbt's from their files, the kit's from the database."""
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.storage import cohorts_root, list_builds
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
except ValueError as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohort_repository
|
||||
rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])]
|
||||
if not rows:
|
||||
print(f"{url}: no builds", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{'source':<6} {'build':>5} {'datos_as_of':<11} {'members':>7} {'created':<25} file")
|
||||
for row in rows:
|
||||
print(f"{row['source']:<6} {row['build']:>5} {row['datos_as_of'] or '':<11} {row['n_members'] or '':>7} "
|
||||
f"{(row['created'] or '')[:25]:<25} {row['file'] or '(not exported)'}")
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_show(args: argparse.Namespace) -> int:
|
||||
"""Prints one build's file, hash and lineage as JSON."""
|
||||
import json
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.storage import cohorts_root, describe_build
|
||||
|
||||
url = f"{args.domain}/{args.cohort}"
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
cohorts = import_module(f"persistance.{args.domain}").cohort_repository if args.source == "kit" else None
|
||||
described = describe_build(root, url, args.source, args.build, cohorts)
|
||||
except (ValueError, LookupError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print(json.dumps(described, indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
if args.source == "dbt" and not args.manifest:
|
||||
parser.error("--source dbt needs --manifest")
|
||||
if args.source == "dbt" and args.build is not None:
|
||||
parser.error("--build names a kit build: it can't go with --source dbt")
|
||||
return _cohort_export(args)
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
|
||||
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
|
||||
|
||||
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
|
||||
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
|
||||
actions = cohorts.add_subparsers(dest="action", metavar="<action>")
|
||||
build = actions.add_parser("build", help="run a cohort's rules and show its attrition; stores nothing")
|
||||
build.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
build.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
build.add_argument("--manifest", required=True, help="the manifest.json `dbt compile` wrote")
|
||||
build.add_argument("--graph", action="store_true", help="print the chain as a Mermaid diagram without running it")
|
||||
build.set_defaults(run=_cohort_build)
|
||||
|
||||
export = actions.add_parser("export", help="export a build to its Parquet file, once")
|
||||
export.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
export.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
export.add_argument("--source", choices=["kit", "dbt"], default="kit",
|
||||
help="the kit's stored build, or one built now from dbt's rules")
|
||||
export.add_argument("--build", type=int, help="the kit build's armado_id; the cohort's latest by default")
|
||||
export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt")
|
||||
export.set_defaults(run=lambda args: _cohort_export_checked(export, args))
|
||||
|
||||
listing = actions.add_parser("list", help="the cohort's builds, from both sources, and whether each has its file")
|
||||
listing.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
listing.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
listing.add_argument("--source", choices=["kit", "dbt"], help="only one source's builds; dbt's read no database")
|
||||
listing.set_defaults(run=_cohort_list)
|
||||
|
||||
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
|
||||
show.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||
show.add_argument("--build", type=int, required=True, help="the build's number")
|
||||
show.set_defaults(run=_cohort_show)
|
||||
|
||||
train = commands.add_parser("train", help="train a model on a cohort build and register a version")
|
||||
train.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
train.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||
train.add_argument("--read", choices=["db", "file"], default="db",
|
||||
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
||||
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||
train.set_defaults(run=lambda args: _train(train, args))
|
||||
|
||||
estimate = commands.add_parser("estimate", help="score a cohort build with a registered version")
|
||||
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
estimate.add_argument("--output", required=True, help="the Parquet file to write")
|
||||
estimate.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||
estimate.add_argument("--read", choices=["db", "file"], default="db",
|
||||
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
||||
estimate.add_argument("--version", help="the model version; the one in production by default")
|
||||
estimate.set_defaults(run=_estimate)
|
||||
|
||||
report = commands.add_parser("report", help="notebooks run on a build's file and kept as MLflow reports")
|
||||
report.set_defaults(run=lambda args: _show_help(report))
|
||||
reports = report.add_subparsers(dest="action", metavar="<report>")
|
||||
eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow")
|
||||
eda.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
eda.add_argument("--notebook", help="the notebook; the scenario's <scenario>/notebooks/01_eda.ipynb by default")
|
||||
eda.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
|
||||
eda.set_defaults(run=_report_eda)
|
||||
|
||||
store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database")
|
||||
store.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
store.add_argument("--input", required=True, help="the Parquet file `estimate` wrote")
|
||||
store.set_defaults(run=_store)
|
||||
|
||||
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops")
|
||||
run.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
run.add_argument("--export", action="store_true", help="export the build to its Parquet file")
|
||||
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
|
||||
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
|
||||
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
|
||||
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
|
||||
run.add_argument("--build", "--armado", dest="armado", type=int,
|
||||
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
|
||||
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
|
||||
run.add_argument("--read", choices=["db", "file"], default="db",
|
||||
help="a kit build read from the database, or its exported file; dbt's builds are files")
|
||||
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
|
||||
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
|
||||
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
|
||||
run.add_argument("--reference-dir", help="tea eeg: train on the EDFs of this folder instead of the configured cohort")
|
||||
run.add_argument("--reference-ages", help="tea eeg: CSV of `archivo` and `edad_meses` (or `edad_anos`); "
|
||||
"without it, each EDF header's age")
|
||||
run.add_argument("--reference-name", help="tea eeg: a name for that cohort (no names or dates of people)")
|
||||
run.add_argument("--line-hz", type=float, help="tea eeg: the mains frequency where it was recorded (60)")
|
||||
run.set_defaults(run=lambda args: _run(run, args))
|
||||
|
||||
tea = commands.add_parser("tea", help="TEA's EEG analysis")
|
||||
tea.set_defaults(run=lambda args: _show_help(tea))
|
||||
tea_actions = tea.add_subparsers(dest="action", metavar="<action>")
|
||||
analyze = tea_actions.add_parser(
|
||||
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
|
||||
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
|
||||
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
|
||||
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
|
||||
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
|
||||
analyze.set_defaults(run=_tea_analyze)
|
||||
export_baselines = tea_actions.add_parser(
|
||||
"export-baselines", help="write the trained age baselines to one bundle: group numbers only, nothing per child")
|
||||
export_baselines.add_argument("--out", required=True, help="the bundle to write (.zip)")
|
||||
export_baselines.add_argument("--environment", choices=["dev", "prod"], default="prod")
|
||||
export_baselines.add_argument("--production", action="store_true",
|
||||
help="the versions in production, instead of the newest trained in --environment")
|
||||
export_baselines.set_defaults(run=_tea_export_baselines)
|
||||
import_baselines = tea_actions.add_parser(
|
||||
"import-baselines", help="register the age baselines of a bundle; promotion still needs their reports")
|
||||
import_baselines.add_argument("bundle", help="the bundle `export-baselines` wrote")
|
||||
import_baselines.set_defaults(run=_tea_import_baselines)
|
||||
|
||||
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
|
||||
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
|
||||
notebook_actions = notebooks.add_subparsers(dest="action", metavar="<action>")
|
||||
serve = notebook_actions.add_parser("serve", help="run each job left in the jobs folder, one at a time")
|
||||
serve.add_argument("--jobs", help="the jobs folder; NOTEBOOK_JOBS_DIR by default")
|
||||
serve.add_argument("--once", action="store_true", help="run the jobs waiting now and stop")
|
||||
serve.set_defaults(run=_serve_notebooks)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
return args.run(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Validators a dataflow puts on its nodes. Nothing here does I/O or imports MLflow.
|
||||
|
||||
- `@checked_frame(schema)`: validates the node's frame with a pandera schema and fails the run if it doesn't hold. The
|
||||
failure names the columns, the checks and how many rows failed, never the values: pandera's own report (and
|
||||
`@check_output(schema=...)`) quotes them.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import pandera.pandas as pandera
|
||||
from hamilton.data_quality.base import DataValidator, ValidationResult
|
||||
from hamilton.function_modifiers import check_output_custom
|
||||
|
||||
|
||||
class FrameCheck(DataValidator):
|
||||
"""A pandera schema as a Hamilton validator whose message carries no data values."""
|
||||
|
||||
def __init__(self, schema: pandera.DataFrameSchema, importance: str = "fail"):
|
||||
super().__init__(importance)
|
||||
self.schema = schema
|
||||
|
||||
def applies_to(self, datatype: type) -> bool:
|
||||
return issubclass(datatype, pd.DataFrame)
|
||||
|
||||
def description(self) -> str:
|
||||
return f"rows satisfy {self.schema.name or 'the schema'}"
|
||||
|
||||
@classmethod
|
||||
def name(cls) -> str:
|
||||
return "frame_check"
|
||||
|
||||
def validate(self, dataset: Any) -> ValidationResult:
|
||||
try:
|
||||
self.schema.validate(dataset, lazy=True)
|
||||
except pandera.errors.SchemaErrors as failed:
|
||||
cases = failed.failure_cases.fillna({"column": "(frame)"})
|
||||
counts = cases.groupby(["column", "check"], dropna=False).size()
|
||||
summary = "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
|
||||
return ValidationResult(False, f"{self.description()} doesn't hold: {summary}")
|
||||
return ValidationResult(True, f"{self.description()}: holds")
|
||||
|
||||
|
||||
def checked_frame(schema: pandera.DataFrameSchema):
|
||||
return check_output_custom(FrameCheck(schema))
|
||||
@@ -1,41 +0,0 @@
|
||||
import importlib
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
|
||||
def resolve_repository(domain: str, entity: str) -> Repository:
|
||||
"""`entity` is the repository's name in `persistance.<domain>` without
|
||||
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
|
||||
module = importlib.import_module(f"persistance.{domain}")
|
||||
try:
|
||||
return getattr(module, f"{entity}_repository")
|
||||
except AttributeError as exc:
|
||||
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
|
||||
|
||||
|
||||
class ScreeningModel(ABC):
|
||||
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
|
||||
|
||||
Data is read through the same `persistance.<domain>.<entity>_repository`
|
||||
objects WebApi writes with, so anything loaded through the import flow
|
||||
is visible here. `train` may also be given rows fetched by the caller.
|
||||
"""
|
||||
|
||||
domain: ClassVar[str]
|
||||
|
||||
def repository(self, entity: str) -> Repository:
|
||||
return resolve_repository(self.domain, entity)
|
||||
|
||||
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
|
||||
"""Every row of `entity` as plain dicts, read in batches."""
|
||||
return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters))
|
||||
|
||||
@abstractmethod
|
||||
def train(self, data: Any = None) -> None:
|
||||
"""Fit the model, optionally on `data` passed in by the caller."""
|
||||
|
||||
@abstractmethod
|
||||
def predict(self, data: Any) -> Any:
|
||||
"""Score `data` and return predictions."""
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaCuModel(ScreeningModel):
|
||||
"""Scaffold for the CaCu (cervical cancer) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.cacu`'s
|
||||
repositories (`paciente_repository`, `citologia_cervical_repository`,
|
||||
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
|
||||
No real model yet; this is interface scaffolding only.
|
||||
"""
|
||||
|
||||
domain = "cacu"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaCu training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaCu prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""CaCu's scenarios and notebooks."""
|
||||
@@ -0,0 +1,121 @@
|
||||
"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology.
|
||||
|
||||
`y` is 1 when a biopsy graded in `event_grades` falls within the window (`horizons_years`, one) of the index date. A member with
|
||||
no such biopsy whose follow-up to the build's cut-off (`datos_as_of`) is shorter than the window isn't known yet:
|
||||
it's scored but left out of training and evaluation. The predictors are the index sample's own results (Bethesda
|
||||
category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported;
|
||||
nothing after them is used.
|
||||
|
||||
The split, the classifier, the fit, the metrics and the classifier's routines (ML-01a) are
|
||||
`models.steps.model_fitting`'s, listed with this module in `model.toml`; `sampling` and `missing_data`, the routines
|
||||
that depend on this scenario's members and predictors, are here. `fitted_model` puts `IndexSampleResults` in front of the fitted pipeline, so the registered model is one
|
||||
scikit-learn `Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through
|
||||
loaders, and registering is the driver's saver (`models.dags.training`).
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pandas as pd
|
||||
import pandera.pandas as pandera
|
||||
from sklearn.base import BaseEstimator, TransformerMixin
|
||||
from sklearn.pipeline import Pipeline
|
||||
|
||||
from models.annotations import checked_frame
|
||||
from models.io.contracts import DAYS_PER_YEAR
|
||||
|
||||
MISSING = "(none)"
|
||||
LABELLED_MEMBERS = pandera.DataFrameSchema(
|
||||
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
|
||||
"fecha_indice": pandera.Column(nullable=False),
|
||||
"y": pandera.Column(int, pandera.Check.isin([0, 1]))},
|
||||
name="labelled members")
|
||||
|
||||
|
||||
def cohort_cutoff(cohort_lineage: dict) -> date:
|
||||
"""The build's cut-off: no event after it is in the file."""
|
||||
return date.fromisoformat(cohort_lineage["datos_as_of"])
|
||||
|
||||
|
||||
def index_sample_results(cohort: pd.DataFrame, predictor_columns: list[str]) -> pd.DataFrame:
|
||||
"""One row per member: `pac_id`, `fecha_indice` and the index sample's results, `(none)` where it has none."""
|
||||
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
|
||||
sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] == cohort["fecha_indice"])]
|
||||
sample = sample.groupby("pac_id")["fuente_id"].first().rename("sample")
|
||||
results = cohort.merge(sample, left_on="pac_id", right_index=True)
|
||||
results = results[results["fuente_id"] == results["sample"]].copy()
|
||||
genotype = results["tipo"] == "vph_genotipo_16_18"
|
||||
results.loc[genotype, "valor_codigo"] = results.loc[genotype, "valor_numerico"].map({1.0: "POSITIVO", 0.0: "NEGATIVO"})
|
||||
results["tipo"] = results["tipo"].replace({"vph_genotipo_16_18": "vph_16_18"})
|
||||
wide = results[results["tipo"].isin(predictor_columns)].pivot_table(
|
||||
index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
|
||||
wide = wide.reindex(columns=list(predictor_columns)).astype(object)
|
||||
return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna(
|
||||
{name: MISSING for name in predictor_columns})
|
||||
|
||||
|
||||
def windowed_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, horizons_years: list[float],
|
||||
event_grades: list[str]) -> pd.DataFrame:
|
||||
"""One row per member: `y`, and `known`, whether the window is complete or the event already happened."""
|
||||
(window_years,) = horizons_years
|
||||
window = window_years * DAYS_PER_YEAR
|
||||
days = (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
|
||||
event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(event_grades) & days.between(0, window)
|
||||
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
|
||||
members["y"] = members["pac_id"].isin(cohort.loc[event, "pac_id"]).astype(int)
|
||||
follow_up = (pd.Timestamp(cohort_cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days
|
||||
members["known"] = (members["y"] == 1) | (follow_up >= window)
|
||||
return members[["pac_id", "y", "known"]]
|
||||
|
||||
|
||||
@checked_frame(LABELLED_MEMBERS)
|
||||
def labelled_members(index_sample_results: pd.DataFrame, windowed_outcomes: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The members whose outcome is known, with their predictors and `y`."""
|
||||
labelled = index_sample_results.merge(windowed_outcomes, on="pac_id")
|
||||
return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True)
|
||||
|
||||
|
||||
class IndexSampleResults(TransformerMixin, BaseEstimator):
|
||||
"""A build's long frame to one row per member, in `pac_id` order, with the index sample's results. Learns
|
||||
nothing."""
|
||||
|
||||
def __init__(self, predictor_columns: list[str]):
|
||||
self.predictor_columns = predictor_columns
|
||||
|
||||
def fit(self, X, y=None):
|
||||
return self
|
||||
|
||||
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
|
||||
return index_sample_results(X, self.predictor_columns)[list(self.predictor_columns)]
|
||||
|
||||
|
||||
def fitted_model(fitted_pipeline: Pipeline, predictor_columns: list[str]) -> Pipeline:
|
||||
"""What's registered: the fitted pipeline behind `IndexSampleResults`."""
|
||||
return Pipeline([("index_sample", IndexSampleResults(predictor_columns)), ("classifier", fitted_pipeline)])
|
||||
|
||||
|
||||
def _dates(frame: pd.DataFrame) -> dict:
|
||||
if frame.empty:
|
||||
return {"n": 0}
|
||||
return {"n": len(frame), "first_index_date": str(frame["fecha_indice"].min()),
|
||||
"last_index_date": str(frame["fecha_indice"].max())}
|
||||
|
||||
|
||||
def sampling(windowed_outcomes: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
|
||||
train_fraction: float, index_attrition: list, prior_observation: dict) -> dict:
|
||||
"""MUESTREO: who could be used (the scenario's index and rules, step by step, and their prior history), and how
|
||||
they were split."""
|
||||
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
|
||||
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
|
||||
"train_fraction": train_fraction, "members": len(windowed_outcomes),
|
||||
"left_out_unknown_outcome": int((~windowed_outcomes["known"]).sum()), "train": _dates(train_set),
|
||||
"test": _dates(test_set)}
|
||||
|
||||
|
||||
def missing_data(index_sample_results: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
|
||||
predictor_columns: list[str]) -> dict:
|
||||
"""DATOS_FALTANTES: how many lacked each predictor, and what was done about it."""
|
||||
def missing(frame: pd.DataFrame) -> dict:
|
||||
return {name: int((frame[name] == MISSING).sum()) for name in predictor_columns}
|
||||
|
||||
return {"method": f"un predictor sin resultado en la muestra índice es la categoría {MISSING!r}; nadie se excluye",
|
||||
"members": missing(index_sample_results), "train": missing(train_set), "test": missing(test_set)}
|
||||
@@ -0,0 +1,33 @@
|
||||
domain = "cacu"
|
||||
scenario = "cin2_logistic"
|
||||
cohort = "cacu/cohorte_vigilancia"
|
||||
outcome = "cin2_12m"
|
||||
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
|
||||
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
|
||||
# The modules whose functions are the graph's nodes, in `with_modules`.
|
||||
modules = ["models.cacu.cin2_logistic.model", "models.steps.model_fitting", "models.steps.indexing"]
|
||||
description = """
|
||||
Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \
|
||||
a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \
|
||||
validación clínica."""
|
||||
|
||||
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
|
||||
[config]
|
||||
classifier = "logistic"
|
||||
train_fraction = 0.7
|
||||
predictor_columns = ["bethesda", "vph", "vph_16_18"]
|
||||
# Provisional, to be decided with the domain expert: the window, in years, in which a CIN2+ biopsy counts as the
|
||||
# outcome; the model's one horizon. On the DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 2-year
|
||||
# window leaves no member with a complete window; 1 year leaves 5,231 known members, 162 with the event.
|
||||
horizons_years = [1.0]
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
|
||||
# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance
|
||||
# cohort, applied in the pipeline. The recruitment window is the source cohort's.
|
||||
[config.index]
|
||||
kind = "primera_citologia"
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
|
||||
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
|
||||
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
|
||||
observacion_previa_minima_dias = 0
|
||||
@@ -0,0 +1,158 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "# CaCu · CIN2+ · 01 — Exploratory analysis of the cohort\n\nFirst notebook of the `cin2_logistic` scenario: **exploratory only**. It describes the surveillance cohort\n(`cacu/cohorte_vigilancia`) from its build's Parquet file: who is in, what was measured at the index sample, and\nwhat happened afterwards. No outcome is computed and no model is fitted here.\n\n**How it gets its data, as in the deployment**\n\n- The domain's database is `CACU_DATABASE_URL`; the cohort files live next to it, in `<data>/cohorts/`,\n or in `COHORTS_DIR` when the data folder is read-only (as in the deployments).\n- A build's file is written **once**: if it already exists for that build, it's read; if not, it's exported\n from the build's members and dbt's timeline view, then read. Running the notebook again rebuilds nothing.\n- Every read goes through the domain's repositories; the notebook never opens a session.\n- **Locally**, with no `CACU_DATABASE_URL`, it works on a copy of the DEV deployment's simulated data in\n `~/.cache/isssteleon-notebooks/`, outside the repository, kept between runs.\n\n**With real data:** commit this notebook without outputs, and don't share counts below the suppression threshold.\n\nKernel: *ISSSTELEON WebApi env: kit + Persistance + models*.",
|
||||
"id": "cacu-cin2-01-00"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 1. Configuration",
|
||||
"id": "cacu-cin2-01-01"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/models/cacu/cin2_logistic/notebooks → ../../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[4] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))",
|
||||
"id": "cacu-cin2-01-02"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 2. dbt's timeline view\n\nThe export reads each member's history from `cacu_linea_de_tiempo`, the view dbt creates at deployment. If the\ndatabase doesn't have it and it's a local copy, it's created here; in a deployment, it has to be deployed first.",
|
||||
"id": "cacu-cin2-01-03"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "from persistance.edges.silver import TIMELINE_COLUMNS # noqa: E402 after the URL is set\nfrom persistance.cacu import cohort_repository, timeline_repository # noqa: E402\nfrom sqlalchemy import column, select, table # noqa: E402\nfrom sqlalchemy.exc import OperationalError # noqa: E402\n\nVIEW = table(f\"{DOMAIN}_linea_de_tiempo\", *(column(c) for c in TIMELINE_COLUMNS))\n\n\ndef from_dbt_view(*, patients, until, known_until):\n \"\"\"The timeline query over dbt's view, with the repository's filters (provisional: it belongs in Persistance).\"\"\"\n query = select(*(VIEW.c[c] for c in TIMELINE_COLUMNS)).order_by(\n VIEW.c.pac_id, VIEW.c.fecha, VIEW.c.clase, VIEW.c.tipo, VIEW.c.fuente_id)\n if patients is not None:\n query = query.where(VIEW.c.pac_id.in_(patients))\n if until is not None:\n query = query.where(VIEW.c.fecha <= until)\n if known_until is not None:\n query = query.where(VIEW.c.conocida_en <= known_until)\n return query\n\n\ndef view_present() -> bool:\n \"\"\"Whether dbt's view exists: an empty read through the repository fails if it doesn't.\"\"\"\n try:\n timeline_repository.with_query(from_dbt_view).read(patients=[])\n return True\n except OperationalError:\n return False\n\n\nhas_view = view_present()\nif not has_view and Path.home() in database.parents:\n schemas = DATA / \"dbt_schemas\"\n schemas.mkdir(exist_ok=True)\n run = subprocess.run([\"uv\", \"run\", \"--no-sync\", \"dbt\", \"run\", \"--profiles-dir\", \".\", \"--profile\", \"cacu\",\n \"--select\", \"cacu_linea_de_tiempo\"], cwd=TRANSFORMATION, capture_output=True, text=True,\n env={**os.environ, \"CACU_DB_PATH\": str(database), \"DBT_SCHEMA_DIR\": str(schemas)})\n print(run.stdout.strip().splitlines()[-1])\n has_view = view_present()\nprint(\"timeline view present:\", has_view)",
|
||||
"id": "cacu-cin2-01-04"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 3. The build's file: read it if it exists, export it once if not\n\nProvisional helpers: they will move into the code (a cycle step that exports each build, and the timeline\nquery over dbt's view in Persistance).",
|
||||
"id": "cacu-cin2-01-05"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "import hashlib\nimport json\nimport tempfile\nfrom datetime import datetime, timezone\n\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.parquet as pq\n\nSCHEMA = pa.schema([\n (\"pac_id\", pa.int64()), (\"fecha_indice\", pa.date32()), (\"fecha\", pa.date32()),\n (\"conocida_en\", pa.timestamp(\"us\", tz=\"UTC\")), (\"clase\", pa.string()), (\"tipo\", pa.string()),\n (\"codigo\", pa.string()), (\"valor_codigo\", pa.string()), (\"valor_numerico\", pa.float64()),\n (\"fuente_tabla\", pa.string()), (\"fuente_id\", pa.string()),\n])\ndef cohort_file(build) -> Path:\n domain, cohort = build.url.split(\"/\", 1)\n return COHORTS / domain / cohort / f\"{build.armado_id}.parquet\"\n\n\ndef lineage_of(path: Path) -> dict:\n meta = pq.read_metadata(path).metadata\n return {k.decode(): v.decode() for k, v in meta.items() if k not in (b\"pandas\", b\"ARROW:schema\")}\n\n\ndef export(build, path: Path) -> None:\n members = cohort_repository.members(build.armado_id)\n rows = timeline_repository.with_query(from_dbt_view).read(\n patients=[m.pac_id for m in members], until=build.datos_as_of, known_until=build.conocida_hasta)\n frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(\n pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=[\"pac_id\", \"fecha_indice\"]), on=\"pac_id\")\n for name in (\"fecha_indice\", \"fecha\"):\n frame[name] = pd.to_datetime(frame[name]).dt.date\n frame[\"conocida_en\"] = pd.to_datetime(frame[\"conocida_en\"], utc=True)\n frame[\"valor_numerico\"] = pd.to_numeric(frame[\"valor_numerico\"])\n lineage = {\"url\": build.url, \"version\": build.version, \"armado_id\": build.armado_id, \"domain\": DOMAIN,\n \"datos_as_of\": build.datos_as_of.isoformat(),\n \"conocida_hasta\": build.conocida_hasta.isoformat() if build.conocida_hasta else \"\",\n \"n_members\": len(members), \"producer\": \"kit build, timeline from dbt view (provisional)\",\n \"built_at\": datetime.now(timezone.utc).isoformat()}\n arrow = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)\n arrow = arrow.replace_schema_metadata({**arrow.schema.metadata, **{k: str(v) for k, v in lineage.items()}})\n path.parent.mkdir(parents=True, exist_ok=True)\n with tempfile.NamedTemporaryFile(dir=path.parent, suffix=\".tmp\", delete=False) as tmp:\n pq.write_table(arrow, tmp.name)\n Path(tmp.name).replace(path) # appears complete or not at all\n\n\ndef ensure(build) -> tuple[Path, str]:\n \"\"\"The build's file: reused if it already exists for this build, exported once if not. Returns (path, what happened).\"\"\"\n path = cohort_file(build)\n if path.exists():\n lineage = lineage_of(path)\n if lineage.get(\"armado_id\") != str(build.armado_id) or lineage.get(\"n_members\") != str(build.n_miembros):\n raise ValueError(f\"{path} doesn't belong to build {build.armado_id}: {lineage}\")\n return path, \"reused\"\n if not has_view:\n raise RuntimeError(\"dbt's timeline view isn't in the database: deploy it before exporting\")\n export(build, path)\n return path, \"exported\"",
|
||||
"id": "cacu-cin2-01-06"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "builds = pd.DataFrame([vars(b) for b in cohort_repository.builds()])\nbuilds[[\"armado_id\", \"url\", \"version\", \"datos_as_of\", \"conocida_hasta\", \"n_miembros\", \"armado_en\"]]",
|
||||
"id": "cacu-cin2-01-07"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "build = cohort_repository.builds(COHORT_URL)[0] # the newest build of the cohort\npath, what = ensure(build)\nprint(what, path)\nprint(\"sha256:\", hashlib.sha256(path.read_bytes()).hexdigest())\nlineage_of(path)",
|
||||
"id": "cacu-cin2-01-08"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "Running it again reuses the file: nothing is rebuilt and the file, and so its hash, stays the same.",
|
||||
"id": "cacu-cin2-01-09"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "again, what = ensure(build)\nprint(what, \"| same file:\", again == path, \"| same sha256:\",\n hashlib.sha256(again.read_bytes()).hexdigest() == hashlib.sha256(path.read_bytes()).hexdigest())",
|
||||
"id": "cacu-cin2-01-10"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 4. The cohort\n\nOne row per member, variable and date. `fecha_indice` is on every row; the index sample is the member's index\nevent (`fuente_tabla`, `fuente_id`), and its results are dated when they were **reported**, usually after the\nindex date.",
|
||||
"id": "cacu-cin2-01-11"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "cohort = pd.read_parquet(path)\ncohort[\"dias\"] = (pd.to_datetime(cohort.fecha) - pd.to_datetime(cohort.fecha_indice)).dt.days\nmembers = cohort.groupby(\"pac_id\").fecha_indice.first()\nprint(f\"{len(cohort):,} rows · {members.size:,} members · index dates {members.min()} to {members.max()}\")\nmembers.pipe(pd.to_datetime).dt.to_period(\"Q\").value_counts().sort_index().rename(\"members by quarter of the index date\").to_frame().T",
|
||||
"id": "cacu-cin2-01-12"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "cohort[\"momento\"] = pd.cut(cohort.dias, [-10**6, -1, 0, 10**6], labels=[\"before\", \"on the index date\", \"after\"])\ncohort.pivot_table(index=[\"clase\", \"tipo\"], columns=\"momento\", values=\"pac_id\", aggfunc=\"count\", observed=False, fill_value=0)",
|
||||
"id": "cacu-cin2-01-13"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 5. At the index sample\n\nThe results of the member's own index cytology: its Bethesda category and its HPV result, matched by the source\nrow of the index event, not by date.",
|
||||
"id": "cacu-cin2-01-14"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "sample = cohort[cohort.tipo == \"citologia\"].merge(members.rename(\"fi\"), left_on=\"pac_id\", right_index=True)\nsample = sample[sample.fecha == sample.fi].groupby(\"pac_id\").fuente_id.first().rename(\"muestra\")\nat_index = cohort.merge(sample, left_on=\"pac_id\", right_index=True)\nat_index = at_index[at_index.fuente_id == at_index.muestra]\nbaseline = at_index.pivot_table(index=\"pac_id\", columns=\"tipo\", values=\"valor_codigo\", aggfunc=\"first\")\nbaseline = baseline.reindex(members.index)\nprint(\"members without an HPV result at the index sample:\", f\"{baseline.vph.isna().mean():.1%}\")\npd.crosstab(baseline.bethesda.fillna(\"(none)\"), baseline.vph.fillna(\"(none)\"), margins=True)",
|
||||
"id": "cacu-cin2-01-15"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## 6. After the index\n\nFollow-up: how long it lasts, how many members had a biopsy and when, and the grades reported.",
|
||||
"id": "cacu-cin2-01-16"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "after = cohort[cohort.dias > 0]\nfollow_up = after.groupby(\"pac_id\").dias.max().reindex(members.index).fillna(0)\nfirst_biopsy = after[after.tipo == \"biopsia\"].groupby(\"pac_id\").dias.min()\nprint(f\"follow-up (days to the last event): median {follow_up.median():.0f}, quartiles {follow_up.quantile(.25):.0f}–{follow_up.quantile(.75):.0f}\")\nprint(f\"members with a biopsy after the index: {first_biopsy.size:,} ({first_biopsy.size / members.size:.1%}); \"\n f\"days to the first one: median {first_biopsy.median():.0f}\")\nafter[after.tipo == \"biopsia\"].valor_codigo.fillna(\"(no grade)\").value_counts().rename(\"biopsy results after the index\").to_frame()",
|
||||
"id": "cacu-cin2-01-17"
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {},
|
||||
"execution_count": null,
|
||||
"outputs": [],
|
||||
"source": "import matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(1, 2, figsize=(11, 3.5))\nfollow_up.div(30.44).plot.hist(bins=30, ax=axes[0], title=\"Follow-up per member (months)\")\nfirst_biopsy.div(30.44).plot.hist(bins=30, ax=axes[1], title=\"Index to first biopsy (months)\")\nfor ax in axes:\n ax.set_ylabel(\"members\")\nplt.tight_layout()",
|
||||
"id": "cacu-cin2-01-18"
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": "## Next\n\n- **02 — profiling and hypothesis tests**, and the outcome itself (prevalent CIN2+ and time to it), computed by\n the model from these rows, not by the cohort.\n- The helpers of sections 2 and 3 move into the code: the export into the cycle, and the timeline query over\n dbt's view into Persistance.",
|
||||
"id": "cacu-cin2-01-19"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "ISSSTELEON WebApi env: kit + Persistance + models (feature/model-proto)",
|
||||
"language": "python",
|
||||
"name": "isssteleon-webapi"
|
||||
},
|
||||
"language_info": {
|
||||
"name": "python"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Kept for callers of the old per-scenario driver: training is `models.dags.training`'s, with this scenario's
|
||||
`model.toml`. `train(source, environment)` and `find_trained(source, environment)` take a `models.io.storage` source."""
|
||||
from functools import partial
|
||||
|
||||
from models.dags.training import Scenario, find_trained as _find_trained, train as _train
|
||||
|
||||
train, find_trained = (partial(f, Scenario.load("cacu", "cin2_logistic")) for f in (_train, _find_trained))
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Prevalence–incidence mixture (PIMixture) likelihood, written plainly: the Weibull family and maximum likelihood.
|
||||
|
||||
Each row has a code `c` and an interval `(l, r]` in years since the index visit:
|
||||
|
||||
- `c = 1`: prevalent at the index visit. Contributes `pi`.
|
||||
- `c = 0`: not prevalent; the disease, if any, appeared in `(l, r]` (`r = inf` means censored at `l`).
|
||||
Contributes `(1 - pi) * (S(l) - S(r))`.
|
||||
- `c = -999`: unknown at the index visit (no colposcopy). Contributes `pi + (1 - pi) * (S(l) - S(r))`, usually
|
||||
with `l = 0`.
|
||||
|
||||
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-H0(t) * exp(Z @ beta))` the survival of the incidence
|
||||
(proportional hazards in `Z`). The baseline cumulative hazard `H0` is a family:
|
||||
|
||||
- `Weibull`: `H0(t) = (t / scale) ** shape`, the default;
|
||||
- `ISpline`: PIMixture's weakly-parametric `H0(t) = sum_j exp(gamma_j) I_j(t)`, with `I_j` the I-spline basis on knots
|
||||
at quantiles of the observed times. Each `I_j` rises from 0 to 1, so `H0` is flat after the last knot.
|
||||
|
||||
Each row may carry a frequency weight `w` (identical rows collapsed into one); the standard errors (`-H^-1`) are those
|
||||
of frequency weights, not of sampling weights.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
from scipy.interpolate import BSpline
|
||||
from scipy.optimize import minimize
|
||||
from scipy.special import expit
|
||||
|
||||
UNKNOWN = -999
|
||||
TINY = 1e-12
|
||||
BOUNDARY = 15.0 # |parameter| beyond this is taken as "at the boundary" (expit(−15) = 3e-7)
|
||||
|
||||
|
||||
def prevalence(theta, X):
|
||||
return expit(X @ theta)
|
||||
|
||||
|
||||
def weibull_survival(t, log_scale, log_shape, beta, Z):
|
||||
"""S(t). S(0) = 1 and S(inf) = 0."""
|
||||
t = np.asarray(t, dtype=float)
|
||||
scale, shape = np.exp(log_scale), np.exp(log_shape)
|
||||
hazard_ratio = np.exp(Z @ beta)
|
||||
with np.errstate(over="ignore", invalid="ignore"):
|
||||
cumulative = (t / scale) ** shape * hazard_ratio
|
||||
survival = np.exp(-cumulative)
|
||||
survival = np.where(t <= 0, 1.0, survival)
|
||||
survival = np.where(np.isinf(t), 0.0, survival)
|
||||
return survival
|
||||
|
||||
|
||||
def ispline_basis(t, order: int, knots) -> np.ndarray:
|
||||
"""(len(t) x (len(knots) + order - 2)) I-spline basis: `I_j(t) = sum_{m >= j} B_m(t)`, the B-splines of degree
|
||||
`order` on `knots` with repeated boundaries. Equals PIMixture's `Ispline(t, order, knots)`, transposed."""
|
||||
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
|
||||
full = np.r_[np.repeat(knots[0], order + 1), knots[1:-1], np.repeat(knots[-1], order + 1)]
|
||||
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
|
||||
bsplines = BSpline.design_matrix(inside, full, order, extrapolate=False).toarray()
|
||||
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
|
||||
basis[t >= knots[-1]] = 1.0
|
||||
basis[t <= knots[0]] = 0.0
|
||||
return basis
|
||||
|
||||
|
||||
def quantile_knots(l, r, n_knots: int) -> tuple[float, ...]:
|
||||
"""PIMixture's knots: quantiles of the unique observed times, the `l` (zeros included) and the finite `r`."""
|
||||
l, r = np.asarray(l, dtype=float), np.asarray(r, dtype=float)
|
||||
times = np.unique(np.r_[l, r[np.isfinite(r)]])
|
||||
return tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots)))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Weibull:
|
||||
"""`H0(t) = (t / scale) ** shape`; params `[log_scale, log_shape]`."""
|
||||
n_params = 2
|
||||
|
||||
def cumulative_hazard(self, t, params):
|
||||
with np.errstate(over="ignore", invalid="ignore"):
|
||||
return (np.asarray(t, dtype=float) / np.exp(params[0])) ** np.exp(params[1])
|
||||
|
||||
def start(self, c, l, r):
|
||||
return np.array([_starting_log_scale(c, l, r), 0.0])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ISpline:
|
||||
"""`H0(t) = sum_j exp(gamma_j) I_j(t)`; params `gamma`, one per basis function."""
|
||||
knots: tuple[float, ...]
|
||||
order: int = 3
|
||||
|
||||
@property
|
||||
def n_params(self):
|
||||
return len(self.knots) + self.order - 2
|
||||
|
||||
def cumulative_hazard(self, t, params):
|
||||
return ispline_basis(t, self.order, self.knots) @ np.exp(params)
|
||||
|
||||
def start(self, c, l, r):
|
||||
"""The exponential start's `H0` at the last knot, shared equally among the basis functions."""
|
||||
rate = np.exp(-_starting_log_scale(c, l, r))
|
||||
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
|
||||
|
||||
|
||||
WEIBULL = Weibull()
|
||||
|
||||
|
||||
def survival(t, baseline_params, beta, Z, baseline=WEIBULL):
|
||||
"""S(t) for any baseline family. S(0) = 1 and S(inf) = 0."""
|
||||
t = np.asarray(t, dtype=float)
|
||||
with np.errstate(over="ignore", invalid="ignore"):
|
||||
cumulative = baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta)
|
||||
found = np.exp(-cumulative)
|
||||
found = np.where(t <= 0, 1.0, found)
|
||||
return np.where(np.isinf(t), 0.0, found)
|
||||
|
||||
|
||||
def split_params(params, n_x, n_z):
|
||||
"""params = [theta (n_x), beta (n_z), log_scale, log_shape]."""
|
||||
theta = params[:n_x]
|
||||
beta = params[n_x:n_x + n_z]
|
||||
log_scale = params[n_x + n_z]
|
||||
log_shape = params[n_x + n_z + 1]
|
||||
return theta, beta, log_scale, log_shape
|
||||
|
||||
|
||||
def neg_loglik(params, c, l, r, X, Z, baseline=WEIBULL, w=None):
|
||||
n_x, n_z = X.shape[1], Z.shape[1]
|
||||
theta, beta, rest = params[:n_x], params[n_x:n_x + n_z], params[n_x + n_z:]
|
||||
w = np.ones(len(c)) if w is None else np.asarray(w, dtype=float)
|
||||
pi = prevalence(theta, X)
|
||||
interval = survival(l, rest, beta, Z, baseline) - survival(r, rest, beta, Z, baseline)
|
||||
interval = np.maximum(interval, TINY)
|
||||
|
||||
row = np.zeros(len(c))
|
||||
prevalent = c == 1
|
||||
row[prevalent] = np.log(pi[prevalent] + TINY)
|
||||
|
||||
not_prevalent = c == 0
|
||||
row[not_prevalent] = np.log(1 - pi[not_prevalent] + TINY) + np.log(interval[not_prevalent])
|
||||
|
||||
unknown = c == UNKNOWN
|
||||
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
|
||||
|
||||
return -np.sum(w * row)
|
||||
|
||||
|
||||
def numerical_hessian(f, x, step=1e-4):
|
||||
"""Central finite differences, one pair of parameters at a time. Plain and slow (4 p² calls), fine for p < 30."""
|
||||
x = np.asarray(x, dtype=float)
|
||||
p = len(x)
|
||||
hessian = np.zeros((p, p))
|
||||
for i in range(p):
|
||||
for j in range(i, p):
|
||||
ei = np.zeros(p)
|
||||
ej = np.zeros(p)
|
||||
ei[i] = step
|
||||
ej[j] = step
|
||||
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (4 * step * step)
|
||||
hessian[i, j] = value
|
||||
hessian[j, i] = value
|
||||
return hessian
|
||||
|
||||
|
||||
def _starting_log_scale(c, l, r):
|
||||
"""log of an exponential scale: time at risk / incident events. With a rare outcome the scale is thousands of
|
||||
years; starting BFGS at the median detection time (a few years) left it in a much worse local optimum."""
|
||||
at_risk = c != 1
|
||||
finite = np.isfinite(r)
|
||||
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
|
||||
events = (at_risk & finite & (r > 0)).sum()
|
||||
return float(np.log(max(exposure, 1e-6) / (events + 0.5)))
|
||||
|
||||
|
||||
def _starting_theta(c, X, ridge=1e-3):
|
||||
"""Prevalence coefficients of a logistic regression of "prevalent" on X among the members whose baseline is
|
||||
known, with a small ridge so a group with no prevalent case gets a large negative value instead of -inf."""
|
||||
known = c != UNKNOWN
|
||||
if not known.any():
|
||||
return np.zeros(X.shape[1])
|
||||
y, Xk = (c[known] == 1).astype(float), X[known]
|
||||
|
||||
def loss(theta):
|
||||
eta = Xk @ theta
|
||||
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
|
||||
|
||||
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
|
||||
|
||||
|
||||
def fit(c, l, r, X, Z, baseline=WEIBULL, w=None):
|
||||
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors; with the
|
||||
Weibull also `log_scale` and `log_shape`."""
|
||||
c, l, r = np.asarray(c), np.asarray(l, dtype=float), np.asarray(r, dtype=float)
|
||||
X, Z = np.asarray(X, dtype=float), np.asarray(Z, dtype=float)
|
||||
n_x, n_z = X.shape[1], Z.shape[1]
|
||||
|
||||
# Two starts, the better optimum kept: the likelihood of a rare outcome has poor local optima (all the risk put in
|
||||
# the prevalence and none in the incidence, or the other way round).
|
||||
start = baseline.start(c, l, r)
|
||||
starts = [np.r_[_starting_theta(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x), np.zeros(n_z), start]]
|
||||
args = (c, l, r, X, Z, baseline, w)
|
||||
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
|
||||
result = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
|
||||
theta, beta, rest = result.x[:n_x], result.x[n_x:n_x + n_z], result.x[n_x + n_z:]
|
||||
# BFGS's own hess_inv is a rough approximation: the standard errors come from a finite-difference Hessian.
|
||||
# A coefficient that ran off to the boundary (e.g. a group with no prevalent case: logit → −inf) has a flat
|
||||
# likelihood, a zero row in the Hessian, and makes the whole matrix singular. It gets no standard error (NaN) and
|
||||
# the others are computed without it.
|
||||
hessian = numerical_hessian(lambda p: neg_loglik(p, *args), result.x)
|
||||
free = np.abs(result.x) < BOUNDARY
|
||||
standard_errors = np.full(len(result.x), np.nan)
|
||||
covariance = np.full((len(result.x), len(result.x)), np.nan)
|
||||
try:
|
||||
covariance[np.ix_(free, free)] = np.linalg.inv(hessian[np.ix_(free, free)])
|
||||
variances = np.diag(covariance)[free]
|
||||
standard_errors[free] = np.sqrt(np.where(variances > 0, variances, np.nan))
|
||||
except np.linalg.LinAlgError:
|
||||
pass
|
||||
found = {
|
||||
"theta": theta,
|
||||
"beta": beta,
|
||||
"baseline": baseline,
|
||||
"baseline_params": rest,
|
||||
"params": result.x,
|
||||
"se": standard_errors,
|
||||
"covariance": covariance,
|
||||
"neg_loglik": result.fun,
|
||||
# BFGS with a numerical gradient often stops with "precision loss" at the optimum; what matters is that
|
||||
# the gradient is ~0 there.
|
||||
# A coefficient at the boundary (see above) keeps a small slope there; only the free ones must be flat.
|
||||
"converged": bool(np.max(np.abs(result.jac[free]), initial=0.0) < 1e-3),
|
||||
"message": result.message,
|
||||
}
|
||||
if isinstance(baseline, Weibull):
|
||||
found["log_scale"], found["log_shape"] = float(rest[0]), float(rest[1])
|
||||
return found
|
||||
|
||||
|
||||
def cumulative_risk(fitted, X, Z, years):
|
||||
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence. A `fitted` without
|
||||
`baseline` (built by hand) is a Weibull with `log_scale` and `log_shape`."""
|
||||
pi = prevalence(fitted["theta"], X)
|
||||
baseline = fitted.get("baseline", WEIBULL)
|
||||
rest = fitted.get("baseline_params")
|
||||
if rest is None:
|
||||
rest = np.array([fitted["log_scale"], fitted["log_shape"]])
|
||||
columns = [pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), rest, fitted["beta"], Z, baseline))
|
||||
for t in years]
|
||||
return np.column_stack(columns)
|
||||
@@ -0,0 +1,309 @@
|
||||
"""CaCu CIN2+ prevalence–incidence prototype: the cumulative risk of CIN2+ at the index visit and at later horizons.
|
||||
|
||||
Each member becomes a code `c` and an interval `(l, r]` in years since the index date (`likelihood`'s convention),
|
||||
from the first CIN2+ biopsy and the last time the member was found free of it before that biopsy. Found free means a
|
||||
biopsy below CIN2+, or a visit whose results each take one of their `known_negative` values (HPV-negative with NILM or
|
||||
ASC-US). CIN2+ is taken as absorbing
|
||||
and a negative as true, so the last negative carries every earlier one:
|
||||
|
||||
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`, `(0, 0]`;
|
||||
- otherwise, found free at least once: `c = 0`, with `l` the last negative (0 if it's within the window, the baseline
|
||||
workup) and `r` the CIN2+ biopsy, or infinity if there's none;
|
||||
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]`, or `(0, inf)`, which carries no information.
|
||||
|
||||
Follow-up without a test isn't counted: a member is free only as far as her last negative, never up to the cut-off.
|
||||
|
||||
`PrevalenceIncidenceMixture` is a scikit-learn estimator: `fit(X, y)` with the members' features and their `c`, `l`,
|
||||
`r`; `predict_proba(X)` gives the cumulative risk at each horizon, CR(t) = π + (1 − π)(1 − S(t)), with the prevalence
|
||||
π logistic in every feature (KPNC's cytology categories as indicators) and the incidence S(t) with proportional
|
||||
hazards in `incidence_features` over a Weibull or I-spline baseline (`incidence`), one mixture per stratum (`strata`).
|
||||
`fitted_model` puts `IndexResults` in front of it, so the registered model is one `Pipeline` that takes a build's long
|
||||
frame. Settings arrive as config (`model.toml`), the cohort through a loader, and registering is the
|
||||
driver's saver (`models.dags.training`).
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pandera.pandas as pandera
|
||||
from hamilton.function_modifiers import extract_fields
|
||||
from sklearn.base import BaseEstimator, TransformerMixin
|
||||
from sklearn.metrics import roc_auc_score
|
||||
from sklearn.pipeline import Pipeline
|
||||
|
||||
from models.annotations import checked_frame
|
||||
from models.cacu.cin2_pim import likelihood
|
||||
from models.io.contracts import DAYS_PER_YEAR
|
||||
from models.steps import model_fitting
|
||||
|
||||
FEATURES = ["cytology", "hpv_positive"]
|
||||
|
||||
|
||||
def _features(history: dict) -> list[str]:
|
||||
"""The model's features: the index results', and the history's one if the scenario has a history."""
|
||||
return FEATURES + ([history["feature"]] if history else [])
|
||||
|
||||
|
||||
def _levels(cytology: dict, history: dict) -> dict:
|
||||
"""The levels of each categorical feature, the reference first."""
|
||||
return {"cytology": list(cytology), **({history["feature"]: list(history["levels"])} if history else {})}
|
||||
INTERVAL_CODED = pandera.DataFrameSchema(
|
||||
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
|
||||
"c": pandera.Column(int, pandera.Check.isin([1, 0, likelihood.UNKNOWN])),
|
||||
"l": pandera.Column(float, pandera.Check.ge(0)),
|
||||
"r": pandera.Column(float, pandera.Check.ge(0))},
|
||||
checks=pandera.Check(lambda frame: frame["r"] >= frame["l"], error="r >= l"),
|
||||
name="interval-coded members")
|
||||
|
||||
|
||||
def _days(cohort: pd.DataFrame) -> pd.Series:
|
||||
return (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
|
||||
|
||||
|
||||
def _most_severe(codes: pd.Series, cytology: dict) -> pd.Series:
|
||||
"""Per `pac_id` (the index of `codes`), the most severe of `cytology`'s categories among the codes; None if none."""
|
||||
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
|
||||
ranks = codes.map(severity).groupby(level=0).max()
|
||||
names = list(cytology)
|
||||
return pd.Series([None if np.isnan(rank) else names[int(rank)] for rank in ranks], index=ranks.index,
|
||||
dtype=object)
|
||||
|
||||
|
||||
def _history(cohort: pd.DataFrame, members: pd.DataFrame, cytology: dict, history: dict) -> pd.Series:
|
||||
"""The history feature: the grade of the results in the `lookback_days` up to the member's first `event` (KPNC's
|
||||
referral before the colposcopy). `high` if a category of `high`; else `low` if one of `low`, or of
|
||||
`low_if_hpv_positive` with a positive HPV; else None (no referral result, or one that wouldn't refer)."""
|
||||
event = cohort[cohort["tipo"] == history["event"]].groupby("pac_id")["fecha"].min()
|
||||
timed = cohort.assign(event=cohort["pac_id"].map(event))
|
||||
before = (pd.to_datetime(timed["event"]) - pd.to_datetime(timed["fecha"])).dt.days
|
||||
near = timed[before.between(0, history["lookback_days"])]
|
||||
results = near[near["tipo"].isin(["bethesda", "glandular"])].set_index("pac_id")["valor_codigo"]
|
||||
worst = pd.Series(_most_severe(results, cytology).reindex(members["pac_id"]).to_numpy(), index=members.index)
|
||||
hpv = near[(near["tipo"] == "vph") & (near["valor_codigo"] == "POSITIVO")]["pac_id"].unique()
|
||||
positive = members["pac_id"].isin(hpv).to_numpy()
|
||||
grade = np.where(worst.isin(history["high"]), "high",
|
||||
np.where(worst.isin(history["low"]) | (worst.isin(history["low_if_hpv_positive"]) & positive),
|
||||
"low", None))
|
||||
return pd.Series(grade, index=members.index, dtype=object)
|
||||
|
||||
|
||||
def index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict, history: dict | None = None) -> pd.DataFrame:
|
||||
"""One row per member, in `pac_id` order: the first squamous (Bethesda), glandular and HPV results within
|
||||
`index_sample_days` of the index date, and the features taken from them. `cytology` maps KPNC's categories, from
|
||||
least to most severe, to the codes of either result; with both results the more severe category wins, and a
|
||||
member with neither, or with codes in no category, gets None. With a `history`, its feature too (`_history`)."""
|
||||
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "glandular", "vph"])]
|
||||
wide = near.sort_values("fecha").pivot_table(index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
|
||||
members = cohort.groupby("pac_id", as_index=False)["fecha_indice"].first()
|
||||
members = members.merge(wide.reindex(columns=["bethesda", "glandular", "vph"]), left_on="pac_id", right_index=True,
|
||||
how="left")
|
||||
codes = members.set_index("pac_id")[["bethesda", "glandular"]].stack()
|
||||
found = _most_severe(codes, cytology).reindex(members["pac_id"]).tolist()
|
||||
members["cytology"] = pd.Series([v if isinstance(v, str) else None for v in found], index=members.index,
|
||||
dtype=object)
|
||||
members["hpv_positive"] = (members["vph"] == "POSITIVO").astype(float)
|
||||
if history:
|
||||
members[history["feature"]] = _history(cohort, members, cytology, history)
|
||||
return members
|
||||
|
||||
|
||||
def _negative_days(cohort: pd.DataFrame, days: pd.Series, event_grades: list[str], known_negative: dict,
|
||||
index_sample_days: int) -> pd.DataFrame:
|
||||
"""`pac_id` and day of every time a member was found free of CIN2+: a biopsy below CIN2+, or a visit with a result
|
||||
of every `known_negative` key among its values, within `index_sample_days` of each other, dated at the last."""
|
||||
timed = cohort.assign(days=days.astype(float))[days >= 0]
|
||||
biopsies = timed[(timed["tipo"] == "biopsia") & ~timed["valor_codigo"].isin(event_grades)][["pac_id", "days"]]
|
||||
visits = None
|
||||
for name, values in known_negative.items():
|
||||
found = timed[(timed["tipo"] == name) & timed["valor_codigo"].isin(values)][["pac_id", "days"]]
|
||||
if visits is None:
|
||||
visits = found
|
||||
continue
|
||||
paired = pd.merge_asof(visits.sort_values("days"), found.rename(columns={"days": name}).sort_values(name),
|
||||
left_on="days", right_on=name, by="pac_id", direction="nearest",
|
||||
tolerance=float(index_sample_days)).dropna(subset=[name])
|
||||
visits = paired.assign(days=paired[["days", name]].max(axis=1))[["pac_id", "days"]]
|
||||
return pd.concat([biopsies, visits], ignore_index=True)
|
||||
|
||||
|
||||
@checked_frame(INTERVAL_CODED)
|
||||
def interval_coded_members(cohort: pd.DataFrame, event_grades: list[str], prevalent_window_months: int,
|
||||
index_sample_days: int, known_negative: dict, cytology: dict, history: dict) -> pd.DataFrame:
|
||||
"""Each member's features with `c`, `l` and `r` (see the module's docstring)."""
|
||||
days = _days(cohort)
|
||||
window = prevalent_window_months * DAYS_PER_YEAR / 12
|
||||
events = cohort[(cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(event_grades) & (days >= 0)]
|
||||
first_event = days[events.index].groupby(events["pac_id"]).min()
|
||||
negatives = _negative_days(cohort, days, event_grades, known_negative, index_sample_days)
|
||||
before_event = ~(negatives["days"] >= negatives["pac_id"].map(first_event))
|
||||
last_negative = negatives[before_event].groupby("pac_id")["days"].max()
|
||||
|
||||
coded = index_results(cohort, index_sample_days, cytology, history)
|
||||
event_days, free_until = coded["pac_id"].map(first_event), coded["pac_id"].map(last_negative)
|
||||
prevalent = event_days <= window
|
||||
found_free = free_until.notna() & ~prevalent
|
||||
later_event = event_days.notna() & ~prevalent
|
||||
|
||||
coded["c"] = np.where(prevalent, 1, np.where(found_free, 0, likelihood.UNKNOWN))
|
||||
coded["l"] = np.where(found_free & (free_until > window), free_until / DAYS_PER_YEAR, 0.0)
|
||||
coded["r"] = np.where(prevalent, 0.0, np.where(later_event, event_days / DAYS_PER_YEAR, np.inf))
|
||||
return coded
|
||||
|
||||
|
||||
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
|
||||
def train_test_split(interval_coded_members: pd.DataFrame, train_fraction: float) -> dict:
|
||||
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
|
||||
return model_fitting.train_test_split(interval_coded_members, train_fraction, target_column="c")
|
||||
|
||||
|
||||
class PrevalenceIncidenceMixture(BaseEstimator):
|
||||
"""Logistic prevalence and proportional-hazards incidence fitted by maximum likelihood (`likelihood.fit`).
|
||||
|
||||
`incidence` picks the baseline: `{"family": "weibull"}` or `{"family": "ispline", "knots": k, "order": o}`, with
|
||||
`k` knots at quantiles of each stratum's observed times (PIMixture's weakly-parametric model). With `strata`, one
|
||||
mixture per combination of their values, as in Cheung et al. 2020 (stratified by HPV, cytology as covariate): the
|
||||
strata leave both designs and a member of a stratum not seen in training gets NaN. A feature listed in `levels`
|
||||
is categorical: one indicator per level but the first (the reference), keeping in each stratum only the levels
|
||||
seen in its training; a member of a level not seen there, or of none, gets NaN and is left out of the fit.
|
||||
Identical rows are collapsed into frequency weights, which `sample_weight` multiplies.
|
||||
"""
|
||||
|
||||
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(),
|
||||
incidence=None, levels=None):
|
||||
self.horizons_years = horizons_years
|
||||
self.incidence_features = incidence_features
|
||||
self.strata = strata
|
||||
self.incidence = incidence
|
||||
self.levels = levels
|
||||
|
||||
def _baseline(self, y: pd.DataFrame):
|
||||
settings = dict(self.incidence or {"family": "weibull"})
|
||||
family = settings.pop("family")
|
||||
if family == "weibull":
|
||||
return likelihood.WEIBULL
|
||||
if family == "ispline":
|
||||
return likelihood.ISpline(likelihood.quantile_knots(y["l"], y["r"], settings["knots"]),
|
||||
settings.get("order", 3))
|
||||
raise ValueError(f"unknown incidence family {family!r}")
|
||||
|
||||
def _seen(self, X: pd.DataFrame) -> dict:
|
||||
"""Each categorical feature's levels present in `X`, in `levels`' order."""
|
||||
return {f: [v for v in values if (X[f] == v).any()] for f, values in (self.levels or {}).items()
|
||||
if f in X.columns and f not in self.strata}
|
||||
|
||||
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
|
||||
"""Rows whose categorical features take a level in `seen`."""
|
||||
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0) if seen \
|
||||
else np.ones(len(X), dtype=bool)
|
||||
|
||||
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
|
||||
columns = []
|
||||
for f in features:
|
||||
if f in self.strata:
|
||||
continue
|
||||
if f in seen:
|
||||
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
|
||||
else:
|
||||
columns.append(X[f].to_numpy(dtype=float))
|
||||
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
|
||||
|
||||
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
|
||||
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
|
||||
return prevalence, self._columns(X, self.incidence_features, seen)
|
||||
|
||||
def _groups(self, X: pd.DataFrame):
|
||||
if not self.strata:
|
||||
return [((), np.arange(len(X)))]
|
||||
return [(key if isinstance(key, tuple) else (key,), rows)
|
||||
for key, rows in X.groupby(list(self.strata), sort=True).indices.items()]
|
||||
|
||||
def fit(self, X: pd.DataFrame, y: pd.DataFrame, sample_weight=None):
|
||||
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)], axis=1)
|
||||
rows["w"] = 1.0 if sample_weight is None else np.asarray(sample_weight, dtype=float)
|
||||
self.fits_, self.seen_ = {}, {}
|
||||
for key, index in self._groups(X):
|
||||
group = rows.iloc[index]
|
||||
seen = self._seen(group)
|
||||
group = group[self._placed(group, seen)].groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
|
||||
prevalence, incidence = self._design(group[X.columns], seen)
|
||||
self.seen_[key] = seen
|
||||
self.fits_[key] = likelihood.fit(group["c"].to_numpy(), group["l"].to_numpy(), group["r"].to_numpy(),
|
||||
prevalence, incidence, self._baseline(group), group["w"].to_numpy())
|
||||
self.neg_loglik_ = float(sum(f["neg_loglik"] for f in self.fits_.values()))
|
||||
self.converged_ = all(f["converged"] for f in self.fits_.values())
|
||||
return self
|
||||
|
||||
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
|
||||
"""One column per horizon: CR(t). The column of t = 0 is the prevalence."""
|
||||
risks = np.full((len(X), len(self.horizons_years)), np.nan)
|
||||
for key, index in self._groups(X):
|
||||
if key not in self.fits_:
|
||||
continue
|
||||
members = X.iloc[index]
|
||||
placed = self._placed(members, self.seen_[key])
|
||||
prevalence, incidence = self._design(members[placed], self.seen_[key])
|
||||
risks[index[placed]] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence,
|
||||
self.horizons_years)
|
||||
return risks
|
||||
|
||||
|
||||
def fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float], incidence: dict,
|
||||
incidence_features: list[str], strata: list[str], cytology: dict,
|
||||
history: dict) -> PrevalenceIncidenceMixture:
|
||||
return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence,
|
||||
_levels(cytology, history)).fit(train_set[_features(history)],
|
||||
train_set[["c", "l", "r"]])
|
||||
|
||||
|
||||
def test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame,
|
||||
history: dict) -> np.ndarray:
|
||||
return fitted_mixture.predict_proba(test_set[_features(history)])
|
||||
|
||||
|
||||
def _status_at(members: pd.DataFrame, horizon: float) -> np.ndarray:
|
||||
"""1 if CIN2+ is known by `horizon`, 0 if known free at it, NaN if not known."""
|
||||
case = (members["c"] == 1) | ((members["c"] != 1) & (members["r"] <= horizon))
|
||||
free = (members["c"] == 0) & (members["l"] >= horizon) & ~case
|
||||
return np.where(case, 1.0, np.where(free, 0.0, np.nan))
|
||||
|
||||
|
||||
def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame, test_set: pd.DataFrame,
|
||||
test_cumulative_risks: np.ndarray, horizons_years: list[float]) -> dict:
|
||||
"""Aggregates only: per horizon, among test members whose status at it is known, how many, the observed and
|
||||
expected rates, the Brier score and, with both classes, the AUC."""
|
||||
found = {"n_train": len(train_set), "n_test": len(test_set), "neg_loglik": float(fitted_mixture.neg_loglik_),
|
||||
"converged": float(fitted_mixture.converged_)}
|
||||
for column, horizon in enumerate(horizons_years):
|
||||
status = _status_at(test_set, horizon)
|
||||
known = ~np.isnan(status) & ~np.isnan(test_cumulative_risks[:, column]) # NaN: a stratum unseen in training
|
||||
y, p = status[known], test_cumulative_risks[known, column]
|
||||
tag = f"{horizon:g}y"
|
||||
found[f"n_known_{tag}"] = int(known.sum())
|
||||
if known.any():
|
||||
found[f"observed_{tag}"] = float(y.mean())
|
||||
found[f"expected_{tag}"] = float(p.mean())
|
||||
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
|
||||
if len(np.unique(y)) == 2:
|
||||
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
|
||||
return found
|
||||
|
||||
|
||||
class IndexResults(TransformerMixin, BaseEstimator):
|
||||
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing."""
|
||||
|
||||
def __init__(self, index_sample_days: int = 30, cytology=None, history=None):
|
||||
self.index_sample_days = index_sample_days
|
||||
self.cytology = cytology
|
||||
self.history = history
|
||||
|
||||
def fit(self, X, y=None):
|
||||
return self
|
||||
|
||||
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
|
||||
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
|
||||
|
||||
|
||||
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict,
|
||||
history: dict) -> Pipeline:
|
||||
"""What's registered: the fitted mixture behind `IndexResults`."""
|
||||
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)),
|
||||
("mixture", fitted_mixture)])
|
||||
@@ -0,0 +1,56 @@
|
||||
domain = "cacu"
|
||||
scenario = "cin2_pim"
|
||||
cohort = "cacu/cohorte_vigilancia"
|
||||
outcome = "cin2"
|
||||
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
|
||||
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
|
||||
# The modules whose functions are the graph's nodes, in `with_modules`.
|
||||
modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"]
|
||||
description = """
|
||||
Prototipo: riesgo acumulado de CIN2+ (biopsia LIEAG, CIS o carcinoma) en la visita índice y a 1, 3 y 5 años, con un \
|
||||
modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \
|
||||
citología índice en las categorías de KPNC como covariable (Cheung et al. 2020). Sin \
|
||||
corrección del sesgo de verificación ni validación clínica."""
|
||||
|
||||
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
|
||||
[config]
|
||||
horizons_years = [0.0, 1.0, 3.0, 5.0]
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
train_fraction = 0.7
|
||||
# Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent.
|
||||
prevalent_window_months = 6
|
||||
# The index sample's results: the first ones within these days of the index date.
|
||||
index_sample_days = 30
|
||||
# The results that make a visit free of CIN2+ without a biopsy: every key with one of its values (KPNC: HPV-negative
|
||||
# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528).
|
||||
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
|
||||
# The incidence's baseline cumulative hazard: { family = "weibull" }, or PIMixture's weakly-parametric
|
||||
# { family = "ispline", knots = k, order = o }, with k knots at quantiles of each stratum's observed times. The
|
||||
# finite times are whole years 1-5, so a basis of more than 5 functions (knots + order - 2) isn't identifiable. KPNC
|
||||
# table 1 is exactly order 4 with 3 knots (bayes-pim, chapter 6).
|
||||
incidence = { family = "ispline", knots = 3, order = 4 }
|
||||
# One mixture per value of these features; the other features enter the prevalence, and those listed here the
|
||||
# incidence. KPNC: stratified by HPV, cytology as covariate (Cheung et al. 2020).
|
||||
strata = ["hpv_positive"]
|
||||
incidence_features = ["cytology"]
|
||||
# A feature of the member's history before the index (e.g. the referral before a colposcopy); none in surveillance.
|
||||
history = {}
|
||||
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
|
||||
# the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma
|
||||
# has no KPNC row: it goes with the high-grade and malignant results.
|
||||
# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance
|
||||
# cohort, applied in the pipeline. The recruitment window is the source cohort's.
|
||||
[config.index]
|
||||
kind = "primera_citologia"
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
|
||||
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
|
||||
observacion_previa_minima_dias = 0
|
||||
|
||||
[config.cytology]
|
||||
NILM = ["NORMAL"]
|
||||
ASC-US = ["ASC-US"]
|
||||
LSIL = ["LIEBG"]
|
||||
ASC-H = ["ASC-H"]
|
||||
AGC = ["AGC"]
|
||||
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
|
||||
@@ -0,0 +1,58 @@
|
||||
domain = "cacu"
|
||||
scenario = "cin2_pim_post_colposcopy"
|
||||
cohort = "cacu/cohorte_total"
|
||||
outcome = "cin2"
|
||||
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
|
||||
# The same dataflow as `cin2_pim`; only the cohort and the config change.
|
||||
modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"]
|
||||
description = """
|
||||
Prototipo: riesgo acumulado de CIN2+ desde la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+, en la visita y a \
|
||||
1, 3 y 5 años (escenario 4 de ASCCP 2019; tabla 17 de KPNC). Mezcla prevalencia–incidencia con I-splines, una por grado \
|
||||
de la referencia (bajo o alto), con el VPH y la citología (tres categorías de KPNC) de esa citología como covariables, \
|
||||
como reproduce exactamente la tabla 17 (capítulo 25 de bayes-pim). CIN2+ porque la biopsia LIEAG no separa CIN2 de CIN3. Sin corrección del sesgo de verificación. PROVISIONAL: una colposcopía sin orden de biopsia (impresión normal) se toma \
|
||||
sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+."""
|
||||
|
||||
[config]
|
||||
horizons_years = [0.0, 1.0, 3.0, 5.0]
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
train_fraction = 0.7
|
||||
prevalent_window_months = 6
|
||||
index_sample_days = 30
|
||||
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
|
||||
incidence = { family = "ispline", knots = 3, order = 4 }
|
||||
# Chapter 25 of bayes-pim: table 17 is reproduced exactly with one baseline per referral grade, the six HPV × cytology
|
||||
# curves proportional within it; one baseline per HPV result is not (residual 4e-3).
|
||||
strata = ["referral_grade"]
|
||||
incidence_features = ["cytology", "hpv_positive"]
|
||||
|
||||
# KPNC groups the post-colposcopy cytology in three: NILM, ASC-US/LSIL and high grade (ASC-H, AGC, HSIL+).
|
||||
# The scenario's index and rules over the total cohort (models/steps/indexing.py), the same as dbt's
|
||||
# cacu/cohorte_post_colposcopia_visita_1 (Cheung et al. 2020): the first surveillance visit with a cotest after the
|
||||
# first colposcopy's result, before any later colposcopy. PROVISIONAL: a colposcopy without a biopsy order is below
|
||||
# CIN2. The recruitment window is the source cohort's (the surveillance cohort's).
|
||||
[config.index]
|
||||
kind = "post_colposcopia"
|
||||
visita = 1
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
referral_lookback_days = 365
|
||||
hysterectomy_cie = ["Z907"]
|
||||
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
|
||||
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
|
||||
observacion_previa_minima_dias = 0
|
||||
|
||||
[config.cytology]
|
||||
NILM = ["NORMAL"]
|
||||
"ASC-US/LSIL" = ["ASC-US", "LIEBG"]
|
||||
"High Grade" = ["ASC-H", "AGC", "LIEAG", "CIS", "ADENOCARCINOMA"]
|
||||
|
||||
# The referral before the colposcopy (Egemen et al. 2020, doi:10.1097/LGT.0000000000000529): low grade is ASC-US,
|
||||
# LSIL or HPV-positive NILM; high grade is ASC-H, AGC or HSIL+. The results in `lookback_days` up to the first
|
||||
# colposcopy, as the cohort's `no_referral_result` rule reads them; a member without one gets none.
|
||||
[config.history]
|
||||
feature = "referral_grade"
|
||||
event = "colposcopia"
|
||||
lookback_days = 365
|
||||
levels = ["low", "high"]
|
||||
low = ["ASC-US/LSIL"]
|
||||
low_if_hpv_positive = ["NILM"]
|
||||
high = ["High Grade"]
|
||||
@@ -0,0 +1,33 @@
|
||||
domain = "cacu"
|
||||
scenario = "cin2_pim_post_treatment"
|
||||
cohort = "cacu/cohorte_post_tratamiento"
|
||||
outcome = "cin2"
|
||||
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
|
||||
# The same dataflow as `cin2_pim`; only the cohort and the config change.
|
||||
modules = ["models.cacu.cin2_pim.model"]
|
||||
description = """
|
||||
Prototipo: riesgo acumulado de CIN2+ desde la primera citología después del tratamiento, en la visita y a 1, 3 y 5 años \
|
||||
(escenario 5 de ASCCP 2019; tablas 24 y 5 de KPNC). Mezcla prevalencia–incidencia con I-splines, una sola línea \
|
||||
base, con el VPH y la citología (tres categorías de KPNC) de esa citología como covariables, como reproduce exactamente \
|
||||
la tabla 24 (capítulo 25 de bayes-pim). Sin estrato de la biopsia previa: \
|
||||
la biopsia LIEAG no separa CIN2 de CIN3, y por lo mismo el desenlace es CIN2+. Sin corrección del sesgo de verificación."""
|
||||
|
||||
[config]
|
||||
horizons_years = [0.0, 1.0, 3.0, 5.0]
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
train_fraction = 0.7
|
||||
prevalent_window_months = 6
|
||||
index_sample_days = 30
|
||||
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
|
||||
incidence = { family = "ispline", knots = 3, order = 4 }
|
||||
# Chapter 25 of bayes-pim: table 24 is reproduced exactly with one baseline for its six HPV × cytology curves (and also
|
||||
# with one per HPV result); the coarser one is kept.
|
||||
strata = []
|
||||
incidence_features = ["cytology", "hpv_positive"]
|
||||
history = {}
|
||||
|
||||
# KPNC groups the post-treatment cytology in three: NILM, ASC-US/LSIL and high grade.
|
||||
[config.cytology]
|
||||
NILM = ["NORMAL"]
|
||||
"ASC-US/LSIL" = ["ASC-US", "LIEBG"]
|
||||
"High Grade" = ["ASC-H", "AGC", "LIEAG", "CIS", "ADENOCARCINOMA"]
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class CaMaModel(ScreeningModel):
|
||||
"""Scaffold for the CaMa (breast cancer) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.cama`'s
|
||||
repositories (`paciente_repository`, `mastografia_repository`,
|
||||
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
|
||||
No real model yet; this is interface scaffolding only.
|
||||
"""
|
||||
|
||||
domain = "cama"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("CaMa training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("CaMa prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""CaMa's scenarios and notebooks."""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Cohorts for the risk models. dbt is their only definition (`Transformation/models/<project>/cohorts/`: population,
|
||||
index date and exclusions as queries in the manifest); this package stores a build of them for the WebApi cycle.
|
||||
|
||||
build.py from dbt's queries to `cohorte_armado` and its rows; the stored frame, wide
|
||||
cama/ CaMa's screening cohort, a PROPOSAL in the old Python-frame format, not built
|
||||
"""
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Armar una cohorte: de las reglas de dbt a `cohorte_armado`, sus miembros y su atrición.
|
||||
|
||||
dbt es la única definición de una cohorte (`Transformation/models/<proyecto>/cohorts/`): su población, su fecha
|
||||
índice y sus exclusiones son consultas del manifest (`models.io.storage.read_queries`), y el armado las corre en la
|
||||
sesión que le dan, con la misma cadena que la exportación (`models.pipelines.cohort_build.build_cohort`). Las
|
||||
reglas que no caben en SQL son del modelo, sobre `cacu/cohorte_total` y la línea de tiempo, no de una cohorte.
|
||||
|
||||
Rearmar con las mismas consultas, los mismos parámetros y los mismos datos no guarda otro armado: la huella del
|
||||
pedido y la del marco (`marco_sha`) ya están. Si los datos cambiaron, el `marco_sha` cambia y se guarda uno nuevo.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from contextlib import nullcontext
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from persistance.edges.dbt import DbtQueryRepository
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from models.io.contracts import CohortQueries
|
||||
from models.pipelines.cohort_build import build_cohort
|
||||
|
||||
|
||||
def json_sha(objeto) -> str:
|
||||
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
|
||||
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
||||
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def queries_sha(queries: CohortQueries) -> str:
|
||||
"""Huella de las reglas: el SQL compilado de cada paso, en su orden. Hace el papel de la definición."""
|
||||
return json_sha({"all_patients": queries.all_patients, "index_date": queries.index_date,
|
||||
"rules": [[rule.order, rule.name, rule.sql] for rule in queries.rules],
|
||||
"variables": queries.variables})
|
||||
|
||||
|
||||
def frame_sha(miembros, variables=()) -> str:
|
||||
"""Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden."""
|
||||
return json_sha({"miembros": sorted([int(m["pac_id"]), m["fecha_indice"].isoformat()] for m in miembros),
|
||||
"variables": sorted([v.pac_id, v.variable, v.valor_codigo, v.valor_numerico] for v in variables)})
|
||||
|
||||
|
||||
def build_of(sesion: Session, queries: CohortQueries, *, cohortes: TablasCohorte, ahora: datetime | None = None):
|
||||
"""El armado sin guardarlo: la fila de `cohorte_armado`, sus exclusiones, sus miembros y sus variables (sin
|
||||
`armado_id`). Las variables son las de la consulta `variables` de la cohorte, si tiene, solo de sus miembros; las
|
||||
que no caben en SQL las calcula el modelo de la línea de tiempo.
|
||||
|
||||
Es lo que recibe `persistance.edges.gold.CohorteRepository.armar` como función de la sesión.
|
||||
"""
|
||||
consultas = DbtQueryRepository(lambda: nullcontext(sesion))
|
||||
built = build_cohort(queries, consultas)
|
||||
miembros = built.study_population.to_dict("records")
|
||||
parametros = {**queries.parameters, "corte": queries.cutoff.isoformat()}
|
||||
reglas_sha = json_sha(queries.parameters)
|
||||
definicion_sha = queries_sha(queries)
|
||||
armado = cohortes.CohorteArmado(
|
||||
url=queries.url, version=queries.version or "0", definicion_sha=definicion_sha, reglas_sha=reglas_sha,
|
||||
parametros=json.dumps(parametros, sort_keys=True), datos_as_of=queries.cutoff,
|
||||
huella=json_sha({"definicion": definicion_sha, "reglas": reglas_sha, "parametros": parametros}),
|
||||
marco_sha="", n_miembros=len(miembros), armado_en=ahora or datetime.now(timezone.utc),
|
||||
)
|
||||
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=fila["step"], n=int(fila["n"]))
|
||||
for orden, fila in enumerate(built.attrition.to_dict("records"), start=1)]
|
||||
filas_miembro = [cohortes.CohorteMiembro(pac_id=int(m["pac_id"]), fecha_indice=m["fecha_indice"],
|
||||
indice_fuente_tabla=m.get("indice_fuente_tabla"),
|
||||
indice_fuente_id=None if m.get("indice_fuente_id") is None
|
||||
else str(m["indice_fuente_id"])) for m in miembros]
|
||||
socias = {int(m["pac_id"]) for m in miembros}
|
||||
variables = [cohortes.CohorteVariable(pac_id=int(v["pac_id"]), variable=v["variable"],
|
||||
valor_codigo=None if v.get("valor_codigo") is None else str(v["valor_codigo"]),
|
||||
valor_numerico=None if v.get("valor_numerico") is None
|
||||
else float(v["valor_numerico"]))
|
||||
for v in (consultas.read(queries.variables) if queries.variables else [])
|
||||
if int(v["pac_id"]) in socias and (v.get("valor_codigo") is not None or v.get("valor_numerico") is not None)]
|
||||
armado.marco_sha = frame_sha(miembros, variables)
|
||||
return armado, exclusiones, filas_miembro, variables
|
||||
|
||||
|
||||
def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int | None:
|
||||
"""El `armado_id` más reciente de la cohorte `url` (el último que se guardó); nulo si no hay. Solo lee."""
|
||||
armado = cohortes.CohorteArmado
|
||||
return sesion.exec(
|
||||
select(armado.armado_id).where(armado.url == url).order_by(armado.armado_id.desc()).limit(1)
|
||||
).first()
|
||||
|
||||
|
||||
def read_frame(sesion: Session, armado_id: int, *, cohortes: TablasCohorte):
|
||||
"""El marco guardado, ancho: (columnas, filas), una por miembro, con las variables que el armado tenga (los de
|
||||
dbt no tienen: solo `pac_id` y `fecha_indice`)."""
|
||||
valores: dict[int, dict] = {}
|
||||
variable = cohortes.CohorteVariable
|
||||
for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)):
|
||||
valores.setdefault(fila.pac_id, {})[fila.variable] = (
|
||||
fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico
|
||||
)
|
||||
nombres = sorted({nombre for porpac in valores.values() for nombre in porpac})
|
||||
miembro = cohortes.CohorteMiembro
|
||||
filas = [
|
||||
(m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres))
|
||||
for m in sesion.exec(select(miembro).where(miembro.armado_id == armado_id).order_by(miembro.pac_id))
|
||||
]
|
||||
return ["pac_id", "fecha_indice", *nombres], filas
|
||||
@@ -0,0 +1 @@
|
||||
"""CaMa's cohorts: the screening cohort, a proposal the cycle doesn't build yet."""
|
||||
@@ -0,0 +1,63 @@
|
||||
# Cohorte de tamizaje mastográfico de CaMa: quién entra al modelo de riesgo de cáncer de mama y con qué marco.
|
||||
#
|
||||
# PROPUESTA (T-21g, 2026-10-21): MD-Q14 está abierta. El índice, la exclusión, el desenlace, el
|
||||
# horizonte y los predictores son una propuesta del orquestador para que CaMa tenga una cohorte que
|
||||
# armar y estimar, como CaCu y TEA. Todas las reglas están en `sin_definir`. Se lee de la línea de
|
||||
# tiempo de CaMa (`cama/linea_de_tiempo.py`).
|
||||
#
|
||||
# Cambiar una regla es cambiar la definición: se sube `version`.
|
||||
|
||||
[group]
|
||||
url = "cama/cohorte_tamizaje"
|
||||
version = "0.1.0"
|
||||
status = "draft"
|
||||
membership = "definitional"
|
||||
title = "Pacientes con un primer BI-RADS"
|
||||
expression = "cama.screening:frame"
|
||||
indice = "Primer BI-RADS de la historia de la paciente (fecha de su resultado), si cae en la ventana de reclutamiento"
|
||||
desenlace = "cancer_de_mama"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "cancer_previo"
|
||||
exclude = true
|
||||
description = "Cáncer de mama antes de la fecha índice: una nota con un CIE-10 de `cie_antecedente` o una biopsia con grado en `grados_cancer`"
|
||||
|
||||
[group.reglas]
|
||||
grados_cancer = ["CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"]
|
||||
cie_antecedente = ["D05", "D050", "D051", "D057", "D059", "C50", "C500", "C501", "C502", "C503", "C504", "C505", "C506", "C508", "C509"]
|
||||
horizonte_dias = 365
|
||||
|
||||
[group.reglas_estado]
|
||||
grados_cancer = { estado = "sin_definir", fuente = "Propuesta T-21g: la lista de `cama.biopsia_cancer` (provisional para CAMA_BIOPSIAS)" }
|
||||
cie_antecedente = { estado = "sin_definir", fuente = "Propuesta T-21g: la lista de `cama.diagnostico.cie_antecedente` (D05 y C50, como en CaCu)" }
|
||||
horizonte_dias = { estado = "sin_definir", fuente = "Propuesta T-21g: un año desde el BI-RADS índice; decide clínica con modelos (MD-Q14)" }
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "d"
|
||||
role = "outcome"
|
||||
tipo = "numero"
|
||||
title = "Cáncer de mama por biopsia dentro del horizonte: 1 sí, 0 no (horizonte vencido al corte), -999 en observación"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "t"
|
||||
role = "outcome"
|
||||
tipo = "numero"
|
||||
title = "Años del índice a la biopsia con cáncer (sin fila = sin cáncer al corte)"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "birads_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "BI-RADS índice"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "calidad_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Calidad de imagen de la mastografía más reciente al índice"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "n_ordenes_previas"
|
||||
role = "covariate"
|
||||
tipo = "numero"
|
||||
title = "Órdenes de estudio antes del índice"
|
||||
@@ -0,0 +1,81 @@
|
||||
"""El marco de la cohorte de tamizaje mastográfico de CaMa, desde la línea de tiempo (`cohorte_tamizaje.toml`). PROPUESTA (MD-Q14).
|
||||
|
||||
Una fila del marco por miembro:
|
||||
|
||||
d 1 = cáncer de mama por biopsia dentro del horizonte; 0 = sin cáncer y el horizonte venció
|
||||
al corte; -999 = sin cáncer y el horizonte todavía no vence (en observación)
|
||||
t años del índice a la biopsia con cáncer (nulo sin cáncer al corte)
|
||||
|
||||
Quién entra:
|
||||
- el índice es el primer BI-RADS con categoría de toda la historia (la fecha de su resultado), si
|
||||
cae en la ventana de reclutamiento;
|
||||
- se excluye a quien tiene cáncer antes del índice: una nota con un CIE-10 de `cie_antecedente` o
|
||||
una biopsia con grado en `grados_cancer`.
|
||||
|
||||
Predictores, todos conocidos a más tardar en el índice: el BI-RADS índice, la calidad de imagen de
|
||||
la mastografía más reciente y cuántas órdenes de estudio hubo antes.
|
||||
"""
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
DIAS_POR_ANIO = 365.25
|
||||
EN_OBSERVACION = -999
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Member:
|
||||
pac_id: int
|
||||
fecha_indice: date
|
||||
indice_fuente_tabla: str
|
||||
indice_fuente_id: str
|
||||
variables: dict # nombre -> valor; un valor nulo no se guarda
|
||||
|
||||
|
||||
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
|
||||
"""(miembros, atrición). `filas`: la línea de tiempo de CaMa, ya recortada al corte (`hasta=corte`)."""
|
||||
grados = set(reglas["grados_cancer"])
|
||||
cie = set(reglas["cie_antecedente"])
|
||||
horizonte = int(reglas["horizonte_dias"])
|
||||
|
||||
por_paciente = defaultdict(list)
|
||||
for fila in filas:
|
||||
if fila["fecha"] is not None and fila["fecha"] <= corte:
|
||||
por_paciente[fila["pac_id"]].append(fila)
|
||||
|
||||
candidatos = cancer_previo = 0
|
||||
miembros = []
|
||||
for pac_id, eventos in sorted(por_paciente.items()):
|
||||
birads = sorted((e for e in eventos if e["tipo"] == "birads" and e["valor_codigo"]),
|
||||
key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
if not birads or not (inicio <= birads[0]["fecha"] < fin):
|
||||
continue
|
||||
indice = birads[0]
|
||||
fecha_indice = indice["fecha"]
|
||||
candidatos += 1
|
||||
biopsias = sorted(e["fecha"] for e in eventos if e["tipo"] == "biopsia" and e["valor_codigo"] in grados)
|
||||
notas = [e["fecha"] for e in eventos if e["tipo"] == "nota_medica" and e["valor_codigo"] in cie]
|
||||
if any(fecha < fecha_indice for fecha in [*biopsias, *notas]):
|
||||
cancer_previo += 1
|
||||
continue
|
||||
|
||||
posteriores = [(fecha - fecha_indice).days for fecha in biopsias]
|
||||
primero = min(posteriores) if posteriores else None
|
||||
if primero is not None and primero <= horizonte:
|
||||
d = 1
|
||||
elif (corte - fecha_indice).days >= horizonte:
|
||||
d = 0
|
||||
else:
|
||||
d = EN_OBSERVACION
|
||||
|
||||
antes = [e for e in eventos if e["fecha"] <= fecha_indice]
|
||||
mastografias = sorted((e for e in antes if e["tipo"] == "mastografia"), key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
miembros.append(Member(pac_id, fecha_indice, indice["fuente_tabla"], indice["fuente_id"], {
|
||||
"d": d, "t": None if primero is None else primero / DIAS_POR_ANIO, "birads_0": indice["valor_codigo"],
|
||||
"calidad_0": mastografias[-1]["valor_codigo"] if mastografias else None,
|
||||
"n_ordenes_previas": sum(1 for e in antes if e["tipo"] == "orden" and e["fecha"] < fecha_indice),
|
||||
}))
|
||||
|
||||
atricion = [("candidatos", candidatos), ("sin cancer_previo", candidatos - cancer_previo)]
|
||||
return miembros, atricion
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Estimating with any scenario's registered version: score a source's build and write the estimate, once.
|
||||
|
||||
Estimation runs the registered pyfunc, outside Hamilton, so a version estimates the same whatever the repository holds
|
||||
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order;
|
||||
its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a
|
||||
classifier that's the positive class at its one horizon. The output has one row per member and horizon
|
||||
(`ESTIMATE_FRAME`); its metadata names the version, the outcome (`model.toml`'s `outcome`) and the source's reference.
|
||||
"""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
|
||||
from models.dags.training import Scenario
|
||||
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
|
||||
from models.io.lineage import matches
|
||||
from models.io.registry import ResolvedVersion, registered_name, registry
|
||||
from models.io.storage import CohortSource, read_metadata, write_once
|
||||
|
||||
|
||||
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
|
||||
"""Whether the output file already holds this version's scores of this build."""
|
||||
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
|
||||
|
||||
|
||||
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float]) -> pd.DataFrame:
|
||||
"""One row per member (in `pac_id` order, as the model gives them) and horizon."""
|
||||
members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable")
|
||||
if probabilities.ndim != 2 or len(probabilities) != len(members):
|
||||
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members")
|
||||
risks = probabilities[:, -len(horizons):]
|
||||
return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
|
||||
"fecha_indice": np.repeat(members["fecha_indice"].to_numpy(), len(horizons)),
|
||||
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
|
||||
"probabilidad": risks.ravel().astype(float)})
|
||||
|
||||
|
||||
def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
|
||||
version: str | None = None) -> tuple[ResolvedVersion, bool]:
|
||||
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
|
||||
`modelo_sha` is copied when the version has it, and isn't checked."""
|
||||
output_path = Path(output_path)
|
||||
resolved = registry.resolve(scenario.domain, scenario.scenario, version)
|
||||
cohort = source.reference()
|
||||
if already_estimated(output_path, resolved.version, cohort):
|
||||
return resolved, False
|
||||
cohort_frame = source.frame()
|
||||
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
|
||||
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
|
||||
risks = estimate_frame(cohort_frame, probabilities, horizons)
|
||||
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
|
||||
provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario),
|
||||
"modelo_version": resolved.version, "mlflow_run_id": resolved.run_id,
|
||||
"desenlace": scenario.outcome, **cohort}
|
||||
if resolved.modelo_sha:
|
||||
provenance["modelo_sha"] = resolved.modelo_sha
|
||||
table = pa.Table.from_pandas(risks, preserve_index=False)
|
||||
write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path)
|
||||
return resolved, True
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Training any scenario: one driver built from the modules its `model.toml` lists, its config, a cohort source and
|
||||
the adapters.
|
||||
|
||||
A scenario is a folder with `model.toml` and its dataflow. `model.toml` names it (`domain`, `scenario`, `cohort`,
|
||||
`outcome`, `description`), lists the `modules` whose functions are the graph's nodes, and holds `[config]`, the values
|
||||
the dataflow receives through `with_config`. The dataflow goes from `cohort` and `cohort_lineage` to `fitted_model` (a
|
||||
scikit-learn estimator that takes the long frame) and `metrics`, with no I/O.
|
||||
|
||||
Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same.
|
||||
`train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks
|
||||
it failed if the graph fails. `find_trained` answers before anything is built whether this source, the installed
|
||||
`models` version, the config and the environment already have a version. A failing node's inputs, which may hold
|
||||
members' rows, are kept out of Hamilton's error log; the exception still says which node failed.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import tomllib
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
from hamilton import base, driver
|
||||
from hamilton.io.materialization import from_, to
|
||||
|
||||
from models.io import adapters # noqa: F401 (registers the loaders and the saver)
|
||||
from models.io.lineage import code_version, matches
|
||||
from models.io.registry import registered_name, registry
|
||||
from models.io.storage import CohortSource
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
REGISTERED_MODEL = "registered_model"
|
||||
# The logger that prints a failing node's inputs (`hamilton.execution.graph_functions.create_error_message`).
|
||||
HAMILTON_NODE_ERRORS = "hamilton.execution.graph_functions"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Scenario:
|
||||
domain: str
|
||||
scenario: str
|
||||
cohort: str
|
||||
outcome: str
|
||||
description: str
|
||||
modules: tuple[ModuleType, ...]
|
||||
config: dict
|
||||
folder: Path
|
||||
requirements: tuple[str, ...] = ()
|
||||
|
||||
@classmethod
|
||||
def from_toml(cls, path: str | Path) -> "Scenario":
|
||||
path = Path(path)
|
||||
found = tomllib.loads(path.read_text())
|
||||
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
|
||||
outcome=found["outcome"], description=found.get("description", ""),
|
||||
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
|
||||
folder=path.parent, requirements=tuple(found.get("requirements", ())))
|
||||
|
||||
@classmethod
|
||||
def load(cls, domain: str, scenario: str) -> "Scenario":
|
||||
"""`models/<domain>/<scenario>/model.toml`; `LookupError` if there's no such scenario."""
|
||||
try:
|
||||
package = import_module(f"models.{domain}.{scenario}")
|
||||
except ModuleNotFoundError as error:
|
||||
raise LookupError(f"no such model: {domain}/{scenario}") from error
|
||||
return cls.from_toml(Path(package.__file__).parent / "model.toml")
|
||||
|
||||
def config_sha256(self) -> str:
|
||||
return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest()
|
||||
|
||||
|
||||
def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver:
|
||||
"""The graph of these modules. Without materializers it takes `cohort` and `cohort_lineage` as inputs."""
|
||||
builder = driver.Builder().with_modules(*modules).with_config(config)
|
||||
if materializers:
|
||||
builder = builder.with_materializers(*materializers)
|
||||
return builder.build()
|
||||
|
||||
|
||||
# What the saver receives: the fitted model and its metrics, and the routines' records when the dataflow has them.
|
||||
SAVED = {"fitted_model", "metrics", "routines"}
|
||||
|
||||
|
||||
def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]:
|
||||
"""The graph's inputs that some node requires, and those every node taking them has a default for."""
|
||||
variables = dr.list_available_variables()
|
||||
inputs = {v.name for v in variables if v.is_external_input}
|
||||
required = set().union(*(v.required_dependencies for v in variables)) & inputs
|
||||
return required, inputs - required
|
||||
|
||||
|
||||
def expected_params(scenario: Scenario, source: CohortSource) -> dict[str, str]:
|
||||
return {**source.reference(), **code_version(), "config_sha256": scenario.config_sha256()}
|
||||
|
||||
|
||||
def find_trained(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str | None:
|
||||
"""The newest version not retired from the same source reference, `models` version, config and environment."""
|
||||
name = registered_name(scenario.domain, scenario.scenario)
|
||||
expected = expected_params(scenario, source)
|
||||
versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True)
|
||||
for mv in versions:
|
||||
if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"):
|
||||
continue
|
||||
if matches(registry.client.get_run(mv.run_id).data.params, expected):
|
||||
return str(mv.version)
|
||||
return None
|
||||
|
||||
|
||||
def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str:
|
||||
"""Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
|
||||
rows."""
|
||||
logging.getLogger(HAMILTON_NODE_ERRORS).setLevel(logging.CRITICAL)
|
||||
run = TrainingRun(domain=scenario.domain, scenario=scenario.scenario, environment=environment,
|
||||
cohorte_armado_id=source.armado_id, cohort=source.reference())
|
||||
try:
|
||||
plain = dataflow(*scenario.modules, config=scenario.config)
|
||||
required, _ = external_inputs(plain)
|
||||
loaders = [loader(target=target, source=source) for target, loader in
|
||||
(("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source),
|
||||
("cohort_lineage", from_.cohort_source_lineage))
|
||||
if target in required]
|
||||
produced = {v.name for v in plain.list_available_variables() if not v.is_external_input}
|
||||
saver = to.registered_model(id=REGISTERED_MODEL, dependencies=sorted(SAVED & produced),
|
||||
combine=base.DictResult(), run=run, description=scenario.description,
|
||||
hyperparameters={**expected_params(scenario, source), **scenario.config},
|
||||
requirements=list(scenario.requirements))
|
||||
dr = dataflow(*scenario.modules, config=scenario.config, materializers=(*loaders, saver))
|
||||
result = dr.execute([REGISTERED_MODEL])
|
||||
except BaseException:
|
||||
run.client.set_terminated(run.run_id, status="FAILED")
|
||||
raise
|
||||
return result[REGISTERED_MODEL]["version"]
|
||||
@@ -0,0 +1,236 @@
|
||||
"""TEA's EEG analysis against the database: which EEGs to analyse, the batch, and its results written to bronze.
|
||||
|
||||
An EEG is pending when it has an EDF and was never analysed, or was analysed with another plan or other module
|
||||
versions, or, being valid, against baselines other than those now in production. One that failed with the current
|
||||
plan and versions waits for a new one instead of failing again on every run.
|
||||
|
||||
Each result replaces the EEG's previous checks, metrics and electrode values in `eeg`, `eeg_criterio`,
|
||||
`eeg_metrica` and `eeg_metrica_electrodo`. Row ids derive from the EEG and what each row is, so a row keeps its id
|
||||
from one analysis to the next and the silver load sees it as changed rather than new. Each result is committed with
|
||||
its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished.
|
||||
|
||||
`cluster` is the `tea` library's: "sync" runs in this process, "local" on a LocalCluster, "auto" on the scheduler in
|
||||
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
|
||||
"""
|
||||
import uuid
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlmodel import Session, col, delete, select
|
||||
|
||||
from core.tea.enums import MetricaEeg
|
||||
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes
|
||||
|
||||
from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions
|
||||
from models.tea.eeg.baselines import Baselines
|
||||
from models.tea.eeg.settings import Settings, settings as model_settings
|
||||
|
||||
COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo"
|
||||
|
||||
|
||||
def checked_settings() -> Settings:
|
||||
"""The analysis's settings, checked against the metric catalog the tables use."""
|
||||
s = model_settings()
|
||||
codes = sorted(m.code for m in s.metrics)
|
||||
if codes != sorted(c.value for c in MetricaEeg):
|
||||
raise ValueError(f"model.toml must map every MetricaEeg code once, not {codes}")
|
||||
return s
|
||||
|
||||
|
||||
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
|
||||
everything: bool = False, limit: int | None = None) -> list[str]:
|
||||
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
|
||||
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
|
||||
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
|
||||
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
|
||||
out, expected = [], None
|
||||
for eeg_id, valid, stored_hash, stored_versions, error in session.exec(query):
|
||||
if everything or stored_hash != plan_hash or stored_versions != versions:
|
||||
out.append(eeg_id)
|
||||
elif valid == 1 and error is None:
|
||||
stored = dict(session.exec(select(EegMetrica.met_codigo, EegMetrica.met_modelo)
|
||||
.where(EegMetrica.met_eeg_id == eeg_id)).all())
|
||||
expected = models() if expected is None else expected
|
||||
if any(stored.get(code) != label for code, label in expected.items()):
|
||||
out.append(eeg_id)
|
||||
if limit is not None and len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def age_months(born, studied, days_per_month: float) -> float | None:
|
||||
if born is None or studied is None or studied < born:
|
||||
return None
|
||||
return round((studied - born).days / days_per_month, 1)
|
||||
|
||||
|
||||
def inputs(session: Session, eeg_id: str, days_per_month: float) -> tuple[bytes, float | None]:
|
||||
eeg = session.get(Eeg, eeg_id)
|
||||
if eeg is None or eeg.eeg_estudio is None:
|
||||
raise LookupError(f"no EDF for EEG {eeg_id!r}")
|
||||
born = session.exec(select(Pacientes.pac_fecha_nacimiento).where(Pacientes.pac_id == eeg.eeg_pac_id)).first()
|
||||
return bytes(eeg.eeg_estudio), age_months(born, eeg.eeg_fecha_estudio, days_per_month)
|
||||
|
||||
|
||||
def row_id(*parts: object) -> str:
|
||||
return str(uuid.uuid5(uuid.NAMESPACE_URL, "tea:eeg/" + "/".join("" if p is None else str(p) for p in parts)))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Rows:
|
||||
eeg: dict
|
||||
criteria: list[EegCriterio]
|
||||
metrics: list[EegMetrica]
|
||||
electrodes: list[EegMetricaElectrodo]
|
||||
|
||||
|
||||
def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows:
|
||||
eeg = {
|
||||
"eeg_valido": m.valid, "eeg_nivel": m.level, "eeg_fraccion_limpia": m.clean_fraction,
|
||||
"eeg_canales_malos": m.bad_channels, "eeg_ruido_linea_db": m.line_db, "eeg_con_sueno": m.asleep,
|
||||
"eeg_edad_meses": m.age_months, "eeg_plan_hash": m.plan_hash, "eeg_versiones": m.versions,
|
||||
"eeg_analizado_en": at or datetime.now(timezone.utc).replace(tzinfo=None), "eeg_error": m.error,
|
||||
}
|
||||
if m.channels is not None:
|
||||
eeg["eeg_canales"] = m.channels
|
||||
if m.duration_min is not None:
|
||||
eeg["eeg_duracion_min"] = m.duration_min
|
||||
|
||||
seen: dict[tuple[str, str | None], int] = {}
|
||||
criteria = []
|
||||
for c in m.checks:
|
||||
n = seen[c.code, c.electrode] = seen.get((c.code, c.electrode), 0) + 1
|
||||
criteria.append(EegCriterio(
|
||||
cri_id=row_id(m.key, "criterio", c.code, c.electrode, n), cri_eeg_id=m.key, cri_codigo=c.code,
|
||||
cri_electrodo=c.electrode, cri_valor=c.value, cri_valor_texto=c.text, cri_unidad=c.unit,
|
||||
cri_bajo=c.low, cri_alto=c.high, cri_decisivo=int(c.decisive), cri_anormal=int(c.abnormal),
|
||||
))
|
||||
|
||||
by_code = {metric.code: metric for metric in s.metrics}
|
||||
metrics, electrodes = [], []
|
||||
for value in m.metrics:
|
||||
metric = by_code[value.code]
|
||||
met_id = row_id(m.key, "metrica", value.code)
|
||||
deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months)
|
||||
used = [metric.scenario] if deviation is not None else []
|
||||
for electrode, raw in sorted(value.electrodes.items()):
|
||||
at_electrode = None
|
||||
if metric.electrode_scenario:
|
||||
at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode,
|
||||
raw, m.age_months)
|
||||
if at_electrode is not None and metric.electrode_scenario not in used:
|
||||
used.append(metric.electrode_scenario)
|
||||
electrodes.append(EegMetricaElectrodo(
|
||||
mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode,
|
||||
mel_valor=raw, mel_z=at_electrode.z if at_electrode else None,
|
||||
))
|
||||
metrics.append(EegMetrica(
|
||||
met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value,
|
||||
met_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None,
|
||||
met_p5=deviation.p5 if deviation else None, met_mediana=deviation.median if deviation else None,
|
||||
met_p95=deviation.p95 if deviation else None,
|
||||
met_modelo=";".join(baselines.label(scenario) for scenario in used) or None,
|
||||
))
|
||||
return Rows(eeg, criteria, metrics, electrodes)
|
||||
|
||||
|
||||
def save(session: Session, eeg_id: str, new: Rows) -> None:
|
||||
"""Replaces the EEG's analysis in the caller's session; the caller commits."""
|
||||
eeg = session.get(Eeg, eeg_id)
|
||||
if eeg is None:
|
||||
raise LookupError(f"no EEG {eeg_id!r}")
|
||||
for column, value in new.eeg.items():
|
||||
setattr(eeg, column, value)
|
||||
session.add(eeg)
|
||||
metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id)
|
||||
session.exec(delete(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids)))
|
||||
session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id))
|
||||
session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id))
|
||||
session.flush()
|
||||
session.add_all([*new.criteria, *new.metrics, *new.electrodes])
|
||||
|
||||
|
||||
def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings):
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
|
||||
if m.error:
|
||||
quality = f"error: {m.error}"
|
||||
elif m.valid:
|
||||
quality = f"valido: {m.level}"
|
||||
else:
|
||||
quality = "no valido: " + "; ".join(c.code for c in m.checks if c.abnormal and c.decisive)
|
||||
return ExtractionRun(
|
||||
domain=s.domain, entity="eeg", entity_pk=m.key, column_extracted=COLUMNS,
|
||||
source_description="eeg.eeg_estudio (EDF)", source_started_at=started, source_ended_at=ended,
|
||||
transform_description=f"tea {s.impl}, plan {s.plan} {m.plan_hash}; {m.versions}",
|
||||
quality_validation=quality,
|
||||
estatus=(EstatusExtraccion.FALLIDA if m.error else EstatusExtraccion.COMPLETADA).value,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Summary:
|
||||
pending: int = 0
|
||||
valid: int = 0
|
||||
not_valid: int = 0
|
||||
failed: int = 0
|
||||
|
||||
|
||||
def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]:
|
||||
out = {}
|
||||
for m in s.metrics:
|
||||
scenarios = [m.scenario, m.electrode_scenario] if m.electrode_scenario else [m.scenario]
|
||||
out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None
|
||||
return out
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
|
||||
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16,
|
||||
settings: Settings | None = None, baselines: Baselines | None = None,
|
||||
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
s = settings or checked_settings()
|
||||
b = baselines or Baselines(s.domain)
|
||||
pipe = pipeline(s)
|
||||
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
|
||||
with eeg_repository.open_session() as session:
|
||||
ids = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
|
||||
everything=everything, limit=limit)
|
||||
summary = Summary(pending=len(ids))
|
||||
|
||||
def write(m: Measurement) -> None:
|
||||
ended = _now()
|
||||
with eeg_repository.open_session() as session:
|
||||
save(session, m.key, rows(m, s, b, at=ended))
|
||||
session.commit()
|
||||
if log_runs:
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
|
||||
if m.error:
|
||||
summary.failed += 1
|
||||
elif m.valid:
|
||||
summary.valid += 1
|
||||
else:
|
||||
summary.not_valid += 1
|
||||
|
||||
def lost(args, exc) -> Measurement:
|
||||
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
|
||||
error=f"{type(exc).__name__}: the batch lost this study")
|
||||
|
||||
for start in range(0, len(ids), batch):
|
||||
argsets = []
|
||||
with eeg_repository.open_session() as session:
|
||||
for eeg_id in ids[start:start + batch]:
|
||||
edf, age = inputs(session, eeg_id, s.days_per_month)
|
||||
argsets.append((eeg_id, edf, age, s))
|
||||
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost)
|
||||
return summary
|
||||
@@ -1,34 +0,0 @@
|
||||
"""ONNX checkpoint inspection (ML-01b, MLD-03).
|
||||
|
||||
Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`,
|
||||
which hands it to MLflow directly — nothing here manages storage paths.
|
||||
`onnx` is an optional dependency (`models[export]`); without it
|
||||
`inspect_onnx_metadata` returns `{"available": False}`.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
|
||||
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
|
||||
`{"available": False}` when the optional `onnx` package isn't installed;
|
||||
`ValueError` when it is and the file isn't a valid ONNX model."""
|
||||
try:
|
||||
import onnx
|
||||
except ImportError:
|
||||
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
|
||||
|
||||
try:
|
||||
model = onnx.load(str(path))
|
||||
onnx.checker.check_model(model)
|
||||
except Exception as exc:
|
||||
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
|
||||
return {
|
||||
"available": True,
|
||||
"ir_version": model.ir_version,
|
||||
"producer_name": model.producer_name,
|
||||
"producer_version": model.producer_version,
|
||||
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
|
||||
"graph_inputs": [i.name for i in model.graph.input],
|
||||
"graph_outputs": [o.name for o in model.graph.output],
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
"""Data in and out, and the contracts: databases, files, the model registry. Nothing here computes."""
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Hamilton's boundary with storage and MLflow: the loaders and the saver a model's driver attaches.
|
||||
|
||||
A model's dataflow has no I/O: it receives `cohort` and `cohort_lineage` and ends at `fitted_model` and `metrics`. The
|
||||
driver (`models.dags.training`) attaches these adapters with `with_materializers`, so they're nodes of the graph before
|
||||
anything runs and nothing in the model imports MLflow:
|
||||
|
||||
- `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage",
|
||||
source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file).
|
||||
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines"], ...)`: records
|
||||
each routine (ML-01a, `TrainingRun.log_routine`), logs the fitted model in the open `TrainingRun` (`tracking`),
|
||||
records the metrics and the config, closes the run, and registers and describes the version (`registry`). Its value
|
||||
is the version's metadata. A dataflow without `routines` still trains and registers, but the registry won't promote
|
||||
it (`ROUTINE_KINDS`).
|
||||
|
||||
The saver pickles the packages of the model's own classes by value, so the registered version loads with
|
||||
scikit-learn and the model's libraries, without this repository. The saver and the metrics being numbers are what keep members' rows out
|
||||
of MLflow. Names are registered once, here, since Hamilton's adapter registry is global and keyed by name.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import sys
|
||||
from collections.abc import Collection
|
||||
from typing import Any
|
||||
|
||||
import cloudpickle
|
||||
import pandas as pd
|
||||
from hamilton import registry as hamilton_registry
|
||||
from hamilton.io.data_adapters import DataLoader, DataSaver
|
||||
|
||||
from models.io.registry import registered_name, registry
|
||||
from models.io.tracking import TrainingRun, pinned
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class CohortSourceLoader(DataLoader):
|
||||
"""A build's long frame, from whatever source reads it."""
|
||||
|
||||
source: Any
|
||||
|
||||
@classmethod
|
||||
def applicable_types(cls) -> Collection[type]:
|
||||
return [pd.DataFrame]
|
||||
|
||||
@classmethod
|
||||
def name(cls) -> str:
|
||||
return "cohort_source"
|
||||
|
||||
def load_data(self, type_: type) -> tuple[pd.DataFrame, dict[str, Any]]:
|
||||
frame = self.source.frame()
|
||||
return frame, {"source": type(self.source).__name__, "rows": len(frame)}
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class CohortSourceLineageLoader(DataLoader):
|
||||
"""A build's lineage, from whatever source reads it."""
|
||||
|
||||
source: Any
|
||||
|
||||
@classmethod
|
||||
def applicable_types(cls) -> Collection[type]:
|
||||
return [dict]
|
||||
|
||||
@classmethod
|
||||
def name(cls) -> str:
|
||||
return "cohort_source_lineage"
|
||||
|
||||
def load_data(self, type_: type) -> tuple[dict, dict[str, Any]]:
|
||||
return self.source.lineage(), {"source": type(self.source).__name__}
|
||||
|
||||
|
||||
def _own_packages(model) -> list:
|
||||
"""The packages of the classes in a fitted model (the model, or each step of a `Pipeline`) whose code isn't an
|
||||
installed library: `models.cacu.cin2_pim` for a class of `models.cacu.cin2_pim.model`. Those are pickled with the
|
||||
model; scikit-learn and the rest are expected where it's loaded."""
|
||||
found = {}
|
||||
for step in [model, *(step for _, step in getattr(model, "steps", []))]:
|
||||
module = sys.modules[type(step).__module__]
|
||||
if module.__name__ == "__main__" or "site-packages" in (getattr(module, "__file__", None) or "site-packages"):
|
||||
continue
|
||||
package = module.__name__.rpartition(".")[0] or module.__name__
|
||||
found[package] = sys.modules[package]
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _numbers(metrics: dict) -> dict[str, float]:
|
||||
found = {}
|
||||
for key, value in metrics.items():
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise TypeError(f"metrics.{key} is a {type(value).__name__}; only numbers are logged")
|
||||
found[key] = float(value)
|
||||
return found
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class RegisteredModelSaver(DataSaver):
|
||||
"""Records `routines`, when the dataflow has them, logs `fitted_model` in `run` with `requirements` (pinned to the
|
||||
installed versions), records `metrics` (numbers only) and `hyperparameters`, closes the run, registers the version
|
||||
and gives it `description`."""
|
||||
|
||||
run: TrainingRun
|
||||
description: str = ""
|
||||
hyperparameters: dict = dataclasses.field(default_factory=dict)
|
||||
requirements: list = dataclasses.field(default_factory=list)
|
||||
|
||||
@classmethod
|
||||
def applicable_types(cls) -> Collection[type]:
|
||||
return [dict]
|
||||
|
||||
@classmethod
|
||||
def name(cls) -> str:
|
||||
return "registered_model"
|
||||
|
||||
def save_data(self, data: dict) -> dict[str, Any]:
|
||||
model, metrics = data["fitted_model"], _numbers(data["metrics"])
|
||||
for kind, record in data.get("routines", {}).items():
|
||||
self.run.log_routine(kind, record)
|
||||
packages = _own_packages(model)
|
||||
for package in packages:
|
||||
cloudpickle.register_pickle_by_value(package)
|
||||
try:
|
||||
self.run.log_model(model, requirements=pinned(self.requirements) if self.requirements else None)
|
||||
finally:
|
||||
for package in packages:
|
||||
cloudpickle.unregister_pickle_by_value(package)
|
||||
self.run.finish(metrics=metrics, hyperparameters=self.hyperparameters)
|
||||
version = registry.register_run(self.run)
|
||||
if self.description:
|
||||
registry.set_description(self.run.domain, self.run.scenario, version, self.description)
|
||||
return {"registered_model": registered_name(self.run.domain, self.run.scenario), "version": version,
|
||||
"mlflow_run_id": self.run.run_id, "modelo_sha": self.run.modelo_sha}
|
||||
|
||||
|
||||
for _adapter in (CohortSourceLoader, CohortSourceLineageLoader, RegisteredModelSaver):
|
||||
hamilton_registry.register_adapter(_adapter)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""The shapes of the data the pipelines read and write. Nothing here reads or writes.
|
||||
|
||||
- A cohort build's Parquet file (`COHORT_SCHEMA`): long, one row per member and event, with the member's index date on
|
||||
every row.
|
||||
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
|
||||
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member and horizon (`horizonte_anios`, years from the
|
||||
index date; 0 is the prevalence).
|
||||
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`).
|
||||
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
|
||||
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
|
||||
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
|
||||
Persistance's `PROVENANCE` expects.
|
||||
"""
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import date
|
||||
from typing import NamedTuple, Protocol, runtime_checkable
|
||||
|
||||
import pandas as pd
|
||||
import pandera.pandas as pandera
|
||||
import pyarrow as pa
|
||||
|
||||
COHORT_SCHEMA = pa.schema([
|
||||
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
|
||||
("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()),
|
||||
("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()),
|
||||
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
|
||||
])
|
||||
|
||||
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "horizonte_anios", "probabilidad")
|
||||
DAYS_PER_YEAR = 365.25 # horizons and intervals are in years from the index date
|
||||
|
||||
# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow
|
||||
# schema says which columns and types; these say what a valid row and a valid file are.
|
||||
COHORT_FRAME = pandera.DataFrameSchema(
|
||||
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
|
||||
"fecha_indice": pandera.Column(nullable=False),
|
||||
"fecha": pandera.Column(nullable=False),
|
||||
"clase": pandera.Column(str, pandera.Check.str_length(min_value=1)),
|
||||
"tipo": pandera.Column(str, pandera.Check.str_length(min_value=1)),
|
||||
"fuente_tabla": pandera.Column(str, nullable=False),
|
||||
"fuente_id": pandera.Column(str, nullable=False)},
|
||||
checks=pandera.Check(lambda frame: frame.groupby("pac_id")["fecha_indice"].nunique().le(1).all(),
|
||||
error="a member has more than one index date"),
|
||||
name="cohort build")
|
||||
|
||||
ESTIMATE_FRAME = pandera.DataFrameSchema(
|
||||
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
|
||||
"fecha_indice": pandera.Column(nullable=False),
|
||||
"horizonte_anios": pandera.Column(float, pandera.Check.ge(0)),
|
||||
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
|
||||
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
|
||||
|
||||
POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables"
|
||||
|
||||
|
||||
class CohortFileError(ValueError):
|
||||
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s, or its rows break
|
||||
`COHORT_FRAME`."""
|
||||
|
||||
|
||||
class EstimateError(ValueError):
|
||||
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice at one horizon, a negative
|
||||
horizon, a probability outside 0..1."""
|
||||
|
||||
|
||||
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
|
||||
"""`frame` if it satisfies `schema`, else `error` naming every failed check (up to ten)."""
|
||||
try:
|
||||
return schema.validate(frame, lazy=True)
|
||||
except pandera.errors.SchemaErrors as failed:
|
||||
cases = failed.failure_cases[["column", "check", "failure_case"]].head(10).to_dict("records")
|
||||
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
|
||||
|
||||
|
||||
class CohortDefinitionError(ValueError):
|
||||
"""The cohort's queries or their results don't follow the structure a build chains."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExclusionRule:
|
||||
name: str
|
||||
description: str
|
||||
order: int
|
||||
sql: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CohortQueries:
|
||||
url: str
|
||||
all_patients: str
|
||||
index_date: str
|
||||
rules: tuple[ExclusionRule, ...]
|
||||
cutoff: date
|
||||
parameters: dict
|
||||
version: str = "" # the population meta's `version`: bumped when a rule changes
|
||||
# optional: the members' stored variables, long (`pac_id`, `variable`, `valor_codigo`, `valor_numerico`)
|
||||
variables: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BuiltCohort:
|
||||
"""The study population (`pac_id`, `fecha_indice` and the index event) and the attrition, one row per step."""
|
||||
|
||||
study_population: pd.DataFrame
|
||||
attrition: pd.DataFrame
|
||||
|
||||
|
||||
class Risk(NamedTuple):
|
||||
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
|
||||
|
||||
pac_id: int
|
||||
fecha_indice: date # the model's index date for this member: the horizons count from it
|
||||
horizonte_anios: float # years from `fecha_indice`; 0 = prevalent
|
||||
probabilidad: float # 0 to 1
|
||||
ic_bajo: float | None = None
|
||||
ic_alto: float | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Provenance:
|
||||
"""Which model the risks come from: the keys a batch stores."""
|
||||
|
||||
modelo_nombre: str
|
||||
modelo_version: str
|
||||
mlflow_run_id: str
|
||||
modelo_sha: str
|
||||
|
||||
def as_dict(self) -> dict[str, str]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class RiskEstimator(Protocol):
|
||||
"""What every risk model the orchestration can call provides."""
|
||||
|
||||
cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia")
|
||||
outcome: str # what it predicts ("cin2_mas")
|
||||
|
||||
def provenance(self) -> Provenance: ...
|
||||
|
||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Each domain's extraction ranker (`extraction.nlp.ranking.LearnedRanker`), versioned in the model registry as
|
||||
`<domain>-extraccion` like any other model (ML-01a, ML-01b, ML-02).
|
||||
|
||||
Every batch it learns from, whether an answer key or the corrections made while reviewing an import, becomes a new
|
||||
DEV version. That version continues from the latest one, and its run records the five routines of what it learned.
|
||||
Extraction uses the version in production when there is one, and otherwise the latest. `EXTRACTION_RANKER` changes
|
||||
that: `produccion` only takes a version in production, and `ninguno` turns the ranker off.
|
||||
|
||||
What it stores are weights over how candidates were found, never document text, and the routines carry counts only.
|
||||
"""
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Iterable, Sequence
|
||||
|
||||
import mlflow.artifacts
|
||||
import mlflow.pyfunc
|
||||
from extraction.nlp.ranking import TRUST_EXAMPLES, Example, LearnedRanker
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
|
||||
from models.io.lineage import registered_name
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
SCENARIO = "extraccion"
|
||||
RANKER_PATH = "ranker/ranker.json"
|
||||
SELECTION_ENV = "EXTRACTION_RANKER"
|
||||
SOURCE_TAG = "ranker.fuente"
|
||||
|
||||
_lock = threading.Lock()
|
||||
_cache: dict[tuple[str, str], LearnedRanker] = {}
|
||||
|
||||
|
||||
class RankerModel(mlflow.pyfunc.PythonModel):
|
||||
"""The ranker as a pyfunc: `predict` takes rows of named features (a DataFrame column `features` of dicts, or a
|
||||
list of dicts) and returns the probability that each candidate is the right value."""
|
||||
|
||||
def __init__(self, state: dict[str, Any]):
|
||||
self.state = state
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
ranker = LearnedRanker.from_dict(self.state)
|
||||
rows = model_input["features"].tolist() if hasattr(model_input, "columns") else list(model_input)
|
||||
return [ranker.probability(row) for row in rows]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Batch:
|
||||
"""What one learning step saw: the examples, and counts for its routine records."""
|
||||
|
||||
examples: Sequence[Example]
|
||||
source: str
|
||||
documents: int
|
||||
records: int
|
||||
# Per field, how many records had a right value that no candidate proposed.
|
||||
unreachable: dict[str, int]
|
||||
|
||||
|
||||
def _versions(client: MlflowClient, domain: str) -> list:
|
||||
try:
|
||||
return sorted(client.search_model_versions(f"name='{registered_name(domain, SCENARIO)}'"), key=lambda mv: int(mv.version))
|
||||
except MlflowException:
|
||||
return []
|
||||
|
||||
|
||||
def _selected(client: MlflowClient, domain: str, *, for_learning: bool = False):
|
||||
from models.io.registry import PRODUCTION_ALIAS
|
||||
|
||||
mode = os.environ.get(SELECTION_ENV, "auto").strip().lower()
|
||||
if mode == "ninguno" and not for_learning:
|
||||
return None
|
||||
if not for_learning:
|
||||
try:
|
||||
return client.get_model_version_by_alias(registered_name(domain, SCENARIO), PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
if mode == "produccion":
|
||||
return None
|
||||
versions = _versions(client, domain)
|
||||
return versions[-1] if versions else None
|
||||
|
||||
|
||||
def _load(client: MlflowClient, domain: str, mv) -> LearnedRanker:
|
||||
key = (domain, str(mv.version))
|
||||
if key not in _cache:
|
||||
state = mlflow.artifacts.load_dict(f"runs:/{mv.run_id}/{RANKER_PATH}")
|
||||
_cache[key] = LearnedRanker.from_dict(state, version=f"{SCENARIO}:{mv.version}")
|
||||
return _cache[key].copy()
|
||||
|
||||
|
||||
def current(domain: str) -> LearnedRanker | None:
|
||||
"""The ranker extraction should use for `domain`, or `None` to rank by confidence alone."""
|
||||
if os.environ.get(SELECTION_ENV, "").strip().lower() == "ninguno":
|
||||
return None
|
||||
client = MlflowClient()
|
||||
mv = _selected(client, domain)
|
||||
return _load(client, domain, mv) if mv is not None else None
|
||||
|
||||
|
||||
def learn(domain: str, batch: Batch) -> str | None:
|
||||
"""Continues the latest version with `batch` and registers the result as a new DEV version; returns it, or
|
||||
`None` when the batch has nothing to learn from."""
|
||||
from models.io.registry import registry
|
||||
|
||||
if not batch.examples:
|
||||
return None
|
||||
with _lock:
|
||||
client = MlflowClient()
|
||||
parent = _selected(client, domain, for_learning=True)
|
||||
ranker = _load(client, domain, parent) if parent is not None else LearnedRanker()
|
||||
before = _quality(ranker, batch.examples)
|
||||
ranker.learn(batch.examples)
|
||||
after = _quality(ranker, batch.examples)
|
||||
run = TrainingRun(domain=domain, scenario=SCENARIO, environment="DEV")
|
||||
client.set_tag(run.run_id, SOURCE_TAG, batch.source)
|
||||
state = ranker.to_dict()
|
||||
client.log_dict(run.run_id, state, RANKER_PATH)
|
||||
for kind, record in _routines(ranker, batch, parent, before, after).items():
|
||||
run.log_routine(kind, record)
|
||||
run.log_model(RankerModel(state))
|
||||
run.finish(
|
||||
metrics={"ejemplos": len(batch.examples), "ejemplos_acumulados": ranker.examples,
|
||||
**{f"{k}_antes": v for k, v in before.items()}, **{f"{k}_despues": v for k, v in after.items()}},
|
||||
hyperparameters={"tasa_aprendizaje": ranker.learning_rate, "l2": ranker.l2, "ejemplos_confianza_plena": TRUST_EXAMPLES},
|
||||
)
|
||||
return registry.register_run(run)
|
||||
|
||||
|
||||
def _quality(ranker: LearnedRanker, examples: Iterable[Example]) -> dict[str, float]:
|
||||
"""Brier score, log loss and accuracy at even odds of the ranker's probabilities on `examples`. Measured before
|
||||
learning from them, it is an honest estimate on data the ranker had not seen (prequential evaluation)."""
|
||||
examples = list(examples)
|
||||
brier = loss = right = 0.0
|
||||
for example in examples:
|
||||
p = ranker.probability(example.x)
|
||||
y = 1.0 if example.label else 0.0
|
||||
brier += (p - y) ** 2
|
||||
loss -= math.log(max(1e-12, p if example.label else 1.0 - p))
|
||||
right += float((p >= 0.5) == example.label)
|
||||
n = max(1, len(examples))
|
||||
return {"brier": round(brier / n, 4), "log_loss": round(loss / n, 4), "exactitud": round(right / n, 4)}
|
||||
|
||||
|
||||
def _routines(ranker: LearnedRanker, batch: Batch, parent, before: dict, after: dict) -> dict[str, dict[str, Any]]:
|
||||
by_field: dict[str, dict[str, int]] = {}
|
||||
for example in batch.examples:
|
||||
counts = by_field.setdefault(example.field, {"correctos": 0, "incorrectos": 0})
|
||||
counts["correctos" if example.label else "incorrectos"] += 1
|
||||
positives = sum(1 for e in batch.examples if e.label)
|
||||
negatives = len(batch.examples) - positives
|
||||
return {
|
||||
"MUESTREO": {
|
||||
"fuente": batch.source,
|
||||
"documentos": batch.documents,
|
||||
"registros": batch.records,
|
||||
"ejemplos": len(batch.examples),
|
||||
"criterio": "cada lectura propuesta de un campo cuyo valor correcto se conoce es un ejemplo",
|
||||
"por_campo": by_field,
|
||||
},
|
||||
"DATOS_FALTANTES": {
|
||||
"tratamiento": "un campo sin valor conocido no aporta ejemplos; uno que debe quedar vacío marca como incorrectas todas sus lecturas",
|
||||
"valor_correcto_sin_lectura": batch.unreachable,
|
||||
},
|
||||
"METODO_ANALITICO": {
|
||||
"metodo": "regresión logística en línea (AdaGrad con L2) sobre cómo se encontró cada lectura",
|
||||
"version_previa": parent.version if parent is not None else None,
|
||||
"ejemplos_acumulados": ranker.examples,
|
||||
"pesos_principales": dict(ranker.strongest()),
|
||||
},
|
||||
"BALANCE_CLASES": {
|
||||
"correctos": positives,
|
||||
"incorrectos": negatives,
|
||||
"ponderacion": "los correctos pesan incorrectos/correctos, hasta 5",
|
||||
},
|
||||
"CONFIANZA_SALIDA": {
|
||||
"antes_de_aprender": before,
|
||||
"despues_de_aprender": after,
|
||||
"confianza_en_el_modelo": round(ranker.trust, 3),
|
||||
"nota": "antes de aprender mide lecturas que el modelo no había visto",
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
"""What each output came from, in one vocabulary for files, runs and versions: the names models are registered under,
|
||||
the keys lineage is recorded with, the code's version, a model's hash, and the rule that an output already exists when
|
||||
its recorded lineage matches what's expected. The hashes of data files live with the files (`models.io.storage`).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea")
|
||||
ARMADO_TAG = "kit.armado_id"
|
||||
MODEL_SHA_TAG = "modelo_sha"
|
||||
MODELS_VERSION_TAG = "models.version"
|
||||
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets; read by `models.tea.eeg.bundle`
|
||||
COHORT_URL_TAG, COHORT_SOURCE_TAG = "cohort.url", "cohort.source"
|
||||
COHORT_BUILD_TAG, COHORT_FILE_TAG = "cohort.build", "cohort.file_sha256"
|
||||
|
||||
|
||||
def registered_name(domain: str, scenario: str) -> str:
|
||||
return f"{domain}-{scenario}"
|
||||
|
||||
|
||||
def code_version() -> dict[str, str]:
|
||||
"""The version of the installed `models` package: what a run's code is, with or without a repository."""
|
||||
return {MODELS_VERSION_TAG: version("models")}
|
||||
|
||||
|
||||
def model_sha(model_dir: str | Path) -> str:
|
||||
"""sha256 of a saved model's pickle (`python_model.pkl` for a pyfunc, `model.pkl` for scikit-learn): the fitted
|
||||
model itself. `MLmodel` is left out because it carries ids and dates, so the same model saved twice has the same
|
||||
sha."""
|
||||
folder = Path(model_dir)
|
||||
pickle = next(path for path in (folder / "python_model.pkl", folder / "model.pkl") if path.exists())
|
||||
return hashlib.sha256(pickle.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def matches(recorded: dict, expected: dict) -> bool:
|
||||
"""Whether an output's recorded lineage has every expected value: then it is already done."""
|
||||
return all(str(recorded.get(key)) == str(value) for key, value in expected.items())
|
||||
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
|
||||
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
|
||||
about on its own: the promotion checks tied to the cohort a version was
|
||||
trained on and to the validation-report convention, and `PredictionService`,
|
||||
which stores each single prediction with the version in production (MLD-4/5,
|
||||
EL-04b).
|
||||
|
||||
Training, versioning, artifact storage and stage live in MLflow itself
|
||||
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
|
||||
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
|
||||
of its versions, never stored here and read from MLflow on every call.
|
||||
Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
|
||||
database). A version points to its build with the `kit.armado_id` tag, and
|
||||
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from core.governance.models import ModelPrediction
|
||||
import mlflow.artifacts
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
from sqlmodel import select
|
||||
|
||||
from models.io.lineage import (
|
||||
ARMADO_TAG,
|
||||
COHORT_BUILD_TAG,
|
||||
COHORT_SOURCE_TAG,
|
||||
COHORT_URL_TAG,
|
||||
DOMAINS,
|
||||
MODEL_SHA_TAG,
|
||||
registered_name,
|
||||
)
|
||||
from models.io.tracking import MODEL_PATH, ROUTINE_KINDS, ROUTINES_PATH, TrainingRun, run_file, run_files
|
||||
|
||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
||||
PRODUCTION_ALIAS = "produccion"
|
||||
REFERENCE_SOURCE = "referencia" # `cohort.source` of a version trained on a cohort outside the platform
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromotionCheck:
|
||||
code: str
|
||||
requirement: str
|
||||
passed: bool
|
||||
detail: str = ""
|
||||
|
||||
|
||||
class PromotionBlocked(Exception):
|
||||
def __init__(self, checks: list[PromotionCheck]):
|
||||
self.checks = checks
|
||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
|
||||
super().__init__(f"la versión no cumple: {failed}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedVersion:
|
||||
"""The version a caller will use, with what it needs to load it and to say where risks came from.
|
||||
`status` is the version's status when it was resolved (`produccion`, `candidata`, `desarrollo` or
|
||||
`retirada`)."""
|
||||
|
||||
domain: str
|
||||
scenario: str
|
||||
version: str
|
||||
run_id: str
|
||||
status: str
|
||||
modelo_sha: str | None
|
||||
|
||||
@property
|
||||
def model_uri(self) -> str:
|
||||
return f"models:/{registered_name(self.domain, self.scenario)}/{self.version}"
|
||||
|
||||
|
||||
class ModelRegistry:
|
||||
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
|
||||
|
||||
def __init__(self, client: MlflowClient | None = None):
|
||||
self._client = client
|
||||
|
||||
@property
|
||||
def client(self) -> MlflowClient:
|
||||
return self._client or MlflowClient()
|
||||
|
||||
def get(self, domain: str, scenario: str, version: str):
|
||||
try:
|
||||
return self.client.get_model_version(registered_name(domain, scenario), version)
|
||||
except MlflowException as exc:
|
||||
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
|
||||
|
||||
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Every version, newest first. `scenario` needs `domain`; `domain`
|
||||
alone matches every scenario of that domain (MLflow's own
|
||||
`search_registered_models` LIKE filter); neither matches everything."""
|
||||
if domain and domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
if scenario and not re.fullmatch(r"[\w-]+", scenario):
|
||||
raise ValueError(f"escenario inválido: {scenario!r}")
|
||||
if domain and scenario:
|
||||
names = [registered_name(domain, scenario)]
|
||||
elif domain:
|
||||
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
|
||||
else:
|
||||
return [self._describe(mv) for mv in self.client.search_model_versions()]
|
||||
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
|
||||
|
||||
def _status(self, mv) -> str:
|
||||
try:
|
||||
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
|
||||
if str(production.version) == str(mv.version):
|
||||
return "produccion"
|
||||
except MlflowException:
|
||||
pass
|
||||
if mv.tags.get("retirada_en"):
|
||||
return "retirada"
|
||||
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
|
||||
|
||||
def status(self, domain: str, scenario: str, version: str) -> str:
|
||||
return self._status(self.get(domain, scenario, version))
|
||||
|
||||
def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion:
|
||||
"""With no `version`, the one holding the `produccion` alias; with a version, that one, whatever
|
||||
its status (to test or compare a candidate). The status travels with it: confirming risks only
|
||||
accepts versions that were in production."""
|
||||
if version is None:
|
||||
try:
|
||||
mv = self.client.get_model_version_by_alias(registered_name(domain, scenario), PRODUCTION_ALIAS)
|
||||
except MlflowException as exc:
|
||||
raise LookupError(f"({domain}, {scenario}) has no version in production") from exc
|
||||
else:
|
||||
mv = self.get(domain, scenario, version)
|
||||
return ResolvedVersion(domain, scenario, str(mv.version), mv.run_id, self._status(mv),
|
||||
mv.tags.get(MODEL_SHA_TAG))
|
||||
|
||||
def register(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | None = None,
|
||||
metrics: dict[str, Any] | None = None,
|
||||
hyperparameters: dict[str, Any] | None = None,
|
||||
**reports: str | None,
|
||||
) -> str:
|
||||
"""For training code that runs elsewhere and reports over the API: a run with these metrics, registered.
|
||||
In-process training opens its own `TrainingRun` and calls `register_run`."""
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
|
||||
return self.register_run(run.finish(metrics=metrics, hyperparameters=hyperparameters), **reports)
|
||||
|
||||
def register_run(self, run: TrainingRun, **reports: str | None) -> str:
|
||||
"""Registers a run as a new version of `<domain>-<scenario>`, tagged with the promotion inputs (environment,
|
||||
cohort link and cohort file, `modelo_sha`, report URIs), and returns the version."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
name = registered_name(run.domain, run.scenario)
|
||||
try:
|
||||
self.client.create_registered_model(name)
|
||||
except MlflowException as exc:
|
||||
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||
raise
|
||||
version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value}
|
||||
if run.cohorte_armado_id is not None:
|
||||
version_tags[ARMADO_TAG] = str(run.cohorte_armado_id)
|
||||
version_tags.update(run.cohort)
|
||||
if run.modelo_sha is not None:
|
||||
version_tags[MODEL_SHA_TAG] = run.modelo_sha
|
||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
||||
source = f"runs:/{run.run_id}/{MODEL_PATH}" if run.modelo_sha is not None else f"runs:/{run.run_id}"
|
||||
return str(self.client.create_model_version(name, source=source, run_id=run.run_id, tags=version_tags).version)
|
||||
|
||||
def set_description(self, domain: str, scenario: str, version: str, description: str) -> None:
|
||||
self.client.update_model_version(registered_name(domain, scenario), version, description=description)
|
||||
|
||||
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
|
||||
"""MLD-01/01b/03 documents are usually written after training."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
name = registered_name(domain, scenario)
|
||||
for tag, uri in reports.items():
|
||||
self.client.set_model_version_tag(name, version, tag, uri or "")
|
||||
|
||||
def artifacts(self, domain: str, scenario: str, version: str) -> list[dict[str, Any]]:
|
||||
"""Every file the version's run stored, at any depth (`path`, `size` in bytes)."""
|
||||
return run_files(self.client, self.get(domain, scenario, version).run_id)
|
||||
|
||||
def artifact(self, domain: str, scenario: str, version: str, path: str) -> tuple[str, bytes]:
|
||||
"""ML-01b: one stored artifact as a file name and its bytes; a folder (the saved model) comes as a zip.
|
||||
`LookupError` for a path the run doesn't hold."""
|
||||
return run_file(self.client, self.get(domain, scenario, version).run_id, path)
|
||||
|
||||
def _describe(self, mv) -> dict[str, Any]:
|
||||
run = self.client.get_run(mv.run_id)
|
||||
return {
|
||||
"name": mv.name,
|
||||
"version": str(mv.version),
|
||||
"run_id": mv.run_id,
|
||||
"tags": dict(mv.tags),
|
||||
"metrics": dict(run.data.metrics),
|
||||
"created_at": _iso(mv.creation_timestamp),
|
||||
"status": self._status(mv),
|
||||
}
|
||||
|
||||
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
||||
return self._describe(self.get(domain, scenario, version))
|
||||
|
||||
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
||||
"""Everything a version came from and produced: its cohort build (with
|
||||
its attrition), logged artifacts and predictions."""
|
||||
mv = self.get(domain, scenario, version)
|
||||
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
return {
|
||||
"model_version": self.describe(domain, scenario, version),
|
||||
"cohorte_armado": armado,
|
||||
"cohorte_exclusiones": exclusiones,
|
||||
"artifacts": run_files(self.client, mv.run_id),
|
||||
"routines": self.routines(mv.run_id),
|
||||
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
|
||||
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
|
||||
}
|
||||
|
||||
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
|
||||
mv = self.get(domain, scenario, version)
|
||||
run = self.client.get_run(mv.run_id)
|
||||
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
dbt_build = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == "dbt" else None
|
||||
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing.
|
||||
reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
|
||||
metrics = run.data.metrics
|
||||
missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)]
|
||||
sha = mv.tags.get(MODEL_SHA_TAG, "")
|
||||
if armado is not None:
|
||||
cohort_detail = f"huella {armado['huella'][:12]}"
|
||||
elif dbt_build is not None:
|
||||
cohort_detail = f"dbt build {dbt_build} de {mv.tags.get(COHORT_URL_TAG)}"
|
||||
elif reference:
|
||||
cohort_detail = f"cohorte de referencia {mv.tags.get(COHORT_URL_TAG)}, listado {reference[:12]}"
|
||||
else:
|
||||
cohort_detail = "sin cohorte"
|
||||
return [
|
||||
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
|
||||
PromotionCheck(
|
||||
"ML-03",
|
||||
"enlazada al armado de cohorte con el que se entrenó",
|
||||
armado is not None or dbt_build is not None or bool(reference),
|
||||
cohort_detail,
|
||||
),
|
||||
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
|
||||
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
|
||||
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
|
||||
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
|
||||
PromotionCheck("ML-01a", "rutinas registradas por la corrida de entrenamiento", not missing,
|
||||
f"faltan: {', '.join(missing)}" if missing else f"{len(ROUTINE_KINDS)} de {len(ROUTINE_KINDS)}"),
|
||||
PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
|
||||
]
|
||||
|
||||
def routines(self, run_id: str) -> dict[str, Any]:
|
||||
"""The routine records the run wrote while training (`TrainingRun.log_routine`), by kind."""
|
||||
found = {}
|
||||
for item in self.client.list_artifacts(run_id, ROUTINES_PATH):
|
||||
kind = Path(item.path).stem
|
||||
if not item.is_dir and kind in ArtifactKind.__members__:
|
||||
found[kind] = json.loads(mlflow.artifacts.load_text(f"runs:/{run_id}/{item.path}"))
|
||||
return found
|
||||
|
||||
def promote(self, domain: str, scenario: str, version: str):
|
||||
"""Makes this the production version of its scenario, tagging the
|
||||
previous one `retirada_en`. Promotion is always a manual step
|
||||
(MLD-01/01b)."""
|
||||
checks = self.checks(domain, scenario, version)
|
||||
if not all(check.passed for check in checks):
|
||||
raise PromotionBlocked(checks)
|
||||
name = registered_name(domain, scenario)
|
||||
try:
|
||||
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
if str(previous.version) != str(version):
|
||||
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
|
||||
except MlflowException:
|
||||
pass
|
||||
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
|
||||
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
|
||||
return self.get(domain, scenario, version)
|
||||
|
||||
def retire(self, domain: str, scenario: str, version: str):
|
||||
"""Withdraws a version from production; its scenario has no active
|
||||
model until another one is promoted, so predictions stop."""
|
||||
name = registered_name(domain, scenario)
|
||||
try:
|
||||
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
active = None
|
||||
if active is None or str(active.version) != str(version):
|
||||
raise ValueError("la versión no está en producción")
|
||||
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
|
||||
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
|
||||
return self.get(domain, scenario, version)
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _iso(epoch_millis: int) -> str:
|
||||
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
|
||||
|
||||
|
||||
registry = ModelRegistry()
|
||||
|
||||
|
||||
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
|
||||
"""The kit cohort build a version was trained on, and its attrition steps."""
|
||||
if not armado_id:
|
||||
return None, []
|
||||
cohortes = import_module(f"persistance.{domain}").cohort_repository
|
||||
armado = cohortes.get(int(armado_id))
|
||||
if armado is None:
|
||||
return None, []
|
||||
exclusion = cohortes.cohortes.CohorteExclusion
|
||||
pasos = cohortes.read(lambda sesion: sesion.exec(
|
||||
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
|
||||
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
|
||||
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
|
||||
"armado_en": armado.armado_en.isoformat()},
|
||||
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
|
||||
|
||||
|
||||
class Predictor(Protocol):
|
||||
"""What the service needs from a model."""
|
||||
|
||||
def predict(self, data: Any) -> Any: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class Interpretability:
|
||||
"""MLD-03: the minimum a prediction reports for clinical interpretation.
|
||||
Each model fills the ones its method has (odds ratio for a logistic
|
||||
regression, hazard ratio for a survival model)."""
|
||||
|
||||
odds_ratio: float | None = None
|
||||
hazard_ratio: float | None = None
|
||||
probabilidad_acumulada: float | None = None
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"odds_ratio": self.odds_ratio,
|
||||
"hazard_ratio": self.hazard_ratio,
|
||||
"probabilidad_acumulada": self.probabilidad_acumulada,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class ApplicabilityRejected(Exception):
|
||||
"""Raised when the EL-04b applicability gate rejects a row. Callers
|
||||
should report it as a client error (4xx), not a server error."""
|
||||
|
||||
|
||||
class PredictionService:
|
||||
"""Runs a model and records its predictions against the
|
||||
MLflow version holding the `produccion` alias for `(domain, scenario)`.
|
||||
|
||||
If `aplicable` is given, each row (a dict of fields) is checked with it
|
||||
(EL-04b). Inapplicable rows are still scored but stored with
|
||||
`applicability_passed=False`, unless `reject_inapplicable` is set.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: Predictor,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
aplicable: Callable[[dict], bool] | None = None,
|
||||
reject_inapplicable: bool = False,
|
||||
):
|
||||
self.model = model
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.aplicable = aplicable
|
||||
self.reject_inapplicable = reject_inapplicable
|
||||
|
||||
def active_model_version(self):
|
||||
"""The MLflow model version currently holding the `produccion`
|
||||
alias for this (domain, scenario), or `None`."""
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
try:
|
||||
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
return None
|
||||
|
||||
def predict_and_record(
|
||||
self,
|
||||
data: Any,
|
||||
*,
|
||||
pac_id_hospital: str,
|
||||
episodio_id: int | None = None,
|
||||
interpretability: Interpretability | None = None,
|
||||
) -> ModelPrediction:
|
||||
"""Scores `data` and stores the result (MLD-5) tagged with the active
|
||||
MLflow model version (MLD-4). `NotImplementedError` from the model is
|
||||
propagated unchanged.
|
||||
"""
|
||||
applicability_passed = True
|
||||
if self.aplicable is not None:
|
||||
if not isinstance(data, dict):
|
||||
raise TypeError("the applicability check needs the input as a dict of fields")
|
||||
applicability_passed = self.aplicable(data)
|
||||
if not applicability_passed and self.reject_inapplicable:
|
||||
raise ApplicabilityRejected(
|
||||
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
|
||||
)
|
||||
|
||||
# Predict first, so an unimplemented model raises NotImplementedError
|
||||
# even when no version is in production.
|
||||
output = self.model.predict(data)
|
||||
|
||||
model_version = self.active_model_version()
|
||||
if model_version is None:
|
||||
raise RuntimeError(
|
||||
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
|
||||
"promueva una con registry.promote antes de predecir"
|
||||
)
|
||||
|
||||
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
prediction = model_prediction_repository.create(
|
||||
ModelPrediction(
|
||||
mlflow_run_id=model_version.run_id,
|
||||
modelo_nombre=model_version.name,
|
||||
modelo_version=str(model_version.version),
|
||||
domain=self.domain,
|
||||
pac_id_hospital=pac_id_hospital,
|
||||
episodio_id=episodio_id,
|
||||
input_hash=input_hash,
|
||||
output=json.dumps(output, default=str),
|
||||
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
|
||||
confianza=output.get("confianza") if isinstance(output, dict) else None,
|
||||
interpretability=interpretability.to_json() if interpretability else None,
|
||||
applicability_passed=applicability_passed,
|
||||
)
|
||||
)
|
||||
return prediction
|
||||
@@ -0,0 +1,382 @@
|
||||
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates) and
|
||||
their hashes, dbt's manifest, a domain's Persistance repositories, the batches of risks they store, and the cohort
|
||||
sources a model trains and estimates on.
|
||||
|
||||
A cohort source (`KitBuild`, `CohortFile`) gives a build's long frame (`COHORT_SCHEMA`), its lineage (at least `url`
|
||||
and `datos_as_of`, as text) and the reference a run, a version and an estimate keep of it (`cohort.url`,
|
||||
`cohort.source`, `cohort.build`), so the dataflow doesn't know where the rows came from. `KitBuild` reads a kit build
|
||||
now from the domain's database (its members, and their timeline up to its clinical cut-off and, when the build has
|
||||
one, its load cut-off `conocida_hasta`; the lineage records when it was read) and writes nothing; reading it again later may give other rows if the
|
||||
timeline changed. `CohortFile` reads an exported file, kit's or dbt's, and its reference adds the file's hash.
|
||||
|
||||
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder
|
||||
beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
|
||||
repository is used, so a model folder reading its cohort file never loads the database layer.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timezone
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, VARIABLES, CohortDefinitionError,
|
||||
CohortFileError, CohortQueries, ExclusionRule, check_frame)
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
|
||||
|
||||
|
||||
def cohorts_root(database_url: str) -> Path:
|
||||
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
|
||||
if configured := os.environ.get("COHORTS_DIR"):
|
||||
return Path(configured)
|
||||
url = make_url(database_url)
|
||||
if url.get_backend_name() != "sqlite" or not url.database:
|
||||
raise ValueError("this database has no data folder: set COHORTS_DIR")
|
||||
return Path(url.database).parent / "cohorts"
|
||||
|
||||
|
||||
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
|
||||
domain, cohort = url.split("/", 1)
|
||||
return root / domain / cohort / f"{armado_id}.parquet"
|
||||
|
||||
|
||||
def dbt_build_path(root: Path, url: str, number: int) -> Path:
|
||||
return cohort_path(root, url, number).parent / "dbt" / f"{number}.parquet"
|
||||
|
||||
|
||||
def _numbers(folder: Path) -> list[int]:
|
||||
return sorted(int(file.stem) for file in folder.glob("*.parquet") if file.stem.isdigit())
|
||||
|
||||
|
||||
def latest_dbt_build(root: Path, url: str) -> tuple[int, Path] | None:
|
||||
"""The highest-numbered build of dbt's rules, or `None` if there's none."""
|
||||
numbers = _numbers(dbt_build_path(root, url, 0).parent)
|
||||
return (numbers[-1], dbt_build_path(root, url, numbers[-1])) if numbers else None
|
||||
|
||||
|
||||
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
|
||||
"""The file of that build, or of the cohort's latest build that has a file."""
|
||||
if armado_id is None:
|
||||
builds = _numbers(cohort_path(root, url, 0).parent)
|
||||
if not builds:
|
||||
raise FileNotFoundError(f"no exported builds of {url} under {root}")
|
||||
armado_id = max(builds)
|
||||
path = cohort_path(root, url, armado_id)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
|
||||
return path
|
||||
|
||||
|
||||
def list_builds(root: Path, url: str, cohorts=None) -> list[dict]:
|
||||
"""One row per build of the cohort, newest first within each source: dbt's builds from their files' metadata, and,
|
||||
with `cohorts` (the domain's `cohort_repository`), the kit's builds and whether each has its file. Without
|
||||
`cohorts` only files are read, never the database."""
|
||||
rows = []
|
||||
for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)):
|
||||
path = dbt_build_path(root, url, number)
|
||||
lineage = read_metadata(path)
|
||||
rows.append({"source": "dbt", "build": number, "datos_as_of": lineage.get("datos_as_of"),
|
||||
"n_members": lineage.get("n_members"), "created": lineage.get("built_at"), "file": str(path)})
|
||||
for build in (cohorts.builds(url) if cohorts is not None else []):
|
||||
path = cohort_path(root, url, build.armado_id)
|
||||
rows.append({"source": "kit", "build": build.armado_id, "datos_as_of": build.datos_as_of.isoformat(),
|
||||
"n_members": str(build.n_miembros), "created": build.armado_en.isoformat(),
|
||||
"file": str(path) if path.exists() else None})
|
||||
return rows
|
||||
|
||||
|
||||
def exported_builds(root: Path, domain: str) -> list[dict]:
|
||||
"""Every build of the domain's cohorts that has its file, newest first within each cohort and source, read from
|
||||
the files alone: `url`, `source`, `build`, `datos_as_of`, `n_members`."""
|
||||
rows = []
|
||||
folder = root / domain
|
||||
for cohort in sorted(p for p in folder.iterdir() if p.is_dir()) if folder.is_dir() else []:
|
||||
url = f"{domain}/{cohort.name}"
|
||||
for source, place in (("kit", cohort), ("dbt", cohort / "dbt")):
|
||||
for number in reversed(_numbers(place)):
|
||||
lineage = read_metadata(place / f"{number}.parquet")
|
||||
rows.append({"url": url, "source": source, "build": number, "datos_as_of": lineage.get("datos_as_of"),
|
||||
"n_members": lineage.get("n_members") or lineage.get("n_miembros")})
|
||||
return rows
|
||||
|
||||
|
||||
def build_file(root: Path, url: str, source: str, build: int) -> Path:
|
||||
"""The file of one exported build; `LookupError` when it isn't there."""
|
||||
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
||||
if source not in ("kit", "dbt") or not path.exists():
|
||||
raise LookupError(f"no hay archivo de la construcción {source} {build} de {url}")
|
||||
return path
|
||||
|
||||
|
||||
def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict:
|
||||
"""One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build
|
||||
without a file is described from `cohorts` (the domain's `cohort_repository`). `LookupError` if there's no such
|
||||
build."""
|
||||
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
|
||||
if path.exists():
|
||||
lineage = read_metadata(path)
|
||||
for key in ("parametros", "rules", "attrition"):
|
||||
if lineage.get(key):
|
||||
lineage[key] = json.loads(lineage[key])
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
return {"source": source, "build": build, "file": str(path), "file_sha256": digest, "lineage": lineage}
|
||||
stored = cohorts.build(build) if source == "kit" and cohorts is not None else None
|
||||
if stored is None or stored.url != url:
|
||||
raise LookupError(f"no {source} build {build} of {url}")
|
||||
return {"source": "kit", "build": build, "file": None, "file_sha256": None,
|
||||
"lineage": {"url": stored.url, "version": stored.version, "datos_as_of": stored.datos_as_of.isoformat(),
|
||||
"n_members": str(stored.n_miembros), "huella": stored.huella, "armado_en": stored.armado_en.isoformat()}}
|
||||
|
||||
|
||||
def read_cohort(path: str | Path) -> pd.DataFrame:
|
||||
"""The build's rows, after checking the file's schema without reading them."""
|
||||
schema = pq.read_schema(path)
|
||||
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
|
||||
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
||||
return check_frame(COHORT_FRAME, pd.read_parquet(path), CohortFileError, str(path))
|
||||
|
||||
|
||||
def write_once(table: pa.Table, path: Path) -> None:
|
||||
"""The file appears complete or not at all: written beside it, then renamed."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle:
|
||||
partial = Path(handle.name)
|
||||
try:
|
||||
pq.write_table(table, partial)
|
||||
partial.replace(path)
|
||||
finally:
|
||||
partial.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_metadata(path: str | Path) -> dict[str, str]:
|
||||
"""A Parquet file's own metadata, without reading any rows."""
|
||||
metadata = pq.read_metadata(path).metadata or {}
|
||||
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
|
||||
|
||||
|
||||
def _one(nodes: list[dict], kind: str, url: str) -> dict:
|
||||
found = [node for node in nodes if node["config"]["meta"]["kind"] == kind]
|
||||
if len(found) != 1:
|
||||
raise CohortDefinitionError(f"{url} needs exactly one `{kind}` query, not {len(found)}")
|
||||
return found[0]
|
||||
|
||||
|
||||
def _compiled(node: dict) -> str:
|
||||
if not node.get("compiled_code"):
|
||||
raise CohortDefinitionError(f"{node['name']} has no compiled SQL in the manifest: run `dbt compile`")
|
||||
return node["compiled_code"]
|
||||
|
||||
|
||||
def read_queries(manifest: str | Path, url: str) -> CohortQueries:
|
||||
"""The cohort's compiled queries, with its exclusions in their `order`.
|
||||
|
||||
An exclusion may read only the index query and the data, never another of the cohort's queries: that keeps every
|
||||
rule's excluded members, and the study population, independent of the order.
|
||||
"""
|
||||
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
|
||||
nodes = [node for node in nodes if node.get("config", {}).get("meta", {}).get("cohort") == url]
|
||||
if not nodes:
|
||||
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
|
||||
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
|
||||
# a cohort may have no exclusions (`cacu/cohorte_total`): its study population is everyone with an index
|
||||
exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION]
|
||||
orders = [node["config"]["meta"]["order"] for node in exclusions]
|
||||
if len(set(orders)) != len(orders):
|
||||
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
|
||||
variables = [node for node in nodes if node["config"]["meta"]["kind"] == VARIABLES]
|
||||
if len(variables) > 1:
|
||||
raise CohortDefinitionError(f"{url} has more than one `{VARIABLES}` query")
|
||||
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
|
||||
for node in [*exclusions, *variables]:
|
||||
if read := steps & set(node["depends_on"]["nodes"]):
|
||||
raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}")
|
||||
meta = population["config"]["meta"]
|
||||
if "cutoff" not in meta:
|
||||
raise CohortDefinitionError(f"the population query of {url} has no `cutoff` in its meta")
|
||||
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
|
||||
for node in exclusions)
|
||||
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
|
||||
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")),
|
||||
str(meta.get("version", "")), _compiled(variables[0]) if variables else None)
|
||||
|
||||
|
||||
def cohort_urls(manifest: str | Path, domain: str) -> list[str]:
|
||||
"""The urls of the domain's cohorts in dbt's manifest (`meta.cohort` of their population queries), sorted: the
|
||||
cohorts the WebApi cycle builds."""
|
||||
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
|
||||
return sorted({node["config"]["meta"]["cohort"] for node in nodes
|
||||
if node.get("config", {}).get("meta", {}).get("kind") == POPULATION
|
||||
and str(node["config"]["meta"].get("cohort", "")).startswith(f"{domain}/")})
|
||||
|
||||
|
||||
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
|
||||
"""Writes a batch of risks for a kit build through the domain's `cohort_repository`: its `lote_id` and whether it's
|
||||
new. The only write the pipelines make to the database; risks of anyone outside the build are refused."""
|
||||
cohorts = importlib.import_module(f"persistance.{domain}").cohort_repository
|
||||
return cohorts.save_batch(armado_id, provenance, outcome, rows)
|
||||
|
||||
|
||||
def resolve_repository(domain: str, entity: str):
|
||||
"""`entity` is the repository's name in `persistance.<domain>` without
|
||||
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
|
||||
module = importlib.import_module(f"persistance.{domain}")
|
||||
try:
|
||||
return getattr(module, f"{entity}_repository")
|
||||
except AttributeError as exc:
|
||||
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
|
||||
|
||||
|
||||
class ReadOnlyRepository:
|
||||
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
||||
Write methods raise `PermissionError` so a training routine cannot
|
||||
modify clinical data."""
|
||||
|
||||
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
|
||||
|
||||
def __init__(self, repository):
|
||||
self._repository = repository
|
||||
self.model = repository.model
|
||||
|
||||
def get(self, id_):
|
||||
return self._repository.get(id_)
|
||||
|
||||
def list(self, *, limit: int = 100, offset: int = 0, **filters):
|
||||
return self._repository.list(limit=limit, offset=offset, **filters)
|
||||
|
||||
def count(self, **filters) -> int:
|
||||
return self._repository.count(**filters)
|
||||
|
||||
def __getattr__(self, name: str):
|
||||
if name in self._WRITE_METHODS:
|
||||
raise PermissionError(
|
||||
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
|
||||
)
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
def file_sha256(*paths: str | Path) -> str:
|
||||
"""The hash of these files' bytes, in this order."""
|
||||
digest = hashlib.sha256()
|
||||
for path in paths:
|
||||
digest.update(Path(path).read_bytes())
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def table_sha256(table: pa.Table) -> str:
|
||||
"""The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same."""
|
||||
sink = pa.BufferOutputStream()
|
||||
table = table.replace_schema_metadata(None)
|
||||
with pa.ipc.new_stream(sink, table.schema) as stream:
|
||||
stream.write_table(table)
|
||||
return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest()
|
||||
|
||||
|
||||
def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]:
|
||||
"""How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or
|
||||
`dbt`), its number in that source and the file's hash. Only a file whose producer is `dbt` is dbt's; any other is a kit
|
||||
build, numbered by its `armado_id`."""
|
||||
source = "dbt" if metadata.get("producer") == "dbt" else "kit"
|
||||
build = metadata["build"] if source == "dbt" else metadata["armado_id"]
|
||||
return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build),
|
||||
COHORT_FILE_TAG: file_sha256}
|
||||
|
||||
|
||||
def require_match(recorded: dict, expected: dict, what: str) -> None:
|
||||
"""Refuses an output whose recorded lineage disagrees with what's expected of it."""
|
||||
if not matches(recorded, expected):
|
||||
raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}")
|
||||
|
||||
|
||||
class CohortSource(Protocol):
|
||||
armado_id: int | None # the kit build it is, if any (ML-03)
|
||||
|
||||
def frame(self) -> pd.DataFrame: ...
|
||||
|
||||
def lineage(self) -> dict[str, str]: ...
|
||||
|
||||
def reference(self) -> dict[str, str]: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
class KitBuild:
|
||||
"""Kit build `build_id` of `domain`, read from its database. `cohorts` and `timeline` default to the domain's
|
||||
`cohort_repository` and `timeline_repository`; tests pass stand-ins."""
|
||||
|
||||
domain: str
|
||||
build_id: int
|
||||
cohorts: Any = None
|
||||
timeline: Any = None
|
||||
_build: Any = field(default=None, init=False, repr=False)
|
||||
|
||||
def __post_init__(self):
|
||||
if self.cohorts is None or self.timeline is None:
|
||||
repositories = import_module(f"persistance.{self.domain}")
|
||||
self.cohorts = self.cohorts or repositories.cohort_repository
|
||||
self.timeline = self.timeline or repositories.timeline_repository
|
||||
|
||||
@property
|
||||
def armado_id(self) -> int:
|
||||
return self.build.armado_id
|
||||
|
||||
@property
|
||||
def build(self):
|
||||
if self._build is None:
|
||||
self._build = self.cohorts.build(self.build_id)
|
||||
if self._build is None:
|
||||
raise LookupError(f"no kit build {self.build_id} in {self.domain}")
|
||||
return self._build
|
||||
|
||||
def known_until(self) -> datetime | None:
|
||||
"""The build's load cut-off, if it has one; without it everything loaded so far is read."""
|
||||
return self.build.conocida_hasta
|
||||
|
||||
def frame(self) -> pd.DataFrame:
|
||||
from models.steps.cohort_file import cohort_events
|
||||
|
||||
members = self.cohorts.members(self.build_id)
|
||||
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"])
|
||||
rows = self.timeline.read(patients=population["pac_id"].tolist(), until=self.build.datos_as_of,
|
||||
known_until=self.known_until())
|
||||
return cohort_events(rows, population, self.build.datos_as_of)
|
||||
|
||||
def lineage(self) -> dict[str, str]:
|
||||
build = self.build
|
||||
return {"url": build.url, "version": build.version, "armado_id": str(build.armado_id), "producer": "kit",
|
||||
"datos_as_of": build.datos_as_of.isoformat(), "n_members": str(build.n_miembros),
|
||||
"known_until": self.known_until().isoformat() if self.known_until() else "",
|
||||
"parametros": getattr(getattr(self.cohorts, "get", lambda _: None)(self.build_id), "parametros", None) or "{}",
|
||||
"read_at": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
def reference(self) -> dict[str, str]:
|
||||
return {COHORT_URL_TAG: self.build.url, COHORT_SOURCE_TAG: "kit", COHORT_BUILD_TAG: str(self.build_id)}
|
||||
|
||||
|
||||
@dataclass
|
||||
class CohortFile:
|
||||
"""An exported build's Parquet file."""
|
||||
|
||||
path: str | Path
|
||||
|
||||
@property
|
||||
def armado_id(self) -> int | None:
|
||||
lineage = self.lineage()
|
||||
return int(lineage["armado_id"]) if lineage.get("producer") != "dbt" and "armado_id" in lineage else None
|
||||
|
||||
def frame(self) -> pd.DataFrame:
|
||||
return read_cohort(self.path)
|
||||
|
||||
def lineage(self) -> dict[str, str]:
|
||||
return read_metadata(self.path)
|
||||
|
||||
def reference(self) -> dict[str, str]:
|
||||
return cohort_reference(self.lineage(), file_sha256(self.path))
|
||||
@@ -0,0 +1,227 @@
|
||||
"""MLflow runs: what happened in one execution (ML-01..ML-05).
|
||||
|
||||
Does not train anything. It opens an MLflow run, records which cohort
|
||||
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
|
||||
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
|
||||
stores the run, metrics and artifacts.
|
||||
|
||||
Each routine around training (ML-01a: sampling, missing data, analytic
|
||||
method, class balance, output confidence) records what it did while the run
|
||||
is open, with `log_routine`: one JSON per routine under `rutinas/`, made of
|
||||
counts and settings, never rows. Turning a run into a registered
|
||||
version is `models.io.registry`'s. It uses `MlflowClient`'s run-scoped
|
||||
methods instead of the fluent API's global active run, so two runs in one
|
||||
process never interfere.
|
||||
|
||||
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
|
||||
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
|
||||
|
||||
Reports are runs too: `record_report` keeps a rendered notebook and its source as artifacts, in an experiment of
|
||||
their own, and `find_run` finds one already made from the same inputs.
|
||||
|
||||
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
|
||||
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
|
||||
model that produced a risk. Which code trained it is recorded apart: every run is
|
||||
tagged with the installed `models` package's version. A PROD run only logs models
|
||||
whose class lives in a module, never one defined in a notebook.
|
||||
|
||||
A model is a scikit-learn estimator (saved with MLflow's sklearn flavor, served
|
||||
through `predict_proba`) or an `mlflow.pyfunc.PythonModel`. Classes of a package
|
||||
registered with `cloudpickle.register_pickle_by_value` are stored with the model,
|
||||
so it loads without this repository.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import zipfile
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import mlflow.pyfunc
|
||||
import mlflow.sklearn
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from mlflow import MlflowClient
|
||||
|
||||
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, matches, model_sha, registered_name
|
||||
from models.io.storage import ReadOnlyRepository, resolve_repository
|
||||
|
||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||
MODEL_PATH = "model"
|
||||
ROUTINES_PATH = "rutinas"
|
||||
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
|
||||
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
|
||||
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
|
||||
|
||||
|
||||
def routine_path(kind: ArtifactKind | str) -> str:
|
||||
return f"{ROUTINES_PATH}/{ArtifactKind(kind).value}.json"
|
||||
|
||||
|
||||
def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | Path, *,
|
||||
metadata: dict[str, Any] | None = None) -> None:
|
||||
"""ML-01a/ML-01b: logs an artifact file to a run, under a folder named for its kind."""
|
||||
client.log_artifact(run_id, str(path), artifact_path=kind)
|
||||
if metadata:
|
||||
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
|
||||
|
||||
|
||||
def run_files(client: MlflowClient, run_id: str, folder: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Every file a run stored, at any depth: `path` and `size` in bytes."""
|
||||
files = []
|
||||
for item in client.list_artifacts(run_id, folder):
|
||||
files.extend(run_files(client, run_id, item.path) if item.is_dir else [{"path": item.path, "size": item.file_size}])
|
||||
return files
|
||||
|
||||
|
||||
def run_file(client: MlflowClient, run_id: str, path: str) -> tuple[str, bytes]:
|
||||
"""A stored file as its name and bytes, or a stored folder as `<name>.zip`. `LookupError` when the run holds
|
||||
nothing at `path`, which is matched against the run's own listing, never resolved on disk."""
|
||||
path = path.strip("/")
|
||||
files = [item["path"] for item in run_files(client, run_id)]
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
if path in files:
|
||||
local = Path(client.download_artifacts(run_id, path, tmp))
|
||||
return local.name, local.read_bytes()
|
||||
inside = [name for name in files if name.startswith(f"{path}/")]
|
||||
if not path or not inside:
|
||||
raise LookupError(f"la corrida no tiene el artefacto {path!r}")
|
||||
client.download_artifacts(run_id, path, tmp)
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as zipped:
|
||||
for name in inside:
|
||||
zipped.write(Path(tmp) / name, name)
|
||||
return f"{Path(path).name}.zip", archive.getvalue()
|
||||
|
||||
|
||||
def experiment_id(client: MlflowClient, name: str) -> str:
|
||||
"""The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set."""
|
||||
experiment = client.get_experiment_by_name(name)
|
||||
if experiment:
|
||||
return experiment.experiment_id
|
||||
root = os.environ.get(ARTIFACT_ROOT_ENV)
|
||||
return client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
|
||||
|
||||
|
||||
def find_run(client: MlflowClient, experiment: str, expected: dict[str, str]) -> str | None:
|
||||
"""The newest finished run of `experiment` whose tags hold every expected value, or `None`."""
|
||||
found = client.get_experiment_by_name(experiment)
|
||||
if found is None:
|
||||
return None
|
||||
for run in client.search_runs([found.experiment_id], order_by=["attributes.start_time DESC"]):
|
||||
if run.info.status == "FINISHED" and matches(run.data.tags, expected):
|
||||
return run.info.run_id
|
||||
return None
|
||||
|
||||
|
||||
def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], files: dict[str, Path]) -> str:
|
||||
"""A finished run of `experiment` with `tags`, the code version, and each file logged under its kind's folder."""
|
||||
run = client.create_run(experiment_id(client, experiment), tags={**code_version(), **tags})
|
||||
try:
|
||||
for kind, path in files.items():
|
||||
log_artifact_file(client, run.info.run_id, kind, path)
|
||||
except Exception:
|
||||
client.set_terminated(run.info.run_id, "FAILED")
|
||||
raise
|
||||
client.set_terminated(run.info.run_id, "FINISHED")
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
def pinned(requirements: list[str]) -> list[str]:
|
||||
"""Each distribution at the version installed here: `scikit-learn` → `scikit-learn==1.7.2`."""
|
||||
return [f"{name}=={version(name)}" for name in requirements]
|
||||
|
||||
|
||||
class TrainingRun:
|
||||
"""One instance per training execution, wrapping one MLflow run. PROD
|
||||
runs name the cohort build they were trained on, so their metrics trace
|
||||
back to that data (ML-03): `cohort`, the reference to its file
|
||||
(`models.io.lineage.cohort_reference`), or `cohorte_armado_id`, a kit build
|
||||
by number; dev runs may omit both.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | None = None,
|
||||
cohort: dict[str, str] | None = None,
|
||||
):
|
||||
if domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
environment = Environment(environment)
|
||||
if environment is Environment.PROD and cohorte_armado_id is None and cohort is None:
|
||||
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id o cohort).")
|
||||
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.environment = environment
|
||||
self.cohorte_armado_id = cohorte_armado_id
|
||||
self.cohort = dict(cohort or {})
|
||||
self.client = MlflowClient()
|
||||
experiment_id = self._experiment_id()
|
||||
run = self.client.create_run(
|
||||
experiment_id,
|
||||
tags={"domain": domain, "scenario": scenario, "environment": environment.value, **code_version()},
|
||||
)
|
||||
self.run_id = run.info.run_id
|
||||
self.modelo_sha: str | None = None
|
||||
if cohorte_armado_id is not None:
|
||||
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
|
||||
for tag, value in self.cohort.items():
|
||||
self.client.set_tag(self.run_id, tag, value)
|
||||
|
||||
def _experiment_id(self) -> str:
|
||||
return experiment_id(self.client, registered_name(self.domain, self.scenario))
|
||||
|
||||
def repository(self, entity: str) -> ReadOnlyRepository:
|
||||
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
|
||||
return ReadOnlyRepository(resolve_repository(self.domain, entity))
|
||||
|
||||
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
|
||||
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
|
||||
named for its kind."""
|
||||
log_artifact_file(self.client, self.run_id, ArtifactKind(kind).value, path, metadata=metadata)
|
||||
|
||||
def log_routine(self, kind: ArtifactKind | str, record: dict[str, Any]) -> None:
|
||||
"""ML-01a: what one routine did in this run, as it ran. A routine that was deliberately skipped records
|
||||
that too (for instance a class balance of "none"), so the run still says what happened."""
|
||||
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
|
||||
|
||||
def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str:
|
||||
"""Saves `model` under the run's `model` folder, tags the run with its `modelo_sha` and returns it.
|
||||
Once per run. `signature` describes columns and types only: no input example, so no patient data
|
||||
reaches MLflow. `requirements` are what an environment needs to load it (`pinned`); without them
|
||||
MLflow infers them from the environment, which in this repository means its whole lock."""
|
||||
if self.modelo_sha is not None:
|
||||
raise RuntimeError("this run already logged its model")
|
||||
if self.environment is Environment.PROD and type(model).__module__ == "__main__":
|
||||
raise ValueError("a PROD run only logs models whose class lives in a module; "
|
||||
f"{type(model).__name__} was defined in a notebook or script")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / MODEL_PATH
|
||||
if isinstance(model, mlflow.pyfunc.PythonModel):
|
||||
mlflow.pyfunc.save_model(path=str(path), python_model=model, signature=signature,
|
||||
pip_requirements=requirements)
|
||||
else:
|
||||
mlflow.sklearn.save_model(model, str(path), serialization_format="cloudpickle", signature=signature,
|
||||
pyfunc_predict_fn="predict_proba", pip_requirements=requirements)
|
||||
sha = model_sha(path)
|
||||
self.client.log_artifacts(self.run_id, str(path), MODEL_PATH)
|
||||
self.client.set_tag(self.run_id, MODEL_SHA_TAG, sha)
|
||||
self.modelo_sha = sha
|
||||
return sha
|
||||
|
||||
def finish(self, *, metrics: dict[str, Any] | None = None, hyperparameters: dict[str, Any] | None = None) -> "TrainingRun":
|
||||
"""Logs metrics and parameters and closes the run. Registering it as a version is the registry's
|
||||
(`models.io.registry.registry.register_run`)."""
|
||||
for key, value in (metrics or {}).items():
|
||||
self.client.log_metric(self.run_id, key, value)
|
||||
for key, value in (hyperparameters or {}).items():
|
||||
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
|
||||
self.client.set_terminated(self.run_id)
|
||||
return self
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""What a notebook run from the platform works with (`models.reports.experiment`): the cohort build's file it was
|
||||
run on and, if one was chosen, a registered model version.
|
||||
|
||||
from models.notebook import experiment
|
||||
|
||||
exp = experiment()
|
||||
cohort = exp.cohort() # the build's rows, checked against the cohort contract
|
||||
model = exp.model() # the chosen version, loaded; None if none was chosen
|
||||
run = exp.training_run() # a DEV training run linked to this build's file (ML-02, ML-03)
|
||||
run.log_routine("MUESTREO", {...})
|
||||
run.log_model(MyModel(...))
|
||||
version = exp.register(run.finish(metrics={...}))
|
||||
|
||||
The notebook gets no database connection and no access to the platform's MLflow (ML-04, ML-05): the build's file
|
||||
is its data, and what it trains goes to a store of its own that the platform imports afterwards as DEV. Outside the
|
||||
platform, set `COHORT_FILE`, `MODELS_DOMAIN` and `MODELS_SCENARIO` (and `MODEL_VERSION`) to work the same way.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
COHORT_FILE_ENV = "COHORT_FILE"
|
||||
DOMAIN_ENV = "MODELS_DOMAIN"
|
||||
SCENARIO_ENV = "MODELS_SCENARIO"
|
||||
VERSION_ENV = "MODEL_VERSION"
|
||||
MODEL_PATH_ENV = "MODEL_PATH"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Experiment:
|
||||
domain: str
|
||||
scenario: str
|
||||
cohort_path: Path
|
||||
version: str | None = None
|
||||
|
||||
def cohort(self) -> pd.DataFrame:
|
||||
from models.io.storage import read_cohort
|
||||
|
||||
return read_cohort(self.cohort_path)
|
||||
|
||||
def lineage(self) -> dict[str, str]:
|
||||
"""The build's own metadata: its cut-off, parameters, rules and attrition."""
|
||||
from models.io.storage import read_metadata
|
||||
|
||||
return read_metadata(self.cohort_path)
|
||||
|
||||
def model(self):
|
||||
"""The chosen version as an MLflow pyfunc (`.predict(cohort)`), or `None`. On the platform it's a copy of the
|
||||
version's saved model (`MODEL_PATH`); elsewhere it's loaded from the registry."""
|
||||
if self.version is None:
|
||||
return None
|
||||
import mlflow.pyfunc
|
||||
|
||||
if path := os.environ.get(MODEL_PATH_ENV):
|
||||
return mlflow.pyfunc.load_model(path)
|
||||
from models.io.registry import registry
|
||||
|
||||
return mlflow.pyfunc.load_model(registry.resolve(self.domain, self.scenario, self.version).model_uri)
|
||||
|
||||
def training_run(self, scenario: str | None = None):
|
||||
"""A DEV run of this domain, linked to the build's file. On the platform it goes to the job's own MLflow and
|
||||
is copied into the real one, as DEV, when the notebook ends (`models.reports.notebook_import`)."""
|
||||
from models.io.storage import cohort_reference, file_sha256
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
cohort = cohort_reference(self.lineage(), file_sha256(self.cohort_path))
|
||||
return TrainingRun(domain=self.domain, scenario=scenario or self.scenario, environment="DEV", cohort=cohort)
|
||||
|
||||
def register(self, run) -> str:
|
||||
"""Registers a finished run as a new DEV version of its scenario and returns the version."""
|
||||
from models.io.registry import registry
|
||||
|
||||
return registry.register_run(run)
|
||||
|
||||
|
||||
def experiment() -> Experiment:
|
||||
missing = [name for name in (COHORT_FILE_ENV, DOMAIN_ENV, SCENARIO_ENV) if not os.environ.get(name)]
|
||||
if missing:
|
||||
raise RuntimeError(f"this notebook wasn't run from the platform: {', '.join(missing)} not set")
|
||||
return Experiment(os.environ[DOMAIN_ENV], os.environ[SCENARIO_ENV], Path(os.environ[COHORT_FILE_ENV]),
|
||||
os.environ.get(VERSION_ENV) or None)
|
||||
+1
-1
@@ -32,7 +32,7 @@ from extraction import FieldKind, FieldSpec, read_document
|
||||
from extraction.nlp import RecordExtractor, SegmentLine
|
||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
|
||||
from extraction.ocr import TesseractOcr
|
||||
from models.base import resolve_repository
|
||||
from models.io.storage import resolve_repository
|
||||
from persistance.repository import Repository
|
||||
|
||||
# Below this confidence a value is stored but flagged for manual review.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Hamilton modules that wire steps into graphs: each function is a node, each parameter an edge."""
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Builds a cohort: all patients -> index date -> A1 -> ... -> An -> study population.
|
||||
|
||||
Lists the steps of `models.steps.cohort`, gives each rule its own `em_<rule>` and `a_<rule>` node, and runs them.
|
||||
"""
|
||||
|
||||
import types
|
||||
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from hamilton.function_modifiers import group, inject, parameterize, source, value
|
||||
|
||||
from persistance.edges.dbt import DbtQueryRepository
|
||||
|
||||
from models.io.contracts import BuiltCohort, CohortQueries
|
||||
from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population
|
||||
|
||||
INPUTS = ("cohort_queries", "dbt_queries")
|
||||
|
||||
|
||||
def _fresh(function):
|
||||
"""A copy to decorate: Hamilton keeps a decorator on the function itself, so decorating the step would carry it into
|
||||
the next build."""
|
||||
copy = types.FunctionType(function.__code__, function.__globals__, function.__name__, function.__defaults__,
|
||||
function.__closure__)
|
||||
copy.__annotations__, copy.__doc__ = dict(function.__annotations__), function.__doc__
|
||||
copy.__module__, copy.__qualname__ = function.__module__, function.__qualname__
|
||||
return copy
|
||||
|
||||
|
||||
def build_driver(queries: CohortQueries) -> driver.Driver:
|
||||
"""The chain for the cohort's rules, in their order."""
|
||||
rules = list(queries.rules)
|
||||
if not rules: # a cohort without rules (`cacu/cohorte_total`): everyone with an index
|
||||
nodes = [all_patients, indexed, inject(last=source("indexed"))(_fresh(study_population)),
|
||||
inject(populations=value([]), rules=value([]))(_fresh(attrition))]
|
||||
return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build()
|
||||
previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]]
|
||||
nodes = [
|
||||
all_patients,
|
||||
indexed,
|
||||
parameterize(**{f"em_{rule.name}": {"rule": value(rule)} for rule in rules})(_fresh(excluded)),
|
||||
parameterize(**{f"a_{rule.name}": {"population": source(before), "flagged": source(f"em_{rule.name}")}
|
||||
for rule, before in zip(rules, previous)})(_fresh(remaining)),
|
||||
inject(last=source(f"a_{rules[-1].name}"))(_fresh(study_population)),
|
||||
inject(populations=group(*[source(f"a_{rule.name}") for rule in rules]), rules=value(rules))(_fresh(attrition)),
|
||||
]
|
||||
return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build()
|
||||
|
||||
|
||||
def build_cohort(queries: CohortQueries, dbt_queries: DbtQueryRepository) -> BuiltCohort:
|
||||
"""Runs the chain; `dbt_queries` is the domain's `dbt_query_repository`."""
|
||||
results = build_driver(queries).execute(["study_population", "attrition"],
|
||||
inputs={"cohort_queries": queries, "dbt_queries": dbt_queries})
|
||||
return BuiltCohort(results["study_population"], results["attrition"])
|
||||
|
||||
|
||||
def mermaid(graph) -> str:
|
||||
"""The chain as a Mermaid diagram, read from the graph without running it."""
|
||||
def label(name: str) -> str:
|
||||
if name.startswith("em_"):
|
||||
return f'{name}["EM: {name[3:]}"]'
|
||||
if name.startswith("a_"):
|
||||
return f'{name}["A: {name[2:]}"]'
|
||||
return f"{name}[({name})]" if name in ("all_patients", "study_population") else f"{name}[{name}]"
|
||||
|
||||
lines = ["graph LR"]
|
||||
for node in graph.nodes.values():
|
||||
if node.name in INPUTS or node.name == "attrition":
|
||||
continue
|
||||
if node.name.startswith("em_"):
|
||||
lines.append(f' r_{node.name[3:]}[/"R: {node.name[3:]}"/] --> {label(node.name)}')
|
||||
lines += [f" {dependency.name} --> {label(node.name)}" for dependency in node.dependencies
|
||||
if dependency.name not in INPUTS]
|
||||
lines += [f" {dependency.name} -.-> attrition" for dependency in graph.nodes["attrition"].dependencies]
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Exports a cohort build to its Parquet file: the members' events up to the cut-off, with the build's lineage.
|
||||
|
||||
The steps come from `models.steps.cohort_file`, the reading and writing from `models.io`. Two sources share them:
|
||||
|
||||
- `export_kit_build`: a build the kit stored, written once to `<armado_id>.parquet`;
|
||||
- `export_dbt_build`: the study population of dbt's rules, built now. A file whose rows hash like the latest one's is
|
||||
reused; otherwise the next number is written.
|
||||
|
||||
The timeline comes from the domain's `timeline_repository` (dbt's view `<domain>_linea_de_tiempo`), cut at the
|
||||
build's date in the query, and dbt's rules run through its `dbt_query_repository`. Nothing here writes to the
|
||||
database.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
|
||||
from models.io.contracts import CohortQueries
|
||||
from models.io.lineage import matches
|
||||
from models.io.storage import (cohort_path, dbt_build_path, latest_dbt_build, read_metadata, require_match,
|
||||
write_once)
|
||||
from models.pipelines.cohort_build import build_cohort
|
||||
from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage
|
||||
|
||||
NODES = [cohort_events, content_sha256, lineage, cohort_table]
|
||||
|
||||
|
||||
def _table(timeline_rows: list[dict], population: pd.DataFrame, cutoff: date, base_lineage: dict) -> tuple[pa.Table, str]:
|
||||
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*NODES)).build()
|
||||
inputs = {"timeline_rows": timeline_rows, "study_population": population, "cutoff": cutoff, "base_lineage": base_lineage}
|
||||
results = dr.execute(["cohort_table", "content_sha256"], inputs=inputs)
|
||||
return results["cohort_table"], results["content_sha256"]
|
||||
|
||||
|
||||
def export_kit_build(cohorts, timeline, root: Path, domain: str, url: str, build_id: int | None = None) -> tuple[Path, str]:
|
||||
"""The kit build's file, reused if it's there and belongs to the build. `cohorts` and `timeline` are the domain's
|
||||
`cohort_repository` and `timeline_repository`."""
|
||||
build_id = build_id if build_id is not None else cohorts.latest_build(url)
|
||||
build = None if build_id is None else cohorts.build(build_id)
|
||||
if build is None or build.url != url:
|
||||
raise LookupError(f"no such build of {url}: {build_id}")
|
||||
path = cohort_path(root, url, build.armado_id)
|
||||
if path.exists():
|
||||
require_match(read_metadata(path), {"armado_id": build.armado_id, "n_members": build.n_miembros}, str(path))
|
||||
return path, "reused"
|
||||
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in cohorts.members(build.armado_id)],
|
||||
columns=["pac_id", "fecha_indice"])
|
||||
base = {"url": url, "version": build.version, "armado_id": build.armado_id, "domain": domain, "producer": "kit",
|
||||
"parametros": cohorts.get(build.armado_id).parametros or "{}", "datos_as_of": build.datos_as_of.isoformat()}
|
||||
table, _ = _table(timeline.read(until=build.datos_as_of), population, build.datos_as_of, base)
|
||||
write_once(table, path)
|
||||
return path, "exported"
|
||||
|
||||
|
||||
def export_dbt_build(queries: CohortQueries, dbt_queries, timeline, root: Path, domain: str) -> tuple[Path, str]:
|
||||
"""Builds the cohort from dbt's rules and writes it, unless its rows are the latest file's. `dbt_queries` and
|
||||
`timeline` are the domain's `dbt_query_repository` and `timeline_repository`."""
|
||||
built = build_cohort(queries, dbt_queries)
|
||||
latest = latest_dbt_build(root, queries.url)
|
||||
number = latest[0] + 1 if latest else 1
|
||||
base = {"url": queries.url, "build": number, "domain": domain, "producer": "dbt",
|
||||
"parametros": json.dumps(queries.parameters, sort_keys=True), "datos_as_of": queries.cutoff.isoformat(),
|
||||
"rules": json.dumps([rule.name for rule in queries.rules]),
|
||||
"attrition": built.attrition.astype(object).where(built.attrition.notna(), None).to_json(orient="records")}
|
||||
table, sha = _table(timeline.read(until=queries.cutoff), built.study_population, queries.cutoff, base)
|
||||
if latest and matches(read_metadata(latest[1]), {"content_sha256": sha}):
|
||||
return latest[1], "reused"
|
||||
path = dbt_build_path(root, queries.url, number)
|
||||
write_once(table, path)
|
||||
return path, "exported"
|
||||
@@ -0,0 +1,51 @@
|
||||
"""The nodes every model DAG reads through: a cohort build, its members and their timeline.
|
||||
|
||||
Each node's first parameter is the asset it reads, given as an input (`Asset`), so the graph shows
|
||||
which tables a model depends on (`persistance.assets.validate` with them as sources). The repositories
|
||||
are inputs too: whoever builds the driver passes a domain's `cohort_repository` and a
|
||||
`timeline_repository` already bound to its query.
|
||||
|
||||
The timeline is cut at the build's clinical date (`datos_as_of`) and always at an explicit load cut-off
|
||||
(`known_until`): the build's `conocida_hasta`, or the moment of the read when the build has none. The run
|
||||
records `known_until`, so the read can be repeated once silver keeps its history.
|
||||
"""
|
||||
|
||||
from dataclasses import fields
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
from persistance.edges.gold import CohortBuild, CohortMember, CohortRepository
|
||||
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.assets import Asset
|
||||
|
||||
MEMBER_COLUMNS = tuple(f.name for f in fields(CohortMember))
|
||||
|
||||
|
||||
class UnknownBuild(LookupError):
|
||||
"""The requested cohort build doesn't exist."""
|
||||
|
||||
|
||||
def cohort_build(cohorte_armado: Asset, cohort_repository: CohortRepository, build_id: int) -> CohortBuild:
|
||||
"""The build's lineage: cohort, version, fingerprints and cut-offs."""
|
||||
build = cohort_repository.build(build_id)
|
||||
if build is None:
|
||||
raise UnknownBuild(f"cohort build {build_id} doesn't exist")
|
||||
return build
|
||||
|
||||
|
||||
def members(cohorte_miembro: Asset, cohort_repository: CohortRepository, cohort_build: CohortBuild) -> pd.DataFrame:
|
||||
"""One row per member (`MEMBER_COLUMNS`), ordered by `pac_id`."""
|
||||
return pd.DataFrame(cohort_repository.members(cohort_build.armado_id), columns=list(MEMBER_COLUMNS))
|
||||
|
||||
|
||||
def known_until(cohort_build: CohortBuild) -> datetime:
|
||||
"""The load cut-off of the read: the build's `conocida_hasta`, or now (UTC) when the build has none."""
|
||||
return cohort_build.conocida_hasta or datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def timeline(linea_de_tiempo: Asset, members: pd.DataFrame, cohort_build: CohortBuild, known_until: datetime,
|
||||
timeline_repository: TimelineRepository) -> pd.DataFrame:
|
||||
"""The members' events (`TIMELINE_COLUMNS`), cut at the build's `datos_as_of` and at `known_until`."""
|
||||
rows = timeline_repository.read(patients=members["pac_id"].tolist(), until=cohort_build.datos_as_of,
|
||||
known_until=known_until)
|
||||
return pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS))
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`).
|
||||
|
||||
The estimate's metadata carries everything the batch needs: the model version and its run (`modelo_nombre`,
|
||||
`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome, and the cohort build it scored; each row carries its horizon. A batch
|
||||
points to its build by `armado_id`, so only builds with a row in `cohorte_armado` can be stored. Storing the same
|
||||
estimate again adds nothing: Persistance finds the batch by its content.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
|
||||
from models.io.storage import read_metadata, store_risk_batch
|
||||
from models.steps.risks import risk_rows
|
||||
|
||||
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
|
||||
REQUIRED = (*PROVENANCE, "desenlace", COHORT_SOURCE_TAG, COHORT_BUILD_TAG)
|
||||
|
||||
|
||||
def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
|
||||
"""Returns the batch's `lote_id` and whether it was written now."""
|
||||
metadata = read_metadata(estimate_path)
|
||||
if missing := [key for key in REQUIRED if not metadata.get(key)]:
|
||||
raise ValueError(f"{estimate_path} lacks {missing}: write it with `python -m models estimate`")
|
||||
if metadata[COHORT_SOURCE_TAG] != "kit":
|
||||
raise LookupError(f"{estimate_path} scores {metadata[COHORT_SOURCE_TAG]} build {metadata[COHORT_BUILD_TAG]}, "
|
||||
"which has no row in cohorte_armado for its batch to point to")
|
||||
rows = risk_rows(pd.read_parquet(estimate_path))
|
||||
return store_risk_batch(domain, int(metadata[COHORT_BUILD_TAG]), {key: metadata[key] for key in PROVENANCE},
|
||||
metadata["desenlace"], rows)
|
||||
@@ -1,127 +0,0 @@
|
||||
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
|
||||
produced it. Callers go through `PredictionService` rather than calling
|
||||
`model.predict(...)` directly.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from core.governance.models import ModelPrediction
|
||||
from mlflow import MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
|
||||
from models.base import ScreeningModel
|
||||
from models.registry import PRODUCTION_ALIAS, registered_name, registry
|
||||
|
||||
|
||||
@dataclass
|
||||
class Interpretability:
|
||||
"""MLD-03: the minimum a prediction reports for clinical interpretation.
|
||||
Each model fills the ones its method has (odds ratio for a logistic
|
||||
regression, hazard ratio for a survival model)."""
|
||||
|
||||
odds_ratio: float | None = None
|
||||
hazard_ratio: float | None = None
|
||||
probabilidad_acumulada: float | None = None
|
||||
|
||||
def to_json(self) -> str:
|
||||
return json.dumps(
|
||||
{
|
||||
"odds_ratio": self.odds_ratio,
|
||||
"hazard_ratio": self.hazard_ratio,
|
||||
"probabilidad_acumulada": self.probabilidad_acumulada,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class ApplicabilityRejected(Exception):
|
||||
"""Raised when the EL-04b applicability gate rejects a row. Callers
|
||||
should report it as a client error (4xx), not a server error."""
|
||||
|
||||
|
||||
class PredictionService:
|
||||
"""Runs a `ScreeningModel` and records its predictions against the
|
||||
MLflow version holding the `produccion` alias for `(domain, scenario)`.
|
||||
|
||||
If `aplicable` is given, each row (a dict of fields) is checked with it
|
||||
(EL-04b). Inapplicable rows are still scored but stored with
|
||||
`applicability_passed=False`, unless `reject_inapplicable` is set.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model: ScreeningModel,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
aplicable: Callable[[dict], bool] | None = None,
|
||||
reject_inapplicable: bool = False,
|
||||
):
|
||||
self.model = model
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.aplicable = aplicable
|
||||
self.reject_inapplicable = reject_inapplicable
|
||||
|
||||
def active_model_version(self):
|
||||
"""The MLflow model version currently holding the `produccion`
|
||||
alias for this (domain, scenario), or `None`."""
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
try:
|
||||
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
return None
|
||||
|
||||
def predict_and_record(
|
||||
self,
|
||||
data: Any,
|
||||
*,
|
||||
pac_id_hospital: str,
|
||||
episodio_id: int | None = None,
|
||||
interpretability: Interpretability | None = None,
|
||||
) -> ModelPrediction:
|
||||
"""Scores `data` and stores the result (MLD-5) tagged with the active
|
||||
MLflow model version (MLD-4). `NotImplementedError` from the model is
|
||||
propagated unchanged.
|
||||
"""
|
||||
applicability_passed = True
|
||||
if self.aplicable is not None:
|
||||
if not isinstance(data, dict):
|
||||
raise TypeError("the applicability check needs the input as a dict of fields")
|
||||
applicability_passed = self.aplicable(data)
|
||||
if not applicability_passed and self.reject_inapplicable:
|
||||
raise ApplicabilityRejected(
|
||||
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
|
||||
)
|
||||
|
||||
# Predict first, so an unimplemented model raises NotImplementedError
|
||||
# even when no version is in production.
|
||||
output = self.model.predict(data)
|
||||
|
||||
model_version = self.active_model_version()
|
||||
if model_version is None:
|
||||
raise RuntimeError(
|
||||
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
|
||||
"promueva una con models.registry.registry.promote antes de predecir"
|
||||
)
|
||||
|
||||
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
prediction = model_prediction_repository.create(
|
||||
ModelPrediction(
|
||||
mlflow_run_id=model_version.run_id,
|
||||
modelo_nombre=model_version.name,
|
||||
modelo_version=str(model_version.version),
|
||||
domain=self.domain,
|
||||
pac_id_hospital=pac_id_hospital,
|
||||
episodio_id=episodio_id,
|
||||
input_hash=input_hash,
|
||||
output=json.dumps(output, default=str),
|
||||
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
|
||||
confianza=output.get("confianza") if isinstance(output, dict) else None,
|
||||
interpretability=interpretability.to_json() if interpretability else None,
|
||||
applicability_passed=applicability_passed,
|
||||
)
|
||||
)
|
||||
return prediction
|
||||
@@ -1,249 +0,0 @@
|
||||
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
|
||||
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
|
||||
about on its own: the promotion checks tied to the cohort a version was
|
||||
trained on and to the validation-report convention.
|
||||
|
||||
Training, versioning, artifact storage and stage live in MLflow itself
|
||||
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
|
||||
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
|
||||
of its versions, never stored here and read from MLflow on every call.
|
||||
Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
|
||||
database). A version points to its build with the `kit.armado_id` tag, and
|
||||
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
|
||||
"""
|
||||
import re
|
||||
import tempfile
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.governance import model_prediction_repository
|
||||
from sqlmodel import select
|
||||
|
||||
from models.export import inspect_onnx_metadata
|
||||
|
||||
DOMAINS = ("cacu", "cama", "tea")
|
||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
||||
PRODUCTION_ALIAS = "produccion"
|
||||
ARMADO_TAG = "kit.armado_id"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromotionCheck:
|
||||
code: str
|
||||
requirement: str
|
||||
passed: bool
|
||||
detail: str = ""
|
||||
|
||||
|
||||
class PromotionBlocked(Exception):
|
||||
def __init__(self, checks: list[PromotionCheck]):
|
||||
self.checks = checks
|
||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
|
||||
super().__init__(f"la versión no cumple: {failed}")
|
||||
|
||||
|
||||
def registered_name(domain: str, scenario: str) -> str:
|
||||
return f"{domain}-{scenario}"
|
||||
|
||||
|
||||
class ModelRegistry:
|
||||
"""`client` is resolved on every access, so it follows the current `MLFLOW_TRACKING_URI`."""
|
||||
|
||||
def __init__(self, client: MlflowClient | None = None):
|
||||
self._client = client
|
||||
|
||||
@property
|
||||
def client(self) -> MlflowClient:
|
||||
return self._client or MlflowClient()
|
||||
|
||||
def get(self, domain: str, scenario: str, version: str):
|
||||
try:
|
||||
return self.client.get_model_version(registered_name(domain, scenario), version)
|
||||
except MlflowException as exc:
|
||||
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
|
||||
|
||||
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Every version, newest first. `scenario` needs `domain`; `domain`
|
||||
alone matches every scenario of that domain (MLflow's own
|
||||
`search_registered_models` LIKE filter); neither matches everything."""
|
||||
if domain and domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
if scenario and not re.fullmatch(r"[\w-]+", scenario):
|
||||
raise ValueError(f"escenario inválido: {scenario!r}")
|
||||
if domain and scenario:
|
||||
names = [registered_name(domain, scenario)]
|
||||
elif domain:
|
||||
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
|
||||
else:
|
||||
return [self._describe(mv) for mv in self.client.search_model_versions()]
|
||||
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
|
||||
|
||||
def _status(self, mv) -> str:
|
||||
try:
|
||||
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
|
||||
if str(production.version) == str(mv.version):
|
||||
return "produccion"
|
||||
except MlflowException:
|
||||
pass
|
||||
if mv.tags.get("retirada_en"):
|
||||
return "retirada"
|
||||
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
|
||||
|
||||
def status(self, domain: str, scenario: str, version: str) -> str:
|
||||
return self._status(self.get(domain, scenario, version))
|
||||
|
||||
def register(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | None = None,
|
||||
metrics: dict[str, Any] | None = None,
|
||||
hyperparameters: dict[str, Any] | None = None,
|
||||
**reports: str | None,
|
||||
) -> str:
|
||||
"""For training code that runs elsewhere and reports over the API.
|
||||
In-process training uses `models.training.TrainingRun` directly."""
|
||||
from models.training import TrainingRun
|
||||
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
|
||||
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
|
||||
|
||||
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
|
||||
"""MLD-01/01b/03 documents are usually written after training."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
name = registered_name(domain, scenario)
|
||||
for tag, uri in reports.items():
|
||||
self.client.set_model_version_tag(name, version, tag, uri or "")
|
||||
|
||||
def add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None:
|
||||
"""Logs an artifact file to the run behind an already-registered
|
||||
version (ML-01a/b), e.g. a checkpoint exported after training.
|
||||
An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is
|
||||
rejected (400) instead of silently stored."""
|
||||
mv = self.get(domain, scenario, version)
|
||||
kind_value = kind.value if hasattr(kind, "value") else str(kind)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / filename
|
||||
path.write_bytes(data)
|
||||
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
|
||||
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
|
||||
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
|
||||
|
||||
def _describe(self, mv) -> dict[str, Any]:
|
||||
run = self.client.get_run(mv.run_id)
|
||||
return {
|
||||
"name": mv.name,
|
||||
"version": str(mv.version),
|
||||
"run_id": mv.run_id,
|
||||
"tags": dict(mv.tags),
|
||||
"metrics": dict(run.data.metrics),
|
||||
"created_at": _iso(mv.creation_timestamp),
|
||||
"status": self._status(mv),
|
||||
}
|
||||
|
||||
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
||||
return self._describe(self.get(domain, scenario, version))
|
||||
|
||||
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
|
||||
"""Everything a version came from and produced: its cohort build (with
|
||||
its attrition), logged artifacts and predictions."""
|
||||
mv = self.get(domain, scenario, version)
|
||||
armado, exclusiones = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
return {
|
||||
"model_version": self.describe(domain, scenario, version),
|
||||
"cohorte_armado": armado,
|
||||
"cohorte_exclusiones": exclusiones,
|
||||
"artifacts": [a.path for a in self.client.list_artifacts(mv.run_id)],
|
||||
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
|
||||
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
|
||||
}
|
||||
|
||||
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
|
||||
mv = self.get(domain, scenario, version)
|
||||
run = self.client.get_run(mv.run_id)
|
||||
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
|
||||
metrics = run.data.metrics
|
||||
artifacts = self.client.list_artifacts(mv.run_id)
|
||||
return [
|
||||
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
|
||||
PromotionCheck(
|
||||
"ML-03",
|
||||
"enlazada al armado de cohorte con el que se entrenó",
|
||||
armado is not None,
|
||||
f"huella {armado['huella'][:12]}" if armado else "sin cohorte",
|
||||
),
|
||||
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
|
||||
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
|
||||
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
|
||||
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
|
||||
PromotionCheck("ML-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
|
||||
]
|
||||
|
||||
def promote(self, domain: str, scenario: str, version: str):
|
||||
"""Makes this the production version of its scenario, tagging the
|
||||
previous one `retirada_en`. Promotion is always a manual step
|
||||
(MLD-01/01b)."""
|
||||
checks = self.checks(domain, scenario, version)
|
||||
if not all(check.passed for check in checks):
|
||||
raise PromotionBlocked(checks)
|
||||
name = registered_name(domain, scenario)
|
||||
try:
|
||||
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
if str(previous.version) != str(version):
|
||||
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
|
||||
except MlflowException:
|
||||
pass
|
||||
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
|
||||
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
|
||||
return self.get(domain, scenario, version)
|
||||
|
||||
def retire(self, domain: str, scenario: str, version: str):
|
||||
"""Withdraws a version from production; its scenario has no active
|
||||
model until another one is promoted, so predictions stop."""
|
||||
name = registered_name(domain, scenario)
|
||||
try:
|
||||
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
except MlflowException:
|
||||
active = None
|
||||
if active is None or str(active.version) != str(version):
|
||||
raise ValueError("la versión no está en producción")
|
||||
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
|
||||
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
|
||||
return self.get(domain, scenario, version)
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _iso(epoch_millis: int) -> str:
|
||||
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
|
||||
|
||||
|
||||
registry = ModelRegistry()
|
||||
|
||||
|
||||
def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]]:
|
||||
"""The kit cohort build a version was trained on, and its attrition steps."""
|
||||
if not armado_id:
|
||||
return None, []
|
||||
cohortes = import_module(f"persistance.{domain}").cohorte_repository
|
||||
armado = cohortes.get(int(armado_id))
|
||||
if armado is None:
|
||||
return None, []
|
||||
exclusion = cohortes.cohortes.CohorteExclusion
|
||||
pasos = cohortes.leer(lambda sesion: sesion.exec(
|
||||
select(exclusion).where(exclusion.armado_id == armado.armado_id).order_by(exclusion.orden)).all())
|
||||
return ({"armado_id": armado.armado_id, "url": armado.url, "version": armado.version, "huella": armado.huella,
|
||||
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
|
||||
"armado_en": armado.armado_en.isoformat()},
|
||||
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Reports: notebooks run on a build's file, rendered and kept in MLflow, using `models.io` to read the build and record
|
||||
the run.
|
||||
|
||||
rendering.py a notebook to a self-contained HTML page (Quarto or Jupyter), and what identifies its content
|
||||
eda.py the exploratory notebook of a scenario, as a report run
|
||||
experiment.py a notebook uploaded to the platform, run on a build's file as a run of `<domain>-<scenario>/experimentos`
|
||||
notebook_jobs.py where that notebook runs: its job folder and the executors (local, or the runner container)
|
||||
notebook_import.py what the notebook trained in its own store, copied into the platform's MLflow as DEV
|
||||
"""
|
||||
@@ -0,0 +1,47 @@
|
||||
"""An exploratory notebook as an MLflow report: run on a build's file, rendered with Quarto, kept as artifacts.
|
||||
|
||||
Each notebook is an experiment, `<domain>-<scenario>/<notebook>` (`cacu-cin2_logistic/01_eda`), and each report a run
|
||||
in it, tagged with the notebook's content hash and the build's file (`models.io.storage.cohort_reference`). Its
|
||||
artifacts are the rendered page (`report/`) and the notebook without outputs (`notebook/`). A notebook and a file that
|
||||
were already reported together are not rendered again.
|
||||
|
||||
The notebook reads the build's file from `COHORT_FILE`, set here, and the database and cohort folder from the
|
||||
environment it inherits.
|
||||
"""
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from mlflow import MlflowClient
|
||||
|
||||
from models.io.lineage import registered_name
|
||||
from models.io.storage import cohort_reference, file_sha256, read_metadata
|
||||
from models.io.tracking import find_run, record_report
|
||||
from models.reports.rendering import notebook_sha256, render_notebook, without_outputs
|
||||
|
||||
COHORT_FILE_ENV = "COHORT_FILE"
|
||||
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report"
|
||||
|
||||
|
||||
def report_experiment(domain: str, scenario: str, notebook: Path) -> str:
|
||||
return f"{registered_name(domain, scenario)}/{notebook.stem}"
|
||||
|
||||
|
||||
def report_eda(notebook_path: str | Path, cohort_path: str | Path, domain: str, scenario: str,
|
||||
kernel: str | None = None) -> tuple[str, bool]:
|
||||
"""Returns the report's run id and whether it was rendered now."""
|
||||
notebook_path, cohort_path = Path(notebook_path), Path(cohort_path)
|
||||
notebook = json.loads(notebook_path.read_text())
|
||||
experiment = report_experiment(domain, scenario, notebook_path)
|
||||
tags = {REPORT_TAG: "eda", NOTEBOOK_TAG: notebook_path.name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook),
|
||||
**cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))}
|
||||
client = MlflowClient()
|
||||
if existing := find_run(client, experiment, tags):
|
||||
return existing, False
|
||||
with tempfile.TemporaryDirectory(prefix="report-") as folder:
|
||||
page = render_notebook(notebook, notebook_path.stem, Path(folder) / f"{notebook_path.stem}.html",
|
||||
env={COHORT_FILE_ENV: str(cohort_path.resolve())}, kernel=kernel)
|
||||
source = Path(folder) / notebook_path.name
|
||||
source.write_text(json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1))
|
||||
return record_report(client, experiment, tags, {"report": page, "notebook": source}), True
|
||||
@@ -0,0 +1,207 @@
|
||||
"""A notebook uploaded to the platform, run on a cohort build's file and kept as an MLflow run (ML-01a, ML-04, ML-05).
|
||||
|
||||
Each run belongs to the experiment `<domain>-<scenario>/experimentos` and is tagged with the notebook's name and
|
||||
content hash, the build's file (`models.io.lineage.cohort_reference`), the model version it was given, if any, the
|
||||
code version and where it ran (`sandbox`: `contenedor` or `local`). It holds the notebook as uploaded (`notebook/`),
|
||||
the page with its outputs (`report/`), what was imported from it (`importado.json`) and, when it failed,
|
||||
`error.txt`. `start` creates the run; `execute` runs the notebook through an executor and closes the run, so a caller
|
||||
can run it in the background and hand out the run's id at once.
|
||||
|
||||
The notebook runs in a job folder of its own (`models.reports.notebook_jobs`) with the build's file as its only data and
|
||||
an MLflow store of its own; what it trained is copied into the platform's MLflow as DEV afterwards
|
||||
(`models.reports.notebook_import`). Where it runs is the executor's: the runner container, with no network and no view
|
||||
of the server's files, or this process for development.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from mlflow import MlflowClient
|
||||
from mlflow.entities import RunStatus
|
||||
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, DOMAINS, code_version, \
|
||||
registered_name
|
||||
from models.reports.notebook_import import import_job
|
||||
from models.reports.notebook_jobs import JOB_TIMEOUT, JOB_TIMEOUT_ENV, PAGE_FILE, executor, prepare_job, read_job_file, \
|
||||
result_of
|
||||
from models.io.storage import cohort_reference, file_sha256, read_metadata
|
||||
from models.io.tracking import MODEL_PATH, experiment_id, run_file, run_files
|
||||
from models.reports.rendering import notebook_sha256, without_outputs
|
||||
|
||||
EXPERIMENT_SUFFIX = "experimentos"
|
||||
KIND_TAG, KIND = "experiment", "notebook"
|
||||
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, VERSION_TAG = "notebook", "notebook.sha256", "model.version"
|
||||
DOMAIN_TAG, SCENARIO_TAG, SANDBOX_TAG = "domain", "scenario", "sandbox"
|
||||
ERROR_PATH, IMPORT_PATH = "error.txt", "importado.json"
|
||||
KEEP_JOBS_ENV = "NOTEBOOK_KEEP_JOBS"
|
||||
# A run still marked as running this long after its job's timeout was cut off (a restart, a killed worker).
|
||||
STALE_MARGIN = timedelta(minutes=30)
|
||||
|
||||
|
||||
def experiment_name(domain: str, scenario: str) -> str:
|
||||
return f"{registered_name(domain, scenario)}/{EXPERIMENT_SUFFIX}"
|
||||
|
||||
|
||||
def check_names(domain: str | None, scenario: str | None) -> None:
|
||||
if domain is not None and domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
if scenario is not None and not re.fullmatch(r"[\w-]{1,100}", scenario):
|
||||
raise ValueError(f"escenario inválido: {scenario!r}")
|
||||
|
||||
|
||||
def notebook_name(filename: str) -> str:
|
||||
"""The name a notebook's files are stored under: its file name without folders or extension, in safe characters."""
|
||||
stem = Path(filename.replace("\\", "/")).name.removesuffix(".ipynb")
|
||||
return re.sub(r"[^\w.-]+", "_", stem).strip("._")[:80] or "notebook"
|
||||
|
||||
|
||||
def check_notebook(notebook: Any) -> dict:
|
||||
"""A Jupyter notebook (nbformat 4), or `ValueError` saying why not."""
|
||||
if not isinstance(notebook, dict) or not isinstance(notebook.get("cells"), list):
|
||||
raise ValueError("el archivo no es un notebook de Jupyter (.ipynb)")
|
||||
if notebook.get("nbformat") != 4:
|
||||
raise ValueError(f"solo se aceptan notebooks en formato 4, no {notebook.get('nbformat')!r}")
|
||||
return notebook
|
||||
|
||||
|
||||
def start(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> str:
|
||||
"""Creates the run, stores the notebook as uploaded and returns the run's id; the notebook hasn't run yet."""
|
||||
check_names(domain, scenario)
|
||||
check_notebook(notebook)
|
||||
name = notebook_name(name)
|
||||
client = MlflowClient()
|
||||
tags = {KIND_TAG: KIND, NOTEBOOK_TAG: name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook), DOMAIN_TAG: domain,
|
||||
SCENARIO_TAG: scenario, **cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path)),
|
||||
**code_version()}
|
||||
if version:
|
||||
tags[VERSION_TAG] = str(version)
|
||||
run = client.create_run(experiment_id(client, experiment_name(domain, scenario)), tags=tags, run_name=name)
|
||||
client.log_text(run.info.run_id, json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1),
|
||||
f"notebook/{name}.ipynb")
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
def execute(run_id: str, notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> bool:
|
||||
"""Runs the notebook through the executor, imports what it trained, stores its page (the cells that ran, when it
|
||||
failed) and closes the run. Returns whether every cell ran."""
|
||||
client = MlflowClient()
|
||||
runner = executor()
|
||||
client.set_tag(run_id, SANDBOX_TAG, runner.name)
|
||||
job = None
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-model-") as tmp:
|
||||
model = _model_copy(client, domain, scenario, version, Path(tmp))
|
||||
job = prepare_job(runner.jobs_root(), run_id, notebook, Path(cohort_path), domain=domain,
|
||||
scenario=scenario, version=version, model_dir=model)
|
||||
runner.run(job)
|
||||
result = result_of(job) or {"ok": False, "error": "el notebook terminó sin resultado"}
|
||||
if page := read_job_file(job, PAGE_FILE):
|
||||
client.log_text(run_id, page.decode("utf-8", "replace"), f"report/{name}.html")
|
||||
cohort = {k: v for k, v in client.get_run(run_id).data.tags.items() if k.startswith("cohort.")}
|
||||
client.log_dict(run_id, import_job(job, run_id, domain, cohort), IMPORT_PATH)
|
||||
except Exception as error:
|
||||
result = {"ok": False, "error": f"{type(error).__name__}: {error}"}
|
||||
finally:
|
||||
if job is not None and not os.environ.get(KEEP_JOBS_ENV):
|
||||
shutil.rmtree(job, ignore_errors=True)
|
||||
if not result["ok"]:
|
||||
client.log_text(run_id, result["error"] or "falló", ERROR_PATH)
|
||||
client.set_terminated(run_id, RunStatus.to_string(RunStatus.FINISHED if result["ok"] else RunStatus.FAILED))
|
||||
return result["ok"]
|
||||
|
||||
|
||||
def _model_copy(client: MlflowClient, domain: str, scenario: str, version: str | None, folder: Path) -> Path | None:
|
||||
"""The chosen version's saved model, downloaded for the job; `None` without a version or a saved model."""
|
||||
if not version:
|
||||
return None
|
||||
from models.io.registry import registry
|
||||
|
||||
resolved = registry.resolve(domain, scenario, version)
|
||||
if not resolved.modelo_sha:
|
||||
return None
|
||||
return Path(client.download_artifacts(resolved.run_id, MODEL_PATH, str(folder)))
|
||||
|
||||
|
||||
def run_notebook(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str,
|
||||
version: str | None = None) -> tuple[str, bool]:
|
||||
run_id = start(notebook, name, cohort_path, domain, scenario, version)
|
||||
return run_id, execute(run_id, notebook, notebook_name(name), cohort_path, domain, scenario, version)
|
||||
|
||||
|
||||
def _status(run) -> str:
|
||||
status = run.info.status
|
||||
if status == "RUNNING":
|
||||
started = datetime.fromtimestamp(run.info.start_time / 1000, tz=timezone.utc)
|
||||
timeout = timedelta(seconds=int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT)))
|
||||
return "interrumpido" if datetime.now(timezone.utc) - started > timeout + STALE_MARGIN else "en_curso"
|
||||
return {"FINISHED": "terminado", "FAILED": "fallido", "KILLED": "interrumpido"}.get(status, status.lower())
|
||||
|
||||
|
||||
def _iso(epoch_millis: int | None) -> str | None:
|
||||
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat() if epoch_millis else None
|
||||
|
||||
|
||||
def _describe(run) -> dict[str, Any]:
|
||||
tags = run.data.tags
|
||||
return {"run_id": run.info.run_id, "notebook": tags.get(NOTEBOOK_TAG), "domain": tags.get(DOMAIN_TAG),
|
||||
"scenario": tags.get(SCENARIO_TAG), "version": tags.get(VERSION_TAG),
|
||||
"cohort": {"url": tags.get(COHORT_URL_TAG), "source": tags.get(COHORT_SOURCE_TAG),
|
||||
"build": tags.get(COHORT_BUILD_TAG)},
|
||||
"notebook_sha256": tags.get(NOTEBOOK_SHA_TAG), "sandbox": tags.get(SANDBOX_TAG), "status": _status(run),
|
||||
"started_at": _iso(run.info.start_time), "ended_at": _iso(run.info.end_time)}
|
||||
|
||||
|
||||
def experiments(domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
|
||||
"""Notebook runs, newest first; `scenario` needs `domain`."""
|
||||
check_names(domain, scenario)
|
||||
client = MlflowClient()
|
||||
pattern = f"{registered_name(domain, scenario) if scenario else (domain + '-%' if domain else '%')}/{EXPERIMENT_SUFFIX}"
|
||||
found = client.search_experiments(filter_string=f"name LIKE '{pattern}'")
|
||||
if not found:
|
||||
return []
|
||||
runs = client.search_runs([e.experiment_id for e in found], filter_string=f"tags.{KIND_TAG} = '{KIND}'",
|
||||
order_by=["attributes.start_time DESC"], max_results=500)
|
||||
return [_describe(run) for run in runs]
|
||||
|
||||
|
||||
def _run(client: MlflowClient, run_id: str):
|
||||
try:
|
||||
run = client.get_run(run_id)
|
||||
except Exception as error:
|
||||
raise LookupError(f"no existe la corrida {run_id!r}") from error
|
||||
if run.data.tags.get(KIND_TAG) != KIND:
|
||||
raise LookupError(f"la corrida {run_id!r} no es de un notebook")
|
||||
return run
|
||||
|
||||
|
||||
def describe(run_id: str) -> dict[str, Any]:
|
||||
"""One notebook run with its files and, if it failed, the error."""
|
||||
client = MlflowClient()
|
||||
run = _run(client, run_id)
|
||||
files = run_files(client, run_id)
|
||||
error = None
|
||||
if any(item["path"] == ERROR_PATH for item in files):
|
||||
error = run_file(client, run_id, ERROR_PATH)[1].decode("utf-8", "replace")
|
||||
return {**_describe(run), "artifacts": files, "error": error}
|
||||
|
||||
|
||||
def artifact(run_id: str, path: str) -> tuple[str, bytes]:
|
||||
client = MlflowClient()
|
||||
_run(client, run_id)
|
||||
return run_file(client, run_id, path)
|
||||
|
||||
|
||||
def page(run_id: str) -> str | None:
|
||||
"""The rendered page, or `None` while there's none."""
|
||||
client = MlflowClient()
|
||||
_run(client, run_id)
|
||||
pages = [item["path"] for item in run_files(client, run_id, "report") if item["path"].endswith(".html")]
|
||||
return run_file(client, run_id, pages[0])[1].decode("utf-8") if pages else None
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Copies what a notebook trained, in its job's own MLflow store, into the platform's (ML-02, ML-03).
|
||||
|
||||
The notebook wrote that store itself, so nothing in it is taken at its word. Only runs of the job's domain
|
||||
(`<domain>-<scenario>` experiments) come across; each becomes a new run tagged DEV, with the cohort reference of the
|
||||
build the job actually had, the notebook's run (`notebook.run_id`) and the model's hash computed here. Registered
|
||||
versions come across as DEV versions of their run, never with an alias, so a notebook can't put anything in
|
||||
production. Files are copied by walking the job folder without following symbolic links, and the store is opened
|
||||
from a copy, so nothing outside the job folder is ever read.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from mlflow import MlflowClient
|
||||
from mlflow.entities import Metric, Param
|
||||
|
||||
from models.io.lineage import MODEL_SHA_TAG, code_version, model_sha
|
||||
from models.reports.notebook_jobs import STORE_FILE, JobError, inside, read_job_file
|
||||
from models.io.tracking import MODEL_PATH, experiment_id
|
||||
|
||||
NOTEBOOK_RUN_TAG = "notebook.run_id"
|
||||
# Above this many bytes of files across a job's runs, nothing more is copied.
|
||||
MAX_IMPORT_BYTES_ENV = "NOTEBOOK_MAX_IMPORT_MB"
|
||||
MAX_IMPORT_MB = 500
|
||||
KEPT_SYSTEM_TAGS = ("mlflow.note.content",)
|
||||
|
||||
|
||||
def import_job(job: Path, notebook_run_id: str, domain: str, cohort: dict[str, str]) -> dict[str, Any]:
|
||||
"""Imports the job's runs and versions; returns what came across and what was left out, and why."""
|
||||
summary: dict[str, Any] = {"runs": [], "versions": [], "skipped": []}
|
||||
data = read_job_file(job, STORE_FILE)
|
||||
if not data:
|
||||
return summary
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-store-") as tmp:
|
||||
copy = Path(tmp) / STORE_FILE
|
||||
copy.write_bytes(data)
|
||||
local = MlflowClient(tracking_uri=f"sqlite:///{copy}", registry_uri=f"sqlite:///{copy}")
|
||||
target = MlflowClient()
|
||||
budget = int(os.environ.get(MAX_IMPORT_BYTES_ENV, MAX_IMPORT_MB)) * 1024 * 1024
|
||||
runs: dict[str, str] = {}
|
||||
for experiment in local.search_experiments():
|
||||
if not re.fullmatch(rf"{domain}-[\w-]{{1,100}}", experiment.name):
|
||||
summary["skipped"].append({"experiment": experiment.name, "reason": "no es un escenario del dominio"})
|
||||
continue
|
||||
for run in local.search_runs([experiment.experiment_id]):
|
||||
try:
|
||||
new_id, budget = _copy_run(local, target, job, run, experiment.name, notebook_run_id, cohort, budget)
|
||||
except JobError as error:
|
||||
summary["skipped"].append({"run": run.info.run_id, "reason": str(error)})
|
||||
continue
|
||||
runs[run.info.run_id] = new_id
|
||||
summary["runs"].append({"run_id": new_id, "experiment": experiment.name})
|
||||
for model in local.search_registered_models():
|
||||
for version in local.search_model_versions(f"name='{model.name}'"):
|
||||
if version.run_id not in runs or not model.name.startswith(f"{domain}-"):
|
||||
summary["skipped"].append({"version": f"{model.name}:{version.version}",
|
||||
"reason": "su corrida no se importó"})
|
||||
continue
|
||||
summary["versions"].append(_copy_version(target, model.name, runs[version.run_id], notebook_run_id))
|
||||
return summary
|
||||
|
||||
|
||||
def _artifact_dir(job: Path, run) -> Path:
|
||||
uri = run.info.artifact_uri
|
||||
path = Path(unquote(urlparse(uri).path)) if "://" in uri else Path(uri)
|
||||
if not inside(job, path):
|
||||
raise JobError(f"los archivos de la corrida están fuera de la carpeta del trabajo: {uri}")
|
||||
return path
|
||||
|
||||
|
||||
def _files(job: Path, folder: Path) -> list[Path]:
|
||||
"""The regular files under `folder`, refusing any symbolic link."""
|
||||
found = []
|
||||
for base, folders, files in os.walk(folder, followlinks=False):
|
||||
for name in folders + files:
|
||||
path = Path(base) / name
|
||||
if path.is_symlink() or not inside(job, path):
|
||||
raise JobError(f"enlace simbólico en los archivos de la corrida: {path.name}")
|
||||
if name in files:
|
||||
found.append(path)
|
||||
return found
|
||||
|
||||
|
||||
def _copy_run(local: MlflowClient, target: MlflowClient, job: Path, run, experiment: str, notebook_run_id: str,
|
||||
cohort: dict[str, str], budget: int) -> tuple[str, int]:
|
||||
folder = _artifact_dir(job, run)
|
||||
files = _files(job, folder) if folder.exists() else []
|
||||
size = sum(path.stat().st_size for path in files)
|
||||
if size > budget:
|
||||
raise JobError(f"sus archivos ({size // 1_000_000} MB) exceden el límite de {MAX_IMPORT_BYTES_ENV}")
|
||||
tags = {k: v for k, v in run.data.tags.items() if not k.startswith("mlflow.") or k in KEPT_SYSTEM_TAGS}
|
||||
tags.update({**cohort, **code_version(), "domain": experiment.split("-", 1)[0],
|
||||
"scenario": experiment.split("-", 1)[1], "environment": "DEV", NOTEBOOK_RUN_TAG: notebook_run_id})
|
||||
tags.pop(MODEL_SHA_TAG, None)
|
||||
tags.pop("kit.armado_id", None)
|
||||
new = target.create_run(experiment_id(target, experiment), tags=tags, run_name=run.info.run_name)
|
||||
new_id = new.info.run_id
|
||||
params = [Param(k, v) for k, v in run.data.params.items()]
|
||||
metrics = [Metric(m.key, m.value, m.timestamp, m.step) for key in run.data.metrics
|
||||
for m in local.get_metric_history(run.info.run_id, key)]
|
||||
for start in range(0, max(len(params), len(metrics)), 100):
|
||||
target.log_batch(new_id, metrics=metrics[start:start + 100], params=params[start:start + 100])
|
||||
with tempfile.TemporaryDirectory(prefix="notebook-files-") as staging:
|
||||
for path in files:
|
||||
destination = Path(staging) / path.relative_to(folder)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(path, destination, follow_symlinks=False)
|
||||
if files:
|
||||
target.log_artifacts(new_id, staging)
|
||||
if (Path(staging) / MODEL_PATH / "python_model.pkl").exists():
|
||||
target.set_tag(new_id, MODEL_SHA_TAG, model_sha(Path(staging) / MODEL_PATH))
|
||||
target.set_terminated(new_id, run.info.status if run.info.status in ("FINISHED", "FAILED") else "KILLED")
|
||||
return new_id, budget - size
|
||||
|
||||
|
||||
def _copy_version(target: MlflowClient, name: str, run_id: str, notebook_run_id: str) -> dict[str, str]:
|
||||
from mlflow import MlflowException
|
||||
|
||||
try:
|
||||
target.create_registered_model(name)
|
||||
except MlflowException as error:
|
||||
if error.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||
raise
|
||||
run = target.get_run(run_id)
|
||||
keep = ("domain", "scenario", "environment", MODEL_SHA_TAG, "cohort.url", "cohort.source", "cohort.build",
|
||||
"cohort.file_sha256")
|
||||
tags = {k: run.data.tags[k] for k in keep if k in run.data.tags}
|
||||
tags[NOTEBOOK_RUN_TAG] = notebook_run_id
|
||||
has_model = MODEL_SHA_TAG in run.data.tags
|
||||
source = f"runs:/{run_id}/{MODEL_PATH}" if has_model else f"runs:/{run_id}"
|
||||
version = target.create_model_version(name, source=source, run_id=run_id, tags=tags)
|
||||
return {"name": name, "version": str(version.version), "run_id": run_id}
|
||||
@@ -0,0 +1,268 @@
|
||||
"""Where an uploaded notebook runs: a job folder, a runner and the executors that hand jobs to it (ML-04, ML-05).
|
||||
|
||||
A job is one folder named after the notebook's run, holding everything the notebook may see: the notebook
|
||||
(`notebook.ipynb`), a copy of the cohort build's file (`cohorte.parquet`), the chosen version's saved model
|
||||
(`model/`) and `job.json`. The notebook runs with that folder as its world: its MLflow is a throwaway store inside it
|
||||
(`mlflow.db`, `artefactos/`), and every database URL is an empty in-memory database. The runner writes the page
|
||||
(`page.html`) and `result.json`; what the notebook trained is imported afterwards by trusted code
|
||||
(`models.reports.notebook_import`).
|
||||
|
||||
Executors are classes in `EXECUTORS`: `local` runs the job in this process, unsandboxed, for development;
|
||||
`contenedor` leaves it in `NOTEBOOK_JOBS_DIR` for the runner container (`python -m models notebooks serve`), which
|
||||
has no network and sees only that folder, and waits for its result. `NOTEBOOK_EXECUTOR` picks one; with
|
||||
`NOTEBOOK_JOBS_DIR` set the default is `contenedor`, otherwise `local`.
|
||||
|
||||
Whatever the notebook wrote is untrusted: files are read only through `read_job_file`, which refuses symbolic links
|
||||
and anything outside the job folder.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from models.reports.rendering import CELL_TIMEOUT_ENV, RenderError, renderer, with_kernel
|
||||
from models.notebook import COHORT_FILE_ENV, DOMAIN_ENV, MODEL_PATH_ENV, SCENARIO_ENV, VERSION_ENV
|
||||
|
||||
JOBS_DIR_ENV = "NOTEBOOK_JOBS_DIR"
|
||||
EXECUTOR_ENV = "NOTEBOOK_EXECUTOR"
|
||||
RUNNER_UID_ENV = "NOTEBOOK_RUNNER_UID"
|
||||
JOB_TIMEOUT_ENV = "NOTEBOOK_JOB_TIMEOUT"
|
||||
JOB_TIMEOUT = 6 * 3600
|
||||
POLL_SECONDS = 2
|
||||
|
||||
JOB_FILE, NOTEBOOK_FILE, COHORT_FILE, MODEL_DIR = "job.json", "notebook.ipynb", "cohorte.parquet", "model"
|
||||
STORE_FILE, STORE_ARTIFACTS, PAGE_FILE, RESULT_FILE = "mlflow.db", "artefactos", "page.html", "result.json"
|
||||
CLAIM_DIR, WORK_DIR = "en_curso", "trabajo"
|
||||
KERNEL = "python3"
|
||||
# What a notebook inherits from the runner's environment; everything else is left out.
|
||||
PASSED_ENV = ("PATH", "LANG", "LC_ALL", "TZ", "SYSTEMROOT", "MODELS_GIT_COMMIT", CELL_TIMEOUT_ENV,
|
||||
"MLFLOW_DISABLE_TELEMETRY", "DO_NOT_TRACK", "MLFLOW_DISABLE_AGENT_HINT")
|
||||
DATABASE_ENVS = ("CACU_DATABASE_URL", "CAMA_DATABASE_URL", "TEA_DATABASE_URL", "GOVERNANCE_DATABASE_URL")
|
||||
EMPTY_DATABASE = "sqlite://"
|
||||
|
||||
|
||||
class JobError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _absolute(path: Path) -> str:
|
||||
"""The path as the job folder is reached, without resolving links on the way to it, so the trusted side and the
|
||||
notebook name its files the same way (`inside`)."""
|
||||
return os.path.abspath(path)
|
||||
|
||||
|
||||
def store_uri(job: Path) -> str:
|
||||
return f"sqlite:///{_absolute(job / STORE_FILE)}"
|
||||
|
||||
|
||||
def prepare_job(root: Path, run_id: str, notebook: dict, cohort_path: Path, *, domain: str, scenario: str,
|
||||
version: str | None, model_dir: Path | None = None) -> Path:
|
||||
"""Writes the job folder, complete or not at all: it's assembled beside the others and renamed into place, so the
|
||||
runner never picks up half a job."""
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
partial = Path(tempfile.mkdtemp(prefix=f".{run_id}-", dir=root))
|
||||
try:
|
||||
(partial / NOTEBOOK_FILE).write_text(json.dumps(with_kernel(notebook, KERNEL), ensure_ascii=False))
|
||||
shutil.copyfile(cohort_path, partial / COHORT_FILE)
|
||||
if model_dir is not None:
|
||||
shutil.copytree(model_dir, partial / MODEL_DIR)
|
||||
(partial / JOB_FILE).write_text(json.dumps({"run_id": run_id, "domain": domain, "scenario": scenario,
|
||||
"version": version}))
|
||||
_hand_over(partial)
|
||||
job = root / run_id
|
||||
partial.rename(job)
|
||||
except BaseException:
|
||||
shutil.rmtree(partial, ignore_errors=True)
|
||||
raise
|
||||
return job
|
||||
|
||||
|
||||
def _hand_over(folder: Path) -> None:
|
||||
"""Gives the job to the runner's user (`NOTEBOOK_RUNNER_UID`) when it isn't this one."""
|
||||
uid = os.environ.get(RUNNER_UID_ENV)
|
||||
os.chmod(folder, 0o755)
|
||||
if not uid or int(uid) == os.getuid():
|
||||
return
|
||||
for base, folders, files in os.walk(folder):
|
||||
for name in [base, *(os.path.join(base, f) for f in folders + files)]:
|
||||
os.chown(name, int(uid), int(uid), follow_symlinks=False)
|
||||
|
||||
|
||||
def notebook_env(job: Path) -> dict[str, str]:
|
||||
spec = json.loads((job / JOB_FILE).read_text())
|
||||
private = job / ".entorno"
|
||||
env = {name: os.environ[name] for name in PASSED_ENV if name in os.environ}
|
||||
env.update({name: EMPTY_DATABASE for name in DATABASE_ENVS})
|
||||
env.update({
|
||||
COHORT_FILE_ENV: _absolute(job / COHORT_FILE), DOMAIN_ENV: spec["domain"], SCENARIO_ENV: spec["scenario"],
|
||||
"MLFLOW_TRACKING_URI": store_uri(job), "MLFLOW_ARTIFACT_ROOT": _absolute(job / STORE_ARTIFACTS),
|
||||
"HOME": _absolute(private), "TMPDIR": _absolute(private / "tmp"), "IPYTHONDIR": _absolute(private / "ipython"),
|
||||
"JUPYTER_RUNTIME_DIR": _absolute(private / "jupyter"), "MPLCONFIGDIR": _absolute(private / "matplotlib"),
|
||||
})
|
||||
if spec.get("version"):
|
||||
env[VERSION_ENV] = str(spec["version"])
|
||||
if (job / MODEL_DIR).is_dir():
|
||||
env[MODEL_PATH_ENV] = _absolute(job / MODEL_DIR)
|
||||
return env
|
||||
|
||||
|
||||
def run_job(job: Path) -> bool:
|
||||
"""Runs the job's notebook and writes its page and `result.json`. Returns whether every cell ran."""
|
||||
env = notebook_env(job)
|
||||
for folder in ("HOME", "TMPDIR", "IPYTHONDIR", "JUPYTER_RUNTIME_DIR", "MPLCONFIGDIR"):
|
||||
Path(env[folder]).mkdir(parents=True, exist_ok=True)
|
||||
work = job / WORK_DIR
|
||||
work.mkdir(exist_ok=True)
|
||||
result: dict[str, Any] = {"ok": True, "error": None}
|
||||
page = None
|
||||
try:
|
||||
page = renderer().render(json.loads((job / NOTEBOOK_FILE).read_text()), "notebook", work, env)
|
||||
except RenderError as error:
|
||||
page, result = error.page, {"ok": False, "error": str(error)}
|
||||
except Exception as error:
|
||||
result = {"ok": False, "error": f"{type(error).__name__}: {error}"}
|
||||
if page is not None:
|
||||
_write_atomically(job / PAGE_FILE, page)
|
||||
_write_atomically(job / RESULT_FILE, json.dumps(result, ensure_ascii=False))
|
||||
return result["ok"]
|
||||
|
||||
|
||||
def _write_atomically(path: Path, text: str) -> None:
|
||||
partial = path.with_name(f".{path.name}.parcial")
|
||||
partial.write_text(text)
|
||||
partial.replace(path)
|
||||
|
||||
|
||||
def read_job_file(job: Path, relative: str) -> bytes | None:
|
||||
"""A file the job left, or `None` if it isn't there. `JobError` for a symbolic link or a path that leaves the job
|
||||
folder: those were planted to make the trusted side read its own files."""
|
||||
path = job / relative
|
||||
if not inside(job, path):
|
||||
raise JobError(f"{relative} sale de la carpeta del trabajo")
|
||||
try:
|
||||
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except OSError as error:
|
||||
raise JobError(f"{relative} no es un archivo regular") from error
|
||||
with os.fdopen(descriptor, "rb") as handle:
|
||||
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
||||
raise JobError(f"{relative} no es un archivo regular")
|
||||
return handle.read()
|
||||
|
||||
|
||||
def inside(job: Path, path: Path) -> bool:
|
||||
"""Whether `path` is within `job` with no symbolic link on the way."""
|
||||
base = Path(os.path.abspath(job))
|
||||
try:
|
||||
parts = Path(os.path.abspath(path)).relative_to(base).parts
|
||||
except ValueError:
|
||||
return False
|
||||
current = base
|
||||
for part in parts:
|
||||
current = current / part
|
||||
if current.is_symlink():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def result_of(job: Path) -> dict[str, Any] | None:
|
||||
data = read_job_file(job, RESULT_FILE)
|
||||
if data is None:
|
||||
return None
|
||||
try:
|
||||
result = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
return {"ok": False, "error": "result.json ilegible"}
|
||||
return {"ok": result.get("ok") is True, "error": str(result.get("error") or "")[:20000] or None}
|
||||
|
||||
|
||||
class NotebookExecutor(ABC):
|
||||
name: str
|
||||
sandboxed: bool
|
||||
|
||||
@abstractmethod
|
||||
def jobs_root(self) -> Path: ...
|
||||
|
||||
@abstractmethod
|
||||
def run(self, job: Path) -> None:
|
||||
"""Returns once the job has its `result.json`; `JobError` if it never gets one."""
|
||||
|
||||
|
||||
EXECUTORS: dict[str, type[NotebookExecutor]] = {}
|
||||
|
||||
|
||||
def register_executor(cls: type[NotebookExecutor]) -> type[NotebookExecutor]:
|
||||
EXECUTORS[cls.name] = cls
|
||||
return cls
|
||||
|
||||
|
||||
@register_executor
|
||||
class LocalExecutor(NotebookExecutor):
|
||||
"""Runs the job in this process's own kernel: nothing keeps the notebook from this machine's files or network."""
|
||||
|
||||
name, sandboxed = "local", False
|
||||
|
||||
def jobs_root(self) -> Path:
|
||||
return Path(os.environ.get(JOBS_DIR_ENV) or Path(tempfile.gettempdir()) / "notebook-jobs")
|
||||
|
||||
def run(self, job: Path) -> None:
|
||||
run_job(job)
|
||||
|
||||
|
||||
@register_executor
|
||||
class ContainerExecutor(NotebookExecutor):
|
||||
"""Leaves the job for the runner container and waits for its result (`NOTEBOOK_JOB_TIMEOUT`, 6 h by default)."""
|
||||
|
||||
name, sandboxed = "contenedor", True
|
||||
|
||||
def jobs_root(self) -> Path:
|
||||
if not os.environ.get(JOBS_DIR_ENV):
|
||||
raise JobError(f"{JOBS_DIR_ENV} no está configurado: no hay carpeta compartida con el contenedor de notebooks")
|
||||
return Path(os.environ[JOBS_DIR_ENV])
|
||||
|
||||
def run(self, job: Path) -> None:
|
||||
deadline = time.monotonic() + int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT))
|
||||
while time.monotonic() < deadline:
|
||||
if result_of(job) is not None:
|
||||
return
|
||||
time.sleep(POLL_SECONDS)
|
||||
raise JobError("el contenedor de notebooks no terminó el trabajo a tiempo (¿está corriendo?)")
|
||||
|
||||
|
||||
def executor() -> NotebookExecutor:
|
||||
chosen = os.environ.get(EXECUTOR_ENV) or ("contenedor" if os.environ.get(JOBS_DIR_ENV) else "local")
|
||||
if chosen not in EXECUTORS:
|
||||
raise JobError(f"{EXECUTOR_ENV}={chosen!r}: use uno de {sorted(EXECUTORS)}")
|
||||
return EXECUTORS[chosen]()
|
||||
|
||||
|
||||
def claim(job: Path) -> bool:
|
||||
"""Takes a ready job for this runner; `False` if it isn't ready or another runner has it."""
|
||||
if not job.is_dir() or job.name.startswith(".") or not (job / JOB_FILE).exists() or (job / RESULT_FILE).exists():
|
||||
return False
|
||||
try:
|
||||
(job / CLAIM_DIR).mkdir()
|
||||
except FileExistsError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def serve(root: Path, *, once: bool = False) -> None:
|
||||
"""The runner's loop: runs each ready job in `root`, oldest first."""
|
||||
while True:
|
||||
for job in sorted((p for p in root.iterdir() if p.is_dir()), key=lambda p: p.stat().st_mtime):
|
||||
if claim(job):
|
||||
try:
|
||||
run_job(job)
|
||||
except Exception as error:
|
||||
_write_atomically(job / RESULT_FILE, json.dumps({"ok": False, "error": f"{type(error).__name__}: {error}"}))
|
||||
if once:
|
||||
return
|
||||
time.sleep(POLL_SECONDS)
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Runs a notebook, renders it to a self-contained HTML page, and identifies its content by its cells' sources, without
|
||||
outputs or execution counts.
|
||||
|
||||
Two renderers, one class each in `RENDERERS`: `quarto`, and `jupyter`, which runs the cells with `nbclient` and
|
||||
exports the page with `nbconvert` (the `notebooks` extra), so it needs nothing outside Python. `NOTEBOOK_RENDERER`
|
||||
picks one; otherwise Quarto when it's installed, else Jupyter.
|
||||
|
||||
`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has
|
||||
Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so
|
||||
`QUARTO_PYTHON` names one that does. The notebook runs with the kernel its metadata
|
||||
names, or `kernel` if given, in the environment given: that's how a report points the notebook at a database, a
|
||||
cohort folder and a build's file. Quarto writes next to its input, so the notebook is copied to a temporary folder
|
||||
first and the source folder is left untouched.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
|
||||
QUARTO_ENV = "QUARTO_BIN"
|
||||
RENDERER_ENV = "NOTEBOOK_RENDERER"
|
||||
# Seconds a single cell may run under the Jupyter renderer.
|
||||
CELL_TIMEOUT_ENV = "NOTEBOOK_CELL_TIMEOUT"
|
||||
CELL_TIMEOUT = 1800
|
||||
|
||||
|
||||
class RenderError(RuntimeError):
|
||||
"""The notebook couldn't be run: a cell raised, the kernel is missing, or the renderer isn't installed. `page` is
|
||||
the page of the cells that did run, when the renderer could still make one."""
|
||||
|
||||
def __init__(self, message: str, page: str | None = None):
|
||||
super().__init__(message)
|
||||
self.page = page
|
||||
|
||||
|
||||
class NotebookRenderer(ABC):
|
||||
name: str
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def available(cls) -> bool: ...
|
||||
|
||||
@abstractmethod
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
"""Runs `notebook` in `folder` with exactly `env` as its environment and returns the page's HTML."""
|
||||
|
||||
|
||||
RENDERERS: dict[str, type[NotebookRenderer]] = {}
|
||||
|
||||
|
||||
def register_renderer(cls: type[NotebookRenderer]) -> type[NotebookRenderer]:
|
||||
RENDERERS[cls.name] = cls
|
||||
return cls
|
||||
|
||||
|
||||
def quarto() -> str:
|
||||
found = os.environ.get(QUARTO_ENV) or shutil.which("quarto")
|
||||
if not found:
|
||||
raise RenderError(f"quarto isn't installed: put it on the PATH or set {QUARTO_ENV}")
|
||||
return found
|
||||
|
||||
|
||||
@register_renderer
|
||||
class QuartoRenderer(NotebookRenderer):
|
||||
name = "quarto"
|
||||
|
||||
@classmethod
|
||||
def available(cls) -> bool:
|
||||
return bool(os.environ.get(QUARTO_ENV) or shutil.which("quarto"))
|
||||
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
source = folder / f"{name}.ipynb"
|
||||
source.write_text(json.dumps(notebook, ensure_ascii=False))
|
||||
done = subprocess.run([quarto(), "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
|
||||
cwd=folder, env=env, capture_output=True, text=True)
|
||||
page = source.with_suffix(".html")
|
||||
if done.returncode or not page.exists():
|
||||
raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}")
|
||||
return page.read_text()
|
||||
|
||||
|
||||
@register_renderer
|
||||
class JupyterRenderer(NotebookRenderer):
|
||||
"""The kernel is the one the notebook names, which must be installed beside this package (`python3` is this
|
||||
package's own interpreter once `ipykernel` is installed)."""
|
||||
|
||||
name = "jupyter"
|
||||
|
||||
@classmethod
|
||||
def available(cls) -> bool:
|
||||
try:
|
||||
import nbclient # noqa: F401
|
||||
import nbconvert # noqa: F401
|
||||
except ImportError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
|
||||
import nbformat
|
||||
from nbclient import NotebookClient
|
||||
from nbclient.exceptions import CellExecutionError, DeadKernelError
|
||||
from nbconvert import HTMLExporter
|
||||
|
||||
node = nbformat.reads(json.dumps(notebook), as_version=4)
|
||||
kernel = node.metadata.get("kernelspec", {}).get("name") or "python3"
|
||||
timeout = int(os.environ.get(CELL_TIMEOUT_ENV, CELL_TIMEOUT))
|
||||
client = NotebookClient(node, timeout=timeout, kernel_name=kernel, resources={"metadata": {"path": str(folder)}})
|
||||
try:
|
||||
client.execute(env=env, cwd=str(folder))
|
||||
except (CellExecutionError, DeadKernelError, TimeoutError) as error:
|
||||
raise RenderError(f"{name}: {str(error)[-2000:]}", page=self._page(HTMLExporter, node)) from error
|
||||
except Exception as error:
|
||||
raise RenderError(f"{name}: el kernel {kernel!r} no pudo correr el notebook: {error}") from error
|
||||
return self._page(HTMLExporter, node)
|
||||
|
||||
@staticmethod
|
||||
def _page(exporter, node) -> str:
|
||||
body, _ = exporter(embed_images=True).from_notebook_node(node)
|
||||
return body
|
||||
|
||||
|
||||
def renderer() -> NotebookRenderer:
|
||||
"""The renderer `NOTEBOOK_RENDERER` names; otherwise Quarto if installed, else Jupyter."""
|
||||
if chosen := os.environ.get(RENDERER_ENV):
|
||||
if chosen not in RENDERERS:
|
||||
raise RenderError(f"{RENDERER_ENV}={chosen!r}: use one of {sorted(RENDERERS)}")
|
||||
return RENDERERS[chosen]()
|
||||
for cls in RENDERERS.values():
|
||||
if cls.available():
|
||||
return cls()
|
||||
raise RenderError(f"no notebook renderer is installed: install quarto or the 'notebooks' extra ({sorted(RENDERERS)})")
|
||||
|
||||
|
||||
def with_kernel(notebook: dict, kernel: str | None) -> dict:
|
||||
if not kernel:
|
||||
return notebook
|
||||
return {**notebook, "metadata": {**notebook.get("metadata", {}),
|
||||
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
|
||||
|
||||
|
||||
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
|
||||
kernel: str | None = None) -> Path:
|
||||
"""Runs and renders `notebook` (its JSON) as `name`, with this process's environment plus `env`, and writes the
|
||||
page to `output`."""
|
||||
with tempfile.TemporaryDirectory(prefix="render-") as folder:
|
||||
page = renderer().render(with_kernel(notebook, kernel), name, Path(folder), {**os.environ, **(env or {})})
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(page)
|
||||
return output
|
||||
|
||||
|
||||
def without_outputs(notebook: dict) -> dict:
|
||||
"""The notebook as written: code cells keep their source and lose their outputs."""
|
||||
cleared = copy.deepcopy(notebook)
|
||||
for cell in cleared["cells"]:
|
||||
if cell["cell_type"] == "code":
|
||||
cell["outputs"], cell["execution_count"] = [], None
|
||||
return cleared
|
||||
|
||||
|
||||
def notebook_sha256(notebook: dict) -> str:
|
||||
"""Changes when a cell's type or source changes, not when the notebook is run again."""
|
||||
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
|
||||
for cell in notebook["cells"]]
|
||||
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()
|
||||
@@ -0,0 +1,4 @@
|
||||
"""The plain functions pipelines are built from: each becomes a Hamilton node once a pipeline lists it.
|
||||
|
||||
They neither read nor write on their own: what they read comes in as a parameter, and a pipeline decides when they run.
|
||||
"""
|
||||
@@ -0,0 +1,52 @@
|
||||
"""The steps of a cohort build: all patients, the index date, each rule's excluded members and what remains.
|
||||
|
||||
They know no rule by name: a pipeline gives each rule its own `excluded` and `remaining` node. The queries run through
|
||||
the domain's `dbt_query_repository`.
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from persistance.edges.dbt import DbtQueryRepository
|
||||
|
||||
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
||||
|
||||
|
||||
def _frame(rows: list[dict], columns: list[str]) -> pd.DataFrame:
|
||||
return pd.DataFrame(rows) if rows else pd.DataFrame(columns=columns)
|
||||
|
||||
|
||||
def all_patients(cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
||||
return _frame(dbt_queries.read(cohort_queries.all_patients), ["pac_id"])
|
||||
|
||||
|
||||
def indexed(all_patients: pd.DataFrame, cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
||||
"""The patients with an index date. A patient outside `all_patients` is an error, not attrition."""
|
||||
index = _frame(dbt_queries.read(cohort_queries.index_date), ["pac_id", "fecha_indice"])
|
||||
if index["pac_id"].duplicated().any():
|
||||
raise CohortDefinitionError("the index query gives a patient more than one index date")
|
||||
if unknown := len(set(index["pac_id"]) - set(all_patients["pac_id"])):
|
||||
raise CohortDefinitionError(f"the index query gives {unknown} patients outside all patients")
|
||||
return index.assign(fecha_indice=pd.to_datetime(index["fecha_indice"]).dt.date)
|
||||
|
||||
|
||||
def excluded(rule: ExclusionRule, dbt_queries: DbtQueryRepository) -> set:
|
||||
"""Everyone the rule flags."""
|
||||
return {row["pac_id"] for row in dbt_queries.read(rule.sql)}
|
||||
|
||||
|
||||
def remaining(population: pd.DataFrame, flagged: set) -> pd.DataFrame:
|
||||
"""The previous population minus a rule's excluded members."""
|
||||
return population[~population["pac_id"].isin(flagged)]
|
||||
|
||||
|
||||
def study_population(last: pd.DataFrame) -> pd.DataFrame:
|
||||
return last
|
||||
|
||||
|
||||
def attrition(all_patients: pd.DataFrame, indexed: pd.DataFrame, populations: list[pd.DataFrame],
|
||||
rules: list[ExclusionRule]) -> pd.DataFrame:
|
||||
"""Each rule is charged only for those it removes from the population it receives."""
|
||||
sizes = [("all_patients", len(all_patients)), ("indexed", len(indexed)),
|
||||
*[(rule.name, len(population)) for rule, population in zip(rules, populations)]]
|
||||
rows = [(step, n, None if i == 0 else sizes[i - 1][1] - n) for i, (step, n) in enumerate(sizes)]
|
||||
return pd.DataFrame(rows, columns=["step", "n", "excluded"]).astype({"excluded": "Int64"})
|
||||
@@ -0,0 +1,42 @@
|
||||
"""The steps from a study population and the timeline to a build's table, with its lineage."""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
|
||||
from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame
|
||||
from models.io.storage import table_sha256
|
||||
|
||||
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
||||
TIMELINE = [name for name in SCHEMA.names if name != "fecha_indice"]
|
||||
|
||||
|
||||
def cohort_events(timeline_rows: list[dict], study_population: pd.DataFrame, cutoff: date) -> pd.DataFrame:
|
||||
"""The members' events up to `cutoff`, in the file's order. A member without events stops the build."""
|
||||
members = study_population[["pac_id", "fecha_indice"]]
|
||||
frame = pd.DataFrame(timeline_rows, columns=TIMELINE).merge(members, on="pac_id")
|
||||
frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date
|
||||
frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True)
|
||||
frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"])
|
||||
frame = frame[frame["fecha"] <= cutoff]
|
||||
if missing := len(members) - frame["pac_id"].nunique():
|
||||
raise ValueError(f"{missing} members have no events in the timeline")
|
||||
return frame.sort_values(ROW_ORDER, kind="stable")[SCHEMA.names].reset_index(drop=True)
|
||||
|
||||
|
||||
def content_sha256(cohort_events: pd.DataFrame) -> str:
|
||||
"""The hash of the rows alone, so the same content gives the same hash whenever it's built."""
|
||||
return table_sha256(pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False))
|
||||
|
||||
|
||||
def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str) -> dict:
|
||||
return {**base_lineage, "n_members": cohort_events["pac_id"].nunique(), "content_sha256": content_sha256,
|
||||
"built_at": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
|
||||
def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table:
|
||||
"""The file's table, once its rows satisfy `COHORT_FRAME`: a build that would fail to read is never written."""
|
||||
check_frame(COHORT_FRAME, cohort_events, CohortFileError, f"build {lineage.get('build') or lineage.get('armado_id')}")
|
||||
table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)
|
||||
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Each scenario's index and its rules, over a cohort's long frame (`COHORT_SCHEMA`), usually `cacu/cohorte_total`.
|
||||
|
||||
A cohort gives every patient's events; a scenario says from when it predicts (the index) and who is out given that
|
||||
index. `[config.index]` of its `model.toml` names the kind and its rules. A scenario that lists this module gets its
|
||||
source cohort as `source_cohort`; the node `cohort` gives that frame re-indexed (`fecha_indice` is the scenario's)
|
||||
with only the members left, and `index_attrition` how many each step leaves. The recruitment window is the source
|
||||
cohort's (its build's parameters), unless the config sets one. The rules are dbt's (`Transformation/models/cacu/cohorts/`, `macros/cacu_post_colposcopy.sql`), in the same
|
||||
order and with the same names, so the two can be compared before either is retired.
|
||||
|
||||
Kinds:
|
||||
|
||||
- `primera_citologia` (surveillance): the first cytology sample, if it falls in the window; out: a biopsy with the
|
||||
outcome before the index (`prior_event`), an index sample with no cytology or HPV result (`no_index_result`).
|
||||
- `post_colposcopia` (visit `visita`): the first colposcopy's episode, its result known at the last report of the
|
||||
biopsies ordered that day (PROVISIONAL: without a biopsy order it is below CIN2, which assumes the colposcopic
|
||||
impression misses no CIN2+); index at that result (`visita = 0`) or at the k-th cytology sample after it, before any
|
||||
later colposcopy; out, in order: `biopsia_sin_resultado`, `cin2_hasta_el_indice`, `antecedente_cacu`,
|
||||
`histerectomia`, `tratamiento_previo`, `sin_referencia`, `sin_cotest` (k ≥ 1).
|
||||
|
||||
Every kind ends with `observacion_previa_insuficiente`: out if the days observed before the index are fewer than
|
||||
`observacion_previa_minima_dias` (default 0, so nobody; owner, 2026-11-20). The data are left-truncated: a rule on
|
||||
earlier events ("no CIN2+ before the index", "first colposcopy", the referral year) reads only what was recorded, so
|
||||
"none before" means "none observed". The rules are kept as written; raising the threshold when the population starts
|
||||
with enough history makes them valid without changing code. Observation starts, for now, at the patient's first
|
||||
event in the frame (the platform's `periodo_observacion` doesn't reach the pipeline).
|
||||
|
||||
A scenario without `[config.index]` keeps its cohort's own index.
|
||||
"""
|
||||
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
|
||||
import pandas as pd
|
||||
|
||||
RESULT_TYPES = ("bethesda", "glandular", "vph")
|
||||
POST_COLPOSCOPY_RULES = ("biopsia_sin_resultado", "cin2_hasta_el_indice", "antecedente_cacu", "histerectomia",
|
||||
"tratamiento_previo", "sin_referencia", "sin_cotest")
|
||||
|
||||
|
||||
def _key(e: dict) -> tuple:
|
||||
return e["fuente_tabla"], e["fuente_id"]
|
||||
|
||||
|
||||
def _in_window(fecha: date, index: dict) -> bool:
|
||||
start, end = index.get("recruitment_start"), index.get("recruitment_end")
|
||||
return (start is None or fecha >= date.fromisoformat(start)) and (end is None or fecha < date.fromisoformat(end))
|
||||
|
||||
|
||||
def _results(events: list[dict], sample: dict) -> dict:
|
||||
"""The sample's Bethesda, glandular and HPV codes (first non-null of each)."""
|
||||
return {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and _key(e) == _key(sample)
|
||||
and e["valor_codigo"] is not None), None) for t in RESULT_TYPES}
|
||||
|
||||
|
||||
def _first_cytology(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
|
||||
"""The surveillance index and, per rule, whether it flags the patient."""
|
||||
samples = sorted((e for e in events if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
if not samples or not _in_window(samples[0]["fecha"], index):
|
||||
return None, []
|
||||
sample, grades = samples[0], set(index["event_grades"])
|
||||
found = _results(events, sample)
|
||||
return sample["fecha"], [
|
||||
("prior_event", any(e["tipo"] == "biopsia" and e["fecha"] < sample["fecha"] and e["valor_codigo"] in grades
|
||||
for e in events)),
|
||||
("no_index_result", all(v is None for v in found.values())),
|
||||
]
|
||||
|
||||
|
||||
def _colposcopy_episode(events: list[dict]) -> dict | None:
|
||||
"""The first colposcopy, when its result is known and how many of that day's biopsy orders have no report."""
|
||||
colposcopies = sorted((e for e in events if e["tipo"] == "colposcopia"),
|
||||
key=lambda e: (e["fecha"], e["fuente_tabla"], e["fuente_id"]))
|
||||
if not colposcopies:
|
||||
return None
|
||||
first = colposcopies[0]
|
||||
orders = {_key(e) for e in events if e["tipo"] == "orden_biopsia" and e["fecha"] == first["fecha"]}
|
||||
reports = [e for e in events if e["tipo"] == "biopsia" and _key(e) in orders]
|
||||
return {"colposcopy": first, "result_date": max((e["fecha"] for e in reports), default=first["fecha"]),
|
||||
"unreported_orders": len(orders - {_key(e) for e in reports})}
|
||||
|
||||
|
||||
def _surveillance_visits(events: list[dict], episode: dict) -> list[dict]:
|
||||
"""The cytology samples after the colposcopy's result is known, before any later colposcopy, in order."""
|
||||
result = episode["result_date"]
|
||||
closing = min((e["fecha"] for e in events if e["tipo"] == "colposcopia" and e["fecha"] > result), default=None)
|
||||
return sorted((e for e in events if e["tipo"] == "citologia" and e["fecha"] > result
|
||||
and (closing is None or e["fecha"] < closing)), key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
|
||||
|
||||
def _post_colposcopy(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
|
||||
"""The index of visit `index["visita"]` and, per rule, whether it flags the patient."""
|
||||
k = int(index["visita"])
|
||||
episode = _colposcopy_episode(events)
|
||||
if episode is None:
|
||||
return None, []
|
||||
if k == 0:
|
||||
sample, fecha = None, episode["result_date"]
|
||||
else:
|
||||
visits = _surveillance_visits(events, episode)
|
||||
if len(visits) < k:
|
||||
return None, []
|
||||
sample, fecha = visits[k - 1], visits[k - 1]["fecha"]
|
||||
if not _in_window(fecha, index):
|
||||
return None, []
|
||||
grades, hysterectomy = set(index["event_grades"]), set(index["hysterectomy_cie"])
|
||||
colposcopy, lookback = episode["colposcopy"]["fecha"], int(index["referral_lookback_days"])
|
||||
|
||||
def up_to(test):
|
||||
return any(e["fecha"] <= fecha and test(e) for e in events)
|
||||
|
||||
flags = [
|
||||
("biopsia_sin_resultado", episode["unreported_orders"] > 0),
|
||||
("cin2_hasta_el_indice", up_to(lambda e: e["tipo"] == "biopsia" and e["valor_codigo"] in grades)),
|
||||
("antecedente_cacu", up_to(lambda e: e["tipo"] == "antecedente")),
|
||||
("histerectomia", up_to(lambda e: e["tipo"] == "nota_medica" and e["valor_codigo"] in hysterectomy)),
|
||||
("tratamiento_previo", up_to(lambda e: e["tipo"] == "tratamiento")),
|
||||
("sin_referencia", not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
|
||||
and 0 <= (colposcopy - e["fecha"]).days <= lookback for e in events)),
|
||||
]
|
||||
if k >= 1:
|
||||
found = _results(events, sample)
|
||||
flags.append(("sin_cotest", found["vph"] is None or (found["bethesda"] is None and found["glandular"] is None)))
|
||||
return fecha, flags
|
||||
|
||||
|
||||
KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposcopy}
|
||||
|
||||
|
||||
def _events(cohort: pd.DataFrame) -> dict[int, list[dict]]:
|
||||
events = defaultdict(list)
|
||||
for e in cohort.to_dict("records"):
|
||||
events[int(e["pac_id"])].append(e)
|
||||
return events
|
||||
|
||||
|
||||
def _prior_days(rows: list[dict], fecha: date) -> int:
|
||||
"""Days observed before the index: from the patient's first event in the frame."""
|
||||
return (fecha - min(e["fecha"] for e in rows)).days
|
||||
|
||||
|
||||
def _indexed_members(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
|
||||
"""(members, attrition): one row per member (`pac_id`, `fecha_indice`), and how many are left after the index and
|
||||
after each rule, in order; each rule is charged only for those it removes from what it receives."""
|
||||
rule, minimum = KINDS[index["kind"]], int(index.get("observacion_previa_minima_dias", 0))
|
||||
events = _events(cohort)
|
||||
found = {}
|
||||
for pac_id, rows in sorted(events.items()):
|
||||
fecha, flags = rule(rows, index)
|
||||
if fecha is not None:
|
||||
flags = [*flags, ("observacion_previa_insuficiente", _prior_days(rows, fecha) < minimum)]
|
||||
found[pac_id] = (fecha, flags)
|
||||
left = {pac_id: flags for pac_id, (fecha, flags) in found.items() if fecha is not None}
|
||||
attrition = [("pacientes", len(found)), ("indexed", len(left))]
|
||||
names = [name for name, _ in next(iter(left.values()), [])]
|
||||
for position, name in enumerate(names):
|
||||
left = {pac_id: flags for pac_id, flags in left.items() if not flags[position][1]}
|
||||
attrition.append((name, len(left)))
|
||||
members = pd.DataFrame([(pac_id, found[pac_id][0]) for pac_id in left], columns=["pac_id", "fecha_indice"])
|
||||
return members, attrition
|
||||
|
||||
|
||||
def _with_window(cohort_lineage: dict, index: dict) -> dict:
|
||||
"""The index config with the source cohort's recruitment window (its build's `parametros`), unless the config
|
||||
sets its own: the window lives once, in the cohort's dbt vars."""
|
||||
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
|
||||
return {**{k: parameters[k] for k in ("recruitment_start", "recruitment_end") if k in parameters}, **index}
|
||||
|
||||
|
||||
def cohort(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> pd.DataFrame:
|
||||
"""The source cohort's long frame re-indexed by the scenario (`[config.index]`): only its members, each with the
|
||||
scenario's `fecha_indice`. Without an index config, the source cohort as it is."""
|
||||
if not index:
|
||||
return source_cohort
|
||||
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
|
||||
return (source_cohort.drop(columns="fecha_indice").merge(members, on="pac_id")[list(source_cohort.columns)]
|
||||
.reset_index(drop=True))
|
||||
|
||||
|
||||
def index_attrition(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> list:
|
||||
"""How many are left after the scenario's index and each of its rules; empty without an index config."""
|
||||
return _indexed_members(source_cohort, _with_window(cohort_lineage, index))[1] if index else []
|
||||
|
||||
|
||||
def prior_observation(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> dict:
|
||||
"""How much history the scenario's members had before their index (aggregates only): how many, how many with
|
||||
under a year, and the median days. Shows the weight of left truncation while the threshold is 0."""
|
||||
if not index:
|
||||
return {}
|
||||
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
|
||||
events = _events(source_cohort)
|
||||
days = pd.Series([_prior_days(events[int(p)], f) for p, f in members.itertuples(index=False)], dtype=float)
|
||||
return {"members": len(days), "under_365_days": int((days < 365).sum()),
|
||||
"median_days": None if days.empty else float(days.median()),
|
||||
"threshold_days": int(index.get("observacion_previa_minima_dias", 0))}
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Fitting a classifier on labelled members and measuring it: the steps every scenario shares.
|
||||
|
||||
A scenario's own module produces `labelled_members` (one row per member whose outcome is known, its predictors and
|
||||
the outcome) and the driver passes both modules to `with_modules`, with `predictor_columns`, `train_fraction` and the
|
||||
`classifier` config. Each node is named after what it produces. No node reads, writes or logs: registering the result
|
||||
is a saver's job.
|
||||
|
||||
The routines' records (ML-01a) a classifier leaves are here too: `analytic_method`, `class_balance` and
|
||||
`output_confidence`, and `routines`, which gathers them with the scenario's own `sampling` and `missing_data` under the
|
||||
kinds the registry checks before promoting.
|
||||
|
||||
The classifier is chosen by config: `@config.when(classifier=...)` picks one `prefit_classifier`, so another
|
||||
classifier is one more function here and no change to any scenario.
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
from hamilton.function_modifiers import config, extract_fields
|
||||
from sklearn.base import ClassifierMixin, clone
|
||||
from sklearn.compose import ColumnTransformer
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
|
||||
SPLIT_ORDER = ("fecha_indice", "pac_id")
|
||||
PROBABILITY = "probabilidad"
|
||||
|
||||
|
||||
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
|
||||
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float, target_column: str = "y",
|
||||
split_order: tuple = SPLIT_ORDER) -> dict:
|
||||
"""The oldest members by `split_order` train and the newest test: a model is judged on cases later than the ones
|
||||
it learned from, never on a shuffled mix."""
|
||||
if target_column not in labelled_members.columns:
|
||||
raise ValueError(f"labelled_members has no {target_column!r} column")
|
||||
ordered = labelled_members.sort_values(list(split_order), kind="stable")
|
||||
cut = int(len(ordered) * train_fraction)
|
||||
return {"train_set": ordered.iloc[:cut], "test_set": ordered.iloc[cut:]}
|
||||
|
||||
|
||||
def encoder(predictor_columns: list[str]) -> ColumnTransformer:
|
||||
"""One-hot predictors; a category not seen in training counts as none of the known ones."""
|
||||
return ColumnTransformer([("predictors", OneHotEncoder(handle_unknown="ignore"), list(predictor_columns))])
|
||||
|
||||
|
||||
@config.when(classifier="logistic")
|
||||
def prefit_classifier__logistic(max_iter: int = 1000) -> ClassifierMixin:
|
||||
"""An unfitted logistic regression."""
|
||||
return LogisticRegression(max_iter=max_iter)
|
||||
|
||||
|
||||
def fitted_pipeline(encoder: ColumnTransformer, prefit_classifier: ClassifierMixin, train_set: pd.DataFrame,
|
||||
predictor_columns: list[str], target_column: str = "y") -> Pipeline:
|
||||
"""The encoder and the classifier fitted on `train_set`. Fits copies, so the prefit nodes stay unfitted."""
|
||||
pipeline = Pipeline([("encode", clone(encoder)), ("classify", clone(prefit_classifier))])
|
||||
return pipeline.fit(train_set[list(predictor_columns)], train_set[target_column])
|
||||
|
||||
|
||||
def test_probabilities(fitted_pipeline: Pipeline, test_set: pd.DataFrame, predictor_columns: list[str]) -> pd.Series:
|
||||
"""The probability of the outcome for each row of `test_set`."""
|
||||
return pd.Series(fitted_pipeline.predict_proba(test_set[list(predictor_columns)])[:, 1], index=test_set.index,
|
||||
name=PROBABILITY)
|
||||
|
||||
|
||||
def auc(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
|
||||
"""Area under the ROC curve on `test_set`; undefined (an error) when the test set has a single class."""
|
||||
return float(roc_auc_score(test_set[target_column], test_probabilities))
|
||||
|
||||
|
||||
def brier_score(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
|
||||
return float(brier_score_loss(test_set[target_column], test_probabilities))
|
||||
|
||||
|
||||
def positive_rate_train(train_set: pd.DataFrame, target_column: str = "y") -> float:
|
||||
return float(train_set[target_column].mean())
|
||||
|
||||
|
||||
def positive_rate_test(test_set: pd.DataFrame, target_column: str = "y") -> float:
|
||||
return float(test_set[target_column].mean())
|
||||
|
||||
|
||||
def mean_probability_test(test_probabilities: pd.Series) -> float:
|
||||
return float(test_probabilities.mean())
|
||||
|
||||
|
||||
def metrics(auc: float, brier_score: float, train_set: pd.DataFrame, test_set: pd.DataFrame,
|
||||
positive_rate_train: float, positive_rate_test: float, mean_probability_test: float) -> dict:
|
||||
"""What a training run records: aggregates only, no patient data. The keys are the names MLflow keeps."""
|
||||
return {"auc": auc, "brier": brier_score, "n_train": len(train_set), "n_test": len(test_set),
|
||||
"positive_rate_train": positive_rate_train, "positive_rate_test": positive_rate_test,
|
||||
"mean_probability_test": mean_probability_test}
|
||||
|
||||
|
||||
def analytic_method(fitted_pipeline: Pipeline) -> dict:
|
||||
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
|
||||
classifier = fitted_pipeline.named_steps["classify"]
|
||||
features = fitted_pipeline.named_steps["encode"].get_feature_names_out()
|
||||
return {"method": "regresión logística sobre los predictores codificados one-hot",
|
||||
"estimator": type(classifier).__name__, "settings": classifier.get_params(),
|
||||
"intercept": float(classifier.intercept_[0]),
|
||||
"coefficients": dict(zip(map(str, features), map(float, classifier.coef_[0])))}
|
||||
|
||||
|
||||
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame, fitted_pipeline: Pipeline) -> dict:
|
||||
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
|
||||
weight = fitted_pipeline.named_steps["classify"].class_weight
|
||||
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
|
||||
"train": {str(k): int(v) for k, v in train_set["y"].value_counts().sort_index().items()},
|
||||
"test": {str(k): int(v) for k, v in test_set["y"].value_counts().sort_index().items()}}
|
||||
|
||||
|
||||
def output_confidence(test_set: pd.DataFrame, test_probabilities: pd.Series, calibration_bins: int = 10) -> dict:
|
||||
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by tenths."""
|
||||
bins = pd.qcut(test_probabilities, q=min(calibration_bins, test_probabilities.nunique()), duplicates="drop")
|
||||
table = pd.DataFrame({"p": test_probabilities, "y": test_set["y"]}).groupby(bins, observed=True).agg(
|
||||
n=("y", "size"), mean_probability=("p", "mean"), observed_rate=("y", "mean"))
|
||||
return {"method": "calibración en la prueba: probabilidad media contra frecuencia observada, por cuantiles",
|
||||
"brier": float(brier_score_loss(test_set["y"], test_probabilities)),
|
||||
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.mean_probability),
|
||||
"observed_rate": float(row.observed_rate)} for interval, row in table.iterrows()]}
|
||||
|
||||
|
||||
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
|
||||
output_confidence: dict) -> dict:
|
||||
"""Each routine's record, by the kind it's stored under (ML-01a)."""
|
||||
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
|
||||
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
|
||||
@@ -0,0 +1,15 @@
|
||||
"""From an estimate's rows to the risks a batch stores: `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo,
|
||||
ic_alto)`; `fecha_indice` is the model's index date for the member, which its horizons count from."""
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
|
||||
|
||||
|
||||
def risk_rows(estimate: pd.DataFrame) -> list[tuple]:
|
||||
"""One risk per member and horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a member scored
|
||||
twice at one horizon or a probability outside 0..1 stops the batch."""
|
||||
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
|
||||
return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), None, None)
|
||||
for pac_id, fecha, horizon, probability in zip(estimate["pac_id"], estimate["fecha_indice"],
|
||||
estimate["horizonte_anios"], estimate["probabilidad"])]
|
||||
@@ -1,21 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from models.base import ScreeningModel
|
||||
|
||||
|
||||
class TeaModel(ScreeningModel):
|
||||
"""Scaffold for the TEA (autism spectrum disorder) screening model.
|
||||
|
||||
Can pull its own training data straight from `persistance.tea`'s
|
||||
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
|
||||
...) or be handed already-fetched rows. No real model yet; this is
|
||||
interface scaffolding only.
|
||||
"""
|
||||
|
||||
domain = "tea"
|
||||
|
||||
def train(self, data: Any = None) -> None:
|
||||
raise NotImplementedError("TEA training is not implemented yet.")
|
||||
|
||||
def predict(self, data: Any) -> Any:
|
||||
raise NotImplementedError("TEA prediction is not implemented yet.")
|
||||
@@ -0,0 +1 @@
|
||||
"""TEA's models: the EEG analysis (`eeg`)."""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""TEA's EEG analysis: the `tea` library run on one stored EDF, without the database.
|
||||
|
||||
`settings.py` maps each metric to a library feature (`model.toml`); `analyze.py` measures one EEG; `baselines.py`
|
||||
compares a value with its promoted age baseline. Reading the EDFs and writing the results back to bronze is
|
||||
`models.eeg_analysis` (`python -m models tea analyze`).
|
||||
"""
|
||||
@@ -0,0 +1,273 @@
|
||||
"""One EEG through the `tea` library: validation, then preprocessing, the processes and the metrics' biomarkers.
|
||||
|
||||
`measure` is the unit of work of a batch and may run on a Dask worker: it takes the EDF's bytes and the age the
|
||||
patient's rows give, touches no database and returns a `Measurement` with the verdict, every quality check and each
|
||||
metric's raw value. The deviation from the age baselines is added afterwards (`baselines.py`), where the registered
|
||||
models are.
|
||||
|
||||
The age is the EDF header's (recording start minus birth date) when the header has both, and the rows' otherwise:
|
||||
the file is written when the study is recorded, the rows' birth date may be missing or mistyped.
|
||||
|
||||
The library reads EDFs from paths only, so the bytes go to a temporary file for the duration of the call.
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from models.tea.eeg.settings import Settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Channel codes the library builds from the reason's first words, and the fixed code each is stored as.
|
||||
CHANNEL_CODES = {"intermittent-contact-by": "intermittent-bursts"}
|
||||
# Header and rows further apart than this, in months, are logged.
|
||||
AGE_DISAGREEMENT_MONTHS = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Check:
|
||||
code: str
|
||||
electrode: str | None
|
||||
value: float | None
|
||||
text: str | None
|
||||
unit: str | None
|
||||
low: float | None
|
||||
high: float | None
|
||||
decisive: bool
|
||||
abnormal: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MetricValue:
|
||||
code: str
|
||||
value: float | None
|
||||
electrodes: dict[str, float | None] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Measurement:
|
||||
key: str
|
||||
age_months: float | None # the age the study was analysed at
|
||||
plan_hash: str
|
||||
versions: str
|
||||
valid: int | None = None
|
||||
level: str | None = None
|
||||
clean_fraction: float | None = None
|
||||
bad_channels: int | None = None
|
||||
line_db: float | None = None
|
||||
channels: int | None = None
|
||||
duration_min: float | None = None
|
||||
asleep: int | None = None
|
||||
checks: tuple[Check, ...] = ()
|
||||
metrics: tuple[MetricValue, ...] = ()
|
||||
error: str | None = None
|
||||
seconds: float = 0.0
|
||||
|
||||
|
||||
def pipeline(settings: Settings):
|
||||
from tea.pipeline import Pipeline
|
||||
|
||||
return Pipeline.default(impl=settings.impl)
|
||||
|
||||
|
||||
def plan(settings: Settings) -> dict:
|
||||
from tea.preprocessing import PLANS
|
||||
|
||||
return PLANS[settings.plan].to_dict()
|
||||
|
||||
|
||||
def phase_detector(pipe, phase: str):
|
||||
base = pipe.module("spindle_detection")
|
||||
return type(base)(variant=base.variant, phase=phase)
|
||||
|
||||
|
||||
def processes(pipe, settings: Settings) -> list[str]:
|
||||
"""The processes the metrics need, in dependency order. Spindle detection itself runs once per sleep stage, so
|
||||
the phased biomarkers contribute only what their stage's detector requires."""
|
||||
from tea.pipeline.run_study import order_for
|
||||
|
||||
needs = [n for m in settings.metrics if not m.phase for n in (m.biomarker, m.electrodes) if n]
|
||||
requires = {r for n in needs for r in pipe.module(n).requires}
|
||||
for phase in settings.phases:
|
||||
requires.update(phase_detector(pipe, phase).requires)
|
||||
return order_for(["metrics"], {**pipe.modules, "metrics": SimpleNamespace(requires=tuple(sorted(requires)))})
|
||||
|
||||
|
||||
def versions(pipe, settings: Settings) -> str:
|
||||
"""What produced an analysis, as `name=version;...`: a new version of any module analyses every EEG again."""
|
||||
names = ["validation", "preprocessing", *processes(pipe, settings)]
|
||||
if settings.phases:
|
||||
names.append("spindle_detection")
|
||||
names += settings.biomarkers
|
||||
return ";".join(f"{n}={getattr(pipe.module(n), 'version', '?')}" for n in dict.fromkeys(names))
|
||||
|
||||
|
||||
def criterion_code(code: str, text: str, electrode: str | None) -> str:
|
||||
"""The library's channel codes are the first words of the reason, numbers included (`amplitude-4.5-x`)."""
|
||||
if electrode is None:
|
||||
return code
|
||||
if code.startswith("amplitude"):
|
||||
return "aux-amplitude" if "out of range" in text else "amplitude"
|
||||
return CHANNEL_CODES.get(code, code)
|
||||
|
||||
|
||||
def _number(value) -> float | None:
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return number if number == number else None
|
||||
|
||||
|
||||
def checks(validation, run: dict) -> tuple[Check, ...]:
|
||||
out = []
|
||||
for c in validation.checks_of(run):
|
||||
text = c.value if isinstance(c.value, str) else None
|
||||
out.append(Check(
|
||||
code=criterion_code(c.code, c.display, c.electrode), electrode=c.electrode,
|
||||
value=None if text is not None else _number(c.value), text=text, unit=c.unit or None,
|
||||
low=_number(c.low), high=_number(c.high), decisive=bool(c.decisive), abnormal=bool(c.abnormal),
|
||||
))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def gate_reasons(summary, plan: dict) -> list[str]:
|
||||
"""The plan's gates on top of the validator's verdict, as the library's own batch applies them."""
|
||||
reasons = list(summary.extra.get("reasons", []))
|
||||
gates = plan.get("gates", {})
|
||||
if gates.get("skip_no_analizable", True) and summary.level == "no_analizable" and not reasons:
|
||||
reasons.append("triage level no_analizable")
|
||||
least = gates.get("min_clean")
|
||||
if least is not None and summary.clean_fraction == summary.clean_fraction and summary.clean_fraction < least:
|
||||
reasons.append(f"plan gate: {100 * summary.clean_fraction:.0f}% clean < {100 * least:.0f}%")
|
||||
return reasons
|
||||
|
||||
|
||||
Features = dict[tuple[str, str | None], dict[str, float | None]]
|
||||
|
||||
|
||||
def features(pipe, study, settings: Settings) -> Features:
|
||||
"""Every feature of each biomarker the metrics read, by biomarker and sleep stage (`None`: no stage), with
|
||||
spindle detection run once per stage."""
|
||||
by_phase = {None: study}
|
||||
for phase in settings.phases:
|
||||
by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study))
|
||||
out: Features = {}
|
||||
for m in settings.metrics:
|
||||
for biomarker in (m.biomarker, m.electrodes):
|
||||
if biomarker and (biomarker, m.phase) not in out:
|
||||
out[biomarker, m.phase] = {k: _number(v) for k, v in
|
||||
pipe.module(biomarker).measure(by_phase[m.phase]).items()}
|
||||
return out
|
||||
|
||||
|
||||
def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]:
|
||||
out = []
|
||||
for m in settings.metrics:
|
||||
electrodes = {}
|
||||
if m.electrodes:
|
||||
electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items()
|
||||
if name.startswith(m.electrode_prefix)}
|
||||
out.append(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), electrodes))
|
||||
return tuple(out)
|
||||
|
||||
|
||||
def _error(exc: Exception) -> str:
|
||||
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
||||
return f"{type(exc).__name__}: {message}"
|
||||
|
||||
|
||||
def _study(pipe, path, settings: Settings, the_plan: dict, age_months: float | None, line_hz: float):
|
||||
"""Validation, then, for a valid study, preprocessing and the processes: (validation run, summary, verdict,
|
||||
study or None)."""
|
||||
from tea.contracts import Study
|
||||
|
||||
validation = pipe.module("validation")
|
||||
run = validation.run(path, line_hz=line_hz)
|
||||
summary = validation.summary_of(run)
|
||||
valid = int(bool(summary.valid) and not gate_reasons(summary, the_plan))
|
||||
if not valid:
|
||||
return run, summary, valid, None
|
||||
preprocessing = pipe.module("preprocessing")
|
||||
study = Study(preprocessing.run(path, preprocessing.plan_for(summary, the_plan), age_months=age_months))
|
||||
for name in processes(pipe, settings):
|
||||
study = study.with_labels(pipe.module(name).predict(study))
|
||||
return run, summary, valid, study
|
||||
|
||||
|
||||
def study_age(key: str, path: Path, row_age: float | None, days_per_month: float) -> float | None:
|
||||
"""The header's age if it has one, else `row_age`. An unreadable header counts as none: validation reports the
|
||||
file."""
|
||||
from tea.contracts import header_age_months
|
||||
|
||||
try:
|
||||
header = header_age_months(path, days_per_month=days_per_month)
|
||||
except Exception: # noqa: BLE001
|
||||
header = None
|
||||
if header is None:
|
||||
return row_age
|
||||
if row_age is not None and abs(header - row_age) > AGE_DISAGREEMENT_MONTHS:
|
||||
log.warning("EEG %s: the EDF header gives %.1f months and the patient's rows %.1f; using the header",
|
||||
key, header, row_age)
|
||||
return header
|
||||
|
||||
|
||||
def measure(key: str, edf: bytes, age_months: float | None, settings: Settings) -> Measurement:
|
||||
"""`age_months` is the rows' age, used when the EDF header has none (`study_age`). Never raises: a failure is a
|
||||
`Measurement` with `error` set, keeping the verdict and checks if validation finished before it."""
|
||||
started = time.time()
|
||||
pipe = pipeline(settings)
|
||||
the_plan = plan(settings)
|
||||
result = dict(key=key, age_months=age_months, plan_hash=the_plan.get("hash", ""), versions=versions(pipe, settings))
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "study.edf"
|
||||
path.write_bytes(edf)
|
||||
result["age_months"] = age = study_age(key, path, age_months, settings.days_per_month)
|
||||
validation = pipe.module("validation")
|
||||
run, summary, valid, study = _study(pipe, path, settings, the_plan, age, settings.line_hz)
|
||||
result.update(
|
||||
valid=valid, level=summary.level, clean_fraction=_number(summary.clean_fraction),
|
||||
bad_channels=len(summary.bad_channels), line_db=_number(summary.line_db),
|
||||
channels=len(run.get("channels", [])) or None,
|
||||
duration_min=round(run["duration_s"] / 60, 2) if run.get("duration_s") else None,
|
||||
checks=checks(validation, run),
|
||||
)
|
||||
if study is None:
|
||||
return Measurement(**result, seconds=round(time.time() - started, 1))
|
||||
asleep = int((study.label("sleep_state").per_window == "sueno").any())
|
||||
return Measurement(**result, asleep=asleep, metrics=_metrics(features(pipe, study, settings), settings),
|
||||
seconds=round(time.time() - started, 1))
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop the batch
|
||||
return Measurement(**result, error=_error(exc), seconds=round(time.time() - started, 1))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReferenceStudy:
|
||||
"""One study of a reference cohort, measured for training: its age, verdict, and every feature of each
|
||||
biomarker the metrics read, by biomarker and sleep stage. No path, file name or date."""
|
||||
|
||||
key: str
|
||||
age_months: float
|
||||
valid: int | None = None
|
||||
features: Features = field(default_factory=dict)
|
||||
error: str | None = None
|
||||
|
||||
|
||||
def reference(key: str, path: str, age_months: float, settings: Settings, line_hz: float) -> ReferenceStudy:
|
||||
"""A reference study read from a local or `s3://` path, at the mains frequency of the cohort's country. Never
|
||||
raises: a failure is a `ReferenceStudy` with `error` set."""
|
||||
from tea.pipeline.storage import local_copy
|
||||
|
||||
pipe = pipeline(settings)
|
||||
try:
|
||||
with local_copy(path) as local:
|
||||
_, _, valid, study = _study(pipe, local, settings, plan(settings), age_months, line_hz)
|
||||
measured = features(pipe, study, settings) if study is not None else {}
|
||||
return ReferenceStudy(key, age_months, valid, measured)
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable study must not stop the batch
|
||||
return ReferenceStudy(key, age_months, error=_error(exc))
|
||||
@@ -0,0 +1,118 @@
|
||||
"""The promoted age baselines: a metric's raw value against its curve at the child's age.
|
||||
|
||||
Each baseline is a trained `tea` biomarker module registered as `tea-<scenario>` with the `produccion` alias. Without
|
||||
one in production a metric keeps its raw value and no deviation, the same as a model never configured.
|
||||
"""
|
||||
import math
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from models.io.lineage import registered_name
|
||||
from models.io.registry import registry as default_registry
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Deviation:
|
||||
z: float | None
|
||||
outside: int | None
|
||||
p5: float | None
|
||||
median: float | None
|
||||
p95: float | None
|
||||
|
||||
|
||||
def _number(value) -> float | None:
|
||||
try:
|
||||
number = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return number if math.isfinite(number) else None
|
||||
|
||||
|
||||
def _load(model_uri: str):
|
||||
"""The library's biomarker module of a registered baseline, leaving `sys.path` as it was.
|
||||
|
||||
The model bundles a partial copy of `tea` and MLflow puts it first on `sys.path` while loading. Left there, a Dask
|
||||
worker spawned afterwards inherits it and can't import `tea.pipeline`. The installed `tea` is imported first so
|
||||
the copy is never the package.
|
||||
"""
|
||||
import tea # noqa: F401
|
||||
from tea.serving import load_biomarker
|
||||
|
||||
path = list(sys.path)
|
||||
try:
|
||||
return load_biomarker(model_uri)
|
||||
finally:
|
||||
sys.path[:] = path
|
||||
|
||||
|
||||
def _feature_baseline(module, feature: str):
|
||||
baselines = getattr(module, "baselines", None)
|
||||
return baselines[feature] if baselines is not None else module.baseline
|
||||
|
||||
|
||||
def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]:
|
||||
"""p5, median and p95 of a centile curve at an age, interpolated on log age as the library's z is; none for a
|
||||
baseline without a curve or an age outside it."""
|
||||
curve = getattr(baseline, "curva", None)
|
||||
if curve is None or age_months is None or age_months <= 0:
|
||||
return None, None, None
|
||||
rows = curve.dropna(subset=["p5", "mediana", "p95"])
|
||||
if not len(rows):
|
||||
return None, None, None
|
||||
log_ages = np.log(rows["edad_meses"].to_numpy(float))
|
||||
at = math.log(age_months)
|
||||
if not log_ages.min() <= at <= log_ages.max():
|
||||
return None, None, None
|
||||
return tuple(_number(np.interp(at, log_ages, rows[c].to_numpy(float))) for c in ("p5", "mediana", "p95"))
|
||||
|
||||
|
||||
class Baselines:
|
||||
"""Resolves each scenario's production version once per instance, and loads it the first time it is used."""
|
||||
|
||||
def __init__(self, domain: str = "tea", registry=default_registry, loader=None):
|
||||
self.domain = domain
|
||||
self.registry = registry
|
||||
self._loader = loader
|
||||
self._resolved: dict[str, object | None] = {}
|
||||
self._loaded: dict[str, object] = {}
|
||||
|
||||
def _resolve(self, scenario: str):
|
||||
if scenario not in self._resolved:
|
||||
try:
|
||||
self._resolved[scenario] = self.registry.resolve(self.domain, scenario)
|
||||
except LookupError:
|
||||
self._resolved[scenario] = None
|
||||
return self._resolved[scenario]
|
||||
|
||||
def label(self, scenario: str) -> str | None:
|
||||
"""`tea-<scenario>/<version>` of the version in production, or none."""
|
||||
resolved = self._resolve(scenario)
|
||||
return f"{registered_name(self.domain, scenario)}/{resolved.version}" if resolved else None
|
||||
|
||||
def module(self, scenario: str):
|
||||
"""The trained biomarker module in production, or none."""
|
||||
resolved = self._resolve(scenario)
|
||||
if resolved is None:
|
||||
return None
|
||||
if scenario not in self._loaded:
|
||||
if self._loader is not None:
|
||||
self._loaded[scenario] = self._loader(resolved.model_uri)
|
||||
else:
|
||||
self._loaded[scenario] = _load(resolved.model_uri)
|
||||
return self._loaded[scenario]
|
||||
|
||||
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None) -> Deviation | None:
|
||||
"""None without a baseline in production; with one, a deviation whose fields are null where the value or
|
||||
the age is missing or the curve doesn't cover the age."""
|
||||
module = self.module(scenario)
|
||||
if module is None:
|
||||
return None
|
||||
baseline = _feature_baseline(module, feature)
|
||||
if value is None or age_months is None:
|
||||
return Deviation(None, None, None, None, None)
|
||||
outside, z = baseline.deviation(np.array([value], float), np.array([age_months], float))
|
||||
z_value = _number(z[0])
|
||||
p5, median, p95 = centiles(baseline, age_months)
|
||||
return Deviation(z_value, int(outside[0]) if z_value is not None else None, p5, median, p95)
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Trained age baselines as a bundle: exported where they were trained, imported on each platform installation.
|
||||
|
||||
What the bundle holds, per scenario: the trained module's saved state (`params.json`, `baseline.json`), which
|
||||
module it is (`module.json`), the preprocessing plan (`plan.json`), the routine records, the metrics, the
|
||||
version's promotion tags and its description; and a manifest with each file's SHA-256. Group numbers only: the
|
||||
library's privacy guard runs over every file before the bundle is written, and refuses a group under 5.
|
||||
|
||||
The import checks the manifest, accepts for each scenario only the library module the platform runs for it,
|
||||
requires the module's hash to match the one recorded where it was trained, and registers it as a new version
|
||||
with the same tags, routine records and metrics, so the registry's promotion checks read it as trained. A
|
||||
version already holding that trained module is kept.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
import zipfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, GIT_COMMIT_TAG, MODEL_SHA_TAG
|
||||
from models.io.lineage import registered_name
|
||||
from models.io.tracking import ROUTINES_PATH, experiment_id
|
||||
from models.tea.eeg import train
|
||||
from models.tea.eeg.analyze import pipeline
|
||||
from models.tea.eeg.settings import Settings
|
||||
|
||||
FORMAT = 1
|
||||
MANIFEST = "manifest.json"
|
||||
# The version tags a bundle carries: what promotion checks and what identifies the trained module. Report links
|
||||
# and promotion dates belong to each installation.
|
||||
TAGS = ("domain", "scenario", "environment", MODEL_SHA_TAG, COHORT_URL_TAG, COHORT_SOURCE_TAG, COHORT_BUILD_TAG,
|
||||
"plan_hash", "module", "module_version", "phase", "baseline")
|
||||
SOURCE_COMMIT_TAG = "origen.git_commit"
|
||||
BUNDLE_TAG = "importado.paquete"
|
||||
EPOCH = (1980, 1, 1, 0, 0, 0) # every zip entry's date, so the same baselines give the same bundle
|
||||
|
||||
|
||||
class BundleError(ValueError):
|
||||
"""A bundle that can't be exported or imported as it is, with the reason."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Exported:
|
||||
path: Path
|
||||
sha256: str
|
||||
versions: dict[str, str]
|
||||
|
||||
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def state_sha(folder: Path) -> str:
|
||||
"""The trained module's hash, as training records it (`train._module_state`): its saved JSON files."""
|
||||
files = sorted(p for p in Path(folder).glob("*.json") if p.name in ("params.json", "baseline.json"))
|
||||
return _sha(b"".join(f.name.encode() + f.read_bytes() for f in files))
|
||||
|
||||
|
||||
def _version(client, scenario: str, environment: str, production: bool):
|
||||
from models.io.registry import PRODUCTION_ALIAS
|
||||
|
||||
name = registered_name(train.DOMAIN, scenario)
|
||||
if production:
|
||||
try:
|
||||
return client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||
except Exception: # noqa: BLE001 -- none in production
|
||||
return None
|
||||
return train.latest(scenario, environment)
|
||||
|
||||
|
||||
def export(s: Settings, out: str | Path, *, environment: str = "PROD", production: bool = False) -> Exported:
|
||||
"""Every scenario's baseline into one bundle at `out`: the version in production with `production`, otherwise
|
||||
the newest trained in `environment`. Refuses a bundle missing a scenario, or holding something the privacy
|
||||
guard refuses."""
|
||||
import mlflow.artifacts
|
||||
from mlflow import MlflowClient
|
||||
from tea.serving.privacy import check_files, check_group, check_text
|
||||
|
||||
client = MlflowClient()
|
||||
versions = {scenario: _version(client, scenario, environment, production) for scenario in s.scenarios}
|
||||
missing = sorted(k for k, mv in versions.items() if mv is None)
|
||||
if missing:
|
||||
raise BundleError(f"no {'production' if production else environment} version of {', '.join(missing)}")
|
||||
manifest = {"formato": FORMAT, "dominio": train.DOMAIN, "escenarios": {}}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
for scenario, mv in versions.items():
|
||||
folder = root / scenario
|
||||
module_dir = folder / "module"
|
||||
module_dir.mkdir(parents=True)
|
||||
model = Path(mlflow.artifacts.download_artifacts(artifact_uri=f"models:/{mv.name}/{mv.version}",
|
||||
dst_path=str(root / ".descargas" / scenario)))
|
||||
saved = next((p.parent for p in model.rglob("module.json") if p.parent.name == "module"), None)
|
||||
if saved is None:
|
||||
raise BundleError(f"{scenario} version {mv.version}: its model has no trained module")
|
||||
for file in ("params.json", "baseline.json", "module.json", "plan.json"):
|
||||
if not (saved / file).exists():
|
||||
raise BundleError(f"{scenario} version {mv.version}: its trained module has no {file}")
|
||||
(module_dir / file).write_bytes((saved / file).read_bytes())
|
||||
if state_sha(module_dir) != mv.tags.get(MODEL_SHA_TAG):
|
||||
raise BundleError(f"{scenario} version {mv.version}: its saved state isn't the one it was trained with")
|
||||
routines = folder / ROUTINES_PATH
|
||||
routines.mkdir()
|
||||
for item in client.list_artifacts(mv.run_id, ROUTINES_PATH):
|
||||
local = mlflow.artifacts.download_artifacts(run_id=mv.run_id, artifact_path=item.path,
|
||||
dst_path=str(root / ".descargas"))
|
||||
(routines / Path(item.path).name).write_text(Path(local).read_text())
|
||||
run = client.get_run(mv.run_id)
|
||||
metrics = dict(run.data.metrics)
|
||||
tags = {k: mv.tags[k] for k in TAGS if k in mv.tags}
|
||||
if run.data.tags.get(GIT_COMMIT_TAG):
|
||||
tags[SOURCE_COMMIT_TAG] = run.data.tags[GIT_COMMIT_TAG]
|
||||
check_group(module_dir, int(metrics.get("n_referencia", 0)) or None)
|
||||
files = sorted(p for p in folder.rglob("*") if p.is_file())
|
||||
manifest["escenarios"][scenario] = {
|
||||
"version_origen": str(mv.version), "tags": tags, "metricas": metrics,
|
||||
"descripcion": mv.description or "",
|
||||
"archivos": {p.relative_to(root).as_posix(): _sha(p.read_bytes()) for p in files},
|
||||
}
|
||||
text = json.dumps(manifest, ensure_ascii=False, indent=1, sort_keys=True)
|
||||
check_text(text)
|
||||
(root / MANIFEST).write_text(text)
|
||||
for scenario in versions:
|
||||
check_files(root / scenario)
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as z:
|
||||
for p in sorted(q for q in root.rglob("*") if q.is_file() and ".descargas" not in q.parts):
|
||||
z.writestr(zipfile.ZipInfo(p.relative_to(root).as_posix(), EPOCH), p.read_bytes())
|
||||
out = Path(out)
|
||||
out.write_bytes(buffer.getvalue())
|
||||
return Exported(out, _sha(buffer.getvalue()), {k: str(mv.version) for k, mv in versions.items()})
|
||||
|
||||
|
||||
def _unpack(data: bytes, root: Path) -> dict:
|
||||
"""The bundle's files under `root`, each checked against the manifest; the manifest."""
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as z:
|
||||
names = z.namelist()
|
||||
for name in names:
|
||||
path = PurePosixPath(name)
|
||||
if path.is_absolute() or ".." in path.parts:
|
||||
raise BundleError(f"the bundle holds a path outside itself: {name}")
|
||||
if MANIFEST not in names:
|
||||
raise BundleError("the bundle has no manifest")
|
||||
manifest = json.loads(z.read(MANIFEST))
|
||||
if manifest.get("formato") != FORMAT or manifest.get("dominio") != train.DOMAIN:
|
||||
raise BundleError("not a bundle of TEA's EEG baselines in a format this platform reads")
|
||||
listed = {f: sha for entry in manifest["escenarios"].values() for f, sha in entry["archivos"].items()}
|
||||
if set(listed) != set(names) - {MANIFEST}:
|
||||
raise BundleError("the bundle's files aren't the ones its manifest lists")
|
||||
for name, sha in listed.items():
|
||||
content = z.read(name)
|
||||
if _sha(content) != sha:
|
||||
raise BundleError(f"{name} changed after the bundle was written")
|
||||
target = root / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(content)
|
||||
return manifest
|
||||
|
||||
|
||||
def import_(s: Settings, bundle: str | Path) -> dict[str, tuple[str, bool]]:
|
||||
"""Registers every baseline of the bundle; by scenario, (version, whether it's new)."""
|
||||
from mlflow import MlflowClient
|
||||
from tea.serving import log_biomarker
|
||||
|
||||
data = Path(bundle).read_bytes()
|
||||
bundle_sha = _sha(data)
|
||||
pipe = pipeline(s)
|
||||
out = {}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
manifest = _unpack(data, root)
|
||||
unknown = sorted(set(manifest["escenarios"]) - set(s.scenarios))
|
||||
if unknown:
|
||||
raise BundleError(f"this platform has no scenario {', '.join(unknown)}")
|
||||
for scenario, entry in manifest["escenarios"].items():
|
||||
tags = dict(entry["tags"])
|
||||
module_dir = root / scenario / "module"
|
||||
sha = state_sha(module_dir)
|
||||
if sha != tags.get(MODEL_SHA_TAG):
|
||||
raise BundleError(f"{scenario}: the module isn't the one recorded where it was trained")
|
||||
biomarker, phase = s.scenarios[scenario]
|
||||
if tags.get("module") != biomarker or (tags.get("phase") or None) != phase:
|
||||
raise BundleError(f"{scenario}: the bundle says it's {tags.get('module')}, not {biomarker}")
|
||||
cls = type(pipe.module(biomarker))
|
||||
declared = json.loads((module_dir / "module.json").read_text()).get("class")
|
||||
if declared != f"{cls.__module__}:{cls.__name__}":
|
||||
raise BundleError(f"{scenario}: the bundle's module class isn't the one this platform runs")
|
||||
existing = train.find_trained(scenario, {MODEL_SHA_TAG: sha, COHORT_BUILD_TAG: tags.get(COHORT_BUILD_TAG, ""),
|
||||
"environment": tags.get("environment", "")})
|
||||
if existing is not None:
|
||||
out[scenario] = (str(existing.version), False)
|
||||
continue
|
||||
module = cls.load(module_dir)
|
||||
name = registered_name(train.DOMAIN, scenario)
|
||||
client = MlflowClient()
|
||||
experiment_id(client, name)
|
||||
n = int(entry["metricas"].get("n_referencia", 0)) or None
|
||||
mv = log_biomarker(module, plan=json.loads((module_dir / "plan.json").read_text()), registered_name=name,
|
||||
run_name=scenario, n_reference=n, experiment=name)
|
||||
routines = {p.stem: json.loads(p.read_text()) for p in sorted((root / scenario / ROUTINES_PATH).glob("*.json"))}
|
||||
train.record(client, name, str(mv.version), mv.run_id, tags={**tags, BUNDLE_TAG: bundle_sha},
|
||||
routines=routines, metrics=entry["metricas"], description=entry["descripcion"])
|
||||
out[scenario] = (str(mv.version), True)
|
||||
return out
|
||||
@@ -0,0 +1,61 @@
|
||||
"""TEA's EEG baselines as a model of the platform: `python -m models run tea eeg --train [--promote]`.
|
||||
|
||||
A baseline isn't trained on a cohort build of the platform but on the reference cohort (`train.py`), so this
|
||||
scenario runs its own steps (`run_steps`) in place of `run`'s cohort-file ones: training every scenario's baseline,
|
||||
then promoting each through the registry's checks. `--reference-dir` trains on a folder of EEGs on this machine
|
||||
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
|
||||
"""
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from models.tea.eeg.settings import settings
|
||||
|
||||
SETTINGS = settings()
|
||||
|
||||
|
||||
def run_steps(args: argparse.Namespace) -> int:
|
||||
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
|
||||
from models.tea.eeg import train
|
||||
|
||||
if args.export or args.estimate or args.store or args.version:
|
||||
print("tea/eeg trains on its reference cohort: only --train and --promote apply", file=sys.stderr)
|
||||
return 2
|
||||
environment = args.environment.upper()
|
||||
s = SETTINGS
|
||||
if getattr(args, "reference_dir", None):
|
||||
from models.tea.eeg.reference import local
|
||||
|
||||
s = local(SETTINGS, folder=args.reference_dir, ages_table=args.reference_ages,
|
||||
name=args.reference_name or "local", line_hz=args.line_hz or 60.0)
|
||||
elif getattr(args, "reference_ages", None) or getattr(args, "line_hz", None):
|
||||
print("--reference-ages and --line-hz go with --reference-dir", file=sys.stderr)
|
||||
return 2
|
||||
versions: dict[str, str] = {}
|
||||
if args.train:
|
||||
for scenario, (version, new) in train.train_all(s, environment).items():
|
||||
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
|
||||
versions[scenario] = version
|
||||
if not args.promote:
|
||||
return 0
|
||||
code = 0
|
||||
for scenario in SETTINGS.scenarios:
|
||||
version = versions.get(scenario) or getattr(train.latest(scenario, environment), "version", None)
|
||||
if version is None:
|
||||
print(f"{scenario}: no {environment} version to promote; use --train", file=sys.stderr)
|
||||
code = 1
|
||||
continue
|
||||
try:
|
||||
current = registry.client.get_model_version_by_alias(registered_name("tea", scenario), PRODUCTION_ALIAS)
|
||||
except Exception: # noqa: BLE001 -- no version in production yet
|
||||
current = None
|
||||
if current is not None and str(current.version) == str(version):
|
||||
print(f"{scenario}: version {version} already in production")
|
||||
continue
|
||||
try:
|
||||
registry.promote("tea", scenario, str(version))
|
||||
print(f"{scenario}: version {version} promoted")
|
||||
except PromotionBlocked as blocked:
|
||||
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
|
||||
print(f"{scenario}: version {version} not promoted, missing: {failed}", file=sys.stderr)
|
||||
code = 1
|
||||
return code
|
||||
@@ -0,0 +1,52 @@
|
||||
# The EEG analysis: the `tea` library's plan and modules, and the library feature each stored metric is.
|
||||
domain = "tea"
|
||||
plan = "director-cluster"
|
||||
impl = "modern"
|
||||
line_hz = 60.0
|
||||
# Completed months at the study: days / days_per_month, as the TEA cohort counts them.
|
||||
days_per_month = 30.4375
|
||||
# The baselines' kind (the library's: "curves", centile curves on log age; or "age_blocks").
|
||||
baseline = "curves"
|
||||
|
||||
# The reference cohort the age baselines are trained on: the Helsinki HK1K EEGs (public), its EDFs and the table of
|
||||
# their ages under `prefix` in the cluster's S3, children of `ages` months. Its mains are at `line_hz`.
|
||||
[reference]
|
||||
name = "hk1k"
|
||||
prefix = "raw/eeg-helsinki/"
|
||||
ages_table = "anon_codex_age_sex.csv"
|
||||
line_hz = 50.0
|
||||
ages = [16.0, 36.0]
|
||||
|
||||
# One entry per `MetricaEeg` code. `phase` runs spindle detection on that sleep stage alone; `electrodes` names the
|
||||
# biomarker whose `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode.
|
||||
# The feature each metric maps to is provisional until the domain expert confirms it.
|
||||
[[metrics]]
|
||||
code = "RITMO_POSTERIOR"
|
||||
biomarker = "posterior_rhythm"
|
||||
feature = "posterior_rhythm_hz"
|
||||
|
||||
[[metrics]]
|
||||
code = "HUSOS_SUENO_N2"
|
||||
biomarker = "spindles"
|
||||
phase = "N2"
|
||||
feature = "spindle_density_per_min_channel"
|
||||
electrodes = "spindle_topography"
|
||||
electrode_prefix = "topo_enh_"
|
||||
|
||||
[[metrics]]
|
||||
code = "HUSOS_SUENO_N3"
|
||||
biomarker = "spindles"
|
||||
phase = "N3"
|
||||
feature = "spindle_density_per_min_channel"
|
||||
electrodes = "spindle_topography"
|
||||
electrode_prefix = "topo_enh_"
|
||||
|
||||
[[metrics]]
|
||||
code = "PICOS_PAROXISTICOS"
|
||||
biomarker = "spikes"
|
||||
feature = "spike_rate_nrem"
|
||||
|
||||
[[metrics]]
|
||||
code = "GRADIENTE_ANTEROPOSTERIOR"
|
||||
biomarker = "gradient"
|
||||
feature = "gradient_delta_sueno"
|
||||
@@ -0,0 +1,62 @@
|
||||
"""A reference cohort on the training machine's own disk: the site's EEGs, which never leave it.
|
||||
|
||||
`local_studies` lists a folder's EDFs (at any depth) with the age of each child at the recording, within
|
||||
`[reference] ages`. The age comes from the ages table when one is given (`archivo` and `edad_meses` or `edad_anos`
|
||||
columns, one row per file name) and from each EDF's header (recording start minus birth date) otherwise. A file with
|
||||
no age is left out. Paths stay in the listing on this machine; what leaves it is the trained baselines and the
|
||||
listing's hash (`train.Listing`).
|
||||
"""
|
||||
import dataclasses
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.tea.eeg.settings import Settings
|
||||
|
||||
LOCAL = "local"
|
||||
|
||||
|
||||
def local(s: Settings, *, folder: str | Path, ages_table: str | Path | None = None, name: str = "local",
|
||||
line_hz: float = 60.0, ages: tuple[float, float] | None = None) -> Settings:
|
||||
"""`s` with its reference cohort replaced by a folder on this machine."""
|
||||
r = dataclasses.replace(s.reference, name=name, storage=LOCAL, prefix=str(Path(folder).resolve()),
|
||||
ages_table=str(Path(ages_table).resolve()) if ages_table else "", line_hz=float(line_hz),
|
||||
ages=tuple(ages) if ages else s.reference.ages)
|
||||
return dataclasses.replace(s, reference=r)
|
||||
|
||||
|
||||
def _table_ages(path: Path) -> dict[str, float]:
|
||||
"""Age in months by file name, from a CSV with `archivo` and `edad_meses` (or `edad_anos`)."""
|
||||
table = pd.read_csv(path)
|
||||
if "archivo" not in table:
|
||||
raise ValueError(f"{path.name}: the ages table needs an `archivo` column with each EDF's file name")
|
||||
if "edad_meses" in table:
|
||||
months = table["edad_meses"].astype(float)
|
||||
elif "edad_anos" in table:
|
||||
months = table["edad_anos"].astype(float) * 12
|
||||
else:
|
||||
raise ValueError(f"{path.name}: the ages table needs `edad_meses` or `edad_anos`")
|
||||
return {str(f): round(float(m), 1) for f, m in zip(table["archivo"], months) if m == m}
|
||||
|
||||
|
||||
def local_studies(s: Settings) -> list[tuple[str, float]]:
|
||||
"""(path, age in months) of each EDF under the reference folder with an age inside `[reference] ages`."""
|
||||
from tea.contracts import header_age_months
|
||||
|
||||
r = s.reference
|
||||
folder = Path(r.prefix)
|
||||
if not folder.is_dir():
|
||||
raise FileNotFoundError(f"no folder {folder}")
|
||||
by_name = _table_ages(Path(r.ages_table)) if r.ages_table else None
|
||||
found = []
|
||||
for path in sorted(p for p in folder.rglob("*") if p.is_file() and p.suffix.lower() == ".edf"):
|
||||
if by_name is not None:
|
||||
age = by_name.get(path.name)
|
||||
else:
|
||||
try:
|
||||
age = header_age_months(path, days_per_month=s.days_per_month)
|
||||
except Exception: # noqa: BLE001 -- an unreadable header is a file with no age
|
||||
age = None
|
||||
if age is not None and r.ages[0] <= age <= r.ages[1]:
|
||||
found.append((str(path), age))
|
||||
return found
|
||||
@@ -0,0 +1,83 @@
|
||||
"""The analysis's settings (`model.toml`): the plan, the implementation and the metrics with their library features.
|
||||
|
||||
Each trained baseline is a registered model `tea-<scenario>`, one per biomarker and sleep stage
|
||||
(`eeg-spindles-n2`, `eeg-spindle-topography-n2`, `eeg-posterior-rhythm`, ...).
|
||||
"""
|
||||
import tomllib
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Metric:
|
||||
code: str
|
||||
biomarker: str
|
||||
feature: str
|
||||
phase: str | None = None
|
||||
electrodes: str | None = None
|
||||
electrode_prefix: str = ""
|
||||
|
||||
@property
|
||||
def scenario(self) -> str:
|
||||
return scenario_of(self.biomarker, self.phase)
|
||||
|
||||
@property
|
||||
def electrode_scenario(self) -> str | None:
|
||||
return scenario_of(self.electrodes, self.phase) if self.electrodes else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Reference:
|
||||
name: str
|
||||
prefix: str
|
||||
ages_table: str
|
||||
line_hz: float
|
||||
ages: tuple[float, float]
|
||||
storage: str = "s3" # "s3": the cluster's S3, read in a worker; "local": a folder on this machine (`reference.py`)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
domain: str
|
||||
plan: str
|
||||
impl: str
|
||||
line_hz: float
|
||||
days_per_month: float
|
||||
baseline: str
|
||||
reference: Reference
|
||||
metrics: tuple[Metric, ...]
|
||||
|
||||
@property
|
||||
def phases(self) -> tuple[str, ...]:
|
||||
return tuple(dict.fromkeys(m.phase for m in self.metrics if m.phase))
|
||||
|
||||
@property
|
||||
def scenarios(self) -> dict[str, tuple[str, str | None]]:
|
||||
"""Each baseline to train, by scenario: (biomarker, sleep stage)."""
|
||||
pairs = [(n, m.phase) for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
|
||||
return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)}
|
||||
|
||||
@property
|
||||
def biomarkers(self) -> tuple[str, ...]:
|
||||
"""Every biomarker a metric reads, its own or its electrodes'."""
|
||||
names = [n for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
|
||||
return tuple(dict.fromkeys(names))
|
||||
|
||||
|
||||
def scenario_of(biomarker: str, phase: str | None) -> str:
|
||||
return "eeg-" + biomarker.replace("_", "-") + (f"-{phase.lower()}" if phase else "")
|
||||
|
||||
|
||||
@cache
|
||||
def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings:
|
||||
raw = tomllib.loads(path.read_text())
|
||||
metrics = tuple(Metric(**m) for m in raw.pop("metrics"))
|
||||
reference = raw.pop("reference")
|
||||
reference = Reference(**{**reference, "ages": tuple(reference["ages"])})
|
||||
codes = [m.code for m in metrics]
|
||||
if len(set(codes)) != len(codes):
|
||||
raise ValueError(f"model.toml maps a metric code twice: {codes}")
|
||||
if raw["impl"] != "modern":
|
||||
raise ValueError("the analysis stores the modern validation's checks: impl must be 'modern'")
|
||||
return Settings(metrics=metrics, reference=reference, **raw)
|
||||
@@ -0,0 +1,230 @@
|
||||
"""The age baselines: trained on the reference cohort and registered, one version per scenario (biomarker and sleep
|
||||
stage), as `tea-<scenario>`.
|
||||
|
||||
1. `listing`: the reference cohort's EDFs and ages, within `[reference] ages`, read from the cluster's S3 in a worker
|
||||
(only the workers reach it). Its hash identifies the cohort a version was trained on (ML-03).
|
||||
2. `measure`: each study through the analysis's own unit of work (`analyze.reference`), as a Dask batch.
|
||||
3. `train_scenario`: a fresh library module trained on the valid studies' features and ages, logged with the
|
||||
library's MLflow model (`tea.serving.log_biomarker`, whose guard refuses groups under 5 and anything per child),
|
||||
then its run and version given what the registry's promotion checks read: environment, the reference cohort,
|
||||
the model's hash, the five routine records and its metrics.
|
||||
|
||||
Promotion is the registry's (`registry.promote`), as for every model: it waits for the technical, clinical and
|
||||
interpretability reports, so the domain expert's validation is what puts a baseline in production.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import tempfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.io.lineage import (
|
||||
COHORT_BUILD_TAG,
|
||||
COHORT_SOURCE_TAG,
|
||||
COHORT_URL_TAG,
|
||||
MODEL_SHA_TAG,
|
||||
code_version,
|
||||
registered_name,
|
||||
)
|
||||
from models.io.registry import REFERENCE_SOURCE
|
||||
from models.io.tracking import experiment_id, routine_path
|
||||
from models.tea.eeg.analyze import ReferenceStudy, pipeline, plan, reference
|
||||
from models.tea.eeg.settings import Settings
|
||||
|
||||
DOMAIN = "tea"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Listing:
|
||||
"""The reference studies to measure, (key, path, age in months), and the hash that identifies them. Keys are
|
||||
positions, never file names."""
|
||||
|
||||
studies: tuple[tuple[str, str, float], ...]
|
||||
sha256: str
|
||||
|
||||
@classmethod
|
||||
def of(cls, name: str, paths_and_ages: list[tuple[str, float]]) -> "Listing":
|
||||
ordered = sorted(paths_and_ages)
|
||||
digest = hashlib.sha256("\n".join(f"{p}|{a}" for p, a in ordered).encode()).hexdigest()
|
||||
return cls(tuple((f"{name}-{k:04d}", p, a) for k, (p, a) in enumerate(ordered, 1)), digest)
|
||||
|
||||
|
||||
def list_reference(s: Settings) -> list[tuple[str, float]]:
|
||||
"""In a worker: (path, age in months) of each reference EDF with an age inside `[reference] ages`, from the
|
||||
cluster's S3 or, for a cohort on this machine, from its folder (`reference.local_studies`)."""
|
||||
from tea.pipeline.storage import s3
|
||||
|
||||
from models.tea.eeg.reference import LOCAL, local_studies
|
||||
|
||||
r = s.reference
|
||||
if r.storage == LOCAL:
|
||||
return local_studies(s)
|
||||
fs = s3()
|
||||
paths = fs.find(r.prefix)
|
||||
tables = [p for p in paths if p.endswith(r.ages_table)]
|
||||
if not tables:
|
||||
raise FileNotFoundError(f"no {r.ages_table} under {r.prefix}")
|
||||
with fs.open(tables[0], "rb") as f:
|
||||
ages = pd.read_csv(f)
|
||||
ages.columns = ["archivo", "edad_anos", *ages.columns[2:]]
|
||||
edfs = {Path(p).name: p for p in paths if p.endswith(".edf")}
|
||||
found = [("s3://" + edfs[row.archivo], round(float(row.edad_anos) * 12, 1))
|
||||
for row in ages.itertuples() if row.archivo in edfs]
|
||||
return [(p, a) for p, a in found if r.ages[0] <= a <= r.ages[1]]
|
||||
|
||||
|
||||
def listing(s: Settings, cluster: str = "auto") -> Listing:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
(found,) = run_batch(list_reference, [(s,)], cluster=cluster)
|
||||
return Listing.of(s.reference.name, found)
|
||||
|
||||
|
||||
def measure(found: Listing, s: Settings, cluster: str = "auto") -> list[ReferenceStudy]:
|
||||
from tea.pipeline.dask_runner import run as run_batch
|
||||
|
||||
def lost(args, exc):
|
||||
return ReferenceStudy(args[0], args[2], error=f"{type(exc).__name__}: the batch lost this study")
|
||||
|
||||
return run_batch(reference, [(k, p, a, s, s.reference.line_hz) for k, p, a in found.studies], cluster=cluster,
|
||||
on_error=lost)
|
||||
|
||||
|
||||
def table(studies: list[ReferenceStudy], biomarker: str, phase: str | None) -> pd.DataFrame:
|
||||
"""The valid studies' features of one biomarker and stage, with their ages: what a baseline is trained on."""
|
||||
rows = [{**st.features[biomarker, phase], "age_months": st.age_months} for st in studies
|
||||
if st.valid == 1 and st.error is None and (biomarker, phase) in st.features]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _module_state(module) -> tuple[str, dict]:
|
||||
"""The trained module's hash (its saved parameters and baselines) and its baselines' state, by feature."""
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
module.save(folder)
|
||||
files = sorted(Path(folder).glob("*.json"))
|
||||
digest = hashlib.sha256(b"".join(f.name.encode() + f.read_bytes() for f in files)).hexdigest()
|
||||
baselines = json.loads((Path(folder) / "baseline.json").read_text())
|
||||
return digest, baselines
|
||||
|
||||
|
||||
def _covered(state: dict, n_min: float) -> tuple[float, float] | None:
|
||||
"""The ages every feature's curve covers with at least `n_min` effective studies."""
|
||||
spans = []
|
||||
for baseline in (state.values() if "name" not in state else [state]):
|
||||
curve = baseline.get("curva") or {}
|
||||
ages = [a for a, n in zip(curve.get("edad_meses", []), curve.get("n_efectivo", [])) if n and n >= n_min]
|
||||
if not ages:
|
||||
return None
|
||||
spans.append((min(ages), max(ages)))
|
||||
return (max(lo for lo, _ in spans), min(hi for _, hi in spans)) if spans else None
|
||||
|
||||
|
||||
def find_trained(scenario: str, expected: dict[str, str]):
|
||||
"""The newest version of the scenario whose tags hold every expected value, or `None`."""
|
||||
from mlflow import MlflowClient
|
||||
|
||||
found = MlflowClient().search_model_versions(f"name='{registered_name(DOMAIN, scenario)}'")
|
||||
matching = [mv for mv in found if all(mv.tags.get(k) == v for k, v in expected.items())]
|
||||
return max(matching, key=lambda mv: int(mv.version), default=None)
|
||||
|
||||
|
||||
def expected_tags(scenario: str, found: Listing, s: Settings, environment: str) -> dict[str, str]:
|
||||
biomarker, phase = s.scenarios[scenario]
|
||||
module = pipeline(s).module(biomarker)
|
||||
return {"environment": environment, COHORT_BUILD_TAG: found.sha256, "plan_hash": plan(s).get("hash", ""),
|
||||
"module": biomarker, "module_version": getattr(module, "version", "?"), "phase": phase or "",
|
||||
"baseline": s.baseline}
|
||||
|
||||
|
||||
def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing, s: Settings, environment: str) -> str:
|
||||
"""Trains, logs and registers one scenario's baseline; returns its version."""
|
||||
from mlflow import MlflowClient
|
||||
from tea.serving import log_biomarker
|
||||
|
||||
biomarker, phase = s.scenarios[scenario]
|
||||
data = table(studies, biomarker, phase)
|
||||
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
|
||||
module.train(data)
|
||||
sha, state = _module_state(module)
|
||||
name = registered_name(DOMAIN, scenario)
|
||||
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
|
||||
experiment_id(MlflowClient(), name)
|
||||
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
|
||||
experiment=name)
|
||||
client, run_id, version = MlflowClient(), mv.run_id, str(mv.version)
|
||||
|
||||
tags = {"domain": DOMAIN, "scenario": scenario, MODEL_SHA_TAG: sha,
|
||||
COHORT_URL_TAG: f"{DOMAIN}/{REFERENCE_SOURCE}/{s.reference.name}", COHORT_SOURCE_TAG: REFERENCE_SOURCE,
|
||||
**expected_tags(scenario, found, s, environment)}
|
||||
features = [c for c in data.columns if c != "age_months"]
|
||||
present = {f: int(data[f].notna().sum()) for f in features}
|
||||
params = getattr(module, "baseline_params", {}) or {}
|
||||
n_min = float(params.get("n_min", 30))
|
||||
covered = _covered(state, n_min) if s.baseline == "curves" else None
|
||||
measured = [st for st in studies if st.error is None]
|
||||
routines = {
|
||||
"MUESTREO": {"cohorte": s.reference.name, "edades_meses": list(s.reference.ages),
|
||||
"estudios_listados": len(found.studies), "medidos": len(measured),
|
||||
"validos": sum(st.valid == 1 for st in measured), "con_error": len(studies) - len(measured),
|
||||
"usados": len(data), "fase_de_sueno": phase},
|
||||
"DATOS_FALTANTES": {"criterio": "cada curva usa los estudios con ese rasgo medido; los demás se omiten",
|
||||
"estudios_con_valor_por_rasgo": present},
|
||||
"METODO_ANALITICO": {"modulo": biomarker, "version_modulo": tags["module_version"], "linea_base": s.baseline,
|
||||
"parametros": params, "plan": s.plan, "plan_hash": tags["plan_hash"],
|
||||
"red_electrica_hz": s.reference.line_hz},
|
||||
"BALANCE_CLASES": {"aplica": False, "motivo": "una curva de referencia por edad no tiene clases"},
|
||||
"CONFIANZA_SALIDA": {"salida": "z contra la curva a la edad del niño; -1/+1 debajo del p5 / arriba del p95",
|
||||
"edades_cubiertas_meses": list(covered) if covered else None,
|
||||
"n_efectivo_minimo": n_min},
|
||||
}
|
||||
metrics = {"n_referencia": len(data), **{f"n.{feature}": n for feature, n in present.items()}}
|
||||
if covered:
|
||||
metrics.update(edad_min_cubierta=covered[0], edad_max_cubierta=covered[1])
|
||||
description = (
|
||||
f"Curva de referencia por edad de {biomarker}{f' en sueño {phase}' if phase else ''}, entrenada en "
|
||||
f"{s.reference.name} ({len(data)} estudios de {s.reference.ages[0]:g} a {s.reference.ages[1]:g} meses). "
|
||||
"Pendiente de validación clínica.")
|
||||
record(client, name, version, run_id, tags=tags, routines=routines, metrics=metrics, description=description)
|
||||
return version
|
||||
|
||||
|
||||
def record(client, name: str, version: str, run_id: str, *, tags: dict[str, str], routines: dict[str, dict],
|
||||
metrics: dict[str, float], description: str) -> None:
|
||||
"""What the registry's promotion checks read, on a version and its run: the tags (on both, with the code
|
||||
version on the run), the routine records, the metrics and the description."""
|
||||
for key, value in {**tags, **code_version()}.items():
|
||||
client.set_tag(run_id, key, value)
|
||||
for key, value in tags.items():
|
||||
client.set_model_version_tag(name, version, key, value)
|
||||
for kind, routine in routines.items():
|
||||
client.log_text(run_id, json.dumps(routine, ensure_ascii=False, indent=1, default=str), routine_path(kind))
|
||||
for key, value in metrics.items():
|
||||
client.log_metric(run_id, key, value)
|
||||
client.update_model_version(name, version, description=description)
|
||||
|
||||
|
||||
def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Listing | None = None,
|
||||
studies: list[ReferenceStudy] | None = None) -> dict[str, tuple[str, bool]]:
|
||||
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
|
||||
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
|
||||
scenario needs it."""
|
||||
found = found or listing(s, cluster)
|
||||
out, pending = {}, []
|
||||
for scenario in s.scenarios:
|
||||
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
|
||||
if existing is not None:
|
||||
out[scenario] = (str(existing.version), False)
|
||||
else:
|
||||
pending.append(scenario)
|
||||
if pending:
|
||||
studies = studies if studies is not None else measure(found, s, cluster)
|
||||
for scenario in pending:
|
||||
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
||||
return out
|
||||
|
||||
|
||||
def latest(scenario: str, environment: str):
|
||||
"""The newest version of the scenario trained in `environment`, or `None`."""
|
||||
return find_trained(scenario, {"environment": environment})
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Helpers for other code's tests: a known `RiskEstimator` to run the risk chain without a trained model.
|
||||
|
||||
`CacuStandIn` gives a fixed, predictable probability from two baseline predictors, without MLflow, so a
|
||||
test of estimating, storing, confirming or publishing risks can assert exact values. It isn't a clinical
|
||||
model and isn't used outside tests; it has no tests of its own.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from models.io.contracts import Provenance, Risk
|
||||
|
||||
# A base probability and what each baseline predictor adds, capped at `tope`.
|
||||
CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
|
||||
NORMAL_PAPS = ("NORMAL",)
|
||||
|
||||
|
||||
class CacuStandIn:
|
||||
"""A deterministic estimator over the frame of `cacu/cohorte_vigilancia`.
|
||||
|
||||
The probability is `CACU_RULE["base"]`, plus `pap_anormal` if `pap_0` is neither `NORMAL` nor null,
|
||||
plus `vph_positivo` if `hpv_0` is `POSITIVO`, capped at `tope`. One `Risk` per member and horizon, in
|
||||
the frame's order, with no interval. `modelo_sha` is the sha256 of the rule, so changing it changes
|
||||
the provenance.
|
||||
"""
|
||||
|
||||
def __init__(self, cohort_url: str = "cacu/cohorte_vigilancia", outcome: str = "cin2_mas",
|
||||
horizons: tuple[float, ...] = (0.0,)):
|
||||
self.cohort_url = cohort_url
|
||||
self.outcome = outcome
|
||||
self.horizons = tuple(horizons)
|
||||
|
||||
def provenance(self) -> Provenance:
|
||||
rule = {"regla": CACU_RULE, "pap_normales": NORMAL_PAPS, "horizontes": self.horizons}
|
||||
sha = hashlib.sha256(json.dumps(rule, sort_keys=True).encode("utf-8")).hexdigest()
|
||||
return Provenance(modelo_nombre="sustituto", modelo_version="1", mlflow_run_id="sin-mlflow", modelo_sha=sha)
|
||||
|
||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]:
|
||||
missing = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columns]
|
||||
if missing:
|
||||
raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.")
|
||||
i_pac, i_fecha, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "fecha_indice", "pap_0", "hpv_0"))
|
||||
risks = []
|
||||
for row in rows:
|
||||
p = CACU_RULE["base"]
|
||||
if row[i_pap] is not None and row[i_pap] not in NORMAL_PAPS:
|
||||
p += CACU_RULE["pap_anormal"]
|
||||
if row[i_hpv] == "POSITIVO":
|
||||
p += CACU_RULE["vph_positivo"]
|
||||
p = min(p, CACU_RULE["tope"])
|
||||
risks += [Risk(int(row[i_pac]), row[i_fecha], float(h), round(p, 6)) for h in self.horizons]
|
||||
return risks
|
||||
@@ -1,143 +0,0 @@
|
||||
"""Bookkeeping around a training run (ML-01..ML-05).
|
||||
|
||||
Does not train anything. It opens an MLflow run, records which cohort
|
||||
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
|
||||
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
|
||||
stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped
|
||||
methods instead of the fluent API's global active run, so two runs in one
|
||||
process never interfere.
|
||||
|
||||
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
|
||||
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from mlflow import MlflowClient, MlflowException
|
||||
from persistance.repository import Repository
|
||||
|
||||
from models.base import resolve_repository
|
||||
from models.registry import ARMADO_TAG, DOMAINS, REPORT_TAGS, registered_name
|
||||
|
||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||
|
||||
|
||||
class ReadOnlyRepository:
|
||||
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
||||
Write methods raise `PermissionError` so a training routine cannot
|
||||
modify clinical data."""
|
||||
|
||||
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
|
||||
|
||||
def __init__(self, repository: Repository):
|
||||
self._repository = repository
|
||||
self.model = repository.model
|
||||
|
||||
def get(self, id_):
|
||||
return self._repository.get(id_)
|
||||
|
||||
def list(self, *, limit: int = 100, offset: int = 0, **filters):
|
||||
return self._repository.list(limit=limit, offset=offset, **filters)
|
||||
|
||||
def count(self, **filters) -> int:
|
||||
return self._repository.count(**filters)
|
||||
|
||||
def __getattr__(self, name: str):
|
||||
if name in self._WRITE_METHODS:
|
||||
raise PermissionError(
|
||||
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
|
||||
)
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
class TrainingRun:
|
||||
"""One instance per training execution, wrapping one MLflow run. PROD
|
||||
runs require `cohorte_armado_id`, the indicator kit cohort build they were
|
||||
trained on, so their metrics trace back to that data (ML-03); dev runs may
|
||||
omit it.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
domain: str,
|
||||
scenario: str,
|
||||
environment: Environment | str,
|
||||
cohorte_armado_id: int | None = None,
|
||||
):
|
||||
if domain not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {domain!r}")
|
||||
environment = Environment(environment)
|
||||
if environment is Environment.PROD and cohorte_armado_id is None:
|
||||
raise ValueError("ML-03: una corrida PROD debe enlazar el armado de cohorte (cohorte_armado_id).")
|
||||
|
||||
self.domain = domain
|
||||
self.scenario = scenario
|
||||
self.environment = environment
|
||||
self.cohorte_armado_id = cohorte_armado_id
|
||||
self.client = MlflowClient()
|
||||
experiment_id = self._experiment_id()
|
||||
run = self.client.create_run(
|
||||
experiment_id,
|
||||
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
|
||||
)
|
||||
self.run_id = run.info.run_id
|
||||
if cohorte_armado_id is not None:
|
||||
self.client.set_tag(self.run_id, ARMADO_TAG, str(cohorte_armado_id))
|
||||
|
||||
def _experiment_id(self) -> str:
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
experiment = self.client.get_experiment_by_name(name)
|
||||
if experiment:
|
||||
return experiment.experiment_id
|
||||
root = os.environ.get(ARTIFACT_ROOT_ENV)
|
||||
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
|
||||
|
||||
def repository(self, entity: str) -> ReadOnlyRepository:
|
||||
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
|
||||
return ReadOnlyRepository(resolve_repository(self.domain, entity))
|
||||
|
||||
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
|
||||
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
|
||||
named for its kind."""
|
||||
kind = ArtifactKind(kind)
|
||||
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
|
||||
if metadata:
|
||||
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
|
||||
|
||||
def finish(
|
||||
self,
|
||||
*,
|
||||
metrics: dict[str, Any] | None = None,
|
||||
hyperparameters: dict[str, Any] | None = None,
|
||||
**reports: str | None,
|
||||
) -> str:
|
||||
"""Logs metrics/params to the run, registers it as a new version of
|
||||
`<domain>-<scenario>` tagged with `models.registry`'s promotion
|
||||
inputs (environment, cohort link, report URIs), and returns the new
|
||||
version string. Call once, after training (and artifact logging)
|
||||
completes."""
|
||||
unknown = set(reports) - set(REPORT_TAGS)
|
||||
if unknown:
|
||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||
for key, value in (metrics or {}).items():
|
||||
self.client.log_metric(self.run_id, key, value)
|
||||
for key, value in (hyperparameters or {}).items():
|
||||
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
|
||||
|
||||
name = registered_name(self.domain, self.scenario)
|
||||
try:
|
||||
self.client.create_registered_model(name)
|
||||
except MlflowException as exc:
|
||||
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||
raise
|
||||
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
|
||||
if self.cohorte_armado_id is not None:
|
||||
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
|
||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
||||
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
|
||||
self.client.set_terminated(self.run_id)
|
||||
return str(model_version.version)
|
||||
+28
-7
@@ -2,24 +2,36 @@
|
||||
name = "models"
|
||||
version = "0.1.0"
|
||||
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
|
||||
requires-python = ">=3.11"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"persistance",
|
||||
"extraction",
|
||||
"mlflow>=2.9",
|
||||
# The model DAGs (`models/pipelines`): each function a node, each parameter an edge.
|
||||
"apache-hamilton>=1.90",
|
||||
# Cohort builds are Parquet files, read and written as frames.
|
||||
"pandas>=2.0",
|
||||
"pyarrow>=15",
|
||||
"scikit-learn>=1.4",
|
||||
# The values of the cohort and estimate files (`models.io.contracts`).
|
||||
"pandera>=0.20",
|
||||
"tea",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# Only needed to read back a checkpoint's own metadata (opset, producer) in
|
||||
# models.export.inspect_onnx_metadata — writing/logging a checkpoint never
|
||||
# requires it, see that module's docstring.
|
||||
export = [
|
||||
"onnx>=1.15",
|
||||
# Reading the EEG baselines' reference cohort from the cluster's S3 (`models.tea.eeg.train`).
|
||||
eeg-reference = ["tea[s3]"]
|
||||
# Running uploaded notebooks without Quarto (models.reports.rendering.JupyterRenderer, models.reports.experiment).
|
||||
notebooks = [
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
tea = { path = "libs/tea", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
@@ -27,10 +39,19 @@ build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["models"]
|
||||
exclude = ["**/notebooks"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"onnx>=1.15",
|
||||
"reportlab>=4.0",
|
||||
"nbclient>=0.10",
|
||||
"nbconvert>=7.16",
|
||||
"ipykernel>=6.29",
|
||||
]
|
||||
# The scenarios' notebooks (`<scenario>/notebooks/`): a Jupyter kernel and the drawing of the Hamilton DAGs.
|
||||
# `graphviz` is only the Python side: drawing also needs Graphviz's `dot` program on the machine.
|
||||
notebooks = [
|
||||
"ipykernel>=6.29",
|
||||
"graphviz>=0.20",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
"""What this module covers: `models.cacu.cin2_logistic`: its outcome (a CIN2+ biopsy within the window, with members
|
||||
whose window isn't complete left out) and predictors (the index sample's results), its temporal split, that training on
|
||||
a build's file registers a version with its lineage, and the `models train`, `models estimate` and `models run`
|
||||
commands over it, repeating no step.
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
|
||||
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `dbt_exported`, builds 1 and 2
|
||||
of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow; `cacu_db` (conftest), an empty CaCu database for
|
||||
the promotion checks.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.__main__ import main
|
||||
from models.cacu.cin2_logistic import model
|
||||
from models.dags import training
|
||||
from models.dags.training import Scenario, dataflow, find_trained, train
|
||||
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
||||
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
|
||||
from models.io.registry import PRODUCTION_ALIAS, registry
|
||||
from models.io.storage import CohortFile
|
||||
from models.steps.model_fitting import train_test_split
|
||||
|
||||
CUTOFF = date(2027, 6, 30)
|
||||
SCENARIO = Scenario.load("cacu", "cin2_logistic")
|
||||
CONFIG = SCENARIO.config
|
||||
PREDICTORS, GRADES = CONFIG["predictor_columns"], CONFIG["event_grades"]
|
||||
|
||||
|
||||
def _outcomes(frame):
|
||||
return model.windowed_outcomes(frame, CUTOFF, [1.0], GRADES)
|
||||
|
||||
|
||||
def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None):
|
||||
clase = {"citologia": "procedimiento", "biopsia": "medicion"}.get(tipo, "medicion")
|
||||
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": clase, "tipo": tipo, "codigo": tipo,
|
||||
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
|
||||
|
||||
|
||||
def _member(pac_id, index, bethesda, vph, biopsy=None, biopsy_day=60):
|
||||
"""The index cytology, its Bethesda and HPV results (same sample, reported on day 7), and a biopsy if given."""
|
||||
sample = f"S{pac_id}"
|
||||
rows = [_row(pac_id, index, 0, "citologia", sample=sample), _row(pac_id, index, 7, "bethesda", bethesda, sample),
|
||||
_row(pac_id, index, 7, "vph", vph, sample)]
|
||||
if biopsy:
|
||||
rows.append(_row(pac_id, index, biopsy_day, "biopsia", biopsy))
|
||||
return rows
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_frame():
|
||||
"""Odd members: LIEAG and HPV positive at the index sample, then a LIEAG biopsy on day 60 (the event). Even members:
|
||||
NORMAL and HPV negative, then a second cytology on day 400 graded LIEAG, which the predictors must ignore."""
|
||||
rows = []
|
||||
for pac_id in range(1, 21):
|
||||
index = date(2025, 1, 1) + timedelta(days=pac_id)
|
||||
if pac_id % 2:
|
||||
rows += _member(pac_id, index, "LIEAG", "POSITIVO", biopsy="LIEAG")
|
||||
else:
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
|
||||
rows += [_row(pac_id, index, 400, "citologia", sample=f"T{pac_id}"),
|
||||
_row(pac_id, index, 405, "bethesda", "LIEAG", f"T{pac_id}")]
|
||||
return pd.DataFrame(rows, columns=SCHEMA.names)
|
||||
|
||||
|
||||
def _write(frame, path, metadata):
|
||||
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), **metadata}
|
||||
pq.write_table(table.replace_schema_metadata({k: str(v) for k, v in lineage.items()}), path)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(cohort_frame, tmp_path):
|
||||
"""The frame as build 7's file."""
|
||||
return _write(cohort_frame, tmp_path / "7.parquet", {"armado_id": 7})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def exported(cohort_frame, tmp_path, monkeypatch):
|
||||
"""Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to."""
|
||||
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia"
|
||||
_write(cohort_frame, folder / "7.parquet", {"armado_id": 7})
|
||||
_write(cohort_frame, folder / "12.parquet", {"armado_id": 12})
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
return folder
|
||||
|
||||
|
||||
def test_predictors_are_the_index_sample_results(cohort_frame):
|
||||
"""Pins down: each member's predictors come from the sample of the index cytology, matched by its source row, and a
|
||||
result the sample doesn't have is `(none)`. Fails if a later sample's result (member 2's LIEAG on day 405) is
|
||||
taken, or a missing result becomes NaN, which the encoder would reject."""
|
||||
found = model.index_sample_results(cohort_frame, PREDICTORS).set_index("pac_id")
|
||||
|
||||
assert len(found) == 20
|
||||
assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"]
|
||||
assert found.loc[2, ["bethesda", "vph"]].tolist() == ["NORMAL", "NEGATIVO"]
|
||||
|
||||
|
||||
def test_the_genotype_is_read_from_its_number():
|
||||
"""Pins down: the HPV 16/18 result is stored as 1 or 0 in `valor_numerico`, and becomes POSITIVO or NEGATIVO. Fails
|
||||
if the genotype is read from `valor_codigo`, which is empty for it."""
|
||||
index = date(2025, 1, 1)
|
||||
frame = pd.DataFrame(_member(1, index, "ASC-US", "POSITIVO")
|
||||
+ [_row(1, index, 7, "vph_genotipo_16_18", sample="S1", numero=1.0)], columns=SCHEMA.names)
|
||||
|
||||
assert model.index_sample_results(frame, PREDICTORS).loc[0, "vph_16_18"] == "POSITIVO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0),
|
||||
("LIEAG", 400, 0)])
|
||||
def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected):
|
||||
"""Pins down: `y` is 1 only for a biopsy graded LIEAG, CIS or CARCINOMA within 12 months of the index date. Fails if
|
||||
a lower grade counts, or a biopsy after the window does."""
|
||||
frame = pd.DataFrame(_member(1, date(2025, 1, 1), "NORMAL", "NEGATIVO", biopsy=grade, biopsy_day=day),
|
||||
columns=SCHEMA.names)
|
||||
|
||||
assert _outcomes(frame).loc[0, "y"] == expected
|
||||
|
||||
|
||||
def test_a_member_without_a_complete_window_is_scored_but_not_trained_on():
|
||||
"""Pins down: a member with no event and less than the window's follow-up to the cut-off isn't known and is left out
|
||||
of `labelled_members`; one with the event is kept however short the follow-up. Fails if unknown members train as negatives,
|
||||
which biases the risk down."""
|
||||
late = date(2027, 3, 1)
|
||||
frame = pd.DataFrame(_member(1, late, "NORMAL", "NEGATIVO") + _member(2, late, "LIEAG", "POSITIVO", biopsy="CIS",
|
||||
biopsy_day=30), columns=SCHEMA.names)
|
||||
outcome = _outcomes(frame).set_index("pac_id")
|
||||
|
||||
assert outcome["known"].tolist() == [False, True]
|
||||
assert model.labelled_members(model.index_sample_results(frame, PREDICTORS), _outcomes(frame))["pac_id"].tolist() == [2]
|
||||
|
||||
|
||||
def test_split_trains_on_the_oldest_index_dates(cohort_frame):
|
||||
"""Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split
|
||||
is random or follows another column."""
|
||||
labelled = model.labelled_members(model.index_sample_results(cohort_frame, PREDICTORS), _outcomes(cohort_frame))
|
||||
parts = train_test_split(labelled, CONFIG["train_fraction"])
|
||||
|
||||
assert (len(parts["train_set"]), len(parts["test_set"])) == (14, 6)
|
||||
assert parts["train_set"]["fecha_indice"].max() < parts["test_set"]["fecha_indice"].min()
|
||||
|
||||
|
||||
def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
||||
"""Pins down the driver's external inputs: the loaders' `source_cohort` (re-indexed into `cohort` by the scenario's index) and `cohort_lineage` and the config's keys, and
|
||||
nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
|
||||
or a module added to the driver rewires a parameter."""
|
||||
required, optional = training.external_inputs(dataflow(*SCENARIO.modules, config=CONFIG))
|
||||
|
||||
assert required == {"source_cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"}
|
||||
assert optional == {"calibration_bins", "classifier", "index", "max_iter", "split_order", "target_column"}
|
||||
|
||||
|
||||
def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
|
||||
"""Pins down: the scenario's graph, without the driver's adapters, runs from a frame to its metrics and its fitted
|
||||
model with no file and no MLflow, and that model takes the long frame: one row per member, in `pac_id` order, the
|
||||
same probabilities the fitted pipeline gives the test set. Fails if a node starts reading, writing or logging, a
|
||||
node name stops matching `models.steps.model_fitting`'s, or `IndexSampleResults` orders members differently."""
|
||||
lineage = {"datos_as_of": CUTOFF.isoformat()}
|
||||
found = dataflow(*SCENARIO.modules, config=CONFIG).execute(
|
||||
["metrics", "fitted_model", "test_set", "test_probabilities"],
|
||||
inputs={"source_cohort": cohort_frame, "cohort_lineage": lineage})
|
||||
|
||||
assert found["metrics"]["n_train"] == 14 and found["metrics"]["n_test"] == 6
|
||||
probabilities = found["fitted_model"].predict_proba(cohort_frame)
|
||||
assert probabilities.shape == (20, 2)
|
||||
test_rows = found["test_set"]["pac_id"].to_numpy() - 1
|
||||
assert probabilities[test_rows, 1] == pytest.approx(found["test_probabilities"].to_numpy())
|
||||
|
||||
|
||||
def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking):
|
||||
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash, the outcome's
|
||||
window and the note that it's a prototype, and a model that takes the long frame. Fails if any is lost, or if the
|
||||
driver stops reaching `registered_model`."""
|
||||
version = train(SCENARIO, CohortFile(cohort_file))
|
||||
|
||||
resolved = registry.resolve("cacu", "cin2_logistic", version)
|
||||
stored = registry.get("cacu", "cin2_logistic", version)
|
||||
run = registry.client.get_run(stored.run_id).data
|
||||
assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha
|
||||
assert "Prototipo" in stored.description and run.params["horizons_years"] == "[1.0]"
|
||||
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
|
||||
assert len(run.params["cohort.file_sha256"]) == 64
|
||||
|
||||
probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
|
||||
assert probabilities.shape == (20, 2) and ((probabilities >= 0) & (probabilities <= 1)).all()
|
||||
|
||||
|
||||
def test_training_records_each_routine_as_it_ran(cohort_file, cacu_db, mlflow_tracking):
|
||||
"""ML-01a: the run holds what sampling, missing data, the method, class balance and calibration actually did, in
|
||||
counts that add up to the split. Fails if a routine node stops being logged by `registered_model` or records
|
||||
something other than this training's own numbers."""
|
||||
version = train(SCENARIO, CohortFile(cohort_file))
|
||||
routines = registry.routines(registry.get("cacu", "cin2_logistic", version).run_id)
|
||||
assert set(routines) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
|
||||
assert routines["MUESTREO"]["train"]["n"] == 14 and routines["MUESTREO"]["test"]["n"] == 6
|
||||
assert sum(routines["BALANCE_CLASES"]["train"].values()) == 14
|
||||
assert sum(b["n"] for b in routines["CONFIANZA_SALIDA"]["bins"]) == 6
|
||||
assert routines["METODO_ANALITICO"]["coefficients"]
|
||||
failed = {check.code for check in registry.checks("cacu", "cin2_logistic", version) if not check.passed}
|
||||
assert "ML-01a" not in failed and "ML-01b" not in failed
|
||||
|
||||
|
||||
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
|
||||
"""Pins down: with no `--armado`, the command uses the highest build number, not the last by name, and registers a
|
||||
DEV version. Fails if builds sort as text (7 after 12), or the default environment changes."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
|
||||
|
||||
assert "version 1" in capsys.readouterr().out
|
||||
stored = registry.get("cacu", "cin2_logistic", "1")
|
||||
assert stored.tags[ARMADO_TAG] == "12" and stored.tags["environment"] == "DEV"
|
||||
|
||||
|
||||
def test_the_command_trains_on_the_build_it_is_given_as_prod(exported, mlflow_tracking):
|
||||
"""Pins down: `--armado` chooses the file and `--environment prod` tags the version PROD. Fails if either option
|
||||
is ignored."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--armado", "7", "--environment", "prod"]) == 0
|
||||
|
||||
stored = registry.get("cacu", "cin2_logistic", "1")
|
||||
assert stored.tags[ARMADO_TAG] == "7" and stored.tags["environment"] == "PROD"
|
||||
|
||||
|
||||
def test_prod_without_a_build_is_refused(capsys):
|
||||
"""Pins down: a prod run has to name its build (ML-03), and it's refused before anything loads. Fails if prod falls
|
||||
back to the latest file."""
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
main(["train", "cacu", "cin2_logistic", "--read", "file", "--environment", "prod"])
|
||||
|
||||
assert stopped.value.code == 2 and "--build" in capsys.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arguments, message", [
|
||||
(["cacu", "ninguno"], "no such model: cacu/ninguno"),
|
||||
(["cacu", "cin2_logistic", "--read", "file", "--armado", "99"], "export it"),
|
||||
])
|
||||
def test_what_is_missing_is_named(exported, arguments, message, capsys):
|
||||
"""Pins down: an unknown model or a build with no file ends with exit 1 and says which, with no traceback and no
|
||||
version. Fails if the command lets the import error through, or trains on another file."""
|
||||
assert main(["train", *arguments]) == 1
|
||||
assert message in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_estimate_scores_each_member_with_the_production_version(exported, mlflow_tracking, tmp_path, capsys):
|
||||
"""Pins down: with no `--version`, the command uses the version holding the production alias and writes one row per
|
||||
member, identified by `pac_id`, with the version and build in the file's metadata. Fails if it takes the newest
|
||||
version instead of the alias, or the output can't be matched to members."""
|
||||
main(["train", "cacu", "cin2_logistic", "--read", "file"])
|
||||
main(["train", "cacu", "cin2_logistic", "--read", "file"])
|
||||
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
|
||||
output = tmp_path / "risks" / "output.parquet"
|
||||
|
||||
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--output", str(output)]) == 0
|
||||
|
||||
assert "version 1" in capsys.readouterr().out
|
||||
risks = pd.read_parquet(output)
|
||||
assert list(risks.columns) == ["pac_id", "fecha_indice", "horizonte_anios", "probabilidad"]
|
||||
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
||||
metadata = pq.read_metadata(output).metadata
|
||||
assert metadata[b"modelo_version"] == b"1" and metadata[b"cohort.build"] == b"12" and metadata[b"cohort.source"] == b"kit"
|
||||
|
||||
|
||||
def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: `--version` runs that version even if it isn't in production. Fails if the option is ignored or the
|
||||
alias becomes mandatory."""
|
||||
main(["train", "cacu", "cin2_logistic", "--read", "file"])
|
||||
output = tmp_path / "output.parquet"
|
||||
|
||||
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--output", str(output), "--version", "1"]) == 0
|
||||
|
||||
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
||||
|
||||
|
||||
def test_estimate_without_a_production_version_is_refused(exported, mlflow_tracking, tmp_path, capsys):
|
||||
"""Pins down: with no `--version` and no version in production, the command ends with exit 1, says so and writes
|
||||
nothing. Fails if it falls back to another version or lets the error through."""
|
||||
main(["train", "cacu", "cin2_logistic", "--read", "file"])
|
||||
output = tmp_path / "output.parquet"
|
||||
|
||||
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--output", str(output)]) == 1
|
||||
|
||||
assert "no version in production" in capsys.readouterr().err and not output.exists()
|
||||
|
||||
|
||||
RUN = ["run", "cacu", "cin2_logistic", "--read", "file"]
|
||||
|
||||
|
||||
def _versions():
|
||||
return registry.client.search_model_versions("name='cacu-cin2_logistic'")
|
||||
|
||||
|
||||
def _armado(armado_id: int) -> None:
|
||||
"""A `CohorteArmado` row at this exact id, matching a build fixture's `armado_id` metadata: `registry.checks`'s
|
||||
ML-03 looks the tag up by id, so promoting a kit-sourced version needs the row to exist, not just the tag."""
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
session.add(CohorteArmado(
|
||||
armado_id=armado_id, url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2025, 12, 31), huella=f"huella-{armado_id}", marco_sha="m",
|
||||
n_miembros=20, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc)))
|
||||
session.commit()
|
||||
|
||||
|
||||
def _promotable(domain: str, scenario: str, version: str) -> None:
|
||||
"""The three reports a fresh training run never carries (MLD-01/01b/03: attached by a human after training,
|
||||
not by the training code), so the version clears every promotion check."""
|
||||
registry.attach_reports(domain, scenario, version, technical_validation_report_uri="docs/tecnica.pdf",
|
||||
clinical_validation_report_uri="docs/clinica.pdf",
|
||||
interpretability_report_uri="docs/interpretabilidad.html")
|
||||
|
||||
|
||||
def test_run_without_a_step_is_refused(capsys):
|
||||
"""Pins down: `run` needs a step named, so it never does everything by default. Fails if an empty call starts running
|
||||
steps."""
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
main(RUN)
|
||||
|
||||
assert stopped.value.code == 2 and "--export" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: `--train` alone registers a version, sets no alias and writes no output. Fails if a step runs without
|
||||
its option."""
|
||||
assert main([*RUN, "--train"]) == 0
|
||||
|
||||
assert len(_versions()) == 1
|
||||
with pytest.raises(LookupError):
|
||||
registry.resolve("cacu", "cin2_logistic")
|
||||
|
||||
|
||||
def test_repeating_every_step_changes_nothing(exported, cacu_db, mlflow_tracking, tmp_path, capsys):
|
||||
"""Pins down: a second identical run registers no version and doesn't rewrite the output. Fails if `--train` stops
|
||||
looking for the existing version, or `--estimate` stops reading the output's metadata."""
|
||||
output = tmp_path / "output.parquet"
|
||||
steps = [*RUN, "--train", "--armado", "12", "--environment", "prod", "--promote", "--estimate", "--output",
|
||||
str(output)]
|
||||
_armado(12)
|
||||
assert main([*RUN, "--train", "--armado", "12", "--environment", "prod"]) == 0
|
||||
_promotable("cacu", "cin2_logistic", "1")
|
||||
capsys.readouterr()
|
||||
|
||||
assert main(steps) == 0
|
||||
written = output.stat().st_mtime_ns
|
||||
capsys.readouterr()
|
||||
|
||||
assert main(steps) == 0
|
||||
|
||||
assert len(_versions()) == 1 and output.stat().st_mtime_ns == written
|
||||
out = capsys.readouterr().out
|
||||
assert "already trained" in out and "already in production" in out and "already estimated" in out
|
||||
|
||||
|
||||
def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
|
||||
"""Pins down: what says a training is the same is the file and the environment, so a build with other content or a
|
||||
PROD run gets its own version. Fails if the check ignores either and reuses a version from something else."""
|
||||
assert main([*RUN, "--train", "--armado", "7"]) == 0
|
||||
assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0
|
||||
frame = pd.read_parquet(exported / "12.parquet")
|
||||
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", {"armado_id": 12})
|
||||
assert main([*RUN, "--train", "--armado", "12"]) == 0
|
||||
|
||||
assert len(_versions()) == 3
|
||||
|
||||
|
||||
def test_another_models_version_trains_again(exported, mlflow_tracking, monkeypatch):
|
||||
"""Pins down: a version trained by another release of `models` isn't reused. Fails if the check stops comparing the
|
||||
installed package's version."""
|
||||
assert main([*RUN, "--train"]) == 0
|
||||
assert find_trained(SCENARIO, CohortFile(exported / "12.parquet")) == "1"
|
||||
|
||||
monkeypatch.setattr(training, "code_version", lambda: {"models.version": "9.9.9"})
|
||||
|
||||
assert find_trained(SCENARIO, CohortFile(exported / "12.parquet")) is None
|
||||
|
||||
|
||||
def test_a_moved_alias_estimates_again(exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: the output is reused only for the same version, so a new production version rewrites it. Fails if
|
||||
`--estimate` skips because the file exists. The alias is moved directly (not through `--promote`, which needs its
|
||||
own promotion checklist satisfied, covered separately): this test is about `--estimate`'s own version tracking."""
|
||||
output = tmp_path / "output.parquet"
|
||||
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
|
||||
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
|
||||
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
|
||||
assert main([*RUN, "--estimate", "--output", str(output)]) == 0
|
||||
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
||||
|
||||
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "2")
|
||||
assert main([*RUN, "--estimate", "--output", str(output)]) == 0
|
||||
|
||||
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2"
|
||||
|
||||
|
||||
def test_promote_needs_a_version(exported, mlflow_tracking, capsys):
|
||||
"""Pins down: `--promote` with nothing trained on the file and no `--version` ends with exit 1 and sets no alias.
|
||||
Fails if it promotes some other version."""
|
||||
assert main([*RUN, "--promote"]) == 1
|
||||
assert "use --train or --version" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_tracking, monkeypatch):
|
||||
"""Pins down: `--export` exports the kit build of `model.toml`'s cohort, and its failure stops the next steps. Fails if
|
||||
the cohort or the build change, or training continues on a stale file."""
|
||||
calls = []
|
||||
|
||||
def refuse(cohorts, read_timeline, root, domain, url, build_id=None):
|
||||
calls.append((domain, url, build_id))
|
||||
raise LookupError(f"no such build of {url}: {build_id}")
|
||||
|
||||
monkeypatch.setattr("models.pipelines.export_cohort.export_kit_build", refuse)
|
||||
|
||||
assert main([*RUN, "--export", "--train", "--armado", "7"]) == 1
|
||||
|
||||
assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)]
|
||||
assert not _versions()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dbt_exported(cohort_frame, tmp_path, monkeypatch):
|
||||
"""Builds 1 and 2 of dbt's rules under `COHORTS_DIR`, in the `dbt/` folder the export writes to; build 2 lacks member 1."""
|
||||
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
|
||||
for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])):
|
||||
path = folder / f"{number}.parquet"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_write(frame, path, {"build": number, "producer": "dbt"})
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
return folder
|
||||
|
||||
|
||||
def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported, mlflow_tracking, capsys):
|
||||
"""Pins down: `--source dbt` trains on the latest dbt build, and the version points to that file (cohort, source,
|
||||
number, hash) with no kit `armado_id`, which would name a kit build that doesn't exist. Fails if the dbt folder is
|
||||
ignored, or the version loses its cohort file."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt"]) == 0
|
||||
|
||||
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
||||
assert ARMADO_TAG not in tags
|
||||
assert (tags["cohort.source"], tags["cohort.build"], tags["cohort.url"]) == ("dbt", "2", "cacu/cohorte_vigilancia")
|
||||
assert len(tags["cohort.file_sha256"]) == 64 and "dbt/2.parquet" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, mlflow_tracking, tmp_path):
|
||||
"""Pins down: a PROD version from dbt build 1 is linked to that build (ML-03) without a kit build, and estimating
|
||||
it writes the same file reference. Fails if PROD still demands a kit `armado_id`, or `--build` stops choosing the
|
||||
dbt file. Also pins down that ML-03 (`registry.checks`) accepts a dbt cohort link, not only the kit's
|
||||
`armado_id`: without that, `--promote` below would always be refused for a dbt-trained version."""
|
||||
output = tmp_path / "output.parquet"
|
||||
base = ["run", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "1", "--environment", "prod"]
|
||||
|
||||
assert main([*base, "--train"]) == 0
|
||||
_promotable("cacu", "cin2_logistic", "1")
|
||||
assert main([*base, "--promote", "--estimate", "--output", str(output)]) == 0
|
||||
|
||||
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
||||
assert tags["environment"] == "PROD" and tags["cohort.build"] == "1"
|
||||
metadata = pq.read_metadata(output).metadata
|
||||
assert metadata[b"cohort.source"] == b"dbt" and metadata[b"cohort.build"] == b"1"
|
||||
assert metadata[b"cohort.file_sha256"].decode() == tags["cohort.file_sha256"]
|
||||
|
||||
|
||||
def test_a_missing_dbt_build_says_how_to_export_it(dbt_exported, capsys):
|
||||
"""Pins down: a dbt build that isn't exported ends with exit 1 and the dbt export command. Fails if the kit's
|
||||
command is suggested or another build is used."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "9"]) == 1
|
||||
assert "--source dbt" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_the_registered_artifact_runs_without_this_repository(cohort_file, cohort_frame, mlflow_tracking,
|
||||
predict_without_repository):
|
||||
"""Pins down: the version scores the long frame in a Python that can't import `models`, with the same probabilities
|
||||
as in this one. Fails if `IndexSampleResults` starts using a function outside the scenario's package, which would
|
||||
be pickled by reference."""
|
||||
uri = registry.resolve("cacu", "cin2_logistic", train(SCENARIO, CohortFile(cohort_file))).model_uri
|
||||
|
||||
outside = predict_without_repository(uri, cohort_frame)
|
||||
|
||||
inside = mlflow.pyfunc.load_model(uri).predict(cohort_frame)
|
||||
assert outside.to_numpy() == pytest.approx(inside)
|
||||
|
||||
|
||||
def test_by_default_the_command_reads_the_kit_build_from_the_database(cohort_frame, kit_stand_ins, mlflow_tracking,
|
||||
monkeypatch, capsys):
|
||||
"""Pins down: with no `--read`, `train` reads the latest kit build's members and timeline through the domain's
|
||||
repositories, cut at the build's date, writes no file, and the version points to the build with no file hash.
|
||||
Fails if the default goes back to the exported file, or the source's reference keeps a hash it can't have."""
|
||||
cohorts, timeline = kit_stand_ins(cohort_frame, 7, CUTOFF)
|
||||
monkeypatch.setattr("persistance.cacu.cohort_repository", cohorts)
|
||||
monkeypatch.setattr("persistance.cacu.timeline_repository", timeline)
|
||||
|
||||
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||
|
||||
assert "from kit build 7" in capsys.readouterr().out
|
||||
assert [read["until"] for read in timeline.reads] == [CUTOFF]
|
||||
tags = registry.get("cacu", "cin2_logistic", "1").tags
|
||||
assert (tags["cohort.source"], tags["cohort.build"], tags[ARMADO_TAG]) == ("kit", "7", "7")
|
||||
assert "cohort.file_sha256" not in tags
|
||||
|
||||
|
||||
def test_no_member_value_reaches_mlflow(cohort_frame, tmp_path, mlflow_tracking, mlflow_store_leaks):
|
||||
"""Pins down the outcome the logger's and the saver's allowlists are there for: after training, no `pac_id` and no
|
||||
source row id of the training data is in MLflow's database or artifacts, as text or as an integer. Fails if a
|
||||
node's rows are logged, the model keeps the training frame, or an error message carries values."""
|
||||
frame = cohort_frame.assign(pac_id=cohort_frame["pac_id"] + 987_650_000,
|
||||
fuente_id="CANARY-" + cohort_frame["fuente_id"])
|
||||
path = _write(frame, tmp_path / "input" / "7.parquet", {"armado_id": 7})
|
||||
|
||||
train(SCENARIO, CohortFile(path))
|
||||
|
||||
leaks = mlflow_store_leaks(tmp_path, texts=["CANARY-"], integers=frame["pac_id"].unique(), skip=("input",))
|
||||
assert leaks == []
|
||||
@@ -0,0 +1,280 @@
|
||||
"""What this module covers: `models.cacu.cin2_pim`: how a member's screening visits and biopsies become a code and an
|
||||
interval (one test per worked example of `docs/codificacion_pim.md`), the dataflow from a long frame to its metrics by horizon, and training and estimating through the generic
|
||||
driver, with every member scored at every horizon, also outside this repository.
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 300 simulated members (a quarter with an abnormal index sample, some with a
|
||||
prevalent or a later CIN2+ biopsy, the normal ones with a later negative cotest); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
|
||||
`predict_without_repository` (conftest).
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import mlflow.pyfunc
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.cacu.cin2_pim import model
|
||||
from models.dags import training
|
||||
from models.dags.estimation import estimate
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from models.io.registry import PRODUCTION_ALIAS, registry
|
||||
from models.io.storage import CohortFile
|
||||
|
||||
CUTOFF = date(2027, 6, 30)
|
||||
SCENARIO = training.Scenario.load("cacu", "cin2_pim")
|
||||
CONFIG = SCENARIO.config
|
||||
|
||||
|
||||
def _row(pac_id, index, days, tipo, valor=None, sample=None):
|
||||
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo,
|
||||
"codigo": tipo, "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "t",
|
||||
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
|
||||
|
||||
|
||||
def _visit(pac_id, index, day, bethesda, vph, sample=None):
|
||||
return [_row(pac_id, index, day, "bethesda", bethesda, sample), _row(pac_id, index, day, "vph", vph, sample)]
|
||||
|
||||
|
||||
def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()):
|
||||
"""The index sample (its Bethesda and HPV results share its source row, as in the timeline), later visits and
|
||||
biopsies."""
|
||||
sample = f"S{pac_id}"
|
||||
rows = [_row(pac_id, index, 0, "citologia", sample=sample), *_visit(pac_id, index, 7, bethesda, vph, sample)]
|
||||
rows += [row for day, b, v in visits for row in _visit(pac_id, index, day, b, v)]
|
||||
return rows + [_row(pac_id, index, day, "biopsia", grade) for day, grade in biopsies]
|
||||
|
||||
|
||||
def _coded(rows):
|
||||
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
coded = model.interval_coded_members(frame, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
|
||||
CONFIG["index_sample_days"], CONFIG["known_negative"], CONFIG["cytology"],
|
||||
CONFIG["history"])
|
||||
return tuple(coded.iloc[0][["c", "l", "r"]])
|
||||
|
||||
|
||||
INDEX = date(2025, 1, 1)
|
||||
ASCUS_HPV = ("ASC-US", "POSITIVO")
|
||||
COTEST_NEGATIVE = ("NORMAL", "NEGATIVO")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_frame():
|
||||
"""Abnormal members (every fourth) are biopsied within 2 months, CIN2+ for a third of them; a tenth of the normal
|
||||
ones has a CIN2+ biopsy between 1 and 2 years later. Index dates rise with `pac_id` over 2023-2024."""
|
||||
rng = np.random.default_rng(0)
|
||||
rows = []
|
||||
for pac_id in range(1, 301):
|
||||
index = date(2023, 1, 1) + timedelta(days=2 * pac_id)
|
||||
if pac_id % 4 == 0:
|
||||
grade = "LIEAG" if rng.random() < 0.35 else "NEGATIVO"
|
||||
rows += _member(pac_id, index, "LIEBG", "POSITIVO", [(45, grade)])
|
||||
elif rng.random() < 0.1:
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")],
|
||||
[(365, *COTEST_NEGATIVE)])
|
||||
else:
|
||||
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", visits=[(int(rng.integers(300, 900)), *COTEST_NEGATIVE)])
|
||||
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(cohort_frame, tmp_path):
|
||||
table = pa.Table.from_pandas(cohort_frame, schema=COHORT_SCHEMA, preserve_index=False)
|
||||
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), "armado_id": "3"}
|
||||
path = tmp_path / "3.parquet"
|
||||
pq.write_table(table.replace_schema_metadata(lineage), path)
|
||||
return path
|
||||
|
||||
|
||||
def test_patient_1_a_cin2_biopsy_at_the_referral_colposcopy_is_prevalent():
|
||||
"""Patient 1: ASC-US/HPV+ at T0, colposcopy a month later finds CIN3. Pins down `(1, 0, 0)`: she counts as a case
|
||||
in the prevalence and adds nothing to the incidence. Fails if a CIN2+ within the window stops being prevalent."""
|
||||
assert _coded(_member(1, INDEX, *ASCUS_HPV, [(30, "LIEAG")])) == (1, 0.0, 0.0)
|
||||
|
||||
|
||||
def test_patient_2_the_interval_opens_at_the_last_negative_not_at_the_index():
|
||||
"""Patient 2: ASC-US/HPV+ at T0, negative biopsies at T1 (a month), negative cotest at T2 (a year), ASC-US/HPV+ at
|
||||
T3 (two years), CIN3 at T4. Pins down `(0, T2, T4]`: the negative colposcopy makes her a control in the prevalence,
|
||||
T2 is the last time she was free, and T3's abnormal result isn't a negative. Fails if `l` goes back to 0 or an
|
||||
abnormal visit is taken for a negative."""
|
||||
c, l, r = _coded(_member(2, INDEX, *ASCUS_HPV, [(30, "NEGATIVO"), (760, "LIEAG")],
|
||||
[(365, *COTEST_NEGATIVE), (730, *ASCUS_HPV)]))
|
||||
|
||||
assert (c, l, r) == (0, pytest.approx(365 / 365.25), pytest.approx(760 / 365.25))
|
||||
|
||||
|
||||
def test_patient_3_a_case_never_found_free_has_an_unknown_baseline():
|
||||
"""Patient 3: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US/HPV+ again at T1, CIN3 at T2. Pins down
|
||||
`(-999, 0, T2]`: she may have been prevalent or incident, the likelihood weighs both, and onset is anywhere up to
|
||||
T2 (not exactly at T2). Fails if a repeated abnormal result is taken for a known baseline."""
|
||||
c, l, r = _coded(_member(3, INDEX, *ASCUS_HPV, [(395, "LIEAG")], [(365, *ASCUS_HPV)]))
|
||||
|
||||
assert (c, l, r) == (-999, 0.0, pytest.approx(395 / 365.25))
|
||||
|
||||
|
||||
def test_patient_4_a_later_negative_cotest_settles_an_unknown_baseline():
|
||||
"""Patient 4: ASC-US/HPV+ at T0, colposcopy skipped, negative cotest at T1 (a year). Pins down `(0, T1, inf)`: CIN2+
|
||||
being absorbing, free at T1 means free at T0, so she's a control in the prevalence and right-censored at T1. Fails
|
||||
if she's left unknown, which throws her away, or censored at the cut-off."""
|
||||
c, l, r = _coded(_member(4, INDEX, *ASCUS_HPV, visits=[(365, *COTEST_NEGATIVE)]))
|
||||
|
||||
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
|
||||
|
||||
|
||||
def test_an_hpv_negative_ascus_is_a_negative_visit():
|
||||
"""KPNC's second negative without histology: ASC-US/HPV+ at T0, colposcopy skipped, ASC-US with HPV negative at T1
|
||||
(a year). Pins down `(0, T1, inf)`, as for patient 4's negative cotest. Fails if `known_negative` goes back to NILM
|
||||
only, which leaves her unknown."""
|
||||
c, l, r = _coded(_member(7, INDEX, *ASCUS_HPV, visits=[(365, "ASC-US", "NEGATIVO")]))
|
||||
|
||||
assert (c, l, r) == (0, pytest.approx(365 / 365.25), np.inf)
|
||||
|
||||
|
||||
def test_an_hpv_positive_nilm_is_not_a_negative_visit():
|
||||
"""The other side of the criterion: ASC-US/HPV+ at T0, colposcopy skipped, NILM with HPV positive at T1. Pins down
|
||||
`(-999, 0, inf)`: a positive test without histology leaves the status unknown. Fails if a NILM alone counts."""
|
||||
assert _coded(_member(8, INDEX, *ASCUS_HPV, visits=[(365, "NORMAL", "POSITIVO")])) == (-999, 0.0, np.inf)
|
||||
|
||||
|
||||
def test_patient_5_a_negative_colposcopy_without_follow_up_counts_only_for_the_prevalence():
|
||||
"""Patient 5: ASC-US/HPV+ at T0, negative biopsies a month later, no further visit. Pins down `(0, 0, inf)`: a
|
||||
control in the prevalence whose factor holds no survival (S(0) = 1). Fails if she's credited follow-up up to the
|
||||
cut-off that no test checked."""
|
||||
assert _coded(_member(5, INDEX, *ASCUS_HPV, [(30, "NEGATIVO")])) == (0, 0.0, np.inf)
|
||||
|
||||
|
||||
def test_patient_6_referred_and_lost_carries_no_information():
|
||||
"""Patient 6: ASC-US/HPV+ at T0, colposcopy skipped, never seen again. Pins down `(-999, 0, inf)`, whose factor
|
||||
is 1. Fails if she's given a code that adds a term."""
|
||||
assert _coded(_member(6, INDEX, *ASCUS_HPV)) == (-999, 0.0, np.inf)
|
||||
|
||||
|
||||
def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
||||
"""Pins down the driver's external inputs: the loaders' `source_cohort` and `cohort_lineage` (the scenario's index
|
||||
re-indexes the first into `cohort`) and the config's keys, and nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
|
||||
or a module added to the driver rewires a parameter."""
|
||||
required, optional = training.external_inputs(training.dataflow(*SCENARIO.modules, config=CONFIG))
|
||||
|
||||
assert required == {"source_cohort", "cohort_lineage", "cytology", "event_grades", "history", "horizons_years", "incidence",
|
||||
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
|
||||
"train_fraction"}
|
||||
assert optional == {"index"} # from the config; a scenario without one keeps its cohort's index
|
||||
|
||||
|
||||
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
|
||||
"""Pins down: the graph runs from a frame to aggregates per horizon with no file and no MLflow, and the expected
|
||||
rate at the index visit is near the observed one. Fails if a horizon is dropped, a metric isn't a number, or the
|
||||
fit stops recovering the prevalence."""
|
||||
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
|
||||
["metrics"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["metrics"]
|
||||
|
||||
assert found["n_train"] == 210 and found["n_test"] == 90
|
||||
assert {f"n_known_{h:g}y" for h in CONFIG["horizons_years"]} <= set(found)
|
||||
assert all(isinstance(value, (int, float)) for value in found.values())
|
||||
assert found["expected_0y"] == pytest.approx(found["observed_0y"], abs=0.05)
|
||||
|
||||
|
||||
def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path,
|
||||
predict_without_repository):
|
||||
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per member
|
||||
and horizon, a risk that doesn't fall with the horizon, the same outside this repository, and storable metadata.
|
||||
Fails if the model or the estimate go back to one horizon, or the registered model needs this repository."""
|
||||
version = training.train(SCENARIO, CohortFile(cohort_file))
|
||||
registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version)
|
||||
output = tmp_path / "estimate.parquet"
|
||||
|
||||
estimate(SCENARIO, CohortFile(cohort_file), output)
|
||||
|
||||
risks = pd.read_parquet(output)
|
||||
assert len(risks) == 300 * len(CONFIG["horizons_years"])
|
||||
by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad")
|
||||
assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all()
|
||||
assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2"
|
||||
|
||||
uri = registry.resolve("cacu", "cin2_pim", version).model_uri
|
||||
outside = predict_without_repository(uri, pd.read_parquet(cohort_file))
|
||||
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
|
||||
assert outside.shape == (300, len(CONFIG["horizons_years"]))
|
||||
np.testing.assert_allclose(outside.to_numpy(), inside)
|
||||
|
||||
|
||||
def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame):
|
||||
"""Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN
|
||||
(not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up."""
|
||||
members = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
|
||||
["interval_coded_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["interval_coded_members"]
|
||||
only_negative = members[members["hpv_positive"] == 0]
|
||||
mixture = model.PrevalenceIncidenceMixture(CONFIG["horizons_years"], ("cytology",), ("hpv_positive",),
|
||||
CONFIG["incidence"], {"cytology": list(CONFIG["cytology"])}).fit(
|
||||
only_negative[model.FEATURES], only_negative[["c", "l", "r"]])
|
||||
|
||||
risks = mixture.predict_proba(members[model.FEATURES])
|
||||
|
||||
assert list(mixture.fits_) == [(0,)]
|
||||
assert np.isnan(risks[members["hpv_positive"].to_numpy() == 1]).all()
|
||||
assert not np.isnan(risks[members["hpv_positive"].to_numpy() == 0]).any()
|
||||
|
||||
|
||||
def test_the_index_cytology_takes_kpncs_categories_not_a_binary():
|
||||
"""Pins down the cytology of the TOML: each squamous or glandular code goes to its KPNC category (LIEBG is LSIL;
|
||||
CIS and adenocarcinoma are HSIL+), with both results the more severe wins (AGC over ASC-US, HSIL+ over AGC), and a
|
||||
member without a cytology gets none rather than the reference. Fails if the categories collapse back to
|
||||
normal/abnormal, the glandular result is ignored, or a missing cytology is read as NILM."""
|
||||
rows = [*_member(1, INDEX, "LIEBG", "POSITIVO"), *_member(2, INDEX, "CIS", "NEGATIVO"),
|
||||
*_member(3, INDEX, "NORMAL", "NEGATIVO"), *_member(4, INDEX, "ASC-US", "POSITIVO"),
|
||||
*_member(5, INDEX, "LIEAG", "POSITIVO"), *_member(6, INDEX, "NORMAL", "POSITIVO")]
|
||||
glandular = [(4, "AGC"), (5, "AGC"), (6, "ADENOCARCINOMA")]
|
||||
rows += [_row(pac_id, INDEX, 7, "glandular", code) for pac_id, code in glandular]
|
||||
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
frame = frame[~((frame["pac_id"] == 3) & (frame["tipo"] == "bethesda"))]
|
||||
|
||||
found = model.index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
|
||||
|
||||
assert found["cytology"].tolist() == ["LSIL", "HSIL+", None, "AGC", "HSIL+", "HSIL+"]
|
||||
|
||||
|
||||
POST_COLPOSCOPY = training.Scenario.load("cacu", "cin2_pim_post_colposcopy")
|
||||
|
||||
|
||||
def _with_referral(rows, pac_id, index, bethesda, vph, colposcopy_days=-200, referral_days=-300):
|
||||
"""A member's rows plus a referral result and a colposcopy before her index date."""
|
||||
return rows + [*_visit(pac_id, index, referral_days, bethesda, vph), _row(pac_id, index, colposcopy_days, "colposcopia")]
|
||||
|
||||
|
||||
def test_the_referral_grade_follows_kpncs_low_and_high_grade():
|
||||
"""Pins down the history of the post-colposcopy TOML: HPV-positive NILM and LSIL referrals are low grade, ASC-H
|
||||
high, an HPV-negative NILM refers no one and a result past the lookback doesn't count. Fails if the grade stops
|
||||
reading the referral before the colposcopy, its HPV condition or the lookback."""
|
||||
config = POST_COLPOSCOPY.config
|
||||
rows = []
|
||||
for pac_id, (bethesda, vph, referral_days) in enumerate([("NORMAL", "POSITIVO", -300), ("LIEBG", "NEGATIVO", -300),
|
||||
("ASC-H", "NEGATIVO", -300), ("NORMAL", "NEGATIVO", -300),
|
||||
("ASC-H", "POSITIVO", -700)], start=1):
|
||||
rows = _with_referral(rows + _member(pac_id, INDEX, "NORMAL", "NEGATIVO"), pac_id, INDEX, bethesda, vph,
|
||||
referral_days=referral_days)
|
||||
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
|
||||
found = model.index_results(frame, config["index_sample_days"], config["cytology"], config["history"])
|
||||
|
||||
assert found["referral_grade"].tolist() == ["low", "low", "high", None, None]
|
||||
assert found["cytology"].tolist() == ["NILM"] * 5
|
||||
|
||||
|
||||
def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame):
|
||||
"""Pins down that a scenario is only its TOML: the post-colposcopy one runs `cin2_pim`'s dataflow with its own
|
||||
cytology groups and referral grade, and gives metrics at every horizon. Fails if the shared dataflow stops taking
|
||||
the history from the config or a scenario needs code of its own."""
|
||||
rows = cohort_frame.to_dict("records")
|
||||
for pac_id, group in cohort_frame.groupby("pac_id"):
|
||||
index = group["fecha_indice"].iloc[0]
|
||||
rows = _with_referral(rows, pac_id, index, "ASC-H" if pac_id % 3 == 0 else "LIEBG", "POSITIVO")
|
||||
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
|
||||
|
||||
found = training.dataflow(*POST_COLPOSCOPY.modules, config=POST_COLPOSCOPY.config).execute(
|
||||
["metrics"], inputs={"source_cohort": frame, "cohort_lineage": {}})["metrics"]
|
||||
|
||||
assert {f"n_known_{h:g}y" for h in POST_COLPOSCOPY.config["horizons_years"]} <= set(found)
|
||||
assert training.Scenario.load("cacu", "cin2_pim_post_treatment").cohort == "cacu/cohorte_post_tratamiento"
|
||||
@@ -0,0 +1,119 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from models.cacu.cin2_pim import likelihood as L
|
||||
|
||||
|
||||
def simulate(n=4000, seed=0):
|
||||
"""Two groups, known prevalence and Weibull incidence, screening every year for 5 years."""
|
||||
rng = np.random.default_rng(seed)
|
||||
group = rng.integers(0, 2, n)
|
||||
X = np.column_stack([np.ones(n), group])
|
||||
Z = group[:, None].astype(float)
|
||||
theta, beta, scale, shape = np.array([-3.0, 1.5]), np.array([0.7]), 8.0, 1.3
|
||||
|
||||
prevalent = rng.random(n) < L.prevalence(theta, X)
|
||||
time = scale * (-np.log(rng.random(n)) / np.exp(Z @ beta)) ** (1 / shape)
|
||||
|
||||
c = np.where(prevalent, 1, 0)
|
||||
l = np.where(prevalent, 0.0, np.minimum(np.floor(time), 5.0))
|
||||
r = np.where(prevalent, 0.0, np.where(time < 5, np.floor(time) + 1, np.inf))
|
||||
return c, l, r, X, Z, theta, beta, scale, shape
|
||||
|
||||
|
||||
def test_survival_limits():
|
||||
Z = np.zeros((3, 1))
|
||||
s = L.weibull_survival([0.0, 2.0, np.inf], np.log(5.0), 0.0, np.zeros(1), Z)
|
||||
assert s[0] == 1.0 and s[2] == 0.0
|
||||
assert s[1] == pytest.approx(np.exp(-2 / 5))
|
||||
|
||||
|
||||
def test_fit_recovers_simulated_parameters():
|
||||
c, l, r, X, Z, theta, beta, scale, shape = simulate()
|
||||
fitted = L.fit(c, l, r, X, Z)
|
||||
assert fitted["converged"]
|
||||
np.testing.assert_allclose(fitted["theta"], theta, atol=0.3)
|
||||
np.testing.assert_allclose(fitted["beta"], beta, atol=0.3)
|
||||
assert np.exp(fitted["log_scale"]) == pytest.approx(scale, rel=0.3)
|
||||
assert np.exp(fitted["log_shape"]) == pytest.approx(shape, rel=0.3)
|
||||
|
||||
|
||||
def test_unknown_rows_only_add_information_about_the_mixture():
|
||||
"""A row with c = -999 and l = 0, r = inf says nothing: it contributes log(1) = 0."""
|
||||
c, l, r, X, Z, *_ = simulate(n=200)
|
||||
params = np.zeros(X.shape[1] + Z.shape[1] + 2)
|
||||
base = L.neg_loglik(params, c, l, r, X, Z)
|
||||
c2 = np.r_[c, L.UNKNOWN]
|
||||
l2, r2 = np.r_[l, 0.0], np.r_[r, np.inf]
|
||||
X2, Z2 = np.vstack([X, X[:1]]), np.vstack([Z, Z[:1]])
|
||||
assert L.neg_loglik(params, c2, l2, r2, X2, Z2) == pytest.approx(base, abs=1e-9)
|
||||
|
||||
|
||||
def test_cumulative_risk_starts_at_prevalence():
|
||||
c, l, r, X, Z, *_ = simulate(n=500)
|
||||
fitted = L.fit(c, l, r, X, Z)
|
||||
cr = L.cumulative_risk(fitted, X, Z, years=[0, 1, 5])
|
||||
np.testing.assert_allclose(cr[:, 0], L.prevalence(fitted["theta"], X))
|
||||
assert np.all(np.diff(cr, axis=1) >= 0)
|
||||
|
||||
|
||||
def test_fit_finds_a_rare_incidence():
|
||||
"""A rare outcome, like CIN3+ with HPV negative: the Weibull scale is thousands of years and only ~1 % has an
|
||||
incident case in 7 yearly visits. Pins down that the fit reaches the optimum near the truth and not the far worse
|
||||
one where a start at the median detection time used to leave it. Fails if the starting scale goes back to the
|
||||
detection times."""
|
||||
rng = np.random.default_rng(3)
|
||||
n = 20000
|
||||
group = rng.integers(0, 2, n)
|
||||
X = np.column_stack([np.ones(n), group])
|
||||
Z = group[:, None].astype(float)
|
||||
theta, beta, scale, shape = np.array([-5.0, 1.0]), np.array([1.4]), 2500.0, 1.08
|
||||
prevalent = rng.random(n) < L.prevalence(theta, X)
|
||||
time = scale * (rng.exponential(size=n) / np.exp(Z @ beta)) ** (1 / shape)
|
||||
c = np.where(prevalent, 1, 0)
|
||||
l = np.where(prevalent, 0.0, np.minimum(np.floor(time), 7.0))
|
||||
r = np.where(prevalent, 0.0, np.where(time < 7, np.floor(time) + 1, np.inf))
|
||||
|
||||
fitted = L.fit(c, l, r, X, Z)
|
||||
truth = L.neg_loglik(np.r_[theta, beta, np.log(scale), np.log(shape)], c, l, r, X, Z)
|
||||
|
||||
assert fitted["converged"] and fitted["neg_loglik"] <= truth + 1e-6
|
||||
np.testing.assert_allclose(fitted["beta"], beta, atol=0.4)
|
||||
assert np.all(np.isfinite(fitted["se"]))
|
||||
|
||||
|
||||
def test_the_ispline_basis_rises_from_0_to_1_and_has_knots_plus_order_minus_2_functions():
|
||||
"""Pins down PIMixture's basis: H0(0) = 0, flat at 1 from the last knot on, each function non-decreasing, and the
|
||||
count PIMixture's `Ispline` gives. Fails if the basis stops starting at 0 (the bug that gave events at t = 1 zero
|
||||
probability) or the count drifts from PIMixture's."""
|
||||
knots = (0.0, 2.0, 5.0)
|
||||
t = np.linspace(0, 8, 81)
|
||||
basis = L.ispline_basis(np.r_[t, np.inf], 3, knots)
|
||||
|
||||
assert basis.shape == (82, len(knots) + 3 - 2)
|
||||
assert (basis[0] == 0).all() and (basis[:-1][t >= 5] == 1).all() and (basis[-1] == 1).all()
|
||||
assert (np.diff(basis[:-1], axis=0) >= -1e-12).all()
|
||||
|
||||
|
||||
def test_the_ispline_mixture_recovers_a_weibull_cumulative_risk():
|
||||
"""Pins down that the weakly-parametric baseline fits data it wasn't generated from: the I-spline's cumulative
|
||||
risk at 1 to 5 years is close to the Weibull truth. Fails if the I-spline's start or parameterization breaks."""
|
||||
c, l, r, X, Z, theta, beta, scale, shape = simulate()
|
||||
baseline = L.ISpline(L.quantile_knots(l, r, 3), order=3)
|
||||
fitted = L.fit(c, l, r, X, Z, baseline)
|
||||
years = [1.0, 3.0, 5.0]
|
||||
truth = L.cumulative_risk({"theta": theta, "beta": beta, "log_scale": np.log(scale), "log_shape": np.log(shape)},
|
||||
X[:2], Z[:2], years)
|
||||
|
||||
assert fitted["converged"]
|
||||
np.testing.assert_allclose(L.cumulative_risk(fitted, X[:2], Z[:2], years), truth, atol=0.02)
|
||||
|
||||
|
||||
def test_a_frequency_weight_is_the_same_as_repeating_the_row():
|
||||
"""Pins down the weights: a row with weight 2 contributes as two identical rows, so collapsing duplicates
|
||||
doesn't change the fit. Fails if the weights stop multiplying each row's log-likelihood."""
|
||||
c, l, r, X, Z, *_ = simulate(n=300)
|
||||
params = np.r_[-3.0, 1.5, 0.7, np.log(8.0), np.log(1.3)]
|
||||
twice = L.neg_loglik(params, *(np.r_[a, a] for a in (c, l, r)), np.r_[X, X], np.r_[Z, Z])
|
||||
|
||||
assert L.neg_loglik(params, c, l, r, X, Z, w=np.full(len(c), 2.0)) == pytest.approx(twice)
|
||||
+126
-18
@@ -1,3 +1,4 @@
|
||||
import mlflow.pyfunc
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -32,6 +33,13 @@ def cacu_db(tmp_path, monkeypatch):
|
||||
engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tea_db(tmp_path, monkeypatch):
|
||||
engine = _wire(monkeypatch, tmp_path, "tea", "core.tea.base", "TeaModel")
|
||||
yield
|
||||
engine.cache_clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mlflow_tracking(tmp_path, monkeypatch):
|
||||
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
|
||||
@@ -44,35 +52,44 @@ def mlflow_tracking(tmp_path, monkeypatch):
|
||||
yield
|
||||
|
||||
|
||||
class Echo(mlflow.pyfunc.PythonModel):
|
||||
"""A model whose class lives in a module, as a PROD run requires: it returns its input."""
|
||||
|
||||
def predict(self, context, model_input, params=None):
|
||||
return model_input
|
||||
|
||||
|
||||
def trained_run(domain: str, scenario: str, armado_id: int | None, metrics: dict, *, routines=None, model: bool = True):
|
||||
"""A finished PROD run as training leaves it: each routine's record (all of them unless `routines` names some)
|
||||
and, with `model`, a saved model."""
|
||||
from core.governance.enums import Environment
|
||||
from models.io.tracking import ROUTINE_KINDS, TrainingRun
|
||||
|
||||
run = TrainingRun(domain=domain, scenario=scenario, environment=Environment.PROD, cohorte_armado_id=armado_id)
|
||||
for kind in ROUTINE_KINDS if routines is None else routines:
|
||||
run.log_routine(kind, {"method": "prueba", "n": 8})
|
||||
if model:
|
||||
run.log_model(Echo())
|
||||
return run.finish(metrics=metrics)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def production_ready(governance_db, cacu_db, mlflow_tracking):
|
||||
"""Factory: registers a PROD version that passes every promotion check,
|
||||
returns (domain, scenario, version)."""
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import registry
|
||||
"""Factory: registers a PROD version whose run recorded every routine and its model, with the three reports,
|
||||
so it passes every promotion check; returns (domain, scenario, version)."""
|
||||
from models.io.registry import registry
|
||||
|
||||
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
|
||||
version = registry.register(
|
||||
domain=domain, scenario=scenario, environment=Environment.PROD,
|
||||
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
|
||||
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
||||
run = trained_run(domain, scenario, armado(f"huella-{tag}"), metrics or {"auc": 0.8})
|
||||
version = registry.register_run(
|
||||
run, technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
|
||||
interpretability_report_uri="docs/interpretabilidad.html",
|
||||
)
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
|
||||
return domain, scenario, version
|
||||
|
||||
return make
|
||||
|
||||
|
||||
def tiny_onnx() -> bytes:
|
||||
import onnx.helper
|
||||
|
||||
node = onnx.helper.make_node("Identity", ["x"], ["y"])
|
||||
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
|
||||
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
|
||||
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
|
||||
|
||||
|
||||
def armado(huella: str) -> int:
|
||||
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
|
||||
from datetime import date, datetime, timezone
|
||||
@@ -91,3 +108,94 @@ def armado(huella: str) -> int:
|
||||
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
|
||||
session.commit()
|
||||
return fila.armado_id
|
||||
|
||||
|
||||
LOAD_WITHOUT_REPOSITORY = """
|
||||
import sys
|
||||
import pandas as pd
|
||||
sys.modules["models"] = None # importing anything from this repository now fails
|
||||
sys.modules["hamilton"] = None # nor Hamilton: the artifact runs where the dataflow isn't installed
|
||||
import mlflow.pyfunc
|
||||
model = mlflow.pyfunc.load_model(sys.argv[1])
|
||||
output = pd.DataFrame(model.predict(pd.read_parquet(sys.argv[2])))
|
||||
output.columns = [str(column) for column in output.columns]
|
||||
output.to_parquet(sys.argv[3])
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def predict_without_repository(tmp_path):
|
||||
"""Runs a registered version in a separate Python where neither `models` nor `hamilton` can be imported, on a
|
||||
frame, and returns its output, columns named `"0"`, `"1"`…: what an environment with MLflow and the model's
|
||||
libraries would get."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import pandas as pd
|
||||
|
||||
def run(model_uri: str, frame: pd.DataFrame) -> pd.DataFrame:
|
||||
source, output = tmp_path / "input.parquet", tmp_path / "output.parquet"
|
||||
frame.to_parquet(source)
|
||||
env = {**os.environ, "MLFLOW_DISABLE_AGENT_HINT": "1", "PYTHONPATH": ""}
|
||||
subprocess.run([sys.executable, "-c", LOAD_WITHOUT_REPOSITORY, model_uri, str(source), str(output)],
|
||||
check=True, env=env, cwd=tmp_path, capture_output=True)
|
||||
return pd.read_parquet(output)
|
||||
|
||||
return run
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit_stand_ins():
|
||||
"""Factory: stand-ins of a domain's `cohort_repository` and `timeline_repository` holding one kit build made of a
|
||||
long frame's members and events, with dates as text as the database returns them. The timeline records each read's
|
||||
patients and cut-offs."""
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from persistance.edges.gold import CohortBuild, CohortMember
|
||||
|
||||
def make(frame, build_id, cutoff, url="cacu/cohorte_vigilancia"):
|
||||
index_dates = frame.groupby("pac_id")["fecha_indice"].first()
|
||||
build = CohortBuild(build_id, url, "1", "huella", "marco", cutoff, None, len(index_dates),
|
||||
datetime(2027, 1, 1, tzinfo=timezone.utc))
|
||||
cohorts = SimpleNamespace(
|
||||
latest_build=lambda asked: build_id if asked == url else None,
|
||||
build=lambda asked: build if asked == build_id else None,
|
||||
members=lambda asked: [CohortMember(int(p), d, "t", str(p)) for p, d in index_dates.items()])
|
||||
rows = [{key: value.isoformat() if hasattr(value, "isoformat") else value
|
||||
for key, value in row.items() if key != "fecha_indice"} for row in frame.to_dict("records")]
|
||||
|
||||
class Timeline:
|
||||
reads = []
|
||||
|
||||
def read(self, *, patients=None, until=None, known_until=None):
|
||||
self.reads.append({"patients": patients, "until": until, "known_until": known_until})
|
||||
return [row for row in rows if patients is None or row["pac_id"] in set(patients)]
|
||||
|
||||
return cohorts, Timeline()
|
||||
|
||||
return make
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mlflow_store_leaks():
|
||||
"""Factory: which of these texts and integers appear, as text or as 8-byte integers, in any file under `root`
|
||||
outside `skip` (the inputs themselves). Used with values only the training data holds, to show they never reached
|
||||
MLflow's database or artifacts."""
|
||||
from pathlib import Path
|
||||
|
||||
def scan(root, texts=(), integers=(), skip=()):
|
||||
needles = {str(t): str(t).encode() for t in texts}
|
||||
for number in integers:
|
||||
needles[f"{number} (text)"] = str(number).encode()
|
||||
needles[f"{number} (int64)"] = int(number).to_bytes(8, "little", signed=True)
|
||||
found = set()
|
||||
for path in Path(root).rglob("*"):
|
||||
if not path.is_file() or any(part in skip for part in path.relative_to(root).parts):
|
||||
continue
|
||||
content = path.read_bytes()
|
||||
found |= {name for name, needle in needles.items() if needle in content}
|
||||
return sorted(found)
|
||||
|
||||
return scan
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""What this module covers: `models.io.adapters` and the generic driver of `models.dags.training`: the loaders feed the
|
||||
graph from any cohort source, the saver logs, registers and describes a version from `fitted_model` and `metrics`, the
|
||||
registered model runs without this repository, metrics that aren't numbers fail the run and register nothing, and a
|
||||
failing node's inputs never reach the log.
|
||||
|
||||
Fixtures: `scenario`, a throwaway scenario package (`model.py`, `model.toml`) under `tmp_path`, whose model gives every
|
||||
member the same risk at two horizons; `cohort_file`, kit build 5's file with members 987654301 to 987654303;
|
||||
`mlflow_tracking` and `predict_without_repository` (conftest).
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
import sys
|
||||
import textwrap
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from hamilton.io.materialization import from_
|
||||
from mlflow.entities import RunStatus
|
||||
|
||||
from models.dags import training
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from models.io.registry import registry
|
||||
from models.io.storage import CohortFile
|
||||
|
||||
MEMBERS = (987654301, 987654302, 987654303)
|
||||
|
||||
SCENARIO_TOML = """
|
||||
domain = "cacu"
|
||||
scenario = "fake_scenario"
|
||||
cohort = "cacu/cohorte_vigilancia"
|
||||
outcome = "fake"
|
||||
modules = ["fake_scenario_pkg.model"]
|
||||
requirements = ["scikit-learn", "numpy"]
|
||||
description = "A scenario for tests."
|
||||
|
||||
[config]
|
||||
risk = 0.25
|
||||
horizons_years = [0.0, 2.0]
|
||||
"""
|
||||
|
||||
SCENARIO_MODEL = '''
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from sklearn.base import BaseEstimator
|
||||
|
||||
|
||||
def member_count(cohort: pd.DataFrame) -> int:
|
||||
return int(cohort["pac_id"].nunique())
|
||||
|
||||
|
||||
def metrics(member_count: int, risk: float) -> dict:
|
||||
return {"n_members": member_count, "risk": risk}
|
||||
|
||||
|
||||
class ConstantRisk(BaseEstimator):
|
||||
def __init__(self, risk=0.25, horizons_years=(0.0, 2.0)):
|
||||
self.risk, self.horizons_years = risk, horizons_years
|
||||
|
||||
def fit(self, X, y=None):
|
||||
return self
|
||||
|
||||
def predict_proba(self, X):
|
||||
return np.full((X["pac_id"].nunique(), len(self.horizons_years)), float(self.risk))
|
||||
|
||||
|
||||
def fitted_model(risk: float, horizons_years: list) -> ConstantRisk:
|
||||
return ConstantRisk(risk, horizons_years)
|
||||
'''
|
||||
|
||||
|
||||
def _write_scenario(root, model_source=SCENARIO_MODEL):
|
||||
package = root / "fake_scenario_pkg"
|
||||
package.mkdir(exist_ok=True)
|
||||
(package / "__init__.py").write_text("")
|
||||
(package / "model.py").write_text(textwrap.dedent(model_source))
|
||||
(package / "model.toml").write_text(SCENARIO_TOML)
|
||||
for name in ("fake_scenario_pkg.model", "fake_scenario_pkg"):
|
||||
sys.modules.pop(name, None)
|
||||
importlib.invalidate_caches()
|
||||
return training.Scenario.from_toml(package / "model.toml")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def scenario(tmp_path, monkeypatch):
|
||||
"""The throwaway scenario, its module importable as `fake_scenario_pkg.model`."""
|
||||
monkeypatch.syspath_prepend(str(tmp_path))
|
||||
return _write_scenario(tmp_path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(tmp_path):
|
||||
rows = [{"pac_id": pac_id, "fecha_indice": date(2025, 1, day), "fecha": date(2025, 1, day),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
|
||||
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "t",
|
||||
"fuente_id": str(pac_id)} for day, pac_id in enumerate(MEMBERS, start=1)]
|
||||
table = pa.Table.from_pandas(pd.DataFrame(rows, columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA,
|
||||
preserve_index=False)
|
||||
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": "2026-12-31", "armado_id": "5"}
|
||||
path = tmp_path / "5.parquet"
|
||||
pq.write_table(table.replace_schema_metadata(lineage), path)
|
||||
return path
|
||||
|
||||
|
||||
def test_the_loaders_feed_the_graph_from_a_source(cohort_file):
|
||||
"""Pins down: `cohort_source` and `cohort_source_lineage` give the nodes the build's frame and its lineage, from the
|
||||
source they're given. Fails if a loader's name changes or it stops asking its source."""
|
||||
def members(cohort: pd.DataFrame) -> int:
|
||||
return len(cohort)
|
||||
|
||||
def build_number(cohort_lineage: dict) -> str:
|
||||
return cohort_lineage["armado_id"]
|
||||
|
||||
module = ad_hoc_utils.create_temporary_module(members, build_number)
|
||||
dr = driver.Builder().with_modules(module).with_materializers(
|
||||
from_.cohort_source(target="cohort", source=CohortFile(cohort_file)),
|
||||
from_.cohort_source_lineage(target="cohort_lineage", source=CohortFile(cohort_file))).build()
|
||||
|
||||
assert dr.execute(["members", "build_number"]) == {"members": 3, "build_number": "5"}
|
||||
|
||||
|
||||
def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scenario, cohort_file, mlflow_tracking):
|
||||
"""Pins down: the saver logs the fitted model, records the metrics, the config and the `models` version, registers
|
||||
the version with its build and describes it. Fails if the saver stops being reached from `registered_model`, or
|
||||
drops any of those."""
|
||||
version = training.train(scenario, CohortFile(cohort_file))
|
||||
|
||||
stored = registry.get("cacu", "fake_scenario", version)
|
||||
run = registry.client.get_run(stored.run_id)
|
||||
assert stored.description == "A scenario for tests." and stored.tags["kit.armado_id"] == "5"
|
||||
assert run.data.metrics == {"n_members": 3.0, "risk": 0.25}
|
||||
assert run.data.params["risk"] == "0.25" and "models.version" in run.data.params
|
||||
assert run.info.status == RunStatus.to_string(RunStatus.FINISHED)
|
||||
assert training.find_trained(scenario, CohortFile(cohort_file)) == version
|
||||
|
||||
|
||||
def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking,
|
||||
predict_without_repository):
|
||||
"""Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the
|
||||
scenario still loads the version and gives a probability per member and horizon. Fails if the model's classes go
|
||||
back to being pickled by reference."""
|
||||
version = training.train(scenario, CohortFile(cohort_file))
|
||||
|
||||
output = predict_without_repository(registry.resolve("cacu", "fake_scenario", version).model_uri,
|
||||
pd.read_parquet(cohort_file))
|
||||
|
||||
assert output.shape == (3, 2) and (output == 0.25).all().all()
|
||||
|
||||
|
||||
def test_metrics_that_are_not_numbers_fail_the_run_and_register_nothing(tmp_path, monkeypatch, cohort_file,
|
||||
mlflow_tracking):
|
||||
"""Pins down: a `metrics` value that isn't a number (a frame put there by mistake) stops the saver before MLflow
|
||||
receives it, marks the run failed and registers no version. Fails if the check goes, or a failed graph leaves a
|
||||
run open or a version behind."""
|
||||
monkeypatch.syspath_prepend(str(tmp_path))
|
||||
leaking = SCENARIO_MODEL.replace('return {"n_members": member_count, "risk": risk}',
|
||||
'return {"n_members": member_count, "rows": pd.DataFrame({"pac_id": [1]})}')
|
||||
scenario = _write_scenario(tmp_path, leaking)
|
||||
|
||||
with pytest.raises(TypeError, match="rows"):
|
||||
training.train(scenario, CohortFile(cohort_file))
|
||||
|
||||
runs = registry.client.search_runs([e.experiment_id for e in registry.client.search_experiments()])
|
||||
assert [r.info.status for r in runs] == [RunStatus.to_string(RunStatus.FAILED)]
|
||||
assert not registry.client.search_model_versions("name='cacu-fake_scenario'")
|
||||
|
||||
|
||||
def test_a_failing_node_does_not_log_its_inputs(tmp_path, monkeypatch, cohort_file, mlflow_tracking, caplog):
|
||||
"""Pins down: when a node fails during training, the exception reaches the caller but Hamilton's log of the node's
|
||||
inputs, which would show the first rows of the cohort, isn't written. Fails if the driver stops silencing
|
||||
`hamilton.execution.graph_functions` or Hamilton moves that message to another logger."""
|
||||
monkeypatch.syspath_prepend(str(tmp_path))
|
||||
scenario = _write_scenario(tmp_path, SCENARIO_MODEL.replace('return int(cohort["pac_id"].nunique())',
|
||||
'return int(cohort["missing"].sum())'))
|
||||
|
||||
with caplog.at_level(logging.DEBUG), pytest.raises(KeyError):
|
||||
training.train(scenario, CohortFile(cohort_file))
|
||||
|
||||
assert not any(str(pac_id) in caplog.text for pac_id in MEMBERS)
|
||||
|
||||
|
||||
def test_the_registered_model_needs_only_its_listed_requirements(scenario, cohort_file, mlflow_tracking):
|
||||
"""Pins down: the version's `requirements.txt` holds the scenario's `requirements`, each pinned to the installed
|
||||
version, and no path or editable install of this repository. Fails if MLflow goes back to inferring them from the
|
||||
environment, which copies the whole lock with `-e ../Persistance` and the like."""
|
||||
import mlflow
|
||||
from importlib.metadata import version as installed
|
||||
|
||||
run_id = registry.get("cacu", "fake_scenario", training.train(scenario, CohortFile(cohort_file))).run_id
|
||||
lines = Path(mlflow.artifacts.download_artifacts(f"runs:/{run_id}/model/requirements.txt")).read_text().split()
|
||||
|
||||
assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines
|
||||
assert not [line for line in lines if line.startswith("-e") or "/" in line]
|
||||
@@ -0,0 +1,95 @@
|
||||
"""What this module covers: listing and describing a cohort's builds (`models.io.storage.list_builds`,
|
||||
`describe_build`) and the `models cohorts list` and `cohorts show` commands.
|
||||
|
||||
Fixtures: `root`, a cohorts folder with dbt builds 1 and 2 and kit build 7's file; `kit`, a stand-in of the cohort
|
||||
repository with kit builds 7 (exported) and 8 (not exported).
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.__main__ import main
|
||||
from models.io.storage import cohort_path, dbt_build_path, describe_build, list_builds
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
ATTRITION = [{"step": "all_patients", "n": 3, "excluded": None}, {"step": "indexed", "n": 2, "excluded": 1}]
|
||||
|
||||
|
||||
def _file(path, **metadata):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
pq.write_table(pa.table({"pac_id": [1]}).replace_schema_metadata({k: str(v) for k, v in metadata.items()}), path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def root(tmp_path):
|
||||
for number in (1, 2):
|
||||
_file(dbt_build_path(tmp_path, URL, number), producer="dbt", build=number, datos_as_of="2026-12-31",
|
||||
n_members=2, built_at=f"2026-11-0{number}T00:00:00+00:00", rules=json.dumps(["prior_event"]),
|
||||
parametros=json.dumps({"cutoff": "2026-12-31"}), attrition=json.dumps(ATTRITION))
|
||||
_file(cohort_path(tmp_path, URL, 7), producer="kit", armado_id=7, datos_as_of="2026-12-31", n_members=2)
|
||||
return tmp_path
|
||||
|
||||
|
||||
def _kit_build(armado_id):
|
||||
return SimpleNamespace(armado_id=armado_id, url=URL, version="0.2.0", datos_as_of=date(2026, 12, 31), n_miembros=2,
|
||||
huella="h", armado_en=datetime(2026, 10, armado_id, tzinfo=timezone.utc))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit():
|
||||
builds = {8: _kit_build(8), 7: _kit_build(7)}
|
||||
return SimpleNamespace(builds=lambda url: list(builds.values()) if url == URL else [], build=builds.get)
|
||||
|
||||
|
||||
def test_both_sources_are_listed_newest_first_with_their_files(root, kit):
|
||||
"""Pins down: dbt's builds come from their files, newest first, and the kit's from the repository, each saying
|
||||
whether its file exists. Fails if a source is dropped, the order is by name, or an unexported build shows a file."""
|
||||
rows = list_builds(root, URL, kit)
|
||||
|
||||
assert [(r["source"], r["build"]) for r in rows] == [("dbt", 2), ("dbt", 1), ("kit", 8), ("kit", 7)]
|
||||
assert rows[2]["file"] is None and rows[3]["file"].endswith("7.parquet")
|
||||
assert rows[0]["created"] == "2026-11-02T00:00:00+00:00"
|
||||
|
||||
|
||||
def test_without_the_repository_only_files_are_read(root):
|
||||
"""Pins down: listing dbt's builds needs no database. Fails if `list_builds` reaches for the kit's builds anyway."""
|
||||
assert [r["source"] for r in list_builds(root, URL)] == ["dbt", "dbt"]
|
||||
|
||||
|
||||
def test_a_dbt_build_is_described_with_its_lineage_decoded(root):
|
||||
"""Pins down: `describe_build` gives the file, its hash, and the parameters, rules and attrition as JSON values,
|
||||
not strings. Fails if the hash is missing or the lineage stays encoded."""
|
||||
described = describe_build(root, URL, "dbt", 2)
|
||||
|
||||
assert len(described["file_sha256"]) == 64
|
||||
assert described["lineage"]["attrition"] == ATTRITION and described["lineage"]["rules"] == ["prior_event"]
|
||||
assert described["lineage"]["parametros"] == {"cutoff": "2026-12-31"}
|
||||
|
||||
|
||||
def test_an_unexported_kit_build_is_described_from_the_database(root, kit):
|
||||
"""Pins down: a kit build without a file still has its lineage, from the repository; an unknown build is a
|
||||
`LookupError`. Fails if an unexported build is reported as missing, or a missing one as empty."""
|
||||
described = describe_build(root, URL, "kit", 8, kit)
|
||||
|
||||
assert described["file"] is None and described["lineage"]["n_members"] == "2"
|
||||
with pytest.raises(LookupError):
|
||||
describe_build(root, URL, "kit", 9, kit)
|
||||
with pytest.raises(LookupError):
|
||||
describe_build(root, URL, "dbt", 9)
|
||||
|
||||
|
||||
def test_the_commands_print_the_dbt_builds(root, monkeypatch, capsys):
|
||||
"""Pins down: `cohorts list --source dbt` and `cohorts show` work from the files alone. Fails if either opens the
|
||||
database for dbt's builds, or `show` prints something other than JSON."""
|
||||
monkeypatch.setenv("COHORTS_DIR", str(root))
|
||||
|
||||
assert main(["cohorts", "list", "cacu", "cohorte_vigilancia", "--source", "dbt"]) == 0
|
||||
listed = capsys.readouterr().out
|
||||
assert "dbt/2.parquet" in listed and "dbt/1.parquet" in listed
|
||||
assert main(["cohorts", "show", "cacu", "cohorte_vigilancia", "--build", "1"]) == 0
|
||||
assert json.loads(capsys.readouterr().out)["build"] == 1
|
||||
@@ -0,0 +1,64 @@
|
||||
"""What this module covers: the `RiskEstimator` contract in `models.io.contracts` and the two records it
|
||||
returns, `Risk` and `Provenance`.
|
||||
|
||||
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
|
||||
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
from models.io.contracts import Provenance, Risk, RiskEstimator
|
||||
|
||||
|
||||
class ConstantEstimator:
|
||||
"""Meets the contract with a fixed probability for every member and horizon."""
|
||||
|
||||
cohort_url = "cacu/cohorte_vigilancia"
|
||||
outcome = "cin2_mas"
|
||||
|
||||
def provenance(self) -> Provenance:
|
||||
return Provenance(modelo_nombre="constant", modelo_version="1", mlflow_run_id="none", modelo_sha="sha")
|
||||
|
||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]:
|
||||
i_pac, i_fecha = columns.index("pac_id"), columns.index("fecha_indice")
|
||||
return [Risk(row[i_pac], row[i_fecha], h, 0.1) for row in rows for h in (0.0, 1.0)]
|
||||
|
||||
|
||||
class Incomplete:
|
||||
"""Has everything but `provenance`."""
|
||||
|
||||
cohort_url = "cacu/cohorte_vigilancia"
|
||||
outcome = "cin2_mas"
|
||||
|
||||
def estimate(self, columns, rows):
|
||||
return []
|
||||
|
||||
|
||||
def test_a_class_with_the_four_members_meets_the_contract():
|
||||
"""Pins down: `RiskEstimator` is checked at run time by its members (`cohort_url`, `outcome`,
|
||||
`provenance`, `estimate`), not by inheritance; missing one fails the check.
|
||||
|
||||
Fails if the protocol stops being `runtime_checkable` or a member is renamed.
|
||||
"""
|
||||
assert isinstance(ConstantEstimator(), RiskEstimator)
|
||||
assert not isinstance(Incomplete(), RiskEstimator)
|
||||
|
||||
|
||||
def test_provenance_has_the_four_keys_a_batch_stores():
|
||||
"""Pins down: `Provenance.as_dict()` has exactly the four keys of the risk batch's provenance columns.
|
||||
|
||||
Fails if a field is renamed or added: the batch columns wouldn't match.
|
||||
"""
|
||||
assert set(ConstantEstimator().provenance().as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id",
|
||||
"modelo_sha"}
|
||||
|
||||
|
||||
def test_a_risk_keeps_the_column_names_and_its_interval_is_optional():
|
||||
"""Pins down: `Risk` fields are named after the columns they're saved to, in that order, and the
|
||||
interval defaults to `None`.
|
||||
|
||||
Fails if a field is renamed or reordered, or the interval becomes required.
|
||||
"""
|
||||
risk = Risk(1, date(2025, 1, 1), 0.0, 0.25)
|
||||
|
||||
assert Risk._fields == ("pac_id", "fecha_indice", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto")
|
||||
assert (risk.ic_bajo, risk.ic_alto) == (None, None)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Each domain's extraction ranker in the model registry
|
||||
(`models.io.extraction_ranker`): every batch it learns from is a new DEV
|
||||
version continuing the latest, with its five routine records and its saved
|
||||
model; extraction takes the version in production, else the latest, and
|
||||
`EXTRACTION_RANKER` can restrict or turn that off.
|
||||
|
||||
Fixtures: `mlflow_tracking` (a SQLite MLflow per test) and `_fresh_cache`
|
||||
(an empty ranker cache and no `EXTRACTION_RANKER`). Batches are built
|
||||
inline by `_batch` from candidates with the features an extractor gives
|
||||
them; no document is read.
|
||||
"""
|
||||
import json
|
||||
|
||||
import mlflow.artifacts
|
||||
import pytest
|
||||
from extraction.document import BBox
|
||||
from extraction.nlp import FieldKind, FieldSpec
|
||||
from extraction.nlp.fields import Evidence, ExtractedValue
|
||||
from extraction.nlp.ranking import examples_for
|
||||
|
||||
from models.io import extraction_ranker
|
||||
from models.io.extraction_ranker import Batch, current, learn
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import ROUTINES_PATH
|
||||
|
||||
GRADO = FieldSpec("bx_cin_grado", FieldKind.CHOICE, choices={"NIC I": "LIEBG", "NIC II": "LIEAG"})
|
||||
|
||||
|
||||
def _batch(right: str = "LIEBG") -> Batch:
|
||||
evidence = Evidence("reporte.pdf", 1, "Diagnóstico: NIC I", BBox(0, 0, 1, 0.1).as_list())
|
||||
candidates = [
|
||||
ExtractedValue("LIEBG", 0.5, "etiqueta", "NIC I", evidence, {"assertion": "afirmado", "section": "resultado"}),
|
||||
ExtractedValue("LIEAG", 0.6, "texto_libre", "NIC II", evidence, {"assertion": "afirmado", "section": "general"}),
|
||||
]
|
||||
examples = examples_for([GRADO], {"bx_cin_grado": candidates}, {"bx_cin_grado": right})
|
||||
return Batch(examples, "revision", documents=1, records=1, unreachable={})
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_cache(monkeypatch):
|
||||
"""No ranker cached from another test, and the default selection."""
|
||||
monkeypatch.setattr(extraction_ranker, "_cache", {})
|
||||
monkeypatch.delenv(extraction_ranker.SELECTION_ENV, raising=False)
|
||||
|
||||
|
||||
def test_each_batch_is_a_new_dev_version_with_its_routines(mlflow_tracking):
|
||||
"""Fails if learning stops registering a DEV version, its run loses one
|
||||
of the five routine records or its saved model, which ML-01a and ML-01b
|
||||
require to promote it."""
|
||||
version = learn("cacu", _batch())
|
||||
described = registry.get("cacu", extraction_ranker.SCENARIO, version)
|
||||
assert described.tags["environment"] == "DEV"
|
||||
checks = {c.code: c.passed for c in registry.checks("cacu", extraction_ranker.SCENARIO, version)}
|
||||
assert checks["ML-01a"] and checks["ML-01b"]
|
||||
|
||||
|
||||
def test_routine_records_hold_counts_never_document_text(mlflow_tracking):
|
||||
"""What a ranker stores can be shared: weights and counts. Fails if a
|
||||
routine record or the ranker's state carries a raw reading or the line
|
||||
it came from."""
|
||||
version = learn("cacu", _batch())
|
||||
run_id = registry.get("cacu", extraction_ranker.SCENARIO, version).run_id
|
||||
stored = json.dumps(mlflow.artifacts.load_dict(f"runs:/{run_id}/{extraction_ranker.RANKER_PATH}"))
|
||||
for kind in ("MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"):
|
||||
stored += mlflow.artifacts.load_text(f"runs:/{run_id}/{ROUTINES_PATH}/{kind}.json")
|
||||
assert "NIC I" not in stored and "Diagnóstico" not in stored and "reporte.pdf" not in stored
|
||||
|
||||
|
||||
def test_learning_continues_from_the_latest_version(mlflow_tracking):
|
||||
"""Fails if a new batch starts from scratch instead of the latest
|
||||
version, which would forget every earlier correction."""
|
||||
learn("cacu", _batch())
|
||||
second = learn("cacu", _batch())
|
||||
ranker = current("cacu")
|
||||
assert ranker.version == f"{extraction_ranker.SCENARIO}:{second}"
|
||||
assert ranker.examples == 2 * len(_batch().examples)
|
||||
|
||||
|
||||
def test_extraction_takes_production_first_and_can_be_turned_off(mlflow_tracking, monkeypatch):
|
||||
"""With a version in production that one is used even when newer DEV
|
||||
versions exist; `produccion` refuses DEV-only registries and `ninguno`
|
||||
turns the ranker off. Fails if the selection order changes."""
|
||||
assert current("cacu") is None
|
||||
first = learn("cacu", _batch())
|
||||
learn("cacu", _batch())
|
||||
registry.client.set_registered_model_alias("cacu-extraccion", "produccion", first)
|
||||
assert current("cacu").version == f"{extraction_ranker.SCENARIO}:{first}"
|
||||
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "ninguno")
|
||||
assert current("cacu") is None
|
||||
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "produccion")
|
||||
assert current("tea") is None
|
||||
|
||||
|
||||
def test_an_empty_batch_registers_nothing(mlflow_tracking):
|
||||
"""Fails if a review without usable examples creates a version."""
|
||||
assert learn("cacu", Batch([], "revision", 0, 0, {})) is None
|
||||
assert registry.versions("cacu", extraction_ranker.SCENARIO) == []
|
||||
@@ -0,0 +1,87 @@
|
||||
"""What this module covers: the value checks of the cohort and estimate files (`COHORT_FRAME`, `ESTIMATE_FRAME`,
|
||||
`check_frame` in `models.io.contracts`), and that reading a cohort file and building one apply them.
|
||||
|
||||
Fixtures: none; `_events` makes a valid two-member frame and each test breaks one rule.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, ESTIMATE_FRAME, CohortFileError, EstimateError,
|
||||
check_frame)
|
||||
from models.io.storage import read_cohort
|
||||
from models.steps.cohort_file import cohort_table
|
||||
|
||||
|
||||
def _events(**changes):
|
||||
frame = pd.DataFrame({"pac_id": [1, 1, 2], "fecha_indice": [date(2025, 1, 1)] * 2 + [date(2025, 2, 1)],
|
||||
"fecha": [date(2025, 1, 1), date(2025, 3, 1), date(2025, 2, 1)],
|
||||
"conocida_en": [datetime(2025, 4, 1, tzinfo=timezone.utc)] * 3,
|
||||
"clase": ["procedimiento", "medicion", "procedimiento"],
|
||||
"tipo": ["citologia", "bethesda", "citologia"], "codigo": ["c", "b", "c"],
|
||||
"valor_codigo": [None, "NORMAL", None], "valor_numerico": [None, None, None],
|
||||
"fuente_tabla": ["citologiacervical"] * 3, "fuente_id": ["a", "a", "b"]})
|
||||
for column, (row, value) in changes.items():
|
||||
frame.loc[row, column] = value
|
||||
return frame
|
||||
|
||||
|
||||
def test_a_valid_build_passes():
|
||||
"""Pins down: a well-formed frame comes back unchanged. Fails if a check rejects valid data, which would stop every
|
||||
export and training."""
|
||||
assert check_frame(COHORT_FRAME, _events(), CohortFileError, "test").equals(_events())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("changes, check", [
|
||||
({"fecha_indice": (1, date(2025, 1, 5))}, "more than one index date"),
|
||||
({"pac_id": (2, 0)}, "greater_than"),
|
||||
({"fecha": (0, None)}, "not_nullable"),
|
||||
({"tipo": (1, "")}, "str_length"),
|
||||
])
|
||||
def test_a_broken_build_names_what_failed(changes, check):
|
||||
"""Pins down: two index dates for a member, a non-positive id, a missing date or an empty type are refused, and
|
||||
the error names the check. Fails if a broken file reaches a model, where it would train on wrong rows."""
|
||||
with pytest.raises(CohortFileError, match=check):
|
||||
check_frame(COHORT_FRAME, _events(**changes), CohortFileError, "test")
|
||||
|
||||
|
||||
def test_reading_and_building_a_file_apply_the_checks(tmp_path):
|
||||
"""Pins down: `read_cohort` refuses a file whose rows break `COHORT_FRAME`, and `cohort_table` refuses to build
|
||||
one. Fails if either path skips the check."""
|
||||
broken = _events(fecha_indice=(1, date(2025, 1, 5)))
|
||||
path = tmp_path / "1.parquet"
|
||||
pq.write_table(pa.Table.from_pandas(broken, schema=COHORT_SCHEMA, preserve_index=False), path)
|
||||
|
||||
with pytest.raises(CohortFileError):
|
||||
read_cohort(path)
|
||||
with pytest.raises(CohortFileError):
|
||||
cohort_table(broken, {"build": 1})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("estimate", [
|
||||
pd.DataFrame({"pac_id": [1, 1], "fecha_indice": [date(2025, 1, 1)] * 2, "horizonte_anios": [1.0, 1.0],
|
||||
"probabilidad": [0.1, 0.2]}),
|
||||
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "horizonte_anios": [1.0], "probabilidad": [1.2]}),
|
||||
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "horizonte_anios": [-1.0], "probabilidad": [0.1]}),
|
||||
pd.DataFrame({"pac_id": [1], "fecha_indice": [date(2025, 1, 1)], "horizonte_anios": [1.0], "probabilidad": [0.1],
|
||||
"extra": [1]}),
|
||||
pd.DataFrame({"fecha_indice": [date(2025, 1, 1)], "pac_id": [1], "horizonte_anios": [1.0], "probabilidad": [0.1]}),
|
||||
])
|
||||
def test_an_estimate_is_one_probability_per_member_and_horizon_in_its_columns(estimate):
|
||||
"""Pins down: a member twice at one horizon, a probability outside 0..1, a negative horizon, an extra column or
|
||||
another column order are refused. Fails if a malformed output can be written or stored as risks."""
|
||||
with pytest.raises(EstimateError):
|
||||
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "test")
|
||||
|
||||
|
||||
def test_an_estimate_may_hold_several_horizons_per_member():
|
||||
"""Pins down: the same member at the prevalence and at later horizons is a valid estimate. Fails if the check goes
|
||||
back to one row per member, which would refuse a prevalence–incidence model's output."""
|
||||
estimate = pd.DataFrame({"pac_id": [1, 1, 1], "fecha_indice": [date(2025, 1, 1)] * 3,
|
||||
"horizonte_anios": [0.0, 1.0, 5.0], "probabilidad": [0.01, 0.02, 0.05]})
|
||||
|
||||
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "test")
|
||||
@@ -0,0 +1,65 @@
|
||||
"""What this module covers: `models.io.lineage`, the vocabulary files, runs and versions record their origin with, and
|
||||
the rule that decides an output is already done; and the hashes of files and tables in `models.io.storage`.
|
||||
|
||||
Fixtures: none; each test builds its own small table or file.
|
||||
"""
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
from models.io.lineage import matches, registered_name
|
||||
from models.io.storage import cohort_reference, file_sha256, require_match, table_sha256
|
||||
|
||||
|
||||
def test_a_table_hashes_by_its_rows_not_its_metadata():
|
||||
"""Pins down: the same rows hash the same whatever metadata the table carries, and another row changes the hash.
|
||||
Fails if metadata such as `built_at` enters the hash, so every rebuild would look new."""
|
||||
table = pa.table({"pac_id": [1, 2]})
|
||||
|
||||
assert table_sha256(table) == table_sha256(table.replace_schema_metadata({"built_at": "now"}))
|
||||
assert table_sha256(table) != table_sha256(pa.table({"pac_id": [1, 2, 3]}))
|
||||
|
||||
|
||||
def test_files_hash_in_order(tmp_path):
|
||||
"""Pins down: several files hash as their bytes in the order given, so a model's code hash covers each file. Fails
|
||||
if a file is skipped or the order stops mattering."""
|
||||
a, b = tmp_path / "a", tmp_path / "b"
|
||||
a.write_bytes(b"one")
|
||||
b.write_bytes(b"two")
|
||||
|
||||
assert file_sha256(a, b) != file_sha256(b, a) != file_sha256(a)
|
||||
|
||||
|
||||
def test_an_output_is_done_when_its_lineage_has_every_expected_value():
|
||||
"""Pins down: recorded lineage matches when every expected key has its value, compared as text since files and
|
||||
MLflow store text; extra keys don't matter. Fails if a missing key counts as a match or numbers stop matching text."""
|
||||
recorded = {"armado_id": "7", "n_members": "2", "built_at": "now"}
|
||||
|
||||
assert matches(recorded, {"armado_id": 7, "n_members": 2})
|
||||
assert not matches(recorded, {"armado_id": 7, "content_sha256": "x"})
|
||||
|
||||
|
||||
def test_a_mismatch_is_refused_with_both_sides():
|
||||
"""Pins down: `require_match` names what was expected and what was found. Fails if a mismatch passes silently."""
|
||||
with pytest.raises(ValueError, match="doesn't belong.*armado_id"):
|
||||
require_match({"armado_id": "1"}, {"armado_id": 2}, "build.parquet")
|
||||
|
||||
|
||||
def test_models_are_registered_as_domain_and_scenario():
|
||||
"""Pins down: the name runs and versions share. Fails if the convention changes on one side only."""
|
||||
assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("metadata, expected", [
|
||||
({"url": "u", "producer": "dbt", "build": "4"}, ("dbt", "4")),
|
||||
({"url": "u", "producer": "kit", "armado_id": "2"}, ("kit", "2")),
|
||||
({"url": "u", "producer": "kit build, timeline from dbt view", "armado_id": "1"}, ("kit", "1")),
|
||||
({"url": "u", "armado_id": "3"}, ("kit", "3")),
|
||||
])
|
||||
def test_a_file_is_dbts_only_when_its_producer_says_dbt(metadata, expected):
|
||||
"""Pins down: a cohort file's source is dbt only for `producer: dbt`; any other producer, or none, is a kit build
|
||||
numbered by `armado_id`. Fails if an older kit file with a descriptive producer is read as dbt's and loses its
|
||||
`armado_id`."""
|
||||
reference = cohort_reference(metadata, "f" * 64)
|
||||
|
||||
assert (reference["cohort.source"], reference["cohort.build"]) == expected
|
||||
@@ -0,0 +1,151 @@
|
||||
"""What this module covers: logging a model in a training run (`TrainingRun.log_model`, `model_sha`), the
|
||||
code version every run records (`code_version`), and choosing the version to use (`registry.resolve`).
|
||||
|
||||
Fixtures: `mlflow_tracking` (from `conftest.py`), a SQLite-backed MLflow per test; `production_ready`
|
||||
(from `conftest.py`), which registers a PROD version that passes every promotion check. `Constant` is a
|
||||
pyfunc that returns one fixed probability per row; `_train` registers a dev version, with or without a
|
||||
logged model.
|
||||
"""
|
||||
|
||||
from importlib.metadata import version
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from core.governance.enums import Environment
|
||||
from mlflow import MlflowClient
|
||||
|
||||
from models.io.lineage import MODEL_SHA_TAG, MODELS_VERSION_TAG
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
|
||||
class Constant(mlflow.pyfunc.PythonModel):
|
||||
"""Returns `p` for every row."""
|
||||
|
||||
def __init__(self, p: float):
|
||||
self.p = p
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> list[float]:
|
||||
return [self.p] * len(model_input)
|
||||
|
||||
|
||||
def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[TrainingRun, str]:
|
||||
"""A dev run of `cacu/<scenario>` that logs `model` (if any) and is registered; returns the run and
|
||||
its version."""
|
||||
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
|
||||
if model is not None:
|
||||
run.log_model(model)
|
||||
return run, registry.register_run(run.finish(metrics={"auc": 0.7}))
|
||||
|
||||
|
||||
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
|
||||
"""Pins down: a run that logs a model registers `runs:/<run_id>/model`, and loading the version gives
|
||||
back that model, tagged with its `modelo_sha` on the run and on the version.
|
||||
|
||||
Fails if `finish` registers the run instead of its model folder, or the sha isn't tagged.
|
||||
"""
|
||||
run, version = _train(Constant(0.25))
|
||||
|
||||
loaded = mlflow.pyfunc.load_model(registry.resolve("cacu", "tamizaje", version).model_uri)
|
||||
mv = registry.get("cacu", "tamizaje", version)
|
||||
|
||||
assert list(loaded.predict(pd.DataFrame({"x": [1, 2]}))) == [0.25, 0.25]
|
||||
assert mv.source == f"runs:/{run.run_id}/model"
|
||||
assert mv.tags[MODEL_SHA_TAG] == run.modelo_sha
|
||||
assert MlflowClient().get_run(run.run_id).data.tags[MODEL_SHA_TAG] == run.modelo_sha
|
||||
|
||||
|
||||
def test_the_sha_is_the_model_not_the_run(mlflow_tracking):
|
||||
"""Pins down: the same model logged in two runs has the same `modelo_sha`; a different model has
|
||||
another one.
|
||||
|
||||
Fails if `model_sha` starts covering files with ids or dates (`MLmodel`), or stops covering the model.
|
||||
"""
|
||||
first, _ = _train(Constant(0.25))
|
||||
second, _ = _train(Constant(0.25))
|
||||
other, _ = _train(Constant(0.30))
|
||||
|
||||
assert first.modelo_sha == second.modelo_sha != other.modelo_sha
|
||||
|
||||
|
||||
def test_a_run_logs_one_model(mlflow_tracking):
|
||||
"""Pins down: a second `log_model` in the same run is refused.
|
||||
|
||||
Fails if a run could hold two models, so its version wouldn't say which one it is.
|
||||
"""
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
run.log_model(Constant(0.25))
|
||||
|
||||
with pytest.raises(RuntimeError, match="already logged"):
|
||||
run.log_model(Constant(0.30))
|
||||
|
||||
|
||||
def test_a_run_without_a_model_still_registers_the_run(mlflow_tracking):
|
||||
"""Pins down: a run that doesn't log a model registers `runs:/<run_id>` with no `modelo_sha`, as
|
||||
before `log_model` existed.
|
||||
|
||||
Fails if `finish` requires a model.
|
||||
"""
|
||||
run, version = _train()
|
||||
|
||||
resolved = registry.resolve("cacu", "tamizaje", version)
|
||||
assert registry.get("cacu", "tamizaje", version).source == f"runs:/{run.run_id}"
|
||||
assert resolved.modelo_sha is None
|
||||
|
||||
|
||||
def test_without_a_version_resolve_takes_production(production_ready):
|
||||
"""Pins down: with no version, `resolve` returns the one holding `produccion`, with that status; with
|
||||
none in production it raises `LookupError`.
|
||||
|
||||
Fails if `resolve` falls back to the latest version instead of failing.
|
||||
"""
|
||||
domain, scenario, version = production_ready("v1")
|
||||
with pytest.raises(LookupError, match="no version in production"):
|
||||
registry.resolve(domain, scenario)
|
||||
|
||||
registry.promote(domain, scenario, version)
|
||||
resolved = registry.resolve(domain, scenario)
|
||||
|
||||
assert (resolved.version, resolved.status) == (version, "produccion")
|
||||
assert resolved.model_uri == f"models:/{domain}-{scenario}/{version}"
|
||||
|
||||
|
||||
def test_an_explicit_version_is_returned_with_its_status(production_ready):
|
||||
"""Pins down: with a version, `resolve` returns it whatever its status (a candidate can be tested),
|
||||
and says which status it has; an unknown version raises `LookupError`.
|
||||
|
||||
Fails if an explicit version is refused for not being in production, or its status is lost.
|
||||
"""
|
||||
domain, scenario, first = production_ready("v1")
|
||||
_, _, second = production_ready("v2")
|
||||
registry.promote(domain, scenario, first)
|
||||
|
||||
assert registry.resolve(domain, scenario, second).status == "candidata"
|
||||
assert registry.resolve(domain, scenario, first).status == "produccion"
|
||||
with pytest.raises(LookupError):
|
||||
registry.resolve(domain, scenario, "99")
|
||||
|
||||
|
||||
def test_every_run_records_the_version_of_the_code(mlflow_tracking):
|
||||
"""Pins down: a run is tagged with the installed `models` package's version, which a deployment without the
|
||||
repository has too. Fails if the tag is dropped or renamed, or the version is read from anywhere else."""
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
|
||||
assert MlflowClient().get_run(run.run_id).data.tags[MODELS_VERSION_TAG] == version("models")
|
||||
|
||||
|
||||
def test_a_prod_run_refuses_a_model_defined_in_a_notebook(mlflow_tracking):
|
||||
"""Pins down: a PROD run only logs a model whose class lives in a module; one defined in a notebook or
|
||||
script (`__main__`) is refused, because its code has no commit to trace. A dev run accepts it.
|
||||
|
||||
Fails if the check is dropped, or starts refusing dev runs or module classes.
|
||||
"""
|
||||
InNotebook = type("InNotebook", (Constant,), {"__module__": "__main__"})
|
||||
prod = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD, cohorte_armado_id=1)
|
||||
|
||||
with pytest.raises(ValueError, match="defined in a notebook"):
|
||||
prod.log_model(InNotebook(0.25))
|
||||
prod.log_model(Constant(0.25))
|
||||
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).log_model(InNotebook(0.25))
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
"""What this module covers: the registry's promotion checks, promotion and retirement, the lineage of a version, and
|
||||
what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`).
|
||||
|
||||
Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model;
|
||||
`governance_db`, `cacu_db` and `mlflow_tracking` (from `conftest.py`); `trained_run` and `armado` (from `conftest.py`)
|
||||
build runs missing a routine or the model.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
from conftest import armado, trained_run
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import PromotionBlocked, registry
|
||||
from models.io.registry import PromotionBlocked, registry
|
||||
|
||||
|
||||
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
|
||||
@@ -9,7 +21,7 @@ def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_track
|
||||
with pytest.raises(PromotionBlocked) as blocked:
|
||||
registry.promote("cacu", "tamizaje", version)
|
||||
failed = {check.code for check in blocked.value.checks if not check.passed}
|
||||
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
|
||||
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01a", "ML-01b"}
|
||||
|
||||
|
||||
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
|
||||
@@ -35,10 +47,44 @@ def test_reports_can_be_attached_after_training(production_ready):
|
||||
registry.attach_reports(domain, scenario, version, metrics="{}")
|
||||
|
||||
|
||||
def test_artifacts_are_logged_to_the_run(production_ready):
|
||||
def test_lineage_lists_every_stored_file_and_each_routine_record(production_ready):
|
||||
"""The lineage lists files inside folders (the saved model) and reads back each routine's record. Fails if
|
||||
`run_files` stops descending into folders or `routines` stops reading `rutinas/`."""
|
||||
domain, scenario, version = production_ready("v1")
|
||||
lineage = registry.lineage(domain, scenario, version)
|
||||
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
|
||||
paths = {item["path"] for item in lineage["artifacts"]}
|
||||
assert "model/MLmodel" in paths and "rutinas/MUESTREO.json" in paths
|
||||
assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routines, model, failing", [
|
||||
([ArtifactKind.MUESTREO], True, "ML-01a"),
|
||||
(None, False, "ML-01b"),
|
||||
])
|
||||
def test_promotion_needs_what_the_training_run_itself_recorded(governance_db, cacu_db, mlflow_tracking, routines, model,
|
||||
failing):
|
||||
"""A run that skipped routine records, or saved no model, is not promoted, whatever else is in order. Fails if
|
||||
the ML-01a check stops requiring every kind in `ROUTINE_KINDS` or the ML-01b check stops requiring `modelo_sha`."""
|
||||
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=routines, model=model)
|
||||
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
|
||||
interpretability_report_uri="i")
|
||||
failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed]
|
||||
assert [check.code for check in failed] == [failing]
|
||||
if failing == "ML-01a":
|
||||
assert "DATOS_FALTANTES" in failed[0].detail
|
||||
|
||||
|
||||
def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready):
|
||||
"""ML-01b: a stored file comes back as itself; the model folder as a zip of its files. Fails if `run_file`
|
||||
stops zipping folders or starts accepting a path the run doesn't list."""
|
||||
domain, scenario, version = production_ready("v1")
|
||||
name, data = registry.artifact(domain, scenario, version, "rutinas/MUESTREO.json")
|
||||
assert name == "MUESTREO.json" and json.loads(data)["n"] == 8
|
||||
name, data = registry.artifact(domain, scenario, version, "model")
|
||||
assert name == "model.zip" and "model/MLmodel" in zipfile.ZipFile(io.BytesIO(data)).namelist()
|
||||
for wrong in ("../mlflow.db", "", "rutinas/OTRO.json"):
|
||||
with pytest.raises(LookupError):
|
||||
registry.artifact(domain, scenario, version, wrong)
|
||||
|
||||
|
||||
def test_retire_and_lineage(production_ready):
|
||||
@@ -55,19 +101,6 @@ def test_retire_and_lineage(production_ready):
|
||||
registry.retire(domain, scenario, second)
|
||||
|
||||
|
||||
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
||||
from models.export import inspect_onnx_metadata
|
||||
|
||||
with pytest.raises(ValueError, match="ONNX"):
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "x.onnx"
|
||||
path.write_bytes(b"weights")
|
||||
inspect_onnx_metadata(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
|
||||
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
|
||||
with pytest.raises(ValueError):
|
||||
@@ -2,17 +2,10 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
from models.base import ScreeningModel
|
||||
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
||||
from models.registry import registry
|
||||
from models.io.registry import ApplicabilityRejected, Interpretability, PredictionService, registry
|
||||
|
||||
|
||||
class StubModel(ScreeningModel):
|
||||
domain = "cacu"
|
||||
|
||||
def train(self, data=None):
|
||||
raise NotImplementedError
|
||||
|
||||
class StubModel:
|
||||
def predict(self, data):
|
||||
return {"label": "positivo", "confianza": 0.73}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""What this module covers: `models.io.storage`: a kit build read from the database and the same build read from its
|
||||
exported file give the dataflow the same frame, each with its own reference, and a build that doesn't exist is named.
|
||||
|
||||
Fixtures: `frame`, a long frame of two members with one event after the cut-off; `kit_stand_ins` (conftest).
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from models.io.storage import CohortFile, KitBuild
|
||||
from models.steps.cohort_file import cohort_events
|
||||
|
||||
CUTOFF = date(2025, 12, 31)
|
||||
|
||||
|
||||
def _row(pac_id, index, fecha, fuente_id):
|
||||
return {"pac_id": pac_id, "fecha_indice": index, "fecha": fecha,
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda",
|
||||
"codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "t",
|
||||
"fuente_id": fuente_id}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def frame():
|
||||
"""Members 10 and 20; member 10 has an event after the cut-off, which no source may return."""
|
||||
return pd.DataFrame([_row(10, date(2025, 1, 1), date(2025, 1, 1), "a"),
|
||||
_row(20, date(2025, 2, 1), date(2025, 2, 1), "b"),
|
||||
_row(10, date(2025, 1, 1), date(2026, 3, 1), "late")], columns=COHORT_SCHEMA.names)
|
||||
|
||||
|
||||
def test_the_database_and_the_file_give_the_same_frame(frame, kit_stand_ins, tmp_path):
|
||||
"""Pins down that the reading is interchangeable: the kit build read through the repositories and its exported
|
||||
file are the same frame, so the dataflow can't tell them apart. Fails if one source cuts, orders or types the rows
|
||||
differently."""
|
||||
cohorts, timeline = kit_stand_ins(frame, 3, CUTOFF)
|
||||
from_database = KitBuild("cacu", 3, cohorts=cohorts, timeline=timeline).frame()
|
||||
population = frame[["pac_id", "fecha_indice"]].drop_duplicates()
|
||||
exported = cohort_events(kit_stand_ins(frame, 3, CUTOFF)[1].read(), population, CUTOFF)
|
||||
path = tmp_path / "3.parquet"
|
||||
pq.write_table(pa.Table.from_pandas(exported, schema=COHORT_SCHEMA, preserve_index=False).replace_schema_metadata(
|
||||
{"url": "cacu/cohorte_vigilancia", "armado_id": "3", "datos_as_of": CUTOFF.isoformat()}), path)
|
||||
|
||||
pd.testing.assert_frame_equal(from_database, CohortFile(path).frame())
|
||||
assert "late" not in from_database["fuente_id"].tolist()
|
||||
|
||||
|
||||
def test_a_kit_build_reads_its_members_up_to_its_cutoffs(frame, kit_stand_ins):
|
||||
"""Pins down: the timeline is asked for the build's members, cut at its clinical date and, since this build has no
|
||||
`conocida_hasta`, at no load cut-off (the lineage records when it was read); the reference names the build without
|
||||
a file hash. Fails if the read takes everyone, loses the clinical cut-off, invents a load cut-off, or the reference
|
||||
claims a hash it doesn't have."""
|
||||
cohorts, timeline = kit_stand_ins(frame, 3, CUTOFF)
|
||||
source = KitBuild("cacu", 3, cohorts=cohorts, timeline=timeline)
|
||||
|
||||
source.frame()
|
||||
|
||||
assert timeline.reads[-1]["patients"] == [10, 20] and timeline.reads[-1]["until"] == CUTOFF
|
||||
assert timeline.reads[-1]["known_until"] is None and source.lineage()["read_at"]
|
||||
assert source.lineage()["datos_as_of"] == "2025-12-31" and source.armado_id == 3
|
||||
assert source.reference() == {"cohort.url": "cacu/cohorte_vigilancia", "cohort.source": "kit", "cohort.build": "3"}
|
||||
|
||||
|
||||
def test_a_missing_kit_build_is_named(frame, kit_stand_ins):
|
||||
"""Pins down: asking for a build the database doesn't have fails with its number before any read. Fails if it
|
||||
reads an empty frame instead."""
|
||||
cohorts, timeline = kit_stand_ins(frame, 3, CUTOFF)
|
||||
|
||||
with pytest.raises(LookupError, match="kit build 9"):
|
||||
KitBuild("cacu", 9, cohorts=cohorts, timeline=timeline).frame()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""What this module covers: `models.io.storage`, reading a cohort build's file; and the rule that a model's folder
|
||||
doesn't import the database layer, since the file is its only input.
|
||||
|
||||
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
|
||||
"""
|
||||
|
||||
import ast
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
import models
|
||||
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortFileError
|
||||
from models.io.storage import read_cohort
|
||||
|
||||
|
||||
def _row(pac_id, fecha_indice, valor, fuente_id):
|
||||
return {"pac_id": pac_id, "fecha_indice": fecha_indice, "fecha": fecha_indice,
|
||||
"conocida_en": datetime(2025, 6, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": "bethesda",
|
||||
"codigo": "bethesda", "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": fuente_id}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(tmp_path):
|
||||
"""Member 10 has two results; member 20 has one."""
|
||||
rows = [_row(10, date(2025, 1, 1), "NORMAL", "a"), _row(10, date(2025, 1, 1), "NORMAL", "b"),
|
||||
_row(20, date(2025, 2, 1), "LIEBG", "c")]
|
||||
path = tmp_path / "1.parquet"
|
||||
pq.write_table(pa.Table.from_pylist(rows, schema=SCHEMA), path)
|
||||
return path
|
||||
|
||||
|
||||
def test_a_cohort_file_reads_as_a_frame(cohort_file):
|
||||
"""Pins down: a build's file comes back with all its rows and columns. Fails if `read_cohort` drops rows or
|
||||
columns, or refuses a file with the right schema."""
|
||||
frame = read_cohort(cohort_file)
|
||||
|
||||
assert list(frame.columns) == SCHEMA.names
|
||||
assert frame["pac_id"].tolist() == [10, 10, 20]
|
||||
|
||||
|
||||
def test_a_file_with_other_columns_is_refused(tmp_path):
|
||||
"""Pins down: `read_cohort` only accepts a cohort build's columns and types. Fails if it stops checking the
|
||||
schema, which would let a model fail later on a missing column."""
|
||||
path = tmp_path / "other.parquet"
|
||||
pq.write_table(pa.table({"pac_id": [1]}), path)
|
||||
with pytest.raises(CohortFileError, match="cohort build's columns"):
|
||||
read_cohort(path)
|
||||
|
||||
|
||||
def test_model_folders_do_not_import_the_database_layer():
|
||||
"""Pins down: a model only sees frames: nothing under `models/cacu`, `cama` or `tea` imports `persistance` or
|
||||
`core`. Fails when a model's folder imports either."""
|
||||
package = Path(models.__file__).parent
|
||||
offenders = []
|
||||
for path in (file for domain in ("cacu", "cama", "tea") for file in (package / domain).rglob("*.py")):
|
||||
for node in ast.walk(ast.parse(path.read_text())):
|
||||
names = [alias.name for alias in node.names] if isinstance(node, ast.Import) else \
|
||||
[node.module or ""] if isinstance(node, ast.ImportFrom) else []
|
||||
offenders += [(path.name, name) for name in names if name.split(".")[0] in ("persistance", "core")]
|
||||
assert not offenders
|
||||
@@ -0,0 +1,28 @@
|
||||
"""What this module covers: `models.io.storage.resolve_repository`, how `models` finds a domain's Persistance repository by name.
|
||||
|
||||
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from models.io.storage import resolve_repository
|
||||
|
||||
|
||||
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
|
||||
"""A repository found by name reads what was written through it, in batches and with filters. Fails if
|
||||
`resolve_repository` looks in another module or stops returning a working repository."""
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
|
||||
repository = resolve_repository("cacu", "paciente")
|
||||
for i in range(7):
|
||||
repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
|
||||
assert [r.pac_id_hospital for r in repository.iter_all(batch_size=3)] == [f"M-{i}" for i in range(7)]
|
||||
assert list(repository.iter_all(pac_id_hospital="M-3"))[0].pac_sexo == "Femenino"
|
||||
|
||||
|
||||
def test_unknown_entity_is_a_clear_error():
|
||||
"""An unknown name raises `ValueError` naming it. Fails if the `AttributeError` is no longer translated."""
|
||||
with pytest.raises(ValueError, match="no nope_repository"):
|
||||
resolve_repository("tea", "nope")
|
||||
@@ -1,10 +1,11 @@
|
||||
import pytest
|
||||
|
||||
from core.governance.enums import ArtifactKind, Environment
|
||||
from models.registry import registry
|
||||
from models.io.registry import registry
|
||||
from mlflow import MlflowException
|
||||
|
||||
from models.training import ReadOnlyRepository, TrainingRun
|
||||
from models.io.storage import ReadOnlyRepository
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
|
||||
def test_prod_run_requires_a_cohort_build():
|
||||
@@ -18,20 +19,20 @@ def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
|
||||
|
||||
|
||||
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
|
||||
checkpoint = tmp_path / "model.onnx"
|
||||
checkpoint.write_bytes(b"fake-onnx-bytes")
|
||||
notes = tmp_path / "notas.json"
|
||||
notes.write_text("{}")
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
|
||||
version = run.finish(metrics={"auc": 0.81})
|
||||
run.log_artifact(ArtifactKind.OTRO, notes, metadata={"origen": "prueba"})
|
||||
version = registry.register_run(run.finish(metrics={"auc": 0.81}))
|
||||
|
||||
mv = registry.get("cacu", "tamizaje", version)
|
||||
assert mv.tags["environment"] == Environment.DEV.value
|
||||
metrics = registry.client.get_run(mv.run_id).data.metrics
|
||||
assert metrics["auc"] == 0.81
|
||||
|
||||
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
|
||||
assert any(path.endswith("model.onnx") for path in artifacts)
|
||||
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.OTRO.value)]
|
||||
assert any(path.endswith("notas.json") for path in artifacts)
|
||||
|
||||
|
||||
def test_read_only_repository_blocks_writes(cacu_db):
|
||||
@@ -61,23 +62,34 @@ def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, t
|
||||
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
|
||||
|
||||
|
||||
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
||||
def test_registering_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
||||
from mlflow import MlflowClient
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
assert run.finish() == "1"
|
||||
assert registry.register_run(run.finish()) == "1"
|
||||
|
||||
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
assert second.finish() == "2"
|
||||
assert registry.register_run(second.finish()) == "2"
|
||||
|
||||
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||
|
||||
def unreachable(name):
|
||||
def unreachable(self, name):
|
||||
raise MlflowException("servidor no disponible")
|
||||
|
||||
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
|
||||
monkeypatch.setattr(MlflowClient, "create_registered_model", unreachable)
|
||||
with pytest.raises(MlflowException, match="no disponible"):
|
||||
third.finish()
|
||||
registry.register_run(third.finish())
|
||||
|
||||
|
||||
def test_unknown_domain_is_rejected():
|
||||
with pytest.raises(ValueError, match="dominio desconocido"):
|
||||
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
|
||||
|
||||
|
||||
def test_finishing_a_run_registers_nothing(mlflow_tracking):
|
||||
"""Pins down: closing a run logs its metrics and ends it, and only the registry turns it into a version, so a run
|
||||
can be kept without becoming a model. Fails if `finish` starts registering again."""
|
||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).finish(metrics={"auc": 0.5})
|
||||
|
||||
assert registry.client.get_run(run.run_id).info.status == "FINISHED"
|
||||
assert registry.client.search_model_versions("name='cacu-tamizaje'") == []
|
||||
@@ -0,0 +1,185 @@
|
||||
"""What this module covers: the reading nodes of `models.pipelines.reading` (`cohort_build`, `members`, `known_until`, `timeline`)
|
||||
run by a Hamilton driver built from that module alone, and their place in the asset graph.
|
||||
|
||||
Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain
|
||||
`timeline_events` table; it returns the `CohortRepository` and a `TimelineRepository` bound to
|
||||
`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and
|
||||
executes the requested nodes.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from core.cacu.base import CaCuModel
|
||||
from core.cacu.indicadores.models import (
|
||||
CohorteArmado,
|
||||
CohorteExclusion,
|
||||
CohorteMiembro,
|
||||
CohorteVariable,
|
||||
EvaluacionRiesgo,
|
||||
EvaluacionRiesgoLote,
|
||||
)
|
||||
from core.indicadores.cohortes import TablasCohorte
|
||||
from hamilton import driver
|
||||
from persistance.edges.gold import CohortRepository
|
||||
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.assets import Asset, InvalidGraph, validate
|
||||
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select
|
||||
from sqlalchemy.pool import StaticPool
|
||||
from sqlmodel import Session, create_engine
|
||||
|
||||
from models.pipelines import reading
|
||||
|
||||
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
|
||||
EvaluacionRiesgo)
|
||||
ASSETS = {name: Asset(name) for name in ("cohorte_armado", "cohorte_miembro", "linea_de_tiempo")}
|
||||
|
||||
metadata = MetaData()
|
||||
events = Table(
|
||||
"timeline_events", metadata,
|
||||
Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime),
|
||||
Column("clase", String), Column("tipo", String), Column("codigo", String),
|
||||
Column("valor_codigo", String), Column("valor_numerico", Float),
|
||||
Column("fuente_tabla", String), Column("fuente_id", String),
|
||||
)
|
||||
|
||||
|
||||
def _event(pac_id, fecha, conocida_en, fuente_id):
|
||||
return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "procedimiento",
|
||||
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "NORMAL", "valor_numerico": None,
|
||||
"fuente_tabla": "citologiacervical", "fuente_id": fuente_id}
|
||||
|
||||
|
||||
EVENTS = [
|
||||
_event(10, date(2025, 2, 1), datetime(2025, 2, 2), "kept-10"),
|
||||
_event(20, date(2025, 3, 1), datetime(2025, 3, 2), "kept-20"),
|
||||
_event(10, date(2026, 2, 1), datetime(2026, 1, 1), "after-datos-as-of"),
|
||||
_event(20, date(2025, 6, 1), datetime(2026, 1, 3), "loaded-after-the-build"),
|
||||
_event(99, date(2025, 2, 1), datetime(2025, 2, 2), "not-a-member"),
|
||||
_event(10, date(2025, 4, 1), datetime(2099, 1, 1), "loaded-in-the-future"),
|
||||
]
|
||||
|
||||
|
||||
def timeline_query(*, patients, until, known_until):
|
||||
"""Stands in for the kit's query: same columns and filters, over `timeline_events`."""
|
||||
query = select(*(events.c[name] for name in TIMELINE_COLUMNS)).order_by(events.c.pac_id, events.c.fecha)
|
||||
if patients is not None:
|
||||
query = query.where(events.c.pac_id.in_(patients))
|
||||
if until is not None:
|
||||
query = query.where(events.c.fecha <= until)
|
||||
if known_until is not None:
|
||||
query = query.where(events.c.conocida_en <= known_until.replace(tzinfo=None))
|
||||
return query
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repositories():
|
||||
"""Build 1 of `cacu/cohorte_vigilancia`: clinical cut-off 2025-12-31, load cut-off 2026-01-02 08:00
|
||||
UTC, members 20 and 10 (inserted in that order). Build 2 has no members; build 3 has member 10 and no
|
||||
load cut-off. `EVENTS` has one event per member inside both cut-offs, one past the clinical cut-off,
|
||||
one loaded after build 1, one of a patient outside the cohort and one loaded in the future.
|
||||
"""
|
||||
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
||||
CaCuModel.metadata.create_all(engine)
|
||||
metadata.create_all(engine)
|
||||
load_cut = {1: "2026-01-02T08:00:00+00:00", 2: "2026-01-02T08:00:00+00:00", 3: None}
|
||||
with Session(engine) as session:
|
||||
session.add_all([
|
||||
CohorteArmado(armado_id=armado_id, url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d",
|
||||
reglas_sha="r", parametros=json.dumps({"corte": "2025-12-31", "conocida_hasta": cut}),
|
||||
datos_as_of=date(2025, 12, 31), huella=f"h{armado_id}", marco_sha=f"m{armado_id}",
|
||||
n_miembros=0, armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc))
|
||||
for armado_id, cut in load_cut.items()
|
||||
])
|
||||
session.add_all([
|
||||
CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=fecha,
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))
|
||||
for armado_id, pac_id, fecha in ((1, 20, date(2025, 3, 1)), (1, 10, date(2025, 2, 1)),
|
||||
(3, 10, date(2025, 2, 1)))
|
||||
])
|
||||
session.commit()
|
||||
session.connection().execute(insert(events), EVENTS)
|
||||
session.commit()
|
||||
factory = lambda: Session(engine) # noqa: E731
|
||||
return CohortRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
|
||||
|
||||
|
||||
def _run(repositories, build_id, nodes=("members", "timeline")):
|
||||
cohort_repository, timeline_repository = repositories
|
||||
dr = driver.Builder().with_modules(reading).build()
|
||||
return dr.execute(list(nodes), inputs={**ASSETS, "cohort_repository": cohort_repository,
|
||||
"timeline_repository": timeline_repository, "build_id": build_id})
|
||||
|
||||
|
||||
def test_reads_the_members_and_their_timeline_of_a_build(repositories):
|
||||
"""Pins down: a driver with only the reading nodes returns the build's members ordered by `pac_id`
|
||||
with `MEMBER_COLUMNS`, and a timeline with `TIMELINE_COLUMNS` holding only the members' events.
|
||||
|
||||
Fails if `members` loses its order or columns, or `timeline` stops filtering by the members.
|
||||
"""
|
||||
result = _run(repositories, 1)
|
||||
|
||||
assert list(result["members"].columns) == list(reading.MEMBER_COLUMNS)
|
||||
assert result["members"]["pac_id"].tolist() == [10, 20]
|
||||
assert list(result["timeline"].columns) == list(TIMELINE_COLUMNS)
|
||||
assert 99 not in result["timeline"]["pac_id"].tolist()
|
||||
|
||||
|
||||
def test_the_timeline_is_cut_where_the_build_was_made(repositories):
|
||||
"""Pins down: the timeline keeps events up to the build's `datos_as_of` and loaded by its
|
||||
`conocida_hasta`, so reading it again gives the build's input.
|
||||
|
||||
Fails if `timeline` reads with no cut-off, or takes the cut-offs from anywhere but the build.
|
||||
"""
|
||||
timeline = _run(repositories, 1)["timeline"]
|
||||
|
||||
assert timeline["fuente_id"].tolist() == ["kept-10", "kept-20"]
|
||||
|
||||
|
||||
def test_a_build_without_a_load_cut_off_is_read_up_to_now(repositories):
|
||||
"""Pins down: when the build has no `conocida_hasta`, `known_until` is the moment of the read (UTC),
|
||||
never `None`, and the timeline is cut there.
|
||||
|
||||
Fails if `known_until` lets `None` through (the read couldn't be repeated) or isn't the one the
|
||||
timeline used.
|
||||
"""
|
||||
before = datetime.now(timezone.utc)
|
||||
result = _run(repositories, 3, nodes=("known_until", "timeline"))
|
||||
|
||||
assert before <= result["known_until"] <= datetime.now(timezone.utc)
|
||||
assert result["timeline"]["fuente_id"].tolist() == ["kept-10"]
|
||||
|
||||
|
||||
def test_a_build_without_members_reads_an_empty_timeline(repositories):
|
||||
"""Pins down: a build with no members gives empty frames with their columns, not everyone's timeline.
|
||||
|
||||
Fails if an empty member list reaches the query as "no patient filter".
|
||||
"""
|
||||
result = _run(repositories, 2)
|
||||
|
||||
assert result["members"].empty and list(result["members"].columns) == list(reading.MEMBER_COLUMNS)
|
||||
assert result["timeline"].empty and list(result["timeline"].columns) == list(TIMELINE_COLUMNS)
|
||||
|
||||
|
||||
def test_an_unknown_build_fails(repositories):
|
||||
"""Pins down: asking for a build that doesn't exist raises `UnknownBuild` naming it.
|
||||
|
||||
Fails if `cohort_build` lets `None` through to the other nodes.
|
||||
"""
|
||||
with pytest.raises(reading.UnknownBuild, match="404"):
|
||||
_run(repositories, 404, nodes=("cohort_build",))
|
||||
|
||||
|
||||
def test_the_assets_read_are_sources_of_the_graph():
|
||||
"""Pins down: the reading nodes read three assets nobody in `models` produces (`cohorte_armado`,
|
||||
`cohorte_miembro`, `linea_de_tiempo`), so the graph validates only with them declared as sources.
|
||||
|
||||
Fails if a node stops declaring the asset it reads, or reads one more without saying so.
|
||||
"""
|
||||
nodes = driver.Builder().with_modules(reading).build().list_available_variables()
|
||||
|
||||
with pytest.raises(InvalidGraph) as error:
|
||||
validate(nodes)
|
||||
assert len(str(error.value).splitlines()) == 3
|
||||
validate(nodes, sources=set(ASSETS))
|
||||
@@ -0,0 +1,226 @@
|
||||
"""What this module covers: notebooks run on a cohort build's file as MLflow runs (`models.reports.experiment`), the
|
||||
job folder and its executors (`models.reports.notebook_jobs`), the import of what a notebook trained
|
||||
(`models.reports.notebook_import`), the API notebooks use inside (`models.notebook`) and the Jupyter renderer: what the
|
||||
notebook can reach, what the run keeps, a notebook that fails, a notebook that tries to reach past its job, the runner
|
||||
as the container runs it, and listing and reading runs back.
|
||||
|
||||
Fixtures: `cohort_file`, a dbt build's file of two members with its metadata; `jupyter`, the Jupyter renderer chosen
|
||||
and MLflow's artifacts kept under the test's folder; `mlflow_tracking` (conftest), a SQLite-backed MLflow. Notebooks
|
||||
are built inline with `_notebook`, naming a kernel the server doesn't have, as an author's would; they run in a real
|
||||
kernel, the platform's own (fails if `notebook_jobs.KERNEL` stops replacing it). `Echo` (conftest) is the saved
|
||||
model a notebook is given.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from models.io.registry import registry
|
||||
from models.reports import experiment
|
||||
|
||||
|
||||
def _notebook(*sources: str) -> dict:
|
||||
return {"cells": [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": [s]}
|
||||
for s in sources],
|
||||
"metadata": {"kernelspec": {"name": "un-kernel-local", "display_name": "local", "language": "python"}},
|
||||
"nbformat": 4, "nbformat_minor": 5}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(tmp_path):
|
||||
rows = [{"pac_id": pac_id, "fecha_indice": date(2025, 1, pac_id), "fecha": date(2025, 1, pac_id),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
|
||||
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": f"S{pac_id}"} for pac_id in (1, 2)]
|
||||
table = pa.Table.from_pandas(pd.DataFrame(rows, columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "3.parquet"
|
||||
path.parent.mkdir(parents=True)
|
||||
metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "3", "datos_as_of": "2025-12-31"}
|
||||
pq.write_table(table.replace_schema_metadata(metadata), path)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jupyter(tmp_path, monkeypatch, mlflow_tracking):
|
||||
monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter")
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
monkeypatch.setenv("CACU_DATABASE_URL", f"sqlite:///{tmp_path / 'real-cacu.db'}")
|
||||
|
||||
|
||||
def test_a_notebook_reads_its_build_and_no_database(jupyter, cohort_file):
|
||||
"""The notebook gets the build's file through `models.notebook` and only an empty in-memory database, whatever the
|
||||
server's own URLs are. Fails if `notebook_env` starts passing the server's environment or the build's file stops
|
||||
reaching the kernel."""
|
||||
notebook = _notebook("import os\nfrom models.notebook import experiment\nexp = experiment()",
|
||||
"print('members', exp.cohort().pac_id.nunique(), os.environ['CACU_DATABASE_URL'] or 'none')")
|
||||
run_id, ok = experiment.run_notebook(notebook, "lee.ipynb", cohort_file, "cacu", "exploracion")
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
page = experiment.page(run_id)
|
||||
assert "members 2 sqlite://" in page and "real-cacu" not in page
|
||||
|
||||
|
||||
def test_the_run_keeps_the_notebook_its_page_and_its_inputs(jupyter, cohort_file):
|
||||
"""The run is tagged with the notebook's hash and the build, and keeps the notebook as uploaded and its page.
|
||||
Fails if `start` stops tagging the inputs or storing the source."""
|
||||
run_id, _ = experiment.run_notebook(_notebook("print(1 + 1)"), "../../otro/suma.ipynb", cohort_file, "cacu", "exploracion")
|
||||
run = experiment.describe(run_id)
|
||||
assert run["status"] == "terminado" and run["notebook"] == "suma"
|
||||
assert run["cohort"] == {"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "3"}
|
||||
assert {a["path"] for a in run["artifacts"]} == {"notebook/suma.ipynb", "report/suma.html", "importado.json"}
|
||||
assert run["sandbox"] == "local"
|
||||
name, data = experiment.artifact(run_id, "notebook/suma.ipynb")
|
||||
assert json.loads(data)["cells"][0]["source"] == ["print(1 + 1)"]
|
||||
|
||||
|
||||
def test_a_failing_cell_fails_the_run_and_keeps_what_ran(jupyter, cohort_file):
|
||||
"""A cell that raises ends the run as failed with the error, and the page shows the cells up to it. Fails if
|
||||
`execute` loses the partial page or leaves the run open."""
|
||||
run_id, ok = experiment.run_notebook(_notebook("print('antes')", "1 / 0", "print('despues')"), "falla", cohort_file,
|
||||
"cacu", "exploracion")
|
||||
run = experiment.describe(run_id)
|
||||
assert not ok and run["status"] == "fallido" and "ZeroDivisionError" in run["error"]
|
||||
assert "antes" in experiment.page(run_id) and "despues" not in experiment.page(run_id).split("ZeroDivisionError")[0]
|
||||
|
||||
|
||||
def test_a_notebook_can_train_and_register_a_dev_version(jupyter, cohort_file):
|
||||
"""Through `models.notebook`, a notebook opens a DEV run linked to its build, records a routine and registers it;
|
||||
the import brings run and version into the platform's MLflow. Fails if `Experiment.training_run` stops linking
|
||||
the build, or `import_job` stops copying runs, their files or their versions."""
|
||||
notebook = _notebook("from models.notebook import experiment\nexp = experiment()\nrun = exp.training_run()\n"
|
||||
"run.log_routine('MUESTREO', {'n': 2})\nprint('version', exp.register(run.finish(metrics={'n': 2})))")
|
||||
run_id, ok = experiment.run_notebook(notebook, "entrena", cohort_file, "cacu", "prueba_nb")
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
stored = registry.get("cacu", "prueba_nb", "1")
|
||||
assert stored.tags["environment"] == "DEV" and stored.tags["cohort.build"] == "3"
|
||||
assert registry.routines(stored.run_id) == {"MUESTREO": {"n": 2}}
|
||||
assert stored.tags["notebook.run_id"] == run_id
|
||||
|
||||
|
||||
def test_runs_are_listed_by_scenario_and_only_notebook_runs_are_read(jupyter, cohort_file):
|
||||
"""Listing finds notebook runs by domain and scenario; reading a run that isn't a notebook's is refused. Fails if
|
||||
`experiments` mixes scenarios or `describe` serves any run."""
|
||||
first, _ = experiment.run_notebook(_notebook("1"), "a", cohort_file, "cacu", "uno")
|
||||
experiment.run_notebook(_notebook("2"), "b", cohort_file, "cacu", "dos")
|
||||
assert [r["run_id"] for r in experiment.experiments("cacu", "uno")] == [first]
|
||||
assert len(experiment.experiments("cacu")) == 2
|
||||
with pytest.raises(ValueError):
|
||||
experiment.experiments("cacu", "x' OR '1'='1")
|
||||
from mlflow import MlflowClient
|
||||
|
||||
other = MlflowClient().create_run("0").info.run_id
|
||||
with pytest.raises(LookupError):
|
||||
experiment.describe(other)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("notebook", [{"cells": "x"}, {"cells": [], "nbformat": 3}, []])
|
||||
def test_what_isnt_a_notebook_is_refused(notebook, jupyter, cohort_file):
|
||||
"""Fails if `check_notebook` lets through something nbclient can't run."""
|
||||
with pytest.raises(ValueError):
|
||||
experiment.start(notebook, "x", cohort_file, "cacu", "exploracion")
|
||||
|
||||
|
||||
def test_a_notebook_cannot_reach_the_platforms_mlflow_or_put_a_version_in_production(jupyter, cohort_file):
|
||||
"""The notebook's MLflow is its job's own store; a version it registers as PROD with the production alias comes
|
||||
across as DEV with no alias, and the cohort tags are the build it really had. Fails if the job's environment
|
||||
starts pointing at the platform's MLflow, or `import_job` starts trusting the notebook's tags or aliases."""
|
||||
notebook = _notebook(
|
||||
"import mlflow\nfrom mlflow import MlflowClient\nfrom models.notebook import experiment\nexp = experiment()\n"
|
||||
"print('tracking', 'mlflow.db' in mlflow.get_tracking_uri() and 'trabajo' not in mlflow.get_tracking_uri())",
|
||||
"from models.io.tracking import TrainingRun\nfrom models.io.registry import registry\n"
|
||||
"run = TrainingRun(domain='cacu', scenario='colado', environment='DEV')\n"
|
||||
"MlflowClient().set_tag(run.run_id, 'cohort.build', '999')\n"
|
||||
"version = registry.register_run(run.finish(metrics={'auc': 0.99}))\n"
|
||||
"MlflowClient().set_model_version_tag('cacu-colado', version, 'environment', 'PROD')\n"
|
||||
"MlflowClient().set_registered_model_alias('cacu-colado', 'produccion', version)")
|
||||
run_id, ok = experiment.run_notebook(notebook, "colado", cohort_file, "cacu", "colado")
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
assert "tracking True" in experiment.page(run_id)
|
||||
stored = registry.get("cacu", "colado", "1")
|
||||
assert stored.tags["environment"] == "DEV" and stored.tags["cohort.build"] == "3"
|
||||
with pytest.raises(LookupError):
|
||||
registry.resolve("cacu", "colado")
|
||||
|
||||
|
||||
def test_files_a_notebook_links_outside_its_job_are_never_read(jupyter, cohort_file, tmp_path):
|
||||
"""A run whose files hold a symbolic link to a file of the server is left out, and the file's content never
|
||||
reaches MLflow. Fails if `import_job` follows links while copying a run's files."""
|
||||
secret = tmp_path / "secreto.txt"
|
||||
secret.write_text("CONTENIDO-PRIVADO")
|
||||
notebook = _notebook(
|
||||
"import os\nfrom pathlib import Path\nfrom models.notebook import experiment\nexp = experiment()\n"
|
||||
"run = exp.training_run()\nrun.log_routine('MUESTREO', {'n': 1})\n"
|
||||
"folder = Path(run.client.get_run(run.run_id).info.artifact_uri)\n"
|
||||
f"os.symlink({str(secret)!r}, folder / 'robado.txt')\nrun.finish()")
|
||||
run_id, ok = experiment.run_notebook(notebook, "enlace", cohort_file, "cacu", "enlace")
|
||||
assert ok
|
||||
summary = json.loads(experiment.artifact(run_id, "importado.json")[1])
|
||||
assert summary["runs"] == [] and "enlace" in summary["skipped"][0]["reason"]
|
||||
|
||||
|
||||
def test_read_job_file_refuses_links_and_paths_out_of_the_job(tmp_path):
|
||||
"""Fails if `read_job_file` follows a symbolic link or a `..` path out of the job folder."""
|
||||
from models.reports.notebook_jobs import JobError, read_job_file
|
||||
|
||||
job = tmp_path / "job"
|
||||
job.mkdir()
|
||||
(tmp_path / "fuera.txt").write_text("x")
|
||||
(job / "page.html").symlink_to(tmp_path / "fuera.txt")
|
||||
for relative in ("page.html", "../fuera.txt"):
|
||||
with pytest.raises(JobError):
|
||||
read_job_file(job, relative)
|
||||
assert read_job_file(job, "no-existe.json") is None
|
||||
|
||||
|
||||
def test_the_runner_runs_jobs_left_for_the_container(cohort_file, tmp_path, monkeypatch, mlflow_tracking):
|
||||
"""With a jobs folder, the WebApi side leaves the job and waits; a separate `models notebooks serve` process with
|
||||
no MLflow or database settings runs it, and the run says it ran in the container. Fails if the executor stops
|
||||
waiting for `result.json`, or the runner needs anything but the jobs folder."""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
jobs = tmp_path / "trabajos"
|
||||
jobs.mkdir()
|
||||
monkeypatch.setenv("NOTEBOOK_JOBS_DIR", str(jobs))
|
||||
monkeypatch.setenv("NOTEBOOK_JOB_TIMEOUT", "120")
|
||||
clean = {k: v for k, v in __import__("os").environ.items()
|
||||
if not k.startswith(("MLFLOW_", "CACU_", "CAMA_", "TEA_", "GOVERNANCE_", "NOTEBOOK_JOBS"))}
|
||||
clean["NOTEBOOK_RENDERER"] = "jupyter"
|
||||
runner = subprocess.Popen([sys.executable, "-m", "models", "notebooks", "serve", "--jobs", str(jobs)], env=clean,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
run_id, ok = experiment.run_notebook(_notebook("print('desde el contenedor')"), "cont", cohort_file, "cacu",
|
||||
"contenedor")
|
||||
finally:
|
||||
runner.terminate()
|
||||
runner.wait(10)
|
||||
run = experiment.describe(run_id)
|
||||
assert ok and run["sandbox"] == "contenedor"
|
||||
assert "desde el contenedor" in experiment.page(run_id)
|
||||
assert list(jobs.iterdir()) == []
|
||||
|
||||
|
||||
def test_a_notebook_given_a_version_loads_its_copy_of_the_model(jupyter, cohort_file):
|
||||
"""The chosen version's saved model is copied into the job and `exp.model()` loads it there, with no access to
|
||||
the registry. Fails if `execute` stops copying the model or `Experiment.model` stops preferring `MODEL_PATH`."""
|
||||
import cloudpickle
|
||||
import conftest
|
||||
from models.io.tracking import TrainingRun
|
||||
|
||||
cloudpickle.register_pickle_by_value(conftest)
|
||||
try:
|
||||
run = TrainingRun(domain="cacu", scenario="probada", environment="DEV")
|
||||
run.log_model(conftest.Echo())
|
||||
version = registry.register_run(run.finish())
|
||||
finally:
|
||||
cloudpickle.unregister_pickle_by_value(conftest)
|
||||
notebook = _notebook("import os, pandas as pd\nfrom models.notebook import experiment\n"
|
||||
"model = experiment().model()\n"
|
||||
"print('copia', os.environ['MODEL_PATH'].endswith('/model'), model.predict(pd.DataFrame({'a': [7]}))['a'][0])")
|
||||
run_id, ok = experiment.run_notebook(notebook, "usa", cohort_file, "cacu", "probada", version)
|
||||
assert ok, experiment.describe(run_id)["error"]
|
||||
assert "copia True 7" in experiment.page(run_id)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""What this module covers: `models.steps.model_fitting` run by a Hamilton driver built from that module alone, the
|
||||
way a scenario's driver uses it: the temporal split, the classifier chosen by config, the fit and the metrics.
|
||||
|
||||
Fixtures: `labelled`, forty members with index dates one day apart, one categorical predictor (`resultado`: `A` is
|
||||
always positive, `B` never) and `y`; `_driver` builds the driver with `classifier = "logistic"` unless told
|
||||
otherwise, and `_run` executes nodes with the three required inputs.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
|
||||
from models.steps import model_fitting
|
||||
|
||||
PREDICTORS = ["resultado"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def labelled() -> pd.DataFrame:
|
||||
"""Forty members, `pac_id` 1..40, index dates from 2025-01-01 one day apart in reverse `pac_id` order (so the
|
||||
oldest is member 40). Members whose `pac_id` is divisible by 4 have `resultado` `A` and `y` 1, the rest `B`
|
||||
and `y` 0."""
|
||||
rows = [{"pac_id": n, "fecha_indice": date(2025, 1, 1) + timedelta(days=40 - n),
|
||||
"resultado": "A" if n % 4 == 0 else "B", "y": int(n % 4 == 0)} for n in range(1, 41)]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _driver(config: dict | None = None):
|
||||
return driver.Builder().with_modules(model_fitting).with_config(
|
||||
{"classifier": "logistic"} if config is None else config).build()
|
||||
|
||||
|
||||
def _run(nodes: list[str], labelled: pd.DataFrame, config: dict | None = None, **inputs) -> dict:
|
||||
required = {"labelled_members": labelled, "predictor_columns": PREDICTORS, "train_fraction": 0.75}
|
||||
return _driver(config).execute(nodes, inputs={**required, **inputs})
|
||||
|
||||
|
||||
def test_the_oldest_members_train_and_the_newest_test(labelled):
|
||||
"""Pins down the temporal split: with 0.75, the 30 oldest index dates train and the 10 newest test, and every
|
||||
member is in exactly one of them. Fails if the split shuffles, ignores the index date or loses rows."""
|
||||
result = _run(["train_set", "test_set"], labelled)
|
||||
train, test = result["train_set"], result["test_set"]
|
||||
assert len(train) == 30 and len(test) == 10
|
||||
assert train["fecha_indice"].max() < test["fecha_indice"].min()
|
||||
assert sorted(train["pac_id"].tolist() + test["pac_id"].tolist()) == list(range(1, 41))
|
||||
|
||||
|
||||
def test_the_driver_needs_only_the_members_the_predictors_the_fraction_and_the_scenarios_routines(labelled):
|
||||
"""Pins down the dataflow's external inputs: the three required ones, and `sampling` and `missing_data`, the two
|
||||
routines (ML-01a) only a scenario can write; `target_column`, `split_order`, `max_iter` and `calibration_bins` have
|
||||
defaults. Fails if a node reads a setting from a global or the disk instead of taking it as an input, or if a new
|
||||
input appears without a default."""
|
||||
required = {v.name for v in _driver().list_available_variables()
|
||||
if v.is_external_input and v.originating_functions and not _has_default(v)}
|
||||
assert required == {"labelled_members", "predictor_columns", "train_fraction", "sampling", "missing_data"}
|
||||
|
||||
|
||||
def _has_default(variable) -> bool:
|
||||
for function in variable.originating_functions:
|
||||
parameter = inspect.signature(function).parameters.get(variable.name)
|
||||
if parameter is not None and parameter.default is inspect.Parameter.empty:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def test_the_classifier_is_chosen_by_config(labelled):
|
||||
"""Pins down `@config.when`: with `classifier = "logistic"` the prefit node is an unfitted logistic regression,
|
||||
and without a known classifier there's no `prefit_classifier` to fit with. Fails if the classifier is built
|
||||
inside `fitted_pipeline` again or the config key changes."""
|
||||
prefit = _run(["prefit_classifier"], labelled)["prefit_classifier"]
|
||||
assert type(prefit).__name__ == "LogisticRegression" and not hasattr(prefit, "coef_")
|
||||
with pytest.raises(ValueError):
|
||||
_run(["fitted_pipeline"], labelled, config={"classifier": "unknown"})
|
||||
|
||||
|
||||
def test_fitting_leaves_the_prefit_nodes_unfitted(labelled):
|
||||
"""Pins down that `fitted_pipeline` fits copies: the `encoder` and `prefit_classifier` values the driver computed
|
||||
stay unfitted. Fails if the fit mutates them, which would leak one run's fit into anything else that reads them."""
|
||||
result = _run(["encoder", "prefit_classifier", "fitted_pipeline"], labelled)
|
||||
assert not hasattr(result["prefit_classifier"], "coef_")
|
||||
assert not hasattr(result["encoder"], "transformers_")
|
||||
assert hasattr(result["fitted_pipeline"].named_steps["classify"], "coef_")
|
||||
|
||||
|
||||
def test_metrics_are_sklearn_s_on_the_test_set_under_the_names_mlflow_keeps(labelled):
|
||||
"""Pins down `metrics`: AUC and Brier computed on the test set's `y` and probabilities, the sizes and rates, with
|
||||
the keys training runs have always recorded. Fails if a metric is computed on the wrong set or a key is renamed
|
||||
(a renamed key splits a model's history in MLflow)."""
|
||||
result = _run(["metrics", "test_set", "test_probabilities"], labelled)
|
||||
test, probabilities, metrics = result["test_set"], result["test_probabilities"], result["metrics"]
|
||||
assert set(metrics) == {"auc", "brier", "n_train", "n_test", "positive_rate_train", "positive_rate_test",
|
||||
"mean_probability_test"}
|
||||
assert metrics["auc"] == pytest.approx(roc_auc_score(test["y"], probabilities))
|
||||
assert metrics["brier"] == pytest.approx(brier_score_loss(test["y"], probabilities))
|
||||
assert (metrics["n_train"], metrics["n_test"]) == (30, 10)
|
||||
assert metrics["positive_rate_test"] == pytest.approx(test["y"].mean())
|
||||
assert probabilities.name == "probabilidad" and probabilities.index.equals(test.index)
|
||||
|
||||
|
||||
def test_an_unseen_category_scores_as_none_of_the_known_ones(labelled):
|
||||
"""Pins down the encoder's `handle_unknown="ignore"`: a test member with a category training never saw still
|
||||
gets a probability, between the two known categories'. Fails if the encoder raises on unknown categories."""
|
||||
pipeline = _run(["fitted_pipeline"], labelled)["fitted_pipeline"]
|
||||
a, b, c = pipeline.predict_proba(pd.DataFrame({"resultado": ["A", "B", "C"]}))[:, 1]
|
||||
assert b < c < a
|
||||
|
||||
|
||||
def test_no_node_reads_writes_or_logs():
|
||||
"""Pins down that the module imports nothing that does I/O (MLflow, the registry, storage, tracking). Fails if a
|
||||
node starts logging or registering again instead of leaving that to a saver."""
|
||||
tree = ast.parse(inspect.getsource(model_fitting))
|
||||
imported = {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names}
|
||||
imported |= {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)}
|
||||
assert not {name for name in imported if name.split(".")[0] in {"mlflow", "persistance"}
|
||||
or name.startswith("models.io")}
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Synthetic EDF+ studies for the EEG analysis's tests: every signal is generated, nothing comes from a patient.
|
||||
|
||||
`edf_bytes(minutes=4, bad=...)` returns a file the `tea` library reads as a real study:
|
||||
- background: pink noise mixed over the head (sources weighted by distance), so neighbouring electrodes correlate;
|
||||
- wake: a posterior rhythm at `rhythm_hz`, strongest on O1 O2 P3 P4, and blinks on Fp1 Fp2;
|
||||
- sleep: frontal slow waves and 13 Hz spindles on the central and frontal electrodes;
|
||||
- EKG, EOG and the mains line; states annotated as the hospital writes them ("Paciente despierto", "Dormido");
|
||||
- `bad`: `flat` channels (no signal) or `loud` ones (eight times the amplitude).
|
||||
|
||||
Written as the hospital's converter writes them: plain labels, microvolts, one fixed range, digital ±32767.
|
||||
"""
|
||||
import tempfile
|
||||
from datetime import date, time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
SCALP = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
|
||||
EARS = ("A1", "A2")
|
||||
AUX = ("LOC", "ROC", "EKG")
|
||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||
SPINDLE = ("F3", "F4", "Fz", "C3", "C4", "Cz")
|
||||
FRONTAL = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8")
|
||||
FULL_SCALE = 4999.9
|
||||
|
||||
|
||||
def _positions():
|
||||
import mne
|
||||
|
||||
pos = mne.channels.make_standard_montage("colin27_1020").get_positions()["ch_pos"]
|
||||
return {ch: np.asarray(pos[ch], float) for ch in SCALP + list(EARS)}
|
||||
|
||||
|
||||
def _pink(rng, n, fs):
|
||||
f = np.fft.rfftfreq(n, 1 / fs)
|
||||
spec = rng.normal(size=f.size) + 1j * rng.normal(size=f.size)
|
||||
spec[1:] /= np.sqrt(f[1:])
|
||||
spec[0] = 0
|
||||
x = np.fft.irfft(spec, n)
|
||||
return x / x.std()
|
||||
|
||||
|
||||
def signals(*, fs: float, minutes: float, rhythm_hz: float, line_hz: float, bad: dict, seed: int):
|
||||
rng = np.random.default_rng(seed)
|
||||
n = int(round(minutes * 60 * fs))
|
||||
t = np.arange(n) / fs
|
||||
wake = t < t[-1] / 2
|
||||
sleep = ~wake
|
||||
pos = _positions()
|
||||
names = SCALP + list(EARS)
|
||||
src = rng.normal(size=(24, 3))
|
||||
src *= np.mean([np.linalg.norm(p) for p in pos.values()]) / np.linalg.norm(src, axis=1, keepdims=True)
|
||||
sources = np.stack([_pink(rng, n, fs) for _ in range(len(src))])
|
||||
data = {}
|
||||
for ch in names:
|
||||
w = np.exp(-np.linalg.norm(src - pos[ch], axis=1) / 0.04)
|
||||
w /= w.sum()
|
||||
data[ch] = 18.0 * (w @ sources) / np.sqrt((w ** 2).sum()) / np.sqrt(len(src)) * 3 + 4.0 * _pink(rng, n, fs)
|
||||
|
||||
alpha = np.sin(2 * np.pi * rhythm_hz * t + rng.uniform(0, 2 * np.pi))
|
||||
for ch in names:
|
||||
y = pos[ch][1]
|
||||
amp = 30.0 if ch in POSTERIOR else 12.0 * np.exp(-(y + 0.05) * 25) if y < 0.05 else 3.0
|
||||
data[ch] += amp * alpha * wake
|
||||
|
||||
slow = np.zeros(n)
|
||||
k = 0
|
||||
while k < n:
|
||||
length = int(fs * rng.uniform(0.8, 1.6))
|
||||
if k + length < n and sleep[k]:
|
||||
slow[k:k + length] = -rng.uniform(80, 200) * np.sin(np.pi * np.arange(length) / length)
|
||||
k += length + int(fs * rng.uniform(0.2, 1.5))
|
||||
spindles = np.zeros(n)
|
||||
for c in np.arange(5.0, n / fs, 8.0):
|
||||
i0 = int(c * fs)
|
||||
if i0 < n and sleep[i0]:
|
||||
length = int(fs * rng.uniform(0.6, 1.8))
|
||||
tt = np.arange(length) / fs
|
||||
seg = 35.0 * np.exp(-0.5 * ((tt - tt[-1] / 2) / (tt[-1] / 5)) ** 2) * np.sin(2 * np.pi * 13.0 * tt)
|
||||
spindles[i0:i0 + length] += seg[: max(0, min(length, n - i0))]
|
||||
for ch in names:
|
||||
data[ch] += slow if ch in FRONTAL else 0.6 * slow if ch in SPINDLE else 0
|
||||
if ch in SPINDLE:
|
||||
data[ch] += spindles
|
||||
|
||||
blinks = np.zeros(n)
|
||||
for c in np.arange(2.0, n / fs, 4.0):
|
||||
i0, length = int((c + rng.uniform(-0.5, 0.5)) * fs), int(0.3 * fs)
|
||||
if 0 <= i0 < n - length and wake[i0]:
|
||||
blinks[i0:i0 + length] += 120 * np.hanning(length)
|
||||
data["Fp1"] += blinks
|
||||
data["Fp2"] += blinks
|
||||
data["LOC"] = 0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
|
||||
data["ROC"] = -0.8 * blinks + 10 * _pink(rng, n, fs) + 0.3 * slow
|
||||
ekg = 20 * rng.normal(size=n)
|
||||
for c in np.arange(0.3, n / fs, 1 / 1.6):
|
||||
i0 = int(c * fs)
|
||||
if i0 + 10 < n:
|
||||
ekg[i0:i0 + 10] += 900 * np.hanning(10)
|
||||
data["EKG"] = ekg
|
||||
for ch in data:
|
||||
data[ch] = data[ch] + 2.0 * np.sin(2 * np.pi * line_hz * t)
|
||||
for ch in bad.get("flat", ()):
|
||||
data[ch] = rng.normal(0, 0.05, n)
|
||||
for ch in bad.get("loud", ()):
|
||||
data[ch] = data[ch] * 8
|
||||
return data, n / fs
|
||||
|
||||
|
||||
def edf_bytes(*, fs: float = 250.0, minutes: float = 4.0, rhythm_hz: float = 7.0, line_hz: float = 60.0,
|
||||
bad: dict | None = None, seed: int = 0, birthdate: date | None = None,
|
||||
startdate: date | None = None) -> bytes:
|
||||
"""`birthdate` and `startdate` go in the header; left out, it says `X` and the 01.01.85 placeholder."""
|
||||
from edfio import Edf, EdfAnnotation, EdfSignal, Patient, Recording
|
||||
|
||||
data, duration = signals(fs=fs, minutes=minutes, rhythm_hz=rhythm_hz, line_hz=line_hz, bad=bad or {}, seed=seed)
|
||||
labels = SCALP + list(EARS) + list(AUX)
|
||||
annotations = [EdfAnnotation(0.5, None, "Paciente despierto"), EdfAnnotation(duration / 2 + 0.5, None, "Dormido")]
|
||||
edf = Edf([EdfSignal(np.clip(data[ch], -FULL_SCALE, FULL_SCALE), fs, label=ch, physical_dimension="uV",
|
||||
physical_range=(-FULL_SCALE, FULL_SCALE), digital_range=(-32767, 32767)) for ch in labels],
|
||||
patient=Patient(birthdate=birthdate), recording=Recording(startdate=startdate),
|
||||
starttime=time(10, 0, 0), data_record_duration=1.0, annotations=annotations)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "study.edf"
|
||||
edf.write(path)
|
||||
return path.read_bytes()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user