Compare commits

...

17 Commits

Author SHA1 Message Date
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
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
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 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
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 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
37 changed files with 2545 additions and 77 deletions
+4 -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/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`) and their hashes (`file_sha256`, `table_sha256`, `cohort_reference`), dbt's manifest (`read_queries`), Persistance repositories, the risk batches, and the cohort sources a model trains and estimates on: `KitBuild`, a kit build read now from the domain's database (nothing written), or `CohortFile`, an exported file, behind one contract (`frame`, `lineage`, `reference`). |
| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the code's version (the installed `models` package, `code_version`), a model's hash (`model_sha`), and `matches`, the one rule for "already done". |
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `run_files`/`run_file` list and download a run's files (a folder as a zip). |
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), the `models` version, and `log_model` with its `modelo_sha` (a scikit-learn estimator, served through `predict_proba`, or a pyfunc). In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. `log_routine` records what each routine around training did, as it runs (ML-01a): one JSON per kind in `ROUTINE_KINDS` (MUESTREO, DATOS_FALTANTES, METODO_ANALITICO, BALANCE_CLASES, CONFIANZA_SALIDA) under `rutinas/`, counts and settings only. `log_analysis` keeps what a run found about its cohort as `analisis/<name>.json`, and `log_report` a self-contained page as `reportes/<name>.html` (aggregates only). `run_files`/`run_file` list and download a run's files (a folder as a zip). |
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03, y ML-01a/ML-01b: las cinco rutinas y el modelo, escritos por la propia corrida) y el alias `produccion`. `artifacts`/`artifact` listan y descargan los archivos de una versión (ML-01b). Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). |
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
@@ -30,13 +30,15 @@ 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. |
| `io/extraction_ranker.py` | Each domain's document extraction ranker (`extraction.nlp.ranking.LearnedRanker`) as the model `<domain>-extraccion`: every batch it learns from (an answer key, or the corrections made while reviewing an import) is a new DEV version continuing the latest, with its five routine records, its weights (`ranker/ranker.json`) and its saved model. `current` gives the version in production, otherwise the latest; `EXTRACTION_RANKER=produccion` only takes production, `ninguno` turns it off. Weights over how candidates were found and counts only, never document text. |
| `notebook.py` | What a notebook uses inside: `experiment()` gives the build's rows (`cohort()`), its metadata, the chosen version loaded (`model()`), a DEV `TrainingRun` linked to the build (`training_run()`) and `register(run)`. |
| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. |
| `io/adapters.py` | Hamilton's boundary with storage and MLflow, attached by the driver with `with_materializers`: the loaders `cohort_source` and `cohort_source_lineage` (any source) and the saver `registered_model`, which logs a scenario's `fitted_model` in the open `TrainingRun`, its `routines`, `population` (`analisis/`) and `reports` (`reportes/`) when the dataflow has them, records its `metrics` (numbers only) and config, registers and describes the version. The packages of the model's own classes are pickled by value, so a version loads without this repository. |
| `annotations.py` | Validators a dataflow puts on its nodes, with no I/O: `@checked_frame(schema)`, a pandera check whose failure names columns and counts, never values. |
| `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. |
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit and its metrics. |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (`horizons_years`, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. `model.toml` (names, `modules`: its `model.py` and `steps/model_fitting.py`, and `[config]`) and `model.py` (the dataflow to `labelled_members`, and `fitted_model`: a scikit-learn `Pipeline` that takes the long frame). Its routines' records (ML-01a: `sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`) are nodes too, and the saver writes them; `train.py` only delegates to `dags/training.py`. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--read db|file] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]`, by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
| `cacu/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull or I-spline incidence, `likelihood.py`), one mixture per HPV stratum, fitted to each member's code and interval; the clinical settings (windows, known-negative results, KPNC's cytology categories, the incidence family) in `model.toml`. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `cacu/cin2_pim/report.py` | The subgroup report of every PIM scenario: per combination of the model's features, Turnbull's interval-censored estimate (prevalent at 0, free in `(l, r]`, unknown baseline in `[0, r]`) with a bootstrap band against the mixture refitted on every coded member with its delta-method band (inverse Hessian, log scale), and E/O at each horizon with log(E/O) taken as normal. `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. |
| `cacu/cin2_pim_post_colposcopy/`, `cacu/cin2_pim_post_treatment/` | `cin2_pim`'s dataflow on the post-colposcopy and post-treatment cohorts (KPNC's scenarios 4 and 5): only a `model.toml`, with KPNC's three post-colposcopy cytology groups and, after colposcopy, the referral grade (`history`). |
| `cacu/survival/` | CaCu's all-cause survival prototype: the mortality at 1, 3 and 5 years from the cancer diagnosis (provisionally the first biopsy reported as invasive carcinoma, `primera_biopsia_invasora` in `[config.index]`: both the inclusion criterion and the index date), from the age group at the diagnosis and the most recent cytology (KPNC's categories) and HPV up to it, with the SEER pipeline's interval survival as `cama/survival` runs it (LR and Bayesian network per interval, stacked) and its population record (`analisis/curvas.json`: KM with Greenwood, adjusted KM, Weibull, and LR/HBN/combined points with bootstrap intervals). The nodes that don't depend on the covariates are CaMa's, called from here; `encode`, `interval_cohort`, `IntervalSurvival`, `labelled_members`, `missing_data`, `analytic_method` and `survival_frame` are copies over CaCu's covariates (issue #9). A version also keeps a subgroup report (`report.py`): per combination of the covariates, the Kaplan-Meier with its Greenwood band against the model's survival with the SEER subgroups' bootstrap interval (`sv_sub_points`), as `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. The death is the timeline's `defuncion` event, emitted by the CaCu dbt timeline (monorepo, same branch). |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `<escenario>/notebooks/`, fuera del paquete instalado. |
| `tea/eeg/` | TEA's EEG analysis on one EDF, with the `tea` library (`libs/tea`, a submodule installed editable): `model.toml` maps each `MetricaEeg` code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); `analyze.measure` runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; `baselines.Baselines` compares a value with its age baseline in production (`tea-eeg-<biomarker>[-<stage>]`): z, -1/0/+1 and the curve's p5/median/p95 at the age. |
| `tea/eeg/train.py`, `tea/eeg/model.py` | TEA's age baselines: `python -m models run tea eeg --train [--promote] [--environment prod]` lists the reference cohort (`[reference]` of `model.toml`: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the `eeg-reference` extra), measures each study with the analysis's own unit of work (`analyze.reference`), and trains each scenario (biomarker and sleep stage) with the library, registered as `tea-eeg-<biomarker>[-<stage>]` through `tea.serving.log_biomarker` and tagged with what promotion checks: environment, the reference cohort (`cohort.source = referencia`, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI`); with a remote scheduler (`DASK_SCHEDULER_ADDRESS`), the workers need `models` and `tea` installed. |
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`).
"""
import copy
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from scipy.stats import norm
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
@@ -36,6 +39,10 @@ from models.io.contracts import DAYS_PER_YEAR
from models.steps import model_fitting
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]:
@@ -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=(),
incidence=None, levels=None):
incidence=None, levels=None, interval_level=None):
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.incidence = incidence
self.levels = levels
self.interval_level = interval_level
def _baseline(self, y: pd.DataFrame):
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())
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:
"""One column per horizon: CR(t). The column of t = 0 is the prevalence."""
risks = np.full((len(X), len(self.horizons_years)), np.nan)
"""One column per horizon: CR(t). The column of t = 0 is the prevalence. With `INDEX_COLUMN` in `X`, its days
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):
if key not in self.fits_:
continue
members = X.iloc[index]
placed = self._placed(members, self.seen_[key])
prevalence, incidence = self._design(members[placed], self.seen_[key])
risks[index[placed]] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence,
self.horizons_years)
rows = index[placed]
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
@@ -287,23 +337,76 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
return found
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing."""
RESULT_TYPES = ("bethesda", "glandular", "vph")
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.cytology = cytology
self.history = history
self.prediction_index = prediction_index
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
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,
history: dict) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`."""
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)),
("mixture", fitted_mixture)])
history: dict, risk_interval_level: float | None = None,
prediction_index: str | None = None) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`, giving each risk's interval at
`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.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"]
modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"]
description = """
Prototipo: riesgo acumulado de CIN2+ (biopsia LIEAG, CIS o carcinoma) en la visita índice y a 1, 3 y 5 años, con un \
modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \
@@ -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."""
# 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]
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"]
train_fraction = 0.7
# 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"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model", "models.steps.indexing"]
modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report", "models.steps.indexing"]
description = """
Prototipo: riesgo acumulado de CIN2+ desde la primera visita de vigilancia (co-test) después de una colposcopía sin CIN2+, en la visita y a \
1, 3 y 5 años (escenario 4 de ASCCP 2019; tabla 17 de KPNC). Mezcla prevalencia–incidencia con I-splines, una por grado \
@@ -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 \
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]
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"]
train_fraction = 0.7
prevalent_window_months = 6
+13 -2
View File
@@ -4,7 +4,7 @@ cohort = "cacu/cohorte_post_tratamiento"
outcome = "cin2"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The same dataflow as `cin2_pim`; only the cohort and the config change.
modules = ["models.cacu.cin2_pim.model"]
modules = ["models.cacu.cin2_pim.model", "models.cacu.cin2_pim.report"]
description = """
Prototipo: riesgo acumulado de CIN2+ desde la primera citología después del tratamiento, en la visita y a 1, 3 y 5 años \
(escenario 5 de ASCCP 2019; tablas 24 y 5 de KPNC). Mezcla prevalencia–incidencia con I-splines, una sola línea \
@@ -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 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]
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"]
train_fraction = 0.7
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}
+35 -13
View File
@@ -21,28 +21,52 @@ from models.io.lineage import matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import CohortSource, read_metadata, write_once
# 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:
"""Whether the output file already holds this version's scores of this build."""
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float]) -> pd.DataFrame:
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float],
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."""
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")
if probabilities.ndim != 2 or len(probabilities) != len(members):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members")
risks, dates = probabilities[:, -len(horizons):], members["fecha_indice"].to_numpy()
if probabilities.shape[1] == len(horizons) + 1:
width = len(horizons) * (3 if intervals else 1)
if probabilities.ndim != 2 or len(probabilities) != len(members) or probabilities.shape[1] not in (width, width + 1):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members and {len(horizons)} horizons"
+ (" with intervals" if intervals else ""))
risks, dates = probabilities[:, -width:], members["fecha_indice"].to_numpy()
if probabilities.shape[1] == width + 1:
decided = ~np.isnan(probabilities[:, 0])
members, risks = members[decided], risks[decided]
dates = pd.to_datetime(probabilities[decided, 0], unit="D").date
return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
"fecha_indice": np.repeat(dates, len(horizons)),
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
"probabilidad": risks.ravel().astype(float)})
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,
@@ -55,9 +79,7 @@ def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
cohort_frame = source.frame()
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
risks = estimate_frame(cohort_frame, probabilities, horizons)
risks = scored_frame(resolved, cohort_frame)
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario),
"modelo_version": resolved.version, "mlflow_run_id": resolved.run_id,
+29 -6
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.
`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
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 logging
import tomllib
from dataclasses import dataclass
from dataclasses import dataclass, field
from importlib import import_module
from pathlib import Path
from types import ModuleType
@@ -47,6 +47,9 @@ class Scenario:
config: dict
folder: Path
requirements: tuple[str, ...] = ()
# 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)
@classmethod
def from_toml(cls, path: str | Path) -> "Scenario":
@@ -55,7 +58,8 @@ class Scenario:
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
outcome=found["outcome"], description=found.get("description", ""),
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
folder=path.parent, requirements=tuple(found.get("requirements", ())))
folder=path.parent, requirements=tuple(found.get("requirements", ())),
estimand=dict(found.get("estimand", {})))
@classmethod
def load(cls, domain: str, scenario: str) -> "Scenario":
@@ -78,9 +82,9 @@ def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Dri
return builder.build()
# What the saver receives: the fitted model and its metrics, and the routines' records and the population results when the
# dataflow has them.
SAVED = {"fitted_model", "metrics", "routines", "population"}
# What the saver receives: the fitted model and its metrics, and the routines' records, the population results and the
# reports' pages when the dataflow has them.
SAVED = {"fitted_model", "metrics", "routines", "population", "reports"}
def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]:
@@ -108,6 +112,23 @@ def find_trained(scenario: Scenario, source: CohortSource, environment: str = "D
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:
"""Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
rows."""
@@ -117,6 +138,8 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") ->
try:
plain = dataflow(*scenario.modules, config=scenario.config)
required, _ = external_inputs(plain)
if drawing := pipeline_drawing(plain):
run.log_diagram("pipeline", *drawing)
loaders = [loader(target=target, source=source) for target, loader in
(("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source),
("cohort_lineage", from_.cohort_source_lineage))
+6 -3
View File
@@ -6,9 +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",
source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file).
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines", "population"], ...)`:
records each routine (ML-01a, `TrainingRun.log_routine`), the dataflow's `population` as the version's `analisis/`
files when it has one (`TrainingRun.log_analysis`), logs the fitted model in the open `TrainingRun` (`tracking`),
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines", "population",
"reports"], ...)`: records each routine (ML-01a, `TrainingRun.log_routine`), the dataflow's `population` as the
version's `analisis/` files and its `reports` as its `reportes/` pages when it has them (`TrainingRun.log_analysis`,
`TrainingRun.log_report`), logs the fitted model in the open `TrainingRun` (`tracking`),
records the metrics and the config, closes the run, and registers and describes the version (`registry`). Its value
is the version's metadata. A dataflow without `routines` still trains and registers, but the registry won't promote
it (`ROUTINE_KINDS`).
@@ -117,6 +118,8 @@ class RegisteredModelSaver(DataSaver):
self.run.log_routine(kind, record)
for name, record in data.get("population", {}).items():
self.run.log_analysis(name, record)
for name, page in data.get("reports", {}).items():
self.run.log_report(name, page)
packages = _own_packages(model)
for package in packages:
cloudpickle.register_pickle_by_value(package)
+6 -1
View File
@@ -48,7 +48,12 @@ ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False),
"horizonte_anios": pandera.Column(float, pandera.Check.ge(0)),
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
"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")
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:
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:
"""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
@@ -236,7 +244,10 @@ class ModelRegistry:
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing.
reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
metrics = run.data.metrics
missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)]
# ML-01a: the training run is itself the registered routine; its records (`TrainingRun.log_routine`) are
# reported, not required, since not every model has each of `ROUTINE_KINDS` (a prevalence-incidence mixture
# has no class balance or classifier calibration).
recorded = [kind.value for kind in ROUTINE_KINDS if kind.value in self.routines(mv.run_id)]
sha = mv.tags.get(MODEL_SHA_TAG, "")
if armado is not None:
cohort_detail = f"huella {armado['huella'][:12]}"
@@ -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-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
PromotionCheck("ML-01a", "rutinas registradas por la corrida de entrenamiento", not missing,
f"faltan: {', '.join(missing)}" if missing else f"{len(ROUTINE_KINDS)} de {len(ROUTINE_KINDS)}"),
PromotionCheck("ML-01a", "rutina registrada por la corrida de entrenamiento", bool(run.info.run_id),
f"corrida {run.info.run_id[:12]}; registros de rutina: {len(recorded)} de {len(ROUTINE_KINDS)}"
+ (f" ({', '.join(recorded)})" if recorded else "")),
PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
]
+14
View File
@@ -51,6 +51,8 @@ ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
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.
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
@@ -197,6 +199,18 @@ class TrainingRun:
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:
"""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
+15 -1
View File
@@ -85,6 +85,9 @@ class QuartoRenderer(NotebookRenderer):
return page.read_text()
HIDE_INPUT_TAG = "remove_input" # what a `#| echo: false` cell gets before the page is exported
@register_renderer
class JupyterRenderer(NotebookRenderer):
"""The kernel is the one the notebook names, which must be installed beside this package (`python3` is this
@@ -121,7 +124,18 @@ class JupyterRenderer(NotebookRenderer):
@staticmethod
def _page(exporter, node) -> str:
body, _ = exporter(embed_images=True).from_notebook_node(node)
"""The page, without the code of the cells that ask for it as Quarto does (`#| echo: false`), so a notebook
renders the same with either renderer."""
from nbconvert.preprocessors import TagRemovePreprocessor
for cell in node.cells:
if cell.cell_type == "code" and any(line.replace(" ", "") == "#|echo:false" for line in cell.source.splitlines()):
tags = cell.metadata.setdefault("tags", [])
if HIDE_INPUT_TAG not in tags:
tags.append(HIDE_INPUT_TAG)
page = exporter(embed_images=True)
page.register_preprocessor(TagRemovePreprocessor(remove_input_tags={HIDE_INPUT_TAG}, enabled=True), enabled=True)
body, _ = page.from_notebook_node(node)
return body
+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()))
+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,
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
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
def risk_rows(estimate: pd.DataFrame) -> list[tuple]:
"""One risk per member and horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a member scored
twice at one horizon or a probability outside 0..1 stops the batch."""
"""One risk per member and horizon, with its interval when the estimate has one, once the rows satisfy
`ESTIMATE_FRAME`: a member scored twice at one horizon or a probability outside 0..1 stops the batch."""
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), None, None)
for pac_id, fecha, horizon, probability in zip(estimate["pac_id"], estimate["fecha_indice"],
estimate["horizonte_anios"], estimate["probabilidad"])]
missing = pd.Series(np.nan, index=estimate.index)
low, high = estimate.get("ic_bajo", missing), estimate.get("ic_alto", missing)
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)]
+4 -1
View File
@@ -40,10 +40,12 @@ seer-survival = [
"matplotlib>=3.8",
"lifelines>=0.28", # the recurrence analysis' penalised Cox model (`models.cama.recurrence`)
]
# The population curves of a CaMa training run (`models.cama.survival.population`): the fractional Weibull's series.
# 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"]
@@ -72,6 +74,7 @@ dev = [
"networkx>=3.0",
"mpmath>=1.3",
"matplotlib>=3.8",
"plotly>=5.18",
"nbclient>=0.10",
"nbconvert>=7.16",
"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).
"""
import json
from datetime import date, datetime, timedelta, timezone
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",
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
"train_fraction"}
assert optional == {"index"} # from the config; a scenario without one keeps its cohort's index
# `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):
@@ -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,
predict_without_repository):
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per member
and horizon, a risk that doesn't fall with the horizon, the same outside this repository, and storable metadata.
Fails if the model or the estimate go back to one horizon, or the registered model needs this repository."""
"""Pins down: through the generic driver the scenario registers a version whose estimate has one row per
precolposcopy member (no biopsy) and horizon, dated at her latest complete cytology, a risk that doesn't fall
with the horizon, the same outside this repository, and storable metadata. Fails if the model or the estimate go
back to one horizon, a biopsied member is scored, or the registered model needs this repository."""
version = training.train(SCENARIO, CohortFile(cohort_file))
registry.client.set_registered_model_alias("cacu-cin2_pim", PRODUCTION_ALIAS, version)
output = tmp_path / "estimate.parquet"
@@ -189,7 +192,12 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
estimate(SCENARIO, CohortFile(cohort_file), 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")
assert (by_member.diff(axis=1).iloc[:, 1:] >= -1e-12).all().all()
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
outside = predict_without_repository(uri, pd.read_parquet(cohort_file))
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
assert outside.shape == (300, len(CONFIG["horizons_years"]))
assert outside.shape == (300, 1 + 3 * len(CONFIG["horizons_years"]))
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):
"""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."""
@@ -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 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+")}
+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
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,
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
@@ -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 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`).
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:
registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-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):
@@ -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}
@pytest.mark.parametrize("routines, model, failing", [
([ArtifactKind.MUESTREO], True, "ML-01a"),
(None, False, "ML-01b"),
])
def test_promotion_needs_what_the_training_run_itself_recorded(governance_db, cacu_db, mlflow_tracking, routines, model,
failing):
"""A run that skipped routine records, or saved no model, is not promoted, whatever else is in order. Fails if
the ML-01a check stops requiring every kind in `ROUTINE_KINDS` or the ML-01b check stops requiring `modelo_sha`."""
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=routines, model=model)
def test_promotion_needs_the_model_the_training_run_itself_saved(governance_db, cacu_db, mlflow_tracking):
"""A run that saved no model is not promoted, whatever else is in order. Fails if the ML-01b check stops requiring
`modelo_sha`."""
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=None, model=False)
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
interpretability_report_uri="i")
failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed]
assert [check.code for check in failed] == [failing]
if failing == "ML-01a":
assert "DATOS_FALTANTES" in failed[0].detail
assert [check.code for check in failed] == ["ML-01b"]
@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):
@@ -101,6 +108,19 @@ def test_retire_and_lineage(production_ready):
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 '%")])
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
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)
+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)]
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]),
_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):
"""Pins down: a member scored twice at one horizon, a probability outside 0..1, or other columns stop the batch
before anything is written. Fails if any of them reaches the database."""
"""Pins down: a member scored twice at one horizon, a probability outside 0..1, other columns, or an interval that
doesn't hold its risk stop the batch before anything is written. Fails if any of them reaches the database."""
with pytest.raises(ValueError):
risk_rows(frame)