CaCu survival: all-cause mortality at 1, 3 and 5 years and subgroup reports #10

Merged
edgar merged 2 commits from integration/cacu-indicadores into dev 2026-11-22 01:00:40 -06:00
23 changed files with 1656 additions and 14 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. |
+1 -1
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 \
@@ -0,0 +1,123 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "8368c95d",
"metadata": {
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"#| echo: false\n",
"#| tags: [parameters]\n",
"turnbull_bootstrap = 200\n",
"report_panels = 24"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "718e1a82",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"from IPython.display import HTML, Markdown, display\n",
"from models.cacu.cin2_pim import report\n",
"from models.dags.training import Scenario, dataflow\n",
"from models.notebook import experiment\n",
"\n",
"exp = experiment()\n",
"scenario = Scenario.load(exp.domain, exp.scenario)\n",
"horizons = scenario.config[\"horizons_years\"]\n",
"risks = dataflow(*scenario.modules, config=scenario.config).execute(\n",
" [\"combination_risks\"], inputs={\"source_cohort\": exp.cohort(), \"cohort_lineage\": exp.lineage(),\n",
" \"turnbull_bootstrap\": turnbull_bootstrap})[\"combination_risks\"]\n",
"ratios = [e for r in risks for e in r[\"e_o\"] if e[\"E_O\"] is not None]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "107af899",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\n",
" f\"**{exp.domain}/{exp.scenario}** · combinaciones: {len(risks)} · pacientes: {sum(r['n'] for r in risks)} · \"\n",
" f\"prevalentes: {sum(r['prevalent'] for r in risks)} · incidentes: {sum(r['incident'] for r in risks)} · \"\n",
" f\"E/O con IC sin 1: {sum(not e['low'] <= 1 <= e['high'] for e in ratios)} de {len(ratios)}\"))"
]
},
{
"cell_type": "markdown",
"id": "5d1c43a8",
"metadata": {},
"source": [
"## Riesgo acumulado de CIN2+ por combinación: Turnbull y mezcla prevalencia-incidencia"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5d5a1559",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(HTML(report._figure(risks, horizons, report_panels).to_html(full_html=False, include_plotlyjs=True)))"
]
},
{
"cell_type": "markdown",
"id": "dc145546",
"metadata": {},
"source": [
"## E/O por combinación y horizonte"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23665b08",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(report._table(risks))"
]
},
{
"cell_type": "markdown",
"id": "98091470",
"metadata": {},
"source": [
"## Métodos"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "474e00f9",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\"\\n\".join(f\"- **{k}**: {v}\" for k, v in report.METHODS.items())))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+268
View File
@@ -0,0 +1,268 @@
"""The subgroup report of a prevalence–incidence training run (every `cin2_pim` scenario): for each combination of the
model's features (KPNC's index cytology, HPV and, with a history, its feature), the model's cumulative risk of CIN2+
with its delta-method band against the combination's own Turnbull estimate with its bootstrap band, and the ratio of
expected to observed risk (E/O) at each horizon with its interval. A version keeps the record (`analisis/subgrupos.json`,
with the methods it used) and the page (`reportes/subgrupos.html`, Plotly, self-contained).
- The model is the scenario's mixture refitted on every interval-coded member (not only the training part), so that it
and the empirical estimate describe the same members.
- The empirical estimate is Turnbull's nonparametric maximum likelihood for interval-censored data (self-consistency,
as `bayes-pim/informe/resultados/24/simular_protocolo.py`), with the members coded as the mixture's likelihood reads
them: a prevalent case is the mass at 0, a member found free is censored in `(l, r]`, and one whose baseline is
unknown in `[0, r]` (prevalent or incident). It respects the interval censoring: a CIN2+ is known only between the
last negative and the biopsy, never at a date. Its band and variance are the percentiles and variance of
`turnbull_bootstrap` resamples of the combination's members.
- The model's band is the delta method over the likelihood: Var(CR(t)) = g' Σ g, with Σ the inverse of the observed
information (the numerical Hessian `likelihood.fit` already inverts) and g the numerical gradient of CR(t) in the
stratum's parameters; a parameter at the boundary has no variance in Σ and counts as fixed. The band is on the log
scale, E exp(±1.96 SE(E)/E).
- E/O: log(E/O) taken as normal, with SE^2 = Var(E)/E^2 + Var(O)/O^2. Empty where O is 0.
Aggregates only: counts, curves and points, never a member's row.
"""
import numpy as np
import pandas as pd
from models.cacu.cin2_pim import likelihood
from models.cacu.cin2_pim.model import PrevalenceIncidenceMixture, _features, _levels
Z = 1.959963984540054 # the normal's 97.5 % quantile
GRID_STEP = 0.1 # years between the points of the model's curve
UNKNOWN = "NA"
NOTICE = "Prototipo sin validación clínica."
METHODS = {
"empirica": "Turnbull (estimador no paramétrico de máxima verosimilitud con censura por intervalos, autoconsistencia): "
"prevalente = masa en 0, libre de CIN2+ = censura en (l, r], basal desconocida = [0, r]; banda e "
"varianza por bootstrap de las pacientes de la combinación",
"modelo": "mezcla prevalencia-incidencia reajustada en todas las pacientes codificadas; banda por método delta sobre "
"la verosimilitud (inversa del Hessiano numérico, gradiente numérico del riesgo acumulado), en escala log; "
"un parámetro en la frontera cuenta como fijo",
"E/O": "riesgo esperado por el modelo entre el observado (Turnbull) a cada horizonte; IC 95 % suponiendo log(E/O) "
"normal, SE² = Var(E)/E² + Var(O)/O²",
}
def _turnbull(c: np.ndarray, l: np.ndarray, r: np.ndarray, iters: int = 5000, tol: float = 1e-10):
"""(support, cumulative mass) of Turnbull's estimate for members coded `(c, l, r)`: the support is 0, every finite
right end and infinity; a prevalent member's set is {0}, a free one's the points in `(l, r]`, an unknown baseline's
the points in `[0, r]`."""
finite = r[np.isfinite(r)]
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
low = np.where(c == 0, l, -np.inf)
high = np.where(c == 1, 0.0, r)
A = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
patterns, counts = np.unique(A, axis=0, return_counts=True)
p = np.full(len(support), 1 / len(support))
for _ in range(iters):
weighted = patterns * p
new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum()
if np.max(np.abs(new - p)) < tol:
p = new
break
p = new
return support, np.cumsum(p)
def _at(support: np.ndarray, cumulative: np.ndarray, t) -> np.ndarray:
"""The estimate's cumulative risk at each of `t` (a step function, right-continuous)."""
idx = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
return np.where(idx < 0, 0.0, cumulative[np.maximum(idx, 0)])
def _label_value(feature: str, value) -> str:
if value is None or (isinstance(value, float) and np.isnan(value)):
return UNKNOWN
if feature == "hpv_positive":
return "positivo" if float(value) == 1.0 else "negativo"
return str(value)
def report_mixture(interval_coded_members: pd.DataFrame, horizons_years: list[float], incidence: dict,
incidence_features: list[str], strata: list[str], cytology: dict,
history: dict) -> PrevalenceIncidenceMixture:
"""The scenario's mixture refitted on every interval-coded member, the model the report sets against Turnbull."""
features = _features(history)
return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence,
_levels(cytology, history)).fit(interval_coded_members[features],
interval_coded_members[["c", "l", "r"]])
def _risk_with_variance(mixture: PrevalenceIncidenceMixture, row: pd.DataFrame, years: np.ndarray):
"""The model's cumulative risk of one combination (`row`, one row) at `years`, and its delta-method variance."""
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
if key not in mixture.fits_:
return None, None
seen = mixture.seen_[key]
if not mixture._placed(row, seen).all():
return None, None
fit = mixture.fits_[key]
X, Zd = mixture._design(row, seen)
n_x, n_z = len(fit["theta"]), len(fit["beta"])
def risk(params):
found = {"theta": params[:n_x], "beta": params[n_x:n_x + n_z], "baseline": fit["baseline"],
"baseline_params": params[n_x + n_z:]}
return likelihood.cumulative_risk(found, X, Zd, years)[0]
params = np.asarray(fit["params"], dtype=float)
point = risk(params)
gradient = np.empty((len(params), len(years)))
for k in range(len(params)):
step = 1e-5 * max(1.0, abs(params[k]))
up, down = params.copy(), params.copy()
up[k] += step
down[k] -= step
gradient[k] = (risk(up) - risk(down)) / (2 * step)
covariance = np.nan_to_num(np.asarray(fit["covariance"], dtype=float), nan=0.0)
variance = np.einsum("ki,kl,li->i", gradient, covariance, gradient)
return point, np.maximum(variance, 0.0)
def combination_risks(interval_coded_members: pd.DataFrame, report_mixture: PrevalenceIncidenceMixture,
horizons_years: list[float], history: dict, turnbull_bootstrap: int = 200) -> list[dict]:
"""Per combination of the features present among the coded members, largest first: its members and prevalent
and incident cases, its Turnbull estimate with the bootstrap band, the model's cumulative risk with the delta-method
band (none for a combination the model can't place: a cytology outside KPNC's categories, a stratum unseen) and
E/O at each horizon (see the module's docstring)."""
features = _features(history)
members = interval_coded_members.reset_index(drop=True)
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label_value(f, v)) for f in features})
table = labels.drop_duplicates().reset_index(drop=True)
horizons = np.asarray(horizons_years, dtype=float)
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
rng = np.random.default_rng(20261122)
records = []
for _, row in table.iterrows():
mask = (labels == row).all(axis=1).to_numpy()
group = members[mask]
c, l, r = group["c"].to_numpy(int), group["l"].to_numpy(float), group["r"].to_numpy(float)
support, cumulative = _turnbull(c, l, r)
boot_grid, boot_h = [], []
for _ in range(turnbull_bootstrap):
pick = rng.integers(0, len(group), len(group))
s_b, c_b = _turnbull(c[pick], l[pick], r[pick])
boot_grid.append(_at(s_b, c_b, grid))
boot_h.append(_at(s_b, c_b, horizons))
boot_grid, boot_h = np.array(boot_grid), np.array(boot_h)
O = _at(support, cumulative, horizons)
var_O = boot_h.var(axis=0, ddof=1) if turnbull_bootstrap > 1 else np.full(len(horizons), np.nan)
empirical = {"years": grid.tolist(), "CR": _at(support, cumulative, grid).tolist(),
"low": np.percentile(boot_grid, 2.5, axis=0).tolist() if turnbull_bootstrap else None,
"high": np.percentile(boot_grid, 97.5, axis=0).tolist() if turnbull_bootstrap else None}
model, ratios = None, []
probe = group.iloc[[0]][features]
E, var_E = _risk_with_variance(report_mixture, probe, horizons)
curve, var_curve = _risk_with_variance(report_mixture, probe, grid)
if curve is not None:
rel = np.where(curve > 0, np.sqrt(var_curve) / np.maximum(curve, 1e-300), 0.0)
model = {"years": grid.tolist(), "CR": curve.tolist(),
"low": np.clip(curve * np.exp(-Z * rel), 0, 1).tolist(),
"high": np.clip(curve * np.exp(Z * rel), 0, 1).tolist()}
for k, h in enumerate(horizons):
entry = {"years": float(h), "E": None if E is None else float(E[k]), "O": float(O[k]),
"E_O": None, "low": None, "high": None}
if E is not None and E[k] > 0 and O[k] > 0 and np.isfinite(var_O[k]):
se = float(np.sqrt(var_E[k] / E[k] ** 2 + var_O[k] / O[k] ** 2))
value = float(E[k] / O[k])
entry.update(E_O=value, low=value * float(np.exp(-Z * se)), high=value * float(np.exp(Z * se)))
ratios.append(entry)
records.append({"combination": row.to_dict(), "n": int(mask.sum()), "prevalent": int((c == 1).sum()),
"incident": int(((c != 1) & np.isfinite(r)).sum()), "empirical": empirical,
"model": model, "e_o": ratios})
return sorted(records, key=lambda x: (-x["n"], list(x["combination"].values())))
def _label(combination: dict) -> str:
names = {"cytology": "citología", "hpv_positive": "VPH"}
return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items())
def _figure(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24):
"""The figure: one panel per combination (the `report_panels` largest), Turnbull's step curve with its band and the
model's curve with its band (a Plotly `Figure`; the page and the notebook draw it)."""
import plotly.graph_objects as go
from plotly.subplots import make_subplots
shown = combination_risks[:report_panels]
columns = 3
rows = max(1, -(-len(shown) // columns))
figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=True,
subplot_titles=[f"{_label(r['combination'])}<br>n = {r['n']}, prevalentes = {r['prevalent']}, "
f"incidentes = {r['incident']}" for r in shown])
for k, record in enumerate(shown):
row, col, first = k // columns + 1, k % columns + 1, k == 0
emp, model = record["empirical"], record["model"]
if emp["low"] is not None:
figure.add_trace(go.Scatter(x=emp["years"], y=emp["high"], mode="lines", line={"width": 0, "shape": "hv"},
hoverinfo="skip", showlegend=False), row=row, col=col)
figure.add_trace(go.Scatter(x=emp["years"], y=emp["low"], mode="lines", line={"width": 0, "shape": "hv"},
fill="tonexty", fillcolor="rgba(120,130,140,0.30)", hoverinfo="skip",
name="IC 95 % Turnbull (bootstrap)", legendgroup="emp_band", showlegend=first),
row=row, col=col)
figure.add_trace(go.Scatter(x=emp["years"], y=emp["CR"], mode="lines", line={"color": "#242628", "width": 2,
"shape": "hv"},
name="Turnbull", legendgroup="emp", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.3f}<extra>Turnbull</extra>"), row=row, col=col)
if model is not None:
figure.add_trace(go.Scatter(x=model["years"], y=model["high"], mode="lines", line={"width": 0},
hoverinfo="skip", showlegend=False), row=row, col=col)
figure.add_trace(go.Scatter(x=model["years"], y=model["low"], mode="lines", line={"width": 0},
fill="tonexty", fillcolor="rgba(111,53,165,0.18)", hoverinfo="skip",
name="IC 95 % modelo (método delta)", legendgroup="model_band",
showlegend=first), row=row, col=col)
figure.add_trace(go.Scatter(x=model["years"], y=model["CR"], mode="lines", line={"color": "#6f35a5",
"width": 2},
name="Mezcla prevalencia-incidencia", legendgroup="model", showlegend=first,
hovertemplate="%{x:.1f} años: %{y:.3f}<extra>modelo</extra>"), row=row, col=col)
figure.update_xaxes(range=[0, max(horizons_years) + 0.05])
figure.update_yaxes(rangemode="tozero")
figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110},
title={"text": "Riesgo acumulado de CIN2+ por combinación de covariables<br>"
f"<sup>Años desde la fecha índice; {NOTICE}</sup>"},
legend={"orientation": "h", "y": 1.0, "yanchor": "bottom", "x": 0})
return figure
def _ratio(e: dict) -> str:
if e["E_O"] is None:
return "—"
flag = "" if e["low"] <= 1 <= e["high"] else " *"
return f"{e['E_O']:.2f} ({e['low']:.2f}–{e['high']:.2f}){flag}"
def _table(combination_risks: list[dict]) -> pd.DataFrame:
"""Every combination's counts and E/O at each horizon (`*`: its interval leaves out 1)."""
return pd.DataFrame([{**r["combination"], "n": r["n"], "prevalentes": r["prevalent"], "incidentes": r["incident"],
**{f"E/O {e['years']:g} a": _ratio(e) for e in r["e_o"]}} for r in combination_risks])
def subgroup_report(combination_risks: list[dict], horizons_years: list[float], report_panels: int = 24) -> str:
"""The page: the figure, the table of every combination's counts and E/O, and the methods."""
figure = _figure(combination_risks, horizons_years, report_panels)
shown = combination_risks[:report_panels]
table = _table(combination_risks)
omitted = len(combination_risks) - len(shown)
notes = (f"<p>{omitted} combinaciones más, sin panel (solo en la tabla).</p>" if omitted > 0 else "") + (
"<p>* el IC de E/O no incluye 1. — sin casos observados a ese horizonte o combinación que el modelo no "
"ubica.</p><h3>Métodos</h3><ul>" + "".join(f"<li><b>{k}</b>: {v}</li>" for k, v in METHODS.items()) + "</ul>")
return ("<!doctype html><html lang=\"es\"><head><meta charset=\"utf-8\"><title>CIN2+ por subgrupo</title></head>"
"<body style=\"font-family:sans-serif;margin:16px\">" + figure.to_html(full_html=False, include_plotlyjs=True)
+ notes + "<h3>Combinaciones</h3>" + table.to_html(index=False, border=0) + "</body></html>")
def subgroups(combination_risks: list[dict]) -> dict:
"""The report's record, with the methods it used."""
return {"version": 1, "metodos": METHODS, "combinations": combination_risks}
def population(subgroups: dict) -> dict:
"""What the saver publishes under `analisis/`, by file name."""
return {"subgrupos": subgroups}
def reports(subgroup_report: str) -> dict:
"""What the saver publishes under `reportes/`, by name."""
return {"subgrupos": subgroup_report}
@@ -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 \
@@ -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 \
View File
+156
View File
@@ -0,0 +1,156 @@
"""What the CaCu survival model is made of: the member table a build's events give, and the interval survival estimator.
`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index
and rules leave get their covariates and the index date; the rest keep their row, empty. The index is the diagnosis
(provisionally the first biopsy reported as invasive carcinoma) and the covariates are the member's most recent
observations up to it: her age group at the index, the cytology of her latest sample (KPNC's categories, the more severe
of its squamous and glandular results) and her latest HPV result. `IntervalSurvival` is CaMa's
(`models.cama.survival.estimator`): per interval of `survival.horizons`, a logistic regression and a Bayesian network
with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`), stacked with
out-of-sample weights; a patient's survival to each horizon is the product of the intervals'.
DUPLICATED (issue #9): `encode`, `interval_cohort` and `IntervalSurvival` are CaMa's with the covariates as `FEATURES`
of this module instead of CaMa's; CaMa's read its own `FEATURES` as a module constant, so they can't be reused without
changing CaMa. The outcome (`outcome_table`) and the settings (`survival_settings`) are CaMa's, imported.
"""
import json
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from models.cama.seer_survival import survival_models as sm
from models.cama.survival.estimator import EPOCH, INDEX_COLUMN, UNKNOWN, WINDOW_KEYS, _band, survival_settings
from models.io.contracts import DAYS_PER_YEAR
from models.steps import indexing
FEATURES = ["age_group", "cytology", "hpv"]
NUMERIC = ["age_years"] # the age before banding
def _latest_cytology(prior: pd.DataFrame, cytology: dict) -> pd.Series:
"""Per `pac_id`, KPNC's category of her latest cytology sample: the more severe of its squamous and glandular
results; None when no result falls in a category."""
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
results = prior[prior["tipo"].isin(["bethesda", "glandular"]) & prior["valor_codigo"].notna()]
latest = results[results["fecha"] == results.groupby("pac_id")["fecha"].transform("max")]
ranks = latest["valor_codigo"].map(severity).groupby(latest["pac_id"]).max()
names = list(cytology)
return ranks.map(lambda rank: None if pd.isna(rank) else names[int(rank)])
def member_table(cohort: pd.DataFrame, age_cuts: list, cytology: dict) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice`, the covariates in `FEATURES` and the
age in years. Each covariate is the member's most recent observation up to the index (the index day included): her
age at the index from her `nacimiento`, her latest cytology sample's category (`_latest_cytology`) and her latest HPV
result; empty where the build has none."""
frame = cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
members["age_group"] = _band(members["age_years"], age_cuts)
prior = frame[frame["fecha"] <= frame["fecha_indice"]]
members["cytology"] = _latest_cytology(prior, cytology).reindex(members.index).astype(object)
hpv = prior[(prior["tipo"] == "vph") & prior["valor_codigo"].notna()].sort_values(["fecha", "fuente_id"])
members["hpv"] = hpv.groupby("pac_id")["valor_codigo"].last().reindex(members.index)
members = members.astype({"cytology": object, "hpv": object})
return members[["fecha_indice", *FEATURES, *NUMERIC]]
def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None):
"""CaMa's `encode` over this module's `FEATURES` (DUPLICATED, issue #9): `(X_dum, X_int, categories, dummy_columns)`.
With no `categories` they are learned from `frame`; with them, a value the fit never saw takes the unknown
category."""
frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str)
if categories is None:
dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns)
categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES}
columns = []
for name in FEATURES:
codes = pd.Categorical(frame[name], categories=categories[name]).codes
fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0
columns.append(np.where(codes < 0, fallback, codes))
X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32)
return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns
def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings):
"""CaMa's `interval_cohort` over this module's `FEATURES` (DUPLICATED, issue #9)."""
X_dum, X_int, categories, dummy_columns = encode(features)
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
return cohort, categories, dummy_columns
class MemberFeatures(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
def __init__(self, index=None, window=None, age_cuts=(35, 45, 55), cytology=None):
self.index = index
self.window = window
self.age_cuts = age_cuts
self.cytology = cytology
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
table = member_table(indexed, list(self.age_cuts), self.cytology) \
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
return table[[*FEATURES, INDEX_COLUMN]]
class IntervalSurvival(BaseEstimator):
"""CaMa's `IntervalSurvival` over this module's `FEATURES` (DUPLICATED, issue #9): per interval, LR and HBN stacked;
the survival to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with
`months` and `event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With
`INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member
without one) and her mortality is empty too."""
def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0)):
self.survival = survival
self.horizons_years = horizons_years
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
s = survival_settings(self.survival)
if [h / 12 for h in s.horizons] != list(self.horizons_years):
raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ")
cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s)
everyone = np.arange(len(X))
if s.combine_active and len(X) >= 2 * s.stack_folds:
weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X)))
self.weights_ = weights["w_LR"].to_numpy()
self.stacking_ = weights.to_dict("records")
else:
self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), []
self.fitted_ = sm.fit_intervals(cohort, s, everyone, None)
self.levels_ = cohort.levels
return self
def interval_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's probability of surviving each interval, given she is alive at its start."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb
def survival_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's survival to each horizon."""
return np.cumprod(self.interval_proba(X), axis=1)
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
mortality = 1.0 - self.survival_proba(X)
if INDEX_COLUMN not in X.columns:
return mortality
dates = pd.to_datetime(X[INDEX_COLUMN])
member = dates.notna().to_numpy()
mortality[~member] = np.nan
return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality])
__all__ = ["FEATURES", "INDEX_COLUMN", "IntervalSurvival", "MemberFeatures", "WINDOW_KEYS", "encode", "interval_cohort",
"member_table"]
+151
View File
@@ -0,0 +1,151 @@
"""CaCu survival prototype: the all-cause mortality at 1, 3 and 5 years from the cancer diagnosis.
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
`[config.index]`): PROVISIONAL, the diagnosis is the first biopsy reported as invasive carcinoma, which is both the
inclusion criterion and the index date. Each member's covariates are her most recent observations up to it: her age
group at the index, her latest cytology (KPNC's categories) and her latest HPV result; her outcome is the months from
the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts the
follow-up). The fit is the SEER pipeline's interval survival, as CaMa's survival scenario runs it
(`models.cama.survival`): per interval a logistic regression and a Bayesian network, stacked. A member without a result
has it as a category of its own.
The nodes that don't depend on the covariates are CaMa's, called from here: Hamilton takes as nodes only the functions
defined in a listed module, and listing CaMa's would bring its covariate-bound nodes too. Those bound to the covariates
(`labelled_members`, `missing_data`, `analytic_method`) are copies over this scenario's `FEATURES` (DUPLICATED, issue
#9). `fitted_model` puts `MemberFeatures` in front of the fitted estimator, so the registered model is one scikit-learn
`Pipeline` that takes a build's long frame.
"""
import json
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
from models.cacu.survival import estimator, report
from models.cacu.survival.estimator import FEATURES, IntervalSurvival, MemberFeatures
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival import estimator as cama_estimator
from models.cama.survival import model as cama
from models.steps import model_fitting
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"months": pandera.Column(int, pandera.Check.ge(0)),
"event": pandera.Column(bool),
**{name: pandera.Column(nullable=True) for name in FEATURES}},
name="labelled members")
def cohort_cutoff(cohort_lineage: dict) -> date:
"""CaMa's: the build's cut-off."""
return cama.cohort_cutoff(cohort_lineage)
def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSettings:
"""CaMa's: the pipeline's survival settings, whose horizons in months must be `horizons_years`."""
return cama.survival_settings(survival, horizons_years)
def member_features(cohort: pd.DataFrame, age_cuts: list[int], cytology: dict) -> pd.DataFrame:
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates (her most recent
observations up to it)."""
return estimator.member_table(cohort, age_cuts, cytology)
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""CaMa's: one row per member, by `pac_id`: months of follow-up and whether she died in them."""
return cama_estimator.outcome_table(cohort, cohort_cutoff, survival_settings.cap_months)
@checked_frame(LABELLED_MEMBERS)
def labelled_members(member_features: pd.DataFrame, member_outcomes: pd.DataFrame) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates, her follow-up and whether she died."""
return member_features.join(member_outcomes).reset_index()
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event")
def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival:
"""The interval survival fitted on the training members."""
return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]])
def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray:
"""The test members' probability of surviving each interval, given they are alive at its start."""
return fitted_survival.interval_proba(test_set[FEATURES])
def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray:
"""The training members' mortality at each horizon (apparent performance)."""
return fitted_survival.predict_proba(train_set[FEATURES])
def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray,
train_mortality: np.ndarray, survival_settings: SurvivalSettings, fitted_survival: IntervalSurvival) -> dict:
"""CaMa's: aggregates only, over the test members' member-intervals, and the apparent AUC at each horizon."""
return cama.metrics(train_set, test_set, test_interval_survival, train_mortality, survival_settings, fitted_survival)
def sampling(index_attrition: list, prior_observation: dict, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""CaMa's MUESTREO: who could be used and how they were split."""
return cama.sampling(index_attrition, prior_observation, train_set, test_set, train_fraction)
def missing_data(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many members lacked each covariate, and what was done about it (DUPLICATED, issue #9)."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int(frame[name].isna().sum()) for name in FEATURES}
return {"method": "un resultado ausente es una categoría más (NA); no se imputa ni se descarta al miembro",
"train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_survival: IntervalSurvival, survival_settings: SurvivalSettings) -> dict:
"""METODO_ANALITICO: the intervals, how the two models are stacked and which covariates the network kept
(DUPLICATED, issue #9)."""
s = survival_settings
return {"method": "supervivencia por intervalos: regresión logística y red bayesiana (CPT tabular) por intervalo, "
"combinadas con pesos fuera de muestra; la supervivencia es el producto de los intervalos",
"intervals_months": [0, *s.horizons], "censoring": s.censoring, "cap_months": s.cap_months,
"hbn_ess": s.hbn_ess, "hbn_max_parents": s.hbn_max_parents, "covariates": FEATURES,
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
for row in fitted_survival.stacking_],
"hbn_parents": [[FEATURES[j] for j in model[0]] for _, model in fitted_survival.fitted_],
"subgroup_report": report.METHODS}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""CaMa's BALANCE_CLASES: deaths and members followed without one in each part."""
return cama.class_balance(train_set, test_set)
def output_confidence(test_set: pd.DataFrame, test_interval_survival: np.ndarray, survival_settings: SurvivalSettings,
calibration_bins: int = 5) -> dict:
"""CaMa's CONFIANZA_SALIDA: the predicted survival of each interval against the observed one, by quantiles."""
return cama.output_confidence(test_set, test_interval_survival, survival_settings, calibration_bins)
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return cama.routines(sampling, missing_data, analytic_method, class_balance, output_confidence)
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
cytology: dict) -> Pipeline:
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), dict(cytology))),
("survival", fitted_survival)])
+87
View File
@@ -0,0 +1,87 @@
domain = "cacu"
scenario = "survival"
cohort = "cacu/cohorte_total"
outcome = "muerte"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cacu.survival.model", "models.cacu.survival.population", "models.cacu.survival.report",
"models.steps.indexing"]
description = """
Prototipo: mortalidad por cualquier causa a 1, 3 y 5 años del diagnóstico de cáncer (provisional: la primera biopsia \
con carcinoma invasor), a partir de la edad al diagnóstico y de la citología (categorías de KPNC) y el VPH más \
recientes hasta él. Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana combinadas), \
como la de CaMa. Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la \
registra."""
[config]
train_fraction = 0.7
# The model's horizons, in years; `survival.horizons` are the same in months.
horizons_years = [1.0, 3.0, 5.0]
# The age at the index in bands, in years. The cytology and HPV are the most recent up to the index, at any distance.
age_cuts = [35, 45, 55]
# The scenario's index and rules, over its source cohort (models/steps/indexing.py). PROVISIONAL: the diagnosis is the
# first biopsy reported as invasive carcinoma (`CARCINOMA`; in situ is not), which is both the inclusion criterion and
# the index date; out: no birth date (no age), a death on or before the biopsy. The recruitment window is the source
# cohort's.
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA"]
# PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone.
observacion_previa_minima_dias = 0
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with CaMa's settings but the
# horizons, the follow-up cap and the HBN's parents.
[config.survival]
age_mode = "categorizada"
include_age = true
age_cuts = [35, 45, 55]
hbn_fixed_parents = [] # no expert parents defined for CaCu yet: learned by the BDeu score
hbn_age_parent = false
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
covariates = []
horizons = [12, 36, 60] # months
censoring = "riesgo" # a model per interval using all the follow-up
combine = true # one LR + HBN indicator, per-interval stacking weights
show_individual = false
stack_folds = 5
stack_shrink = 20
n_boot = 100
n_boot_sub = 100
seed = 42
hbn_ess = 1000
hbn_max_parents = 5
k_ident = "clasico"
curves = "ajustada"
adjust_step = 3
show_raw_km = true
ylim_main = []
inset_zoom = false
inset_months = 60
cap_months = 60 # follow-up is cut here: a later death counts as alive
min_events_sub = 5
ks_max_seconds = 120
ks_sub_max_seconds = 180
xlim_sub = []
ylim_sub = {}
# What the dashboard's survival chart says (provisional: to be defined with the clinicians).
[config.etiquetas]
titulo = "Supervivencia después de la biopsia con carcinoma invasor"
eje_x = "Meses desde el diagnóstico"
eje_y = "Supervivencia S(t)"
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
weibull = "Weibull"
weibull_fraccional = "Weibull fraccional"
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
# the glandular result (as `cin2_pim`); with both results the more severe category wins.
[config.cytology]
NILM = ["NORMAL"]
ASC-US = ["ASC-US"]
LSIL = ["LIEBG"]
ASC-H = ["ASC-H"]
AGC = ["AGC"]
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
@@ -0,0 +1,119 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "43f4f2cf",
"metadata": {
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"#| echo: false\n",
"#| tags: [parameters]\n",
"report_panels = 24"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6f01c5ec",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"from IPython.display import HTML, Markdown, display\n",
"from models.cacu.survival import report\n",
"from models.dags.training import Scenario, dataflow\n",
"from models.notebook import experiment\n",
"\n",
"exp = experiment()\n",
"scenario = Scenario.load(exp.domain, exp.scenario)\n",
"found = dataflow(*scenario.modules, config=scenario.config).execute(\n",
" [\"combination_survival\", \"survival_settings\"], inputs={\"source_cohort\": exp.cohort(), \"cohort_lineage\": exp.lineage()})\n",
"survival, settings = found[\"combination_survival\"], found[\"survival_settings\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61c183ea",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\n",
" f\"**{exp.domain}/{exp.scenario}** · combinaciones: {len(survival)} · pacientes: {sum(r['n'] for r in survival)} · \"\n",
" f\"defunciones: {sum(r['deaths'] for r in survival)} · horizontes: {', '.join(f'{h} m' for h in settings.horizons)}\"))"
]
},
{
"cell_type": "markdown",
"id": "fd940976",
"metadata": {},
"source": [
"## Supervivencia por combinación: Kaplan-Meier y modelo"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3498c913",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(HTML(report._figure(survival, scenario.config['etiquetas'], settings, report_panels).to_html(full_html=False, include_plotlyjs=True)))"
]
},
{
"cell_type": "markdown",
"id": "2d917e18",
"metadata": {},
"source": [
"## Pacientes y defunciones por combinación"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1870121a",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(report._table(survival))"
]
},
{
"cell_type": "markdown",
"id": "2ef312c0",
"metadata": {},
"source": [
"## Métodos"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c63b624",
"metadata": {},
"outputs": [],
"source": [
"#| echo: false\n",
"display(Markdown(\"\\n\".join(f\"- **{k}**: {v}\" for k, v in report.METHODS.items())))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+87
View File
@@ -0,0 +1,87 @@
"""The population results of a training run, what the dashboard draws: the survival of the whole cohort and the model's
survival at each horizon, as CaMa's survival scenario publishes them (`models.cama.survival.population`).
Over every member of the indexed cohort: the Kaplan-Meier curve with its Greenwood interval, the covariate-adjusted
curve, the classic and the fractional Weibull fitted to it, and the mean survival at each horizon by the logistic
regression, the Bayesian network and their stacked combination, each with a 95 % bootstrap interval. The record is the
version's `analisis/curvas.json`; its labels come from `[config.etiquetas]`.
Every node but `survival_frame` is CaMa's, called from here (Hamilton takes only the functions defined in a listed
module). `survival_frame` is a copy over this scenario's `FEATURES` (DUPLICATED, issue #9).
"""
import numpy as np
import pandas as pd
from models.cacu.survival.estimator import FEATURES
from models.cama.seer_survival import survival_curves as luis
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival import population as cama
from models.cama.survival.estimator import UNKNOWN
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts
as alive) and the covariates as categories (DUPLICATED, issue #9)."""
s, lm = survival_settings, labelled_members
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
for name in FEATURES:
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
return luis.SurvivalFrame(df, list(FEATURES), None, [])
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
return cama.curve_cohort(survival_frame, survival_settings)
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
return cama.km_raw(survival_frame, survival_settings)
def km_curve(km_raw: luis.KaplanMeier) -> dict:
return cama.km_curve(km_raw)
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
return cama.adjusted_km(curve_cohort, km_raw, survival_settings)
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
return cama.population_weights(curve_cohort, survival_settings)
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
return cama.luis_points(curve_cohort, population_weights, survival_settings)
def point_estimates(luis_points: luis.Points) -> dict:
return cama.point_estimates(luis_points)
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> np.ndarray:
return cama.bootstrap_points(curve_cohort, population_weights, luis_points, survival_settings)
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
return cama.weibull_fits(adjusted_km, survival_frame, survival_settings)
def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
point_estimates: dict, bootstrap_points: np.ndarray, population_weights: pd.DataFrame,
survival_settings: SurvivalSettings, etiquetas: dict) -> dict:
"""CaMa's: the `curvas` record the dashboard draws."""
return cama.population_curves(labelled_members, km_curve, adjusted_km, weibull_fits, point_estimates,
bootstrap_points, population_weights, survival_settings, etiquetas)
def population(population_curves: dict, subgroups: dict) -> dict:
"""What the saver publishes under `analisis/`, by file name: the curves, and each combination of the covariates'
Kaplan-Meier and model survival with the methods used (`report.subgroups`). CaMa adds its SEER development stages
instead, which need covariates CaCu doesn't have."""
return {**population_curves, "subgrupos": subgroups}
+136
View File
@@ -0,0 +1,136 @@
"""The subgroup report of a training run: for each combination of the covariates (age group, latest cytology, latest
HPV), the model's survival at each horizon with its 95 % interval against the combination's own Kaplan-Meier curve with
its Greenwood band. A version keeps the record (`subgroups`, in `analisis/subgrupos.json`, with the methods it used)
and the page (`reportes/subgrupos.html`, Plotly, self-contained).
The methods are the SEER pipeline's for its subgroups, called as they are (`models.cama.seer_survival.survival_curves`):
the models are fitted on every member of the indexed cohort (the population curves' cohort, `population.curve_cohort`),
each subgroup has its own stacking weights out of sample (`sv_sub_weights`), and the model's survival of a subgroup is
its members' mean with a bootstrap percentile interval (`sv_sub_points`: `survival.n_boot_sub` resamples, the HBN's
parents of the full fit kept). The Kaplan-Meier curve of a combination is over its members only
(`fractional_weibull.km_curva`, Greenwood on the log-log scale), month by month up to its longest follow-up; death times
are exact (to the month), so it respects their censoring. Aggregates only: counts, curves and points, never a
member's row.
"""
import numpy as np
import pandas as pd
from models.cacu.survival.estimator import FEATURES
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import survival_curves as luis
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
NOTICE = "Prototipo sin validación clínica."
METHODS = {
"empirica": "Kaplan-Meier por combinación de covariables, IC 95 % de Greenwood en escala log-log "
"(models.cama.seer_survival.fractional_weibull.km_curva)",
"modelo": "supervivencia por intervalos (LR y red bayesiana, combinadas con pesos fuera de muestra por subgrupo) "
"ajustada en toda la cohorte; media de la combinación con IC 95 % bootstrap percentil "
"(models.cama.seer_survival.survival_curves.sv_sub_weights y sv_sub_points)",
}
def combination_survival(survival_frame: luis.SurvivalFrame, curve_cohort: sm.Cohort, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> list[dict]:
"""Per combination of the covariates present in the cohort, largest first: its members and deaths, its
Kaplan-Meier curve with the Greenwood band, and the combined model's survival at each horizon with its bootstrap
interval (see the module's docstring)."""
s, df = survival_settings, survival_frame.df.reset_index(drop=True)
combos = df[FEATURES].astype(str)
table = combos.drop_duplicates().reset_index(drop=True)
masks = {str(j): (combos == row).all(axis=1).to_numpy() for j, row in table.iterrows()}
weights = luis.sv_sub_weights(curve_cohort, masks, luis.sv_oof(curve_cohort, s), s)
points = luis.sv_sub_points(curve_cohort, masks, weights, luis_points, s)
months, event = df["meses_int"].to_numpy(int), df["evento"].to_numpy(bool)
name = "COMB" if s.combine_active else "LR"
records = []
for j, row in table.iterrows():
members = masks[str(j)]
follow = int(months[members].max())
km, km_low, km_high = fw.km_curva(months[members], event[members], follow)
model = points[str(j)].query("modelo == @name").sort_values("meses")
records.append({
"combination": row.to_dict(), "n": int(members.sum()), "deaths": int(event[members].sum()),
"km": {"months": list(range(follow + 1)), "S": km.tolist(), "low": km_low.tolist(), "high": km_high.tolist()},
"model": {"months": [0, *map(int, model["meses"])], "S": [1.0, *map(float, model["S"])],
"low": [1.0, *map(float, model["IC_inf"])], "high": [1.0, *map(float, model["IC_sup"])]},
})
return sorted(records, key=lambda r: (-r["n"], list(r["combination"].values())))
def _label(combination: dict) -> str:
names = {"age_group": "edad", "cytology": "citología", "hpv": "VPH"}
return " · ".join(f"{names.get(k, k)} {v}" for k, v in combination.items())
def _figure(combination_survival: list[dict], etiquetas: dict, survival_settings: SurvivalSettings,
report_panels: int = 24):
"""The figure: one panel per combination (the `report_panels` largest), the Kaplan-Meier step curve with its band
and the model's points with their intervals (a Plotly `Figure`; the page and the notebook draw it)."""
import plotly.graph_objects as go
from plotly.subplots import make_subplots
shown = combination_survival[:report_panels]
columns = 3
rows = max(1, -(-len(shown) // columns))
figure = make_subplots(rows=rows, cols=columns, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.08 / max(rows, 1) * 3,
subplot_titles=[f"{_label(r['combination'])}<br>n = {r['n']}, defunciones = {r['deaths']}"
for r in shown])
for k, record in enumerate(shown):
row, col, first = k // columns + 1, k % columns + 1, k == 0
km, model = record["km"], record["model"]
figure.add_trace(go.Scatter(x=km["months"], y=km["high"], mode="lines", line={"width": 0, "shape": "hv"},
hoverinfo="skip", showlegend=False, legendgroup="km"), row=row, col=col)
figure.add_trace(go.Scatter(x=km["months"], y=km["low"], mode="lines", line={"width": 0, "shape": "hv"},
fill="tonexty", fillcolor="rgba(120,130,140,0.30)", name="IC 95 % Greenwood",
legendgroup="km", showlegend=first, hoverinfo="skip"), row=row, col=col)
figure.add_trace(go.Scatter(x=km["months"], y=km["S"], mode="lines", line={"color": "#242628", "width": 2, "shape": "hv"},
name=etiquetas.get("km_crudo", "Kaplan-Meier"), legendgroup="kmline", showlegend=first,
hovertemplate="mes %{x}: S = %{y:.3f}<extra>KM</extra>"), row=row, col=col)
S, low, high = np.array(model["S"]), np.array(model["low"]), np.array(model["high"])
figure.add_trace(go.Scatter(x=model["months"], y=S, mode="lines+markers", line={"color": "#6f35a5", "dash": "dot"},
marker={"symbol": "diamond", "size": 9},
error_y={"type": "data", "symmetric": False, "array": high - S, "arrayminus": S - low},
name=etiquetas.get("puntos", "Modelo (IC 95 % bootstrap)"), legendgroup="model",
showlegend=first, hovertemplate="mes %{x}: S = %{y:.3f}<extra>modelo</extra>"),
row=row, col=col)
figure.update_xaxes(range=[0, max(survival_settings.horizons) + 1], title_text=None)
figure.update_yaxes(range=[0, 1.03])
figure.update_layout(height=300 * rows + 120, template="plotly_white", margin={"t": 110},
title={"text": f"{etiquetas.get('titulo', 'Supervivencia')} — por combinación de covariables<br>"
f"<sup>{etiquetas.get('eje_x', 'Meses')}; {NOTICE}</sup>"},
legend={"orientation": "h", "y": 1.0, "yanchor": "bottom", "x": 0})
return figure
def _table(combination_survival: list[dict]) -> pd.DataFrame:
"""Every combination's counts."""
return pd.DataFrame([{**r["combination"], "n": r["n"], "defunciones": r["deaths"]} for r in combination_survival])
def subgroup_report(combination_survival: list[dict], etiquetas: dict, survival_settings: SurvivalSettings,
report_panels: int = 24) -> str:
"""The page: the figure, the table of every combination's counts and the methods."""
figure = _figure(combination_survival, etiquetas, survival_settings, report_panels)
counts = _table(combination_survival)
omitted = max(0, len(combination_survival) - report_panels)
note = (f"<p>{omitted} combinaciones más, sin panel (solo en la tabla).</p>" if omitted > 0 else "") + (
"<h3>Métodos</h3><ul>" + "".join(f"<li><b>{k}</b>: {v}</li>" for k, v in METHODS.items()) + "</ul>")
return ("<!doctype html><html lang=\"es\"><head><meta charset=\"utf-8\"><title>Supervivencia por subgrupo</title>"
"</head><body style=\"font-family:sans-serif;margin:16px\">"
+ figure.to_html(full_html=False, include_plotlyjs=True)
+ note + "<h3>Combinaciones</h3>" + counts.to_html(index=False, border=0) + "</body></html>")
def subgroups(combination_survival: list[dict]) -> dict:
"""The report's record, with the methods it used."""
return {"version": 1, "metodos": METHODS, "combinations": combination_survival}
def reports(subgroup_report: str) -> dict:
"""What the saver publishes under `reportes/`, by name."""
return {"subgrupos": subgroup_report}
+3 -3
View File
@@ -78,9 +78,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]]:
+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
View File
@@ -51,6 +51,7 @@ ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
ROUTINES_PATH = "rutinas"
ANALYSIS_PATH = "analisis"
REPORTS_PATH = "reportes"
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
@@ -197,6 +198,11 @@ 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_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()))
+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",
+282
View File
@@ -0,0 +1,282 @@
"""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}}
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. Members 241 to 244 must be left out: a CIS biopsy only (no index), 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"}
def test_the_index_is_the_first_carcinoma_biopsy_and_its_rules_leave_out_who_they_should(cohort_frame):
"""Pins down the provisional index: members 1 to 240 are indexed at their biopsy reported as invasive carcinoma, not
at an earlier CIS biopsy nor at their first observation; a CIS biopsy only (241), 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]`, counts in situ as 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)
assert set(indexed["pac_id"].unique()) == set(range(1, N + 1))
assert attrition["sin_nacimiento"] == N + 1 and attrition["defuncion_hasta_el_indice"] == N
five = cohort_frame[cohort_frame["pac_id"] == 5]
diagnosis = five[(five["tipo"] == "biopsia") & (five["valor_codigo"] == "CARCINOMA")]["fecha"].iloc[0]
assert indexed[indexed["pac_id"] == 5]["fecha_indice"].iloc[0] == diagnosis
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 the members the
scenario leaves out absent. Fails if the version cannot score a build or the estimate keeps the cohort's index."""
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"} <= set(files)
risks = pq.read_table(output).to_pandas()
assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} and set(risks["pac_id"]) == set(range(1, N + 1))
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
+82 -1
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", "report_panels", "turnbull_bootstrap"}
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
@@ -278,3 +280,82 @@ 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_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
+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"] == ["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)