Compare commits

...

54 Commits

Author SHA1 Message Date
ulises c12ea569cf Submodule URLs relative to this repository's remote 2026-11-23 20:01:46 -06:00
alberto 3908ddf74d Merge pull request 'TEA EEG: cluster choice for training and analysis, text EEG ids, run progress' (#16) from feature/tea-eeg-analysis into dev 2026-11-23 09:38:29 -06:00
ulises 2a04ee8c8e TEA EEG: training and analysis choose the cluster, EEG ids are text, run progress snapshots; tea library pointer 2026-11-23 09:29:41 -06:00
Roberto Treviño Cervantes f9d97f4d12 Scenarios: batch_estimates turns off the cycle's per-member scoring; off for CaMa recurrence, answered per clinical scenario 2026-11-23 00:14:14 -06:00
Roberto Treviño Cervantes 674bdc4bb2 CaMa survival figure: every point from the pipeline's survival stage, the whole cohort's included 2026-11-22 23:46:57 -06:00
Roberto Treviño Cervantes 678c02b79d Merge dev into the CaMa consolidation branch 2026-11-22 23:27:34 -06:00
edgar 1c445286eb Merge pull request 'CaCu models: survival interval, yearly PIM horizons, registry listing of production scenarios' (#14) from integration/cacu-indicadores into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/models/pulls/14
2026-11-22 23:24:57 -06:00
Roberto Treviño Cervantes 706f7510c5 CaMa survival: the scenario points from the pipeline's depuration and survival stage over the current members 2026-11-22 23:22:31 -06:00
Roberto Treviño Cervantes 07c91adbe6 CaMa survival figure: Weibull fits on the scenario's own deaths and the pipeline's published points, as its survival stage draws a subgroup 2026-11-22 22:59:47 -06:00
alberto 8545c36bc4 Merge pull request 'TEA: ADOS-2 scoring command and library pointer' (#13) from feature/tea-eeg-analysis into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/models/pulls/13
2026-11-22 22:13:32 -06:00
ulises 6d653e9f17 TEA: score ADOS-2 evaluations from their items (calibrated severity score and classification) with a score-ados2 command; tea library pointer 2026-11-22 22:01:50 -06:00
ulises a9ab8612f8 TEA: ADOS-2 association job, EEG zone values, spike minutes as exposure and the count baselines' reference range; tea library 0.3.0 2026-11-22 21:47:15 -06:00
edgar ccaa6fca12 Registry: list a domain's scenarios with a version in production 2026-11-22 20:34:38 -06:00
edgar e1f388c702 Read the CaCu PIM curves at every year from 0 to 5
The horizons are evaluation points of the fitted I-spline curve, so the fit is unchanged; each batch gains the 2- and 4-year rows.
2026-11-22 20:26:47 -06:00
edgar 55d675c8a8 CaCu survival: each risk comes with its combination's bootstrap interval
The covariates are categorical, so every member of a combination gets the same mortality. Training keeps, per
combination of its members, the percentiles of the mortality of `risk_interval_replicas` refits on bootstrap resamples
(`risk_interval_level`, 0.95), and estimating writes it as each risk's interval. A combination training never saw has
none.
2026-11-22 20:10:40 -06:00
Roberto Treviño Cervantes b3e02f0980 CaMa recurrence trains on the loaded METABRIC and SCAN-B patients in the total cohort, not on bundled files; the second survival scenario is retired 2026-11-22 19:51:20 -06:00
edgar c676dde0d0 CaCu survival: a case is a carcinoma, invasive or in situ
The scenario's diagnosis is the first biopsy reported as CIS or invasive carcinoma (`event_grades`), so in situ cases
are followed too and a CIS before an invasive carcinoma is the index date.
2026-11-22 19:16:05 -06:00
Roberto Treviño Cervantes 5a10be44d0 CaMa survival: no member is followed past today 2026-11-22 18:04:57 -06:00
edgar 34b26d8c85 CaCu survival: an estimand that shows the probability of surviving
The model gives the probability of dying (`muerte`, like every batch the probability of its outcome); `complement =
"supervivencia"` tells the screens to show its complement as the probability of surviving, from the first invasive
biopsy, with its covariates.
2026-11-22 15:04:03 -06:00
edgar f00dd31450 CaCu PIM estimands: a probability, its covariates, and the surveillance index in short
The quantity is "Probabilidad"; each scenario names the covariates it uses, which the patient's record writes under
the table; the surveillance and cancer scenarios name their index as the latest cytology with cytology and HPV
results.
2026-11-22 15:04:03 -06:00
edgar 547ceedea3 Merge pull request 'CaCu PIM: risk intervals, estimand, latest-cytology index, cancer outcome; pipeline drawings' (#12) from integration/cacu-indicadores into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/models/pulls/12
2026-11-22 13:46:19 -06:00
Roberto Treviño Cervantes d91ac7c14b CaMa survival: the members' stage, surgery and adjuvant treatments, read by the clinical scenarios and the development stages 2026-11-22 11:36:52 -06:00
edgar 28858c6966 CaCu: the surveillance PIM with cancer as the outcome (cancer_pim)
The same dataflow, cohort, index and prediction index as the CIN2+ surveillance model, with carcinoma as the only
event, like the cancer column of KPNC's tables: the patient's two risks are of the same visit. The subgroup report
template serves it too.
2026-11-22 09:34:35 -06:00
edgar 835817930d CaCu PIM: the estimand says what the number is, not how its interval is computed
The interval's method (delta method on the log scale) is the version's subgroup report's; the screens that show the
estimand don't need it.
2026-11-22 09:34:35 -06:00
Roberto Treviño Cervantes 94c7cf93dc Merge the CaMa SEER survival and METABRIC/SCAN-B recurrence work into dev's CaMa models 2026-11-22 09:18:15 -06:00
edgar 7928b478f9 CaCu PIM subgroup report: risks in percent, one scale per panel, the empirical method in plain words
The figure drew proportions with no unit, which read as a risk a hundred times smaller than the table's and the
patient's. Each panel now has its own y scale, so a low-risk combination isn't flattened by a high-risk one, and the
methods describe Turnbull's curve by what each patient contributes to it.
2026-11-22 07:38:47 -06:00
edgar 46bc6bcf39 CaCu PIM: risk intervals, what the number is, and the surveillance risk from the latest cytology
- The registered mixture gives each risk's interval at `risk_interval_level` (delta method on the log scale, from
  the fit's inverse Hessian), so the patient's risk carries it.
- `[estimand]` in `model.toml` says what the model's number is (quantity, outcome, index date, unit of the horizons,
  interval), read into `Scenario.estimand` for the screens that show it.
- The surveillance scenario predicts from each patient's latest cytology with both cytology and HPV results, before
  any colposcopy (`prediction_index = "ultima_citologia"`): every new complete sample is a new index date, and a
  sample still missing a result gives way to the one before. Patients past a colposcopy are the post-colposcopy
  scenario's. Training keeps the first cytology in the window. The rule runs inside the registered model, so it loads
  without this repository.
2026-11-22 07:38:39 -06:00
edgar 78a4748592 Estimates: each risk's interval when the model gives one; a member it can't place has no rows
A run with `risk_interval_level` has a model that gives, after the risk at each horizon, its interval's lower and
upper ends; the estimate keeps them as `ic_bajo` and `ic_alto`, the contract checks that they hold the risk, and the
batch stores them. `scored_frame` is the one place that reads the run and calls the model, for the command and the
WebApi's cycle. A member whose risk is NaN (a combination the model never saw) is left out instead of stopping the
whole batch.
2026-11-22 07:38:17 -06:00
edgar 271c799d0a Tests: the PIM likelihood gives KPNC's published risks to machine precision
A fixture of the published cumulative risks at 0-5 years of KPNC's tables 1, 17, 18, 24 and 25 (CIN2+ and CIN3+),
with the knots, spline coefficients and proportional factors that reproduce them, checked against
`cumulative_risk` to 1e-12. Aggregates of public tables only.
2026-11-22 07:38:07 -06:00
edgar d090bb0f9f Governance: each version stores the drawing of its dataflow as files of its own
Training stores the scenario's Hamilton graph as `diagramas/pipeline.dot` and, when Graphviz's `dot` is installed,
`diagramas/pipeline.svg`, listed next to the version's other files. Without the `graphviz` package there is no
drawing and training goes on.
2026-11-22 07:38:07 -06:00
edgar 0b25a5687e Merge pull request 'CaCu survival: all-cause mortality at 1, 3 and 5 years and subgroup reports' (#10) from integration/cacu-indicadores into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/models/pulls/10
2026-11-22 01:00:39 -06:00
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
luis c42f544173 Tests for the SEER survival pipeline's stages and runner 2026-11-20 13:40:06 -06:00
luis 305e855a15 CaMa SEER survival pipeline: the six scripts as Hamilton DAGs, one module of nodes per stage and the heavy routines apart
Stages 01-06 (depuration, MCA balancing and categorization, bootstrap indices, stepwise LR and hybrid Bayesian network, survival curves, risk factors), settings in model.toml, run.py writing each stage's files and pipeline.py as the runner that replaces ejecutar_pipeline.py. New extras seer-survival and seer-survival-dca; experiments/ excluded from the wheel.
2026-11-20 13:40:06 -06:00
luis 76d6b96409 Keep the original SEER survival scripts as experiments (not packaged) 2026-11-20 13:40:06 -06:00
100 changed files with 8582 additions and 966 deletions
+1 -1
View File
@@ -1,3 +1,3 @@
[submodule "tea"] [submodule "tea"]
path = libs/tea path = libs/tea
url = ssh://git@10.0.10.41:2222/alberto/tea.git url = ../../alberto/tea.git
+5 -2
View File
@@ -15,7 +15,7 @@ WebApi.
| `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). | | `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). |
| `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`) and their hashes (`file_sha256`, `table_sha256`, `cohort_reference`), dbt's manifest (`read_queries`), Persistance repositories, the risk batches, and the cohort sources a model trains and estimates on: `KitBuild`, a kit build read now from the domain's database (nothing written), or `CohortFile`, an exported file, behind one contract (`frame`, `lineage`, `reference`). | | `io/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/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the code's version (the installed `models` package, `code_version`), a model's hash (`model_sha`), and `matches`, the one rule for "already done". |
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `run_files`/`run_file` list and download a run's files (a folder as a zip). | | `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). In PROD, only models whose class lives in a module. `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). | | `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. | | `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. | | `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. |
@@ -30,18 +30,21 @@ WebApi.
| `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. | | `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. | | `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)`. | | `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. | | `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` 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. | | `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. | | `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. | | `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_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/` | 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/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. | | `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/` | 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/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. | | `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]`. | | `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). | | `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. | | `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. |
+47 -1
View File
@@ -4,8 +4,10 @@ Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit
command that needs them, so `--help` stays immediate. command that needs them, so `--help` stays immediate.
""" """
import argparse import argparse
import json
import sys import sys
from collections.abc import Sequence from collections.abc import Sequence
from dataclasses import asdict
def _show_help(parser: argparse.ArgumentParser) -> int: def _show_help(parser: argparse.ArgumentParser) -> int:
@@ -164,13 +166,49 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
def _tea_analyze(args: argparse.Namespace) -> int: def _tea_analyze(args: argparse.Namespace) -> int:
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`).""" """The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
if args.ids is not None and (args.all or args.limit is not None):
print("--ids cannot be combined with --all or --limit", file=sys.stderr)
return 2
ids = [value.strip() for value in args.ids.split(",")] if args.ids is not None else None
if ids is not None and not all(ids):
print("--ids requires a comma-separated list of EEG ids", file=sys.stderr)
return 2
from models.eeg_analysis import analyze_pending from models.eeg_analysis import analyze_pending
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster) try:
s = analyze_pending(everything=args.all, limit=args.limit, ids=ids, cluster=args.cluster)
except LookupError as error:
print(error, file=sys.stderr)
return 1
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed") print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
print(f"summary: {json.dumps(asdict(s))}")
return 1 if s.failed else 0 return 1 if s.failed else 0
def _tea_score_ados2(args: argparse.Namespace) -> int:
"""The ADOS-2 CSS and classification from the stored item scores (`models.ados2_scoring`)."""
from models.ados2_scoring import score_pending
s = score_pending(overwrite=args.all)
print(f"{s.evaluations} evaluations: {s.scored} scored, {s.unscored} without enough to score")
return 0
def _tea_relate_ados2(args: argparse.Namespace) -> int:
"""The ADOS-2 association fitted on the analysed EEGs (`models.ados2_relation`)."""
from models.ados2_relation import relate
s = relate()
if s.unchanged:
print(f"{s.children} children: the cohort is that of {s.version}, nothing written")
elif s.version is None:
print(f"{s.children} children: no association could be estimated, nothing written")
else:
print(f"{s.version}: {s.children} children, level {s.level}, {s.associations} associations, "
f"{s.scored} patient probabilities")
return 0
def _tea_export_baselines(args: argparse.Namespace) -> int: def _tea_export_baselines(args: argparse.Namespace) -> int:
"""The trained age baselines as one bundle (`models.tea.eeg.bundle`).""" """The trained age baselines as one bundle (`models.tea.eeg.bundle`)."""
from models.tea.eeg.bundle import BundleError, export from models.tea.eeg.bundle import BundleError, export
@@ -518,9 +556,17 @@ def build_parser() -> argparse.ArgumentParser:
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines") "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("--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("--limit", type=int, help="at most this many EEGs")
analyze.add_argument("--ids", help="comma-separated EEG IDs to analyse again")
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto", 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") help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
analyze.set_defaults(run=_tea_analyze) analyze.set_defaults(run=_tea_analyze)
score_ados2 = tea_actions.add_parser(
"score-ados2", help="compute the ADOS-2 CSS and classification from the item scores, module and age")
score_ados2.add_argument("--all", action="store_true", help="also recompute values already stored")
score_ados2.set_defaults(run=_tea_score_ados2)
relate_ados2 = tea_actions.add_parser(
"relate-ados2", help="fit the ADOS-2 association on the analysed EEGs and store it as a new version")
relate_ados2.set_defaults(run=_tea_relate_ados2)
export_baselines = tea_actions.add_parser( 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", 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("--out", required=True, help="the bundle to write (.zip)")
+189
View File
@@ -0,0 +1,189 @@
"""The ADOS-2 association against the TEA database: the cohort from bronze, the `tea` library's fit, and its rows in
`relacion_ados2` and `relacion_ados2_paciente`.
The cohort is one row per child with a valid analysed EEG and an ADOS-2: the child's first valid EEG with some
predictor (its zone z and metric z, its age) and first ADOS-2 (module, item scores, CSS). Every valid EEG of those
children is then scored, so the study's EEG has its probabilities whichever EEG it is.
A fit is a version `tea-<UTC time>-<fingerprint>`: the time keeps versions in order (the gold view shows the
greatest), the fingerprint is that of the scored EEGs, which of them the fit used, and the module and level. Inputs
equal to the latest version's write nothing. Versions are
written unvalidated (`rel_validado` 0) until the domain expert validates them.
"""
from __future__ import annotations
import hashlib
import math
from dataclasses import dataclass
from datetime import datetime, timezone
import pandas as pd
from sqlmodel import Session, col, select
from core.tea.enums import NivelRelacionAdos2
from core.tea.models import (
ADOS2_ITEMS,
Ados2,
Eeg,
EegMetrica,
EegMetricaZona,
RelacionAdos2,
RelacionAdos2Paciente,
)
from models.tea.ados2.settings import Settings, settings
VERSION_PREFIX = "tea-"
LEVELS = {"item": NivelRelacionAdos2.ITEM.value, "domain": NivelRelacionAdos2.DOMINIO.value}
ZONED = ("spikes", "spindles")
@dataclass
class Summary:
version: str | None = None
level: str | None = None
children: int = 0
associations: int = 0
scored: int = 0
unchanged: bool = False
def _predictors(session: Session, eeg_ids: list[str], s: Settings) -> pd.DataFrame:
"""One row per EEG with a column per predictor: `z_<biomarker>_<zone>` and `z_<biomarker>`."""
codes = {code: b for b, code in s.biomarkers.items()}
metrics = session.exec(select(EegMetrica.met_id, EegMetrica.met_eeg_id, EegMetrica.met_codigo, EegMetrica.met_z)
.where(col(EegMetrica.met_eeg_id).in_(eeg_ids))
.where(col(EegMetrica.met_codigo).in_(list(codes)))).all()
values: dict[str, dict[str, float]] = {e: {} for e in eeg_ids}
zoned = {}
for met_id, eeg_id, code, z in metrics:
biomarker = codes[code]
if biomarker in ZONED:
zoned[met_id] = (eeg_id, biomarker)
elif z is not None:
values[eeg_id][f"z_{biomarker}"] = z
if zoned:
for met_id, zone, z in session.exec(select(EegMetricaZona.mez_met_id, EegMetricaZona.mez_zona,
EegMetricaZona.mez_z)
.where(col(EegMetricaZona.mez_met_id).in_(list(zoned)))).all():
if z is not None:
eeg_id, biomarker = zoned[met_id]
values[eeg_id][f"z_{biomarker}_{zone}"] = z
return pd.DataFrame.from_dict(values, orient="index")
def cohort(session: Session, s: Settings) -> tuple[pd.DataFrame, pd.DataFrame]:
"""The fit's cohort (the first valid EEG of each child with an ADOS-2) and the table to score (every valid EEG
of those children), both keyed by EEG id, in the library's columns."""
eegs = session.exec(select(Eeg.eeg_id, Eeg.eeg_pac_id, Eeg.eeg_fecha_estudio, Eeg.eeg_edad_meses)
.where(Eeg.eeg_valido == 1).where(col(Eeg.eeg_edad_meses).is_not(None))).all()
ados = session.exec(select(Ados2).where(col(Ados2.ado_pac_id).is_not(None))).all()
first: dict[int, Ados2] = {}
for a in sorted(ados, key=lambda a: (a.ado_fecha is None, a.ado_fecha, a.ado_id)):
first.setdefault(a.ado_pac_id, a)
rows = []
for eeg_id, pac_id, fecha, edad in eegs:
a = first.get(pac_id)
if a is None:
continue
rows.append({"key": eeg_id, "pac_id": pac_id, "fecha": fecha, "age_months": float(edad),
"ados_module": a.ado_modulo, "css": a.ado_css,
**{code: getattr(a, f"ado_{code}") for code in ADOS2_ITEMS}})
columns = ["key", "pac_id", "fecha", "age_months", "ados_module", "css", *ADOS2_ITEMS]
scored = pd.DataFrame(rows, columns=columns)
if len(scored):
z = _predictors(session, scored["key"].tolist(), s)
scored = scored.join(z, on="key")
scored = scored.sort_values(["pac_id", "fecha", "key"], na_position="last").reset_index(drop=True)
predictors = [c for c in scored.columns if c.startswith("z_")]
with_predictors = scored[predictors].notna().any(axis=1) if predictors else pd.Series(False, index=scored.index)
fit = scored[with_predictors].drop_duplicates("pac_id").reset_index(drop=True)
return fit.drop(columns=["pac_id", "fecha"]), scored.drop(columns=["pac_id", "fecha"])
def fingerprint(fit: pd.DataFrame, scored: pd.DataFrame, module: str) -> str:
"""Eight hex digits of the scored EEGs, which of them the fit used, and `module` (name, version, level);
independent of row and column order."""
t = scored.assign(_fit=scored["key"].isin(fit["key"]))
t = t.reindex(sorted(t.columns), axis=1).sort_values("key").reset_index(drop=True)
text = module + "\n" + t.to_csv(index=False, float_format="%.6g")
return hashlib.sha256(text.encode()).hexdigest()[:8]
def _latest(session: Session) -> str | None:
versions = session.exec(select(RelacionAdos2.rel_version)
.where(col(RelacionAdos2.rel_version).startswith(VERSION_PREFIX))).all()
return max(versions, default=None)
def _finite(value) -> float | None:
"""The value as a float, or none when missing or infinite (an open interval): not every engine stores inf."""
if value is None or pd.isna(value):
return None
value = float(value)
return value if math.isfinite(value) else None
def _row_id(*parts) -> str:
from models.eeg_analysis import row_id
return row_id("relacion-ados2", *parts)
def rows(module, version: str, associations: pd.DataFrame, scores: pd.DataFrame,
s: Settings) -> tuple[list[RelacionAdos2], list[RelacionAdos2Paciente]]:
"""The estimated associations as `relacion_ados2` rows and their scores as `relacion_ados2_paciente` rows."""
level = LEVELS[module.fitted["level"]]
# An odds ratio rounded to 0 or never estimated is no association to show (`rel_or` is above 0).
estimated = associations[associations["odds_ratio"].astype(float) > 0]
models, ids = [], {}
for a in estimated.itertuples():
rel_id = _row_id(version, a.biomarker, a.zone, a.outcome_code)
ids[a.biomarker, a.zone, a.outcome_code] = rel_id
models.append(RelacionAdos2(
rel_id=rel_id, rel_version=version, rel_nivel=level, rel_validado=0,
rel_n_cohorte=int(module.fitted["n"]), rel_biomarcador=s.biomarkers[a.biomarker], rel_zona=a.zone,
rel_tipo=LEVELS[a.kind], rel_resultado=a.outcome_code, rel_evento=a.event, rel_or=_finite(a.odds_ratio),
rel_ic_inf=_finite(a.ci_low), rel_ic_sup=_finite(a.ci_high), rel_q=_finite(a.q)))
patients = []
for r in scores.itertuples():
rel_id = ids.get((r.biomarker, r.zone, r.outcome_code))
if rel_id is None:
continue
patients.append(RelacionAdos2Paciente(
rap_id=_row_id(rel_id, r.key), rap_rel_id=rel_id, rap_eeg_id=r.key, rap_valor_z=float(r.z),
rap_probabilidad=float(r.probability), rap_probabilidad_referencia=float(r.reference_probability)))
return models, patients
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def relate(*, settings_: Settings | None = None, at: datetime | None = None) -> Summary:
"""Fits the association on the current cohort and writes it as a new version, unless the cohort is the latest
version's. Nothing is written when no association could be estimated."""
from tea.pipeline import registry
from persistance.tea import relacion_ados2_repository
s = settings_ or settings()
with relacion_ados2_repository.open_session() as session:
fit, scored = cohort(session, s)
summary = Summary(children=len(fit))
if not len(fit):
return summary
module = type(registry.association(s.association, s.impl))(level=s.level)
mark = fingerprint(fit, scored, f"{module.name}/{module.version}/{module.impl}/{s.level}")
latest = _latest(session)
if latest is not None and latest.endswith(f"-{mark}"):
return Summary(version=latest, children=len(fit), unchanged=True)
module.fit(fit)
version = f"{VERSION_PREFIX}{(at or _now()):%Y%m%dT%H%M%S}-{mark}"
models, patients = rows(module, version, module.associations(), module.score(scored), s)
summary.level = module.fitted["level"]
if not models:
return summary
session.add_all([*models, *patients])
session.commit()
summary.version, summary.associations, summary.scored = version, len(models), len(patients)
return summary
+61
View File
@@ -0,0 +1,61 @@
"""The ADOS-2 CSS and classification against the TEA database: each evaluation's item scores, module, algorithm and
the child's age at the evaluation go through `tea.scoring`, and the result is written to `ado_css` and
`ado_clasificacion`.
A value a source already gave is kept unless `overwrite` is set. An evaluation without items or module is left as
it is.
"""
from __future__ import annotations
from dataclasses import dataclass
from sqlmodel import Session, select
from core.tea.models import ADOS2_ITEMS, Ados2, Pacientes
from tea.scoring import score
DAYS_PER_MONTH = 30.4375
@dataclass
class Summary:
evaluations: int = 0
scored: int = 0
unscored: int = 0
def age_months(born, on) -> float | None:
if born is None or on is None:
return None
return (on - born).days / DAYS_PER_MONTH
def score_all(session: Session, *, overwrite: bool = False) -> Summary:
"""Scores every evaluation in the session's database and commits."""
births = dict(session.exec(select(Pacientes.pac_id, Pacientes.pac_fecha_nacimiento)).all())
summary = Summary()
for row in session.exec(select(Ados2)).all():
summary.evaluations += 1
if not overwrite and row.ado_css is not None and row.ado_clasificacion is not None:
continue
items = {code: getattr(row, f"ado_{code}") for code in ADOS2_ITEMS}
result = score(row.ado_modulo, items, age_months=age_months(births.get(row.ado_pac_id), row.ado_fecha),
algorithm=row.ado_algoritmo)
if result is None or (result.css is None and result.classification is None):
summary.unscored += 1
continue
if overwrite or row.ado_css is None:
row.ado_css = result.css if result.css is not None else row.ado_css
if overwrite or row.ado_clasificacion is None:
row.ado_clasificacion = result.classification or row.ado_clasificacion
session.add(row)
summary.scored += 1
session.commit()
return summary
def score_pending(*, overwrite: bool = False) -> Summary:
from persistance.tea import relacion_ados2_repository
with relacion_ados2_repository.open_session() as session:
return score_all(session, overwrite=overwrite)
View File
+72
View File
@@ -0,0 +1,72 @@
domain = "cacu"
scenario = "cancer_pim"
cohort = "cacu/cohorte_vigilancia"
outcome = "cancer"
# 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 cáncer cervicouterino (biopsia de 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, como la columna de cáncer de las tablas de KPNC (Cheung et al. 2020), \
con la misma cohorte y la misma fecha índice que el modelo de CIN2+ de vigilancia. 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.
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga cáncer cervicouterino en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "Cáncer: biopsia de carcinoma"
index_date = "la última citología con resultado de citología y de VPH"
horizons_unit = "años"
covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC"
[config]
horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results)
# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's
# index (the first cytology in the window). None predicts from the cohort's index too.
prediction_index = "ultima_citologia"
event_grades = ["CARCINOMA"]
train_fraction = 0.7
# Provisional: a carcinoma 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 the outcome 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 = ["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"]
+116 -13
View File
@@ -22,10 +22,13 @@ frame. Settings arrive as config (`model.toml`), the cohort through a loader, an
driver's saver (`models.dags.training`). driver's saver (`models.dags.training`).
""" """
import copy
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import pandera.pandas as pandera import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields from hamilton.function_modifiers import extract_fields
from scipy.stats import norm
from sklearn.base import BaseEstimator, TransformerMixin from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline from sklearn.pipeline import Pipeline
@@ -36,6 +39,10 @@ from models.io.contracts import DAYS_PER_YEAR
from models.steps import model_fitting from models.steps import model_fitting
FEATURES = ["cytology", "hpv_positive"] FEATURES = ["cytology", "hpv_positive"]
# The member's prediction index (days since 1970-01-01), when `IndexResults` picks it: the first column of the output.
INDEX_COLUMN = "fecha_indice_modelo"
EPOCH = pd.Timestamp("1970-01-01")
PREDICTION_INDEXES = ("ultima_citologia",)
def _features(history: dict) -> list[str]: def _features(history: dict) -> list[str]:
@@ -168,12 +175,13 @@ class PrevalenceIncidenceMixture(BaseEstimator):
""" """
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(), def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(),
incidence=None, levels=None): incidence=None, levels=None, interval_level=None):
self.horizons_years = horizons_years self.horizons_years = horizons_years
self.incidence_features = incidence_features self.incidence_features = incidence_features
self.strata = strata self.strata = strata
self.incidence = incidence self.incidence = incidence
self.levels = levels self.levels = levels
self.interval_level = interval_level
def _baseline(self, y: pd.DataFrame): def _baseline(self, y: pd.DataFrame):
settings = dict(self.incidence or {"family": "weibull"}) settings = dict(self.incidence or {"family": "weibull"})
@@ -232,17 +240,59 @@ class PrevalenceIncidenceMixture(BaseEstimator):
self.converged_ = all(f["converged"] for f in self.fits_.values()) self.converged_ = all(f["converged"] for f in self.fits_.values())
return self return self
def risk_with_variance(self, key: tuple, prevalence: np.ndarray, incidence: np.ndarray, years) -> tuple:
"""CR(t) of each design row of stratum `key` at `years`, and its delta-method variance (central differences
of CR in every parameter, with the fit's inverse Hessian)."""
fit = self.fits_[key]
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, prevalence, incidence, years)
params = np.asarray(fit["params"], dtype=float)
gradient = np.empty((len(params), len(prevalence), 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)
return risk(params), np.maximum(np.einsum("kij,kl,lij->ij", gradient, covariance, gradient), 0.0)
def predict_proba(self, X: pd.DataFrame) -> np.ndarray: def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
"""One column per horizon: CR(t). The column of t = 0 is the prevalence.""" """One column per horizon: CR(t). The column of t = 0 is the prevalence. With `INDEX_COLUMN` in `X`, its days
risks = np.full((len(X), len(self.horizons_years)), np.nan) since 1970-01-01 come first and a member without that date gets no risk. With `interval_level`, two more
blocks of as many columns: the interval's lower and upper ends, CR · exp(∓z · SE / CR) (delta method on the
log scale, clipped to [0, 1])."""
if INDEX_COLUMN in X.columns:
dates = pd.to_datetime(X[INDEX_COLUMN])
risks = self.predict_proba(X.drop(columns=INDEX_COLUMN))
risks[dates.isna().to_numpy()] = np.nan
return np.column_stack([(dates - EPOCH).dt.days.to_numpy(dtype=float), risks])
h = len(self.horizons_years)
risks = np.full((len(X), 3 * h if self.interval_level else h), np.nan)
z = norm.ppf(0.5 + self.interval_level / 2) if self.interval_level else None
for key, index in self._groups(X): for key, index in self._groups(X):
if key not in self.fits_: if key not in self.fits_:
continue continue
members = X.iloc[index] members = X.iloc[index]
placed = self._placed(members, self.seen_[key]) placed = self._placed(members, self.seen_[key])
prevalence, incidence = self._design(members[placed], self.seen_[key]) prevalence, incidence = self._design(members[placed], self.seen_[key])
risks[index[placed]] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence, rows = index[placed]
self.horizons_years) if not self.interval_level:
risks[rows] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence, self.horizons_years)
continue
design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True)
point, variance = self.risk_with_variance(key, unique[:, :prevalence.shape[1]],
unique[:, prevalence.shape[1]:], self.horizons_years)
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
np.clip(point * np.exp(z * relative), 0, 1)])
risks[rows] = band[inverse.ravel()]
return risks return risks
@@ -287,23 +337,76 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
return found return found
class IndexResults(TransformerMixin, BaseEstimator): RESULT_TYPES = ("bethesda", "glandular", "vph")
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing.""" REFERRED = ("colposcopia", "biopsia") # a patient with either is past the surveillance model
def __init__(self, index_sample_days: int = 30, cytology=None, history=None):
def latest_precolposcopy_cytology(cohort: pd.DataFrame) -> pd.DataFrame:
"""Per patient with no colposcopy and no biopsy in the frame, the date of her latest cytology sample with a
cytology result (Bethesda or glandular) and an HPV result, linked to it by its source row: `pac_id`, `fecha`. A
sample still missing either result gives way to the one before it; a patient with none, or referred, is absent.
Self-contained: it runs inside the registered model, without this repository."""
referred = set(cohort.loc[cohort["tipo"].isin(REFERRED), "pac_id"])
key = ["pac_id", "fuente_tabla", "fuente_id"]
samples = cohort.loc[(cohort["tipo"] == "citologia") & ~cohort["pac_id"].isin(referred), [*key, "fecha"]]
results = cohort[cohort["tipo"].isin(RESULT_TYPES) & cohort["valor_codigo"].notna()]
has = results.pivot_table(index=key, columns="tipo", values="valor_codigo", aggfunc="first")
has = has.reindex(columns=list(RESULT_TYPES))
complete = has[(has["bethesda"].notna() | has["glandular"].notna()) & has["vph"].notna()].index
samples = samples.set_index(key)
samples = samples[samples.index.isin(complete)].reset_index()
latest = samples.sort_values(["pac_id", "fecha", "fuente_id"]).groupby("pac_id", as_index=False).last()
return latest[["pac_id", "fecha"]].reset_index(drop=True)
def latest_index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict,
history: dict | None = None) -> pd.DataFrame:
"""`index_results` at each member's latest complete cytology before any colposcopy
(`latest_precolposcopy_cytology`), with that date in `INDEX_COLUMN`; one row per member in `pac_id`
order, with no features and no date for a member without such a sample."""
chosen = latest_precolposcopy_cytology(cohort).set_index("pac_id")["fecha"]
members = pd.DataFrame({"pac_id": sorted(cohort["pac_id"].unique())})
eligible = cohort[cohort["pac_id"].isin(chosen.index)]
if len(eligible):
found = index_results(eligible.assign(fecha_indice=eligible["pac_id"].map(chosen)), index_sample_days,
cytology, history)
members = members.merge(found[["pac_id", *_features(history)]], on="pac_id", how="left")
else:
members = members.assign(**{f: np.nan for f in _features(history)})
members[INDEX_COLUMN] = pd.to_datetime(members["pac_id"].map(chosen))
return members
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing. By default at the
cohort's index date, as in training; with `prediction_index = "ultima_citologia"` at each member's latest
complete cytology before any colposcopy (`latest_index_results`), with that date as `INDEX_COLUMN`."""
def __init__(self, index_sample_days: int = 30, cytology=None, history=None, prediction_index=None):
self.index_sample_days = index_sample_days self.index_sample_days = index_sample_days
self.cytology = cytology self.cytology = cytology
self.history = history self.history = history
self.prediction_index = prediction_index
def fit(self, X, y=None): def fit(self, X, y=None):
return self return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame: def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)] if self.prediction_index is None:
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
if self.prediction_index not in PREDICTION_INDEXES:
raise ValueError(f"unknown prediction_index {self.prediction_index!r}; known: {PREDICTION_INDEXES}")
found = latest_index_results(X, self.index_sample_days, self.cytology, self.history)
return found[[*_features(self.history), INDEX_COLUMN]].reset_index(drop=True)
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict, def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict,
history: dict) -> Pipeline: history: dict, risk_interval_level: float | None = None,
"""What's registered: the fitted mixture behind `IndexResults`.""" prediction_index: str | None = None) -> Pipeline:
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)), """What's registered: the fitted mixture behind `IndexResults`, giving each risk's interval at
("mixture", fitted_mixture)]) `risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run), from the
index `prediction_index` names (the cohort's when none)."""
registered = copy.copy(fitted_mixture)
registered.interval_level = risk_interval_level
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history, prediction_index)),
("mixture", registered)])
+17 -2
View File
@@ -5,7 +5,7 @@ outcome = "cin2"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged. # 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"] requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`. # The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"] modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"]
description = """ 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 \ 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 \ modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \
@@ -13,8 +13,23 @@ citología índice en las categorías de KPNC como covariable (Cheung et al. 202
corrección del sesgo de verificación ni validación clínica.""" 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. # The dataflow's config (`with_config`); each key is an input of the nodes that name it.
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la última citología con resultado de citología y de VPH"
horizons_unit = "años"
covariates = "VPH de la citología índice (un ajuste por resultado) y citología índice en las categorías de KPNC"
[config] [config]
horizons_years = [0.0, 1.0, 3.0, 5.0] horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
# From when it predicts: "ultima_citologia" is each patient's latest complete cytology (cytology and HPV results)
# before any colposcopy; patients past a colposcopy belong to the post-colposcopy scenario. Training keeps the cohort's
# index (the first cytology in the window). None predicts from the cohort's index too.
prediction_index = "ultima_citologia"
event_grades = ["LIEAG", "CIS", "CARCINOMA"] event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7 train_fraction = 0.7
# Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent. # Provisional: a CIN2+ biopsy within this window of the index date counts as prevalent.
@@ -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
}
+279
View File
@@ -0,0 +1,279 @@
"""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": "curva empírica de Turnbull: el estimador no paramétrico del riesgo acumulado cuando solo se sabe entre "
"qué dos visitas apareció el CIN2+ (censura por intervalos), calculado con el algoritmo EM de Turnbull "
"(1976). Cada paciente aporta el intervalo donde pudo estar su evento: un caso prevalente, el instante "
"0 (así la curva arranca en la prevalencia observada, comparable con la del modelo); una paciente "
"vista libre de CIN2+, el intervalo entre su último negativo y su biopsia CIN2+ (o sin fin); una sin "
"negativo previo, desde 0 hasta su biopsia. Banda y 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 _percent(values) -> list[float]:
return [100 * v for v in values]
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), in percent like the table and
the patient's risk. Each panel has its own y scale, so a combination of low risk isn't flattened by one of high
risk."""
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=False,
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=_percent(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=_percent(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=_percent(emp["CR"]), mode="lines", line={"color": "#242628", "width": 2,
"shape": "hv"},
name="Turnbull", legendgroup="emp", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.2f} %<extra>Turnbull</extra>"), row=row, col=col)
if model is not None:
figure.add_trace(go.Scatter(x=model["years"], y=_percent(model["high"]), mode="lines", line={"width": 0},
hoverinfo="skip", showlegend=False), row=row, col=col)
figure.add_trace(go.Scatter(x=model["years"], y=_percent(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=_percent(model["CR"]), mode="lines", line={"color": "#6f35a5",
"width": 2},
name="Mezcla prevalencia-incidencia", legendgroup="model", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.2f} %<extra>modelo</extra>"), row=row, col=col)
figure.update_xaxes(range=[0, max(horizons_years) + 0.05])
figure.update_yaxes(rangemode="tozero", ticksuffix=" %")
figure.update_yaxes(title_text="Riesgo acumulado (%)", col=1)
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}
@@ -4,7 +4,7 @@ cohort = "cacu/cohorte_total"
outcome = "cin2" outcome = "cin2"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"] requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change. # The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"] modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"]
description = """ 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 \ 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 \ 1, 3 y 5 años (escenario 4 de ASCCP 2019; tabla 17 de KPNC). Mezcla prevalencia–incidencia con I-splines, una por grado \
@@ -12,8 +12,19 @@ de la referencia (bajo o alto), con el VPH y la citología (tres categorías de
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 \ 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+.""" sin CIN2+, lo que supone que la impresión colposcópica no omite ningún CIN2+."""
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+"
horizons_unit = "años"
covariates = "grado de la citología que la refirió a colposcopía (un ajuste por grado), VPH y citología de la visita índice en tres categorías de KPNC"
[config] [config]
horizons_years = [0.0, 1.0, 3.0, 5.0] horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
event_grades = ["LIEAG", "CIS", "CARCINOMA"] event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7 train_fraction = 0.7
prevalent_window_months = 6 prevalent_window_months = 6
+13 -2
View File
@@ -4,7 +4,7 @@ cohort = "cacu/cohorte_post_tratamiento"
outcome = "cin2" outcome = "cin2"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"] requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change. # The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model"] modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report"]
description = """ 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 \ 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 \ (escenario 5 de ASCCP 2019; tablas 24 y 5 de KPNC). Mezcla prevalencia–incidencia con I-splines, una sola línea \
@@ -12,8 +12,19 @@ base, con el VPH y la citología (tres categorías de KPNC) de esa citología co
la tabla 24 (capítulo 25 de bayes-pim). Sin estrato de la biopsia previa: \ 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.""" la biopsia LIEAG no separa CIN2 de CIN3, y por lo mismo el desenlace es CIN2+. Sin corrección del sesgo de verificación."""
# What the model's number is, as the patient's screen and the governance pages show it.
[estimand]
quantity = "Probabilidad"
description = "Probabilidad de que la paciente tenga CIN2+ en la fecha índice o lo desarrolle antes de cada horizonte."
outcome = "CIN2+: biopsia LIEAG, CIS o carcinoma"
index_date = "la primera citología después del tratamiento"
horizons_unit = "años"
covariates = "VPH y citología de la citología índice en tres categorías de KPNC"
[config] [config]
horizons_years = [0.0, 1.0, 3.0, 5.0] horizons_years = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
# The level of each risk's interval (delta method), given with the estimate; none gives no interval.
risk_interval_level = 0.95
event_grades = ["LIEAG", "CIS", "CARCINOMA"] event_grades = ["LIEAG", "CIS", "CARCINOMA"]
train_fraction = 0.7 train_fraction = 0.7
prevalent_window_months = 6 prevalent_window_months = 6
View File
+199
View File
@@ -0,0 +1,199 @@
"""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]]
def _combinations(X: pd.DataFrame) -> pd.DataFrame:
"""Each member's combination of the covariates, as `encode` reads them (a missing value is `UNKNOWN`)."""
return X[FEATURES].astype(object).where(X[FEATURES].notna(), UNKNOWN).astype(str).reset_index(drop=True)
def _frame(combinations: pd.DataFrame) -> pd.DataFrame:
return combinations.replace(UNKNOWN, None)
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.
With `interval_level`, two more blocks follow the mortality: its interval's lower and upper ends. The covariates
are categorical, so every member of a combination gets the same mortality, and so the same interval: `fit` keeps
one per combination of the training members (`interval_table_`), the percentiles of the mortality of
`interval_replicas` refits of this same model on bootstrap resamples of them (seeded by `seed`). A combination the
training never saw has no interval."""
def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0), interval_level=None, interval_replicas=100,
seed=0):
self.survival = survival
self.horizons_years = horizons_years
self.interval_level = interval_level
self.interval_replicas = interval_replicas
self.seed = seed
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
self.interval_table_ = self._interval_table(X, y) if self.interval_level else {}
return self
def _interval_table(self, X: pd.DataFrame, y: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
combinations = _combinations(X).drop_duplicates()
rng = np.random.default_rng(self.seed)
replicas = []
for _ in range(int(self.interval_replicas)):
rows = rng.integers(0, len(X), len(X))
refit = IntervalSurvival(self.survival, self.horizons_years)
refit.fit(X.iloc[rows].reset_index(drop=True), y.iloc[rows].reset_index(drop=True))
replicas.append(1.0 - refit.survival_proba(_frame(combinations)))
tail = 50 * (1 - self.interval_level)
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
rows = combinations.itertuples(index=False)
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
def mortality_interval(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""Each member's interval ends at each horizon: her combination's, empty for one the training never saw."""
empty = ([np.nan] * len(self.horizons_years),) * 2
ends = [self.interval_table_.get(tuple(c), empty) for c in _combinations(X).itertuples(index=False)]
return (np.array([e[0] for e in ends], dtype=float).reshape(len(X), -1),
np.array([e[1] for e in ends], dtype=float).reshape(len(X), -1))
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 self.interval_level:
mortality = np.column_stack([mortality, *self.mortality_interval(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"]
+154
View File
@@ -0,0 +1,154 @@
"""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],
risk_interval_level: float | None = None, risk_interval_replicas: int = 100) -> IntervalSurvival:
"""The interval survival fitted on the training members, with each combination's bootstrap interval at
`risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run)."""
return IntervalSurvival(survival, tuple(horizons_years), risk_interval_level, risk_interval_replicas).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 1.0 - fitted_survival.survival_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)])
+102
View File
@@ -0,0 +1,102 @@
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 o in situ), 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."""
# What the model's number is, as the patient's screen shows it. The model gives the probability of dying; the screen
# shows its complement, the probability of surviving, with the interval's ends swapped.
[estimand]
quantity = "Probabilidad de supervivencia"
description = "Probabilidad de que la paciente siga viva a cada horizonte desde el diagnóstico de cáncer."
outcome = "Muerte por cualquier causa"
index_date = "la primera biopsia con carcinoma invasor o in situ"
horizons_unit = "años"
covariates = "grupo de edad al diagnóstico, citología (categorías de KPNC) y VPH más recientes hasta él"
complement = "supervivencia"
[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 level of each risk's interval: per combination of the covariates, the percentiles of `risk_interval_replicas`
# refits on bootstrap resamples of the training members. None gives no interval.
risk_interval_level = 0.95
risk_interval_replicas = 100
# 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 carcinoma, invasive or in situ (`CARCINOMA`, `CIS`), 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 = ["CIS", "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 o in situ"
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}
+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)
+5 -2
View File
@@ -1,5 +1,5 @@
"""One cohort's patients as the frame the analysis reads: one row per patient with the follow-up in months, the recurrence """One cohort's patients as the frame the analysis reads: one row per patient with the follow-up in months, the recurrence
event and each covariate's category, built from the timeline by the dictionary (`[variables]` of `model.toml`). event and each covariate's category, built from the timeline by the dictionary (`[variables]` of `cohorts.toml`).
The index is the date of the patient's first biopsy reported as invasive carcinoma, the diagnosis (the cohort's `fecha_indice`); the follow-up runs from The index is the date of the patient's first biopsy reported as invasive carcinoma, the diagnosis (the cohort's `fecha_indice`); the follow-up runs from
it to the recurrence or, without one, to the last contact. The events are a cohort's (`fecha_indice` is the index). A covariate is read from the events up to it to the recurrence or, without one, to the last contact. The events are a cohort's (`fecha_indice` is the index). A covariate is read from the events up to
@@ -13,7 +13,7 @@ import pandas as pd
from models.cama.seer_survival.variables import Reader, category_of from models.cama.seer_survival.variables import Reader, category_of
TOML = Path(__file__).with_name("model.toml") TOML = Path(__file__).with_name("cohorts.toml")
SOURCE_CODE = {"metabric": "METABRIC", "scanb": "SCANB"} SOURCE_CODE = {"metabric": "METABRIC", "scanb": "SCANB"}
@@ -74,6 +74,9 @@ def recode(events: pd.DataFrame, model: dict, cohort: str, *, of_source: bool =
result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy() result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy()
elif spec.get("terciles"): elif spec.get("terciles"):
count = reader.value(spec["source"], True) count = reader.value(spec["source"], True)
if count.notna().sum() == 0:
result[name] = spec["missing"]
continue
q = count.quantile([1 / 3, 2 / 3]).to_numpy() q = count.quantile([1 / 3, 2 / 3]).to_numpy()
result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy() result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy()
else: else:
+27 -5
View File
@@ -1,16 +1,22 @@
"""METABRIC's and SCAN-B's clinical files as CaMa import files: one CSV per bronze entity, named by the fields the import """METABRIC's and SCAN-B's clinical files as CaMa import files: one CSV per bronze entity, named by the fields the import
schemas take, to be uploaded through the platform's import like any other source. schemas take, to be uploaded through the platform's import like any other source.
python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR [--diagnosis-from 2018-01-01 --spread-days 540
--censor 2026-11-21]
What goes where is the dictionary's (`[variables.*]` of `model.toml`): each source category is stored as the catalog value What goes where is the dictionary's (`[variables.*]` of `cohorts.toml`): each source category is stored as the catalog value
the dictionary names and read back as the same category. The files record no calendar dates: the diagnosis is a fixed day the dictionary names and read back as the same category. The files record no calendar dates: the diagnosis is a fixed day
of its year, the birth is the diagnosis minus the age (rounded up to a whole day, so a patient on an age cut stays on its upper side), and the recurrence (or the last contact) is the diagnosis plus the of its year, the birth is the diagnosis minus the age (rounded up to a whole day, so a patient on an age cut stays on its upper side), and the recurrence (or the last contact) is the diagnosis plus the
follow-up, and a discharge note closes it: the patients have been treated. A date holds whole days, so the follow-up is stored as the whole-day count nearest to the exact months that keeps follow-up, and a discharge note closes it: the patients have been treated. A date holds whole days, so the follow-up is stored as the whole-day count nearest to the exact months that keeps
the month it falls in and its side of every horizon. the month it falls in and its side of every horizon.
`--diagnosis-from` places the diagnoses in a window of the platform's own (spread over `--spread-days` days, the same day for
the same patient on every run) in place of the dictionary's fixed year, and `--censor` ends every follow-up by that day: a
recurrence after it is not known yet, and the patient is a last contact on that day.
""" """
import argparse import argparse
import hashlib
import math import math
import tomllib import tomllib
from pathlib import Path from pathlib import Path
@@ -18,7 +24,7 @@ from pathlib import Path
import numpy as np import numpy as np
import pandas as pd import pandas as pd
TOML = Path(__file__).with_name("model.toml") TOML = Path(__file__).with_name("cohorts.toml")
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "NotaMedica": "notas", "TratamientoMama": "tratamientos", ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "NotaMedica": "notas", "TratamientoMama": "tratamientos",
"SeguimientoMama": "seguimientos"} "SeguimientoMama": "seguimientos"}
FEMALE = "Femenino" FEMALE = "Femenino"
@@ -49,7 +55,13 @@ def _known(raw: pd.Series) -> pd.Series:
return raw.notna() & ~raw.astype(str).str.strip().isin(UNKNOWN) return raw.notna() & ~raw.astype(str).str.strip().isin(UNKNOWN)
def convert(raw: pd.DataFrame, cohort: str, model: dict) -> dict[str, pd.DataFrame]: def _spread(ids: pd.Series, days: int) -> pd.Series:
"""A day in [0, days) per patient, fixed by her identifier."""
return ids.map(lambda i: int.from_bytes(hashlib.sha256(str(i).encode()).digest()[:4], "big") % days)
def convert(raw: pd.DataFrame, cohort: str, model: dict, *, diagnosis_from: str | None = None, spread_days: int = 1,
censor: str | None = None) -> dict[str, pd.DataFrame]:
dictionary = model["variables"] dictionary = model["variables"]
index = dictionary["index"] index = dictionary["index"]
cfg = dictionary["cohorts"][cohort] cfg = dictionary["cohorts"][cohort]
@@ -77,8 +89,14 @@ def convert(raw: pd.DataFrame, cohort: str, model: dict) -> dict[str, pd.DataFra
else: else:
year = pd.Series(int(cfg["diagnosis_year"]), index=frame.index) year = pd.Series(int(cfg["diagnosis_year"]), index=frame.index)
diagnosis = pd.to_datetime(year.astype(str) + "-" + cfg["diagnosis_month_day"]) diagnosis = pd.to_datetime(year.astype(str) + "-" + cfg["diagnosis_month_day"])
if diagnosis_from:
diagnosis = pd.Timestamp(diagnosis_from) + pd.to_timedelta(_spread(frame[cfg["id"]], spread_days), unit="D")
birth = diagnosis - pd.to_timedelta(np.ceil(age * 365.25), unit="D") birth = diagnosis - pd.to_timedelta(np.ceil(age * 365.25), unit="D")
end = diagnosis + pd.to_timedelta(days, unit="D") end = diagnosis + pd.to_timedelta(days, unit="D")
if censor:
late = end > pd.Timestamp(censor)
event = event.where(~late, 0)
end = end.where(~late, pd.Timestamp(censor))
ident = cohort.upper() + "-" + frame[cfg["id"]].astype(str) ident = cohort.upper() + "-" + frame[cfg["id"]].astype(str)
date = lambda s: s.dt.strftime("%Y-%m-%d") date = lambda s: s.dt.strftime("%Y-%m-%d")
@@ -146,11 +164,15 @@ def main(argv=None) -> None:
ap.add_argument("cohort", choices=["metabric", "scanb"]) ap.add_argument("cohort", choices=["metabric", "scanb"])
ap.add_argument("file") ap.add_argument("file")
ap.add_argument("out_dir") ap.add_argument("out_dir")
ap.add_argument("--diagnosis-from", help="first day of the diagnoses (YYYY-MM-DD); the dictionary's year without it")
ap.add_argument("--spread-days", type=int, default=1, help="days over which the diagnoses are spread")
ap.add_argument("--censor", help="last day of follow-up (YYYY-MM-DD)")
args = ap.parse_args(argv) args = ap.parse_args(argv)
raw = pd.read_csv(args.file, sep="\t", dtype=str, low_memory=False, keep_default_na=False) raw = pd.read_csv(args.file, sep="\t", dtype=str, low_memory=False, keep_default_na=False)
out = Path(args.out_dir) out = Path(args.out_dir)
out.mkdir(parents=True, exist_ok=True) out.mkdir(parents=True, exist_ok=True)
for entity, table in convert(raw, args.cohort, load()).items(): for entity, table in convert(raw, args.cohort, load(), diagnosis_from=args.diagnosis_from,
spread_days=args.spread_days, censor=args.censor).items():
table.to_csv(out / f"{args.cohort}_{ENTITIES[entity]}.csv", index=False) table.to_csv(out / f"{args.cohort}_{ENTITIES[entity]}.csv", index=False)
+400
View File
@@ -0,0 +1,400 @@
# CaMa recurrence: the METABRIC and SCAN-B analyses of Luis as one scenario. Each cohort has its own covariates, categories and
# clinical scenarios, as in his scripts; the cohorts are not pooled.
domain = "cama"
scenario = "recurrence"
cohort = "cama/cohorte_total"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "mpmath"]
settings_tables = ["modeling", "calculator", "variables"]
description = """
Recurrencia del cáncer de mama a 12, 36 y 60 meses desde el diagnóstico: regresión logística y red bayesiana, combinadas, \
sobre las variables de las cohortes METABRIC y SCAN-B; una figura por escenario clínico."""
[config]
horizons_months = [12, 36, 60]
# ---- settings of the stages (Luis's scripts 03, 04 and 05) ----
[modeling]
seed = 42
unknown_label = "Desconocido"
cramer_v_max = 0.80 # of a pair of non-treatment covariates with V >= this, the one with more unknowns is dropped
alpha_prefilter = 0.10 # univariate prefilter of the logistic regression
alpha_in = 0.10 # stepwise: p to enter
alpha_out = 0.15 # stepwise: p to leave
bdeu_ess = 10
max_parents = 6
test_share = 0.30 # the 70/30 split of the AUC
[calculator]
min_events = 15 # a scenario is drawn only with at least this many recurrences
bootstrap_replicas = 200
cap_months = 72 # the curves are drawn dotted past the follow-up up to here
fractional_weibull_budget_s = 60
# ---- the variable dictionary ----
# `rules` read the timeline (`source` = the study of the catalog, `codes` its values; `ge`/`lt` bound a number) and give
# the category; `missing` is the category when no rule holds (the unknown is one more category, never imputed).
# `<cohort>.column` is the source file's column; `<cohort>.values` maps its values to the codes the loader sends;
# `<cohort>.labels` renames the rules' category where the source names it differently (neutral label = source label);
# `[variables.X.<cohort>]` replaces the rules for a variable whose categories differ between the cohorts.
[variables]
window_days_after_index = 365
[variables.index]
id_column = "paciente"
months_column = "tiempo_meses"
event_column = "evento"
death_source = "defuncion"
birth_source = "nacimiento"
recurrence_source = "recurrencia"
last_contact_source = "ultimo_contacto"
days_per_month = 30.4375
[variables.cohorts.metabric]
id = "Patient ID"
months = "Relapse Free Status (Months)"
event = "Relapse Free Status" # "1:Recurred" is the event; rows without status or months are dropped
event_prefix = "1"
diagnosis_age = "Age at Diagnosis" # years
sex_filter = {}
diagnosis_month_day = "07-01"
diagnosis_year = 2000 # METABRIC records no year: a fixed one, the follow-up runs from it
# Per covariate, the source columns and category cuts as the preparation script defines them.
[variables.cohorts.scanb]
id = "PatientName"
months = "RFI_days" # days, divided by days_per_month
months_divisor = 30.4375
event = "RFI_event"
sex_filter = { column = "Gender", value = "F" }
diagnosis_age = "Age_5year_bin" # the bin's lower edge; the age is that value minus 2, as in the script
diagnosis_age_offset = -2
diagnosis_month_day = "07-01"
diagnosis_year_column = "dxYear"
# Cuts shared by both cohorts (pd.cut with the right edge open).
[variables.Edad]
cuts = [0, 45, 60, 75, 200]
labels = ["<45", "45-59", "60-74", "75+"]
missing = "Desconocido"
[variables.Tamano_tumor]
bronze = "BiopsiaMama.bx_tamano_tumor_mm"
source = "tamano_tumor_mm"
cuts = [0, 20.01, 50.01, 10000]
labels = ["<=20 mm", "21-50 mm", ">50 mm"]
missing = "Desconocido"
metabric = { column = "Tumor Size" }
scanb = { column = "TumorSize_mm" }
[variables.Ganglios_positivos]
bronze = "BiopsiaMama.bx_ganglios_positivos"
source = "ganglios_positivos"
cuts = [0, 1, 4, 1000]
labels = ["0", "1-3", "4+"]
missing = "Desconocido"
metabric = { column = "Lymph nodes examined positive" }
scanb = { column = "NodeMetSpec", number_values = { "NodeNegative" = 0, "SubMicroMet" = 0, "1to3" = 2, "4toX" = 6 } }
[variables.Grado_histologico]
bronze = "BiopsiaMama.bx_grado_nottingham"
rules = [
{ source = "grado_nottingham", codes = ["G1"], then = "1" },
{ source = "grado_nottingham", codes = ["G2"], then = "2" },
{ source = "grado_nottingham", codes = ["G3"], then = "3" },
]
missing = "Desconocido"
metabric = { column = "Neoplasm Histologic Grade", values = { "1.0" = "G1", "2.0" = "G2", "3.0" = "G3" } }
scanb = { column = "NHG", values = { "Grade1" = "G1", "Grade2" = "G2", "Grade3" = "G3" } }
[variables.Receptor_estrogeno]
bronze = "BiopsiaMama.bx_receptor_estrogeno"
rules = [
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "ER Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "ER", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.Receptor_progesterona]
bronze = "BiopsiaMama.bx_receptor_progesterona"
rules = [
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "PR Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "PR", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.HER2]
bronze = "BiopsiaMama.bx_her2_fish"
rules = [
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positive" },
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negative" },
{ source = "her2", codes = ["H3"], then = "Positive" },
{ source = "her2", codes = ["H0", "H1"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "HER2 Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
scanb = { column = "HER2", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
[variables.Tipo_histologico]
bronze = "BiopsiaMama.bx_tipo_histologico"
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Breast Invasive Ductal Carcinoma" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Breast Mixed Ductal and Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Breast Invasive Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Invasive Breast Carcinoma" },
{ source = "tipo_histologico", codes = ["8480/3"], then = "Breast Invasive Mixed Mucinous Carcinoma" },
{ source = "tipo_histologico", codes = ["8000/3"], then = "Breast" },
{ source = "tipo_histologico", codes = ["9120/3"], then = "Breast Angiosarcoma" },
{ source = "tipo_histologico", codes = ["8575/3"], then = "Metaplastic Breast Cancer" },
]
missing = "Desconocido"
metabric = { column = "Cancer Type Detailed", values = { "Breast Invasive Ductal Carcinoma" = "8500/3", "Breast Mixed Ductal and Lobular Carcinoma" = "8522/3", "Breast Invasive Lobular Carcinoma" = "8520/3", "Invasive Breast Carcinoma" = "8010/3", "Breast Invasive Mixed Mucinous Carcinoma" = "8480/3", "Breast" = "8000/3", "Breast Angiosarcoma" = "9120/3", "Metaplastic Breast Cancer" = "8575/3" } }
[variables.Tipo_histologico.scanb]
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Lobular" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Ductal-Lobular" },
{ source = "tipo_histologico", codes = ["8523/3"], then = "Ductal-Other" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Other" },
]
column = "Histology"
values = { "Ductal" = "8500/3", "Lobular" = "8520/3", "Ductal-Lobular" = "8522/3", "Ductal-Other" = "8523/3", "Other" = "8010/3" }
[variables.Estado_menopausico]
bronze = "Paciente.pac_estado_menopausico"
rules = [
{ source = "estado_menopausico", codes = ["POSMENOPAUSIA"], then = "Post" },
{ source = "estado_menopausico", codes = ["PREMENOPAUSIA"], then = "Pre" },
]
missing = "Desconocido"
metabric = { column = "Inferred Menopausal State", values = { "Post" = "POSMENOPAUSIA", "Pre" = "PREMENOPAUSIA" } }
scanb = { column = "MenopauseStatus_bin", values = { "Postmenopausal" = "POSMENOPAUSIA", "Premenopausal" = "PREMENOPAUSIA" }, labels = { "Post" = "Postmenopausal", "Pre" = "Premenopausal" } }
[variables.Lateralidad]
bronze = "BiopsiaMama.bx_lateralidad"
rules = [
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Left" },
{ source = "lateralidad", codes = ["DERECHA"], then = "Right" },
]
missing = "Desconocido"
metabric = { column = "Primary Tumor Laterality", values = { "Left" = "IZQUIERDA", "Right" = "DERECHA" } }
scanb = { column = "Laterality", values = { "LEFT" = "IZQUIERDA", "RIGHT" = "DERECHA" }, labels = { "Left" = "LEFT", "Right" = "RIGHT" } }
# Treatments. The category is the source's own, as the scenarios of each cohort name them.
[variables.Cirugia]
treatment = "cirugia"
rules = [
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL"], then = "MASTECTOMY" },
{ source = "cirugia", codes = ["SEGMENTECTOMIA"], then = "BREAST CONSERVING" },
]
missing = "Desconocido"
metabric = { column = "Type of Breast Surgery", values = { "MASTECTOMY" = "MASTECTOMIA_TOTAL", "BREAST CONSERVING" = "SEGMENTECTOMIA" } }
scanb = { column = "SurgeryType", values = { "Mastectomy" = "MASTECTOMIA_TOTAL", "Lumpectomy" = "SEGMENTECTOMIA" }, labels = { "MASTECTOMY" = "Mastectomy", "BREAST CONSERVING" = "Lumpectomy" } }
[variables.Quimioterapia]
treatment = "quimioterapia"
rules = [
{ source = "quimioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "quimioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Chemotherapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Chemotherapy", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Radioterapia]
treatment = "radioterapia"
rules = [
{ source = "radioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "radioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Radio Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Radiation", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Hormonoterapia]
treatment = "hormonoterapia"
rules = [
{ source = "hormonoterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "hormonoterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Hormone Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Endocrine", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
# ---- METABRIC only ----
[variables.Carga_mutacional]
bronze = "Paciente.pac_carga_mutacional"
source = "carga_mutacional"
terciles = true # the cohort's own terciles of the mutation count
labels = ["baja", "media", "alta"]
missing = "Desconocido"
metabric = { column = "Mutation Count" }
[variables.Subtipo_PAM50]
bronze = "Paciente.pac_pam50"
rules = [
{ source = "pam50", codes = ["LUMA"], then = "LumA" },
{ source = "pam50", codes = ["LUMB"], then = "LumB" },
{ source = "pam50", codes = ["HER2"], then = "Her2" },
{ source = "pam50", codes = ["BASAL"], then = "Basal" },
{ source = "pam50", codes = ["CLAUDIN_LOW"], then = "claudin-low" },
{ source = "pam50", codes = ["NORMAL"], then = "Normal" },
{ source = "pam50", codes = ["NC"], then = "NC" },
]
missing = "Desconocido"
metabric = { column = "Pam50 + Claudin-low subtype", values = { "LumA" = "LUMA", "LumB" = "LUMB", "Her2" = "HER2", "Basal" = "BASAL", "claudin-low" = "CLAUDIN_LOW", "Normal" = "NORMAL", "NC" = "NC" } }
[variables.Celularidad]
bronze = "Paciente.pac_celularidad"
rules = [
{ source = "celularidad", codes = ["ALTA"], then = "High" },
{ source = "celularidad", codes = ["MODERADA"], then = "Moderate" },
{ source = "celularidad", codes = ["BAJA"], then = "Low" },
]
missing = "Desconocido"
metabric = { column = "Cellularity", values = { "High" = "ALTA", "Moderate" = "MODERADA", "Low" = "BAJA" } }
[variables.Cluster_integrativo]
bronze = "Paciente.pac_cluster_integrativo"
rules = [
{ source = "cluster_integrativo", codes = ["IC1"], then = "1" },
{ source = "cluster_integrativo", codes = ["IC2"], then = "2" },
{ source = "cluster_integrativo", codes = ["IC3"], then = "3" },
{ source = "cluster_integrativo", codes = ["IC4ERP"], then = "4ER+" },
{ source = "cluster_integrativo", codes = ["IC4ERN"], then = "4ER-" },
{ source = "cluster_integrativo", codes = ["IC5"], then = "5" },
{ source = "cluster_integrativo", codes = ["IC6"], then = "6" },
{ source = "cluster_integrativo", codes = ["IC7"], then = "7" },
{ source = "cluster_integrativo", codes = ["IC8"], then = "8" },
{ source = "cluster_integrativo", codes = ["IC9"], then = "9" },
{ source = "cluster_integrativo", codes = ["IC10"], then = "10" },
]
missing = "Desconocido"
metabric = { column = "Integrative Cluster", values = { "1" = "IC1", "2" = "IC2", "3" = "IC3", "4ER+" = "IC4ERP", "4ER-" = "IC4ERN", "5" = "IC5", "6" = "IC6", "7" = "IC7", "8" = "IC8", "9" = "IC9", "10" = "IC10" } }
# ---- SCAN-B only ----
[variables.Ki67]
bronze = "Paciente.pac_ki67_categoria"
rules = [
{ source = "ki67_categoria", codes = ["BAJO"], then = "Low" },
{ source = "ki67_categoria", codes = ["INTERMEDIO"], then = "Intermediate" },
{ source = "ki67_categoria", codes = ["ALTO"], then = "High" },
]
missing = "Desconocido"
scanb = { column = "Ki67", values = { "Low" = "BAJO", "Intermediate" = "INTERMEDIO", "High" = "ALTO" } }
[variables.Subtipo_clinico]
bronze = "Paciente.pac_subtipo_clinico"
rules = [
{ source = "subtipo_clinico", codes = ["LUMINAL_A"], then = "Luminal A" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_NEG"], then = "Luminal B HER2-" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_POS"], then = "Luminal B HER2+" },
{ source = "subtipo_clinico", codes = ["BASAL_LIKE"], then = "Basal-like" },
{ source = "subtipo_clinico", codes = ["NO_LUMINAL_HER2_POS"], then = "Non-luminal HER2+" },
{ source = "subtipo_clinico", codes = ["LUMINAL_NO_DETERMINADO"], then = "Luminal undetermined" },
{ source = "subtipo_clinico", codes = ["RE_NEG_NO_DETERMINADO"], then = "ER- undetermined" },
]
missing = "Desconocido"
scanb = { column = "ClinicalSubtype", values = { "Luminal A" = "LUMINAL_A", "Luminal B HER2-" = "LUMINAL_B_HER2_NEG", "Luminal B HER2+" = "LUMINAL_B_HER2_POS", "Basal-like" = "BASAL_LIKE", "Non-luminal HER2+" = "NO_LUMINAL_HER2_POS", "Luminal undetermined" = "LUMINAL_NO_DETERMINADO", "ER- undetermined" = "RE_NEG_NO_DETERMINADO" } }
[variables.Estadio_clinico]
bronze = "NotaMedica.nm_estadio_clinico"
rules = [
{ source = "estadio_clinico", codes = ["E0"], then = "0" },
{ source = "estadio_clinico", codes = ["EI"], then = "1" },
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "2" },
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "3" },
]
missing = "Desconocido"
scanb = { column = "tnm_ClinicalStage", values = { "0" = "E0", "1" = "EI", "2" = "EIIA", "3" = "EIIIA" } }
[variables.AntiHER2]
treatment = "anti_her2"
rules = [
{ source = "anti_her2", codes = ["ADYUVANTE"], then = "Yes" },
{ source = "anti_her2", codes = ["NINGUNA"], then = "No" },
]
missing = "Desconocido"
scanb = { column = "AntiHER2", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA" }
# ---- which variables each cohort's model is designed on (before the Cramér's-V pruning) ----
[cohorts.metabric]
name = "METABRIC"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Estado_menopausico",
"Cluster_integrativo", "Lateralidad", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
[cohorts.scanb]
name = "SCAN-B"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Ki67", "Subtipo_clinico", "Tipo_histologico", "Estado_menopausico", "Lateralidad",
"Estadio_clinico", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
# ---- the clinical scenarios (SUBGRUPOS of `05_calculadora.py`): a conjunction of covariate categories ----
[[cohorts.metabric.scenarios]]
name = "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.metabric.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.metabric.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.metabric.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.metabric.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.metabric.scenarios]]
name = "Basal (PAM50)"
when = { Subtipo_PAM50 = ["Basal"] }
[[cohorts.metabric.scenarios]]
name = "HER2 (PAM50)"
when = { Subtipo_PAM50 = ["Her2"] }
[[cohorts.metabric.scenarios]]
name = "Luminal B (PAM50)"
when = { Subtipo_PAM50 = ["LumB"] }
[[cohorts.metabric.scenarios]]
name = "RE+ · 1-3 ganglios · cirugía conservadora"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["1-3"], Cirugia = ["BREAST CONSERVING"] }
[[cohorts.metabric.scenarios]]
name = "RE− · grado 3"
when = { Receptor_estrogeno = ["Negative"], Grado_histologico = ["3"] }
[[cohorts.scanb.scenarios]]
name = "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Subtipo_clinico = ["Luminal A"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.scanb.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.scanb.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.scanb.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.scanb.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.scanb.scenarios]]
name = "Basal-like"
when = { Subtipo_clinico = ["Basal-like"] }
[[cohorts.scanb.scenarios]]
name = "HER2+ (luminal B HER2+ o no luminal)"
when = { Subtipo_clinico = ["Luminal B HER2+", "Non-luminal HER2+"] }
[[cohorts.scanb.scenarios]]
name = "Luminal B HER2−"
when = { Subtipo_clinico = ["Luminal B HER2-"] }
[[cohorts.scanb.scenarios]]
name = "Luminal · 1-3 ganglios · lumpectomía"
when = { Subtipo_clinico = ["Luminal A", "Luminal B HER2-"], Ganglios_positivos = ["1-3"], Cirugia = ["Lumpectomy"] }
[[cohorts.scanb.scenarios]]
name = "Grado 3"
when = { Grado_histologico = ["3"] }
+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)
+159
View File
@@ -0,0 +1,159 @@
"""CaMa's recurrence analysis as a scenario: the dataflow from the cohort's patients loaded from METABRIC and SCAN-B (the
`fuente` of each, indexed at her first invasive biopsy) 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 import cohort as timeline
from models.cama.recurrence.prep import Prepared, finish
COHORTS = ("metabric", "scanb")
def dictionary() -> dict:
"""The variables, cohorts and scenarios of `cohorts.toml`."""
return timeline.load()
def prepared(cohort: pd.DataFrame, dictionary: dict, recurrence: dict) -> dict[str, Prepared]:
"""Each cohort's patients as one table of categories with its covariates (`cohort.recode`, then `prep`)."""
fixed = ["paciente", "tiempo_meses", "evento"]
return {name: finish(timeline.recode(cohort, dictionary, name), fixed, dictionary["cohorts"][name]["treatment"],
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": "pacientes cargadas de METABRIC y SCAN-B (`fuente`)"},
"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"])}}}
+30 -394
View File
@@ -1,402 +1,38 @@
# CaMa recurrence: the METABRIC and SCAN-B analyses of Luis as one scenario. Each cohort has its own covariates, categories and # CaMa recurrence analysis: the risk of recurrence by clinical scenario, trained on the patients loaded from METABRIC and
# clinical scenarios, as in his scripts; the cohorts are not pooled. # SCAN-B (`cohort_import`, through the platform's import) and read from the database by the dictionary of `cohorts.toml`.
# The scenarios' figures are what the dashboard shows; the hospital's patient is placed in the scenarios her covariates meet.
domain = "cama" domain = "cama"
scenario = "recurrence" scenario = "recurrence"
cohort = "cama/cohorte_total" cohort = "cama/cohorte_total"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "mpmath"] outcome = "recurrencia"
settings_tables = ["modeling", "calculator", "variables"] modules = ["models.cama.recurrence.model", "models.steps.indexing"]
description = """ description = """\
Recurrencia del cáncer de mama a 12, 36 y 60 meses desde el diagnóstico: regresión logística y red bayesiana, combinadas, \ Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36 y 60 meses por escenario clínico, con una \
sobre las variables de las cohortes METABRIC y SCAN-B; una figura por escenario clínico.""" regresión logística y una red bayesiana por horizonte, entrenadas con las pacientes cargadas de dos cohortes externas (METABRIC y SCAN-B). Pendiente \
de validación clínica."""
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
# Its figures are answered per clinical scenario (`/cama/modelo/recurrencia`); the cycle does not score each member.
batch_estimates = false
[config] [config.recurrence]
horizons_months = [12, 36, 60] 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
# ---- settings of the stages (Luis's scripts 03, 04 and 05) ----
[modeling]
seed = 42 seed = 42
unknown_label = "Desconocido"
cramer_v_max = 0.80 # of a pair of non-treatment covariates with V >= this, the one with more unknowns is dropped
alpha_prefilter = 0.10 # univariate prefilter of the logistic regression
alpha_in = 0.10 # stepwise: p to enter
alpha_out = 0.15 # stepwise: p to leave
bdeu_ess = 10 bdeu_ess = 10
max_parents = 6 max_parents = 6
test_share = 0.30 # the 70/30 split of the AUC 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
[calculator] [config.index]
min_events = 15 # a scenario is drawn only with at least this many recurrences kind = "primera_biopsia_invasora"
bootstrap_replicas = 200 event_grades = ["CARCINOMA_INVASOR"]
cap_months = 72 # the curves are drawn dotted past the follow-up up to here observacion_previa_minima_dias = 0
fractional_weibull_budget_s = 60
# ---- the variable dictionary ----
# `rules` read the timeline (`source` = the study of the catalog, `codes` its values; `ge`/`lt` bound a number) and give
# the category; `missing` is the category when no rule holds (the unknown is one more category, never imputed).
# `<cohort>.column` is the source file's column; `<cohort>.values` maps its values to the codes the loader sends;
# `<cohort>.labels` renames the rules' category where the source names it differently (neutral label = source label);
# `[variables.X.<cohort>]` replaces the rules for a variable whose categories differ between the cohorts.
[variables]
window_days_after_index = 365
[variables.index]
id_column = "paciente"
months_column = "tiempo_meses"
event_column = "evento"
death_source = "defuncion"
birth_source = "nacimiento"
recurrence_source = "recurrencia"
last_contact_source = "ultimo_contacto"
days_per_month = 30.4375
[variables.cohorts.metabric]
file = "brca_metabric_clinical_data.tsv"
id = "Patient ID"
months = "Relapse Free Status (Months)"
event = "Relapse Free Status" # "1:Recurred" is the event; rows without status or months are dropped
event_prefix = "1"
diagnosis_age = "Age at Diagnosis" # years
sex_filter = {}
diagnosis_month_day = "07-01"
diagnosis_year = 2000 # METABRIC records no year: a fixed one, the follow-up runs from it
# Per covariate, the source columns and category cuts as the preparation script defines them.
[variables.cohorts.scanb]
file = "scanb_clinical_metadata.txt"
id = "PatientName"
months = "RFI_days" # days, divided by days_per_month
months_divisor = 30.4375
event = "RFI_event"
sex_filter = { column = "Gender", value = "F" }
diagnosis_age = "Age_5year_bin" # the bin's lower edge; the age is that value minus 2, as in the script
diagnosis_age_offset = -2
diagnosis_month_day = "07-01"
diagnosis_year_column = "dxYear"
# Cuts shared by both cohorts (pd.cut with the right edge open).
[variables.Edad]
cuts = [0, 45, 60, 75, 200]
labels = ["<45", "45-59", "60-74", "75+"]
missing = "Desconocido"
[variables.Tamano_tumor]
bronze = "BiopsiaMama.bx_tamano_tumor_mm"
source = "tamano_tumor_mm"
cuts = [0, 20.01, 50.01, 10000]
labels = ["<=20 mm", "21-50 mm", ">50 mm"]
missing = "Desconocido"
metabric = { column = "Tumor Size" }
scanb = { column = "TumorSize_mm" }
[variables.Ganglios_positivos]
bronze = "BiopsiaMama.bx_ganglios_positivos"
source = "ganglios_positivos"
cuts = [0, 1, 4, 1000]
labels = ["0", "1-3", "4+"]
missing = "Desconocido"
metabric = { column = "Lymph nodes examined positive" }
scanb = { column = "NodeMetSpec", number_values = { "NodeNegative" = 0, "SubMicroMet" = 0, "1to3" = 2, "4toX" = 6 } }
[variables.Grado_histologico]
bronze = "BiopsiaMama.bx_grado_nottingham"
rules = [
{ source = "grado_nottingham", codes = ["G1"], then = "1" },
{ source = "grado_nottingham", codes = ["G2"], then = "2" },
{ source = "grado_nottingham", codes = ["G3"], then = "3" },
]
missing = "Desconocido"
metabric = { column = "Neoplasm Histologic Grade", values = { "1.0" = "G1", "2.0" = "G2", "3.0" = "G3" } }
scanb = { column = "NHG", values = { "Grade1" = "G1", "Grade2" = "G2", "Grade3" = "G3" } }
[variables.Receptor_estrogeno]
bronze = "BiopsiaMama.bx_receptor_estrogeno"
rules = [
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "ER Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "ER", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.Receptor_progesterona]
bronze = "BiopsiaMama.bx_receptor_progesterona"
rules = [
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "PR Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "PR", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.HER2]
bronze = "BiopsiaMama.bx_her2_fish"
rules = [
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positive" },
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negative" },
{ source = "her2", codes = ["H3"], then = "Positive" },
{ source = "her2", codes = ["H0", "H1"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "HER2 Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
scanb = { column = "HER2", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
[variables.Tipo_histologico]
bronze = "BiopsiaMama.bx_tipo_histologico"
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Breast Invasive Ductal Carcinoma" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Breast Mixed Ductal and Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Breast Invasive Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Invasive Breast Carcinoma" },
{ source = "tipo_histologico", codes = ["8480/3"], then = "Breast Invasive Mixed Mucinous Carcinoma" },
{ source = "tipo_histologico", codes = ["8000/3"], then = "Breast" },
{ source = "tipo_histologico", codes = ["9120/3"], then = "Breast Angiosarcoma" },
{ source = "tipo_histologico", codes = ["8575/3"], then = "Metaplastic Breast Cancer" },
]
missing = "Desconocido"
metabric = { column = "Cancer Type Detailed", values = { "Breast Invasive Ductal Carcinoma" = "8500/3", "Breast Mixed Ductal and Lobular Carcinoma" = "8522/3", "Breast Invasive Lobular Carcinoma" = "8520/3", "Invasive Breast Carcinoma" = "8010/3", "Breast Invasive Mixed Mucinous Carcinoma" = "8480/3", "Breast" = "8000/3", "Breast Angiosarcoma" = "9120/3", "Metaplastic Breast Cancer" = "8575/3" } }
[variables.Tipo_histologico.scanb]
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Lobular" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Ductal-Lobular" },
{ source = "tipo_histologico", codes = ["8523/3"], then = "Ductal-Other" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Other" },
]
column = "Histology"
values = { "Ductal" = "8500/3", "Lobular" = "8520/3", "Ductal-Lobular" = "8522/3", "Ductal-Other" = "8523/3", "Other" = "8010/3" }
[variables.Estado_menopausico]
bronze = "Paciente.pac_estado_menopausico"
rules = [
{ source = "estado_menopausico", codes = ["POSMENOPAUSIA"], then = "Post" },
{ source = "estado_menopausico", codes = ["PREMENOPAUSIA"], then = "Pre" },
]
missing = "Desconocido"
metabric = { column = "Inferred Menopausal State", values = { "Post" = "POSMENOPAUSIA", "Pre" = "PREMENOPAUSIA" } }
scanb = { column = "MenopauseStatus_bin", values = { "Postmenopausal" = "POSMENOPAUSIA", "Premenopausal" = "PREMENOPAUSIA" }, labels = { "Post" = "Postmenopausal", "Pre" = "Premenopausal" } }
[variables.Lateralidad]
bronze = "BiopsiaMama.bx_lateralidad"
rules = [
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Left" },
{ source = "lateralidad", codes = ["DERECHA"], then = "Right" },
]
missing = "Desconocido"
metabric = { column = "Primary Tumor Laterality", values = { "Left" = "IZQUIERDA", "Right" = "DERECHA" } }
scanb = { column = "Laterality", values = { "LEFT" = "IZQUIERDA", "RIGHT" = "DERECHA" }, labels = { "Left" = "LEFT", "Right" = "RIGHT" } }
# Treatments. The category is the source's own, as the scenarios of each cohort name them.
[variables.Cirugia]
treatment = "cirugia"
rules = [
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL"], then = "MASTECTOMY" },
{ source = "cirugia", codes = ["SEGMENTECTOMIA"], then = "BREAST CONSERVING" },
]
missing = "Desconocido"
metabric = { column = "Type of Breast Surgery", values = { "MASTECTOMY" = "MASTECTOMIA_TOTAL", "BREAST CONSERVING" = "SEGMENTECTOMIA" } }
scanb = { column = "SurgeryType", values = { "Mastectomy" = "MASTECTOMIA_TOTAL", "Lumpectomy" = "SEGMENTECTOMIA" }, labels = { "MASTECTOMY" = "Mastectomy", "BREAST CONSERVING" = "Lumpectomy" } }
[variables.Quimioterapia]
treatment = "quimioterapia"
rules = [
{ source = "quimioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "quimioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Chemotherapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Chemotherapy", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Radioterapia]
treatment = "radioterapia"
rules = [
{ source = "radioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "radioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Radio Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Radiation", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Hormonoterapia]
treatment = "hormonoterapia"
rules = [
{ source = "hormonoterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "hormonoterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Hormone Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Endocrine", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
# ---- METABRIC only ----
[variables.Carga_mutacional]
bronze = "Paciente.pac_carga_mutacional"
source = "carga_mutacional"
terciles = true # the cohort's own terciles of the mutation count
labels = ["baja", "media", "alta"]
missing = "Desconocido"
metabric = { column = "Mutation Count" }
[variables.Subtipo_PAM50]
bronze = "Paciente.pac_pam50"
rules = [
{ source = "pam50", codes = ["LUMA"], then = "LumA" },
{ source = "pam50", codes = ["LUMB"], then = "LumB" },
{ source = "pam50", codes = ["HER2"], then = "Her2" },
{ source = "pam50", codes = ["BASAL"], then = "Basal" },
{ source = "pam50", codes = ["CLAUDIN_LOW"], then = "claudin-low" },
{ source = "pam50", codes = ["NORMAL"], then = "Normal" },
{ source = "pam50", codes = ["NC"], then = "NC" },
]
missing = "Desconocido"
metabric = { column = "Pam50 + Claudin-low subtype", values = { "LumA" = "LUMA", "LumB" = "LUMB", "Her2" = "HER2", "Basal" = "BASAL", "claudin-low" = "CLAUDIN_LOW", "Normal" = "NORMAL", "NC" = "NC" } }
[variables.Celularidad]
bronze = "Paciente.pac_celularidad"
rules = [
{ source = "celularidad", codes = ["ALTA"], then = "High" },
{ source = "celularidad", codes = ["MODERADA"], then = "Moderate" },
{ source = "celularidad", codes = ["BAJA"], then = "Low" },
]
missing = "Desconocido"
metabric = { column = "Cellularity", values = { "High" = "ALTA", "Moderate" = "MODERADA", "Low" = "BAJA" } }
[variables.Cluster_integrativo]
bronze = "Paciente.pac_cluster_integrativo"
rules = [
{ source = "cluster_integrativo", codes = ["IC1"], then = "1" },
{ source = "cluster_integrativo", codes = ["IC2"], then = "2" },
{ source = "cluster_integrativo", codes = ["IC3"], then = "3" },
{ source = "cluster_integrativo", codes = ["IC4ERP"], then = "4ER+" },
{ source = "cluster_integrativo", codes = ["IC4ERN"], then = "4ER-" },
{ source = "cluster_integrativo", codes = ["IC5"], then = "5" },
{ source = "cluster_integrativo", codes = ["IC6"], then = "6" },
{ source = "cluster_integrativo", codes = ["IC7"], then = "7" },
{ source = "cluster_integrativo", codes = ["IC8"], then = "8" },
{ source = "cluster_integrativo", codes = ["IC9"], then = "9" },
{ source = "cluster_integrativo", codes = ["IC10"], then = "10" },
]
missing = "Desconocido"
metabric = { column = "Integrative Cluster", values = { "1" = "IC1", "2" = "IC2", "3" = "IC3", "4ER+" = "IC4ERP", "4ER-" = "IC4ERN", "5" = "IC5", "6" = "IC6", "7" = "IC7", "8" = "IC8", "9" = "IC9", "10" = "IC10" } }
# ---- SCAN-B only ----
[variables.Ki67]
bronze = "Paciente.pac_ki67_categoria"
rules = [
{ source = "ki67_categoria", codes = ["BAJO"], then = "Low" },
{ source = "ki67_categoria", codes = ["INTERMEDIO"], then = "Intermediate" },
{ source = "ki67_categoria", codes = ["ALTO"], then = "High" },
]
missing = "Desconocido"
scanb = { column = "Ki67", values = { "Low" = "BAJO", "Intermediate" = "INTERMEDIO", "High" = "ALTO" } }
[variables.Subtipo_clinico]
bronze = "Paciente.pac_subtipo_clinico"
rules = [
{ source = "subtipo_clinico", codes = ["LUMINAL_A"], then = "Luminal A" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_NEG"], then = "Luminal B HER2-" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_POS"], then = "Luminal B HER2+" },
{ source = "subtipo_clinico", codes = ["BASAL_LIKE"], then = "Basal-like" },
{ source = "subtipo_clinico", codes = ["NO_LUMINAL_HER2_POS"], then = "Non-luminal HER2+" },
{ source = "subtipo_clinico", codes = ["LUMINAL_NO_DETERMINADO"], then = "Luminal undetermined" },
{ source = "subtipo_clinico", codes = ["RE_NEG_NO_DETERMINADO"], then = "ER- undetermined" },
]
missing = "Desconocido"
scanb = { column = "ClinicalSubtype", values = { "Luminal A" = "LUMINAL_A", "Luminal B HER2-" = "LUMINAL_B_HER2_NEG", "Luminal B HER2+" = "LUMINAL_B_HER2_POS", "Basal-like" = "BASAL_LIKE", "Non-luminal HER2+" = "NO_LUMINAL_HER2_POS", "Luminal undetermined" = "LUMINAL_NO_DETERMINADO", "ER- undetermined" = "RE_NEG_NO_DETERMINADO" } }
[variables.Estadio_clinico]
bronze = "NotaMedica.nm_estadio_clinico"
rules = [
{ source = "estadio_clinico", codes = ["E0"], then = "0" },
{ source = "estadio_clinico", codes = ["EI"], then = "1" },
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "2" },
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "3" },
]
missing = "Desconocido"
scanb = { column = "tnm_ClinicalStage", values = { "0" = "E0", "1" = "EI", "2" = "EIIA", "3" = "EIIIA" } }
[variables.AntiHER2]
treatment = "anti_her2"
rules = [
{ source = "anti_her2", codes = ["ADYUVANTE"], then = "Yes" },
{ source = "anti_her2", codes = ["NINGUNA"], then = "No" },
]
missing = "Desconocido"
scanb = { column = "AntiHER2", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA" }
# ---- which variables each cohort's model is designed on (before the Cramér's-V pruning) ----
[cohorts.metabric]
name = "METABRIC"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Estado_menopausico",
"Cluster_integrativo", "Lateralidad", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
[cohorts.scanb]
name = "SCAN-B"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Ki67", "Subtipo_clinico", "Tipo_histologico", "Estado_menopausico", "Lateralidad",
"Estadio_clinico", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
# ---- the clinical scenarios (SUBGRUPOS of `05_calculadora.py`): a conjunction of covariate categories ----
[[cohorts.metabric.scenarios]]
name = "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.metabric.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.metabric.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.metabric.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.metabric.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.metabric.scenarios]]
name = "Basal (PAM50)"
when = { Subtipo_PAM50 = ["Basal"] }
[[cohorts.metabric.scenarios]]
name = "HER2 (PAM50)"
when = { Subtipo_PAM50 = ["Her2"] }
[[cohorts.metabric.scenarios]]
name = "Luminal B (PAM50)"
when = { Subtipo_PAM50 = ["LumB"] }
[[cohorts.metabric.scenarios]]
name = "RE+ · 1-3 ganglios · cirugía conservadora"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["1-3"], Cirugia = ["BREAST CONSERVING"] }
[[cohorts.metabric.scenarios]]
name = "RE− · grado 3"
when = { Receptor_estrogeno = ["Negative"], Grado_histologico = ["3"] }
[[cohorts.scanb.scenarios]]
name = "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Subtipo_clinico = ["Luminal A"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.scanb.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.scanb.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.scanb.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.scanb.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.scanb.scenarios]]
name = "Basal-like"
when = { Subtipo_clinico = ["Basal-like"] }
[[cohorts.scanb.scenarios]]
name = "HER2+ (luminal B HER2+ o no luminal)"
when = { Subtipo_clinico = ["Luminal B HER2+", "Non-luminal HER2+"] }
[[cohorts.scanb.scenarios]]
name = "Luminal B HER2−"
when = { Subtipo_clinico = ["Luminal B HER2-"] }
[[cohorts.scanb.scenarios]]
name = "Luminal · 1-3 ganglios · lumpectomía"
when = { Subtipo_clinico = ["Luminal A", "Luminal B HER2-"], Ganglios_positivos = ["1-3"], Cirugia = ["Lumpectomy"] }
[[cohorts.scanb.scenarios]]
name = "Grado 3"
when = { Grado_histologico = ["3"] }
+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"]))
+51
View File
@@ -0,0 +1,51 @@
"""The recurrence analysis' data: each cohort's patients (`cohort.recode`) as one table, the covariates as categories with
the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped, as in
`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
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 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)
-121
View File
@@ -1,121 +0,0 @@
"""CaMa survival as a registered scenario: from the cohort's long frame to a fitted model, its metrics and the routines'
records. The six stages of the pipeline (`run.py`) are the analysis; the scenario runs the first, the depuration, over the
members' variables and fits the interval models of the survival stage (`seer_model.fit`).
Nodes: `recoded` (the dictionary applied to the cohort), `depurated` (stage 01), `fitted_model`, `metrics` and `routines`.
The cohort's own index, the first invasive biopsy, is `models.steps.indexing`'s (`[config.index]`).
"""
import tempfile
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.seer_survival import run, variables
from models.cama.seer_survival import seer_model as sm_
from models.cama.seer_survival import survival_curves as sc
from models.cama.seer_survival import survival_models as fits
from models.cama.seer_survival.settings import Settings, load
RECODED_FILE = "dataframe_recodificado.csv"
def settings() -> Settings:
return load()
def dictionary() -> dict:
return variables.load()
def recoded(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame:
"""One row per member, in the columns of the variable dictionary."""
return variables.recode(cohort, dictionary)
def depurated(recoded: pd.DataFrame, settings: Settings) -> pd.DataFrame:
"""Stage 01 over the members: the frame without the variables the depuration drops."""
with tempfile.TemporaryDirectory() as folder:
path = Path(folder)
recoded.to_csv(path / RECODED_FILE, index=False)
run.run_depuration(path / RECODED_FILE, path / "sin_mapa.json", path, settings)
return pd.read_csv(path / run.DEPURATED, dtype=str, keep_default_na=False)
def fitted_model(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, settings: Settings,
index: dict) -> sm_.SeerSurvivalModel:
return sm_.fit(recoded, depurated, dictionary, settings.survival, index)
def metrics(fitted_model: sm_.SeerSurvivalModel) -> dict:
state = fitted_model.fit_state
return {"members": state.members, "deaths": state.deaths, "covariates": len(state.design.covariates),
"replicas": len(state.replicas),
**{f"weight_lr_interval_{i + 1}": float(w) for i, w in enumerate(state.weights)}}
def sampling(recoded: pd.DataFrame, fitted_model: sm_.SeerSurvivalModel, index_attrition: list, prior_observation: dict,
dictionary: dict) -> dict:
"""MUESTREO: who could be used (the index and each rule's attrition, their prior history), the follow-up and the
resampling."""
s, state = fitted_model.survival, fitted_model.fit_state
return {"method": "toda la cohorte indexada en su primera biopsia invasora; sin partición: la validación es de las "
f"predicciones fuera de muestra en {s.stack_folds} pliegues y de las réplicas bootstrap",
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"members": state.members, "deaths": state.deaths, "follow_up_cap_months": s.cap_months,
"bootstrap_replicas": len(state.replicas), "stack_folds": s.stack_folds}
def missing_data(recoded: pd.DataFrame, dictionary: dict) -> dict:
"""DATOS_FALTANTES: how many members lack each variable (its `missing` category), and what is done about it."""
counts = {}
for name in variables.variable_names(dictionary):
spec = dictionary[name]
if spec.get("internal"):
continue
counts[name] = int((recoded[variables.column_of(name, spec)] == spec["missing"]).sum())
return {"method": "un dato ausente es la categoría `missing` de su variable en el diccionario; nadie se excluye",
"members": len(recoded), "missing_by_variable": counts}
def analytic_method(fitted_model: sm_.SeerSurvivalModel) -> dict:
"""METODO_ANALITICO: the LR coefficients and the HBN's parents of each interval, and the weights that combine them."""
s, state = fitted_model.survival, fitted_model.fit_state
design = state.design
names = [f"{c}={k}" for c in design.covariates for k in design.sorted_categories[c][1:]]
intervals = []
for (a, b), fit, weight in zip(zip([0] + list(s.horizons[:-1]), s.horizons), state.point, state.weights):
intervals.append({"interval_months": [int(a), int(b)], "weight_lr": float(weight),
"intercept": float(fit.intercept), "coefficients": dict(zip(names, map(float, fit.coef))),
"hbn_parents": [design.covariates[j] for j in fit.parents]})
return {"method": "regresión logística y red bayesiana con tabla de probabilidad por intervalo, combinadas con el peso "
"que maximiza la verosimilitud fuera de muestra", "covariates": design.covariates, "intervals": intervals}
def class_balance(fitted_model: sm_.SeerSurvivalModel, depurated: pd.DataFrame) -> dict:
"""BALANCE_CLASES: the members at risk and the deaths of each interval; none is reweighted but the half weight of a
censoring inside an interval."""
s = fitted_model.survival
frame = sc.survival_frame(depurated, s)
months, event = frame.df["meses_int"].values, frame.df["evento"].values
rows = []
for a, b in zip([0] + list(s.horizons[:-1]), s.horizons):
at_risk = months >= a
rows.append({"interval_months": [int(a), int(b)], "at_risk": int(at_risk.sum()),
"deaths": int((event & at_risk & (months < b)).sum()),
"censored": int(((~event) & at_risk & (months < b)).sum())})
return {"method": "las clases se usan en su proporción observada; una censura dentro de un intervalo pesa la mitad",
"intervals": rows}
def output_confidence(fitted_model: sm_.SeerSurvivalModel) -> dict:
"""CONFIANZA_SALIDA: the survival at each horizon of the members of each decile of predicted survival, out of sample,
against the Kaplan-Meier of those members."""
return {"method": "calibración fuera de muestra: supervivencia predicha contra Kaplan-Meier, por deciles",
"deciles": fitted_model.fit_state.calibration}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict, output_confidence: dict) -> dict:
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
-30
View File
@@ -1,26 +1,4 @@
# CaMa SEER survival pipeline: settings of each stage. Paths are never here: they enter the DAG as inputs. # CaMa SEER survival pipeline: settings of each stage. Paths are never here: they enter the DAG as inputs.
domain = "cama"
scenario = "seer_survival"
cohort = "cama/cohorte_total"
outcome = "survival_18m"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "cloudpickle"]
modules = ["models.cama.seer_survival.model", "models.steps.indexing"]
# The tables whose values make a version a different one (with `[config]`): the depuration, the survival stage's settings
# and the variable dictionary.
settings_tables = ["depuration", "survival", "variables"]
description = """
Supervivencia del cáncer de mama a 6, 12 y 18 meses desde el diagnóstico (primera biopsia con carcinoma invasor): \
regresión logística y red bayesiana por intervalo, combinadas, sobre las variables del diccionario del modelo; \
entrenado y validado con los datos de SEER."""
# The dataflow's config (`with_config`).
[config]
horizons_years = [0.5, 1.0, 1.5]
[config.index]
kind = "primera_biopsia_invasora"
observacion_previa_minima_dias = 0
[depuration] [depuration]
exclude = ["Outcome_cat"] # never analysed or touched exclude = ["Outcome_cat"] # never analysed or touched
@@ -271,14 +249,6 @@ conditions = [
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] } { variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
] ]
[figure]
# The scenario figure computed on request (`SeerSurvivalModel.figure_record`): the seconds the fractional Weibull may take,
# the least members and deaths a scenario needs to be drawn, and the bootstrap replicas applied (empty: all of the model's).
ks_max_seconds = 30
min_members = 30
min_deaths = 5
n_boot = 100
[risk_factors] [risk_factors]
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not # A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
# crossing 1 and Benjamini-Hochberg p < alpha), c2 stability: the variable enters the LR stepwise in at least freq_min # crossing 1 and Benjamini-Hochberg p < alpha), c2 stability: the variable enters the LR stepwise in at least freq_min
+4 -3
View File
@@ -53,11 +53,12 @@ STAGES = [
Stage("05", lambda d, s: run.run_survival(d / run.DEPURATED, d, s), (run.DEPURATED,), 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", ("curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.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), Stage("06", lambda d, s: run.run_risk_factors(d / run.NATURAL, d, settings=s),
(run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"), (run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"),
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"), ("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv",
("risk_factors.py", "risk_factor_stats.py", "settings.py", "run.py")), "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 import pandas as pd
from models.cama.seer_survival import risk_factor_stats as stats 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 from models.cama.seer_survival.settings import RiskFactorSettings
CRITERIA = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"] 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], 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: risk_treatment: list[str], risk_factors: RiskFactorSettings) -> pd.DataFrame | None:
"""The treatment variables' adjusted associations with death, descriptive and not classified (confounding by """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: if not risk_treatment:
return None return None
variables = risk_intrinsic + risk_treatment variables = risk_intrinsic + risk_treatment
tr = stats.fit_odds(risk_data, risk_follow_up.death, variables) tr = stats.fit_odds(risk_data, risk_follow_up.death, variables)
tr["variable"] = [stats.variable_of(t, variables) for t in tr["termino"]] tr["variable"] = [stats.variable_of(t, variables) for t in tr["termino"]]
tr = tr[tr["variable"].isin(risk_treatment)].copy() 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["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["referencia"] = [stats.reference(risk_data, v) for v in tr["variable"]]
tr["p_ajustado_BH"] = stats.benjamini_hochberg(tr["p"]) 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, "horizonte_meses": risk_factors.horizon, "tope_meses": risk_factors.cap_months,
"replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas), "replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas),
"criterios_evaluados": risk_classification.criteria, "variables_tratamiento_excluidas": risk_treatment} "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))
+6 -4
View File
@@ -11,7 +11,7 @@ from pathlib import Path
import numpy as np import numpy as np
from hamilton import driver from hamilton import driver
from models.cama.seer_survival import (variables, balancing, bootstrap, categorization, depuration, modeling, resampling, from models.cama.seer_survival import (balancing, bootstrap, categorization, depuration, modeling, resampling,
risk_factors, survival_curves) risk_factors, survival_curves)
from models.cama.seer_survival.settings import Settings, load from models.cama.seer_survival.settings import Settings, load
@@ -166,7 +166,7 @@ def run_survival(depurated_csv: str, output_dir: str, settings: Settings | None
dr = driver.Builder().with_modules(survival_curves).build() dr = driver.Builder().with_modules(survival_curves).build()
r = dr.execute(["sv_table", "sv_main_figure", "sv_weights_cohort", "sv_sub_figures", "sv_sub_fits_table", r = dr.execute(["sv_table", "sv_main_figure", "sv_weights_cohort", "sv_sub_figures", "sv_sub_fits_table",
"sv_sub_points_table", "sv_sub_weights_table", "sv_age_test"], "sv_sub_points_table", "sv_sub_weights_table", "sv_age_test"],
inputs={"depurated_csv": str(depurated_csv), "survival": s, "dictionary": variables.load()}) inputs={"depurated_csv": str(depurated_csv), "survival": s})
r["sv_table"].to_csv(out / f"curva_supervivencia_puntos_LR_HBN{suffix}.csv", index=False) r["sv_table"].to_csv(out / f"curva_supervivencia_puntos_LR_HBN{suffix}.csv", index=False)
r["sv_main_figure"].savefig(out / f"curva_supervivencia_KM_KS_LR_HBN{suffix}.png", dpi=200) r["sv_main_figure"].savefig(out / f"curva_supervivencia_KM_KS_LR_HBN{suffix}.png", dpi=200)
if r["sv_weights_cohort"] is not None: if r["sv_weights_cohort"] is not None:
@@ -193,13 +193,15 @@ def run_risk_factors(natural_csv: str, output_dir: str, bootstrap_selection_csv:
inputs = {"natural_csv": str(natural_csv), inputs = {"natural_csv": str(natural_csv),
"bootstrap_selection_csv": str(bootstrap_selection_csv or out / "seleccion_bootstrap.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} "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"], r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria",
inputs=inputs) "risk_scenario_factors"], inputs=inputs)
r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False) r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False)
r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv") r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv")
if r["risk_treatment_associations"] is not None: if r["risk_treatment_associations"] is not None:
r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False) r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False)
_dump(out / "factores_riesgo_criterios.json", r["risk_criteria"]) _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 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
-225
View File
@@ -1,225 +0,0 @@
"""The registered CaMa survival model: the dictionary, the covariates the depuration kept, and the interval models of the
survival stage (LR and HBN per interval, the weights that combine them, and the replicas that give their intervals), fitted
on a cohort and kept. It scores any cohort's members from their timelines, and draws a clinical scenario's figure
(`figure_record`): Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the LR / HBN / combined
survival at the horizons with a bootstrap interval.
The fitted state is plain arrays and dictionaries; `rehydrate` puts a saved model's state into the current class, so a
version trained earlier is scored by today's code.
"""
import time
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import survival_curves as sc
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival import variables
from models.cama.seer_survival.settings import SurvivalSettings
from models.steps import indexing
NO_CATEGORY = "NA"
def figure_settings() -> dict:
"""`[figure]` of `model.toml`: what `figure_record` takes besides the scenario."""
import tomllib
return tomllib.loads(variables.TOML.read_text(encoding="utf-8"))["figure"]
@dataclass(frozen=True, eq=False)
class Design:
"""The covariates' coding the fits were made with: each covariate's categories sorted (the dummies drop the first) and in
order of first appearance (the HBN's integer codes), so any frame is coded as the training cohort was."""
covariates: list[str]
sorted_categories: dict[str, list[str]]
appearance: dict[str, list[str]]
@classmethod
def of(cls, frame: sc.SurvivalFrame) -> "Design":
df = frame.df
return cls(list(frame.covariates), {c: sorted(df[c].unique()) for c in frame.covariates},
{c: list(pd.factorize(df[c])[1]) for c in frame.covariates})
@property
def levels(self) -> np.ndarray:
return np.array([len(self.appearance[c]) for c in self.covariates])
def encode(self, df: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""(dummies, integer codes); a category the training cohort never had is coded as its reference."""
dummies, codes = [], []
for c in self.covariates:
values = df[c].fillna(NO_CATEGORY).astype(str).str.strip()
dummies += [(values == k).to_numpy(np.float32) for k in self.sorted_categories[c][1:]]
position = {k: i for i, k in enumerate(self.appearance[c])}
codes.append(values.map(position).fillna(0).astype(int).to_numpy())
return np.column_stack(dummies), np.column_stack(codes)
@dataclass
class Fit:
"""What `fit` leaves: the point fits, the bootstrap replicas' fits, the weights of the combination (the cohort's and each
configured scenario's) and what the cohort was."""
point: list
replicas: list
weights: np.ndarray
scenario_weights: dict
design: Design
members: int
deaths: int
calibration: list = field(default_factory=list)
class SeerSurvivalModel(BaseEstimator):
"""Scores a cohort's long frame (`predict_proba`: per member, in `pac_id` order, the risk of dying by each horizon)."""
def __init__(self, dictionary=None, survival=None, index=None, fit_state=None, kept=None, horizons_years=None):
self.dictionary = dictionary
self.survival = survival
self.index = index
self.fit_state = fit_state
self.kept = kept
self.horizons_years = horizons_years
@classmethod
def rehydrate(cls, saved) -> "SeerSurvivalModel":
"""The current class holding a saved model's state."""
model = cls.__new__(cls)
model.__dict__.update(saved.__dict__)
return model
# ------------------------------------------------------------------ from the timeline to the design
def recode(self, cohort: pd.DataFrame, *, indexed: bool = False) -> pd.DataFrame:
"""One row per member in the columns the dictionary makes; the cohort is re-indexed at the first invasive biopsy
unless it already is."""
if not indexed and self.index:
cohort = indexing.cohort(cohort, {}, self.index)
return variables.recode(cohort, self.dictionary)
def frame(self, recoded: pd.DataFrame) -> sc.SurvivalFrame:
"""The recoded members as the survival stage reads them, restricted to the covariates the depuration kept."""
columns = [c for c in recoded.columns if c in self.kept or not c.endswith("_cat")]
frame = sc.survival_frame(recoded[columns], self.survival)
covariates = [c for c in self.fit_state.design.covariates]
for c in covariates:
if c not in frame.df.columns:
frame.df[c] = NO_CATEGORY
return sc.SurvivalFrame(frame.df, covariates, frame.age_col, frame.numeric_cols)
def _survival(self, frame: sc.SurvivalFrame, weights=None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
design = self.fit_state.design
X_dum, X_int = design.encode(frame.df)
P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels)
W = self.fit_state.weights if weights is None else weights
return np.cumprod(P_lr, axis=1), np.cumprod(P_hb, axis=1), sm.mix(P_lr, P_hb, W)
def predict_proba(self, cohort: pd.DataFrame) -> np.ndarray:
recoded = self.recode(cohort)
frame = self.frame(recoded)
combined = self._survival(frame)[2]
order = np.argsort(recoded[self.dictionary["index"]["id_column"]].to_numpy())
return 1 - combined[order]
def predict(self, cohort: pd.DataFrame) -> np.ndarray:
return self.predict_proba(cohort)
# ------------------------------------------------------------------ a scenario's figure
def scenario_names(self) -> list[str]:
return [spec["name"] for spec in self.survival.subgroups]
def scenario_masks(self, frame: sc.SurvivalFrame) -> dict[str, np.ndarray]:
return sc.sv_masks(frame, self.survival, self.dictionary)
def figure_record(self, frame: sc.SurvivalFrame, scenario: str, *, ks_max_seconds: float = 30.0, n_boot: int | None = None,
min_members: int = 30, min_deaths: int = 5, extrapolate_months: int | None = None) -> dict:
"""The figure of one scenario over the members of `frame`; `None` for the parts a scenario with too few members or
deaths cannot support. The interval of each point is the percentile of the replicas' mean survival over members
resampled with replacement."""
s = self.survival
masks = self.scenario_masks(frame)
mask = masks[scenario]
df = frame.df[mask]
deaths = int(df["evento"].sum())
record = {"scenario": scenario, "members": int(len(df)), "deaths": deaths, "horizons": list(s.horizons), "points": []}
if len(df) < min_members or deaths < min_deaths:
return {**record, "drawable": False}
months, events = df["meses_int"].values, df["evento"].values
horizon = max(s.months_max, max(s.horizons))
S, lo, hi = fw.km_curva(months, events, horizon)
d, c = fw.tabla_eventos(months, events)
weibull = fw.ajustar_weibull(d, c)
fractional = fw.ajustar_ks(d, c, k_fijo=sc._fixed_k(weibull, s), lam_ref=weibull["lam"], max_seg=ks_max_seconds)
reach = extrapolate_months or s.months_extrapolated
grid = np.arange(0, reach + 1, dtype=float)
record.update(drawable=True, months=list(range(horizon + 1)), km={"S": S.tolist(), "lo": lo.tolist(), "hi": hi.tolist()},
curve_months=grid.tolist(),
weibull={"k": float(weibull["k"]), "S": np.asarray(weibull["S"](grid)).tolist()},
fractional={"k": float(fractional["k"]), "alpha": float(fractional["alpha"]), "beta": float(fractional["beta"]),
"S": np.asarray(fractional["S"](grid)).tolist()})
weights = self.fit_state.scenario_weights.get(scenario, self.fit_state.weights)
design = self.fit_state.design
X_dum, X_int = design.encode(df)
rng = np.random.default_rng(s.seed + 1)
replicas = self.fit_state.replicas[: n_boot if n_boot is not None else len(self.fit_state.replicas)]
started, boots = time.monotonic(), []
P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels)
point = [np.cumprod(P_lr, axis=1).mean(0), np.cumprod(P_hb, axis=1).mean(0), sm.mix(P_lr, P_hb, weights).mean(0)]
for fits in replicas:
pick = rng.integers(0, len(df), len(df))
Pl, Ph = sm.apply_intervals(fits, X_dum[pick], X_int[pick], design.levels)
boots.append(np.concatenate([np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0),
sm.mix(Pl, Ph, weights).mean(0)]))
ic = np.percentile(np.array(boots), [2.5, 97.5], axis=0) if boots else np.full((2, 3 * len(s.horizons)), np.nan)
for j, name in enumerate(("LR", "HBN", "COMB")):
for i, h in enumerate(s.horizons):
k = j * len(s.horizons) + i
record["points"].append({"model": name, "months": int(h), "S": float(point[j][i]),
"low": float(ic[0, k]), "high": float(ic[1, k])})
record["seconds"] = round(time.monotonic() - started, 2)
return record
def fit(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, survival: SurvivalSettings, index: dict | None,
n_boot: int | None = None, on_progress=None) -> SeerSurvivalModel:
"""The model fitted on `recoded` members (all the dictionary's columns) whose covariates are those of `depurated`."""
s = survival
kept = [c for c in depurated.columns if c.endswith("_cat")]
frame = sc.survival_frame(depurated, s)
cohort = sc.sv_cohort(frame, s)
N = len(cohort.months)
everyone = np.arange(N)
oof_lr, oof_hb = sm.out_of_fold(cohort, s, N)
weights = sm.stacking_weights(cohort, s, np.ones(N, bool), oof_lr, oof_hb)["w_LR"].values
point = sm.fit_intervals(cohort, s, everyone)
reference = [f.parents for f in point] if s.hbn_parents == "fijos" else None
masks = sc.sv_masks(frame, s, dictionary)
scenario_weights = {name: sm.stacking_weights(cohort, s, mask, oof_lr, oof_hb)["w_LR"].values for name, mask in masks.items()}
rng = np.random.default_rng(s.seed)
replicas = []
for r in range(s.n_boot if n_boot is None else n_boot):
replicas.append(sm.fit_intervals(cohort, s, rng.integers(0, N, N), reference))
if on_progress:
on_progress(r + 1)
out_of_sample = sm.mix(oof_lr, oof_hb, weights)
horizon = len(s.horizons) - 1
deciles = pd.qcut(pd.Series(out_of_sample[:, horizon]).rank(method="first"), 10, labels=False)
calibration = []
for q in range(10):
pick = (deciles == q).to_numpy()
curve, _, _ = fw.km_curva(cohort.months[pick], cohort.event[pick], int(s.horizons[-1]))
calibration.append({"decile": q + 1, "members": int(pick.sum()),
"predicted": {str(h): float(out_of_sample[pick, i].mean()) for i, h in enumerate(s.horizons)},
"observed": {str(h): float(curve[int(h)]) for h in s.horizons}})
state = Fit(point, replicas, weights, scenario_weights, Design.of(frame), N, int(frame.df["evento"].sum()), calibration)
horizons = [h / 12 for h in s.horizons]
return SeerSurvivalModel(dictionary, s, index, state, kept, horizons)
+2 -2
View File
@@ -148,7 +148,7 @@ class SurvivalSettings:
ks_sub_max_seconds: int ks_sub_max_seconds: int
xlim_sub: tuple[float, ...] xlim_sub: tuple[float, ...]
ylim_sub: dict ylim_sub: dict
subgroups: tuple[dict, ...] subgroups: tuple[dict, ...] = ()
@property @property
def file_suffix(self) -> str: def file_suffix(self) -> str:
@@ -213,5 +213,5 @@ def load(path: Path = TOML) -> Settings:
bootstrap=_group(BootstrapSettings, raw["bootstrap"]), bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
modeling=_group(ModelingSettings, raw["modeling"]), modeling=_group(ModelingSettings, raw["modeling"]),
survival=_group(SurvivalSettings, {**raw["survival"], survival=_group(SurvivalSettings, {**raw["survival"],
"subgroups": tuple(raw["survival"]["subgroups"])}), "subgroups": tuple(raw["survival"].get("subgroups", ()))}),
risk_factors=_group(RiskFactorSettings, raw["risk_factors"])) risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
+6 -2
View File
@@ -16,6 +16,7 @@ from matplotlib.figure import Figure
from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LogisticRegression
from models.cama.seer_survival import fractional_weibull as fw 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 import survival_models as sm
from models.cama.seer_survival import variables from models.cama.seer_survival import variables
from models.cama.seer_survival.settings import SurvivalSettings from models.cama.seer_survival.settings import SurvivalSettings
@@ -327,8 +328,11 @@ def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.
# ---------------------------------------------------------------- subgroups # ---------------------------------------------------------------- subgroups
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings, dictionary: dict) -> dict[str, np.ndarray]: def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings, dictionary: dict | None = None) -> dict[str, np.ndarray]:
"""Each scenario's mask over the cohort: every condition of its spec must hold.""" """Each clinical scenario's mask over the cohort: the `subgroups` of the settings over the variable dictionary when
both are given, else `scenarios.masks`. Every condition of a scenario must hold."""
if not (survival.subgroups and dictionary):
return scenarios.masks(sv_frame.df)
df = sv_frame.df df = sv_frame.df
masks = {} masks = {}
for spec in survival.subgroups: for spec in survival.subgroups:
+48 -13
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]) 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): 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 """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.""" patients of `idx` alive at its start; and the HBN's parents of each interval."""
test = idx if test is None else test test = idx if test is None else test
m, e = c.months[idx], c.event[idx] return predict_intervals(fit_intervals(c, s, idx, parents), c.X_dum[test], c.X_int[test], c.levels)
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
def patient_survival(c: Cohort, s: SurvivalSettings, idx, mode, parents=None): def patient_survival(c: Cohort, s: SurvivalSettings, idx, mode, parents=None):
@@ -258,7 +293,7 @@ class IntervalFit:
cpt: np.ndarray cpt: np.ndarray
def fit_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None) -> list[IntervalFit]: def fit_kept_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None) -> list[IntervalFit]:
"""The per-interval LR and HBN `interval_predictions` fits on the patients of `idx`, kept instead of applied.""" """The per-interval LR and HBN `interval_predictions` fits on the patients of `idx`, kept instead of applied."""
m, e = c.months[idx], c.event[idx] m, e = c.months[idx], c.event[idx]
fits = [] fits = []
View File
+142
View File
@@ -0,0 +1,142 @@
"""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
CONTEXT_COLUMNS = {"Estadio_cat": "stage", "Tratamiento_quirurgico_cat": "surgery", "Radioterapia_cat": "radiotherapy",
"Quimioterapia_cat": "chemotherapy"}
# 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",
"curva_supervivencia_puntos_LR_HBN.csv": "cohorte_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
# The name the whole cohort's points go by among the subgroups' (`subgroup_points`).
WHOLE_COHORT = "Toda la cohorte"
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, source in CONTEXT_COLUMNS.items():
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy() if source in lm else "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": [c for c, s in CONTEXT_COLUMNS.items() if s not in labelled_members], "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}
def subgroup_points(labelled_members: pd.DataFrame, desarrollo: dict) -> list[dict]:
"""The pipeline's stages 01 and 05 over the members as they are now: the depuration, then the LR and HBN fitted on them with
each clinical scenario's survival at the horizons and its bootstrap interval (`subgrupos_puntos`), and the whole cohort's
(`cohorte_puntos`, as subgroup `WHOLE_COHORT`), one row per model, horizon and scenario. What the dashboard draws as a
scenario's points between trainings."""
from models.cama.seer_survival import pipeline
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")
pipeline.run_pipeline(out, only=["01", "05"], everything=True, settings=_seer_settings(desarrollo))
cohort = pd.read_csv(out / "curva_supervivencia_puntos_LR_HBN.csv").assign(subgrupo=WHOLE_COHORT)
table = pd.concat([pd.read_csv(out / "subgrupos_puntos_LR_HBN.csv"), cohort[["modelo", "meses", "S", "IC_inf", "IC_sup", "subgrupo"]]],
ignore_index=True)
table = table.replace([np.inf, -np.inf], np.nan).astype(object)
return table.where(table.notna(), None).to_dict("records")
+218
View File
@@ -0,0 +1,218 @@
"""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"}
# What describes a member's disease and treatment without being a covariate: the clinical scenarios and the development
# stages read them. The stage is the one reported with the diagnosis; a treatment counts in the first year after it.
CONTEXT = ["stage", "surgery", "radiotherapy", "chemotherapy"]
TREATMENT_DAYS = 365
SURGERY_LABELS = {"SEGMENTECTOMIA": "Cirugía conservadora", "ESCISIONAL": "Cirugía conservadora",
"MASTECTOMIA_TOTAL": "Mastectomía", "MASTECTOMIA_RADICAL_MODIFICADA": "Mastectomía",
"SIN_CIRUGIA": "Sin cirugía"}
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
stage = near[near["tipo"] == "estadio_clinico"].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
members["stage"] = stage.map(lambda v: v[1:] if isinstance(v, str) and v.startswith("E") else v)
treated = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, TREATMENT_DAYS)].sort_values(["fecha", "fuente_id"])
surgery = treated[treated["tipo"] == "cirugia"].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
members["surgery"] = surgery.map(lambda v: SURGERY_LABELS.get(v, "Otra cirugía") if isinstance(v, str) else None)
for kind, name in (("radioterapia", "radiotherapy"), ("quimioterapia", "chemotherapy")):
given = set(treated.loc[treated["tipo"] == kind, "pac_id"])
members[name] = ["Sí" if pac in given else "No" for pac in members.index]
return members[["fecha_indice", *FEATURES, *NUMERIC, *CONTEXT]]
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 = min(pd.Timestamp(cutoff), pd.Timestamp.today().normalize()) # nobody is followed past today
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])
+117
View File
@@ -0,0 +1,117 @@
"""The survival figure of a clinical scenario over the data ingested so far, as the SEER pipeline's survival stage draws a subgroup.
Training and tuning happen in governance; here the production version's results are only shown. 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, or the whole cohort's when she is in none. The
record has the Kaplan-Meier curve of what happened to the scenario's members with its Greenwood band, the classic and fractional
Weibull fitted to their deaths, and the pipeline's LR, HBN and combined survival at each horizon with their bootstrap intervals:
the survival stage's points for the scenario (`development.subgroup_points`), never a model of this module's.
"""
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.development import WHOLE_COHORT
from models.cama.survival.estimator import IntervalSurvival, molecular_subtype, survival_settings
from models.dags.training import Scenario, dataflow
MIN_MEMBERS = 30
MIN_EVENTS = 5
WHOLE = WHOLE_COHORT
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, by her age, molecular subtype, stage and surgery."""
raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy(),
"Estadio_cat": labelled["stage"].to_numpy(), "Tratamiento_quirurgico_cat": labelled["surgery"].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 published_points(rows: list[dict], name: str | None) -> dict | None:
"""The points the pipeline's survival stage published for subgroup `name` (`subgrupos_puntos`, or `cohorte_puntos` for `WHOLE`:
its model with the stage and the treatments, with their bootstrap intervals), by series; `None` when it published none for it."""
found = [r for r in rows if r.get("subgrupo") == (name or WHOLE)]
if not found:
return None
out = {}
for series in population.SERIES:
mine = sorted((r for r in found if r["modelo"] == series), key=lambda r: r["meses"])
if not mine:
return None
out[series] = {"S": [float(r["S"]) for r in mine], "low": [float(r["IC_inf"]) for r in mine],
"high": [float(r["IC_sup"]) for r in mine]}
return out
def curves(scenario: Scenario, labelled: pd.DataFrame, name: str | None, points: dict | None) -> dict:
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone), as the pipeline's survival stage
draws a subgroup: the Kaplan-Meier, and the classic and fractional Weibull fitted to the same members' deaths, with the
stage's `points` for it (`published_points`). `QueryError` for an unknown scenario, one with too few members to say
anything, or one the stage has no points for yet."""
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}.")
if points is None:
raise QueryError("El modelo todavía no tiene la supervivencia de este escenario; se calcula en el siguiente recálculo de indicadores.")
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))
followed, died = selected["months"].to_numpy(int), selected["event"].to_numpy(bool)
months, ended = np.minimum(followed, cap), died & (followed < cap)
S, low, high = luis.fw.km_curva(months, ended, cap)
d, c = luis.fw.tabla_eventos(months, ended)
classic = luis.fw.ajustar_weibull(d, c)
fractional = luis.fw.ajustar_ks(d, c, k_fijo=luis._fixed_k(classic, s), lam_ref=classic["lam"], max_seg=s.ks_sub_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(ended.sum()), "median_follow_up_months": float(np.median(followed)),
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": int(s.n_boot if name in (None, WHOLE) else s.n_boot_sub),
"km": {"months": list(range(cap + 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": 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}}
+40 -12
View File
@@ -21,22 +21,52 @@ from models.io.lineage import matches
from models.io.registry import ResolvedVersion, registered_name, registry from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import CohortSource, read_metadata, write_once from models.io.storage import CohortSource, read_metadata, write_once
# The config key, logged with the run, of a model whose risks come with their interval (`estimate_frame`).
INTERVAL_PARAM = "risk_interval_level"
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool: 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.""" """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}) 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: def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float],
"""One row per member (in `pac_id` order, as the model gives them) and horizon.""" intervals: bool = False) -> 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. A member without
a risk (NaN: one the model can't place) has no rows. With `intervals`
the model gives three blocks of one column per horizon, the risk and its interval's lower and upper ends
(`ic_bajo`, `ic_alto`)."""
members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable") members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable")
if probabilities.ndim != 2 or len(probabilities) != len(members): width = len(horizons) * (3 if intervals else 1)
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members") if probabilities.ndim != 2 or len(probabilities) != len(members) or probabilities.shape[1] not in (width, width + 1):
risks = probabilities[:, -len(horizons):] raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members and {len(horizons)} horizons"
return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int), + (" with intervals" if intervals else ""))
"fecha_indice": np.repeat(members["fecha_indice"].to_numpy(), len(horizons)), risks, dates = probabilities[:, -width:], members["fecha_indice"].to_numpy()
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)), if probabilities.shape[1] == width + 1:
"probabilidad": risks.ravel().astype(float)}) decided = ~np.isnan(probabilities[:, 0])
members, risks = members[decided], risks[decided]
dates = pd.to_datetime(probabilities[decided, 0], unit="D").date
scored = ~np.isnan(risks[:, :len(horizons)]).any(axis=1) # a member the model can't place (a combination unseen in training)
members, risks, dates = members[scored], risks[scored], dates[scored]
blocks = np.split(risks, 3 if intervals else 1, axis=1)
frame = 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": blocks[0].ravel().astype(float)})
if intervals:
frame["ic_bajo"], frame["ic_alto"] = blocks[1].ravel().astype(float), blocks[2].ravel().astype(float)
return frame
def scored_frame(resolved: ResolvedVersion, cohort_frame: pd.DataFrame) -> pd.DataFrame:
"""The version's estimate of a build's long frame: its model's output at the run's horizons, with the interval
when the run has `INTERVAL_PARAM`."""
params = registry.client.get_run(resolved.run_id).data.params
intervals = params.get(INTERVAL_PARAM) not in (None, "", "None", "null")
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
return estimate_frame(cohort_frame, probabilities, json.loads(params["horizons_years"]), intervals)
def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path, def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
@@ -49,9 +79,7 @@ def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
if already_estimated(output_path, resolved.version, cohort): if already_estimated(output_path, resolved.version, cohort):
return resolved, False return resolved, False
cohort_frame = source.frame() cohort_frame = source.frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"]) risks = scored_frame(resolved, cohort_frame)
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") check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario), provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario),
"modelo_version": resolved.version, "mlflow_run_id": resolved.run_id, "modelo_version": resolved.version, "mlflow_run_id": resolved.run_id,
+32 -5
View File
@@ -8,7 +8,7 @@ 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. 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 `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 it failed if the graph fails. Before running, it stores the graph's drawing as `diagramas/pipeline.svg` (and its `.dot`). `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 `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. members' rows, are kept out of Hamilton's error log; the exception still says which node failed.
""" """
@@ -17,7 +17,7 @@ import hashlib
import json import json
import logging import logging
import tomllib import tomllib
from dataclasses import dataclass from dataclasses import dataclass, field
from importlib import import_module from importlib import import_module
from pathlib import Path from pathlib import Path
from types import ModuleType from types import ModuleType
@@ -49,6 +49,12 @@ class Scenario:
requirements: tuple[str, ...] = () requirements: tuple[str, ...] = ()
# Tables of `model.toml` outside `[config]` that still make a version a different one (`settings_tables`). # Tables of `model.toml` outside `[config]` that still make a version a different one (`settings_tables`).
tables: dict | None = None tables: dict | None = None
# What the model's number is (`[estimand]`): `quantity`, `description`, `outcome`, `index_date`, `horizons_unit`;
# what a screen shows next to each risk. How its interval is computed is the version's report's, not the screen's.
estimand: dict = field(default_factory=dict)
# Whether the cycle scores every member of the cohort with the version in production (`batch_estimates`); off for a
# model whose answers are per clinical scenario, not a risk per member.
batch_estimates: bool = True
@classmethod @classmethod
def from_toml(cls, path: str | Path) -> "Scenario": def from_toml(cls, path: str | Path) -> "Scenario":
@@ -58,7 +64,8 @@ class Scenario:
outcome=found["outcome"], description=found.get("description", ""), outcome=found["outcome"], description=found.get("description", ""),
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"], modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
folder=path.parent, requirements=tuple(found.get("requirements", ())), folder=path.parent, requirements=tuple(found.get("requirements", ())),
tables={name: found[name] for name in found.get("settings_tables", ())} or None) tables={name: found[name] for name in found.get("settings_tables", ())} or None,
estimand=dict(found.get("estimand", {})), batch_estimates=bool(found.get("batch_estimates", True)))
@classmethod @classmethod
def load(cls, domain: str, scenario: str) -> "Scenario": def load(cls, domain: str, scenario: str) -> "Scenario":
@@ -82,8 +89,9 @@ def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Dri
return builder.build() return builder.build()
# What the saver receives: the fitted model and its metrics, and the routines' records when the dataflow has them. # What the saver receives: the fitted model and its metrics, and the routines' records, the population results and the
SAVED = {"fitted_model", "metrics", "routines"} # 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]]: def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]:
@@ -111,6 +119,23 @@ def find_trained(scenario: Scenario, source: CohortSource, environment: str = "D
return None return None
def pipeline_drawing(dr: driver.Driver) -> tuple[str, str | None] | None:
"""The scenario's Hamilton graph as Graphviz source and SVG: every node of its modules and the external inputs,
left to right. The SVG is None when Graphviz's `dot` program is missing; the whole drawing is None when the
`graphviz` package is (the `notebooks` extra)."""
try:
graph = dr.display_all_functions(None, orient="LR", show_schema=False)
except ImportError:
return None
if graph is None: # Hamilton logs the missing `graphviz` and gives nothing
return None
try:
svg = graph.pipe(format="svg", encoding="utf-8")
except Exception: # graphviz.ExecutableNotFound or a failed render: the source still goes
svg = None
return graph.source, svg
def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str: 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 """Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
rows.""" rows."""
@@ -120,6 +145,8 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") ->
try: try:
plain = dataflow(*scenario.modules, config=scenario.config) plain = dataflow(*scenario.modules, config=scenario.config)
required, _ = external_inputs(plain) required, _ = external_inputs(plain)
if drawing := pipeline_drawing(plain):
run.log_diagram("pipeline", *drawing)
loaders = [loader(target=target, source=source) for target, loader in loaders = [loader(target=target, source=source) for target, loader in
(("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source), (("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source),
("cohort_lineage", from_.cohort_source_lineage)) ("cohort_lineage", from_.cohort_source_lineage))
+83 -46
View File
@@ -4,8 +4,8 @@ An EEG is pending when it has an EDF and was never analysed, or was analysed wit
versions, or, being valid, against baselines other than those now in production. One that failed with the current 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. 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`, Each result replaces the EEG's previous checks, metrics, electrode and zone 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 `eeg_metrica`, `eeg_metrica_electrodo` and `eeg_metrica_zona`. 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 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. its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrupted batch keeps what it finished.
@@ -13,18 +13,20 @@ its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrup
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise. `DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
""" """
import uuid import uuid
from collections.abc import Callable, Mapping from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from itertools import batched
from sqlalchemy import case
from sqlmodel import Session, col, delete, select from sqlmodel import Session, col, delete, select
from core.tea.enums import MetricaEeg from core.tea.enums import MetricaEeg
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Pacientes from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, EegMetricaZona, Pacientes
from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions from models.tea.eeg.analyze import Measurement, measure, pipeline, plan, versions
from models.tea.eeg.baselines import Baselines from models.tea.eeg.baselines import Baselines
from models.tea.eeg.settings import Settings, settings as model_settings from models.tea.eeg.settings import Settings, scenario_of, settings as model_settings
COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo" COLUMNS = "eeg_valido,eeg_criterio,eeg_metrica,eeg_metrica_electrodo"
@@ -38,10 +40,26 @@ def checked_settings() -> Settings:
return s return s
def selected_ids(session: Session, ids: Sequence[int | str]) -> list[str]:
"""Resolve requested IDs and return the ones with stored EDFs."""
requested = {str(eeg_id) for eeg_id in ids}
has_edf = case((Eeg.eeg_estudio.is_not(None), 1), else_=0)
found = {}
for group in batched(requested, 500):
query = select(Eeg.eeg_id, has_edf).where(col(Eeg.eeg_id).in_(group))
found.update(session.exec(query).all())
missing = sorted(requested - found.keys())
if missing:
raise LookupError(f"No se encontraron los EEG: {', '.join(missing)}")
return sorted(eeg_id for eeg_id, stored in found.items() if stored)
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]], 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]: everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None) -> list[str]:
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed """`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.""" with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
if ids is not None:
return selected_ids(session, ids)
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where( 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) Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
out, expected = [], None out, expected = [], None
@@ -83,6 +101,7 @@ class Rows:
criteria: list[EegCriterio] criteria: list[EegCriterio]
metrics: list[EegMetrica] metrics: list[EegMetrica]
electrodes: list[EegMetricaElectrodo] electrodes: list[EegMetricaElectrodo]
zones: list[EegMetricaZona]
def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows: def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None = None) -> Rows:
@@ -108,23 +127,34 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None
)) ))
by_code = {metric.code: metric for metric in s.metrics} by_code = {metric.code: metric for metric in s.metrics}
metrics, electrodes = [], [] metrics, electrodes, zones = [], [], []
for value in m.metrics: for value in m.metrics:
metric = by_code[value.code] metric = by_code[value.code]
met_id = row_id(m.key, "metrica", value.code) met_id = row_id(m.key, "metrica", value.code)
deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months) deviation = baselines.deviation(metric.scenario, metric.feature, value.value, m.age_months, value.exposure)
used = [metric.scenario] if deviation is not None else [] used = [metric.scenario] if deviation is not None else []
for electrode, raw in sorted(value.electrodes.items()): for electrode, raw in sorted(value.electrodes.items()):
at_electrode = None at_electrode = None
if metric.electrode_scenario: if metric.electrode_scenario:
at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode, at_electrode = baselines.deviation(metric.electrode_scenario, metric.electrode_prefix + electrode,
raw, m.age_months) raw, m.age_months, value.exposure)
if at_electrode is not None and metric.electrode_scenario not in used: if at_electrode is not None and metric.electrode_scenario not in used:
used.append(metric.electrode_scenario) used.append(metric.electrode_scenario)
electrodes.append(EegMetricaElectrodo( electrodes.append(EegMetricaElectrodo(
mel_id=row_id(m.key, "metrica", value.code, electrode), mel_met_id=met_id, mel_electrodo=electrode, 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, mel_valor=raw, mel_z=at_electrode.z if at_electrode else None,
)) ))
for zone, raw in sorted(value.zones.items()):
at_zone = None
if metric.zone_scenario:
at_zone = baselines.deviation(metric.zone_scenario, metric.zone_prefix + zone, raw, m.age_months,
value.exposure)
if at_zone is not None and metric.zone_scenario not in used:
used.append(metric.zone_scenario)
zones.append(EegMetricaZona(
mez_id=row_id(m.key, "metrica", value.code, "zona", zone), mez_met_id=met_id, mez_zona=zone,
mez_valor=raw, mez_z=at_zone.z if at_zone else None,
))
metrics.append(EegMetrica( metrics.append(EegMetrica(
met_id=met_id, met_eeg_id=m.key, met_codigo=value.code, met_valor=value.value, 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_z=deviation.z if deviation else None, met_fuera=deviation.outside if deviation else None,
@@ -132,7 +162,7 @@ def rows(m: Measurement, s: Settings, baselines: Baselines, at: datetime | None
met_p95=deviation.p95 if deviation else None, met_p95=deviation.p95 if deviation else None,
met_modelo=";".join(baselines.label(scenario) for scenario in used) or None, met_modelo=";".join(baselines.label(scenario) for scenario in used) or None,
)) ))
return Rows(eeg, criteria, metrics, electrodes) return Rows(eeg, criteria, metrics, electrodes, zones)
def save(session: Session, eeg_id: str, new: Rows) -> None: def save(session: Session, eeg_id: str, new: Rows) -> None:
@@ -145,10 +175,11 @@ def save(session: Session, eeg_id: str, new: Rows) -> None:
session.add(eeg) session.add(eeg)
metric_ids = select(EegMetrica.met_id).where(EegMetrica.met_eeg_id == eeg_id) 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(EegMetricaElectrodo).where(col(EegMetricaElectrodo.mel_met_id).in_(metric_ids)))
session.exec(delete(EegMetricaZona).where(col(EegMetricaZona.mez_met_id).in_(metric_ids)))
session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id)) session.exec(delete(EegMetrica).where(EegMetrica.met_eeg_id == eeg_id))
session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id)) session.exec(delete(EegCriterio).where(EegCriterio.cri_eeg_id == eeg_id))
session.flush() session.flush()
session.add_all([*new.criteria, *new.metrics, *new.electrodes]) session.add_all([*new.criteria, *new.metrics, *new.electrodes, *new.zones])
def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings): def extraction_run(m: Measurement, started: datetime, ended: datetime, s: Settings):
@@ -181,7 +212,7 @@ class Summary:
def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]: def expected_models(s: Settings, baselines: Baselines) -> dict[str, str | None]:
out = {} out = {}
for m in s.metrics: for m in s.metrics:
scenarios = [m.scenario, m.electrode_scenario] if m.electrode_scenario else [m.scenario] scenarios = [scenario_of(n, m.phase) for n in m.readers]
out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None out[m.code] = ";".join(label for label in map(baselines.label, scenarios) if label) or None
return out return out
@@ -190,47 +221,53 @@ def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None) return datetime.now(timezone.utc).replace(tzinfo=None)
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16, def analyze_pending(*, everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None,
cluster: str = "auto", batch: int = 16,
settings: Settings | None = None, baselines: Baselines | None = None, settings: Settings | None = None, baselines: Baselines | None = None,
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary: measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
from tea.pipeline.dask_runner import run as run_batch from tea.pipeline.dask_runner import run as run_batch
from tea.pipeline.run_monitor import monitor_from_env
from persistance.tea import eeg_repository from persistance.tea import eeg_repository
s = settings or checked_settings() with monitor_from_env() as monitor:
b = baselines or Baselines(s.domain) s = settings or checked_settings()
pipe = pipeline(s) b = baselines or Baselines(s.domain)
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s) pipe = pipeline(s)
with eeg_repository.open_session() as session: plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
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: with eeg_repository.open_session() as session:
save(session, m.key, rows(m, s, b, at=ended)) selected = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
session.commit() everything=everything, limit=limit, ids=ids)
if log_runs: summary = Summary(pending=len(selected))
from persistance.governance import extraction_run_repository monitor.total(summary.pending)
monitor.phase("analizando")
extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s)) def write(m: Measurement) -> None:
if m.error: ended = _now()
summary.failed += 1 with eeg_repository.open_session() as session:
elif m.valid: save(session, m.key, rows(m, s, b, at=ended))
summary.valid += 1 session.commit()
else: monitor.advance()
summary.not_valid += 1 if log_runs:
from persistance.governance import extraction_run_repository
def lost(args, exc) -> Measurement: extraction_run_repository.create(extraction_run(m, ended - timedelta(seconds=m.seconds), ended, s))
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current, if m.error:
error=f"{type(exc).__name__}: the batch lost this study") summary.failed += 1
elif m.valid:
summary.valid += 1
else:
summary.not_valid += 1
for start in range(0, len(ids), batch): def lost(args, exc) -> Measurement:
argsets = [] return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
with eeg_repository.open_session() as session: error=f"{type(exc).__name__}: the batch lost this study")
for eeg_id in ids[start:start + batch]:
edf, age = inputs(session, eeg_id, s.days_per_month) for start in range(0, len(selected), batch):
argsets.append((eeg_id, edf, age, s)) argsets = []
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost) with eeg_repository.open_session() as session:
return summary for eeg_id in selected[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, track_progress=False)
return summary
+8 -2
View File
@@ -6,8 +6,10 @@ anything runs and nothing in the model imports MLflow:
- `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage", - `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). source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file).
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines"], ...)`: records - `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines", "population",
each routine (ML-01a, `TrainingRun.log_routine`), logs the fitted model in the open `TrainingRun` (`tracking`), "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 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 is the version's metadata. A dataflow without `routines` still trains and registers, but the registry won't promote
it (`ROUTINE_KINDS`). it (`ROUTINE_KINDS`).
@@ -114,6 +116,10 @@ class RegisteredModelSaver(DataSaver):
model, metrics = data["fitted_model"], _numbers(data["metrics"]) model, metrics = data["fitted_model"], _numbers(data["metrics"])
for kind, record in data.get("routines", {}).items(): for kind, record in data.get("routines", {}).items():
self.run.log_routine(kind, record) 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) packages = _own_packages(model)
for package in packages: for package in packages:
cloudpickle.register_pickle_by_value(package) cloudpickle.register_pickle_by_value(package)
+6 -1
View File
@@ -48,7 +48,12 @@ ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0)), {"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False), "fecha_indice": pandera.Column(nullable=False),
"horizonte_anios": pandera.Column(float, pandera.Check.ge(0)), "horizonte_anios": pandera.Column(float, pandera.Check.ge(0)),
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))}, "probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1)),
# the risk's interval, from a model that gives one (NaN where it can't)
"ic_bajo": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False),
"ic_alto": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False)},
checks=pandera.Check(lambda f: ~(f["ic_bajo"] > f["probabilidad"]) & ~(f["ic_alto"] < f["probabilidad"])
if "ic_bajo" in f else pd.Series(True, index=f.index), error="ic_bajo <= probabilidad <= ic_alto"),
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate") strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables" POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables"
+15 -3
View File
@@ -125,6 +125,14 @@ class ModelRegistry:
def status(self, domain: str, scenario: str, version: str) -> str: def status(self, domain: str, scenario: str, version: str) -> str:
return self._status(self.get(domain, scenario, version)) return self._status(self.get(domain, scenario, version))
def in_production(self, domain: str) -> list[str]:
"""The scenarios of `domain` with a version holding the `produccion` alias, by name."""
if domain not in DOMAINS:
raise ValueError(f"dominio desconocido: {domain!r}")
prefix = registered_name(domain, "")
models = self.client.search_registered_models(filter_string=f"name LIKE '{prefix}%'")
return sorted(m.name.removeprefix(prefix) for m in models if PRODUCTION_ALIAS in (m.aliases or {}))
def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion: def resolve(self, domain: str, scenario: str, version: str | None = None) -> ResolvedVersion:
"""With no `version`, the one holding the `produccion` alias; with a version, that one, whatever """With no `version`, the one holding the `produccion` alias; with a version, that one, whatever
its status (to test or compare a candidate). The status travels with it: confirming risks only its status (to test or compare a candidate). The status travels with it: confirming risks only
@@ -236,7 +244,10 @@ class ModelRegistry:
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing. # 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 reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
metrics = run.data.metrics 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, "") sha = mv.tags.get(MODEL_SHA_TAG, "")
if armado is not None: if armado is not None:
cohort_detail = f"huella {armado['huella'][:12]}" cohort_detail = f"huella {armado['huella'][:12]}"
@@ -258,8 +269,9 @@ class ModelRegistry:
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-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-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("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, PromotionCheck("ML-01a", "rutina registrada por la corrida de entrenamiento", bool(run.info.run_id),
f"faltan: {', '.join(missing)}" if missing else f"{len(ROUTINE_KINDS)} de {len(ROUTINE_KINDS)}"), 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]), PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
] ]
+20
View File
@@ -50,6 +50,9 @@ from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT" ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model" MODEL_PATH = "model"
ROUTINES_PATH = "rutinas" ROUTINES_PATH = "rutinas"
ANALYSIS_PATH = "analisis"
REPORTS_PATH = "reportes"
DIAGRAMS_PATH = "diagramas"
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one. # 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, ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA) ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
@@ -191,6 +194,23 @@ class TrainingRun:
that too (for instance a class balance of "none"), so the run still says what happened.""" 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)) self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
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_diagram(self, name: str, dot: str, svg: str | None = None) -> None:
"""A drawing of the run's dataflow, `diagramas/<name>.dot` (Graphviz source) and, when Graphviz's `dot` could
draw it, `diagramas/<name>.svg`: each one more file of the version, listed and downloaded on its own."""
self.client.log_text(self.run_id, dot, f"{DIAGRAMS_PATH}/{name}.dot")
if svg is not None:
self.client.log_text(self.run_id, svg, f"{DIAGRAMS_PATH}/{name}.svg")
def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str: 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. """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 Once per run. `signature` describes columns and types only: no input example, so no patient data
+15 -1
View File
@@ -85,6 +85,9 @@ class QuartoRenderer(NotebookRenderer):
return page.read_text() return page.read_text()
HIDE_INPUT_TAG = "remove_input" # what a `#| echo: false` cell gets before the page is exported
@register_renderer @register_renderer
class JupyterRenderer(NotebookRenderer): class JupyterRenderer(NotebookRenderer):
"""The kernel is the one the notebook names, which must be installed beside this package (`python3` is this """The kernel is the one the notebook names, which must be installed beside this package (`python3` is this
@@ -121,7 +124,18 @@ class JupyterRenderer(NotebookRenderer):
@staticmethod @staticmethod
def _page(exporter, node) -> str: 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 return body
+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()))
+20 -1
View File
@@ -17,6 +17,10 @@ Kinds:
later colposcopy; out, in order: `biopsia_sin_resultado`, `cin2_hasta_el_indice`, `antecedente_cacu`, later colposcopy; out, in order: `biopsia_sin_resultado`, `cin2_hasta_el_indice`, `antecedente_cacu`,
`histerectomia`, `tratamiento_previo`, `sin_referencia`, `sin_cotest` (k ≥ 1). `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 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 `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 earlier events ("no CIN2+ before the index", "first colposcopy", the referral year) reads only what was recorded, so
@@ -127,7 +131,22 @@ def _post_colposcopy(events: list[dict], index: dict) -> tuple[date | None, list
return fecha, flags return fecha, flags
KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposcopy} 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 _first_invasive_biopsy(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]: def _first_invasive_biopsy(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
+13 -5
View File
@@ -1,15 +1,23 @@
"""From an estimate's rows to the risks a batch stores: `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo, """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.""" ic_alto)`; `fecha_indice` is the model's index date for the member, which its horizons count from."""
import numpy as np
import pandas as pd import pandas as pd
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
def risk_rows(estimate: pd.DataFrame) -> list[tuple]: 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 """One risk per member and horizon, with its interval when the estimate has one, once the rows satisfy
twice at one horizon or a probability outside 0..1 stops the batch.""" `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") check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), None, None) missing = pd.Series(np.nan, index=estimate.index)
for pac_id, fecha, horizon, probability in zip(estimate["pac_id"], estimate["fecha_indice"], low, high = estimate.get("ic_bajo", missing), estimate.get("ic_alto", missing)
estimate["horizonte_anios"], estimate["probabilidad"])]
def value(v):
return None if pd.isna(v) else float(v)
return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), value(lo), value(hi))
for pac_id, fecha, horizon, probability, lo, hi in zip(estimate["pac_id"], estimate["fecha_indice"],
estimate["horizonte_anios"],
estimate["probabilidad"], low, high)]
+1 -1
View File
@@ -1 +1 @@
"""TEA's models: the EEG analysis (`eeg`).""" """TEA's models: the EEG analysis (`eeg`) and the ADOS-2 association (`ados2`)."""
+2
View File
@@ -0,0 +1,2 @@
"""TEA's ADOS-2 association: the `tea` library module and the metrics it reads (`model.toml`); fitted on the
database by `models.ados2_relation`."""
+13
View File
@@ -0,0 +1,13 @@
# The ADOS-2 association: the `tea` library's cohort-level module, and the stored EEG metric each of its biomarkers
# reads. Spike and spindle predictors are the metric's zone z (`eeg_metrica_zona`); the posterior rhythm and the
# gradient are the metric's own z (`eeg_metrica.met_z`).
association = "ados2_association"
impl = "modern"
# "auto": by item when the cohort has ADOS-2 item scores, by the CSS otherwise; or "item", "domain".
level = "auto"
[biomarkers]
spikes = "PICOS_PAROXISTICOS"
spindles = "HUSOS_SUENO_N2"
posterior_rhythm = "RITMO_POSTERIOR"
gradient = "GRADIENTE_ANTEROPOSTERIOR"
+20
View File
@@ -0,0 +1,20 @@
"""The ADOS-2 association's settings (`model.toml`): the library module, its implementation and level, and the
stored EEG metric each of its biomarkers reads."""
import tomllib
from dataclasses import dataclass
from functools import cache
from pathlib import Path
@dataclass(frozen=True)
class Settings:
association: str
impl: str
level: str
biomarkers: dict[str, str] # library biomarker -> `MetricaEeg` code
@cache
def settings(path: Path = Path(__file__).with_name("model.toml")) -> Settings:
raw = tomllib.loads(path.read_text())
return Settings(raw["association"], raw["impl"], raw["level"], dict(raw["biomarkers"]))
+17 -11
View File
@@ -46,6 +46,8 @@ class MetricValue:
code: str code: str
value: float | None value: float | None
electrodes: dict[str, float | None] = field(default_factory=dict) electrodes: dict[str, float | None] = field(default_factory=dict)
zones: dict[str, float | None] = field(default_factory=dict)
exposure: float | None = None # what a count baseline divides the value, electrodes and zones by
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -90,7 +92,7 @@ def processes(pipe, settings: Settings) -> list[str]:
the phased biomarkers contribute only what their stage's detector requires.""" the phased biomarkers contribute only what their stage's detector requires."""
from tea.pipeline.run_study import order_for 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] needs = [n for m in settings.metrics if not m.phase for n in m.readers]
requires = {r for n in needs for r in pipe.module(n).requires} requires = {r for n in needs for r in pipe.module(n).requires}
for phase in settings.phases: for phase in settings.phases:
requires.update(phase_detector(pipe, phase).requires) requires.update(phase_detector(pipe, phase).requires)
@@ -158,22 +160,26 @@ def features(pipe, study, settings: Settings) -> Features:
by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study)) by_phase[phase] = study.with_labels(phase_detector(pipe, phase).predict(study))
out: Features = {} out: Features = {}
for m in settings.metrics: for m in settings.metrics:
for biomarker in (m.biomarker, m.electrodes): for biomarker in m.readers:
if biomarker and (biomarker, m.phase) not in out: if (biomarker, m.phase) not in out:
out[biomarker, m.phase] = {k: _number(v) for k, v in out[biomarker, m.phase] = {k: _number(v) for k, v in
pipe.module(biomarker).measure(by_phase[m.phase]).items()} pipe.module(biomarker).measure(by_phase[m.phase]).items()}
return out return out
def _prefixed(measured: Features, biomarker: str | None, phase: str | None, prefix: str) -> dict[str, float | None]:
"""The features of `biomarker` whose name starts with `prefix`, by the rest of the name."""
if not biomarker:
return {}
return {name.removeprefix(prefix): v for name, v in measured[biomarker, phase].items() if name.startswith(prefix)}
def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]: def _metrics(measured: Features, settings: Settings) -> tuple[MetricValue, ...]:
out = [] return tuple(MetricValue(m.code, measured[m.biomarker, m.phase].get(m.feature),
for m in settings.metrics: _prefixed(measured, m.electrodes, m.phase, m.electrode_prefix),
electrodes = {} _prefixed(measured, m.zones, m.phase, m.zone_prefix),
if m.electrodes: measured[m.biomarker, m.phase].get(m.exposure) if m.exposure else None)
electrodes = {name.removeprefix(m.electrode_prefix): v for name, v in measured[m.electrodes, m.phase].items() for m in settings.metrics)
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: def _error(exc: Exception) -> str:
+26 -6
View File
@@ -47,9 +47,15 @@ def _load(model_uri: str):
sys.path[:] = path sys.path[:] = path
def _takes_exposure(baseline) -> bool:
import inspect
return "exposure" in inspect.signature(baseline.deviation).parameters
def _feature_baseline(module, feature: str): def _feature_baseline(module, feature: str):
baselines = getattr(module, "baselines", None) baselines = getattr(module, "baselines", None)
return baselines[feature] if baselines is not None else module.baseline return baselines.get(feature) if baselines is not None else module.baseline
def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]: def centiles(baseline, age_months: float) -> tuple[float | None, float | None, float | None]:
@@ -103,16 +109,30 @@ class Baselines:
self._loaded[scenario] = _load(resolved.model_uri) self._loaded[scenario] = _load(resolved.model_uri)
return self._loaded[scenario] return self._loaded[scenario]
def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None) -> Deviation | None: def deviation(self, scenario: str, feature: str, value: float | None, age_months: float | None,
exposure: float | None = None) -> Deviation | None:
"""None without a baseline in production; with one, a deviation whose fields are null where the value or """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.""" the age is missing or the curve doesn't cover the age. `exposure` reaches a baseline that takes one (a count
against its minutes), whose p5, median and p95 are then the rates expected in those minutes; the others
ignore it."""
module = self.module(scenario) module = self.module(scenario)
if module is None: if module is None:
return None return None
baseline = _feature_baseline(module, feature) baseline = _feature_baseline(module, feature)
if baseline is None:
return None
if value is None or age_months is None: if value is None or age_months is None:
return Deviation(None, None, None, None, None) return Deviation(None, None, None, None, None)
outside, z = baseline.deviation(np.array([value], float), np.array([age_months], float)) args = (np.array([value], float), np.array([age_months], float))
minutes = np.array([np.nan if exposure is None else exposure], float)
if _takes_exposure(baseline):
outside, z = baseline.deviation(*args, exposure=minutes)
else:
outside, z = baseline.deviation(*args)
z_value = _number(z[0]) z_value = _number(z[0])
p5, median, p95 = centiles(baseline, age_months) if hasattr(baseline, "percentiles"):
return Deviation(z_value, int(outside[0]) if z_value is not None else None, p5, median, p95) p5, median, p95 = (_number(v) for v in baseline.percentiles(args[1], minutes)[0])
else:
p5, median, p95 = centiles(baseline, age_months)
outside_value = _number(outside[0])
return Deviation(z_value, int(outside_value) if outside_value is not None else None, p5, median, p95)
+9 -1
View File
@@ -6,11 +6,19 @@ then promoting each through the registry's checks. `--reference-dir` trains on a
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`). instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
""" """
import argparse import argparse
import os
import sys import sys
from models.tea.eeg.settings import settings from models.tea.eeg.settings import settings
SETTINGS = settings() SETTINGS = settings()
CLUSTERS = ("auto", "local", "remote", "sync")
def _cluster() -> str:
"""Where training measures the studies: `EEG_ANALYSIS_CLUSTER` when it names a runner, else `auto`."""
chosen = os.environ.get("EEG_ANALYSIS_CLUSTER", "auto")
return chosen if chosen in CLUSTERS else "auto"
def run_steps(args: argparse.Namespace) -> int: def run_steps(args: argparse.Namespace) -> int:
@@ -32,7 +40,7 @@ def run_steps(args: argparse.Namespace) -> int:
return 2 return 2
versions: dict[str, str] = {} versions: dict[str, str] = {}
if args.train: if args.train:
for scenario, (version, new) in train.train_all(s, environment).items(): for scenario, (version, new) in train.train_all(s, environment, cluster=_cluster()).items():
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}") print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
versions[scenario] = version versions[scenario] = version
if not args.promote: if not args.promote:
+13 -1
View File
@@ -18,7 +18,10 @@ line_hz = 50.0
ages = [16.0, 36.0] ages = [16.0, 36.0]
# One entry per `MetricaEeg` code. `phase` runs spindle detection on that sleep stage alone; `electrodes` names the # 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. # biomarker whose `<electrode_prefix><electrode>` features are the metric's value per 10-20 electrode, and `zones` the
# one whose `<zone_prefix><zone>` features are its value per scalp zone (`tea.contracts.ZONES`), which the ADOS-2
# association reads. `exposure` names the feature a count baseline divides by: spikes are counted against the
# minutes they were looked for in, since most children of the reference have none.
# The feature each metric maps to is provisional until the domain expert confirms it. # The feature each metric maps to is provisional until the domain expert confirms it.
[[metrics]] [[metrics]]
code = "RITMO_POSTERIOR" code = "RITMO_POSTERIOR"
@@ -32,6 +35,8 @@ phase = "N2"
feature = "spindle_density_per_min_channel" feature = "spindle_density_per_min_channel"
electrodes = "spindle_topography" electrodes = "spindle_topography"
electrode_prefix = "topo_enh_" electrode_prefix = "topo_enh_"
zones = "spindles"
zone_prefix = "spindle_zone_"
[[metrics]] [[metrics]]
code = "HUSOS_SUENO_N3" code = "HUSOS_SUENO_N3"
@@ -40,11 +45,18 @@ phase = "N3"
feature = "spindle_density_per_min_channel" feature = "spindle_density_per_min_channel"
electrodes = "spindle_topography" electrodes = "spindle_topography"
electrode_prefix = "topo_enh_" electrode_prefix = "topo_enh_"
zones = "spindles"
zone_prefix = "spindle_zone_"
[[metrics]] [[metrics]]
code = "PICOS_PAROXISTICOS" code = "PICOS_PAROXISTICOS"
biomarker = "spikes" biomarker = "spikes"
feature = "spike_rate_nrem" feature = "spike_rate_nrem"
electrodes = "spikes"
electrode_prefix = "spike_density_nrem_"
zones = "spikes"
zone_prefix = "spike_zone_rate_nrem_"
exposure = "spike_minutes_nrem"
[[metrics]] [[metrics]]
code = "GRADIENTE_ANTEROPOSTERIOR" code = "GRADIENTE_ANTEROPOSTERIOR"
+15 -3
View File
@@ -17,6 +17,9 @@ class Metric:
phase: str | None = None phase: str | None = None
electrodes: str | None = None electrodes: str | None = None
electrode_prefix: str = "" electrode_prefix: str = ""
zones: str | None = None
zone_prefix: str = ""
exposure: str | None = None # the biomarker's feature a count baseline divides by (its minutes)
@property @property
def scenario(self) -> str: def scenario(self) -> str:
@@ -26,6 +29,15 @@ class Metric:
def electrode_scenario(self) -> str | None: def electrode_scenario(self) -> str | None:
return scenario_of(self.electrodes, self.phase) if self.electrodes else None return scenario_of(self.electrodes, self.phase) if self.electrodes else None
@property
def zone_scenario(self) -> str | None:
return scenario_of(self.zones, self.phase) if self.zones else None
@property
def readers(self) -> tuple[str, ...]:
"""The biomarkers the metric reads: its own, its electrodes' and its zones'."""
return tuple(dict.fromkeys(n for n in (self.biomarker, self.electrodes, self.zones) if n))
@dataclass(frozen=True) @dataclass(frozen=True)
class Reference: class Reference:
@@ -55,13 +67,13 @@ class Settings:
@property @property
def scenarios(self) -> dict[str, tuple[str, str | None]]: def scenarios(self) -> dict[str, tuple[str, str | None]]:
"""Each baseline to train, by scenario: (biomarker, sleep stage).""" """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] pairs = [(n, m.phase) for m in self.metrics for n in m.readers]
return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)} return {scenario_of(b, phase): (b, phase) for b, phase in dict.fromkeys(pairs)}
@property @property
def biomarkers(self) -> tuple[str, ...]: def biomarkers(self) -> tuple[str, ...]:
"""Every biomarker a metric reads, its own or its electrodes'.""" """Every biomarker a metric reads, its own, its electrodes' or its zones'."""
names = [n for m in self.metrics for n in (m.biomarker, m.electrodes) if n] names = [n for m in self.metrics for n in m.readers]
return tuple(dict.fromkeys(names)) return tuple(dict.fromkeys(names))
+24 -14
View File
@@ -19,6 +19,7 @@ from dataclasses import dataclass
from pathlib import Path from pathlib import Path
import pandas as pd import pandas as pd
from tea.pipeline.run_monitor import active_monitor, monitor_from_env
from models.io.lineage import ( from models.io.lineage import (
COHORT_BUILD_TAG, COHORT_BUILD_TAG,
@@ -78,7 +79,7 @@ def list_reference(s: Settings) -> list[tuple[str, float]]:
def listing(s: Settings, cluster: str = "auto") -> Listing: def listing(s: Settings, cluster: str = "auto") -> Listing:
from tea.pipeline.dask_runner import run as run_batch from tea.pipeline.dask_runner import run as run_batch
(found,) = run_batch(list_reference, [(s,)], cluster=cluster) (found,) = run_batch(list_reference, [(s,)], cluster=cluster, track_progress=False)
return Listing.of(s.reference.name, found) return Listing.of(s.reference.name, found)
@@ -146,9 +147,14 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
biomarker, phase = s.scenarios[scenario] biomarker, phase = s.scenarios[scenario]
data = table(studies, biomarker, phase) data = table(studies, biomarker, phase)
module = type(pipeline(s).module(biomarker))(baseline=s.baseline) module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
monitor = active_monitor()
if monitor is not None:
monitor.phase("ajustando")
module.train(data) module.train(data)
sha, state = _module_state(module) sha, state = _module_state(module)
name = registered_name(DOMAIN, scenario) name = registered_name(DOMAIN, scenario)
if monitor is not None:
monitor.phase("registrando")
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns. # Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
experiment_id(MlflowClient(), name) experiment_id(MlflowClient(), name)
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data), mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
@@ -210,19 +216,23 @@ def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Li
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same """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 listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
scenario needs it.""" scenario needs it."""
found = found or listing(s, cluster) with monitor_from_env() as monitor:
out, pending = {}, [] found = found or listing(s, cluster)
for scenario in s.scenarios: out, pending = {}, []
existing = find_trained(scenario, expected_tags(scenario, found, s, environment)) for scenario in s.scenarios:
if existing is not None: existing = find_trained(scenario, expected_tags(scenario, found, s, environment))
out[scenario] = (str(existing.version), False) if existing is not None:
else: out[scenario] = (str(existing.version), False)
pending.append(scenario) else:
if pending: pending.append(scenario)
studies = studies if studies is not None else measure(found, s, cluster) if pending:
for scenario in pending: if studies is None:
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True) monitor.total(len(found.studies))
return out monitor.phase("midiendo")
studies = 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): def latest(scenario: str, environment: str):
+10
View File
@@ -38,6 +38,14 @@ seer-survival = [
"networkx>=3.0", "networkx>=3.0",
"mpmath>=1.3", "mpmath>=1.3",
"matplotlib>=3.8", "matplotlib>=3.8",
"lifelines>=0.28", # the recurrence analysis' penalised Cox model (`models.cama.recurrence`)
]
# The population curves of a survival training run (`models.cama.survival.population`): the fractional Weibull's series;
# plotly for the CaCu survival scenario's subgroup page.
survival-curves = [
"scipy>=1.11",
"mpmath>=1.3",
"plotly>=5.18", # the CaCu survival scenario's subgroup report page (`models.cacu.survival.report`)
] ]
seer-survival-dca = ["dcurves>=1.1"] seer-survival-dca = ["dcurves>=1.1"]
@@ -62,9 +70,11 @@ dev = [
"scipy>=1.11", "scipy>=1.11",
"statsmodels>=0.14", "statsmodels>=0.14",
"pgmpy>=1.0", "pgmpy>=1.0",
"lifelines>=0.28",
"networkx>=3.0", "networkx>=3.0",
"mpmath>=1.3", "mpmath>=1.3",
"matplotlib>=3.8", "matplotlib>=3.8",
"plotly>=5.18",
"nbclient>=0.10", "nbclient>=0.10",
"nbconvert>=7.16", "nbconvert>=7.16",
"ipykernel>=6.29", "ipykernel>=6.29",
+141
View File
@@ -0,0 +1,141 @@
table,outcome,group,curve,knots,gamma,eta,cr0,cr1,cr2,cr3,cr4,cr5,max_abs
1,CIN2+,HPV negativo,AGC,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",0.0,0.0241115195644835,0.0256092196204436,0.0268181400278813,0.028171784403177,0.0297901538513425,0.031523974593383,4.440892098500626e-16
1,CIN2+,HPV negativo,ASC-H,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",0.675059058469885,0.0953469396720264,0.0980718969717476,0.100268497329922,0.102724939896397,0.10565744916419,0.108793929166055,4.440892098500626e-16
1,CIN2+,HPV negativo,ASC-US,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",0.3716720902899113,0.0006886909862562,0.00291195228696667,0.00470541300218982,0.00671238510720408,0.00911019894943088,0.0116770710796392,4.440892098500626e-16
1,CIN2+,HPV negativo,HSIL+,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",2.0164005981856348,0.468287640749052,0.474386433098624,0.47926496337816,0.484680892189583,0.491091841584196,0.497883312012614,4.440892098500626e-16
1,CIN2+,HPV negativo,LSIL,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",1.0694381631654704,0.0321089460773336,0.036430742300162,0.0399099701641632,0.0437959045534305,0.0484282146868277,0.05337460404111,4.440892098500626e-16
1,CIN2+,HPV negativo,NILM,"[0.0, 3.749999999999426, 10.992706060410129]","[-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106]",-0.6656887215701865,3.90353647266218e-05,0.000828013277650686,0.00146529413171444,0.00217932287701656,0.00303362524453662,0.00394964078320864,4.440892098500626e-16
1,CIN2+,HPV positivo,AGC,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",0.0,0.400884761372207,0.423177327520334,0.453148774204697,0.47722331054264,0.491809730088738,0.500142601911983,7.771561172376096e-16
1,CIN2+,HPV positivo,ASC-H,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",0.2126697727739812,0.501106699178966,0.523966961254572,0.554371985820979,0.578511314319372,0.593010085492955,0.601248908320567,7.771561172376096e-16
1,CIN2+,HPV positivo,ASC-US,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",-0.7533953307304859,0.134977733606003,0.150282229405366,0.171360576935273,0.188738761408003,0.19947466518464,0.205681128069832,7.771561172376096e-16
1,CIN2+,HPV positivo,HSIL+,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",0.007560314353099129,0.768895742132862,0.777558954414099,0.789202267331941,0.798551251948637,0.80421408879622,0.807448580381107,7.771561172376096e-16
1,CIN2+,HPV positivo,LSIL,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",-0.7121375835534804,0.150720429636477,0.166373432071245,0.187912288999706,0.205652819554319,0.216604598846303,0.222933043955648,7.771561172376096e-16
1,CIN2+,HPV positivo,NILM,"[0.0, 3.7291666666669765, 7.200620785886926]","[-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466]",-0.9861148498309161,0.0498612570542781,0.0632060742965726,0.0816675057209598,0.0969615559339089,0.106443878949773,0.111937675985206,7.771561172376096e-16
1,CIN3+,HPV negativo,AGC,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",0.0,0.0106844641637163,0.0115079789994108,0.0121411816481693,0.0128347160639286,0.0136669643759362,0.0145666781897423,3.3306690738754696e-16
1,CIN3+,HPV negativo,ASC-H,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",-0.04872187576775001,0.0342206380443041,0.034986346556643,0.0355751224053339,0.0362200176140623,0.0369939268279508,0.0378306072669854,3.3306690738754696e-16
1,CIN3+,HPV negativo,ASC-US,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",-0.09879946244479822,0.000397811063724171,0.00115163989720337,0.0017313009790938,0.00236623247962954,0.00312821209932418,0.00395202899225357,3.3306690738754696e-16
1,CIN3+,HPV negativo,HSIL+,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",2.004887966546689,0.252144671903415,0.256754712682076,0.260282641941786,0.264130077325419,0.268724170611435,0.273662742092822,3.3306690738754696e-16
1,CIN3+,HPV negativo,LSIL,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",0.8576201610700221,0.0105183209491033,0.0124590219555563,0.013949740055348,0.0155810064976098,0.017536490040242,0.0196479749836111,3.3306690738754696e-16
1,CIN3+,HPV negativo,NILM,"[0.0, 3.7500000000006812, 7.523483812808309]","[-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815]",-1.174571179173883,2.28864043889962e-05,0.000280128375297359,0.000478023113087691,0.000694873939389557,0.000955236140567136,0.00123687521303424,3.3306690738754696e-16
1,CIN3+,HPV positivo,AGC,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",0.0,0.262739413900099,0.276609416274342,0.302317768969549,0.324522607011181,0.338063429715532,0.345343732440977,3.885780586188048e-16
1,CIN3+,HPV positivo,ASC-H,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-0.09530733394718151,0.25730149160114,0.270014560302542,0.293637521742104,0.314104857280649,0.326616057076886,0.333352370721709,3.885780586188048e-16
1,CIN3+,HPV positivo,ASC-US,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-1.3767188384949076,0.0444540193603678,0.0490236673279738,0.0576697985578552,0.0653314891820387,0.0700965762622234,0.0726887422509778,3.885780586188048e-16
1,CIN3+,HPV positivo,HSIL+,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-0.30370002843403754,0.488648915271303,0.495766893454262,0.509055662871487,0.520636978488655,0.527748325122181,0.531587512570922,3.885780586188048e-16
1,CIN3+,HPV positivo,LSIL,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-1.4329033456135163,0.042676750204802,0.0470053353775885,0.0551984713012144,0.0624621762259645,0.0669813807353154,0.0694403197238233,3.885780586188048e-16
1,CIN3+,HPV positivo,NILM,"[0.0, 3.7291666666666847, 7.292848376237279]","[-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737]",-1.4575108528337812,0.0213187485278357,0.0256365794003271,0.0338106666152414,0.0410589243006993,0.0455692063201592,0.0480235134204469,3.885780586188048e-16
17,CIN2+,label_0+label_2: High Grade | HPV-negative,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 3.95989990234375, 4.47021484375]","[-3.9228738479090945, -2.641724806005263, -3.734740862816677, -4.055863260141345, -4.947911436939447]",0.0,0.123579923952225,0.15102756718187801,0.184365754779829,0.210945417069017,0.227846791207951,0.237559121707946,4.163336342344337e-16
17,CIN2+,label_0+label_2: High Grade | HPV-negative,<CIN2 | ASC-US/LSIL,"[0.0, 3.95989990234375, 4.47021484375]","[-3.9228738479090945, -2.641724806005263, -3.734740862816677, -4.055863260141345, -4.947911436939447]",-1.0672586464162441,0.008007515968007129,0.0188047699694367,0.0322318229603189,0.0431971868013434,0.0502963963549639,0.054422158764861395,4.163336342344337e-16
17,CIN2+,label_0+label_2: High Grade | HPV-negative,<CIN2 | NILM,"[0.0, 3.95989990234375, 4.47021484375]","[-3.9228738479090945, -2.641724806005263, -3.734740862816677, -4.055863260141345, -4.947911436939447]",-2.5402918082419363,0.00021709070750837198,0.00272210458747353,0.00586705802785506,0.00846046698055248,0.0101517369447562,0.0111391137977098,4.163336342344337e-16
17,CIN2+,label_0+label_2: High Grade | HPV-positive,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 2.75, 5.5]","[-3.5065053026338764, -1.8731662048345261, -2.3420581756483396, -3.811317909251368, -4.133916986812303]",0.0,0.539026420832674,0.570211122864893,0.606491135373487,0.634169795753661,0.6511985060144551,0.660783913749291,4.440892098500626e-16
17,CIN2+,label_0+label_2: High Grade | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 2.75, 5.5]","[-3.5065053026338764, -1.8731662048345261, -2.3420581756483396, -3.811317909251368, -4.133916986812303]",-0.319733986184771,0.206897038243222,0.246239084107875,0.293008432352947,0.329486737548833,0.352304022461775,0.365281610981382,4.440892098500626e-16
17,CIN2+,label_0+label_2: High Grade | HPV-positive,<CIN2 | NILM,"[0.0, 2.75, 5.5]","[-3.5065053026338764, -1.8731662048345261, -2.3420581756483396, -3.811317909251368, -4.133916986812303]",-0.6515872090196151,0.09983770568447399,0.132109526744864,0.171100384178412,0.20201930698049397,0.22160052012735001,0.232824345859495,4.440892098500626e-16
17,CIN2+,label_0+label_2: Low Grade | HPV-negative,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 2.75, 5.5]","[-9.60325253538708, -3.7390337694370426, -4.32693762836679, -8.059250158880516, -5.539079202132769]",0.0,0.0818102195529921,0.08816299645362341,0.0994708114947793,0.10864916988177599,0.113888872396136,0.11695548954333301,1.5959455978986625e-16
17,CIN2+,label_0+label_2: Low Grade | HPV-negative,<CIN2 | ASC-US/LSIL,"[0.0, 2.75, 5.5]","[-9.60325253538708, -3.7390337694370426, -4.32693762836679, -8.059250158880516, -5.539079202132769]",-0.032048176979885025,0.0046423195748839605,0.011312529019801001,0.0231890012469638,0.0328323851663901,0.038338961914485596,0.0415622474077153,1.5959455978986625e-16
17,CIN2+,label_0+label_2: Low Grade | HPV-negative,<CIN2 | NILM,"[0.0, 2.75, 5.5]","[-9.60325253538708, -3.7390337694370426, -4.32693762836679, -8.059250158880516, -5.539079202132769]",-0.9340386881343488,6.352805491541261e-05,0.0027879235521406,0.00766594465494657,0.0116527593369533,0.0139399179550898,0.0152823233565092,1.5959455978986625e-16
17,CIN2+,label_0+label_2: Low Grade | HPV-positive,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 2.8531250000000004, 5.3625]","[-7.48294359780084, -1.8089325565913317, -2.494687509379357, -4.681199745539646, -3.882722349957299]",0.0,0.49306433151293594,0.516539536787493,0.556033375006267,0.586032637229327,0.6023693176552191,0.611672827894284,8.881784197001252e-16
17,CIN2+,label_0+label_2: Low Grade | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 2.8531250000000004, 5.3625]","[-7.48294359780084, -1.8089325565913317, -2.494687509379357, -4.681199745539646, -3.882722349957299]",-0.9030074448223038,0.11667547120604099,0.133490367287367,0.162911881278714,0.18631750771560898,0.199489640993048,0.20713523821422497,8.881784197001252e-16
17,CIN2+,label_0+label_2: Low Grade | HPV-positive,<CIN2 | NILM,"[0.0, 2.8531250000000004, 5.3625]","[-7.48294359780084, -1.8089325565913317, -2.494687509379357, -4.681199745539646, -3.882722349957299]",-1.1294181009525135,0.06097283674749279,0.07525408930616,0.100378568900568,0.120493677221056,0.131865432528085,0.138483393848094,8.881784197001252e-16
17,CIN2+,label_0: High Grade,<CIN2 | HPV-negative | ASC-H/AGC/HSIL+,"[0.0, 3.2499999999999982, 8.524999999999997]","[-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708]",0.0,0.123579923952225,0.15102756718187801,0.184365754779829,0.210945417069017,0.227846791207951,0.237559121707946,4.440892098500626e-16
17,CIN2+,label_0: High Grade,<CIN2 | HPV-negative | ASC-US/LSIL,"[0.0, 3.2499999999999982, 8.524999999999997]","[-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708]",-1.0672586464162428,0.008007515968007129,0.0188047699694367,0.0322318229603189,0.0431971868013434,0.0502963963549639,0.054422158764861395,4.440892098500626e-16
17,CIN2+,label_0: High Grade,<CIN2 | HPV-negative | NILM,"[0.0, 3.2499999999999982, 8.524999999999997]","[-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708]",-2.5402918082419377,0.00021709070750837198,0.00272210458747353,0.00586705802785506,0.00846046698055248,0.0101517369447562,0.0111391137977098,4.440892098500626e-16
17,CIN2+,label_0: High Grade,<CIN2 | HPV-positive | ASC-H/AGC/HSIL+,"[0.0, 3.2499999999999982, 8.524999999999997]","[-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708]",0.7891037999664713,0.539026420832674,0.570211122864893,0.606491135373487,0.634169795753661,0.6511985060144551,0.660783913749291,4.440892098500626e-16
17,CIN2+,label_0: High Grade,<CIN2 | HPV-positive | ASC-US/LSIL,"[0.0, 3.2499999999999982, 8.524999999999997]","[-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708]",0.46936981378170023,0.206897038243222,0.246239084107875,0.293008432352947,0.329486737548833,0.352304022461775,0.365281610981382,4.440892098500626e-16
17,CIN2+,label_0: High Grade,<CIN2 | HPV-positive | NILM,"[0.0, 3.2499999999999982, 8.524999999999997]","[-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708]",0.1375165909468566,0.09983770568447399,0.132109526744864,0.171100384178412,0.20201930698049397,0.22160052012735001,0.232824345859495,4.440892098500626e-16
17,CIN2+,label_0: Low Grade,<CIN2 | HPV-negative | ASC-H/AGC/HSIL+,"[0.0, 3.40234375, 6.5203125]","[-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177]",0.0,0.0818102195529921,0.08816299645362341,0.0994708114947793,0.10864916988177599,0.113888872396136,0.11695548954333301,6.661338147750939e-16
17,CIN2+,label_0: Low Grade,<CIN2 | HPV-negative | ASC-US/LSIL,"[0.0, 3.40234375, 6.5203125]","[-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177]",-0.032048176979882936,0.0046423195748839605,0.011312529019801001,0.0231890012469638,0.0328323851663901,0.038338961914485596,0.0415622474077153,6.661338147750939e-16
17,CIN2+,label_0: Low Grade,<CIN2 | HPV-negative | NILM,"[0.0, 3.40234375, 6.5203125]","[-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177]",-0.9340386881343479,6.352805491541261e-05,0.0027879235521406,0.00766594465494657,0.0116527593369533,0.0139399179550898,0.0152823233565092,6.661338147750939e-16
17,CIN2+,label_0: Low Grade,<CIN2 | HPV-positive | ASC-H/AGC/HSIL+,"[0.0, 3.40234375, 6.5203125]","[-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177]",1.9212169342400942,0.49306433151293594,0.516539536787493,0.556033375006267,0.586032637229327,0.6023693176552191,0.611672827894284,6.661338147750939e-16
17,CIN2+,label_0: Low Grade,<CIN2 | HPV-positive | ASC-US/LSIL,"[0.0, 3.40234375, 6.5203125]","[-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177]",1.0182094894177909,0.11667547120604099,0.133490367287367,0.162911881278714,0.18631750771560898,0.199489640993048,0.20713523821422497,6.661338147750939e-16
17,CIN2+,label_0: Low Grade,<CIN2 | HPV-positive | NILM,"[0.0, 3.40234375, 6.5203125]","[-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177]",0.7917988332875814,0.06097283674749279,0.07525408930616,0.100378568900568,0.120493677221056,0.131865432528085,0.138483393848094,6.661338147750939e-16
17,CIN3+,label_0+label_2: High Grade | HPV-negative,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 3.35150480270386, 5.140167140960691]","[-11.008186733553266, -2.748795416105142, -4.010248009038462, -4.60664472360736, -6.087336519091521]",0.0,0.056152193511642905,0.0714736818636741,0.0987872766172283,0.120837895850705,0.133591678274714,0.14053180371033702,1.3877787807814457e-16
17,CIN3+,label_0+label_2: High Grade | HPV-negative,<CIN2 | ASC-US/LSIL,"[0.0, 3.35150480270386, 5.140167140960691]","[-11.008186733553266, -2.748795416105142, -4.010248009038462, -4.60664472360736, -6.087336519091521]",-2.189971905541478,0.0028073559928682,0.00463224593407769,0.00795285226750279,0.0106994765123714,0.012316140575016302,0.0132047680498179,1.3877787807814457e-16
17,CIN3+,label_0+label_2: High Grade | HPV-negative,<CIN2 | NILM,"[0.0, 3.35150480270386, 5.140167140960691]","[-11.008186733553266, -2.748795416105142, -4.010248009038462, -4.60664472360736, -6.087336519091521]",-3.0083113846638474,0.000217474670789548,0.00102505375178246,0.00249666617420671,0.00371598505957691,0.00443456123574488,0.00482981907149305,1.3877787807814457e-16
17,CIN3+,label_0+label_2: High Grade | HPV-positive,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 3.3515625000000027, 5.388281249999999]","[-10.54691011249509, -2.240786746752028, -3.632622617326058, -4.17107995201359, -5.755718773586673]",0.0,0.283925046033346,0.302266314811659,0.33452512019192904,0.360154491149052,0.374807893081757,0.382728941543987,4.996003610813204e-16
17,CIN3+,label_0+label_2: High Grade | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 3.3515625000000027, 5.388281249999999]","[-10.54691011249509, -2.240786746752028, -3.632622617326058, -4.17107995201359, -5.755718773586673]",-0.20773512406798625,0.0660029115279839,0.0854856922082638,0.11998776652616999,0.14762324557453899,0.163516655451206,0.172137039735473,4.996003610813204e-16
17,CIN3+,label_0+label_2: High Grade | HPV-positive,<CIN2 | NILM,"[0.0, 3.3515625000000027, 5.388281249999999]","[-10.54691011249509, -2.240786746752028, -3.632622617326058, -4.17107995201359, -5.755718773586673]",-0.7339090471758761,0.0502224880729527,0.061979053698500604,0.08305330055168661,0.100178305176523,0.110129965710093,0.115559974612717,4.996003610813204e-16
17,CIN3+,label_0+label_2: Low Grade | HPV-negative,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 3.3921875000000004, 6.4796875]","[-12.617897003010304, -3.7970179725994324, -6.525658531159966, -6.073030586317113, -6.257924890927562]",0.0,0.0164593639076601,0.020865910131221202,0.0288255780656094,0.0352978662713855,0.0389342494067136,0.040947433590996195,1.1796119636642288e-16
17,CIN3+,label_0+label_2: Low Grade | HPV-negative,<CIN2 | ASC-US/LSIL,"[0.0, 3.3921875000000004, 6.4796875]","[-12.617897003010304, -3.7970179725994324, -6.525658531159966, -6.073030586317113, -6.257924890927562]",-1.0508854390530271,0.00045816445105480803,0.00202616816773695,0.0048701701194103705,0.00719392459035741,0.00850395144411777,0.00923059884268837,1.1796119636642288e-16
17,CIN3+,label_0+label_2: Low Grade | HPV-negative,<CIN2 | NILM,"[0.0, 3.3921875000000004, 6.4796875]","[-12.617897003010304, -3.7970179725994324, -6.525658531159966, -6.073030586317113, -6.257924890927562]",-1.801676728882616,3.1533490176679904e-05,0.0007722429160041671,0.00211729098575043,0.00321779960310556,0.0038388157570307404,0.00418346861821767,1.1796119636642288e-16
17,CIN3+,label_0+label_2: Low Grade | HPV-positive,<CIN2 | ASC-H/AGC/HSIL+,"[0.0, 3.4375000000000027, 4.9499999999999975]","[-10.826280746746997, -2.620033444443425, -3.9378457923904575, -4.578177810857306, -5.766887479985344]",0.0,0.22971674078599702,0.244083348646396,0.269516047197888,0.289711503374328,0.300869906443187,0.306989756904408,2.220446049250313e-16
17,CIN3+,label_0+label_2: Low Grade | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 3.4375000000000027, 4.9499999999999975]","[-10.826280746746997, -2.620033444443425, -3.9378457923904575, -4.578177810857306, -5.766887479985344]",-1.2387735560750097,0.0310566408302113,0.0363278167844026,0.0458363669929681,0.053555780922701406,0.0578879736180621,0.0602848606723243,2.220446049250313e-16
17,CIN3+,label_0+label_2: Low Grade | HPV-positive,<CIN2 | NILM,"[0.0, 3.4375000000000027, 4.9499999999999975]","[-10.826280746746997, -2.620033444443425, -3.9378457923904575, -4.578177810857306, -5.766887479985344]",-1.1595249391199973,0.0205211557608812,0.026287808771337698,0.036683552066823805,0.0451169464582727,0.0498473486599558,0.0524637842176785,2.220446049250313e-16
17,CIN3+,label_0: High Grade,<CIN2 | HPV-negative | ASC-H/AGC/HSIL+,"[0.0, 3.3000000000000025, 5.431249999999999]","[-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483]",0.0,0.056152193511642905,0.0714736818636741,0.0987872766172283,0.120837895850705,0.133591678274714,0.14053180371033702,4.996003610813204e-16
17,CIN3+,label_0: High Grade,<CIN2 | HPV-negative | ASC-US/LSIL,"[0.0, 3.3000000000000025, 5.431249999999999]","[-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483]",-2.189971905541481,0.0028073559928682,0.00463224593407769,0.00795285226750279,0.0106994765123714,0.012316140575016302,0.0132047680498179,4.996003610813204e-16
17,CIN3+,label_0: High Grade,<CIN2 | HPV-negative | NILM,"[0.0, 3.3000000000000025, 5.431249999999999]","[-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483]",-3.008311384663847,0.000217474670789548,0.00102505375178246,0.00249666617420671,0.00371598505957691,0.00443456123574488,0.00482981907149305,4.996003610813204e-16
17,CIN3+,label_0: High Grade,<CIN2 | HPV-positive | ASC-H/AGC/HSIL+,"[0.0, 3.3000000000000025, 5.431249999999999]","[-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483]",0.46085110304222565,0.283925046033346,0.302266314811659,0.33452512019192904,0.360154491149052,0.374807893081757,0.382728941543987,4.996003610813204e-16
17,CIN3+,label_0: High Grade,<CIN2 | HPV-positive | ASC-US/LSIL,"[0.0, 3.3000000000000025, 5.431249999999999]","[-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483]",0.2531159789742397,0.0660029115279839,0.0854856922082638,0.11998776652616999,0.14762324557453899,0.163516655451206,0.172137039735473,4.996003610813204e-16
17,CIN3+,label_0: High Grade,<CIN2 | HPV-positive | NILM,"[0.0, 3.3000000000000025, 5.431249999999999]","[-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483]",-0.27305794413365025,0.0502224880729527,0.061979053698500604,0.08305330055168661,0.100178305176523,0.110129965710093,0.115559974612717,4.996003610813204e-16
17,CIN3+,label_0: Low Grade,<CIN2 | HPV-negative | ASC-H/AGC/HSIL+,"[0.0, 3.9189535140991256, 4.434260654449458]","[-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621]",0.0,0.0164593639076601,0.020865910131221202,0.0288255780656094,0.0352978662713855,0.0389342494067136,0.040947433590996195,2.220446049250313e-16
17,CIN3+,label_0: Low Grade,<CIN2 | HPV-negative | ASC-US/LSIL,"[0.0, 3.9189535140991256, 4.434260654449458]","[-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621]",-1.0508854390530284,0.00045816445105480803,0.00202616816773695,0.0048701701194103705,0.00719392459035741,0.00850395144411777,0.00923059884268837,2.220446049250313e-16
17,CIN3+,label_0: Low Grade,<CIN2 | HPV-negative | NILM,"[0.0, 3.9189535140991256, 4.434260654449458]","[-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621]",-1.8016767288826154,3.1533490176679904e-05,0.0007722429160041671,0.00211729098575043,0.00321779960310556,0.0038388157570307404,0.00418346861821767,2.220446049250313e-16
17,CIN3+,label_0: Low Grade,<CIN2 | HPV-positive | ASC-H/AGC/HSIL+,"[0.0, 3.9189535140991256, 4.434260654449458]","[-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621]",1.4333705313265157,0.22971674078599702,0.244083348646396,0.269516047197888,0.289711503374328,0.300869906443187,0.306989756904408,2.220446049250313e-16
17,CIN3+,label_0: Low Grade,<CIN2 | HPV-positive | ASC-US/LSIL,"[0.0, 3.9189535140991256, 4.434260654449458]","[-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621]",0.19459697525150654,0.0310566408302113,0.0363278167844026,0.0458363669929681,0.053555780922701406,0.0578879736180621,0.0602848606723243,2.220446049250313e-16
17,CIN3+,label_0: Low Grade,<CIN2 | HPV-positive | NILM,"[0.0, 3.9189535140991256, 4.434260654449458]","[-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621]",0.2738455922065207,0.0205211557608812,0.026287808771337698,0.036683552066823805,0.0451169464582727,0.0498473486599558,0.0524637842176785,2.220446049250313e-16
18,CIN2+,label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 2.8529907226562505, 4.98558349609375]","[-10.34844881940246, -2.24210128461073, -4.564413713372809, -6.455917689788004, -10.613171503266397]",0.0,0.0754015255440931,0.103265794337961,0.145179223258591,0.169473034365134,0.177288570696931,0.17854208342549,5.551115123125783e-16
18,CIN2+,label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive,<CIN2 | High Grade,"[0.0, 2.8529907226562505, 4.98558349609375]","[-10.34844881940246, -2.24210128461073, -4.564413713372809, -6.455917689788004, -10.613171503266397]",0.7616733125518199,0.499132506342513,0.530907195266614,0.576617975356811,0.60197210394162,0.609951509308618,0.61122329054014,5.551115123125783e-16
18,CIN2+,label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive,<CIN2 | NILM,"[0.0, 2.8529907226562505, 4.98558349609375]","[-10.34844881940246, -2.24210128461073, -4.564413713372809, -6.455917689788004, -10.613171503266397]",-0.8363475431129561,2.38238037242056e-15,0.013171196210381599,0.0334278190860156,0.045427494874570096,0.0493301039184659,0.0499579850656342,5.551115123125783e-16
18,CIN2+,label_0+label_2+label_3: High Grade | HPV-negative/ASCUS/LSIL | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 1.993764424324036, 5.465644538402557]","[-8.058643072974567, -1.8886850796043781, -1.2230492132635378, -3.60609859472805, -4.573943855420296]",0.0,2.10984399628414e-18,0.0642167383232001,0.18451512993242702,0.288932661609402,0.35257094621844204,0.37886263581951196,3.3306690738754696e-16
18,CIN2+,label_0+label_2+label_3: High Grade | HPV-negative/ASCUS/LSIL | HPV-positive,<CIN2 | High Grade,"[0.0, 1.993764424324036, 5.465644538402557]","[-8.058643072974567, -1.8886850796043781, -1.2230492132635378, -3.60609859472805, -4.573943855420296]",1.1563566686924174,0.833305441055717,0.865008364666254,0.9128290596846701,0.9436044942776021,0.958137282157014,0.96330532556192,3.3306690738754696e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 2.75, 5.5]","[-3.9596440054374784, -3.378672278185891, -3.9875232602526585, -3.6722810703457265, -4.280386842686037]",0.0,0.0659044703742194,0.089746688578391,0.109230111875092,0.12529894916311102,0.140192313505222,0.155753880872501,5.551115123125783e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive,<CIN2 | High Grade,"[0.0, 2.75, 5.5]","[-3.9596440054374784, -3.378672278185891, -3.9875232602526585, -3.6722810703457265, -4.280386842686037]",0.5773343339569103,0.5912195695356339,0.609619591237797,0.6243790956833439,0.636363776097805,0.647319257929656,0.658608929897879,5.551115123125783e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive,<CIN2 | NILM,"[0.0, 2.75, 5.5]","[-3.9596440054374784, -3.378672278185891, -3.9875232602526585, -3.6722810703457265, -4.280386842686037]",-0.9820914167155511,0.0360575716765237,0.0453470409822074,0.0530518709507203,0.0594860854426566,0.0655159757267125,0.07188660783930981,5.551115123125783e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative,<CIN2 | ASC-US/LSIL,"[0.0, 2.75, 5.5]","[-20.536131988436342, -4.260644311297781, -3.356872403985886, -4.45548462017129, -5.841778904258112]",0.0,0.0131140716015184,0.018207911105975902,0.0312017894163993,0.047561186468938796,0.0620103077731488,0.0712615583346978,3.3306690738754696e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative,<CIN2 | High Grade,"[0.0, 2.75, 5.5]","[-20.536131988436342, -4.260644311297781, -3.356872403985886, -4.45548462017129, -5.841778904258112]",-11.455432116776514,0.300073811964724,0.300073850328629,0.300073949099842,0.300074075354672,0.300074188683584,0.30007426216439703,3.3306690738754696e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative,<CIN2 | NILM,"[0.0, 2.75, 5.5]","[-20.536131988436342, -4.260644311297781, -3.356872403985886, -4.45548462017129, -5.841778904258112]",-1.039851888850465,1.17957341124561e-14,0.00182768948185797,0.006517879154542669,0.012481064395005601,0.0178032520807647,0.021238743258582802,3.3306690738754696e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 2.749972265958786, 5.499840152263641]","[-19.34733193429554, -4.88827911091044, -3.9845120611245077, -5.082976995007613, -6.469267687925621]",0.0,0.07351057572352189,0.07606669896412671,0.08261525750923729,0.0909184496853561,0.098307541381759,0.10306639528883099,3.3306690738754696e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-positive,<CIN2 | High Grade,"[0.0, 2.749972265958786, 5.499840152263641]","[-19.34733193429554, -4.88827911091044, -3.9845120611245077, -5.082976995007613, -6.469267687925621]",4.061397297742704,0.230831397902068,0.3448148392882,0.5664644165634131,0.7442690505691949,0.840774931785191,0.8828905441660799,3.3306690738754696e-16
18,CIN2+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-positive,<CIN2 | NILM,"[0.0, 2.749972265958786, 5.499840152263641]","[-19.34733193429554, -4.88827911091044, -3.9845120611245077, -5.082976995007613, -6.469267687925621]",0.9425976641150026,0.036133527238391,0.0429441067797216,0.060257919509119004,0.08193408722379729,0.10096490141836799,0.11309287374098201,3.3306690738754696e-16
18,CIN3+,label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 2.8187500000000014, 4.88125]","[-21.931975912646944, -19.932014656863323, -21.959260875279913, -24.216762631029734, -25.901625072089512]",0.0,0.018868845497754902,0.0188688463833303,0.0188688474376925,0.0188688480451513,0.0188688482436359,0.0188688482756456,3.3306690738754696e-16
18,CIN3+,label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive,<CIN2 | High Grade,"[0.0, 2.8187500000000014, 4.88125]","[-21.931975912646944, -19.932014656863323, -21.959260875279913, -24.216762631029734, -25.901625072089512]",18.299272734135396,0.49755217974530097,0.5361550132958299,0.578266941318611,0.60077031262867,0.607859732457989,0.608991201389804,3.3306690738754696e-16
18,CIN3+,label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive,<CIN2 | NILM,"[0.0, 2.8187500000000014, 4.88125]","[-21.931975912646944, -19.932014656863323, -21.959260875279913, -24.216762631029734, -25.901625072089512]",16.680005520674186,7.72700650525083e-14,0.0157072262649549,0.03408677208965,0.0445196994119019,0.0479041281479215,0.0484488140137436,3.3306690738754696e-16
18,CIN3+,label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive,<CIN2 | ASC-US/LSIL,"[0.0, 3.2656250000000018, 5.568750000000001]","[-11.005120843490367, -4.072537754707295, -5.0977913217951665, -4.988725499836527, -6.606418997592393]",0.0,0.0112275700334512,0.015367350846191199,0.023149001780099397,0.030254251011826997,0.0356877959932409,0.0400104534558627,3.608224830031759e-16
18,CIN3+,label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive,<CIN2 | High Grade,"[0.0, 3.2656250000000018, 5.568750000000001]","[-11.005120843490367, -4.072537754707295, -5.0977913217951665, -4.988725499836527, -6.606418997592393]",1.1781712219333076,0.157836568529019,0.169236578546972,0.19037560996425398,0.20934934334176,0.223649651775841,0.23489762154274,3.608224830031759e-16
18,CIN3+,label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive,<CIN2 | NILM,"[0.0, 3.2656250000000018, 5.568750000000001]","[-11.005120843490367, -4.072537754707295, -5.0977913217951665, -4.988725499836527, -6.606418997592393]",-0.5125493120224014,0.010348964132360201,0.0128328458157558,0.0175132256919939,0.0217998505127751,0.0250864342949192,0.0277063839176718,3.608224830031759e-16
18,CIN3+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative,<CIN2 | ASC-US/LSIL,"[0.0, 3.473531723022455, 4.096420288085933]","[-9.852766225403219, -5.348005437798218, -9.227888582465996, -8.275788592809148, -9.138133904340833]",0.0,0.006557383449894349,0.00795848645101952,0.010099205818607,0.0113355021822377,0.0117227067039258,0.0117796357536864,5.551115123125783e-17
18,CIN3+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative,<CIN2 | High Grade,"[0.0, 3.473531723022455, 4.096420288085933]","[-9.852766225403219, -5.348005437798218, -9.227888582465996, -8.275788592809148, -9.138133904340833]",-11.266547261922307,0.0999947153911425,0.09999473164211899,0.099994756516062,0.0999947709056376,0.0999947754161124,0.0999947760794175,5.551115123125783e-17
18,CIN3+,label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative,<CIN2 | NILM,"[0.0, 3.473531723022455, 4.096420288085933]","[-9.852766225403219, -5.348005437798218, -9.227888582465996, -8.275788592809148, -9.138133904340833]",-0.5297140871380742,3.5738078826717895e-35,0.000830618074109002,0.00210063628986212,0.00283460464295726,0.00306455905801228,0.00309837141083125,5.551115123125783e-17
18,CIN3+,label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL,<CIN2 | HPV-negative | ASC-US/LSIL,"[0.0, 2.7500272259116176, 5.281872798502446]","[-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774]",0.0,0.006557383449894349,0.00795848645101952,0.010099205818607,0.0113355021822377,0.0117227067039258,0.0117796357536864,2.4216739724636227e-15
18,CIN3+,label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL,<CIN2 | HPV-negative | High Grade,"[0.0, 2.7500272259116176, 5.281872798502446]","[-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774]",-11.266547261886572,0.0999947153911425,0.09999473164211899,0.099994756516062,0.0999947709056376,0.0999947754161124,0.0999947760794175,2.4216739724636227e-15
18,CIN3+,label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL,<CIN2 | HPV-negative | NILM,"[0.0, 2.7500272259116176, 5.281872798502446]","[-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774]",-0.5297140871380728,3.5738078826717895e-35,0.000830618074109002,0.00210063628986212,0.00283460464295726,0.00306455905801228,0.00309837141083125,2.4216739724636227e-15
18,CIN3+,label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL,<CIN2 | HPV-positive | ASC-US/LSIL,"[0.0, 2.7500272259116176, 5.281872798502446]","[-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774]",-27.299467870607586,0.0147068843215046,0.0147068843215059,0.0147068843215079,0.014706884321509,0.0147068843215093,0.014706884321509399,2.4216739724636227e-15
18,CIN3+,label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL,<CIN2 | HPV-positive | High Grade,"[0.0, 2.7500272259116176, 5.281872798502446]","[-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774]",4.4558478579098715,0.0769197677445438,0.182575885831324,0.321353903291499,0.39060597796332,0.410823095045538,0.413739088439336,2.4216739724636227e-15
18,CIN3+,label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL,<CIN2 | HPV-positive | NILM,"[0.0, 2.7500272259116176, 5.281872798502446]","[-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774]",1.3214479115965938,5.106044319392471e-40,0.00527694836759951,0.0133000310093961,0.017911804765725802,0.0193529432788598,0.019564696974458298,2.4216739724636227e-15
24,CIN2+,label_1: HPV-negative,Treatment for CIN 3 | ASC-US/LSIL,"[0.0, 3.0250000000000004, 5.225]","[-5.970564123896623, -2.9583893638499363, -4.516974672861336, -5.780793455732832, -6.209824875259012]",0.0,0.0262214431467089,0.0416928080114781,0.0646927106456137,0.0807470937165037,0.08826314484108369,0.0917702560686117,4.163336342344337e-16
24,CIN2+,label_1: HPV-negative,Treatment for CIN 3 | High Grade,"[0.0, 3.0250000000000004, 5.225]","[-5.970564123896623, -2.9583893638499363, -4.516974672861336, -5.780793455732832, -6.209824875259012]",-10.729002075719931,0.21056564309331802,0.21056591998573299,0.21056633999139301,0.210566639329971,0.21056678127012798,0.21056684790255598,4.163336342344337e-16
24,CIN2+,label_1: HPV-negative,Treatment for CIN 3 | NILM,"[0.0, 3.0250000000000004, 5.225]","[-5.970564123896623, -2.9583893638499363, -4.516974672861336, -5.780793455732832, -6.209824875259012]",-0.9535043052028737,0.00114916052911648,0.0072952786692584305,0.0165459402914708,0.023086242714399397,0.026172299707561398,0.0276176550475499,4.163336342344337e-16
24,CIN2+,label_1: HPV-positive,Treatment for CIN 3 | ASC-US/LSIL,"[0.0, 2.8875, 5.225]","[-4.909963766900336, -1.87064845459847, -3.1538174160037586, -5.191561600237883, -4.820452622627722]",0.0,0.21346052558124298,0.25135818692788603,0.305386982153937,0.341496774219641,0.35795709489185595,0.365541687427744,4.440892098500626e-16
24,CIN2+,label_1: HPV-positive,Treatment for CIN 3 | High Grade,"[0.0, 2.8875, 5.225]","[-4.909963766900336, -1.87064845459847, -3.1538174160037586, -5.191561600237883, -4.820452622627722]",0.4241078676772622,0.718841415723524,0.7392788126726241,0.7674794483957981,0.785696434253688,0.793828658616323,0.797539091168836,4.440892098500626e-16
24,CIN2+,label_1: HPV-positive,Treatment for CIN 3 | NILM,"[0.0, 2.8875, 5.225]","[-4.909963766900336, -1.87064845459847, -3.1538174160037586, -5.191561600237883, -4.820452622627722]",-0.2934210941211471,0.08629421216615149,0.11932921444308199,0.167172915569126,0.199676460972488,0.214642521254526,0.22157134454827,4.440892098500626e-16
24,CIN2+,(todas juntas): ,Treatment for CIN 3 | HPV-negative | ASC-US/LSIL,"[0.0, 3.0392578124999985, 6.147070312500004]","[-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997]",0.0,0.0262214431467089,0.0416928080114781,0.0646927106456137,0.0807470937165037,0.08826314484108369,0.0917702560686117,4.440892098500626e-16
24,CIN2+,(todas juntas): ,Treatment for CIN 3 | HPV-negative | High Grade,"[0.0, 3.0392578124999985, 6.147070312500004]","[-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997]",-10.729002075702507,0.21056564309331802,0.21056591998573299,0.21056633999139301,0.210566639329971,0.21056678127012798,0.21056684790255598,4.440892098500626e-16
24,CIN2+,(todas juntas): ,Treatment for CIN 3 | HPV-negative | NILM,"[0.0, 3.0392578124999985, 6.147070312500004]","[-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997]",-0.9535043052028733,0.00114916052911648,0.0072952786692584305,0.0165459402914708,0.023086242714399397,0.026172299707561398,0.0276176550475499,4.440892098500626e-16
24,CIN2+,(todas juntas): ,Treatment for CIN 3 | HPV-positive | ASC-US/LSIL,"[0.0, 3.0392578124999985, 6.147070312500004]","[-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997]",1.126031972593485,0.21346052558124298,0.25135818692788603,0.305386982153937,0.341496774219641,0.35795709489185595,0.365541687427744,4.440892098500626e-16
24,CIN2+,(todas juntas): ,Treatment for CIN 3 | HPV-positive | High Grade,"[0.0, 3.0392578124999985, 6.147070312500004]","[-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997]",1.550139840270747,0.718841415723524,0.7392788126726241,0.7674794483957981,0.785696434253688,0.793828658616323,0.797539091168836,4.440892098500626e-16
24,CIN2+,(todas juntas): ,Treatment for CIN 3 | HPV-positive | NILM,"[0.0, 3.0392578124999985, 6.147070312500004]","[-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997]",0.8326108784723378,0.08629421216615149,0.11932921444308199,0.167172915569126,0.199676460972488,0.214642521254526,0.22157134454827,4.440892098500626e-16
24,CIN3+,label_1: HPV-negative,Treatment for CIN 3 | ASC-US/LSIL,"[0.0, 3.2656250000000018, 4.674999999999999]","[-10.75052455883268, -3.7407644366146644, -5.366941921959517, -6.1266345031929, -7.140714307357668]",0.0,0.00749275883282888,0.0140702718574874,0.0251859308624384,0.0331275183226566,0.036734651218946104,0.0381750857365055,2.220446049250313e-16
24,CIN3+,label_1: HPV-negative,Treatment for CIN 3 | High Grade,"[0.0, 3.2656250000000018, 4.674999999999999]","[-10.75052455883268, -3.7407644366146644, -5.366941921959517, -6.1266345031929, -7.140714307357668]",-10.453417548881681,0.175428184775675,0.17542834295072499,0.175428612672362,0.175428807265387,0.17542889617954,0.17542893177864202,2.220446049250313e-16
24,CIN3+,label_1: HPV-negative,Treatment for CIN 3 | NILM,"[0.0, 3.2656250000000018, 4.674999999999999]","[-10.75052455883268, -3.7407644366146644, -5.366941921959517, -6.1266345031929, -7.140714307357668]",-0.6387834786259222,0.000288048962219205,0.0037912398055393298,0.009736625843226439,0.0140039316381632,0.0159476393037477,0.0167247788723049,2.220446049250313e-16
24,CIN3+,label_1: HPV-positive,Treatment for CIN 3 | ASC-US/LSIL,"[0.0, 3.2656250000000018, 4.674999999999999]","[-9.365330068085091, -2.3555699458788215, -3.9817474312236376, -4.741440012456921, -5.7555198166218045]",0.0,0.102172567414265,0.125711673454009,0.16443615710668202,0.191304726578008,0.20329233727663698,0.20804192662846,5.551115123125783e-16
24,CIN3+,label_1: HPV-positive,Treatment for CIN 3 | High Grade,"[0.0, 3.2656250000000018, 4.674999999999999]","[-9.365330068085091, -2.3555699458788215, -3.9817474312236376, -4.741440012456921, -5.7555198166218045]",0.65783616404365,0.527002022130951,0.550651254477406,0.58828309749054,0.613460217784654,0.624445965439573,0.628756365442339,5.551115123125783e-16
24,CIN3+,label_1: HPV-positive,Treatment for CIN 3 | NILM,"[0.0, 3.2656250000000018, 4.674999999999999]","[-9.365330068085091, -2.3555699458788215, -3.9817474312236376, -4.741440012456921, -5.7555198166218045]",-0.6016494080274817,0.058115292449263896,0.0717266377266579,0.09448470144641959,0.11055643859221301,0.117804742530884,0.120690204232158,5.551115123125783e-16
24,CIN3+,(todas juntas): ,Treatment for CIN 3 | HPV-negative | ASC-US/LSIL,"[0.0, 3.2449462890625016, 4.685742187499999]","[-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049]",0.0,0.00749275883282888,0.0140702718574874,0.0251859308624384,0.0331275183226566,0.036734651218946104,0.0381750857365055,5.551115123125783e-16
24,CIN3+,(todas juntas): ,Treatment for CIN 3 | HPV-negative | High Grade,"[0.0, 3.2449462890625016, 4.685742187499999]","[-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049]",-10.453417548844534,0.175428184775675,0.17542834295072499,0.175428612672362,0.175428807265387,0.17542889617954,0.17542893177864202,5.551115123125783e-16
24,CIN3+,(todas juntas): ,Treatment for CIN 3 | HPV-negative | NILM,"[0.0, 3.2449462890625016, 4.685742187499999]","[-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049]",-0.6387834786259241,0.000288048962219205,0.0037912398055393298,0.009736625843226439,0.0140039316381632,0.0159476393037477,0.0167247788723049,5.551115123125783e-16
24,CIN3+,(todas juntas): ,Treatment for CIN 3 | HPV-positive | ASC-US/LSIL,"[0.0, 3.2449462890625016, 4.685742187499999]","[-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049]",1.385194490735862,0.102172567414265,0.125711673454009,0.16443615710668202,0.191304726578008,0.20329233727663698,0.20804192662846,5.551115123125783e-16
24,CIN3+,(todas juntas): ,Treatment for CIN 3 | HPV-positive | High Grade,"[0.0, 3.2449462890625016, 4.685742187499999]","[-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049]",2.043030654779511,0.527002022130951,0.550651254477406,0.58828309749054,0.613460217784654,0.624445965439573,0.628756365442339,5.551115123125783e-16
24,CIN3+,(todas juntas): ,Treatment for CIN 3 | HPV-positive | NILM,"[0.0, 3.2449462890625016, 4.685742187499999]","[-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049]",0.7835450827083796,0.058115292449263896,0.0717266377266579,0.09448470144641959,0.11055643859221301,0.117804742530884,0.120690204232158,5.551115123125783e-16
25,CIN2+,label_0: High Grade,Treatment for CIN3 | ASCUS-LSIL HPV-negative,"[0.0, 3.5068246841430617, 4.498048400878903]","[-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275]",0.0,0.00689426072206779,0.0234041056060416,0.050432715718639595,0.0688704714867694,0.0768074028972754,0.07935829582749071,3.3306690738754696e-16
25,CIN2+,label_0: High Grade,Treatment for CIN3 | Cotest-negative,"[0.0, 3.5068246841430617, 4.498048400878903]","[-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275]",-1.171860477937203,0.00116569116099475,0.00633957157518789,0.0149417396800686,0.020907203198276297,0.023500281742851802,0.024336951511278803,3.3306690738754696e-16
25,CIN2+,label_0: High Grade,Treatment for CIN3 | HighGrade,"[0.0, 3.5068246841430617, 4.498048400878903]","[-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275]",0.6664303268151888,0.609348144462981,0.6218948655778039,0.642004999920256,0.655416346620817,0.661112832617304,0.662933846623046,3.3306690738754696e-16
25,CIN2+,label_0: High Grade,Treatment for CIN3 | LowGrade,"[0.0, 3.5068246841430617, 4.498048400878903]","[-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275]",0.9978027150138086,0.148218727717598,0.186081707352701,0.245741894515564,0.284807629791837,0.301222257287978,0.30644683574999404,3.3306690738754696e-16
25,CIN2+,label_0: Low Grade,Treatment for CIN3 | ASCUS-LSIL HPV-negative,"[0.0, 2.75, 5.775]","[-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695]",0.0,0.0491750046718411,0.0637135560502284,0.08407235294447821,0.09678228478318751,0.102804510484527,0.107012417563002,4.996003610813204e-16
25,CIN2+,label_0: Low Grade,Treatment for CIN3 | Cotest-negative,"[0.0, 2.75, 5.775]","[-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695]",-0.7542155007340696,0.00113944145053942,0.00835288281943979,0.0185545319124284,0.024984382853127398,0.028047709175761798,0.0301946136369331,4.996003610813204e-16
25,CIN2+,label_0: Low Grade,Treatment for CIN3 | HighGrade,"[0.0, 2.75, 5.775]","[-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695]",0.3854366675002079,0.505615330492757,0.516689472960763,0.532061385494076,0.541577094082526,0.546063945791907,0.549190652662297,4.996003610813204e-16
25,CIN2+,label_0: Low Grade,Treatment for CIN3 | LowGrade,"[0.0, 2.75, 5.775]","[-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695]",0.8345314151494438,0.16759208587594798,0.196621979175685,0.23629631191997402,0.260489803439742,0.271799493725444,0.27964341551433497,4.996003610813204e-16
25,CIN3+,label_0: High Grade,Treatment for CIN3 | ASCUS-LSIL HPV-negative,"[0.0, 3.093750000000001, 4.949999999999999]","[-11.65621566124099, -4.3784350073280045, -6.399237709979687, -7.520958947104618, -11.54649229806419]",0.0,6.616310929246371e-22,0.00344063446225507,0.00908842803702181,0.0128583636308344,0.014321824844177,0.014659239877557899,3.3306690738754696e-16
25,CIN3+,label_0: High Grade,Treatment for CIN3 | HighGrade,"[0.0, 3.093750000000001, 4.949999999999999]","[-11.65621566124099, -4.3784350073280045, -6.399237709979687, -7.520958947104618, -11.54649229806419]",1.8321853909330095,0.470938641571351,0.482208888835742,0.500271656617588,0.512031663130867,0.516533734139799,0.517566765289406,3.3306690738754696e-16
25,CIN3+,label_0: High Grade,Treatment for CIN3 | LowGrade,"[0.0, 3.093750000000001, 4.949999999999999]","[-11.65621566124099, -4.3784350073280045, -6.399237709979687, -7.520958947104618, -11.54649229806419]",2.048734936225644,0.0791682483413729,0.10346386850759601,0.142135447953194,0.167132789739333,0.17666419487572899,0.17884822315252102,3.3306690738754696e-16
25,CIN3+,label_0: Low Grade,Treatment for CIN3 | ASCUS-LSIL HPV-negative,"[0.0, 3.0239257812500004, 5.2142578125]","[-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101]",0.0,0.016393231121640497,0.0267142535746957,0.0431674882906643,0.0541326061215275,0.05962404507213279,0.0631155908076441,2.220446049250313e-16
25,CIN3+,label_0: Low Grade,Treatment for CIN3 | Cotest-negative,"[0.0, 3.0239257812500004, 5.2142578125]","[-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101]",-1.2834799456120654,0.00056859310178751,0.00348534850162038,0.00818167134838134,0.0113440101892865,0.012937709304145199,0.013954510943629499,2.220446049250313e-16
25,CIN3+,label_0: Low Grade,Treatment for CIN3 | HighGrade,"[0.0, 3.0239257812500004, 5.2142578125]","[-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101]",0.6594645601199031,0.32894402939158196,0.342493691231193,0.363817761773228,0.377840417952489,0.384806371694159,0.389215739325888,2.220446049250313e-16
25,CIN3+,label_0: Low Grade,Treatment for CIN3 | LowGrade,"[0.0, 3.0239257812500004, 5.2142578125]","[-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101]",0.30595946805334373,0.0909136890929964,0.103842681541942,0.12435198959338001,0.13795044713030602,0.144739553455262,0.149048808616415,2.220446049250313e-16
1 table outcome group curve knots gamma eta cr0 cr1 cr2 cr3 cr4 cr5 max_abs
2 1 CIN2+ HPV negativo AGC [0.0, 3.749999999999426, 10.992706060410129] [-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106] 0.0 0.0241115195644835 0.0256092196204436 0.0268181400278813 0.028171784403177 0.0297901538513425 0.031523974593383 4.440892098500626e-16
3 1 CIN2+ HPV negativo ASC-H [0.0, 3.749999999999426, 10.992706060410129] [-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106] 0.675059058469885 0.0953469396720264 0.0980718969717476 0.100268497329922 0.102724939896397 0.10565744916419 0.108793929166055 4.440892098500626e-16
4 1 CIN2+ HPV negativo ASC-US [0.0, 3.749999999999426, 10.992706060410129] [-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106] 0.3716720902899113 0.0006886909862562 0.00291195228696667 0.00470541300218982 0.00671238510720408 0.00911019894943088 0.0116770710796392 4.440892098500626e-16
5 1 CIN2+ HPV negativo HSIL+ [0.0, 3.749999999999426, 10.992706060410129] [-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106] 2.0164005981856348 0.468287640749052 0.474386433098624 0.47926496337816 0.484680892189583 0.491091841584196 0.497883312012614 4.440892098500626e-16
6 1 CIN2+ HPV negativo LSIL [0.0, 3.749999999999426, 10.992706060410129] [-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106] 1.0694381631654704 0.0321089460773336 0.036430742300162 0.0399099701641632 0.0437959045534305 0.0484282146868277 0.05337460404111 4.440892098500626e-16
7 1 CIN2+ HPV negativo NILM [0.0, 3.749999999999426, 10.992706060410129] [-6.324383795005433, -6.37479744714196, -4.735247839134645, -7.506441621422714, -5.286359290355106] -0.6656887215701865 3.90353647266218e-05 0.000828013277650686 0.00146529413171444 0.00217932287701656 0.00303362524453662 0.00394964078320864 4.440892098500626e-16
8 1 CIN2+ HPV positivo AGC [0.0, 3.7291666666669765, 7.200620785886926] [-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466] 0.0 0.400884761372207 0.423177327520334 0.453148774204697 0.47722331054264 0.491809730088738 0.500142601911983 7.771561172376096e-16
9 1 CIN2+ HPV positivo ASC-H [0.0, 3.7291666666669765, 7.200620785886926] [-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466] 0.2126697727739812 0.501106699178966 0.523966961254572 0.554371985820979 0.578511314319372 0.593010085492955 0.601248908320567 7.771561172376096e-16
10 1 CIN2+ HPV positivo ASC-US [0.0, 3.7291666666669765, 7.200620785886926] [-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466] -0.7533953307304859 0.134977733606003 0.150282229405366 0.171360576935273 0.188738761408003 0.19947466518464 0.205681128069832 7.771561172376096e-16
11 1 CIN2+ HPV positivo HSIL+ [0.0, 3.7291666666669765, 7.200620785886926] [-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466] 0.007560314353099129 0.768895742132862 0.777558954414099 0.789202267331941 0.798551251948637 0.80421408879622 0.807448580381107 7.771561172376096e-16
12 1 CIN2+ HPV positivo LSIL [0.0, 3.7291666666669765, 7.200620785886926] [-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466] -0.7121375835534804 0.150720429636477 0.166373432071245 0.187912288999706 0.205652819554319 0.216604598846303 0.222933043955648 7.771561172376096e-16
13 1 CIN2+ HPV positivo NILM [0.0, 3.7291666666669765, 7.200620785886926] [-4.0640514538410475, -1.880658423593201, -5.23057999132761, -3.8132214643020976, -4.486047029509466] -0.9861148498309161 0.0498612570542781 0.0632060742965726 0.0816675057209598 0.0969615559339089 0.106443878949773 0.111937675985206 7.771561172376096e-16
14 1 CIN3+ HPV negativo AGC [0.0, 3.7500000000006812, 7.523483812808309] [-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815] 0.0 0.0106844641637163 0.0115079789994108 0.0121411816481693 0.0128347160639286 0.0136669643759362 0.0145666781897423 3.3306690738754696e-16
15 1 CIN3+ HPV negativo ASC-H [0.0, 3.7500000000006812, 7.523483812808309] [-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815] -0.04872187576775001 0.0342206380443041 0.034986346556643 0.0355751224053339 0.0362200176140623 0.0369939268279508 0.0378306072669854 3.3306690738754696e-16
16 1 CIN3+ HPV negativo ASC-US [0.0, 3.7500000000006812, 7.523483812808309] [-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815] -0.09879946244479822 0.000397811063724171 0.00115163989720337 0.0017313009790938 0.00236623247962954 0.00312821209932418 0.00395202899225357 3.3306690738754696e-16
17 1 CIN3+ HPV negativo HSIL+ [0.0, 3.7500000000006812, 7.523483812808309] [-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815] 2.004887966546689 0.252144671903415 0.256754712682076 0.260282641941786 0.264130077325419 0.268724170611435 0.273662742092822 3.3306690738754696e-16
18 1 CIN3+ HPV negativo LSIL [0.0, 3.7500000000006812, 7.523483812808309] [-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815] 0.8576201610700221 0.0105183209491033 0.0124590219555563 0.013949740055348 0.0155810064976098 0.017536490040242 0.0196479749836111 3.3306690738754696e-16
19 1 CIN3+ HPV negativo NILM [0.0, 3.7500000000006812, 7.523483812808309] [-6.917115440250148, -7.478080654840027, -6.091702497080626, -6.494690725423079, -7.317898593962815] -1.174571179173883 2.28864043889962e-05 0.000280128375297359 0.000478023113087691 0.000694873939389557 0.000955236140567136 0.00123687521303424 3.3306690738754696e-16
20 1 CIN3+ HPV positivo AGC [0.0, 3.7291666666666847, 7.292848376237279] [-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737] 0.0 0.262739413900099 0.276609416274342 0.302317768969549 0.324522607011181 0.338063429715532 0.345343732440977 3.885780586188048e-16
21 1 CIN3+ HPV positivo ASC-H [0.0, 3.7291666666666847, 7.292848376237279] [-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737] -0.09530733394718151 0.25730149160114 0.270014560302542 0.293637521742104 0.314104857280649 0.326616057076886 0.333352370721709 3.885780586188048e-16
22 1 CIN3+ HPV positivo ASC-US [0.0, 3.7291666666666847, 7.292848376237279] [-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737] -1.3767188384949076 0.0444540193603678 0.0490236673279738 0.0576697985578552 0.0653314891820387 0.0700965762622234 0.0726887422509778 3.885780586188048e-16
23 1 CIN3+ HPV positivo HSIL+ [0.0, 3.7291666666666847, 7.292848376237279] [-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737] -0.30370002843403754 0.488648915271303 0.495766893454262 0.509055662871487 0.520636978488655 0.527748325122181 0.531587512570922 3.885780586188048e-16
24 1 CIN3+ HPV positivo LSIL [0.0, 3.7291666666666847, 7.292848376237279] [-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737] -1.4329033456135163 0.042676750204802 0.0470053353775885 0.0551984713012144 0.0624621762259645 0.0669813807353154 0.0694403197238233 3.885780586188048e-16
25 1 CIN3+ HPV positivo NILM [0.0, 3.7291666666666847, 7.292848376237279] [-8.653010231501607, -2.175574663798926, -5.954714336781031, -4.396870683350268, -5.000172264868737] -1.4575108528337812 0.0213187485278357 0.0256365794003271 0.0338106666152414 0.0410589243006993 0.0455692063201592 0.0480235134204469 3.885780586188048e-16
26 17 CIN2+ label_0+label_2: High Grade | HPV-negative <CIN2 | ASC-H/AGC/HSIL+ [0.0, 3.95989990234375, 4.47021484375] [-3.9228738479090945, -2.641724806005263, -3.734740862816677, -4.055863260141345, -4.947911436939447] 0.0 0.123579923952225 0.15102756718187801 0.184365754779829 0.210945417069017 0.227846791207951 0.237559121707946 4.163336342344337e-16
27 17 CIN2+ label_0+label_2: High Grade | HPV-negative <CIN2 | ASC-US/LSIL [0.0, 3.95989990234375, 4.47021484375] [-3.9228738479090945, -2.641724806005263, -3.734740862816677, -4.055863260141345, -4.947911436939447] -1.0672586464162441 0.008007515968007129 0.0188047699694367 0.0322318229603189 0.0431971868013434 0.0502963963549639 0.054422158764861395 4.163336342344337e-16
28 17 CIN2+ label_0+label_2: High Grade | HPV-negative <CIN2 | NILM [0.0, 3.95989990234375, 4.47021484375] [-3.9228738479090945, -2.641724806005263, -3.734740862816677, -4.055863260141345, -4.947911436939447] -2.5402918082419363 0.00021709070750837198 0.00272210458747353 0.00586705802785506 0.00846046698055248 0.0101517369447562 0.0111391137977098 4.163336342344337e-16
29 17 CIN2+ label_0+label_2: High Grade | HPV-positive <CIN2 | ASC-H/AGC/HSIL+ [0.0, 2.75, 5.5] [-3.5065053026338764, -1.8731662048345261, -2.3420581756483396, -3.811317909251368, -4.133916986812303] 0.0 0.539026420832674 0.570211122864893 0.606491135373487 0.634169795753661 0.6511985060144551 0.660783913749291 4.440892098500626e-16
30 17 CIN2+ label_0+label_2: High Grade | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 2.75, 5.5] [-3.5065053026338764, -1.8731662048345261, -2.3420581756483396, -3.811317909251368, -4.133916986812303] -0.319733986184771 0.206897038243222 0.246239084107875 0.293008432352947 0.329486737548833 0.352304022461775 0.365281610981382 4.440892098500626e-16
31 17 CIN2+ label_0+label_2: High Grade | HPV-positive <CIN2 | NILM [0.0, 2.75, 5.5] [-3.5065053026338764, -1.8731662048345261, -2.3420581756483396, -3.811317909251368, -4.133916986812303] -0.6515872090196151 0.09983770568447399 0.132109526744864 0.171100384178412 0.20201930698049397 0.22160052012735001 0.232824345859495 4.440892098500626e-16
32 17 CIN2+ label_0+label_2: Low Grade | HPV-negative <CIN2 | ASC-H/AGC/HSIL+ [0.0, 2.75, 5.5] [-9.60325253538708, -3.7390337694370426, -4.32693762836679, -8.059250158880516, -5.539079202132769] 0.0 0.0818102195529921 0.08816299645362341 0.0994708114947793 0.10864916988177599 0.113888872396136 0.11695548954333301 1.5959455978986625e-16
33 17 CIN2+ label_0+label_2: Low Grade | HPV-negative <CIN2 | ASC-US/LSIL [0.0, 2.75, 5.5] [-9.60325253538708, -3.7390337694370426, -4.32693762836679, -8.059250158880516, -5.539079202132769] -0.032048176979885025 0.0046423195748839605 0.011312529019801001 0.0231890012469638 0.0328323851663901 0.038338961914485596 0.0415622474077153 1.5959455978986625e-16
34 17 CIN2+ label_0+label_2: Low Grade | HPV-negative <CIN2 | NILM [0.0, 2.75, 5.5] [-9.60325253538708, -3.7390337694370426, -4.32693762836679, -8.059250158880516, -5.539079202132769] -0.9340386881343488 6.352805491541261e-05 0.0027879235521406 0.00766594465494657 0.0116527593369533 0.0139399179550898 0.0152823233565092 1.5959455978986625e-16
35 17 CIN2+ label_0+label_2: Low Grade | HPV-positive <CIN2 | ASC-H/AGC/HSIL+ [0.0, 2.8531250000000004, 5.3625] [-7.48294359780084, -1.8089325565913317, -2.494687509379357, -4.681199745539646, -3.882722349957299] 0.0 0.49306433151293594 0.516539536787493 0.556033375006267 0.586032637229327 0.6023693176552191 0.611672827894284 8.881784197001252e-16
36 17 CIN2+ label_0+label_2: Low Grade | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 2.8531250000000004, 5.3625] [-7.48294359780084, -1.8089325565913317, -2.494687509379357, -4.681199745539646, -3.882722349957299] -0.9030074448223038 0.11667547120604099 0.133490367287367 0.162911881278714 0.18631750771560898 0.199489640993048 0.20713523821422497 8.881784197001252e-16
37 17 CIN2+ label_0+label_2: Low Grade | HPV-positive <CIN2 | NILM [0.0, 2.8531250000000004, 5.3625] [-7.48294359780084, -1.8089325565913317, -2.494687509379357, -4.681199745539646, -3.882722349957299] -1.1294181009525135 0.06097283674749279 0.07525408930616 0.100378568900568 0.120493677221056 0.131865432528085 0.138483393848094 8.881784197001252e-16
38 17 CIN2+ label_0: High Grade <CIN2 | HPV-negative | ASC-H/AGC/HSIL+ [0.0, 3.2499999999999982, 8.524999999999997] [-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708] 0.0 0.123579923952225 0.15102756718187801 0.184365754779829 0.210945417069017 0.227846791207951 0.237559121707946 4.440892098500626e-16
39 17 CIN2+ label_0: High Grade <CIN2 | HPV-negative | ASC-US/LSIL [0.0, 3.2499999999999982, 8.524999999999997] [-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708] -1.0672586464162428 0.008007515968007129 0.0188047699694367 0.0322318229603189 0.0431971868013434 0.0502963963549639 0.054422158764861395 4.440892098500626e-16
40 17 CIN2+ label_0: High Grade <CIN2 | HPV-negative | NILM [0.0, 3.2499999999999982, 8.524999999999997] [-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708] -2.5402918082419377 0.00021709070750837198 0.00272210458747353 0.00586705802785506 0.00846046698055248 0.0101517369447562 0.0111391137977098 4.440892098500626e-16
41 17 CIN2+ label_0: High Grade <CIN2 | HPV-positive | ASC-H/AGC/HSIL+ [0.0, 3.2499999999999982, 8.524999999999997] [-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708] 0.7891037999664713 0.539026420832674 0.570211122864893 0.606491135373487 0.634169795753661 0.6511985060144551 0.660783913749291 4.440892098500626e-16
42 17 CIN2+ label_0: High Grade <CIN2 | HPV-positive | ASC-US/LSIL [0.0, 3.2499999999999982, 8.524999999999997] [-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708] 0.46936981378170023 0.206897038243222 0.246239084107875 0.293008432352947 0.329486737548833 0.352304022461775 0.365281610981382 4.440892098500626e-16
43 17 CIN2+ label_0: High Grade <CIN2 | HPV-positive | NILM [0.0, 3.2499999999999982, 8.524999999999997] [-4.122265634159465, -2.1255463991307395, -4.369657957705268, -7.100053626222385, -4.696492375941708] 0.1375165909468566 0.09983770568447399 0.132109526744864 0.171100384178412 0.20201930698049397 0.22160052012735001 0.232824345859495 4.440892098500626e-16
44 17 CIN2+ label_0: Low Grade <CIN2 | HPV-negative | ASC-H/AGC/HSIL+ [0.0, 3.40234375, 6.5203125] [-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177] 0.0 0.0818102195529921 0.08816299645362341 0.0994708114947793 0.10864916988177599 0.113888872396136 0.11695548954333301 6.661338147750939e-16
45 17 CIN2+ label_0: Low Grade <CIN2 | HPV-negative | ASC-US/LSIL [0.0, 3.40234375, 6.5203125] [-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177] -0.032048176979882936 0.0046423195748839605 0.011312529019801001 0.0231890012469638 0.0328323851663901 0.038338961914485596 0.0415622474077153 6.661338147750939e-16
46 17 CIN2+ label_0: Low Grade <CIN2 | HPV-negative | NILM [0.0, 3.40234375, 6.5203125] [-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177] -0.9340386881343479 6.352805491541261e-05 0.0027879235521406 0.00766594465494657 0.0116527593369533 0.0139399179550898 0.0152823233565092 6.661338147750939e-16
47 17 CIN2+ label_0: Low Grade <CIN2 | HPV-positive | ASC-H/AGC/HSIL+ [0.0, 3.40234375, 6.5203125] [-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177] 1.9212169342400942 0.49306433151293594 0.516539536787493 0.556033375006267 0.586032637229327 0.6023693176552191 0.611672827894284 6.661338147750939e-16
48 17 CIN2+ label_0: Low Grade <CIN2 | HPV-positive | ASC-US/LSIL [0.0, 3.40234375, 6.5203125] [-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177] 1.0182094894177909 0.11667547120604099 0.133490367287367 0.162911881278714 0.18631750771560898 0.199489640993048 0.20713523821422497 6.661338147750939e-16
49 17 CIN2+ label_0: Low Grade <CIN2 | HPV-positive | NILM [0.0, 3.40234375, 6.5203125] [-8.888048023332304, -3.366606384789105, -6.291599660352853, -5.405967579947326, -5.825837965415177] 0.7917988332875814 0.06097283674749279 0.07525408930616 0.100378568900568 0.120493677221056 0.131865432528085 0.138483393848094 6.661338147750939e-16
50 17 CIN3+ label_0+label_2: High Grade | HPV-negative <CIN2 | ASC-H/AGC/HSIL+ [0.0, 3.35150480270386, 5.140167140960691] [-11.008186733553266, -2.748795416105142, -4.010248009038462, -4.60664472360736, -6.087336519091521] 0.0 0.056152193511642905 0.0714736818636741 0.0987872766172283 0.120837895850705 0.133591678274714 0.14053180371033702 1.3877787807814457e-16
51 17 CIN3+ label_0+label_2: High Grade | HPV-negative <CIN2 | ASC-US/LSIL [0.0, 3.35150480270386, 5.140167140960691] [-11.008186733553266, -2.748795416105142, -4.010248009038462, -4.60664472360736, -6.087336519091521] -2.189971905541478 0.0028073559928682 0.00463224593407769 0.00795285226750279 0.0106994765123714 0.012316140575016302 0.0132047680498179 1.3877787807814457e-16
52 17 CIN3+ label_0+label_2: High Grade | HPV-negative <CIN2 | NILM [0.0, 3.35150480270386, 5.140167140960691] [-11.008186733553266, -2.748795416105142, -4.010248009038462, -4.60664472360736, -6.087336519091521] -3.0083113846638474 0.000217474670789548 0.00102505375178246 0.00249666617420671 0.00371598505957691 0.00443456123574488 0.00482981907149305 1.3877787807814457e-16
53 17 CIN3+ label_0+label_2: High Grade | HPV-positive <CIN2 | ASC-H/AGC/HSIL+ [0.0, 3.3515625000000027, 5.388281249999999] [-10.54691011249509, -2.240786746752028, -3.632622617326058, -4.17107995201359, -5.755718773586673] 0.0 0.283925046033346 0.302266314811659 0.33452512019192904 0.360154491149052 0.374807893081757 0.382728941543987 4.996003610813204e-16
54 17 CIN3+ label_0+label_2: High Grade | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 3.3515625000000027, 5.388281249999999] [-10.54691011249509, -2.240786746752028, -3.632622617326058, -4.17107995201359, -5.755718773586673] -0.20773512406798625 0.0660029115279839 0.0854856922082638 0.11998776652616999 0.14762324557453899 0.163516655451206 0.172137039735473 4.996003610813204e-16
55 17 CIN3+ label_0+label_2: High Grade | HPV-positive <CIN2 | NILM [0.0, 3.3515625000000027, 5.388281249999999] [-10.54691011249509, -2.240786746752028, -3.632622617326058, -4.17107995201359, -5.755718773586673] -0.7339090471758761 0.0502224880729527 0.061979053698500604 0.08305330055168661 0.100178305176523 0.110129965710093 0.115559974612717 4.996003610813204e-16
56 17 CIN3+ label_0+label_2: Low Grade | HPV-negative <CIN2 | ASC-H/AGC/HSIL+ [0.0, 3.3921875000000004, 6.4796875] [-12.617897003010304, -3.7970179725994324, -6.525658531159966, -6.073030586317113, -6.257924890927562] 0.0 0.0164593639076601 0.020865910131221202 0.0288255780656094 0.0352978662713855 0.0389342494067136 0.040947433590996195 1.1796119636642288e-16
57 17 CIN3+ label_0+label_2: Low Grade | HPV-negative <CIN2 | ASC-US/LSIL [0.0, 3.3921875000000004, 6.4796875] [-12.617897003010304, -3.7970179725994324, -6.525658531159966, -6.073030586317113, -6.257924890927562] -1.0508854390530271 0.00045816445105480803 0.00202616816773695 0.0048701701194103705 0.00719392459035741 0.00850395144411777 0.00923059884268837 1.1796119636642288e-16
58 17 CIN3+ label_0+label_2: Low Grade | HPV-negative <CIN2 | NILM [0.0, 3.3921875000000004, 6.4796875] [-12.617897003010304, -3.7970179725994324, -6.525658531159966, -6.073030586317113, -6.257924890927562] -1.801676728882616 3.1533490176679904e-05 0.0007722429160041671 0.00211729098575043 0.00321779960310556 0.0038388157570307404 0.00418346861821767 1.1796119636642288e-16
59 17 CIN3+ label_0+label_2: Low Grade | HPV-positive <CIN2 | ASC-H/AGC/HSIL+ [0.0, 3.4375000000000027, 4.9499999999999975] [-10.826280746746997, -2.620033444443425, -3.9378457923904575, -4.578177810857306, -5.766887479985344] 0.0 0.22971674078599702 0.244083348646396 0.269516047197888 0.289711503374328 0.300869906443187 0.306989756904408 2.220446049250313e-16
60 17 CIN3+ label_0+label_2: Low Grade | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 3.4375000000000027, 4.9499999999999975] [-10.826280746746997, -2.620033444443425, -3.9378457923904575, -4.578177810857306, -5.766887479985344] -1.2387735560750097 0.0310566408302113 0.0363278167844026 0.0458363669929681 0.053555780922701406 0.0578879736180621 0.0602848606723243 2.220446049250313e-16
61 17 CIN3+ label_0+label_2: Low Grade | HPV-positive <CIN2 | NILM [0.0, 3.4375000000000027, 4.9499999999999975] [-10.826280746746997, -2.620033444443425, -3.9378457923904575, -4.578177810857306, -5.766887479985344] -1.1595249391199973 0.0205211557608812 0.026287808771337698 0.036683552066823805 0.0451169464582727 0.0498473486599558 0.0524637842176785 2.220446049250313e-16
62 17 CIN3+ label_0: High Grade <CIN2 | HPV-negative | ASC-H/AGC/HSIL+ [0.0, 3.3000000000000025, 5.431249999999999] [-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483] 0.0 0.056152193511642905 0.0714736818636741 0.0987872766172283 0.120837895850705 0.133591678274714 0.14053180371033702 4.996003610813204e-16
63 17 CIN3+ label_0: High Grade <CIN2 | HPV-negative | ASC-US/LSIL [0.0, 3.3000000000000025, 5.431249999999999] [-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483] -2.189971905541481 0.0028073559928682 0.00463224593407769 0.00795285226750279 0.0106994765123714 0.012316140575016302 0.0132047680498179 4.996003610813204e-16
64 17 CIN3+ label_0: High Grade <CIN2 | HPV-negative | NILM [0.0, 3.3000000000000025, 5.431249999999999] [-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483] -3.008311384663847 0.000217474670789548 0.00102505375178246 0.00249666617420671 0.00371598505957691 0.00443456123574488 0.00482981907149305 4.996003610813204e-16
65 17 CIN3+ label_0: High Grade <CIN2 | HPV-positive | ASC-H/AGC/HSIL+ [0.0, 3.3000000000000025, 5.431249999999999] [-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483] 0.46085110304222565 0.283925046033346 0.302266314811659 0.33452512019192904 0.360154491149052 0.374807893081757 0.382728941543987 4.996003610813204e-16
66 17 CIN3+ label_0: High Grade <CIN2 | HPV-positive | ASC-US/LSIL [0.0, 3.3000000000000025, 5.431249999999999] [-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483] 0.2531159789742397 0.0660029115279839 0.0854856922082638 0.11998776652616999 0.14762324557453899 0.163516655451206 0.172137039735473 4.996003610813204e-16
67 17 CIN3+ label_0: High Grade <CIN2 | HPV-positive | NILM [0.0, 3.3000000000000025, 5.431249999999999] [-11.51750433879959, -2.7087160287989778, -4.031034504451944, -4.701181851669925, -6.015461348929483] -0.27305794413365025 0.0502224880729527 0.061979053698500604 0.08305330055168661 0.100178305176523 0.110129965710093 0.115559974612717 4.996003610813204e-16
68 17 CIN3+ label_0: Low Grade <CIN2 | HPV-negative | ASC-H/AGC/HSIL+ [0.0, 3.9189535140991256, 4.434260654449458] [-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621] 0.0 0.0164593639076601 0.020865910131221202 0.0288255780656094 0.0352978662713855 0.0389342494067136 0.040947433590996195 2.220446049250313e-16
69 17 CIN3+ label_0: Low Grade <CIN2 | HPV-negative | ASC-US/LSIL [0.0, 3.9189535140991256, 4.434260654449458] [-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621] -1.0508854390530284 0.00045816445105480803 0.00202616816773695 0.0048701701194103705 0.00719392459035741 0.00850395144411777 0.00923059884268837 2.220446049250313e-16
70 17 CIN3+ label_0: Low Grade <CIN2 | HPV-negative | NILM [0.0, 3.9189535140991256, 4.434260654449458] [-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621] -1.8016767288826154 3.1533490176679904e-05 0.0007722429160041671 0.00211729098575043 0.00321779960310556 0.0038388157570307404 0.00418346861821767 2.220446049250313e-16
71 17 CIN3+ label_0: Low Grade <CIN2 | HPV-positive | ASC-H/AGC/HSIL+ [0.0, 3.9189535140991256, 4.434260654449458] [-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621] 1.4333705313265157 0.22971674078599702 0.244083348646396 0.269516047197888 0.289711503374328 0.300869906443187 0.306989756904408 2.220446049250313e-16
72 17 CIN3+ label_0: Low Grade <CIN2 | HPV-positive | ASC-US/LSIL [0.0, 3.9189535140991256, 4.434260654449458] [-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621] 0.19459697525150654 0.0310566408302113 0.0363278167844026 0.0458363669929681 0.053555780922701406 0.0578879736180621 0.0602848606723243 2.220446049250313e-16
73 17 CIN3+ label_0: Low Grade <CIN2 | HPV-positive | NILM [0.0, 3.9189535140991256, 4.434260654449458] [-11.53231335554015, -4.033464618657092, -5.704458893257282, -5.85096328236219, -6.65917891628621] 0.2738455922065207 0.0205211557608812 0.026287808771337698 0.036683552066823805 0.0451169464582727 0.0498473486599558 0.0524637842176785 2.220446049250313e-16
74 18 CIN2+ label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 2.8529907226562505, 4.98558349609375] [-10.34844881940246, -2.24210128461073, -4.564413713372809, -6.455917689788004, -10.613171503266397] 0.0 0.0754015255440931 0.103265794337961 0.145179223258591 0.169473034365134 0.177288570696931 0.17854208342549 5.551115123125783e-16
75 18 CIN2+ label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive <CIN2 | High Grade [0.0, 2.8529907226562505, 4.98558349609375] [-10.34844881940246, -2.24210128461073, -4.564413713372809, -6.455917689788004, -10.613171503266397] 0.7616733125518199 0.499132506342513 0.530907195266614 0.576617975356811 0.60197210394162 0.609951509308618 0.61122329054014 5.551115123125783e-16
76 18 CIN2+ label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive <CIN2 | NILM [0.0, 2.8529907226562505, 4.98558349609375] [-10.34844881940246, -2.24210128461073, -4.564413713372809, -6.455917689788004, -10.613171503266397] -0.8363475431129561 2.38238037242056e-15 0.013171196210381599 0.0334278190860156 0.045427494874570096 0.0493301039184659 0.0499579850656342 5.551115123125783e-16
77 18 CIN2+ label_0+label_2+label_3: High Grade | HPV-negative/ASCUS/LSIL | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 1.993764424324036, 5.465644538402557] [-8.058643072974567, -1.8886850796043781, -1.2230492132635378, -3.60609859472805, -4.573943855420296] 0.0 2.10984399628414e-18 0.0642167383232001 0.18451512993242702 0.288932661609402 0.35257094621844204 0.37886263581951196 3.3306690738754696e-16
78 18 CIN2+ label_0+label_2+label_3: High Grade | HPV-negative/ASCUS/LSIL | HPV-positive <CIN2 | High Grade [0.0, 1.993764424324036, 5.465644538402557] [-8.058643072974567, -1.8886850796043781, -1.2230492132635378, -3.60609859472805, -4.573943855420296] 1.1563566686924174 0.833305441055717 0.865008364666254 0.9128290596846701 0.9436044942776021 0.958137282157014 0.96330532556192 3.3306690738754696e-16
79 18 CIN2+ label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 2.75, 5.5] [-3.9596440054374784, -3.378672278185891, -3.9875232602526585, -3.6722810703457265, -4.280386842686037] 0.0 0.0659044703742194 0.089746688578391 0.109230111875092 0.12529894916311102 0.140192313505222 0.155753880872501 5.551115123125783e-16
80 18 CIN2+ label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive <CIN2 | High Grade [0.0, 2.75, 5.5] [-3.9596440054374784, -3.378672278185891, -3.9875232602526585, -3.6722810703457265, -4.280386842686037] 0.5773343339569103 0.5912195695356339 0.609619591237797 0.6243790956833439 0.636363776097805 0.647319257929656 0.658608929897879 5.551115123125783e-16
81 18 CIN2+ label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive <CIN2 | NILM [0.0, 2.75, 5.5] [-3.9596440054374784, -3.378672278185891, -3.9875232602526585, -3.6722810703457265, -4.280386842686037] -0.9820914167155511 0.0360575716765237 0.0453470409822074 0.0530518709507203 0.0594860854426566 0.0655159757267125 0.07188660783930981 5.551115123125783e-16
82 18 CIN2+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative <CIN2 | ASC-US/LSIL [0.0, 2.75, 5.5] [-20.536131988436342, -4.260644311297781, -3.356872403985886, -4.45548462017129, -5.841778904258112] 0.0 0.0131140716015184 0.018207911105975902 0.0312017894163993 0.047561186468938796 0.0620103077731488 0.0712615583346978 3.3306690738754696e-16
83 18 CIN2+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative <CIN2 | High Grade [0.0, 2.75, 5.5] [-20.536131988436342, -4.260644311297781, -3.356872403985886, -4.45548462017129, -5.841778904258112] -11.455432116776514 0.300073811964724 0.300073850328629 0.300073949099842 0.300074075354672 0.300074188683584 0.30007426216439703 3.3306690738754696e-16
84 18 CIN2+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative <CIN2 | NILM [0.0, 2.75, 5.5] [-20.536131988436342, -4.260644311297781, -3.356872403985886, -4.45548462017129, -5.841778904258112] -1.039851888850465 1.17957341124561e-14 0.00182768948185797 0.006517879154542669 0.012481064395005601 0.0178032520807647 0.021238743258582802 3.3306690738754696e-16
85 18 CIN2+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 2.749972265958786, 5.499840152263641] [-19.34733193429554, -4.88827911091044, -3.9845120611245077, -5.082976995007613, -6.469267687925621] 0.0 0.07351057572352189 0.07606669896412671 0.08261525750923729 0.0909184496853561 0.098307541381759 0.10306639528883099 3.3306690738754696e-16
86 18 CIN2+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-positive <CIN2 | High Grade [0.0, 2.749972265958786, 5.499840152263641] [-19.34733193429554, -4.88827911091044, -3.9845120611245077, -5.082976995007613, -6.469267687925621] 4.061397297742704 0.230831397902068 0.3448148392882 0.5664644165634131 0.7442690505691949 0.840774931785191 0.8828905441660799 3.3306690738754696e-16
87 18 CIN2+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-positive <CIN2 | NILM [0.0, 2.749972265958786, 5.499840152263641] [-19.34733193429554, -4.88827911091044, -3.9845120611245077, -5.082976995007613, -6.469267687925621] 0.9425976641150026 0.036133527238391 0.0429441067797216 0.060257919509119004 0.08193408722379729 0.10096490141836799 0.11309287374098201 3.3306690738754696e-16
88 18 CIN3+ label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 2.8187500000000014, 4.88125] [-21.931975912646944, -19.932014656863323, -21.959260875279913, -24.216762631029734, -25.901625072089512] 0.0 0.018868845497754902 0.0188688463833303 0.0188688474376925 0.0188688480451513 0.0188688482436359 0.0188688482756456 3.3306690738754696e-16
89 18 CIN3+ label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive <CIN2 | High Grade [0.0, 2.8187500000000014, 4.88125] [-21.931975912646944, -19.932014656863323, -21.959260875279913, -24.216762631029734, -25.901625072089512] 18.299272734135396 0.49755217974530097 0.5361550132958299 0.578266941318611 0.60077031262867 0.607859732457989 0.608991201389804 3.3306690738754696e-16
90 18 CIN3+ label_0+label_2+label_3: High Grade | Cotest-negative | HPV-positive <CIN2 | NILM [0.0, 2.8187500000000014, 4.88125] [-21.931975912646944, -19.932014656863323, -21.959260875279913, -24.216762631029734, -25.901625072089512] 16.680005520674186 7.72700650525083e-14 0.0157072262649549 0.03408677208965 0.0445196994119019 0.0479041281479215 0.0484488140137436 3.3306690738754696e-16
91 18 CIN3+ label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive <CIN2 | ASC-US/LSIL [0.0, 3.2656250000000018, 5.568750000000001] [-11.005120843490367, -4.072537754707295, -5.0977913217951665, -4.988725499836527, -6.606418997592393] 0.0 0.0112275700334512 0.015367350846191199 0.023149001780099397 0.030254251011826997 0.0356877959932409 0.0400104534558627 3.608224830031759e-16
92 18 CIN3+ label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive <CIN2 | High Grade [0.0, 3.2656250000000018, 5.568750000000001] [-11.005120843490367, -4.072537754707295, -5.0977913217951665, -4.988725499836527, -6.606418997592393] 1.1781712219333076 0.157836568529019 0.169236578546972 0.19037560996425398 0.20934934334176 0.223649651775841 0.23489762154274 3.608224830031759e-16
93 18 CIN3+ label_0+label_2+label_3: Low Grade | Cotest-negative | HPV-positive <CIN2 | NILM [0.0, 3.2656250000000018, 5.568750000000001] [-11.005120843490367, -4.072537754707295, -5.0977913217951665, -4.988725499836527, -6.606418997592393] -0.5125493120224014 0.010348964132360201 0.0128328458157558 0.0175132256919939 0.0217998505127751 0.0250864342949192 0.0277063839176718 3.608224830031759e-16
94 18 CIN3+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative <CIN2 | ASC-US/LSIL [0.0, 3.473531723022455, 4.096420288085933] [-9.852766225403219, -5.348005437798218, -9.227888582465996, -8.275788592809148, -9.138133904340833] 0.0 0.006557383449894349 0.00795848645101952 0.010099205818607 0.0113355021822377 0.0117227067039258 0.0117796357536864 5.551115123125783e-17
95 18 CIN3+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative <CIN2 | High Grade [0.0, 3.473531723022455, 4.096420288085933] [-9.852766225403219, -5.348005437798218, -9.227888582465996, -8.275788592809148, -9.138133904340833] -11.266547261922307 0.0999947153911425 0.09999473164211899 0.099994756516062 0.0999947709056376 0.0999947754161124 0.0999947760794175 5.551115123125783e-17
96 18 CIN3+ label_0+label_2+label_3: Low Grade | HPV-negative/ASCUS/LSIL | HPV-negative <CIN2 | NILM [0.0, 3.473531723022455, 4.096420288085933] [-9.852766225403219, -5.348005437798218, -9.227888582465996, -8.275788592809148, -9.138133904340833] -0.5297140871380742 3.5738078826717895e-35 0.000830618074109002 0.00210063628986212 0.00283460464295726 0.00306455905801228 0.00309837141083125 5.551115123125783e-17
97 18 CIN3+ label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL <CIN2 | HPV-negative | ASC-US/LSIL [0.0, 2.7500272259116176, 5.281872798502446] [-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774] 0.0 0.006557383449894349 0.00795848645101952 0.010099205818607 0.0113355021822377 0.0117227067039258 0.0117796357536864 2.4216739724636227e-15
98 18 CIN3+ label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL <CIN2 | HPV-negative | High Grade [0.0, 2.7500272259116176, 5.281872798502446] [-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774] -11.266547261886572 0.0999947153911425 0.09999473164211899 0.099994756516062 0.0999947709056376 0.0999947754161124 0.0999947760794175 2.4216739724636227e-15
99 18 CIN3+ label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL <CIN2 | HPV-negative | NILM [0.0, 2.7500272259116176, 5.281872798502446] [-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774] -0.5297140871380728 3.5738078826717895e-35 0.000830618074109002 0.00210063628986212 0.00283460464295726 0.00306455905801228 0.00309837141083125 2.4216739724636227e-15
100 18 CIN3+ label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL <CIN2 | HPV-positive | ASC-US/LSIL [0.0, 2.7500272259116176, 5.281872798502446] [-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774] -27.299467870607586 0.0147068843215046 0.0147068843215059 0.0147068843215079 0.014706884321509 0.0147068843215093 0.014706884321509399 2.4216739724636227e-15
101 18 CIN3+ label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL <CIN2 | HPV-positive | High Grade [0.0, 2.7500272259116176, 5.281872798502446] [-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774] 4.4558478579098715 0.0769197677445438 0.182575885831324 0.321353903291499 0.39060597796332 0.410823095045538 0.413739088439336 2.4216739724636227e-15
102 18 CIN3+ label_0+label_2: Low Grade | HPV-negative/ASCUS/LSIL <CIN2 | HPV-positive | NILM [0.0, 2.7500272259116176, 5.281872798502446] [-19.74001165167534, -5.285936631490191, -8.513690926779626, -11.736464163463973, -15.062291758785774] 1.3214479115965938 5.106044319392471e-40 0.00527694836759951 0.0133000310093961 0.017911804765725802 0.0193529432788598 0.019564696974458298 2.4216739724636227e-15
103 24 CIN2+ label_1: HPV-negative Treatment for CIN 3 | ASC-US/LSIL [0.0, 3.0250000000000004, 5.225] [-5.970564123896623, -2.9583893638499363, -4.516974672861336, -5.780793455732832, -6.209824875259012] 0.0 0.0262214431467089 0.0416928080114781 0.0646927106456137 0.0807470937165037 0.08826314484108369 0.0917702560686117 4.163336342344337e-16
104 24 CIN2+ label_1: HPV-negative Treatment for CIN 3 | High Grade [0.0, 3.0250000000000004, 5.225] [-5.970564123896623, -2.9583893638499363, -4.516974672861336, -5.780793455732832, -6.209824875259012] -10.729002075719931 0.21056564309331802 0.21056591998573299 0.21056633999139301 0.210566639329971 0.21056678127012798 0.21056684790255598 4.163336342344337e-16
105 24 CIN2+ label_1: HPV-negative Treatment for CIN 3 | NILM [0.0, 3.0250000000000004, 5.225] [-5.970564123896623, -2.9583893638499363, -4.516974672861336, -5.780793455732832, -6.209824875259012] -0.9535043052028737 0.00114916052911648 0.0072952786692584305 0.0165459402914708 0.023086242714399397 0.026172299707561398 0.0276176550475499 4.163336342344337e-16
106 24 CIN2+ label_1: HPV-positive Treatment for CIN 3 | ASC-US/LSIL [0.0, 2.8875, 5.225] [-4.909963766900336, -1.87064845459847, -3.1538174160037586, -5.191561600237883, -4.820452622627722] 0.0 0.21346052558124298 0.25135818692788603 0.305386982153937 0.341496774219641 0.35795709489185595 0.365541687427744 4.440892098500626e-16
107 24 CIN2+ label_1: HPV-positive Treatment for CIN 3 | High Grade [0.0, 2.8875, 5.225] [-4.909963766900336, -1.87064845459847, -3.1538174160037586, -5.191561600237883, -4.820452622627722] 0.4241078676772622 0.718841415723524 0.7392788126726241 0.7674794483957981 0.785696434253688 0.793828658616323 0.797539091168836 4.440892098500626e-16
108 24 CIN2+ label_1: HPV-positive Treatment for CIN 3 | NILM [0.0, 2.8875, 5.225] [-4.909963766900336, -1.87064845459847, -3.1538174160037586, -5.191561600237883, -4.820452622627722] -0.2934210941211471 0.08629421216615149 0.11932921444308199 0.167172915569126 0.199676460972488 0.214642521254526 0.22157134454827 4.440892098500626e-16
109 24 CIN2+ (todas juntas): Treatment for CIN 3 | HPV-negative | ASC-US/LSIL [0.0, 3.0392578124999985, 6.147070312500004] [-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997] 0.0 0.0262214431467089 0.0416928080114781 0.0646927106456137 0.0807470937165037 0.08826314484108369 0.0917702560686117 4.440892098500626e-16
110 24 CIN2+ (todas juntas): Treatment for CIN 3 | HPV-negative | High Grade [0.0, 3.0392578124999985, 6.147070312500004] [-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997] -10.729002075702507 0.21056564309331802 0.21056591998573299 0.21056633999139301 0.210566639329971 0.21056678127012798 0.21056684790255598 4.440892098500626e-16
111 24 CIN2+ (todas juntas): Treatment for CIN 3 | HPV-negative | NILM [0.0, 3.0392578124999985, 6.147070312500004] [-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997] -0.9535043052028733 0.00114916052911648 0.0072952786692584305 0.0165459402914708 0.023086242714399397 0.026172299707561398 0.0276176550475499 4.440892098500626e-16
112 24 CIN2+ (todas juntas): Treatment for CIN 3 | HPV-positive | ASC-US/LSIL [0.0, 3.0392578124999985, 6.147070312500004] [-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997] 1.126031972593485 0.21346052558124298 0.25135818692788603 0.305386982153937 0.341496774219641 0.35795709489185595 0.365541687427744 4.440892098500626e-16
113 24 CIN2+ (todas juntas): Treatment for CIN 3 | HPV-positive | High Grade [0.0, 3.0392578124999985, 6.147070312500004] [-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997] 1.550139840270747 0.718841415723524 0.7392788126726241 0.7674794483957981 0.785696434253688 0.793828658616323 0.797539091168836 4.440892098500626e-16
114 24 CIN2+ (todas juntas): Treatment for CIN 3 | HPV-positive | NILM [0.0, 3.0392578124999985, 6.147070312500004] [-5.96423984634528, -2.791937776700103, -5.553638795339543, -6.227771274064003, -5.259712198998997] 0.8326108784723378 0.08629421216615149 0.11932921444308199 0.167172915569126 0.199676460972488 0.214642521254526 0.22157134454827 4.440892098500626e-16
115 24 CIN3+ label_1: HPV-negative Treatment for CIN 3 | ASC-US/LSIL [0.0, 3.2656250000000018, 4.674999999999999] [-10.75052455883268, -3.7407644366146644, -5.366941921959517, -6.1266345031929, -7.140714307357668] 0.0 0.00749275883282888 0.0140702718574874 0.0251859308624384 0.0331275183226566 0.036734651218946104 0.0381750857365055 2.220446049250313e-16
116 24 CIN3+ label_1: HPV-negative Treatment for CIN 3 | High Grade [0.0, 3.2656250000000018, 4.674999999999999] [-10.75052455883268, -3.7407644366146644, -5.366941921959517, -6.1266345031929, -7.140714307357668] -10.453417548881681 0.175428184775675 0.17542834295072499 0.175428612672362 0.175428807265387 0.17542889617954 0.17542893177864202 2.220446049250313e-16
117 24 CIN3+ label_1: HPV-negative Treatment for CIN 3 | NILM [0.0, 3.2656250000000018, 4.674999999999999] [-10.75052455883268, -3.7407644366146644, -5.366941921959517, -6.1266345031929, -7.140714307357668] -0.6387834786259222 0.000288048962219205 0.0037912398055393298 0.009736625843226439 0.0140039316381632 0.0159476393037477 0.0167247788723049 2.220446049250313e-16
118 24 CIN3+ label_1: HPV-positive Treatment for CIN 3 | ASC-US/LSIL [0.0, 3.2656250000000018, 4.674999999999999] [-9.365330068085091, -2.3555699458788215, -3.9817474312236376, -4.741440012456921, -5.7555198166218045] 0.0 0.102172567414265 0.125711673454009 0.16443615710668202 0.191304726578008 0.20329233727663698 0.20804192662846 5.551115123125783e-16
119 24 CIN3+ label_1: HPV-positive Treatment for CIN 3 | High Grade [0.0, 3.2656250000000018, 4.674999999999999] [-9.365330068085091, -2.3555699458788215, -3.9817474312236376, -4.741440012456921, -5.7555198166218045] 0.65783616404365 0.527002022130951 0.550651254477406 0.58828309749054 0.613460217784654 0.624445965439573 0.628756365442339 5.551115123125783e-16
120 24 CIN3+ label_1: HPV-positive Treatment for CIN 3 | NILM [0.0, 3.2656250000000018, 4.674999999999999] [-9.365330068085091, -2.3555699458788215, -3.9817474312236376, -4.741440012456921, -5.7555198166218045] -0.6016494080274817 0.058115292449263896 0.0717266377266579 0.09448470144641959 0.11055643859221301 0.117804742530884 0.120690204232158 5.551115123125783e-16
121 24 CIN3+ (todas juntas): Treatment for CIN 3 | HPV-negative | ASC-US/LSIL [0.0, 3.2449462890625016, 4.685742187499999] [-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049] 0.0 0.00749275883282888 0.0140702718574874 0.0251859308624384 0.0331275183226566 0.036734651218946104 0.0381750857365055 5.551115123125783e-16
122 24 CIN3+ (todas juntas): Treatment for CIN 3 | HPV-negative | High Grade [0.0, 3.2449462890625016, 4.685742187499999] [-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049] -10.453417548844534 0.175428184775675 0.17542834295072499 0.175428612672362 0.175428807265387 0.17542889617954 0.17542893177864202 5.551115123125783e-16
123 24 CIN3+ (todas juntas): Treatment for CIN 3 | HPV-negative | NILM [0.0, 3.2449462890625016, 4.685742187499999] [-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049] -0.6387834786259241 0.000288048962219205 0.0037912398055393298 0.009736625843226439 0.0140039316381632 0.0159476393037477 0.0167247788723049 5.551115123125783e-16
124 24 CIN3+ (todas juntas): Treatment for CIN 3 | HPV-positive | ASC-US/LSIL [0.0, 3.2449462890625016, 4.685742187499999] [-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049] 1.385194490735862 0.102172567414265 0.125711673454009 0.16443615710668202 0.191304726578008 0.20329233727663698 0.20804192662846 5.551115123125783e-16
125 24 CIN3+ (todas juntas): Treatment for CIN 3 | HPV-positive | High Grade [0.0, 3.2449462890625016, 4.685742187499999] [-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049] 2.043030654779511 0.527002022130951 0.550651254477406 0.58828309749054 0.613460217784654 0.624445965439573 0.628756365442339 5.551115123125783e-16
126 24 CIN3+ (todas juntas): Treatment for CIN 3 | HPV-positive | NILM [0.0, 3.2449462890625016, 4.685742187499999] [-10.844088333095861, -3.744491191548657, -5.3380576060538, -6.14859693806409, -7.139654756162049] 0.7835450827083796 0.058115292449263896 0.0717266377266579 0.09448470144641959 0.11055643859221301 0.117804742530884 0.120690204232158 5.551115123125783e-16
127 25 CIN2+ label_0: High Grade Treatment for CIN3 | ASCUS-LSIL HPV-negative [0.0, 3.5068246841430617, 4.498048400878903] [-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275] 0.0 0.00689426072206779 0.0234041056060416 0.050432715718639595 0.0688704714867694 0.0768074028972754 0.07935829582749071 3.3306690738754696e-16
128 25 CIN2+ label_0: High Grade Treatment for CIN3 | Cotest-negative [0.0, 3.5068246841430617, 4.498048400878903] [-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275] -1.171860477937203 0.00116569116099475 0.00633957157518789 0.0149417396800686 0.020907203198276297 0.023500281742851802 0.024336951511278803 3.3306690738754696e-16
129 25 CIN2+ label_0: High Grade Treatment for CIN3 | HighGrade [0.0, 3.5068246841430617, 4.498048400878903] [-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275] 0.6664303268151888 0.609348144462981 0.6218948655778039 0.642004999920256 0.655416346620817 0.661112832617304 0.662933846623046 3.3306690738754696e-16
130 25 CIN2+ label_0: High Grade Treatment for CIN3 | LowGrade [0.0, 3.5068246841430617, 4.498048400878903] [-8.596411927947557, -2.7827500664139877, -5.123368036297188, -5.04140686733415, -6.6509943777656275] 0.9978027150138086 0.148218727717598 0.186081707352701 0.245741894515564 0.284807629791837 0.301222257287978 0.30644683574999404 3.3306690738754696e-16
131 25 CIN2+ label_0: Low Grade Treatment for CIN3 | ASCUS-LSIL HPV-negative [0.0, 2.75, 5.775] [-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695] 0.0 0.0491750046718411 0.0637135560502284 0.08407235294447821 0.09678228478318751 0.102804510484527 0.107012417563002 4.996003610813204e-16
132 25 CIN2+ label_0: Low Grade Treatment for CIN3 | Cotest-negative [0.0, 2.75, 5.775] [-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695] -0.7542155007340696 0.00113944145053942 0.00835288281943979 0.0185545319124284 0.024984382853127398 0.028047709175761798 0.0301946136369331 4.996003610813204e-16
133 25 CIN2+ label_0: Low Grade Treatment for CIN3 | HighGrade [0.0, 2.75, 5.775] [-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695] 0.3854366675002079 0.505615330492757 0.516689472960763 0.532061385494076 0.541577094082526 0.546063945791907 0.549190652662297 4.996003610813204e-16
134 25 CIN2+ label_0: Low Grade Treatment for CIN3 | LowGrade [0.0, 2.75, 5.775] [-6.201392856810505, -2.9340273490511635, -6.621741705447746, -5.207340087226381, -5.221145417911695] 0.8345314151494438 0.16759208587594798 0.196621979175685 0.23629631191997402 0.260489803439742 0.271799493725444 0.27964341551433497 4.996003610813204e-16
135 25 CIN3+ label_0: High Grade Treatment for CIN3 | ASCUS-LSIL HPV-negative [0.0, 3.093750000000001, 4.949999999999999] [-11.65621566124099, -4.3784350073280045, -6.399237709979687, -7.520958947104618, -11.54649229806419] 0.0 6.616310929246371e-22 0.00344063446225507 0.00908842803702181 0.0128583636308344 0.014321824844177 0.014659239877557899 3.3306690738754696e-16
136 25 CIN3+ label_0: High Grade Treatment for CIN3 | HighGrade [0.0, 3.093750000000001, 4.949999999999999] [-11.65621566124099, -4.3784350073280045, -6.399237709979687, -7.520958947104618, -11.54649229806419] 1.8321853909330095 0.470938641571351 0.482208888835742 0.500271656617588 0.512031663130867 0.516533734139799 0.517566765289406 3.3306690738754696e-16
137 25 CIN3+ label_0: High Grade Treatment for CIN3 | LowGrade [0.0, 3.093750000000001, 4.949999999999999] [-11.65621566124099, -4.3784350073280045, -6.399237709979687, -7.520958947104618, -11.54649229806419] 2.048734936225644 0.0791682483413729 0.10346386850759601 0.142135447953194 0.167132789739333 0.17666419487572899 0.17884822315252102 3.3306690738754696e-16
138 25 CIN3+ label_0: Low Grade Treatment for CIN3 | ASCUS-LSIL HPV-negative [0.0, 3.0239257812500004, 5.2142578125] [-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101] 0.0 0.016393231121640497 0.0267142535746957 0.0431674882906643 0.0541326061215275 0.05962404507213279 0.0631155908076441 2.220446049250313e-16
139 25 CIN3+ label_0: Low Grade Treatment for CIN3 | Cotest-negative [0.0, 3.0239257812500004, 5.2142578125] [-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101] -1.2834799456120654 0.00056859310178751 0.00348534850162038 0.00818167134838134 0.0113440101892865 0.012937709304145199 0.013954510943629499 2.220446049250313e-16
140 25 CIN3+ label_0: Low Grade Treatment for CIN3 | HighGrade [0.0, 3.0239257812500004, 5.2142578125] [-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101] 0.6594645601199031 0.32894402939158196 0.342493691231193 0.363817761773228 0.377840417952489 0.384806371694159 0.389215739325888 2.220446049250313e-16
141 25 CIN3+ label_0: Low Grade Treatment for CIN3 | LowGrade [0.0, 3.0239257812500004, 5.2142578125] [-9.032473598361769, -3.2280057531071598, -6.183553694822977, -5.077619931052827, -6.782439103358101] 0.30595946805334373 0.0909136890929964 0.103842681541942 0.12435198959338001 0.13795044713030602 0.144739553455262 0.149048808616415 2.220446049250313e-16
+317
View File
@@ -0,0 +1,317 @@
"""What this module covers: `models.cacu.survival`: the index it takes from the total cohort (provisionally the first
biopsy reported as invasive carcinoma, with its rules), the covariates (the most recent observations up to it) and the
outcome it derives from a build's events, that the estimator learns the direction the data give, that the dataflow
reaches its metrics, its five routines and its population record without MLflow, and that training registers a version
that dates each risk by the model's own index.
Fixtures: `cohort_frame`, a long frame of 240 members of the total cohort, diagnosed in 2018-2020 and followed to the
2026 cut-off, whose death depends on their latest cytology before the diagnosis (HSIL+) and HPV, with members that
must be left out;
`cohort_file`, that frame as a build's Parquet file with its lineage; `mlflow_tracking` (conftest), a SQLite-backed
MLflow.
"""
import dataclasses
import json
from datetime import date, datetime, timedelta, timezone
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cacu.survival import estimator
from models.cacu.survival.estimator import FEATURES, IntervalSurvival
from models.cama.survival.estimator import outcome_table
from models.dags.estimation import estimate
from models.dags.training import Scenario, dataflow, external_inputs, train
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.registry import registry
from models.io.storage import CohortFile, read_cohort, read_metadata
from models.steps import indexing
CUTOFF = date(2026, 1, 1)
SCENARIO = Scenario.load("cacu", "survival")
CONFIG = SCENARIO.config
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": CUTOFF.isoformat()}
LINEAGE = {"url": "cacu/cohorte_total", "datos_as_of": CUTOFF.isoformat(), "parametros": json.dumps(WINDOW)}
N = 240
QUICK = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}, "risk_interval_replicas": 20}
def _row(pac_id, when, tipo, valor=None, source="t", source_id=None, first=None):
return {"pac_id": pac_id, "fecha_indice": first or when, "fecha": when,
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": None, "fuente_tabla": source,
"fuente_id": source_id or f"{pac_id}-{tipo}-{when}"}
def _sample(pac_id, when, bethesda, vph, first=None):
"""A cytology sample and its Bethesda and HPV results on the same source row, as the timeline gives them."""
key = f"S{pac_id}-{when}"
return [_row(pac_id, when, "citologia", source_id=key, first=first),
_row(pac_id, when, "bethesda", bethesda, source_id=key, first=first),
_row(pac_id, when, "vph", vph, source_id=key, first=first)]
def _person(pac_id, born, first, died=None):
rows = [_row(pac_id, born, "nacimiento", source="persona", first=first)]
if died:
rows.append(_row(pac_id, died, "defuncion", source="persona", first=first))
return rows
def _carcinoma(pac_id, when, first=None, grade="CARCINOMA"):
return [_row(pac_id, when, "biopsia", grade, source_id=f"B{pac_id}-{when}", first=first)]
@pytest.fixture(scope="module")
def cohort_frame():
"""240 members, each with her birth, an old normal cotest, a latest cytology 1-6 months before her diagnosis (NILM,
LSIL or HSIL+; HPV positive or not), a CIS biopsy before the diagnosis for some, the diagnosis (a biopsy reported
as invasive carcinoma) in 2018-2020 and, if she dies by the cut-off, her death: exponential in months, faster with
HSIL+ and with a positive HPV. Member 241 has a CIS biopsy only, which is her diagnosis (in situ counts); members
242 to 244 must be left out: no birth date (`sin_nacimiento`), a death before the diagnosis
(`defuncion_hasta_el_indice`), a diagnosis before the window."""
rng = np.random.default_rng(5)
rows = []
for pac_id in range(1, N + 1):
index = date(2018, 1, 1) + timedelta(days=int(rng.integers(0, 1095)))
bethesda = str(rng.choice(["NORMAL", "LIEBG", "LIEAG"], p=[0.5, 0.25, 0.25]))
vph = str(rng.choice(["POSITIVO", "NEGATIVO"]))
rate = 0.004 * np.exp(1.6 * (bethesda == "LIEAG") + 0.5 * (vph == "POSITIVO"))
died = index + timedelta(days=1 + int(rng.exponential(1 / rate) * 30.4375)) # after the diagnosis
first = index - timedelta(days=900)
rows += _person(pac_id, date(1960, 1, 1) + timedelta(days=pac_id * 40), first, died if died <= CUTOFF else None)
rows += _sample(pac_id, first, "NORMAL", "NEGATIVO", first=first)
rows += _sample(pac_id, index - timedelta(days=int(rng.integers(30, 180))), bethesda, vph, first=first)
if pac_id % 5 == 0:
rows += _carcinoma(pac_id, index - timedelta(days=20), first=first, grade="CIS")
rows += _carcinoma(pac_id, index, first=first)
first = date(2019, 1, 1)
rows += _person(241, date(1970, 1, 1), first) + _sample(241, first, "LIEAG", "POSITIVO", first=first)
rows += _carcinoma(241, first + timedelta(days=30), first=first, grade="CIS")
rows += _sample(242, first, "LIEAG", "POSITIVO", first=first) + _carcinoma(242, first + timedelta(days=30), first=first)
rows += _person(243, date(1970, 1, 1), first, died=first + timedelta(days=10))
rows += _sample(243, first, "LIEAG", "POSITIVO", first=first) + _carcinoma(243, first + timedelta(days=30), first=first)
rows += _person(244, date(1970, 1, 1), date(2014, 1, 1)) + _carcinoma(244, date(2015, 1, 1), first=date(2014, 1, 1))
return pd.DataFrame(rows, columns=SCHEMA.names)
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 3's file, with the lineage a dbt build gives."""
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
path = tmp_path / "3.parquet"
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "3"}), path)
return path
def _indexed(frame):
return indexing.cohort(frame, LINEAGE, CONFIG["index"])
@pytest.fixture(scope="module")
def labelled(cohort_frame):
"""The 240 indexed members with their covariates and outcome, as the dataflow labels them."""
indexed = _indexed(cohort_frame)
features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["cytology"])
cap = CONFIG["survival"]["cap_months"]
return features.join(outcome_table(indexed, CUTOFF, cap)).reset_index()
def test_the_graph_takes_exactly_its_config_and_the_cohort():
"""Pins down the driver's external inputs: the loaders' `source_cohort` and `cohort_lineage` and the config's keys,
and nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed CaMa node) and becomes an
input."""
required, optional = external_inputs(dataflow(*SCENARIO.modules, config=CONFIG))
assert required == {"source_cohort", "cohort_lineage", "age_cuts", "cytology", "etiquetas", "horizons_years",
"index", "survival", "train_fraction"}
# `index` is required: the registered model re-indexes a build with it.
assert optional == {"calibration_bins", "report_panels", "risk_interval_level", "risk_interval_replicas"}
def _primer_carcinoma(frame: pd.DataFrame) -> pd.Series:
"""Each member's first biopsy reported as carcinoma, in situ or invasive: the survival scenario's diagnosis."""
biopsias = frame[(frame["tipo"] == "biopsia") & frame["valor_codigo"].isin(["CIS", "CARCINOMA"])]
return biopsias.groupby("pac_id")["fecha"].min()
def test_the_index_is_the_first_carcinoma_biopsy_and_its_rules_leave_out_who_they_should(cohort_frame):
"""Pins down the provisional index: each member is indexed at her first biopsy reported as carcinoma, in situ or
invasive, not at her first observation: an earlier CIS biopsy is the diagnosis (member 5), and a CIS biopsy only
(241) is a case too; no birth date (242), a death before the diagnosis (243) and a diagnosis before the window
(244) leave the cohort. Fails if the scenario stops taking `[config.index]`, drops in situ from the diagnosis, or
takes the window from elsewhere than the lineage."""
attrition = dict(indexing.index_attrition(cohort_frame, LINEAGE, CONFIG["index"]))
indexed = _indexed(cohort_frame)
# a CIS 20 days before a diagnosis at the window's start puts that member's diagnosis before the window
inicio = date.fromisoformat(WINDOW["recruitment_start"])
antes = set(_primer_carcinoma(cohort_frame)[lambda d: d < inicio].index) & set(range(1, N + 1))
assert set(indexed["pac_id"].unique()) == (set(range(1, N + 1)) | {241}) - antes
assert attrition["sin_nacimiento"] == N + 2 - len(antes)
assert attrition["defuncion_hasta_el_indice"] == N + 1 - len(antes)
five = cohort_frame[cohort_frame["pac_id"] == 5]
in_situ = five[(five["tipo"] == "biopsia") & (five["valor_codigo"] == "CIS")]["fecha"].iloc[0]
assert indexed[indexed["pac_id"] == 5]["fecha_indice"].iloc[0] == in_situ
def test_the_covariates_are_the_most_recent_observations_up_to_the_diagnosis(cohort_frame):
"""Pins down: the cytology and HPV are the member's latest before the diagnosis, not her first ones (an old normal
cotest) nor a later, worse sample; the cytology is in KPNC's categories (`LIEAG` is `HSIL+`); the age group is the
age at the diagnosis. Fails if the covariates read the first sample, a sample after the index, or the age at
another date."""
one = cohort_frame[cohort_frame["pac_id"] == 1]
diagnosis = one[(one["tipo"] == "biopsia") & (one["valor_codigo"] == "CARCINOMA")]["fecha"].iloc[0]
later = pd.DataFrame(_sample(1, diagnosis + timedelta(days=60), "LIEAG", "POSITIVO", first=diagnosis),
columns=SCHEMA.names)
table = estimator.member_table(_indexed(pd.concat([one, later])), CONFIG["age_cuts"], CONFIG["cytology"])
row = table.loc[1]
before = one[(one["tipo"] == "bethesda") & (one["fecha"] <= diagnosis)].sort_values("fecha")
latest = before["valor_codigo"].iloc[-1]
assert row["cytology"] == {"NORMAL": "NILM", "LIEBG": "LSIL", "LIEAG": "HSIL+"}[latest]
hpv = one[(one["tipo"] == "vph") & (one["fecha"] <= diagnosis)].sort_values("fecha")["valor_codigo"].iloc[-1]
assert row["hpv"] == hpv
age = (diagnosis - (date(1960, 1, 1) + timedelta(days=40))).days / 365.25
assert row["age_group"] == ("<35" if age < 35 else "35-44" if age < 45 else "45-54" if age < 55 else "≥55")
def test_hsil_moves_the_mortality_the_way_the_data_say(labelled):
"""Pins down: fitted on members whose death depends on HSIL+ and HPV, the estimator gives HSIL+ a higher mortality
than NILM at every horizon, growing with the horizon and in 0 to 1. Fails if the fit stops using the covariates or
the survival stops being a product of the intervals."""
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
labelled[["months", "event"]])
probe = labelled[FEATURES].iloc[[0, 0]].copy()
probe["cytology"] = ["NILM", "HSIL+"]
probe["hpv"] = "POSITIVO"
mortality = model.predict_proba(probe)
assert mortality.shape == (2, 3) and ((0 <= mortality) & (mortality <= 1)).all()
assert (mortality[1] > mortality[0]).all() and (np.diff(mortality, axis=1) >= 0).all()
def test_the_dataflow_reaches_its_metrics_routines_and_population_record_without_mlflow(cohort_frame):
"""Pins down: from the source cohort and its lineage the graph gives metrics that are numbers, the five routine
records (ML-01a) as JSON over this scenario's covariates, and the `curvas` record with KM and LR, HBN and combined
points at 12, 36 and 60 months. Fails if a CaMa node called from here changes its inputs, a routine goes missing,
or the record stops carrying a series."""
result = dataflow(*SCENARIO.modules, config=QUICK).execute(
["metrics", "routines", "population"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
assert all(isinstance(v, (int, float)) for v in result["metrics"].values())
assert result["metrics"]["n_train"] + result["metrics"]["n_test"] == N
routines = result["routines"]
assert set(routines) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
assert routines["METODO_ANALITICO"]["covariates"] == FEATURES and set(routines["DATOS_FALTANTES"]["train"]) == set(FEATURES)
json.dumps(routines)
curves = result["population"]["curvas"]
assert curves["horizons_months"] == [12, 36, 60] and curves["n"] == N and set(curves["points"]) == {"LR", "HBN", "COMB"}
assert curves["etiquetas"]["eje_x"] == CONFIG["etiquetas"]["eje_x"]
json.dumps(curves)
def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking,
tmp_path):
"""Pins down: training on a build's file registers a version with its population record; estimating with it writes
one row per scored member and horizon, dated by the model's index (the carcinoma biopsy), with its combination's
bootstrap interval holding it, and with the members the scenario leaves out absent. Fails if the version cannot
score a build, the estimate keeps the cohort's index, or the risks lose their interval."""
version = train(dataclasses.replace(SCENARIO, config=QUICK), CohortFile(cohort_file))
output = tmp_path / "estimate.parquet"
resolved, wrote = estimate(SCENARIO, CohortFile(cohort_file), output, version)
assert wrote and resolved.version == version
files = [f["path"] for f in registry.artifacts("cacu", "survival", version)]
assert {"analisis/curvas.json", "analisis/subgrupos.json", "reportes/subgrupos.html", "diagramas/pipeline.dot",
"diagramas/pipeline.svg"} <= set(files)
risks = pq.read_table(output).to_pandas()
inicio = date.fromisoformat(WINDOW["recruitment_start"])
antes = set(_primer_carcinoma(read_cohort(cohort_file))[lambda d: d < inicio].index)
assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0}
assert risks[["ic_bajo", "ic_alto"]].notna().all().all()
assert ((risks["ic_bajo"] <= risks["probabilidad"]) & (risks["probabilidad"] <= risks["ic_alto"])).mean() > 0.9
assert set(risks["pac_id"]) == (set(range(1, N + 1)) | {241}) - antes
frame = read_cohort(cohort_file)
diagnosis = frame[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "CARCINOMA") & (frame["pac_id"] == 1)]
assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == diagnosis["fecha"].iloc[0]
assert read_metadata(output)["desenlace"] == "muerte"
def test_the_subgroup_report_sets_each_combinations_model_against_its_kaplan_meier(cohort_frame):
"""Pins down the report: one record per combination of the covariates present, with its members and deaths adding
up to the cohort, its Kaplan-Meier with a band that holds it, and the model's survival at 0, 12, 36 and 60 months
with its bootstrap interval (the SEER pipeline's subgroups); the model sets HSIL+ below NILM (same age and HPV),
the record names its methods, and the page is Plotly's with a panel per combination. Fails if a combination goes
missing, a band is inverted, the methods go unrecorded, the record stops being JSON, or the page stops drawing the
two series."""
result = dataflow(*SCENARIO.modules, config=QUICK).execute(
["population", "reports"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
combos = result["population"]["subgrupos"]["combinations"]
assert sum(c["n"] for c in combos) == N and sum(c["deaths"] for c in combos) == result["population"]["curvas"]["events"]
for c in combos:
km, model = c["km"], c["model"]
assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(km["low"], km["S"], km["high"]))
assert model["months"] == [0, 12, 36, 60] and model["S"][0] == 1.0
assert all(0 <= lo <= hi <= 1 for lo, hi in zip(model["low"], model["high"]))
assert set(result["population"]["subgrupos"]["metodos"]) == {"empirica", "modelo"}
by = {tuple(c["combination"].values()): c["model"]["S"][-1] for c in combos}
pairs = [(by[(a, "NILM", h)], by[(a, "HSIL+", h)]) for a, _, h in by if (a, "NILM", h) in by and (a, "HSIL+", h) in by]
assert pairs and all(hsil < nilm for nilm, hsil in pairs)
json.dumps(combos)
page = result["reports"]["subgrupos"]
assert page.startswith("<!doctype html>") and "plotly" in page.lower() and "IC 95 % Greenwood" in page
assert "Métodos" in page and "sv_sub_points" in page
def _run_notebook(path, cohort_file, domain, scenario, monkeypatch, **parameters):
"""Runs a notebook's code cells in this process, as the platform's runner would on a build's file (`COHORT_FILE`,
`MODELS_DOMAIN`, `MODELS_SCENARIO`), with `parameters` replacing its parameters cell; returns its namespace."""
import nbformat
monkeypatch.setenv("COHORT_FILE", str(cohort_file))
monkeypatch.setenv("MODELS_DOMAIN", domain)
monkeypatch.setenv("MODELS_SCENARIO", scenario)
namespace = {}
for cell in nbformat.read(path, as_version=4).cells:
if cell.cell_type != "code":
continue
exec(cell.source, namespace)
if "parameters" in cell.metadata.get("tags", []):
namespace.update(parameters)
return namespace
def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch):
"""Pins down the survival report's notebook (`models/cacu/survival/notebooks/reporte_subgrupos.ipynb`): its cells run
on a build's file with the platform's environment and compute every indexed member's combination. Fails if the
notebook drifts from the report's functions or the scenario's config."""
from pathlib import Path
path = Path(estimator.__file__).parent / "notebooks" / "reporte_subgrupos.ipynb"
found = _run_notebook(path, cohort_file, "cacu", "survival", monkeypatch)
assert sum(r["n"] for r in found["survival"]) == N
def test_the_survival_scenario_shows_the_probability_of_surviving():
"""Pins down: the scenario's estimand names the probability of surviving and marks it as the complement of the
model's number (the probability of dying), so the patient's record shows survival, with its covariates. Fails if
`complement` is dropped: the record would show a death probability labelled as survival."""
estimand = Scenario.load("cacu", "survival").estimand
assert estimand["quantity"] == "Probabilidad de supervivencia" and estimand["complement"] == "supervivencia"
assert estimand["index_date"] == "la primera biopsia con carcinoma invasor o in situ"
assert "VPH" in estimand["covariates"]
def test_a_survival_case_is_a_carcinoma_invasive_or_in_situ():
"""Pins down: the survival scenario's index is the first biopsy of CIS or invasive carcinoma, so in situ cases are
followed too. Fails if CIS drops out of the index, which would leave its patients without a survival estimate."""
assert Scenario.load("cacu", "survival").config["index"]["event_grades"] == ["CIS", "CARCINOMA"]
+54
View File
@@ -0,0 +1,54 @@
"""What this module covers: the `cancer_pim` scenario, the surveillance PIM with carcinoma as the outcome, through its
dataflow and its registered model.
Fixtures: `cohort_frame`, members of `test_cin2_pim`'s design whose CIN2+ biopsies are carcinomas for a part of them.
"""
import numpy as np
import pandas as pd
import pytest
from models.cacu.cin2_pim import model
from models.dags import training
from tests.cacu.test_cin2_pim import cohort_frame as cin2_cohort_frame # noqa: F401
SCENARIO = training.Scenario.load("cacu", "cancer_pim")
SURVEILLANCE = training.Scenario.load("cacu", "cin2_pim")
@pytest.fixture
def cohort_frame(cin2_cohort_frame): # noqa: F811
"""`test_cin2_pim`'s members with every third LIEAG biopsy reported as carcinoma."""
frame = cin2_cohort_frame.copy()
lieag = frame.index[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "LIEAG")]
frame.loc[lieag[::3], "valor_codigo"] = "CARCINOMA"
return frame
def test_the_scenario_is_the_surveillance_model_with_carcinoma_as_the_outcome():
"""Pins down: same dataflow, cohort, index and prediction index as the CIN2+ surveillance model, with carcinoma as
the only event, so the patient's two risks speak of the same visit. Fails if the scenarios drift apart."""
assert SCENARIO.config["event_grades"] == ["CARCINOMA"] == SCENARIO.config["index"]["event_grades"]
assert SCENARIO.outcome == "cancer" and SCENARIO.cohort == SURVEILLANCE.cohort
assert [m.__name__ for m in SCENARIO.modules] == [m.__name__ for m in SURVEILLANCE.modules]
same = {k: v for k, v in SCENARIO.config.items() if k not in ("event_grades", "index")}
assert same == {k: v for k, v in SURVEILLANCE.config.items() if k not in ("event_grades", "index")}
assert SCENARIO.estimand["outcome"].startswith("Cáncer")
def test_the_dataflow_counts_only_carcinomas_as_events(cohort_frame):
"""Pins down: a LIEAG biopsy is not a case for this scenario, and the registered model gives a cancer risk no
higher than the CIN2+ model's at the same visit. Fails if `event_grades` stops reaching the coding."""
run = training.dataflow(*SCENARIO.modules, config=SCENARIO.config).execute(
["interval_coded_members", "fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})
coded = run["interval_coded_members"]
carcinomas = set(cohort_frame.loc[cohort_frame["valor_codigo"] == "CARCINOMA", "pac_id"])
cases = set(coded.loc[(coded["c"] == 1) | np.isfinite(coded["r"]), "pac_id"])
assert cases == carcinomas
cin2 = training.dataflow(*SURVEILLANCE.modules, config=SURVEILLANCE.config).execute(
["fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["fitted_model"]
h = len(SCENARIO.config["horizons_years"])
cancer, cin2plus = (m.predict_proba(cohort_frame)[:, 1:1 + h] for m in (run["fitted_model"], cin2))
scored = ~np.isnan(cancer) & ~np.isnan(cin2plus)
assert scored.any() and (cancer[scored] <= cin2plus[scored] + 1e-6).all()
+189 -6
View File
@@ -7,6 +7,7 @@ prevalent or a later CIN2+ biopsy, the normal ones with a later negative cotest)
`predict_without_repository` (conftest). `predict_without_repository` (conftest).
""" """
import json
from datetime import date, datetime, timedelta, timezone from datetime import date, datetime, timedelta, timezone
import mlflow.pyfunc import mlflow.pyfunc
@@ -161,7 +162,8 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort():
assert required == {"source_cohort", "cohort_lineage", "cytology", "event_grades", "history", "horizons_years", "incidence", assert required == {"source_cohort", "cohort_lineage", "cytology", "event_grades", "history", "horizons_years", "incidence",
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata", "incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
"train_fraction"} "train_fraction"}
assert optional == {"index"} # from the config; a scenario without one keeps its cohort's index # `index` from the config (a scenario without one keeps its cohort's index); the report's settings have defaults.
assert optional == {"index", "prediction_index", "report_panels", "risk_interval_level", "turnbull_bootstrap"}
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame): def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
@@ -179,9 +181,10 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path, def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file, mlflow_tracking, tmp_path,
predict_without_repository): predict_without_repository):
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per member """Pins down: through the generic driver the scenario registers a version whose estimate has one row per
and horizon, a risk that doesn't fall with the horizon, the same outside this repository, and storable metadata. precolposcopy member (no biopsy) and horizon, dated at her latest complete cytology, a risk that doesn't fall
Fails if the model or the estimate go back to one horizon, or the registered model needs this repository.""" with the horizon, the same outside this repository, and storable metadata. Fails if the model or the estimate go
back to one horizon, a biopsied member is scored, or the registered model needs this repository."""
version = training.train(SCENARIO, CohortFile(cohort_file)) version = training.train(SCENARIO, CohortFile(cohort_file))
registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version) registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version)
output = tmp_path / "estimate.parquet" output = tmp_path / "estimate.parquet"
@@ -189,7 +192,12 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
estimate(SCENARIO, CohortFile(cohort_file), output) estimate(SCENARIO, CohortFile(cohort_file), output)
risks = pd.read_parquet(output) risks = pd.read_parquet(output)
assert len(risks) == 300 * len(CONFIG["horizons_years"]) frame = pd.read_parquet(cohort_file)
biopsied = set(frame.loc[frame["tipo"] == "biopsia", "pac_id"])
assert set(risks["pac_id"]) == set(frame["pac_id"]) - biopsied
assert len(risks) == (300 - len(biopsied)) * len(CONFIG["horizons_years"])
scored = risks.dropna(subset=["ic_bajo"])
assert len(scored) and ((scored["ic_bajo"] <= scored["probabilidad"]) & (scored["probabilidad"] <= scored["ic_alto"])).all()
by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad") by_member = risks.pivot(index="pac_id", columns="horizonte_anios", values="probabilidad")
assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all() assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all()
assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2" assert pq.read_metadata(output).metadata[b"desenlace"] == b"cin2"
@@ -197,10 +205,76 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
uri = registry.resolve("cacu", "cin2_pim", version).model_uri uri = registry.resolve("cacu", "cin2_pim", version).model_uri
outside = predict_without_repository(uri, pd.read_parquet(cohort_file)) outside = predict_without_repository(uri, pd.read_parquet(cohort_file))
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file)) inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
assert outside.shape == (300, len(CONFIG["horizons_years"])) assert outside.shape == (300, 1 + 3 * len(CONFIG["horizons_years"]))
np.testing.assert_allclose(outside.to_numpy(), inside) np.testing.assert_allclose(outside.to_numpy(), inside)
def test_the_prediction_index_is_the_latest_complete_cytology_before_any_colposcopy():
"""Pins down the surveillance model's prediction index: the latest cytology with both results; one missing its
HPV gives way to the one before; a patient with a colposcopy or a biopsy gets none (the post-colposcopy scenario
scores her). Fails if the index goes back to the cohort's first cytology or a referred patient is scored."""
def sample(pac_id, day, bethesda, vph):
key = f"S{pac_id}-{day}"
rows = [_row(pac_id, INDEX, day, "citologia", sample=key), _row(pac_id, INDEX, day + 7, "bethesda", bethesda, key)]
return rows + ([_row(pac_id, INDEX, day + 7, "vph", vph, key)] if vph else [])
rows = [*sample(1, 0, "ASC-US", "NEGATIVO"), *sample(1, 700, "LIEBG", "POSITIVO"),
*sample(2, 0, "NORMAL", "NEGATIVO"), *sample(2, 900, "LIEBG", None),
*sample(3, 0, "LIEBG", "POSITIVO"), _row(3, INDEX, 40, "colposcopia"), *sample(3, 400, "NORMAL", "NEGATIVO")]
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
found = model.latest_index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
assert found["pac_id"].tolist() == [1, 2, 3]
assert found[model.INDEX_COLUMN].dt.date.tolist()[:2] == [INDEX + timedelta(days=700), INDEX]
assert found["cytology"].tolist()[:2] == ["LSIL", "NILM"] and found["hpv_positive"].tolist()[:2] == [1.0, 0.0]
assert pd.isna(found[model.INDEX_COLUMN].iloc[2]) and pd.isna(found["cytology"].iloc[2])
def test_the_registered_model_dates_each_risk_at_its_prediction_index(cohort_frame):
"""Pins down: with `prediction_index` the registered model gives the index date first (days since 1970) and the
risk of that visit's results, and no risk to a member without one. Fails if the date column is dropped, the
risk is computed from the cohort's index, or a member without an index gets a risk."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["fitted_model", "fitted_mixture"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})
output = found["fitted_model"].predict_proba(cohort_frame)
features = model.latest_index_results(cohort_frame, CONFIG["index_sample_days"], CONFIG["cytology"])
h = len(CONFIG["horizons_years"])
dated = ~np.isnan(output[:, 0])
assert dated.sum() == features[model.INDEX_COLUMN].notna().sum() and np.isnan(output[~dated, 1:]).all()
np.testing.assert_allclose(output[dated, 0], (features.loc[dated, model.INDEX_COLUMN] - model.EPOCH).dt.days)
expected = found["fitted_mixture"].predict_proba(features.loc[dated, model._features(CONFIG["history"])])
np.testing.assert_allclose(output[dated, 1:1 + h], expected)
def test_the_interval_brackets_the_same_risk(cohort_frame):
"""Pins down: with `interval_level` the mixture gives the risk unchanged and, after it, the interval's lower and
upper ends around it, NaN only where the risk is. Fails if the delta method moves the point, the blocks' order
changes, or an end crosses the risk."""
found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["fitted_mixture", "test_set", "fitted_model"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})
X = found["test_set"][model._features(CONFIG["history"])]
h = len(CONFIG["horizons_years"])
point = found["fitted_mixture"].predict_proba(X)
banded = found["fitted_model"].named_steps["mixture"].predict_proba(X)
assert found["fitted_mixture"].interval_level is None and banded.shape == (len(X), 3 * h)
np.testing.assert_allclose(banded[:, :h], point)
low, high, known = banded[:, h:2 * h], banded[:, 2 * h:], ~np.isnan(point)
assert (np.isnan(low) == ~known).all() and (low[known] <= point[known]).all() and (point[known] <= high[known]).all()
assert (high[known] - low[known]).max() > 0
def test_the_scenario_says_what_its_number_is():
"""Pins down: `[estimand]` reaches the scenario with what the screens show next to each risk. Fails if the key is
renamed or `Scenario.from_toml` stops reading it."""
assert SCENARIO.estimand["quantity"] == "Probabilidad" and SCENARIO.estimand["horizons_unit"] == "años"
assert "KPNC" in SCENARIO.estimand["covariates"]
assert {"description", "outcome", "index_date"} <= set(SCENARIO.estimand) and "interval" not in SCENARIO.estimand
def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame): def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame):
"""Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN """Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN
(not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up.""" (not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up."""
@@ -278,3 +352,112 @@ def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame):
assert {f"n_known_{h:g}y" for h in POST_COLPOSCOPY.config["horizons_years"]} <= set(found) assert {f"n_known_{h:g}y" for h in POST_COLPOSCOPY.config["horizons_years"]} <= set(found)
assert training.Scenario.load("cacu", "cin2_pim_post_treatment").cohort == "cacu/cohorte_post_tratamiento" assert training.Scenario.load("cacu", "cin2_pim_post_treatment").cohort == "cacu/cohorte_post_tratamiento"
def test_the_subgroup_report_sets_each_combinations_mixture_against_turnbull(cohort_frame):
"""Pins down the report of every PIM scenario: one record per combination of the features present, its members
adding up to the coded members; Turnbull's cumulative risk never falls and stays in [0, 1] inside its band; the
model's risk sits inside its delta-method band; E/O, where Turnbull observed a case, equals E over O inside its
interval; the record names its methods and the page is Plotly's. Fails if a combination goes missing, Turnbull
stops respecting the intervals' ordering, a band is inverted, E/O loses its interval, or the methods go
unrecorded."""
config = {**CONFIG}
result = training.dataflow(*SCENARIO.modules, config=config).execute(
["population", "reports", "interval_coded_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {},
"turnbull_bootstrap": 40})
record = result["population"]["subgrupos"]
combos = record["combinations"]
assert sum(c["n"] for c in combos) == len(result["interval_coded_members"])
assert set(record["metodos"]) == {"empirica", "modelo", "E/O"}
for c in combos:
emp = c["empirical"]
assert np.all(np.diff(emp["CR"]) >= -1e-12) and 0 <= emp["CR"][0] and emp["CR"][-1] <= 1 + 1e-12
assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(emp["low"], emp["CR"], emp["high"]))
if c["model"] is not None:
m = c["model"]
assert all(lo - 1e-9 <= v <= hi + 1e-9 for lo, v, hi in zip(m["low"], m["CR"], m["high"]))
for e in c["e_o"]:
if e["E_O"] is not None:
assert e["low"] <= e["E_O"] <= e["high"] and e["E_O"] == pytest.approx(e["E"] / e["O"])
assert any(e["E_O"] is not None for c in combos for e in c["e_o"])
json.dumps(record)
page = result["reports"]["subgrupos"]
assert page.startswith("<!doctype html>") and "Turnbull" in page and "método delta" in page
def test_turnbull_puts_a_prevalent_case_at_zero_and_an_interval_case_inside_its_interval():
"""Pins down Turnbull's coding: a prevalent member is mass at 0, a member found free and then a case is mass inside
`(l, r]`, a member free to the end carries mass beyond every finite point. Fails if the prevalence leaks past 0 or
a case is placed outside its interval."""
from models.cacu.cin2_pim.report import _at, _turnbull
c = np.array([1, 0, 0, 0])
l = np.array([0.0, 1.0, 2.0, 3.0])
r = np.array([0.0, 2.0, np.inf, np.inf])
support, cumulative = _turnbull(c, l, r)
assert _at(support, cumulative, [0.0])[0] == pytest.approx(0.25)
assert _at(support, cumulative, [2.0])[0] == pytest.approx(0.5)
assert _at(support, cumulative, [1.5])[0] == pytest.approx(0.25)
def _run_notebook(path, cohort_file, domain, scenario, monkeypatch, **parameters):
"""Runs a notebook's code cells in this process, as the platform's runner would on a build's file (`COHORT_FILE`,
`MODELS_DOMAIN`, `MODELS_SCENARIO`), with `parameters` replacing its parameters cell; returns its namespace."""
import nbformat
monkeypatch.setenv("COHORT_FILE", str(cohort_file))
monkeypatch.setenv("MODELS_DOMAIN", domain)
monkeypatch.setenv("MODELS_SCENARIO", scenario)
namespace = {}
for cell in nbformat.read(path, as_version=4).cells:
if cell.cell_type != "code":
continue
exec(cell.source, namespace)
if "parameters" in cell.metadata.get("tags", []):
namespace.update(parameters)
return namespace
def test_the_subgroup_figure_draws_risks_in_percent():
"""Pins down: the report's curves are in percent, like the patient's risk and the table, with the axis saying so.
Fails if the figure goes back to proportions, which read as a risk a hundred times smaller."""
from models.cacu.cin2_pim import report
curve = {"years": [0.0, 5.0], "CR": [0.1, 0.2], "low": [0.05, 0.15], "high": [0.15, 0.25]}
record = {"combination": {"cytology": "LSIL", "hpv_positive": "positivo"}, "n": 10, "prevalent": 1,
"incident": 1, "empirical": curve, "model": curve, "e_o": []}
figure = report._figure([record], [0.0, 5.0])
assert [list(t.y) for t in figure.data if t.name in ("Turnbull", "Mezcla prevalencia-incidencia")] == [[10.0, 20.0]] * 2
assert figure.layout.yaxis.ticksuffix == " %" and "%" in figure.layout.yaxis.title.text
def test_each_subgroup_panel_has_its_own_scale():
"""Pins down: panels don't share the y axis, so each combination's curves fill their panel. Fails if the
subplots go back to one shared scale, where a 0.5 % curve is a flat line next to a 50 % one."""
from models.cacu.cin2_pim import report
def record(level, risk):
curve = {"years": [0.0, 5.0], "CR": [risk, risk], "low": [risk, risk], "high": [risk, risk]}
return {"combination": {"cytology": level, "hpv_positive": "positivo"}, "n": 10, "prevalent": 1,
"incident": 1, "empirical": curve, "model": curve, "e_o": []}
figure = report._figure([record("NILM", 0.005), record("HSIL+", 0.5)], [0.0, 5.0])
assert figure.layout.yaxis2.matches is None and figure.layout.yaxis2.anchor == "x2"
def test_the_subgroup_notebook_runs_on_a_builds_file(cohort_file, monkeypatch):
"""Pins down the PIM report's notebook (`models/cacu/cin2_pim/notebooks/reporte_subgrupos.ipynb`): its cells run on a
build's file with the platform's environment, compute the same combinations the dataflow does and draw them. Fails
if the notebook drifts from the report's functions or the scenario it is run for."""
from pathlib import Path
path = Path(model.__file__).parent / "notebooks" / "reporte_subgrupos.ipynb"
found = _run_notebook(path, cohort_file, "cacu", "cin2_pim", monkeypatch, turnbull_bootstrap=20)
assert found["risks"] and sum(r["n"] for r in found["risks"]) > 0 and found["turnbull_bootstrap"] == 20
@@ -0,0 +1,49 @@
"""What this module covers: `models.cacu.cin2_pim.likelihood` against KPNC's published risks (Cheung et al. 2020,
doi:10.1097/LGT.0000000000000528; tables of Egemen et al. 2020, doi:10.1097/LGT.0000000000000529).
`data/kpnc_reference.csv` holds the published cumulative risks at 0–5 years of the KPNC curves that one shared
I-spline baseline (order 4, 3 knots) with a proportional factor per curve reproduces to the rounding of the tables
(bayes-pim chapters 6 and 25): table 1 (screening, one baseline per current HPV), 17 (post-colposcopy), 18
(post-colposcopy, 2nd visit, the exact groups only), 24 and 25 (post-treatment). Each row is one curve with its group's
knots and γ and its own η; its CR(0) is the published one. Tables 4, 19 and 26, which no grouping reproduces, are left
out. Aggregates of public tables only.
"""
import json
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from scipy.special import logit
from models.cacu.cin2_pim import likelihood as L
REFERENCE = pd.read_csv(Path(__file__).parent / "data" / "kpnc_reference.csv", dtype={"table": str})
YEARS = range(6)
@pytest.mark.parametrize("key, group", list(REFERENCE.groupby(["table", "outcome", "group"])),
ids=lambda v: " ".join(v) if isinstance(v, tuple) else "")
def test_the_mixture_gives_kpncs_published_risks(key, group):
"""Pins down: with KPNC's knots, γ and η, `cumulative_risk` (logistic prevalence, PIMixture's I-splines,
proportional hazards) gives every published risk at 0–5 years to 1e-12. Fails if the I-spline basis, its
parameterization (exp γ), the proportional factor or the mixture CR = π + (1 − π)(1 − S) drift from PIMixture's."""
knots, gamma = json.loads(group["knots"].iloc[0]), np.array(json.loads(group["gamma"].iloc[0]))
n = len(group)
with np.errstate(divide="ignore"):
theta = logit(group["cr0"].to_numpy())
fitted = {"theta": theta, "beta": group["eta"].to_numpy(), "baseline": L.ISpline(tuple(knots), order=4),
"baseline_params": gamma}
found = L.cumulative_risk(fitted, np.eye(n), np.eye(n), YEARS)
published = group[[f"cr{t}" for t in YEARS]].to_numpy()
np.testing.assert_allclose(found, published, rtol=0, atol=1e-12)
def test_the_reference_covers_the_scenarios_tables():
"""Pins down: the fixture keeps the screening table and the post-colposcopy and post-treatment ones, both outcomes
each. Fails if a rebuild of the fixture drops a table the scenarios are checked against."""
assert {(t, o) for t, o in REFERENCE[["table", "outcome"]].itertuples(index=False)} == {
(t, o) for t in ("1", "17", "18", "24", "25") for o in ("CIN2+", "CIN3+")}
+166
View File
@@ -0,0 +1,166 @@
"""What this module covers: CaMa's recurrence analysis (`models.cama.recurrence`) over the total cohort's timeline: each
cohort's patients read by the dictionary (`cohort.recode`), the whole dataflow (the figures of the scenarios, the tables, the
routines the registry asks for and the saved model), training a version from a build, and the import files that put the
cohorts in the platform (`cohort_import`).
Fixtures: `cohort_frame`, a long frame of 600 patients loaded from METABRIC and 600 from SCAN-B (their `fuente`), each with
her birth, an invasive biopsy in 2018-2019 with grade, estrogen receptor, size and nodes, a surgery, and her recurrence or
last contact (recurrence faster with grade 3, a large tumor and no estrogen receptor), plus 20 hospital patients with no
`fuente` that neither cohort takes; `cohort_file`, that frame as a build's Parquet file with its lineage; `mlflow_tracking`
(conftest), a SQLite-backed MLflow.
"""
import dataclasses
import json
from datetime import date, datetime, timedelta, timezone
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cama.recurrence import cohort, cohort_import
from models.cama.recurrence.model import RecurrenceModel
from models.dags.training import Scenario, dataflow, train
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.storage import CohortFile
from models.steps import indexing
N = 600
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": "2026-12-31"}
LINEAGE = {"url": "cama/cohorte_total", "datos_as_of": "2026-11-21", "parametros": json.dumps(WINDOW)}
SMALL = {"horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2, "n_boot_calc": 3, "min_events": 5,
"ks_seconds": 2, "max_parents": 3}
def _row(pac_id, when, first, tipo, valor=None, numero=None, source_id=None):
return {"pac_id": pac_id, "fecha_indice": first, "fecha": when, "conocida_en": datetime(2026, 11, 21, tzinfo=timezone.utc),
"clase": "medicion", "tipo": tipo, "codigo": tipo, "valor_codigo": valor, "valor_numerico": numero,
"fuente_tabla": "silver", "fuente_id": source_id or f"{pac_id}-{tipo}"}
def _patient(rng, pac_id, source):
index = date(2018, 1, 1) + timedelta(days=int(rng.integers(0, 540)))
grade, er = str(rng.choice(["G1", "G2", "G3"])), bool(rng.random() < 0.7)
size, nodes = float(rng.gamma(4, 7)), int(rng.integers(0, 9))
rate = 0.012 * np.exp(0.8 * (int(grade[1]) - 2) + 0.5 * (size > 30) - 0.5 * er)
months, followed = rng.exponential(1 / rate), rng.uniform(30, 90)
end = index + timedelta(days=int(min(months, followed) * 30.4375))
born = index - timedelta(days=int(rng.normal(60, 12) * 365.25))
rows = [_row(pac_id, born, born, "nacimiento")]
if source:
rows.append(_row(pac_id, born, born, "fuente", source))
rows += [_row(pac_id, index, born, "biopsia", "CARCINOMA_INVASOR"), _row(pac_id, index, born, "grado_nottingham", grade),
_row(pac_id, index, born, "receptor_estrogeno", "POSITIVO" if er else "NEGATIVO"),
_row(pac_id, index, born, "tamano_tumor_mm", numero=size), _row(pac_id, index, born, "ganglios_positivos", numero=float(nodes)),
_row(pac_id, index, born, "cirugia", str(rng.choice(["MASTECTOMIA_TOTAL", "SEGMENTECTOMIA"])))]
rows.append(_row(pac_id, end, born, "recurrencia" if months <= followed else "ultimo_contacto"))
return rows
@pytest.fixture(scope="module")
def cohort_frame():
"""METABRIC's patients are 1-600, SCAN-B's 1001-1600, and 2001-2020 are the hospital's own."""
rng = np.random.default_rng(5)
rows = []
for offset, source in ((0, "METABRIC"), (1000, "SCANB")):
for i in range(1, N + 1):
rows += _patient(rng, offset + i, source)
for i in range(2001, 2021):
rows += _patient(rng, i, None)
return pd.DataFrame(rows, columns=SCHEMA.names)
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 4's file, with the lineage a dbt build gives."""
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
path = tmp_path / "4.parquet"
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "4"}), path)
return path
def _small(scenario: Scenario) -> Scenario:
return dataclasses.replace(scenario, config={**scenario.config, "recurrence": {**scenario.config["recurrence"], **SMALL}})
def test_each_cohort_takes_only_the_patients_loaded_from_it(cohort_frame):
"""Pins down: METABRIC's frame has its 600 patients and SCAN-B's its own, with the follow-up in months from the biopsy,
the recurrence as the event and the dictionary's categories (the unknown one more), once the scenario's index (the first
invasive biopsy) is set; the hospital's patients are in neither. Fails if `recode` stops filtering by `fuente`, reads another index, or a rule maps a code to another category."""
model = cohort.load()
indexed = indexing.cohort(cohort_frame, LINEAGE, Scenario.load("cama", "recurrence").config["index"])
metabric = cohort.recode(indexed, model, "metabric")
scanb = cohort.recode(indexed, model, "scanb")
assert len(metabric) == N and set(metabric["paciente"]) == set(range(1, N + 1))
assert len(scanb) == N and set(scanb["paciente"]) == set(range(1001, 1001 + N))
assert (metabric["tiempo_meses"] > 0).all() and 0 < metabric["evento"].sum() < N
assert set(metabric["Grado_histologico"]) == {"1", "2", "3"}
assert set(metabric["Receptor_estrogeno"]) == {"Positive", "Negative"}
assert set(metabric["Cirugia"]) == {"MASTECTOMY", "BREAST CONSERVING"} and set(scanb["Cirugia"]) == {"Mastectomy", "Lumpectomy"}
assert set(metabric["Subtipo_PAM50"]) == {"Desconocido"}
def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(cohort_frame):
"""Pins down: the dataflow over the total cohort's timeline gives a figure for each scenario with enough recurrences (the
Kaplan-Meier with its band, both Weibull and the combined recurrence-free probability at each horizon with its interval),
the tables behind them, the five routines the registry asks for and a model whose probabilities are in [0, 1]. Fails if a
stage stops feeding the next, the figures lose a curve or a routine is missing."""
scenario = _small(Scenario.load("cama", "recurrence"))
dr = dataflow(*scenario.modules, config=scenario.config)
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"],
inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
figures = r["population"]["recurrencia"]["escenarios"]
assert figures and {f["cohorte"] for f in figures} <= {"metabric", "scanb"}
one = figures[0]
assert set(one) >= {"escenario", "condiciones", "n", "recaidas", "km", "weibull", "weibull_fractional", "points"}
comb = one["points"]["COMB"]
assert len(comb["S"]) == 2 and all(lo <= s <= hi + 1e-9 for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
assert {"auc", "factores_riesgo", "calculadora", "escenarios_resumen"} <= set(r["population"]["recurrencia_desarrollo"]["tablas"])
assert set(r["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
assert r["metrics"] and all(isinstance(v, float) for v in r["metrics"].values())
assert len(r["prepared"]["metabric"].cohort) == len(r["prepared"]["scanb"].cohort) == N
model: RecurrenceModel = r["fitted_model"]
p = model.predict_proba(r["prepared"]["metabric"].cohort.head(50))
assert p.shape == (50, 2) and ((p >= 0) & (p <= 1)).all()
def test_a_version_trains_from_a_build_registers_and_publishes_its_figures(cohort_file, mlflow_tracking):
"""Pins down: training the scenario on a build of the total cohort registers a PROD version that carries the figures the
dashboard draws (`analisis/recurrencia.json`) and the tables. Fails if the version cannot be saved or loses its figures."""
from models.io.registry import registry
version = train(_small(Scenario.load("cama", "recurrence")), CohortFile(cohort_file), "PROD")
_, figures = registry.artifact("cama", "recurrence", version, "analisis/recurrencia.json")
_, tables = registry.artifact("cama", "recurrence", version, "analisis/recurrencia_desarrollo.json")
assert json.loads(figures)["escenarios"] and "auc" in json.loads(tables)["tablas"]
def test_the_import_files_place_the_diagnoses_in_a_window_and_end_the_follow_up_at_the_censor():
"""Pins down: with `diagnosis_from` every diagnosis falls in the given span (the same day for the same patient), and with
`censor` no date is after it: a recurrence after it becomes a last contact on that day. Fails if the dictionary's fixed year
is kept, the spread depends on the row order, or a follow-up runs past the censor."""
raw = pd.DataFrame({"Patient ID": ["A", "B", "C"], "Relapse Free Status": ["1:Recurred", "0:Not Recurred", "1:Recurred"],
"Relapse Free Status (Months)": ["10", "200", "120"], "Age at Diagnosis": ["50", "61", "70"]})
model = cohort_import.load()
named = [s["metabric"]["column"] for s in model["variables"].values() if isinstance(s, dict) and "column" in s.get("metabric", {})]
raw = raw.reindex(columns=[*raw.columns, *named], fill_value="")
tables = cohort_import.convert(raw, "metabric", model, diagnosis_from="2018-01-01", spread_days=540,
censor="2026-11-21")
again = cohort_import.convert(raw.iloc[::-1], "metabric", model, diagnosis_from="2018-01-01",
spread_days=540, censor="2026-11-21")
diagnosis = pd.to_datetime(tables["BiopsiaMama"].set_index("pac_id_hospital")["bx_fecha_reporte"])
assert diagnosis.between("2018-01-01", "2019-06-24").all()
assert diagnosis.equals(pd.to_datetime(again["BiopsiaMama"].set_index("pac_id_hospital")["bx_fecha_reporte"]).reindex(diagnosis.index))
follow = tables["SeguimientoMama"].set_index("pac_id_hospital")
assert (pd.to_datetime(follow["seg_fecha"]) <= "2026-11-21").all()
assert follow.loc["METABRIC-A", "seg_tipo"] == "recurrencia"
assert follow.loc["METABRIC-C", "seg_tipo"] == "ultimo_contacto" and follow.loc["METABRIC-C", "seg_fecha"] == "2026-11-21"
+103
View File
@@ -0,0 +1,103 @@
"""The SEER survival pipeline's stages: depuration (01) and bootstrapping (03), on small synthetic frames."""
import dataclasses
import json
import numpy as np
import pandas as pd
import pytest
from models.cama.seer_survival import depuration, depuration_stats as stats, run
from models.cama.seer_survival.settings import BootstrapSettings, Settings, load
@pytest.fixture
def settings() -> Settings:
s = load()
return dataclasses.replace(s, depuration=dataclasses.replace(s.depuration, null_perm=5))
@pytest.fixture
def recoded() -> pd.DataFrame:
"""`B_cat` repeats `A_cat` under other labels; `Tumor_group` repeats `T_cat` and is the preferred of the two; `C_cat`
and `D_cat` are independent; `Outcome_cat` is never touched."""
rng = np.random.default_rng(1)
n = 600
a = rng.choice(list("abcd"), n)
t = rng.choice(["t1", "t2", "t3"], n)
return pd.DataFrame({
"A_cat": a, "B_cat": pd.Series(a).map({"a": "w", "b": "x", "c": "y", "d": "z"}).values, "raw_b": a,
"T_cat": t, "Tumor_group": pd.Series(t).map({"t1": "g1", "t2": "g2", "t3": "g3"}).values,
"C_cat": rng.choice(["u", "v", "w"], n), "D_cat": rng.choice(["p", "q"], n),
"Outcome_cat": rng.choice(["0", "1"], n)})
def test_the_duplicate_is_dropped_with_its_raw_column_and_the_preferred_one_is_kept(tmp_path, settings, recoded):
recoded.to_csv(tmp_path / "recoded.csv", index=False)
(tmp_path / "map.json").write_text(json.dumps({"B_cat": "raw_b"}))
r = run.run_depuration(tmp_path / "recoded.csv", tmp_path / "map.json", tmp_path, settings, generated_at="t")
assert sorted(r["elimination"].dropped["variable"]) == ["B_cat", "T_cat"]
assert set(r["elimination"].dropped["paso"]) == {"A duplicada"}
out = pd.read_csv(tmp_path / run.DEPURATED, dtype=str)
assert list(out.columns) == ["A_cat", "Tumor_group", "C_cat", "D_cat", "Outcome_cat"]
kept = json.loads((tmp_path / run.DEPURATION_DIR / "variables_conservadas.json").read_text())
assert kept["crudas_eliminadas"] == ["raw_b"]
for name in ("calibracion_U_pares.csv", "calibracion_umbrales.json", "variables_eliminadas.csv"):
assert (tmp_path / run.DEPURATION_DIR / name).exists()
def test_the_analysis_leaves_out_excluded_and_constant_columns(settings, recoded):
recoded["K_cat"] = "same"
frame = depuration.analysis_frame(recoded, settings.depuration)
assert "Outcome_cat" not in frame and "K_cat" not in frame and "raw_b" not in frame
assert "Tumor_group" in frame
def test_a_protected_variable_is_never_dropped(settings, recoded):
s = dataclasses.replace(settings.depuration, protected=("B_cat",))
frame = depuration.analysis_frame(recoded, s)
t = stats.Thresholds(s.dup_u, s.u_redund, s.gvif_drop, s.cluster_method, 0.5, 0.5, False)
dropped = stats.eliminate(frame, list(frame.columns), t, s)
assert "B_cat" not in set(dropped["variable"]) and "A_cat" in set(dropped["variable"])
def test_theil_u_of_a_relabelled_copy_is_one_and_of_independent_variables_near_zero(recoded):
U = stats.theil_u_matrix(recoded, ["A_cat", "B_cat", "C_cat"])
assert U.loc["A_cat", "B_cat"] == pytest.approx(1.0) and U.loc["B_cat", "A_cat"] == pytest.approx(1.0)
assert U.loc["A_cat", "C_cat"] < 0.05
def test_auto_thresholds_take_the_calibrations_suggestions(settings, recoded):
s = dataclasses.replace(settings.depuration, thresholds_auto=True)
frame = depuration.analysis_frame(recoded, s)
c = stats.calibrate(frame, list(frame.columns), s, "t")
t = stats.thresholds_in_use(c, s)
assert t.auto and t.u_redund == c.u_suggestion["U"] and t.dup_u == c.dup_u_suggested
def test_calibration_needs_two_variables(settings):
frame = pd.DataFrame({"A_cat": ["a", "b"] * 50})
with pytest.raises(ValueError, match="al menos 2"):
stats.calibrate(frame, ["A_cat"], settings.depuration, "t")
def test_unknown_settings_are_refused(tmp_path):
bad = tmp_path / "model.toml"
bad.write_text("[depuration]\nnope = 1\n[bootstrap]\nn_bootstrap = 1\nrandom_state = 0\n")
with pytest.raises(ValueError, match="unknown settings"):
load(bad)
def test_the_bootstrap_indices_are_reproducible_and_within_the_rows(tmp_path):
pd.DataFrame({"x": range(50)}).to_csv(tmp_path / "balanced.csv", index=False)
s = dataclasses.replace(load(), bootstrap=BootstrapSettings(n_bootstrap=7, random_state=3))
first = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"]
again = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"]
assert first.shape == (7, 50) and first.min() >= 0 and first.max() < 50
assert np.array_equal(first, again) and np.array_equal(np.load(tmp_path / run.BOOTSTRAP_INDICES), first)
meta = json.loads((tmp_path / run.BOOTSTRAP_METADATA).read_text())
assert (meta["n_filas"], meta["n_bootstrap"], meta["random_state"]) == (50, 7, 3)
+301
View File
@@ -0,0 +1,301 @@
"""The numeric cores of the SEER survival pipeline's stages 02, 04, 05 and 06, and its runner, on small synthetic data."""
import os
import time
import numpy as np
import pandas as pd
import pytest
from models.cama.seer_survival import (balancing_stats, categorization_stats as cs, fractional_weibull as fw, hbn,
lr_selection, pipeline, risk_factor_stats as rf, survival_models as sm)
from models.cama.seer_survival import risk_factors, scenarios
from models.cama.seer_survival.settings import load
# ---------------------------------------------------------------- settings
def test_every_stage_has_its_settings():
s = load()
assert s.balancing.mca_variant in ("con_edad", "sin_edad")
assert "Biología + tratamiento" in {s.categorization.age_final}
assert set(s.categorization.proposals) >= {"P1_actual", "P6_clinico_fijo", "P7_cuantiles"}
assert s.modeling.canonical_map["Age_group"] == "Edad"
assert len(scenarios.SCENARIOS) == 13 and s.survival.combine_active and s.survival.months_max == 24
assert s.risk_factors.treatment == ("Tratamiento_quirurgico", "Radioterapia", "Quimioterapia")
# ---------------------------------------------------------------- 02a balancing
def test_age_midpoints():
mid = balancing_stats.age_midpoint
assert mid("40-44 years") == 42 and mid("85+ years") == 90 and mid("05") == 5 and np.isnan(mid("unknown"))
def test_the_outcome_treats_censoring_and_incomplete_years_as_unknown():
s = load().balancing
labels = {"m": "Survival months", "v": "Vital status", "y": "Year of diagnosis"}
df = pd.DataFrame({"m": ["30", "5", "5", "30", "40"], "v": ["Alive", "Dead", "Alive", "Dead", "Alive"],
"y": ["2000", "2000", "2000", "2001", "2001"]})
# alive with 5 months is censored: unknown; year 2000 has 1 of 3 censored (> 10 %), so the whole year leaves
assert np.isnan(balancing_stats.outcome_values(df, labels, s)).tolist() == [True, True, True, False, False]
assert balancing_stats.outcome_values(df, labels, s)[3:].tolist() == [1.0, 1.0]
keep = balancing_stats.outcome_values(df, labels, s.__class__(**{**s.__dict__, "exclude_censored_years": False}))
assert keep[0] == 1.0 and keep[1] == 0.0 and np.isnan(keep[2]) # only the censored patient stays unknown
def test_the_undersampling_keeps_every_death_and_the_survivors_nearest_to_them():
F = np.array([[0.0], [0.1], [5.0], [9.0], [0.2], [8.0]])
outcome = np.array([0, 1, 1, 1, 0, 1]) # 0 = death (minority): rows 0 and 4
keep, dist = balancing_stats.select_informed_undersample(F, outcome, 0, 1, target_ratio=1.0)
assert keep.tolist() == [True, True, True, False, True, False] # 2 deaths + the 2 nearest survivors
assert dist[1] == pytest.approx(0.1) and dist[3] == pytest.approx(8.8)
# ---------------------------------------------------------------- 02b categorization
def _axis_frame(rng_seed=0):
"""Ten levels; the category mix flips between level 4 and 5 (the only real boundary)."""
rng = np.random.default_rng(rng_seed)
levels = [f"{i:02d}" for i in range(10)]
rows = []
for i, level in enumerate(levels):
for _ in range(300):
p = 0.9 if i < 5 else 0.1
rows.append({"lvl": level, "X_cat": "a" if rng.random() < p else "b",
"Y_cat": "u" if rng.random() < (0.85 if i < 5 else 0.15) else "v"})
return pd.DataFrame(rows), levels
def test_segmentation_finds_the_one_boundary_where_the_composition_flips():
df, levels = _axis_frame()
axis = cs.Axis.of(df, "lvl", levels, list(range(10)), "corte_x")
s = load().categorization
result = cs.segment(df, axis, ["X", "Y"], {}, s, min_n=100)
assert result.bounds == [5] and result.segments == [(0, 5), (5, 10)]
assert result.effect_sizes["cambio_medio"].iloc[0] > 0.7
assert cs.level_to_group(result.segments, levels)["00"] == "00 a 04"
def test_small_segments_are_merged_into_the_most_similar_neighbour():
counts = {"c": pd.DataFrame([[50, 0], [50, 0], [0, 50], [0, 50], [45, 5]], columns=["a", "b"])}
segs, log = cs.fix_small_segments(counts, np.array([50, 50, 50, 50, 50]), [2, 4], 5, min_n=80)
assert all(sum(50 for _ in range(a, b)) >= 80 for a, b in segs) and log
def test_configurations_are_every_combination_of_blocks():
configs = cs.configurations({"outcome": ["Outcome"], "biología": ["A", "B"], "tratamiento": ["T"]})
assert set(configs) == {"Solo outcome", "Solo biología", "Solo tratamiento", "Outcome + biología",
"Outcome + tratamiento", "Biología + tratamiento", "Outcome + biología + tratamiento"}
assert configs["Biología + tratamiento"] == ["A", "B", "T"]
def test_tumor_sizes_and_levels():
assert cs.tumor_size_mm("023") == 23.0 and np.isnan(cs.tumor_size_mm("000")) and np.isnan(cs.tumor_size_mm("999"))
assert cs.tumor_bin_label(23.0, 5, 100) == "021-025 mm" and cs.tumor_bin_label(101.0, 5, 100) == ">100 mm"
levels, mids = cs.tumor_levels(5, 100)
assert levels[0] == "001-005 mm" and levels[-1] == ">100 mm" and len(levels) == len(mids) == 21 and mids[0] == 3.0
def test_quantile_and_clinical_cuts_partition_the_axis():
assert cs.quantile_bounds(np.array([10, 10, 10, 10, 10, 10, 10, 10]), 4) == [2, 4, 6]
segs = cs.segments_from_bounds([3, 3, 0, 99, 5], 8)
assert segs == [(0, 3), (3, 5), (5, 8)]
def test_sensitivity_and_specificity_at_a_cut():
idx = np.array([0, 0, 1, 1, 2, 2, 3, 3])
death = np.array([0, 0, 0, 1, 0, 1, 1, 1], bool)
r = cs.sens_spec_at_cut(idx, death, 2)
assert r["lado_alto_riesgo"] == "arriba del corte" and r["sensibilidad"] == 0.75 and r["especificidad"] == 0.75
def test_the_overlap_of_identical_distributions_is_one():
a = pd.Series(["x", "y", "x", "y"])
assert cs.overlap_coefficient(a, a, ["x", "y"]) == 1.0
assert cs.overlap_coefficient(pd.Series(["x"] * 4), pd.Series(["y"] * 4), ["x", "y"]) == 0.0
# ---------------------------------------------------------------- 04 modeling
def test_the_stepwise_keeps_the_signal_and_drops_the_noise():
rng = np.random.default_rng(3)
n = 1500
signal, noise = rng.normal(size=n), rng.normal(size=n)
y = pd.Series((rng.random(n) < 1 / (1 + np.exp(-2 * signal))).astype(int))
X = pd.DataFrame({"signal": signal, "noise": noise, "noise2": rng.normal(size=n)})
assert lr_selection.stepwise_selection(X, y) == ["signal"]
def test_the_prefilter_sorts_by_chi_square_and_caps_the_columns():
rng = np.random.default_rng(4)
y = pd.Series(rng.integers(0, 2, 800))
X = pd.DataFrame({"weak": ((y.values + (rng.random(800) < 0.4)) > 0).astype(float),
"strong": ((y.values + (rng.random(800) < 0.05)) > 0).astype(float),
"none": rng.integers(0, 2, 800).astype(float)})
assert lr_selection.prefiltered_columns(X, y, 0.10, 40) == ["strong", "weak"]
assert lr_selection.prefiltered_columns(X, y, 0.10, 1) == ["strong"]
def test_the_temporal_tiers_order_demography_tumor_treatment_outcome():
s = load().modeling
tiers = hbn.temporal_order(["Estadio", "Edad", "Radioterapia", "outcome", "Rara"], s)
assert tiers == [["Rara"], ["Edad"], ["Estadio"], ["Radioterapia"], ["outcome"]]
# ---------------------------------------------------------------- 05 survival
def test_the_classic_weibull_fit_recovers_its_parameters():
rng = np.random.default_rng(5)
t = 80.0 * rng.weibull(1.4, 6000)
months = np.minimum(np.floor(t).astype(int), 40)
event = t < 40
d, c = fw.tabla_eventos(months, event)
w = fw.ajustar_weibull(d, c)
assert w["k"] == pytest.approx(1.4, abs=0.15) and w["lam"] == pytest.approx(80.0, rel=0.12)
def test_the_fractional_weibull_is_a_valid_survival_function():
t = np.array([0.0, 1.0, 5.0, 12.0, 24.0])
S = fw.S_ks(t, k=1.0, alpha=1.0, beta=0.5, lam=60.0)
assert S[0] == 1.0 and np.all(np.diff(S) <= 1e-12) and np.all((S >= 0) & (S <= 1))
assert fw.kilbas_saigo([0.0], 1.0, 1.0, 0.0)[0] == 1.0
assert np.all(np.isnan(fw.S_ks(t, k=0.5, alpha=0.4, beta=1.0, lam=60.0))) # k + alpha <= 1: out of region
def test_kaplan_meier_with_no_censoring_is_the_survivor_fraction():
months = np.array([1, 1, 2, 3, 3, 3, 5, 5, 6, 6])
S, lo, hi = fw.km_curva(months, np.ones(10, bool), 6)
assert S[:7].tolist() == pytest.approx([1.0, 1.0, 0.8, 0.7, 0.4, 0.4, 0.2]) # S[m]: alive at the start of month m
assert np.all(lo <= S + 1e-12) and np.all(S <= hi + 1e-12)
def test_the_censoring_weights():
m, e = np.array([2, 5, 8, 12]), np.array([True, False, True, False])
known, y, w = sm.censoring_weights(m, e, 6, "excluir")
assert known.tolist() == [True, False, True, True] and y.tolist() == [0, 0, 1, 1] and w.tolist() == [1, 1, 1, 1]
assert sm.censoring_weights(m, e, 6, "ipcw")[2].min() >= 1.0
def test_the_stacking_weight_follows_the_better_model_and_shrinks_with_few_deaths():
rng = np.random.default_rng(6)
n = 2000
c = sm.Cohort(months=np.full(n, 20), event=np.zeros(n, bool), X_dum=np.zeros((n, 1)), X_int=np.zeros((n, 1), int),
levels=np.array([1]), borders=[0, 6], fixed_parents=None)
truth = rng.random(n) < 0.7 # survives the interval
c = sm.Cohort(np.where(truth, 20, 3), ~truth, c.X_dum, c.X_int, c.levels, c.borders, None)
good = np.where(truth, 0.9, 0.2)[:, None]
bad = np.full((n, 1), 0.7)
s = load().survival
t = sm.stacking_weights(c, s, np.ones(n, bool), good, bad)
assert t["w_LR"].iloc[0] > 0.9 and t["w_LR_sin_contraer"].iloc[0] >= t["w_LR"].iloc[0]
assert t["decision"].iloc[0] in ("solo LR", "mezcla")
def test_the_fixed_hbn_parents_are_found_by_keyword_and_age_is_added():
s = load().survival
cov = ["Estadio_cat", "Tipo_histologico_cat", "Tratamiento_quirurgico_cat", "Quimioterapia_cat", "Radioterapia_cat",
"Edad_cat", "Race"]
assert sm.fixed_parent_indices(cov, s) == [0, 1, 2, 3, 4, 5]
with pytest.raises(AssertionError, match="Estadio"):
sm.fixed_parent_indices(["Edad_cat"], s)
# ---------------------------------------------------------------- 06 risk factors
def test_benjamini_hochberg():
p = [0.01, 0.04, 0.03, 0.005]
assert rf.benjamini_hochberg(p).tolist() == pytest.approx([0.02, 0.04, 0.04, 0.02])
def test_the_odds_of_a_risky_category_are_above_one_and_its_survival_lower():
rng = np.random.default_rng(7)
n = 4000
stage = rng.choice(["I", "IV"], n, p=[0.7, 0.3])
death = (rng.random(n) < np.where(stage == "IV", 0.5, 0.1)).astype(int)
data = pd.DataFrame({"Estadio": stage, "Sexo": rng.choice(["f", "m"], n)})
t = rf.fit_odds(data, death, ["Estadio", "Sexo"])
row = t[t["termino"] == "Estadio_IV"].iloc[0]
assert row["OR_muerte"] > 5 and row["IC95_inf"] > 1 and rf.reference(data, "Estadio") == "I"
months = np.where(death == 1, 8, 24)
d = rf.survival_difference(data, months, death.astype(bool), "Estadio", "IV", "I", 18)
assert d["delta_S18"] < -0.2 and d["delta_IC95_sup"] < 0 and d["n_categoria"] == int((stage == "IV").sum())
# ---------------------------------------------------------------- the runner
def test_a_stage_is_current_only_when_its_outputs_are_newer_than_its_code_and_inputs(tmp_path):
stage = next(e for e in pipeline.STAGES if e.id == "03")
assert not pipeline.is_current(stage, tmp_path) # no outputs
for name in stage.requires + stage.produces:
(tmp_path / name).write_text("x")
future = time.time() + 3600
for name in stage.produces:
os.utime(tmp_path / name, (future, future))
assert pipeline.is_current(stage, tmp_path)
os.utime(tmp_path / stage.requires[0], (future + 10, future + 10)) # the input changed after the outputs
assert not pipeline.is_current(stage, tmp_path)
(tmp_path / stage.produces[0]).write_text("") # an empty output is no output
assert not pipeline.is_current(stage, tmp_path)
def test_the_runner_names_the_missing_inputs_and_logs_each_stage(tmp_path, monkeypatch):
with pytest.raises(FileNotFoundError, match="faltan entradas"):
pipeline.run_pipeline(tmp_path, only=["01"])
ran = []
stage = pipeline.Stage("99", lambda d, s: ran.append("ok"), (), ("out.csv",), ())
monkeypatch.setattr(pipeline, "STAGES", [stage, pipeline.Stage("98", lambda d, s: ran.append("again"), (), (), ())])
pipeline.run_pipeline(tmp_path, settings=object())
assert ran == ["ok", "again"]
(tmp_path / "out.csv").write_text("x")
log = pipeline.run_pipeline(tmp_path, settings=object())
assert [row[:2] for row in log] == [("99", "saltada"), ("98", "ok")] # 99's output is current; 98 has none to check
assert (tmp_path / pipeline.LOG).read_text().splitlines()[0] == "etapa,estado,segundos"
def test_treatment_associations_are_none_when_no_treatment_variable_varies():
"""Pins down: a cohort where every treatment column is a single category (as when the hospital reports none) gives
no associations, as the docstring says, and not a missing-columns error. Fails if the empty case is formatted."""
from models.cama.seer_survival import risk_factors
from models.cama.seer_survival.settings import load
rng = np.random.default_rng(8)
n = 300
data = pd.DataFrame({"Grado": rng.choice(["G1", "G3"], n), "Radioterapia": "Desconocido"})
follow = risk_factors.FollowUp(death=pd.Series(rng.integers(0, 2, n)), months=pd.Series(rng.uniform(1, 20, n)),
event=pd.Series(rng.integers(0, 2, n)))
assert risk_factors.risk_treatment_associations(data, follow, ["Grado"], ["Radioterapia"], load().risk_factors) is None
def test_a_scenario_holds_the_patients_who_meet_every_condition_and_none_without_the_column():
"""Pins down: a scenario's mask is the patients who meet all its conditions over the raw columns (age from the age column,
stage, subtype and surgery by keyword), and a cohort without a column has nobody in the scenarios that need it. Fails if
a condition is dropped, an age edge moves, or a missing column makes a scenario include everyone."""
raw = pd.DataFrame({"Age recode": ["30-34 years", "60-64 years", "75-79 years", "60-64 years"],
"Stage": ["IIA", "IIIB", "IV", "I"], "Subtype (HER2+)": ["HER2+", "HER2+", "HER2-", "HER2+"]})
found = scenarios.masks(raw)
assert found["< 45 años"].tolist() == [True, False, False, False]
assert found["≥ 75 años"].tolist() == [False, False, True, False]
assert found["Estadio IV"].tolist() == [False, False, True, False]
assert found["HER2+ · ≥60 años · estadio III–IV (Alto)"].tolist() == [False, True, False, False]
assert not found["HER2− · estadio 0–II · cirugía conservadora"].any() # no surgery column: nobody
assert not scenarios.masks(raw[["Age recode"]])["Estadio I"].any() # no stage column: nobody
def test_the_risk_factors_of_a_scenario_are_the_classified_categories_most_of_it_shares():
"""Pins down: a classified risk factor that nearly all of a scenario has is listed as defining it, a protector that most
has as most of it, and one that few have is left out. Fails if the shares are taken over the cohort instead of the
scenario, or a category under the presence floor is listed."""
table = pd.DataFrame({"variable": ["Grado", "Grado", "Subtipo"], "categoria": ["G3", "G1", "A"], "clasificacion": ["riesgo robusto", "protector sugerente", "riesgo robusto"],
"OR_muerte": [2.0, 0.5, 3.0], "IC95_inf": [1.2, 0.3, 1.1], "IC95_sup": [3.0, 0.9, 5.0], "delta_S18": [-0.1, 0.05, -0.2]})
data = pd.DataFrame({"Grado": ["G3"] * 10 + ["G1"] * 6 + ["G3"] * 4, "Subtipo": ["A"] * 1 + ["B"] * 19})
mask = np.array([True] * 10 + [False] * 10) # the scenario: the first ten, all grade 3 and one of subtype A
classification = risk_factors.Classification(table, ["c1"])
found = risk_factors.risk_scenario_factors(classification, None, data, {"Grado 3": mask})
row = found.summary.iloc[0]
assert "Grado=G3" in row["riesgo_definitorios"] and row["n_factores_riesgo_incluidos"] == 1
assert set(found.details["variable"]) == {"Grado", "Subtipo"} # subtype A is 10 % of the scenario: present
assert found.details[found.details["categoria"] == "G1"].empty # no scenario member has G1
+561
View File
@@ -0,0 +1,561 @@
"""What this module covers: `models.cama.survival`: the index it takes from the total cohort (the first invasive biopsy
report, with its rules), the covariates and outcome it derives from a build's events, the interval survival estimator
(that it scores unseen categories and intervals without deaths, and that grade and ER move the mortality the way the
data say), that the dataflow reaches its metrics and routines without MLflow, that training registers a version with
its lineage and estimating with it dates each risk by the model's own index.
Fixtures: `cohort_frame`, a long frame of 240 members of the total cohort whose death depends on the grade and on ER,
with members that must be left out; `cohort_file`, that frame as a build's Parquet file with its lineage (the window
in its parameters); `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
import json
from datetime import date, datetime, timedelta, timezone
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cama.survival import estimator
from models.cama.survival.estimator import FEATURES, INDEX_COLUMN, IntervalSurvival, MemberFeatures
from models.dags.estimation import estimate
from models.dags.training import Scenario, dataflow, find_trained, train
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.storage import CohortFile, read_cohort, read_metadata
from models.steps import indexing
CUTOFF = date(2026, 1, 1)
SCENARIO = Scenario.load("cama", "survival")
CONFIG = SCENARIO.config
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": CUTOFF.isoformat()}
LINEAGE = {"url": "cama/cohorte_total", "datos_as_of": CUTOFF.isoformat(), "parametros": json.dumps(WINDOW)}
N = 240
def _row(pac_id, when, tipo, valor=None, numero=None, source="biopsiamama", source_id=None, first=None):
return {"pac_id": pac_id, "fecha_indice": first or when, "fecha": when,
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": source,
"fuente_id": source_id or f"{pac_id}-{tipo}"}
def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, first=None, size=30.0):
"""The invasive biopsy report of `pac_id` on `index`, with its results."""
key = f"B{pac_id}"
rows = [_row(pac_id, index, "biopsia", "CARCINOMA_INVASOR", source_id=key, first=first),
_row(pac_id, index, "tipo_histologico", "DUCTAL_INFILTRANTE", source_id=key, first=first),
_row(pac_id, index, "grado_nottingham", grade, source_id=key, first=first),
_row(pac_id, index, "receptor_estrogeno", er, source_id=key, first=first),
_row(pac_id, index, "receptor_progesterona", er, source_id=key, first=first),
_row(pac_id, index, "her2", her2, source_id=key, first=first),
_row(pac_id, index, "ki67_pct", numero=ki67, source_id=key, first=first),
_row(pac_id, index, "tamano_tumor_mm", numero=size, source_id=key, first=first)]
return rows
def _person(pac_id, born, first, died=None):
rows = [_row(pac_id, born, "nacimiento", source="persona", first=first)]
if died:
rows.append(_row(pac_id, died, "defuncion", source="persona", first=first))
return rows
@pytest.fixture(scope="module")
def cohort_frame():
"""240 members, each with her birth, an invasive biopsy report in 2024-01..2025-06 (grade 1 to 3, ER positive or
negative) and, if she dies by the cut-off, her death: exponential in months, faster with grade 3 and without ER.
Members 241 to 245 must be left out: a benign biopsy only, no birth date, a death before the report, a report
before the window, and an invasive report after the cut-off."""
rng = np.random.default_rng(3)
rows = []
for pac_id in range(1, N + 1):
index = date(2024, 1, 1) + timedelta(days=int(rng.integers(0, 546)))
grade, er = str(rng.choice(["G1", "G2", "G3"])), str(rng.choice(["POSITIVO", "NEGATIVO"]))
rate = 0.012 * np.exp(1.3 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
died = index + timedelta(days=int(rng.exponential(1 / rate) * 30.4375))
rows += _person(pac_id, date(1960, 1, 1) + timedelta(days=pac_id * 30), index - timedelta(days=10),
died if died <= CUTOFF else None)
rows += _report(pac_id, index, grade, er, first=index - timedelta(days=10))
first = date(2025, 1, 1)
rows += [_row(241, first, "biopsia", "BENIGNO", source_id="B241", first=first)]
rows += _report(242, first, first=first)
rows += _person(243, date(1960, 1, 1), first, died=first - timedelta(days=20)) + _report(243, first, first=first)
rows += _person(244, date(1960, 1, 1), date(2010, 1, 1)) + _report(244, date(2010, 3, 1), first=date(2010, 1, 1))
rows += _person(245, date(1960, 1, 1), first) + _report(245, date(2026, 3, 1), first=first)
return pd.DataFrame(rows, columns=SCHEMA.names)
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 3's file, with the lineage a dbt build gives."""
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
path = tmp_path / "3.parquet"
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "3"}), path)
return path
def _indexed(frame):
return indexing.cohort(frame, LINEAGE, CONFIG["index"])
def test_the_index_is_the_first_invasive_biopsy_report_and_its_rules_leave_out_who_cannot_be_followed(cohort_frame):
"""Pins down: members 1 to 240 are indexed at their invasive report; a benign biopsy has no index (241), a missing
birth date (242), a death before the report (243) and a report outside the window (244, and 245 after the cut-off
window end) leave the cohort, each charged to its own rule. Fails if the kind stops reading the grade, the window
or either rule."""
attrition = dict(indexing.index_attrition(cohort_frame, LINEAGE, CONFIG["index"]))
assert attrition["pacientes"] == N + 5 and attrition["indexed"] == N + 3
assert attrition["sin_nacimiento"] == N + 2 and attrition["defuncion_hasta_el_indice"] == N + 1
members = _indexed(cohort_frame)["pac_id"].unique()
assert set(members) == set(range(1, N + 1)) | {245}
reindexed = _indexed(cohort_frame).groupby("pac_id")["fecha_indice"].first()
assert reindexed[1] == cohort_frame[(cohort_frame["pac_id"] == 1) & (cohort_frame["tipo"] == "biopsia")]["fecha"].iloc[0]
def test_covariates_are_the_index_reports_results(cohort_frame):
"""Pins down: the covariates are the results of the report on the index date: type, grade, ER, PR, HER2 and the
Ki-67 band; a grade reported a year later does not replace them, and the age group is the age at the index. Fails
if the covariates read another report or window, or the age is taken at another date."""
one = cohort_frame[cohort_frame["pac_id"] == 1]
later = pd.DataFrame([_row(1, date(2025, 12, 1), "grado_nottingham", "G1" if one[one["tipo"] == "grado_nottingham"][
"valor_codigo"].iloc[0] != "G1" else "G3", first=one["fecha_indice"].iloc[0])], columns=SCHEMA.names)
table = estimator.member_table(_indexed(pd.concat([one, later])), CONFIG["age_cuts"], CONFIG["ki67_cuts"],
CONFIG["result_days"], CONFIG["size_cuts"])
row = table.loc[1]
reported = one[one["tipo"] == "grado_nottingham"]["valor_codigo"].iloc[0]
assert (row["histologic_type"], row["grade"], row["her2"], row["ki67_group"], row["size_group"]) == (
"DUCTAL_INFILTRANTE", reported, "H1", "14-19", "20-49")
assert row["er"] == one[one["tipo"] == "receptor_estrogeno"]["valor_codigo"].iloc[0] == row["pr"]
born, index = date(1960, 1, 1) + timedelta(days=30), table.loc[1, "fecha_indice"].date()
age = (index - born).days / 365.25
assert row["age_group"] == ("<45" if age < 45 else "45-59" if age < 60 else "60-74" if age < 75 else "≥75")
def test_the_outcome_is_the_months_to_death_or_to_the_cutoff_cut_at_the_cap(cohort_frame):
"""Pins down: a member who dies in follow-up has her whole months to the death and `event`; one without a death is
followed to the cut-off without it; a death after `cap_months` counts as alive at the cap. Fails if the months, the
censoring date or the cap change."""
rows = (_person(1, date(1960, 1, 1), date(2024, 1, 1), died=date(2024, 8, 10)) + _report(1, date(2024, 1, 1))
+ _person(2, date(1960, 1, 1), date(2025, 1, 1)) + _report(2, date(2025, 1, 1))
+ _person(3, date(1960, 1, 1), date(2023, 1, 1), died=date(2025, 11, 1)) + _report(3, date(2023, 1, 1)))
frame = pd.DataFrame(rows, columns=SCHEMA.names)
table = estimator.outcome_table(frame, CUTOFF, cap_months=24)
assert table.loc[1].tolist() == [7, True] # 2024-01-01 to 2024-08-10: 222 days
assert table.loc[2].tolist() == [11, False] # 2025-01-01 to the cut-off: 365 days, 11.99 whole months
assert table.loc[3].tolist() == [24, False] # dies after 24 months: alive at the cap
@pytest.fixture(scope="module")
def labelled(cohort_frame):
"""The 240 indexed members with their covariates and outcome, as the dataflow labels them."""
indexed = _indexed(cohort_frame)
indexed = indexed[indexed["pac_id"] <= N]
features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["ki67_cuts"], CONFIG["result_days"], CONFIG["size_cuts"])
return features.join(estimator.outcome_table(indexed, CUTOFF, 24)).reset_index()
def test_grade_and_er_move_the_mortality_the_way_the_data_say(labelled):
"""Pins down: fitted on members whose death depends on grade 3 and on no ER, the estimator gives grade 3 a higher
mortality at every horizon than grade 1, and the mortality grows with the horizon and stays in 0 to 1. Fails if the
fit stops using the covariates or the survival stops being a product of the intervals."""
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
labelled[["months", "event"]])
probe = labelled[FEATURES].iloc[[0, 0]].copy()
probe["grade"] = ["G1", "G3"]
probe["er"] = "POSITIVO"
mortality = model.predict_proba(probe)
assert mortality.shape == (2, 3) and ((0 <= mortality) & (mortality <= 1)).all()
assert (mortality[1] > mortality[0]).all() and (np.diff(mortality, axis=1) >= 0).all()
def test_a_category_unseen_in_training_and_an_interval_without_deaths_are_scored(labelled):
"""Pins down: a grade the model never saw scores as unknown rather than failing, and a cohort where nobody dies in
the last interval still fits (a constant stands for the logistic regression). Fails if either raises."""
early = labelled.assign(event=labelled["event"] & (labelled["months"] < 12))
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(early[FEATURES],
early[["months", "event"]])
unseen = labelled[FEATURES].iloc[[0]].assign(grade="G9")
mortality = model.predict_proba(unseen)
assert np.isfinite(mortality).all()
assert mortality[0, 2] - mortality[0, 1] < 0.05 # nobody died in 12-18 months: only the network's smoothing remains
def test_the_pipeline_takes_the_total_cohort_and_scores_only_who_the_index_leaves(cohort_frame, labelled):
"""Pins down: the registered shape (`MemberFeatures` then the estimator) takes the unindexed frame, gives one row
per member of the frame, and leaves empty the members the scenario leaves out, with the model's index date first for
the rest. Fails if scoring stops indexing the build as training did."""
from sklearn.pipeline import Pipeline
fitted = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
labelled[["months", "event"]])
pipeline = Pipeline([("members", MemberFeatures(dict(CONFIG["index"]), WINDOW, tuple(CONFIG["age_cuts"]),
tuple(CONFIG["ki67_cuts"]), CONFIG["result_days"], tuple(CONFIG["size_cuts"]))),
("survival", fitted)])
scored = pipeline.predict_proba(cohort_frame)
assert scored.shape == (N + 5, 4)
assert np.isnan(scored[N:N + 4, 0]).all() and not np.isnan(scored[:N, 0]).any()
assert not np.isnan(scored[N + 4, 0]) # member 245: indexed (her report is in the window), scored
def test_the_dataflow_reaches_its_metrics_and_routines_without_mlflow(cohort_frame):
"""Pins down: from the source cohort and its lineage the graph gives metrics that are numbers, and the five routine
records the registry checks before promoting. Fails if a node stops producing its record or a metric is not a
number."""
dr = dataflow(*SCENARIO.modules, config=CONFIG)
result = dr.execute(["metrics", "routines", "index_attrition"],
inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
assert all(isinstance(v, (int, float)) for v in result["metrics"].values())
assert result["metrics"]["n_train"] + result["metrics"]["n_test"] == N + 1
assert set(result["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES",
"CONFIANZA_SALIDA"}
json.dumps(result["routines"])
def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking,
tmp_path):
"""Pins down: training on a build's file registers a version; estimating with it writes one row per scored member
and horizon, dated by the model's index (the report), not by the cohort's, with the members the scenario leaves out
absent. Fails if the version cannot score a build or the estimate keeps the cohort's index date."""
version = train(SCENARIO, CohortFile(cohort_file))
output = tmp_path / "estimate.parquet"
resolved, wrote = estimate(SCENARIO, CohortFile(cohort_file), output, version)
assert wrote and resolved.version == version and find_trained(SCENARIO, CohortFile(cohort_file)) == version
risks = pq.read_table(output).to_pandas()
assert set(risks["horizonte_anios"]) == {0.5, 1.0, 1.5}
assert set(risks["pac_id"]) == set(range(1, N + 1)) | {245}
frame = read_cohort(cohort_file)
report = frame[(frame["tipo"] == "biopsia") & (frame["pac_id"] == 1)]["fecha"].iloc[0]
assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == report
assert read_metadata(output)["desenlace"] == "muerte"
@pytest.fixture(scope="module")
def population_record(cohort_frame):
"""The `curvas` record the dataflow publishes for the 240 indexed members, with a small bootstrap to stay quick."""
config = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}}
dr = dataflow(*SCENARIO.modules, config=config)
return dr.execute(["population_curves"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["population_curves"]["curvas"]
def test_the_population_record_has_the_figures_curves_points_and_labels(population_record):
"""Pins down: the record the dashboard draws has the Kaplan-Meier with its band, the adjusted curve, both Weibull
curves, LR, HBN and combined points at 6, 12 and 18 months each with a 95 % interval, and the labels from the
settings. Fails if a curve or a series is missing, a curve rises, a band does not hold its curve, an interval is
inverted, or the labels stop coming from `[config.etiquetas]`."""
r = population_record
assert r["horizons_months"] == [6, 12, 18] and r["n"] == N + 1 and r["events"] > 20
km = r["km"]
assert km["months"][0] == 0 and km["S"][0] == 1.0 and np.all(np.diff(km["S"]) <= 1e-12)
assert all(lo <= s <= hi for lo, s, hi in zip(km["low"], km["S"], km["high"]))
for curve in (r["km_adjusted"]["S"], r["weibull"]["S"], r["weibull_fractional"]["S"]):
assert curve[0] == pytest.approx(1.0, abs=1e-6) and np.all(np.diff(curve) <= 1e-9)
assert set(r["points"]) == {"LR", "HBN", "COMB"}
for series in r["points"].values():
assert len(series["S"]) == 3 and all(0 <= lo <= hi <= 1 for lo, hi in zip(series["low"], series["high"]))
assert series["S"] == sorted(series["S"], reverse=True)
assert r["etiquetas"]["eje_x"] == CONFIG["etiquetas"]["eje_x"]
json.dumps(r)
def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking):
"""Pins down: training registers the `analisis/curvas.json` file with the version, and it is the record the dataflow
built. Fails if the saver stops logging a dataflow's `population`."""
from models.io.registry import registry
version = train(SCENARIO, CohortFile(cohort_file))
files = [f["path"] for f in registry.artifacts("cama", "survival", version)]
name, content = registry.artifact("cama", "survival", version, "analisis/curvas.json")
record = json.loads(content)
assert "analisis/curvas.json" in files and name == "curvas.json"
assert record["horizons_months"] == [6, 12, 18] and set(record["points"]) == {"LR", "HBN", "COMB"}
@pytest.fixture(scope="module")
def development_record(cohort_frame):
"""The `desarrollo` record the dataflow publishes for the 240 indexed members, with the smallest budget."""
config = {**CONFIG, "desarrollo": {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}}
dr = dataflow(*SCENARIO.modules, config=config)
return dr.execute(["development"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["development"]["desarrollo"]
def test_a_stage_that_cannot_run_on_the_cohort_is_recorded_and_does_not_stop_the_others(development_record):
"""Pins down: on a cohort whose covariates barely vary (the 240 members here) the SEER stages that need variation
publish their error in the record and the run still produces it, with every stage listed. Fails if one stage's
exception escapes the node, which would stop a version from training. The stage and the treatments come from the
members' timeline, so none of them is listed as unavailable; fails if the record stops reading them."""
assert [e["etapa"] for e in development_record["etapas"]] == ["01", "02", "03", "04", "05", "06"]
assert set(development_record["errores"]) <= {"01", "02", "03", "04", "05", "06"}
assert development_record["variables_no_disponibles"] == []
def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_cohort():
"""Pins down: on 600 members with varied covariates all six SEER stages run and publish their tables and figures.
Fails if a stage errors on a cohort of this shape or stops writing what the dashboard reads."""
from models.cama.survival import development as dev
rng = np.random.default_rng(11)
n = 600
grade = rng.choice(["G1", "G2", "G3"], n, p=[0.2, 0.5, 0.3])
er = rng.choice(["POSITIVO", "NEGATIVO"], n, p=[0.7, 0.3])
risk = 0.03 * np.exp(1.0 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
months = np.minimum(rng.exponential(1 / risk), 30).round()
members = pd.DataFrame({
"fecha_indice": pd.to_datetime("2024-01-01") + pd.to_timedelta(rng.integers(0, 540, n), unit="D"),
"months": months.astype(int), "event": rng.random(n) < 1 - np.exp(-risk * 24),
"age_years": rng.normal(58, 12, n).clip(25, 90), "size_mm": rng.integers(5, 70, n).astype(float),
"histologic_type": rng.choice(["8500/3", "8520/3"], n, p=[0.85, 0.15]), "grade": grade, "er": er,
"pr": rng.choice(["POSITIVO", "NEGATIVO"], n), "her2": rng.choice(["H0", "H1", "H2", "H3"], n),
"ki67_group": rng.choice(["<14", "14-19", "≥20"], n)})
members["months"] = np.where(members["event"], np.minimum(members["months"], 23), 24)
settings = {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}
r = dev.development(members, settings)["desarrollo"]
assert r["errores"] == {}, r["errores"]
assert {"or_lr_balanceada", "hbn_arcos", "subgrupos_weibull", "prueba_edad"} <= set(r["tablas"])
arcs = r["tablas"]["hbn_arcos"]
assert arcs["columnas"] == list(arcs["filas"][0]) and len(arcs["columnas"]) > 1
assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values())
def _stage_five_table(csv_path, survival):
"""The table of the SEER pipeline's stage 5 for the main curve (`sv_table`): its own nodes over a CSV of the cohort."""
from hamilton import driver
from models.cama.seer_survival import survival_curves
dr = driver.Builder().with_modules(survival_curves).build()
return dr.execute(["sv_table"], inputs={"depurated_csv": str(csv_path), "survival": survival})["sv_table"]
@pytest.fixture(scope="module")
def members_frame(cohort_frame):
"""The 240 indexed members, labelled (covariates, follow-up, death), as the figure's nodes take them."""
return dataflow(*SCENARIO.modules, config=SCENARIO.config).execute(
["labelled_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["labelled_members"]
def test_the_published_figure_is_the_seer_pipelines_stage_five_on_the_same_members(members_frame, tmp_path):
"""Pins down: the Kaplan-Meier curve, the adjusted curve, the stacking weights, the points of LR, HBN and their
combination and their bootstrap interval in the published record are those that `models.cama.seer_survival`'s own stage 5
(`run_survival`, on a CSV of the same members and the same settings) gives. Fails if the record's code path stops being
the pipeline's, which would make the dashboard's figure another model's."""
import dataclasses
from models.cama.survival import estimator
survival = {**CONFIG["survival"], "n_boot": 6, "ks_max_seconds": 5}
config = {**CONFIG, "survival": survival}
ours = dataflow(*SCENARIO.modules, config=config).execute(
["population_curves"], inputs={"source_cohort": pd.DataFrame(), "cohort_lineage": {}},
overrides={"labelled_members": members_frame})["population_curves"]["curvas"]
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
for name in estimator.FEATURES:
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
csv.to_csv(tmp_path / "depurado.csv", index=False)
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
for model in ("LR", "HBN", "COMB"):
rows = theirs[theirs["modelo"] == model]
assert ours["points"][model]["S"] == pytest.approx(rows["S"].tolist(), abs=1e-9)
assert ours["points"][model]["low"] == pytest.approx(rows["IC_inf"].tolist(), abs=1e-9)
assert ours["points"][model]["high"] == pytest.approx(rows["IC_sup"].tolist(), abs=1e-9)
km = theirs[theirs["modelo"] == "COMB"]
assert [ours["km"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_crudo"].tolist(), abs=1e-9)
assert [ours["km_adjusted"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_ajustada"].tolist(), abs=1e-9)
def test_the_production_model_predicts_what_the_pipelines_points_say(members_frame, tmp_path):
"""Pins down: the `IntervalSurvival` a version in production is (the model that scores each patient) gives, averaged over
the members it was fitted on, the survival at each horizon that the pipeline's stage 5 gives for LR, HBN and their
combination, exactly (the same data, the same settings). Fails if the model that scores patients drifts from the model whose
figure is published."""
import dataclasses
from models.cama.survival import estimator
from models.cama.survival.estimator import IntervalSurvival
survival = {**CONFIG["survival"], "n_boot": 0}
model = IntervalSurvival(survival, tuple(h / 12 for h in survival["horizons"])).fit(
members_frame[estimator.FEATURES], members_frame[["months", "event"]])
mean_combined = model.survival_proba(members_frame[estimator.FEATURES]).mean(axis=0)
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
for name in estimator.FEATURES:
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
csv.to_csv(tmp_path / "depurado.csv", index=False)
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
assert mean_combined == pytest.approx(theirs[theirs["modelo"] == "COMB"]["S"].tolist(), abs=1e-6)
@pytest.fixture(scope="module")
def production_model(members_frame):
"""A model fitted on the 240 members: what a version in production is when the dashboard scores a selection."""
return IntervalSurvival(CONFIG["survival"], tuple(h / 12 for h in CONFIG["survival"]["horizons"])).fit(
members_frame[FEATURES], members_frame[["months", "event"]])
def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(members_frame, production_model, monkeypatch):
"""Pins down: the record of a scenario is for its members only (their count and deaths), its points are the model's mean
survival for them at the model's horizons with an interval around it, and nothing is refitted (the same scenario twice gives
the same record). Fails if the scenario's mask is ignored, or the scenario changes the model's horizons."""
from models.cama.survival import live
young = np.arange(len(members_frame)) < 120
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Primeras 120": young})
everyone = live.curves(SCENARIO, production_model, members_frame, None)
first = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
again = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
assert everyone["n"] == len(members_frame) and everyone["escenario"] == "Toda la cohorte" and everyone["horizons_months"] == [6, 12, 18]
assert first["n"] == 120 and first["escenario"] == "Primeras 120" and first["points"] == again["points"]
comb = first["points"]["COMB"]
assert all(lo <= s <= hi for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"])
def test_the_live_figure_fits_its_curves_to_the_members_deaths_and_takes_the_published_points(members_frame, production_model):
"""Pins down: the Weibull curves of a scenario's figure follow its members' own deaths (close to their Kaplan-Meier, as the
pipeline's survival stage fits a subgroup), and the points are the ones the version published for the subgroup when it did.
Fails if the curves are fitted to the model's prediction instead of the data, or the published points are ignored."""
from models.cama.survival import live
rows = [{"modelo": m, "meses": h, "S": 0.8, "IC_inf": 0.7, "IC_sup": 0.9, "subgrupo": "Toda la cohorte"}
for m in ("LR", "HBN", "COMB") for h in (6, 12, 18)]
published = live.published_points(rows, "Toda la cohorte")
record = live.curves(SCENARIO, production_model, members_frame, None, published)
km, weibull = np.asarray(record["km"]["S"]), np.asarray(record["weibull"]["S"])
at_months = np.interp(np.arange(len(km)), record["weibull"]["t"], weibull)
assert np.abs(at_months - km).max() < 0.05
assert record["points"]["COMB"] == {"S": [0.8] * 3, "low": [0.7] * 3, "high": [0.9] * 3}
assert live.published_points(rows, "Otro") is None
def test_a_patient_sees_the_scenarios_she_belongs_to_or_the_whole_cohort(members_frame, monkeypatch):
"""Pins down: a patient's scenarios are those whose mask holds her and that have enough members to draw; in none, the whole
cohort; and a patient outside the cohort is refused. Fails if a scenario too small to draw is offered, or a patient in no
scenario is left with nothing."""
from models.cama.survival import live
first, last = int(members_frame["pac_id"].iloc[0]), int(members_frame["pac_id"].iloc[-1])
inside = np.arange(len(members_frame)) < 100
tiny = np.arange(len(members_frame)) < 3
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Grande": inside, "Diminuto": tiny})
assert live.patient_scenarios(members_frame, first) == ["Grande"] # in both; the tiny one has too few to draw
assert live.patient_scenarios(members_frame, last) == ["Toda la cohorte"] # in neither
with pytest.raises(live.QueryError):
live.patient_scenarios(members_frame, 10**9)
def test_the_scenarios_use_the_hospitals_age_and_subtype_and_none_that_needs_a_stage(members_frame):
"""Pins down: the scenario masks use the age in years and a subtype derived from the receptors (hormone receptors and
HER2 3+ / 0-1+), and a scenario that needs the stage or the surgery, which the hospital does not report, has no member.
Fails if a stage scenario includes everyone, or the subtype ignores the receptors."""
from models.cama.seer_survival import scenarios
from models.cama.survival import live
n = len(members_frame)
frame = members_frame.assign(er=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "POSITIVO"], n),
pr=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "NEGATIVO"], n),
her2=np.resize(["H1", "H3", "H0", "H2"], n))
found = live.molecular_subtype(frame).iloc[:4].tolist()
masks = live.scenario_masks(frame)
assert found == ["HR+/HER2-", "HR-/HER2+", "HR-/HER2-", "Desconocido"] # HER2 2+ is equivocal: unknown
assert set(masks) == set(scenarios.SCENARIOS)
assert not masks["Estadio IV"].any() and not masks["Triple negativo (HR−/HER2−) · estadio 0–II"].any()
@pytest.mark.parametrize("name", ["No existe", "Estadio IV"])
def test_a_scenario_that_cannot_be_answered_says_why(members_frame, production_model, name):
"""Pins down: an unknown scenario and one with too few members to say anything (every stage scenario, with the stage not
reported) are each a `QueryError` with a message. Fails if either runs and draws a meaningless figure or fails with an
unreadable error."""
from models.cama.survival import live
with pytest.raises(live.QueryError):
live.curves(SCENARIO, production_model, members_frame, name)
def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():
"""Pins down: the month-by-month survival equals the model's at each horizon, starts at 1, never rises, and goes on past
the last horizon at the last interval's rate. Fails if the interpolation misses a horizon or the curve can go up."""
from models.cama.survival import live
curve = live.monthly(np.array([[0.9, 0.8, 0.6]]), [6, 12, 18], 24)[0]
assert curve[0] == 1.0 and curve[6] == pytest.approx(0.9) and curve[12] == pytest.approx(0.8) and curve[18] == pytest.approx(0.6)
assert (np.diff(curve) <= 1e-12).all() and curve[24] < curve[18]
def test_a_saved_model_whose_class_is_older_still_scores_with_the_current_code(members_frame, production_model):
"""Pins down: the fitted state of a model, put in an object of a class without the current methods (what loading a saved
model from before a code change gives), scores the same as the model itself once rehydrated. Fails if the live figure
depends on the class a version was saved with, which makes every older version unusable after a change."""
from types import SimpleNamespace
from models.cama.survival import live
stale = SimpleNamespace(**production_model.__dict__)
again = live.rehydrate(stale).component_survival(members_frame[FEATURES])
for name, expected in production_model.component_survival(members_frame[FEATURES]).items():
assert again[name] == pytest.approx(expected)
def test_the_members_carry_their_stage_and_treatments_and_the_scenarios_read_them():
"""Pins down: a member's stage is the one reported with her diagnosis and her surgery, radiotherapy and chemotherapy are
those of the year after it, and the clinical scenarios that need a stage or a conservative surgery find her. Fails if
`member_table` stops reading them or `live.scenario_masks` goes back to age and subtype only."""
from models.cama.survival import estimator, live
rows = []
for pac, (stage, surgery, her2) in enumerate([("EI", "SEGMENTECTOMIA", "H0"), ("EIV", "MASTECTOMIA_TOTAL", "H3")], start=1):
rows += [
{"pac_id": pac, "tipo": "nacimiento", "fecha": "1950-01-01", "valor_codigo": None, "valor_numerico": None},
{"pac_id": pac, "tipo": "biopsia", "fecha": "2025-01-10", "valor_codigo": "CARCINOMA_INVASOR", "valor_numerico": None},
{"pac_id": pac, "tipo": "estadio_clinico", "fecha": "2025-01-10", "valor_codigo": stage, "valor_numerico": None},
{"pac_id": pac, "tipo": "her2", "fecha": "2025-01-10", "valor_codigo": her2, "valor_numerico": None},
{"pac_id": pac, "tipo": "receptor_estrogeno", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None},
{"pac_id": pac, "tipo": "receptor_progesterona", "fecha": "2025-01-10", "valor_codigo": "NEGATIVO", "valor_numerico": None},
{"pac_id": pac, "tipo": "cirugia", "fecha": "2025-03-01", "valor_codigo": surgery, "valor_numerico": None},
]
rows.append({"pac_id": 1, "tipo": "radioterapia", "fecha": "2025-05-01", "valor_codigo": "ADYUVANTE", "valor_numerico": None})
cohort = pd.DataFrame(rows).assign(fecha_indice="2025-01-10", fuente_id="x")
members = estimator.member_table(cohort, [45, 60, 75], [14, 20], 30)
assert members.loc[1, ["stage", "surgery", "radiotherapy", "chemotherapy"]].tolist() == ["I", "Cirugía conservadora", "Sí", "No"]
assert members.loc[2, ["stage", "surgery", "radiotherapy"]].tolist() == ["IV", "Mastectomía", "No"]
masks = live.scenario_masks(members.reset_index())
assert masks["Estadio I"].tolist() == [True, False] and masks["Estadio IV"].tolist() == [False, True]
+25
View File
@@ -139,6 +139,21 @@ def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scen
assert training.find_trained(scenario, CohortFile(cohort_file)) == version assert training.find_trained(scenario, CohortFile(cohort_file)) == version
def test_training_stores_the_drawing_of_its_dataflow_as_files_of_the_version(scenario, cohort_file, mlflow_tracking):
"""Pins down: the version lists `diagramas/pipeline.dot` and, with Graphviz's `dot`, `diagramas/pipeline.svg`, one
file each (no archive), and the drawing names the scenario's nodes. Fails if training stops drawing its graph or
stores it as anything but separate files."""
pytest.importorskip("graphviz")
version = training.train(scenario, CohortFile(cohort_file))
files = {f["path"] for f in registry.artifacts("cacu", "fake_scenario", version)}
name, dot = registry.artifact("cacu", "fake_scenario", version, "diagramas/pipeline.dot")
assert name == "pipeline.dot" and b"fitted_model" in dot and b"metrics" in dot
assert "diagramas/pipeline.svg" in files or not training.pipeline_drawing(
training.dataflow(*scenario.modules, config=scenario.config))[1]
assert not any(path.endswith(".zip") for path in files)
def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking, def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking,
predict_without_repository): predict_without_repository):
"""Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the """Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the
@@ -196,3 +211,13 @@ def test_the_registered_model_needs_only_its_listed_requirements(scenario, cohor
assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines
assert not [line for line in lines if line.startswith("-e") or "/" in line] assert not [line for line in lines if line.startswith("-e") or "/" in line]
def test_without_graphviz_training_has_no_drawing_and_still_registers():
"""Pins down: when Hamilton can't draw (no `graphviz` package, it gives None instead of raising), the drawing
is skipped rather than stopping the training. Fails if `pipeline_drawing` reads a missing graph."""
from types import SimpleNamespace
from models.dags.training import pipeline_drawing
assert pipeline_drawing(SimpleNamespace(display_all_functions=lambda *a, **k: None)) is None
+34 -14
View File
@@ -1,4 +1,4 @@
"""What this module covers: the registry's promotion checks, promotion and retirement, the lineage of a version, and """What this module covers: the registry's promotion checks, promotion and retirement, the scenarios in production, the lineage of a version, and
what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`). what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`).
Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model; Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model;
@@ -21,7 +21,7 @@ def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_track
with pytest.raises(PromotionBlocked) as blocked: with pytest.raises(PromotionBlocked) as blocked:
registry.promote("cacu", "tamizaje", version) registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed} failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01a", "ML-01b"} assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready): def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
@@ -57,21 +57,28 @@ def test_lineage_lists_every_stored_file_and_each_routine_record(production_read
assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8} assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8}
@pytest.mark.parametrize("routines, model, failing", [ def test_promotion_needs_the_model_the_training_run_itself_saved(governance_db, cacu_db, mlflow_tracking):
([ArtifactKind.MUESTREO], True, "ML-01a"), """A run that saved no model is not promoted, whatever else is in order. Fails if the ML-01b check stops requiring
(None, False, "ML-01b"), `modelo_sha`."""
]) run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=None, model=False)
def test_promotion_needs_what_the_training_run_itself_recorded(governance_db, cacu_db, mlflow_tracking, routines, model,
failing):
"""A run that skipped routine records, or saved no model, is not promoted, whatever else is in order. Fails if
the ML-01a check stops requiring every kind in `ROUTINE_KINDS` or the ML-01b check stops requiring `modelo_sha`."""
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=routines, model=model)
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c", version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
interpretability_report_uri="i") interpretability_report_uri="i")
failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed] failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed]
assert [check.code for check in failed] == [failing] assert [check.code for check in failed] == ["ML-01b"]
if failing == "ML-01a":
assert "DATOS_FALTANTES" in failed[0].detail
@pytest.mark.parametrize("routines, recorded", [([], "0 de 5"), ([ArtifactKind.MUESTREO], "1 de 5 (MUESTREO)")])
def test_the_training_run_is_the_registered_routine_and_its_records_are_reported(governance_db, cacu_db,
mlflow_tracking, routines, recorded):
"""ML-01a: the version's training run is the registered routine, so a model without some routine records (a
prevalence-incidence mixture has no class balance) can still be promoted; the check reports which records the
run holds. Fails if ML-01a goes back to requiring every kind in `ROUTINE_KINDS`, or stops reporting them."""
run = trained_run("cacu", "parcial", armado("huella-x"), {"auc": 0.8}, routines=routines, model=True)
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
interpretability_report_uri="i")
checks = {check.code: check for check in registry.checks("cacu", "parcial", version)}
assert checks["ML-01a"].passed and recorded in checks["ML-01a"].detail
assert all(check.passed for check in checks.values())
def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready): def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready):
@@ -101,6 +108,19 @@ def test_retire_and_lineage(production_ready):
registry.retire(domain, scenario, second) registry.retire(domain, scenario, second)
def test_in_production_lists_the_scenarios_holding_the_alias(production_ready):
"""Only scenarios of the domain with a version in production are listed; a candidate or a retired one is not.
Fails if `in_production` stops reading the `produccion` alias or leaks another domain's models."""
domain, scenario, version = production_ready("v1")
production_ready("v1-dx", scenario="diagnostico")
assert registry.in_production(domain) == []
registry.promote(domain, scenario, version)
assert registry.in_production(domain) == [scenario]
assert registry.in_production("cama") == []
registry.retire(domain, scenario, version)
assert registry.in_production(domain) == []
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")]) @pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario): def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
with pytest.raises(ValueError): with pytest.raises(ValueError):
+21
View File
@@ -0,0 +1,21 @@
"""What this module covers: `models.reports.rendering.JupyterRenderer`'s page keeps out the code of a cell that asks for
it as Quarto does (`#| echo: false`) and keeps its output, so a notebook renders the same with either renderer.
No kernel runs: the cells carry their outputs already."""
import nbformat
from nbconvert import HTMLExporter
from models.reports.rendering import JupyterRenderer
def test_a_cell_with_echo_false_shows_its_output_and_not_its_code():
"""Pins down: the hidden cell's source (a marker in its code) is not on the page, its output is, and a cell without
the option still shows its code. Fails if the Jupyter renderer stops honouring `#| echo: false`."""
hidden = nbformat.v4.new_code_cell("#| echo: false\nsecret_marker_in_code = 1\nprint('salida visible')")
hidden.outputs = [nbformat.v4.new_output("stream", name="stdout", text="salida visible\n")]
shown = nbformat.v4.new_code_cell("codigo_que_se_ve = 2")
node = nbformat.v4.new_notebook(cells=[hidden, shown])
page = JupyterRenderer._page(HTMLExporter, node)
assert "salida visible" in page and "secret_marker_in_code" not in page and "codigo_que_se_ve" in page
+36
View File
@@ -0,0 +1,36 @@
"""What this module covers: `models.reports.templates`: the notebooks kept in the code are listed by domain with the
scenarios they can run for, read by id, and an id outside their layout is refused."""
import pytest
from models.reports.templates import notebook_templates, template_notebook
def test_the_cacu_templates_are_listed_with_the_scenarios_they_serve():
"""Pins down: CaCu's subgroup reports are listed; the PIM one serves every scenario whose dataflow lists its
report, the survival one only its own. Fails if a template stops being found or its scenarios stop following the
`model.toml` modules."""
found = {t["id"]: t for t in notebook_templates("cacu")}
pim, survival = found["cacu/cin2_pim/reporte_subgrupos"], found["cacu/survival/reporte_subgrupos"]
assert pim["scenarios"] == ["cancer_pim", "cin2_pim", "cin2_pim_post_colposcopy", "cin2_pim_post_treatment"]
assert survival["scenarios"] == ["survival"] and survival["domain"] == "cacu" and survival["title"]
def test_a_template_is_read_by_its_id():
"""Pins down: an id gives the template's name and its notebook (nbformat 4). Fails if the id stops naming the
file under `models/<domain>/<scenario>/notebooks/`."""
name, notebook = template_notebook("cacu/survival/reporte_subgrupos")
assert name == "reporte_subgrupos" and notebook["nbformat"] == 4 and notebook["cells"]
@pytest.mark.parametrize("template_id, error", [
("cacu/survival/../../io/x", ValueError), ("cacu/../../etc/passwd", ValueError), ("otro/survival/x", ValueError),
("cacu/survival/no_existe", LookupError), ("", ValueError),
])
def test_an_id_outside_the_templates_is_refused(template_id, error):
"""Pins down: an id with other characters, another domain, or no such file is refused before anything is read.
Fails if a crafted id reaches a file outside the templates."""
with pytest.raises(error):
template_notebook(template_id)
+35
View File
@@ -0,0 +1,35 @@
"""An invented ADOS-2 association cohort: one row per child in the `tea` library's cohort columns, with two planted
effects (spikes in temporal_izq raise item 18, spindles in central lower the CSS) and everything else null."""
import numpy as np
import pandas as pd
from tea.associations.ados2 import _items as items
from tea.contracts import ZONES
ITEM_CODES = sorted({c for _, _, codes in items.ITEMS.values() for c in codes.values()})
def cohort(n: int = 60, seed: int = 4, with_items: bool = True) -> pd.DataFrame:
rng = np.random.default_rng(seed)
age = rng.uniform(16, 37, n).round(1)
module = np.where(age < 31, "TODDLER", np.where(rng.random(n) < .7, "MODULO_1", "MODULO_2"))
t = pd.DataFrame({"key": [f"e-{i:03d}" for i in range(n)], "age_months": age, "ados_module": module})
shared = rng.normal(0, 1, n)
for zone in ZONES:
t[f"z_spikes_{zone}"] = (.5 * shared + .85 * rng.normal(0, 1, n)).round(3)
t[f"z_spindles_{zone}"] = rng.normal(0, 1, n).round(3)
t["z_posterior_rhythm"] = rng.normal(0, 1, n).round(3)
t["z_gradient"] = rng.normal(0, 1, n).round(3)
for number, (_, _, codes) in items.ITEMS.items():
latent = rng.logistic(0, 1, n) + (1.6 * t["z_spikes_temporal_izq"].to_numpy() if number == 18 else 0)
level = np.digitize(latent, [-.3, 1.4, 3.2])
for m, code in codes.items():
if code not in t:
t[code] = np.nan
t.loc[t.ados_module == m, code] = level[t.ados_module.to_numpy() == m]
severity = rng.normal(0, 1, n) - .9 * t["z_spindles_central"].to_numpy()
t["css"] = np.clip(np.round(6 + 1.8 * severity), 1, 10).astype(int)
for code in ITEM_CODES:
if code not in t:
t[code] = np.nan
return t if with_items else t.drop(columns=ITEM_CODES)
+141
View File
@@ -0,0 +1,141 @@
"""What this module covers: the `tea` library's ADOS-2 association (`tea.associations.ados2`, modern, and
`tea.legacy.associations.ados2`, the research code vendored): the pairs it tests, the module-independent outcome
codes, recovery of planted effects, legacy and modern agreeing, the per-child scores and the saved state.
Fixtures: `cohort_items`, 60 invented children of 16 to 37 months (Toddler module under 31 months, Module 1 or 2
above) with item scores and a CSS, whose spike z in temporal_izq raises item 18 (intonation) and whose spindle z in
central lowers the CSS, everything else null; `cohort_css`, the same children without item scores; `fits`, both
implementations fitted once on each cohort.
"""
import numpy as np
import pandas as pd
import pytest
from ados2_cohort import ITEM_CODES, cohort
from tea.associations.ados2 import Ados2Association
from tea.associations.ados2 import _items as items
from tea.contracts import ASSOCIATION_COLUMNS, SCORE_COLUMNS, ZONES
from tea.legacy.associations.ados2 import LegacyAdos2Association
@pytest.fixture(scope="module")
def cohort_items():
"""60 children with item scores: spikes in temporal_izq raise item 18, spindles in central lower the CSS."""
return cohort()
@pytest.fixture(scope="module")
def cohort_css(cohort_items):
"""The same children with the CSS only, as when the psychologist reports no items."""
return cohort_items.drop(columns=[c for c in ITEM_CODES if c in cohort_items])
@pytest.fixture(scope="module")
def fits(cohort_items, cohort_css):
"""Modern and legacy, each fitted once on both cohorts, by (impl, level)."""
return {(impl, level): cls().fit(c) for impl, cls in (("modern", Ados2Association),
("legacy", LegacyAdos2Association))
for level, c in (("item", cohort_items), ("domain", cohort_css))}
def test_level_follows_the_cohort_and_codes_are_module_independent(fits):
"""Pins down: a cohort with items is fitted by item and one without by the CSS; item outcomes carry
`ados2_item_NN` and domain outcomes `CSS`, with events `>=1` and `>=8`; zones are the library's, `posterior`
or `global`. Fails if the level stops following the data, an outcome goes back to a per-module column code (one
code is another item in another module), or a zone code leaves the shared list."""
for impl in ("modern", "legacy"):
assert fits[impl, "item"].fitted["level"] == "item"
assert fits[impl, "domain"].fitted["level"] == "domain"
a = fits[impl, "item"].associations()
assert list(a.columns) == list(ASSOCIATION_COLUMNS)
assert set(a.outcome_code) <= {items.item_code(n) for n in items.ITEMS} | {"CSS"}
assert set(a.loc[a.kind == "item", "event"]) == {">=1"}
assert set(a.loc[a.kind == "domain", "event"]) == {">=8"}
assert set(a.zone) <= set(ZONES) | {"posterior", "global"}
assert set(fits[impl, "domain"].associations().outcome_code) == {"CSS"}
def test_the_planted_effects_are_found(fits):
"""Pins down: the item fit finds spikes in temporal_izq raising item 18 (odds ratio above 1, q < 0.05) and the CSS
fit finds spindles in central lowering the CSS (odds ratio below 1, q < 0.05). Fails if the Firth or ordinal fit,
the item read per module, or the q values break."""
a = fits["modern", "item"].associations().set_index(["biomarker", "zone", "outcome_code"])
item = a.loc[("spikes", "temporal_izq", "ados2_item_18")]
assert item.odds_ratio > 1 and item.q < .05
d = fits["modern", "domain"].associations().set_index(["biomarker", "zone", "outcome_code"])
css = d.loc[("spindles", "central", "CSS")]
assert css.odds_ratio < 1 and css.q < .05
@pytest.mark.parametrize("level", ["item", "domain"])
def test_legacy_and_modern_agree(fits, cohort_items, cohort_css, level):
"""Pins down: the modern port gives the vendored research code's odds ratios, intervals, p, q and per-child
probabilities exactly, at both levels. Fails if either side's design matrix, fit, interval search, FLIC
intercept or pair list drifts from the other."""
cohort = cohort_items if level == "item" else cohort_css
m, legacy = fits["modern", level], fits["legacy", level]
keys = ["biomarker", "zone", "outcome_code"]
joined = m.associations().merge(legacy.associations(), on=keys, suffixes=("_m", "_l"), validate="1:1")
assert len(joined) == len(m.associations()) == len(legacy.associations())
for c in ("odds_ratio", "ci_low", "ci_high", "p", "q", "sens_odds_ratio"):
np.testing.assert_allclose(joined[f"{c}_m"].astype(float), joined[f"{c}_l"].astype(float), rtol=1e-9)
scores = m.score(cohort).merge(legacy.score(cohort), on=["key", *keys], suffixes=("_m", "_l"), validate="1:1")
assert len(scores) == len(legacy.score(cohort)) > 0
np.testing.assert_allclose(scores.probability_m, scores.probability_l, atol=1e-9)
np.testing.assert_allclose(scores.reference_probability_m, scores.reference_probability_l, atol=1e-9)
def test_an_item_is_read_from_the_column_of_the_childs_module(cohort_items):
"""Pins down: item 11 (showing) is `sa_b12` in the Toddler module, `sa_b9` in Module 1 and `sa_b5` in Module 2,
and each child's score comes from its own module's column, with 3 as 2 and 7 as 0. Fails if items are read by
one column code for every module."""
t = pd.DataFrame({"ados_module": ["TODDLER", "MODULO_1", "MODULO_2", "MODULO_2"],
"sa_b12": [1, 2, 0, 0], "sa_b9": [0, 3, 0, 0], "sa_b5": [2, 0, 7, np.nan]})
assert items.item_scores(t, 11).tolist()[:3] == [1.0, 2.0, 0.0]
assert np.isnan(items.item_scores(t, 11).iloc[3])
def test_scores_cover_only_the_modules_with_the_item_and_survive_save_and_load(fits, cohort_items, tmp_path):
"""Pins down: a child is scored on an item only when its module has that item, every score row has a z and a
probability in [0, 1], and a saved and reloaded fit scores the same. Fails if scoring ignores the module, the
saved state misses what scoring needs, or the columns drift from `SCORE_COLUMNS`."""
m = fits["modern", "item"]
scores = m.score(cohort_items)
assert list(scores.columns) == list(SCORE_COLUMNS)
modules = cohort_items.set_index("key").ados_module
item_16 = scores[scores.outcome_code == "ados2_item_16"] # Module 2 only
assert set(modules[item_16.key]) <= {"MODULO_2"}
assert scores.probability.between(0, 1).all() and scores.z.notna().all()
m.save(tmp_path)
again = Ados2Association.load(tmp_path).score(cohort_items)
pd.testing.assert_frame_equal(scores, again)
def test_registered_under_the_association_groups():
"""Pins down: both implementations resolve through the entry points and pass the association protocol, and
the per-study pipeline does not load them. Fails if a registration is dropped or the association lands in the
pipeline's module groups."""
from tea.pipeline import registry
assert registry.association("ados2_association").impl == "modern"
assert registry.association("ados2_association", "legacy").impl == "legacy"
assert "ados2_association" not in registry.available("modern")
def test_a_module_the_fit_never_saw_is_not_scored_as_the_reference(fits, cohort_items):
"""Pins down: a child whose module was not in the pair's fit (here an unknown `MODULO_3`) gets no probability
instead of the reference module's. Fails if unseen levels fall back to all-zero indicators."""
m = fits["modern", "domain"]
other = cohort_items.head(3).assign(ados_module="MODULO_3", key=["x-1", "x-2", "x-3"])
assert m.score(other).empty
def test_a_singular_pair_or_an_infinite_z_does_not_stop_the_fit(cohort_css):
"""Pins down: a predictor equal to the module indicator (a rank-deficient design) leaves that pair with a reason
and no estimate while every other pair is fitted, and an infinite z is dropped rather than fitted. Fails if a
singular information matrix aborts the whole fit, or `inf` reaches the design."""
t = cohort_css.copy()
t["z_gradient"] = (t["ados_module"] == "TODDLER").astype(float)
t.loc[0, "z_posterior_rhythm"] = np.inf
a = Ados2Association().fit(t).associations().set_index(["biomarker", "zone"])
assert a["odds_ratio"].notna().sum() >= len(a) - 2
assert a.loc[("posterior_rhythm", "posterior"), "n"] == len(t) - 1
+140
View File
@@ -0,0 +1,140 @@
"""What this module covers: the ADOS-2 association against the TEA database (`models.ados2_relation`): the cohort
it builds from bronze (first valid EEG and first ADOS-2 per child), the rows it writes to `relacion_ados2` and
`relacion_ados2_paciente`, and versions (a new cohort is a later version, the same cohort writes nothing).
Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, the invented cohort of `ados2_cohort` without item
scores (60 children, spindles in central lowering the CSS) written to bronze: each child with an ADOS-2 and a valid
analysed EEG `e-NNN` whose metric z and zone z are the cohort's, plus a later valid EEG `e-000-b` of child 1, an
invalid EEG of child 2 and a child 99 with an EEG and no ADOS-2.
"""
from datetime import date, datetime
import pytest
from ados2_cohort import ITEM_CODES, cohort
from sqlmodel import Session, select
from core.tea.models import Ados2, Eeg, EegMetrica, EegMetricaZona, Pacientes, RelacionAdos2, RelacionAdos2Paciente
from models import ados2_relation as rel
from tea.contracts import ZONES
CODES = {"spikes": "PICOS_PAROXISTICOS", "spindles": "HUSOS_SUENO_N2", "posterior_rhythm": "RITMO_POSTERIOR",
"gradient": "GRADIENTE_ANTEROPOSTERIOR"}
def _eeg(session, eeg_id, pac_id, row, *, studied=date(2025, 6, 1), valid=1):
session.add(Eeg(eeg_id=eeg_id, eeg_pac_id=pac_id, eeg_fecha_estudio=studied, eeg_valido=valid,
eeg_edad_meses=float(row.age_months)))
for biomarker, code in CODES.items():
met_id = f"{eeg_id}/{code}"
zoned = biomarker in rel.ZONED
session.add(EegMetrica(met_id=met_id, met_eeg_id=eeg_id, met_codigo=code,
met_z=None if zoned else float(row[f"z_{biomarker}"])))
if zoned:
session.add_all([EegMetricaZona(mez_id=f"{met_id}/{z}", mez_met_id=met_id, mez_zona=z,
mez_z=float(row[f"z_{biomarker}_{z}"])) for z in ZONES])
def _engine():
from persistance.db import get_tea_engine
return get_tea_engine()
@pytest.fixture
def stored(tea_db):
"""The CSS-only invented cohort in bronze, with the extra EEGs and child the module docstring lists."""
t = cohort().drop(columns=ITEM_CODES)
with Session(_engine()) as s:
for i, row in t.iterrows():
pac_id = i + 1
s.add(Pacientes(pac_id=pac_id, pac_id_hospital=f"H-{pac_id}"))
s.add(Ados2(ado_id=f"a-{pac_id}", ado_pac_id=pac_id, ado_fecha=date(2025, 5, 1),
ado_modulo=row.ados_module, ado_css=int(row.css)))
_eeg(s, row.key, pac_id, row)
_eeg(s, "e-000-b", 1, t.iloc[0], studied=date(2025, 9, 1))
_eeg(s, "e-001-x", 2, t.iloc[1], studied=date(2025, 3, 1), valid=0)
s.add(Pacientes(pac_id=99, pac_id_hospital="H-99"))
_eeg(s, "e-099", 99, t.iloc[2])
s.commit()
return t
def _read():
with Session(_engine()) as s:
return s.exec(select(RelacionAdos2)).all(), s.exec(select(RelacionAdos2Paciente)).all()
def test_a_fit_writes_one_version_of_estimated_rows_on_the_platform_codes(stored):
"""Pins down: one fit writes a `tea-<time>-<fingerprint>` version, unvalidated, over the 60 children with a
valid EEG and an ADOS-2, with the metric codes, `CSS` outcomes and an `>=8` event, and finds the planted
spindle effect in central. Fails if the cohort takes the child without ADOS-2 or the invalid EEG, the
biomarker codes stop following `model.toml`, or the written estimates stop being the library's."""
summary = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
models, patients = _read()
assert summary.children == 60 and summary.level == "domain"
assert summary.version.startswith("tea-20261121T120000-") and len(summary.version) <= 32
assert {m.rel_version for m in models} == {summary.version} and len(models) == summary.associations
assert {m.rel_validado for m in models} == {0} and {m.rel_n_cohorte for m in models} == {60}
assert {m.rel_resultado for m in models} == {"CSS"} and {m.rel_evento for m in models} == {">=8"}
assert {m.rel_biomarcador for m in models} <= set(CODES.values())
central = next(m for m in models if m.rel_biomarcador == "HUSOS_SUENO_N2" and m.rel_zona == "central")
assert central.rel_or < 1 and central.rel_q < .05
assert len(patients) == summary.scored
def test_every_valid_eeg_of_the_cohort_is_scored_and_no_other(stored):
"""Pins down: child 1's later valid EEG gets probabilities too (the gold view shows the study's EEG, whichever
it is), while the invalid EEG and the EEG of the child without ADOS-2 get none. Fails if scoring stops at the
fit's EEGs or starts scoring outside the cohort."""
rel.relate()
_, patients = _read()
eegs = {p.rap_eeg_id for p in patients}
assert {"e-000", "e-000-b"} <= eegs
assert not {"e-001-x", "e-099"} & eegs
assert all(0 <= p.rap_probabilidad <= 1 and 0 <= p.rap_probabilidad_referencia <= 1 for p in patients)
def test_the_same_cohort_writes_nothing_and_a_new_one_is_a_later_version(stored):
"""Pins down: fitting the same cohort again writes nothing and names the latest version; a changed z is a new
version that sorts after the first, so the gold view's greatest version is the newest fit. Fails if reruns
duplicate versions, or the version stops sorting by time."""
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
again = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
assert again.unchanged and again.version == first.version
assert len({m.rel_version for m in _read()[0]}) == 1
with Session(_engine()) as s:
zone = s.get(EegMetricaZona, "e-000/HUSOS_SUENO_N2/central")
zone.mez_z = 3.0
s.add(zone)
s.commit()
later = rel.relate(at=datetime(2026, 11, 23, 12, 0, 0))
assert not later.unchanged and later.version > first.version
assert {m.rel_version for m in _read()[0]} == {first.version, later.version}
def test_an_open_interval_is_stored_as_null():
"""Pins down: an infinite interval limit (the profile never crossed the threshold) is stored as NULL, which every
engine accepts. Fails if `inf` reaches the database (MySQL and SQL Server reject it)."""
assert rel._finite(float("inf")) is None and rel._finite(None) is None and rel._finite(2.5) == 2.5
def test_the_fit_uses_the_first_eeg_with_predictors_and_a_new_eeg_is_a_new_version(stored):
"""Pins down: a child whose earliest valid EEG has no metric rows is fitted on its next EEG, and a valid EEG
added for a child already in the fit (so the fit table is the same) is still a new version that scores it.
Fails if the fit takes an EEG without predictors (the child would drop out of every model), or the fingerprint
covers only the fit table (the new EEG would stay unscored)."""
with Session(_engine()) as s:
s.add(Eeg(eeg_id="e-000-a", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 1, 1), eeg_valido=1,
eeg_edad_meses=20.0))
s.commit()
first = rel.relate(at=datetime(2026, 11, 21, 12, 0, 0))
assert first.children == 60
assert "e-000-a" not in {p.rap_eeg_id for p in _read()[1]}
with Session(_engine()) as s:
_eeg(s, "e-000-c", 1, stored.iloc[0], studied=date(2025, 12, 1))
s.commit()
later = rel.relate(at=datetime(2026, 11, 22, 12, 0, 0))
assert not later.unchanged and later.version > first.version
models, patients = _read()
latest = {m.rel_id for m in models if m.rel_version == later.version}
assert "e-000-c" in {p.rap_eeg_id for p in patients if p.rap_rel_id in latest}
+104
View File
@@ -0,0 +1,104 @@
"""What this module covers: the ADOS-2 totals, CSS and classification of `tea.scoring`, and the job that writes
them to the TEA database (`models.ados2_scoring`).
Fixtures: `tea_db` (an empty SQLite TEA database); `stored`, a child born 2022-01-01 with three Module 3 evaluations
(items summing to 12, no CSS), one Module 1 evaluation (some words, items summing to 6) and one evaluation that
already carries a CSS of 9 and a classification from its source.
"""
from datetime import date
import pytest
from sqlmodel import Session, select
from core.tea.models import Ados2, Pacientes
from models import ados2_scoring
from tea.scoring import score
ITEMS_12 = {"sa_b1": 2, "sa_b2": 2, "sa_b3": 2, "sa_b4": 2, "rrb_d1": 2, "rrb_d2": 2}
def test_a_score_of_three_counts_as_two():
"""Pins down: item scores above 2 are capped at 2, as the algorithms do. Fails if the cap is dropped (the
total would be 8, not 4)."""
s = score("MODULO_3", {"sa_b1": 3, "sa_b2": 3, "rrb_d1": 3, "rrb_d2": 3})
assert (s.social_affect, s.restricted_repetitive, s.total) == (4, 4, 8)
def test_the_css_rises_with_the_total_and_the_classification_follows_it():
"""Pins down: for one module a higher total never gives a lower CSS, and the classification is no-spectrum
under CSS 3, spectrum from 3 and autism from 5. Fails if a cut-point row stops being ordered or the
classification thresholds move."""
codes = [f"sa_b{i}" for i in range(1, 13)] + ["rrb_d1", "rrb_d2", "rrb_d4", "rrb_d5"]
scores = [score("MODULO_3", {c: 2 if i < n else 0 for i, c in enumerate(codes)}) for n in range(0, 17)]
css = [s.css for s in scores]
assert css == sorted(css) and css[0] == 1 and css[-1] == 10
assert [scores[0].classification, scores[3].classification, scores[8].classification] == [
"NO_ESPECTRO", "ESPECTRO_AUTISTA", "AUTISMO"]
@pytest.mark.parametrize("module, age, algorithm, expected", [
("MODULO_1", None, "Algunas palabras", None),
("MODULO_1", 40.0, None, None),
("MODULO_2", None, None, None),
("MODULO_3", None, None, 7),
])
def test_a_table_that_needs_age_or_language_level_gives_no_css_without_them(module, age, algorithm, expected):
"""Pins down: Modules 1 and 2 give no CSS without the child's age (and Module 1 without its algorithm), Module 3
needs neither. Fails if a missing age silently picks a table."""
assert score(module, ITEMS_12, age_months=age, algorithm=algorithm).css == expected
def test_the_toddler_module_gives_a_range_of_concern_and_no_css():
"""Pins down: Toddler totals become a classification by age band and never a CSS: a total of 12 is mild to
moderate at 25 months and at 19, 9 is none at 19 but mild to moderate at 25. Fails if Toddler starts
returning a CSS or the two age bands share cut points."""
t12 = {**{f"sa_b{i}": 2 for i in (1, 4, 5, 6)}, "rrb_d1": 2, "rrb_d2": 2}
t9 = {**{f"sa_b{i}": 2 for i in (1, 4, 5)}, "rrb_d1": 2, "rrb_d2": 1}
assert [score("TODDLER", t12, age_months=m).classification for m in (19, 25)] == ["PREOCUPACION_LEVE_MODERADA"] * 2
assert [score("TODDLER", t9, age_months=m).classification for m in (19, 25)] == [
"NO_ESPECTRO", "PREOCUPACION_LEVE_MODERADA"]
assert score("TODDLER", t12, age_months=25).css is None
def test_an_unknown_module_or_missing_domain_is_not_scored():
"""Pins down: no score without a known module or without items in both domains. Fails if a half-read PDF is
scored from one domain."""
assert score(None, ITEMS_12) is None
assert score("MODULO_9", ITEMS_12) is None
assert score("MODULO_3", {"sa_b1": 2}) is None
@pytest.fixture
def stored(tea_db):
"""Child 1 (born 2022-01-01) with the evaluations the module docstring lists."""
from persistance.db import get_tea_engine
with Session(get_tea_engine()) as s:
s.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2022, 1, 1)))
for i in (1, 2, 3):
s.add(Ados2(ado_id=f"a-{i}", ado_pac_id=1, ado_fecha=date(2026, 1, 1), ado_modulo="MODULO_3",
**{f"ado_{k}": v for k, v in ITEMS_12.items()}))
s.add(Ados2(ado_id="m1", ado_pac_id=1, ado_fecha=date(2025, 1, 1), ado_modulo="MODULO_1",
ado_algoritmo="Algunas palabras", ado_sa_a2=2, ado_sa_b1=2, ado_sa_b3=1, ado_rrb_d1=1))
s.add(Ados2(ado_id="given", ado_pac_id=1, ado_fecha=date(2026, 1, 1), ado_modulo="MODULO_3", ado_css=9,
ado_clasificacion="AUTISMO", **{f"ado_{k}": v for k, v in ITEMS_12.items()}))
s.commit()
yield s
def test_the_job_fills_what_is_empty_and_keeps_what_a_source_gave(stored):
"""Pins down: `score_all` writes CSS and classification on evaluations that lack them, uses the age at the
evaluation (3 years for the Module 1 one, so the under-five table) and leaves a stored CSS alone. Fails if it
overwrites a source's value by default or reads the wrong age."""
summary = ados2_scoring.score_all(stored)
assert (summary.evaluations, summary.scored) == (5, 4)
rows = {r.ado_id: r for r in stored.exec(select(Ados2)).all()}
assert rows["a-1"].ado_css == 7 and rows["a-1"].ado_clasificacion == "AUTISMO"
assert rows["m1"].ado_css == 3 and rows["m1"].ado_clasificacion == "ESPECTRO_AUTISTA"
assert rows["given"].ado_css == 9
def test_overwrite_recomputes_what_a_source_gave(stored):
"""Pins down: with `overwrite` the stored CSS is recomputed from the items. Fails if `overwrite` is ignored."""
ados2_scoring.score_all(stored, overwrite=True)
assert stored.get(Ados2, "given").ado_css == 7
+32
View File
@@ -0,0 +1,32 @@
"""Outside markers for centile and age-block references in modern and legacy tea.
Fixtures: parameterized baseline modules and in-memory synthetic control values.
"""
import numpy as np
import pytest
from tea.biomarkers.spindles import _baseline as modern
from tea.legacy.biomarkers.spindles import _baseline as legacy
@pytest.mark.parametrize("baseline", (modern, legacy))
def test_centile_outside_requires_a_reference(baseline):
"""Pin float -1/0/+1 and missing values. Fails if missing data, uncovered ages or sparse controls give zero."""
curve = baseline.CentileCurves().fit(np.tile([1, 2, 3], 50), np.repeat([12, 24, 36], 50))
outside, _ = curve.deviation([0, 2, 4, np.nan, 2, 2], [24, 24, 24, 24, 60, np.nan])
assert outside.dtype.kind == "f"
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan, np.nan])
sparse = baseline.CentileCurves().fit([1, 2], [12, 36])
assert np.isnan(sparse.deviation([2], [24])[0][0])
@pytest.mark.parametrize("baseline", (modern, legacy))
def test_age_block_outside_requires_a_z_score(baseline):
"""Pin float markers with a valid score. Fails if a missing score or degenerate MAD is classified in range."""
fitted = baseline.AgeBlockZ().fit(np.arange(30), np.full(30, 24))
outside, _ = fitted.deviation([-2, 15, 40, np.nan, 15], [24, 24, 24, 24, np.nan])
assert outside.dtype.kind == "f"
np.testing.assert_array_equal(outside, [-1, 0, 1, np.nan, np.nan])
flat = baseline.AgeBlockZ().fit(np.ones(30), np.full(30, 24))
assert np.isnan(flat.deviation([1], [24])[0][0])
+196
View File
@@ -0,0 +1,196 @@
"""Cover cluster probes using clean_environment, loopback_port and monkeypatch.
Fails if mode resolution, connection handling or independent probe results regress.
"""
import socket
from contextlib import nullcontext
from time import perf_counter
from types import SimpleNamespace
from unittest.mock import Mock
import distributed
import pytest
from tea.pipeline import cluster_status
from tea.pipeline.cluster_status import ClusterStatus
@pytest.fixture(autouse=True)
def clean_environment(monkeypatch):
"""Clear cluster configuration so machine settings cannot change probe targets or results."""
for variable in (
"DASK_SCHEDULER_ADDRESS",
"TEA_DASK_EXPECTED_WORKERS",
"TEA_DASK_DASHBOARD_URL",
"TEA_DASK_DASHBOARD_PORT",
):
monkeypatch.delenv(variable, raising=False)
@pytest.fixture
def loopback_port():
"""Reserve a loopback port so live probes cannot connect to another service."""
try:
port = socket.socket()
except PermissionError as exc:
pytest.skip(f"TCP sockets are unavailable: {exc}")
with port:
try:
port.bind(("127.0.0.1", 0))
except PermissionError as exc:
pytest.skip(f"Loopback binding is unavailable: {exc}")
yield port.getsockname()[1]
@pytest.mark.parametrize("mode", ["auto", "local", "sync"])
def test_non_remote_mode_does_not_connect(monkeypatch, mode):
"""Pin the full non-remote response. Fail if a client starts or a probe reports a value."""
client = Mock()
monkeypatch.setattr(distributed, "Client", client)
if mode != "auto":
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:8786")
assert ClusterStatus().check(mode) == {
"mode": "local" if mode == "auto" else mode,
"scheduler": None,
"reachable": True,
"workers": None,
"expected_workers": None,
"versions_ok": None,
"version_error": None,
"dashboard_ok": None,
"dashboard_url": None,
"reference": None,
"latency_ms": None,
"error": None,
}
client.assert_not_called()
def test_unreachable_scheduler_is_bounded(monkeypatch, loopback_port):
"""Pin failure on a closed TCP port. Fail if it raises or ignores the connection timeout."""
monkeypatch.setenv("TEA_DASK_DASHBOARD_PORT", str(loopback_port))
start = perf_counter()
status = ClusterStatus().check(scheduler=f"tcp://127.0.0.1:{loopback_port}")
assert perf_counter() - start < 9
assert status["mode"] == "remote"
assert status["reachable"] is False
assert status["error"]
assert status["workers"] is None
assert status["versions_ok"] is None
assert status["dashboard_ok"] is False
@pytest.mark.usefixtures("loopback_port")
def test_reachable_scheduler_reports_one_worker(monkeypatch):
"""Pin health on a real Dask worker. Fail if the client miscounts it or skips version checks."""
with distributed.LocalCluster(
n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0"
) as cluster:
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", cluster.scheduler_address)
monkeypatch.setenv("TEA_DASK_EXPECTED_WORKERS", "2")
port = cluster.scheduler.services["dashboard"].port
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", f"http://127.0.0.1:{port}/status")
monkeypatch.setenv("no_proxy", "127.0.0.1")
status = ClusterStatus().check()
assert status["scheduler"] == cluster.scheduler_address
assert status["reachable"] is True
assert status["workers"] == 1
assert status["expected_workers"] == 2
assert status["versions_ok"] is True
assert status["dashboard_ok"] is True
assert status["latency_ms"] >= 0
assert status["error"] is None
@pytest.mark.parametrize("dashboard_healthy", [True, False])
def test_version_mismatch_and_dashboard_are_independent(monkeypatch, dashboard_healthy):
"""Pin zero-worker and mismatch responses. Fail if either prevents an independent dashboard probe."""
client = Mock()
client.scheduler_info.return_value = {"workers": {}}
client.get_versions.side_effect = ValueError("version mismatch")
connect = Mock(return_value=client)
monkeypatch.setattr(distributed, "Client", connect)
if dashboard_healthy:
dashboard_url = "https://dashboard.example/status?view=all"
health_url = "https://dashboard.example/health"
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", dashboard_url)
open_health = Mock(return_value=nullcontext(SimpleNamespace(status=200)))
else:
dashboard_url = "http://scheduler:8787/status"
health_url = "http://scheduler:8787/health"
open_health = Mock(side_effect=TimeoutError)
monkeypatch.setattr(cluster_status, "urlopen", open_health)
status = ClusterStatus().check("remote", "tcp://scheduler:8786", "cohort")
assert status["reachable"] is True
assert status["error"] is None
assert status["workers"] == 0
assert status["versions_ok"] is False
assert status["version_error"] == "version mismatch"
assert status["dashboard_ok"] is dashboard_healthy
assert status["dashboard_url"] == dashboard_url
assert status["reference"] is None
connect.assert_called_once_with("tcp://scheduler:8786", timeout=5)
client.get_versions.assert_called_once_with(check=True)
client.submit.assert_not_called()
client.close.assert_called_once_with()
open_health.assert_called_once_with(health_url, timeout=3)
def test_warning_only_version_mismatch_is_reported(monkeypatch):
"""Pin mismatches returned by Dask without an exception. Fail if they count as compatible."""
client = Mock()
client.scheduler_info.return_value = {"workers": {"worker": {}}}
matching = {"packages": {"distributed": "2026.8.0"}}
client.get_versions.return_value = {
"scheduler": matching,
"client": matching,
"workers": {"worker": {"packages": {"distributed": "2026.9.0"}}},
}
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
status = ClusterStatus().check(scheduler="tcp://scheduler:8786")
assert status["versions_ok"] is False
assert "Mismatched versions found" in status["version_error"]
@pytest.mark.parametrize("name", ["cohort-1", "../escape", ".."])
def test_reference_submission_requires_safe_name(monkeypatch, name):
"""Pin worker-side reference lookup. Fail if an unsafe name is submitted or a valid count is lost."""
client = Mock()
client.scheduler_info.return_value = {"workers": {"worker": {}}}
client.submit.return_value.result.return_value = 3
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
status = ClusterStatus().check(scheduler="tcp://scheduler:8786", reference_name=name)
if name == "cohort-1":
client.submit.assert_called_once_with(cluster_status._count_edfs, name, pure=False)
assert status["reference"] == {"name": name, "edfs": 3}
else:
client.submit.assert_not_called()
assert status["reference"] is None
def test_local_workers_can_be_capped_by_the_environment(monkeypatch):
"""Pins down: `TEA_LOCAL_WORKERS` fixes the size of a local cluster, an explicit count still wins, and a value
below one means one worker.
Fails if a local run on a shared machine can no longer be limited from the environment.
"""
from tea.pipeline.dask_runner import local_workers
monkeypatch.setenv("TEA_LOCAL_WORKERS", "1")
assert local_workers() == 1
monkeypatch.setenv("TEA_LOCAL_WORKERS", "0")
assert local_workers() == 1
assert local_workers(n_workers=3) == 3
+78 -3
View File
@@ -1,9 +1,10 @@
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea` """What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
library. library, plus EEG selection and the CLI summary. Fails if explicit selection skips current studies or the CLI
stops reporting its final counts.
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
posterior channels flat; and bytes that are not an EDF. posterior channels flat; and bytes that are not an EDF. `selection_session` holds three EEG rows in SQLite.
""" """
import pytest import pytest
from synth_edf import edf_bytes from synth_edf import edf_bytes
@@ -18,7 +19,7 @@ FLAT = ["C3", "C4", "Cz", "P3", "P4", "Pz", "O1", "O2"]
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
def measured(): def measured():
"""The three studies' measurements, keyed `clean`, `flat` and `broken`; the clean child is 27.5 months old.""" """Measure clean, flat, and broken studies to expose changes in triage and metrics."""
s = settings() s = settings()
return { return {
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s), "clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
@@ -115,3 +116,77 @@ def test_channel_codes_lose_their_numbers():
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \ assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
"intermittent-bursts" "intermittent-bursts"
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows" assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
@pytest.fixture
def selection_session():
"""Store current, pending, and EDF-less EEGs to expose scope regressions."""
from sqlmodel import Session, create_engine
from core.tea.models import Eeg
engine = create_engine("sqlite://")
Eeg.__table__.create(engine)
with Session(engine) as session:
session.add_all([
Eeg(eeg_id="1", eeg_estudio=b"edf", eeg_plan_hash="current", eeg_versiones="current", eeg_valido=0),
Eeg(eeg_id="2"),
Eeg(eeg_id="3", eeg_estudio=b"edf"),
])
session.commit()
yield session
engine.dispose()
def test_explicit_ids_select_current_edfs(selection_session):
"""Pin explicit reanalysis. Fail if current EEGs are skipped or EDF-less and unrequested rows are selected."""
from models.eeg_analysis import pending_ids
options = {"plan_hash": "current", "versions": "current", "models": dict}
assert pending_ids(selection_session, **options) == ["3"]
assert pending_ids(selection_session, ids=[2, 1, 1], **options) == ["1"]
with pytest.raises(LookupError, match=r"8, 9"):
pending_ids(selection_session, ids=[1, 9, 8], **options)
@pytest.mark.parametrize("failed", [0, 1])
def test_analyze_cli_emits_summary_and_passes_ids(monkeypatch, capsys, failed):
"""Pin the final JSON line and failure status. Fail if explicit IDs or the failed count are ignored."""
import json
from models import eeg_analysis
from models.__main__ import main
def analyze(**options):
assert options == {"everything": False, "limit": None, "ids": ["1", "2"], "cluster": "sync"}
return eeg_analysis.Summary(pending=2, valid=1, not_valid=1 - failed, failed=failed)
monkeypatch.setattr(eeg_analysis, "analyze_pending", analyze)
assert main(["tea", "analyze", "--ids", "1,2", "--cluster", "sync"]) == failed
line = capsys.readouterr().out.splitlines()[-1]
assert line.startswith("summary: ")
assert json.loads(line.removeprefix("summary: ")) == {
"pending": 2, "valid": 1, "not_valid": 1 - failed, "failed": failed,
}
def test_explicit_ids_may_be_uuids(selection_session):
"""Pin that ids are matched as strings, so the UUID ids real EEGs carry select their rows. Fail if ids go back
to being parsed as integers."""
from core.tea.models import Eeg
from models.eeg_analysis import selected_ids
uuid = "ed257fbd-61d5-4c9c-bb72-00c4ec550961"
selection_session.add(Eeg(eeg_id=uuid, eeg_estudio=b"EDF"))
selection_session.commit()
assert selected_ids(selection_session, [uuid]) == [uuid]
with pytest.raises(LookupError, match="no-such-id"):
selected_ids(selection_session, [uuid, "no-such-id"])
@pytest.mark.parametrize("other", [["--all"], ["--limit", "2"]])
def test_analyze_cli_rejects_conflicting_scope(other):
"""Pin exit 2 for ambiguous scopes. Fail if an explicit ID request can start with another scope."""
from models.__main__ import main
assert main(["tea", "analyze", "--ids", "1", *other]) == 2
+28 -1
View File
@@ -144,7 +144,34 @@ def test_an_analysis_replaces_the_previous_one_with_the_same_ids(bronze, curves)
(1, "tea-eeg-posterior-rhythm/3") (1, "tea-eeg-posterior-rhythm/3")
assert metrics["HUSOS_SUENO_N2"].met_z is None and metrics["HUSOS_SUENO_N2"].met_modelo is None assert metrics["HUSOS_SUENO_N2"].met_z is None and metrics["HUSOS_SUENO_N2"].met_modelo is None
electrodes = sorted((e.mel_met_id, e.mel_electrodo, e.mel_valor) for e in _all(EegMetricaElectrodo)) electrodes = sorted((e.mel_met_id, e.mel_electrodo, e.mel_valor) for e in _all(EegMetricaElectrodo))
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3")) mapped = [m.code for m in settings().metrics if m.electrodes]
assert electrodes == sorted((metrics[code].met_id, "Fz", 1.5) for code in mapped)
@pytest.mark.parametrize("case", ("uncovered_age", "missing_cutoffs"))
def test_missing_reference_stores_null_outside(bronze, curves, case):
"""Pin SQL NULL when a reference interval is absent. Fails if a missing marker is cast to int or stored as zero."""
from persistance.tea import eeg_repository
age = 60.0
if case == "missing_cutoffs":
from tea.biomarkers.posterior_rhythm._baseline import AgeBlockZ
age = 26.0
reference = AgeBlockZ().fit([5.0, 6.0, 7.0], [age] * 3)
reference.state["cortes"] = [float("nan")] * 2
curves.module("eeg-posterior-rhythm").baseline = reference
measurement = fake_measure("e-1", b"edf", age, settings())
with eeg_repository.open_session() as session:
save(session, "e-1", rows(measurement, settings(), curves))
session.commit()
metric = next(row for row in _all(EegMetrica) if row.met_codigo == "RITMO_POSTERIOR")
assert metric.met_valor == 9.0
assert metric.met_modelo == "tea-eeg-posterior-rhythm/3"
assert metric.met_fuera is None
if case == "missing_cutoffs":
assert metric.met_z == pytest.approx(3.0 / 1.4826)
def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves): def test_the_batch_analyses_each_pending_eeg_once_and_logs_it(bronze, governance_db, curves):
+17
View File
@@ -184,3 +184,20 @@ def test_a_reference_study_is_measured_from_its_path(tmp_path):
assert (st.valid, st.error) == (1, None) assert (st.valid, st.error) == (1, None)
assert set(st.features) == set(settings().scenarios.values()) assert set(st.features) == set(settings().scenarios.values())
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features) assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)
def test_training_reads_the_cluster_choice_from_the_environment(monkeypatch):
"""Pins down: training measures its studies on the runner `EEG_ANALYSIS_CLUSTER` names, and falls back to `auto`
for an unset or unknown value (including `off`, which only the analysis understands).
Fails if `run_steps` stops passing the choice to `train_all`, or lets an unknown value reach the runner.
"""
from models.tea.eeg import model
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
assert model._cluster() == "auto"
for chosen in ("auto", "local", "remote", "sync"):
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", chosen)
assert model._cluster() == chosen
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "off")
assert model._cluster() == "auto"
+166
View File
@@ -0,0 +1,166 @@
"""What this module covers: the zone values of the EEG analysis (`models.tea.eeg.settings` zones,
`analyze._metrics`, `models.eeg_analysis.rows` and `save`): which metrics read zones, how a biomarker's
`<zone_prefix><zone>` features become a metric's zones, and the `eeg_metrica_zona` rows with the z of the zone's
baseline, replaced on the next analysis.
Fixtures: `tea_db` (an empty SQLite TEA database); `spike_zones`, `Baselines` whose only production version is
`tea-eeg-spikes/2`, a spikes module with one centile curve, 0.5/1/2 spikes per minute at p5/median/p95 at every age,
for `spike_zone_rate_nrem_temporal_izq` alone.
"""
from datetime import date
from types import SimpleNamespace
import pandas as pd
import pytest
from sqlmodel import select
from core.tea.models import Eeg, EegMetrica, EegMetricaZona, Pacientes
from models.eeg_analysis import rows, save
from models.tea.eeg.analyze import Measurement, MetricValue, _metrics
from models.tea.eeg.baselines import Baselines
from models.tea.eeg.settings import settings
from tea.contracts import ZONES
@pytest.fixture
def spike_zones():
"""Spikes in production with a curve for the temporal_izq zone feature only."""
from tea.biomarkers.spikes._baseline import CentileCurves
curve = pd.DataFrame({"edad_meses": [12.0, 36.0], "n_efectivo": [50.0] * 2, "p5": [0.5] * 2, "p25": [0.8] * 2,
"mediana": [1.0] * 2, "p75": [1.4] * 2, "p95": [2.0] * 2})
module = SimpleNamespace(baselines={"spike_zone_rate_nrem_temporal_izq": CentileCurves(curva=curve)})
class Registry:
def resolve(self, domain, scenario):
if scenario != "eeg-spikes":
raise LookupError(scenario)
return SimpleNamespace(version="2", model_uri="models:/tea-eeg-spikes/2")
return Baselines("tea", registry=Registry(), loader=lambda uri: module)
def test_spikes_and_spindles_read_zones_and_their_scenarios_are_trained():
"""Pins down: the spike metric reads `spike_zone_rate_nrem_<zone>` and the per-electrode `spike_density_nrem_<E>`
from spikes with `spike_minutes_nrem` as exposure, both spindle metrics read `spindle_zone_<zone>` from spindles
at their stage, and no scenario is added for them (the zone features train with the metric's own biomarker).
Fails if `model.toml` loses the zones the ADOS-2 association reads, or zones start a scenario of their own."""
s = settings()
by_code = {m.code: m for m in s.metrics}
spikes = by_code["PICOS_PAROXISTICOS"]
assert (spikes.zones, spikes.zone_prefix, spikes.electrodes, spikes.electrode_prefix) == (
"spikes", "spike_zone_rate_nrem_", "spikes", "spike_density_nrem_")
assert spikes.exposure == "spike_minutes_nrem"
assert spikes.zone_scenario == spikes.scenario == "eeg-spikes"
for code in ("HUSOS_SUENO_N2", "HUSOS_SUENO_N3"):
assert (by_code[code].zones, by_code[code].zone_prefix) == ("spindles", "spindle_zone_")
assert set(s.scenarios) == {"eeg-posterior-rhythm", "eeg-spindles-n2", "eeg-spindles-n3",
"eeg-spindle-topography-n2", "eeg-spindle-topography-n3", "eeg-spikes",
"eeg-gradient"}
def test_a_biomarkers_zone_features_become_the_metrics_zones():
"""Pins down: the features named `<zone_prefix><zone>` are the metric's zones by zone code, the electrode map
keeps its own prefix, and a feature whose name only starts like the prefix's biomarker is left out. Fails if
the prefix is not stripped or zone and electrode features mix."""
s = settings()
spikes = {"spike_rate_nrem": 0.7, "spike_density_nrem_T3": 1.2,
**{f"spike_zone_rate_nrem_{z}": float(i) for i, z in enumerate(ZONES)},
"spike_zone_rate_awake_central": 9.0, "spike_minutes_nrem": 12.5}
measured = {("posterior_rhythm", None): {}, ("spindles", "N2"): {}, ("spindles", "N3"): {},
("spindle_topography", "N2"): {}, ("spindle_topography", "N3"): {}, ("spikes", None): spikes,
("gradient", None): {}}
value = {v.code: v for v in _metrics(measured, s)}["PICOS_PAROXISTICOS"]
assert value.value == 0.7
assert value.electrodes == {"T3": 1.2}
assert value.zones == {z: float(i) for i, z in enumerate(ZONES)}
assert value.exposure == 12.5
def test_zone_rows_carry_the_zone_baselines_z_and_are_replaced(tea_db, spike_zones):
"""Pins down: each zone of a metric is an `eeg_metrica_zona` row of that metric, with the z of the zone's own
curve where one is in production and null elsewhere, and a new analysis replaces them. Fails if zone rows are
not written, read another feature's baseline, or pile up across analyses."""
from persistance.tea import eeg_repository
s = settings()
with eeg_repository.open_session() as session:
session.add_all([Pacientes(pac_id=1), Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2026, 3, 1))])
session.commit()
zones = {"temporal_izq": 2.0, "central": 1.0}
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
metrics=tuple(MetricValue(x.code, 1.0, {}, zones if x.code == "PICOS_PAROXISTICOS" else {})
for x in s.metrics))
for _ in range(2):
with eeg_repository.open_session() as session:
save(session, "e-1", rows(m, s, spike_zones))
session.commit()
with eeg_repository.open_session() as session:
found = {z.mez_zona: z for z in session.exec(select(EegMetricaZona)).all()}
met_id = session.exec(select(EegMetrica.met_id).where(EegMetrica.met_codigo == "PICOS_PAROXISTICOS")).one()
assert set(found) == {"temporal_izq", "central"}
assert {z.mez_met_id for z in found.values()} == {met_id}
assert found["temporal_izq"].mez_z == pytest.approx(1.645) and found["temporal_izq"].mez_valor == 2.0
assert found["central"].mez_z is None
def test_a_count_baseline_gets_the_metrics_minutes(tea_db):
"""Pins down: a baseline whose `deviation` takes `exposure` gets the metric's minutes for the value, every
electrode and every zone, and one without that parameter is called as before. Fails if the minutes stop reaching
count baselines (spike z would be computed against no exposure) or curves start receiving them."""
import numpy as np
seen = []
class Count:
def deviation(self, values, ages_months, exposure=None):
seen.append(float(exposure[0]))
return np.array([0.0]), np.array([1.0])
module = SimpleNamespace(baselines={"spike_rate_nrem": Count(), "spike_density_nrem_T3": Count(),
"spike_zone_rate_nrem_central": Count()})
class Registry:
def resolve(self, domain, scenario):
if scenario != "eeg-spikes":
raise LookupError(scenario)
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
s = settings()
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
metrics=tuple(MetricValue(x.code, 1.0, {"T3": 0.5}, {"central": 0.2}, 12.5)
if x.code == "PICOS_PAROXISTICOS" else MetricValue(x.code, 1.0)
for x in s.metrics))
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
assert seen == [12.5, 12.5, 12.5]
assert [z.mez_z for z in out.zones] == [1.0] and [e.mel_z for e in out.electrodes] == [1.0]
def test_a_count_baselines_range_is_its_own_for_the_minutes(tea_db):
"""Pins down: a baseline with `percentiles` gives the metric's p5, median and p95 from the metric's minutes, and
the metric row stores them, so a spike metric with a z has a reference range. Fails if count baselines lose their
range (the patient summary then refuses the EEG: a metric with a z and no reference)."""
import numpy as np
class Count:
def deviation(self, values, ages_months, exposure=None):
return np.array([0.0]), np.array([0.5])
def percentiles(self, ages_months, exposure):
return np.array([[0.0, 0.1, 0.4]]) * 10 / exposure[0]
module = SimpleNamespace(baselines={"spike_rate_nrem": Count()})
class Registry:
def resolve(self, domain, scenario):
if scenario != "eeg-spikes":
raise LookupError(scenario)
return SimpleNamespace(version="4", model_uri="models:/tea-eeg-spikes/4")
s = settings()
m = Measurement(key="e-1", age_months=24.0, plan_hash="h", versions="v", valid=1,
metrics=tuple(MetricValue(x.code, 1.0, {}, {}, 20.0) if x.code == "PICOS_PAROXISTICOS"
else MetricValue(x.code, 1.0) for x in s.metrics))
out = rows(m, s, Baselines("tea", registry=Registry(), loader=lambda uri: module))
spikes = next(r for r in out.metrics if r.met_codigo == "PICOS_PAROXISTICOS")
assert (spikes.met_p5, spikes.met_mediana, spikes.met_p95) == (0.0, 0.05, 0.2)
+163
View File
@@ -0,0 +1,163 @@
"""Cover optional, atomic progress reporting and ETA with temporary files and a fake clock.
Fails if monitoring changes unconfigured runs, publishes incomplete samples, or miscalculates throughput.
"""
import json
import time
import pytest
from distributed import Client, LocalCluster
from tea.pipeline import run_monitor
def test_monitor_without_directory(monkeypatch):
"""Pin the no-op monitor. Fail if an unconfigured run activates sampling."""
monkeypatch.delenv("RUN_PROGRESS_DIR", raising=False)
with run_monitor.monitor_from_env() as monitor:
monitor.start()
monitor.phase("analizando")
monitor.total(12)
monitor.advance()
assert run_monitor.active_monitor() is None
monitor.stop()
def test_local_cluster_progress(tmp_path, monkeypatch):
"""Pin live Dask telemetry and atomic snapshots. Fail if progress stalls, grows unbounded, or tears."""
path = tmp_path / "progress.json"
replace = run_monitor.os.replace
replacements = []
def verify_replace(source, target):
if target == path:
assert json.loads(source.read_text())["history"]
if path.exists():
assert json.loads(path.read_text())["history"]
replacements.append(source)
replace(source, target)
def read_until(predicate):
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
if path.exists():
progress = json.loads(path.read_text())
if predicate(progress):
return progress
time.sleep(0.01)
pytest.fail("Timed out waiting for progress")
monkeypatch.setattr(run_monitor.os, "replace", verify_replace)
with LocalCluster(n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0") as cluster:
with Client(cluster) as client, run_monitor.RunMonitor(tmp_path, interval=0.1, history=4) as monitor:
monitor.start(client, ("local", None))
monitor.total(10)
monitor.phase("midiendo")
initial = read_until(lambda p: p["phase"] == "midiendo" and p["tasks"] and p["cluster"]["workers"])
assert initial["done"] == 0 and initial["eta_s"] is None
assert set(initial["tasks"]) == {"processing", "waiting", "memory", "erred"}
assert initial["cluster"]["workers"][0]["threads"] == 1
monitor.advance(3)
measured = read_until(lambda p: p["done"] == 3 and len(p["history"]) == 4)
assert measured["eta_s"] > 0
monitor.advance(2)
monitor.phase("ajustando")
monitor.stop()
final = json.loads(path.read_text())
assert final["done"] == 5 and final["eta_s"] is None
assert final["phase"] == "ajustando"
assert len(final["history"]) == 4
assert final["history"][-1]["done"] == 5
assert len(replacements) >= 5
assert list(tmp_path.iterdir()) == [path]
def test_eta_smoothed_rate(tmp_path, monkeypatch):
"""Pin ETA arithmetic and its threshold. Fail if cumulative or instantaneous rate replaces smoothing."""
now = 100.0
monkeypatch.setattr(run_monitor, "monotonic", lambda: now)
monkeypatch.setattr(run_monitor.Thread, "start", lambda self: None)
monkeypatch.setenv("RUN_PROGRESS_DIR", str(tmp_path))
path = tmp_path / "progress.json"
with run_monitor.monitor_from_env() as monitor:
assert run_monitor.active_monitor() is monitor
monitor.phase("analizando")
monitor.total(20)
monitor.advance(2)
now += 2
monitor._write_sample()
first = json.loads(path.read_text())
assert first["eta_s"] is None
assert first["tasks"] is None and first["cluster"] is None
monitor.advance(4)
now += 2
monitor._write_sample()
assert json.loads(path.read_text())["eta_s"] == pytest.approx(14 / (0.3 * 2 + 0.7))
class _FakeClient:
"""A stand-in for a Dask client with one busy worker, whose status the test can flip."""
status = "running"
def scheduler_info(self):
return {"workers": {"tcp://w:1": {"name": "w", "nthreads": 1, "memory_limit": 1000,
"metrics": {"cpu": 90.0, "memory": 500, "executing": 1}}}}
def _wait_for(path, condition, seconds=5.0):
"""The last snapshot at `path` once `condition(snapshot)` holds, or fail after `seconds`."""
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if path.exists():
snapshot = json.loads(path.read_text())
if condition(snapshot):
return snapshot
time.sleep(0.02)
raise AssertionError(f"no snapshot matched: {path.read_text() if path.exists() else 'no file'}")
def test_the_cluster_figures_clear_when_the_client_is_released(tmp_path):
"""Pin that `release` drops the cluster and task figures from every later snapshot, including the final one.
Fail if a finished run keeps reporting its last CPU, RAM and task counts as if the cluster were still busy."""
path = tmp_path / "progress.json"
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
monitor.start(_FakeClient(), ("local", None))
busy = _wait_for(path, lambda s: s["cluster"] and s["cluster"]["cpu_pct"] == 90.0)
assert busy["cluster"]["workers"][0]["name"] == "w"
monitor.release()
cleared = _wait_for(path, lambda s: s["cluster"] is None)
assert cleared["tasks"] is None
monitor.stop()
final = json.loads(path.read_text())
assert final["cluster"] is None and final["tasks"] is None
def test_the_cluster_figures_clear_when_the_sampler_sees_a_closed_client(tmp_path):
"""Pin that a client closed without a `release` call still stops being reported on the next sample.
Fail if the sampler goes on writing the last figures of a client whose status is closed."""
path = tmp_path / "progress.json"
client = _FakeClient()
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
monitor.start(client, ("remote", "tcp://s:1"))
_wait_for(path, lambda s: s["cluster"] and s["cluster"]["scheduler"] == "tcp://s:1")
client.status = "closed"
_wait_for(path, lambda s: s["cluster"] is None and s["tasks"] is None)
monitor.stop()
def test_a_client_attached_later_is_reported_again(tmp_path):
"""Pin that releasing one client does not stop the next one (a run opens a cluster per phase) from reporting.
Fail if `release` leaves the monitor unable to take a new client."""
path = tmp_path / "progress.json"
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
first = _FakeClient()
monitor.start(first, ("local", None))
_wait_for(path, lambda s: s["cluster"] is not None)
monitor.release(first)
_wait_for(path, lambda s: s["cluster"] is None)
monitor.start(_FakeClient(), ("local", None))
_wait_for(path, lambda s: s["cluster"] is not None and s["cluster"]["cpu_pct"] == 90.0)
monitor.stop()
+99
View File
@@ -0,0 +1,99 @@
"""What this module covers: the spikes biomarker's baselines around the per-electrode and
per-zone features: training from a feature table that predates them, and loading a baseline
saved before they existed. Both implementations, modern and legacy.
Fixtures: `old_table`, a DataFrame with only the original seven study-wide spikes features and
an age column, as a reference cohort measured before the density features existed; `full_table`,
the same rows plus every current feature.
"""
import importlib
import json
import numpy as np
import pandas as pd
import pytest
ORIGINAL = ("spike_rate_awake", "spike_rate_nrem", "spike_nrem_activation", "spike_focus_frac",
"spike_laterality", "spike_frac_generalized", "spike_index_nrem")
MODULES = (("tea.biomarkers.spikes.api", "Spikes"),
("tea.legacy.biomarkers.spikes.api", "LegacySpikes"))
@pytest.fixture(scope="module")
def old_table():
"""Twelve synthetic children with only the study-wide spikes features and their ages."""
rng = np.random.default_rng(0)
t = pd.DataFrame({f: rng.uniform(0.0, 2.0, size=12) for f in ORIGINAL})
t["age_months"] = np.linspace(16.0, 36.0, 12)
return t
@pytest.fixture(scope="module")
def full_table(old_table):
"""`old_table` plus every per-electrode, per-zone and inherited feature the module has now."""
rng = np.random.default_rng(1)
t = old_table.copy()
cls = getattr(importlib.import_module(MODULES[0][0]), MODULES[0][1])
for f in cls.features:
if f not in t.columns:
t[f] = rng.uniform(0.0, 2.0, size=len(t))
return t
@pytest.mark.parametrize("path,name", MODULES)
def test_training_skips_features_the_table_lacks(path, name, old_table, tmp_path):
"""Pins down: training from a table without the new columns works, fits only the columns
it has, and saving then loading that baseline keeps predicting those features only.
Fails if `train` starts requiring the new columns, or if save/load stops round-tripping
a baseline that knows nothing about them.
"""
cls = getattr(importlib.import_module(path), name)
module = cls().train(old_table)
out = module.predict(old_table)
assert set(out.feature) == set(ORIGINAL)
module.save(tmp_path)
loaded = cls.load(tmp_path)
assert set(loaded.predict(old_table).feature) == set(ORIGINAL)
assert len(cls.features) > len(ORIGINAL)
@pytest.mark.parametrize("path,name", MODULES)
def test_a_baseline_saved_before_the_new_features_loads_and_predicts(path, name, old_table,
full_table, tmp_path):
"""Pins down: a baseline bundle written before the new features existed (no new
parameters in params.json, none of the new features in baseline.json) loads into the
current module and predicts; the new features simply have no baseline and are not
evaluated.
Fails if load starts requiring the new parameters, if a saved baseline stops being
readable after the feature list grows, or if predict evaluates a feature that has no
fitted baseline.
"""
cls = getattr(importlib.import_module(path), name)
cls().train(old_table).save(tmp_path)
params = json.loads((tmp_path / "params.json").read_text())
for k in ("vent_s", "rechazar_transitorio", "herencia_s"):
params.pop(k, None)
(tmp_path / "params.json").write_text(json.dumps(params))
loaded = cls.load(tmp_path)
out = loaded.predict(full_table)
assert set(out.feature) == set(ORIGINAL)
assert len(out) == len(full_table) * len(ORIGINAL)
@pytest.mark.parametrize("path,name", MODULES)
def test_a_full_baseline_round_trips(path, name, full_table, tmp_path):
"""Pins down: with every column present, train fits all features and save/load predicts
the same deviations.
Fails if the per-electrode and per-zone features stop getting their own baselines when
the training table has them.
"""
cls = getattr(importlib.import_module(path), name)
module = cls().train(full_table)
before = module.predict(full_table)
assert set(before.feature) == set(cls.features)
module.save(tmp_path)
after = cls.load(tmp_path).predict(full_table)
pd.testing.assert_frame_equal(before, after)
+142
View File
@@ -0,0 +1,142 @@
"""What this module covers: the count reference of spike candidates (`_baseline.CountRate` of both spikes modules)
and how `Spikes` / `LegacySpikes` use it: the aggregate rate and its dispersion, a child's z from the tail of its
own count in its own minutes, NaN without exposure, the per-electrode zone scale, and which features it serves.
Fixtures: `count_rate`, parametrized over the modern and legacy `CountRate` classes; `reference`, 200 invented
children of 16 to 36 months with 5 to 15 clean NREM minutes and Poisson candidates at 0.02 per minute (most have
none), as rates.
"""
import numpy as np
import pandas as pd
import pytest
from scipy import stats
from tea.biomarkers.spikes import _baseline as modern_baseline
from tea.biomarkers.spikes import api as modern
from tea.legacy.biomarkers.spikes import _baseline as legacy_baseline
from tea.legacy.biomarkers.spikes import api as legacy
@pytest.fixture(params=["modern", "legacy"])
def count_rate(request):
"""The implementation's `CountRate` class."""
return {"modern": modern_baseline, "legacy": legacy_baseline}[request.param].CountRate
@pytest.fixture
def reference():
"""(rates, ages, minutes) of 200 children with Poisson candidates at 0.02 per minute."""
rng = np.random.default_rng(3)
minutes = rng.uniform(5, 15, 200).round(2)
counts = rng.poisson(0.02 * minutes)
return counts / minutes, rng.uniform(16, 36, 200), minutes
def test_the_reference_is_the_aggregate_rate_with_its_dispersion(count_rate):
"""Pins down: the rate is all candidates over all minutes of the children within the ages (one child of 50
months left out) and the dispersion is the research code's moments estimate, Poisson (inf) without excess.
Fails if the rate becomes a mean of per-child rates, the age range stops filtering, or the moments change."""
rates = np.array([0, 0.1, 0.2, 0])
b = count_rate().fit(rates, np.array([20, 20, 30, 50.0]), exposure=np.array([10, 10, 20, 30.0]))
assert b.state["rate"] == pytest.approx(5 / 40) and b.state["reference"] == 3 and b.state["events"] == 5
n, mu = np.array([0, 1, 4]), 5 / 40 * np.array([10, 10, 20])
excess = ((n - mu) ** 2 - n).sum()
assert b.state["k"] == (pytest.approx((mu ** 2).sum() / excess) if excess > 0 else np.inf)
flat = count_rate().fit(np.array([0.1, 0.1]), np.array([20, 20.0]), exposure=np.array([10, 10.0]))
assert flat.state["k"] == np.inf
def test_a_count_is_judged_in_its_own_minutes(count_rate, reference):
"""Pins down: no candidates is a mildly negative z (never -inf), the same one candidate is rarer in fewer
minutes, many candidates in few minutes are outside +1 with a large z, and z is the normal quantile of the mid-p
tail. Fails if z stops using the child's minutes, the mid-p correction, or the 0.05 cut for `outside`."""
b = count_rate().fit(*reference[:2], exposure=reference[2])
outside, z = b.deviation(np.array([0.0, 1 / 5, 1 / 40, 8 / 5]), np.full(4, 24.0),
exposure=np.array([10.0, 5.0, 40.0, 5.0]))
assert -1 < z[0] < 0
assert z[1] > z[2]
assert outside.tolist() == [0.0, 0.0, 0.0, 1.0] and z[3] > 3
mu = b.state["rate"] * 5.0
tail = stats.poisson.sf(0, mu) if np.isinf(b.state["k"]) else stats.nbinom.sf(0, b.state["k"],
b.state["k"] / (b.state["k"] + mu))
at = (stats.poisson.pmf(1, mu) if np.isinf(b.state["k"])
else stats.nbinom.pmf(1, b.state["k"], b.state["k"] / (b.state["k"] + mu)))
assert z[1] == pytest.approx(stats.norm.ppf(1 - (tail - at / 2)))
def test_no_exposure_value_age_or_reference_is_nan(count_rate, reference):
"""Pins down: without minutes, with zero minutes, without a value, at an age outside the range, or against a
reference with no minutes, z and outside are NaN, and a reference with no candidates at all clips z instead of
reaching infinity. Fails if any of them reads as within the reference, or `inf` leaves the baseline."""
b = count_rate().fit(*reference[:2], exposure=reference[2])
outside, z = b.deviation(np.array([0.1, 0.1, np.nan, 0.1]), np.array([24, 24, 24, 60.0]),
exposure=np.array([np.nan, 0.0, 10.0, 10.0]))
assert np.isnan(z).all() and np.isnan(outside).all()
assert np.isnan(b.deviation(np.array([0.1]), np.array([24.0]))[1]).all()
empty = count_rate().fit(np.array([0.1]), np.array([24.0]), exposure=np.array([np.nan]))
assert np.isnan(empty.deviation(np.array([0.1]), np.array([24.0]), exposure=np.array([10.0]))[1]).all()
none = count_rate().fit(np.zeros(5), np.full(5, 24.0), exposure=np.full(5, 10.0))
assert none.deviation(np.array([0.5]), np.array([24.0]), exposure=np.array([10.0]))[1][0] == count_rate.Z_MAX
def test_the_reference_range_is_the_rates_expected_in_the_childs_minutes(count_rate, reference):
"""Pins down: the p5, median and p95 of a count reference are the reference count's quantiles in the child's own
minutes (times the zone scale) as rates, ordered, narrower in rate with more minutes, and NaN where z is NaN.
Fails if the range stops using the child's minutes or the scale, or a child without minutes gets one (the
patient summary shows it as the metric's reference)."""
b = count_rate(scale=2.0).fit(*reference[:2], exposure=reference[2])
out = b.percentiles(np.array([24.0, 24.0, 24.0, 60.0]), np.array([5.0, 400.0, np.nan, 10.0]))
mu, k = b.state["rate"] * 400.0 * 2.0, b.state["k"]
p95 = stats.poisson.ppf(0.95, mu) if np.isinf(k) else stats.nbinom.ppf(0.95, k, k / (k + mu))
assert out[1, 2] == pytest.approx(p95 / 800.0)
assert (np.diff(out[:2], axis=1) >= 0).all()
assert out[1, 2] - out[1, 0] < out[0, 2] - out[0, 0] or out[0, 2] == 0
assert np.isnan(out[2:]).all()
def test_round_trip_and_scale(count_rate, reference):
"""Pins down: `to_dict` / `from_dict` keep the state and the scale, and a per-electrode zone value is counted
back through its electrodes (0.1 per minute per electrode over 3 electrodes in 10 minutes is 3 candidates).
Fails if the scale is lost on save or not applied."""
b = count_rate(scale=3.0).fit(*reference[:2], exposure=reference[2])
again = count_rate.from_dict(b.to_dict())
args = (np.array([0.1]), np.array([24.0]))
assert again.deviation(*args, exposure=np.array([10.0]))[1] == pytest.approx(
b.deviation(*args, exposure=np.array([10.0]))[1])
assert again.scale == 3.0
counts, exposure = b._counts(np.array([0.1]), np.array([10.0]))
assert counts.tolist() == [3.0] and exposure.tolist() == [30.0]
@pytest.mark.parametrize("module", [modern, legacy], ids=["modern", "legacy"])
def test_the_rates_are_counted_against_their_minutes(module, reference):
"""Pins down: every rate and density feature (overall, per electrode, per zone, unnormalised zone, inherited)
has a count baseline whose exposure is the minutes of its own state and variant, the minutes themselves have no
baseline, and the other spike features keep the configured one; a table without the minutes gives NaN for the
counted features. Fails if a rate falls back to centile curves (collapsed at 0 in the reference) or reads
another state's minutes."""
spikes = (module.Spikes if module is modern else module.LegacySpikes)()
assert set(module.EXPOSURE) == {f for f in module.FEATURES if f.startswith(
("spike_rate_", "spike_density_", "spike_zone_", "spike_inherited_rate_", "spike_inherited_zone_"))}
assert all(module.EXPOSURE[f].endswith(("_nrem" if "nrem" in f else "_awake")) for f in module.EXPOSURE)
assert not set(module.MINUTES) & set(module.FEATURES)
assert {spikes.baselines[f].name for f in module.EXPOSURE} == {"count_rate"}
assert spikes.baselines["spike_laterality"].name == "curves"
rates, ages, minutes = reference
table = pd.DataFrame({"spike_rate_nrem": rates, "spike_minutes_nrem": minutes, "age_months": ages})
spikes.train(table)
out = spikes.predict(table.iloc[:3]).set_index("feature")
assert out.loc["spike_rate_nrem", "z"].notna().all()
blind = spikes.predict(table.iloc[:3].drop(columns="spike_minutes_nrem")).set_index("feature")
assert blind.loc["spike_rate_nrem", "z"].isna().all()
def test_legacy_and_modern_count_alike(reference):
"""Pins down: both implementations' count baselines give the same reference and the same z. Fails if one copy
of `CountRate` drifts from the other."""
rates, ages, minutes = reference
a = modern_baseline.CountRate().fit(rates, ages, exposure=minutes)
b = legacy_baseline.CountRate().fit(rates, ages, exposure=minutes)
assert a.state == b.state
np.testing.assert_array_equal(a.deviation(rates, ages, exposure=minutes)[1],
b.deviation(rates, ages, exposure=minutes)[1])
+424
View File
@@ -0,0 +1,424 @@
"""What this module covers: the spikes biomarker's density features: only useful candidates
count (a field and no vertex/POSTS/ocular mark), the per-electrode and per-zone density per
state, the 0-vs-NaN convention, and the inherited-state variant where a stretch without a
clean-window state takes the nearest labeled window's state (30 s, conservative on
transitions, never before the stable start). Both implementations, modern and legacy, are
exercised and must agree.
Fixtures: synthetic in-memory studies built around 1/f noise with spike waveforms injected
(`density_study`: 40 field spikes at C3 in sleep and 20 isolated artifacts on O2 in wake;
`rejected_study`: all sleep, a 20 s stretch the QC left without a state, and 20 s annotated
as crying; `edge_study`: a single clean sleep window at 10-14 s with one field spike at 13 s;
`montage_study`: sleep windows at 2-6 s and 30-34 s with field spikes at 10 s, 24 s and 31 s)
and a quiet all-wake study. Nothing comes from a patient.
"""
import contextlib
import importlib
import io
import numpy as np
import pandas as pd
import pytest
FS = 250.0
DUR = 600.0
SCALP = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
C3_NEIGHBORS = ("F3", "T3", "Cz", "P3")
DENSITY_MODULES = ("tea.biomarkers.spikes._density", "tea.legacy.biomarkers.spikes._density")
def _fondo(n, n_ch, rng):
"""1/f noise at ~20 µV per channel, as the director's spike-detector validation uses."""
f = np.fft.rfftfreq(n, 1 / FS)
f[0] = f[1]
out = np.empty((n, n_ch))
for j in range(n_ch):
esp = (1.0 / f) * np.exp(1j * rng.uniform(0, 2 * np.pi, len(f)))
y = np.fft.irfft(esp, n)
out[:, j] = y / np.std(y) * 20.0
return out
def _punta(dur_ms=50.0, amp=120.0, post=60.0):
"""A spike with its slow posterior wave, as the director's criterion 3 describes."""
n = int(dur_ms * FS / 1000)
t = np.linspace(-1, 1, max(n, 3))
p = amp * (1 - t ** 2) ** 2
m = int(0.30 * FS)
s = -post * np.sin(np.pi * np.linspace(0, 1, m))
return np.concatenate([p, s])
def _add_spikes(x, rng, canal, spans, field):
"""`spikes` per (start_s, end_s) span on `canal`, with the field on its 10-20 neighbors
when `field`, as one simultaneous discharge."""
idx = {c: i for i, c in enumerate(SCALP)}
pun = _punta()
for a, b, k in spans:
for t in np.sort(rng.uniform(a, b, k)):
i = int(t * FS)
x[i:i + len(pun), idx[canal]] += pun
if field:
for v in C3_NEIGHBORS:
x[i:i + len(pun), idx[v]] += 0.6 * pun
return x
def _study(x, labels, annotations=()):
"""The contracts' Study around an in-memory (samples, channels) µV array: one variant,
4 s windows at a 2 s step labeled by sleep_state, and the annotated states as
annotation_mask events (the same annotations ride the variant for the legacy adapter,
whose director code translates them itself)."""
import mne
from tea.contracts import Labels, Preprocessed, Study
from tea.processes.annotation_mask.api import state_of
n = x.shape[0]
raw = mne.io.RawArray(x.T * 1e-6, mne.create_info(SCALP[: x.shape[1]], FS, ch_types="eeg"),
verbose="error")
anns = [(float(t0), float(d), e) for t0, d, e in annotations]
if anns:
onsets, durs, descs = zip(*anns)
raw.set_annotations(mne.Annotations(list(onsets), list(durs), list(descs)))
starts = np.arange(0.0, n / FS - 4.0 + 1e-9, 2.0)
windows = pd.DataFrame({"start_s": starts, "end_s": starts + 4.0, "clean": True, "gap": False})
prep = Preprocessed(variants={"hp05_prom": raw}, windows=windows, age_months=24.0,
plan={"name": "synthetic"}, plan_hash="synthetic")
sleep_state = Labels("sleep_state",
per_window=pd.Series(labels, index=windows.index, name="vigilancia"))
events = pd.DataFrame([{"onset_s": t0, "duration_s": d, "estado": state_of(e)}
for t0, d, e in anns if state_of(e)],
columns=["onset_s", "duration_s", "estado"])
annotation_mask = Labels("annotation_mask", events=events)
return Study(prep, {"sleep_state": sleep_state, "annotation_mask": annotation_mask})
def _labels_for(edits):
"""A 600 s window at 2 s step labeled 'sueno' everywhere, with `edits` {start_s: label}."""
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
labels = np.full(len(starts), "sueno", dtype=object)
for t0, e in edits.items():
labels[starts == float(t0)] = e
return list(labels)
@pytest.fixture(scope="module")
def density_study():
"""Half sleep, half wake: 40 spikes with field at C3 in the sleep half, 20 isolated
artifacts on O2 in the wake half (no field: they must not count as useful)."""
rng = np.random.default_rng(5)
x = _fondo(int(DUR * FS), len(SCALP), rng)
x = _add_spikes(x, rng, "C3", [(200.0, 290.0, 40)], field=True)
solo = _punta(dur_ms=50.0, amp=150.0, post=0.0)
idx = {c: i for i, c in enumerate(SCALP)}
for t in np.sort(rng.uniform(310.0, 590.0, 20)):
i = int(t * FS)
x[i:i + len(solo), idx["O2"]] += 1.4 * solo
starts = np.arange(0.0, DUR - 4.0 + 1e-9, 2.0)
labels = np.where(starts < 300.0, "sueno", "vigilia")
return _study(x, labels)
@pytest.fixture(scope="module")
def rejected_study():
"""All sleep: 6 spikes in a 20 s stretch the QC left without a state (150-170 s), 6 in
clean sleep, 6 in a stretch annotated as crying (400-420 s)."""
rng = np.random.default_rng(8)
x = _fondo(int(DUR * FS), len(SCALP), rng)
x = _add_spikes(x, rng, "C3", [(152.0, 168.0, 6), (200.0, 216.0, 6), (402.0, 418.0, 6)],
field=True)
labels = _labels_for({t0: "sin_estado" for t0 in range(148, 170, 2)})
return _study(x, labels, annotations=((400.0, 20.0, "Llanto"),))
@pytest.fixture(scope="module")
def wake_study():
"""Two quiet minutes of wake: no spike, no sleep."""
rng = np.random.default_rng(2)
labels = ["vigilia"] * len(np.arange(0.0, 120.0 - 4.0 + 1e-9, 2.0))
return _study(_fondo(int(120 * FS), len(SCALP), rng), labels)
@pytest.fixture(scope="module")
def edge_study():
"""One minute with a single clean sleep window at 10-14 s and one field spike at 13 s:
inside the 4 s window the state was classified on, beyond the 2 s grid step."""
rng = np.random.default_rng(11)
x = _fondo(int(60 * FS), len(SCALP), rng)
x = _add_spikes(x, rng, "C3", [(12.9, 13.1, 1)], field=True)
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
labels = np.full(len(starts), "sin_estado", dtype=object)
labels[starts == 10.0] = "sueno"
return _study(x, list(labels))
@pytest.fixture(scope="module")
def montage_study():
"""One minute with clean sleep windows at 2-6 s and 30-34 s and field spikes at 10 s
(unlabeled gap before the stable start), 24 s (unlabeled gap after it) and 31 s
(inside the second window)."""
rng = np.random.default_rng(13)
x = _fondo(int(60 * FS), len(SCALP), rng)
x = _add_spikes(x, rng, "C3", [(9.9, 10.1, 1), (23.9, 24.1, 1), (30.9, 31.1, 1)],
field=True)
starts = np.arange(0.0, 60.0 - 4.0 + 1e-9, 2.0)
labels = np.full(len(starts), "sin_estado", dtype=object)
labels[starts == 2.0] = "sueno"
labels[starts == 30.0] = "sueno"
return _study(x, list(labels))
def _measure(impl, study, **kwargs):
path = "tea.legacy.biomarkers.spikes.api" if impl == "legacy" else "tea.biomarkers.spikes.api"
cls = getattr(importlib.import_module(path), "LegacySpikes" if impl == "legacy" else "Spikes")
return cls(**kwargs).measure(study)
@pytest.fixture(scope="module")
def measured_density(density_study):
"""The density study measured by both implementations, {'modern': {...}, 'legacy': {...}}."""
return {impl: _measure(impl, density_study) for impl in ("modern", "legacy")}
@pytest.fixture(scope="module")
def measured_rejected(rejected_study):
"""The rejected-stretch study measured by both implementations."""
return {impl: _measure(impl, rejected_study) for impl in ("modern", "legacy")}
def test_useful_candidates_map_to_c3_and_the_central_zone(measured_density):
"""Pins down: with field spikes at C3 in sleep, the NREM density lands on C3 and the
central zone (per electrode, so it divides by the zone's 3 electrodes), every other
electrode is exactly 0, and the isolated wake artifacts on O2 count nowhere.
Fails if candidates without a field start counting, if canal_max stops being the
electrode a discharge is attributed to, or if the zone density stops being normalised
per electrode.
"""
m = measured_density["modern"]
assert m["spike_rate_nrem"] > 0
# the density divides by the unrounded minutes (the por_canal convention) and the
# rate by the two-decimal minutes (the indicadores convention), so they can differ
# by that rounding
assert m["spike_density_nrem_C3"] == pytest.approx(m["spike_rate_nrem"], rel=0.01)
assert m["spike_density_nrem_C3"] > 10 * max(m["spike_rate_awake"], 0.01)
for e in SCALP:
esperado = m["spike_rate_nrem"] if e == "C3" else 0.0
assert m[f"spike_density_nrem_{e}"] == pytest.approx(esperado, rel=0.01), e
assert m["spike_zone_nrem_central"] == pytest.approx(m["spike_rate_nrem"] / 3, rel=0.01)
assert m["spike_zone_nrem_frontal_izq"] == 0.0
assert m["spike_zone_nrem_occipital"] == 0.0
assert m["spike_density_awake_O2"] == 0.0
def test_a_quiet_present_electrode_is_zero_and_a_state_without_minutes_is_nan(wake_study):
"""Pins down: an electrode present with no candidates reads 0, never NaN, while a state
with no clean minutes (no sleep in an all-wake study) makes every feature of that state
NaN, inherited ones included.
Fails if the densities stop distinguishing 'no candidates' (0) from 'no denominator'
(NaN), or if the inherited variant stops honouring the same convention.
"""
m = _measure("modern", wake_study)
for e in SCALP:
assert m[f"spike_density_nrem_{e}"] != m[f"spike_density_nrem_{e}"] # NaN
assert m[f"spike_density_awake_{e}"] == 0.0
for z in ("central", "occipital", "temporal_der"):
assert m[f"spike_zone_nrem_{z}"] != m[f"spike_zone_nrem_{z}"]
assert m[f"spike_zone_awake_{z}"] == 0.0
assert m[f"spike_inherited_zone_nrem_{z}"] != m[f"spike_inherited_zone_nrem_{z}"]
assert m["spike_inherited_rate_nrem"] != m["spike_inherited_rate_nrem"]
assert m["spike_inherited_rate_awake"] == pytest.approx(0.0)
@pytest.mark.parametrize("module", DENSITY_MODULES)
def test_absent_electrode_and_zone_are_nan(module):
"""Pins down: an electrode missing from the montage has a NaN density (it cannot be
measured), and a zone with no present electrode is NaN too.
Fails if absent electrodes start reading as a measured 0.
"""
mod = importlib.import_module(module)
ev = pd.DataFrame({"canal_max": ["C3", "C3"], "fase": ["sueno", "sueno"],
"vertice": [False, False], "posts": [False, False],
"ocular": [False, False], "vecinos": [2, 2]})
out = mod.electrode_densities(ev, {"sueno": 2.0}, electrodes=("C3", "T6"), present=("C3",))
assert out["spike_density_nrem_C3"] == pytest.approx(1.0)
assert out["spike_density_nrem_T6"] != out["spike_density_nrem_T6"]
zonas = mod.zone_densities(ev, {"sueno": 2.0}, present=("C3",))
assert zonas["spike_zone_nrem_central"] == pytest.approx(1.0)
assert zonas["spike_zone_nrem_temporal_der"] != zonas["spike_zone_nrem_temporal_der"]
@pytest.mark.parametrize("module", DENSITY_MODULES)
def test_states_inherit_from_the_nearest_labeled_window(module):
"""Pins down (port of the research repo's inheritance test): a stretch the QC left
unlabeled takes the nearest clean window's state up to 30 s away; farther, or before
the first labeled window (or `t_min`), it stays without a state; intervals never
overlap.
Fails if the 30 s reach, the nearest-window rule or the `t_min` floor stop being
applied.
"""
mod = importlib.import_module(module)
t0 = np.r_[np.arange(20, 40, 2.0), np.arange(60, 98, 2.0), np.arange(200, 240, 2.0)]
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": "sueno"})
v = mod.inherit_states(labeled, 300.0, inherit_s=30.0, t_min=15.0)
def etq(t):
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
return (v.etiqueta[m].iloc[0], bool(v.heredado[m].iloc[0])) if m.any() else (None, None)
assert etq(30) == ("sueno", False) # clean window
assert etq(50) == ("sueno", True) # 20 s gap between clean windows
assert etq(120) == ("sueno", True) # 20 s after the last clean window
assert etq(150) == (None, None) # more than 30 s away from both
assert etq(18) == (None, None) # before the first clean window (t_min 15)
assert not (v.t_ini_s.to_numpy()[1:] < v.t_fin_s.to_numpy()[:-1]).any()
@pytest.mark.parametrize("module", DENSITY_MODULES)
def test_inheritance_is_conservative_across_state_transitions(module):
"""Pins down (port of the research repo's conservative-transition test): an unlabeled
stretch between two different states stays 'transicion' and counts in neither; between
two windows of the same state it inherits that state.
Fails if the transition rule starts assigning one of the two states.
"""
mod = importlib.import_module(module)
t0 = np.r_[np.arange(0, 40, 2.0), np.arange(60, 100, 2.0), np.arange(110, 150, 2.0)]
e = np.r_[["somnolencia"] * 20, ["sueno"] * 20, ["sueno"] * 20]
labeled = pd.DataFrame({"t_ini_s": t0, "t_fin_s": t0 + 2.0, "etiqueta": e})
v = mod.inherit_states(labeled, 160.0)
def etq(t):
m = (v.t_ini_s <= t) & (t < v.t_fin_s)
return v.etiqueta[m].iloc[0] if m.any() else None
assert etq(45) == "transicion" and etq(58) == "transicion"
assert etq(105) == "sueno"
assert etq(30) == "somnolencia" and etq(70) == "sueno"
@pytest.mark.parametrize("module", DENSITY_MODULES)
def test_candidate_category_marks_isolated_and_marked(module):
"""Pins down: a candidate is 'util' only with a field and no mark; the director's mark
order (posts, vertice, ocular) wins over 'aislado'.
Fails if the category rule starts counting marked or fieldless candidates as useful.
"""
mod = importlib.import_module(module)
ev = pd.DataFrame({"vecinos": [2, 0, 3, 1, 0],
"posts": [False, False, True, False, False],
"vertice": [False, False, False, True, False],
"ocular": [False, False, False, False, True]})
assert list(mod.candidate_category(ev)) == ["util", "aislado", "posts", "vertice", "ocular"]
def test_rejected_stretch_counts_only_when_inherited(measured_rejected):
"""Pins down (port of the research repo's rejected-window test): spikes in a stretch
the QC left without a state count in NREM only through inheritance — the direct rate
sees only the clean-stretch spikes — and spikes in a stretch annotated as crying count
nowhere, because the detector's own gate rejects those windows.
Fails if the inherited variant starts using the direct states, or if annotated states
stop gating the detector.
"""
for m in measured_rejected.values():
assert 0 < m["spike_rate_nrem"] < m["spike_inherited_rate_nrem"]
assert m["spike_inherited_rate_nrem"] == pytest.approx(2 * m["spike_rate_nrem"], rel=0.2)
assert m["spike_inherited_zone_nrem_central"] > m["spike_zone_nrem_central"]
assert m["spike_inherited_rate_awake"] != m["spike_inherited_rate_awake"] # no wake
def test_without_inheritance_the_inherited_variant_matches_the_direct(rejected_study):
"""Pins down: with the inheritance reach at 0 the inherited variant reduces to the
direct one (same candidates, same minutes).
Fails if the inherited run stops deriving its states from the inheritance intervals.
"""
m = _measure("modern", rejected_study, herencia_s=0.0)
assert m["spike_inherited_rate_nrem"] == pytest.approx(m["spike_rate_nrem"], rel=1e-9)
assert m["spike_inherited_zone_nrem_central"] == pytest.approx(m["spike_zone_nrem_central"],
rel=1e-9)
@pytest.mark.parametrize("impl", ("modern", "legacy"))
def test_candidate_inside_the_classified_window_counts_as_direct(impl, edge_study):
"""Pins down (the reviewer's 13 s scenario): a candidate at 13 s with a single clean
4 s sleep window starting at 10 s lies inside the window's own state, so the direct
NREM rate counts it (1 spike over the 4 clean gate minutes of [10, 14)); the inherited
run labels 13 s as direct too and only stretches [14, 44) inherit.
Fails if `_vig` shortens the state windows to the 2 s grid step again: the spike would
fall outside every window, the direct rate would read 0 and only the inherited run
would count it.
"""
m = _measure(impl, edge_study)
assert m["spike_rate_nrem"] == pytest.approx(14.286, abs=0.001) # 1 / 0.07 rounded minutes
assert m["spike_density_nrem_C3"] == pytest.approx(15.0, abs=0.01) # 1 over 4/60 unrounded
assert m["spike_inherited_rate_nrem"] == pytest.approx(1.754, abs=0.001)
@pytest.mark.parametrize("impl", ("modern", "legacy"))
def test_no_inherited_state_before_the_stable_start(impl, montage_study):
"""Pins down (the reviewer's stable-start scenario): with the stable start at 20 s,
the spike at 10 s — in the gap after an early labeled window but before the stable
start — gets no state anywhere, while the spike at 24 s inherits and the spike at
31 s is direct. The direct run sees only 31 s (0.13 clean sleep minutes, rate 7.692);
the inherited run counts 24 s and 31 s but not 10 s (0.73 minutes, rate 2.74). With
the default stable start of 0 the 10 s spike inherits as well (0.97 minutes, 3.093).
Fails if `measure` stops passing the stable start to the inheritance (the 10 s spike
would count in the inherited rate) or if the early window's reach is clamped wrongly.
"""
m = _measure(impl, montage_study, stable_start_s=20.0)
assert m["spike_rate_nrem"] == pytest.approx(7.692, abs=0.001)
assert m["spike_inherited_rate_nrem"] == pytest.approx(2.74, abs=0.001)
sin_montaje = _measure(impl, montage_study)
assert sin_montaje["spike_inherited_rate_nrem"] == pytest.approx(3.093, abs=0.001)
@pytest.mark.parametrize("impl", ("modern", "legacy"))
def test_crying_annotation_rejects_gate_windows(impl, rejected_study):
"""Pins down (port of the research repo's annotated-window test): the detector's 2 s
gate rejects the windows of the crying stretch and nothing else.
Fails if annotated states stop reaching the quality gate (the crying spikes would then
count as sleep).
"""
if impl == "modern":
from tea.biomarkers.spikes import _density
from tea.biomarkers.spikes.api import Spikes
module = Spikes()
est, canales = module._prepare(rejected_study)
gate = _density.gate_windows(est, canales, module.vent_s, module.rechazar_transitorio)
else:
from tea.legacy.biomarkers.spikes import _adapter, _density
from tea.legacy.biomarkers.spikes._director import eeg_io
module = _density
with _adapter.estudio(rejected_study.prep, "hp05_prom", eeg_io) as est, \
contextlib.redirect_stdout(io.StringIO()):
gate = _density.gate_windows(est, eeg_io, 2.0, False)
lloro = gate.motivo.str.contains("estado llanto", regex=False)
assert lloro.sum() >= 8 and not gate[lloro].apta.any()
assert gate[~lloro].apta.all()
def test_legacy_and_modern_agree_on_every_feature(measured_density, measured_rejected):
"""Pins down: both implementations expose the same 79 features with the same values on
the same study, old and new alike.
Fails if one implementation's port of the detector, the densities or the inheritance
drifts from the other's.
"""
for nombre, medido in (("density", measured_density), ("rejected", measured_rejected)):
moderno, legado = medido["modern"], medido["legacy"]
assert set(moderno) == set(legado)
for f, v in moderno.items():
otro = legado[f]
iguales = v == otro or (np.isnan(v) and np.isnan(otro))
assert iguales or v == pytest.approx(otro, rel=1e-6, abs=1e-12), (nombre, f, v, otro)
+154
View File
@@ -0,0 +1,154 @@
"""Spindle detection and summaries, plus loading partial spindle baselines.
Fixtures: `sleep_recording` supplies synthetic EEG with short, long or sustained
sigma bursts. `tmp_path` holds a saved spindle baseline.
"""
from types import SimpleNamespace
import numpy as np
import pandas as pd
import pytest
from tea.biomarkers.spindles.api import Spindles
from tea.legacy.biomarkers.spindles.api import LegacySpindles
from tea.legacy.processes.spindle_detection.api import LegacySpindleDetection
from tea.processes.spindle_detection.api import SpindleDetection
CHANNELS = "Fp1 Fp2 F7 F3 Fz F4 F8 T3 C3 Cz C4 T4 T5 P3 Pz P4 T6 O1 O2".split()
FS = 250
DENSITY = "spindle_density_per_min_channel"
NO_LONG = "spindle_density_per_min_channel_no_long"
@pytest.fixture
def sleep_recording():
"""Make 600 s of sleep on the 10-20 montage with selectable sigma bursts."""
def make(mode):
rng = np.random.default_rng(1)
duration = 600
freq = np.fft.rfftfreq(duration * FS, 1 / FS)
freq[0] = freq[1]
voltages = np.empty((duration * FS, len(CHANNELS)))
for i in range(len(CHANNELS)):
spectrum = np.exp(1j * rng.uniform(0, 2 * np.pi, len(freq))) / freq
background = np.fft.irfft(spectrum)
voltages[:, i] = background * (20 / background.std())
def inject(start, length, hz, amplitude, gains):
t = np.arange(int(length * FS)) / FS
envelope = np.hanning(len(t)) if length < 2 else np.clip(np.minimum(t, length - t) / 0.5, 0, 1)
wave = amplitude * envelope * np.sin(2 * np.pi * hz * t)
for channel, gain in gains.items():
a = int(start * FS)
voltages[a:a + len(t), CHANNELS.index(channel)] += gain * wave
short = dict.fromkeys(("F3", "F4", "C3", "C4", "Cz"), 1.0) | {"Fz": 0.8, "P3": 0.7, "P4": 0.7}
starts = np.arange(5, duration - 10, 9.0)
if mode != "empty":
for start in starts + rng.uniform(-1, 1, len(starts)):
if mode == "long" and (200 < start < 240 or 400 < start < 410):
continue
inject(start, 1, 12.5, 50, short)
if mode == "long":
inject(205, 25, 13, 60, {"C3": 1, "C4": 1, "Cz": 1, "F3": 0.8, "F4": 0.8})
inject(402, 5, 12, 60, {"Fz": 1, "F3": 0.6, "F4": 0.6})
if mode == "continuous":
inject(0, duration * 0.6, 13, 60, short)
if mode == "empty":
voltages.fill(0)
class Raw:
n_times = len(voltages)
ch_names = CHANNELS
info = {"sfreq": FS}
annotations = ()
def get_channel_types(self):
return ["eeg"] * len(self.ch_names)
def get_data(self, picks):
return voltages[:, [self.ch_names.index(name) for name in picks]].T / 1e6
windows = pd.DataFrame({"start_s": np.arange(0, duration, 4.0)})
return SimpleNamespace(variant=lambda _: Raw(), windows=windows)
return make
IMPLEMENTATIONS = ((SpindleDetection, Spindles), (LegacySpindleDetection, LegacySpindles))
def measure(prep, implementation, phase="N2"):
detector, biomarker = implementation
labels = {"sleep_state": SimpleNamespace(per_window=["sueno"] * len(prep.windows)),
"slow_wave_staging": SimpleNamespace(per_window=["N2"] * len(prep.windows))}
study = SimpleNamespace(prep=prep, label=labels.__getitem__)
labels["spindle_detection"] = detector(phase=phase).predict(study)
return biomarker().measure(study), labels["spindle_detection"].events
def test_long_runs_split_events_and_density(sleep_recording):
"""Pin long/extreme counts and the existing density. Fails if split events disappear from the old density."""
prep = sleep_recording("long")
outputs = []
for implementation in IMPLEMENTATIONS:
result, events = measure(prep, implementation)
assert ((events.channel == "C3") & events.onset_s.between(204, 231)).sum() >= 6
assert result["spindle_n_long_runs"] == 6
assert result["spindle_n_extreme"] == 5
assert 24 <= result["spindle_max_run_s"] <= 27
assert result[DENSITY] == round(len(events) / 10 / 13, 3)
assert result[NO_LONG] < result[DENSITY]
outputs.append(result)
for feature in ("spindle_n_long_runs", "spindle_n_extreme", "spindle_max_run_s",
"spindle_sigma_occupancy_median", "spindle_sigma_occupancy_max", NO_LONG):
assert outputs[0][feature] == pytest.approx(outputs[1][feature], abs=0.01)
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
def test_short_bursts_and_sustained_sigma(sleep_recording, implementation):
"""Pin zero long runs with short spindles and occupancy with sustained sigma. Fails if occupancy uses event thresholds."""
short, _ = measure(sleep_recording("short"), implementation)
sustained, _ = measure(sleep_recording("continuous"), implementation)
assert short["spindle_n_long_runs"] == short["spindle_n_extreme"] == 0
assert short[NO_LONG] == short[DENSITY]
assert short["spindle_sigma_occupancy_max"] < 0.45
assert sustained["spindle_sigma_occupancy_max"] >= 0.55
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
def test_spindle_density_by_electrode_and_zone(sleep_recording, implementation):
"""Pin event counts per sleep minute and per searched electrode, NaN on a channel the detector never searches
(O1, and so the occipital zone). Fails if empty searched channels are omitted, an unsearched channel reports a
density, or a phase leaks."""
prep = sleep_recording("short")
result, events = measure(prep, implementation)
counts = events.channel.value_counts()
assert counts["C3"] > 0 and counts["Fz"] > 0
assert result["spindle_electrode_C3"] == counts["C3"] / 10
assert np.isnan(result["spindle_electrode_O1"])
assert np.isnan(result["spindle_zone_occipital"])
assert result["spindle_zone_central"] == counts[["C3", "Cz", "C4"]].sum() / 30
other_phase, _ = measure(prep, implementation, phase="N3")
assert all(np.isnan(value) for value in other_phase.values())
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
def test_sleep_without_spindles_is_nan(sleep_recording, implementation):
"""Pin missing outputs on event-free sleep. Fails if any feature reports a value without a detected spindle."""
result, events = measure(sleep_recording("empty"), implementation)
assert events.empty and events.attrs["searched"]
assert all(np.isnan(value) for value in result.values())
@pytest.mark.parametrize("biomarker", (Spindles, LegacySpindles))
def test_spindle_baselines_load_without_new_features(tmp_path, biomarker):
"""Pin save/load of a single-feature baseline. Fails if train or predict requires all current feature columns."""
table = pd.DataFrame({"age_months": [12, 24, 36], DENSITY: [0.1, 0.2, 0.3]})
module = biomarker(baseline_params={"n_min": 1}).train(table)
module.save(tmp_path)
loaded = biomarker.load(tmp_path)
assert list(loaded.baselines) == [DENSITY]
assert loaded.predict(table).feature.tolist() == [DENSITY] * len(table)
+30
View File
@@ -0,0 +1,30 @@
"""What this module covers: `models.dags.estimation.estimate_frame`, from a model's output to the estimate's rows.
Fixtures: none; a two-member cohort frame built in each test.
"""
from datetime import date
import numpy as np
import pandas as pd
from models.dags.estimation import estimate_frame
COHORT = pd.DataFrame({"pac_id": [1, 2], "fecha_indice": [date(2025, 1, 1), date(2025, 2, 1)]})
def test_a_member_the_model_cannot_place_has_no_rows():
"""Pins down: a member whose risk is NaN (a combination unseen in training) is left out and the rest keep their
rows, so one such member doesn't stop the whole batch. Fails if the NaN reaches the estimate's contract."""
found = estimate_frame(COHORT, np.array([[0.1, 0.2], [np.nan, np.nan]]), [0.0, 1.0])
assert found["pac_id"].tolist() == [1, 1] and found["probabilidad"].tolist() == [0.1, 0.2]
def test_with_intervals_the_unplaced_member_is_left_out_too():
"""Pins down: with intervals, the risk block decides who is scored and each kept row has its two ends. Fails if
the blocks are read in another order or a NaN end drops a member that has a risk."""
output = np.array([[0.1, 0.05, 0.2], [np.nan, np.nan, np.nan]])
found = estimate_frame(COHORT, output, [1.0], intervals=True)
assert found[["pac_id", "probabilidad", "ic_bajo", "ic_alto"]].values.tolist() == [[1, 0.1, 0.05, 0.2]]
+11 -3
View File
@@ -75,11 +75,19 @@ def test_each_row_becomes_one_risk_at_its_horizon():
(2, d2, 3.0, 0.23, None, None)] (2, d2, 3.0, 0.23, None, None)]
def test_a_risk_keeps_the_interval_the_model_gave():
"""Pins down: an estimate with `ic_bajo` and `ic_alto` stores them with each risk, and NaN (a member the model
couldn't bound) is stored as no interval. Fails if `risk_rows` drops the interval or stores NaN."""
frame = _estimate((1, 2)).assign(ic_bajo=[0.05, float("nan")], ic_alto=[0.2, float("nan")])
assert [row[4:] for row in risk_rows(frame)] == [(0.05, 0.2), (None, None)]
@pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]), @pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]),
_estimate().rename(columns={"probabilidad": "p"})]) _estimate().rename(columns={"probabilidad": "p"}),
_estimate().assign(ic_bajo=[0.2, 0.1, 0.3], ic_alto=[0.3, 0.3, 0.4])])
def test_a_malformed_estimate_stops_the_batch(frame): def test_a_malformed_estimate_stops_the_batch(frame):
"""Pins down: a member scored twice at one horizon, a probability outside 0..1, or other columns stop the batch """Pins down: a member scored twice at one horizon, a probability outside 0..1, other columns, or an interval that
before anything is written. Fails if any of them reaches the database.""" doesn't hold its risk stop the batch before anything is written. Fails if any of them reaches the database."""
with pytest.raises(ValueError): with pytest.raises(ValueError):
risk_rows(frame) risk_rows(frame)