Compare commits

..

3 Commits

70 changed files with 803 additions and 5340 deletions
-3
View File
@@ -1,3 +0,0 @@
[submodule "tea"]
path = libs/tea
url = ssh://git@10.0.10.41:2222/alberto/tea.git
+13 -20
View File
@@ -2,11 +2,9 @@
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 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
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
WebApi.
| Módulo | Qué hace |
@@ -15,7 +13,7 @@ WebApi.
| `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/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. `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). `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. |
| `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. |
@@ -23,25 +21,20 @@ WebApi.
| `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. |
| `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 `cohort_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 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. Renderers are classes in `rendering.py` (`RENDERERS`, `register_renderer`): `quarto` (`QUARTO_BIN`, and a Python with Jupyter in `QUARTO_PYTHON`) 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). |
| `pipelines/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. |
| `io/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. |
| `io/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. |
| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` (which refuses a build with no rows or with a member, a date or an event missing: `MODEL_COHORT`, pandera) 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`). |
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit, its metrics and the routine records every classifier shares (`sampling`, `analytic_method`, `class_balance`, `output_confidence`), gathered by `routines` with the scenario's `missing_data` (ML-01a). |
| `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`, `fitted_model`: a scikit-learn `Pipeline` that takes the long frame, and its `missing_data` routine record). Training records its five routines. 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 incidence, `likelihood.py`), fitted to each member's code and interval; the clinical settings (windows, known-negative results) in `model.toml`. Its dataflow records its own five routines. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `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). |
| `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. |
-172
View File
@@ -1,172 +0,0 @@
# 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 libs/tea deleted from 05ee02990c
+10 -97
View File
@@ -25,17 +25,6 @@ def _scenario(args: argparse.Namespace):
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
@@ -148,11 +137,11 @@ def _report_eda(args: argparse.Namespace) -> int:
def _serve_notebooks(args: argparse.Namespace) -> int:
"""The runner container's loop (`models.reports.notebook_jobs.serve`)."""
"""The runner container's loop (`models.io.notebook_jobs.serve`)."""
import os
from pathlib import Path
from models.reports.notebook_jobs import JOBS_DIR_ENV, serve
from models.io.notebook_jobs import JOBS_DIR_ENV, serve
folder = args.jobs or os.environ.get(JOBS_DIR_ENV)
if not folder:
@@ -162,46 +151,6 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
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)):
@@ -210,12 +159,10 @@ def _estimate(args: argparse.Namespace) -> int:
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
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
name = registered_name(args.domain, args.scenario)
try:
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
@@ -224,12 +171,7 @@ def _promote_step(args: argparse.Namespace, version: str) -> int:
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
registry.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
print(f"in production: version {version}")
return 0
@@ -238,8 +180,6 @@ 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"):
@@ -441,7 +381,7 @@ def build_parser() -> argparse.ArgumentParser:
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("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'")
show.add_argument("--build", type=int, required=True, help="the build's number")
show.set_defaults(run=_cohort_show)
@@ -450,7 +390,7 @@ def build_parser() -> argparse.ArgumentParser:
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("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or 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")
@@ -462,7 +402,7 @@ def build_parser() -> argparse.ArgumentParser:
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("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or 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")
@@ -477,7 +417,7 @@ def build_parser() -> argparse.ArgumentParser:
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("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or 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)
@@ -497,42 +437,15 @@ def build_parser() -> argparse.ArgumentParser:
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("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or 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>")
+5 -7
View File
@@ -12,6 +12,8 @@ import pandera.pandas as pandera
from hamilton.data_quality.base import DataValidator, ValidationResult
from hamilton.function_modifiers import check_output_custom
from models.io.contracts import failed_checks
class FrameCheck(DataValidator):
"""A pandera schema as a Hamilton validator whose message carries no data values."""
@@ -31,13 +33,9 @@ class FrameCheck(DataValidator):
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}")
failed = failed_checks(self.schema, dataset)
if failed:
return ValidationResult(False, f"{self.description()} doesn't hold: {failed}")
return ValidationResult(True, f"{self.description()}: holds")
+17 -31
View File
@@ -6,9 +6,8 @@ it's scored but left out of training and evaluation. The predictors are the inde
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
The split, the classifier, the fit, the metrics and the routine records (ML-01a) are `models.steps.model_fitting`'s,
listed with this module in `model.toml`; `missing_data` and `members_left_out` are this scenario's part of them. `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`).
"""
@@ -74,6 +73,21 @@ def labelled_members(index_sample_results: pd.DataFrame, windowed_outcomes: pd.D
return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True)
def members_left_out(windowed_outcomes: pd.DataFrame) -> int:
"""The members scored but not trained on: their outcome isn't known yet."""
return int((~windowed_outcomes["known"]).sum())
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)}
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."""
@@ -91,31 +105,3 @@ class IndexSampleResults(TransformerMixin, BaseEstimator):
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)}
+1 -11
View File
@@ -5,7 +5,7 @@ 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"]
modules = ["models.cacu.cin2_logistic.model", "models.steps.model_fitting"]
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 \
@@ -21,13 +21,3 @@ predictor_columns = ["bethesda", "vph", "vph_16_18"]
# 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
-7
View File
@@ -1,7 +0,0 @@
"""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))
+32 -144
View File
@@ -8,21 +8,11 @@ Each row has a code `c` and an interval `(l, r]` in years since the index visit:
- `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.
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-(t / scale) ** shape * exp(Z @ beta))` the Weibull
survival of the incidence (proportional hazards in `Z`).
"""
from dataclasses import dataclass
import numpy as np
from scipy.interpolate import BSpline
from scipy.optimize import minimize
from scipy.special import expit
@@ -48,71 +38,6 @@ def weibull_survival(t, log_scale, log_shape, beta, Z):
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]
@@ -122,25 +47,24 @@ def split_params(params, n_x, n_z):
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)
def neg_loglik(params, c, l, r, X, Z):
theta, beta, log_scale, log_shape = split_params(params, X.shape[1], Z.shape[1])
pi = prevalence(theta, X)
interval = survival(l, rest, beta, Z, baseline) - survival(r, rest, beta, Z, baseline)
interval = weibull_survival(l, log_scale, log_shape, beta, Z) - weibull_survival(r, log_scale, log_shape, beta, Z)
interval = np.maximum(interval, TINY)
row = np.zeros(len(c))
total = 0.0
prevalent = c == 1
row[prevalent] = np.log(pi[prevalent] + TINY)
total += np.sum(np.log(pi[prevalent] + TINY))
not_prevalent = c == 0
row[not_prevalent] = np.log(1 - pi[not_prevalent] + TINY) + np.log(interval[not_prevalent])
total += np.sum(np.log(1 - pi[not_prevalent] + TINY))
total += np.sum(np.log(interval[not_prevalent]))
unknown = c == UNKNOWN
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
total += np.sum(np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY))
return -np.sum(w * row)
return -total
def numerical_hessian(f, x, step=1e-4):
@@ -160,88 +84,52 @@ def numerical_hessian(f, x, step=1e-4):
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`."""
def fit(c, l, r, X, Z):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors."""
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:]
start = np.zeros(n_x + n_z + 2)
finite = r[np.isfinite(r) & (r > 0)]
start[n_x + n_z] = np.log(np.median(finite)) if len(finite) else 0.0
result = minimize(neg_loglik, start, args=(c, l, r, X, Z), method="BFGS")
theta, beta, log_scale, log_shape = split_params(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)
hessian = numerical_hessian(lambda p: neg_loglik(p, c, l, r, X, Z), 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]
covariance = np.linalg.inv(hessian[np.ix_(free, free)])
variances = np.diag(covariance)
standard_errors[free] = np.sqrt(np.where(variances > 0, variances, np.nan))
except np.linalg.LinAlgError:
pass
found = {
return {
"theta": theta,
"beta": beta,
"baseline": baseline,
"baseline_params": rest,
"log_scale": log_scale,
"log_shape": log_shape,
"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),
"converged": bool(np.max(np.abs(result.jac)) < 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`."""
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence."""
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]
columns = []
for t in years:
survival = weibull_survival(np.full(len(X), float(t)), fitted["log_scale"], fitted["log_shape"],
fitted["beta"], Z)
columns.append(pi + (1 - pi) * (1 - survival))
return np.column_stack(columns)
+112 -192
View File
@@ -1,27 +1,26 @@
"""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:
Each member becomes a code `c` and an interval `(l, r]` in years (`likelihood`'s convention), from the index sample's
results and the biopsies after it:
- 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.
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`;
- otherwise, a known negative baseline (`known_negative` results, or a biopsy in the window below CIN2+): `c = 0`, with
`(0, t_event]` if a later biopsy is CIN2+ and `(follow-up, inf)` if none is;
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]` or `(0, inf)`.
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.
The interval's left end is 0 for a later event: the last negative visit before it isn't looked for.
`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
π logistic in every feature and the incidence S(t) Weibull with proportional hazards in `incidence_features`.
The routine records (ML-01a) are nodes too: `sampling`, `missing_data`, `analytic_method`, `class_balance` and
`output_confidence`, gathered by `routines`. `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 and its lineage through loaders, and registering is the
driver's saver (`models.dags.training`).
"""
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
@@ -35,17 +34,7 @@ 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 {})}
FEATURES = ["abnormal_cytology", "hpv_positive"]
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])),
@@ -59,92 +48,43 @@ 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"])]
def index_results(cohort: pd.DataFrame, index_sample_days: int) -> pd.DataFrame:
"""One row per member, in `pac_id` order: the first Bethesda and HPV results within `index_sample_days` of the
index date, and the features taken from them."""
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "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 = members.merge(wide.reindex(columns=["bethesda", "vph"]), left_on="pac_id", right_index=True, how="left")
members["abnormal_cytology"] = (members["bethesda"].notna() & (members["bethesda"] != "NORMAL")).astype(float)
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)
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"])
@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:
def interval_coded_members(cohort: pd.DataFrame, cohort_cutoff: date, event_grades: list[str],
prevalent_window_months: int, index_sample_days: int, known_negative: dict) -> pd.DataFrame:
"""Each member's features with `c`, `l` and `r` (see the module's docstring)."""
days = _days(cohort)
biopsies = cohort[(cohort["tipo"] == "biopsia") & (days >= 0)].assign(days=days)
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()
first_event = biopsies[biopsies["valor_codigo"].isin(event_grades)].groupby("pac_id")["days"].min()
negative_biopsy = biopsies[~biopsies["valor_codigo"].isin(event_grades) & (biopsies["days"] <= window)]
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)
coded = index_results(cohort, index_sample_days)
results_negative = np.logical_and.reduce([coded[name] == value for name, value in known_negative.items()])
event_days = coded["pac_id"].map(first_event)
follow_up = (pd.Timestamp(cohort_cutoff) - pd.to_datetime(coded["fecha_indice"])).dt.days / DAYS_PER_YEAR
prevalent = event_days <= window
found_free = free_until.notna() & ~prevalent
baseline_negative = results_negative | coded["pac_id"].isin(negative_biopsy["pac_id"])
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["c"] = np.where(prevalent, 1, np.where(baseline_negative, 0, likelihood.UNKNOWN))
coded["l"] = np.where(~prevalent & baseline_negative & ~later_event, follow_up, 0.0)
coded["r"] = np.where(prevalent, 0.0, np.where(later_event, event_days / DAYS_PER_YEAR, np.inf))
return coded
@@ -156,107 +96,37 @@ def train_test_split(interval_coded_members: pd.DataFrame, train_fraction: float
class PrevalenceIncidenceMixture(BaseEstimator):
"""Logistic prevalence and proportional-hazards incidence fitted by maximum likelihood (`likelihood.fit`).
"""Logistic prevalence and Weibull 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):
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",)):
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 _design(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), X.to_numpy(dtype=float)])
return prevalence, X[list(self.incidence_features)].to_numpy(dtype=float)
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())
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
prevalence, incidence = self._design(X)
found = likelihood.fit(y["c"], y["l"], y["r"], prevalence, incidence)
self.theta_, self.beta_ = found["theta"], found["beta"]
self.log_scale_, self.log_shape_ = float(found["log_scale"]), float(found["log_shape"])
self.standard_errors_, self.neg_loglik_, self.converged_ = found["se"], found["neg_loglik"], found["converged"]
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
prevalence, incidence = self._design(X)
fitted = {"theta": self.theta_, "beta": self.beta_, "log_scale": self.log_scale_, "log_shape": self.log_shape_}
return likelihood.cumulative_risk(fitted, prevalence, incidence, self.horizons_years)
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 fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float]) -> PrevalenceIncidenceMixture:
return PrevalenceIncidenceMixture(horizons_years).fit(train_set[FEATURES], 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 test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame) -> np.ndarray:
return fitted_mixture.predict_proba(test_set[FEATURES])
def _status_at(members: pd.DataFrame, horizon: float) -> np.ndarray:
@@ -274,7 +144,7 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
"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
known = ~np.isnan(status)
y, p = status[known], test_cumulative_risks[known, column]
tag = f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
@@ -287,23 +157,73 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
return found
def sampling(interval_coded_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""MUESTREO: every member is used; the split is `models.steps.model_fitting`'s."""
return model_fitting.sampling(interval_coded_members, train_set, test_set, train_fraction)
def missing_data(interval_coded_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many lacked each index result or a known baseline, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {"bethesda": int(frame["bethesda"].isna().sum()), "vph": int(frame["vph"].isna().sum()),
"unknown_baseline": int((frame["c"] == likelihood.UNKNOWN).sum())}
return {"method": "sin Bethesda no cuenta como citología anormal y sin VPH no cuenta como positivo; una línea "
"basal desconocida entra a la verosimilitud como mezcla de prevalente y no prevalente; nadie se "
"excluye",
"members": missing(interval_coded_members), "train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_mixture: PrevalenceIncidenceMixture) -> dict:
"""METODO_ANALITICO: the fitted mixture and its parameters."""
return {"method": "mezcla de prevalencia (logística) e incidencia (Weibull de riesgos proporcionales) por máxima "
"verosimilitud con censura por intervalo",
"estimator": type(fitted_mixture).__name__, "settings": fitted_mixture.get_params(),
"prevalence_coefficients": dict(zip(["intercept", *FEATURES], map(float, fitted_mixture.theta_))),
"incidence_coefficients": dict(zip(fitted_mixture.incidence_features, map(float, fitted_mixture.beta_))),
"log_scale": fitted_mixture.log_scale_, "log_shape": fitted_mixture.log_shape_,
"neg_loglik": float(fitted_mixture.neg_loglik_), "converged": bool(fitted_mixture.converged_)}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""BALANCE_CLASES: how many members have each baseline code (1 prevalent, 0 known negative, -999 unknown)."""
def counts(frame: pd.DataFrame) -> dict:
return {str(code): int(n) for code, n in frame["c"].value_counts().sort_index().items()}
return {"method": "ninguno: los códigos se usan en su proporción observada", "train": counts(train_set),
"test": counts(test_set)}
def output_confidence(metrics: dict, horizons_years: list[float]) -> dict:
"""CONFIANZA_SALIDA: per horizon, among the test members whose status at it is known, the expected risk against
the observed rate."""
names = {"n_known": "n", "expected": "mean_probability", "observed": "observed_rate", "brier": "brier"}
return {"method": "calibración en la prueba por horizonte: riesgo acumulado medio contra frecuencia observada, "
"entre quienes tienen estado conocido en ese horizonte",
"horizons": [{"years": horizon, **{name: metrics[f"{key}_{horizon:g}y"] for key, name in names.items()
if f"{key}_{horizon:g}y" in metrics}} for horizon in horizons_years]}
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 model_fitting.routines(sampling, missing_data, analytic_method, class_balance, output_confidence)
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):
def __init__(self, index_sample_days: int = 30):
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)]
return index_results(X, self.index_sample_days)[FEATURES]
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict,
history: dict) -> Pipeline:
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`."""
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)),
("mixture", fitted_mixture)])
return Pipeline([("index_results", IndexResults(index_sample_days)), ("mixture", fitted_mixture)])
+4 -36
View File
@@ -5,11 +5,10 @@ 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"]
modules = ["models.cacu.cin2_pim.model"]
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 \
modelo de mezcla prevalencia (logística) e incidencia (Weibull) a partir de la citología y el VPH índice. 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.
@@ -21,36 +20,5 @@ train_fraction = 0.7
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"]
# The results that make a baseline known negative without a biopsy.
known_negative = { bethesda = "NORMAL", vph = "NEGATIVO" }
@@ -1,58 +0,0 @@
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"]
@@ -1,33 +0,0 @@
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"]
+5 -4
View File
@@ -1,6 +1,7 @@
"""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.
"""Cohorts for the risk models: each one a TOML definition (FHIR `Group` and `EvidenceVariable`s) and the rule that
builds its frame from the patients' timeline (dbt's view, through Persistance).
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
definition.py a cohort's definition, read from its TOML
build.py from the timeline to `cohorte_armado` and its rows; the stored frame, wide
<project>/<name>.py a cohort's rule (`expression` in its TOML); `<project>/proposals/`: not built yet
"""
+88 -57
View File
@@ -1,79 +1,111 @@
"""Armar una cohorte: de las reglas de dbt a `cohorte_armado`, sus miembros y su atrición.
"""Armar una cohorte: de la línea de tiempo a `cohorte_armado`, sus miembros, su atrición y sus variables.
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.
El armado lee solo la línea de tiempo: la vista de dbt `<proyecto>_linea_de_tiempo`, por la consulta que le dan
(`TimelineRepository.query`), recortada al corte y,
si se pide, a lo que ya estaba cargado (`conocida_hasta`, por el inicio de la carga: sin
versiones de fila es aproximado, ADR-MD-009). La regla de
la cohorte es la función que nombra su definición (`expression`).
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.
Rearmar con la misma definición, 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 un armado nuevo.
`linaje` da las etiquetas `kit.*` que lleva la corrida de MLflow que entrena o
valida con este armado: llaves y huellas, nunca filas ni `pac_id`.
"""
import hashlib
import inspect
import json
from contextlib import nullcontext
from datetime import datetime, timezone
from datetime import date, datetime, timezone
from importlib import import_module
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
from models.cohorts.definition import Definition, json_sha
DECIMALS = 9 # redondeo de los tiempos en la huella del marco
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 timeline_rows(sesion: Session, linea, *, pacientes=None, hasta=None, conocida_hasta=None) -> list[dict]:
"""The timeline as rows, run on `sesion`. `linea` builds its `select` (`TimelineRepository.query`)."""
consulta = linea(patients=pacientes, until=hasta, known_until=conocida_hasta)
return [dict(fila._mapping) for fila in sesion.execute(consulta)]
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_of(
sesion: Session,
definicion: Definition,
inicio: date,
fin: date,
corte: date,
*,
linea,
pacientes: list[int] | None = None,
conocida_hasta: datetime | None = None,
):
"""El marco sin guardarlo: (miembros, atrición). Con `pacientes`, solo los de la lista (evaluar a una paciente)."""
filas = timeline_rows(sesion, linea, pacientes=pacientes, hasta=corte, conocida_hasta=conocida_hasta)
return definicion.function()(filas, definicion.reglas, inicio, fin, corte)
def frame_sha(miembros, variables=()) -> str:
def frame_sha(miembros, definicion: Definition) -> 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)})
nombres = [v.nombre for v in definicion.variables]
def redondo(valor):
return round(valor, DECIMALS) if isinstance(valor, float) else valor
return json_sha([[m.pac_id, m.fecha_indice.isoformat(), *(redondo(m.variables.get(n)) for n in nombres)]
for m in sorted(miembros, key=lambda m: m.pac_id)])
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.
def code_sha(definicion: Definition) -> str:
"""Huella del código que arma el marco (el módulo de su `expression`): hace el papel del SQL."""
modulo = import_module(f"models.cohorts.{definicion.expression.split(':')[0]}")
return json_sha(inspect.getsource(modulo))
def build_of(
sesion: Session,
definicion: Definition,
inicio: date,
fin: date,
corte: date,
*,
cohortes: TablasCohorte,
linea,
conocida_hasta: datetime | None = None,
ahora: datetime | None = None,
):
"""El armado sin guardarlo: la fila de `cohorte_armado` y sus exclusiones, miembros y variables (sin `armado_id`).
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)
miembros, atricion = frame_of(sesion, definicion, inicio, fin, corte, linea=linea,
conocida_hasta=conocida_hasta)
parametros = {"reclutamiento_inicio": inicio.isoformat(), "reclutamiento_fin": fin.isoformat(),
"corte": corte.isoformat(), "conocida_hasta": conocida_hasta and conocida_hasta.isoformat()}
huella = json_sha({"definicion": definicion.definicion_sha, "reglas": definicion.reglas_sha,
"codigo": code_sha(definicion), "parametros": parametros})
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),
url=definicion.url, version=definicion.version, definicion_sha=definicion.definicion_sha,
reglas_sha=definicion.reglas_sha, parametros=json.dumps(parametros, sort_keys=True), datos_as_of=corte,
huella=huella, marco_sha=frame_sha(miembros, definicion), 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)
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=paso, n=n)
for orden, (paso, n) in enumerate(atricion, start=1)]
filas_miembro = [cohortes.CohorteMiembro(pac_id=m.pac_id, fecha_indice=m.fecha_indice,
indice_fuente_tabla=m.indice_fuente_tabla,
indice_fuente_id=m.indice_fuente_id) for m in miembros]
tipos = {v.nombre: v.tipo for v in definicion.variables}
variables = [
cohortes.CohorteVariable(pac_id=m.pac_id, variable=nombre,
**({"valor_codigo": str(valor)} if tipos[nombre] == "codigo"
else {"valor_numerico": float(valor)}))
for m in miembros for nombre, valor in m.variables.items() if valor is not None
]
return armado, exclusiones, filas_miembro, variables
@@ -85,16 +117,15 @@ def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int |
).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`)."""
def read_frame(sesion: Session, armado_id: int, definicion: Definition, *, cohortes: TablasCohorte):
"""El marco guardado, ancho: (columnas, filas), una por miembro. Lo que recibe el modelo."""
nombres = [v.nombre for v in definicion.variables]
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))
+1
View File
@@ -0,0 +1 @@
"""CaCu's cohorts: the surveillance cohort."""
+106
View File
@@ -0,0 +1,106 @@
"""El marco de la cohorte de vigilancia de CaCu, desde la línea de tiempo (`cohorte_vigilancia.toml`).
Las reglas 0.2.0 del kit de campo, sobre las filas de la línea de tiempo de dbt
(`cacu_linea_de_tiempo`) en lugar de SQL sobre tablas. Una fila del marco por miembro, con el desenlace como lo
pide el modelo de mezcla prevalencia–incidencia (Modelo-cacu):
c 1 = evento en la ventana basal; 0 = sin evento basal; -999 = estado basal desconocido
l, r el intervalo (l, r] en que aparece el evento, en años desde la índice.
Con c = 1 valen -999. r nulo = sin evento hasta el corte.
Quién entra:
- la índice es la primera citología de toda la historia, si cae en la ventana;
- se excluye a quien tuvo una biopsia con el desenlace antes de la índice;
- y luego a quien no tiene resultado citológico ni de VPH en la índice.
El desenlace solo se observa al verificar: una biopsia (positiva o negativa) o, con
`negativo_da_l`, un tamizaje completamente negativo posterior (`no_prevalente`).
Con `negativo_confirma_no_prevalente`, ese tamizaje vuelve c = 0 a quien era -999.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
DIAS_POR_ANIO = 365.25
SIN_ESTADO = -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 _by_patient(filas):
pacientes = defaultdict(list)
for fila in filas:
pacientes[fila["pac_id"]].append(fila)
return pacientes
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 CaCu, ya recortada al corte (`hasta=corte`)."""
grados = set(reglas["grados_evento"])
ventana = int(reglas["ventana_basal_dias"])
pap_negativo = set(reglas["no_prevalente"]["pap"])
vph_negativo = set(reglas["no_prevalente"]["vph"])
candidatas = evento_previo = sin_resultado = 0
miembros = []
for pac_id, eventos in sorted(_by_patient(filas).items()):
eventos = [e for e in eventos if e["fecha"] <= corte]
resultado = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "bethesda"}
vph = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "vph"}
tomas = sorted((e for e in eventos if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
if not tomas or not (inicio <= tomas[0]["fecha"] < fin):
continue
indice = tomas[0]
llave = (indice["fuente_tabla"], indice["fuente_id"])
fecha_indice, pap_0, hpv_0 = indice["fecha"], resultado.get(llave), vph.get(llave)
candidatas += 1
biopsias = [(e["fecha"], e["valor_codigo"] in grados) for e in eventos if e["tipo"] == "biopsia"]
if any(positiva and fecha < fecha_indice for fecha, positiva in biopsias):
evento_previo += 1
continue
if pap_0 is None and hpv_0 is None:
sin_resultado += 1
continue
verificaciones = [((fecha - fecha_indice).days, positiva, "biopsia")
for fecha, positiva in biopsias if fecha >= fecha_indice]
if reglas["negativo_da_l"]:
for toma in tomas[1:]:
clave = (toma["fuente_tabla"], toma["fuente_id"])
if toma["fecha"] > fecha_indice and resultado.get(clave) in pap_negativo and vph.get(clave) in vph_negativo:
verificaciones.append(((toma["fecha"] - fecha_indice).days, False, "tamizaje"))
positivas = [d for d, positiva, _ in verificaciones if positiva]
primera_positiva = min(positivas) if positivas else None
negativas = [d for d, positiva, _ in verificaciones
if not positiva and (primera_positiva is None or d < primera_positiva)]
ultima_negativa = max(negativas) if negativas else None
if primera_positiva is not None and primera_positiva <= ventana:
c = 1
elif any(not positiva and tipo == "biopsia" and d <= ventana for d, positiva, tipo in verificaciones):
c = 0
elif pap_0 in pap_negativo and hpv_0 in vph_negativo:
c = 0
elif reglas["negativo_confirma_no_prevalente"] and ultima_negativa is not None:
c = 0
else:
c = SIN_ESTADO
if c == 1:
l = r = SIN_ESTADO
else:
l = (ultima_negativa or 0) / DIAS_POR_ANIO if c == 0 else 0
r = None if primera_positiva is None else primera_positiva / DIAS_POR_ANIO
miembros.append(Member(pac_id, fecha_indice, *llave,
{"c": c, "l": l, "r": r, "pap_0": pap_0, "hpv_0": hpv_0}))
atricion = [("candidatas", candidatas), ("sin evento_previo", candidatas - evento_previo),
("sin sin_resultado", len(miembros))]
return miembros, atricion
+78
View File
@@ -0,0 +1,78 @@
# Cohorte de vigilancia de CaCu: quién entra al modelo de riesgo de CIN2+ y con qué marco.
#
# Definición 0.2.0 del kit de campo (indicadores_kit_0/campo/cohortes/cacu/
# cohorte_vigilancia_reglas.toml): mismas reglas y mismo formato de [group.reglas],
# el que lee Modelo-cacu (`reglas_de_toml`). Lo que cambia es de dónde lee: la línea de
# tiempo del kit (`cdm/linea_de_tiempo.py`), no SQL sobre tablas.
#
# Cambiar una regla es cambiar la definición: se sube `version`.
[group]
url = "cacu/cohorte_vigilancia"
version = "0.2.0"
status = "draft"
membership = "definitional"
title = "Mujeres en vigilancia por citología"
expression = "cacu.surveillance:frame"
indice = "Primera citología de la historia de la paciente, si cae en la ventana de reclutamiento"
desenlace = "cin2_mas"
[[group.characteristic]]
code = "evento_previo"
exclude = true
description = "Biopsia con el desenlace antes de la fecha índice: no está en riesgo de un primer evento"
[[group.characteristic]]
code = "sin_resultado"
exclude = true
description = "La citología índice no tiene resultado citológico ni de VPH: no hay predictores"
[group.reglas]
grados_evento = ["LIEAG", "CIS", "CARCINOMA"]
ventana_basal_dias = 90
negativo_da_l = true
negativo_confirma_no_prevalente = true
colposcopia_negativa = []
[group.reglas.no_prevalente]
pap = ["NORMAL"]
vph = ["NEGATIVO"]
description = "Tamizaje completamente negativo: confirma que no es prevalente"
[group.reglas_estado]
grados_evento = { estado = "vigente", fuente = "Modelo-cacu: desenlace CIN2+; CIN3+ no se puede con este staging (I-K31)" }
no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-08 (traspaso_modelos.md M11)" }
negativo_da_l = { estado = "vigente", fuente = "Usuario, 2026-10-08" }
negativo_confirma_no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-09 (traspaso_modelos.md M13)" }
ventana_basal_dias = { estado = "sin_definir", fuente = "90 es el valor con que se probó la 0.0.1 de campo; por decidir con quien lleva el modelo" }
colposcopia_negativa = { estado = "sin_definir", fuente = "La colposcopia no tiene fuente en staging (I-K32): vacía, no se lee" }
[[evidenceVariable]]
name = "c"
role = "outcome"
tipo = "numero"
title = "Estado basal: 1 prevalente, 0 no prevalente, -999 desconocido"
[[evidenceVariable]]
name = "l"
role = "outcome"
tipo = "numero"
title = "Último momento sin enfermedad, en años desde la índice (-999 si c = 1)"
[[evidenceVariable]]
name = "r"
role = "outcome"
tipo = "numero"
title = "Primer momento con enfermedad, en años desde la índice (sin fila = sin evento al corte)"
[[evidenceVariable]]
name = "pap_0"
role = "covariate"
tipo = "codigo"
title = "Categoría citológica de la citología índice"
[[evidenceVariable]]
name = "hpv_0"
role = "covariate"
tipo = "codigo"
title = "Resultado de VPH de la misma muestra"
+82
View File
@@ -0,0 +1,82 @@
"""La definición de una cohorte, de su TOML: FHIR `Group` definicional más sus `EvidenceVariable`.
Igual que un Measure: la definición es un archivo (`<proyecto>/<nombre>.toml`),
las reglas clínicas son datos (`[group.reglas]`) y la función que arma el marco se
nombra con `expression` (`modulo:funcion`, relativo a `models.cohorts`).
"""
import hashlib
import json
import tomllib
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
ROOT = Path(__file__).resolve().parent # `<proyecto>/<nombre>.toml`, next to its rule module
@dataclass(frozen=True)
class Variable:
nombre: str
rol: str # outcome o covariate
tipo: str # numero o codigo
titulo: str
@dataclass(frozen=True)
class Definition:
url: str
version: str
titulo: str
expression: str
desenlace: str
reglas: dict
variables: tuple[Variable, ...]
definicion_sha: str # sha256 del TOML
@property
def reglas_sha(self) -> str:
return json_sha(self.reglas)
def function(self):
"""La función que arma el marco: `funcion(filas_de_linea, reglas, inicio, fin, corte)`."""
return function_of(self.expression)
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 cohort_path(proyecto: str, nombre: str, *, propuesta: bool = False) -> Path:
"""A cohort's TOML. `propuesta`: from `<proyecto>/proposals/`, which the cycle doesn't build."""
return ROOT / proyecto / ("proposals" if propuesta else "") / f"{nombre}.toml"
def read_definition(ruta: Path) -> Definition:
texto = ruta.read_text(encoding="utf-8")
doc = tomllib.loads(texto)
g = doc["group"]
reglas = dict(g["reglas"])
if "no_prevalente" in reglas: # regla de CaCu: su `description` es texto, no regla
reglas["no_prevalente"] = {k: v for k, v in reglas["no_prevalente"].items() if k != "description"}
variables = tuple(Variable(v["name"], v["role"], v["tipo"], v["title"]) for v in doc["evidenceVariable"])
nombres = [v.nombre for v in variables]
if len(set(nombres)) != len(nombres):
raise ValueError(f"{g['url']}: variables repetidas.")
return Definition(
url=g["url"], version=g["version"], titulo=g["title"], expression=g["expression"],
desenlace=g["desenlace"], reglas=reglas, variables=variables,
definicion_sha=hashlib.sha256(texto.encode("utf-8")).hexdigest(),
)
def function_of(expresion: str):
"""The function of `module:function`, relative to `models.cohorts`. Fails if the module doesn't define it."""
modulo, nombre = expresion.split(":")
function = getattr(import_module(f"models.cohorts.{modulo}"), nombre, None)
if not callable(function):
raise ValueError(f"{modulo} debe definir la función {nombre}.")
return function
+5 -4
View File
@@ -1,8 +1,9 @@
"""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
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order.
A build with no rows, or with nulls where a member, a date or an event goes, is refused first (`storage.model_frame`).
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.
"""
@@ -19,7 +20,7 @@ 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
from models.io.storage import CohortSource, model_frame, read_metadata, write_once
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
@@ -48,7 +49,7 @@ def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
cohort = source.reference()
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
cohort_frame = source.frame()
cohort_frame = model_frame(source)
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)
+7 -9
View File
@@ -4,7 +4,8 @@ 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.
scikit-learn estimator that takes the long frame), `metrics` and, for a version that can be promoted, `routines` (what each
routine around training did, by kind, ML-01a), 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
@@ -32,6 +33,8 @@ from models.io.storage import CohortSource
from models.io.tracking import TrainingRun
REGISTERED_MODEL = "registered_model"
# A scenario without this node registers a version that ML-01a keeps out of production.
ROUTINES = "routines"
# The logger that prints a failing node's inputs (`hamilton.execution.graph_functions.create_error_message`).
HAMILTON_NODE_ERRORS = "hamilton.execution.graph_functions"
@@ -78,10 +81,6 @@ def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Dri
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()
@@ -117,11 +116,10 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") ->
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))
(("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),
produced = ["fitted_model", "metrics", *(v.name for v in plain.list_available_variables() if v.name == ROUTINES)]
saver = to.registered_model(id=REGISTERED_MODEL, dependencies=produced,
combine=base.DictResult(), run=run, description=scenario.description,
hyperparameters={**expected_params(scenario, source), **scenario.config},
requirements=list(scenario.requirements))
-236
View File
@@ -1,236 +0,0 @@
"""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
+11 -10
View File
@@ -6,11 +6,11 @@ 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 frame is checked against `MODEL_COHORT` whatever its source: a build with no rows, or with a member, a date or
an event missing, stops the run before any node reads it.
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics"], ...)`: 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.
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
@@ -28,12 +28,13 @@ 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.storage import model_frame
from models.io.tracking import TrainingRun, pinned
@dataclasses.dataclass
class CohortSourceLoader(DataLoader):
"""A build's long frame, from whatever source reads it."""
"""A build's long frame, from whatever source reads it, if a model may read it (`storage.model_frame`)."""
source: Any
@@ -46,7 +47,7 @@ class CohortSourceLoader(DataLoader):
return "cohort_source"
def load_data(self, type_: type) -> tuple[pd.DataFrame, dict[str, Any]]:
frame = self.source.frame()
frame = model_frame(self.source)
return frame, {"source": type(self.source).__name__, "rows": len(frame)}
@@ -93,9 +94,9 @@ def _numbers(metrics: dict) -> dict[str, float]:
@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`."""
"""Records each of `routines` (ML-01a) in `run`, logs `fitted_model` 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 = ""
+26 -7
View File
@@ -5,7 +5,8 @@
- 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 values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`), and what a model may read
(`MODEL_COHORT`): a build's rows, and at least one.
- 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
@@ -44,6 +45,12 @@ COHORT_FRAME = pandera.DataFrameSchema(
error="a member has more than one index date"),
name="cohort build")
# A build with no rows is a valid file, and nothing a model can train on or score.
MODEL_COHORT = pandera.DataFrameSchema(
COHORT_FRAME.columns,
checks=[*COHORT_FRAME.checks, pandera.Check(lambda frame: len(frame) > 0, error="the build has no rows")],
name="cohort build a model reads")
ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False),
@@ -51,7 +58,7 @@ ESTIMATE_FRAME = pandera.DataFrameSchema(
"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"
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
class CohortFileError(ValueError):
@@ -59,6 +66,10 @@ class CohortFileError(ValueError):
`COHORT_FRAME`."""
class UnusableCohortError(ValueError):
"""The rows a source gave a model break `MODEL_COHORT`: none at all, or a member, date or event missing."""
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."""
@@ -73,6 +84,18 @@ def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: typ
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
def failed_checks(schema: pandera.DataFrameSchema, frame: pd.DataFrame) -> str | None:
"""The checks `frame` fails, each with its column and how many rows failed it, never a value; `None` when it
satisfies `schema`."""
try:
schema.validate(frame, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases.fillna({"column": "(frame)"})
counts = cases.groupby(["column", "check"], dropna=False).size()
return "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
return None
class CohortDefinitionError(ValueError):
"""The cohort's queries or their results don't follow the structure a build chains."""
@@ -93,9 +116,6 @@ class CohortQueries:
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)
@@ -110,8 +130,7 @@ 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
horizonte_anios: float # years from the index date; 0 = prevalent
probabilidad: float # 0 to 1
ic_bajo: float | None = None
ic_alto: float | None = None
-1
View File
@@ -11,7 +11,6 @@ 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"
@@ -20,7 +20,7 @@ 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.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"
@@ -5,7 +5,7 @@ A job is one folder named after the notebook's run, holding everything the noteb
(`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`).
(`models.io.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
@@ -41,7 +41,7 @@ STORE_FILE, STORE_ARTIFACTS, PAGE_FILE, RESULT_FILE = "mlflow.db", "artefactos",
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,
PASSED_ENV = ("PATH", "LANG", "LC_ALL", "TZ", "SYSTEMROOT", 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://"
+3 -23
View File
@@ -30,20 +30,11 @@ 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.lineage import ARMADO_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)
@@ -232,27 +223,16 @@ class ModelRegistry:
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,
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", "")),
+18 -19
View File
@@ -30,8 +30,9 @@ 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.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
CohortFileError, CohortQueries, ExclusionRule, MODEL_COHORT, UnusableCohortError,
check_frame, failed_checks)
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
@@ -188,16 +189,14 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
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]
if not exclusions:
raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries")
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]:
for node in exclusions:
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"]
@@ -206,17 +205,7 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
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}/")})
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
@@ -307,6 +296,17 @@ class CohortSource(Protocol):
def reference(self) -> dict[str, str]: ...
def model_frame(source: CohortSource) -> pd.DataFrame:
"""The source's frame, if a model may read it (`MODEL_COHORT`): a build with no rows, or with a member, a date or
an event missing, is refused whether it came from the database or a file. The refusal names the failed checks and
how many rows failed each, never a value."""
frame = source.frame()
failed = failed_checks(MODEL_COHORT, frame)
if failed:
raise UnusableCohortError(f"{type(source).__name__} isn't a {MODEL_COHORT.name}: {failed}")
return frame
@dataclass
class KitBuild:
"""Kit build `build_id` of `domain`, read from its database. `cohorts` and `timeline` default to the domain's
@@ -354,7 +354,6 @@ class KitBuild:
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]:
+2 -2
View File
@@ -1,4 +1,4 @@
"""What a notebook run from the platform works with (`models.reports.experiment`): the cohort build's file it was
"""What a notebook run from the platform works with (`models.pipelines.experiment`): the cohort build's file it was
run on and, if one was chosen, a registered model version.
from models.notebook import experiment
@@ -62,7 +62,7 @@ class Experiment:
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`)."""
is copied into the real one, as DEV, when the notebook ends (`models.io.notebook_import`)."""
from models.io.storage import cohort_reference, file_sha256
from models.io.tracking import TrainingRun
-4
View File
@@ -29,10 +29,6 @@ def _fresh(function):
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,
@@ -1,15 +1,15 @@
"""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
content hash, the build's file (`models.io.storage.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
The notebook runs in a job folder of its own (`models.io.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
(`models.io.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.
"""
@@ -25,10 +25,9 @@ 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, \
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, DOMAINS, code_version, registered_name
from models.io.notebook_import import import_job
from models.io.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
+4 -7
View File
@@ -1,9 +1,6 @@
"""Reports: notebooks run on a build's file, rendered and kept in MLflow, using `models.io` to read the build and record
the run.
"""Reports: notebooks run on a build's file, rendered with Quarto 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
rendering.py a notebook to a self-contained HTML page with Quarto, and what identifies its content
eda.py the exploratory notebook of a scenario, as a report run
"""
+3 -3
View File
@@ -1,9 +1,9 @@
"""Runs a notebook, renders it to a self-contained HTML page, and identifies its content by its cells' sources, without
outputs or execution counts.
"""Runs a notebook and renders it to a self-contained HTML page.
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.
picks one; otherwise Quarto when it's installed, else Jupyter. A notebook's content is identified by its cells' sources, without outputs or
execution counts.
`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
-195
View File
@@ -1,195 +0,0 @@
"""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))}
+40 -17
View File
@@ -5,9 +5,10 @@ the outcome) and the driver passes both modules to `with_modules`, with `predict
`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.
`routines` gathers what each routine around training did (ML-01a), by the kind it's stored under: `sampling`,
`analytic_method`, `class_balance` and `output_confidence` are here; `missing_data` is the scenario's, since only it
knows what a missing predictor is. A scenario that leaves members out before `labelled_members` says how many with a
`members_left_out` node.
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.
@@ -91,31 +92,53 @@ def metrics(auc: float, brier_score: float, train_set: pd.DataFrame, test_set: p
"mean_probability_test": mean_probability_test}
def _index_dates(frame: pd.DataFrame, column: str) -> dict:
if frame.empty:
return {"n": 0}
return {"n": len(frame), "first_index_date": str(frame[column].min()), "last_index_date": str(frame[column].max())}
def sampling(labelled_members: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame, train_fraction: float,
members_left_out: int = 0, split_order: tuple = SPLIT_ORDER) -> dict:
"""MUESTREO: who could be used, and how they were split."""
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
"train_fraction": train_fraction, "members": len(labelled_members) + members_left_out,
"left_out_unknown_outcome": members_left_out, "train": _index_dates(train_set, split_order[0]),
"test": _index_dates(test_set, split_order[0])}
def analytic_method(fitted_pipeline: Pipeline) -> dict:
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
"""METODO_ANALITICO: the fitted classifier, its settings and, when it has them, 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])))}
found = {"method": f"{type(classifier).__name__} sobre los predictores codificados one-hot",
"estimator": type(classifier).__name__, "settings": classifier.get_params()}
if hasattr(classifier, "coef_"):
features = fitted_pipeline.named_steps["encode"].get_feature_names_out()
found["intercept"] = float(classifier.intercept_[0])
found["coefficients"] = dict(zip(map(str, features), map(float, classifier.coef_[0])))
return found
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame, fitted_pipeline: Pipeline) -> dict:
def _class_counts(frame: pd.DataFrame, column: str) -> dict:
return {str(value): int(n) for value, n in frame[column].value_counts().sort_index().items()}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame, fitted_pipeline: Pipeline,
target_column: str = "y") -> dict:
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
weight = fitted_pipeline.named_steps["classify"].class_weight
weight = getattr(fitted_pipeline.named_steps["classify"], "class_weight", None)
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()}}
"train": _class_counts(train_set, target_column), "test": _class_counts(test_set, target_column)}
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."""
def output_confidence(test_set: pd.DataFrame, test_probabilities: pd.Series, brier_score: float,
target_column: str = "y", calibration_bins: int = 10) -> dict:
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by quantiles."""
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(
table = pd.DataFrame({"p": test_probabilities, "y": test_set[target_column]}).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)),
"brier": brier_score,
"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()]}
+4 -5
View File
@@ -1,5 +1,4 @@
"""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."""
"""From an estimate's rows to the risks a batch stores: `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`."""
import pandas as pd
@@ -10,6 +9,6 @@ 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"])]
return [(int(pac_id), float(horizon), float(probability), None, None)
for pac_id, horizon, probability in zip(estimate["pac_id"], estimate["horizonte_anios"],
estimate["probabilidad"])]
-1
View File
@@ -1 +0,0 @@
"""TEA's models: the EEG analysis (`eeg`)."""
-6
View File
@@ -1,6 +0,0 @@
"""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`).
"""
-273
View File
@@ -1,273 +0,0 @@
"""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))
-118
View File
@@ -1,118 +0,0 @@
"""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)
-205
View File
@@ -1,205 +0,0 @@
"""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
-61
View File
@@ -1,61 +0,0 @@
"""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
-52
View File
@@ -1,52 +0,0 @@
# 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"
-62
View File
@@ -1,62 +0,0 @@
"""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
-83
View File
@@ -1,83 +0,0 @@
"""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)
-230
View File
@@ -1,230 +0,0 @@
"""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})
+2 -2
View File
@@ -39,7 +39,7 @@ class CacuStandIn:
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"))
i_pac, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "pap_0", "hpv_0"))
risks = []
for row in rows:
p = CACU_RULE["base"]
@@ -48,5 +48,5 @@ class CacuStandIn:
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]
risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons]
return risks
+2 -6
View File
@@ -2,7 +2,7 @@
name = "models"
version = "0.1.0"
description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening models."
requires-python = ">=3.12"
requires-python = ">=3.11"
dependencies = [
"persistance",
"extraction",
@@ -15,13 +15,10 @@ dependencies = [
"scikit-learn>=1.4",
# The values of the cohort and estimate files (`models.io.contracts`).
"pandera>=0.20",
"tea",
]
[project.optional-dependencies]
# 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).
# Running uploaded notebooks without Quarto (models.reports.rendering.JupyterRenderer, models.pipelines.experiment).
notebooks = [
"nbclient>=0.10",
"nbconvert>=7.16",
@@ -31,7 +28,6 @@ notebooks = [
[tool.uv.sources]
persistance = { path = "../Persistance", editable = true }
extraction = { path = "../Extraction", editable = true }
tea = { path = "libs/tea", editable = true }
[build-system]
requires = ["hatchling"]
+14 -50
View File
@@ -151,13 +151,13 @@ def test_split_trains_on_the_oldest_index_dates(cohort_frame):
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
"""Pins down the driver's external inputs: the loaders' `cohort` 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"}
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"}
assert optional == {"calibration_bins", "classifier", "max_iter", "split_order", "target_column"}
def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
@@ -168,7 +168,7 @@ def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
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})
inputs={"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)
@@ -197,8 +197,8 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame
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."""
counts that add up to the split. Fails if the saver stops logging the `routines` node, a routine node leaves the
graph, or one 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"}
@@ -297,30 +297,6 @@ 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."""
@@ -340,17 +316,11 @@ def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path
registry.resolve("cacu", "cin2_logistic")
def test_repeating_every_step_changes_nothing(exported, cacu_db, mlflow_tracking, tmp_path, capsys):
def test_repeating_every_step_changes_nothing(exported, 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()
steps = [*RUN, "--train", "--promote", "--estimate", "--output", str(output)]
assert main(steps) == 0
written = output.stat().st_mtime_ns
capsys.readouterr()
@@ -387,17 +357,14 @@ def test_another_models_version_trains_again(exported, mlflow_tracking, monkeypa
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."""
`--estimate` skips because the file exists."""
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 main([*RUN, "--promote", "--version", "1", "--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 main([*RUN, "--promote", "--version", "2", "--estimate", "--output", str(output)]) == 0
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2"
@@ -453,14 +420,11 @@ def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported,
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."""
dbt file."""
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
assert main(["run", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "1", "--environment", "prod",
"--train", "--promote", "--estimate", "--output", str(output)]) == 0
tags = registry.get("cacu", "cin2_logistic", "1").tags
assert tags["environment"] == "PROD" and tags["cohort.build"] == "1"
+47 -173
View File
@@ -1,9 +1,9 @@
"""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
"""What this module covers: `models.cacu.cin2_pim`: how a member's index results and biopsies become a code and an
interval, 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
prevalent or a later CIN2+ biopsy); `cohort_file`, that frame as kit build 3's file; `mlflow_tracking` and
`predict_without_repository` (conftest).
"""
@@ -28,37 +28,23 @@ SCENARIO = training.Scenario.load("cacu", "cin2_pim")
CONFIG = SCENARIO.config
def _row(pac_id, index, days, tipo, valor=None, sample=None):
def _row(pac_id, index, days, tipo, valor=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}"}
"fuente_id": 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)]
def _member(pac_id, index, bethesda, vph, biopsies=()):
rows = [_row(pac_id, index, 0, "citologia"), _row(pac_id, index, 7, "bethesda", bethesda),
_row(pac_id, index, 7, "vph", vph)]
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")
return model.interval_coded_members(frame, CUTOFF, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
CONFIG["index_sample_days"], CONFIG["known_negative"]).set_index("pac_id")
@pytest.fixture
@@ -73,10 +59,9 @@ def cohort_frame():
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)])
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", [(int(rng.integers(400, 800)), "LIEAG")])
else:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO", visits=[(int(rng.integers(300, 900)), *COTEST_NEGATIVE)])
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
@@ -89,79 +74,33 @@ def cohort_file(cohort_frame, tmp_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_each_member_gets_its_code_and_interval():
"""Pins down the coding: a CIN2+ biopsy in the window is prevalent; a known negative baseline with a later CIN2+
biopsy is incident in `(0, t]`; a known negative without one is censored at its follow-up; an abnormal sample with
no biopsy is unknown in `(0, inf)`; a negative biopsy in the window makes the baseline known. Fails if any case
gets another code, which changes what the likelihood counts."""
index = date(2025, 1, 1)
coded = _coded(_member(1, index, "LIEAG", "POSITIVO", [(30, "LIEAG")])
+ _member(2, index, "NORMAL", "NEGATIVO", [(730, "CIS")])
+ _member(3, index, "NORMAL", "NEGATIVO")
+ _member(4, index, "ASC-US", "POSITIVO")
+ _member(5, index, "ASC-US", "POSITIVO", [(60, "NEGATIVO")]))
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)
assert coded["c"].tolist() == [1, 0, 0, -999, 0]
assert coded.loc[2, "r"] == pytest.approx(730 / 365.25) and coded.loc[2, "l"] == 0.0
assert coded.loc[3, "l"] == pytest.approx((CUTOFF - index).days / 365.25) and np.isinf(coded.loc[3, "r"])
assert (coded.loc[4, "l"], coded.loc[4, "r"]) == (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,
"""Pins down the driver's external inputs: the loaders' `cohort` 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(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
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "index_sample_days",
"known_negative", "prevalent_window_months", "train_fraction"}
assert optional == set()
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
@@ -169,7 +108,7 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
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"]
["metrics"], inputs={"cohort": cohort_frame, "cohort_lineage": {"datos_as_of": CUTOFF.isoformat()}})["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)
@@ -177,6 +116,20 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
assert found["expected_0y"] == pytest.approx(found["observed_0y"], abs=0.05)
def test_the_dataflow_records_each_routine(cohort_frame):
"""ML-01a: the graph gives the five routine records, in counts that add up to the split and one calibration entry
per horizon. Fails if a routine node leaves the graph, so a trained version could never be promoted, or records
something other than this fit's own numbers."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["routines"], inputs={"cohort": cohort_frame, "cohort_lineage": {"datos_as_of": CUTOFF.isoformat()}})["routines"]
assert set(found) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
assert found["MUESTREO"]["train"]["n"] == 210 and found["MUESTREO"]["test"]["n"] == 90
assert sum(found["BALANCE_CLASES"]["train"].values()) == 210
assert [h["years"] for h in found["CONFIANZA_SALIDA"]["horizons"]] == CONFIG["horizons_years"]
assert set(found["METODO_ANALITICO"]["prevalence_coefficients"]) == {"intercept", "abnormal_cytology", "hpv_positive"}
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
@@ -199,82 +152,3 @@ def test_training_and_estimating_score_every_member_at_every_horizon(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"
-62
View File
@@ -55,65 +55,3 @@ def test_cumulative_risk_starts_at_prevalence():
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)
-7
View File
@@ -33,13 +33,6 @@ 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`."""
+34 -2
View File
@@ -1,5 +1,6 @@
"""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
graph from any cohort source and refuse a build with no rows or with nulls where a member, a date or an event goes,
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.
@@ -24,7 +25,7 @@ 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.contracts import COHORT_SCHEMA, UnusableCohortError
from models.io.registry import registry
from models.io.storage import CohortFile
@@ -124,6 +125,37 @@ def test_the_loaders_feed_the_graph_from_a_source(cohort_file):
assert dr.execute(["members", "build_number"]) == {"members": 3, "build_number": "5"}
class _FrameSource:
"""A source that gives the frame it holds, as a database read would, without `read_cohort`'s checks."""
def __init__(self, frame):
self._frame = frame
def frame(self):
return self._frame
@pytest.mark.parametrize("change, check", [
(lambda frame: frame.iloc[0:0], "the build has no rows"),
(lambda frame: frame.assign(fecha_indice=None), "fecha_indice: not_nullable failed 3 time"),
(lambda frame: frame.assign(tipo=[None, "citologia", "citologia"]), "tipo: not_nullable failed 1 time"),
])
def test_a_build_with_no_rows_or_with_nulls_never_reaches_a_node(cohort_file, change, check):
"""Pins down: the `cohort_source` loader refuses an empty frame, and one with a null index date or event type, from
a source that doesn't check its own rows, naming the check and the count but no member. Fails if the loader stops
validating `MODEL_COHORT`, the schema loses its no-rows check, or the refusal starts quoting values."""
def members(cohort: pd.DataFrame) -> int:
return len(cohort)
broken = _FrameSource(change(CohortFile(cohort_file).frame()))
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(members)).with_materializers(
from_.cohort_source(target="cohort", source=broken)).build()
with pytest.raises(UnusableCohortError, match=check) as refused:
dr.execute(["members"])
assert not any(str(member) in str(refused.value) for member in MEMBERS)
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
+4 -5
View File
@@ -5,7 +5,6 @@ Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that mee
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
"""
from datetime import date
from models.io.contracts import Provenance, Risk, RiskEstimator
@@ -19,8 +18,8 @@ class ConstantEstimator:
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)]
i_pac = columns.index("pac_id")
return [Risk(row[i_pac], h, 0.1) for row in rows for h in (0.0, 1.0)]
class Incomplete:
@@ -58,7 +57,7 @@ def test_a_risk_keeps_the_column_names_and_its_interval_is_optional():
Fails if a field is renamed or reordered, or the interval becomes required.
"""
risk = Risk(1, date(2025, 1, 1), 0.0, 0.25)
risk = Risk(1, 0.0, 0.25)
assert Risk._fields == ("pac_id", "fecha_indice", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto")
assert Risk._fields == ("pac_id", "horizonte_anios", "probabilidad", "ic_bajo", "ic_alto")
assert (risk.ic_bajo, risk.ic_alto) == (None, None)
@@ -1,6 +1,6 @@
"""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
"""What this module covers: notebooks run on a cohort build's file as MLflow runs (`models.pipelines.experiment`), the
job folder and its executors (`models.io.notebook_jobs`), the import of what a notebook trained
(`models.io.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.
@@ -21,7 +21,7 @@ import pytest
from models.io.contracts import COHORT_SCHEMA
from models.io.registry import registry
from models.reports import experiment
from models.pipelines import experiment
def _notebook(*sources: str) -> dict:
@@ -164,7 +164,7 @@ def test_files_a_notebook_links_outside_its_job_are_never_read(jupyter, cohort_f
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
from models.io.notebook_jobs import JobError, read_job_file
job = tmp_path / "job"
job.mkdir()
+4 -4
View File
@@ -50,14 +50,14 @@ def test_the_oldest_members_train_and_the_newest_test(labelled):
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
def test_the_driver_needs_only_the_members_the_predictors_and_the_fraction(labelled):
"""Pins down the dataflow's external inputs: the three required ones and `missing_data`, the routine record only
a scenario can write; `target_column`, `split_order`, `max_iter`, `calibration_bins` and `members_left_out` 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"}
assert required == {"labelled_members", "missing_data", "predictor_columns", "train_fraction"}
def _has_default(variable) -> bool:
-126
View File
@@ -1,126 +0,0 @@
"""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()
-140
View File
@@ -1,140 +0,0 @@
"""What this module covers: the age an EEG is analysed at. The `tea` library reads it from the EDF header (recording
start minus birth date, `header_age_months`) when no age is passed, and `measure` prefers it over the age the
patient's rows give.
Fixtures: `dated` and `undated`, paths to one-minute synthetic studies (`synth_edf.py`); `dated`'s header says the
child was born 2023-06-01 and recorded 2025-06-01 (24.0 months), `undated`'s has neither date. `measured_dated` is the
four-minute dated study measured once, with 27.5 months from the rows.
"""
import logging
from datetime import date
import pytest
from synth_edf import edf_bytes
from models.tea.eeg.analyze import measure, study_age
from models.tea.eeg.settings import settings
BORN, RECORDED = date(2023, 6, 1), date(2025, 6, 1)
HEADER_AGE = 24.0
ROW_AGE = 27.5
def _write(tmp_path, name: str, **header) -> str:
path = tmp_path / f"{name}.edf"
path.write_bytes(edf_bytes(minutes=1, **header))
return str(path)
@pytest.fixture
def dated(tmp_path):
"""A study whose header has the birth date and the recording date."""
return _write(tmp_path, "dated", birthdate=BORN, startdate=RECORDED)
@pytest.fixture
def undated(tmp_path):
"""A study whose header has neither date (`X` and the 01.01.85 placeholder)."""
return _write(tmp_path, "undated")
@pytest.fixture(scope="module")
def measured_dated():
"""The dated study, four minutes long so it passes validation, measured with the rows' 27.5 months."""
return measure("dated", edf_bytes(minutes=4, birthdate=BORN, startdate=RECORDED), ROW_AGE, settings())
def test_header_age_is_start_minus_birth_in_months(dated):
"""Pins down: the header age is (start - birth) days / 30.4375, to one decimal, like `eeg_analysis.age_months`.
Fails if `header_age_months` reads another header field, uses another month length or stops rounding, which
would put the header age and the rows' age on different scales.
"""
from tea.contracts import header_age_months
assert header_age_months(dated) == HEADER_AGE
assert header_age_months(dated, days_per_month=30.0) == round(731 / 30.0, 1)
@pytest.mark.parametrize("header", [
{},
{"startdate": RECORDED},
{"birthdate": BORN},
{"birthdate": date(2025, 7, 1), "startdate": RECORDED},
{"birthdate": date(2000, 1, 1), "startdate": RECORDED},
], ids=["no-dates", "no-birth", "placeholder-start", "born-after-start", "over-18-years"])
def test_header_without_a_usable_age_gives_none(tmp_path, header):
"""Pins down: a missing birth date, the 01.01.85 placeholder start, a birth after the start and an age over 216
months all give no header age.
Fails if `header_age_months` stops checking any of them: anonymised or mis-clocked files would then be analysed
at a nonsense age instead of the rows' age.
"""
from tea.contracts import header_age_months
assert header_age_months(_write(tmp_path, "study", **header)) is None
def test_recording_takes_the_header_age_unless_one_is_passed(dated):
"""Pins down: `Recording.from_edf` without an age carries the header's, and an explicit age still wins.
Fails if `from_edf` stops falling back to the header, or lets the header override an age the caller passed
(reference cohorts pass their manifest ages).
"""
from tea.contracts import Recording
assert Recording.from_edf(dated).age_months == HEADER_AGE
assert Recording.from_edf(dated, age_months=ROW_AGE).age_months == ROW_AGE
def test_preprocessing_takes_the_header_age_unless_one_is_passed(dated, undated):
"""Pins down: modern preprocessing without an age carries the header's in `Preprocessed.age_months`, keeps an
explicit one, and has none for a header without dates.
Fails if `Preprocessing.run` stops falling back to the header, which would leave the biomarkers' age baselines
without an age for every caller that doesn't pass one.
"""
from tea.preprocessing import DIRECTOR_CLUSTER, Preprocessing
plan = DIRECTOR_CLUSTER.to_dict()
assert Preprocessing().run(dated, plan).age_months == HEADER_AGE
assert Preprocessing().run(dated, plan, age_months=ROW_AGE).age_months == ROW_AGE
assert Preprocessing().run(undated, plan).age_months is None
def test_study_age_prefers_the_header_and_logs_a_disagreement(dated, caplog):
"""Pins down: with both ages, `study_age` returns the header's and logs that the rows disagree by more than a
month.
Fails if the rows' age wins again, or if a disagreement stops being logged.
"""
with caplog.at_level(logging.WARNING, logger="models.tea.eeg.analyze"):
assert study_age("e1", dated, ROW_AGE, 30.4375) == HEADER_AGE
assert "e1" in caplog.text and "24.0" in caplog.text and "27.5" in caplog.text
caplog.clear()
with caplog.at_level(logging.WARNING, logger="models.tea.eeg.analyze"):
assert study_age("e1", dated, 24.3, 30.4375) == HEADER_AGE
assert caplog.text == ""
def test_study_age_falls_back_to_the_rows(undated, tmp_path):
"""Pins down: a header without dates, or a file that isn't an EDF, gives the rows' age, which may be None.
Fails if `study_age` returns None, or raises, when the header has no age: EEGs from hospitals that anonymise
their files would lose the age the platform has.
"""
broken = tmp_path / "broken.edf"
broken.write_bytes(b"not an edf")
assert study_age("e1", undated, ROW_AGE, 30.4375) == ROW_AGE
assert study_age("e1", undated, None, 30.4375) is None
assert study_age("e1", broken, ROW_AGE, 30.4375) == ROW_AGE
def test_measure_analyses_and_reports_the_header_age(measured_dated):
"""Pins down: `measure` on a study whose header has an age reports that age, not the rows', on a valid
analysis; that is what `eeg_edad_meses` and the baseline deviations are written from.
Fails if `measure` reports the argument instead of the age it analysed at, or stops reading the header.
"""
m = measured_dated
assert (m.valid, m.error, m.age_months) == (1, None, HEADER_AGE)
-117
View File
@@ -1,117 +0,0 @@
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
library.
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
posterior channels flat; and bytes that are not an EDF.
"""
import pytest
from synth_edf import edf_bytes
from core.tea.enums import CriterioEeg, ELECTRODOS_10_20, MetricaEeg
from models.eeg_analysis import checked_settings
from models.tea.eeg.analyze import criterion_code, measure, pipeline
from models.tea.eeg.settings import scenario_of, settings
FLAT = ["C3", "C4", "Cz", "P3", "P4", "Pz", "O1", "O2"]
@pytest.fixture(scope="module")
def measured():
"""The three studies' measurements, keyed `clean`, `flat` and `broken`; the clean child is 27.5 months old."""
s = settings()
return {
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
"flat": measure("flat", edf_bytes(minutes=4, bad={"flat": FLAT}, seed=1), 27.5, s),
"broken": measure("broken", b"not an edf", None, s),
}
def test_every_metric_is_a_feature_of_its_biomarker():
"""Pins down: each `MetricaEeg` code maps to a feature the library's biomarker actually measures.
Fails if `model.toml` names a feature, biomarker or electrode prefix the library doesn't have (a renamed feature
would otherwise leave the metric null on every EEG), or leaves a `MetricaEeg` code unmapped.
"""
s = checked_settings()
pipe = pipeline(s)
assert sorted(m.code for m in s.metrics) == sorted(c.value for c in MetricaEeg)
for m in s.metrics:
assert m.feature in pipe.module(m.biomarker).features, m.code
if m.electrodes:
electrodes = [f.removeprefix(m.electrode_prefix) for f in pipe.module(m.electrodes).features
if f.startswith(m.electrode_prefix)]
assert electrodes and set(electrodes) <= set(ELECTRODOS_10_20), m.code
def test_each_baseline_has_its_own_scenario_per_sleep_stage():
"""Pins down: a biomarker's baseline is registered per sleep stage, as `eeg-<biomarker>[-<stage>]`.
Fails if the two stages' spindles share one registered model, or the naming changes without the trained models.
"""
assert scenario_of("spindle_topography", "N2") == "eeg-spindle-topography-n2"
assert scenario_of("posterior_rhythm", None) == "eeg-posterior-rhythm"
assert len({m.scenario for m in settings().metrics}) == len(settings().metrics)
def test_a_clean_study_is_valid_and_has_every_metric(measured):
"""Pins down: a clean study gets the verdict, the study-wide checks and one value per metric, with the
spindles' value per electrode, the sleep it contains and the age it was measured at.
Fails if `measure` stops running the processes the biomarkers need, drops a metric, or loses the electrodes.
"""
m = measured["clean"]
assert (m.valid, m.level, m.error, m.asleep, m.age_months) == (1, "completo", None, 1, 27.5)
assert {c.code for c in m.checks} >= {"clean-windows", "internal-coverage", "usable-scalp", "triage-level"}
assert not any(c.abnormal for c in m.checks)
values = {v.code: v for v in m.metrics}
assert set(values) == {c.value for c in MetricaEeg}
assert values["RITMO_POSTERIOR"].value == pytest.approx(7.0, abs=0.5)
assert values["HUSOS_SUENO_N2"].value > 0
assert set(values["HUSOS_SUENO_N2"].electrodes) <= set(ELECTRODOS_10_20)
assert m.plan_hash and "spindle_detection=" in m.versions
def test_flat_channels_make_the_study_not_valid_with_a_check_per_electrode(measured):
"""Pins down: a study the validator rejects keeps its checks, one per bad channel with its electrode, and has
no metrics.
Fails if a rejected study is measured anyway, or the channel checks lose their electrode or normalised code.
"""
m = measured["flat"]
assert (m.valid, m.error, m.metrics) == (0, None, ())
dead = {c.electrode for c in m.checks if c.code == CriterioEeg.CANAL_MUERTO.value}
assert dead == set(FLAT)
assert any(c.decisive and c.abnormal and c.electrode is None for c in m.checks)
def test_a_file_that_is_not_an_edf_is_not_valid_rather_than_an_error(measured):
"""Pins down: unreadable bytes are the validator's `file` check, not an analysis error.
Fails if `measure` raises, or reports the file as an error (which would retry it on every run).
"""
m = measured["broken"]
assert (m.valid, m.error) == (0, None)
assert [c.code for c in m.checks] == [CriterioEeg.ARCHIVO.value]
def test_every_check_code_is_in_the_catalog(measured):
"""Pins down: the codes `measure` stores are `CriterioEeg` values.
Fails if the library adds or rewords a check and `criterion_code` stops normalising it.
"""
codes = {c.code for m in measured.values() for c in m.checks}
assert codes <= {c.value for c in CriterioEeg}
def test_channel_codes_lose_their_numbers():
"""Pins down: the library's channel codes, which embed the measured numbers, become fixed codes.
Fails if `criterion_code` stops mapping amplitude or burst reasons, or touches the study-wide codes.
"""
assert criterion_code("amplitude-4.5-x", "amplitude 4.5 x the scalp median", "C3") == "amplitude"
assert criterion_code("amplitude-25000-uv,", "amplitude 25000 uV, out of range even for ekg", "EKG") == \
"aux-amplitude"
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
"intermittent-bursts"
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
-199
View File
@@ -1,199 +0,0 @@
"""What this module covers: training the EEG age baselines on a cohort on the training machine's own disk
(`models.tea.eeg.reference`), and moving the trained baselines between installations as a bundle
(`models.tea.eeg.bundle`), with nothing per child in it.
Fixtures: `two_stores`, a site's MLflow store and a platform's, each a SQLite file with its own artifact folder,
switched by the returned function; `trained`, the seven baselines trained in the site's store on a synthetic
reference cohort with no EDF (200 children of 16 to 36 months whose features rise with age), as PROD versions.
"""
import io
import json
import zipfile
from datetime import date
import numpy as np
import pytest
from models.tea.eeg import bundle, train
from models.tea.eeg.analyze import ReferenceStudy, pipeline
from models.tea.eeg.reference import local, local_studies
from models.tea.eeg.settings import settings
@pytest.fixture
def two_stores(tmp_path, monkeypatch):
"""`use("sitio")` or `use("plataforma")` points MLflow, and the registry, at that installation's store."""
import mlflow
monkeypatch.chdir(tmp_path)
def use(name: str) -> None:
uri = f"sqlite:///{tmp_path / f'{name}.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / f"{name}-artefactos"))
mlflow.set_tracking_uri(uri)
use("sitio")
return use
@pytest.fixture
def trained(two_stores):
"""The seven scenarios trained as PROD in the site's store; returns their versions by scenario."""
s = settings()
pipe = pipeline(s)
rng = np.random.default_rng(0)
ages = np.round(np.sort(rng.uniform(16, 36, 200)), 1)
found = train.Listing.of("sitio", [(f"/datos/eeg/{k}.edf", float(a)) for k, a in enumerate(ages)])
studies = [ReferenceStudy(key, age, 1, {(b, phase): {f: float(abs(1 + 0.02 * age + rng.normal(0, 0.2)))
for f in pipe.module(b).features}
for b, phase in s.scenarios.values()})
for key, _, age in found.studies]
return {k: v for k, (v, _) in train.train_all(s, "PROD", found=found, studies=studies).items()}
def test_a_local_cohort_lists_its_edfs_with_the_table_or_header_age(tmp_path):
"""Pins down: a local cohort is every EDF under its folder, at any depth, with the age of its ages table, or of
its header without one; files without an age or outside the age range are left out.
Fails if a nested EDF is missed, an age outside `[reference] ages` gets in, or the header stops being the
fallback.
"""
from synth_edf import edf_bytes
folder = tmp_path / "eeg"
(folder / "2026").mkdir(parents=True)
born = date(2023, 1, 1)
(folder / "a.edf").write_bytes(edf_bytes(minutes=0.1, birthdate=born, startdate=date(2025, 1, 1))) # 24.0 m
(folder / "2026" / "b.EDF").write_bytes(edf_bytes(minutes=0.1, birthdate=born, startdate=date(2026, 6, 1)))
(folder / "c.edf").write_bytes(edf_bytes(minutes=0.1)) # no birth date in the header
s = local(settings(), folder=folder, line_hz=60)
assert [(p.split("/")[-1], a) for p, a in local_studies(s)] == [("a.edf", 24.0)] # b is 41 months
table = tmp_path / "edades.csv"
table.write_text("archivo,edad_anos\na.edf,1.5\nb.EDF,2.5\nc.edf,\n")
s = local(settings(), folder=folder, ages_table=table, line_hz=60)
assert sorted((p.split("/")[-1], a) for p, a in local_studies(s)) == [("a.edf", 18.0), ("b.EDF", 30.0)]
assert (s.reference.storage, s.reference.line_hz) == ("local", 60.0)
def test_a_local_cohort_trains_through_the_listing(tmp_path, monkeypatch):
"""Pins down: `listing` reads a local cohort on this machine, keyed by position, so its file names never reach
MLflow; its hash still changes with the files.
Fails if the listing goes back to S3 for a local cohort, or a key carries a file name.
"""
from synth_edf import edf_bytes
folder = tmp_path / "eeg"
folder.mkdir()
(folder / "garcia-lopez.edf").write_bytes(edf_bytes(minutes=0.1, birthdate=date(2023, 1, 1),
startdate=date(2025, 1, 1)))
found = train.listing(local(settings(), folder=folder, name="sitio"), cluster="sync")
assert [k for k, _, _ in found.studies] == ["sitio-0001"]
assert "garcia" not in found.sha256
def test_the_bundle_holds_group_numbers_only_and_imports_as_trained(trained, two_stores, tmp_path):
"""Pins down: the bundle has every scenario's trained state, plan, routine records, metrics and tags, and no
reference path or study key; imported into another store, each baseline is a new version with the same model
hash, cohort and routine records, so the registry's checks pass as where it was trained, and it scores the
analysis once promoted; importing the same bundle again registers nothing.
Fails if a per-study value or path reaches the bundle, the import changes the trained module, drops a promotion
input, or duplicates versions.
"""
from models.io.registry import registry
from models.tea.eeg.baselines import Baselines
out = tmp_path / "baselines.zip"
exported = bundle.export(settings(), out, environment="PROD")
assert exported.versions == trained
with zipfile.ZipFile(out) as z:
names = z.namelist()
text = b"".join(z.read(n) for n in names).decode()
manifest = json.loads(z.read(bundle.MANIFEST))
assert set(manifest["escenarios"]) == set(settings().scenarios)
assert "eeg-spindles-n2/module/baseline.json" in names and "eeg-spindles-n2/rutinas/MUESTREO.json" in names
assert "/datos/eeg" not in text and "sitio-0001" not in text
site_sha = manifest["escenarios"]["eeg-posterior-rhythm"]["tags"]["modelo_sha"]
two_stores("plataforma")
first = bundle.import_(settings(), out)
assert all(new for _, new in first.values())
assert bundle.import_(settings(), out) == {k: (v, False) for k, (v, _) in first.items()}
version = first["eeg-posterior-rhythm"][0]
mv = registry.get("tea", "eeg-posterior-rhythm", version)
assert (mv.tags["modelo_sha"], mv.tags["cohort.source"], mv.tags[bundle.BUNDLE_TAG]) == \
(site_sha, "referencia", exported.sha256)
passed = {c.code for c in registry.checks("tea", "eeg-posterior-rhythm", version) if c.passed}
assert {"ML-02", "ML-03", "ML-01a", "ML-01b"} <= passed
registry.attach_reports("tea", "eeg-posterior-rhythm", version, technical_validation_report_uri="r://t",
clinical_validation_report_uri="r://c", interpretability_report_uri="r://i")
registry.promote("tea", "eeg-posterior-rhythm", version)
d = Baselines("tea").deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 1 + 0.02 * 26, 26.0)
assert d is not None and d.outside == 0
def _rewritten(data: bytes, change) -> bytes:
"""The bundle with `change(files)` applied to its files (name -> bytes), the manifest kept as it was."""
with zipfile.ZipFile(io.BytesIO(data)) as z:
files = {n: z.read(n) for n in z.namelist()}
change(files)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w") as z:
for name, content in files.items():
z.writestr(name, content)
return buffer.getvalue()
def test_an_altered_bundle_is_refused(trained, two_stores, tmp_path):
"""Pins down: the import refuses a bundle whose file changed after it was written, one with a path outside
itself, and one whose module class, even with its manifest rewritten to match, isn't the one this platform runs
for that scenario.
Fails if the import stops checking the manifest, unpacks outside its folder, or loads a class a bundle names.
"""
out = tmp_path / "baselines.zip"
bundle.export(settings(), out, environment="PROD")
data = out.read_bytes()
two_stores("plataforma")
def bump(files):
files["eeg-gradient/module/baseline.json"] += b" "
def escape(files):
files["../fuera.json"] = b"{}"
def other_class(files):
path = "eeg-gradient/module/module.json"
files[path] = json.dumps({"class": "os:system"}).encode()
manifest = json.loads(files[bundle.MANIFEST])
manifest["escenarios"]["eeg-gradient"]["archivos"][path] = bundle._sha(files[path])
files[bundle.MANIFEST] = json.dumps(manifest).encode()
for change, reason in ((bump, "changed after"), (escape, "outside itself"), (other_class, "module class")):
target = tmp_path / f"{change.__name__}.zip"
target.write_bytes(_rewritten(data, change))
with pytest.raises(bundle.BundleError, match=reason):
bundle.import_(settings(), target)
def test_an_incomplete_export_is_refused(two_stores, tmp_path):
"""Pins down: nothing is written while a scenario has no version to export.
Fails if a partial bundle leaves the site (the platform would score some metrics and not others).
"""
with pytest.raises(bundle.BundleError, match="no PROD version"):
bundle.export(settings(), tmp_path / "baselines.zip", environment="PROD")
assert not (tmp_path / "baselines.zip").exists()
def test_run_takes_local_reference_flags_only_with_a_folder(two_stores):
"""Pins down: the local cohort's ages and mains frequency go with its folder.
Fails if `--line-hz` alone is silently ignored and HK1K's 50 Hz is used for a cohort recorded at 60 Hz.
"""
from models.__main__ import main
assert main(["run", "tea", "eeg", "--train", "--line-hz", "60"]) == 2
-223
View File
@@ -1,223 +0,0 @@
"""What this module covers: the EEG analysis around `measure`: the baselines' deviation (`models.tea.eeg.baselines`),
and `models.eeg_analysis`: writing an analysis back to bronze, choosing the pending EEGs, and the batch with its
governance log.
Fixtures: `tea_db` and `governance_db` (empty SQLite databases); `bronze`, two patients born 2024-01-01 with one EEG
each, studied 2026-03-01 (26.0 months): `e-1` with an EDF, `e-2` without one; `curves`, a baselines stand-in whose
posterior-rhythm curve has p5/median/p95 of 5/6/7 Hz at 24 months; `fake_measure`, a `measure` that returns a valid
measurement with a 9 Hz posterior rhythm and a spindle value at Fz, without the library.
"""
import math
from datetime import date
from types import SimpleNamespace
import pandas as pd
import pytest
from sqlmodel import select
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes
from models.eeg_analysis import age_months, analyze_pending, checked_settings as settings, rows, save
from models.tea.eeg.analyze import Check, Measurement, MetricValue
from models.tea.eeg.baselines import Baselines, centiles
@pytest.fixture
def curves():
"""`Baselines` whose only production version is `tea-eeg-posterior-rhythm/3`, a centile curve over 12-36 months."""
from tea.biomarkers.posterior_rhythm._baseline import CentileCurves
curve = pd.DataFrame({"edad_meses": [12.0, 24.0, 36.0], "n_efectivo": [50.0] * 3, "p5": [4.0, 5.0, 6.0],
"p25": [4.5, 5.5, 6.5], "mediana": [5.0, 6.0, 7.0], "p75": [5.5, 6.5, 7.5],
"p95": [6.0, 7.0, 8.0]})
module = SimpleNamespace(baseline=CentileCurves(curva=curve))
class Registry:
def resolve(self, domain, scenario):
if scenario != "eeg-posterior-rhythm":
raise LookupError(scenario)
return SimpleNamespace(version="3", model_uri="models:/tea-eeg-posterior-rhythm/3")
return Baselines("tea", registry=Registry(), loader=lambda uri: module)
@pytest.fixture
def bronze(tea_db):
"""Patients 1 and 2, born 2024-01-01; EEG `e-1` (patient 1, with an EDF) and `e-2` (patient 2, without)."""
from persistance.tea import eeg_repository
with eeg_repository.open_session() as session:
session.add_all([
Pacientes(pac_id=1, pac_fecha_nacimiento=date(2024, 1, 1)),
Pacientes(pac_id=2, pac_fecha_nacimiento=date(2024, 1, 1)),
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 3, 1), eeg_estudio=b"edf", eeg_canales=99),
Eeg(eeg_id="e-2", eeg_pac_id=2, eeg_fecha_estudio=date(2026, 3, 1)),
])
session.commit()
def current(s):
"""The plan hash and module versions an analysis made now would store."""
from models.tea.eeg.analyze import pipeline, plan, versions
return plan(s)["hash"], versions(pipeline(s), s)
def fake_measure(key, edf, age, s):
"""A valid measurement of `key` with the current plan and versions: 9 Hz posterior rhythm, N2 spindles
3.0/min, 1.5 at Fz for each sleep stage's spindles, and one channel check."""
assert edf == b"edf"
values = {"RITMO_POSTERIOR": 9.0, "HUSOS_SUENO_N2": 3.0}
plan_hash, versions = current(s)
return Measurement(
key=key, age_months=age, plan_hash=plan_hash, versions=versions, valid=1, level="completo", clean_fraction=0.9,
bad_channels=1, line_db=10.0, channels=21, duration_min=20.0, asleep=1,
checks=(Check("usable-scalp", None, 18.0, None, "electrodes", 12.0, None, True, False),
Check("dead-channel", "T3", None, "dead channel", None, None, None, False, True)),
metrics=tuple(MetricValue(m.code, values.get(m.code), {"Fz": 1.5} if m.electrodes else {})
for m in s.metrics),
)
def _all(model):
from persistance.tea import eeg_repository
with eeg_repository.open_session() as session:
return session.exec(select(model)).all()
def test_a_value_is_compared_with_the_curve_at_the_childs_age(curves):
"""Pins down: z, -1/0/+1 and the curve's p5/median/p95 come from the promoted baseline at the age given.
Fails if `deviation` reads the wrong baseline, stops interpolating the centiles at the age, or reports a
deviation for a metric without a baseline in production.
"""
d = curves.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 9.0, 24.0)
assert (d.outside, d.p5, d.median, d.p95) == (1, 5.0, 6.0, 7.0)
assert d.z == pytest.approx((9.0 - 6.0) / (1.0 / 1.645))
assert curves.deviation("eeg-spikes", "spike_rate_nrem", 1.0, 24.0) is None
assert curves.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", 9.0, None).z is None
assert curves.label("eeg-posterior-rhythm") == "tea-eeg-posterior-rhythm/3"
def test_an_age_outside_the_curve_has_no_centiles(curves):
"""Pins down: no p5/median/p95 outside the ages the curve covers, as the library gives no z there.
Fails if `centiles` extrapolates the curve.
"""
baseline = curves.module("eeg-posterior-rhythm").baseline
assert centiles(baseline, 60.0) == (None, None, None)
assert centiles(baseline, 18.0)[1] == pytest.approx(5.0 + math.log(18 / 12) / math.log(2))
def test_the_age_is_completed_months_at_the_study():
"""Pins down: the age is days / 30.4375 to one decimal, and unknown without both dates or before birth.
Fails if the analysis counts ages differently from the TEA cohort.
"""
assert age_months(date(2024, 1, 1), date(2026, 3, 1), 30.4375) == 26.0
assert age_months(None, date(2026, 3, 1), 30.4375) is None
assert age_months(date(2026, 3, 2), date(2026, 3, 1), 30.4375) is None
def test_an_analysis_replaces_the_previous_one_with_the_same_ids(bronze, curves):
"""Pins down: writing an analysis sets the EEG's columns and replaces its checks, metrics and electrodes; a
second write of the same analysis leaves the same rows with the same ids.
Fails if `save` appends instead of replacing, or row ids stop deriving from the EEG and what each row is (the
silver load would then see every re-analysis as new rows).
"""
from persistance.tea import eeg_repository
m = fake_measure("e-1", b"edf", 26.0, settings())
for _ in range(2):
with eeg_repository.open_session() as session:
save(session, "e-1", rows(m, settings(), curves))
session.commit()
eeg = eeg_repository.get("e-1")
assert (eeg.eeg_valido, eeg.eeg_nivel, eeg.eeg_canales, eeg.eeg_edad_meses, eeg.eeg_plan_hash) == \
(1, "completo", 21, 26.0, current(settings())[0])
assert sorted((c.cri_codigo, c.cri_electrodo) for c in _all(EegCriterio)) == \
[("dead-channel", "T3"), ("usable-scalp", None)]
metrics = {x.met_codigo: x for x in _all(EegMetrica)}
assert len(metrics) == 5
assert (metrics["RITMO_POSTERIOR"].met_fuera, metrics["RITMO_POSTERIOR"].met_modelo) == \
(1, "tea-eeg-posterior-rhythm/3")
assert metrics["HUSOS_SUENO_N2"].met_z is None and metrics["HUSOS_SUENO_N2"].met_modelo is None
electrodes = sorted((e.mel_met_id, e.mel_electrodo, e.mel_valor) for e in _all(EegMetricaElectrodo))
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"))
def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves):
"""Pins down: only EEGs with an EDF are analysed, the child's age goes to the measurement, each result is
logged as an `ExtractionRun`, and a second batch with the same plan, versions and baselines does nothing.
Fails if the pending selection stops skipping analysed EEGs or EEGs without an EDF, or the batch stops logging.
"""
from persistance.governance import extraction_run_repository
first = analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure)
assert (first.pending, first.valid, first.failed) == (1, 1, 0)
assert {e.eeg_id: e.eeg_edad_meses for e in _all(Eeg)} == {"e-1": 26.0, "e-2": None}
assert [(r.entity, r.entity_pk, r.estatus) for r in extraction_run_repository.list()] == \
[("eeg", "e-1", "COMPLETADA")]
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure).pending == 0
def test_a_new_baseline_in_production_makes_valid_eegs_pending(bronze, governance_db, curves):
"""Pins down: a valid EEG analysed against one baseline version is pending again once another is promoted.
Fails if the pending selection stops comparing `met_modelo` with the versions now in production.
"""
analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure)
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure).pending == 0
curves._resolved["eeg-posterior-rhythm"] = SimpleNamespace(version="4", model_uri="models:/x/4")
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=fake_measure, log_runs=False).pending == 1
def test_a_failed_study_is_stored_and_not_retried(bronze, governance_db, curves):
"""Pins down: a study whose analysis failed is written with its error and logged FALLIDA, and the next batch
with the same plan and versions leaves it alone.
Fails if a failure stops being stored (the EEG would be retried on every cycle) or stops being logged.
"""
from persistance.governance import extraction_run_repository
def failed(key, edf, age, s):
plan_hash, versions = current(s)
return Measurement(key=key, age_months=age, plan_hash=plan_hash, versions=versions,
error="MemoryError: worker killed")
def never(*args):
raise AssertionError("an EEG that failed with these versions was analysed again")
summary = analyze_pending(cluster="sync", baselines=curves, measure_fn=failed)
assert (summary.pending, summary.failed) == (1, 1)
assert {e.eeg_id: e.eeg_error for e in _all(Eeg)}["e-1"] == "MemoryError: worker killed"
assert [r.estatus for r in extraction_run_repository.list()] == ["FALLIDA"]
assert analyze_pending(cluster="sync", baselines=curves, measure_fn=never).pending == 0
def test_the_real_analysis_writes_a_synthetic_study(tea_db, governance_db, curves):
"""Pins down: the whole chain on the real library, from an EDF stored in `eeg` to its verdict, checks and
metrics in bronze, with the posterior rhythm compared with its curve.
Fails if `measure` and `store` stop agreeing on the shape of a measurement, or the batch stops reading the
stored EDF.
"""
from synth_edf import edf_bytes
from persistance.tea import eeg_repository
with eeg_repository.open_session() as session:
session.add_all([Pacientes(pac_id=1, pac_fecha_nacimiento=date(2024, 1, 1)),
Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 7, 1),
eeg_estudio=edf_bytes(minutes=4))])
session.commit()
summary = analyze_pending(cluster="sync", baselines=curves)
assert (summary.valid, summary.failed) == (1, 0)
assert eeg_repository.get("e-1").eeg_con_sueno == 1
rhythm = {m.met_codigo: m for m in _all(EegMetrica)}["RITMO_POSTERIOR"]
assert rhythm.met_valor == pytest.approx(7.0, abs=0.5)
assert 6.0 < rhythm.met_mediana < 7.0 and rhythm.met_p5 < rhythm.met_valor < rhythm.met_p95
assert rhythm.met_fuera == 0
assert {c.cri_codigo for c in _all(EegCriterio)} >= {"clean-windows", "usable-scalp"}
-186
View File
@@ -1,186 +0,0 @@
"""What this module covers: the EEG age baselines (`models.tea.eeg.train`, `models.tea.eeg.model`): the reference
listing, the training table, training and registering each scenario with what the registry's promotion checks read,
promotion, and the analysis scoring a value with a promoted baseline.
Fixtures: `mlflow_tracking` (a SQLite MLflow per test); `reference`, a synthetic reference cohort with no EDF: 200
children of 16 to 36 months whose every feature rises with age plus noise, as `ReferenceStudy` rows of each biomarker
and sleep stage the metrics read, and the listing they'd come from.
"""
import numpy as np
import pytest
from models.tea.eeg import train
from models.tea.eeg.analyze import ReferenceStudy, pipeline
from models.tea.eeg.settings import settings
@pytest.fixture
def reference():
"""(listing, studies): 200 valid children whose features are 1 + 0.02 x age + noise; one more invalid and one
failed, which training must leave out."""
s = settings()
pipe = pipeline(s)
rng = np.random.default_rng(0)
ages = np.round(np.sort(rng.uniform(16, 36, 200)), 1)
found = train.Listing.of("prueba", [(f"s3://prueba/{k}.edf", float(a)) for k, a in enumerate(ages)])
studies = []
for (key, _, age) in found.studies:
features = {(b, phase): {f: float(abs(1 + 0.02 * age + rng.normal(0, 0.2))) for f in pipe.module(b).features}
for b, phase in s.scenarios.values()}
studies.append(ReferenceStudy(key, age, 1, features))
studies += [ReferenceStudy("prueba-x", 20.0, 0), ReferenceStudy("prueba-y", 20.0, error="ValueError: boom")]
return found, studies
def test_a_listing_is_identified_by_its_studies_not_their_order():
"""Pins down: the listing's keys are positions (no file names leave), and its hash depends on which studies and
ages it holds, not on the order they were found in.
Fails if a key carries a file name, or the hash changes with the order S3 lists the files in.
"""
a = train.Listing.of("hk1k", [("s3://x/b.edf", 20.0), ("s3://x/a.edf", 30.0)])
b = train.Listing.of("hk1k", [("s3://x/a.edf", 30.0), ("s3://x/b.edf", 20.0)])
assert a == b and [k for k, _, _ in a.studies] == ["hk1k-0001", "hk1k-0002"]
assert train.Listing.of("hk1k", [("s3://x/a.edf", 31.0), ("s3://x/b.edf", 20.0)]).sha256 != a.sha256
def test_the_table_takes_only_valid_measured_studies(reference):
"""Pins down: a baseline trains on the valid, measured studies' features of its biomarker and stage, with their
ages. Fails if an invalid or failed study reaches a curve."""
_, studies = reference
data = train.table(studies, "spindles", "N2")
assert len(data) == 200 and "age_months" in data and "spindle_density_per_min_channel" in data
def test_each_scenario_is_registered_with_what_promotion_checks(mlflow_tracking, reference):
"""Pins down: training registers every scenario as `tea-<scenario>` with its environment, the reference cohort
(ML-03), its model hash (ML-01b), the five routine records (ML-01a) and metrics; training again on the same
listing, plan and module versions registers nothing; and until the reports are attached, promotion is refused.
Fails if a scenario is missing, a promotion input stops being recorded, re-training duplicates versions, or a
baseline reaches production without the clinical validation report.
"""
from models.io.registry import PromotionBlocked, registry
found, studies = reference
s = settings()
first = train.train_all(s, "PROD", found=found, studies=studies)
assert set(first) == set(s.scenarios) and all(new for _, new in first.values())
assert train.train_all(s, "PROD", found=found, studies=[]) == {k: (v, False) for k, (v, _) in first.items()}
version = first["eeg-posterior-rhythm"][0]
checks = {(c.code, c.requirement): c for c in registry.checks("tea", "eeg-posterior-rhythm", version)}
passed = {code for (code, _), c in checks.items() if c.passed}
assert {"ML-02", "ML-03", "ML-01a", "ML-01b"} <= passed
assert "listado" in checks["ML-03", "enlazada al armado de cohorte con el que se entrenó"].detail
assert "MLD-01b" not in passed
with pytest.raises(PromotionBlocked):
registry.promote("tea", "eeg-posterior-rhythm", version)
def test_each_baseline_keeps_its_artifacts_under_the_artifact_root(mlflow_tracking, reference, tmp_path, monkeypatch):
"""Pins down: with `MLFLOW_ARTIFACT_ROOT` set, every scenario's run writes its model and routine records under
that root, not in `./mlruns` of the working directory.
Fails if training lets `tea.serving.log_biomarker` create the experiment at MLflow's default location: in a
container the working directory isn't the data volume, and the registered baselines would point at files that
disappear with it.
"""
from mlflow import MlflowClient
root = tmp_path / "artefactos"
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(root))
found, studies = reference
trained = train.train_all(settings(), "PROD", found=found, studies=studies)
client = MlflowClient()
for scenario, (version, _) in trained.items():
run = client.get_run(client.get_model_version(f"tea-{scenario}", version).run_id)
assert run.info.artifact_uri.startswith(str(root)), scenario
assert any((root / f"tea-{scenario}").rglob("*.json")), scenario
assert not (tmp_path / "mlruns").exists()
def test_a_promoted_baseline_scores_the_analysis(mlflow_tracking, reference):
"""Pins down: once its reports are attached, a baseline is promoted, and the analysis's `Baselines` loads it
from the registry and gives a value at an age its curve covers a z, -1/0/+1 and the curve's centiles.
Fails if the registered model stops being the library's (the analysis couldn't load it), or promotion and the
analysis disagree on the scenario's registered name.
"""
from models.io.registry import registry
from models.tea.eeg.baselines import Baselines
found, studies = reference
s = settings()
(version, _) = train.train_all(s, "PROD", found=found, studies=studies)["eeg-posterior-rhythm"]
registry.attach_reports("tea", "eeg-posterior-rhythm", version, technical_validation_report_uri="r://t",
clinical_validation_report_uri="r://c", interpretability_report_uri="r://i")
registry.promote("tea", "eeg-posterior-rhythm", version)
baselines = Baselines("tea")
median = 1 + 0.02 * 26
d = baselines.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", median, 26.0)
assert d is not None and abs(d.z) < 1 and d.outside == 0 and d.p5 < median < d.p95
assert baselines.deviation("eeg-posterior-rhythm", "posterior_rhythm_hz", median + 2, 26.0).outside == 1
assert baselines.label("eeg-posterior-rhythm") == f"tea-eeg-posterior-rhythm/{version}"
def test_loading_a_baseline_leaves_the_import_path_alone(mlflow_tracking, reference):
"""Pins down: loading a promoted baseline leaves `sys.path` as it was and `tea` the installed package, so a Dask
worker spawned after the first batch still imports `tea.pipeline`.
Fails if `Baselines` loads through MLflow without restoring `sys.path`: the model's bundled partial `tea` would
shadow the library in every worker spawned afterwards, and each of their studies would fail with
`No module named 'tea.pipeline'`.
"""
import subprocess
import sys
import tea
from models.io.registry import registry
from models.tea.eeg.baselines import Baselines
found, studies = reference
(version, _) = train.train_all(settings(), "PROD", found=found, studies=studies)["eeg-posterior-rhythm"]
registry.attach_reports("tea", "eeg-posterior-rhythm", version, technical_validation_report_uri="r://t",
clinical_validation_report_uri="r://c", interpretability_report_uri="r://i")
registry.promote("tea", "eeg-posterior-rhythm", version)
before, package = list(sys.path), tea.__file__
assert Baselines("tea").module("eeg-posterior-rhythm") is not None
assert sys.path == before
assert sys.modules["tea"].__file__ == package
spawned = subprocess.run([sys.executable, "-c", "import sys, json; sys.path[:] = json.loads(sys.argv[1]); "
"import tea.pipeline", __import__("json").dumps(sys.path)], capture_output=True)
assert spawned.returncode == 0, spawned.stderr.decode()[-300:]
def test_run_takes_only_train_and_promote_for_the_baselines(mlflow_tracking):
"""Pins down: `models run tea eeg` runs the baselines' own steps: a cohort step is refused, and promoting with
nothing trained says so and fails.
Fails if the scenario falls back to the cohort-file steps, which it has no file for.
"""
from models.__main__ import main
assert main(["run", "tea", "eeg", "--export"]) == 2
assert main(["run", "tea", "eeg", "--promote"]) == 1
def test_a_reference_study_is_measured_from_its_path(tmp_path):
"""Pins down: `reference` reads a study from a path, at the cohort's mains frequency, and returns every feature
of each biomarker and stage the metrics read.
Fails if the reference unit stops sharing the analysis's study (validation, processes, per-stage spindles).
"""
from synth_edf import edf_bytes
from models.tea.eeg.analyze import reference as measure_reference
path = tmp_path / "study.edf"
path.write_bytes(edf_bytes(minutes=4, line_hz=50.0))
st = measure_reference("prueba-0001", str(path), 27.0, settings(), 50.0)
assert (st.valid, st.error) == (1, None)
assert set(st.features) == set(settings().scenarios.values())
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)
+2 -68
View File
@@ -16,7 +16,7 @@ from sqlmodel import Session
from models.__main__ import main
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
from models.io.storage import cohort_urls, read_queries
from models.io.storage import read_queries
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
from models.steps import cohort
@@ -125,11 +125,10 @@ def test_a_population_without_cutoff_is_refused(manifest):
@pytest.mark.parametrize("change, message", [
(lambda n: n[:1] + n[2:], "exactly one `index`"),
(lambda n: n[:2], "no `exclusion` queries"),
(lambda n: [*n, _node("third", "exclusion", _rows(5), 1)], "repeats an `order`"),
(lambda n: [*n, _node("third", "exclusion", _rows(5), 3, ["first"])], "may only read"),
(lambda n: [*n[:2], n[2] | {"compiled_code": None}, n[3]], "dbt compile"),
(lambda n: [*n, _node("v1", "variables", _rows(1)), _node("v2", "variables", _rows(1))], "more than one `variables`"),
(lambda n: [*n, _node("v", "variables", _rows(1)) | {"depends_on": {"nodes": ["model.p.first"]}}], "may only read"),
])
def test_a_badly_defined_cohort_is_refused(manifest, change, message):
"""Pins down: what the chain relies on is checked when reading. The fourth case is what keeps the rules commutable: an
@@ -220,68 +219,3 @@ def test_a_query_that_fails_points_to_the_view(manifest, cacu_db, capsys):
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes))]) == 1
assert "dbt run --select cacu_linea_de_tiempo" in capsys.readouterr().err
def test_a_cohort_without_rules_is_everyone_with_an_index(manifest):
"""Pins down: a cohort with no exclusions (`cacu/cohorte_total`) reads, and its study population is every patient
with an index, with only the population and index steps in its attrition. Fails if exclusions become required
again or the chain needs a last rule."""
queries = read_queries(manifest(_standard()[:2]), URL)
built = build_cohort(queries, _sqlite_reader())
assert queries.rules == ()
assert sorted(built.study_population["pac_id"]) == [1, 2, 3, 4, 5]
assert built.attrition[["step", "n"]].values.tolist() == [["all_patients", 6], ["indexed", 5]]
def test_the_cycle_builds_the_domains_cohorts_of_the_manifest(manifest):
"""Pins down: the cohorts of a domain are the `meta.cohort` of the manifest's population queries with that
prefix, sorted, once each; another domain's are not. Fails if an index or exclusion query names a cohort the
cycle then builds, or the prefix leaks."""
path = manifest([*_standard(), _node("x", "population", _rows(1)) | {"config": {"meta": {"cohort": "cama/c", "kind": "population"}}}])
assert cohort_urls(path, "cacu") == ["cacu/other", URL]
assert cohort_urls(path, "cama") == ["cama/c"]
assert cohort_urls(path, "tea") == []
def test_version_and_variables_come_from_the_manifest(manifest):
"""Pins down: the population meta's `version` and the optional `variables` query reach `CohortQueries`. Fails if
either is dropped, so builds would lose their version or the WebApp its variables."""
nodes = _standard()
nodes[0]["config"]["meta"]["version"] = "1.2.0"
sql = "select 1 as pac_id, 'pap_0' as variable, 'NORMAL' as valor_codigo, null as valor_numerico"
queries = read_queries(manifest([*nodes, _node("vars", "variables", sql, reads=["index"])]), URL)
assert (queries.version, queries.variables) == ("1.2.0", sql)
def test_the_stored_build_comes_from_dbts_queries(manifest):
"""Pins down: `models.cohorts.build.build_of` turns dbt's queries into the cycle's rows: the build with the
population meta's version and the count of the study population, one exclusion row per attrition step, the
members, and the `variables` query's values of members only. Fails if the build stops running dbt's rules, keeps
a non-member's variable, or its frame hash ignores the variables."""
from core.cacu.indicadores.models import (CohorteArmado, CohorteExclusion, CohorteMiembro, CohorteVariable,
EvaluacionRiesgo, EvaluacionRiesgoLote)
from core.indicadores.cohortes import TablasCohorte
from models.cohorts.build import build_of
tables = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
EvaluacionRiesgo)
nodes = _standard()
nodes[0]["config"]["meta"]["version"] = "0.3.0"
sql = ("select 1 as pac_id, 'pap_0' as variable, 'NORMAL' as valor_codigo, null as valor_numerico "
"union all select 2, 'pap_0', 'ASC-US', null")
with_variables = read_queries(manifest([*nodes, _node("vars", "variables", sql, reads=["index"])]), URL)
without = read_queries(manifest(nodes), URL)
with Session(create_engine("sqlite://")) as session:
build, exclusions, members, variables = build_of(session, with_variables, cohortes=tables)
plain, *_ = build_of(session, without, cohortes=tables)
assert (build.url, build.version, build.n_miembros) == (URL, "0.3.0", 2)
assert [(e.paso, e.n) for e in exclusions] == [("all_patients", 6), ("indexed", 5), ("first", 3), ("second", 2)]
assert sorted(m.pac_id for m in members) == [1, 5]
assert [(v.pac_id, v.variable, v.valor_codigo) for v in variables] == [(1, "pap_0", "NORMAL")]
assert build.marco_sha != plain.marco_sha and build.huella != plain.huella
-184
View File
@@ -1,184 +0,0 @@
"""What this module covers: `models.steps.indexing`, each scenario's index and rules over a cohort's long frame: the
surveillance index, the post-colposcopy episode, its numbered visits, the index of each visit, each rule in its order
and the attrition, the re-indexed frame and the recruitment window taken from the source cohort. The cases are those
of dbt's unit tests (`cacu_post_colposcopy.yml`, `cacu_surveillance.yml`), which the pipeline must match.
Fixtures: none; each test builds its rows with `_row`.
"""
import json
from datetime import date, timedelta
import pandas as pd
import pytest
from models.io.contracts import COHORT_SCHEMA
from models.steps import indexing
RULES = {"event_grades": ["LIEAG", "CIS", "CARCINOMA"], "referral_lookback_days": 365, "hysterectomy_cie": ["Z907"]}
COLPOSCOPY = date(2025, 1, 10)
def _row(pac_id, tipo, fecha, valor=None, fuente_id="a", fuente_tabla="t"):
return {"pac_id": pac_id, "fecha_indice": date(2020, 1, 1), "fecha": fecha, "conocida_en": None, "clase": "x",
"tipo": tipo, "codigo": tipo, "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": fuente_tabla,
"fuente_id": f"{pac_id}{fuente_id}"}
def _after(days):
return COLPOSCOPY + timedelta(days=days)
def _visit(pac_id, days, name, hpv="NEGATIVO", pap="NORMAL"):
rows = [_row(pac_id, "citologia", _after(days), fuente_id=name)]
rows += [_row(pac_id, "vph", _after(days + 10), hpv, fuente_id=name)] if hpv else []
return rows + ([_row(pac_id, "bethesda", _after(days + 12), pap, fuente_id=name)] if pap else [])
def _patient(pac_id, *extra, referral=True, biopsy="LIEBG"):
"""A referral 30 days before the colposcopy, a biopsy ordered there and reported 20 days later (`biopsy`; None:
none ordered) and cotest visits at 200 and 560 days."""
rows = [_row(pac_id, "colposcopia", COLPOSCOPY, fuente_id="c")]
rows += [_row(pac_id, "bethesda", _after(-30), "ASC-US", fuente_id="r")] if referral else []
if biopsy:
rows += [_row(pac_id, "orden_biopsia", COLPOSCOPY, fuente_id="o"),
_row(pac_id, "biopsia", _after(20), biopsy, fuente_id="o")]
return rows + _visit(pac_id, 200, "v1") + _visit(pac_id, 560, "v2", hpv="POSITIVO") + list(extra)
def _frame(rows):
return pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
def _post(rows, k, **window):
return indexing._indexed_members(_frame(rows), {"kind": "post_colposcopia", "visita": k, **RULES, **window})
def test_the_result_date_is_the_last_report_of_the_colposcopys_biopsies():
"""Pins down, as dbt's episode unit test: the later of two reports of biopsies ordered on the first colposcopy's
day; a later colposcopy's biopsy doesn't count; with no order the colposcopy's day; an order with no report is
counted. Fails if the episode takes a later colposcopy or another day's biopsy."""
rows = [_row(1, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o1"),
_row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o2"), _row(1, "biopsia", _after(10), "LIEBG", fuente_id="o1"),
_row(1, "biopsia", _after(21), "NEGATIVO", fuente_id="o2"), _row(1, "colposcopia", _after(150), fuente_id="c2"),
_row(1, "orden_biopsia", _after(150), fuente_id="o3"), _row(1, "biopsia", _after(170), "LIEBG", fuente_id="o3")]
episode = indexing._colposcopy_episode(rows)
no_biopsy = indexing._colposcopy_episode([_row(2, "colposcopia", COLPOSCOPY)])
unreported = indexing._colposcopy_episode([_row(3, "colposcopia", COLPOSCOPY), _row(3, "orden_biopsia", COLPOSCOPY, fuente_id="o")])
assert (episode["result_date"], episode["unreported_orders"]) == (_after(21), 0)
assert (no_biopsy["result_date"], no_biopsy["unreported_orders"]) == (COLPOSCOPY, 0)
assert (unreported["result_date"], unreported["unreported_orders"]) == (COLPOSCOPY, 1)
def test_visits_follow_the_result_and_stop_at_the_next_colposcopy():
"""Pins down, as dbt's visits unit test: a sample on the colposcopy's day or before its result isn't a visit; the
two after it are visits 1 and 2; one after a second colposcopy isn't. Fails if visits start before the result or
continue after a re-referral."""
rows = [_row(1, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o"),
_row(1, "biopsia", _after(21), "NEGATIVO", fuente_id="o"), _row(1, "citologia", COLPOSCOPY, fuente_id="a"),
_row(1, "citologia", _after(10), fuente_id="b"), _row(1, "citologia", _after(170), fuente_id="c1"),
_row(1, "citologia", _after(370), fuente_id="d"), _row(1, "colposcopia", _after(415), fuente_id="c2"),
_row(1, "citologia", _after(600), fuente_id="e")]
found = indexing._surveillance_visits(rows, indexing._colposcopy_episode(rows))
assert [v["fuente_id"] for v in found] == ["1c1", "1d"]
@pytest.mark.parametrize("k, index", [(0, _after(20)), (1, _after(200))])
def test_each_visit_has_its_own_index(k, index):
"""Pins down: visit 0 is indexed when the biopsy is reported, visit 1 at its sample. Fails if a cohort takes
another visit or the colposcopy's own date when a biopsy was reported later."""
members, _ = _post(_patient(1), k)
assert members.values.tolist() == [[1, index]]
def test_the_window_applies_to_the_scenarios_index():
"""Pins down: the recruitment window is checked on the scenario's index (visit 1 at 200 days), not on the first
event. Fails if the window is read off another date."""
inside, _ = _post(_patient(1), 1, recruitment_start=_after(100).isoformat())
outside, _ = _post(_patient(1), 1, recruitment_start=_after(300).isoformat())
assert (len(inside), len(outside)) == (1, 0)
def test_sin_cotest_needs_hpv_and_cytology_of_the_index_sample():
"""Pins down, as dbt's unit test: a visit with HPV and Bethesda stays; HPV alone or cytology alone is flagged; an
HPV of another sample doesn't count. Fails if either result alone, or another sample's, counts as a cotest."""
def first_visit(pac_id, **kw):
return [r for r in _patient(pac_id) if not r["fuente_id"].endswith(("v1", "v2"))] + _visit(pac_id, 200, "v1", **kw)
rows = (first_visit(1) + first_visit(2, pap=None) + first_visit(3, hpv=None) + first_visit(4, hpv=None)
+ [_row(4, "vph", _after(100), "POSITIVO", fuente_id="z")])
members, attrition = _post(rows, 1)
assert members["pac_id"].tolist() == [1] and attrition[-2:] == [("sin_cotest", 1), ("observacion_previa_insuficiente", 1)]
def test_rules_in_order_with_attrition():
"""Pins down the order and each rule, as dbt: an unreported order (1), CIN2+ found by the colposcopy (2), a cancer
history note (3), a hysterectomy ICD-10 (4), a treatment (5), no referral in the year before the colposcopy (6);
patient 7 stays; visit 0 has no `sin_cotest`. Fails if a rule, its date bound or the order changes."""
rows = (_patient(1, _row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o9")) + _patient(2, biopsy="LIEAG")
+ _patient(3, _row(3, "antecedente", _after(-400), fuente_id="n"))
+ _patient(4, _row(4, "nota_medica", _after(-400), "Z907", fuente_id="n"))
+ _patient(5, _row(5, "tratamiento", _after(15), fuente_id="n")) + _patient(6, referral=False)
+ _patient(7, _row(7, "nota_medica", _after(-400), "N871", fuente_id="n")))
members, attrition = _post(rows, 0)
assert members["pac_id"].tolist() == [7]
assert attrition == [("pacientes", 7), ("indexed", 7), ("biopsia_sin_resultado", 6), ("cin2_hasta_el_indice", 5),
("antecedente_cacu", 4), ("histerectomia", 3), ("tratamiento_previo", 2), ("sin_referencia", 1),
("observacion_previa_insuficiente", 1)]
def test_surveillance_index_and_rules_as_dbt():
"""Pins down the surveillance kind, as dbt's surveillance cohort: the first sample is the index; a CIN2+ biopsy
before it (`prior_event`) and an index sample without any result (`no_index_result`) are out; a glandular-only
result counts. Fails if the index takes a later sample or a rule changes."""
def sample(pac_id, day, *results):
return [_row(pac_id, "citologia", _after(day), fuente_id=f"s{day}")] + [
_row(pac_id, tipo, _after(day + 7), valor, fuente_id=f"s{day}") for tipo, valor in results]
rows = (sample(1, 0, ("bethesda", "NORMAL")) + sample(1, 300, ("bethesda", "LIEBG"))
+ sample(2, 0, ("vph", "POSITIVO")) + [_row(2, "biopsia", _after(-10), "LIEAG")]
+ sample(3, 0) + sample(4, 0, ("glandular", "AGC")))
members, attrition = indexing._indexed_members(_frame(rows), {"kind": "primera_citologia", **RULES})
assert members.values.tolist() == [[1, _after(0)], [4, _after(0)]]
assert attrition == [("pacientes", 4), ("indexed", 4), ("prior_event", 3), ("no_index_result", 2),
("observacion_previa_insuficiente", 2)]
def test_the_node_reindexes_the_frame_with_the_source_cohorts_window():
"""Pins down `cohort`: only the scenario's members, each with the scenario's `fecha_indice`, every event kept;
the window from the source build's `parametros`; without `[config.index]` the source as it is. Fails if the frame
keeps the source's index dates, drops events, or the window isn't the source cohort's."""
source = _frame(_patient(1) + _patient(2, referral=False))
lineage = {"parametros": json.dumps({"recruitment_start": "2024-01-01", "recruitment_end": "2027-01-01"})}
index = {"kind": "post_colposcopia", "visita": 1, **RULES}
reindexed = indexing.cohort(source, lineage, index)
closed = indexing.cohort(source, {"parametros": json.dumps({"recruitment_end": "2025-01-01"})}, index)
assert set(reindexed["pac_id"]) == {1} and set(reindexed["fecha_indice"]) == {_after(200)}
assert len(reindexed) == (source["pac_id"] == 1).sum()
assert closed.empty and indexing.cohort(source, lineage, None) is source
def test_prior_observation_is_a_threshold_on_the_days_before_the_index():
"""Pins down the left-truncation rule: with the default 0 nobody is out; with 230 days, patient 1 (first event 30
days before her colposcopy, visit 1 at 200 days: 230 days observed) stays and with 231 she is out; the summary
counts members with under a year of history. Fails if the days are counted from another date, the bound flips,
or the default stops being 0."""
rows = _patient(1)
assert len(_post(rows, 1)[0]) == 1
assert len(_post(rows, 1, observacion_previa_minima_dias=230)[0]) == 1
assert len(_post(rows, 1, observacion_previa_minima_dias=231)[0]) == 0
summary = indexing.prior_observation(_frame(rows), {}, {"kind": "post_colposcopia", "visita": 1, **RULES})
assert summary == {"members": 1, "under_365_days": 1, "median_days": 230.0, "threshold_days": 0}
+3 -5
View File
@@ -66,13 +66,11 @@ def _stored():
def test_each_row_becomes_one_risk_at_its_horizon():
"""Pins down: a risk is `(pac_id, fecha_indice, horizonte_anios, probabilidad, None, None)`, one per member and
horizon, the index date and the horizon taken from the row. Fails if the horizon is dropped, taken from elsewhere, or the interval is filled with
"""Pins down: a risk is `(pac_id, horizonte_anios, probabilidad, None, None)`, one per member and horizon, the
horizon taken from the row. Fails if the horizon is dropped, taken from elsewhere, or the interval is filled with
something the model didn't give."""
d1, d2 = date(2025, 1, 1), date(2025, 1, 2)
assert risk_rows(_estimate((1, 2), horizons=(0.0, 3.0))) == [
(1, d1, 0.0, 0.1, None, None), (1, d1, 3.0, 0.13, None, None), (2, d2, 0.0, 0.2, None, None),
(2, d2, 3.0, 0.23, None, None)]
(1, 0.0, 0.1, None, None), (1, 3.0, 0.13, None, None), (2, 0.0, 0.2, None, None), (2, 3.0, 0.23, None, None)]
@pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]),