Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6fded849a2 | |||
| 0d75ff6baa | |||
| 6f6c3cd4c2 |
@@ -13,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. |
|
||||
@@ -21,20 +21,19 @@ 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. |
|
||||
| `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. |
|
||||
|
||||
@@ -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
+5
-12
@@ -137,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:
|
||||
@@ -159,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
|
||||
@@ -173,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
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
|
||||
@@ -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,29 +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) -> 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(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,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))
|
||||
@@ -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
@@ -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)])
|
||||
|
||||
@@ -8,8 +8,7 @@ requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
|
||||
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,27 +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.
|
||||
[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,43 +0,0 @@
|
||||
domain = "cacu"
|
||||
scenario = "cin2_pim_post_colposcopy"
|
||||
cohort = "cacu/cohorte_post_colposcopia"
|
||||
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 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."""
|
||||
|
||||
[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+).
|
||||
[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"]
|
||||
@@ -1,90 +0,0 @@
|
||||
"""The post-colposcopy cohort's frame, from the timeline (`post_colposcopy.toml`).
|
||||
|
||||
The same rules as dbt's `cacu_post_colposcopy_*` models, over timeline rows instead of SQL over tables:
|
||||
|
||||
- the index is the first cytology more than `colposcopy_result_days` after the patient's first colposcopy, if it
|
||||
falls in the recruitment window;
|
||||
- then, in this order, the exclusions `prior_event`, `prior_treatment`, `no_referral_result`, `no_index_result`.
|
||||
|
||||
Each exclusion reads only the index and the timeline; a patient may be flagged by several, and attrition charges
|
||||
each rule only for the members it removes from those it receives.
|
||||
"""
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
RESULT_TYPES = ("bethesda", "glandular", "vph")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Member:
|
||||
pac_id: int
|
||||
fecha_indice: date
|
||||
indice_fuente_tabla: str
|
||||
indice_fuente_id: str
|
||||
variables: dict # name -> value
|
||||
|
||||
|
||||
def _by_patient(filas):
|
||||
patients = defaultdict(list)
|
||||
for fila in filas:
|
||||
patients[fila["pac_id"]].append(fila)
|
||||
return patients
|
||||
|
||||
|
||||
def _index(events, rules: dict, inicio: date, fin: date):
|
||||
"""(index cytology, first colposcopy date), or None when the patient has no index in the window."""
|
||||
colposcopies = [e["fecha"] for e in events if e["tipo"] == "colposcopia"]
|
||||
if not colposcopies:
|
||||
return None
|
||||
colposcopy = min(colposcopies)
|
||||
wait = int(rules["colposcopy_result_days"])
|
||||
cytologies = sorted((e for e in events if e["tipo"] == "citologia" and (e["fecha"] - colposcopy).days > wait),
|
||||
key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
if not cytologies or not (inicio <= cytologies[0]["fecha"] < fin):
|
||||
return None
|
||||
return cytologies[0], colposcopy
|
||||
|
||||
|
||||
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
|
||||
"""(members, attrition). `filas`: the CaCu timeline, already cut at the cut-off (`hasta=corte`)."""
|
||||
grades = set(reglas["event_grades"])
|
||||
lookback = int(reglas["referral_lookback_days"])
|
||||
|
||||
candidates = []
|
||||
for pac_id, events in sorted(_by_patient(filas).items()):
|
||||
events = [e for e in events if e["fecha"] <= corte]
|
||||
found = _index(events, reglas, inicio, fin)
|
||||
if found:
|
||||
candidates.append((pac_id, events, *found))
|
||||
|
||||
def prior_event(events, index, colposcopy):
|
||||
return any(e["tipo"] == "biopsia" and e["fecha"] < index["fecha"] and e["valor_codigo"] in grades for e in events)
|
||||
|
||||
def prior_treatment(events, index, colposcopy):
|
||||
return any(e["tipo"] == "tratamiento" and e["fecha"] < index["fecha"] for e in events)
|
||||
|
||||
def no_referral_result(events, index, colposcopy):
|
||||
return 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)
|
||||
|
||||
def no_index_result(events, index, colposcopy):
|
||||
return not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
|
||||
and (e["fuente_tabla"], e["fuente_id"]) == (index["fuente_tabla"], index["fuente_id"])
|
||||
for e in events)
|
||||
|
||||
attrition = [("candidatas", len(candidates))]
|
||||
for name, rule in (("prior_event", prior_event), ("prior_treatment", prior_treatment),
|
||||
("no_referral_result", no_referral_result), ("no_index_result", no_index_result)):
|
||||
candidates = [c for c in candidates if not rule(*c[1:])]
|
||||
attrition.append((f"sin {name}", len(candidates)))
|
||||
|
||||
members = []
|
||||
for pac_id, events, index, _ in candidates:
|
||||
key = (index["fuente_tabla"], index["fuente_id"])
|
||||
values = {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and (e["fuente_tabla"], e["fuente_id"]) == key
|
||||
and e["valor_codigo"] is not None), None) for t in RESULT_TYPES}
|
||||
members.append(Member(pac_id, index["fecha"], *key,
|
||||
{"pap_0": values["bethesda"], "glandular_0": values["glandular"], "hpv_0": values["vph"]}))
|
||||
return members, attrition
|
||||
@@ -1,63 +0,0 @@
|
||||
# Cohorte posterior a colposcopia de CaCu: mujeres con su primera citología tras la primera colposcopia.
|
||||
#
|
||||
# Same index and exclusions, in the same order and with the same names, as the dbt models
|
||||
# (Transformation/models/cacu/cohorts/post_colposcopy); parameters are the dbt vars `post_colposcopy_cohort`.
|
||||
# Changing a rule changes the definition: bump `version`.
|
||||
|
||||
[group]
|
||||
url = "cacu/cohorte_post_colposcopia"
|
||||
version = "0.1.0"
|
||||
status = "draft"
|
||||
membership = "definitional"
|
||||
title = "Mujeres tras colposcopia, por citología"
|
||||
expression = "cacu.post_colposcopy:frame"
|
||||
indice = "Primera citología más de colposcopy_result_days después de la primera colposcopia, si cae en la ventana de reclutamiento"
|
||||
desenlace = "cin2_mas"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "prior_event"
|
||||
exclude = true
|
||||
description = "Biopsia con el desenlace antes de la fecha índice"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "prior_treatment"
|
||||
exclude = true
|
||||
description = "Tratada antes de la fecha índice: pertenece a la cohorte posterior al tratamiento"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "no_referral_result"
|
||||
exclude = true
|
||||
description = "Sin resultado citológico ni de VPH en los referral_lookback_days hasta la colposcopia"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "no_index_result"
|
||||
exclude = true
|
||||
description = "La citología índice no tiene resultado citológico (escamoso o glandular) ni de VPH"
|
||||
|
||||
[group.reglas]
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
colposcopy_result_days = 90
|
||||
referral_lookback_days = 365
|
||||
|
||||
[group.reglas_estado]
|
||||
event_grades = { estado = "vigente", fuente = "Desenlace CIN2+; LIEAG junta CIN2 y CIN3, así que CIN3+ no se puede leer" }
|
||||
colposcopy_result_days = { estado = "sin_definir", fuente = "Valor provisional: 90 es nuestro, no de KPNC; por decidir con quien lleva el modelo" }
|
||||
referral_lookback_days = { estado = "sin_definir", fuente = "Valor provisional: 365 cubre una derivación y su espera; por decidir con quien lleva el modelo" }
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "pap_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Squamous Bethesda category of the index cytology"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "glandular_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Glandular category of the index cytology"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "hpv_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "HPV result of the same sample"
|
||||
@@ -1,88 +0,0 @@
|
||||
"""The post-treatment cohort's frame, from the timeline (`post_treatment.toml`).
|
||||
|
||||
The same rules as dbt's `cacu_post_treatment_*` models, over timeline rows instead of SQL over tables:
|
||||
|
||||
- the index is the first cytology more than `index_after_days` after the patient's first treatment, if it falls in
|
||||
the recruitment window;
|
||||
- then, in this order, the exclusions `no_pretreatment_biopsy`, `event_before_index`, `no_index_result`.
|
||||
|
||||
Each exclusion reads only the index and the timeline; a patient may be flagged by several, and attrition charges
|
||||
each rule only for the members it removes from those it receives.
|
||||
"""
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
RESULT_TYPES = ("bethesda", "glandular", "vph")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Member:
|
||||
pac_id: int
|
||||
fecha_indice: date
|
||||
indice_fuente_tabla: str
|
||||
indice_fuente_id: str
|
||||
variables: dict # name -> value
|
||||
|
||||
|
||||
def _by_patient(filas):
|
||||
patients = defaultdict(list)
|
||||
for fila in filas:
|
||||
patients[fila["pac_id"]].append(fila)
|
||||
return patients
|
||||
|
||||
|
||||
def _index(events, rules: dict, inicio: date, fin: date):
|
||||
"""(index cytology, first treatment date), or None when the patient has no index in the window."""
|
||||
treatments = [e["fecha"] for e in events if e["tipo"] == "tratamiento"]
|
||||
if not treatments:
|
||||
return None
|
||||
treatment = min(treatments)
|
||||
wait = int(rules["index_after_days"])
|
||||
cytologies = sorted((e for e in events if e["tipo"] == "citologia" and (e["fecha"] - treatment).days > wait),
|
||||
key=lambda e: (e["fecha"], e["fuente_id"]))
|
||||
if not cytologies or not (inicio <= cytologies[0]["fecha"] < fin):
|
||||
return None
|
||||
return cytologies[0], treatment
|
||||
|
||||
|
||||
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
|
||||
"""(members, attrition). `filas`: the CaCu timeline, already cut at the cut-off (`hasta=corte`)."""
|
||||
grades = set(reglas["event_grades"])
|
||||
lookback = int(reglas["pretreatment_lookback_days"])
|
||||
|
||||
candidates = []
|
||||
for pac_id, events in sorted(_by_patient(filas).items()):
|
||||
events = [e for e in events if e["fecha"] <= corte]
|
||||
found = _index(events, reglas, inicio, fin)
|
||||
if found:
|
||||
candidates.append((pac_id, events, *found))
|
||||
|
||||
def no_pretreatment_biopsy(events, index, treatment):
|
||||
return not any(e["tipo"] == "biopsia" and e["valor_codigo"] is not None
|
||||
and 0 <= (treatment - e["fecha"]).days <= lookback for e in events)
|
||||
|
||||
def event_before_index(events, index, treatment):
|
||||
return any(e["tipo"] == "biopsia" and treatment < e["fecha"] < index["fecha"] and e["valor_codigo"] in grades
|
||||
for e in events)
|
||||
|
||||
def no_index_result(events, index, treatment):
|
||||
return not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
|
||||
and (e["fuente_tabla"], e["fuente_id"]) == (index["fuente_tabla"], index["fuente_id"])
|
||||
for e in events)
|
||||
|
||||
attrition = [("candidatas", len(candidates))]
|
||||
for name, rule in (("no_pretreatment_biopsy", no_pretreatment_biopsy), ("event_before_index", event_before_index),
|
||||
("no_index_result", no_index_result)):
|
||||
candidates = [c for c in candidates if not rule(*c[1:])]
|
||||
attrition.append((f"sin {name}", len(candidates)))
|
||||
|
||||
members = []
|
||||
for pac_id, events, index, _ in candidates:
|
||||
key = (index["fuente_tabla"], index["fuente_id"])
|
||||
values = {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and (e["fuente_tabla"], e["fuente_id"]) == key
|
||||
and e["valor_codigo"] is not None), None) for t in RESULT_TYPES}
|
||||
members.append(Member(pac_id, index["fecha"], *key,
|
||||
{"pap_0": values["bethesda"], "glandular_0": values["glandular"], "hpv_0": values["vph"]}))
|
||||
return members, attrition
|
||||
@@ -1,58 +0,0 @@
|
||||
# Cohorte posterior a tratamiento de CaCu: mujeres con su primera citología tras el primer tratamiento.
|
||||
#
|
||||
# Same index and exclusions, in the same order and with the same names, as the dbt models
|
||||
# (Transformation/models/cacu/cohorts/post_treatment); parameters are the dbt vars `post_treatment_cohort`.
|
||||
# Changing a rule changes the definition: bump `version`.
|
||||
|
||||
[group]
|
||||
url = "cacu/cohorte_post_tratamiento"
|
||||
version = "0.1.0"
|
||||
status = "draft"
|
||||
membership = "definitional"
|
||||
title = "Mujeres tras tratamiento, por citología"
|
||||
expression = "cacu.post_treatment:frame"
|
||||
indice = "Primera citología más de index_after_days después del primer tratamiento, si cae en la ventana de reclutamiento"
|
||||
desenlace = "cin2_mas"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "no_pretreatment_biopsy"
|
||||
exclude = true
|
||||
description = "Sin biopsia reportada en los pretreatment_lookback_days hasta el tratamiento"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "event_before_index"
|
||||
exclude = true
|
||||
description = "Biopsia con el desenlace entre el tratamiento y la fecha índice"
|
||||
|
||||
[[group.characteristic]]
|
||||
code = "no_index_result"
|
||||
exclude = true
|
||||
description = "La citología índice no tiene resultado citológico (escamoso o glandular) ni de VPH"
|
||||
|
||||
[group.reglas]
|
||||
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
index_after_days = 90
|
||||
pretreatment_lookback_days = 365
|
||||
|
||||
[group.reglas_estado]
|
||||
event_grades = { estado = "vigente", fuente = "Desenlace CIN2+; LIEAG junta CIN2 y CIN3, así que CIN3+ no se puede leer" }
|
||||
index_after_days = { estado = "sin_definir", fuente = "Valor provisional: 90 días tras el tratamiento; por decidir con quien lleva el modelo" }
|
||||
pretreatment_lookback_days = { estado = "sin_definir", fuente = "Valor provisional: 365 días hasta el tratamiento; por decidir con quien lleva el modelo" }
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "pap_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Squamous Bethesda category of the index cytology"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "glandular_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "Glandular category of the index cytology"
|
||||
|
||||
[[evidenceVariable]]
|
||||
name = "hpv_0"
|
||||
role = "covariate"
|
||||
tipo = "codigo"
|
||||
title = "HPV result of the same sample"
|
||||
@@ -11,7 +11,7 @@ pide el modelo de mezcla prevalencia–incidencia (Modelo-cacu):
|
||||
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 (escamoso o glandular) ni de VPH en 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`).
|
||||
@@ -55,7 +55,6 @@ def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[li
|
||||
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"}
|
||||
glandular = {(e["fuente_tabla"], e["fuente_id"]) for e in eventos if e["tipo"] == "glandular" and e["valor_codigo"]}
|
||||
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
|
||||
@@ -67,7 +66,7 @@ def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[li
|
||||
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 and llave not in glandular:
|
||||
if pap_0 is None and hpv_0 is None:
|
||||
sin_resultado += 1
|
||||
continue
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ description = "Biopsia con el desenlace antes de la fecha índice: no está en r
|
||||
[[group.characteristic]]
|
||||
code = "sin_resultado"
|
||||
exclude = true
|
||||
description = "La citología índice no tiene resultado citológico (escamoso o glandular) ni de VPH: no hay predictores"
|
||||
description = "La citología índice no tiene resultado citológico ni de VPH: no hay predictores"
|
||||
|
||||
[group.reglas]
|
||||
grados_evento = ["LIEAG", "CIS", "CARCINOMA"]
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
@@ -119,8 +118,8 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") ->
|
||||
loaders = [loader(target=target, source=source) for target, loader in
|
||||
(("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))
|
||||
|
||||
+11
-10
@@ -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 = ""
|
||||
|
||||
+24
-1
@@ -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),
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -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
-18
@@ -30,15 +30,7 @@ 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")
|
||||
@@ -231,23 +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
|
||||
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)}"
|
||||
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,
|
||||
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", "")),
|
||||
|
||||
+13
-1
@@ -31,7 +31,8 @@ import pyarrow.parquet as pq
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
|
||||
CohortFileError, CohortQueries, ExclusionRule, check_frame)
|
||||
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
|
||||
|
||||
|
||||
@@ -295,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
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
"""
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()]}
|
||||
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# 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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
+43
-166
@@ -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).
|
||||
"""
|
||||
|
||||
@@ -35,27 +35,16 @@ def _row(pac_id, index, days, tipo, valor=None):
|
||||
"fuente_id": f"{pac_id}-{tipo}-{days}"}
|
||||
|
||||
|
||||
def _visit(pac_id, index, day, bethesda, vph):
|
||||
return [_row(pac_id, index, day, "bethesda", bethesda), _row(pac_id, index, day, "vph", vph)]
|
||||
|
||||
|
||||
def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()):
|
||||
rows = [_row(pac_id, index, 0, "citologia"), *_visit(pac_id, index, 7, bethesda, vph)]
|
||||
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
|
||||
@@ -70,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)
|
||||
|
||||
|
||||
@@ -86,78 +74,32 @@ 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 loader's `cohort` 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(training.dataflow(*SCENARIO.modules, config=CONFIG))
|
||||
|
||||
assert required == {"cohort", "cytology", "event_grades", "history", "horizons_years", "incidence",
|
||||
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
|
||||
"train_fraction"}
|
||||
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "index_sample_days",
|
||||
"known_negative", "prevalent_window_months", "train_fraction"}
|
||||
assert optional == set()
|
||||
|
||||
|
||||
@@ -166,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={"cohort": cohort_frame})["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)
|
||||
@@ -174,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
|
||||
@@ -196,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={"cohort": cohort_frame})["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={"cohort": frame})["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"
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,176 +0,0 @@
|
||||
"""What this module covers: `models.cohorts.cacu.post_colposcopy.frame`: the index cytology, each exclusion in its
|
||||
order, the attrition counts, and the definition's TOML.
|
||||
|
||||
Fixtures: none; each test builds its timeline rows with `_row`.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
from models.cohorts.cacu import post_colposcopy
|
||||
from models.cohorts.definition import cohort_path, read_definition
|
||||
|
||||
RULES = {"event_grades": ["LIEAG", "CIS", "CARCINOMA"], "colposcopy_result_days": 90, "referral_lookback_days": 365}
|
||||
START, END, CUTOFF = date(2025, 1, 1), date(2026, 1, 1), date(2026, 12, 31)
|
||||
COLPOSCOPY = date(2025, 1, 1)
|
||||
|
||||
|
||||
def _row(pac_id, tipo, fecha, valor=None, fuente_id="a", fuente_tabla="t"):
|
||||
return {"pac_id": pac_id, "fecha": fecha, "tipo": tipo, "valor_codigo": valor, "fuente_tabla": fuente_tabla,
|
||||
"fuente_id": f"{pac_id}{fuente_id}"}
|
||||
|
||||
|
||||
def _after(days):
|
||||
return COLPOSCOPY + timedelta(days=days)
|
||||
|
||||
|
||||
def _patient(pac_id, *extra, referral=True, index_result="LIEBG"):
|
||||
"""A patient with a colposcopy, a referral result 30 days before it, and an index cytology 200 days after."""
|
||||
rows = [_row(pac_id, "colposcopia", COLPOSCOPY, fuente_id="c"),
|
||||
_row(pac_id, "citologia", _after(200), fuente_id="i")]
|
||||
if referral:
|
||||
rows.append(_row(pac_id, "bethesda", _after(-30), "ASC-US", fuente_id="r"))
|
||||
if index_result:
|
||||
rows.append(_row(pac_id, "bethesda", _after(200), index_result, fuente_id="i"))
|
||||
return rows + list(extra)
|
||||
|
||||
|
||||
def _run(rows, rules=RULES):
|
||||
return post_colposcopy.frame(rows, rules, START, END, CUTOFF)
|
||||
|
||||
|
||||
def test_index_is_the_first_cytology_after_the_biopsy_window():
|
||||
"""Pins down, as dbt's index unit test does: a cytology 30 days after the colposcopy is within the biopsy
|
||||
window and doesn't count; the one at 200 days is the index, even with a later colposcopy. A patient with no
|
||||
colposcopy, and one whose first cytology falls outside the recruitment window, have no index. Fails if the index
|
||||
stops waiting for the biopsies, takes a later colposcopy, or ignores the window."""
|
||||
rows = _patient(1, _row(1, "colposcopia", _after(59), fuente_id="c2"), _row(1, "citologia", _after(30), fuente_id="e"))
|
||||
rows += [_row(2, "citologia", _after(200), fuente_id="d"), _row(2, "bethesda", _after(200), "LIEBG", fuente_id="d")]
|
||||
rows += [_row(3, "colposcopia", date(2025, 11, 1), fuente_id="c"), _row(3, "citologia", date(2026, 6, 1), fuente_id="e"),
|
||||
_row(3, "bethesda", date(2026, 6, 1), "LIEBG", fuente_id="e"), _row(3, "bethesda", date(2025, 10, 1), "LIEBG", fuente_id="r")]
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [(m.pac_id, m.fecha_indice, m.indice_fuente_id) for m in members] == [(1, _after(200), "1i")]
|
||||
assert attrition[0] == ("candidatas", 1)
|
||||
|
||||
|
||||
def test_index_needs_more_than_the_wait_days():
|
||||
"""Pins down: a cytology exactly `colposcopy_result_days` after the colposcopy is too early, one day more is
|
||||
the index. Fails if the comparison becomes `>=`."""
|
||||
rows = [_row(1, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(1, "bethesda", _after(-1), "LIEBG", fuente_id="r"),
|
||||
_row(1, "citologia", _after(90), fuente_id="x"), _row(1, "citologia", _after(91), fuente_id="y"),
|
||||
_row(1, "vph", _after(91), "POSITIVO", fuente_id="y")]
|
||||
|
||||
members, _ = _run(rows)
|
||||
|
||||
assert [m.indice_fuente_id for m in members] == ["1y"]
|
||||
|
||||
|
||||
def test_index_ignores_cytologies_after_the_cutoff():
|
||||
"""Pins down: a cytology after the cut-off is not an index. Fails if the cut-off stops applying."""
|
||||
rows = _patient(1)
|
||||
|
||||
members, attrition = post_colposcopy.frame(rows, RULES, START, END, _after(100))
|
||||
|
||||
assert members == [] and attrition[0] == ("candidatas", 0)
|
||||
|
||||
|
||||
def test_member_carries_the_index_results():
|
||||
"""Pins down: the member's variables are the squamous, glandular and HPV results of the index cytology only,
|
||||
and a missing one is None. Fails if results of other samples leak in or a variable is renamed."""
|
||||
rows = _patient(1, _row(1, "glandular", _after(200), "AGC", fuente_id="i"),
|
||||
_row(1, "vph", _after(250), "POSITIVO", fuente_id="z"))
|
||||
|
||||
members, _ = _run(rows)
|
||||
|
||||
assert members[0].variables == {"pap_0": "LIEBG", "glandular_0": "AGC", "hpv_0": None}
|
||||
|
||||
|
||||
def test_prior_event_excludes_a_biopsy_with_the_outcome_before_the_index():
|
||||
"""Pins down: a CIN2+ biopsy before the index date flags the patient; a negative one, or a CIN2+ on the index
|
||||
date, doesn't. Fails if the event grades or the strict `<` change."""
|
||||
rows = (_patient(1, _row(1, "biopsia", _after(10), "CIS")) + _patient(2, _row(2, "biopsia", _after(10), "NEGATIVO"))
|
||||
+ _patient(3, _row(3, "biopsia", _after(200), "LIEAG")))
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [2, 3]
|
||||
assert attrition[:2] == [("candidatas", 3), ("sin prior_event", 2)]
|
||||
|
||||
|
||||
def test_prior_treatment_excludes_a_treatment_before_the_index():
|
||||
"""Pins down: a treatment before the index date flags the patient (she belongs to the post-treatment cohort); one
|
||||
on the index date doesn't. Fails if the interval's end or the event type change."""
|
||||
rows = (_patient(1, _row(1, "tratamiento", _after(100))) + _patient(2, _row(2, "tratamiento", _after(200))))
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [2]
|
||||
assert attrition[2] == ("sin prior_treatment", 1)
|
||||
|
||||
|
||||
def test_no_referral_result_looks_back_from_the_colposcopy():
|
||||
"""Pins down, as dbt's unit test does: a result 100 days before the colposcopy is the referral and the patient
|
||||
stays; one 400 days before (past the lookback) or one after the colposcopy leaves her out; 365 days exactly
|
||||
still counts. Fails if the lookback, its direction or the result types change."""
|
||||
def case(pac_id, tipo, days, valor="LIEBG"):
|
||||
return _patient(pac_id, _row(pac_id, tipo, _after(days), valor, fuente_id="q"), referral=False)
|
||||
|
||||
rows = (case(1, "vph", -100, "POSITIVO") + case(2, "bethesda", -400) + case(3, "bethesda", 14)
|
||||
+ case(4, "glandular", -365, "AGC") + case(5, "vph", -366, "POSITIVO"))
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [1, 4]
|
||||
assert attrition[3] == ("sin no_referral_result", 2)
|
||||
|
||||
|
||||
def test_no_referral_result_needs_a_value():
|
||||
"""Pins down: a referral row without a code is not a result. Fails if null codes start to count."""
|
||||
rows = _patient(1, _row(1, "bethesda", _after(-10), None, fuente_id="q"), referral=False)
|
||||
|
||||
members, _ = _run(rows)
|
||||
|
||||
assert members == []
|
||||
|
||||
|
||||
def test_no_index_result_needs_a_result_of_the_index_cytology():
|
||||
"""Pins down: an index cytology with only a glandular result (or only HPV) stays; one with none, or whose
|
||||
results belong to another sample, is left out. Fails if the rule reads only the squamous result or ignores the
|
||||
sample."""
|
||||
rows = (_patient(1, _row(1, "glandular", _after(200), "AGC", fuente_id="i"), index_result=None)
|
||||
+ _patient(2, _row(2, "vph", _after(200), "NEGATIVO", fuente_id="i"), index_result=None)
|
||||
+ _patient(3, index_result=None)
|
||||
+ _patient(4, _row(4, "bethesda", _after(200), None, fuente_id="i"), index_result=None)
|
||||
+ _patient(5, _row(5, "vph", _after(250), "POSITIVO", fuente_id="z"), index_result=None))
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [1, 2]
|
||||
assert attrition[4] == ("sin no_index_result", 2)
|
||||
|
||||
|
||||
def test_attrition_charges_each_rule_only_for_what_it_removes_from_the_rest():
|
||||
"""Pins down: a patient flagged by several rules is charged to the first in order. Fails if each rule counted
|
||||
against all candidates."""
|
||||
rows = _patient(1, _row(1, "biopsia", _after(10), "CIS"), _row(1, "tratamiento", _after(20)), referral=False,
|
||||
index_result=None)
|
||||
rows += _patient(2)
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [2]
|
||||
assert attrition == [("candidatas", 2), ("sin prior_event", 1), ("sin prior_treatment", 1),
|
||||
("sin no_referral_result", 1), ("sin no_index_result", 1)]
|
||||
|
||||
|
||||
def test_definition_loads_and_resolves_the_frame():
|
||||
"""Pins down: the TOML loads through `read_definition`, with the dbt rule parameters, and its `expression`
|
||||
resolves to `post_colposcopy.frame`. Fails if a required key is dropped or the expression is renamed."""
|
||||
definition = read_definition(cohort_path("cacu", "post_colposcopy"))
|
||||
|
||||
assert definition.url == "cacu/cohorte_post_colposcopia"
|
||||
assert definition.function() is post_colposcopy.frame
|
||||
assert definition.reglas["event_grades"] == ["LIEAG", "CIS", "CARCINOMA"]
|
||||
assert (definition.reglas["colposcopy_result_days"], definition.reglas["referral_lookback_days"]) == (90, 365)
|
||||
assert [v.nombre for v in definition.variables] == ["pap_0", "glandular_0", "hpv_0"]
|
||||
@@ -1,146 +0,0 @@
|
||||
"""What this module covers: `models.cohorts.cacu.post_treatment.frame`: the index cytology, each exclusion in its
|
||||
order, the attrition counts, and the definition's TOML.
|
||||
|
||||
Fixtures: none; each test builds its timeline rows with `_row`.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
from models.cohorts.cacu import post_treatment
|
||||
from models.cohorts.definition import cohort_path, read_definition
|
||||
|
||||
RULES = {"event_grades": ["LIEAG", "CIS", "CARCINOMA"], "index_after_days": 90, "pretreatment_lookback_days": 365}
|
||||
START, END, CUTOFF = date(2025, 1, 1), date(2026, 1, 1), date(2026, 12, 31)
|
||||
TREATMENT = date(2025, 1, 1)
|
||||
|
||||
|
||||
def _row(pac_id, tipo, fecha, valor=None, fuente_id="a", fuente_tabla="t"):
|
||||
return {"pac_id": pac_id, "fecha": fecha, "tipo": tipo, "valor_codigo": valor, "fuente_tabla": fuente_tabla,
|
||||
"fuente_id": f"{pac_id}{fuente_id}"}
|
||||
|
||||
|
||||
def _after(days):
|
||||
return TREATMENT + timedelta(days=days)
|
||||
|
||||
|
||||
def _patient(pac_id, *extra, biopsy=True, index_result="LIEBG"):
|
||||
"""A patient with a treatment, a biopsy 30 days before it, and an index cytology 180 days after."""
|
||||
rows = [_row(pac_id, "tratamiento", TREATMENT, fuente_id="x"), _row(pac_id, "citologia", _after(180), fuente_id="i")]
|
||||
if biopsy:
|
||||
rows.append(_row(pac_id, "biopsia", _after(-30), "LIEAG", fuente_id="b"))
|
||||
if index_result:
|
||||
rows.append(_row(pac_id, "bethesda", _after(180), index_result, fuente_id="i"))
|
||||
return rows + list(extra)
|
||||
|
||||
|
||||
def _run(rows, rules=RULES):
|
||||
return post_treatment.frame(rows, rules, START, END, CUTOFF)
|
||||
|
||||
|
||||
def test_index_is_the_first_cytology_past_the_days_after_treatment():
|
||||
"""Pins down, as dbt's index unit test does: a cytology 60 days after the first treatment is too early; the one
|
||||
at 180 days is the index, even with a later treatment. A patient never treated has no index. Fails if the index
|
||||
stops waiting `index_after_days` or takes a later treatment."""
|
||||
rows = _patient(1, _row(1, "tratamiento", _after(31), fuente_id="x2"), _row(1, "citologia", _after(60), fuente_id="e"))
|
||||
rows += [_row(2, "citologia", _after(180), fuente_id="c"), _row(2, "bethesda", _after(180), "LIEBG", fuente_id="c")]
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [(m.pac_id, m.fecha_indice, m.indice_fuente_id) for m in members] == [(1, _after(180), "1i")]
|
||||
assert attrition[0] == ("candidatas", 1)
|
||||
|
||||
|
||||
def test_index_needs_more_than_the_wait_days_and_falls_in_the_window():
|
||||
"""Pins down: a cytology exactly `index_after_days` after the treatment is too early, one day more is the
|
||||
index; an index outside the recruitment window or after the cut-off gives no member. Fails if the comparison
|
||||
becomes `>=` or the window/cut-off stop applying."""
|
||||
base = [_row(1, "tratamiento", TREATMENT, fuente_id="x"), _row(1, "biopsia", _after(-5), "LIEAG", fuente_id="b"),
|
||||
_row(1, "citologia", _after(90), fuente_id="x"), _row(1, "citologia", _after(91), fuente_id="y"),
|
||||
_row(1, "vph", _after(91), "POSITIVO", fuente_id="y")]
|
||||
late = [_row(2, "tratamiento", date(2025, 11, 1), fuente_id="x"), _row(2, "biopsia", date(2025, 10, 1), "LIEAG", fuente_id="b"),
|
||||
_row(2, "citologia", date(2026, 6, 1), fuente_id="e"), _row(2, "vph", date(2026, 6, 1), "POSITIVO", fuente_id="e")]
|
||||
|
||||
members, _ = _run(base + late)
|
||||
cut, _ = post_treatment.frame(base, RULES, START, END, _after(91 - 1))
|
||||
|
||||
assert [m.indice_fuente_id for m in members] == ["1y"]
|
||||
assert cut == []
|
||||
|
||||
|
||||
def test_member_carries_the_index_results():
|
||||
"""Pins down: the member's variables are the squamous, glandular and HPV results of the index cytology only,
|
||||
and a missing one is None. Fails if results of other samples leak in or a variable is renamed."""
|
||||
rows = _patient(1, _row(1, "glandular", _after(180), "AGC", fuente_id="i"),
|
||||
_row(1, "vph", _after(250), "POSITIVO", fuente_id="z"))
|
||||
|
||||
members, _ = _run(rows)
|
||||
|
||||
assert members[0].variables == {"pap_0": "LIEBG", "glandular_0": "AGC", "hpv_0": None}
|
||||
|
||||
|
||||
def test_no_pretreatment_biopsy_looks_back_from_the_treatment():
|
||||
"""Pins down: a biopsy 365 days before the treatment still counts, 366 days or after the treatment doesn't, and
|
||||
a biopsy without a code isn't a report. Fails if the lookback, its direction or the null check change."""
|
||||
def case(pac_id, days, valor="NEGATIVO"):
|
||||
return _patient(pac_id, _row(pac_id, "biopsia", _after(days), valor, fuente_id="q"), biopsy=False)
|
||||
|
||||
rows = case(1, -365) + case(2, -366) + case(3, 10) + case(4, -20, None) + case(5, 0)
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [1, 5]
|
||||
assert attrition[1] == ("sin no_pretreatment_biopsy", 2)
|
||||
|
||||
|
||||
def test_event_before_index_is_between_treatment_and_index():
|
||||
"""Pins down, as dbt's unit test does: a CIN2+ biopsy between the treatment and the index is flagged; one before
|
||||
the treatment, on the treatment date or on the index date isn't; a negative one between them isn't. Fails if
|
||||
the interval's ends or the grades change."""
|
||||
rows = (_patient(1, _row(1, "biopsia", _after(60), "LIEAG")) + _patient(2, _row(2, "biopsia", _after(-60), "LIEAG"))
|
||||
+ _patient(3, _row(3, "biopsia", _after(180), "LIEAG")) + _patient(4, _row(4, "biopsia", _after(60), "NEGATIVO"))
|
||||
+ _patient(5, _row(5, "biopsia", _after(0), "CIS")))
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [2, 3, 4, 5]
|
||||
assert attrition[2] == ("sin event_before_index", 4)
|
||||
|
||||
|
||||
def test_no_index_result_needs_a_result_of_the_index_cytology():
|
||||
"""Pins down: an index cytology with only a glandular result (or only HPV) stays; one with none, or whose
|
||||
results belong to another sample, is left out. Fails if the rule reads only the squamous result or ignores the
|
||||
sample."""
|
||||
rows = (_patient(1, _row(1, "glandular", _after(180), "AGC", fuente_id="i"), index_result=None)
|
||||
+ _patient(2, _row(2, "vph", _after(180), "NEGATIVO", fuente_id="i"), index_result=None)
|
||||
+ _patient(3, index_result=None)
|
||||
+ _patient(4, _row(4, "bethesda", _after(180), None, fuente_id="i"), index_result=None)
|
||||
+ _patient(5, _row(5, "vph", _after(250), "POSITIVO", fuente_id="z"), index_result=None))
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [1, 2]
|
||||
assert attrition[3] == ("sin no_index_result", 2)
|
||||
|
||||
|
||||
def test_attrition_charges_each_rule_only_for_what_it_removes_from_the_rest():
|
||||
"""Pins down: a patient flagged by several rules is charged to the first in order. Fails if each rule counted
|
||||
against all candidates."""
|
||||
rows = _patient(1, _row(1, "biopsia", _after(60), "CIS"), biopsy=False, index_result=None) + _patient(2)
|
||||
|
||||
members, attrition = _run(rows)
|
||||
|
||||
assert [m.pac_id for m in members] == [2]
|
||||
assert attrition == [("candidatas", 2), ("sin no_pretreatment_biopsy", 1), ("sin event_before_index", 1),
|
||||
("sin no_index_result", 1)]
|
||||
|
||||
|
||||
def test_definition_loads_and_resolves_the_frame():
|
||||
"""Pins down: the TOML loads through `read_definition`, with the dbt rule parameters, and its `expression`
|
||||
resolves to `post_treatment.frame`. Fails if a required key is dropped or the expression is renamed."""
|
||||
definition = read_definition(cohort_path("cacu", "post_treatment"))
|
||||
|
||||
assert definition.url == "cacu/cohorte_post_tratamiento"
|
||||
assert definition.function() is post_treatment.frame
|
||||
assert definition.reglas["event_grades"] == ["LIEAG", "CIS", "CARCINOMA"]
|
||||
assert (definition.reglas["index_after_days"], definition.reglas["pretreatment_lookback_days"]) == (90, 365)
|
||||
assert [v.nombre for v in definition.variables] == ["pap_0", "glandular_0", "hpv_0"]
|
||||
@@ -1,30 +0,0 @@
|
||||
"""What this module covers: `models.cohorts.cacu.surveillance.frame`'s rule for an index cytology without results.
|
||||
|
||||
Fixtures: none; each test builds its timeline rows with `_event`.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from models.cohorts.cacu import surveillance
|
||||
|
||||
RULES = {"grados_evento": ["LIEAG"], "ventana_basal_dias": 180, "no_prevalente": {"pap": ["NORMAL"], "vph": ["NEGATIVO"]},
|
||||
"negativo_da_l": False, "negativo_confirma_no_prevalente": False}
|
||||
INDEX = date(2025, 1, 1)
|
||||
|
||||
|
||||
def _event(pac_id, tipo, valor=None, fuente_id="a"):
|
||||
return {"pac_id": pac_id, "fecha": INDEX, "tipo": tipo, "valor_codigo": valor, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": f"{pac_id}{fuente_id}"}
|
||||
|
||||
|
||||
def test_a_glandular_result_alone_is_an_index_result():
|
||||
"""Pins down, as dbt's `cacu_surveillance_excl_no_index_result` does: a member whose index cytology has only a
|
||||
glandular result (AGC) stays, and one with no result of any kind is left out. Fails if the rule goes back to
|
||||
reading only the squamous Bethesda and HPV."""
|
||||
rows = [_event(1, "citologia"), _event(1, "glandular", "AGC"),
|
||||
_event(2, "citologia"), _event(2, "glandular", None)]
|
||||
|
||||
members, attrition = surveillance.frame(rows, RULES, date(2024, 1, 1), date(2026, 1, 1), date(2026, 12, 31))
|
||||
|
||||
assert [m.pac_id for m in members] == [1]
|
||||
assert attrition[-1] == ("sin sin_resultado", 1)
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user