Compare commits

..

40 Commits

Author SHA1 Message Date
edgar e8c264e571 Subgroup reports for CaCu's survival and PIM scenarios, as version files and as notebooks in the code
Every CaCu PIM scenario (cin2_pim, post-colposcopy, post-treatment) and the survival scenario now keep, per
combination of their covariates, the model against its empirical estimate, with the methods each used:

- PIM (models/cacu/cin2_pim/report.py): Turnbull's interval-censored estimate (prevalent = mass at 0, free in (l, r],
  unknown baseline in [0, r]; ported from bayes-pim chapter 24) with a bootstrap band, against the mixture refitted on
  every coded member with a delta-method band over the likelihood (inverse numerical Hessian, numerical gradient of
  CR(t), log scale); E/O at each horizon with log(E/O) taken as normal.
- Survival (models/cacu/survival/report.py): Kaplan-Meier with Greenwood's band against the SEER pipeline's own
  subgroup points and bootstrap interval (survival_curves.sv_sub_weights and sv_sub_points, called as they are).

A version keeps the record as analisis/subgrupos.json and a self-contained Plotly page as reportes/subgrupos.html
(TrainingRun.log_report; the saver publishes a dataflow's `reports`). The same drawing is a notebook in the code,
models/cacu/{cin2_pim,survival}/notebooks/reporte_subgrupos.ipynb: chart names and computed results only, a
`parameters` cell, `#| echo: false` cells. models.reports.templates lists those notebooks with the scenarios each serves
and reads one by id, for the WebApi's /governance/notebook-templates. The Jupyter renderer now drops the code of
`#| echo: false` cells, as Quarto does.

plotly>=5.18 joins the `survival-curves` extra (installed by the WebApi) and the dev group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 22:41:04 -06:00
edgar 9cba11c2ec CaCu survival: all-cause mortality at 1, 3 and 5 years from the cancer diagnosis
A new scenario, models/cacu/survival, from the total cohort. PROVISIONAL index: the first biopsy reported as invasive
carcinoma (`primera_biopsia_invasora` with `CARCINOMA`), both the inclusion criterion and the index date; out without
a birth date or with a death on or before it. The covariates are the most recent observations up to the diagnosis:
the age group at it, the latest cytology sample in KPNC's categories and the latest HPV result. The outcome is the
timeline's `defuncion` (emitted by the monorepo's CaCu timeline on its own branch).

The fit is the SEER pipeline's interval survival as cama/survival runs it (LR and Bayesian network per interval,
stacked), and a version publishes the same population record, `analisis/curvas.json` (KM with Greenwood, adjusted KM,
Weibull, LR/HBN/combined points with bootstrap intervals): the survival panel a collaborator's proof of concept asked
for, without its synthetic covariates or its fixed 50:50 mix.

CaMa's code is not changed. The nodes that don't depend on the covariates call CaMa's; encode, interval_cohort,
IntervalSurvival, labelled_members, missing_data, analytic_method and survival_frame are copies over CaCu's covariates,
because CaMa's read its FEATURES as a module constant. Issue #9 records the duplication and how to remove it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 21:37:43 -06:00
edgar feb934da2f ML-01a: the training run is the registered routine; its routine records are reported, not required
Not every model has each of the five routine records (a prevalence-incidence mixture has no class balance or
classifier calibration), so requiring all of them blocked promotion of models whose run is in order. The check now
passes when the version comes from its training run and its detail says which records the run holds
("registros de rutina: k de 5 (...)"). A version declared over the API still can't be promoted: it has no saved
model (ML-01b).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 19:17:45 -06:00
angel b608dc0b53 Merge pull request 'CaMa: survival and recurrence models, the live scenario figures, and their training from governance' (#7) from feature/cama-roundtrip into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/models/pulls/7
2026-11-21 15:03:33 -06:00
rockdrigo 1b9afb22ea CaMa: the SEER stages see the molecular subtype; the subtype derivation is shared; the live menu reads the scenarios that can be drawn 2026-11-21 14:43:46 -06:00
rockdrigo 3fdc59df6d CaMa recurrence: the CLI entry imports its data folder; test of the entry a governance job runs 2026-11-21 13:43:19 -06:00
rockdrigo 9fe1f86c8b CaMa recurrence: a version trains, registers and publishes its figures (test) 2026-11-21 13:41:15 -06:00
rockdrigo 0804937578 CaMa recurrence: the METABRIC and SCAN-B analysis as a trainable scenario, with its scenario figures and a patient-to-scenario match 2026-11-21 13:34:56 -06:00
rockdrigo e99eb499d6 CaMa survival: the live figure is the clinical scenario's, over the production model and the live cohort 2026-11-21 13:14:06 -06:00
rockdrigo b1006a97d7 CaMa survival: the clinical scenarios are a shared module and stage 6 lists each scenario's risk factors; the live figure drops the unused options 2026-11-21 13:03:19 -06:00
rockdrigo 997aebd068 CaMa survival: a saved model is rehydrated with the current class before scoring 2026-11-21 12:15:22 -06:00
rockdrigo b8936522be CaMa survival: the figure for a selection of members, scored with the production model over the live cohort; the pipeline's chart wording 2026-11-21 12:07:21 -06:00
rockdrigo ec430c3ee3 CaMa survival: the published figure runs the SEER pipeline's stage-5 functions, and the production model keeps its structure settings 2026-11-21 10:33:48 -06:00
rockdrigo 0cf3e60341 CaMa survival: the published figure carries no test-data note 2026-11-21 10:13:47 -06:00
rockdrigo 4c8b559557 CaMa development record: tables carry their column order 2026-11-21 05:03:52 -06:00
rockdrigo f3be09467f CaMa survival: the SEER pipeline is imported only when a run develops the model 2026-11-21 03:33:44 -06:00
rockdrigo 9cccec5274 CaMa survival: lesion-size feature and the SEER development stages published with each version 2026-11-21 03:28:13 -06:00
rockdrigo 67787adfd4 Merge the SEER survival pipeline
# Conflicts:
#	README.md
#	models/cama/seer_survival/survival_models.py
#	pyproject.toml
2026-11-21 02:07:49 -06:00
rockdrigo edda0fd7b7 Merge CaMa survival scenario and its population results 2026-11-21 02:07:45 -06:00
rockdrigo acc8c371bc CaMa survival: the SEER interval-survival pipeline as a scenario with population results
models/cama/seer_survival is the SEER survival pipeline as Hamilton dataflows, with the interval LR and network keeping
their per-interval fits and surviving an interval without deaths. models/cama/survival is the scenario: it indexes the
total cohort at the first invasive biopsy report (steps/indexing.py), derives the covariates and the outcome from the
cohort's events, fits the interval survival, writes the five routines and publishes the population curves
(analisis/curvas.json) with the version. An estimate may carry the model's own index date.
2026-11-21 02:07:34 -06:00
edgar 941ae15a3e A risk carries the model's index date for its member
Risk and risk_rows give (pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo, ic_alto), the shape a batch now
stores: the horizons count from the model's index date, taken from the estimate's rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:46 -06:00
edgar 410de1d3b7 Each scenario's index and rules in its pipeline, matching dbt's cohorts
models/steps/indexing.py: a scenario that lists it gets its source cohort as `source_cohort`, and the node `cohort`
re-indexes it by `[config.index]` of its model.toml: the surveillance kind (first cytology) and the post-colposcopy
kind (visit k), with dbt's rules in dbt's order and names, the recruitment window taken from the source cohort's
parameters. Every kind ends with `observacion_previa_insuficiente`, a threshold on the days observed before the index
(0 for now: the data are left-truncated, so rules on earlier events read only what was recorded). On the synthetic
copy the pipeline gives dbt's patients, index dates and attrition for cin2_pim and cin2_logistic (surveillance) and
cin2_pim_post_colposcopy (visit 1, now on cacu/cohorte_total). cin2_logistic's MUESTREO records the index attrition and
the prior history; a stored build's lineage carries its parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 21:54:47 -06:00
edgar 0880181219 Merge dev into feature/cohorts-dbt-canonical: TEA EEG analysis and baselines
Conflicts: the README keeps this branch's rows and adds TEA's; `__main__` keeps the Scenario-based commands and adds
`_own_steps`; pyproject keeps the reports/ paths and adds the `eeg-reference` extra. `GIT_COMMIT_TAG` comes back in
`models.io.lineage` as the name of MLflow's own tag, which `models.tea.eeg.bundle` reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:05:13 -06:00
edgar ea6db36b23 dbt is the only definition of a cohort: the stored build runs dbt's queries
The WebApi cycle's build (models.cohorts.build.build_of) runs the cohort's queries from dbt's manifest with the same
chain as the export, instead of a Python frame per cohort; the TOML definitions, their frames and definition.py are
removed. A cohort may have no exclusions (cacu/cohorte_total, for models whose rules don't fit SQL) and an optional
`variables` query; the population meta carries the cohort's version. cohort_urls lists a domain's cohorts in the
manifest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 19:52:05 -06:00
edgar 06829a4498 Post-colposcopy scenario reads the cohort of the first surveillance visit
cin2_pim_post_colposcopy now reads cacu/cohorte_post_colposcopia_visita_1 (dbt): Cheung et al. 2020 index the risk at
the first surveillance visit with a cotest, not at the first cytology. Its description states the provisional
assumption that a colposcopy without a biopsy order is below CIN2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 19:52:02 -06:00
edgar 7d50786ac2 cin2_pim post-colposcopy and post-treatment scenarios, and their kit cohorts
Two TOML-only scenarios on cin2_pim's dataflow (KPNC's scenarios 4 and 5): CIN2+, KPNC's three post cytology groups,
the referral grade as history after colposcopy, and the strata that reproduce KPNC's tables 17 and 24 (one mixture per
referral grade; one mixture). The kit definitions of both cohorts mirror the dbt rules, so the WebApi cycle can build
them and KitBuild read them. A notebook describes the scenarios, their encoders and the shared DAG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 12:09:40 -06:00
edgar bde02109ab Surveillance cohort: a glandular-only index result counts as an index result
Mirror of the dbt rule no_index_result, which now reads the timeline's glandular rows (AGC, ADENOCARCINOMA) next to
the Bethesda and HPV ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 12:09:28 -06:00
edgar 3e72063e3f cin2_pim with PIMixture's I-spline baseline, frequency weights, HPV strata and KPNC's cytology categories
The incidence baseline is chosen in model.toml (Weibull or I-splines of order 4 with knots at quantiles, equal to
PIMixture's Ispline); identical rows are fitted once with their count as weight; one mixture per stratum, a member of
an unseen stratum or level gets NaN. The index cytology goes into KPNC's six categories, glandular results included and
the most severe winning; an optional history feature is read from the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 12:06:05 -06:00
AlbertoPMDM 200cb106e1 Merge feature/tea-eeg-analysis into feature/tea-eeg-baseline-bundles 2026-11-20 09:40:20 -06:00
AlbertoPMDM 70646e64b6 TEA EEG baselines trained on a local cohort and moved between installations as a bundle of group numbers 2026-11-20 09:36:41 -06:00
AlbertoPMDM 8eac071778 Loading a TEA EEG baseline leaves sys.path as it was, so later Dask workers still import tea.pipeline 2026-11-20 09:33:21 -06:00
AlbertoPMDM 7b8a4e8499 TEA EEG baselines keep their artifacts under MLFLOW_ARTIFACT_ROOT, not in the working directory 2026-11-19 23:17:42 -06:00
edgar 01e4406838 The notebook runner moves to reports/: experiment, notebook_jobs and notebook_import next to rendering and eda
They run a notebook on a build's file and keep it as an MLflow run, as eda does; io/ keeps the storage and MLflow
boundary and pipelines/ the cohort pipelines. Moved whole with git mv, imports repointed; models.notebook, the API
notebooks import, stays where it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:50:46 -06:00
edgar dce29670a4 The classifier's routines join the fitting steps: analytic_method, class_balance, output_confidence and routines
They depend only on the fitted pipeline and the split, so every scenario that lists models.steps.model_fitting
records them; sampling and missing_data stay in cin2_logistic, which owns windowed_outcomes and index_sample_results.
Moved as written in the merge (git blame -C follows them to 1b45bc6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:46:50 -06:00
edgar 6fbf573999 Merge dev into the Hamilton dataflow: the governance routines and the notebook runner on scenarios declared in model.toml
dev's 1b45bc6 (governance requirements, sandboxed notebooks) was written on the per-scenario driver that this branch
replaced with models.dags; it is carried over in that shape:

- cin2_logistic: the five ML-01a routines (sampling, missing_data, analytic_method, class_balance, output_confidence)
  and `routines` are nodes of the scenario's dataflow, on its node names (windowed_outcomes, train_set, test_set,
  fitted_pipeline, test_probabilities); `calibration_bins` is a config input with a default.
- io/adapters, dags/training: the saver writes each routine with TrainingRun.log_routine before logging the model;
  the driver hands it `routines` when the dataflow has that node. Without it a scenario still trains, but the registry
  won't promote it (ROUTINE_KINDS).
- io/tracking: dev's log_routine, run_files and run_file next to this branch's log_model (scikit-learn or pyfunc,
  pinned requirements).
- reports/rendering: dev's Quarto and Jupyter renderers (io/rendering.py, followed as a rename) with this branch's
  notebook hash; notebook_jobs and experiment import it from there, and cohort_reference and file_sha256 from
  io/storage.
- cin2_logistic/train.py: a delegate to models.dags.training for callers of the old driver.
- Persistance's English names from dev: persistance.edges.gold, cohort_repository.

Tests: 219 passed against the monorepo's dev Persistance, Extraction and Core (OCR with tesseract deselected).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:44:34 -06:00
edgar fe7f881ade CIN2+ PIM coding as KPNC's: a visit is free of CIN2+ with HPV-negative and NILM or ASC-US, a positive without histology leaves it unknown
known_negative takes lists per key; the last negative carries every earlier one, and follow-up without a test isn't
counted. docs/codificacion_pim.md gives the six example patients, each with its unit test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:23:36 -06:00
AlbertoPMDM 3669aa9eae TEA EEG analysis at the age the EDF header gives, the patient's rows as fallback; tea library 0.2.0 2026-11-19 19:20:29 -06:00
AlbertoPMDM 25c460f80e feat(tea): EEG analysis and age baselines on the tea library, installed from the libs/tea submodule 2026-11-19 15:43:27 -06:00
edgar 0be622c12d Models as a dataflow with Hamilton adapters: scenarios declared in model.toml, cohort read from the database or a file, a scikit-learn model registered with its requirements, estimates per horizon, and the CIN2+ prevalence-incidence scenario 2026-11-11 23:27:38 -06:00
edgar c9eb68ee42 Fitting steps every scenario shares: a temporal split, the classifier chosen by config, the fit and its metrics 2026-11-11 23:27:38 -06:00
131 changed files with 28123 additions and 1049 deletions
+3
View File
@@ -12,3 +12,6 @@ uv.lock
mlflow.db
mlruns/
mlartifacts/
# Jupyter
.ipynb_checkpoints/
+3
View File
@@ -0,0 +1,3 @@
[submodule "tea"]
path = libs/tea
url = ssh://git@10.0.10.41:2222/alberto/tea.git
+27 -14
View File
@@ -2,18 +2,20 @@
Lo que rodea a los modelos de riesgo de CaCu, CaMa y TEA: registro de
versiones en MLflow con requisitos de promoción, registro de predicciones y
los trabajos de OCR de reportes. Las cohortes con que se entrena son los
armados del kit de indicadores (`cohorte_armado`, en la base de cada
dominio). Lee y escribe por los mismos repositorios de `Persistance` que usa
los trabajos de OCR de reportes. Las cohortes se definen solo en dbt
(`Transformation/models/<dominio>/cohorts/`); el ciclo de la WebApi guarda un
armado de ellas (`cohorte_armado`, en la base de cada dominio, por
`models/cohorts/build.py`), y con ese armado se entrena y se estima. Las reglas
que no caben en SQL son del modelo, sobre `cacu/cohorte_total`. Lee y escribe por los mismos repositorios de `Persistance` que usa
WebApi.
| Módulo | Qué hace |
|---|---|
| `__main__.py` | La línea de comandos: `python -m models <comando>`. Cada área agrega ahí sus subcomandos. |
| `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). |
| `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`), dbt's manifest (`read_queries`), and Persistance repositories (`resolve_repository`, `ReadOnlyRepository`, ML-04). |
| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the hashes of code, files, tables and models (`code_version`, `model_sha`), and `matches`, the one rule for "already done". |
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), environment (ML-02), git commit and `log_model` with its `modelo_sha`. 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). |
| `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. `log_analysis` keeps what a run found about its cohort as `analisis/<name>.json`, and `log_report` a self-contained page as `reportes/<name>.html` (aggregates only). `run_files`/`run_file` list and download a run's files (a folder as a zip). |
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03, y ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias `produccion`. `artifacts`/`artifact` listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). |
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
@@ -21,16 +23,27 @@ 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 at the model's 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`. |
| `steps/report.py`, `pipelines/report_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 `notebooks/<scenario>/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it to one HTML page (`io/rendering.py`), 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. With Quarto, `QUARTO_BIN` and a Python with Jupyter (`QUARTO_PYTHON`). |
| `io/rendering.py` | 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). |
| `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. |
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member and horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
| `reports/` (`rendering.py`, `eda.py`) | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `<scenario>/notebooks/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). Rendering: Runs a notebook and renders its page. Renderers are classes (`RENDERERS`, `register_renderer`): `quarto` and `jupyter` (`nbclient` + `nbconvert`, the `notebooks` extra). `NOTEBOOK_RENDERER` picks one; otherwise Quarto if installed, else Jupyter. `NOTEBOOK_CELL_TIMEOUT` limits each cell (1800 s). |
| `reports/experiment.py` | A notebook uploaded to the platform, run on one exported cohort build as a run of `<domain>-<scenario>/experimentos`: the notebook, its page, what was imported from it (`importado.json`), `error.txt` if it failed, and tags for the notebook's hash, the build's file, the version, the code and where it ran (`sandbox`). `start` and `execute` are separate so the WebApi runs it in the background. |
| `reports/notebook_jobs.py` | Where the notebook runs: a job folder with the notebook, a copy of the build's file and of the chosen model, and an MLflow store of its own; every database URL is an empty in-memory one. Executors: `contenedor` leaves the job in `NOTEBOOK_JOBS_DIR` for the runner (`python -m models notebooks serve`, the `notebooks` container: no network, read-only, unprivileged, only that folder); `local` runs it in this process, unisolated, for development. |
| `reports/notebook_import.py` | Copies what the notebook trained in its own store into the platform's MLflow, as DEV runs and versions with the build's real cohort tags and a recomputed `modelo_sha`, never with an alias; refuses symbolic links and anything outside the job folder. |
| `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `<domain>-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. |
| `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Training records its five routines (`sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`). Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), 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/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
| `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`, its `routines`, `population` (`analisis/`) and `reports` (`reportes/`) when the dataflow has them, 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/report.py` | The subgroup report of every PIM scenario: per combination of the model's features, Turnbull's interval-censored estimate (prevalent at 0, free in `(l, r]`, unknown baseline in `[0, r]`) with a bootstrap band against the mixture refitted on every coded member with its delta-method band (inverse Hessian, log scale), and E/O at each horizon with log(E/O) taken as normal. `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. |
| `cacu/cin2_pim_post_colposcopy/`, `cacu/cin2_pim_post_treatment/` | `cin2_pim`'s dataflow on the post-colposcopy and post-treatment cohorts (KPNC's scenarios 4 and 5): only a `model.toml`, with KPNC's three post-colposcopy cytology groups and, after colposcopy, the referral grade (`history`). |
| `cacu/survival/` | CaCu's all-cause survival prototype: the mortality at 1, 3 and 5 years from the cancer diagnosis (provisionally the first biopsy reported as invasive carcinoma, `primera_biopsia_invasora` in `[config.index]`: both the inclusion criterion and the index date), from the age group at the diagnosis and the most recent cytology (KPNC's categories) and HPV up to it, with the SEER pipeline's interval survival as `cama/survival` runs it (LR and Bayesian network per interval, stacked) and its population record (`analisis/curvas.json`: KM with Greenwood, adjusted KM, Weibull, and LR/HBN/combined points with bootstrap intervals). The nodes that don't depend on the covariates are CaMa's, called from here; `encode`, `interval_cohort`, `IntervalSurvival`, `labelled_members`, `missing_data`, `analytic_method` and `survival_frame` are copies over CaCu's covariates (issue #9). A version also keeps a subgroup report (`report.py`): per combination of the covariates, the Kaplan-Meier with its Greenwood band against the model's survival with the SEER subgroups' bootstrap interval (`sv_sub_points`), as `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. The death is the timeline's `defuncion` event, emitted by the CaCu dbt timeline (monorepo, same branch). |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `<escenario>/notebooks/`, fuera del paquete instalado. |
| `tea/eeg/` | TEA's EEG analysis on one EDF, with the `tea` library (`libs/tea`, a submodule installed editable): `model.toml` maps each `MetricaEeg` code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); `analyze.measure` runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; `baselines.Baselines` compares a value with its age baseline in production (`tea-eeg-<biomarker>[-<stage>]`): z, -1/0/+1 and the curve's p5/median/p95 at the age. |
| `tea/eeg/train.py`, `tea/eeg/model.py` | TEA's age baselines: `python -m models run tea eeg --train [--promote] [--environment prod]` lists the reference cohort (`[reference]` of `model.toml`: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the `eeg-reference` extra), measures each study with the analysis's own unit of work (`analyze.reference`), and trains each scenario (biomarker and sleep stage) with the library, registered as `tea-eeg-<biomarker>[-<stage>]` through `tea.serving.log_biomarker` and tagged with what promotion checks: environment, the reference cohort (`cohort.source = referencia`, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI`); with a remote scheduler (`DASK_SCHEDULER_ADDRESS`), the workers need `models` and `tea` installed. |
| `tea/eeg/reference.py`, `tea/eeg/bundle.py` | Training the baselines where the EEGs live and shipping only the result. `models run tea eeg --train --reference-dir DIR [--reference-ages edades.csv] [--reference-name NAME] [--line-hz 60]` trains on a folder of EDFs on this machine (ages from the table's `archivo` and `edad_meses` or `edad_anos`, or from each EDF header); file names stay in the listing, keyed by position. `models tea export-baselines --out baselines.zip [--environment prod] [--production]` writes every scenario's trained module, plan, routine records, metrics and promotion tags, with a SHA-256 manifest, after the library's privacy guard; `models tea import-baselines baselines.zip` checks the manifest, accepts only the module class the platform runs for each scenario, requires the trained module's hash, and registers new versions with the same tags (an already-registered module is kept). Promotion still waits for the three reports. |
| `eeg_analysis.py` | The EEG analysis against TEA's database: the pending EEGs (an EDF never analysed, or analysed with another plan, other module versions or other baselines), the batch (`cluster`: this process, a LocalCluster or `DASK_SCHEDULER_ADDRESS`), each result written to `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo` with ids that survive a re-analysis, and one governance `ExtractionRun` per EEG. `python -m models tea analyze [--all] [--limit N] [--cluster auto\|local\|remote\|sync]`. |
| `cama/seer_survival/` | CaMa's SEER survival pipeline, ported from six scripts into Hamilton DAGs, one per stage (extra `seer-survival`). Settings in `model.toml` (`settings.py`); paths are inputs, never settings. Each stage is a module of nodes plus, where the routine is heavy, a module of plain functions apart (as `tea/eeg/analyze.py`): `depuration.py` + `depuration_stats.py` (01: Theil's U and GVIF redundancy screen and its threshold calibration), `balancing.py` + `balancing_stats.py` and `categorization.py` + `categorization_stats.py` (02: 18-month outcome, MCA undersampling, Bayesian change-point grouping of age and tumor size, categorization proposals), `bootstrap.py` (03: resample indices), `modeling.py` + `lr_selection.py`, `hbn.py`, `natural.py`, `resampling.py` + `replica.py` (04: stepwise LR, hybrid Bayesian network, natural-population LR, bootstrap and proposal replicas), `survival_curves.py` + `survival_models.py`, `fractional_weibull.py` (05: Kaplan-Meier, classic and Kilbas-Saigo Weibull, stacked LR + HBN survival, subgroups) and `risk_factors.py` + `risk_factor_stats.py` (06: four-criteria risk factors). `run.py` writes each stage's files; `pipeline.py` runs them in order, skipping the current ones: `python -m models.cama.seer_survival --data DIR [--solo 05] [--desde 02] [--forzar 02 04] [--todo]`. |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
+172
View File
@@ -0,0 +1,172 @@
# Codificación de la línea de tiempo para el modelo prevalencia–incidencia
Cómo la historia de cada paciente se resume en un código $C$ y un intervalo $(L, R]$, qué factor aporta a la
verosimilitud y en qué columnas del *Enrollment table* de KPNC cae. La codificación la hace
`models.cacu.cin2_pim.model.interval_coded_members`; cada ejemplo de abajo tiene su prueba unitaria en
`tests/cacu/test_cin2_pim.py` (`test_patient_1_…` a `test_patient_6_…`, más VPH−/ASC-US como negativo y
VPH+/NILM como desconocido).
## Modelo
- $\pi(x) = \operatorname{expit}(x^\top\theta)$: probabilidad de NIC2+ en la visita índice (prevalencia, logística).
- $S(t \mid z) = \exp\{-\Lambda_0(t)\, e^{z^\top\beta}\}$: supervivencia libre de NIC2+ incidente (riesgos
proporcionales), con $\Lambda_0$ Weibull, $(t/\lambda)^k$, o los I-splines de PIMixture, $\sum_j e^{\gamma_j} I_j(t)$
(`incidence` en `model.toml`). Una mezcla por estrato (`strata`: VPH en el tamizaje,
grado de la referencia después de colposcopía, ninguno después de tratamiento), con la citología índice en las
categorías de KPNC.
- Riesgo acumulado: $CR(t) = \pi + (1-\pi)\,[1 - S(t)]$.
El tiempo se cuenta en años desde la visita índice $T_0$.
## Reglas de codificación
- $R$: fecha de la **primera biopsia NIC2+** (o $\infty$ si no hay).
- $L$: fecha del **último hallazgo libre de NIC2+ antes de $R$**: una biopsia menor a NIC2+, o una visita con
visita con VPH negativo y citología NILM o ASC-US (el negativo sin histología de KPNC; `known_negative` en
`model.toml`). Una prueba positiva sin histología (VPH+, o LSIL o peor) deja el estado desconocido. Si cae dentro
de la ventana basal (`prevalent_window_months`), $L = 0$.
- $C = 1$ si $R$ cae dentro de la ventana basal; $C = 0$ si hubo al menos un hallazgo libre; si no, $C = -999$.
- El seguimiento sin prueba no cuenta: nadie se considera libre hasta el corte de datos, solo hasta su último negativo.
## Factor de verosimilitud por paciente
| $C$ | $(L, R]$ | Factor $\mathcal{L}_i$ | Logística | Incidencia |
|---|---|---|---|---|
| 1 | $(0, 0]$ | $\pi$ | caso | — |
| 0 | $(L, R]$, $R<\infty$ | $(1-\pi)\,[S(L) - S(R)]$ | control | censura por intervalo |
| 0 | $(L, \infty)$ | $(1-\pi)\,S(L)$ | control | censura derecha en $L$ ($L=0$: nada) |
| −999 | $(0, R]$ | $\pi + (1-\pi)\,[1 - S(R)]$ | latente | latente |
| −999 | $(0, \infty)$ | $1$ | — | — |
Con $C$ conocido el logaritmo se separa en una logística y un modelo de supervivencia con censura por intervalo:
$$
\ell = \underbrace{\sum_{C=1}\log\pi + \sum_{C=0}\log(1-\pi)}_{\text{logística}}
+ \underbrace{\sum_{C=0}\log[S(L)-S(R)]}_{\text{incidencia}}
+ \sum_{C=-999}\log\{\pi + (1-\pi)[1-S(R)]\}.
$$
Solo los desconocidos acoplan las dos partes. La probabilidad posterior de que un desconocido diagnosticado en $R$
fuera prevalente es $w = \pi / \{\pi + (1-\pi)[1-S(R)]\}$.
### Por qué varias visitas dan un solo factor
Con enfermedad absorbente (no regresa), negativos verdaderos (sensibilidad 1) y calendario de visitas no informativo,
para negativos en $t_1 < \dots < L$ y NIC2+ en $R$:
$$
P(\text{neg } t_1,\dots,\text{neg } L,\ \text{pos } R) = P(T > L,\ T \le R) = S(L) - S(R).
$$
El último negativo implica todos los anteriores. Si la sensibilidad es menor que 1 o la lesión puede regresar, cada
visita aporta su propio factor (verosimilitud con filtro hacia adelante, como en el modelo generativo de `bayes-pim`).
## Ejemplos
Todas las pacientes tienen ASC-US/VPH+ en $T_0$, así que entran en la celda **VPH+ / ASC-US** del Enrollment table
(la celda la define el resultado índice; visitas posteriores no crean otra fila en esta tabla).
| Paciente | Historia | $(C, L, R]$ | Factor | Logística | Incidencia | Columnas del Excel |
|---|---|---|---|---|---|---|
| 1 | $T_1$ (1 mes): colposcopía, NIC3 | $(1, 0, 0]$ | $\pi$ | caso | — | n, informativa, caso, prevalente |
| 2 | $T_1$: biopsias normales; $T_2$ (1 año): cotest negativo; $T_3$: ASC-US/VPH+; $T_4$: NIC3 | $(0, T_2, T_4]$ | $(1-\pi)[S(T_2)-S(T_4)]$ | control | intervalo $(T_2, T_4]$ | n, informativa, caso, incidente |
| 3 | Colposcopía omitida; $T_1$: ASC-US/VPH+; $T_2$: NIC3 | $(-999, 0, T_2]$ | $\pi + (1-\pi)[1-S(T_2)]$ | latente (peso $w$) | latente (peso $1-w$) | n, informativa, caso, desconocido |
| 4 | Colposcopía omitida; $T_1$ (1 año): cotest negativo | $(0, T_1, \infty)$ | $(1-\pi)\,S(T_1)$ | control | censura derecha en $T_1$ | n, informativa |
| 5 | $T_1$ (1 mes): biopsias normales; sin más visitas | $(0, 0, \infty)$ | $1-\pi$ | control | — | n, informativa |
| 6 | Colposcopía omitida; no regresa | $(-999, 0, \infty)$ | $1$ | — | — | n |
Prevalente, incidente y desconocido reparten solo a los **casos**; las no-caso informativas (4 y 5) no tienen
columna propia.
Notas:
- **Paciente 2.** El ASC-US/VPH+ de $T_3$ no es un negativo: la lesión pudo existir desde $T_3$. La biopsia normal de
$T_1$ queda implicada por el negativo de $T_2$.
- **Paciente 3.** No es $L = R = T_2$ (eso diría que la lesión apareció justo en $T_2$). Es censura izquierda en
$T_2$: $T \le T_2$, incluida la masa en cero (prevalente).
- **Paciente 4.** Depende de que la lesión no regrese: razonable para NIC3+, discutible para NIC2 (que regresa con
frecuencia), y de que el cotest negativo sea verdadero. $R = \infty$; el $-999$ es el código de $C$, no de $R$.
- **Paciente 5.** El negativo cae en la ventana basal, $L = 0$ y $S(0) = 1$: solo informa la prevalencia.
- **Paciente 6.** No aporta, siempre que la pérdida de seguimiento sea no informativa (MAR); si quienes omiten la
colposcopía tienen otro riesgo, el modelo no lo detecta.
## Protocolo clínico de KPNC y definiciones de la tabla
Cheung LC, Egemen D, Chen X, et al. *2019 ASCCP Risk-Based Management Consensus Guidelines: Methods for Risk
Estimation, Recommended Management, and Validation*. J Low Genit Tract Dis 2020;24(2):90–101.
doi:10.1097/LGT.0000000000000528 (PMC7147416). Las tablas de riesgo están en Egemen D, et al., J Low Genit Tract Dis
2020;24(2):132–143, doi:10.1097/LGT.0000000000000529, y las de genotipificación (VPH16/18) en Demarco M, et al., J Low
Genit Tract Dis 2020;24(2):144–147, doi:10.1097/LGT.0000000000000530.
**Protocolo** (sección *Screening Tests and Clinical Management in the KPNC*):
> "Patients with cytologic abnormalities were referred to colposcopy per Kaiser guidelines, which closely resembled US
> consensus recommendations. However, those without abnormalities, specifically patients who tested HPV negative/NILM
> (cotest negative) were asked to return for testing in 3 years. […] Patients with HPV-negative/ASC-US or
> HPV-positive/NILM results were monitored annually and referred to colposcopy for either a subsequent abnormal
> cytology result or HPV positivity (after 2005)."
Cotest (HC2 + citología) desde 2003 en ≥ 30 años, desde 2013 en 25–29; tratamiento de NIC2+ con LEEP.
**Qué mide el riesgo** (sección *Risk Estimation and Definition of Intervals…*):
> "The CIN 2+ and CIN 3+ risks represent precancers and cancers that are detectable through colposcopy with multiple
> biopsies (not just targeted to the single worst appearing region)."
**Definiciones de prevalente, incidente y desconocido** (misma sección):
> "We define prevalent CIN 3+ as CIN 3+ detected after colposcopic referral because of the baseline (current) test
> results. We define a patient as having <CIN 3 at a visit if the diagnosis was either (1) directly confirmed through
> histopathology or, in the absence of histopathologic outcomes, (2) if neither HPV nor cytology tests were positive
> (i.e., HPV negative/NILM or HPV negative/ASC-US). […] patients with positive test results (HPV-positive or ≥LSIL
> cytology results), but without histopathologic outcomes or a future <CIN 3 to rule out CIN 3+, are considered to
> have unknown (in statistical terms, "latent") histologic status at that screen."
> "(1) prevalent (left-censored at the current test), (2) incident (interval-censored between the last result <CIN 3
> and the time of CIN 3+ detection), or (3) unknown prevalent or incident (CIN 3+ detected in follow-up but cannot rule
> out disease prevalence). Patients who never had CIN 3+ detected were considered right censored at the time of the
> last <CIN 3 visit. Individuals who were never defined as <CIN 3 or CIN 3+ at any time points did not contribute to
> risk estimation."
Ejemplos de historias codificadas: apéndice C (material suplementario) del mismo artículo.
**Supuestos declarados** (Discusión): (1) VPH−/NILM y VPH−/ASC-US son <NIC3; (2) la histopatología es correcta;
(3) el NIC3+ diagnosticado no regresa; (4) censura independiente y no informativa; (5) que un caso de seguimiento sea
prevalente o incidente depende solo de covariables conocidas (MAR).
**Genotipificación.** VPH16/18 solo se midió en una submuestra en dos fases (estudio PaP); se ponderó cada paciente
por el inverso de su fracción de muestreo ("survey weights") para reconstituir la cohorte.
### Diferencias con nuestro protocolo
- **Biopsia.** KPNC define el riesgo respecto a colposcopía con biopsias múltiples. Aquí solo se biopsia si la
impresión colposcópica es LIEBG+. Una colposcopía con impresión normal y sin biopsia no es "<CIN 3 confirmado por
histopatología": bajo las definiciones de KPNC la visita queda **desconocida**, no negativa. Tratarla como negativa
exige modelar la sensibilidad de la impresión colposcópica (modelo por visita). Además, el riesgo "inmediato" que
estimemos es el detectable con biopsia dirigida, menor que el de KPNC: una razón O/E < 1 frente a sus tablas no
significa por sí sola menor riesgo.
- **Negativo sin histología.** Alineado con KPNC (2026-11-13): VPH−/NILM y VPH−/ASC-US, en la basal y en el
seguimiento, en `models-pim` (`known_negative`) y en la simulación de `bayes-pim` (`cells.NEGATIVE_CYTOLOGY`,
`generative.pim_codes`). Antes solo NILM/VPH−; la simulación además contaba como negativo un resultado "leve"
del seguimiento (VPH+/NILM, VPH−/LSIL), que ahora deja el estado desconocido.
- **Genotipificación.** Nuestras submuestras con VPH16/18 no vienen de un diseño con fracciones conocidas: la
probabilidad de estar tipificada (por unidad, periodo, laboratorio, resultado) tendría que estimarse, y el IPW con
pesos estimados (que Hyun et al. 2017 contemplan) solo corrige si la tipificación es MAR dadas esas variables.
## Referencia y estimación
Hyun N, Cheung LC, Pan Q, Schiffman M, Katki HA. *Flexible risk prediction models for left or interval-censored data
from electronic health records*. Ann Appl Stat 2017;11(2):1063–1084. doi:10.1214/17-AOAS1036.
- Los desconocidos se tratan **dentro de la verosimilitud** como $C$ faltante bajo MAR: su factor es la mezcla de la
tabla y el mecanismo de faltante es ignorable. No se imputan ni se ponderan.
- El **IPW** del artículo es para otra cosa: la tipificación de VPH se hizo solo en una submuestra estratificada en dos
fases (9,258 de 33,295 mujeres), y cada mujer de la submuestra se pondera por el inverso de su probabilidad de
inclusión para representar a la cohorte. Sin submuestreo, todos los pesos valen 1 y se recupera la verosimilitud de
arriba.
- El **algoritmo iterativo** es el del estimador semiparamétrico (logística-Cox con $\Lambda$ no paramétrica): alterna
(i) $\Lambda$ con el *iterative convex minorant* (ICM) dados los coeficientes y (ii) los coeficientes
$(\theta, \beta)$ con IRLS dado $\Lambda$, hasta converger. El modelo débilmente paramétrico ($\Lambda$ con B-splines
integrados) se ajusta con Newton–Raphson. Nuestro Weibull maximiza la misma verosimilitud directamente.
- Supuestos que el propio artículo declara: enfermedad progresiva (sin regresión) y verificación perfecta del
desenlace; ambos se relajan solo con un modelo por visita.
File diff suppressed because one or more lines are too long
Submodule
+1
Submodule libs/tea added at 05ee02990c
+158 -52
View File
@@ -14,27 +14,35 @@ def _show_help(parser: argparse.ArgumentParser) -> int:
return 2
def _model_module(args: argparse.Namespace, name: str):
"""A module of the model's folder; `None` and a message on stderr if there's no such model."""
from importlib import import_module
def _scenario(args: argparse.Namespace):
"""The scenario's `model.toml`; `None` and a message on stderr if there's no such model."""
from models.dags.training import Scenario
package = f"models.{args.domain}.{args.scenario}"
try:
return import_module(f"{package}.{name}")
except ModuleNotFoundError as error:
if not (error.name or "").startswith(package):
raise
print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr)
return Scenario.load(args.domain, args.scenario)
except LookupError as error:
print(error, file=sys.stderr)
return None
def _cohort_file(args: argparse.Namespace, model):
def _own_steps(args: argparse.Namespace):
"""A scenario that isn't trained on a cohort build runs its own steps: its `model.run_steps`, or `None`."""
from importlib import import_module
try:
model = import_module(f"models.{args.domain}.{args.scenario}.model")
except ModuleNotFoundError:
return None
return getattr(model, "run_steps", None)
def _cohort_file(args: argparse.Namespace, scenario):
"""The build's exported file; `None` and a message on stderr if it's missing."""
from persistance.settings import settings
from models.io.storage import cohorts_root, dbt_build_path, find_cohort_file, latest_dbt_build
url = model.SETTINGS["cohort"]
url = scenario.cohort
command = f"python -m models cohorts export {url.replace('/', ' ')}" + (" --source dbt" if args.source == "dbt" else "")
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
@@ -52,28 +60,51 @@ def _cohort_file(args: argparse.Namespace, model):
return None
def _cohort_source(args: argparse.Namespace, scenario):
"""Where the build's rows come from: a kit build from the database (`--read db`, the default), or an exported
file (`--read file`, and always for dbt's builds, which only exist as files). `None` and a message if missing."""
from models.io.storage import CohortFile, KitBuild
if args.source == "kit" and getattr(args, "read", "file") == "db":
from importlib import import_module
cohorts = import_module(f"persistance.{args.domain}").cohort_repository
build_id = args.armado if args.armado is not None else cohorts.latest_build(scenario.cohort)
if build_id is None:
print(f"no kit builds of {scenario.cohort}", file=sys.stderr)
return None
return KitBuild(args.domain, build_id, cohorts=cohorts)
path = _cohort_file(args, scenario)
return CohortFile(path) if path else None
def _describe(source) -> str:
return str(getattr(source, "path", None) or f"kit build {source.build_id}")
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Trains the model on the build's file, always as a new version."""
"""Trains the model on the build, always as a new version."""
if args.environment == "prod" and args.armado is None:
parser.error("a prod run names its cohort build: --build (ML-03)")
if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")):
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
return 1
if not (path := _cohort_file(args, model)):
return 1
print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}")
from models.dags.training import train
print(f"{args.domain}/{args.scenario} version {train(scenario, source, args.environment.upper())}, "
f"from {_describe(source)}")
return 0
def _estimate_step(args: argparse.Namespace, path) -> int:
estimator = _model_module(args, "estimate")
if not estimator:
return 1
def _estimate_step(args: argparse.Namespace, scenario, source) -> int:
from models.dags.estimation import estimate
try:
resolved, written = estimator.estimate(path, args.output, args.version)
resolved, written = estimate(scenario, source, args.output, args.version)
except LookupError as error:
print(error, file=sys.stderr)
return 1
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {path}, to {args.output}")
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {_describe(source)}, "
f"to {args.output}")
return 0
@@ -98,13 +129,12 @@ def _report_eda(args: argparse.Namespace) -> int:
"""Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report."""
from pathlib import Path
from models.io.rendering import RenderError
from models.pipelines.report_eda import report_eda
from models.reports.eda import report_eda
from models.reports.rendering import RenderError
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
if not (scenario := _scenario(args)) or not (path := _cohort_file(args, scenario)):
return 1
notebook = Path(args.notebook) if args.notebook else (
Path(model.__file__).parents[1] / "notebooks" / args.scenario / "01_eda.ipynb")
notebook = Path(args.notebook) if args.notebook else scenario.folder / "notebooks" / "01_eda.ipynb"
if not notebook.exists():
print(f"no notebook at {notebook}", file=sys.stderr)
return 1
@@ -118,11 +148,11 @@ def _report_eda(args: argparse.Namespace) -> int:
def _serve_notebooks(args: argparse.Namespace) -> int:
"""The runner container's loop (`models.io.notebook_jobs.serve`)."""
"""The runner container's loop (`models.reports.notebook_jobs.serve`)."""
import os
from pathlib import Path
from models.io.notebook_jobs import JOBS_DIR_ENV, serve
from models.reports.notebook_jobs import JOBS_DIR_ENV, serve
folder = args.jobs or os.environ.get(JOBS_DIR_ENV)
if not folder:
@@ -132,11 +162,51 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build's file with a registered version and writes the output file."""
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
def _tea_analyze(args: argparse.Namespace) -> int:
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
from models.eeg_analysis import analyze_pending
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster)
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
return 1 if s.failed else 0
def _tea_export_baselines(args: argparse.Namespace) -> int:
"""The trained age baselines as one bundle (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, export
from models.tea.eeg.settings import settings
try:
done = export(settings(), args.out, environment=args.environment.upper(), production=args.production)
except BundleError as error:
print(f"not exported: {error}", file=sys.stderr)
return 1
return _estimate_step(args, path)
for scenario, version in done.versions.items():
print(f"{scenario}: version {version}")
print(f"written: {done.path} (sha256 {done.sha256})")
return 0
def _tea_import_baselines(args: argparse.Namespace) -> int:
"""The age baselines of a bundle, registered (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, import_
from models.tea.eeg.settings import settings
try:
done = import_(settings(), args.bundle)
except BundleError as error:
print(f"not imported: {error}", file=sys.stderr)
return 1
for scenario, (version, new) in done.items():
print(f"{scenario}: {'imported as' if new else 'already registered as'} version {version}")
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build with a registered version and writes the output file."""
if not (scenario := _scenario(args)) or not (source := _cohort_source(args, scenario)):
return 1
return _estimate_step(args, scenario, source)
def _promote_step(args: argparse.Namespace, version: str) -> int:
@@ -168,6 +238,8 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
if not (args.export or args.train or args.promote or args.estimate or args.store):
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
if (own := _own_steps(args)) is not None:
return own(args)
if (args.estimate or args.store) and not args.output:
parser.error("--estimate and --store need --output")
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
@@ -178,11 +250,12 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
parser.error("a dbt build is numbered when it's exported: --build can't go with --export --source dbt")
if args.train and args.version:
parser.error("--version names an existing version: it can't go with --train")
if not (model := _model_module(args, "model")):
if not (scenario := _scenario(args)):
return 1
if args.export:
cohort = model.SETTINGS["cohort"].split("/", 1)[1]
args.read = "file"
cohort = scenario.cohort.split("/", 1)[1]
export = argparse.Namespace(domain=args.domain, cohort=cohort, source=args.source, build=args.armado,
manifest=args.manifest)
if args.source == "dbt":
@@ -192,25 +265,25 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
if not (args.train or args.promote or args.estimate):
return _store_step(args, args.output) if args.store else 0
if not (path := _cohort_file(args, model)):
if not (source := _cohort_source(args, scenario)):
return 1
version = args.version
if args.train or (args.promote and not version):
if not (trainer := _model_module(args, "train")):
return 1
from models.dags.training import find_trained, train
environment = args.environment.upper()
version = trainer.find_trained(path, environment)
version = find_trained(scenario, source, environment)
if args.train and version:
print(f"already trained: version {version}, from {path}")
print(f"already trained: version {version}, from {_describe(source)}")
elif args.train:
version = trainer.train(path, environment)
print(f"trained: version {version}, from {path}")
version = train(scenario, source, environment)
print(f"trained: version {version}, from {_describe(source)}")
elif not version:
print(f"no {environment} version trained on {path}: use --train or --version", file=sys.stderr)
print(f"no {environment} version trained on {_describe(source)}: use --train or --version", file=sys.stderr)
return 1
if args.promote and (code := _promote_step(args, version)):
return code
if args.estimate and (code := _estimate_step(args, path)):
if args.estimate and (code := _estimate_step(args, scenario, source)):
return code
return _store_step(args, args.output) if args.store else 0
@@ -368,26 +441,30 @@ def build_parser() -> argparse.ArgumentParser:
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
show.add_argument("domain", choices=["cacu", "cama", "tea"])
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'")
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
show.add_argument("--build", type=int, required=True, help="the build's number")
show.set_defaults(run=_cohort_show)
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
train = commands.add_parser("train", help="train a model on a cohort build and register a version")
train.add_argument("domain", choices=["cacu", "cama", "tea"])
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
train.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
train.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
train.set_defaults(run=lambda args: _train(train, args))
estimate = commands.add_parser("estimate", help="score a cohort build's file with a registered version")
estimate = commands.add_parser("estimate", help="score a cohort build with a registered version")
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
estimate.add_argument("--output", required=True, help="the Parquet file to write")
estimate.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
estimate.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
@@ -397,10 +474,10 @@ def build_parser() -> argparse.ArgumentParser:
eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow")
eda.add_argument("domain", choices=["cacu", "cama", "tea"])
eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
eda.add_argument("--notebook", help="the notebook; the scenario's notebooks/<scenario>/01_eda.ipynb by default")
eda.add_argument("--notebook", help="the notebook; the scenario's <scenario>/notebooks/01_eda.ipynb by default")
eda.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
eda.set_defaults(run=_report_eda)
@@ -420,13 +497,42 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
run.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="kit: a build the WebApi cycle stored; dbt: one built now (both from dbt's rules)")
run.add_argument("--read", choices=["db", "file"], default="db",
help="a kit build read from the database, or its exported file; dbt's builds are files")
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.add_argument("--reference-dir", help="tea eeg: train on the EDFs of this folder instead of the configured cohort")
run.add_argument("--reference-ages", help="tea eeg: CSV of `archivo` and `edad_meses` (or `edad_anos`); "
"without it, each EDF header's age")
run.add_argument("--reference-name", help="tea eeg: a name for that cohort (no names or dates of people)")
run.add_argument("--line-hz", type=float, help="tea eeg: the mains frequency where it was recorded (60)")
run.set_defaults(run=lambda args: _run(run, args))
tea = commands.add_parser("tea", help="TEA's EEG analysis")
tea.set_defaults(run=lambda args: _show_help(tea))
tea_actions = tea.add_subparsers(dest="action", metavar="<action>")
analyze = tea_actions.add_parser(
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
analyze.set_defaults(run=_tea_analyze)
export_baselines = tea_actions.add_parser(
"export-baselines", help="write the trained age baselines to one bundle: group numbers only, nothing per child")
export_baselines.add_argument("--out", required=True, help="the bundle to write (.zip)")
export_baselines.add_argument("--environment", choices=["dev", "prod"], default="prod")
export_baselines.add_argument("--production", action="store_true",
help="the versions in production, instead of the newest trained in --environment")
export_baselines.set_defaults(run=_tea_export_baselines)
import_baselines = tea_actions.add_parser(
"import-baselines", help="register the age baselines of a bundle; promotion still needs their reports")
import_baselines.add_argument("bundle", help="the bundle `export-baselines` wrote")
import_baselines.set_defaults(run=_tea_import_baselines)
notebooks = commands.add_parser("notebooks", help="the runner of notebooks uploaded to the platform")
notebooks.set_defaults(run=lambda args: _show_help(notebooks))
notebook_actions = notebooks.add_subparsers(dest="action", metavar="<action>")
+45
View File
@@ -0,0 +1,45 @@
"""Validators a dataflow puts on its nodes. Nothing here does I/O or imports MLflow.
- `@checked_frame(schema)`: validates the node's frame with a pandera schema and fails the run if it doesn't hold. The
failure names the columns, the checks and how many rows failed, never the values: pandera's own report (and
`@check_output(schema=...)`) quotes them.
"""
from typing import Any
import pandas as pd
import pandera.pandas as pandera
from hamilton.data_quality.base import DataValidator, ValidationResult
from hamilton.function_modifiers import check_output_custom
class FrameCheck(DataValidator):
"""A pandera schema as a Hamilton validator whose message carries no data values."""
def __init__(self, schema: pandera.DataFrameSchema, importance: str = "fail"):
super().__init__(importance)
self.schema = schema
def applies_to(self, datatype: type) -> bool:
return issubclass(datatype, pd.DataFrame)
def description(self) -> str:
return f"rows satisfy {self.schema.name or 'the schema'}"
@classmethod
def name(cls) -> str:
return "frame_check"
def validate(self, dataset: Any) -> ValidationResult:
try:
self.schema.validate(dataset, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases.fillna({"column": "(frame)"})
counts = cases.groupby(["column", "check"], dropna=False).size()
summary = "; ".join(f"{column}: {check} failed {n} time(s)" for (column, check), n in counts.items())
return ValidationResult(False, f"{self.description()} doesn't hold: {summary}")
return ValidationResult(True, f"{self.description()}: holds")
def checked_frame(schema: pandera.DataFrameSchema):
return check_output_custom(FrameCheck(schema))
-41
View File
@@ -1,41 +0,0 @@
"""Scores a build's file with a registered version and writes the probabilities to a Parquet file."""
from pathlib import Path
import mlflow.pyfunc
import pyarrow as pa
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import read_cohort, read_metadata, write_once
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
"""Whether the output file already holds this version's scores of this build's file."""
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]:
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
The file's metadata says which version and which build's file (`models.io.lineage.cohort_reference`) its rows
come from, and the outcome and horizon they estimate (`cin2_12m`, 1.0 years); `modelo_sha` is copied when the
version has it, and isn't checked."""
domain, scenario = SETTINGS["domain"], SETTINGS["scenario"]
output_path = Path(output_path)
resolved = registry.resolve(domain, scenario, version)
cohort = cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
window = SETTINGS["outcome_window_months"]
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
"mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12),
**cohort}
if resolved.modelo_sha:
provenance["modelo_sha"] = resolved.modelo_sha
table = pa.Table.from_pandas(risks, preserve_index=False)
write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path)
return resolved, True
+58 -152
View File
@@ -1,127 +1,96 @@
"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology.
`y` is 1 when a biopsy graded in `event_grades` falls within `outcome_window_months` of the index date. A member with
`y` is 1 when a biopsy graded in `event_grades` falls within the window (`horizons_years`, one) of the index date. A member with
no such biopsy whose follow-up to the build's cut-off (`datos_as_of`) is shorter than the window isn't known yet:
it's scored but left out of training and evaluation. The predictors are the index sample's own results (Bethesda
category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported;
nothing after them is used.
Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver.
The split, the classifier, the fit, the metrics and the classifier's routines (ML-01a) are
`models.steps.model_fitting`'s, listed with this module in `model.toml`; `sampling` and `missing_data`, the routines
that depend on this scenario's members and predictors, are here. `fitted_model` puts `IndexSampleResults` in front of the fitted pipeline, so the registered model is one
scikit-learn `Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through
loaders, and registering is the driver's saver (`models.dags.training`).
"""
import tomllib
from datetime import date
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
import pandera.pandas as pandera
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256
from models.io.registry import registry
from models.io.storage import read_cohort, read_metadata
from models.io.tracking import TrainingRun
from models.annotations import checked_frame
from models.io.contracts import DAYS_PER_YEAR
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
PREDICTORS = ("bethesda", "vph", "vph_16_18")
MISSING = "(none)"
DAYS_PER_MONTH = 30.44
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"y": pandera.Column(int, pandera.Check.isin([0, 1]))},
name="labelled members")
def cohort(cohort_path: str) -> pd.DataFrame:
return read_cohort(cohort_path)
def lineage(cohort_path: str) -> dict:
return read_metadata(cohort_path)
def cohort_sha256(cohort_path: str) -> str:
return file_sha256(cohort_path)
def code_sha256() -> str:
"""The hash of this folder's steps and settings: what says the model itself changed."""
folder = Path(__file__).parent
return file_sha256(folder / "model.py", folder / "model.toml")
def cutoff(lineage: dict) -> date:
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file."""
return date.fromisoformat(lineage["datos_as_of"])
return date.fromisoformat(cohort_lineage["datos_as_of"])
def predictors(cohort: pd.DataFrame) -> pd.DataFrame:
def index_sample_results(cohort: pd.DataFrame, predictor_columns: list[str]) -> pd.DataFrame:
"""One row per member: `pac_id`, `fecha_indice` and the index sample's results, `(none)` where it has none."""
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] == cohort["fecha_indice"])]
sample = sample.groupby("pac_id")["fuente_id"].first().rename("sample")
results = cohort.merge(sample, left_on="pac_id", right_index=True)
results = results[results["fuente_id"] == results["sample"]]
results = results[results["fuente_id"] == results["sample"]].copy()
genotype = results["tipo"] == "vph_genotipo_16_18"
results.loc[genotype, "valor_codigo"] = results.loc[genotype, "valor_numerico"].map({1.0: "POSITIVO", 0.0: "NEGATIVO"})
results["tipo"] = results["tipo"].replace({"vph_genotipo_16_18": "vph_16_18"})
wide = results[results["tipo"].isin(PREDICTORS)].pivot_table(
wide = results[results["tipo"].isin(predictor_columns)].pivot_table(
index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
wide = wide.reindex(columns=list(PREDICTORS))
wide = wide.reindex(columns=list(predictor_columns)).astype(object)
return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna(
{name: MISSING for name in PREDICTORS})
{name: MISSING for name in predictor_columns})
def outcome(cohort: pd.DataFrame, cutoff: date) -> pd.DataFrame:
def windowed_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, horizons_years: list[float],
event_grades: list[str]) -> pd.DataFrame:
"""One row per member: `y`, and `known`, whether the window is complete or the event already happened."""
window = SETTINGS["outcome_window_months"] * DAYS_PER_MONTH
(window_years,) = horizons_years
window = window_years * DAYS_PER_YEAR
days = (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(SETTINGS["event_grades"]) & days.between(0, window)
event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(event_grades) & days.between(0, window)
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
members["y"] = members["pac_id"].isin(cohort.loc[event, "pac_id"]).astype(int)
follow_up = (pd.Timestamp(cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days
follow_up = (pd.Timestamp(cohort_cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days
members["known"] = (members["y"] == 1) | (follow_up >= window)
return members[["pac_id", "y", "known"]]
def prepare(predictors: pd.DataFrame, outcome: pd.DataFrame) -> pd.DataFrame:
@checked_frame(LABELLED_MEMBERS)
def labelled_members(index_sample_results: pd.DataFrame, windowed_outcomes: pd.DataFrame) -> pd.DataFrame:
"""The members whose outcome is known, with their predictors and `y`."""
labelled = predictors.merge(outcome, on="pac_id")
labelled = index_sample_results.merge(windowed_outcomes, on="pac_id")
return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True)
def split(prepare: pd.DataFrame) -> dict:
"""The oldest index dates train and the newest test."""
ordered = prepare.sort_values(["fecha_indice", "pac_id"], kind="stable")
cut = int(len(ordered) * SETTINGS["train_fraction"])
return {"train": ordered.iloc[:cut], "test": ordered.iloc[cut:]}
class IndexSampleResults(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member, in `pac_id` order, with the index sample's results. Learns
nothing."""
def __init__(self, predictor_columns: list[str]):
self.predictor_columns = predictor_columns
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_sample_results(X, self.predictor_columns)[list(self.predictor_columns)]
def train(split: dict) -> pd.DataFrame:
return split["train"]
def test(split: dict) -> pd.DataFrame:
return split["test"]
def fit(train: pd.DataFrame) -> Pipeline:
"""One-hot predictors, an unseen category counted as none of the known ones, and a logistic regression."""
encode = ColumnTransformer([("results", OneHotEncoder(handle_unknown="ignore"), list(PREDICTORS))])
return Pipeline([("encode", encode), ("logistic", LogisticRegression(max_iter=1000))]).fit(
train[list(PREDICTORS)], train["y"])
def predict(fit: Pipeline, test: pd.DataFrame) -> pd.Series:
"""The probability of `y` for each row of `test`."""
return pd.Series(fit.predict_proba(test[list(PREDICTORS)])[:, 1], index=test.index, name="probabilidad")
def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dict:
"""Aggregates only: no patient data reaches MLflow."""
return {"auc": float(roc_auc_score(test["y"], predict)), "brier": float(brier_score_loss(test["y"], predict)),
"n_train": len(train), "n_test": len(test), "positive_rate_train": float(train["y"].mean()),
"positive_rate_test": float(test["y"].mean()), "mean_probability_test": float(predict.mean())}
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:
@@ -131,85 +100,22 @@ def _dates(frame: pd.DataFrame) -> dict:
"last_index_date": str(frame["fecha_indice"].max())}
def sampling(outcome: pd.DataFrame, train: pd.DataFrame, test: pd.DataFrame) -> dict:
"""MUESTREO: who could be used, and how they were split."""
def sampling(windowed_outcomes: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float, index_attrition: list, prior_observation: dict) -> dict:
"""MUESTREO: who could be used (the scenario's index and rules, step by step, and their prior history), and how
they were split."""
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
"train_fraction": SETTINGS["train_fraction"], "members": len(outcome),
"left_out_unknown_outcome": int((~outcome["known"]).sum()), "train": _dates(train), "test": _dates(test)}
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"train_fraction": train_fraction, "members": len(windowed_outcomes),
"left_out_unknown_outcome": int((~windowed_outcomes["known"]).sum()), "train": _dates(train_set),
"test": _dates(test_set)}
def missing_data(predictors: pd.DataFrame, train: pd.DataFrame, test: pd.DataFrame) -> dict:
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 PREDICTORS}
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(predictors), "train": missing(train), "test": missing(test)}
def analytic_method(fit: Pipeline) -> dict:
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
logistic = fit.named_steps["logistic"]
features = fit.named_steps["encode"].get_feature_names_out()
return {"method": "regresión logística sobre los predictores codificados one-hot",
"estimator": type(logistic).__name__, "settings": logistic.get_params(),
"intercept": float(logistic.intercept_[0]),
"coefficients": dict(zip(map(str, features), map(float, logistic.coef_[0])))}
def class_balance(train: pd.DataFrame, test: pd.DataFrame, fit: Pipeline) -> dict:
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
weight = fit.named_steps["logistic"].class_weight
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
"train": {str(k): int(v) for k, v in train["y"].value_counts().sort_index().items()},
"test": {str(k): int(v) for k, v in test["y"].value_counts().sort_index().items()}}
def output_confidence(test: pd.DataFrame, predict: pd.Series) -> dict:
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by tenths."""
bins = pd.qcut(predict, q=min(SETTINGS.get("calibration_bins", 10), predict.nunique()), duplicates="drop")
table = pd.DataFrame({"p": predict, "y": test["y"]}).groupby(bins, observed=True).agg(
n=("y", "size"), mean_probability=("p", "mean"), observed_rate=("y", "mean"))
return {"method": "calibración en la prueba: probabilidad media contra frecuencia observada, por cuantiles",
"brier": float(brier_score_loss(test["y"], predict)),
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.mean_probability),
"observed_rate": float(row.observed_rate)} for interval, row in table.iterrows()]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
class Cin2Logistic(mlflow.pyfunc.PythonModel):
"""The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`
for every member, whether their outcome is known or not."""
def __init__(self, fitted: Pipeline):
self.fitted = fitted
def predict(self, context, model_input, params=None):
members = predictors(model_input)
return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members))
def registered_model(fit: Pipeline, evaluate: dict, routines: dict, lineage: dict, cohort_path: str,
cohort_sha256: str, code_sha256: str, environment: str) -> str:
"""Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content,
and which build it is, from the kit or from dbt's rules."""
cohort = cohort_reference(lineage, cohort_sha256)
armado_id = int(lineage["armado_id"]) if cohort[COHORT_SOURCE_TAG] == "kit" else None
run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment,
cohorte_armado_id=armado_id, cohort=cohort)
for kind, record in routines.items():
run.log_routine(kind, record)
run.log_model(Cin2Logistic(fit))
run.finish(metrics=evaluate, hyperparameters={
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256,
"outcome_window_months": SETTINGS["outcome_window_months"], "event_grades": ",".join(SETTINGS["event_grades"]),
"horizon_years": SETTINGS["outcome_window_months"] / 12})
version = registry.register_run(run)
registry.set_description(SETTINGS["domain"], SETTINGS["scenario"], version, SETTINGS["description"])
return version
"members": missing(index_sample_results), "train": missing(train_set), "test": missing(test_set)}
+26 -6
View File
@@ -1,13 +1,33 @@
domain = "cacu"
scenario = "cin2_logistic"
cohort = "cacu/cohorte_vigilancia"
train_fraction = 0.7
# Provisional, to be decided with the domain expert: the window in which a CIN2+ biopsy counts as the outcome. On the
# DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 24-month window leaves no member with a
# complete window; 12 months leaves 5,231 known members, 162 with the event.
outcome_window_months = 12
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
outcome = "cin2_12m"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.cin2_logistic.model", "models.steps.model_fitting", "models.steps.indexing"]
description = """
Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \
a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \
validación clínica."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
[config]
classifier = "logistic"
train_fraction = 0.7
predictor_columns = ["bethesda", "vph", "vph_16_18"]
# Provisional, to be decided with the domain expert: the window, in years, in which a CIN2+ biopsy counts as the
# outcome; the model's one horizon. On the DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 2-year
# window leaves no member with a complete window; 1 year leaves 5,231 known members, 162 with the event.
horizons_years = [1.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance
# cohort, applied in the pipeline. The recruitment window is the source cohort's.
[config.index]
kind = "primera_citologia"
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
observacion_previa_minima_dias = 0
@@ -17,7 +17,7 @@
"metadata": {},
"execution_count": null,
"outputs": [],
"source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/models/cacu/notebooks/cin2_logistic → ../../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[4] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))",
"source": "import os\nimport subprocess\nfrom pathlib import Path\n\nDOMAIN = \"cacu\"\nCOHORT_URL = \"cacu/cohorte_vigilancia\"\n# The dbt project, next to this repository in the ISSSTELEON tree (models/models/cacu/cin2_logistic/notebooks → ../../../../../Transformation).\nTRANSFORMATION = Path(os.environ.get(\"TRANSFORMATION_DIR\", Path.cwd().parents[4] / \"Transformation\"))\n\nif \"CACU_DATABASE_URL\" not in os.environ:\n # Local: a copy of the DEV deployment's simulated data, made once and kept between runs.\n local = Path.home() / \".cache\" / \"isssteleon-notebooks\" / \"data\"\n local.mkdir(parents=True, exist_ok=True)\n if not (local / \"cacu.db\").exists():\n subprocess.run([\"docker\", \"cp\", \"isssteleon-internal-dev-webapi-1:/data/cacu.db\", str(local / \"cacu.db\")], check=True)\n os.environ[\"CACU_DATABASE_URL\"] = f\"sqlite:///{local / 'cacu.db'}\"\n\nfrom sqlalchemy.engine import make_url # noqa: E402 after the URL is set\n\ndatabase = Path(make_url(os.environ[\"CACU_DATABASE_URL\"]).database.removeprefix(\"file:\"))\nDATA = database.parent\nCOHORTS = Path(os.environ.get(\"COHORTS_DIR\", DATA / \"cohorts\"))\nprint(\"database:\", database)\nprint(\"cohort files:\", COHORTS, \"| writable:\", os.access(COHORTS if COHORTS.exists() else COHORTS.parent, os.W_OK))",
"id": "cacu-cin2-01-02"
},
{
+5 -25
View File
@@ -1,27 +1,7 @@
"""The model's Hamilton driver, and what makes repeating a training a no-op."""
"""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 hamilton import driver
from models.dags.training import Scenario, find_trained as _find_trained, train as _train
from models.cacu.cin2_logistic import model
from models.io.lineage import matches
from models.io.registry import registered_name, registry
def train(cohort_path: str, environment: str = "DEV") -> str:
"""Trains on a build's file and returns the registered version."""
dr = driver.Builder().with_modules(model).build()
inputs = {"cohort_path": str(cohort_path), "environment": environment}
return dr.execute(["registered_model"], inputs=inputs)["registered_model"]
def find_trained(cohort_path: str, environment: str = "DEV") -> str | None:
"""The newest version not retired from the same file, code and environment."""
name = registered_name(model.SETTINGS["domain"], model.SETTINGS["scenario"])
expected = {"cohort_sha256": model.cohort_sha256(str(cohort_path)), "code_sha256": model.code_sha256()}
versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True)
for mv in versions:
if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"):
continue
if matches(registry.client.get_run(mv.run_id).data.params, expected):
return str(mv.version)
return None
train, find_trained = (partial(f, Scenario.load("cacu", "cin2_logistic")) for f in (_train, _find_trained))
View File
+247
View File
@@ -0,0 +1,247 @@
"""Prevalence–incidence mixture (PIMixture) likelihood, written plainly: the Weibull family and maximum likelihood.
Each row has a code `c` and an interval `(l, r]` in years since the index visit:
- `c = 1`: prevalent at the index visit. Contributes `pi`.
- `c = 0`: not prevalent; the disease, if any, appeared in `(l, r]` (`r = inf` means censored at `l`).
Contributes `(1 - pi) * (S(l) - S(r))`.
- `c = -999`: unknown at the index visit (no colposcopy). Contributes `pi + (1 - pi) * (S(l) - S(r))`, usually
with `l = 0`.
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-H0(t) * exp(Z @ beta))` the survival of the incidence
(proportional hazards in `Z`). The baseline cumulative hazard `H0` is a family:
- `Weibull`: `H0(t) = (t / scale) ** shape`, the default;
- `ISpline`: PIMixture's weakly-parametric `H0(t) = sum_j exp(gamma_j) I_j(t)`, with `I_j` the I-spline basis on knots
at quantiles of the observed times. Each `I_j` rises from 0 to 1, so `H0` is flat after the last knot.
Each row may carry a frequency weight `w` (identical rows collapsed into one); the standard errors (`-H^-1`) are those
of frequency weights, not of sampling weights.
"""
from dataclasses import dataclass
import numpy as np
from scipy.interpolate import BSpline
from scipy.optimize import minimize
from scipy.special import expit
UNKNOWN = -999
TINY = 1e-12
BOUNDARY = 15.0 # |parameter| beyond this is taken as "at the boundary" (expit(−15) = 3e-7)
def prevalence(theta, X):
return expit(X @ theta)
def weibull_survival(t, log_scale, log_shape, beta, Z):
"""S(t). S(0) = 1 and S(inf) = 0."""
t = np.asarray(t, dtype=float)
scale, shape = np.exp(log_scale), np.exp(log_shape)
hazard_ratio = np.exp(Z @ beta)
with np.errstate(over="ignore", invalid="ignore"):
cumulative = (t / scale) ** shape * hazard_ratio
survival = np.exp(-cumulative)
survival = np.where(t <= 0, 1.0, survival)
survival = np.where(np.isinf(t), 0.0, survival)
return survival
def ispline_basis(t, order: int, knots) -> np.ndarray:
"""(len(t) x (len(knots) + order - 2)) I-spline basis: `I_j(t) = sum_{m >= j} B_m(t)`, the B-splines of degree
`order` on `knots` with repeated boundaries. Equals PIMixture's `Ispline(t, order, knots)`, transposed."""
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
full = np.r_[np.repeat(knots[0], order + 1), knots[1:-1], np.repeat(knots[-1], order + 1)]
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
bsplines = BSpline.design_matrix(inside, full, order, extrapolate=False).toarray()
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
basis[t >= knots[-1]] = 1.0
basis[t <= knots[0]] = 0.0
return basis
def quantile_knots(l, r, n_knots: int) -> tuple[float, ...]:
"""PIMixture's knots: quantiles of the unique observed times, the `l` (zeros included) and the finite `r`."""
l, r = np.asarray(l, dtype=float), np.asarray(r, dtype=float)
times = np.unique(np.r_[l, r[np.isfinite(r)]])
return tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots)))
@dataclass(frozen=True)
class Weibull:
"""`H0(t) = (t / scale) ** shape`; params `[log_scale, log_shape]`."""
n_params = 2
def cumulative_hazard(self, t, params):
with np.errstate(over="ignore", invalid="ignore"):
return (np.asarray(t, dtype=float) / np.exp(params[0])) ** np.exp(params[1])
def start(self, c, l, r):
return np.array([_starting_log_scale(c, l, r), 0.0])
@dataclass(frozen=True)
class ISpline:
"""`H0(t) = sum_j exp(gamma_j) I_j(t)`; params `gamma`, one per basis function."""
knots: tuple[float, ...]
order: int = 3
@property
def n_params(self):
return len(self.knots) + self.order - 2
def cumulative_hazard(self, t, params):
return ispline_basis(t, self.order, self.knots) @ np.exp(params)
def start(self, c, l, r):
"""The exponential start's `H0` at the last knot, shared equally among the basis functions."""
rate = np.exp(-_starting_log_scale(c, l, r))
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
WEIBULL = Weibull()
def survival(t, baseline_params, beta, Z, baseline=WEIBULL):
"""S(t) for any baseline family. S(0) = 1 and S(inf) = 0."""
t = np.asarray(t, dtype=float)
with np.errstate(over="ignore", invalid="ignore"):
cumulative = baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta)
found = np.exp(-cumulative)
found = np.where(t <= 0, 1.0, found)
return np.where(np.isinf(t), 0.0, found)
def split_params(params, n_x, n_z):
"""params = [theta (n_x), beta (n_z), log_scale, log_shape]."""
theta = params[:n_x]
beta = params[n_x:n_x + n_z]
log_scale = params[n_x + n_z]
log_shape = params[n_x + n_z + 1]
return theta, beta, log_scale, log_shape
def neg_loglik(params, c, l, r, X, Z, baseline=WEIBULL, w=None):
n_x, n_z = X.shape[1], Z.shape[1]
theta, beta, rest = params[:n_x], params[n_x:n_x + n_z], params[n_x + n_z:]
w = np.ones(len(c)) if w is None else np.asarray(w, dtype=float)
pi = prevalence(theta, X)
interval = survival(l, rest, beta, Z, baseline) - survival(r, rest, beta, Z, baseline)
interval = np.maximum(interval, TINY)
row = np.zeros(len(c))
prevalent = c == 1
row[prevalent] = np.log(pi[prevalent] + TINY)
not_prevalent = c == 0
row[not_prevalent] = np.log(1 - pi[not_prevalent] + TINY) + np.log(interval[not_prevalent])
unknown = c == UNKNOWN
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
return -np.sum(w * row)
def numerical_hessian(f, x, step=1e-4):
"""Central finite differences, one pair of parameters at a time. Plain and slow (4 p² calls), fine for p < 30."""
x = np.asarray(x, dtype=float)
p = len(x)
hessian = np.zeros((p, p))
for i in range(p):
for j in range(i, p):
ei = np.zeros(p)
ej = np.zeros(p)
ei[i] = step
ej[j] = step
value = (f(x + ei + ej) - f(x + ei - ej) - f(x - ei + ej) + f(x - ei - ej)) / (4 * step * step)
hessian[i, j] = value
hessian[j, i] = value
return hessian
def _starting_log_scale(c, l, r):
"""log of an exponential scale: time at risk / incident events. With a rare outcome the scale is thousands of
years; starting BFGS at the median detection time (a few years) left it in a much worse local optimum."""
at_risk = c != 1
finite = np.isfinite(r)
exposure = np.where(finite, (l + r) / 2, l)[at_risk].sum()
events = (at_risk & finite & (r > 0)).sum()
return float(np.log(max(exposure, 1e-6) / (events + 0.5)))
def _starting_theta(c, X, ridge=1e-3):
"""Prevalence coefficients of a logistic regression of "prevalent" on X among the members whose baseline is
known, with a small ridge so a group with no prevalent case gets a large negative value instead of -inf."""
known = c != UNKNOWN
if not known.any():
return np.zeros(X.shape[1])
y, Xk = (c[known] == 1).astype(float), X[known]
def loss(theta):
eta = Xk @ theta
return np.sum(np.logaddexp(0, eta) - y * eta) + ridge * theta @ theta
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
def fit(c, l, r, X, Z, baseline=WEIBULL, w=None):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors; with the
Weibull also `log_scale` and `log_shape`."""
c, l, r = np.asarray(c), np.asarray(l, dtype=float), np.asarray(r, dtype=float)
X, Z = np.asarray(X, dtype=float), np.asarray(Z, dtype=float)
n_x, n_z = X.shape[1], Z.shape[1]
# Two starts, the better optimum kept: the likelihood of a rare outcome has poor local optima (all the risk put in
# the prevalence and none in the incidence, or the other way round).
start = baseline.start(c, l, r)
starts = [np.r_[_starting_theta(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x), np.zeros(n_z), start]]
args = (c, l, r, X, Z, baseline, w)
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
result = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
theta, beta, rest = result.x[:n_x], result.x[n_x:n_x + n_z], result.x[n_x + n_z:]
# BFGS's own hess_inv is a rough approximation: the standard errors come from a finite-difference Hessian.
# A coefficient that ran off to the boundary (e.g. a group with no prevalent case: logit → −inf) has a flat
# likelihood, a zero row in the Hessian, and makes the whole matrix singular. It gets no standard error (NaN) and
# the others are computed without it.
hessian = numerical_hessian(lambda p: neg_loglik(p, *args), result.x)
free = np.abs(result.x) < BOUNDARY
standard_errors = np.full(len(result.x), np.nan)
covariance = np.full((len(result.x), len(result.x)), np.nan)
try:
covariance[np.ix_(free, free)] = np.linalg.inv(hessian[np.ix_(free, free)])
variances = np.diag(covariance)[free]
standard_errors[free] = np.sqrt(np.where(variances > 0, variances, np.nan))
except np.linalg.LinAlgError:
pass
found = {
"theta": theta,
"beta": beta,
"baseline": baseline,
"baseline_params": rest,
"params": result.x,
"se": standard_errors,
"covariance": covariance,
"neg_loglik": result.fun,
# BFGS with a numerical gradient often stops with "precision loss" at the optimum; what matters is that
# the gradient is ~0 there.
# A coefficient at the boundary (see above) keeps a small slope there; only the free ones must be flat.
"converged": bool(np.max(np.abs(result.jac[free]), initial=0.0) < 1e-3),
"message": result.message,
}
if isinstance(baseline, Weibull):
found["log_scale"], found["log_shape"] = float(rest[0]), float(rest[1])
return found
def cumulative_risk(fitted, X, Z, years):
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence. A `fitted` without
`baseline` (built by hand) is a Weibull with `log_scale` and `log_shape`."""
pi = prevalence(fitted["theta"], X)
baseline = fitted.get("baseline", WEIBULL)
rest = fitted.get("baseline_params")
if rest is None:
rest = np.array([fitted["log_scale"], fitted["log_shape"]])
columns = [pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), rest, fitted["beta"], Z, baseline))
for t in years]
return np.column_stack(columns)
+309
View File
@@ -0,0 +1,309 @@
"""CaCu CIN2+ prevalence–incidence prototype: the cumulative risk of CIN2+ at the index visit and at later horizons.
Each member becomes a code `c` and an interval `(l, r]` in years since the index date (`likelihood`'s convention),
from the first CIN2+ biopsy and the last time the member was found free of it before that biopsy. Found free means a
biopsy below CIN2+, or a visit whose results each take one of their `known_negative` values (HPV-negative with NILM or
ASC-US). CIN2+ is taken as absorbing
and a negative as true, so the last negative carries every earlier one:
- a CIN2+ biopsy within `prevalent_window_months`: prevalent, `c = 1`, `(0, 0]`;
- otherwise, found free at least once: `c = 0`, with `l` the last negative (0 if it's within the window, the baseline
workup) and `r` the CIN2+ biopsy, or infinity if there's none;
- otherwise the baseline is unknown: `c = -999`, with `(0, t_event]`, or `(0, inf)`, which carries no information.
Follow-up without a test isn't counted: a member is free only as far as her last negative, never up to the cut-off.
`PrevalenceIncidenceMixture` is a scikit-learn estimator: `fit(X, y)` with the members' features and their `c`, `l`,
`r`; `predict_proba(X)` gives the cumulative risk at each horizon, CR(t) = π + (1 − π)(1 − S(t)), with the prevalence
π logistic in every feature (KPNC's cytology categories as indicators) and the incidence S(t) with proportional
hazards in `incidence_features` over a Weibull or I-spline baseline (`incidence`), one mixture per stratum (`strata`).
`fitted_model` puts `IndexResults` in front of it, so the registered model is one `Pipeline` that takes a build's long
frame. Settings arrive as config (`model.toml`), the cohort through a loader, and registering is the
driver's saver (`models.dags.training`).
"""
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
from models.cacu.cin2_pim import likelihood
from models.io.contracts import DAYS_PER_YEAR
from models.steps import model_fitting
FEATURES = ["cytology", "hpv_positive"]
def _features(history: dict) -> list[str]:
"""The model's features: the index results', and the history's one if the scenario has a history."""
return FEATURES + ([history["feature"]] if history else [])
def _levels(cytology: dict, history: dict) -> dict:
"""The levels of each categorical feature, the reference first."""
return {"cytology": list(cytology), **({history["feature"]: list(history["levels"])} if history else {})}
INTERVAL_CODED = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"c": pandera.Column(int, pandera.Check.isin([1, 0, likelihood.UNKNOWN])),
"l": pandera.Column(float, pandera.Check.ge(0)),
"r": pandera.Column(float, pandera.Check.ge(0))},
checks=pandera.Check(lambda frame: frame["r"] >= frame["l"], error="r >= l"),
name="interval-coded members")
def _days(cohort: pd.DataFrame) -> pd.Series:
return (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
def _most_severe(codes: pd.Series, cytology: dict) -> pd.Series:
"""Per `pac_id` (the index of `codes`), the most severe of `cytology`'s categories among the codes; None if none."""
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
ranks = codes.map(severity).groupby(level=0).max()
names = list(cytology)
return pd.Series([None if np.isnan(rank) else names[int(rank)] for rank in ranks], index=ranks.index,
dtype=object)
def _history(cohort: pd.DataFrame, members: pd.DataFrame, cytology: dict, history: dict) -> pd.Series:
"""The history feature: the grade of the results in the `lookback_days` up to the member's first `event` (KPNC's
referral before the colposcopy). `high` if a category of `high`; else `low` if one of `low`, or of
`low_if_hpv_positive` with a positive HPV; else None (no referral result, or one that wouldn't refer)."""
event = cohort[cohort["tipo"] == history["event"]].groupby("pac_id")["fecha"].min()
timed = cohort.assign(event=cohort["pac_id"].map(event))
before = (pd.to_datetime(timed["event"]) - pd.to_datetime(timed["fecha"])).dt.days
near = timed[before.between(0, history["lookback_days"])]
results = near[near["tipo"].isin(["bethesda", "glandular"])].set_index("pac_id")["valor_codigo"]
worst = pd.Series(_most_severe(results, cytology).reindex(members["pac_id"]).to_numpy(), index=members.index)
hpv = near[(near["tipo"] == "vph") & (near["valor_codigo"] == "POSITIVO")]["pac_id"].unique()
positive = members["pac_id"].isin(hpv).to_numpy()
grade = np.where(worst.isin(history["high"]), "high",
np.where(worst.isin(history["low"]) | (worst.isin(history["low_if_hpv_positive"]) & positive),
"low", None))
return pd.Series(grade, index=members.index, dtype=object)
def index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict, history: dict | None = None) -> pd.DataFrame:
"""One row per member, in `pac_id` order: the first squamous (Bethesda), glandular and HPV results within
`index_sample_days` of the index date, and the features taken from them. `cytology` maps KPNC's categories, from
least to most severe, to the codes of either result; with both results the more severe category wins, and a
member with neither, or with codes in no category, gets None. With a `history`, its feature too (`_history`)."""
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "glandular", "vph"])]
wide = near.sort_values("fecha").pivot_table(index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
members = cohort.groupby("pac_id", as_index=False)["fecha_indice"].first()
members = members.merge(wide.reindex(columns=["bethesda", "glandular", "vph"]), left_on="pac_id", right_index=True,
how="left")
codes = members.set_index("pac_id")[["bethesda", "glandular"]].stack()
found = _most_severe(codes, cytology).reindex(members["pac_id"]).tolist()
members["cytology"] = pd.Series([v if isinstance(v, str) else None for v in found], index=members.index,
dtype=object)
members["hpv_positive"] = (members["vph"] == "POSITIVO").astype(float)
if history:
members[history["feature"]] = _history(cohort, members, cytology, history)
return members
def _negative_days(cohort: pd.DataFrame, days: pd.Series, event_grades: list[str], known_negative: dict,
index_sample_days: int) -> pd.DataFrame:
"""`pac_id` and day of every time a member was found free of CIN2+: a biopsy below CIN2+, or a visit with a result
of every `known_negative` key among its values, within `index_sample_days` of each other, dated at the last."""
timed = cohort.assign(days=days.astype(float))[days >= 0]
biopsies = timed[(timed["tipo"] == "biopsia") & ~timed["valor_codigo"].isin(event_grades)][["pac_id", "days"]]
visits = None
for name, values in known_negative.items():
found = timed[(timed["tipo"] == name) & timed["valor_codigo"].isin(values)][["pac_id", "days"]]
if visits is None:
visits = found
continue
paired = pd.merge_asof(visits.sort_values("days"), found.rename(columns={"days": name}).sort_values(name),
left_on="days", right_on=name, by="pac_id", direction="nearest",
tolerance=float(index_sample_days)).dropna(subset=[name])
visits = paired.assign(days=paired[["days", name]].max(axis=1))[["pac_id", "days"]]
return pd.concat([biopsies, visits], ignore_index=True)
@checked_frame(INTERVAL_CODED)
def interval_coded_members(cohort: pd.DataFrame, event_grades: list[str], prevalent_window_months: int,
index_sample_days: int, known_negative: dict, cytology: dict, history: dict) -> pd.DataFrame:
"""Each member's features with `c`, `l` and `r` (see the module's docstring)."""
days = _days(cohort)
window = prevalent_window_months * DAYS_PER_YEAR / 12
events = cohort[(cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(event_grades) & (days >= 0)]
first_event = days[events.index].groupby(events["pac_id"]).min()
negatives = _negative_days(cohort, days, event_grades, known_negative, index_sample_days)
before_event = ~(negatives["days"] >= negatives["pac_id"].map(first_event))
last_negative = negatives[before_event].groupby("pac_id")["days"].max()
coded = index_results(cohort, index_sample_days, cytology, history)
event_days, free_until = coded["pac_id"].map(first_event), coded["pac_id"].map(last_negative)
prevalent = event_days <= window
found_free = free_until.notna() & ~prevalent
later_event = event_days.notna() & ~prevalent
coded["c"] = np.where(prevalent, 1, np.where(found_free, 0, likelihood.UNKNOWN))
coded["l"] = np.where(found_free & (free_until > window), free_until / DAYS_PER_YEAR, 0.0)
coded["r"] = np.where(prevalent, 0.0, np.where(later_event, event_days / DAYS_PER_YEAR, np.inf))
return coded
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(interval_coded_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(interval_coded_members, train_fraction, target_column="c")
class PrevalenceIncidenceMixture(BaseEstimator):
"""Logistic prevalence and proportional-hazards incidence fitted by maximum likelihood (`likelihood.fit`).
`incidence` picks the baseline: `{"family": "weibull"}` or `{"family": "ispline", "knots": k, "order": o}`, with
`k` knots at quantiles of each stratum's observed times (PIMixture's weakly-parametric model). With `strata`, one
mixture per combination of their values, as in Cheung et al. 2020 (stratified by HPV, cytology as covariate): the
strata leave both designs and a member of a stratum not seen in training gets NaN. A feature listed in `levels`
is categorical: one indicator per level but the first (the reference), keeping in each stratum only the levels
seen in its training; a member of a level not seen there, or of none, gets NaN and is left out of the fit.
Identical rows are collapsed into frequency weights, which `sample_weight` multiplies.
"""
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(),
incidence=None, levels=None):
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.incidence = incidence
self.levels = levels
def _baseline(self, y: pd.DataFrame):
settings = dict(self.incidence or {"family": "weibull"})
family = settings.pop("family")
if family == "weibull":
return likelihood.WEIBULL
if family == "ispline":
return likelihood.ISpline(likelihood.quantile_knots(y["l"], y["r"], settings["knots"]),
settings.get("order", 3))
raise ValueError(f"unknown incidence family {family!r}")
def _seen(self, X: pd.DataFrame) -> dict:
"""Each categorical feature's levels present in `X`, in `levels`' order."""
return {f: [v for v in values if (X[f] == v).any()] for f, values in (self.levels or {}).items()
if f in X.columns and f not in self.strata}
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
"""Rows whose categorical features take a level in `seen`."""
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0) if seen \
else np.ones(len(X), dtype=bool)
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
columns = []
for f in features:
if f in self.strata:
continue
if f in seen:
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
else:
columns.append(X[f].to_numpy(dtype=float))
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
return prevalence, self._columns(X, self.incidence_features, seen)
def _groups(self, X: pd.DataFrame):
if not self.strata:
return [((), np.arange(len(X)))]
return [(key if isinstance(key, tuple) else (key,), rows)
for key, rows in X.groupby(list(self.strata), sort=True).indices.items()]
def fit(self, X: pd.DataFrame, y: pd.DataFrame, sample_weight=None):
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)], axis=1)
rows["w"] = 1.0 if sample_weight is None else np.asarray(sample_weight, dtype=float)
self.fits_, self.seen_ = {}, {}
for key, index in self._groups(X):
group = rows.iloc[index]
seen = self._seen(group)
group = group[self._placed(group, seen)].groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
prevalence, incidence = self._design(group[X.columns], seen)
self.seen_[key] = seen
self.fits_[key] = likelihood.fit(group["c"].to_numpy(), group["l"].to_numpy(), group["r"].to_numpy(),
prevalence, incidence, self._baseline(group), group["w"].to_numpy())
self.neg_loglik_ = float(sum(f["neg_loglik"] for f in self.fits_.values()))
self.converged_ = all(f["converged"] for f in self.fits_.values())
return self
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
"""One column per horizon: CR(t). The column of t = 0 is the prevalence."""
risks = np.full((len(X), len(self.horizons_years)), np.nan)
for key, index in self._groups(X):
if key not in self.fits_:
continue
members = X.iloc[index]
placed = self._placed(members, self.seen_[key])
prevalence, incidence = self._design(members[placed], self.seen_[key])
risks[index[placed]] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence,
self.horizons_years)
return risks
def fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float], incidence: dict,
incidence_features: list[str], strata: list[str], cytology: dict,
history: dict) -> PrevalenceIncidenceMixture:
return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence,
_levels(cytology, history)).fit(train_set[_features(history)],
train_set[["c", "l", "r"]])
def test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame,
history: dict) -> np.ndarray:
return fitted_mixture.predict_proba(test_set[_features(history)])
def _status_at(members: pd.DataFrame, horizon: float) -> np.ndarray:
"""1 if CIN2+ is known by `horizon`, 0 if known free at it, NaN if not known."""
case = (members["c"] == 1) | ((members["c"] != 1) & (members["r"] <= horizon))
free = (members["c"] == 0) & (members["l"] >= horizon) & ~case
return np.where(case, 1.0, np.where(free, 0.0, np.nan))
def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame, test_set: pd.DataFrame,
test_cumulative_risks: np.ndarray, horizons_years: list[float]) -> dict:
"""Aggregates only: per horizon, among test members whose status at it is known, how many, the observed and
expected rates, the Brier score and, with both classes, the AUC."""
found = {"n_train": len(train_set), "n_test": len(test_set), "neg_loglik": float(fitted_mixture.neg_loglik_),
"converged": float(fitted_mixture.converged_)}
for column, horizon in enumerate(horizons_years):
status = _status_at(test_set, horizon)
known = ~np.isnan(status) & ~np.isnan(test_cumulative_risks[:, column]) # NaN: a stratum unseen in training
y, p = status[known], test_cumulative_risks[known, column]
tag = f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
if known.any():
found[f"observed_{tag}"] = float(y.mean())
found[f"expected_{tag}"] = float(p.mean())
found[f"brier_{tag}"] = float(np.mean((p - y) ** 2))
if len(np.unique(y)) == 2:
found[f"auc_{tag}"] = float(roc_auc_score(y, p))
return found
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing."""
def __init__(self, index_sample_days: int = 30, cytology=None, history=None):
self.index_sample_days = index_sample_days
self.cytology = cytology
self.history = history
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict,
history: dict) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`."""
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)),
("mixture", fitted_mixture)])
+56
View File
@@ -0,0 +1,56 @@
domain = "cacu"
scenario = "cin2_pim"
cohort = "cacu/cohorte_vigilancia"
outcome = "cin2"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"]
description = """
Prototipo: riesgo acumulado de CIN2+ (biopsia LIEAG, CIS o carcinoma) en la visita índice y a 1, 3 y 5 años, con un \
modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \
citología índice en las categorías de KPNC como covariable (Cheung et al. 2020). Sin \
corrección del sesgo de verificación ni validación clínica."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
# Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent.
prevalent_window_months = 6
# The index sample's results: the first ones within these days of the index date.
index_sample_days = 30
# The results that make a visit free of CIN2+ without a biopsy: every key with one of its values (KPNC: HPV-negative
# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528).
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
# The incidence's baseline cumulative hazard: { family = "weibull" }, or PIMixture's weakly-parametric
# { family = "ispline", knots = k, order = o }, with k knots at quantiles of each stratum's observed times. The
# finite times are whole years 1-5, so a basis of more than 5 functions (knots + order - 2) isn't identifiable. KPNC
# table 1 is exactly order 4 with 3 knots (bayes-pim, chapter 6).
incidence = { family = "ispline", knots = 3, order = 4 }
# One mixture per value of these features; the other features enter the prevalence, and those listed here the
# incidence. KPNC: stratified by HPV, cytology as covariate (Cheung et al. 2020).
strata = ["hpv_positive"]
incidence_features = ["cytology"]
# A feature of the member's history before the index (e.g. the referral before a colposcopy); none in surveillance.
history = {}
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
# the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma
# has no KPNC row: it goes with the high-grade and malignant results.
# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance
# cohort, applied in the pipeline. The recruitment window is the source cohort's.
[config.index]
kind = "primera_citologia"
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
observacion_previa_minima_dias = 0
[config.cytology]
NILM = ["NORMAL"]
ASC-US = ["ASC-US"]
LSIL = ["LIEBG"]
ASC-H = ["ASC-H"]
AGC = ["AGC"]
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
@@ -0,0 +1,123 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "8368c95d",
"metadata": {
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"#| echo: false\n",
"#| tags: [parameters]\n",
"turnbull_bootstrap = 200\n",
"report_panels = 24"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "718e1a82",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"from IPython.display import HTML, Markdown, display\n",
"from models.cacu.cin2_pim import report\n",
"from models.dags.training import Scenario, dataflow\n",
"from models.notebook import experiment\n",
"\n",
"exp = experiment()\n",
"scenario = Scenario.load(exp.domain, exp.scenario)\n",
"horizons = scenario.config[\"horizons_years\"]\n",
"risks = dataflow(*scenario.modules, config=scenario.config).execute(\n",
" [\"combination_risks\"], inputs={\"source_cohort\": exp.cohort(), \"cohort_lineage\": exp.lineage(),\n",
" \"turnbull_bootstrap\": turnbull_bootstrap})[\"combination_risks\"]\n",
"ratios = [e for r in risks for e in r[\"e_o\"] if e[\"E_O\"] is not None]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "107af899",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\n",
" f\"**{exp.domain}/{exp.scenario}** · combinaciones: {len(risks)} · pacientes: {sum(r['n'] for r in risks)} · \"\n",
" f\"prevalentes: {sum(r['prevalent'] for r in risks)} · incidentes: {sum(r['incident'] for r in risks)} · \"\n",
" f\"E/O con IC sin 1: {sum(not e['low'] <= 1 <= e['high'] for e in ratios)} de {len(ratios)}\"))"
]
},
{
"cell_type": "markdown",
"id": "5d1c43a8",
"metadata": {},
"source": [
"## Riesgo acumulado de CIN2+ por combinación: Turnbull y mezcla prevalencia-incidencia"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5d5a1559",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(HTML(report._figure(risks, horizons, report_panels).to_html(full_html=False, include_plotlyjs=True)))"
]
},
{
"cell_type": "markdown",
"id": "dc145546",
"metadata": {},
"source": [
"## E/O por combinación y horizonte"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23665b08",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(report._table(risks))"
]
},
{
"cell_type": "markdown",
"id": "98091470",
"metadata": {},
"source": [
"## Métodos"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "474e00f9",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\"\\n\".join(f\"- **{k}**: {v}\" for k, v in report.METHODS.items())))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+268
View File
@@ -0,0 +1,268 @@
"""The subgroup report of a prevalence–incidence training run (every `cin2_pim` scenario): for each combination of the
model's features (KPNC's index cytology, HPV and, with a history, its feature), the model's cumulative risk of CIN2+
with its delta-method band against the combination's own Turnbull estimate with its bootstrap band, and the ratio of
expected to observed risk (E/O) at each horizon with its interval. A version keeps the record (`analisis/subgrupos.json`,
with the methods it used) and the page (`reportes/subgrupos.html`, Plotly, self-contained).
- The model is the scenario's mixture refitted on every interval-coded member (not only the training part), so that it
and the empirical estimate describe the same members.
- The empirical estimate is Turnbull's nonparametric maximum likelihood for interval-censored data (self-consistency,
as `bayes-pim/informe/resultados/24/simular_protocolo.py`), with the members coded as the mixture's likelihood reads
them: a prevalent case is the mass at 0, a member found free is censored in `(l, r]`, and one whose baseline is
unknown in `[0, r]` (prevalent or incident). It respects the interval censoring: a CIN2+ is known only between the
last negative and the biopsy, never at a date. Its band and variance are the percentiles and variance of
`turnbull_bootstrap` resamples of the combination's members.
- The model's band is the delta method over the likelihood: Var(CR(t)) = g' Σ g, with Σ the inverse of the observed
information (the numerical Hessian `likelihood.fit` already inverts) and g the numerical gradient of CR(t) in the
stratum's parameters; a parameter at the boundary has no variance in Σ and counts as fixed. The band is on the log
scale, E exp(±1.96 SE(E)/E).
- E/O: log(E/O) taken as normal, with SE^2 = Var(E)/E^2 + Var(O)/O^2. Empty where O is 0.
Aggregates only: counts, curves and points, never a member's row.
"""
import numpy as np
import pandas as pd
from models.cacu.cin2_pim import likelihood
from models.cacu.cin2_pim.model import PrevalenceIncidenceMixture, _features, _levels
Z = 1.959963984540054 # the normal's 97.5 % quantile
GRID_STEP = 0.1 # years between the points of the model's curve
UNKNOWN = "NA"
NOTICE = "Prototipo sin validación clínica."
METHODS = {
"empirica": "Turnbull (estimador no paramétrico de máxima verosimilitud con censura por intervalos, autoconsistencia): "
"prevalente = masa en 0, libre de CIN2+ = censura en (l, r], basal desconocida = [0, r]; banda e "
"varianza por bootstrap de las pacientes de la combinación",
"modelo": "mezcla prevalencia-incidencia reajustada en todas las pacientes codificadas; banda por método delta sobre "
"la verosimilitud (inversa del Hessiano numérico, gradiente numérico del riesgo acumulado), en escala log; "
"un parámetro en la frontera cuenta como fijo",
"E/O": "riesgo esperado por el modelo entre el observado (Turnbull) a cada horizonte; IC 95 % suponiendo log(E/O) "
"normal, SE² = Var(E)/E² + Var(O)/O²",
}
def _turnbull(c: np.ndarray, l: np.ndarray, r: np.ndarray, iters: int = 5000, tol: float = 1e-10):
"""(support, cumulative mass) of Turnbull's estimate for members coded `(c, l, r)`: the support is 0, every finite
right end and infinity; a prevalent member's set is {0}, a free one's the points in `(l, r]`, an unknown baseline's
the points in `[0, r]`."""
finite = r[np.isfinite(r)]
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
low = np.where(c == 0, l, -np.inf)
high = np.where(c == 1, 0.0, r)
A = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
patterns, counts = np.unique(A, axis=0, return_counts=True)
p = np.full(len(support), 1 / len(support))
for _ in range(iters):
weighted = patterns * p
new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum()
if np.max(np.abs(new - p)) < tol:
p = new
break
p = new
return support, np.cumsum(p)
def _at(support: np.ndarray, cumulative: np.ndarray, t) -> np.ndarray:
"""The estimate's cumulative risk at each of `t` (a step function, right-continuous)."""
idx = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
return np.where(idx < 0, 0.0, cumulative[np.maximum(idx, 0)])
def _label_value(feature: str, value) -> str:
if value is None or (isinstance(value, float) and np.isnan(value)):
return UNKNOWN
if feature == "hpv_positive":
return "positivo" if float(value) == 1.0 else "negativo"
return str(value)
def report_mixture(interval_coded_members: pd.DataFrame, horizons_years: list[float], incidence: dict,
incidence_features: list[str], strata: list[str], cytology: dict,
history: dict) -> PrevalenceIncidenceMixture:
"""The scenario's mixture refitted on every interval-coded member, the model the report sets against Turnbull."""
features = _features(history)
return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence,
_levels(cytology, history)).fit(interval_coded_members[features],
interval_coded_members[["c", "l", "r"]])
def _risk_with_variance(mixture: PrevalenceIncidenceMixture, row: pd.DataFrame, years: np.ndarray):
"""The model's cumulative risk of one combination (`row`, one row) at `years`, and its delta-method variance."""
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
if key not in mixture.fits_:
return None, None
seen = mixture.seen_[key]
if not mixture._placed(row, seen).all():
return None, None
fit = mixture.fits_[key]
X, Zd = mixture._design(row, seen)
n_x, n_z = len(fit["theta"]), len(fit["beta"])
def risk(params):
found = {"theta": params[:n_x], "beta": params[n_x:n_x + n_z], "baseline": fit["baseline"],
"baseline_params": params[n_x + n_z:]}
return likelihood.cumulative_risk(found, X, Zd, years)[0]
params = np.asarray(fit["params"], dtype=float)
point = risk(params)
gradient = np.empty((len(params), len(years)))
for k in range(len(params)):
step = 1e-5 * max(1.0, abs(params[k]))
up, down = params.copy(), params.copy()
up[k] += step
down[k] -= step
gradient[k] = (risk(up) - risk(down)) / (2 * step)
covariance = np.nan_to_num(np.asarray(fit["covariance"], dtype=float), nan=0.0)
variance = np.einsum("ki,kl,li->i", gradient, covariance, gradient)
return point, np.maximum(variance, 0.0)
def combination_risks(interval_coded_members: pd.DataFrame, report_mixture: PrevalenceIncidenceMixture,
horizons_years: list[float], history: dict, turnbull_bootstrap: int = 200) -> list[dict]:
"""Per combination of the features present among the coded members, largest first: its members and prevalent
and incident cases, its Turnbull estimate with the bootstrap band, the model's cumulative risk with the delta-method
band (none for a combination the model can't place: a cytology outside KPNC's categories, a stratum unseen) and
E/O at each horizon (see the module's docstring)."""
features = _features(history)
members = interval_coded_members.reset_index(drop=True)
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label_value(f, v)) for f in features})
table = labels.drop_duplicates().reset_index(drop=True)
horizons = np.asarray(horizons_years, dtype=float)
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
rng = np.random.default_rng(20261122)
records = []
for _, row in table.iterrows():
mask = (labels == row).all(axis=1).to_numpy()
group = members[mask]
c, l, r = group["c"].to_numpy(int), group["l"].to_numpy(float), group["r"].to_numpy(float)
support, cumulative = _turnbull(c, l, r)
boot_grid, boot_h = [], []
for _ in range(turnbull_bootstrap):
pick = rng.integers(0, len(group), len(group))
s_b, c_b = _turnbull(c[pick], l[pick], r[pick])
boot_grid.append(_at(s_b, c_b, grid))
boot_h.append(_at(s_b, c_b, horizons))
boot_grid, boot_h = np.array(boot_grid), np.array(boot_h)
O = _at(support, cumulative, horizons)
var_O = boot_h.var(axis=0, ddof=1) if turnbull_bootstrap > 1 else np.full(len(horizons), np.nan)
empirical = {"years": grid.tolist(), "CR": _at(support, cumulative, grid).tolist(),
"low": np.percentile(boot_grid, 2.5, axis=0).tolist() if turnbull_bootstrap else None,
"high": np.percentile(boot_grid, 97.5, axis=0).tolist() if turnbull_bootstrap else None}
model, ratios = None, []
probe = group.iloc[[0]][features]
E, var_E = _risk_with_variance(report_mixture, probe, horizons)
curve, var_curve = _risk_with_variance(report_mixture, probe, grid)
if curve is not None:
rel = np.where(curve > 0, np.sqrt(var_curve) / np.maximum(curve, 1e-300), 0.0)
model = {"years": grid.tolist(), "CR": curve.tolist(),
"low": np.clip(curve * np.exp(-Z * rel), 0, 1).tolist(),
"high": np.clip(curve * np.exp(Z * rel), 0, 1).tolist()}
for k, h in enumerate(horizons):
entry = {"years": float(h), "E": None if E is None else float(E[k]), "O": float(O[k]),
"E_O": None, "low": None, "high": None}
if E is not None and E[k] > 0 and O[k] > 0 and np.isfinite(var_O[k]):
se = float(np.sqrt(var_E[k] / E[k] ** 2 + var_O[k] / O[k] ** 2))
value = float(E[k] / O[k])
entry.update(E_O=value, low=value * float(np.exp(-Z * se)), high=value * float(np.exp(Z * se)))
ratios.append(entry)
records.append({"combination": row.to_dict(), "n": int(mask.sum()), "prevalent": int((c == 1).sum()),
"incident": int(((c != 1) & np.isfinite(r)).sum()), "empirical": empirical,
"model": model, "e_o": ratios})
return sorted(records, key=lambda x: (-x["n"], list(x["combination"].values())))
def _label(combination: dict) -> str:
names = {"cytology": "citología", "hpv_positive": "VPH"}
return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items())
def _figure(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24):
"""The figure: one panel per combination (the `report_panels` largest), Turnbull's step curve with its band and the
model's curve with its band (a Plotly `Figure`; the page and the notebook draw it)."""
import plotly.graph_objects as go
from plotly.subplots import make_subplots
shown = combination_risks[:report_panels]
columns = 3
rows = max(1, -(-len(shown) // columns))
figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=True,
subplot_titles=[f"{_label(r['combination'])}<br>n = {r['n']}, prevalentes = {r['prevalent']}, "
f"incidentes = {r['incident']}" for r in shown])
for k, record in enumerate(shown):
row, col, first = k // columns + 1, k % columns + 1, k == 0
emp, model = record["empirical"], record["model"]
if emp["low"] is not None:
figure.add_trace(go.Scatter(x=emp["years"], y=emp["high"], mode="lines", line={"width": 0, "shape": "hv"},
hoverinfo="skip", showlegend=False), row=row, col=col)
figure.add_trace(go.Scatter(x=emp["years"], y=emp["low"], mode="lines", line={"width": 0, "shape": "hv"},
fill="tonexty", fillcolor="rgba(120,130,140,0.30)", hoverinfo="skip",
name="IC 95 % Turnbull (bootstrap)", legendgroup="emp_band", showlegend=first),
row=row, col=col)
figure.add_trace(go.Scatter(x=emp["years"], y=emp["CR"], mode="lines", line={"color": "#242628", "width": 2,
"shape": "hv"},
name="Turnbull", legendgroup="emp", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.3f}<extra>Turnbull</extra>"), row=row, col=col)
if model is not None:
figure.add_trace(go.Scatter(x=model["years"], y=model["high"], mode="lines", line={"width": 0},
hoverinfo="skip", showlegend=False), row=row, col=col)
figure.add_trace(go.Scatter(x=model["years"], y=model["low"], mode="lines", line={"width": 0},
fill="tonexty", fillcolor="rgba(111,53,165,0.18)", hoverinfo="skip",
name="IC 95 % modelo (método delta)", legendgroup="model_band",
showlegend=first), row=row, col=col)
figure.add_trace(go.Scatter(x=model["years"], y=model["CR"], mode="lines", line={"color": "#6f35a5",
"width": 2},
name="Mezcla prevalencia-incidencia", legendgroup="model", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.3f}<extra>modelo</extra>"), row=row, col=col)
figure.update_xaxes(range=[0, max(horizons_years) + 0.05])
figure.update_yaxes(rangemode="tozero")
figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110},
title={"text": "Riesgo acumulado de CIN2+ por combinación de covariables<br>"
f"<sup>Años desde la fecha índice; {NOTICE}</sup>"},
legend={"orientation": "h", "y": 1.0, "yanchor": "bottom", "x": 0})
return figure
def _ratio(e: dict) -> str:
if e["E_O"] is None:
return "—"
flag = "" if e["low"] <= 1 <= e["high"] else " *"
return f"{e['E_O']:.2f} ({e['low']:.2f}–{e['high']:.2f}){flag}"
def _table(combination_risks: list[dict]) -> pd.DataFrame:
"""Every combination's counts and E/O at each horizon (`*`: its interval leaves out 1)."""
return pd.DataFrame([{**r["combination"], "n": r["n"], "prevalentes": r["prevalent"], "incidentes": r["incident"],
**{f"E/O {e['years']:g} a": _ratio(e) for e in r["e_o"]}} for r in combination_risks])
def subgroup_report(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24) -> str:
"""The page: the figure, the table of every combination's counts and E/O, and the methods."""
figure = _figure(combination_risks, horizons_years, report_panels)
shown = combination_risks[:report_panels]
table = _table(combination_risks)
omitted = len(combination_risks) - len(shown)
notes = (f"<p>{omitted} combinaciones más, sin panel (solo en la tabla).</p>" if omitted > 0 else "") + (
"<p>* el IC de E/O no incluye 1. — sin casos observados a ese horizonte o combinación que el modelo no "
"ubica.</p><h3>Métodos</h3><ul>" + "".join(f"<li><b>{k}</b>: {v}</li>" for k, v in METHODS.items()) + "</ul>")
return ("<!doctype html><html lang=\"es\"><head><meta charset=\"utf-8\"><title>CIN2+ por subgrupo</title></head>"
"<body style=\"font-family:sans-serif;margin:16px\">" + figure.to_html(full_html=False, include_plotlyjs=True)
+ notes + "<h3>Combinaciones</h3>" + table.to_html(index=False, border=0) + "</body></html>")
def subgroups(combination_risks: list[dict]) -> dict:
"""The report's record, with the methods it used."""
return {"version": 1, "metodos": METHODS, "combinations": combination_risks}
def population(subgroups: dict) -> dict:
"""What the saver publishes under `analisis/`, by file name."""
return {"subgrupos": subgroups}
def reports(subgroup_report: str) -> dict:
"""What the saver publishes under `reportes/`, by name."""
return {"subgrupos": subgroup_report}
@@ -0,0 +1,58 @@
domain = "cacu"
scenario = "cin2_pim_post_colposcopy"
cohort = "cacu/cohorte_total"
outcome = "cin2"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"]
description = """
Prototipo: riesgo acumulado de CIN2+ desde la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+, en la visita y a \
1, 3 y 5 años (escenario 4 de ASCCP 2019; tabla 17 de KPNC). Mezcla prevalencia–incidencia con I-splines, una por grado \
de la referencia (bajo o alto), con el VPH y la citología (tres categorías de KPNC) de esa citología como covariables, \
como reproduce exactamente la tabla 17 (capítulo 25 de bayes-pim). CIN2+ porque la biopsia LIEAG no separa CIN2 de CIN3. Sin corrección del sesgo de verificación. PROVISIONAL: una colposcopía sin orden de biopsia (impresión normal) se toma \
sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+."""
[config]
horizons_years = [0.0, 1.0, 3.0, 5.0]
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7
prevalent_window_months = 6
index_sample_days = 30
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
incidence = { family = "ispline", knots = 3, order = 4 }
# Chapter 25 of bayes-pim: table 17 is reproduced exactly with one baseline per referral grade, the six HPV × cytology
# curves proportional within it; one baseline per HPV result is not (residual 4e-3).
strata = ["referral_grade"]
incidence_features = ["cytology", "hpv_positive"]
# KPNC groups the post-colposcopy cytology in three: NILM, ASC-US/LSIL and high grade (ASC-H, AGC, HSIL+).
# The scenario's index and rules over the total cohort (models/steps/indexing.py), the same as dbt's
# cacu/cohorte_post_colposcopia_visita_1 (Cheung et al. 2020): the first surveillance visit with a cotest after the
# first colposcopy's result, before any later colposcopy. PROVISIONAL: a colposcopy without a biopsy order is below
# CIN2. The recruitment window is the source cohort's (the surveillance cohort's).
[config.index]
kind = "post_colposcopia"
visita = 1
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
referral_lookback_days = 365
hysterectomy_cie = ["Z907"]
# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded;
# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20).
observacion_previa_minima_dias = 0
[config.cytology]
NILM = ["NORMAL"]
"ASC-US/LSIL" = ["ASC-US", "LIEBG"]
"High Grade" = ["ASC-H", "AGC", "LIEAG", "CIS", "ADENOCARCINOMA"]
# The referral before the colposcopy (Egemen et al. 2020, doi:10.1097/LGT.0000000000000529): low grade is ASC-US,
# LSIL or HPV-positive NILM; high grade is ASC-H, AGC or HSIL+. The results in `lookback_days` up to the first
# colposcopy, as the cohort's `no_referral_result` rule reads them; a member without one gets none.
[config.history]
feature = "referral_grade"
event = "colposcopia"
lookback_days = 365
levels = ["low", "high"]
low = ["ASC-US/LSIL"]
low_if_hpv_positive = ["NILM"]
high = ["High Grade"]
@@ -0,0 +1,33 @@
domain = "cacu"
scenario = "cin2_pim_post_treatment"
cohort = "cacu/cohorte_post_tratamiento"
outcome = "cin2"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report"]
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"]
View File
+156
View File
@@ -0,0 +1,156 @@
"""What the CaCu survival model is made of: the member table a build's events give, and the interval survival estimator.
`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index
and rules leave get their covariates and the index date; the rest keep their row, empty. The index is the diagnosis
(provisionally the first biopsy reported as invasive carcinoma) and the covariates are the member's most recent
observations up to it: her age group at the index, the cytology of her latest sample (KPNC's categories, the more severe
of its squamous and glandular results) and her latest HPV result. `IntervalSurvival` is CaMa's
(`models.cama.survival.estimator`): per interval of `survival.horizons`, a logistic regression and a Bayesian network
with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`), stacked with
out-of-sample weights; a patient's survival to each horizon is the product of the intervals'.
DUPLICATED (issue #9): `encode`, `interval_cohort` and `IntervalSurvival` are CaMa's with the covariates as `FEATURES`
of this module instead of CaMa's; CaMa's read its own `FEATURES` as a module constant, so they can't be reused without
changing CaMa. The outcome (`outcome_table`) and the settings (`survival_settings`) are CaMa's, imported.
"""
import json
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from models.cama.seer_survival import survival_models as sm
from models.cama.survival.estimator import EPOCH, INDEX_COLUMN, UNKNOWN, WINDOW_KEYS, _band, survival_settings
from models.io.contracts import DAYS_PER_YEAR
from models.steps import indexing
FEATURES = ["age_group", "cytology", "hpv"]
NUMERIC = ["age_years"] # the age before banding
def _latest_cytology(prior: pd.DataFrame, cytology: dict) -> pd.Series:
"""Per `pac_id`, KPNC's category of her latest cytology sample: the more severe of its squamous and glandular
results; None when no result falls in a category."""
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
results = prior[prior["tipo"].isin(["bethesda", "glandular"]) & prior["valor_codigo"].notna()]
latest = results[results["fecha"] == results.groupby("pac_id")["fecha"].transform("max")]
ranks = latest["valor_codigo"].map(severity).groupby(latest["pac_id"]).max()
names = list(cytology)
return ranks.map(lambda rank: None if pd.isna(rank) else names[int(rank)])
def member_table(cohort: pd.DataFrame, age_cuts: list, cytology: dict) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice`, the covariates in `FEATURES` and the
age in years. Each covariate is the member's most recent observation up to the index (the index day included): her
age at the index from her `nacimiento`, her latest cytology sample's category (`_latest_cytology`) and her latest HPV
result; empty where the build has none."""
frame = cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
members["age_group"] = _band(members["age_years"], age_cuts)
prior = frame[frame["fecha"] <= frame["fecha_indice"]]
members["cytology"] = _latest_cytology(prior, cytology).reindex(members.index).astype(object)
hpv = prior[(prior["tipo"] == "vph") & prior["valor_codigo"].notna()].sort_values(["fecha", "fuente_id"])
members["hpv"] = hpv.groupby("pac_id")["valor_codigo"].last().reindex(members.index)
members = members.astype({"cytology": object, "hpv": object})
return members[["fecha_indice", *FEATURES, *NUMERIC]]
def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None):
"""CaMa's `encode` over this module's `FEATURES` (DUPLICATED, issue #9): `(X_dum, X_int, categories, dummy_columns)`.
With no `categories` they are learned from `frame`; with them, a value the fit never saw takes the unknown
category."""
frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str)
if categories is None:
dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns)
categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES}
columns = []
for name in FEATURES:
codes = pd.Categorical(frame[name], categories=categories[name]).codes
fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0
columns.append(np.where(codes < 0, fallback, codes))
X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32)
return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns
def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings):
"""CaMa's `interval_cohort` over this module's `FEATURES` (DUPLICATED, issue #9)."""
X_dum, X_int, categories, dummy_columns = encode(features)
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
return cohort, categories, dummy_columns
class MemberFeatures(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
def __init__(self, index=None, window=None, age_cuts=(35, 45, 55), cytology=None):
self.index = index
self.window = window
self.age_cuts = age_cuts
self.cytology = cytology
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
table = member_table(indexed, list(self.age_cuts), self.cytology) \
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
return table[[*FEATURES, INDEX_COLUMN]]
class IntervalSurvival(BaseEstimator):
"""CaMa's `IntervalSurvival` over this module's `FEATURES` (DUPLICATED, issue #9): per interval, LR and HBN stacked;
the survival to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with
`months` and `event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With
`INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member
without one) and her mortality is empty too."""
def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0)):
self.survival = survival
self.horizons_years = horizons_years
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
s = survival_settings(self.survival)
if [h / 12 for h in s.horizons] != list(self.horizons_years):
raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ")
cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s)
everyone = np.arange(len(X))
if s.combine_active and len(X) >= 2 * s.stack_folds:
weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X)))
self.weights_ = weights["w_LR"].to_numpy()
self.stacking_ = weights.to_dict("records")
else:
self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), []
self.fitted_ = sm.fit_intervals(cohort, s, everyone, None)
self.levels_ = cohort.levels
return self
def interval_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's probability of surviving each interval, given she is alive at its start."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb
def survival_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's survival to each horizon."""
return np.cumprod(self.interval_proba(X), axis=1)
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
mortality = 1.0 - self.survival_proba(X)
if INDEX_COLUMN not in X.columns:
return mortality
dates = pd.to_datetime(X[INDEX_COLUMN])
member = dates.notna().to_numpy()
mortality[~member] = np.nan
return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality])
__all__ = ["FEATURES", "INDEX_COLUMN", "IntervalSurvival", "MemberFeatures", "WINDOW_KEYS", "encode", "interval_cohort",
"member_table"]
+151
View File
@@ -0,0 +1,151 @@
"""CaCu survival prototype: the all-cause mortality at 1, 3 and 5 years from the cancer diagnosis.
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
`[config.index]`): PROVISIONAL, the diagnosis is the first biopsy reported as invasive carcinoma, which is both the
inclusion criterion and the index date. Each member's covariates are her most recent observations up to it: her age
group at the index, her latest cytology (KPNC's categories) and her latest HPV result; her outcome is the months from
the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts the
follow-up). The fit is the SEER pipeline's interval survival, as CaMa's survival scenario runs it
(`models.cama.survival`): per interval a logistic regression and a Bayesian network, stacked. A member without a result
has it as a category of its own.
The nodes that don't depend on the covariates are CaMa's, called from here: Hamilton takes as nodes only the functions
defined in a listed module, and listing CaMa's would bring its covariate-bound nodes too. Those bound to the covariates
(`labelled_members`, `missing_data`, `analytic_method`) are copies over this scenario's `FEATURES` (DUPLICATED, issue
#9). `fitted_model` puts `MemberFeatures` in front of the fitted estimator, so the registered model is one scikit-learn
`Pipeline` that takes a build's long frame.
"""
import json
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
from models.cacu.survival import estimator, report
from models.cacu.survival.estimator import FEATURES, IntervalSurvival, MemberFeatures
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival import estimator as cama_estimator
from models.cama.survival import model as cama
from models.steps import model_fitting
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"months": pandera.Column(int, pandera.Check.ge(0)),
"event": pandera.Column(bool),
**{name: pandera.Column(nullable=True) for name in FEATURES}},
name="labelled members")
def cohort_cutoff(cohort_lineage: dict) -> date:
"""CaMa's: the build's cut-off."""
return cama.cohort_cutoff(cohort_lineage)
def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSettings:
"""CaMa's: the pipeline's survival settings, whose horizons in months must be `horizons_years`."""
return cama.survival_settings(survival, horizons_years)
def member_features(cohort: pd.DataFrame, age_cuts: list[int], cytology: dict) -> pd.DataFrame:
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates (her most recent
observations up to it)."""
return estimator.member_table(cohort, age_cuts, cytology)
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""CaMa's: one row per member, by `pac_id`: months of follow-up and whether she died in them."""
return cama_estimator.outcome_table(cohort, cohort_cutoff, survival_settings.cap_months)
@checked_frame(LABELLED_MEMBERS)
def labelled_members(member_features: pd.DataFrame, member_outcomes: pd.DataFrame) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates, her follow-up and whether she died."""
return member_features.join(member_outcomes).reset_index()
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event")
def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival:
"""The interval survival fitted on the training members."""
return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]])
def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray:
"""The test members' probability of surviving each interval, given they are alive at its start."""
return fitted_survival.interval_proba(test_set[FEATURES])
def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray:
"""The training members' mortality at each horizon (apparent performance)."""
return fitted_survival.predict_proba(train_set[FEATURES])
def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray,
train_mortality: np.ndarray, survival_settings: SurvivalSettings, fitted_survival: IntervalSurvival) -> dict:
"""CaMa's: aggregates only, over the test members' member-intervals, and the apparent AUC at each horizon."""
return cama.metrics(train_set, test_set, test_interval_survival, train_mortality, survival_settings, fitted_survival)
def sampling(index_attrition: list, prior_observation: dict, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""CaMa's MUESTREO: who could be used and how they were split."""
return cama.sampling(index_attrition, prior_observation, train_set, test_set, train_fraction)
def missing_data(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many members lacked each covariate, and what was done about it (DUPLICATED, issue #9)."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int(frame[name].isna().sum()) for name in FEATURES}
return {"method": "un resultado ausente es una categoría más (NA); no se imputa ni se descarta al miembro",
"train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_survival: IntervalSurvival, survival_settings: SurvivalSettings) -> dict:
"""METODO_ANALITICO: the intervals, how the two models are stacked and which covariates the network kept
(DUPLICATED, issue #9)."""
s = survival_settings
return {"method": "supervivencia por intervalos: regresión logística y red bayesiana (CPT tabular) por intervalo, "
"combinadas con pesos fuera de muestra; la supervivencia es el producto de los intervalos",
"intervals_months": [0, *s.horizons], "censoring": s.censoring, "cap_months": s.cap_months,
"hbn_ess": s.hbn_ess, "hbn_max_parents": s.hbn_max_parents, "covariates": FEATURES,
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
for row in fitted_survival.stacking_],
"hbn_parents": [[FEATURES[j] for j in model[0]] for _, model in fitted_survival.fitted_],
"subgroup_report": report.METHODS}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""CaMa's BALANCE_CLASES: deaths and members followed without one in each part."""
return cama.class_balance(train_set, test_set)
def output_confidence(test_set: pd.DataFrame, test_interval_survival: np.ndarray, survival_settings: SurvivalSettings,
calibration_bins: int = 5) -> dict:
"""CaMa's CONFIANZA_SALIDA: the predicted survival of each interval against the observed one, by quantiles."""
return cama.output_confidence(test_set, test_interval_survival, survival_settings, calibration_bins)
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 cama.routines(sampling, missing_data, analytic_method, class_balance, output_confidence)
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
cytology: dict) -> Pipeline:
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), dict(cytology))),
("survival", fitted_survival)])
+87
View File
@@ -0,0 +1,87 @@
domain = "cacu"
scenario = "survival"
cohort = "cacu/cohorte_total"
outcome = "muerte"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.survival.model", "models.cacu.survival.population", "models.cacu.survival.report",
"models.steps.indexing"]
description = """
Prototipo: mortalidad por cualquier causa a 1, 3 y 5 años del diagnóstico de cáncer (provisional: la primera biopsia \
con carcinoma invasor), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \
recientes hasta él. Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana combinadas), \
como la de CaMa. Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la \
registra."""
[config]
train_fraction = 0.7
# The model's horizons, in years; `survival.horizons` are the same in months.
horizons_years = [1.0, 3.0, 5.0]
# The age at the index in bands, in years. The cytology and HPV are the most recent up to the index, at any distance.
age_cuts = [35, 45, 55]
# The scenario's index and rules, over its source cohort (models/steps/indexing.py). PROVISIONAL: the diagnosis is the
# first biopsy reported as invasive carcinoma (`CARCINOMA`; in situ is not), which is both the inclusion criterion and
# the index date; out: no birth date (no age), a death on or before the biopsy. The recruitment window is the source
# cohort's.
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone.
observacion_previa_minima_dias = 0
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with CaMa's settings but the
# horizons, the follow-up cap and the HBN's parents.
[config.survival]
age_mode = "categorizada"
include_age = true
age_cuts = [35, 45, 55]
hbn_fixed_parents = [] # no expert parents defined for CaCu yet: learned by the BDeu score
hbn_age_parent = false
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
covariates = []
horizons = [12, 36, 60] # months
censoring = "riesgo" # a model per interval using all the follow-up
combine = true # one LR + HBN indicator, per-interval stacking weights
show_individual = false
stack_folds = 5
stack_shrink = 20
n_boot = 100
n_boot_sub = 100
seed = 42
hbn_ess = 1000
hbn_max_parents = 5
k_ident = "clasico"
curves = "ajustada"
adjust_step = 3
show_raw_km = true
ylim_main = []
inset_zoom = false
inset_months = 60
cap_months = 60 # follow-up is cut here: a later death counts as alive
min_events_sub = 5
ks_max_seconds = 120
ks_sub_max_seconds = 180
xlim_sub = []
ylim_sub = {}
# What the dashboard's survival chart says (provisional: to be defined with the clinicians).
[config.etiquetas]
titulo = "Supervivencia después de la biopsia con carcinoma invasor"
eje_x = "Meses desde el diagnóstico"
eje_y = "Supervivencia S(t)"
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
weibull = "Weibull"
weibull_fraccional = "Weibull fraccional"
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
# the glandular result (as `cin2_pim`); with both results the more severe category wins.
[config.cytology]
NILM = ["NORMAL"]
ASC-US = ["ASC-US"]
LSIL = ["LIEBG"]
ASC-H = ["ASC-H"]
AGC = ["AGC"]
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
@@ -0,0 +1,119 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "43f4f2cf",
"metadata": {
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"#| echo: false\n",
"#| tags: [parameters]\n",
"report_panels = 24"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6f01c5ec",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"from IPython.display import HTML, Markdown, display\n",
"from models.cacu.survival import report\n",
"from models.dags.training import Scenario, dataflow\n",
"from models.notebook import experiment\n",
"\n",
"exp = experiment()\n",
"scenario = Scenario.load(exp.domain, exp.scenario)\n",
"found = dataflow(*scenario.modules, config=scenario.config).execute(\n",
" [\"combination_survival\", \"survival_settings\"], inputs={\"source_cohort\": exp.cohort(), \"cohort_lineage\": exp.lineage()})\n",
"survival, settings = found[\"combination_survival\"], found[\"survival_settings\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61c183ea",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\n",
" f\"**{exp.domain}/{exp.scenario}** · combinaciones: {len(survival)} · pacientes: {sum(r['n'] for r in survival)} · \"\n",
" f\"defunciones: {sum(r['deaths'] for r in survival)} · horizontes: {', '.join(f'{h} m' for h in settings.horizons)}\"))"
]
},
{
"cell_type": "markdown",
"id": "fd940976",
"metadata": {},
"source": [
"## Supervivencia por combinación: Kaplan-Meier y modelo"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3498c913",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(HTML(report._figure(survival, scenario.config['etiquetas'], settings, report_panels).to_html(full_html=False, include_plotlyjs=True)))"
]
},
{
"cell_type": "markdown",
"id": "2d917e18",
"metadata": {},
"source": [
"## Pacientes y defunciones por combinación"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1870121a",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(report._table(survival))"
]
},
{
"cell_type": "markdown",
"id": "2ef312c0",
"metadata": {},
"source": [
"## Métodos"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c63b624",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\"\\n\".join(f\"- **{k}**: {v}\" for k, v in report.METHODS.items())))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+87
View File
@@ -0,0 +1,87 @@
"""The population results of a training run, what the dashboard draws: the survival of the whole cohort and the model's
survival at each horizon, as CaMa's survival scenario publishes them (`models.cama.survival.population`).
Over every member of the indexed cohort: the Kaplan-Meier curve with its Greenwood interval, the covariate-adjusted
curve, the classic and the fractional Weibull fitted to it, and the mean survival at each horizon by the logistic
regression, the Bayesian network and their stacked combination, each with a 95 % bootstrap interval. The record is the
version's `analisis/curvas.json`; its labels come from `[config.etiquetas]`.
Every node but `survival_frame` is CaMa's, called from here (Hamilton takes only the functions defined in a listed
module). `survival_frame` is a copy over this scenario's `FEATURES` (DUPLICATED, issue #9).
"""
import numpy as np
import pandas as pd
from models.cacu.survival.estimator import FEATURES
from models.cama.seer_survival import survival_curves as luis
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival import population as cama
from models.cama.survival.estimator import UNKNOWN
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts
as alive) and the covariates as categories (DUPLICATED, issue #9)."""
s, lm = survival_settings, labelled_members
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
for name in FEATURES:
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
return luis.SurvivalFrame(df, list(FEATURES), None, [])
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
return cama.curve_cohort(survival_frame, survival_settings)
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
return cama.km_raw(survival_frame, survival_settings)
def km_curve(km_raw: luis.KaplanMeier) -> dict:
return cama.km_curve(km_raw)
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
return cama.adjusted_km(curve_cohort, km_raw, survival_settings)
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
return cama.population_weights(curve_cohort, survival_settings)
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
return cama.luis_points(curve_cohort, population_weights, survival_settings)
def point_estimates(luis_points: luis.Points) -> dict:
return cama.point_estimates(luis_points)
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> np.ndarray:
return cama.bootstrap_points(curve_cohort, population_weights, luis_points, survival_settings)
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
return cama.weibull_fits(adjusted_km, survival_frame, survival_settings)
def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
point_estimates: dict, bootstrap_points: np.ndarray, population_weights: pd.DataFrame,
survival_settings: SurvivalSettings, etiquetas: dict) -> dict:
"""CaMa's: the `curvas` record the dashboard draws."""
return cama.population_curves(labelled_members, km_curve, adjusted_km, weibull_fits, point_estimates,
bootstrap_points, population_weights, survival_settings, etiquetas)
def population(population_curves: dict, subgroups: dict) -> dict:
"""What the saver publishes under `analisis/`, by file name: the curves, and each combination of the covariates'
Kaplan-Meier and model survival with the methods used (`report.subgroups`). CaMa adds its SEER development stages
instead, which need covariates CaCu doesn't have."""
return {**population_curves, "subgrupos": subgroups}
+136
View File
@@ -0,0 +1,136 @@
"""The subgroup report of a training run: for each combination of the covariates (age group, latest cytology, latest
HPV), the model's survival at each horizon with its 95 % interval against the combination's own Kaplan-Meier curve with
its Greenwood band. A version keeps the record (`subgroups`, in `analisis/subgrupos.json`, with the methods it used)
and the page (`reportes/subgrupos.html`, Plotly, self-contained).
The methods are the SEER pipeline's for its subgroups, called as they are (`models.cama.seer_survival.survival_curves`):
the models are fitted on every member of the indexed cohort (the population curves' cohort, `population.curve_cohort`),
each subgroup has its own stacking weights out of sample (`sv_sub_weights`), and the model's survival of a subgroup is
its members' mean with a bootstrap percentile interval (`sv_sub_points`: `survival.n_boot_sub` resamples, the HBN's
parents of the full fit kept). The Kaplan-Meier curve of a combination is over its members only
(`fractional_weibull.km_curva`, Greenwood on the log-log scale), month by month up to its longest follow-up; death times
are exact (to the month), so it respects their censoring. Aggregates only: counts, curves and points, never a
member's row.
"""
import numpy as np
import pandas as pd
from models.cacu.survival.estimator import FEATURES
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import survival_curves as luis
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
NOTICE = "Prototipo sin validación clínica."
METHODS = {
"empirica": "Kaplan-Meier por combinación de covariables, IC 95 % de Greenwood en escala log-log "
"(models.cama.seer_survival.fractional_weibull.km_curva)",
"modelo": "supervivencia por intervalos (LR y red bayesiana, combinadas con pesos fuera de muestra por subgrupo) "
"ajustada en toda la cohorte; media de la combinación con IC 95 % bootstrap percentil "
"(models.cama.seer_survival.survival_curves.sv_sub_weights y sv_sub_points)",
}
def combination_survival(survival_frame: luis.SurvivalFrame, curve_cohort: sm.Cohort, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> list[dict]:
"""Per combination of the covariates present in the cohort, largest first: its members and deaths, its
Kaplan-Meier curve with the Greenwood band, and the combined model's survival at each horizon with its bootstrap
interval (see the module's docstring)."""
s, df = survival_settings, survival_frame.df.reset_index(drop=True)
combos = df[FEATURES].astype(str)
table = combos.drop_duplicates().reset_index(drop=True)
masks = {str(j): (combos == row).all(axis=1).to_numpy() for j, row in table.iterrows()}
weights = luis.sv_sub_weights(curve_cohort, masks, luis.sv_oof(curve_cohort, s), s)
points = luis.sv_sub_points(curve_cohort, masks, weights, luis_points, s)
months, event = df["meses_int"].to_numpy(int), df["evento"].to_numpy(bool)
name = "COMB" if s.combine_active else "LR"
records = []
for j, row in table.iterrows():
members = masks[str(j)]
follow = int(months[members].max())
km, km_low, km_high = fw.km_curva(months[members], event[members], follow)
model = points[str(j)].query("modelo == @name").sort_values("meses")
records.append({
"combination": row.to_dict(), "n": int(members.sum()), "deaths": int(event[members].sum()),
"km": {"months": list(range(follow + 1)), "S": km.tolist(), "low": km_low.tolist(), "high": km_high.tolist()},
"model": {"months": [0, *map(int, model["meses"])], "S": [1.0, *map(float, model["S"])],
"low": [1.0, *map(float, model["IC_inf"])], "high": [1.0, *map(float, model["IC_sup"])]},
})
return sorted(records, key=lambda r: (-r["n"], list(r["combination"].values())))
def _label(combination: dict) -> str:
names = {"age_group": "edad", "cytology": "citología", "hpv": "VPH"}
return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items())
def _figure(combination_survival: list[dict], etiquetas: dict, survival_settings: SurvivalSettings,
report_panels: int = 24):
"""The figure: one panel per combination (the `report_panels` largest), the Kaplan-Meier step curve with its band
and the model's points with their intervals (a Plotly `Figure`; the page and the notebook draw it)."""
import plotly.graph_objects as go
from plotly.subplots import make_subplots
shown = combination_survival[:report_panels]
columns = 3
rows = max(1, -(-len(shown) // columns))
figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.08 / max(rows, 1) * 3,
subplot_titles=[f"{_label(r['combination'])}<br>n = {r['n']}, defunciones = {r['deaths']}"
for r in shown])
for k, record in enumerate(shown):
row, col, first = k // columns + 1, k % columns + 1, k == 0
km, model = record["km"], record["model"]
figure.add_trace(go.Scatter(x=km["months"], y=km["high"], mode="lines", line={"width": 0, "shape": "hv"},
hoverinfo="skip", showlegend=False, legendgroup="km"), row=row, col=col)
figure.add_trace(go.Scatter(x=km["months"], y=km["low"], mode="lines", line={"width": 0, "shape": "hv"},
fill="tonexty", fillcolor="rgba(120,130,140,0.30)", name="IC 95 % Greenwood",
legendgroup="km", showlegend=first, hoverinfo="skip"), row=row, col=col)
figure.add_trace(go.Scatter(x=km["months"], y=km["S"], mode="lines", line={"color": "#242628", "width": 2, "shape": "hv"},
name=etiquetas.get("km_crudo", "Kaplan-Meier"), legendgroup="kmline", showlegend=first,
hovertemplate="mes %{x}: S = %{y:.3f}<extra>KM</extra>"), row=row, col=col)
S, low, high = np.array(model["S"]), np.array(model["low"]), np.array(model["high"])
figure.add_trace(go.Scatter(x=model["months"], y=S, mode="lines+markers", line={"color": "#6f35a5", "dash": "dot"},
marker={"symbol": "diamond", "size": 9},
error_y={"type": "data", "symmetric": False, "array": high - S, "arrayminus": S - low},
name=etiquetas.get("puntos", "Modelo (IC 95 % bootstrap)"), legendgroup="model",
showlegend=first, hovertemplate="mes %{x}: S = %{y:.3f}<extra>modelo</extra>"),
row=row, col=col)
figure.update_xaxes(range=[0, max(survival_settings.horizons) + 1], title_text=None)
figure.update_yaxes(range=[0, 1.03])
figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110},
title={"text": f"{etiquetas.get('titulo', 'Supervivencia')} — por combinación de covariables<br>"
f"<sup>{etiquetas.get('eje_x', 'Meses')}; {NOTICE}</sup>"},
legend={"orientation": "h", "y": 1.0, "yanchor": "bottom", "x": 0})
return figure
def _table(combination_survival: list[dict]) -> pd.DataFrame:
"""Every combination's counts."""
return pd.DataFrame([{**r["combination"], "n": r["n"], "defunciones": r["deaths"]} for r in combination_survival])
def subgroup_report(combination_survival: list[dict], etiquetas: dict, survival_settings: SurvivalSettings,
report_panels: int = 24) -> str:
"""The page: the figure, the table of every combination's counts and the methods."""
figure = _figure(combination_survival, etiquetas, survival_settings, report_panels)
counts = _table(combination_survival)
omitted = max(0, len(combination_survival) - report_panels)
note = (f"<p>{omitted} combinaciones más, sin panel (solo en la tabla).</p>" if omitted > 0 else "") + (
"<h3>Métodos</h3><ul>" + "".join(f"<li><b>{k}</b>: {v}</li>" for k, v in METHODS.items()) + "</ul>")
return ("<!doctype html><html lang=\"es\"><head><meta charset=\"utf-8\"><title>Supervivencia por subgrupo</title>"
"</head><body style=\"font-family:sans-serif;margin:16px\">"
+ figure.to_html(full_html=False, include_plotlyjs=True)
+ note + "<h3>Combinaciones</h3>" + counts.to_html(index=False, border=0) + "</body></html>")
def subgroups(combination_survival: list[dict]) -> dict:
"""The report's record, with the methods it used."""
return {"version": 1, "metodos": METHODS, "combinations": combination_survival}
def reports(subgroup_report: str) -> dict:
"""What the saver publishes under `reportes/`, by name."""
return {"subgrupos": subgroup_report}
View File
+223
View File
@@ -0,0 +1,223 @@
"""The recurrence calculator: for each clinical scenario of a cohort (a subgroup defined by covariates), the figure the
dashboard shows: the Kaplan-Meier curve of the scenario's patients with its Greenwood band, the classic and the fractional
Weibull fitted to it (dotted past the follow-up), and the recurrence-free probability at each horizon by the combination of
the LR and the HBN of that horizon, with a bootstrap interval. Ported from `05_calculadora.py`; the Weibull routines are the
survival analysis' (`models.cama.seer_survival.fractional_weibull`).
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence.factors import ORDER # noqa: F401 (the classification vocabulary is shared)
from models.cama.recurrence.modeling import CohortModels
from models.cama.recurrence.prep import Prepared
from models.cama.seer_survival import fractional_weibull as fw
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
}
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
PCT_DEFINING, PCT_MAJORITY, PCT_PRESENT = 0.95, 0.50, 0.10
@dataclass(frozen=True)
class CalculatorSettings:
seed: int = 42
n_boot: int = 200
min_events: int = 15
cap_months: int = 72
bdeu_ess: int = 10
ks_seconds: int = 60
class _Calculator:
def __init__(self, prepared: Prepared, fitted: CohortModels, s: CalculatorSettings):
self.s, self.fitted, self.covariates = s, fitted, prepared.covariates
df = prepared.cohort
self.df, self.N = df, len(df)
self.time, self.event_num = df["tiempo_meses"].values, df["evento"].values
self.X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(df[v])[0] for v in self.covariates}
self.levels = {v: int(self.codes[v].max()) + 1 for v in self.covariates}
@staticmethod
def _logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def _p_lr(self, train_idx, y, terms):
if not terms:
return np.full(self.N, y.mean())
m = self._logit(y, self.X.iloc[train_idx][terms])
return None if m is None else m.predict(sm.add_constant(self.X[terms], has_constant="add")).values
def _key(self, parents, rows):
k = np.zeros(len(rows), dtype=np.int64)
for p in parents:
k = k * self.levels[p] + self.codes[p][rows]
return k
def _p_hbn(self, train_idx, y, parents):
if not parents:
return np.full(self.N, y.mean())
q = int(np.prod([self.levels[p] for p in parents]))
alpha = self.s.bdeu_ess / (2 * q)
k_train = self._key(parents, train_idx)
n = pd.Series(1, index=k_train).groupby(level=0).sum()
n1 = pd.Series(y, index=k_train).groupby(level=0).sum()
table = (n1 + alpha) / (n + 2 * alpha)
return table.reindex(self._key(parents, np.arange(self.N))).fillna(y.mean()).values
def _risks(self, idx, H):
t, e = self.time[idx], self.event_num[idx]
recurs = (e == 1) & (t <= H)
ok = recurs | (t > H)
train, y = idx[ok], recurs[ok].astype(int)
mh = self.fitted.models[str(H)]
p_lr, p_hbn = self._p_lr(train, y, mh["terminos_lr"]), self._p_hbn(train, y, mh["padres_hbn"])
return None if p_lr is None else (p_lr, p_hbn)
def mean_risk(self, idx, masks, horizons):
out = {n: np.full(len(horizons), np.nan) for n in masks}
for j, H in enumerate(horizons):
r = self._risks(idx, H)
if r is None:
return None
combined = (r[0] + r[1]) / 2
for n, mask in masks.items():
sel = mask[idx]
if sel.any():
out[n][j] = combined[idx][sel].mean()
return out
def scenario_masks(df: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
return {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in scenarios.items()}
def _presence(share: float) -> str:
if share >= PCT_DEFINING:
return "definitoria"
if share >= PCT_MAJORITY:
return "mayoritaria"
return "presente" if share >= PCT_PRESENT else "minoritaria"
def calculator(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], settings: CalculatorSettings,
scenarios: dict | None = None) -> tuple[list[dict], pd.DataFrame]:
"""The figure record of each scenario with enough recurrences, and the table of their points."""
scenarios = scenarios if scenarios is not None else SCENARIOS[name]
c = _Calculator(prepared, fitted, settings)
masks = scenario_masks(prepared.cohort, scenarios)
everyone = np.arange(c.N)
points = c.mean_risk(everyone, masks, horizons)
rng = np.random.default_rng(settings.seed)
boots = {n: [] for n in masks}
for _ in range(settings.n_boot):
r = c.mean_risk(rng.integers(0, c.N, c.N), masks, horizons)
if r is None:
continue
for n in masks:
boots[n].append(r[n])
months_int = np.floor(c.time).astype(int)
event = c.event_num == 1
records, rows = [], []
for scenario, mask in masks.items():
n_sub, events = int(mask.sum()), int(prepared.cohort.loc[mask, "evento"].sum())
if n_sub == 0 or events < settings.min_events:
continue
m_s, e_s = months_int[mask], event[mask]
d, cen = fw.tabla_eventos(m_s, e_s)
classic = fw.ajustar_weibull(d, cen)
fractional = fw.ajustar_ks(d, cen, k_fijo=classic["k"], lam_ref=classic["lam"], max_seg=settings.ks_seconds)
observed = int(m_s.max())
S, low, high = fw.km_curva(m_s, e_s, observed)
free = 1 - points[scenario]
B = np.array(boots[scenario])
ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(horizons)), np.nan)
grid = np.linspace(0, settings.cap_months, 289)
records.append({
"cohorte": name, "cohorte_nombre": LABELS[name], "escenario": scenario, "condiciones": scenarios[scenario],
"n": n_sub, "recaidas": events, "horizons_months": horizons, "observado_hasta": observed, "months_max": settings.cap_months,
"km": {"months": list(range(observed + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
"points": {"COMB": {"S": free.tolist(), "low": np.clip(ic[0], 0, 1).tolist(), "high": np.clip(ic[1], 0, 1).tolist()}},
"bootstrap_replicas": len(B)})
for j, H in enumerate(horizons):
rows.append({"cohorte": name, "subgrupo": scenario, "n": n_sub, "recaidas": events, "horizonte_meses": H,
"S_libre_LR_HBN": free[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - free[j],
"S_libre_KM": S[min(H, observed)] if H <= observed else np.nan, "replicas_bootstrap": len(B)})
return records, pd.DataFrame(rows).round(4)
def scenario_risk_factors(name: str, prepared: Prepared, factors: pd.DataFrame, horizons: list[int],
scenarios: dict | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Which classified risk factors, protectors and treatments make up each scenario: a category nearly all of it has
defines it, most of it describes it. Returns the detail and the per-scenario summary."""
scenarios = scenarios if scenarios is not None else SCENARIOS[name]
df = prepared.cohort
masks = scenario_masks(df, scenarios)
fr = factors[(factors["cohorte"] == name) & factors["horizonte_meses"].isin(horizons)]
fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy()
fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0])
details, summary = [], []
for scenario, mask in masks.items():
n_sub = int(mask.sum())
if n_sub == 0 or fr.empty:
continue
cond = scenarios[scenario]
shares = {(v, cat): (float((df.loc[mask, v] == cat).mean()), float((df[v] == cat).mean())) for v, cat in set(zip(fr["variable"], fr["categoria"]))}
det = fr.copy()
det["pct_en_escenario"] = [shares[(v, cat)][0] for v, cat in zip(det["variable"], det["categoria"])]
det["pct_en_cohorte"] = [shares[(v, cat)][1] for v, cat in zip(det["variable"], det["categoria"])]
det["presencia"] = det["pct_en_escenario"].map(_presence)
det["en_definicion"] = [cat in cond.get(v, []) for v, cat in zip(det["variable"], det["categoria"])]
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items())
det.insert(0, "escenario", scenario)
det.insert(1, "definicion", definition)
det.insert(2, "n_escenario", n_sub)
cols = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria",
"clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte", "presencia", "en_definicion"]
details.append(det[det["pct_en_escenario"] >= PCT_PRESENT][cols])
for H in horizons:
d = det[det["horizonte_meses"] == H]
row = {"cohorte": name, "escenario": scenario, "definicion": definition, "n_escenario": n_sub, "horizonte_meses": H}
for kind in ("riesgo", "protector", "tratamiento"):
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
part = d[(d["tipo_efecto"] == kind) & (d["presencia"] == level)]
row[f"{kind}_{label}"] = "; ".join(
f"{v}={cat} ({k.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
for v, cat, k, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
row["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
summary.append(row)
return (pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame()), pd.DataFrame(summary)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+135
View File
@@ -0,0 +1,135 @@
"""The risk factors of the recurrence models: a category is a risk factor (or a protector) from four criteria, as in the
survival analysis: the multivariable OR, its stability in the bootstrap, the Markov blanket of the Bayesian network and the
survival difference; treatments are reported apart, never classified. Ported from `04_factores_riesgo.py`.
"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence.modeling import CohortModels
from models.cama.recurrence.prep import Prepared
ORDER = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
COLUMNS = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "clasificacion"]
def benjamini_hochberg(p) -> np.ndarray:
p = np.asarray(p, float)
order = np.argsort(p)
adjusted = np.empty_like(p)
m, previous = len(p), 1.0
for rank, i in zip(range(m, 0, -1), order[::-1]):
previous = min(previous, p[i] * m / rank)
adjusted[i] = previous
return adjusted
def _variable_of(term: str, variables: list[str]) -> str:
return next(v for v in sorted(variables, key=len, reverse=True) if term.startswith(v + "_"))
def _km_at(m, e, h):
T = int(m.max()) + 2
d, c = np.bincount(m[e], minlength=T), np.bincount(m[~e], minlength=T)
at_risk = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(at_risk > 0, 1 - d / np.maximum(at_risk, 1), 1.0)
v = np.where((at_risk > 0) & (at_risk > d), d / (np.maximum(at_risk, 1) * np.maximum(at_risk - d, 1)), 0.0)
h = min(h, T - 1)
S = np.prod(q[:h + 1])
return S, S * np.sqrt(np.sum(v[:h + 1]))
def _at_horizon(name: str, prepared: Prepared, fitted: CohortModels, H: int, alpha: float, freq_min: float) -> pd.DataFrame:
total, variables, treatment = prepared.cohort, prepared.covariates, prepared.treatment
intrinsic = [v for v in variables if v not in treatment]
recurs = (total["evento"] == 1) & (total["tiempo_meses"] <= H)
free = total["tiempo_meses"] > H
km_data = total.copy()
coh = total[recurs | free].reset_index(drop=True)
data = coh[variables].astype(str)
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
months = np.floor(np.minimum(km_data["tiempo_meses"].values, H + 1)).astype(int)
event = ((km_data["evento"] == 1) & (km_data["tiempo_meses"] <= H)).values
km_data = km_data[variables].astype(str)
def reference(v):
return data[v].value_counts().idxmax()
def fit_or(model_vars):
X = pd.get_dummies(data[model_vars], drop_first=False).astype(float)
refs = {v: f"{v}_{reference(v)}" for v in model_vars}
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
model = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = model.conf_int()
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(model.params[X.columns].values),
"IC95_inf": np.exp(ci.loc[X.columns, 0].values), "IC95_sup": np.exp(ci.loc[X.columns, 1].values),
"p": model.pvalues[X.columns].values})
def delta_s(v, cat, ref):
a, b = (km_data[v] == cat).values, (km_data[v] == ref).values
Sa, ea = _km_at(months[a], event[a], H)
Sb, eb = _km_at(months[b], event[b], H)
d, se = Sa - Sb, np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
"delta_IC95_inf": d - 1.96 * se, "delta_IC95_sup": d + 1.96 * se})
def complete(t, model_vars):
t = t.copy()
t["variable"] = [_variable_of(x, model_vars) for x in t["termino"]]
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
t["referencia"] = [reference(v) for v in t["variable"]]
t["p_ajustado_BH"] = benjamini_hochberg(t["p"])
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab = complete(fit_or(intrinsic), intrinsic)
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < alpha)
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
mh = fitted.models.get(str(H), {})
n_rep, selection = mh.get("n_replicas", 0), mh.get("seleccion_lr", {})
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: selection.get(v, 0) / n_rep if n_rep else np.nan)
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= freq_min
tab["en_manta_markov"] = tab["variable"].isin(set(mh.get("padres_hbn", [])))
tab["c3_manta_markov"] = tab["en_manta_markov"]
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
def classify(r):
if r["categoria"] == "Desconocido":
return "no aplica (categoria desconocida)"
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
return f"{r['direccion']} robusto"
if r["criterios_cumplidos"] >= 2:
return f"{r['direccion']} sugerente"
return "no concluyente"
tab["clasificacion"] = tab.apply(classify, axis=1)
tab["tipo"] = "factor de riesgo"
if treatment:
tr = fit_or(intrinsic + treatment)
tr["_v"] = [_variable_of(t, intrinsic + treatment) for t in tr["termino"]]
tr = tr[tr["_v"].isin(treatment) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
tr = complete(tr, treatment)
tr["tipo"] = "tratamiento"
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"], tab["horizonte_meses"] = name, H
return tab
def risk_factors(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], alpha: float = 0.05,
freq_min: float = 0.80) -> pd.DataFrame:
"""The classified categories of each horizon, risk factors first, as `factores_riesgo_recurrencia.csv`."""
new = pd.concat([_at_horizon(name, prepared, fitted, H, alpha, freq_min) for H in horizons], ignore_index=True)
new["_t"] = (new["tipo"] != "factor de riesgo").astype(int)
new["_o"] = new["clasificacion"].map(ORDER).fillna(5)
return new.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[COLUMNS].round(4)
+153
View File
@@ -0,0 +1,153 @@
"""CaMa's recurrence analysis as a scenario: the dataflow from the two external cohorts to the registered model, its results and
its routines. Each node is one stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery
(`models.dags.training.train`) saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the
dashboard shows are in `population["recurrencia"]`.
"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence import calculator as calc
from models.cama.recurrence import factors as fac
from models.cama.recurrence import modeling
from models.cama.recurrence.prep import FILES, PREPARE, Prepared
from models.cama.recurrence.source import data_folder
from models.cama.recurrence.steps import run_steps # noqa: F401 (the CLI's own steps: not a node)
COHORTS = ("metabric", "scanb")
def prepared(recurrence: dict) -> dict[str, Prepared]:
"""Each cohort as one table of categories with its covariates (`prep`)."""
folder = data_folder(recurrence["data_dir"])
return {name: PREPARE[name](str(folder / FILES[name]), recurrence["v_max"]) for name in COHORTS}
def fits(prepared: dict[str, Prepared], recurrence: dict) -> dict[str, modeling.CohortModels]:
"""The LR and the HBN at each horizon of each cohort, with their AUC (`modeling`)."""
base = {k: recurrence[k] for k in ("seed", "bdeu_ess", "max_parents", "alpha_in", "alpha_out", "alpha_prefilter")}
return {name: modeling.fit_cohort(name, prepared[name], list(recurrence["horizons"]),
modeling.FitSettings(n_bootstrap=recurrence[f"n_bootstrap_{name}"], **base)) for name in COHORTS}
def factors_table(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> pd.DataFrame:
"""The classified risk factors of both cohorts at each horizon (`factors`)."""
return pd.concat([fac.risk_factors(n, prepared[n], fits[n], list(recurrence["horizons"]), recurrence["alpha"], recurrence["freq_min"])
for n in COHORTS], ignore_index=True)
def calculators(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict[str, tuple[list[dict], pd.DataFrame]]:
"""The figure of each scenario of each cohort and the table of their points (`calculator`)."""
s = calc.CalculatorSettings(seed=recurrence["seed"], n_boot=recurrence["n_boot_calc"], min_events=recurrence["min_events"],
cap_months=recurrence["cap_months"], bdeu_ess=recurrence["bdeu_ess"], ks_seconds=recurrence["ks_seconds"])
return {n: calc.calculator(n, prepared[n], fits[n], list(recurrence["horizons"]), s) for n in COHORTS}
def scenario_factors(prepared: dict[str, Prepared], factors_table: pd.DataFrame, recurrence: dict) -> dict[str, pd.DataFrame]:
"""The risk factors that make up each scenario (`calculator.scenario_risk_factors`): the summary of both cohorts."""
summaries = [calc.scenario_risk_factors(n, prepared[n], factors_table, list(recurrence["horizons"]))[1] for n in COHORTS]
return {"resumen": pd.concat(summaries, ignore_index=True)}
class RecurrenceModel:
"""The recurrence models of one cohort fitted on all of it: at each horizon the logistic regression on the terms the
stepwise chose and the Bayesian network's table over the parents it chose. `predict_proba(X)` is the recurrence probability
at each horizon, the mean of the two models; `X` has the cohort's covariates as categories (the unknown, "Desconocido")."""
def __init__(self, cohort: str, horizons: list[int], covariates: list[str], tables: dict):
self.cohort, self.horizons, self.covariates, self.tables_ = cohort, horizons, covariates, tables
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
out = np.zeros((len(X), len(self.horizons)))
for j, H in enumerate(self.horizons):
t = self.tables_[str(H)]
p_lr = np.full(len(X), t["lr_prior"])
if t["lr_terms"]:
dummies = pd.get_dummies(X[self.covariates].astype(str)).astype(float).reindex(columns=t["lr_terms"], fill_value=0.0)
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + dummies.values @ np.asarray(t["lr_coefficients"]))))
parents, cpt = t["hbn_parents"], t["hbn_cpt"]
p_hbn = np.full(len(X), t["hbn_prior"]) if not parents else np.array(
[cpt.get(tuple(row), t["hbn_prior"]) for row in X[parents].astype(str).values])
out[:, j] = (p_lr + p_hbn) / 2
return out
def _tables(prepared: Prepared, fitted: modeling.CohortModels, horizons: list[int], bdeu_ess: int) -> dict:
"""What `RecurrenceModel` keeps from the fit on the whole cohort, per horizon."""
f = modeling._Fitter(prepared, modeling.FitSettings(bdeu_ess=bdeu_ess))
tables = {}
for H in horizons:
coh = f.at_horizon(H)
mh = fitted.models[str(H)]
terms, parents = mh["terminos_lr"], mh["padres_hbn"]
entry = {"lr_prior": float(coh["y"].mean()), "lr_terms": terms, "lr_constant": 0.0, "lr_coefficients": [],
"hbn_parents": parents, "hbn_prior": float(coh["y"].mean()), "hbn_cpt": {}}
if terms:
X = f.encode(coh)[terms]
model = f.logit(coh["y"], X)
if model is not None:
entry["lr_constant"], entry["lr_coefficients"] = float(model.params["const"]), [float(model.params[t]) for t in terms]
if parents:
table = f.bn_table(coh)
alpha = bdeu_ess / (2 * int(np.prod([table[p].nunique() for p in parents])))
g = table.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
entry["hbn_cpt"] = {(k if isinstance(k, tuple) else (k,)): float((r.n1 + alpha) / (r.n + 2 * alpha)) for k, r in g.iterrows()}
tables[str(H)] = entry
return tables
def fitted_model(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> RecurrenceModel:
"""The model that is saved: METABRIC's, the larger of the two cohorts' external references for the covariates both share."""
return RecurrenceModel("metabric", list(recurrence["horizons"]), prepared["metabric"].covariates,
_tables(prepared["metabric"], fits["metabric"], list(recurrence["horizons"]), recurrence["bdeu_ess"]))
def metrics(fits: dict[str, modeling.CohortModels]) -> dict:
"""Numbers only: each cohort's AUC by internal validation and by bootstrap, per horizon and model, and its Cox C-index."""
found = {}
for name, fit in fits.items():
for _, r in fit.auc.iterrows():
if r["horizonte_meses"] == "completo":
found[f"{name}.c_index_cox"] = float(r["AUC_validacion_interna"])
continue
tag = f"{name}.auc_{r['modelo']}_{int(r['horizonte_meses'])}m"
found[tag] = float(r["AUC_validacion_interna"])
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
return found
def routines(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict:
"""The five routine records the registry's promotion reads (ML-01a)."""
return {
"MUESTREO": {"cohortes": {n: {"pacientes": len(p.cohort), "recaidas": int(p.cohort["evento"].sum()), "covariables": len(p.covariates),
"eliminadas_por_colinealidad": p.eliminated} for n, p in prepared.items()},
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "METABRIC y SCAN-B (externas)"},
"DATOS_FALTANTES": {"criterio": "el dato faltante es una categoría más («Desconocido»); no se imputa ni se descarta",
"desconocidos_por_covariable": {n: {c: float((p.cohort[c] == "Desconocido").mean()) for c in p.covariates} for n, p in prepared.items()}},
"METODO_ANALITICO": {"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte",
"horizontes_meses": recurrence["horizons"], "alfa_entrada": recurrence["alpha_in"], "alfa_salida": recurrence["alpha_out"],
"ess_bdeu": recurrence["bdeu_ess"], "maximo_de_padres": recurrence["max_parents"], "cox_penalizado": 0.05,
"combinacion": "promedio de la LR y la HBN"},
"BALANCE_CLASES": {"aplica": False, "motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres de ella después; no se rebalancea"},
"CONFIANZA_SALIDA": {"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por bootstrap",
"replicas": {"metabric": recurrence["n_bootstrap_metabric"], "scanb": recurrence["n_bootstrap_scanb"], "calculadora": recurrence["n_boot_calc"]},
"eventos_minimos_por_escenario": recurrence["min_events"]},
}
def population(calculators: dict, fits: dict[str, modeling.CohortModels], factors_table: pd.DataFrame, scenario_factors: dict,
recurrence: dict) -> dict:
"""What the version publishes under `analisis/`: `recurrencia`, the figure of each scenario of each cohort the dashboard
draws, and `recurrencia_desarrollo`, the tables behind them."""
figures = [r for n in COHORTS for r in calculators[n][0]]
points = pd.concat([calculators[n][1] for n in COHORTS], ignore_index=True)
auc = pd.concat([fits[n].auc for n in COHORTS], ignore_index=True)
def table(df: pd.DataFrame) -> dict:
df = df.replace([np.inf, -np.inf], np.nan).astype(object)
return {"columnas": [str(c) for c in df.columns], "filas": df.where(df.notna(), None).to_dict("records")}
return {"recurrencia": {"version": 1, "horizons_months": list(recurrence["horizons"]), "escenarios": figures},
"recurrencia_desarrollo": {"version": 1, "tablas": {"auc": table(auc), "factores_riesgo": table(factors_table),
"calculadora": table(points), "escenarios_resumen": table(scenario_factors["resumen"])}}}
+33
View File
@@ -0,0 +1,33 @@
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, from two external cohorts (METABRIC and SCAN-B).
# Trained from governance on the files in `data/`; the scenarios' figures are what the dashboard shows. Its covariates are the
# cohorts' own; the hospital's patient is placed in the scenarios her covariates meet.
domain = "cama"
scenario = "recurrence"
cohort = "cama/externa"
outcome = "recurrencia"
external = true # trained on files, not on a dbt cohort of the platform
modules = ["models.cama.recurrence.model"]
description = """\
Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36 y 60 meses por escenario clínico, con una \
regresión logística y una red bayesiana por horizonte, entrenadas en dos cohortes externas (METABRIC y SCAN-B). Pendiente \
de validación clínica."""
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
[config.recurrence]
data_dir = "" # empty: the `data/` folder of this package
horizons = [12, 36, 60] # months
v_max = 0.80 # Cramér's V from which of two covariates the one with more unknowns is dropped
seed = 42
bdeu_ess = 10
max_parents = 6
alpha_in = 0.10
alpha_out = 0.15
alpha_prefilter = 0.10
alpha = 0.05 # the risk factors' significance
freq_min = 0.80 # the bootstrap's stability criterion
n_bootstrap_metabric = 100
n_bootstrap_scanb = 40
n_boot_calc = 200 # replicas of each scenario's interval
min_events = 15 # recurrences a scenario needs to be drawn
cap_months = 72 # the figure's time axis
ks_seconds = 60 # time budget of each fractional Weibull fit
+194
View File
@@ -0,0 +1,194 @@
"""The recurrence models of one cohort: at each horizon the logistic regression (stepwise) and the Bayesian network (the
BDeu-greedy parents of the outcome), their AUC by internal validation and by bootstrap, how often each covariate enters the
bootstrap's regressions and the parents, and the penalised Cox model's concordance. Ported from `03_modelado.py` without its
figures. The selected terms and parents of each horizon are what the risk factors and the calculator read.
"""
import warnings
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.estimators import BDeu
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.recurrence.prep import Prepared
@dataclass(frozen=True)
class FitSettings:
seed: int = 42
n_bootstrap: int = 100
bdeu_ess: int = 10
max_parents: int = 6
alpha_in: float = 0.10
alpha_out: float = 0.15
alpha_prefilter: float = 0.10
@dataclass(frozen=True, eq=False)
class CohortModels:
models: dict[str, dict] # by horizon: the LR terms, the HBN parents and how often each entered the bootstrap
auc: pd.DataFrame
c_index: float
class _Fitter:
def __init__(self, prepared: Prepared, settings: FitSettings):
self.covariates, self.s, self.total = prepared.covariates, settings, prepared.cohort
def encode(self, df: pd.DataFrame) -> pd.DataFrame:
X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
@staticmethod
def logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def prefilter(self, X, y) -> list[str]:
keep = []
for c in X.columns:
m = self.logit(y, X[[c]])
if m is not None and m.pvalues[c] < self.s.alpha_prefilter:
keep.append(c)
return keep
def stepwise(self, X, y) -> list[str]:
included = []
for _ in range(200):
changed, best, best_p = False, None, self.s.alpha_in
for c in [c for c in X.columns if c not in included]:
m = self.logit(y, X[included + [c]])
if m is not None and m.pvalues[c] < best_p:
best, best_p = c, m.pvalues[c]
if best is not None:
included.append(best)
changed = True
if included:
m = self.logit(y, X[included])
if m is not None:
p = m.pvalues.drop("const")
if p.max() > self.s.alpha_out:
included.remove(p.idxmax())
changed = True
if not changed:
break
return included
def lr(self, train: pd.DataFrame, test: pd.DataFrame):
X_all = self.encode(pd.concat([train, test]))
X_tr, X_te = X_all.loc[train.index], X_all.loc[test.index]
X_tr = X_tr.loc[:, X_tr.nunique() > 1]
X_te = X_te[X_tr.columns]
candidates = self.prefilter(X_tr, train["y"])
selected = self.stepwise(X_tr[candidates], train["y"]) if candidates else []
if not selected:
return None, [], np.full(len(test), train["y"].mean())
model = self.logit(train["y"], X_tr[selected])
return model, selected, model.predict(sm.add_constant(X_te[selected], has_constant="add")).values
def variable_of(self, term: str) -> str:
return next((c for c in sorted(self.covariates, key=len, reverse=True) if term.startswith(c + "_")), term)
def parents(self, train: pd.DataFrame) -> list[str]:
score = BDeu(train, equivalent_sample_size=self.s.bdeu_ess)
parents, current = [], score.local_score("outcome", [])
while len(parents) < self.s.max_parents:
best, gain = None, 0
for c in self.covariates:
if c in parents:
continue
g = score.local_score("outcome", parents + [c]) - current
if g > gain:
best, gain = c, g
if best is None:
break
parents.append(best)
current += gain
return parents
def hbn(self, train: pd.DataFrame, test: pd.DataFrame, parents: list[str]) -> np.ndarray:
if not parents:
return np.full(len(test), (train["outcome"] == "1").mean())
q = int(np.prod([train[p].nunique() for p in parents]))
alpha = self.s.bdeu_ess / (2 * q)
g = train.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
overall = (train["outcome"] == "1").mean()
table = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
return np.array([table.get(k, overall) for k in map(tuple, test[parents].values)])
def bn_table(self, df: pd.DataFrame) -> pd.DataFrame:
t = df[self.covariates].astype(str).copy()
t["outcome"] = df["y"].astype(int).astype(str)
return t
def at_horizon(self, H: int) -> pd.DataFrame:
recurs = (self.total["evento"] == 1) & (self.total["tiempo_meses"] <= H)
free = self.total["tiempo_meses"] > H
d = self.total[recurs | free].reset_index(drop=True)
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
return d
def fit_cohort(name: str, prepared: Prepared, horizons: list[int], settings: FitSettings) -> CohortModels:
"""The LR and the HBN at each horizon, their AUC and the bootstrap's, and the Cox model's concordance."""
warnings.filterwarnings("ignore")
f, s = _Fitter(prepared, settings), settings
total = prepared.cohort
cox_df = pd.get_dummies(total[["tiempo_meses", "evento"] + f.covariates], columns=f.covariates, drop_first=True).astype(float)
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
tr, te = train_test_split(cox_df, test_size=0.3, random_state=s.seed, stratify=cox_df["evento"])
ok = [c for c in tr.columns if c in ("tiempo_meses", "evento") or 10 <= tr[c].sum() <= len(tr) - 10]
tr, te = tr[ok], te[ok]
cox = CoxPHFitter(penalizer=0.05).fit(tr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
c_index = float(concordance_index(te["tiempo_meses"], -cox.predict_partial_hazard(te), te["evento"]))
rows, models = [], {}
for H in horizons:
coh = f.at_horizon(H)
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=s.seed, stratify=coh["y"])
train, test = coh.loc[tr_idx], coh.loc[te_idx]
_, selected, p_lr = f.lr(train, test)
auc_lr = roc_auc_score(test["y"], p_lr)
bn_train, bn_test = f.bn_table(train), f.bn_table(test)
parents = f.parents(bn_train)
auc_hbn = roc_auc_score(test["y"], f.hbn(bn_train, bn_test, parents))
rng = np.random.default_rng(s.seed)
aucs, count_lr, count_hbn, n_rep = [], {}, {}, 0
for b in range(s.n_bootstrap):
boot = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
try:
b_train, b_test = train_test_split(boot, test_size=0.3, random_state=s.seed + b, stratify=boot["y"])
m, _, p = f.lr(b_train, b_test)
a_lr = roc_auc_score(b_test["y"], p)
bt, be = f.bn_table(b_train), f.bn_table(b_test)
pa = f.parents(bt)
a_h = roc_auc_score(b_test["y"], f.hbn(bt, be, pa))
except Exception:
continue
aucs.append((a_lr, a_h))
n_rep += 1
if m is not None:
for v in {f.variable_of(t) for t in m.params.drop("const").index}:
count_lr[v] = count_lr.get(v, 0) + 1
for v in pa:
count_hbn[v] = count_hbn.get(v, 0) + 1
aucs = np.array(aucs) if aucs else np.full((1, 2), np.nan)
for j, (label, auc) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
rows.append({"cohorte": name, "horizonte_meses": H, "modelo": label, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
"AUC_validacion_interna": auc, "AUC_bootstrap_medio": np.nanmean(aucs[:, j]),
"AUC_bootstrap_IC95_inf": np.nanpercentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.nanpercentile(aucs[:, j], 97.5),
"replicas_bootstrap": n_rep})
models[str(H)] = {"terminos_lr": list(selected), "padres_hbn": parents, "n_replicas": n_rep,
"seleccion_lr": count_lr, "seleccion_hbn": count_hbn,
"arcos_hbn": [[p, "outcome"] for p in parents]}
rows.append({"cohorte": name, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(total),
"recurrencias": int(total["evento"].sum()), "AUC_validacion_interna": c_index})
return CohortModels(models, pd.DataFrame(rows).round(4), c_index)
+36
View File
@@ -0,0 +1,36 @@
"""A hospital patient in the recurrence analysis' terms: her covariates as the external cohorts name them, and the scenarios
(subgroups defined by covariates) she belongs to. What the hospital does not report (nodes, subtype, surgery...) is not given, so
a scenario that needs it does not include her."""
import numpy as np
import pandas as pd
from models.cama.recurrence import prep
POSITIVE = {"POSITIVO": "Positive", "NEGATIVO": "Negative"}
HER2 = {"H3": "Positive", "H0": "Negative", "H1": "Negative"} # 2+ is equivocal: not given
def _bin(value, cuts: list, labels: list) -> str | None:
if value is None or pd.isna(value):
return None
return str(pd.cut([float(value)], cuts, labels=labels, right=False)[0])
def covariates_of(row: pd.Series) -> dict[str, str]:
"""The covariates of one labelled member (`models.cama.survival.live.members`) that the cohorts also have."""
found = {
"Edad": _bin(row.get("age_years"), prep.AGE_CUTS, prep.AGE_LABELS),
"Tamano_tumor": _bin(row.get("size_mm"), prep.SIZE_CUTS, prep.SIZE_LABELS),
"Grado_histologico": {"G1": "1", "G2": "2", "G3": "3"}.get(row.get("grade")),
"Receptor_estrogeno": POSITIVE.get(row.get("er")),
"Receptor_progesterona": POSITIVE.get(row.get("pr")),
"HER2": HER2.get(row.get("her2")),
}
return {k: v for k, v in found.items() if v is not None}
def matching(scenarios: list[dict], covariates: dict[str, str]) -> list[dict]:
"""The scenarios whose every condition her covariates meet, the larger first within each cohort."""
met = [s for s in scenarios if all(var in covariates and covariates[var] in values for var, values in s["condiciones"].items())]
return sorted(met, key=lambda s: (s["cohorte"], -s["n"]))
+108
View File
@@ -0,0 +1,108 @@
"""The recurrence analysis' data: the two external cohorts (METABRIC and SCAN-B) as one table each, the covariates as
categories with the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped. Ported
from `01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency
DAYS_PER_MONTH = 30.4375
AGE_CUTS, AGE_LABELS = [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]
SIZE_CUTS, SIZE_LABELS = [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]
NODE_CUTS, NODE_LABELS = [0, 1, 4, 1e3], ["0", "1-3", "4+"]
@dataclass(frozen=True, eq=False)
class Prepared:
cohort: pd.DataFrame # paciente, tiempo_meses, evento and the covariates
covariates: list[str]
treatment: list[str]
eliminated: list[str]
def _unknown(s: pd.Series) -> pd.Series:
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
def _cut(s: pd.Series, cuts: list, labels: list) -> pd.Series:
return _unknown(pd.cut(s, cuts, labels=labels, right=False).astype("object"))
def cramer_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b)
chi2 = chi2_contingency(table, correction=False)[0]
k = min(table.shape) - 1
return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0
def _drop_collinear(out: pd.DataFrame, covariates: list[str], treatment: list[str], v_max: float) -> tuple[list[str], list[str]]:
"""Of each pair of non-treatment covariates with V at or above `v_max`, the one with more unknowns goes."""
covariates, eliminated = list(covariates), []
candidates = [c for c in covariates if c not in treatment]
pairs = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]), reverse=True)
for v, a, b in pairs:
if v < v_max:
break
if a in eliminated or b in eliminated:
continue
drop = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b
eliminated.append(drop)
covariates.remove(drop)
return covariates, eliminated
def _finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
covariates = [c for c in out.columns if c not in fixed]
covariates, eliminated = _drop_collinear(out, covariates, treatment, v_max)
return Prepared(out[[*fixed, *covariates]], covariates, [c for c in treatment if c in covariates], eliminated)
def prepare_metabric(path: str, v_max: float) -> Prepared:
d = pd.read_csv(path, sep="\t")
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["Patient ID"]})
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
out["Edad"] = _cut(d["Age at Diagnosis"], AGE_CUTS, AGE_LABELS)
out["Tamano_tumor"] = _cut(d["Tumor Size"], SIZE_CUTS, SIZE_LABELS)
out["Ganglios_positivos"] = _cut(d["Lymph nodes examined positive"], NODE_CUTS, NODE_LABELS)
out["Grado_histologico"] = _unknown(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
mutations = d["Mutation Count"]
q = mutations.quantile([1 / 3, 2 / 3]).values
out["Carga_mutacional"] = _cut(mutations, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
for name, column in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
out[name] = _unknown(d[column])
return _finish(out, ["paciente", "tiempo_meses", "evento"], ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], v_max)
def prepare_scanb(path: str, v_max: float) -> Prepared:
d = pd.read_csv(path, sep="\t", low_memory=False)
d = d[d["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["PatientName"]})
out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH
out["evento"] = d["RFI_event"].astype(int)
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
out["Edad"] = _cut(d["Age_5year_bin"].astype(float) - 2, AGE_CUTS, AGE_LABELS)
out["Tamano_tumor"] = _cut(d["TumorSize_mm"], SIZE_CUTS, SIZE_LABELS)
out["Ganglios_positivos"] = _unknown(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
out["Grado_histologico"] = _unknown(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
for name, column in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
out[name] = _unknown(d[column])
return _finish(out, ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], v_max)
PREPARE = {"metabric": prepare_metabric, "scanb": prepare_scanb}
FILES = {"metabric": "brca_metabric_clinical_data.tsv", "scanb": "scanb_clinical_metadata.txt"}
+42
View File
@@ -0,0 +1,42 @@
"""The recurrence analysis' training data: two files on disk, not a cohort of the platform. It takes the part of a cohort source
(`models.io.storage.CohortSource`) for the training run: the reference the version is traced to, which is the hash of the files."""
import hashlib
from dataclasses import dataclass
from pathlib import Path
import pandas as pd
from models.cama.recurrence.prep import FILES
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG
from models.io.registry import REFERENCE_SOURCE
PACKAGE_DATA = Path(__file__).parent / "data"
URL = "cama/externa/metabric+scanb"
def data_folder(configured: str) -> Path:
return Path(configured) if configured else PACKAGE_DATA
@dataclass
class ExternalCohorts:
"""The METABRIC and SCAN-B files of a folder."""
folder: Path = PACKAGE_DATA
armado_id: int | None = None
def sha256(self) -> str:
digest = hashlib.sha256()
for name in sorted(FILES.values()):
digest.update((self.folder / name).read_bytes())
return digest.hexdigest()
def frame(self) -> pd.DataFrame:
return pd.DataFrame()
def lineage(self) -> dict[str, str]:
return {"url": URL, "files": ",".join(sorted(FILES.values())), "sha256": self.sha256()}
def reference(self) -> dict[str, str]:
return {COHORT_URL_TAG: URL, COHORT_SOURCE_TAG: REFERENCE_SOURCE, COHORT_BUILD_TAG: self.sha256()}
+31
View File
@@ -0,0 +1,31 @@
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
import argparse
import sys
def run_steps(args: argparse.Namespace) -> int:
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
from models.__main__ import _promote_step
from models.cama.recurrence.source import ExternalCohorts, data_folder
from models.dags.training import Scenario, find_trained, train
if args.export or args.estimate or args.store or args.version:
print("cama/recurrence trains on its external cohorts: only --train and --promote apply", file=sys.stderr)
return 2
scenario = Scenario.load("cama", "recurrence")
source = ExternalCohorts(data_folder(scenario.config["recurrence"]["data_dir"]))
environment = args.environment.upper()
version = find_trained(scenario, source, environment)
if args.train:
if version:
print(f"already trained: version {version}, from {source.lineage()['sha256'][:12]}")
else:
version = train(scenario, source, environment)
print(f"trained: version {version}, from {source.lineage()['sha256'][:12]}")
if args.promote:
if not version:
print(f"no {environment} version trained: use --train", file=sys.stderr)
return 1
return _promote_step(args, version)
return 0
+1 -58
View File
@@ -151,64 +151,7 @@ xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty
[survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0]
# Subgroups: every condition present must hold. her2 = "pos" | "neg"; triple_negative (HR-/HER2-); age_min (>=) and
# age_max (<) in years; stages (0..4); conservative (conservative surgery).
[[survival.subgroups]]
name = "HER2+ · ≥60 años · estadio III–IV (Alto)"
her2 = "pos"
age_min = 60
stages = [3, 4]
[[survival.subgroups]]
name = "HER2+ · <60 años · estadio 0–II (Bajo)"
her2 = "pos"
age_max = 60
stages = [0, 1, 2]
[[survival.subgroups]]
name = "Estadio IV"
stages = [4]
[[survival.subgroups]]
name = "Estadio I"
stages = [1]
[[survival.subgroups]]
name = "≥ 75 años"
age_min = 75
[[survival.subgroups]]
name = "< 45 años"
age_max = 45
[[survival.subgroups]]
name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora"
her2 = "neg"
age_max = 45
stages = [0, 1, 2]
conservative = true
[[survival.subgroups]]
name = "HER2− · estadio 0–II · cirugía conservadora"
her2 = "neg"
stages = [0, 1, 2]
conservative = true
[[survival.subgroups]]
name = "HER2+ · estadio 0–II · cirugía conservadora"
her2 = "pos"
stages = [0, 1, 2]
conservative = true
[[survival.subgroups]]
name = "Jóvenes (<45) · estadio 0–II"
age_max = 45
stages = [0, 1, 2]
[[survival.subgroups]]
name = "Jóvenes (<45) · HER2−"
her2 = "neg"
age_max = 45
[[survival.subgroups]]
name = "Triple negativo (HR−/HER2−) · estadio 0–II"
triple_negative = true
stages = [0, 1, 2]
[[survival.subgroups]]
name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora"
her2 = "neg"
age_min = 65
stages = [0, 1, 2]
conservative = true
# The subgroups of the survival curves, and the risk factors of each, are the clinical scenarios of `scenarios.py`.
[risk_factors]
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
+4 -3
View File
@@ -53,11 +53,12 @@ STAGES = [
Stage("05", lambda d, s: run.run_survival(d / run.DEPURATED, d, s), (run.DEPURATED,),
("curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"),
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "settings.py", "run.py")),
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "scenarios.py", "settings.py", "run.py")),
Stage("06", lambda d, s: run.run_risk_factors(d / run.NATURAL, d, settings=s),
(run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"),
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"),
("risk_factors.py", "risk_factor_stats.py", "settings.py", "run.py")),
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv",
"escenarios_factores_riesgo.csv", "escenarios_resumen.csv"),
("risk_factors.py", "risk_factor_stats.py", "scenarios.py", "settings.py", "run.py")),
]
+75 -1
View File
@@ -15,6 +15,7 @@ import numpy as np
import pandas as pd
from models.cama.seer_survival import risk_factor_stats as stats
from models.cama.seer_survival import scenarios
from models.cama.seer_survival.settings import RiskFactorSettings
CRITERIA = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
@@ -205,13 +206,16 @@ def risk_variable_summary(risk_classification: Classification) -> pd.DataFrame:
def risk_treatment_associations(risk_data: pd.DataFrame, risk_follow_up: FollowUp, risk_intrinsic: list[str],
risk_treatment: list[str], risk_factors: RiskFactorSettings) -> pd.DataFrame | None:
"""The treatment variables' adjusted associations with death, descriptive and not classified (confounding by
indication); None when there are none."""
indication); None when there are none
or none of them varies."""
if not risk_treatment:
return None
variables = risk_intrinsic + risk_treatment
tr = stats.fit_odds(risk_data, risk_follow_up.death, variables)
tr["variable"] = [stats.variable_of(t, variables) for t in tr["termino"]]
tr = tr[tr["variable"].isin(risk_treatment)].copy()
if tr.empty:
return None
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
tr["referencia"] = [stats.reference(risk_data, v) for v in tr["variable"]]
tr["p_ajustado_BH"] = stats.benjamini_hochberg(tr["p"])
@@ -230,3 +234,73 @@ def risk_criteria(risk_classification: Classification, risk_bootstrap_frequency:
"horizonte_meses": risk_factors.horizon, "tope_meses": risk_factors.cap_months,
"replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas),
"criterios_evaluados": risk_classification.criteria, "variables_tratamiento_excluidas": risk_treatment}
# ---------------------------------------------------------------- the risk factors of each clinical scenario
PCT_DEFINING = 0.95 # the category is in at least this share of the scenario: it defines it
PCT_MAJORITY = 0.50
PCT_PRESENT = 0.10
@dataclass(frozen=True, eq=False)
class ScenarioFactors:
details: pd.DataFrame # per scenario and classified category: its share of the scenario and of the cohort
summary: pd.DataFrame # per scenario: the risk factors, protectors and treatments that define it or are most of it
def _presence(share: float) -> str:
if share >= PCT_DEFINING:
return "definitoria"
if share >= PCT_MAJORITY:
return "mayoritaria"
return "presente" if share >= PCT_PRESENT else "minoritaria"
def risk_scenario_masks(risk_natural: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each clinical scenario's mask over the natural population (`scenarios.masks`), on its raw columns."""
return scenarios.masks(risk_natural.drop(columns=[c for c in ("Age_group", "Tumor_group") if c in risk_natural.columns]))
def risk_scenario_factors(risk_classification: Classification, risk_treatment_associations: pd.DataFrame | None,
risk_data: pd.DataFrame, risk_scenario_masks: dict[str, np.ndarray]) -> ScenarioFactors:
"""Which of the classified risk factors, protectors and treatment associations make up each clinical scenario: a
category that is nearly all of a scenario defines it, one that is most of it describes it."""
table = risk_classification.table
classified = table[table["clasificacion"].str.contains("robusto|sugerente")].copy()
classified["tipo"] = classified["clasificacion"].str.split().str[0]
if risk_treatment_associations is not None and len(risk_treatment_associations):
treatment = risk_treatment_associations.copy()
treatment["clasificacion"], treatment["tipo"] = "tratamiento (no se clasifica)", "tratamiento"
classified = pd.concat([classified, treatment], ignore_index=True)
details, summary = [], []
for name, mask in risk_scenario_masks.items():
size = int(mask.sum())
if size == 0:
continue
definition = scenarios.describe(scenarios.SCENARIOS[name]) if name in scenarios.SCENARIOS else ""
rows = []
for _, r in classified.iterrows():
share = float((risk_data[r["variable"]][mask] == r["categoria"]).mean())
rows.append({"escenario": name, "definicion": definition, "n_escenario": size,
"tipo": r["tipo"], "variable": r["variable"], "categoria": r["categoria"], "clasificacion": r["clasificacion"],
"OR_muerte": r["OR_muerte"], "IC95_inf": r["IC95_inf"], "IC95_sup": r["IC95_sup"], "delta_S18": r["delta_S18"],
"pct_en_escenario": share, "pct_en_cohorte": float((risk_data[r["variable"]] == r["categoria"]).mean()),
"presencia": _presence(share)})
found = pd.DataFrame(rows, columns=["escenario", "definicion", "n_escenario", "tipo", "variable", "categoria", "clasificacion",
"OR_muerte", "IC95_inf", "IC95_sup", "delta_S18", "pct_en_escenario", "pct_en_cohorte", "presencia"])
details.append(found[found["pct_en_escenario"] >= PCT_PRESENT])
def listed(kind, levels):
part = found[(found["tipo"] == kind) & (found["presencia"].isin(levels))]
return "; ".join(f"{a}={b} ({c.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
for a, b, c, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
row = {"escenario": name, "definicion": definition, "n_escenario": size}
for kind in ("riesgo", "protector", "tratamiento"):
row[f"{kind}_definitorios"] = listed(kind, ["definitoria"])
row[f"{kind}_mayoritarios"] = listed(kind, ["mayoritaria"])
row["n_factores_riesgo_incluidos"] = int(((found["tipo"] == "riesgo") & found["presencia"].isin(["definitoria", "mayoritaria"])).sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
summary.append(row)
return ScenarioFactors(pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame(), pd.DataFrame(summary))
+4 -2
View File
@@ -193,13 +193,15 @@ def run_risk_factors(natural_csv: str, output_dir: str, bootstrap_selection_csv:
inputs = {"natural_csv": str(natural_csv),
"bootstrap_selection_csv": str(bootstrap_selection_csv or out / "seleccion_bootstrap.csv"),
"hbn_arcs_csv": str(hbn_arcs_csv or out / "hbn_arcos.csv"), "risk_factors": settings.risk_factors}
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria"],
inputs=inputs)
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria",
"risk_scenario_factors"], inputs=inputs)
r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False)
r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv")
if r["risk_treatment_associations"] is not None:
r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False)
_dump(out / "factores_riesgo_criterios.json", r["risk_criteria"])
r["risk_scenario_factors"].details.to_csv(out / "escenarios_factores_riesgo.csv", index=False)
r["risk_scenario_factors"].summary.to_csv(out / "escenarios_resumen.csv", index=False)
return r
+116
View File
@@ -0,0 +1,116 @@
"""The clinical scenarios of the survival analysis: the subgroups whose curves stage 5 draws and whose risk factors stage 6
lists. Each is a set of conditions over the cohort's raw columns (age, stage, molecular subtype, surgery); the columns are
found by keyword, so a cohort without one of them has no patient in the scenarios that need it. Ported from
`escenarios_clinicos.py`.
"""
import re
import numpy as np
import pandas as pd
def find_col(df: pd.DataFrame, keywords) -> str | None:
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords):
return col
return None
def _age(v) -> float:
m = re.search(r"\d+", str(v))
return float(m.group()) if m else np.nan
def _stage(v) -> float:
u = str(v).upper().replace("STAGE", "").strip()
if u.startswith("0") or u == "IS":
return 0
for prefix, value in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
if u.startswith(prefix):
return value
return np.nan
def _age_column(df: pd.DataFrame) -> str | None:
candidates = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
if not candidates:
return None
return sorted(candidates, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0]
def values_by_axis(df: pd.DataFrame) -> dict[str, pd.Series]:
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
col_subtype = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
col_surgery = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
col_age = _age_column(df)
n = len(df)
return {
"edad": df[col_age].map(_age).astype(float) if col_age else pd.Series(np.nan, index=df.index),
"estadio": df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index),
"subtipo": df[col_subtype].astype(str) if col_subtype else pd.Series([""] * n, index=df.index),
"cirugia": df[col_surgery].astype(str).str.lower() if col_surgery else pd.Series([""] * n, index=df.index),
}
AGE_BELOW = lambda x: ("edad", "<", x)
AGE_FROM = lambda x: ("edad", ">=", x)
STAGE_0_II = ("estadio", "en", [0, 1, 2])
STAGE_III_IV = ("estadio", "en", [3, 4])
HER2_POS = ("subtipo", "contiene", "HER2+")
HER2_NEG = ("subtipo", "contiene", "HER2-")
TRIPLE_NEG = ("subtipo", "contiene", "HR-/HER2-")
CONSERVATIVE = ("cirugia", "contiene", "conserv")
SCENARIOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": [HER2_POS, AGE_FROM(60), STAGE_III_IV],
"HER2+ · <60 años · estadio 0–II (Bajo)": [HER2_POS, AGE_BELOW(60), STAGE_0_II],
"Estadio IV": [("estadio", "en", [4])],
"Estadio I": [("estadio", "en", [1])],
"≥ 75 años": [AGE_FROM(75)],
"< 45 años": [AGE_BELOW(45)],
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": [AGE_BELOW(45), HER2_NEG, STAGE_0_II, CONSERVATIVE],
"HER2− · estadio 0–II · cirugía conservadora": [HER2_NEG, STAGE_0_II, CONSERVATIVE],
"HER2+ · estadio 0–II · cirugía conservadora": [HER2_POS, STAGE_0_II, CONSERVATIVE],
"Jóvenes (<45) · estadio 0–II": [AGE_BELOW(45), STAGE_0_II],
"Jóvenes (<45) · HER2−": [AGE_BELOW(45), HER2_NEG],
"Triple negativo (HR−/HER2−) · estadio 0–II": [TRIPLE_NEG, STAGE_0_II],
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": [AGE_FROM(65), HER2_NEG, STAGE_0_II, CONSERVATIVE],
}
STAGE_LABEL = {0: "0", 1: "I", 2: "II", 3: "III", 4: "IV"}
def describe(conditions) -> str:
parts = []
for axis, op, value in conditions:
if axis == "edad":
parts.append(f"edad {op} {value:g}")
elif axis == "estadio":
parts.append("estadio " + "/".join(STAGE_LABEL[v] for v in value))
elif axis == "subtipo":
parts.append(f"subtipo {value}")
elif axis == "cirugia":
parts.append("cirugía conservadora")
return "; ".join(parts)
def masks(df: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each scenario's mask over the cohort: every condition must hold."""
values = values_by_axis(df)
out = {}
for name, conditions in SCENARIOS.items():
mask = pd.Series(True, index=df.index)
for axis, op, value in conditions:
s = values[axis]
if op == "<":
mask &= (s < value).fillna(False)
elif op == ">=":
mask &= (s >= value).fillna(False)
elif op == "en":
mask &= s.isin(value)
else:
mask &= s.str.contains(value, regex=False)
out[name] = mask.values.astype(bool)
return out
+1 -3
View File
@@ -148,7 +148,6 @@ class SurvivalSettings:
ks_sub_max_seconds: int
xlim_sub: tuple[float, ...]
ylim_sub: dict
subgroups: tuple[dict, ...]
@property
def file_suffix(self) -> str:
@@ -212,6 +211,5 @@ def load(path: Path = TOML) -> Settings:
categorization=_group(CategorizationSettings, raw["categorization"]),
bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
modeling=_group(ModelingSettings, raw["modeling"]),
survival=_group(SurvivalSettings, {**raw["survival"],
"subgroups": tuple(raw["survival"]["subgroups"])}),
survival=_group(SurvivalSettings, raw["survival"]),
risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
+3 -43
View File
@@ -16,6 +16,7 @@ from matplotlib.figure import Figure
from sklearn.linear_model import LogisticRegression
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import scenarios
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
@@ -322,50 +323,9 @@ def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.
# ---------------------------------------------------------------- subgroups
def _stage(v):
u = str(v).upper().replace("STAGE", "").strip()
if u.startswith("0") or u == "IS":
return 0
for prefix, val in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
if u.startswith(prefix):
return val
return np.nan
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> dict[str, np.ndarray]:
"""Each subgroup's mask over the cohort: every condition of its spec must hold."""
df = sv_frame.df
n = len(df)
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else _find_col(df, ["estadio", "stage"])
col_sub = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else _find_col(df, ["subtipo", "subtype"])
col_surg = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else _find_col(df, ["quirurg", "surg"])
age = df["_edad"].values.astype(float)
stage = (df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index)).values.astype(float)
sub = df[col_sub].astype(str) if col_sub else None
flags = {"her2neg": sub.str.contains("HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
"triple_negative": sub.str.contains("HR-/HER2-", regex=False).values if sub is not None else np.zeros(n, bool),
"her2pos": sub.str.contains("HER2+", regex=False).values if sub is not None else np.zeros(n, bool),
"conservative": (df[col_surg].astype(str).str.lower().str.contains("conserv").values
if col_surg else np.zeros(n, bool))}
masks = {}
for spec in survival.subgroups:
mask = np.ones(n, bool)
if spec.get("her2") == "pos":
mask &= flags["her2pos"]
if spec.get("her2") == "neg":
mask &= flags["her2neg"]
if spec.get("triple_negative"):
mask &= flags["triple_negative"]
if spec.get("conservative"):
mask &= flags["conservative"]
if "age_min" in spec:
mask &= age >= spec["age_min"]
if "age_max" in spec:
mask &= age < spec["age_max"]
if "stages" in spec:
mask &= np.isin(stage, spec["stages"])
masks[spec["name"]] = mask
return masks
"""Each clinical scenario's mask over the cohort (`scenarios.masks`): every condition of the scenario must hold."""
return scenarios.masks(sv_frame.df)
def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None,
+47 -12
View File
@@ -137,22 +137,57 @@ def predict_horizon(c: Cohort, s: SurvivalSettings, idx, h, mode, parents=None):
return lr.predict_proba(c.X_dum[idx])[:, 1], predict_hbn(mod, c.X_int[idx], c.levels), list(mod[0])
class ConstantProbability:
"""What stands in for a logistic regression in an interval where everyone at risk had the same outcome (nobody
died in it, or everybody did): the same probability for every patient, with `predict_proba`'s two columns."""
def __init__(self, p: float):
self.p = float(p)
def predict_proba(self, X):
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
def _fit_lr(X, y, w):
"""The unpenalized LR of an interval, or a constant when there is nothing to tell apart."""
if len(y) == 0:
return ConstantProbability(1.0)
if y.min() == y.max():
return ConstantProbability(float(y[0]))
return LogisticRegression(C=1e6, max_iter=500).fit(X, y, sample_weight=w)
def fit_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None):
"""Per interval, `(LR, HBN)` fitted on the patients of `idx` alive at its start: what a model keeps to score
patients it never saw (`predict_intervals`)."""
m, e = c.months[idx], c.event[idx]
fitted = []
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
sel = np.where(m >= a)[0] # alive at the start of the interval
if len(sel) == 0:
fitted.append((ConstantProbability(1.0), ([], np.array([1.0]))))
continue
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = survives the interval
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censored within the interval: half a risk
lr = _fit_lr(c.X_dum[idx][sel], y, w)
mod = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
fitted.append((lr, mod))
return fitted
def predict_intervals(fitted, X_dum, X_int, levels):
"""Per interval, the probability of surviving it by the LR and by the HBN, for the rows of `X_dum` and `X_int`, and
the HBN's parents of each interval."""
P_lr = [lr.predict_proba(X_dum)[:, 1] for lr, _ in fitted]
P_hb = [predict_hbn(mod, X_int, levels) for _, mod in fitted]
return np.column_stack(P_lr), np.column_stack(P_hb), [list(mod[0]) for _, mod in fitted]
def interval_predictions(c: Cohort, s: SurvivalSettings, idx, parents=None, test=None):
"""Per interval, the probability of surviving it for the `test` patients (default `idx`) by LR and HBN, fitted on the
patients of `idx` alive at its start; and the HBN's parents of each interval."""
test = idx if test is None else test
m, e = c.months[idx], c.event[idx]
P_lr, P_hb, pads = [], [], []
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
sel = np.where(m >= a)[0] # alive at the start of the interval
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = survives the interval
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censored within the interval: half a risk
lr = LogisticRegression(C=1e6, max_iter=500).fit(c.X_dum[idx][sel], y, sample_weight=w)
mod = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
P_lr.append(lr.predict_proba(c.X_dum[test])[:, 1])
P_hb.append(predict_hbn(mod, c.X_int[test], c.levels))
pads.append(list(mod[0]))
return np.column_stack(P_lr), np.column_stack(P_hb), pads
return predict_intervals(fit_intervals(c, s, idx, parents), c.X_dum[test], c.X_int[test], c.levels)
def patient_survival(c: Cohort, s: SurvivalSettings, idx, mode, parents=None):
View File
+119
View File
@@ -0,0 +1,119 @@
"""The SEER development stages over the cohort a run trains on: what the dashboard shows as the model's development.
The members are written as the pipeline's recoded file (`models.cama.seer_survival`, stages 01 to 06): the depuration of
redundant variables, the balanced cohort and its age and tumor categorization, the stepwise logistic regression and the
Bayesian network with their comparison, the bootstrap, the survival curves of the subgroups and the risk factors. Their
tables and figures are the version's `analisis/desarrollo.json`. Stage and treatment are not in the hospital's data yet, so
they enter as `Desconocido` and the record names them; a stage that cannot run publishes its error and the others go on.
"""
import base64
import dataclasses
import tempfile
import traceback
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.survival.estimator import molecular_subtype
UNAVAILABLE = ("Estadio_cat", "Tratamiento_quirurgico_cat", "Radioterapia_cat", "Quimioterapia_cat")
# What the dashboard reads: the file written by a stage, under the name it is published with.
TABLES = {
"or_lr_balanceada.csv": "or_lr_balanceada", "hbn_arcos.csv": "hbn_arcos",
"metricas_diferenciacion.csv": "metricas_diferenciacion", "auc_validacion_interna.csv": "auc_validacion_interna",
"seleccion_bootstrap.csv": "seleccion_bootstrap", "auc_bootstrap.csv": "auc_bootstrap",
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
"escenarios_resumen.csv": "escenarios_resumen", "escenarios_factores_riesgo.csv": "escenarios_factores_riesgo",
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
}
MAX_ROWS = 60
MAX_FIGURE_BYTES = 400_000
def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame:
"""The members as the pipeline's recoded file: its raw SEER columns (year, age level, months, vital status, tumor
size) and the categorical ones, each unknown value `Desconocido`."""
lm = labelled_members
age = lm["age_years"].fillna(lm["age_years"].median()).to_numpy()
lower = (np.floor(age / 5) * 5).astype(int)
frame = pd.DataFrame({
"Year of diagnosis": pd.to_datetime(lm["fecha_indice"]).dt.year.astype(str),
"Age recode with <1 year olds": [f"{v}-{v + 4} years" if v < 85 else "85+ years" for v in lower],
"Survival months": lm["months"].astype(float).astype(str),
"Vital status recode (study cutoff used)": np.where(lm["event"], "Dead", "Alive"),
"Tumor size summary (mm)": lm["size_mm"].map(lambda v: "" if pd.isna(v) else str(int(v))),
})
for column, source in (("Tipo_histologico_cat", "histologic_type"), ("Grado_histologico_cat", "grade"),
("Receptor_estrogeno_cat", "er"), ("Receptor_progesterona_cat", "pr"),
("HER2_IHQ_cat", "her2"), ("Ki67_cat", "ki67_group")):
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy()
frame["Subtipo_molecular_cat"] = molecular_subtype(lm).to_numpy() # the scenarios of stage 5 and 6 read the subtype
for column in UNAVAILABLE:
frame[column] = "Desconocido"
return frame
def _seer_settings(development: dict):
"""The pipeline's own settings with this model's budget (`[config.desarrollo]`) and its Ki-67 column, which the
SEER dictionary does not have."""
from models.cama.seer_survival.settings import load
s = load()
m = s.modeling
modeling = dataclasses.replace(
m, canonical_map={**m.canonical_map, "Ki67_cat": "Ki67"}, categorical_order=(*m.categorical_order, "Ki67"),
tier_tumor=(*m.tier_tumor, "Ki67"), n_bootstrap_run=development["n_bootstrap"],
bootstrap_max_seconds=development["bootstrap_max_seconds"], bootstrap_restarts=development["bootstrap_restarts"],
n_splits_prop=development["n_splits_proposals"], proposals_max_seconds=development["proposals_max_seconds"],
n_restarts=development["restarts"])
return dataclasses.replace(
s, modeling=modeling, depuration=dataclasses.replace(s.depuration, null_perm=development["null_perm"]),
balancing=dataclasses.replace(s.balancing, exclude_censored_years=False))
def _records(path: Path) -> dict:
"""The table as `{"columnas": [...], "filas": [...]}`: the columns in the file's order, which JSON objects do not keep."""
table = pd.read_csv(path)
if table.columns[0].startswith("Unnamed"):
table = table.rename(columns={table.columns[0]: "indice"})
table = table.head(MAX_ROWS).replace([np.inf, -np.inf], np.nan).astype(object)
return {"columnas": [str(c) for c in table.columns], "filas": table.where(table.notna(), None).to_dict("records")}
def development(labelled_members: pd.DataFrame, desarrollo: dict) -> dict:
"""`{"desarrollo": record}`, or `{}` when `[config.desarrollo]` has `enabled = false`."""
if not desarrollo.get("enabled", True):
return {}
from models.cama.seer_survival import pipeline # the `seer-survival` extra: scoring a member does not need it
errors, log = {}, []
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp)
_recoded_frame(labelled_members).to_csv(out / pipeline.RECODED, index=False)
(out / pipeline.COLUMN_MAP).write_text("{}", encoding="utf-8")
settings = _seer_settings(desarrollo)
for stage in pipeline.STAGES:
try:
log += pipeline.run_pipeline(out, only=[stage.id], everything=True, settings=settings)
except Exception as error:
errors[stage.id] = f"{type(error).__name__}: {error}"
log.append((stage.id, "error", 0))
traceback.print_exc()
tables = {name: _records(out / file) for file, name in TABLES.items() if (out / file).exists()}
figures = {}
for path in sorted(out.rglob("*.png")):
raw = path.read_bytes()
if len(raw) <= MAX_FIGURE_BYTES:
figures[path.stem] = base64.b64encode(raw).decode("ascii")
return {"desarrollo": {
"version": 1, "n": int(len(labelled_members)), "etapas": [{"etapa": s, "estado": e, "segundos": t} for s, e, t in log],
"errores": errors, "variables_no_disponibles": list(UNAVAILABLE), "tablas": tables, "figuras": figures}}
def population(population_curves: dict, development: dict) -> dict:
"""Everything the version publishes about its cohort, by file name under `analisis/`: the curves and the development."""
return {**population_curves, **development}
+203
View File
@@ -0,0 +1,203 @@
"""What the CaMa survival model is made of: the member table a build's events give, and the interval survival estimator.
`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index
and rules leave get their covariates at the index (age group, the biopsy report's histological type, Nottingham grade,
ER, PR, HER2 and Ki-67 band, read from the report's results within `result_days` of the index) and the index date; the
rest keep their row, empty. `IntervalSurvival` fits, per interval of `survival.horizons`, a logistic regression and a
Bayesian network with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`),
stacks them with out-of-sample weights and scores a patient's survival to each horizon as the product of the intervals'.
The registered model is `Pipeline([MemberFeatures, IntervalSurvival])`, so it takes a build's long frame.
Everything the registered model needs when it scores is in this package, which the registry pickles by value.
"""
import json
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.io.contracts import DAYS_PER_YEAR
from models.steps import indexing
UNKNOWN = "NA"
DAYS_PER_MONTH = 30.4375
INDEX_COLUMN = "fecha_indice_modelo"
NUMERIC = ["age_years", "size_mm", "ki67_pct"] # the covariates before banding: the SEER development stages band them themselves
FEATURES = ["age_group", "histologic_type", "grade", "er", "pr", "her2", "ki67_group", "size_group"]
RESULTS = {"tipo_histologico": "histologic_type", "grado_nottingham": "grade", "receptor_estrogeno": "er",
"receptor_progesterona": "pr", "her2": "her2"}
WINDOW_KEYS = ("recruitment_start", "recruitment_end")
DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above
EPOCH = pd.Timestamp("1970-01-01")
def molecular_subtype(labelled: pd.DataFrame) -> pd.Series:
"""The SEER subtype string (`HR+/HER2-`...) from the receptors: hormone-positive when either is, HER2-positive at 3+ and
negative at 0 and 1+; an equivocal (2+) or missing HER2 leaves the subtype unknown, so it is in no HER2 scenario."""
hr_positive = (labelled["er"] == "POSITIVO") | (labelled["pr"] == "POSITIVO")
hr_known = labelled["er"].isin(["POSITIVO", "NEGATIVO"]) | labelled["pr"].isin(["POSITIVO", "NEGATIVO"])
her2 = labelled["her2"].map({"H3": "+", "H0": "-", "H1": "-"})
subtype = np.where(hr_known & her2.notna(), np.where(hr_positive, "HR+", "HR-") + "/HER2" + her2.fillna(""), "Desconocido")
return pd.Series(subtype, index=labelled.index)
def survival_settings(table: dict) -> SurvivalSettings:
"""`SurvivalSettings` from a `[config.survival]` table: lists become tuples, an unknown key is an error."""
return SurvivalSettings(**{key: tuple(value) if isinstance(value, list) else value for key, value in table.items()})
def _band(values: pd.Series, cuts: list) -> pd.Series:
"""The values in the bands the cuts make: `<c1`, `c1-(c2-1)`, ..., `≥cn`; empty where the value is."""
edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in zip(cuts[:-1], cuts[1:])], f"≥{cuts[-1]}"]
return pd.cut(values, edges, right=False, labels=labels).astype(object)
def _dated(cohort: pd.DataFrame) -> pd.DataFrame:
return cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
def member_table(cohort: pd.DataFrame, age_cuts: list, ki67_cuts: list, result_days: int,
size_cuts: list | None = None) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice` and the covariates in `FEATURES`,
empty where the build has no such result near the index."""
frame = _dated(cohort)
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
members["age_group"] = _band(members["age_years"], age_cuts)
near = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, result_days)]
near = near.sort_values(["fecha", "fuente_id"])
for tipo, name in RESULTS.items():
members[name] = near[near["tipo"] == tipo].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
ki67 = near[near["tipo"] == "ki67_pct"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
members["ki67_group"] = _band(ki67, ki67_cuts)
size = near[near["tipo"] == "tamano_tumor_mm"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
members["size_group"] = _band(size, size_cuts or DEFAULT_SIZE_CUTS)
members["size_mm"], members["ki67_pct"] = size, ki67
return members[["fecha_indice", *FEATURES, *NUMERIC]]
def outcome_table(cohort: pd.DataFrame, cutoff, cap_months: int) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: whole months from the index to her death or, if she
has none by the cut-off, to the cut-off (`months`), and whether she died (`event`). Follow-up is cut at
`cap_months`: a later death counts as alive."""
frame = _dated(cohort)
index = frame.groupby("pac_id")["fecha_indice"].first()
death = frame[frame["tipo"] == "defuncion"].groupby("pac_id")["fecha"].min().reindex(index.index)
cutoff = pd.Timestamp(cutoff)
died = (death.notna() & (death <= cutoff)).to_numpy()
end = death.where(died, cutoff)
months = np.floor((end - index).dt.days.to_numpy() / DAYS_PER_MONTH).astype(int).clip(min=0)
if cap_months:
died = died & (months < cap_months)
months = np.minimum(months, cap_months)
return pd.DataFrame({"months": months, "event": died}, index=index.index)
def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None):
"""The covariates as the interval models take them: `(X_dum, X_int, categories, dummy_columns)`. With no `categories`
they are learned from `frame` (the first appearance of each value, the first alphabetical level of each covariate
as the dummies' reference); with them, `frame` is coded as the fitted model coded its training rows, and a value it
never saw takes the unknown category."""
frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str)
if categories is None:
dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns)
categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES}
columns = []
for name in FEATURES:
codes = pd.Categorical(frame[name], categories=categories[name]).codes
fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0
columns.append(np.where(codes < 0, fallback, codes))
X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32)
return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns
def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings: SurvivalSettings):
"""The pipeline's `Cohort` of these members, with the categories and dummy columns it was coded by."""
X_dum, X_int, categories, dummy_columns = encode(features)
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
return cohort, categories, dummy_columns
class MemberFeatures(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
def __init__(self, index=None, window=None, age_cuts=(45, 60, 75), ki67_cuts=(14, 20), result_days=30,
size_cuts=DEFAULT_SIZE_CUTS):
self.index = index
self.window = window
self.age_cuts = age_cuts
self.ki67_cuts = ki67_cuts
self.result_days = result_days
self.size_cuts = size_cuts
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
table = member_table(indexed, list(self.age_cuts), list(self.ki67_cuts), self.result_days, list(self.size_cuts)) \
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
return table[[*FEATURES, INDEX_COLUMN]]
class IntervalSurvival(BaseEstimator):
"""The stage-5 interval survival of the SEER pipeline as an estimator: per interval, LR and HBN stacked; the survival
to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with `months` and
`event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With
`INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member
without one) and her mortality is empty too."""
def __init__(self, survival=None, horizons_years=(0.5, 1.0, 1.5)):
self.survival = survival
self.horizons_years = horizons_years
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
s = survival_settings(self.survival)
if [h / 12 for h in s.horizons] != list(self.horizons_years):
raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ")
cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s)
everyone = np.arange(len(X))
if s.combine_active and len(X) >= 2 * s.stack_folds:
weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X)))
self.weights_ = weights["w_LR"].to_numpy()
self.stacking_ = weights.to_dict("records")
else:
self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), []
self.fitted_ = sm.fit_intervals(cohort, s, everyone, None)
self.levels_ = cohort.levels
return self
def interval_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's probability of surviving each interval, given she is alive at its start."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb
def survival_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's survival to each horizon."""
return np.cumprod(self.interval_proba(X), axis=1)
def component_survival(self, X: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each member's survival to each horizon by the logistic regression, by the Bayesian network and by their
stacked combination (`survival_proba`)."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return {"LR": np.cumprod(P_lr, axis=1), "HBN": np.cumprod(P_hb, axis=1), "COMB": self.survival_proba(X)}
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
mortality = 1.0 - self.survival_proba(X)
if INDEX_COLUMN not in X.columns:
return mortality
dates = pd.to_datetime(X[INDEX_COLUMN])
member = dates.notna().to_numpy()
mortality[~member] = np.nan
return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality])
+116
View File
@@ -0,0 +1,116 @@
"""The survival figure of a clinical scenario, scored with the model in production over the data ingested so far.
Training and tuning happen in governance; here the production version is only applied. The scenarios are the subgroups of
the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one
share a figure, and a patient sees the figure of each scenario she belongs to. The record is the one the training run
publishes for the whole cohort (`population`), for the scenario's members: the Kaplan-Meier curve of what happened to them
with its Greenwood band, the survival the model predicts for them (their mean at each horizon by the logistic regression, the
Bayesian network and their combination, with a 95 % interval from resampling the members), and the Weibull fits the SEER
pipeline makes to that prediction. Nothing is fitted on the scenario and nothing is stored.
"""
from types import SimpleNamespace
import numpy as np
import pandas as pd
from models.cama.seer_survival import scenarios
from models.cama.seer_survival import survival_curves as luis
from models.cama.survival import population
from models.cama.survival.estimator import FEATURES, IntervalSurvival, molecular_subtype, survival_settings
from models.dags.training import Scenario, dataflow
MIN_MEMBERS = 30
MIN_EVENTS = 5
REPLICAS = 200
SEED = 42
WHOLE = "Toda la cohorte"
class QueryError(ValueError):
"""The scenario cannot be answered; the message says why, in the reader's language."""
def rehydrate(model) -> IntervalSurvival:
"""The fitted model as the current `IntervalSurvival` code runs it. A version's saved model carries its class as it was
when it was trained; its fitted state (`fitted_`, `weights_`, the codings) is what makes it that version, so that state
is put in the current class and its methods are the code's."""
current = IntervalSurvival.__new__(IntervalSurvival)
current.__dict__.update(model.__dict__)
return current
def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates and follow-up (the scenario's `labelled_members`)."""
dr = dataflow(*scenario.modules, config=scenario.config)
return dr.execute(["labelled_members"], inputs={"source_cohort": frame, "cohort_lineage": lineage})["labelled_members"]
def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each scenario's mask over the members. The age and the subtype are the hospital's; stage and surgery are not reported
yet, so a scenario that needs them has no member."""
raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy()}, index=labelled.index)
return scenarios.masks(raw)
def answerable(labelled: pd.DataFrame, mask: np.ndarray) -> bool:
return int(mask.sum()) >= MIN_MEMBERS and int(labelled["event"].to_numpy()[mask].sum()) >= MIN_EVENTS
def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]:
"""The scenarios `pac_id` belongs to and that have enough members to draw; the whole cohort when she is in none."""
row = np.flatnonzero(labelled["pac_id"].to_numpy() == pac_id)
if len(row) == 0:
raise QueryError("La paciente no está en la cohorte del modelo.")
found = [name for name, mask in scenario_masks(labelled).items() if mask[row[0]] and answerable(labelled, mask)]
return found or [WHOLE]
def monthly(survival: np.ndarray, horizons: list[int], months: int) -> np.ndarray:
"""Each member's survival month by month from 0 to `months`: log-linear between the horizons, which is a constant hazard
in each interval, and past the last one with the hazard of the last interval."""
borders = np.array([0, *horizons], float)
log = np.log(np.clip(np.column_stack([np.ones(len(survival)), survival]), 1e-12, 1.0))
grid = np.arange(months + 1, dtype=float)
out = np.empty((len(survival), len(grid)))
slope = (log[:, -1] - log[:, -2]) / (borders[-1] - borders[-2])
for i in range(len(survival)):
out[i] = np.where(grid > borders[-1], log[i, -1] + slope[i] * (grid - borders[-1]), np.interp(grid, borders, log[i]))
return np.minimum.accumulate(np.exp(out), axis=1)
def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None) -> dict:
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone) scored with `model` (the fitted
`IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything."""
if name in (None, WHOLE):
mask = np.ones(len(labelled), bool)
else:
masks = scenario_masks(labelled)
if name not in masks:
raise QueryError(f"No hay un escenario clínico «{name}».")
mask = masks[name]
if not answerable(labelled, mask):
raise QueryError(f"El escenario tiene {int(mask.sum())} pacientes y {int(labelled['event'].to_numpy()[mask].sum())} defunciones; "
f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.")
selected = labelled[mask].reset_index(drop=True)
s = survival_settings(scenario.config["survival"])
horizons, cap = list(s.horizons), max(s.cap_months, max(s.horizons))
predicted = model.component_survival(selected[FEATURES])
resample = np.random.default_rng(SEED).integers(0, len(selected), (REPLICAS, len(selected)))
points = {}
for series in population.SERIES:
low, high = np.percentile(predicted[series][resample].mean(axis=1), [2.5, 97.5], axis=0)
points[series] = {"S": predicted[series].mean(axis=0).tolist(), "low": low.tolist(), "high": high.tolist()}
followed, died = selected["months"].to_numpy(int), selected["event"].to_numpy(bool)
S, low, high = luis.fw.km_curva(np.minimum(followed, cap), died & (followed < cap), cap)
adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0)
classic, fractional = luis._fit_to_curve(adjusted, len(selected), s, s.ks_max_seconds)
grid = np.arange(0, cap + population.GRID_STEP, population.GRID_STEP)
return {"version": population.RECORD_VERSION, "escenario": name or WHOLE, "n": int(len(selected)),
"events": int((died & (followed < cap)).sum()), "median_follow_up_months": float(np.median(followed)),
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": REPLICAS,
"km": {"months": list(range(cap + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
"km_adjusted": {"months": list(range(len(adjusted))), "S": adjusted.tolist()},
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
"points": points, "etiquetas": scenario.config.get("etiquetas", {})}
+221
View File
@@ -0,0 +1,221 @@
"""CaMa survival prototype: the mortality of a woman with an invasive carcinoma at 6, 12 and 18 months from the first
invasive biopsy report.
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
`[config.index]`): the index is the first biopsy report graded invasive. Each member's covariates are the results of
that report (histological type, Nottingham grade, ER, PR, HER2, Ki-67, lesion size) and her age at the index; her outcome is the
months from the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts
the follow-up). The fit is the SEER pipeline's interval survival (`models.cama.seer_survival.survival_models`): per
interval a logistic regression and a Bayesian network, stacked. A member without a result has it as a category of its
own, as the pipeline does with its unknowns.
The split, the metrics and the routines (ML-01a) are here; the temporal split is `models.steps.model_fitting`'s.
`fitted_model` puts `MemberFeatures` in front of the fitted estimator, 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`).
"""
import json
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival import estimator
from models.cama.survival.estimator import FEATURES, IntervalSurvival, MemberFeatures
from models.steps import model_fitting
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"months": pandera.Column(int, pandera.Check.ge(0)),
"event": pandera.Column(bool),
**{name: pandera.Column(nullable=True) for name in FEATURES}},
name="labelled members")
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file, and a member without a death is followed to it."""
return date.fromisoformat(cohort_lineage["datos_as_of"])
def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSettings:
"""The pipeline's survival settings; its horizons, in months, must be `horizons_years`."""
settings = estimator.survival_settings(survival)
if [h / 12 for h in settings.horizons] != list(horizons_years):
raise ValueError(f"survival.horizons {list(settings.horizons)} and horizons_years {horizons_years} differ")
return settings
def member_features(cohort: pd.DataFrame, age_cuts: list[int], ki67_cuts: list[int], result_days: int,
size_cuts: list[int]) -> pd.DataFrame:
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates."""
return estimator.member_table(cohort, age_cuts, ki67_cuts, result_days, size_cuts)
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""One row per member, by `pac_id`: months of follow-up and whether she died in them."""
return estimator.outcome_table(cohort, cohort_cutoff, survival_settings.cap_months)
@checked_frame(LABELLED_MEMBERS)
def labelled_members(member_features: pd.DataFrame, member_outcomes: pd.DataFrame) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates, her follow-up and whether she died."""
return member_features.join(member_outcomes).reset_index()
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event")
def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival:
"""The interval survival fitted on the training members."""
return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]])
def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray:
"""The test members' probability of surviving each interval, given they are alive at its start."""
return fitted_survival.interval_proba(test_set[FEATURES])
def _interval_outcomes(frame: pd.DataFrame, borders: list[int], probabilities: np.ndarray) -> pd.DataFrame:
"""One row per member and interval she was at risk in: the model's probability of surviving it, whether she did
(`survived`) and its weight (a censoring inside the interval counts half, as in the fit)."""
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
rows = []
for j, (a, b) in enumerate(zip(borders[:-1], borders[1:])):
at_risk = months >= a
died = event & (months < b)
rows.append(pd.DataFrame({"interval": f"{a}-{b}", "p": probabilities[at_risk, j],
"survived": (~died[at_risk]).astype(float),
"weight": np.where((~event & (months < b))[at_risk], 0.5, 1.0)}))
return pd.concat(rows, ignore_index=True)
def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray:
"""The training members' mortality at each horizon (apparent performance: they are what the model was fitted on)."""
return fitted_survival.predict_proba(train_set[FEATURES])
def _known_status_auc(frame: pd.DataFrame, mortality: np.ndarray, horizon_months: int, column: int) -> dict:
"""The AUC of the mortality at one horizon among the members whose status there is known (died before it, or
followed to it), and how many they are; empty without both outcomes in at least 20 members."""
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
died = event & (months < horizon_months)
known = died | (months >= horizon_months)
if known.sum() < 20 or len(np.unique(died[known])) < 2:
return {}
return {"auc": float(roc_auc_score(died[known], mortality[known, column])), "n": int(known.sum())}
def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray,
train_mortality: np.ndarray, survival_settings: SurvivalSettings, fitted_survival: IntervalSurvival) -> dict:
"""Aggregates only: the members and deaths in each part and, over the member-intervals of the test members (every
month they were followed, not only the members whose status at a horizon is known), their number, the observed and
expected survival, the weighted Brier score and, with both outcomes, the AUC. A temporal split leaves the newest
members little follow-up, so a metric at one horizon would be of the few that died. The `auc_train_*` are the
apparent discrimination at each horizon, on the members the model was fitted on: they say the covariates were
used, not how it will do on new patients."""
found = {"n_train": len(train_set), "n_test": len(test_set), "events_train": int(train_set["event"].sum()),
"events_test": int(test_set["event"].sum())}
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
found["n_member_intervals_test"] = len(pairs)
if len(pairs):
w, y, p = pairs["weight"].to_numpy(), pairs["survived"].to_numpy(), pairs["p"].to_numpy()
found.update(observed_survival=float(np.average(y, weights=w)), expected_survival=float(np.average(p, weights=w)),
brier_interval=float(np.average((p - y) ** 2, weights=w)))
if len(np.unique(y)) == 2:
found["auc_interval"] = float(roc_auc_score(y, p, sample_weight=w))
for column, months in enumerate(survival_settings.horizons):
apparent = _known_status_auc(train_set, train_mortality, months, column)
if apparent:
found[f"auc_train_{months}m"], found[f"n_known_train_{months}m"] = apparent["auc"], apparent["n"]
for row, months in zip(fitted_survival.stacking_, survival_settings.horizons):
found[f"stack_w_lr_{months}m"] = float(row["w_LR"])
return found
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(index_attrition: list, prior_observation: dict, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""MUESTREO: who could be used (the scenario's index and rules, step by step, and their prior history), and how
they were split."""
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"train_fraction": train_fraction, "train": _dates(train_set), "test": _dates(test_set)}
def missing_data(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many members lacked each covariate, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int(frame[name].isna().sum()) for name in FEATURES}
return {"method": "un resultado ausente es una categoría más (NA); no se imputa ni se descarta al miembro",
"train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_survival: IntervalSurvival, survival_settings: SurvivalSettings) -> dict:
"""METODO_ANALITICO: the intervals, how the two models are stacked and which covariates the network kept."""
s = survival_settings
return {"method": "supervivencia por intervalos: regresión logística y red bayesiana (CPT tabular) por intervalo, "
"combinadas con pesos fuera de muestra; la supervivencia es el producto de los intervalos",
"intervals_months": [0, *s.horizons], "censoring": s.censoring, "cap_months": s.cap_months,
"hbn_ess": s.hbn_ess, "hbn_max_parents": s.hbn_max_parents, "covariates": FEATURES,
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
for row in fitted_survival.stacking_],
"hbn_parents": [[FEATURES[j] for j in model[0]] for _, model in fitted_survival.fitted_]}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""BALANCE_CLASES: deaths and members followed without one in each part; the classes are used as observed."""
def counts(frame: pd.DataFrame) -> dict:
return {"muertes": int(frame["event"].sum()), "sin muerte": int((~frame["event"]).sum())}
return {"method": "ninguno: no se remuestrea ni se pondera por clase; una censura dentro de un intervalo pesa medio "
"riesgo", "train": counts(train_set), "test": counts(test_set)}
def output_confidence(test_set: pd.DataFrame, test_interval_survival: np.ndarray, survival_settings: SurvivalSettings,
calibration_bins: int = 5) -> dict:
"""CONFIANZA_SALIDA: over the test members' member-intervals, the predicted survival of the interval against the
observed one, by quantiles."""
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
if len(pairs) == 0 or pairs["p"].nunique() < 2:
return {"method": "calibración en la prueba: sin dispersión suficiente para formar cuantiles", "n": len(pairs)}
bins = pd.qcut(pairs["p"], q=min(calibration_bins, pairs["p"].nunique()), duplicates="drop")
table = pairs.assign(py=pairs["p"] * pairs["weight"], sy=pairs["survived"] * pairs["weight"]).groupby(
bins, observed=True).agg(n=("p", "size"), w=("weight", "sum"), py=("py", "sum"), sy=("sy", "sum"))
return {"method": "calibración en la prueba por intervalo: supervivencia media prevista contra observada, por "
"cuantiles de los miembro-intervalos",
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.py / row.w),
"observed_rate": float(row.sy / row.w)} for interval, row in table.iterrows()]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
ki67_cuts: list[int], result_days: int, size_cuts: list[int]) -> Pipeline:
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), tuple(ki67_cuts), result_days, tuple(size_cuts))),
("survival", fitted_survival)])
+92
View File
@@ -0,0 +1,92 @@
domain = "cama"
scenario = "survival"
cohort = "cama/cohorte_total"
outcome = "muerte"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cama.survival.model", "models.cama.survival.population", "models.cama.survival.development", "models.steps.indexing"]
description = """
Prototipo: mortalidad por cualquier causa a los 6, 12 y 18 meses del primer reporte de biopsia con carcinoma invasor, \
a partir de la edad y de los resultados de ese reporte (tipo histológico, grado de Nottingham, receptores de estrógeno \
y de progesterona, HER2, Ki-67 y tamaño de la lesión). Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana \
combinadas). Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la registra."""
[config]
train_fraction = 0.7
# The model's horizons, in years; `survival.horizons` are the same in months.
horizons_years = [0.5, 1.0, 1.5]
# Covariate bands: the age at the index, in years, the Ki-67 percentage and the lesion size in millimetres (T1, T2, T3).
age_cuts = [45, 60, 75]
ki67_cuts = [14, 20]
size_cuts = [20, 50]
# A report's results count for the index when they are dated up to this many days after it (and a week before).
result_days = 30
# The scenario's index and rules, over its source cohort (models/steps/indexing.py). The recruitment window is the
# source cohort's.
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA_INVASOR"]
# PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone.
observacion_previa_minima_dias = 0
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with its settings.
[config.desarrollo]
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort,
# with the pipeline's own budgets (`models/cama/seer_survival/model.toml`). The bootstrap and the proposals stop at their
# time caps and use what they have. One adaptation: `exclude_censored_years` is off, because this follow-up is short and
# would leave every year out of the outcome.
enabled = true
null_perm = 100
n_bootstrap = 60
bootstrap_max_seconds = 2700
bootstrap_restarts = 3
n_splits_proposals = 5
proposals_max_seconds = 3600
restarts = 10
[config.survival]
age_mode = "categorizada"
include_age = true
age_cuts = [45, 60, 75]
hbn_fixed_parents = ["histologic_type", "age_group"] # the SEER pipeline's expert parents that this data has (its stage and treatment are not reported yet); empty = learn them by the BDeu score
hbn_age_parent = false # the grouped age is already in `hbn_fixed_parents`
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
covariates = []
horizons = [6, 12, 18] # months
censoring = "riesgo" # a model per interval using all the follow-up
combine = true # one LR + HBN indicator, per-interval stacking weights
show_individual = false
stack_folds = 5
stack_shrink = 20
n_boot = 100
n_boot_sub = 100
seed = 42
hbn_ess = 1000
hbn_max_parents = 5
k_ident = "clasico"
curves = "ajustada"
adjust_step = 3
show_raw_km = true
ylim_main = []
inset_zoom = false
inset_months = 18
cap_months = 24 # follow-up is cut here: a later death counts as alive
min_events_sub = 5
ks_max_seconds = 120
ks_sub_max_seconds = 180
xlim_sub = []
ylim_sub = {}
# What the dashboard's survival chart says, in the clinicians' words (provisional: to be defined with them). The record a
# training run publishes carries these, so changing one is a setting and a new run.
[config.etiquetas]
# The wording of the survival figure, as the SEER pipeline's own chart has it; to be defined with the clinicians.
titulo = "Supervivencia después del primer reporte de biopsia con carcinoma invasor"
eje_x = "Meses desde el diagnóstico"
eje_y = "Supervivencia S(t)"
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
weibull = "Weibull"
weibull_fraccional = "Weibull fraccional"
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
+115
View File
@@ -0,0 +1,115 @@
"""The population results of a training run, what the dashboard draws: the survival of the whole cohort and the model's
survival at each horizon.
Over every member of the indexed cohort (not only the training part), with the SEER pipeline's stage-5 routines
(`models.cama.seer_survival`): the Kaplan-Meier curve with its Greenwood interval, the covariate-adjusted curve (the
mean of the members' interval survival), the classic and the fractional (Kilbas-Saigo) Weibull fitted to it, and the
mean survival at each horizon by the logistic regression, the Bayesian network and their stacked combination, each with
a 95 % bootstrap interval. The record is the version's `analisis/curvas.json` (`models.io.tracking.TrainingRun.log_analysis`),
which the WebApi serves from the production version. The labels the chart carries come from `[config.etiquetas]`, so
the clinicians' wording is a setting, not code.
"""
import numpy as np
import pandas as pd
from models.cama.seer_survival import survival_curves as luis
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival.estimator import FEATURES, UNKNOWN
SERIES = ("LR", "HBN", "COMB")
GRID_STEP = 0.25 # months between the points of a fitted curve
RECORD_VERSION = 1
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts as
alive) and the covariates as categories."""
s, lm = survival_settings, labelled_members
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
for name in FEATURES:
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
return luis.SurvivalFrame(df, list(FEATURES), None, [])
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
"""The members coded as the stage-5 models take them (`survival_curves.sv_cohort`)."""
return luis.sv_cohort(survival_frame, survival_settings)
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
"""Kaplan-Meier with the Greenwood interval (`survival_curves.sv_km`)."""
return luis.sv_km(survival_frame, survival_settings)
def km_curve(km_raw: luis.KaplanMeier) -> dict:
"""Kaplan-Meier from the index to `months_max`, with its interval, as the record carries it."""
return {"months": list(range(km_raw.T + 1)), "S": km_raw.S.tolist(), "low": km_raw.lo.tolist(), "high": km_raw.hi.tolist()}
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
"""The covariate-adjusted survival curve, month by month (`survival_curves.sv_adjusted`)."""
return luis.sv_adjusted(curve_cohort, km_raw, survival_settings)
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""The stacking of LR and HBN over the whole cohort: per interval, the weight of the LR (`sv_weights_cohort`)."""
return luis.sv_weights_cohort(curve_cohort, luis.sv_oof(curve_cohort, survival_settings), survival_settings)
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
"""The mean survival at each horizon by LR, HBN and the combination, fitted on every member (`sv_points`)."""
return luis.sv_points(curve_cohort, population_weights, survival_settings)
def point_estimates(luis_points: luis.Points) -> dict:
return {"LR": luis_points.lr, "HBN": luis_points.hbn, "COMB": luis_points.combined}
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> np.ndarray:
"""One row per replica: the mean survival at each horizon of LR, HBN and the combination, refitted on a resample, the
HBN's parents kept or learned again as `hbn_parents` says (`sv_bootstrap`)."""
return luis.sv_bootstrap(curve_cohort, population_weights, luis_points, survival_settings)
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
"""The classic and the fractional Weibull fitted to the adjusted curve as if it came from as many members as the
cohort has (`survival_curves._fit_to_curve`), evaluated on a grid of months, with their parameters."""
classic, fractional = luis._fit_to_curve(adjusted_km, len(survival_frame.df), survival_settings, survival_settings.ks_max_seconds)
grid = np.arange(0, len(adjusted_km) - 1 + GRID_STEP, GRID_STEP)
parameters = lambda fit: {key: float(fit[key]) for key in ("k", "alpha", "beta", "lam", "nll") if key in fit}
return {"t": grid.tolist(), "classic": np.asarray(classic["S"](grid), float).tolist(),
"fractional": np.asarray(fractional["S"](grid), float).tolist(),
"parameters": {"classic": parameters(classic), "fractional": parameters(fractional)}}
def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
point_estimates: dict, bootstrap_points: np.ndarray, population_weights: pd.DataFrame,
survival_settings: SurvivalSettings, etiquetas: dict) -> dict:
"""What a version publishes about its cohort, by file name under `analisis/`: `curvas`, the record the dashboard
draws (the figure's curves, its points and their intervals, and the labels)."""
horizons = list(survival_settings.horizons)
low, high = np.nanpercentile(bootstrap_points, [2.5, 97.5], axis=0)
points = {}
for j, name in enumerate(SERIES):
columns = slice(j * len(horizons), (j + 1) * len(horizons))
points[name] = {"S": [float(v) for v in point_estimates[name]], "low": [float(v) for v in low[columns]],
"high": [float(v) for v in high[columns]]}
months, events = labelled_members["months"], labelled_members["event"]
return {"curvas": {
"version": RECORD_VERSION, "n": int(len(labelled_members)), "events": int(events.sum()),
"median_follow_up_months": float(months.median()), "horizons_months": horizons,
"months_max": km_curve["months"][-1], "bootstrap_replicas": int(survival_settings.n_boot),
"km": km_curve, "km_adjusted": {"months": list(range(len(adjusted_km))), "S": adjusted_km.tolist()},
"weibull": {"t": weibull_fits["t"], "S": weibull_fits["classic"]},
"weibull_fractional": {"t": weibull_fits["t"], "S": weibull_fits["fractional"]},
"weibull_parameters": weibull_fits["parameters"], "points": points,
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
for row in population_weights.to_dict("records")],
"etiquetas": etiquetas}}
+4 -5
View File
@@ -1,7 +1,6 @@
"""Cohorts for the risk models: each one a TOML definition (FHIR `Group` and `EvidenceVariable`s) and the rule that
builds its frame from the patients' timeline (dbt's view, through Persistance).
"""Cohorts for the risk models. dbt is their only definition (`Transformation/models/<project>/cohorts/`: population,
index date and exclusions as queries in the manifest); this package stores a build of them for the WebApi cycle.
definition.py a cohort's definition, read from its TOML
build.py from the timeline to `cohorte_armado` and its rows; the stored frame, wide
<project>/<name>.py a cohort's rule (`expression` in its TOML); `<project>/proposals/`: not built yet
build.py from dbt's queries to `cohorte_armado` and its rows; the stored frame, wide
cama/ CaMa's screening cohort, a PROPOSAL in the old Python-frame format, not built
"""
+57 -88
View File
@@ -1,111 +1,79 @@
"""Armar una cohorte: de la línea de tiempo a `cohorte_armado`, sus miembros, su atrición y sus variables.
"""Armar una cohorte: de las reglas de dbt a `cohorte_armado`, sus miembros y su atrición.
El armado lee solo la línea de tiempo: la vista de dbt `<proyecto>_linea_de_tiempo`, por la consulta que le dan
(`TimelineRepository.query`), recortada al corte y,
si se pide, a lo que ya estaba cargado (`conocida_hasta`, por el inicio de la carga: sin
versiones de fila es aproximado, ADR-MD-009). La regla de
la cohorte es la función que nombra su definición (`expression`).
dbt es la única definición de una cohorte (`Transformation/models/<proyecto>/cohorts/`): su población, su fecha
índice y sus exclusiones son consultas del manifest (`models.io.storage.read_queries`), y el armado las corre en la
sesión que le dan, con la misma cadena que la exportación (`models.pipelines.cohort_build.build_cohort`). Las
reglas que no caben en SQL son del modelo, sobre `cacu/cohorte_total` y la línea de tiempo, no de una cohorte.
Rearmar con la misma definición, los mismos parámetros y los mismos datos no
guarda otro armado: la huella del pedido y la del marco (`marco_sha`) ya están.
Si los datos cambiaron, el `marco_sha` cambia y se guarda un armado nuevo.
`linaje` da las etiquetas `kit.*` que lleva la corrida de MLflow que entrena o
valida con este armado: llaves y huellas, nunca filas ni `pac_id`.
Rearmar con las mismas consultas, los mismos parámetros y los mismos datos no guarda otro armado: la huella del
pedido y la del marco (`marco_sha`) ya están. Si los datos cambiaron, el `marco_sha` cambia y se guarda uno nuevo.
"""
import inspect
import hashlib
import json
from datetime import date, datetime, timezone
from importlib import import_module
from contextlib import nullcontext
from datetime import datetime, timezone
from core.indicadores.cohortes import TablasCohorte
from persistance.edges.dbt import DbtQueryRepository
from sqlmodel import Session, select
from models.cohorts.definition import Definition, json_sha
DECIMALS = 9 # redondeo de los tiempos en la huella del marco
from models.io.contracts import CohortQueries
from models.pipelines.cohort_build import build_cohort
def timeline_rows(sesion: Session, linea, *, pacientes=None, hasta=None, conocida_hasta=None) -> list[dict]:
"""The timeline as rows, run on `sesion`. `linea` builds its `select` (`TimelineRepository.query`)."""
consulta = linea(patients=pacientes, until=hasta, known_until=conocida_hasta)
return [dict(fila._mapping) for fila in sesion.execute(consulta)]
def json_sha(objeto) -> str:
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
def frame_of(
sesion: Session,
definicion: Definition,
inicio: date,
fin: date,
corte: date,
*,
linea,
pacientes: list[int] | None = None,
conocida_hasta: datetime | None = None,
):
"""El marco sin guardarlo: (miembros, atrición). Con `pacientes`, solo los de la lista (evaluar a una paciente)."""
filas = timeline_rows(sesion, linea, pacientes=pacientes, hasta=corte, conocida_hasta=conocida_hasta)
return definicion.function()(filas, definicion.reglas, inicio, fin, corte)
def queries_sha(queries: CohortQueries) -> str:
"""Huella de las reglas: el SQL compilado de cada paso, en su orden. Hace el papel de la definición."""
return json_sha({"all_patients": queries.all_patients, "index_date": queries.index_date,
"rules": [[rule.order, rule.name, rule.sql] for rule in queries.rules],
"variables": queries.variables})
def frame_sha(miembros, definicion: Definition) -> str:
def frame_sha(miembros, variables=()) -> str:
"""Huella del contenido del marco: cada miembro con su fecha índice y sus variables, en orden."""
nombres = [v.nombre for v in definicion.variables]
def redondo(valor):
return round(valor, DECIMALS) if isinstance(valor, float) else valor
return json_sha([[m.pac_id, m.fecha_indice.isoformat(), *(redondo(m.variables.get(n)) for n in nombres)]
for m in sorted(miembros, key=lambda m: m.pac_id)])
return json_sha({"miembros": sorted([int(m["pac_id"]), m["fecha_indice"].isoformat()] for m in miembros),
"variables": sorted([v.pac_id, v.variable, v.valor_codigo, v.valor_numerico] for v in variables)})
def code_sha(definicion: Definition) -> str:
"""Huella del código que arma el marco (el módulo de su `expression`): hace el papel del SQL."""
modulo = import_module(f"models.cohorts.{definicion.expression.split(':')[0]}")
return json_sha(inspect.getsource(modulo))
def build_of(
sesion: Session,
definicion: Definition,
inicio: date,
fin: date,
corte: date,
*,
cohortes: TablasCohorte,
linea,
conocida_hasta: datetime | None = None,
ahora: datetime | None = None,
):
"""El armado sin guardarlo: la fila de `cohorte_armado` y sus exclusiones, miembros y variables (sin `armado_id`).
def build_of(sesion: Session, queries: CohortQueries, *, cohortes: TablasCohorte, ahora: datetime | None = None):
"""El armado sin guardarlo: la fila de `cohorte_armado`, sus exclusiones, sus miembros y sus variables (sin
`armado_id`). Las variables son las de la consulta `variables` de la cohorte, si tiene, solo de sus miembros; las
que no caben en SQL las calcula el modelo de la línea de tiempo.
Es lo que recibe `persistance.edges.gold.CohorteRepository.armar` como función de la sesión.
"""
miembros, atricion = frame_of(sesion, definicion, inicio, fin, corte, linea=linea,
conocida_hasta=conocida_hasta)
parametros = {"reclutamiento_inicio": inicio.isoformat(), "reclutamiento_fin": fin.isoformat(),
"corte": corte.isoformat(), "conocida_hasta": conocida_hasta and conocida_hasta.isoformat()}
huella = json_sha({"definicion": definicion.definicion_sha, "reglas": definicion.reglas_sha,
"codigo": code_sha(definicion), "parametros": parametros})
consultas = DbtQueryRepository(lambda: nullcontext(sesion))
built = build_cohort(queries, consultas)
miembros = built.study_population.to_dict("records")
parametros = {**queries.parameters, "corte": queries.cutoff.isoformat()}
reglas_sha = json_sha(queries.parameters)
definicion_sha = queries_sha(queries)
armado = cohortes.CohorteArmado(
url=definicion.url, version=definicion.version, definicion_sha=definicion.definicion_sha,
reglas_sha=definicion.reglas_sha, parametros=json.dumps(parametros, sort_keys=True), datos_as_of=corte,
huella=huella, marco_sha=frame_sha(miembros, definicion), n_miembros=len(miembros),
armado_en=ahora or datetime.now(timezone.utc),
url=queries.url, version=queries.version or "0", definicion_sha=definicion_sha, reglas_sha=reglas_sha,
parametros=json.dumps(parametros, sort_keys=True), datos_as_of=queries.cutoff,
huella=json_sha({"definicion": definicion_sha, "reglas": reglas_sha, "parametros": parametros}),
marco_sha="", n_miembros=len(miembros), armado_en=ahora or datetime.now(timezone.utc),
)
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=paso, n=n)
for orden, (paso, n) in enumerate(atricion, start=1)]
filas_miembro = [cohortes.CohorteMiembro(pac_id=m.pac_id, fecha_indice=m.fecha_indice,
indice_fuente_tabla=m.indice_fuente_tabla,
indice_fuente_id=m.indice_fuente_id) for m in miembros]
tipos = {v.nombre: v.tipo for v in definicion.variables}
variables = [
cohortes.CohorteVariable(pac_id=m.pac_id, variable=nombre,
**({"valor_codigo": str(valor)} if tipos[nombre] == "codigo"
else {"valor_numerico": float(valor)}))
for m in miembros for nombre, valor in m.variables.items() if valor is not None
]
exclusiones = [cohortes.CohorteExclusion(orden=orden, paso=fila["step"], n=int(fila["n"]))
for orden, fila in enumerate(built.attrition.to_dict("records"), start=1)]
filas_miembro = [cohortes.CohorteMiembro(pac_id=int(m["pac_id"]), fecha_indice=m["fecha_indice"],
indice_fuente_tabla=m.get("indice_fuente_tabla"),
indice_fuente_id=None if m.get("indice_fuente_id") is None
else str(m["indice_fuente_id"])) for m in miembros]
socias = {int(m["pac_id"]) for m in miembros}
variables = [cohortes.CohorteVariable(pac_id=int(v["pac_id"]), variable=v["variable"],
valor_codigo=None if v.get("valor_codigo") is None else str(v["valor_codigo"]),
valor_numerico=None if v.get("valor_numerico") is None
else float(v["valor_numerico"]))
for v in (consultas.read(queries.variables) if queries.variables else [])
if int(v["pac_id"]) in socias and (v.get("valor_codigo") is not None or v.get("valor_numerico") is not None)]
armado.marco_sha = frame_sha(miembros, variables)
return armado, exclusiones, filas_miembro, variables
@@ -117,15 +85,16 @@ def latest_build(sesion: Session, url: str, *, cohortes: TablasCohorte) -> int |
).first()
def read_frame(sesion: Session, armado_id: int, definicion: Definition, *, cohortes: TablasCohorte):
"""El marco guardado, ancho: (columnas, filas), una por miembro. Lo que recibe el modelo."""
nombres = [v.nombre for v in definicion.variables]
def read_frame(sesion: Session, armado_id: int, *, cohortes: TablasCohorte):
"""El marco guardado, ancho: (columnas, filas), una por miembro, con las variables que el armado tenga (los de
dbt no tienen: solo `pac_id` y `fecha_indice`)."""
valores: dict[int, dict] = {}
variable = cohortes.CohorteVariable
for fila in sesion.exec(select(variable).where(variable.armado_id == armado_id)):
valores.setdefault(fila.pac_id, {})[fila.variable] = (
fila.valor_codigo if fila.valor_codigo is not None else fila.valor_numerico
)
nombres = sorted({nombre for porpac in valores.values() for nombre in porpac})
miembro = cohortes.CohorteMiembro
filas = [
(m.pac_id, m.fecha_indice, *(valores.get(m.pac_id, {}).get(n) for n in nombres))
-1
View File
@@ -1 +0,0 @@
"""CaCu's cohorts: the surveillance cohort."""
-106
View File
@@ -1,106 +0,0 @@
"""El marco de la cohorte de vigilancia de CaCu, desde la línea de tiempo (`cohorte_vigilancia.toml`).
Las reglas 0.2.0 del kit de campo, sobre las filas de la línea de tiempo de dbt
(`cacu_linea_de_tiempo`) en lugar de SQL sobre tablas. Una fila del marco por miembro, con el desenlace como lo
pide el modelo de mezcla prevalencia–incidencia (Modelo-cacu):
c 1 = evento en la ventana basal; 0 = sin evento basal; -999 = estado basal desconocido
l, r el intervalo (l, r] en que aparece el evento, en años desde la índice.
Con c = 1 valen -999. r nulo = sin evento hasta el corte.
Quién entra:
- la índice es la primera citología de toda la historia, si cae en la ventana;
- se excluye a quien tuvo una biopsia con el desenlace antes de la índice;
- y luego a quien no tiene resultado citológico ni de VPH en la índice.
El desenlace solo se observa al verificar: una biopsia (positiva o negativa) o, con
`negativo_da_l`, un tamizaje completamente negativo posterior (`no_prevalente`).
Con `negativo_confirma_no_prevalente`, ese tamizaje vuelve c = 0 a quien era -999.
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import date
DIAS_POR_ANIO = 365.25
SIN_ESTADO = -999
@dataclass(frozen=True)
class Member:
pac_id: int
fecha_indice: date
indice_fuente_tabla: str
indice_fuente_id: str
variables: dict # nombre -> valor; un valor nulo no se guarda
def _by_patient(filas):
pacientes = defaultdict(list)
for fila in filas:
pacientes[fila["pac_id"]].append(fila)
return pacientes
def frame(filas, reglas: dict, inicio: date, fin: date, corte: date) -> tuple[list[Member], list[tuple[str, int]]]:
"""(miembros, atrición). `filas`: la línea de tiempo de CaCu, ya recortada al corte (`hasta=corte`)."""
grados = set(reglas["grados_evento"])
ventana = int(reglas["ventana_basal_dias"])
pap_negativo = set(reglas["no_prevalente"]["pap"])
vph_negativo = set(reglas["no_prevalente"]["vph"])
candidatas = evento_previo = sin_resultado = 0
miembros = []
for pac_id, eventos in sorted(_by_patient(filas).items()):
eventos = [e for e in eventos if e["fecha"] <= corte]
resultado = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "bethesda"}
vph = {(e["fuente_tabla"], e["fuente_id"]): e["valor_codigo"] for e in eventos if e["tipo"] == "vph"}
tomas = sorted((e for e in eventos if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
if not tomas or not (inicio <= tomas[0]["fecha"] < fin):
continue
indice = tomas[0]
llave = (indice["fuente_tabla"], indice["fuente_id"])
fecha_indice, pap_0, hpv_0 = indice["fecha"], resultado.get(llave), vph.get(llave)
candidatas += 1
biopsias = [(e["fecha"], e["valor_codigo"] in grados) for e in eventos if e["tipo"] == "biopsia"]
if any(positiva and fecha < fecha_indice for fecha, positiva in biopsias):
evento_previo += 1
continue
if pap_0 is None and hpv_0 is None:
sin_resultado += 1
continue
verificaciones = [((fecha - fecha_indice).days, positiva, "biopsia")
for fecha, positiva in biopsias if fecha >= fecha_indice]
if reglas["negativo_da_l"]:
for toma in tomas[1:]:
clave = (toma["fuente_tabla"], toma["fuente_id"])
if toma["fecha"] > fecha_indice and resultado.get(clave) in pap_negativo and vph.get(clave) in vph_negativo:
verificaciones.append(((toma["fecha"] - fecha_indice).days, False, "tamizaje"))
positivas = [d for d, positiva, _ in verificaciones if positiva]
primera_positiva = min(positivas) if positivas else None
negativas = [d for d, positiva, _ in verificaciones
if not positiva and (primera_positiva is None or d < primera_positiva)]
ultima_negativa = max(negativas) if negativas else None
if primera_positiva is not None and primera_positiva <= ventana:
c = 1
elif any(not positiva and tipo == "biopsia" and d <= ventana for d, positiva, tipo in verificaciones):
c = 0
elif pap_0 in pap_negativo and hpv_0 in vph_negativo:
c = 0
elif reglas["negativo_confirma_no_prevalente"] and ultima_negativa is not None:
c = 0
else:
c = SIN_ESTADO
if c == 1:
l = r = SIN_ESTADO
else:
l = (ultima_negativa or 0) / DIAS_POR_ANIO if c == 0 else 0
r = None if primera_positiva is None else primera_positiva / DIAS_POR_ANIO
miembros.append(Member(pac_id, fecha_indice, *llave,
{"c": c, "l": l, "r": r, "pap_0": pap_0, "hpv_0": hpv_0}))
atricion = [("candidatas", candidatas), ("sin evento_previo", candidatas - evento_previo),
("sin sin_resultado", len(miembros))]
return miembros, atricion
-78
View File
@@ -1,78 +0,0 @@
# Cohorte de vigilancia de CaCu: quién entra al modelo de riesgo de CIN2+ y con qué marco.
#
# Definición 0.2.0 del kit de campo (indicadores_kit_0/campo/cohortes/cacu/
# cohorte_vigilancia_reglas.toml): mismas reglas y mismo formato de [group.reglas],
# el que lee Modelo-cacu (`reglas_de_toml`). Lo que cambia es de dónde lee: la línea de
# tiempo del kit (`cdm/linea_de_tiempo.py`), no SQL sobre tablas.
#
# Cambiar una regla es cambiar la definición: se sube `version`.
[group]
url = "cacu/cohorte_vigilancia"
version = "0.2.0"
status = "draft"
membership = "definitional"
title = "Mujeres en vigilancia por citología"
expression = "cacu.surveillance:frame"
indice = "Primera citología de la historia de la paciente, si cae en la ventana de reclutamiento"
desenlace = "cin2_mas"
[[group.characteristic]]
code = "evento_previo"
exclude = true
description = "Biopsia con el desenlace antes de la fecha índice: no está en riesgo de un primer evento"
[[group.characteristic]]
code = "sin_resultado"
exclude = true
description = "La citología índice no tiene resultado citológico ni de VPH: no hay predictores"
[group.reglas]
grados_evento = ["LIEAG", "CIS", "CARCINOMA"]
ventana_basal_dias = 90
negativo_da_l = true
negativo_confirma_no_prevalente = true
colposcopia_negativa = []
[group.reglas.no_prevalente]
pap = ["NORMAL"]
vph = ["NEGATIVO"]
description = "Tamizaje completamente negativo: confirma que no es prevalente"
[group.reglas_estado]
grados_evento = { estado = "vigente", fuente = "Modelo-cacu: desenlace CIN2+; CIN3+ no se puede con este staging (I-K31)" }
no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-08 (traspaso_modelos.md M11)" }
negativo_da_l = { estado = "vigente", fuente = "Usuario, 2026-10-08" }
negativo_confirma_no_prevalente = { estado = "vigente", fuente = "Usuario, 2026-10-09 (traspaso_modelos.md M13)" }
ventana_basal_dias = { estado = "sin_definir", fuente = "90 es el valor con que se probó la 0.0.1 de campo; por decidir con quien lleva el modelo" }
colposcopia_negativa = { estado = "sin_definir", fuente = "La colposcopia no tiene fuente en staging (I-K32): vacía, no se lee" }
[[evidenceVariable]]
name = "c"
role = "outcome"
tipo = "numero"
title = "Estado basal: 1 prevalente, 0 no prevalente, -999 desconocido"
[[evidenceVariable]]
name = "l"
role = "outcome"
tipo = "numero"
title = "Último momento sin enfermedad, en años desde la índice (-999 si c = 1)"
[[evidenceVariable]]
name = "r"
role = "outcome"
tipo = "numero"
title = "Primer momento con enfermedad, en años desde la índice (sin fila = sin evento al corte)"
[[evidenceVariable]]
name = "pap_0"
role = "covariate"
tipo = "codigo"
title = "Categoría citológica de la citología índice"
[[evidenceVariable]]
name = "hpv_0"
role = "covariate"
tipo = "codigo"
title = "Resultado de VPH de la misma muestra"
-82
View File
@@ -1,82 +0,0 @@
"""La definición de una cohorte, de su TOML: FHIR `Group` definicional más sus `EvidenceVariable`.
Igual que un Measure: la definición es un archivo (`<proyecto>/<nombre>.toml`),
las reglas clínicas son datos (`[group.reglas]`) y la función que arma el marco se
nombra con `expression` (`modulo:funcion`, relativo a `models.cohorts`).
"""
import hashlib
import json
import tomllib
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
ROOT = Path(__file__).resolve().parent # `<proyecto>/<nombre>.toml`, next to its rule module
@dataclass(frozen=True)
class Variable:
nombre: str
rol: str # outcome o covariate
tipo: str # numero o codigo
titulo: str
@dataclass(frozen=True)
class Definition:
url: str
version: str
titulo: str
expression: str
desenlace: str
reglas: dict
variables: tuple[Variable, ...]
definicion_sha: str # sha256 del TOML
@property
def reglas_sha(self) -> str:
return json_sha(self.reglas)
def function(self):
"""La función que arma el marco: `funcion(filas_de_linea, reglas, inicio, fin, corte)`."""
return function_of(self.expression)
def json_sha(objeto) -> str:
"""sha256 del JSON canónico: claves ordenadas, sin espacios."""
texto = json.dumps(objeto, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
def cohort_path(proyecto: str, nombre: str, *, propuesta: bool = False) -> Path:
"""A cohort's TOML. `propuesta`: from `<proyecto>/proposals/`, which the cycle doesn't build."""
return ROOT / proyecto / ("proposals" if propuesta else "") / f"{nombre}.toml"
def read_definition(ruta: Path) -> Definition:
texto = ruta.read_text(encoding="utf-8")
doc = tomllib.loads(texto)
g = doc["group"]
reglas = dict(g["reglas"])
if "no_prevalente" in reglas: # regla de CaCu: su `description` es texto, no regla
reglas["no_prevalente"] = {k: v for k, v in reglas["no_prevalente"].items() if k != "description"}
variables = tuple(Variable(v["name"], v["role"], v["tipo"], v["title"]) for v in doc["evidenceVariable"])
nombres = [v.nombre for v in variables]
if len(set(nombres)) != len(nombres):
raise ValueError(f"{g['url']}: variables repetidas.")
return Definition(
url=g["url"], version=g["version"], titulo=g["title"], expression=g["expression"],
desenlace=g["desenlace"], reglas=reglas, variables=variables,
definicion_sha=hashlib.sha256(texto.encode("utf-8")).hexdigest(),
)
def function_of(expresion: str):
"""The function of `module:function`, relative to `models.cohorts`. Fails if the module doesn't define it."""
modulo, nombre = expresion.split(":")
function = getattr(import_module(f"models.cohorts.{modulo}"), nombre, None)
if not callable(function):
raise ValueError(f"{modulo} debe definir la función {nombre}.")
return function
View File
+69
View File
@@ -0,0 +1,69 @@
"""Estimating with any scenario's registered version: score a source's build and write the estimate, once.
Estimation runs the registered pyfunc, outside Hamilton, so a version estimates the same whatever the repository holds
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order;
its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a
classifier that's the positive class at its one horizon. The output has one row per member and horizon
(`ESTIMATE_FRAME`); its metadata names the version, the outcome (`model.toml`'s `outcome`) and the source's reference.
"""
import json
from pathlib import Path
import mlflow.pyfunc
import numpy as np
import pandas as pd
import pyarrow as pa
from models.dags.training import Scenario
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import CohortSource, read_metadata, write_once
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
"""Whether the output file already holds this version's scores of this build."""
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float]) -> pd.DataFrame:
"""One row per member (in `pac_id` order, as the model gives them) and horizon. A model that decides its own index
date (`models.steps.indexing`) gives it as one more first column, in days since 1970-01-01, with the members it
leaves out empty: their rows are dropped and the rest are dated by it, not by the cohort's index."""
members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable")
if probabilities.ndim != 2 or len(probabilities) != len(members):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members")
risks, dates = probabilities[:, -len(horizons):], members["fecha_indice"].to_numpy()
if probabilities.shape[1] == len(horizons) + 1:
decided = ~np.isnan(probabilities[:, 0])
members, risks = members[decided], risks[decided]
dates = pd.to_datetime(probabilities[decided, 0], unit="D").date
return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
"fecha_indice": np.repeat(dates, len(horizons)),
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
"probabilidad": risks.ravel().astype(float)})
def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
version: str | None = None) -> tuple[ResolvedVersion, bool]:
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
`modelo_sha` is copied when the version has it, and isn't checked."""
output_path = Path(output_path)
resolved = registry.resolve(scenario.domain, scenario.scenario, version)
cohort = source.reference()
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
cohort_frame = source.frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
risks = estimate_frame(cohort_frame, probabilities, horizons)
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario),
"modelo_version": resolved.version, "mlflow_run_id": resolved.run_id,
"desenlace": scenario.outcome, **cohort}
if resolved.modelo_sha:
provenance["modelo_sha"] = resolved.modelo_sha
table = pa.Table.from_pandas(risks, preserve_index=False)
write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path)
return resolved, True
+134
View File
@@ -0,0 +1,134 @@
"""Training any scenario: one driver built from the modules its `model.toml` lists, its config, a cohort source and
the adapters.
A scenario is a folder with `model.toml` and its dataflow. `model.toml` names it (`domain`, `scenario`, `cohort`,
`outcome`, `description`), lists the `modules` whose functions are the graph's nodes, and holds `[config]`, the values
the dataflow receives through `with_config`. The dataflow goes from `cohort` and `cohort_lineage` to `fitted_model` (a
scikit-learn estimator that takes the long frame) and `metrics`, with no I/O.
Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same.
`train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks
it failed if the graph fails. `find_trained` answers before anything is built whether this source, the installed
`models` version, the config and the environment already have a version. A failing node's inputs, which may hold
members' rows, are kept out of Hamilton's error log; the exception still says which node failed.
"""
import hashlib
import json
import logging
import tomllib
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
from types import ModuleType
from hamilton import base, driver
from hamilton.io.materialization import from_, to
from models.io import adapters # noqa: F401 (registers the loaders and the saver)
from models.io.lineage import code_version, matches
from models.io.registry import registered_name, registry
from models.io.storage import CohortSource
from models.io.tracking import TrainingRun
REGISTERED_MODEL = "registered_model"
# The logger that prints a failing node's inputs (`hamilton.execution.graph_functions.create_error_message`).
HAMILTON_NODE_ERRORS = "hamilton.execution.graph_functions"
@dataclass(frozen=True)
class Scenario:
domain: str
scenario: str
cohort: str
outcome: str
description: str
modules: tuple[ModuleType, ...]
config: dict
folder: Path
requirements: tuple[str, ...] = ()
@classmethod
def from_toml(cls, path: str | Path) -> "Scenario":
path = Path(path)
found = tomllib.loads(path.read_text())
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
outcome=found["outcome"], description=found.get("description", ""),
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
folder=path.parent, requirements=tuple(found.get("requirements", ())))
@classmethod
def load(cls, domain: str, scenario: str) -> "Scenario":
"""`models/<domain>/<scenario>/model.toml`; `LookupError` if there's no such scenario."""
try:
package = import_module(f"models.{domain}.{scenario}")
except ModuleNotFoundError as error:
raise LookupError(f"no such model: {domain}/{scenario}") from error
return cls.from_toml(Path(package.__file__).parent / "model.toml")
def config_sha256(self) -> str:
return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest()
def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver:
"""The graph of these modules. Without materializers it takes `cohort` and `cohort_lineage` as inputs."""
builder = driver.Builder().with_modules(*modules).with_config(config)
if materializers:
builder = builder.with_materializers(*materializers)
return builder.build()
# What the saver receives: the fitted model and its metrics, and the routines' records, the population results and the
# reports' pages when the dataflow has them.
SAVED = {"fitted_model", "metrics", "routines", "population", "reports"}
def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]:
"""The graph's inputs that some node requires, and those every node taking them has a default for."""
variables = dr.list_available_variables()
inputs = {v.name for v in variables if v.is_external_input}
required = set().union(*(v.required_dependencies for v in variables)) & inputs
return required, inputs - required
def expected_params(scenario: Scenario, source: CohortSource) -> dict[str, str]:
return {**source.reference(), **code_version(), "config_sha256": scenario.config_sha256()}
def find_trained(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str | None:
"""The newest version not retired from the same source reference, `models` version, config and environment."""
name = registered_name(scenario.domain, scenario.scenario)
expected = expected_params(scenario, source)
versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True)
for mv in versions:
if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"):
continue
if matches(registry.client.get_run(mv.run_id).data.params, expected):
return str(mv.version)
return None
def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str:
"""Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
rows."""
logging.getLogger(HAMILTON_NODE_ERRORS).setLevel(logging.CRITICAL)
run = TrainingRun(domain=scenario.domain, scenario=scenario.scenario, environment=environment,
cohorte_armado_id=source.armado_id, cohort=source.reference())
try:
plain = dataflow(*scenario.modules, config=scenario.config)
required, _ = external_inputs(plain)
loaders = [loader(target=target, source=source) for target, loader in
(("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source),
("cohort_lineage", from_.cohort_source_lineage))
if target in required]
produced = {v.name for v in plain.list_available_variables() if not v.is_external_input}
saver = to.registered_model(id=REGISTERED_MODEL, dependencies=sorted(SAVED & produced),
combine=base.DictResult(), run=run, description=scenario.description,
hyperparameters={**expected_params(scenario, source), **scenario.config},
requirements=list(scenario.requirements))
dr = dataflow(*scenario.modules, config=scenario.config, materializers=(*loaders, saver))
result = dr.execute([REGISTERED_MODEL])
except BaseException:
run.client.set_terminated(run.run_id, status="FAILED")
raise
return result[REGISTERED_MODEL]["version"]
+236
View File
@@ -0,0 +1,236 @@
"""TEA's EEG analysis against the database: which EEGs to analyse, the batch, and its results written to bronze.
An EEG is pending when it has an EDF and was never analysed, or was analysed with another plan or other module
versions, or, being valid, against baselines other than those now in production. One that failed with the current
plan and versions waits for a new one instead of failing again on every run.
Each result replaces the EEG's previous checks, metrics and electrode values in `eeg`, `eeg_criterio`,
`eeg_metrica` and `eeg_metrica_electrodo`. Row ids derive from the EEG and what each row is, so a row keeps its id
from one analysis to the next and the silver load sees it as changed rather than new. Each result is committed with
its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished.
`cluster` is the `tea` library's: "sync" runs in this process, "local" on a LocalCluster, "auto" on the scheduler in
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
"""
import uuid
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from sqlmodel import Session, col, delete, select
from core.tea.enums import MetricaEeg
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes
from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions
from models.tea.eeg.baselines import Baselines
from models.tea.eeg.settings import Settings, settings as model_settings
COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo"
def checked_settings() -> Settings:
"""The analysis's settings, checked against the metric catalog the tables use."""
s = model_settings()
codes = sorted(m.code for m in s.metrics)
if codes != sorted(c.value for c in MetricaEeg):
raise ValueError(f"model.toml must map every MetricaEeg code once, not {codes}")
return s
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
everything: bool = False, limit: int | None = None) -> list[str]:
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
out, expected = [], None
for eeg_id, valid, stored_hash, stored_versions, error in session.exec(query):
if everything or stored_hash != plan_hash or stored_versions != versions:
out.append(eeg_id)
elif valid == 1 and error is None:
stored = dict(session.exec(select(EegMetrica.met_codigo, EegMetrica.met_modelo)
.where(EegMetrica.met_eeg_id == eeg_id)).all())
expected = models() if expected is None else expected
if any(stored.get(code) != label for code, label in expected.items()):
out.append(eeg_id)
if limit is not None and len(out) >= limit:
break
return out
def age_months(born, studied, days_per_month: float) -> float | None:
if born is None or studied is None or studied < born:
return None
return round((studied - born).days / days_per_month, 1)
def inputs(session: Session, eeg_id: str, days_per_month: float) -> tuple[bytes, float | None]:
eeg = session.get(Eeg, eeg_id)
if eeg is None or eeg.eeg_estudio is None:
raise LookupError(f"no EDF for EEG {eeg_id!r}")
born = session.exec(select(Pacientes.pac_fecha_nacimiento).where(Pacientes.pac_id == eeg.eeg_pac_id)).first()
return bytes(eeg.eeg_estudio), age_months(born, eeg.eeg_fecha_estudio, days_per_month)
def row_id(*parts: object) -> str:
return str(uuid.uuid5(uuid.NAMESPACE_URL, "tea:eeg/" + "/".join("" if p is None else str(p) for p in parts)))
@dataclass
class Rows:
eeg: dict
criteria: list[EegCriterio]
metrics: list[EegMetrica]
electrodes: list[EegMetricaElectrodo]
def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows:
eeg = {
"eeg_valido": m.valid, "eeg_nivel": m.level, "eeg_fraccion_limpia": m.clean_fraction,
"eeg_canales_malos": m.bad_channels, "eeg_ruido_linea_db": m.line_db, "eeg_con_sueno": m.asleep,
"eeg_edad_meses": m.age_months, "eeg_plan_hash": m.plan_hash, "eeg_versiones": m.versions,
"eeg_analizado_en": at or datetime.now(timezone.utc).replace(tzinfo=None), "eeg_error": m.error,
}
if m.channels is not None:
eeg["eeg_canales"] = m.channels
if m.duration_min is not None:
eeg["eeg_duracion_min"] = m.duration_min
seen: dict[tuple[str, str | None], int] = {}
criteria = []
for c in m.checks:
n = seen[c.code, c.electrode] = seen.get((c.code, c.electrode), 0) + 1
criteria.append(EegCriterio(
cri_id=row_id(m.key, "criterio", c.code, c.electrode, n), cri_eeg_id=m.key, cri_codigo=c.code,
cri_electrodo=c.electrode, cri_valor=c.value, cri_valor_texto=c.text, cri_unidad=c.unit,
cri_bajo=c.low, cri_alto=c.high, cri_decisivo=int(c.decisive), cri_anormal=int(c.abnormal),
))
by_code = {metric.code: metric for metric in s.metrics}
metrics, electrodes = [], []
for value in m.metrics:
metric = by_code[value.code]
met_id = row_id(m.key, "metrica", value.code)
deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months)
used = [metric.scenario] if deviation is not None else []
for electrode, raw in sorted(value.electrodes.items()):
at_electrode = None
if metric.electrode_scenario:
at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode,
raw, m.age_months)
if at_electrode is not None and metric.electrode_scenario not in used:
used.append(metric.electrode_scenario)
electrodes.append(EegMetricaElectrodo(
mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode,
mel_valor=raw, mel_z=at_electrode.z if at_electrode else None,
))
metrics.append(EegMetrica(
met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value,
met_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None,
met_p5=deviation.p5 if deviation else None, met_mediana=deviation.median if deviation else None,
met_p95=deviation.p95 if deviation else None,
met_modelo=";".join(baselines.label(scenario) for scenario in used) or None,
))
return Rows(eeg, criteria, metrics, electrodes)
def save(session: Session, eeg_id: str, new: Rows) -> None:
"""Replaces the EEG's analysis in the caller's session; the caller commits."""
eeg = session.get(Eeg, eeg_id)
if eeg is None:
raise LookupError(f"no EEG {eeg_id!r}")
for column, value in new.eeg.items():
setattr(eeg, column, value)
session.add(eeg)
metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id)
session.exec(delete(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids)))
session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id))
session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id))
session.flush()
session.add_all([*new.criteria, *new.metrics, *new.electrodes])
def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings):
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
if m.error:
quality = f"error: {m.error}"
elif m.valid:
quality = f"valido: {m.level}"
else:
quality = "no valido: " + "; ".join(c.code for c in m.checks if c.abnormal and c.decisive)
return ExtractionRun(
domain=s.domain, entity="eeg", entity_pk=m.key, column_extracted=COLUMNS,
source_description="eeg.eeg_estudio (EDF)", source_started_at=started, source_ended_at=ended,
transform_description=f"tea {s.impl}, plan {s.plan} {m.plan_hash}; {m.versions}",
quality_validation=quality,
estatus=(EstatusExtraccion.FALLIDA if m.error else EstatusExtraccion.COMPLETADA).value,
)
@dataclass
class Summary:
pending: int = 0
valid: int = 0
not_valid: int = 0
failed: int = 0
def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]:
out = {}
for m in s.metrics:
scenarios = [m.scenario, m.electrode_scenario] if m.electrode_scenario else [m.scenario]
out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None
return out
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16,
settings: Settings | None = None, baselines: Baselines | None = None,
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
from tea.pipeline.dask_runner import run as run_batch
from persistance.tea import eeg_repository
s = settings or checked_settings()
b = baselines or Baselines(s.domain)
pipe = pipeline(s)
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
with eeg_repository.open_session() as session:
ids = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
everything=everything, limit=limit)
summary = Summary(pending=len(ids))
def write(m: Measurement) -> None:
ended = _now()
with eeg_repository.open_session() as session:
save(session, m.key, rows(m, s, b, at=ended))
session.commit()
if log_runs:
from persistance.governance import extraction_run_repository
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
if m.error:
summary.failed += 1
elif m.valid:
summary.valid += 1
else:
summary.not_valid += 1
def lost(args, exc) -> Measurement:
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
error=f"{type(exc).__name__}: the batch lost this study")
for start in range(0, len(ids), batch):
argsets = []
with eeg_repository.open_session() as session:
for eeg_id in ids[start:start + batch]:
edf, age = inputs(session, eeg_id, s.days_per_month)
argsets.append((eeg_id, edf, age, s))
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost)
return summary
+140
View File
@@ -0,0 +1,140 @@
"""Hamilton's boundary with storage and MLflow: the loaders and the saver a model's driver attaches.
A model's dataflow has no I/O: it receives `cohort` and `cohort_lineage` and ends at `fitted_model` and `metrics`. The
driver (`models.dags.training`) attaches these adapters with `with_materializers`, so they're nodes of the graph before
anything runs and nothing in the model imports MLflow:
- `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage",
source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file).
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines", "population",
"reports"], ...)`: records each routine (ML-01a, `TrainingRun.log_routine`), the dataflow's `population` as the
version's `analisis/` files and its `reports` as its `reportes/` pages when it has them (`TrainingRun.log_analysis`,
`TrainingRun.log_report`), logs the fitted model in the open `TrainingRun` (`tracking`),
records the metrics and the config, closes the run, and registers and describes the version (`registry`). Its value
is the version's metadata. A dataflow without `routines` still trains and registers, but the registry won't promote
it (`ROUTINE_KINDS`).
The saver pickles the packages of the model's own classes by value, so the registered version loads with
scikit-learn and the model's libraries, without this repository. The saver and the metrics being numbers are what keep members' rows out
of MLflow. Names are registered once, here, since Hamilton's adapter registry is global and keyed by name.
"""
import dataclasses
import sys
from collections.abc import Collection
from typing import Any
import cloudpickle
import pandas as pd
from hamilton import registry as hamilton_registry
from hamilton.io.data_adapters import DataLoader, DataSaver
from models.io.registry import registered_name, registry
from models.io.tracking import TrainingRun, pinned
@dataclasses.dataclass
class CohortSourceLoader(DataLoader):
"""A build's long frame, from whatever source reads it."""
source: Any
@classmethod
def applicable_types(cls) -> Collection[type]:
return [pd.DataFrame]
@classmethod
def name(cls) -> str:
return "cohort_source"
def load_data(self, type_: type) -> tuple[pd.DataFrame, dict[str, Any]]:
frame = self.source.frame()
return frame, {"source": type(self.source).__name__, "rows": len(frame)}
@dataclasses.dataclass
class CohortSourceLineageLoader(DataLoader):
"""A build's lineage, from whatever source reads it."""
source: Any
@classmethod
def applicable_types(cls) -> Collection[type]:
return [dict]
@classmethod
def name(cls) -> str:
return "cohort_source_lineage"
def load_data(self, type_: type) -> tuple[dict, dict[str, Any]]:
return self.source.lineage(), {"source": type(self.source).__name__}
def _own_packages(model) -> list:
"""The packages of the classes in a fitted model (the model, or each step of a `Pipeline`) whose code isn't an
installed library: `models.cacu.cin2_pim` for a class of `models.cacu.cin2_pim.model`. Those are pickled with the
model; scikit-learn and the rest are expected where it's loaded."""
found = {}
for step in [model, *(step for _, step in getattr(model, "steps", []))]:
module = sys.modules[type(step).__module__]
if module.__name__ == "__main__" or "site-packages" in (getattr(module, "__file__", None) or "site-packages"):
continue
package = module.__name__.rpartition(".")[0] or module.__name__
found[package] = sys.modules[package]
return list(found.values())
def _numbers(metrics: dict) -> dict[str, float]:
found = {}
for key, value in metrics.items():
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"metrics.{key} is a {type(value).__name__}; only numbers are logged")
found[key] = float(value)
return found
@dataclasses.dataclass
class RegisteredModelSaver(DataSaver):
"""Records `routines`, when the dataflow has them, logs `fitted_model` in `run` with `requirements` (pinned to the
installed versions), records `metrics` (numbers only) and `hyperparameters`, closes the run, registers the version
and gives it `description`."""
run: TrainingRun
description: str = ""
hyperparameters: dict = dataclasses.field(default_factory=dict)
requirements: list = dataclasses.field(default_factory=list)
@classmethod
def applicable_types(cls) -> Collection[type]:
return [dict]
@classmethod
def name(cls) -> str:
return "registered_model"
def save_data(self, data: dict) -> dict[str, Any]:
model, metrics = data["fitted_model"], _numbers(data["metrics"])
for kind, record in data.get("routines", {}).items():
self.run.log_routine(kind, record)
for name, record in data.get("population", {}).items():
self.run.log_analysis(name, record)
for name, page in data.get("reports", {}).items():
self.run.log_report(name, page)
packages = _own_packages(model)
for package in packages:
cloudpickle.register_pickle_by_value(package)
try:
self.run.log_model(model, requirements=pinned(self.requirements) if self.requirements else None)
finally:
for package in packages:
cloudpickle.unregister_pickle_by_value(package)
self.run.finish(metrics=metrics, hyperparameters=self.hyperparameters)
version = registry.register_run(self.run)
if self.description:
registry.set_description(self.run.domain, self.run.scenario, version, self.description)
return {"registered_model": registered_name(self.run.domain, self.run.scenario), "version": version,
"mlflow_run_id": self.run.run_id, "modelo_sha": self.run.modelo_sha}
for _adapter in (CohortSourceLoader, CohortSourceLineageLoader, RegisteredModelSaver):
hamilton_registry.register_adapter(_adapter)
+15 -7
View File
@@ -3,7 +3,8 @@
- A cohort build's Parquet file (`COHORT_SCHEMA`): long, one row per member and event, with the member's index date on
every row.
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member and horizon (`horizonte_anios`, years from the
index date; 0 is the prevalence).
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`).
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
@@ -26,7 +27,8 @@ COHORT_SCHEMA = pa.schema([
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
])
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "horizonte_anios", "probabilidad")
DAYS_PER_YEAR = 365.25 # horizons and intervals are in years from the index date
# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow
# schema says which columns and types; these say what a valid row and a valid file are.
@@ -43,12 +45,13 @@ COHORT_FRAME = pandera.DataFrameSchema(
name="cohort build")
ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False),
"horizonte_anios": pandera.Column(float, pandera.Check.ge(0)),
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
strict=True, ordered=True, name="estimate")
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables"
class CohortFileError(ValueError):
@@ -57,7 +60,8 @@ class CohortFileError(ValueError):
class EstimateError(ValueError):
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1."""
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice at one horizon, a negative
horizon, a probability outside 0..1."""
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
@@ -89,6 +93,9 @@ class CohortQueries:
rules: tuple[ExclusionRule, ...]
cutoff: date
parameters: dict
version: str = "" # the population meta's `version`: bumped when a rule changes
# optional: the members' stored variables, long (`pac_id`, `variable`, `valor_codigo`, `valor_numerico`)
variables: str | None = None
@dataclass(frozen=True)
@@ -103,7 +110,8 @@ class Risk(NamedTuple):
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
pac_id: int
horizonte_anios: float # years from the index date; 0 = prevalent
fecha_indice: date # the model's index date for this member: the horizons count from it
horizonte_anios: float # years from `fecha_indice`; 0 = prevalent
probabilidad: float # 0 to 1
ic_bajo: float | None = None
ic_alto: float | None = None
+13 -56
View File
@@ -1,21 +1,17 @@
"""What each output came from, in one vocabulary for files, runs and versions: the names models are registered under,
the keys lineage is recorded with, the hashes that identify code, data and models, and the rule that an output already
exists when its recorded lineage matches what's expected.
the keys lineage is recorded with, the code's version, a model's hash, and the rule that an output already exists when
its recorded lineage matches what's expected. The hashes of data files live with the files (`models.io.storage`).
"""
import hashlib
import os
import subprocess
from importlib.metadata import version
from pathlib import Path
import pyarrow as pa
DOMAINS = ("cacu", "cama", "tea")
ARMADO_TAG = "kit.armado_id"
MODEL_SHA_TAG = "modelo_sha"
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
GIT_DIRTY_TAG = "models.git.dirty"
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
MODELS_VERSION_TAG = "models.version"
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets; read by `models.tea.eeg.bundle`
COHORT_URL_TAG, COHORT_SOURCE_TAG = "cohort.url", "cohort.source"
COHORT_BUILD_TAG, COHORT_FILE_TAG = "cohort.build", "cohort.file_sha256"
@@ -25,52 +21,17 @@ def registered_name(domain: str, scenario: str) -> str:
def code_version() -> dict[str, str]:
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
nothing is recorded."""
root = Path(__file__).resolve().parent
try:
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
check=True).stdout.strip()
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
capture_output=True, text=True, check=True).stdout.strip()
except (OSError, subprocess.CalledProcessError):
commit = os.environ.get(GIT_COMMIT_ENV)
return {GIT_COMMIT_TAG: commit} if commit else {}
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
"""The version of the installed `models` package: what a run's code is, with or without a repository."""
return {MODELS_VERSION_TAG: version("models")}
def model_sha(model_dir: str | Path) -> str:
"""sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left
out because it carries ids and dates, so the same model saved twice has the same sha."""
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]:
"""How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or
`dbt`), its number in that source and the file's hash. Only a file whose producer is `dbt` is dbt's; any other is a kit
build, numbered by its `armado_id`."""
source = "dbt" if metadata.get("producer") == "dbt" else "kit"
build = metadata["build"] if source == "dbt" else metadata["armado_id"]
return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build),
COHORT_FILE_TAG: file_sha256}
def file_sha256(*paths: str | Path) -> str:
"""The hash of these files' bytes, in this order."""
digest = hashlib.sha256()
for path in paths:
digest.update(Path(path).read_bytes())
return digest.hexdigest()
def table_sha256(table: pa.Table) -> str:
"""The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same."""
sink = pa.BufferOutputStream()
table = table.replace_schema_metadata(None)
with pa.ipc.new_stream(sink, table.schema) as stream:
stream.write_table(table)
return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest()
"""sha256 of a saved model's pickle (`python_model.pkl` for a pyfunc, `model.pkl` for scikit-learn): the fitted
model itself. `MLmodel` is left out because it carries ids and dates, so the same model saved twice has the same
sha."""
folder = Path(model_dir)
pickle = next(path for path in (folder / "python_model.pkl", folder / "model.pkl") if path.exists())
return hashlib.sha256(pickle.read_bytes()).hexdigest()
def matches(recorded: dict, expected: dict) -> bool:
@@ -78,7 +39,3 @@ def matches(recorded: dict, expected: dict) -> bool:
return all(str(recorded.get(key)) == str(value) for key, value in expected.items())
def require_match(recorded: dict, expected: dict, what: str) -> None:
"""Refuses an output whose recorded lineage disagrees with what's expected of it."""
if not matches(recorded, expected):
raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}")
+13 -4
View File
@@ -43,6 +43,7 @@ from models.io.tracking import MODEL_PATH, ROUTINE_KINDS, ROUTINES_PATH, Trainin
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
REFERENCE_SOURCE = "referencia" # `cohort.source` of a version trained on a cohort outside the platform
@dataclass(frozen=True)
@@ -232,13 +233,20 @@ class ModelRegistry:
run = self.client.get_run(mv.run_id)
armado, _ = _armado(domain, mv.tags.get(ARMADO_TAG))
dbt_build = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == "dbt" else None
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing.
reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
metrics = run.data.metrics
missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)]
# ML-01a: the training run is itself the registered routine; its records (`TrainingRun.log_routine`) are
# reported, not required, since not every model has each of `ROUTINE_KINDS` (a prevalence-incidence mixture
# has no class balance or classifier calibration).
recorded = [kind.value for kind in ROUTINE_KINDS if kind.value in self.routines(mv.run_id)]
sha = mv.tags.get(MODEL_SHA_TAG, "")
if armado is not None:
cohort_detail = f"huella {armado['huella'][:12]}"
elif dbt_build is not None:
cohort_detail = f"dbt build {dbt_build} de {mv.tags.get(COHORT_URL_TAG)}"
elif reference:
cohort_detail = f"cohorte de referencia {mv.tags.get(COHORT_URL_TAG)}, listado {reference[:12]}"
else:
cohort_detail = "sin cohorte"
return [
@@ -246,15 +254,16 @@ class ModelRegistry:
PromotionCheck(
"ML-03",
"enlazada al armado de cohorte con el que se entrenó",
armado is not None or dbt_build is not None,
armado is not None or dbt_build is not None or bool(reference),
cohort_detail,
),
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
PromotionCheck("ML-01a", "rutinas registradas por la corrida de entrenamiento", not missing,
f"faltan: {', '.join(missing)}" if missing else f"{len(ROUTINE_KINDS)} de {len(ROUTINE_KINDS)}"),
PromotionCheck("ML-01a", "rutina registrada por la corrida de entrenamiento", bool(run.info.run_id),
f"corrida {run.info.run_id[:12]}; registros de rutina: {len(recorded)} de {len(ROUTINE_KINDS)}"
+ (f" ({', '.join(recorded)})" if recorded else "")),
PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
]
+150 -8
View File
@@ -1,5 +1,13 @@
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's
manifest, a domain's Persistance repositories, and the batches of risks they store.
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates) and
their hashes, dbt's manifest, a domain's Persistance repositories, the batches of risks they store, and the cohort
sources a model trains and estimates on.
A cohort source (`KitBuild`, `CohortFile`) gives a build's long frame (`COHORT_SCHEMA`), its lineage (at least `url`
and `datos_as_of`, as text) and the reference a run, a version and an estimate keep of it (`cohort.url`,
`cohort.source`, `cohort.build`), so the dataflow doesn't know where the rows came from. `KitBuild` reads a kit build
now from the domain's database (its members, and their timeline up to its clinical cut-off and, when the build has
one, its load cut-off `conocida_hasta`; the lineage records when it was read) and writes nothing; reading it again later may give other rows if the
timeline changed. `CohortFile` reads an exported file, kit's or dbt's, and its reference adds the file's hash.
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder
beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
@@ -11,16 +19,20 @@ import importlib
import json
import os
import tempfile
from datetime import date
from dataclasses import dataclass, field
from datetime import date, datetime, timezone
from importlib import import_module
from pathlib import Path
from typing import Any, Protocol
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from sqlalchemy.engine import make_url
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, VARIABLES, CohortDefinitionError,
CohortFileError, CohortQueries, ExclusionRule, check_frame)
from models.io.lineage import COHORT_BUILD_TAG, COHORT_FILE_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, matches
def cohorts_root(database_url: str) -> Path:
@@ -176,14 +188,16 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
if not nodes:
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
# a cohort may have no exclusions (`cacu/cohorte_total`): its study population is everyone with an index
exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION]
if not exclusions:
raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries")
orders = [node["config"]["meta"]["order"] for node in exclusions]
if len(set(orders)) != len(orders):
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
variables = [node for node in nodes if node["config"]["meta"]["kind"] == VARIABLES]
if len(variables) > 1:
raise CohortDefinitionError(f"{url} has more than one `{VARIABLES}` query")
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
for node in exclusions:
for node in [*exclusions, *variables]:
if read := steps & set(node["depends_on"]["nodes"]):
raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}")
meta = population["config"]["meta"]
@@ -192,7 +206,17 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
for node in exclusions)
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")),
str(meta.get("version", "")), _compiled(variables[0]) if variables else None)
def cohort_urls(manifest: str | Path, domain: str) -> list[str]:
"""The urls of the domain's cohorts in dbt's manifest (`meta.cohort` of their population queries), sorted: the
cohorts the WebApi cycle builds."""
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
return sorted({node["config"]["meta"]["cohort"] for node in nodes
if node.get("config", {}).get("meta", {}).get("kind") == POPULATION
and str(node["config"]["meta"].get("cohort", "")).startswith(f"{domain}/")})
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
@@ -238,3 +262,121 @@ class ReadOnlyRepository:
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
def file_sha256(*paths: str | Path) -> str:
"""The hash of these files' bytes, in this order."""
digest = hashlib.sha256()
for path in paths:
digest.update(Path(path).read_bytes())
return digest.hexdigest()
def table_sha256(table: pa.Table) -> str:
"""The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same."""
sink = pa.BufferOutputStream()
table = table.replace_schema_metadata(None)
with pa.ipc.new_stream(sink, table.schema) as stream:
stream.write_table(table)
return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest()
def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]:
"""How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or
`dbt`), its number in that source and the file's hash. Only a file whose producer is `dbt` is dbt's; any other is a kit
build, numbered by its `armado_id`."""
source = "dbt" if metadata.get("producer") == "dbt" else "kit"
build = metadata["build"] if source == "dbt" else metadata["armado_id"]
return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build),
COHORT_FILE_TAG: file_sha256}
def require_match(recorded: dict, expected: dict, what: str) -> None:
"""Refuses an output whose recorded lineage disagrees with what's expected of it."""
if not matches(recorded, expected):
raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}")
class CohortSource(Protocol):
armado_id: int | None # the kit build it is, if any (ML-03)
def frame(self) -> pd.DataFrame: ...
def lineage(self) -> dict[str, str]: ...
def reference(self) -> dict[str, str]: ...
@dataclass
class KitBuild:
"""Kit build `build_id` of `domain`, read from its database. `cohorts` and `timeline` default to the domain's
`cohort_repository` and `timeline_repository`; tests pass stand-ins."""
domain: str
build_id: int
cohorts: Any = None
timeline: Any = None
_build: Any = field(default=None, init=False, repr=False)
def __post_init__(self):
if self.cohorts is None or self.timeline is None:
repositories = import_module(f"persistance.{self.domain}")
self.cohorts = self.cohorts or repositories.cohort_repository
self.timeline = self.timeline or repositories.timeline_repository
@property
def armado_id(self) -> int:
return self.build.armado_id
@property
def build(self):
if self._build is None:
self._build = self.cohorts.build(self.build_id)
if self._build is None:
raise LookupError(f"no kit build {self.build_id} in {self.domain}")
return self._build
def known_until(self) -> datetime | None:
"""The build's load cut-off, if it has one; without it everything loaded so far is read."""
return self.build.conocida_hasta
def frame(self) -> pd.DataFrame:
from models.steps.cohort_file import cohort_events
members = self.cohorts.members(self.build_id)
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"])
rows = self.timeline.read(patients=population["pac_id"].tolist(), until=self.build.datos_as_of,
known_until=self.known_until())
return cohort_events(rows, population, self.build.datos_as_of)
def lineage(self) -> dict[str, str]:
build = self.build
return {"url": build.url, "version": build.version, "armado_id": str(build.armado_id), "producer": "kit",
"datos_as_of": build.datos_as_of.isoformat(), "n_members": str(build.n_miembros),
"known_until": self.known_until().isoformat() if self.known_until() else "",
"parametros": getattr(getattr(self.cohorts, "get", lambda _: None)(self.build_id), "parametros", None) or "{}",
"read_at": datetime.now(timezone.utc).isoformat()}
def reference(self) -> dict[str, str]:
return {COHORT_URL_TAG: self.build.url, COHORT_SOURCE_TAG: "kit", COHORT_BUILD_TAG: str(self.build_id)}
@dataclass
class CohortFile:
"""An exported build's Parquet file."""
path: str | Path
@property
def armado_id(self) -> int | None:
lineage = self.lineage()
return int(lineage["armado_id"]) if lineage.get("producer") != "dbt" and "armado_id" in lineage else None
def frame(self) -> pd.DataFrame:
return read_cohort(self.path)
def lineage(self) -> dict[str, str]:
return read_metadata(self.path)
def reference(self) -> dict[str, str]:
return cohort_reference(self.lineage(), file_sha256(self.path))
+39 -11
View File
@@ -22,20 +22,25 @@ their own, and `find_run` finds one already made from the same inputs.
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
model that produced a risk. Which code trained it is recorded apart: every run is
tagged with the git commit of this package's repository and whether it had
uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the
delivered images). A PROD run only logs models whose class lives in a module, at a
known commit, never one defined in a notebook.
tagged with the installed `models` package's version. A PROD run only logs models
whose class lives in a module, never one defined in a notebook.
A model is a scikit-learn estimator (saved with MLflow's sklearn flavor, served
through `predict_proba`) or an `mlflow.pyfunc.PythonModel`. Classes of a package
registered with `cloudpickle.register_pickle_by_value` are stored with the model,
so it loads without this repository.
"""
import io
import json
import os
import tempfile
import zipfile
from importlib.metadata import version
from pathlib import Path
from typing import Any
import mlflow.pyfunc
import mlflow.sklearn
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient
@@ -45,6 +50,8 @@ from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
ROUTINES_PATH = "rutinas"
ANALYSIS_PATH = "analisis"
REPORTS_PATH = "reportes"
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
@@ -123,6 +130,11 @@ def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], f
return run.info.run_id
def pinned(requirements: list[str]) -> list[str]:
"""Each distribution at the version installed here: `scikit-learn` → `scikit-learn==1.7.2`."""
return [f"{name}=={version(name)}" for name in requirements]
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs name the cohort build they were trained on, so their metrics trace
@@ -181,18 +193,34 @@ class TrainingRun:
that too (for instance a class balance of "none"), so the run still says what happened."""
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str:
"""Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its
`modelo_sha` and returns it. Once per run. `signature` describes columns and types only: no input
example, so no patient data reaches MLflow."""
def log_analysis(self, name: str, record: dict[str, Any]) -> None:
"""What the run found about its cohort, a JSON file `analisis/<name>.json` that the version publishes: the
population results a dashboard draws, which are not a prediction of any member."""
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, default=str), f"{ANALYSIS_PATH}/{name}.json")
def log_report(self, name: str, page: str) -> None:
"""A page the run wrote about its cohort, `reportes/<name>.html` (self-contained: its scripts inside), which the
version keeps for whoever reviews it. Like `log_analysis`, aggregates only."""
self.client.log_text(self.run_id, page, f"{REPORTS_PATH}/{name}.html")
def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str:
"""Saves `model` under the run's `model` folder, tags the run with its `modelo_sha` and returns it.
Once per run. `signature` describes columns and types only: no input example, so no patient data
reaches MLflow. `requirements` are what an environment needs to load it (`pinned`); without them
MLflow infers them from the environment, which in this repository means its whole lock."""
if self.modelo_sha is not None:
raise RuntimeError("this run already logged its model")
if self.environment is Environment.PROD and type(python_model).__module__ == "__main__":
if self.environment is Environment.PROD and type(model).__module__ == "__main__":
raise ValueError("a PROD run only logs models whose class lives in a module; "
f"{type(python_model).__name__} was defined in a notebook or script")
f"{type(model).__name__} was defined in a notebook or script")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / MODEL_PATH
mlflow.pyfunc.save_model(path=str(path), python_model=python_model, signature=signature)
if isinstance(model, mlflow.pyfunc.PythonModel):
mlflow.pyfunc.save_model(path=str(path), python_model=model, signature=signature,
pip_requirements=requirements)
else:
mlflow.sklearn.save_model(model, str(path), serialization_format="cloudpickle", signature=signature,
pyfunc_predict_fn="predict_proba", pip_requirements=requirements)
sha = model_sha(path)
self.client.log_artifacts(self.run_id, str(path), MODEL_PATH)
self.client.set_tag(self.run_id, MODEL_SHA_TAG, sha)
+3 -3
View File
@@ -1,4 +1,4 @@
"""What a notebook run from the platform works with (`models.pipelines.experiment`): the cohort build's file it was
"""What a notebook run from the platform works with (`models.reports.experiment`): the cohort build's file it was
run on and, if one was chosen, a registered model version.
from models.notebook import experiment
@@ -62,8 +62,8 @@ 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.io.notebook_import`)."""
from models.io.lineage import cohort_reference, file_sha256
is copied into the real one, as DEV, when the notebook ends (`models.reports.notebook_import`)."""
from models.io.storage import cohort_reference, file_sha256
from models.io.tracking import TrainingRun
cohort = cohort_reference(self.lineage(), file_sha256(self.cohort_path))
+4
View File
@@ -29,6 +29,10 @@ def _fresh(function):
def build_driver(queries: CohortQueries) -> driver.Driver:
"""The chain for the cohort's rules, in their order."""
rules = list(queries.rules)
if not rules: # a cohort without rules (`cacu/cohorte_total`): everyone with an index
nodes = [all_patients, indexed, inject(last=source("indexed"))(_fresh(study_population)),
inject(populations=value([]), rules=value([]))(_fresh(attrition))]
return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build()
previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]]
nodes = [
all_patients,
+3 -2
View File
@@ -20,8 +20,9 @@ import pyarrow as pa
from hamilton import ad_hoc_utils, driver
from models.io.contracts import CohortQueries
from models.io.lineage import matches, require_match
from models.io.storage import cohort_path, dbt_build_path, latest_dbt_build, read_metadata, write_once
from models.io.lineage import matches
from models.io.storage import (cohort_path, dbt_build_path, latest_dbt_build, read_metadata, require_match,
write_once)
from models.pipelines.cohort_build import build_cohort
from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage
+3 -3
View File
@@ -1,7 +1,7 @@
"""Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`).
The estimate's metadata carries everything the batch needs: the model version and its run (`modelo_nombre`,
`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome and its horizon, and the cohort build it scored. A batch
`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome, and the cohort build it scored; each row carries its horizon. A batch
points to its build by `armado_id`, so only builds with a row in `cohorte_armado` can be stored. Storing the same
estimate again adds nothing: Persistance finds the batch by its content.
"""
@@ -15,7 +15,7 @@ from models.io.storage import read_metadata, store_risk_batch
from models.steps.risks import risk_rows
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
REQUIRED = (*PROVENANCE, "desenlace", "horizonte_anios", COHORT_SOURCE_TAG, COHORT_BUILD_TAG)
REQUIRED = (*PROVENANCE, "desenlace", COHORT_SOURCE_TAG, COHORT_BUILD_TAG)
def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
@@ -26,6 +26,6 @@ def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
if metadata[COHORT_SOURCE_TAG] != "kit":
raise LookupError(f"{estimate_path} scores {metadata[COHORT_SOURCE_TAG]} build {metadata[COHORT_BUILD_TAG]}, "
"which has no row in cohorte_armado for its batch to point to")
rows = risk_rows(pd.read_parquet(estimate_path), float(metadata["horizonte_anios"]))
rows = risk_rows(pd.read_parquet(estimate_path))
return store_risk_batch(domain, int(metadata[COHORT_BUILD_TAG]), {key: metadata[key] for key in PROVENANCE},
metadata["desenlace"], rows)
+9
View File
@@ -0,0 +1,9 @@
"""Reports: notebooks run on a build's file, rendered and kept in MLflow, using `models.io` to read the build and record
the run.
rendering.py a notebook to a self-contained HTML page (Quarto or Jupyter), and what identifies its content
eda.py the exploratory notebook of a scenario, as a report run
experiment.py a notebook uploaded to the platform, run on a build's file as a run of `<domain>-<scenario>/experimentos`
notebook_jobs.py where that notebook runs: its job folder and the executors (local, or the runner container)
notebook_import.py what the notebook trained in its own store, copied into the platform's MLflow as DEV
"""
@@ -1,7 +1,7 @@
"""An exploratory notebook as an MLflow report: run on a build's file, rendered with Quarto, kept as artifacts.
Each notebook is an experiment, `<domain>-<scenario>/<notebook>` (`cacu-cin2_logistic/01_eda`), and each report a run
in it, tagged with the notebook's content hash and the build's file (`models.io.lineage.cohort_reference`). Its
in it, tagged with the notebook's content hash and the build's file (`models.io.storage.cohort_reference`). Its
artifacts are the rendered page (`report/`) and the notebook without outputs (`notebook/`). A notebook and a file that
were already reported together are not rendered again.
@@ -15,11 +15,10 @@ from pathlib import Path
from mlflow import MlflowClient
from models.io.lineage import cohort_reference, file_sha256, registered_name
from models.io.rendering import render_notebook
from models.io.storage import read_metadata
from models.io.lineage import registered_name
from models.io.storage import cohort_reference, file_sha256, read_metadata
from models.io.tracking import find_run, record_report
from models.steps.report import notebook_sha256, without_outputs
from models.reports.rendering import notebook_sha256, render_notebook, without_outputs
COHORT_FILE_ENV = "COHORT_FILE"
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report"
@@ -7,9 +7,9 @@ the page with its outputs (`report/`), what was imported from it (`importado.jso
`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.io.notebook_jobs`) with the build's file as its only data and
The notebook runs in a job folder of its own (`models.reports.notebook_jobs`) with the build's file as its only data and
an MLflow store of its own; what it trained is copied into the platform's MLflow as DEV afterwards
(`models.io.notebook_import`). Where it runs is the executor's: the runner container, with no network and no view
(`models.reports.notebook_import`). Where it runs is the executor's: the runner container, with no network and no view
of the server's files, or this process for development.
"""
@@ -26,13 +26,13 @@ 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, \
cohort_reference, file_sha256, 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, \
registered_name
from models.reports.notebook_import import import_job
from models.reports.notebook_jobs import JOB_TIMEOUT, JOB_TIMEOUT_ENV, PAGE_FILE, executor, prepare_job, read_job_file, \
result_of
from models.io.storage import read_metadata
from models.io.storage import cohort_reference, file_sha256, read_metadata
from models.io.tracking import MODEL_PATH, experiment_id, run_file, run_files
from models.steps.report import notebook_sha256, without_outputs
from models.reports.rendering import notebook_sha256, without_outputs
EXPERIMENT_SUFFIX = "experimentos"
KIND_TAG, KIND = "experiment", "notebook"
@@ -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.io.notebook_jobs import STORE_FILE, JobError, inside, read_job_file
from models.reports.notebook_jobs import STORE_FILE, JobError, inside, read_job_file
from models.io.tracking import MODEL_PATH, experiment_id
NOTEBOOK_RUN_TAG = "notebook.run_id"
@@ -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.io.notebook_import`).
(`models.reports.notebook_import`).
Executors are classes in `EXECUTORS`: `local` runs the job in this process, unsandboxed, for development;
`contenedor` leaves it in `NOTEBOOK_JOBS_DIR` for the runner container (`python -m models notebooks serve`), which
@@ -26,7 +26,7 @@ from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any
from models.io.rendering import CELL_TIMEOUT_ENV, RenderError, renderer, with_kernel
from models.reports.rendering import CELL_TIMEOUT_ENV, RenderError, renderer, with_kernel
from models.notebook import COHORT_FILE_ENV, DOMAIN_ENV, MODEL_PATH_ENV, SCENARIO_ENV, VERSION_ENV
JOBS_DIR_ENV = "NOTEBOOK_JOBS_DIR"
@@ -1,4 +1,5 @@
"""Runs a notebook and renders it to a self-contained HTML page.
"""Runs a notebook, renders it to a self-contained HTML page, and identifies its content by its cells' sources, without
outputs or execution counts.
Two renderers, one class each in `RENDERERS`: `quarto`, and `jupyter`, which runs the cells with `nbclient` and
exports the page with `nbconvert` (the `notebooks` extra), so it needs nothing outside Python. `NOTEBOOK_RENDERER`
@@ -12,6 +13,8 @@ cohort folder and a build's file. Quarto writes next to its input, so the notebo
first and the source folder is left untouched.
"""
import copy
import hashlib
import json
import os
import shutil
@@ -82,6 +85,9 @@ class QuartoRenderer(NotebookRenderer):
return page.read_text()
HIDE_INPUT_TAG = "remove_input" # what a `#| echo: false` cell gets before the page is exported
@register_renderer
class JupyterRenderer(NotebookRenderer):
"""The kernel is the one the notebook names, which must be installed beside this package (`python3` is this
@@ -118,7 +124,18 @@ class JupyterRenderer(NotebookRenderer):
@staticmethod
def _page(exporter, node) -> str:
body, _ = exporter(embed_images=True).from_notebook_node(node)
"""The page, without the code of the cells that ask for it as Quarto does (`#| echo: false`), so a notebook
renders the same with either renderer."""
from nbconvert.preprocessors import TagRemovePreprocessor
for cell in node.cells:
if cell.cell_type == "code" and any(line.replace(" ", "") == "#|echo:false" for line in cell.source.splitlines()):
tags = cell.metadata.setdefault("tags", [])
if HIDE_INPUT_TAG not in tags:
tags.append(HIDE_INPUT_TAG)
page = exporter(embed_images=True)
page.register_preprocessor(TagRemovePreprocessor(remove_input_tags={HIDE_INPUT_TAG}, enabled=True), enabled=True)
body, _ = page.from_notebook_node(node)
return body
@@ -150,3 +167,19 @@ def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, s
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(page)
return output
def without_outputs(notebook: dict) -> dict:
"""The notebook as written: code cells keep their source and lose their outputs."""
cleared = copy.deepcopy(notebook)
for cell in cleared["cells"]:
if cell["cell_type"] == "code":
cell["outputs"], cell["execution_count"] = [], None
return cleared
def notebook_sha256(notebook: dict) -> str:
"""Changes when a cell's type or source changes, not when the notebook is run again."""
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
for cell in notebook["cells"]]
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()
+67
View File
@@ -0,0 +1,67 @@
"""The notebooks kept in the code, ready to run from the platform: `models/<domain>/<scenario>/notebooks/*.ipynb`.
A template's id is `<domain>/<scenario>/<name>` (its file without `.ipynb`). It runs like an uploaded notebook
(`models.reports.experiment`), on a build's file and for a scenario: the one of its folder, or any other whose dataflow
lists a module of that folder's package (the PIM report serves `cin2_pim`, `cin2_pim_post_colposcopy` and
`cin2_pim_post_treatment`). Only files under that layout are read: an id that names anything else is refused.
"""
import json
import re
import tomllib
from pathlib import Path
from models.io.lineage import DOMAINS
from models.reports.experiment import check_notebook
ROOT = Path(__file__).resolve().parent.parent
FOLDER = "notebooks"
TEMPLATE_ID = re.compile(r"(?P<domain>[a-z]+)/(?P<scenario>[\w-]+)/(?P<name>[\w.-]+)")
def _modules(domain: str) -> dict[str, list[str]]:
"""Each scenario of `domain` and the modules its `model.toml` lists."""
found = {}
for toml in sorted((ROOT / domain).glob("*/model.toml")):
found[toml.parent.name] = list(tomllib.loads(toml.read_text()).get("modules", []))
return found
def notebook_templates(domain: str | None = None) -> list[dict]:
"""Every template, by domain and folder: `id`, `domain`, `scenario` (its folder), `name`, `scenarios` (those it
can run for) and `title` (its first heading, else its name)."""
found = []
for dom in ([domain] if domain else sorted(DOMAINS)):
if dom not in DOMAINS:
raise ValueError(f"dominio desconocido: {dom!r}")
modules = _modules(dom)
for path in sorted((ROOT / dom).glob(f"*/{FOLDER}/*.ipynb")):
scenario, package = path.parent.parent.name, f"models.{dom}.{path.parent.parent.name}."
serves = sorted(s for s, mods in modules.items() if s == scenario or any(m.startswith(package) for m in mods))
found.append({"id": f"{dom}/{scenario}/{path.stem}", "domain": dom, "scenario": scenario, "name": path.stem,
"scenarios": serves, "title": _title(path) or path.stem})
return found
def _title(path: Path) -> str | None:
try:
cells = json.loads(path.read_text()).get("cells", [])
except (OSError, json.JSONDecodeError):
return None
for cell in cells:
if cell.get("cell_type") == "markdown":
for line in "".join(cell.get("source", "")).splitlines():
if line.startswith("#"):
return line.lstrip("#").strip()
return None
def template_notebook(template_id: str) -> tuple[str, dict]:
"""(name, notebook) of a template; `LookupError` if there's no such template, `ValueError` if the id isn't one."""
match = TEMPLATE_ID.fullmatch(template_id or "")
if not match or match["domain"] not in DOMAINS:
raise ValueError(f"plantilla inválida: {template_id!r}")
path = (ROOT / match["domain"] / match["scenario"] / FOLDER / f"{match['name']}.ipynb").resolve()
if ROOT not in path.parents or not path.is_file():
raise LookupError(f"no hay plantilla {template_id!r}")
return match["name"], check_notebook(json.loads(path.read_text()))
+1 -1
View File
@@ -6,7 +6,7 @@ import pandas as pd
import pyarrow as pa
from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame
from models.io.lineage import table_sha256
from models.io.storage import table_sha256
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
TIMELINE = [name for name in SCHEMA.names if name != "fecha_indice"]
+214
View File
@@ -0,0 +1,214 @@
"""Each scenario's index and its rules, over a cohort's long frame (`COHORT_SCHEMA`), usually `cacu/cohorte_total`.
A cohort gives every patient's events; a scenario says from when it predicts (the index) and who is out given that
index. `[config.index]` of its `model.toml` names the kind and its rules. A scenario that lists this module gets its
source cohort as `source_cohort`; the node `cohort` gives that frame re-indexed (`fecha_indice` is the scenario's)
with only the members left, and `index_attrition` how many each step leaves. The recruitment window is the source
cohort's (its build's parameters), unless the config sets one. The rules are dbt's (`Transformation/models/cacu/cohorts/`, `macros/cacu_post_colposcopy.sql`), in the same
order and with the same names, so the two can be compared before either is retired.
Kinds:
- `primera_citologia` (surveillance): the first cytology sample, if it falls in the window; out: a biopsy with the
outcome before the index (`prior_event`), an index sample with no cytology or HPV result (`no_index_result`).
- `post_colposcopia` (visit `visita`): the first colposcopy's episode, its result known at the last report of the
biopsies ordered that day (PROVISIONAL: without a biopsy order it is below CIN2, which assumes the colposcopic
impression misses no CIN2+); index at that result (`visita = 0`) or at the k-th cytology sample after it, before any
later colposcopy; out, in order: `biopsia_sin_resultado`, `cin2_hasta_el_indice`, `antecedente_cacu`,
`histerectomia`, `tratamiento_previo`, `sin_referencia`, `sin_cotest` (k ≥ 1).
- `primera_biopsia_invasora` (CaMa survival): the first biopsy report graded in `event_grades` (`CARCINOMA_INVASOR`),
if it falls in the window; out, in order: `sin_nacimiento` (no birth date, so no age), `defuncion_hasta_el_indice`
(a death on or before the index, which leaves no time to the event).
Every kind ends with `observacion_previa_insuficiente`: out if the days observed before the index are fewer than
`observacion_previa_minima_dias` (default 0, so nobody; owner, 2026-11-20). The data are left-truncated: a rule on
earlier events ("no CIN2+ before the index", "first colposcopy", the referral year) reads only what was recorded, so
"none before" means "none observed". The rules are kept as written; raising the threshold when the population starts
with enough history makes them valid without changing code. Observation starts, for now, at the patient's first
event in the frame (the platform's `periodo_observacion` doesn't reach the pipeline).
A scenario without `[config.index]` keeps its cohort's own index.
"""
import json
from collections import defaultdict
from datetime import date
import pandas as pd
RESULT_TYPES = ("bethesda", "glandular", "vph")
POST_COLPOSCOPY_RULES = ("biopsia_sin_resultado", "cin2_hasta_el_indice", "antecedente_cacu", "histerectomia",
"tratamiento_previo", "sin_referencia", "sin_cotest")
def _key(e: dict) -> tuple:
return e["fuente_tabla"], e["fuente_id"]
def _in_window(fecha: date, index: dict) -> bool:
start, end = index.get("recruitment_start"), index.get("recruitment_end")
return (start is None or fecha >= date.fromisoformat(start)) and (end is None or fecha < date.fromisoformat(end))
def _results(events: list[dict], sample: dict) -> dict:
"""The sample's Bethesda, glandular and HPV codes (first non-null of each)."""
return {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and _key(e) == _key(sample)
and e["valor_codigo"] is not None), None) for t in RESULT_TYPES}
def _first_cytology(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
"""The surveillance index and, per rule, whether it flags the patient."""
samples = sorted((e for e in events if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"]))
if not samples or not _in_window(samples[0]["fecha"], index):
return None, []
sample, grades = samples[0], set(index["event_grades"])
found = _results(events, sample)
return sample["fecha"], [
("prior_event", any(e["tipo"] == "biopsia" and e["fecha"] < sample["fecha"] and e["valor_codigo"] in grades
for e in events)),
("no_index_result", all(v is None for v in found.values())),
]
def _colposcopy_episode(events: list[dict]) -> dict | None:
"""The first colposcopy, when its result is known and how many of that day's biopsy orders have no report."""
colposcopies = sorted((e for e in events if e["tipo"] == "colposcopia"),
key=lambda e: (e["fecha"], e["fuente_tabla"], e["fuente_id"]))
if not colposcopies:
return None
first = colposcopies[0]
orders = {_key(e) for e in events if e["tipo"] == "orden_biopsia" and e["fecha"] == first["fecha"]}
reports = [e for e in events if e["tipo"] == "biopsia" and _key(e) in orders]
return {"colposcopy": first, "result_date": max((e["fecha"] for e in reports), default=first["fecha"]),
"unreported_orders": len(orders - {_key(e) for e in reports})}
def _surveillance_visits(events: list[dict], episode: dict) -> list[dict]:
"""The cytology samples after the colposcopy's result is known, before any later colposcopy, in order."""
result = episode["result_date"]
closing = min((e["fecha"] for e in events if e["tipo"] == "colposcopia" and e["fecha"] > result), default=None)
return sorted((e for e in events if e["tipo"] == "citologia" and e["fecha"] > result
and (closing is None or e["fecha"] < closing)), key=lambda e: (e["fecha"], e["fuente_id"]))
def _post_colposcopy(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
"""The index of visit `index["visita"]` and, per rule, whether it flags the patient."""
k = int(index["visita"])
episode = _colposcopy_episode(events)
if episode is None:
return None, []
if k == 0:
sample, fecha = None, episode["result_date"]
else:
visits = _surveillance_visits(events, episode)
if len(visits) < k:
return None, []
sample, fecha = visits[k - 1], visits[k - 1]["fecha"]
if not _in_window(fecha, index):
return None, []
grades, hysterectomy = set(index["event_grades"]), set(index["hysterectomy_cie"])
colposcopy, lookback = episode["colposcopy"]["fecha"], int(index["referral_lookback_days"])
def up_to(test):
return any(e["fecha"] <= fecha and test(e) for e in events)
flags = [
("biopsia_sin_resultado", episode["unreported_orders"] > 0),
("cin2_hasta_el_indice", up_to(lambda e: e["tipo"] == "biopsia" and e["valor_codigo"] in grades)),
("antecedente_cacu", up_to(lambda e: e["tipo"] == "antecedente")),
("histerectomia", up_to(lambda e: e["tipo"] == "nota_medica" and e["valor_codigo"] in hysterectomy)),
("tratamiento_previo", up_to(lambda e: e["tipo"] == "tratamiento")),
("sin_referencia", not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None
and 0 <= (colposcopy - e["fecha"]).days <= lookback for e in events)),
]
if k >= 1:
found = _results(events, sample)
flags.append(("sin_cotest", found["vph"] is None or (found["bethesda"] is None and found["glandular"] is None)))
return fecha, flags
def _first_invasive_biopsy(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
"""The CaMa survival index and, per rule, whether it flags the patient."""
grades = set(index["event_grades"])
reports = sorted((e for e in events if e["tipo"] == "biopsia" and e["valor_codigo"] in grades),
key=lambda e: (e["fecha"], e["fuente_id"]))
if not reports or not _in_window(reports[0]["fecha"], index):
return None, []
fecha = reports[0]["fecha"]
return fecha, [
("sin_nacimiento", not any(e["tipo"] == "nacimiento" for e in events)),
("defuncion_hasta_el_indice", any(e["tipo"] == "defuncion" and e["fecha"] <= fecha for e in events)),
]
KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposcopy,
"primera_biopsia_invasora": _first_invasive_biopsy}
def _events(cohort: pd.DataFrame) -> dict[int, list[dict]]:
events = defaultdict(list)
for e in cohort.to_dict("records"):
events[int(e["pac_id"])].append(e)
return events
def _prior_days(rows: list[dict], fecha: date) -> int:
"""Days observed before the index: from the patient's first event in the frame."""
return (fecha - min(e["fecha"] for e in rows)).days
def _indexed_members(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
"""(members, attrition): one row per member (`pac_id`, `fecha_indice`), and how many are left after the index and
after each rule, in order; each rule is charged only for those it removes from what it receives."""
rule, minimum = KINDS[index["kind"]], int(index.get("observacion_previa_minima_dias", 0))
events = _events(cohort)
found = {}
for pac_id, rows in sorted(events.items()):
fecha, flags = rule(rows, index)
if fecha is not None:
flags = [*flags, ("observacion_previa_insuficiente", _prior_days(rows, fecha) < minimum)]
found[pac_id] = (fecha, flags)
left = {pac_id: flags for pac_id, (fecha, flags) in found.items() if fecha is not None}
attrition = [("pacientes", len(found)), ("indexed", len(left))]
names = [name for name, _ in next(iter(left.values()), [])]
for position, name in enumerate(names):
left = {pac_id: flags for pac_id, flags in left.items() if not flags[position][1]}
attrition.append((name, len(left)))
members = pd.DataFrame([(pac_id, found[pac_id][0]) for pac_id in left], columns=["pac_id", "fecha_indice"])
return members, attrition
def _with_window(cohort_lineage: dict, index: dict) -> dict:
"""The index config with the source cohort's recruitment window (its build's `parametros`), unless the config
sets its own: the window lives once, in the cohort's dbt vars."""
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
return {**{k: parameters[k] for k in ("recruitment_start", "recruitment_end") if k in parameters}, **index}
def cohort(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> pd.DataFrame:
"""The source cohort's long frame re-indexed by the scenario (`[config.index]`): only its members, each with the
scenario's `fecha_indice`. Without an index config, the source cohort as it is."""
if not index:
return source_cohort
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
return (source_cohort.drop(columns="fecha_indice").merge(members, on="pac_id")[list(source_cohort.columns)]
.reset_index(drop=True))
def index_attrition(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> list:
"""How many are left after the scenario's index and each of its rules; empty without an index config."""
return _indexed_members(source_cohort, _with_window(cohort_lineage, index))[1] if index else []
def prior_observation(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> dict:
"""How much history the scenario's members had before their index (aggregates only): how many, how many with
under a year, and the median days. Shows the weight of left truncation while the threshold is 0."""
if not index:
return {}
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
events = _events(source_cohort)
days = pd.Series([_prior_days(events[int(p)], f) for p, f in members.itertuples(index=False)], dtype=float)
return {"members": len(days), "under_365_days": int((days < 365).sum()),
"median_days": None if days.empty else float(days.median()),
"threshold_days": int(index.get("observacion_previa_minima_dias", 0))}
+127
View File
@@ -0,0 +1,127 @@
"""Fitting a classifier on labelled members and measuring it: the steps every scenario shares.
A scenario's own module produces `labelled_members` (one row per member whose outcome is known, its predictors and
the outcome) and the driver passes both modules to `with_modules`, with `predictor_columns`, `train_fraction` and the
`classifier` config. Each node is named after what it produces. No node reads, writes or logs: registering the result
is a saver's job.
The routines' records (ML-01a) a classifier leaves are here too: `analytic_method`, `class_balance` and
`output_confidence`, and `routines`, which gathers them with the scenario's own `sampling` and `missing_data` under the
kinds the registry checks before promoting.
The classifier is chosen by config: `@config.when(classifier=...)` picks one `prefit_classifier`, so another
classifier is one more function here and no change to any scenario.
"""
import pandas as pd
from hamilton.function_modifiers import config, extract_fields
from sklearn.base import ClassifierMixin, clone
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
SPLIT_ORDER = ("fecha_indice", "pac_id")
PROBABILITY = "probabilidad"
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float, target_column: str = "y",
split_order: tuple = SPLIT_ORDER) -> dict:
"""The oldest members by `split_order` train and the newest test: a model is judged on cases later than the ones
it learned from, never on a shuffled mix."""
if target_column not in labelled_members.columns:
raise ValueError(f"labelled_members has no {target_column!r} column")
ordered = labelled_members.sort_values(list(split_order), kind="stable")
cut = int(len(ordered) * train_fraction)
return {"train_set": ordered.iloc[:cut], "test_set": ordered.iloc[cut:]}
def encoder(predictor_columns: list[str]) -> ColumnTransformer:
"""One-hot predictors; a category not seen in training counts as none of the known ones."""
return ColumnTransformer([("predictors", OneHotEncoder(handle_unknown="ignore"), list(predictor_columns))])
@config.when(classifier="logistic")
def prefit_classifier__logistic(max_iter: int = 1000) -> ClassifierMixin:
"""An unfitted logistic regression."""
return LogisticRegression(max_iter=max_iter)
def fitted_pipeline(encoder: ColumnTransformer, prefit_classifier: ClassifierMixin, train_set: pd.DataFrame,
predictor_columns: list[str], target_column: str = "y") -> Pipeline:
"""The encoder and the classifier fitted on `train_set`. Fits copies, so the prefit nodes stay unfitted."""
pipeline = Pipeline([("encode", clone(encoder)), ("classify", clone(prefit_classifier))])
return pipeline.fit(train_set[list(predictor_columns)], train_set[target_column])
def test_probabilities(fitted_pipeline: Pipeline, test_set: pd.DataFrame, predictor_columns: list[str]) -> pd.Series:
"""The probability of the outcome for each row of `test_set`."""
return pd.Series(fitted_pipeline.predict_proba(test_set[list(predictor_columns)])[:, 1], index=test_set.index,
name=PROBABILITY)
def auc(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
"""Area under the ROC curve on `test_set`; undefined (an error) when the test set has a single class."""
return float(roc_auc_score(test_set[target_column], test_probabilities))
def brier_score(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
return float(brier_score_loss(test_set[target_column], test_probabilities))
def positive_rate_train(train_set: pd.DataFrame, target_column: str = "y") -> float:
return float(train_set[target_column].mean())
def positive_rate_test(test_set: pd.DataFrame, target_column: str = "y") -> float:
return float(test_set[target_column].mean())
def mean_probability_test(test_probabilities: pd.Series) -> float:
return float(test_probabilities.mean())
def metrics(auc: float, brier_score: float, train_set: pd.DataFrame, test_set: pd.DataFrame,
positive_rate_train: float, positive_rate_test: float, mean_probability_test: float) -> dict:
"""What a training run records: aggregates only, no patient data. The keys are the names MLflow keeps."""
return {"auc": auc, "brier": brier_score, "n_train": len(train_set), "n_test": len(test_set),
"positive_rate_train": positive_rate_train, "positive_rate_test": positive_rate_test,
"mean_probability_test": mean_probability_test}
def analytic_method(fitted_pipeline: Pipeline) -> dict:
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
classifier = fitted_pipeline.named_steps["classify"]
features = fitted_pipeline.named_steps["encode"].get_feature_names_out()
return {"method": "regresión logística sobre los predictores codificados one-hot",
"estimator": type(classifier).__name__, "settings": classifier.get_params(),
"intercept": float(classifier.intercept_[0]),
"coefficients": dict(zip(map(str, features), map(float, classifier.coef_[0])))}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame, fitted_pipeline: Pipeline) -> dict:
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
weight = fitted_pipeline.named_steps["classify"].class_weight
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
"train": {str(k): int(v) for k, v in train_set["y"].value_counts().sort_index().items()},
"test": {str(k): int(v) for k, v in test_set["y"].value_counts().sort_index().items()}}
def output_confidence(test_set: pd.DataFrame, test_probabilities: pd.Series, calibration_bins: int = 10) -> dict:
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by tenths."""
bins = pd.qcut(test_probabilities, q=min(calibration_bins, test_probabilities.nunique()), duplicates="drop")
table = pd.DataFrame({"p": test_probabilities, "y": test_set["y"]}).groupby(bins, observed=True).agg(
n=("y", "size"), mean_probability=("p", "mean"), observed_rate=("y", "mean"))
return {"method": "calibración en la prueba: probabilidad media contra frecuencia observada, por cuantiles",
"brier": float(brier_score_loss(test_set["y"], test_probabilities)),
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.mean_probability),
"observed_rate": float(row.observed_rate)} for interval, row in table.iterrows()]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
-21
View File
@@ -1,21 +0,0 @@
"""What identifies a notebook's content: its cells' sources, without outputs or execution counts."""
import copy
import hashlib
import json
def without_outputs(notebook: dict) -> dict:
"""The notebook as written: code cells keep their source and lose their outputs."""
cleared = copy.deepcopy(notebook)
for cell in cleared["cells"]:
if cell["cell_type"] == "code":
cell["outputs"], cell["execution_count"] = [], None
return cleared
def notebook_sha256(notebook: dict) -> str:
"""Changes when a cell's type or source changes, not when the notebook is run again."""
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
for cell in notebook["cells"]]
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()
+8 -6
View File
@@ -1,13 +1,15 @@
"""From an estimate's rows to the risks a batch stores: `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`."""
"""From an estimate's rows to the risks a batch stores: `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo,
ic_alto)`; `fecha_indice` is the model's index date for the member, which its horizons count from."""
import pandas as pd
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
"""One risk per member at the model's horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a
member scored twice or a probability outside 0..1 stops the batch."""
def risk_rows(estimate: pd.DataFrame) -> list[tuple]:
"""One risk per member and horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a member scored
twice at one horizon or a probability outside 0..1 stops the batch."""
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
return [(int(pac_id), float(horizon_years), float(probability), None, None)
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]
return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), None, None)
for pac_id, fecha, horizon, probability in zip(estimate["pac_id"], estimate["fecha_indice"],
estimate["horizonte_anios"], estimate["probabilidad"])]
+1
View File
@@ -0,0 +1 @@
"""TEA's models: the EEG analysis (`eeg`)."""
+6
View File
@@ -0,0 +1,6 @@
"""TEA's EEG analysis: the `tea` library run on one stored EDF, without the database.
`settings.py` maps each metric to a library feature (`model.toml`); `analyze.py` measures one EEG; `baselines.py`
compares a value with its promoted age baseline. Reading the EDFs and writing the results back to bronze is
`models.eeg_analysis` (`python -m models tea analyze`).
"""
+273
View File
@@ -0,0 +1,273 @@
"""One EEG through the `tea` library: validation, then preprocessing, the processes and the metrics' biomarkers.
`measure` is the unit of work of a batch and may run on a Dask worker: it takes the EDF's bytes and the age the
patient's rows give, touches no database and returns a `Measurement` with the verdict, every quality check and each
metric's raw value. The deviation from the age baselines is added afterwards (`baselines.py`), where the registered
models are.
The age is the EDF header's (recording start minus birth date) when the header has both, and the rows' otherwise:
the file is written when the study is recorded, the rows' birth date may be missing or mistyped.
The library reads EDFs from paths only, so the bytes go to a temporary file for the duration of the call.
"""
import logging
import re
import tempfile
import time
from dataclasses import dataclass, field
from pathlib import Path
from types import SimpleNamespace
from models.tea.eeg.settings import Settings
log = logging.getLogger(__name__)
# Channel codes the library builds from the reason's first words, and the fixed code each is stored as.
CHANNEL_CODES = {"intermittent-contact-by": "intermittent-bursts"}
# Header and rows further apart than this, in months, are logged.
AGE_DISAGREEMENT_MONTHS = 1.0
@dataclass(frozen=True)
class Check:
code: str
electrode: str | None
value: float | None
text: str | None
unit: str | None
low: float | None
high: float | None
decisive: bool
abnormal: bool
@dataclass(frozen=True)
class MetricValue:
code: str
value: float | None
electrodes: dict[str, float | None] = field(default_factory=dict)
@dataclass(frozen=True)
class Measurement:
key: str
age_months: float | None # the age the study was analysed at
plan_hash: str
versions: str
valid: int | None = None
level: str | None = None
clean_fraction: float | None = None
bad_channels: int | None = None
line_db: float | None = None
channels: int | None = None
duration_min: float | None = None
asleep: int | None = None
checks: tuple[Check, ...] = ()
metrics: tuple[MetricValue, ...] = ()
error: str | None = None
seconds: float = 0.0
def pipeline(settings: Settings):
from tea.pipeline import Pipeline
return Pipeline.default(impl=settings.impl)
def plan(settings: Settings) -> dict:
from tea.preprocessing import PLANS
return PLANS[settings.plan].to_dict()
def phase_detector(pipe, phase: str):
base = pipe.module("spindle_detection")
return type(base)(variant=base.variant, phase=phase)
def processes(pipe, settings: Settings) -> list[str]:
"""The processes the metrics need, in dependency order. Spindle detection itself runs once per sleep stage, so
the phased biomarkers contribute only what their stage's detector requires."""
from tea.pipeline.run_study import order_for
needs = [n for m in settings.metrics if not m.phase for n in (m.biomarker, m.electrodes) if n]
requires = {r for n in needs for r in pipe.module(n).requires}
for phase in settings.phases:
requires.update(phase_detector(pipe, phase).requires)
return order_for(["metrics"], {**pipe.modules, "metrics": SimpleNamespace(requires=tuple(sorted(requires)))})
def versions(pipe, settings: Settings) -> str:
"""What produced an analysis, as `name=version;...`: a new version of any module analyses every EEG again."""
names = ["validation", "preprocessing", *processes(pipe, settings)]
if settings.phases:
names.append("spindle_detection")
names += settings.biomarkers
return ";".join(f"{n}={getattr(pipe.module(n), 'version', '?')}" for n in dict.fromkeys(names))
def criterion_code(code: str, text: str, electrode: str | None) -> str:
"""The library's channel codes are the first words of the reason, numbers included (`amplitude-4.5-x`)."""
if electrode is None:
return code
if code.startswith("amplitude"):
return "aux-amplitude" if "out of range" in text else "amplitude"
return CHANNEL_CODES.get(code, code)
def _number(value) -> float | None:
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if number == number else None
def checks(validation, run: dict) -> tuple[Check, ...]:
out = []
for c in validation.checks_of(run):
text = c.value if isinstance(c.value, str) else None
out.append(Check(
code=criterion_code(c.code, c.display, c.electrode), electrode=c.electrode,
value=None if text is not None else _number(c.value), text=text, unit=c.unit or None,
low=_number(c.low), high=_number(c.high), decisive=bool(c.decisive), abnormal=bool(c.abnormal),
))
return tuple(out)
def gate_reasons(summary, plan: dict) -> list[str]:
"""The plan's gates on top of the validator's verdict, as the library's own batch applies them."""
reasons = list(summary.extra.get("reasons", []))
gates = plan.get("gates", {})
if gates.get("skip_no_analizable", True) and summary.level == "no_analizable" and not reasons:
reasons.append("triage level no_analizable")
least = gates.get("min_clean")
if least is not None and summary.clean_fraction == summary.clean_fraction and summary.clean_fraction < least:
reasons.append(f"plan gate: {100 * summary.clean_fraction:.0f}% clean < {100 * least:.0f}%")
return reasons
Features = dict[tuple[str, str | None], dict[str, float | None]]
def features(pipe, study, settings: Settings) -> Features:
"""Every feature of each biomarker the metrics read, by biomarker and sleep stage (`None`: no stage), with
spindle detection run once per stage."""
by_phase = {None: study}
for phase in settings.phases:
by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study))
out: Features = {}
for m in settings.metrics:
for biomarker in (m.biomarker, m.electrodes):
if biomarker and (biomarker, m.phase) not in out:
out[biomarker, m.phase] = {k: _number(v) for k, v in
pipe.module(biomarker).measure(by_phase[m.phase]).items()}
return out
def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]:
out = []
for m in settings.metrics:
electrodes = {}
if m.electrodes:
electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items()
if name.startswith(m.electrode_prefix)}
out.append(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature), electrodes))
return tuple(out)
def _error(exc: Exception) -> str:
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
return f"{type(exc).__name__}: {message}"
def _study(pipe, path, settings: Settings, the_plan: dict, age_months: float | None, line_hz: float):
"""Validation, then, for a valid study, preprocessing and the processes: (validation run, summary, verdict,
study or None)."""
from tea.contracts import Study
validation = pipe.module("validation")
run = validation.run(path, line_hz=line_hz)
summary = validation.summary_of(run)
valid = int(bool(summary.valid) and not gate_reasons(summary, the_plan))
if not valid:
return run, summary, valid, None
preprocessing = pipe.module("preprocessing")
study = Study(preprocessing.run(path, preprocessing.plan_for(summary, the_plan), age_months=age_months))
for name in processes(pipe, settings):
study = study.with_labels(pipe.module(name).predict(study))
return run, summary, valid, study
def study_age(key: str, path: Path, row_age: float | None, days_per_month: float) -> float | None:
"""The header's age if it has one, else `row_age`. An unreadable header counts as none: validation reports the
file."""
from tea.contracts import header_age_months
try:
header = header_age_months(path, days_per_month=days_per_month)
except Exception: # noqa: BLE001
header = None
if header is None:
return row_age
if row_age is not None and abs(header - row_age) > AGE_DISAGREEMENT_MONTHS:
log.warning("EEG %s: the EDF header gives %.1f months and the patient's rows %.1f; using the header",
key, header, row_age)
return header
def measure(key: str, edf: bytes, age_months: float | None, settings: Settings) -> Measurement:
"""`age_months` is the rows' age, used when the EDF header has none (`study_age`). Never raises: a failure is a
`Measurement` with `error` set, keeping the verdict and checks if validation finished before it."""
started = time.time()
pipe = pipeline(settings)
the_plan = plan(settings)
result = dict(key=key, age_months=age_months, plan_hash=the_plan.get("hash", ""), versions=versions(pipe, settings))
try:
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "study.edf"
path.write_bytes(edf)
result["age_months"] = age = study_age(key, path, age_months, settings.days_per_month)
validation = pipe.module("validation")
run, summary, valid, study = _study(pipe, path, settings, the_plan, age, settings.line_hz)
result.update(
valid=valid, level=summary.level, clean_fraction=_number(summary.clean_fraction),
bad_channels=len(summary.bad_channels), line_db=_number(summary.line_db),
channels=len(run.get("channels", [])) or None,
duration_min=round(run["duration_s"] / 60, 2) if run.get("duration_s") else None,
checks=checks(validation, run),
)
if study is None:
return Measurement(**result, seconds=round(time.time() - started, 1))
asleep = int((study.label("sleep_state").per_window == "sueno").any())
return Measurement(**result, asleep=asleep, metrics=_metrics(features(pipe, study, settings), settings),
seconds=round(time.time() - started, 1))
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop the batch
return Measurement(**result, error=_error(exc), seconds=round(time.time() - started, 1))
@dataclass(frozen=True)
class ReferenceStudy:
"""One study of a reference cohort, measured for training: its age, verdict, and every feature of each
biomarker the metrics read, by biomarker and sleep stage. No path, file name or date."""
key: str
age_months: float
valid: int | None = None
features: Features = field(default_factory=dict)
error: str | None = None
def reference(key: str, path: str, age_months: float, settings: Settings, line_hz: float) -> ReferenceStudy:
"""A reference study read from a local or `s3://` path, at the mains frequency of the cohort's country. Never
raises: a failure is a `ReferenceStudy` with `error` set."""
from tea.pipeline.storage import local_copy
pipe = pipeline(settings)
try:
with local_copy(path) as local:
_, _, valid, study = _study(pipe, local, settings, plan(settings), age_months, line_hz)
measured = features(pipe, study, settings) if study is not None else {}
return ReferenceStudy(key, age_months, valid, measured)
except Exception as exc: # noqa: BLE001 -- one unreadable study must not stop the batch
return ReferenceStudy(key, age_months, error=_error(exc))
+118
View File
@@ -0,0 +1,118 @@
"""The promoted age baselines: a metric's raw value against its curve at the child's age.
Each baseline is a trained `tea` biomarker module registered as `tea-<scenario>` with the `produccion` alias. Without
one in production a metric keeps its raw value and no deviation, the same as a model never configured.
"""
import math
import sys
from dataclasses import dataclass
import numpy as np
from models.io.lineage import registered_name
from models.io.registry import registry as default_registry
@dataclass(frozen=True)
class Deviation:
z: float | None
outside: int | None
p5: float | None
median: float | None
p95: float | None
def _number(value) -> float | None:
try:
number = float(value)
except (TypeError, ValueError):
return None
return number if math.isfinite(number) else None
def _load(model_uri: str):
"""The library's biomarker module of a registered baseline, leaving `sys.path` as it was.
The model bundles a partial copy of `tea` and MLflow puts it first on `sys.path` while loading. Left there, a Dask
worker spawned afterwards inherits it and can't import `tea.pipeline`. The installed `tea` is imported first so
the copy is never the package.
"""
import tea # noqa: F401
from tea.serving import load_biomarker
path = list(sys.path)
try:
return load_biomarker(model_uri)
finally:
sys.path[:] = path
def _feature_baseline(module, feature: str):
baselines = getattr(module, "baselines", None)
return baselines[feature] if baselines is not None else module.baseline
def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]:
"""p5, median and p95 of a centile curve at an age, interpolated on log age as the library's z is; none for a
baseline without a curve or an age outside it."""
curve = getattr(baseline, "curva", None)
if curve is None or age_months is None or age_months <= 0:
return None, None, None
rows = curve.dropna(subset=["p5", "mediana", "p95"])
if not len(rows):
return None, None, None
log_ages = np.log(rows["edad_meses"].to_numpy(float))
at = math.log(age_months)
if not log_ages.min() <= at <= log_ages.max():
return None, None, None
return tuple(_number(np.interp(at, log_ages, rows[c].to_numpy(float))) for c in ("p5", "mediana", "p95"))
class Baselines:
"""Resolves each scenario's production version once per instance, and loads it the first time it is used."""
def __init__(self, domain: str = "tea", registry=default_registry, loader=None):
self.domain = domain
self.registry = registry
self._loader = loader
self._resolved: dict[str, object | None] = {}
self._loaded: dict[str, object] = {}
def _resolve(self, scenario: str):
if scenario not in self._resolved:
try:
self._resolved[scenario] = self.registry.resolve(self.domain, scenario)
except LookupError:
self._resolved[scenario] = None
return self._resolved[scenario]
def label(self, scenario: str) -> str | None:
"""`tea-<scenario>/<version>` of the version in production, or none."""
resolved = self._resolve(scenario)
return f"{registered_name(self.domain, scenario)}/{resolved.version}" if resolved else None
def module(self, scenario: str):
"""The trained biomarker module in production, or none."""
resolved = self._resolve(scenario)
if resolved is None:
return None
if scenario not in self._loaded:
if self._loader is not None:
self._loaded[scenario] = self._loader(resolved.model_uri)
else:
self._loaded[scenario] = _load(resolved.model_uri)
return self._loaded[scenario]
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None) -> Deviation | None:
"""None without a baseline in production; with one, a deviation whose fields are null where the value or
the age is missing or the curve doesn't cover the age."""
module = self.module(scenario)
if module is None:
return None
baseline = _feature_baseline(module, feature)
if value is None or age_months is None:
return Deviation(None, None, None, None, None)
outside, z = baseline.deviation(np.array([value], float), np.array([age_months], float))
z_value = _number(z[0])
p5, median, p95 = centiles(baseline, age_months)
return Deviation(z_value, int(outside[0]) if z_value is not None else None, p5, median, p95)
+205
View File
@@ -0,0 +1,205 @@
"""Trained age baselines as a bundle: exported where they were trained, imported on each platform installation.
What the bundle holds, per scenario: the trained module's saved state (`params.json`, `baseline.json`), which
module it is (`module.json`), the preprocessing plan (`plan.json`), the routine records, the metrics, the
version's promotion tags and its description; and a manifest with each file's SHA-256. Group numbers only: the
library's privacy guard runs over every file before the bundle is written, and refuses a group under 5.
The import checks the manifest, accepts for each scenario only the library module the platform runs for it,
requires the module's hash to match the one recorded where it was trained, and registers it as a new version
with the same tags, routine records and metrics, so the registry's promotion checks read it as trained. A
version already holding that trained module is kept.
"""
import hashlib
import io
import json
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, GIT_COMMIT_TAG, MODEL_SHA_TAG
from models.io.lineage import registered_name
from models.io.tracking import ROUTINES_PATH, experiment_id
from models.tea.eeg import train
from models.tea.eeg.analyze import pipeline
from models.tea.eeg.settings import Settings
FORMAT = 1
MANIFEST = "manifest.json"
# The version tags a bundle carries: what promotion checks and what identifies the trained module. Report links
# and promotion dates belong to each installation.
TAGS = ("domain", "scenario", "environment", MODEL_SHA_TAG, COHORT_URL_TAG, COHORT_SOURCE_TAG, COHORT_BUILD_TAG,
"plan_hash", "module", "module_version", "phase", "baseline")
SOURCE_COMMIT_TAG = "origen.git_commit"
BUNDLE_TAG = "importado.paquete"
EPOCH = (1980, 1, 1, 0, 0, 0) # every zip entry's date, so the same baselines give the same bundle
class BundleError(ValueError):
"""A bundle that can't be exported or imported as it is, with the reason."""
@dataclass(frozen=True)
class Exported:
path: Path
sha256: str
versions: dict[str, str]
def _sha(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def state_sha(folder: Path) -> str:
"""The trained module's hash, as training records it (`train._module_state`): its saved JSON files."""
files = sorted(p for p in Path(folder).glob("*.json") if p.name in ("params.json", "baseline.json"))
return _sha(b"".join(f.name.encode() + f.read_bytes() for f in files))
def _version(client, scenario: str, environment: str, production: bool):
from models.io.registry import PRODUCTION_ALIAS
name = registered_name(train.DOMAIN, scenario)
if production:
try:
return client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except Exception: # noqa: BLE001 -- none in production
return None
return train.latest(scenario, environment)
def export(s: Settings, out: str | Path, *, environment: str = "PROD", production: bool = False) -> Exported:
"""Every scenario's baseline into one bundle at `out`: the version in production with `production`, otherwise
the newest trained in `environment`. Refuses a bundle missing a scenario, or holding something the privacy
guard refuses."""
import mlflow.artifacts
from mlflow import MlflowClient
from tea.serving.privacy import check_files, check_group, check_text
client = MlflowClient()
versions = {scenario: _version(client, scenario, environment, production) for scenario in s.scenarios}
missing = sorted(k for k, mv in versions.items() if mv is None)
if missing:
raise BundleError(f"no {'production' if production else environment} version of {', '.join(missing)}")
manifest = {"formato": FORMAT, "dominio": train.DOMAIN, "escenarios": {}}
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for scenario, mv in versions.items():
folder = root / scenario
module_dir = folder / "module"
module_dir.mkdir(parents=True)
model = Path(mlflow.artifacts.download_artifacts(artifact_uri=f"models:/{mv.name}/{mv.version}",
dst_path=str(root / ".descargas" / scenario)))
saved = next((p.parent for p in model.rglob("module.json") if p.parent.name == "module"), None)
if saved is None:
raise BundleError(f"{scenario} version {mv.version}: its model has no trained module")
for file in ("params.json", "baseline.json", "module.json", "plan.json"):
if not (saved / file).exists():
raise BundleError(f"{scenario} version {mv.version}: its trained module has no {file}")
(module_dir / file).write_bytes((saved / file).read_bytes())
if state_sha(module_dir) != mv.tags.get(MODEL_SHA_TAG):
raise BundleError(f"{scenario} version {mv.version}: its saved state isn't the one it was trained with")
routines = folder / ROUTINES_PATH
routines.mkdir()
for item in client.list_artifacts(mv.run_id, ROUTINES_PATH):
local = mlflow.artifacts.download_artifacts(run_id=mv.run_id, artifact_path=item.path,
dst_path=str(root / ".descargas"))
(routines / Path(item.path).name).write_text(Path(local).read_text())
run = client.get_run(mv.run_id)
metrics = dict(run.data.metrics)
tags = {k: mv.tags[k] for k in TAGS if k in mv.tags}
if run.data.tags.get(GIT_COMMIT_TAG):
tags[SOURCE_COMMIT_TAG] = run.data.tags[GIT_COMMIT_TAG]
check_group(module_dir, int(metrics.get("n_referencia", 0)) or None)
files = sorted(p for p in folder.rglob("*") if p.is_file())
manifest["escenarios"][scenario] = {
"version_origen": str(mv.version), "tags": tags, "metricas": metrics,
"descripcion": mv.description or "",
"archivos": {p.relative_to(root).as_posix(): _sha(p.read_bytes()) for p in files},
}
text = json.dumps(manifest, ensure_ascii=False, indent=1, sort_keys=True)
check_text(text)
(root / MANIFEST).write_text(text)
for scenario in versions:
check_files(root / scenario)
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as z:
for p in sorted(q for q in root.rglob("*") if q.is_file() and ".descargas" not in q.parts):
z.writestr(zipfile.ZipInfo(p.relative_to(root).as_posix(), EPOCH), p.read_bytes())
out = Path(out)
out.write_bytes(buffer.getvalue())
return Exported(out, _sha(buffer.getvalue()), {k: str(mv.version) for k, mv in versions.items()})
def _unpack(data: bytes, root: Path) -> dict:
"""The bundle's files under `root`, each checked against the manifest; the manifest."""
with zipfile.ZipFile(io.BytesIO(data)) as z:
names = z.namelist()
for name in names:
path = PurePosixPath(name)
if path.is_absolute() or ".." in path.parts:
raise BundleError(f"the bundle holds a path outside itself: {name}")
if MANIFEST not in names:
raise BundleError("the bundle has no manifest")
manifest = json.loads(z.read(MANIFEST))
if manifest.get("formato") != FORMAT or manifest.get("dominio") != train.DOMAIN:
raise BundleError("not a bundle of TEA's EEG baselines in a format this platform reads")
listed = {f: sha for entry in manifest["escenarios"].values() for f, sha in entry["archivos"].items()}
if set(listed) != set(names) - {MANIFEST}:
raise BundleError("the bundle's files aren't the ones its manifest lists")
for name, sha in listed.items():
content = z.read(name)
if _sha(content) != sha:
raise BundleError(f"{name} changed after the bundle was written")
target = root / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
return manifest
def import_(s: Settings, bundle: str | Path) -> dict[str, tuple[str, bool]]:
"""Registers every baseline of the bundle; by scenario, (version, whether it's new)."""
from mlflow import MlflowClient
from tea.serving import log_biomarker
data = Path(bundle).read_bytes()
bundle_sha = _sha(data)
pipe = pipeline(s)
out = {}
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
manifest = _unpack(data, root)
unknown = sorted(set(manifest["escenarios"]) - set(s.scenarios))
if unknown:
raise BundleError(f"this platform has no scenario {', '.join(unknown)}")
for scenario, entry in manifest["escenarios"].items():
tags = dict(entry["tags"])
module_dir = root / scenario / "module"
sha = state_sha(module_dir)
if sha != tags.get(MODEL_SHA_TAG):
raise BundleError(f"{scenario}: the module isn't the one recorded where it was trained")
biomarker, phase = s.scenarios[scenario]
if tags.get("module") != biomarker or (tags.get("phase") or None) != phase:
raise BundleError(f"{scenario}: the bundle says it's {tags.get('module')}, not {biomarker}")
cls = type(pipe.module(biomarker))
declared = json.loads((module_dir / "module.json").read_text()).get("class")
if declared != f"{cls.__module__}:{cls.__name__}":
raise BundleError(f"{scenario}: the bundle's module class isn't the one this platform runs")
existing = train.find_trained(scenario, {MODEL_SHA_TAG: sha, COHORT_BUILD_TAG: tags.get(COHORT_BUILD_TAG, ""),
"environment": tags.get("environment", "")})
if existing is not None:
out[scenario] = (str(existing.version), False)
continue
module = cls.load(module_dir)
name = registered_name(train.DOMAIN, scenario)
client = MlflowClient()
experiment_id(client, name)
n = int(entry["metricas"].get("n_referencia", 0)) or None
mv = log_biomarker(module, plan=json.loads((module_dir / "plan.json").read_text()), registered_name=name,
run_name=scenario, n_reference=n, experiment=name)
routines = {p.stem: json.loads(p.read_text()) for p in sorted((root / scenario / ROUTINES_PATH).glob("*.json"))}
train.record(client, name, str(mv.version), mv.run_id, tags={**tags, BUNDLE_TAG: bundle_sha},
routines=routines, metrics=entry["metricas"], description=entry["descripcion"])
out[scenario] = (str(mv.version), True)
return out
+61
View File
@@ -0,0 +1,61 @@
"""TEA's EEG baselines as a model of the platform: `python -m models run tea eeg --train [--promote]`.
A baseline isn't trained on a cohort build of the platform but on the reference cohort (`train.py`), so this
scenario runs its own steps (`run_steps`) in place of `run`'s cohort-file ones: training every scenario's baseline,
then promoting each through the registry's checks. `--reference-dir` trains on a folder of EEGs on this machine
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
"""
import argparse
import sys
from models.tea.eeg.settings import settings
SETTINGS = settings()
def run_steps(args: argparse.Namespace) -> int:
from models.io.registry import PRODUCTION_ALIAS, PromotionBlocked, registered_name, registry
from models.tea.eeg import train
if args.export or args.estimate or args.store or args.version:
print("tea/eeg trains on its reference cohort: only --train and --promote apply", file=sys.stderr)
return 2
environment = args.environment.upper()
s = SETTINGS
if getattr(args, "reference_dir", None):
from models.tea.eeg.reference import local
s = local(SETTINGS, folder=args.reference_dir, ages_table=args.reference_ages,
name=args.reference_name or "local", line_hz=args.line_hz or 60.0)
elif getattr(args, "reference_ages", None) or getattr(args, "line_hz", None):
print("--reference-ages and --line-hz go with --reference-dir", file=sys.stderr)
return 2
versions: dict[str, str] = {}
if args.train:
for scenario, (version, new) in train.train_all(s, environment).items():
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
versions[scenario] = version
if not args.promote:
return 0
code = 0
for scenario in SETTINGS.scenarios:
version = versions.get(scenario) or getattr(train.latest(scenario, environment), "version", None)
if version is None:
print(f"{scenario}: no {environment} version to promote; use --train", file=sys.stderr)
code = 1
continue
try:
current = registry.client.get_model_version_by_alias(registered_name("tea", scenario), PRODUCTION_ALIAS)
except Exception: # noqa: BLE001 -- no version in production yet
current = None
if current is not None and str(current.version) == str(version):
print(f"{scenario}: version {version} already in production")
continue
try:
registry.promote("tea", scenario, str(version))
print(f"{scenario}: version {version} promoted")
except PromotionBlocked as blocked:
failed = ", ".join(f"{c.code} ({c.requirement})" for c in blocked.checks if not c.passed)
print(f"{scenario}: version {version} not promoted, missing: {failed}", file=sys.stderr)
code = 1
return code
+52
View File
@@ -0,0 +1,52 @@
# The EEG analysis: the `tea` library's plan and modules, and the library feature each stored metric is.
domain = "tea"
plan = "director-cluster"
impl = "modern"
line_hz = 60.0
# Completed months at the study: days / days_per_month, as the TEA cohort counts them.
days_per_month = 30.4375
# The baselines' kind (the library's: "curves", centile curves on log age; or "age_blocks").
baseline = "curves"
# The reference cohort the age baselines are trained on: the Helsinki HK1K EEGs (public), its EDFs and the table of
# their ages under `prefix` in the cluster's S3, children of `ages` months. Its mains are at `line_hz`.
[reference]
name = "hk1k"
prefix = "raw/eeg-helsinki/"
ages_table = "anon_codex_age_sex.csv"
line_hz = 50.0
ages = [16.0, 36.0]
# One entry per `MetricaEeg` code. `phase` runs spindle detection on that sleep stage alone; `electrodes` names the
# biomarker whose `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode.
# The feature each metric maps to is provisional until the domain expert confirms it.
[[metrics]]
code = "RITMO_POSTERIOR"
biomarker = "posterior_rhythm"
feature = "posterior_rhythm_hz"
[[metrics]]
code = "HUSOS_SUENO_N2"
biomarker = "spindles"
phase = "N2"
feature = "spindle_density_per_min_channel"
electrodes = "spindle_topography"
electrode_prefix = "topo_enh_"
[[metrics]]
code = "HUSOS_SUENO_N3"
biomarker = "spindles"
phase = "N3"
feature = "spindle_density_per_min_channel"
electrodes = "spindle_topography"
electrode_prefix = "topo_enh_"
[[metrics]]
code = "PICOS_PAROXISTICOS"
biomarker = "spikes"
feature = "spike_rate_nrem"
[[metrics]]
code = "GRADIENTE_ANTEROPOSTERIOR"
biomarker = "gradient"
feature = "gradient_delta_sueno"
+62
View File
@@ -0,0 +1,62 @@
"""A reference cohort on the training machine's own disk: the site's EEGs, which never leave it.
`local_studies` lists a folder's EDFs (at any depth) with the age of each child at the recording, within
`[reference] ages`. The age comes from the ages table when one is given (`archivo` and `edad_meses` or `edad_anos`
columns, one row per file name) and from each EDF's header (recording start minus birth date) otherwise. A file with
no age is left out. Paths stay in the listing on this machine; what leaves it is the trained baselines and the
listing's hash (`train.Listing`).
"""
import dataclasses
from pathlib import Path
import pandas as pd
from models.tea.eeg.settings import Settings
LOCAL = "local"
def local(s: Settings, *, folder: str | Path, ages_table: str | Path | None = None, name: str = "local",
line_hz: float = 60.0, ages: tuple[float, float] | None = None) -> Settings:
"""`s` with its reference cohort replaced by a folder on this machine."""
r = dataclasses.replace(s.reference, name=name, storage=LOCAL, prefix=str(Path(folder).resolve()),
ages_table=str(Path(ages_table).resolve()) if ages_table else "", line_hz=float(line_hz),
ages=tuple(ages) if ages else s.reference.ages)
return dataclasses.replace(s, reference=r)
def _table_ages(path: Path) -> dict[str, float]:
"""Age in months by file name, from a CSV with `archivo` and `edad_meses` (or `edad_anos`)."""
table = pd.read_csv(path)
if "archivo" not in table:
raise ValueError(f"{path.name}: the ages table needs an `archivo` column with each EDF's file name")
if "edad_meses" in table:
months = table["edad_meses"].astype(float)
elif "edad_anos" in table:
months = table["edad_anos"].astype(float) * 12
else:
raise ValueError(f"{path.name}: the ages table needs `edad_meses` or `edad_anos`")
return {str(f): round(float(m), 1) for f, m in zip(table["archivo"], months) if m == m}
def local_studies(s: Settings) -> list[tuple[str, float]]:
"""(path, age in months) of each EDF under the reference folder with an age inside `[reference] ages`."""
from tea.contracts import header_age_months
r = s.reference
folder = Path(r.prefix)
if not folder.is_dir():
raise FileNotFoundError(f"no folder {folder}")
by_name = _table_ages(Path(r.ages_table)) if r.ages_table else None
found = []
for path in sorted(p for p in folder.rglob("*") if p.is_file() and p.suffix.lower() == ".edf"):
if by_name is not None:
age = by_name.get(path.name)
else:
try:
age = header_age_months(path, days_per_month=s.days_per_month)
except Exception: # noqa: BLE001 -- an unreadable header is a file with no age
age = None
if age is not None and r.ages[0] <= age <= r.ages[1]:
found.append((str(path), age))
return found
+83
View File
@@ -0,0 +1,83 @@
"""The analysis's settings (`model.toml`): the plan, the implementation and the metrics with their library features.
Each trained baseline is a registered model `tea-<scenario>`, one per biomarker and sleep stage
(`eeg-spindles-n2`, `eeg-spindle-topography-n2`, `eeg-posterior-rhythm`, ...).
"""
import tomllib
from dataclasses import dataclass
from functools import cache
from pathlib import Path
@dataclass(frozen=True)
class Metric:
code: str
biomarker: str
feature: str
phase: str | None = None
electrodes: str | None = None
electrode_prefix: str = ""
@property
def scenario(self) -> str:
return scenario_of(self.biomarker, self.phase)
@property
def electrode_scenario(self) -> str | None:
return scenario_of(self.electrodes, self.phase) if self.electrodes else None
@dataclass(frozen=True)
class Reference:
name: str
prefix: str
ages_table: str
line_hz: float
ages: tuple[float, float]
storage: str = "s3" # "s3": the cluster's S3, read in a worker; "local": a folder on this machine (`reference.py`)
@dataclass(frozen=True)
class Settings:
domain: str
plan: str
impl: str
line_hz: float
days_per_month: float
baseline: str
reference: Reference
metrics: tuple[Metric, ...]
@property
def phases(self) -> tuple[str, ...]:
return tuple(dict.fromkeys(m.phase for m in self.metrics if m.phase))
@property
def scenarios(self) -> dict[str, tuple[str, str | None]]:
"""Each baseline to train, by scenario: (biomarker, sleep stage)."""
pairs = [(n, m.phase) for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)}
@property
def biomarkers(self) -> tuple[str, ...]:
"""Every biomarker a metric reads, its own or its electrodes'."""
names = [n for m in self.metrics for n in (m.biomarker, m.electrodes) if n]
return tuple(dict.fromkeys(names))
def scenario_of(biomarker: str, phase: str | None) -> str:
return "eeg-" + biomarker.replace("_", "-") + (f"-{phase.lower()}" if phase else "")
@cache
def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings:
raw = tomllib.loads(path.read_text())
metrics = tuple(Metric(**m) for m in raw.pop("metrics"))
reference = raw.pop("reference")
reference = Reference(**{**reference, "ages": tuple(reference["ages"])})
codes = [m.code for m in metrics]
if len(set(codes)) != len(codes):
raise ValueError(f"model.toml maps a metric code twice: {codes}")
if raw["impl"] != "modern":
raise ValueError("the analysis stores the modern validation's checks: impl must be 'modern'")
return Settings(metrics=metrics, reference=reference, **raw)
+230
View File
@@ -0,0 +1,230 @@
"""The age baselines: trained on the reference cohort and registered, one version per scenario (biomarker and sleep
stage), as `tea-<scenario>`.
1. `listing`: the reference cohort's EDFs and ages, within `[reference] ages`, read from the cluster's S3 in a worker
(only the workers reach it). Its hash identifies the cohort a version was trained on (ML-03).
2. `measure`: each study through the analysis's own unit of work (`analyze.reference`), as a Dask batch.
3. `train_scenario`: a fresh library module trained on the valid studies' features and ages, logged with the
library's MLflow model (`tea.serving.log_biomarker`, whose guard refuses groups under 5 and anything per child),
then its run and version given what the registry's promotion checks read: environment, the reference cohort,
the model's hash, the five routine records and its metrics.
Promotion is the registry's (`registry.promote`), as for every model: it waits for the technical, clinical and
interpretability reports, so the domain expert's validation is what puts a baseline in production.
"""
import hashlib
import json
import tempfile
from dataclasses import dataclass
from pathlib import Path
import pandas as pd
from models.io.lineage import (
COHORT_BUILD_TAG,
COHORT_SOURCE_TAG,
COHORT_URL_TAG,
MODEL_SHA_TAG,
code_version,
registered_name,
)
from models.io.registry import REFERENCE_SOURCE
from models.io.tracking import experiment_id, routine_path
from models.tea.eeg.analyze import ReferenceStudy, pipeline, plan, reference
from models.tea.eeg.settings import Settings
DOMAIN = "tea"
@dataclass(frozen=True)
class Listing:
"""The reference studies to measure, (key, path, age in months), and the hash that identifies them. Keys are
positions, never file names."""
studies: tuple[tuple[str, str, float], ...]
sha256: str
@classmethod
def of(cls, name: str, paths_and_ages: list[tuple[str, float]]) -> "Listing":
ordered = sorted(paths_and_ages)
digest = hashlib.sha256("\n".join(f"{p}|{a}" for p, a in ordered).encode()).hexdigest()
return cls(tuple((f"{name}-{k:04d}", p, a) for k, (p, a) in enumerate(ordered, 1)), digest)
def list_reference(s: Settings) -> list[tuple[str, float]]:
"""In a worker: (path, age in months) of each reference EDF with an age inside `[reference] ages`, from the
cluster's S3 or, for a cohort on this machine, from its folder (`reference.local_studies`)."""
from tea.pipeline.storage import s3
from models.tea.eeg.reference import LOCAL, local_studies
r = s.reference
if r.storage == LOCAL:
return local_studies(s)
fs = s3()
paths = fs.find(r.prefix)
tables = [p for p in paths if p.endswith(r.ages_table)]
if not tables:
raise FileNotFoundError(f"no {r.ages_table} under {r.prefix}")
with fs.open(tables[0], "rb") as f:
ages = pd.read_csv(f)
ages.columns = ["archivo", "edad_anos", *ages.columns[2:]]
edfs = {Path(p).name: p for p in paths if p.endswith(".edf")}
found = [("s3://" + edfs[row.archivo], round(float(row.edad_anos) * 12, 1))
for row in ages.itertuples() if row.archivo in edfs]
return [(p, a) for p, a in found if r.ages[0] <= a <= r.ages[1]]
def listing(s: Settings, cluster: str = "auto") -> Listing:
from tea.pipeline.dask_runner import run as run_batch
(found,) = run_batch(list_reference, [(s,)], cluster=cluster)
return Listing.of(s.reference.name, found)
def measure(found: Listing, s: Settings, cluster: str = "auto") -> list[ReferenceStudy]:
from tea.pipeline.dask_runner import run as run_batch
def lost(args, exc):
return ReferenceStudy(args[0], args[2], error=f"{type(exc).__name__}: the batch lost this study")
return run_batch(reference, [(k, p, a, s, s.reference.line_hz) for k, p, a in found.studies], cluster=cluster,
on_error=lost)
def table(studies: list[ReferenceStudy], biomarker: str, phase: str | None) -> pd.DataFrame:
"""The valid studies' features of one biomarker and stage, with their ages: what a baseline is trained on."""
rows = [{**st.features[biomarker, phase], "age_months": st.age_months} for st in studies
if st.valid == 1 and st.error is None and (biomarker, phase) in st.features]
return pd.DataFrame(rows)
def _module_state(module) -> tuple[str, dict]:
"""The trained module's hash (its saved parameters and baselines) and its baselines' state, by feature."""
with tempfile.TemporaryDirectory() as folder:
module.save(folder)
files = sorted(Path(folder).glob("*.json"))
digest = hashlib.sha256(b"".join(f.name.encode() + f.read_bytes() for f in files)).hexdigest()
baselines = json.loads((Path(folder) / "baseline.json").read_text())
return digest, baselines
def _covered(state: dict, n_min: float) -> tuple[float, float] | None:
"""The ages every feature's curve covers with at least `n_min` effective studies."""
spans = []
for baseline in (state.values() if "name" not in state else [state]):
curve = baseline.get("curva") or {}
ages = [a for a, n in zip(curve.get("edad_meses", []), curve.get("n_efectivo", [])) if n and n >= n_min]
if not ages:
return None
spans.append((min(ages), max(ages)))
return (max(lo for lo, _ in spans), min(hi for _, hi in spans)) if spans else None
def find_trained(scenario: str, expected: dict[str, str]):
"""The newest version of the scenario whose tags hold every expected value, or `None`."""
from mlflow import MlflowClient
found = MlflowClient().search_model_versions(f"name='{registered_name(DOMAIN, scenario)}'")
matching = [mv for mv in found if all(mv.tags.get(k) == v for k, v in expected.items())]
return max(matching, key=lambda mv: int(mv.version), default=None)
def expected_tags(scenario: str, found: Listing, s: Settings, environment: str) -> dict[str, str]:
biomarker, phase = s.scenarios[scenario]
module = pipeline(s).module(biomarker)
return {"environment": environment, COHORT_BUILD_TAG: found.sha256, "plan_hash": plan(s).get("hash", ""),
"module": biomarker, "module_version": getattr(module, "version", "?"), "phase": phase or "",
"baseline": s.baseline}
def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing, s: Settings, environment: str) -> str:
"""Trains, logs and registers one scenario's baseline; returns its version."""
from mlflow import MlflowClient
from tea.serving import log_biomarker
biomarker, phase = s.scenarios[scenario]
data = table(studies, biomarker, phase)
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
module.train(data)
sha, state = _module_state(module)
name = registered_name(DOMAIN, scenario)
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
experiment_id(MlflowClient(), name)
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
experiment=name)
client, run_id, version = MlflowClient(), mv.run_id, str(mv.version)
tags = {"domain": DOMAIN, "scenario": scenario, MODEL_SHA_TAG: sha,
COHORT_URL_TAG: f"{DOMAIN}/{REFERENCE_SOURCE}/{s.reference.name}", COHORT_SOURCE_TAG: REFERENCE_SOURCE,
**expected_tags(scenario, found, s, environment)}
features = [c for c in data.columns if c != "age_months"]
present = {f: int(data[f].notna().sum()) for f in features}
params = getattr(module, "baseline_params", {}) or {}
n_min = float(params.get("n_min", 30))
covered = _covered(state, n_min) if s.baseline == "curves" else None
measured = [st for st in studies if st.error is None]
routines = {
"MUESTREO": {"cohorte": s.reference.name, "edades_meses": list(s.reference.ages),
"estudios_listados": len(found.studies), "medidos": len(measured),
"validos": sum(st.valid == 1 for st in measured), "con_error": len(studies) - len(measured),
"usados": len(data), "fase_de_sueno": phase},
"DATOS_FALTANTES": {"criterio": "cada curva usa los estudios con ese rasgo medido; los demás se omiten",
"estudios_con_valor_por_rasgo": present},
"METODO_ANALITICO": {"modulo": biomarker, "version_modulo": tags["module_version"], "linea_base": s.baseline,
"parametros": params, "plan": s.plan, "plan_hash": tags["plan_hash"],
"red_electrica_hz": s.reference.line_hz},
"BALANCE_CLASES": {"aplica": False, "motivo": "una curva de referencia por edad no tiene clases"},
"CONFIANZA_SALIDA": {"salida": "z contra la curva a la edad del niño; -1/+1 debajo del p5 / arriba del p95",
"edades_cubiertas_meses": list(covered) if covered else None,
"n_efectivo_minimo": n_min},
}
metrics = {"n_referencia": len(data), **{f"n.{feature}": n for feature, n in present.items()}}
if covered:
metrics.update(edad_min_cubierta=covered[0], edad_max_cubierta=covered[1])
description = (
f"Curva de referencia por edad de {biomarker}{f' en sueño {phase}' if phase else ''}, entrenada en "
f"{s.reference.name} ({len(data)} estudios de {s.reference.ages[0]:g} a {s.reference.ages[1]:g} meses). "
"Pendiente de validación clínica.")
record(client, name, version, run_id, tags=tags, routines=routines, metrics=metrics, description=description)
return version
def record(client, name: str, version: str, run_id: str, *, tags: dict[str, str], routines: dict[str, dict],
metrics: dict[str, float], description: str) -> None:
"""What the registry's promotion checks read, on a version and its run: the tags (on both, with the code
version on the run), the routine records, the metrics and the description."""
for key, value in {**tags, **code_version()}.items():
client.set_tag(run_id, key, value)
for key, value in tags.items():
client.set_model_version_tag(name, version, key, value)
for kind, routine in routines.items():
client.log_text(run_id, json.dumps(routine, ensure_ascii=False, indent=1, default=str), routine_path(kind))
for key, value in metrics.items():
client.log_metric(run_id, key, value)
client.update_model_version(name, version, description=description)
def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Listing | None = None,
studies: list[ReferenceStudy] | None = None) -> dict[str, tuple[str, bool]]:
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
scenario needs it."""
found = found or listing(s, cluster)
out, pending = {}, []
for scenario in s.scenarios:
existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
if existing is not None:
out[scenario] = (str(existing.version), False)
else:
pending.append(scenario)
if pending:
studies = studies if studies is not None else measure(found, s, cluster)
for scenario in pending:
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
return out
def latest(scenario: str, environment: str):
"""The newest version of the scenario trained in `environment`, or `None`."""
return find_trained(scenario, {"environment": environment})
+2 -2
View File
@@ -39,7 +39,7 @@ class CacuStandIn:
missing = [c for c in ("pac_id", "pap_0", "hpv_0") if c not in columns]
if missing:
raise ValueError(f"The frame lacks the columns {missing}: the stand-in needs them.")
i_pac, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "pap_0", "hpv_0"))
i_pac, i_fecha, i_pap, i_hpv = (columns.index(c) for c in ("pac_id", "fecha_indice", "pap_0", "hpv_0"))
risks = []
for row in rows:
p = CACU_RULE["base"]
@@ -48,5 +48,5 @@ class CacuStandIn:
if row[i_hpv] == "POSITIVO":
p += CACU_RULE["vph_positivo"]
p = min(p, CACU_RULE["tope"])
risks += [Risk(int(row[i_pac]), float(h), round(p, 6)) for h in self.horizons]
risks += [Risk(int(row[i_pac]), row[i_fecha], float(h), round(p, 6)) for h in self.horizons]
return risks

Some files were not shown because too many files have changed in this diff Show More