Compare commits

..

4 Commits

Author SHA1 Message Date
ulises 73c5176482 CaMa recurrence: the METABRIC and SCAN-B analysis as a model over the loaded cohorts
Luis's recurrence scripts are kept as experiments. `models/cama/recurrence` holds the variable dictionary, the
scenarios and the settings as data (`model.toml`), the writer of each cohort file as CaMa import files, the recode of the
timeline into the per-patient frame and the analysis (Cramér's-V pruning, logistic terms and Bayesian-network parents per
horizon, the scenario figures). The variable reader of the survival model is public so both share it. Includes the survival
pipeline work this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:39 -06:00
luis 9c7c718a7b Tests for the SEER survival pipeline's stages and runner 2026-11-22 03:28:04 -06:00
luis 42161eb612 CaMa SEER survival pipeline: the six scripts as Hamilton DAGs, one module of nodes per stage and the heavy routines apart
Stages 01-06 (depuration, MCA balancing and categorization, bootstrap indices, stepwise LR and hybrid Bayesian network, survival curves, risk factors), settings in model.toml, run.py writing each stage's files and pipeline.py as the runner that replaces ejecutar_pipeline.py. New extras seer-survival and seer-survival-dca; experiments/ excluded from the wheel.
2026-11-22 03:28:04 -06:00
luis c70aef2a04 Keep the original SEER survival scripts as experiments (not packaged) 2026-11-22 03:28:01 -06:00
71 changed files with 3122 additions and 21341 deletions
+2 -5
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. `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/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/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,21 +30,18 @@ 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`, 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. |
| `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. |
| `annotations.py` | Validators a dataflow puts on its nodes, with no I/O: `@checked_frame(schema)`, a pandera check whose failure names columns and counts, never values. |
| `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. |
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit and its metrics. |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (`horizons_years`, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. `model.toml` (names, `modules`: its `model.py` and `steps/model_fitting.py`, and `[config]`) and `model.py` (the dataflow to `labelled_members`, and `fitted_model`: a scikit-learn `Pipeline` that takes the long frame). Its routines' records (ML-01a: `sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`) are nodes too, and the saver writes them; `train.py` only delegates to `dags/training.py`. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--read db|file] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]`, by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
| `cacu/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull or I-spline incidence, `likelihood.py`), one mixture per HPV stratum, fitted to each member's code and interval; the clinical settings (windows, known-negative results, KPNC's cytology categories, the incidence family) in `model.toml`. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `cacu/cin2_pim/report.py` | The subgroup report of every PIM scenario: per combination of the model's features, Turnbull's interval-censored estimate (prevalent at 0, free in `(l, r]`, unknown baseline in `[0, r]`) with a bootstrap band against the mixture refitted on every coded member with its delta-method band (inverse Hessian, log scale), and E/O at each horizon with log(E/O) taken as normal. `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. |
| `cacu/cin2_pim_post_colposcopy/`, `cacu/cin2_pim_post_treatment/` | `cin2_pim`'s dataflow on the post-colposcopy and post-treatment cohorts (KPNC's scenarios 4 and 5): only a `model.toml`, with KPNC's three post-colposcopy cytology groups and, after colposcopy, the referral grade (`history`). |
| `cacu/survival/` | CaCu's all-cause survival prototype: the mortality at 1, 3 and 5 years from the cancer diagnosis (provisionally the first biopsy reported as invasive carcinoma, `primera_biopsia_invasora` in `[config.index]`: both the inclusion criterion and the index date), from the age group at the diagnosis and the most recent cytology (KPNC's categories) and HPV up to it, with the SEER pipeline's interval survival as `cama/survival` runs it (LR and Bayesian network per interval, stacked) and its population record (`analisis/curvas.json`: KM with Greenwood, adjusted KM, Weibull, and LR/HBN/combined points with bootstrap intervals). The nodes that don't depend on the covariates are CaMa's, called from here; `encode`, `interval_cohort`, `IntervalSurvival`, `labelled_members`, `missing_data`, `analytic_method` and `survival_frame` are copies over CaCu's covariates (issue #9). A version also keeps a subgroup report (`report.py`): per combination of the covariates, the Kaplan-Meier with its Greenwood band against the model's survival with the SEER subgroups' bootstrap interval (`sv_sub_points`), as `analisis/subgrupos.json` (with its methods) and the Plotly page `reportes/subgrupos.html`. The death is the timeline's `defuncion` event, emitted by the CaCu dbt timeline (monorepo, same branch). |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `<escenario>/notebooks/`, fuera del paquete instalado. |
| `tea/eeg/` | TEA's EEG analysis on one EDF, with the `tea` library (`libs/tea`, a submodule installed editable): `model.toml` maps each `MetricaEeg` code to a library feature, provisional until the domain expert confirms it (spindles once per sleep stage, with their value per electrode); `analyze.measure` runs validation, preprocessing, the processes and the biomarkers on the EDF's bytes, without the database, so a Dask worker can run it; `baselines.Baselines` compares a value with its age baseline in production (`tea-eeg-<biomarker>[-<stage>]`): z, -1/0/+1 and the curve's p5/median/p95 at the age. |
| `tea/eeg/train.py`, `tea/eeg/model.py` | TEA's age baselines: `python -m models run tea eeg --train [--promote] [--environment prod]` lists the reference cohort (`[reference]` of `model.toml`: HK1K, 16 to 36 months, 50 Hz mains) in a Dask worker from the cluster's S3 (the `eeg-reference` extra), measures each study with the analysis's own unit of work (`analyze.reference`), and trains each scenario (biomarker and sleep stage) with the library, registered as `tea-eeg-<biomarker>[-<stage>]` through `tea.serving.log_biomarker` and tagged with what promotion checks: environment, the reference cohort (`cohort.source = referencia`, the listing's hash: ML-03), the trained state's hash (ML-01b), the five routine records (ML-01a) and metrics. A scenario already trained on the same listing, plan, module version and baseline isn't trained again. Promotion waits for the technical, clinical and interpretability reports, like any model. It must register in the MLflow the platform reads (`MLFLOW_TRACKING_URI`); with a remote scheduler (`DASK_SCHEDULER_ADDRESS`), the workers need `models` and `tea` installed. |
| `tea/eeg/reference.py`, `tea/eeg/bundle.py` | Training the baselines where the EEGs live and shipping only the result. `models run tea eeg --train --reference-dir DIR [--reference-ages edades.csv] [--reference-name NAME] [--line-hz 60]` trains on a folder of EDFs on this machine (ages from the table's `archivo` and `edad_meses` or `edad_anos`, or from each EDF header); file names stay in the listing, keyed by position. `models tea export-baselines --out baselines.zip [--environment prod] [--production]` writes every scenario's trained module, plan, routine records, metrics and promotion tags, with a SHA-256 manifest, after the library's privacy guard; `models tea import-baselines baselines.zip` checks the manifest, accepts only the module class the platform runs for each scenario, requires the trained module's hash, and registers new versions with the same tags (an already-registered module is kept). Promotion still waits for the three reports. |
| `eeg_analysis.py` | The EEG analysis against TEA's database: the pending EEGs (an EDF never analysed, or analysed with another plan, other module versions or other baselines), the batch (`cluster`: this process, a LocalCluster or `DASK_SCHEDULER_ADDRESS`), each result written to `eeg`, `eeg_criterio`, `eeg_metrica` and `eeg_metrica_electrodo` with ids that survive a re-analysis, and one governance `ExtractionRun` per EEG. `python -m models tea analyze [--all] [--limit N] [--cluster auto\|local\|remote\|sync]`. |
| `cama/seer_survival/` | CaMa's SEER survival pipeline, ported from six scripts into Hamilton DAGs, one per stage (extra `seer-survival`). Settings in `model.toml` (`settings.py`); paths are inputs, never settings. Each stage is a module of nodes plus, where the routine is heavy, a module of plain functions apart (as `tea/eeg/analyze.py`): `depuration.py` + `depuration_stats.py` (01: Theil's U and GVIF redundancy screen and its threshold calibration), `balancing.py` + `balancing_stats.py` and `categorization.py` + `categorization_stats.py` (02: 18-month outcome, MCA undersampling, Bayesian change-point grouping of age and tumor size, categorization proposals), `bootstrap.py` (03: resample indices), `modeling.py` + `lr_selection.py`, `hbn.py`, `natural.py`, `resampling.py` + `replica.py` (04: stepwise LR, hybrid Bayesian network, natural-population LR, bootstrap and proposal replicas), `survival_curves.py` + `survival_models.py`, `fractional_weibull.py` (05: Kaplan-Meier, classic and Kilbas-Saigo Weibull, stacked LR + HBN survival, subgroups) and `risk_factors.py` + `risk_factor_stats.py` (06: four-criteria risk factors). `run.py` writes each stage's files; `pipeline.py` runs them in order, skipping the current ones: `python -m models.cama.seer_survival --data DIR [--solo 05] [--desde 02] [--forzar 02 04] [--todo]`. |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
+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.cacu.cin2_pim.report", "models.steps.indexing"]
modules = ["models.cacu.cin2_pim.model", "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 \
@@ -1,123 +0,0 @@
{
"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
@@ -1,268 +0,0 @@
"""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.cacu.cin2_pim.report", "models.steps.indexing"]
modules = ["models.cacu.cin2_pim.model", "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", "models.cacu.cin2_pim.report"]
modules = ["models.cacu.cin2_pim.model"]
description = """
Prototipo: riesgo acumulado de CIN2+ desde la primera citología después del tratamiento, en la visita y a 1, 3 y 5 años \
(escenario 5 de ASCCP 2019; tablas 24 y 5 de KPNC). Mezcla prevalencia–incidencia con I-splines, una sola línea \
View File
-156
View File
@@ -1,156 +0,0 @@
"""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
@@ -1,151 +0,0 @@
"""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
@@ -1,87 +0,0 @@
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"]
@@ -1,119 +0,0 @@
{
"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
@@ -1,87 +0,0 @@
"""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
@@ -1,136 +0,0 @@
"""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}
@@ -0,0 +1,71 @@
import json
import os
import numpy as np
import pandas as pd
CSV_ENTRADA = "./brca_metabric_clinical_data.tsv"
DIR_INT = "./intermedios_recurrencia"
os.makedirs(DIR_INT, exist_ok=True)
V_MAX = 0.80
d = pd.read_csv(CSV_ENTRADA, sep="\t")
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["Patient ID"]})
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
def con_desconocido(s):
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
def cortar(s, cortes, etiquetas):
c = pd.cut(s, cortes, labels=etiquetas, right=False)
return con_desconocido(c.astype("object"))
out["Edad"] = cortar(d["Age at Diagnosis"], [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
out["Tamano_tumor"] = cortar(d["Tumor Size"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
out["Ganglios_positivos"] = cortar(d["Lymph nodes examined positive"], [0, 1, 4, 1e3], ["0", "1-3", "4+"])
out["Grado_histologico"] = con_desconocido(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
mc = d["Mutation Count"]
q = mc.quantile([1 / 3, 2 / 3]).values
out["Carga_mutacional"] = cortar(mc, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
for nombre, col in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
out[nombre] = con_desconocido(d[col])
TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento")]
def cramer_v(a, b):
t = pd.crosstab(a, b)
from scipy.stats import chi2_contingency
chi2 = chi2_contingency(t, correction=False)[0]
n = t.values.sum()
k = min(t.shape) - 1
return np.sqrt(chi2 / (n * k)) if k > 0 else 0.0
eliminadas = []
cand = [c for c in covariables if c not in TRATAMIENTO]
pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True)
for v, a, b in pares:
if v < V_MAX:
break
if a in eliminadas or b in eliminadas:
continue
na_a, na_b = (out[a] == "Desconocido").mean(), (out[b] == "Desconocido").mean()
quitar = a if na_a >= na_b else b
eliminadas.append(quitar)
covariables.remove(quitar)
pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia.csv", index=False)
out = out[["paciente", "tiempo_meses", "evento"] + covariables]
out.to_csv(f"{DIR_INT}/cohorte_recurrencia.csv", index=False)
with open(f"{DIR_INT}/covariables_recurrencia.json", "w", encoding="utf8") as f:
json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables],
"eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False)
@@ -0,0 +1,70 @@
import json
import os
import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency
CSV_ENTRADA = "./scanb_clinical_metadata.txt"
V_MAX = 0.80
DIAS_POR_MES = 30.4375
DIR_INT = "./intermedios_recurrencia"
os.makedirs(DIR_INT, exist_ok=True)
d = pd.read_csv(CSV_ENTRADA, sep="\t", low_memory=False)
d = d[d["Gender"] == "F"]
d = d.dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["PatientName"]})
out["tiempo_meses"] = d["RFI_days"].astype(float) / DIAS_POR_MES
out["evento"] = d["RFI_event"].astype(int)
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
def con_desconocido(s):
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
def cortar(s, cortes, etiquetas):
return con_desconocido(pd.cut(s, cortes, labels=etiquetas, right=False).astype("object"))
out["Edad"] = cortar(d["Age_5year_bin"].astype(float) - 2, [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
out["Tamano_tumor"] = cortar(d["TumorSize_mm"], [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
out["Ganglios_positivos"] = con_desconocido(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
out["Grado_histologico"] = con_desconocido(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
for nombre, col in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
out[nombre] = con_desconocido(d[col])
TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
covariables = [c for c in out.columns if c not in ("paciente", "tiempo_meses", "evento", "muerte_sin_recaida")]
def cramer_v(a, b):
t = pd.crosstab(a, b)
chi2 = chi2_contingency(t, correction=False)[0]
k = min(t.shape) - 1
return np.sqrt(chi2 / (t.values.sum() * k)) if k > 0 else 0.0
eliminadas = []
cand = [c for c in covariables if c not in TRATAMIENTO]
pares = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(cand) for b in cand[i + 1:]), reverse=True)
for v, a, b in pares:
if v < V_MAX:
break
if a in eliminadas or b in eliminadas:
continue
quitar = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b
eliminadas.append(quitar)
covariables.remove(quitar)
pd.DataFrame({"variable_eliminada": eliminadas}).to_csv(f"{DIR_INT}/variables_eliminadas_recurrencia_scanb.csv", index=False)
out = out[["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] + covariables]
out.to_csv(f"{DIR_INT}/cohorte_recurrencia_scanb.csv", index=False)
with open(f"{DIR_INT}/covariables_recurrencia_scanb.json", "w", encoding="utf8") as f:
json.dump({"covariables": covariables, "tratamiento": [c for c in TRATAMIENTO if c in covariables],
"eliminadas_por_colinealidad": eliminadas}, f, indent=2, ensure_ascii=False)
@@ -0,0 +1,261 @@
import json
import os
import sys
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.calibration import calibration_curve
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.estimators import HillClimbSearch, BDeu
from pgmpy.causal_discovery import ExpertKnowledge
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import networkx as nx
warnings.filterwarnings("ignore")
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia"
os.makedirs(DIR_INT, exist_ok=True)
os.makedirs(DIR_FIG, exist_ok=True)
SEMILLA = 42
N_BOOTSTRAP = int(os.environ.get("N_BOOTSTRAP", 100 if COHORTE == "metabric" else 40))
BDEU_ESS = 10
MAX_PADRES = 6
ALFA_IN, ALFA_OUT, ALFA_PREFILTRO = 0.10, 0.15, 0.10
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
covariables = meta["covariables"]
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables})
TIER_DEMOGRAFIA = ["Edad", "Estado_menopausico"]
TIER_TUMOR = ["Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
"Receptor_progesterona", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Cluster_integrativo", "Lateralidad",
"Ki67", "Subtipo_clinico", "Estadio_clinico"]
TIER_TRATAMIENTO = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
# ---- funciones ----
def orden_temporal(cols):
tiers = [[c for c in t if c in cols] for t in (TIER_DEMOGRAFIA, TIER_TUMOR, TIER_TRATAMIENTO, ["outcome"])]
sin = [c for c in cols if c not in sum(tiers, [])]
return ([sin] if sin else []) + [t for t in tiers if t]
def codificar(df):
X = pd.get_dummies(df[covariables], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
def ajuste_logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def prefiltro(X, y):
keep = []
for c in X.columns:
m = ajuste_logit(y, X[[c]])
if m is not None and m.pvalues[c] < ALFA_PREFILTRO:
keep.append(c)
return keep
def stepwise(X, y):
incl = []
for _ in range(200):
cambio = False
mejor, p_mejor = None, ALFA_IN
for c in [c for c in X.columns if c not in incl]:
m = ajuste_logit(y, X[incl + [c]])
if m is not None and m.pvalues[c] < p_mejor:
mejor, p_mejor = c, m.pvalues[c]
if mejor is not None:
incl.append(mejor)
cambio = True
if incl:
m = ajuste_logit(y, X[incl])
if m is not None:
p = m.pvalues.drop("const")
if p.max() > ALFA_OUT:
incl.remove(p.idxmax())
cambio = True
if not cambio:
break
return incl
def lr_completo(df_train, df_test):
Xall = codificar(pd.concat([df_train, df_test]))
Xtr, Xte = Xall.loc[df_train.index], Xall.loc[df_test.index]
Xtr = Xtr.loc[:, Xtr.nunique() > 1]
Xte = Xte[Xtr.columns]
cand = prefiltro(Xtr, df_train["y"])
sel = stepwise(Xtr[cand], df_train["y"]) if cand else []
if not sel:
return None, [], np.full(len(df_test), df_train["y"].mean())
m = ajuste_logit(df_train["y"], Xtr[sel])
return m, sel, m.predict(sm.add_constant(Xte[sel], has_constant="add")).values
def variable_de(t):
return next((c for c in sorted(covariables, key=len, reverse=True) if t.startswith(c + "_")), t)
def padres_outcome(train, candidatos):
sc = BDeu(train, equivalent_sample_size=BDEU_ESS)
padres, actual = [], sc.local_score("outcome", [])
while len(padres) < MAX_PADRES:
mejor, ganancia = None, 0
for c in candidatos:
if c in padres:
continue
g = sc.local_score("outcome", padres + [c]) - actual
if g > ganancia:
mejor, ganancia = c, g
if mejor is None:
break
padres.append(mejor)
actual += ganancia
return padres
def prob_hbn(train, test, padres):
if not padres:
return np.full(len(test), (train["outcome"] == "1").mean())
q = int(np.prod([train[p].nunique() for p in padres]))
alpha = BDEU_ESS / (2 * q)
g = train.groupby(padres)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
p_glob = (train["outcome"] == "1").mean()
tabla = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
return np.array([tabla.get(k, p_glob) for k in map(tuple, test[padres].values)])
def tabla_bn(df):
t = df[covariables].astype(str).copy()
t["outcome"] = df["y"].astype(int).astype(str)
return t
def cohorte_a_horizonte(H):
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
libre = coh_total["tiempo_meses"] > H
d = coh_total[recurre | libre].reset_index(drop=True)
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
return d
# ---- Cox de referencia (tiempo completo) ----
cox_df = pd.get_dummies(coh_total[["tiempo_meses", "evento"] + covariables], columns=covariables, drop_first=True).astype(float)
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
ctr, cte = train_test_split(cox_df, test_size=0.3, random_state=SEMILLA, stratify=cox_df["evento"])
_ok = [c for c in ctr.columns if c in ("tiempo_meses", "evento") or 10 <= ctr[c].sum() <= len(ctr) - 10]
ctr, cte = ctr[_ok], cte[_ok]
cox = CoxPHFitter(penalizer=0.05).fit(ctr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
c_index = concordance_index(cte["tiempo_meses"], -cox.predict_partial_hazard(cte), cte["evento"])
# ---- modelos por horizonte ----
filas_auc, modelos_json, curvas = [], {}, {}
for H in HORIZONTES:
coh = cohorte_a_horizonte(H)
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=SEMILLA, stratify=coh["y"])
tr, te = coh.loc[tr_idx], coh.loc[te_idx]
modelo_lr, sel_lr, p_lr = lr_completo(tr, te)
auc_lr = roc_auc_score(te["y"], p_lr)
bn_tr, bn_te = tabla_bn(tr), tabla_bn(te)
padres = padres_outcome(bn_tr, covariables)
p_hbn = prob_hbn(bn_tr, bn_te, padres)
auc_hbn = roc_auc_score(te["y"], p_hbn)
if H == max(HORIZONTES):
expert = ExpertKnowledge(temporal_order=orden_temporal(list(bn_tr.columns)))
estructura = HillClimbSearch(bn_tr).estimate(scoring_method=BDeu(bn_tr, equivalent_sample_size=BDEU_ESS), max_indegree=4,
expert_knowledge=expert, show_progress=False)
arcos_red = [(u, v) for u, v in estructura.edges() if u != "outcome" and v != "outcome"] + [(p, "outcome") for p in padres]
G = nx.DiGraph(arcos_red)
plt.figure(figsize=(10, 7))
nx.draw(G, nx.spring_layout(G, seed=SEMILLA, k=0.9), with_labels=True, node_color="lightblue", node_size=2200, font_size=7, arrowsize=14)
plt.title(f"Estructura de la red bayesiana ({COHORTE}, {H} meses)")
plt.tight_layout()
plt.savefig(f"{DIR_FIG}/hbn_estructura_{COHORTE}.png", dpi=150)
plt.close()
rng = np.random.default_rng(SEMILLA)
aucs, cuenta_lr, cuenta_hbn, n_lr, n_hbn = [], {}, {}, 0, 0
for b in range(N_BOOTSTRAP):
db = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
try:
dtr, dte = train_test_split(db, test_size=0.3, random_state=SEMILLA + b, stratify=db["y"])
m, sel, p = lr_completo(dtr, dte)
a_lr = roc_auc_score(dte["y"], p)
btr, bte = tabla_bn(dtr), tabla_bn(dte)
pa = padres_outcome(btr, covariables)
a_h = roc_auc_score(dte["y"], prob_hbn(btr, bte, pa))
except Exception:
continue
aucs.append((a_lr, a_h))
n_lr += 1
n_hbn += 1
if m is not None:
for v in {variable_de(t) for t in m.params.drop("const").index}:
cuenta_lr[v] = cuenta_lr.get(v, 0) + 1
for v in pa:
cuenta_hbn[v] = cuenta_hbn.get(v, 0) + 1
aucs = np.array(aucs)
for j, (nombre, auc_int) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": H, "modelo": nombre, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
"AUC_validacion_interna": auc_int, "AUC_bootstrap_medio": aucs[:, j].mean(),
"AUC_bootstrap_IC95_inf": np.percentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.percentile(aucs[:, j], 97.5),
"replicas_bootstrap": len(aucs)})
ci = modelo_lr.conf_int()
modelos_json[str(H)] = {"terminos_lr": list(sel_lr), "padres_hbn": padres, "n_replicas": n_lr,
"seleccion_lr": cuenta_lr, "seleccion_hbn": cuenta_hbn,
"arcos_hbn": [list(a) for a in (arcos_red if H == max(HORIZONTES) else [(p, "outcome") for p in padres])]}
curvas[H] = (te["y"].values, p_lr, p_hbn)
filas_auc.append({"cohorte": COHORTE, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(coh_total),
"recurrencias": int(coh_total["evento"].sum()), "AUC_validacion_interna": c_index})
json.dump(modelos_json, open(f"{DIR_INT}/modelos{SFX}.json", "w", encoding="utf8"), indent=1, ensure_ascii=False)
# ---- consolidado de AUC (un solo archivo con las dos cohortes) ----
nuevo = pd.DataFrame(filas_auc)
destino = "./auc_recurrencia.csv"
if os.path.exists(destino):
previo = pd.read_csv(destino)
previo = previo[~((previo["cohorte"] == COHORTE) & (previo["horizonte_meses"].astype(str).isin([str(h) for h in HORIZONTES] + ["completo"])))]
nuevo = pd.concat([previo, nuevo], ignore_index=True)
nuevo.round(4).to_csv(destino, index=False)
# ---- figuras: ROC y calibracion (un panel por horizonte) ----
for nombre_fig, tipo in [("roc", "roc"), ("calibracion", "cal")]:
fig, axs = plt.subplots(1, len(HORIZONTES), figsize=(5.2 * len(HORIZONTES), 5), squeeze=False)
for ax, H in zip(axs[0], HORIZONTES):
y, pl, ph = curvas[H]
for nom, p in [("LR", pl), ("HBN", ph)]:
if tipo == "roc":
f, t, _ = roc_curve(y, p)
ax.plot(f, t, label=f"{nom} (AUC {roc_auc_score(y, p):.3f})")
else:
fr, mp = calibration_curve(y, p, n_bins=8, strategy="quantile")
ax.plot(mp, fr, "o-", label=nom)
ax.plot([0, 1], [0, 1], "k:")
ax.set_title(f"{COHORTE}: {H} meses")
ax.set_xlabel("1 - especificidad" if tipo == "roc" else "probabilidad predicha de recurrencia")
ax.set_ylabel("sensibilidad" if tipo == "roc" else "frecuencia observada")
ax.legend()
fig.tight_layout()
fig.savefig(f"{DIR_FIG}/{nombre_fig}_{COHORTE}.png", dpi=150)
plt.close(fig)
@@ -0,0 +1,158 @@
import sys
import os
import json
import numpy as np
import pandas as pd
import statsmodels.api as sm
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
DIR_INT = "./intermedios_recurrencia"
ALFA = 0.05
FREQ_MIN = 0.80
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
variables = meta["covariables"]
tratamiento = meta["tratamiento"]
intrinsecas = [v for v in variables if v not in tratamiento]
modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8"))
coh_total = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in variables})
# ---- funciones ----
def bh(p):
p = np.asarray(p, float)
orden = np.argsort(p)
aj = np.empty_like(p)
m = len(p)
prev = 1.0
for rango, i in zip(range(m, 0, -1), orden[::-1]):
prev = min(prev, p[i] * m / rango)
aj[i] = prev
return aj
def variable_de(termino, vars_modelo):
return next(v for v in sorted(vars_modelo, key=len, reverse=True) if termino.startswith(v + "_"))
def km_en(m, e, h):
T = int(m.max()) + 2
d = np.bincount(m[e], minlength=T)
c = np.bincount(m[~e], minlength=T)
en_riesgo = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(en_riesgo > 0, 1 - d / np.maximum(en_riesgo, 1), 1.0)
v = np.where((en_riesgo > 0) & (en_riesgo > d), d / (np.maximum(en_riesgo, 1) * np.maximum(en_riesgo - d, 1)), 0.0)
h = min(h, T - 1)
S = np.prod(q[:h + 1])
return S, S * np.sqrt(np.sum(v[:h + 1]))
def procesar_horizonte(H):
recurre = (coh_total["evento"] == 1) & (coh_total["tiempo_meses"] <= H)
libre = coh_total["tiempo_meses"] > H
datos_km = coh_total.copy()
coh = coh_total[recurre | libre].reset_index(drop=True)
datos = coh[variables].astype(str)
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
meses = np.floor(np.minimum(datos_km["tiempo_meses"].values, H + 1)).astype(int)
evento = ((datos_km["evento"] == 1) & (datos_km["tiempo_meses"] <= H)).values
datos_km = datos_km[variables].astype(str)
def referencia(v):
return datos[v].value_counts().idxmax()
def ajustar_or(vars_modelo):
X = pd.get_dummies(datos[vars_modelo], drop_first=False).astype(float)
refs = {v: f"{v}_{referencia(v)}" for v in vars_modelo}
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
modelo = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ic = modelo.conf_int()
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(modelo.params[X.columns].values),
"IC95_inf": np.exp(ic.loc[X.columns, 0].values), "IC95_sup": np.exp(ic.loc[X.columns, 1].values),
"p": modelo.pvalues[X.columns].values})
def delta_s(v, cat, ref):
a = (datos_km[v] == cat).values
b = (datos_km[v] == ref).values
Sa, ea = km_en(meses[a], evento[a], H)
Sb, eb = km_en(meses[b], evento[b], H)
d = Sa - Sb
es = np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
"delta_IC95_inf": d - 1.96 * es, "delta_IC95_sup": d + 1.96 * es})
def completar(t, vars_modelo):
t = t.copy()
t["variable"] = [variable_de(x, vars_modelo) for x in t["termino"]]
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
t["referencia"] = [referencia(v) for v in t["variable"]]
t["p_ajustado_BH"] = bh(t["p"])
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab = completar(ajustar_or(intrinsecas), intrinsecas)
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALFA)
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
mh = modelos.get(str(H), {})
n_rep = mh.get("n_replicas", 0)
sel = mh.get("seleccion_lr", {})
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: sel.get(v, 0) / n_rep if n_rep else np.nan)
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
manta = set(mh.get("padres_hbn", []))
tab["en_manta_markov"] = tab["variable"].isin(manta)
tab["c3_manta_markov"] = tab["en_manta_markov"]
crit = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
tab["criterios_cumplidos"] = tab[crit].astype(bool).sum(axis=1)
def clasificar(r):
if r["categoria"] == "Desconocido":
return "no aplica (categoria desconocida)"
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
return f"{r['direccion']} robusto"
if r["criterios_cumplidos"] >= 2:
return f"{r['direccion']} sugerente"
return "no concluyente"
tab["clasificacion"] = tab.apply(clasificar, axis=1)
tab["tipo"] = "factor de riesgo"
if tratamiento:
tr = ajustar_or(intrinsecas + tratamiento)
tr["_v"] = [variable_de(t, intrinsecas + tratamiento) for t in tr["termino"]]
tr = tr[tr["_v"].isin(tratamiento) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
tr = completar(tr, tratamiento)
tr["tipo"] = "tratamiento"
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"] = COHORTE
tab["horizonte_meses"] = H
return tab
columnas = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "clasificacion"]
orden = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
nuevo = pd.concat([procesar_horizonte(H) for H in HORIZONTES], ignore_index=True)
nuevo["_t"] = (nuevo["tipo"] != "factor de riesgo").astype(int)
nuevo["_o"] = nuevo["clasificacion"].map(orden).fillna(5)
nuevo = nuevo.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[columnas]
destino = "./factores_riesgo_recurrencia.csv"
if os.path.exists(destino):
previo = pd.read_csv(destino)
previo = previo[previo["cohorte"] != COHORTE]
nuevo = pd.concat([previo, nuevo], ignore_index=True)
nuevo.round(4).to_csv(destino, index=False)
@@ -0,0 +1,450 @@
import sys
import os
import re
import json
import time
import subprocess
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy.optimize import minimize
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
try:
import mpmath as mp
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "mpmath"])
import mpmath as mp
COHORTE = sys.argv[1] if len(sys.argv) > 1 else "metabric"
HORIZONTES = [int(h) for h in sys.argv[2:]] or [12, 36, 60]
SFX = "" if COHORTE == "metabric" else f"_{COHORTE}"
DIR_INT, DIR_FIG = "./intermedios_recurrencia", "./figuras_recurrencia"
os.makedirs(DIR_FIG, exist_ok=True)
SEMILLA = 42
B_BOOT = int(os.environ.get("N_BOOT_CALC", 200))
MIN_EVENTOS = 15
TOPE_MESES = 72
BDEU_ESS = 10
COLOR_PUNTOS, MARCA_PUNTOS = "#6a3d9a", "D"
SUBGRUPOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
}[COHORTE]
# ---- ajuste parametrico (Weibull y Weibull fraccional de Kilbas-Saigo) ----
from functools import lru_cache
from scipy.special import gammaln
@lru_cache(maxsize=256)
def _coefs(rho, m, l, N, dps):
mp.mp.dps = dps
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
c = [mp.mpf(1)]
for i in range(N - 1):
c.append(c[-1] * mp.exp(mp.loggamma(rho*(m*i + l) + 1) - mp.loggamma(rho*(m*i + l + 1) + 1)))
return tuple(c)
def _log_terms(az, rho, m, l, N):
i = np.arange(N - 1)
logc = np.concatenate([[0.0], np.cumsum(gammaln(rho*(m*i + l) + 1) - gammaln(rho*(m*i + l + 1) + 1))])
n = np.arange(N)
with np.errstate(divide="ignore"):
lt = logc[None, :] + n[None, :] * np.log(np.where(az[:, None] > 0, az[:, None], 1.0))
return lt
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
z = np.atleast_1d(np.asarray(z, float)); rho, m, l = float(rho), float(m), float(l)
out = np.full(z.shape, np.nan)
az = np.abs(z)
N = 400
lt = _log_terms(az, rho, m, l, N)
lmax, llast = lt.max(axis=1), lt[:, -1]
zero = az == 0
out[zero] = 1.0
okf = (~zero) & (lmax <= 12.0) & (llast < -40.0)
if okf.any():
terms = np.exp(lt[okf]) * ((-1.0) ** np.arange(N))[None, :]
terms[:, 0] = 1.0
out[okf] = terms.sum(axis=1)
rest = np.where(~zero & ~okf)[0]
if rest.size:
with np.errstate(over="ignore"):
est = np.where(az[rest] > 1, az[rest] ** (1.0 / rho) / m, 0.0)
est = np.maximum(est, lmax[rest])
use = rest[est <= logmax_cap]
if use.size:
est_u = est[est <= logmax_cap]
dps = 30 + int(est_u.max() / 2.3) + 10
zmax = float(az[use].max())
with np.errstate(over="ignore"):
N2 = int(min(nmax, 3 * zmax ** (1.0 / rho) / (rho * m) + 100))
N2 = max(N2, 60)
while True:
c = _coefs(round(rho, 12), round(m, 12), round(l, 12), N2, dps)
mp.mp.dps = dps
last = abs(c[-1]) * mp.mpf(zmax) ** (N2 - 1)
if last < tol or N2 >= nmax:
break
N2 *= 2
if last < tol:
cr = list(c)[::-1]
for j in use:
out[j] = float(mp.polyval(cr, mp.mpf(float(z[j]))))
return out
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
tau1 = lam if tau1 is None else tau1
tau2 = lam if tau2 is None else tau2
t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0:
return np.full_like(t, np.nan)
m = s/beta + 1; l = s/beta
pref = float(mp.exp(mp.loggamma(k+1) - mp.loggamma(k+alpha-1)))
with np.errstate(divide="ignore", invalid="ignore"):
z = -pref * (t/lam)**k * (t/tau1)**(alpha-1) * (t/tau2)**(beta-1)
z = np.where(t > 0, z, 0.0)
res = np.ones_like(t)
pos = t > 0
if pos.any():
res[pos] = kilbas_saigo(z[pos], beta, m, l)
return np.clip(res, 0.0, 1.0)
def S_weibull(t, k, lam):
t = np.asarray(t, float)
return np.exp(-(t/lam)**k)
def tabla_eventos(meses, evento):
meses = np.asarray(meses, int); evento = np.asarray(evento, bool)
T = int(meses.max()) + 2
d = np.bincount(meses[evento], minlength=T); c = np.bincount(meses[~evento], minlength=T)
return d, c
def _nll_from_S(Sfun, d, c):
T = len(d)
grid = np.arange(0, T + 1, dtype=float)
Sg = Sfun(grid)
mid = Sfun(np.arange(T) + 0.5)
pe = np.clip(Sg[:-1] - Sg[1:], 1e-300, None)
if not (np.all(np.isfinite(Sg)) and np.all(np.isfinite(mid))):
return 1e12
return -(np.sum(d * np.log(pe)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
def ajustar_weibull(d, c):
f = lambda p: _nll_from_S(lambda t: S_weibull(t, np.exp(p[0]), np.exp(p[1])), d, c)
best = None
for k0 in (0.7, 1.0, 1.5):
for l0 in (50., 200., 1000.):
r = minimize(f, [np.log(k0), np.log(l0)], method="Nelder-Mead",
options=dict(xatol=1e-5, fatol=1e-8, maxiter=2000))
if best is None or r.fun < best.fun: best = r
k, lam = np.exp(best.x)
return dict(modelo="Weibull", k=k, alpha=1.0, beta=1.0, lam=lam, nll=best.fun, n_par=2,
S=lambda t: S_weibull(t, k, lam))
def ajustar_ks(d, c, k_fijo=1.0, lam_ref=None, max_seg=120):
amin = max(0.0, 1.0 - k_fijo) + 1e-6
def unpack(p):
return amin + np.exp(p[0]), 1/(1+np.exp(-p[1])), np.exp(p[2])
T_max = float(len(d))
t_fin = time.time() + max_seg
agotado = [False]
def f(p):
if time.time() > t_fin:
agotado[0] = True
return 1e12
a, b, lam = unpack(p)
if k_fijo + a <= 1 or k_fijo + a + b <= 2 or not (1.0 <= lam <= 1e7) or (T_max / lam) ** (k_fijo + a + b - 2) > 300:
return 1e12
try:
return _nll_from_S(lambda t: S_ks(t, k_fijo, a, b, lam), d, c)
except Exception:
return 1e12
lams = [lam_ref] if lam_ref else []
lams += [100., 500.]
best = None
inicios = []
if lam_ref:
inicios.append([np.log(max(1.0 - amin, 1e-9)), 8.0, np.log(lam_ref)])
for l0 in lams:
for a0 in (0.3, 1.0):
for b0 in (0.5, 0.9):
inicios.append([np.log(a0), np.log(b0/(1-b0)), np.log(l0)])
for p0 in inicios:
if time.time() > t_fin and best is not None: break
r = minimize(f, p0, method="Nelder-Mead", options=dict(xatol=1e-5, fatol=1e-9, maxiter=1200))
if best is None or r.fun < best.fun: best = r
a, b, lam = unpack(best.x)
return dict(modelo="Kilbas-Saigo", k=k_fijo, alpha=a, beta=b, lam=lam, nll=best.fun, n_par=3,
S=lambda t: S_ks(t, k_fijo, a, b, lam))
def km_curva(meses_int, evento, T):
d, c = tabla_eventos(meses_int, evento)
L = max(len(d), T + 1)
d = np.pad(d, (0, L - len(d))); c = np.pad(c, (0, L - len(c)))
nr = len(meses_int) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(nr > 0, 1 - d / np.maximum(nr, 1), 1.0)
v = np.where((nr > 0) & (nr > d), d / (np.maximum(nr, 1) * np.maximum(nr - d, 1)), 0.0)
S = np.concatenate([[1.0], np.cumprod(q)])[:T + 1]
V = np.concatenate([[0.0], np.cumsum(v)])[:T + 1]
with np.errstate(divide="ignore", invalid="ignore"):
se = np.sqrt(V) / np.abs(np.log(S))
lo = np.where((S > 0) & (S < 1), S ** np.exp(1.96 * se), S)
hi = np.where((S > 0) & (S < 1), S ** np.exp(-1.96 * se), S)
return S, lo, hi
# ---- datos y modelos ya seleccionados en 03_modelado.py ----
meta = json.load(open(f"{DIR_INT}/covariables_recurrencia{SFX}.json", encoding="utf8"))
covariables = meta["covariables"]
modelos = json.load(open(f"{DIR_INT}/modelos{SFX}.json", encoding="utf8"))
df = pd.read_csv(f"{DIR_INT}/cohorte_recurrencia{SFX}.csv", dtype={c: str for c in covariables})
N = len(df)
meses_int = np.floor(df["tiempo_meses"].values).astype(int)
evento = (df["evento"] == 1).values
tiempo, ev_num = df["tiempo_meses"].values, df["evento"].values
X_dum = pd.get_dummies(df[covariables], drop_first=True).astype(float)
codigos = {v: pd.factorize(df[v])[0] for v in covariables}
niveles = {v: int(codigos[v].max()) + 1 for v in covariables}
def ajuste_logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def prob_lr(idx_ent, y_ent, terminos):
if not terminos:
return np.full(N, y_ent.mean())
m = ajuste_logit(y_ent, X_dum.iloc[idx_ent][terminos])
if m is None:
return None
return m.predict(sm.add_constant(X_dum[terminos], has_constant="add")).values
def clave(padres, filas):
k = np.zeros(len(filas), dtype=np.int64)
for p in padres:
k = k * niveles[p] + codigos[p][filas]
return k
def prob_hbn(idx_ent, y_ent, padres):
if not padres:
return np.full(N, y_ent.mean())
q = int(np.prod([niveles[p] for p in padres]))
alpha = BDEU_ESS / (2 * q)
k_ent = clave(padres, idx_ent)
n = pd.Series(1, index=k_ent).groupby(level=0).sum()
n1 = pd.Series(y_ent, index=k_ent).groupby(level=0).sum()
tabla = (n1 + alpha) / (n + 2 * alpha)
p_glob = y_ent.mean()
return tabla.reindex(clave(padres, np.arange(N))).fillna(p_glob).values
def riesgos(idx, H):
t, e = tiempo[idx], ev_num[idx]
rec = (e == 1) & (t <= H)
ok = rec | (t > H)
ent = idx[ok]
y = rec[ok].astype(int)
mh = modelos[str(H)]
pl = prob_lr(ent, y, mh["terminos_lr"])
ph = prob_hbn(ent, y, mh["padres_hbn"])
if pl is None:
return None
return pl, ph
def riesgo_subgrupo(idx, masks):
out = {n: np.full(len(HORIZONTES), np.nan) for n in masks}
for j, H in enumerate(HORIZONTES):
r = riesgos(idx, H)
if r is None:
return None
comb = (r[0] + r[1]) / 2
for n, mk in masks.items():
sel = mk[idx]
if sel.any():
out[n][j] = comb[idx][sel].mean()
return out
# ---- subgrupos y bootstrap ----
MASCARAS = {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in SUBGRUPOS.items()}
todos = np.arange(N)
puntos = riesgo_subgrupo(todos, MASCARAS)
rng = np.random.default_rng(SEMILLA)
boots = {n: [] for n in MASCARAS}
for b in range(B_BOOT):
r = riesgo_subgrupo(rng.integers(0, N, N), MASCARAS)
if r is None:
continue
for n in MASCARAS:
boots[n].append(r[n])
def graficar(nombre, mk):
sub = df[mk]
n_, ev_ = len(sub), int(sub["evento"].sum())
if n_ == 0 or ev_ < MIN_EVENTOS:
return None
m_s, e_s = meses_int[mk], evento[mk]
d_, c_ = tabla_eventos(m_s, e_s)
w_ = ajustar_weibull(d_, c_)
ks_ = ajustar_ks(d_, c_, k_fijo=w_["k"], lam_ref=w_["lam"], max_seg=60)
Tm = int(m_s.max())
Sk, lok, hik = km_curva(m_s, e_s, Tm)
tt = np.arange(Tm + 1)
r = 1 - puntos[nombre]
B = np.array(boots[nombre])
ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(HORIZONTES)), np.nan)
fig, ax = plt.subplots(figsize=(9, 5.2))
ax.fill_between(tt, lok, hik, step="post", color="#9aa5b1", alpha=.3, lw=0)
ax.step(tt, Sk, where="post", color="#222", lw=1.6, label="Kaplan-Meier (IC 95 % Greenwood)")
for ajuste, col, ls, lb in [(w_, "#1f77b4", "-", "Weibull"), (ks_, "#d1495b", "--", "Weibull fraccional")]:
t_in = np.linspace(0, Tm, 300)
t_ex = np.linspace(Tm, TOPE_MESES, 200)
ax.plot(t_in, ajuste["S"](t_in), color=col, lw=2.2, ls=ls, label=lb)
ax.plot(t_ex, ajuste["S"](t_ex), color=col, lw=1.4, ls=":")
ax.errorbar(HORIZONTES, r, yerr=[np.clip(r - ic[0], 0, None), np.clip(ic[1] - r, 0, None)], fmt=MARCA_PUNTOS, color=COLOR_PUNTOS,
ms=9, capsize=4, lw=1.8, mec="white", mew=1, label="LR + HBN combinado (IC 95 % bootstrap)", zorder=5)
x1 = TOPE_MESES + 0.8
xs = np.linspace(0, x1, 400)
v = np.concatenate([w_["S"](xs), ks_["S"](xs), Sk[:int(min(x1, Tm)) + 1], lok[:int(min(x1, Tm)) + 1], r, ic.ravel()])
v = v[np.isfinite(v)]
mg = (v.max() - v.min()) * .06
ax.set_xlim(0, x1)
ax.set_ylim(max(0, v.min() - mg), min(1.005, v.max() + mg))
ax.set_xlabel("Meses desde el diagnóstico")
ax.set_ylabel("Libre de recaída S(t)")
ax.grid(alpha=.25)
ax.set_title(f"{nombre}\n{'SCAN-B' if COHORTE == 'scanb' else 'METABRIC'} · n={n_:,}, recaídas={ev_:,}", fontsize=11)
ax.legend(frameon=False, loc="lower left", fontsize=9)
for sp in ("top", "right"):
ax.spines[sp].set_visible(False)
fig.tight_layout()
arch = re.sub(r"[^A-Za-z0-9]+", "_", nombre.replace("≥", "ge").replace("≤", "le").replace("<", "lt").replace(">", "gt")
.replace("−", "neg").replace("+", "pos").replace("ñ", "n").replace("á", "a").replace("í", "i").replace("é", "e")).strip("_")
fig.savefig(f"{DIR_FIG}/subgrupo_{COHORTE}_{arch}.png", dpi=170)
plt.close(fig)
filas = []
for j, H in enumerate(HORIZONTES):
filas.append({"cohorte": COHORTE, "subgrupo": nombre, "n": n_, "recaidas": ev_, "horizonte_meses": H,
"S_libre_LR_HBN": r[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - r[j],
"S_libre_KM": Sk[min(H, Tm)] if H <= Tm else np.nan, "replicas_bootstrap": len(B)})
return filas
filas = []
for nombre, mk in MASCARAS.items():
f = graficar(nombre, mk)
if f:
filas += f
nuevo = pd.DataFrame(filas)
destino = "./calculadora_recurrencia_subgrupos.csv"
if os.path.exists(destino):
previo = pd.read_csv(destino)
nuevo = pd.concat([previo[previo["cohorte"] != COHORTE], nuevo], ignore_index=True)
nuevo.round(4).to_csv(destino, index=False)
# ---- escenarios clinicos: factores de riesgo que incluye cada subgrupo ----
PCT_DEFINITORIA = 0.95
PCT_MAYORITARIA = 0.50
PCT_PRESENTE = 0.10
def nivel_presencia(p):
if p >= PCT_DEFINITORIA:
return "definitoria"
if p >= PCT_MAYORITARIA:
return "mayoritaria"
return "presente" if p >= PCT_PRESENTE else "minoritaria"
def definicion(cond):
return "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items())
if os.path.exists("./factores_riesgo_recurrencia.csv"):
fr = pd.read_csv("./factores_riesgo_recurrencia.csv", dtype={"categoria": str})
fr = fr[(fr["cohorte"] == COHORTE) & fr["horizonte_meses"].isin(HORIZONTES)]
fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy()
fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0])
filas_esc, filas_res = [], []
for nombre, mk in MASCARAS.items():
n_sub = int(mk.sum())
if n_sub == 0:
continue
cond = SUBGRUPOS[nombre]
pct = {}
for v, c in set(zip(fr["variable"], fr["categoria"])):
pct[(v, c)] = (float((df.loc[mk, v] == c).mean()), float((df[v] == c).mean()))
det = fr.copy()
det["pct_en_escenario"] = [pct[(v, c)][0] for v, c in zip(det["variable"], det["categoria"])]
det["pct_en_cohorte"] = [pct[(v, c)][1] for v, c in zip(det["variable"], det["categoria"])]
det["presencia"] = det["pct_en_escenario"].map(nivel_presencia)
det["en_definicion"] = [c in cond.get(v, []) for v, c in zip(det["variable"], det["categoria"])]
det.insert(0, "escenario", nombre)
det.insert(1, "definicion", definicion(cond))
det.insert(2, "n_escenario", n_sub)
columnas = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria",
"clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte",
"presencia", "en_definicion"]
filas_esc.append(det[det["pct_en_escenario"] >= PCT_PRESENTE][columnas])
for H in HORIZONTES:
d = det[det["horizonte_meses"] == H]
fila = {"cohorte": COHORTE, "escenario": nombre, "definicion": definicion(cond), "n_escenario": n_sub, "horizonte_meses": H}
for tipo in ("riesgo", "protector", "tratamiento"):
for nivel, etiqueta in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
s_ = d[(d["tipo_efecto"] == tipo) & (d["presencia"] == nivel)]
fila[f"{tipo}_{etiqueta}"] = "; ".join(
f"{v}={c} ({k.split()[-1] if tipo != 'tratamiento' else 'asociacion'}, {p:.0%})"
for v, c, k, p in zip(s_["variable"], s_["categoria"], s_["clasificacion"], s_["pct_en_escenario"]))
fila["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum())
fila["incluye_factor_riesgo"] = fila["n_factores_riesgo_incluidos"] > 0
filas_res.append(fila)
for archivo, filas_x in (("./escenarios_factores_riesgo_recurrencia.csv", pd.concat(filas_esc, ignore_index=True)),
("./escenarios_resumen_recurrencia.csv", pd.DataFrame(filas_res))):
if os.path.exists(archivo):
previo = pd.read_csv(archivo)
filas_x = pd.concat([previo[previo["cohorte"] != COHORTE], filas_x], ignore_index=True)
filas_x.round(4).to_csv(archivo, index=False)
@@ -0,0 +1,33 @@
import argparse
import csv
import subprocess
import sys
import time
ap = argparse.ArgumentParser()
ap.add_argument("--cohorte", choices=["metabric", "scanb"])
ap.add_argument("--horizontes", nargs="+", default=["12", "36", "60"])
a = ap.parse_args()
cohortes = [a.cohorte] if a.cohorte else ["metabric", "scanb"]
prep = {"metabric": "01_preparacion_metabric.py", "scanb": "02_preparacion_scanb.py"}
pasos = []
for c in cohortes:
pasos.append((f"preparacion_{c}", [prep[c]]))
pasos.append((f"03_modelado_{c}", ["03_modelado.py", c] + a.horizontes))
pasos.append((f"04_factores_riesgo_{c}", ["04_factores_riesgo.py", c] + a.horizontes))
pasos.append((f"05_calculadora_{c}", ["05_calculadora.py", c] + a.horizontes))
bit = []
for nombre, cmd in pasos:
t0 = time.time()
r = subprocess.run([sys.executable, "-W", "ignore"] + cmd, capture_output=True, text=True)
bit.append([nombre, "ok" if r.returncode == 0 else "ERROR", round(time.time() - t0, 1)])
with open("bitacora_recurrencia.csv", "w", newline="", encoding="utf8") as f:
w = csv.writer(f)
w.writerow(["paso", "estado", "segundos"])
w.writerows(bit)
if r.returncode != 0:
sys.stderr.write(f"\n[{nombre}] fallo:\n{r.stderr[-3000:]}\n")
sys.exit(1)
+243
View File
@@ -0,0 +1,243 @@
"""Luis's recurrence analysis of one cohort over its frame (`cohort.recode`): the covariates that survive the
collinearity pruning, the logistic regression and the Bayesian network's outcome parents of each horizon, and the figure
of each clinical scenario (Kaplan-Meier with its Greenwood band, the Weibull and the fractional Weibull, and the
combined estimate at each horizon with its bootstrap interval).
Every number a stage uses is the model's (`modeling`, `calculator` of `model.toml`).
"""
import warnings
import numpy as np
import pandas as pd
import statsmodels.api as sm
from pgmpy.estimators import BDeu
from scipy.stats import chi2_contingency
from sklearn.model_selection import train_test_split
from models.cama.seer_survival.fractional_weibull import ajustar_ks, ajustar_weibull, km_curva, tabla_eventos
warnings.filterwarnings("ignore")
def cramer_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b)
chi2 = chi2_contingency(table, correction=False)[0]
k = min(table.shape) - 1
return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0
def prune_covariates(frame: pd.DataFrame, covariates: list[str], treatment: list[str], settings: dict) -> tuple[list, list]:
"""Of each pair of non-treatment covariates with Cramér's V at or above the limit, the one with more unknowns goes."""
unknown = settings["unknown_label"]
kept, dropped = list(covariates), []
candidates = [c for c in covariates if c not in treatment]
pairs = sorted(((cramer_v(frame[a], frame[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]),
reverse=True)
for v, a, b in pairs:
if v < settings["cramer_v_max"]:
break
if a in dropped or b in dropped:
continue
out = a if (frame[a] == unknown).mean() >= (frame[b] == unknown).mean() else b
dropped.append(out)
kept.remove(out)
return kept, dropped
def horizon_cohort(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
"""The patients who recurred by the horizon or are free beyond it; the rest were censored before it and are left out."""
recurred = (frame["evento"] == 1) & (frame["tiempo_meses"] <= horizon)
free = frame["tiempo_meses"] > horizon
out = frame[recurred | free].reset_index(drop=True)
out["y"] = ((out["evento"] == 1) & (out["tiempo_meses"] <= horizon)).astype(int)
return out
def _encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
def _logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def _prefilter(X: pd.DataFrame, y, alpha: float) -> list[str]:
keep = []
for c in X.columns:
fit = _logit(y, X[[c]])
if fit is not None and fit.pvalues[c] < alpha:
keep.append(c)
return keep
def _stepwise(X: pd.DataFrame, y, alpha_in: float, alpha_out: float) -> list[str]:
chosen: list[str] = []
for _ in range(200):
changed = False
best, best_p = None, alpha_in
for c in [c for c in X.columns if c not in chosen]:
fit = _logit(y, X[chosen + [c]])
if fit is not None and fit.pvalues[c] < best_p:
best, best_p = c, fit.pvalues[c]
if best is not None:
chosen.append(best)
changed = True
if chosen:
fit = _logit(y, X[chosen])
if fit is not None:
p = fit.pvalues.drop("const")
if p.max() > alpha_out:
chosen.remove(p.idxmax())
changed = True
if not changed:
break
return chosen
def logistic_terms(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]:
both = _encode(pd.concat([train, test]), covariates)
X = both.loc[train.index]
X = X.loc[:, X.nunique() > 1]
candidates = _prefilter(X, train["y"], settings["alpha_prefilter"])
return _stepwise(X[candidates], train["y"], settings["alpha_in"], settings["alpha_out"]) if candidates else []
def outcome_parents(frame: pd.DataFrame, covariates: list[str], settings: dict) -> list[str]:
"""The outcome's parents by greedy BDeu, at most `max_parents`."""
table = frame[covariates].astype(str).copy()
table["outcome"] = frame["y"].astype(int).astype(str)
score = BDeu(table, equivalent_sample_size=settings["bdeu_ess"])
parents, current = [], score.local_score("outcome", [])
while len(parents) < settings["max_parents"]:
best, gain = None, 0
for c in covariates:
if c in parents:
continue
g = score.local_score("outcome", parents + [c]) - current
if g > gain:
best, gain = c, g
if best is None:
break
parents.append(best)
current += gain
return parents
def select_models(frame: pd.DataFrame, covariates: list[str], horizons: list[int], settings: dict) -> dict:
"""The logistic terms and the Bayesian network's outcome parents of each horizon, selected on the 70/30 split."""
models = {}
for horizon in horizons:
cohort = horizon_cohort(frame, horizon)
train_idx, test_idx = train_test_split(cohort.index, test_size=settings["test_share"], random_state=settings["seed"],
stratify=cohort["y"])
train, test = cohort.loc[train_idx], cohort.loc[test_idx]
models[horizon] = {"lr_terms": logistic_terms(train, test, covariates, settings),
"hbn_parents": outcome_parents(train, covariates, settings)}
return models
class Calculator:
"""The combined estimate (mean of the logistic regression and the Bayesian network) of a group of patients, refitting
both on any resample of the cohort with the terms and parents selected for each horizon."""
def __init__(self, frame: pd.DataFrame, covariates: list[str], models: dict, horizons: list[int], ess: int):
self.frame, self.horizons, self.models, self.ess = frame, horizons, models, ess
self.n = len(frame)
self.time = frame["tiempo_meses"].to_numpy()
self.event = frame["evento"].to_numpy()
self.dummies = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(frame[v])[0] for v in covariates}
self.levels = {v: int(self.codes[v].max()) + 1 for v in covariates}
def _lr(self, rows, y, terms):
if not terms:
return np.full(self.n, y.mean())
fit = _logit(y, self.dummies.iloc[rows][terms])
if fit is None:
return None
return fit.predict(sm.add_constant(self.dummies[terms], has_constant="add")).to_numpy()
def _key(self, parents, rows):
key = np.zeros(len(rows), dtype=np.int64)
for p in parents:
key = key * self.levels[p] + self.codes[p][rows]
return key
def _hbn(self, rows, y, parents):
if not parents:
return np.full(self.n, y.mean())
q = int(np.prod([self.levels[p] for p in parents]))
alpha = self.ess / (2 * q)
key = self._key(parents, rows)
n = pd.Series(1, index=key).groupby(level=0).sum()
n1 = pd.Series(y, index=key).groupby(level=0).sum()
table = (n1 + alpha) / (n + 2 * alpha)
return table.reindex(self._key(parents, np.arange(self.n))).fillna(y.mean()).to_numpy()
def risk(self, rows: np.ndarray, masks: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None:
"""For each group, its members' mean combined risk at every horizon, fitted on `rows` (a resample or all)."""
out = {name: np.full(len(self.horizons), np.nan) for name in masks}
for j, horizon in enumerate(self.horizons):
t, e = self.time[rows], self.event[rows]
recurred = (e == 1) & (t <= horizon)
fit_rows = rows[recurred | (t > horizon)]
y = recurred[recurred | (t > horizon)].astype(int)
model = self.models[horizon]
lr = self._lr(fit_rows, y, model["lr_terms"])
if lr is None:
return None
combined = (lr + self._hbn(fit_rows, y, model["hbn_parents"])) / 2
for name, mask in masks.items():
chosen = mask[rows]
if chosen.any():
out[name][j] = combined[rows][chosen].mean()
return out
def bootstrap(self, masks: dict[str, np.ndarray], replicas: int, seed: int) -> dict[str, list]:
rng = np.random.default_rng(seed)
draws = {name: [] for name in masks}
for _ in range(replicas):
risk = self.risk(rng.integers(0, self.n, self.n), masks)
if risk is None:
continue
for name in masks:
draws[name].append(risk[name])
return draws
def scenario_masks(frame: pd.DataFrame, scenarios: list[dict]) -> dict[str, np.ndarray]:
return {s["name"]: np.logical_and.reduce([frame[v].isin(c).to_numpy() for v, c in s["when"].items()]) for s in scenarios}
def scenario_figure(frame: pd.DataFrame, name: str, mask: np.ndarray, point: np.ndarray, draws: list,
horizons: list[int], settings: dict) -> dict | None:
"""The figure record of a scenario, or None when it has fewer recurrences than the calculator draws."""
members = frame[mask]
events = int(members["evento"].sum())
if len(members) == 0 or events < settings["min_events"]:
return None
months = np.floor(members["tiempo_meses"].to_numpy()).astype(int)
event = (members["evento"] == 1).to_numpy()
d, c = tabla_eventos(months, event)
weibull = ajustar_weibull(d, c)
fractional = ajustar_ks(d, c, k_fijo=weibull["k"], lam_ref=weibull["lam"], max_seg=settings["fractional_weibull_budget_s"])
last = int(months.max())
survival, low, high = km_curva(months, event, last)
t = np.arange(0, settings["cap_months"] * 4 + 1) / 4
free = 1 - point
boot = np.array(draws)
interval = 1 - np.nanpercentile(boot, [97.5, 2.5], axis=0) if len(boot) else np.full((2, len(horizons)), np.nan)
clean = lambda a: [None if not np.isfinite(x) else float(x) for x in a]
return {
"escenario": name, "n": int(len(members)), "recaidas": events, "observado_hasta": last,
"months_max": settings["cap_months"], "horizons_months": horizons, "bootstrap_replicas": len(boot),
"km": {"months": list(range(last + 1)), "S": clean(survival), "low": clean(low), "high": clean(high)},
"weibull": {"t": t.tolist(), "S": clean(weibull["S"](t))},
"weibull_fractional": {"t": t.tolist(), "S": clean(fractional["S"](t))},
"points": {"COMB": {"S": clean(free), "low": clean(interval[0]), "high": clean(interval[1])}},
}
-223
View File
@@ -1,223 +0,0 @@
"""The recurrence calculator: for each clinical scenario of a cohort (a subgroup defined by covariates), the figure the
dashboard shows: the Kaplan-Meier curve of the scenario's patients with its Greenwood band, the classic and the fractional
Weibull fitted to it (dotted past the follow-up), and the recurrence-free probability at each horizon by the combination of
the LR and the HBN of that horizon, with a bootstrap interval. Ported from `05_calculadora.py`; the Weibull routines are the
survival analysis' (`models.cama.seer_survival.fractional_weibull`).
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence.factors import ORDER # noqa: F401 (the classification vocabulary is shared)
from models.cama.recurrence.modeling import CohortModels
from models.cama.recurrence.prep import Prepared
from models.cama.seer_survival import fractional_weibull as fw
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"], "Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"], "Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"], "Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
}
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
PCT_DEFINING, PCT_MAJORITY, PCT_PRESENT = 0.95, 0.50, 0.10
@dataclass(frozen=True)
class CalculatorSettings:
seed: int = 42
n_boot: int = 200
min_events: int = 15
cap_months: int = 72
bdeu_ess: int = 10
ks_seconds: int = 60
class _Calculator:
def __init__(self, prepared: Prepared, fitted: CohortModels, s: CalculatorSettings):
self.s, self.fitted, self.covariates = s, fitted, prepared.covariates
df = prepared.cohort
self.df, self.N = df, len(df)
self.time, self.event_num = df["tiempo_meses"].values, df["evento"].values
self.X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float)
self.codes = {v: pd.factorize(df[v])[0] for v in self.covariates}
self.levels = {v: int(self.codes[v].max()) + 1 for v in self.covariates}
@staticmethod
def _logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X, has_constant="add")).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def _p_lr(self, train_idx, y, terms):
if not terms:
return np.full(self.N, y.mean())
m = self._logit(y, self.X.iloc[train_idx][terms])
return None if m is None else m.predict(sm.add_constant(self.X[terms], has_constant="add")).values
def _key(self, parents, rows):
k = np.zeros(len(rows), dtype=np.int64)
for p in parents:
k = k * self.levels[p] + self.codes[p][rows]
return k
def _p_hbn(self, train_idx, y, parents):
if not parents:
return np.full(self.N, y.mean())
q = int(np.prod([self.levels[p] for p in parents]))
alpha = self.s.bdeu_ess / (2 * q)
k_train = self._key(parents, train_idx)
n = pd.Series(1, index=k_train).groupby(level=0).sum()
n1 = pd.Series(y, index=k_train).groupby(level=0).sum()
table = (n1 + alpha) / (n + 2 * alpha)
return table.reindex(self._key(parents, np.arange(self.N))).fillna(y.mean()).values
def _risks(self, idx, H):
t, e = self.time[idx], self.event_num[idx]
recurs = (e == 1) & (t <= H)
ok = recurs | (t > H)
train, y = idx[ok], recurs[ok].astype(int)
mh = self.fitted.models[str(H)]
p_lr, p_hbn = self._p_lr(train, y, mh["terminos_lr"]), self._p_hbn(train, y, mh["padres_hbn"])
return None if p_lr is None else (p_lr, p_hbn)
def mean_risk(self, idx, masks, horizons):
out = {n: np.full(len(horizons), np.nan) for n in masks}
for j, H in enumerate(horizons):
r = self._risks(idx, H)
if r is None:
return None
combined = (r[0] + r[1]) / 2
for n, mask in masks.items():
sel = mask[idx]
if sel.any():
out[n][j] = combined[idx][sel].mean()
return out
def scenario_masks(df: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
return {n: np.logical_and.reduce([df[v].isin(c).values for v, c in cond.items()]) for n, cond in scenarios.items()}
def _presence(share: float) -> str:
if share >= PCT_DEFINING:
return "definitoria"
if share >= PCT_MAJORITY:
return "mayoritaria"
return "presente" if share >= PCT_PRESENT else "minoritaria"
def calculator(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], settings: CalculatorSettings,
scenarios: dict | None = None) -> tuple[list[dict], pd.DataFrame]:
"""The figure record of each scenario with enough recurrences, and the table of their points."""
scenarios = scenarios if scenarios is not None else SCENARIOS[name]
c = _Calculator(prepared, fitted, settings)
masks = scenario_masks(prepared.cohort, scenarios)
everyone = np.arange(c.N)
points = c.mean_risk(everyone, masks, horizons)
rng = np.random.default_rng(settings.seed)
boots = {n: [] for n in masks}
for _ in range(settings.n_boot):
r = c.mean_risk(rng.integers(0, c.N, c.N), masks, horizons)
if r is None:
continue
for n in masks:
boots[n].append(r[n])
months_int = np.floor(c.time).astype(int)
event = c.event_num == 1
records, rows = [], []
for scenario, mask in masks.items():
n_sub, events = int(mask.sum()), int(prepared.cohort.loc[mask, "evento"].sum())
if n_sub == 0 or events < settings.min_events:
continue
m_s, e_s = months_int[mask], event[mask]
d, cen = fw.tabla_eventos(m_s, e_s)
classic = fw.ajustar_weibull(d, cen)
fractional = fw.ajustar_ks(d, cen, k_fijo=classic["k"], lam_ref=classic["lam"], max_seg=settings.ks_seconds)
observed = int(m_s.max())
S, low, high = fw.km_curva(m_s, e_s, observed)
free = 1 - points[scenario]
B = np.array(boots[scenario])
ic = 1 - np.nanpercentile(B, [97.5, 2.5], axis=0) if len(B) else np.full((2, len(horizons)), np.nan)
grid = np.linspace(0, settings.cap_months, 289)
records.append({
"cohorte": name, "cohorte_nombre": LABELS[name], "escenario": scenario, "condiciones": scenarios[scenario],
"n": n_sub, "recaidas": events, "horizons_months": horizons, "observado_hasta": observed, "months_max": settings.cap_months,
"km": {"months": list(range(observed + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
"points": {"COMB": {"S": free.tolist(), "low": np.clip(ic[0], 0, 1).tolist(), "high": np.clip(ic[1], 0, 1).tolist()}},
"bootstrap_replicas": len(B)})
for j, H in enumerate(horizons):
rows.append({"cohorte": name, "subgrupo": scenario, "n": n_sub, "recaidas": events, "horizonte_meses": H,
"S_libre_LR_HBN": free[j], "IC95_inf": ic[0, j], "IC95_sup": ic[1, j], "riesgo_recurrencia": 1 - free[j],
"S_libre_KM": S[min(H, observed)] if H <= observed else np.nan, "replicas_bootstrap": len(B)})
return records, pd.DataFrame(rows).round(4)
def scenario_risk_factors(name: str, prepared: Prepared, factors: pd.DataFrame, horizons: list[int],
scenarios: dict | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Which classified risk factors, protectors and treatments make up each scenario: a category nearly all of it has
defines it, most of it describes it. Returns the detail and the per-scenario summary."""
scenarios = scenarios if scenarios is not None else SCENARIOS[name]
df = prepared.cohort
masks = scenario_masks(df, scenarios)
fr = factors[(factors["cohorte"] == name) & factors["horizonte_meses"].isin(horizons)]
fr = fr[fr["clasificacion"].str.contains("robusto|sugerente|tratamiento")].copy()
fr["tipo_efecto"] = np.where(fr["tipo"] == "tratamiento", "tratamiento", fr["clasificacion"].str.split().str[0])
details, summary = [], []
for scenario, mask in masks.items():
n_sub = int(mask.sum())
if n_sub == 0 or fr.empty:
continue
cond = scenarios[scenario]
shares = {(v, cat): (float((df.loc[mask, v] == cat).mean()), float((df[v] == cat).mean())) for v, cat in set(zip(fr["variable"], fr["categoria"]))}
det = fr.copy()
det["pct_en_escenario"] = [shares[(v, cat)][0] for v, cat in zip(det["variable"], det["categoria"])]
det["pct_en_cohorte"] = [shares[(v, cat)][1] for v, cat in zip(det["variable"], det["categoria"])]
det["presencia"] = det["pct_en_escenario"].map(_presence)
det["en_definicion"] = [cat in cond.get(v, []) for v, cat in zip(det["variable"], det["categoria"])]
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in cond.items())
det.insert(0, "escenario", scenario)
det.insert(1, "definicion", definition)
det.insert(2, "n_escenario", n_sub)
cols = ["cohorte", "escenario", "definicion", "n_escenario", "horizonte_meses", "tipo_efecto", "variable", "categoria",
"clasificacion", "OR_recurrencia", "IC95_inf", "IC95_sup", "delta_S", "pct_en_escenario", "pct_en_cohorte", "presencia", "en_definicion"]
details.append(det[det["pct_en_escenario"] >= PCT_PRESENT][cols])
for H in horizons:
d = det[det["horizonte_meses"] == H]
row = {"cohorte": name, "escenario": scenario, "definicion": definition, "n_escenario": n_sub, "horizonte_meses": H}
for kind in ("riesgo", "protector", "tratamiento"):
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
part = d[(d["tipo_efecto"] == kind) & (d["presencia"] == level)]
row[f"{kind}_{label}"] = "; ".join(
f"{v}={cat} ({k.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
for v, cat, k, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
row["n_factores_riesgo_incluidos"] = int(((d["tipo_efecto"] == "riesgo") & d["presencia"].isin(["definitoria", "mayoritaria"])).sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
summary.append(row)
return (pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame()), pd.DataFrame(summary)
+83
View File
@@ -0,0 +1,83 @@
"""One cohort's patients as the frame the analysis reads: one row per patient with the follow-up in months, the recurrence
event and each covariate's category, built from the timeline by the dictionary (`[variables]` of `model.toml`).
The index is the date of the patient's first biopsy reported as invasive carcinoma, the diagnosis (the cohort's `fecha_indice`); the follow-up runs from
it to the recurrence or, without one, to the last contact. The events are a cohort's (`fecha_indice` is the index). A covariate is read from the events up to
`window_days_after_index` after the index; a category no rule gives is the variable's `missing` one.
"""
import tomllib
from pathlib import Path
import pandas as pd
from models.cama.seer_survival.variables import Reader, category_of
TOML = Path(__file__).with_name("model.toml")
SOURCE_CODE = {"metabric": "METABRIC", "scanb": "SCANB"}
def load(path: Path = TOML) -> dict:
return tomllib.loads(Path(path).read_text(encoding="utf-8"))
def _spec(dictionary: dict, name: str, cohort: str) -> dict:
spec = dictionary[name]
own = spec.get(cohort, {})
return {**spec, "rules": own["rules"]} if "rules" in own else spec
def _cut(values: pd.Series, cuts: list, labels: list, missing: str) -> pd.Series:
cut = pd.cut(values, cuts, labels=labels, right=False)
return cut.astype("object").where(cut.notna(), missing).astype(str)
def recode(events: pd.DataFrame, model: dict, cohort: str, *, of_source: bool = True, follow_up: bool = True) -> pd.DataFrame:
"""One row per patient. `of_source` keeps only the patients whose record comes from this cohort's source (a patient of
another source is read with the same variables when it is false); `follow_up` drops those with no recurrence or
last contact, whose time is unknown."""
dictionary = model["variables"]
index = dictionary["index"]
events = events.copy()
events["fecha"] = pd.to_datetime(events["fecha"])
events["fecha_indice"] = pd.to_datetime(events["fecha_indice"])
if of_source:
source = events[events["tipo"] == "fuente"].groupby("pac_id")["valor_codigo"].last()
patients = pd.Index(sorted(source[source == SOURCE_CODE[cohort]].index), name="pac_id")
else:
patients = pd.Index(sorted(events["pac_id"].unique()), name="pac_id")
events = events[events["pac_id"].isin(patients)]
start = events.groupby("pac_id")["fecha_indice"].first().reindex(patients)
recurrence = events[events["tipo"] == index["recurrence_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
contact = events[events["tipo"] == index["last_contact_source"]].groupby("pac_id")["fecha"].max().reindex(patients)
end = recurrence.fillna(contact)
birth = events[events["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
window = pd.Timedelta(days=int(dictionary["window_days_after_index"]))
visible = events[events["fecha"] <= events["pac_id"].map(start) + window]
reader = Reader(visible, patients, {})
result = pd.DataFrame(index=patients)
result["paciente"] = patients.to_numpy()
result["tiempo_meses"] = ((end - start).dt.days / index["days_per_month"]).to_numpy()
result["evento"] = recurrence.notna().astype(int).to_numpy()
unknown = dictionary["Edad"]["missing"]
for name in model["cohorts"][cohort]["covariates"]:
spec = _spec(dictionary, name, cohort)
if name == "Edad":
age = (start - birth).dt.days / 365.25
result[name] = _cut(age, spec["cuts"], spec["labels"], unknown).to_numpy()
elif "rules" in spec:
category = category_of(spec, reader)
labels = spec.get(cohort, {}).get("labels", {})
result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy()
elif spec.get("terciles"):
count = reader.value(spec["source"], True)
q = count.quantile([1 / 3, 2 / 3]).to_numpy()
result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy()
else:
result[name] = _cut(reader.value(spec["source"], True), spec["cuts"], spec["labels"], spec["missing"]).to_numpy()
keep = start.notna().to_numpy() & (end.notna().to_numpy() if follow_up else True)
result = result[keep]
return result.reset_index(drop=True)
+158
View File
@@ -0,0 +1,158 @@
"""METABRIC's and SCAN-B's clinical files as CaMa import files: one CSV per bronze entity, named by the fields the import
schemas take, to be uploaded through the platform's import like any other source.
python -m models.cama.recurrence.cohort_import metabric FILE OUT_DIR
What goes where is the dictionary's (`[variables.*]` of `model.toml`): each source category is stored as the catalog value
the dictionary names and read back as the same category. The files record no calendar dates: the diagnosis is a fixed day
of its year, the birth is the diagnosis minus the age (rounded up to a whole day, so a patient on an age cut stays on its upper side), and the recurrence (or the last contact) is the diagnosis plus the
follow-up, and a discharge note closes it: the patients have been treated. A date holds whole days, so the follow-up is stored as the whole-day count nearest to the exact months that keeps
the month it falls in and its side of every horizon.
"""
import argparse
import math
import tomllib
from pathlib import Path
import numpy as np
import pandas as pd
TOML = Path(__file__).with_name("model.toml")
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "NotaMedica": "notas", "TratamientoMama": "tratamientos",
"SeguimientoMama": "seguimientos"}
FEMALE = "Femenino"
UNKNOWN = {"", "NA", "nan", "NaN", "None"}
def load(path: Path = TOML) -> dict:
return tomllib.loads(Path(path).read_text(encoding="utf-8"))
def follow_up_days(months: float, horizons: list[int], days_per_month: float) -> int:
"""The whole days nearest to `months` that keep floor(months) and, for each horizon, whether the follow-up is within it."""
exact = months * days_per_month
month = math.floor(months)
low = math.ceil(month * days_per_month)
high = math.ceil((month + 1) * days_per_month) - 1
sides = [months <= h for h in horizons]
first = int(round(exact))
for step in range(0, high - low + 2):
for day in (first - step, first + step):
if low <= day <= high and math.floor(day / days_per_month) == month \
and [day / days_per_month <= h for h in horizons] == sides:
return day
return first
def _known(raw: pd.Series) -> pd.Series:
return raw.notna() & ~raw.astype(str).str.strip().isin(UNKNOWN)
def convert(raw: pd.DataFrame, cohort: str, model: dict) -> dict[str, pd.DataFrame]:
dictionary = model["variables"]
index = dictionary["index"]
cfg = dictionary["cohorts"][cohort]
covariates = model["cohorts"][cohort]["covariates"]
horizons = model["config"]["horizons_months"]
dpm = index["days_per_month"]
frame = raw
if cfg["sex_filter"]:
frame = frame[frame[cfg["sex_filter"]["column"]] == cfg["sex_filter"]["value"]]
frame = frame[_known(frame[cfg["months"]]) & _known(frame[cfg["event"]])].copy()
if cohort == "scanb":
days = pd.to_numeric(frame[cfg["months"]]).round().astype(int)
event = pd.to_numeric(frame[cfg["event"]]).astype(int)
else:
months = pd.to_numeric(frame[cfg["months"]])
days = pd.Series([follow_up_days(m, horizons, dpm) for m in months], index=frame.index)
event = frame[cfg["event"]].astype(str).str.startswith(cfg["event_prefix"]).astype(int)
age = pd.to_numeric(frame[cfg["diagnosis_age"]], errors="coerce") + cfg.get("diagnosis_age_offset", 0)
frame, days, event, age = (x[age.notna()] for x in (frame, days, event, age))
if "diagnosis_year_column" in cfg:
year = pd.to_numeric(frame[cfg["diagnosis_year_column"]], errors="coerce").fillna(2000).astype(int)
else:
year = pd.Series(int(cfg["diagnosis_year"]), index=frame.index)
diagnosis = pd.to_datetime(year.astype(str) + "-" + cfg["diagnosis_month_day"])
birth = diagnosis - pd.to_timedelta(np.ceil(age * 365.25), unit="D")
end = diagnosis + pd.to_timedelta(days, unit="D")
ident = cohort.upper() + "-" + frame[cfg["id"]].astype(str)
date = lambda s: s.dt.strftime("%Y-%m-%d")
tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES}
tables["Paciente"]["pac_sexo"] = FEMALE
tables["Paciente"]["pac_fecha_nacimiento"] = date(birth)
tables["Paciente"]["pac_fuente"] = "SCANB" if cohort == "scanb" else "METABRIC"
tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis)
tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis)
treatments = []
for name in covariates:
spec = dictionary[name]
source = spec.get(cohort)
if not source or "column" not in source:
continue
column = frame[source["column"]]
known = _known(column)
if "treatment" in spec:
code = column.astype(str).map(source["values"])
code = code.where(~known | code.notna(), source.get("absent")).where(known)
rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": spec["treatment"], "trat_fecha": date(diagnosis),
"trat_detalle": code})[code.notna()]
if spec["treatment"] == "cirugia":
rows["trat_lateralidad"] = None
treatments.append(rows)
continue
if "bronze" not in spec:
continue
entity, target = spec["bronze"].split(".")
if "number_values" in source:
value = column.astype(str).map(source["number_values"])
elif "values" in source:
value = column.astype(str).map(source["values"])
else:
value = pd.to_numeric(column.where(known), errors="coerce")
tables[entity][target] = value.where(known)
tables["BiopsiaMama"]["bx_grado_histologico"] = "CARCINOMA_INVASOR"
if "Cirugia" in covariates and "bx_lateralidad" in tables["BiopsiaMama"]:
for rows in treatments:
if (rows["trat_tipo"] == "cirugia").any():
rows["trat_lateralidad"] = tables["BiopsiaMama"]["bx_lateralidad"].reindex(rows.index)
tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True)
notes = tables["NotaMedica"]
notes["nm_id_hospital"] = ident + "-dx"
notes["nm_fecha"] = date(diagnosis)
notes["nm_tipo_nota"] = "CONSULTA"
follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(end),
"nm_tipo_nota": "EGRESO"})
tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True)
recurred = event.eq(1)
contact = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["last_contact_source"], "seg_fecha": date(end),
"seg_detalle": "VIVA"})[~recurred]
recurrence = pd.DataFrame({"pac_id_hospital": ident, "seg_tipo": index["recurrence_source"], "seg_fecha": date(end),
"seg_detalle": "NO_ESPECIFICADO"})[recurred]
tables["SeguimientoMama"] = pd.concat([recurrence, contact], ignore_index=True)
return tables
def main(argv=None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("cohort", choices=["metabric", "scanb"])
ap.add_argument("file")
ap.add_argument("out_dir")
args = ap.parse_args(argv)
raw = pd.read_csv(args.file, sep="\t", dtype=str, low_memory=False, keep_default_na=False)
out = Path(args.out_dir)
out.mkdir(parents=True, exist_ok=True)
for entity, table in convert(raw, args.cohort, load()).items():
table.to_csv(out / f"{args.cohort}_{ENTITIES[entity]}.csv", index=False)
if __name__ == "__main__":
main()
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-135
View File
@@ -1,135 +0,0 @@
"""The risk factors of the recurrence models: a category is a risk factor (or a protector) from four criteria, as in the
survival analysis: the multivariable OR, its stability in the bootstrap, the Markov blanket of the Bayesian network and the
survival difference; treatments are reported apart, never classified. Ported from `04_factores_riesgo.py`.
"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence.modeling import CohortModels
from models.cama.recurrence.prep import Prepared
ORDER = {"riesgo robusto": 0, "protector robusto": 1, "riesgo sugerente": 2, "protector sugerente": 3, "no concluyente": 4}
COLUMNS = ["cohorte", "horizonte_meses", "tipo", "variable", "categoria", "referencia", "n_categoria", "OR_recurrencia", "IC95_inf",
"IC95_sup", "p", "p_ajustado_BH", "freq_seleccion_bootstrap", "en_manta_markov", "S_libre_categoria", "S_libre_referencia",
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia",
"criterios_cumplidos", "clasificacion"]
def benjamini_hochberg(p) -> np.ndarray:
p = np.asarray(p, float)
order = np.argsort(p)
adjusted = np.empty_like(p)
m, previous = len(p), 1.0
for rank, i in zip(range(m, 0, -1), order[::-1]):
previous = min(previous, p[i] * m / rank)
adjusted[i] = previous
return adjusted
def _variable_of(term: str, variables: list[str]) -> str:
return next(v for v in sorted(variables, key=len, reverse=True) if term.startswith(v + "_"))
def _km_at(m, e, h):
T = int(m.max()) + 2
d, c = np.bincount(m[e], minlength=T), np.bincount(m[~e], minlength=T)
at_risk = len(m) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
with np.errstate(divide="ignore", invalid="ignore"):
q = np.where(at_risk > 0, 1 - d / np.maximum(at_risk, 1), 1.0)
v = np.where((at_risk > 0) & (at_risk > d), d / (np.maximum(at_risk, 1) * np.maximum(at_risk - d, 1)), 0.0)
h = min(h, T - 1)
S = np.prod(q[:h + 1])
return S, S * np.sqrt(np.sum(v[:h + 1]))
def _at_horizon(name: str, prepared: Prepared, fitted: CohortModels, H: int, alpha: float, freq_min: float) -> pd.DataFrame:
total, variables, treatment = prepared.cohort, prepared.covariates, prepared.treatment
intrinsic = [v for v in variables if v not in treatment]
recurs = (total["evento"] == 1) & (total["tiempo_meses"] <= H)
free = total["tiempo_meses"] > H
km_data = total.copy()
coh = total[recurs | free].reset_index(drop=True)
data = coh[variables].astype(str)
y = ((coh["evento"] == 1) & (coh["tiempo_meses"] <= H)).astype(int).values
months = np.floor(np.minimum(km_data["tiempo_meses"].values, H + 1)).astype(int)
event = ((km_data["evento"] == 1) & (km_data["tiempo_meses"] <= H)).values
km_data = km_data[variables].astype(str)
def reference(v):
return data[v].value_counts().idxmax()
def fit_or(model_vars):
X = pd.get_dummies(data[model_vars], drop_first=False).astype(float)
refs = {v: f"{v}_{reference(v)}" for v in model_vars}
X = X.drop(columns=[r for r in refs.values() if r in X.columns])
X = X.loc[:, X.nunique() > 1]
X = X.loc[:, ~X.T.duplicated()]
model = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
ci = model.conf_int()
return pd.DataFrame({"termino": X.columns, "OR_recurrencia": np.exp(model.params[X.columns].values),
"IC95_inf": np.exp(ci.loc[X.columns, 0].values), "IC95_sup": np.exp(ci.loc[X.columns, 1].values),
"p": model.pvalues[X.columns].values})
def delta_s(v, cat, ref):
a, b = (km_data[v] == cat).values, (km_data[v] == ref).values
Sa, ea = _km_at(months[a], event[a], H)
Sb, eb = _km_at(months[b], event[b], H)
d, se = Sa - Sb, np.sqrt(ea ** 2 + eb ** 2)
return pd.Series({"n_categoria": int(a.sum()), "S_libre_categoria": Sa, "S_libre_referencia": Sb, "delta_S": d,
"delta_IC95_inf": d - 1.96 * se, "delta_IC95_sup": d + 1.96 * se})
def complete(t, model_vars):
t = t.copy()
t["variable"] = [_variable_of(x, model_vars) for x in t["termino"]]
t["categoria"] = [x[len(v) + 1:] for x, v in zip(t["termino"], t["variable"])]
t["referencia"] = [reference(v) for v in t["variable"]]
t["p_ajustado_BH"] = benjamini_hochberg(t["p"])
ds = pd.DataFrame([delta_s(v, c, r) for v, c, r in zip(t["variable"], t["categoria"], t["referencia"])])
return pd.concat([t.reset_index(drop=True), ds.reset_index(drop=True)], axis=1)
tab = complete(fit_or(intrinsic), intrinsic)
tab["direccion"] = np.where(tab["OR_recurrencia"] > 1, "riesgo", "protector")
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < alpha)
tab["c4_supervivencia"] = ((tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)) & \
(np.sign(tab["delta_S"]) == np.where(tab["direccion"] == "riesgo", -1, 1))
mh = fitted.models.get(str(H), {})
n_rep, selection = mh.get("n_replicas", 0), mh.get("seleccion_lr", {})
tab["freq_seleccion_bootstrap"] = tab["variable"].map(lambda v: selection.get(v, 0) / n_rep if n_rep else np.nan)
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= freq_min
tab["en_manta_markov"] = tab["variable"].isin(set(mh.get("padres_hbn", [])))
tab["c3_manta_markov"] = tab["en_manta_markov"]
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
def classify(r):
if r["categoria"] == "Desconocido":
return "no aplica (categoria desconocida)"
if r["c1_or"] and r["criterios_cumplidos"] >= 3:
return f"{r['direccion']} robusto"
if r["criterios_cumplidos"] >= 2:
return f"{r['direccion']} sugerente"
return "no concluyente"
tab["clasificacion"] = tab.apply(classify, axis=1)
tab["tipo"] = "factor de riesgo"
if treatment:
tr = fit_or(intrinsic + treatment)
tr["_v"] = [_variable_of(t, intrinsic + treatment) for t in tr["termino"]]
tr = tr[tr["_v"].isin(treatment) & ~tr["termino"].str.endswith("_Desconocido")].drop(columns="_v")
tr = complete(tr, treatment)
tr["tipo"] = "tratamiento"
tr["clasificacion"] = "tratamiento (no se clasifica; asociacion, no efecto causal)"
tab = pd.concat([tab, tr], ignore_index=True)
tab["cohorte"], tab["horizonte_meses"] = name, H
return tab
def risk_factors(name: str, prepared: Prepared, fitted: CohortModels, horizons: list[int], alpha: float = 0.05,
freq_min: float = 0.80) -> pd.DataFrame:
"""The classified categories of each horizon, risk factors first, as `factores_riesgo_recurrencia.csv`."""
new = pd.concat([_at_horizon(name, prepared, fitted, H, alpha, freq_min) for H in horizons], ignore_index=True)
new["_t"] = (new["tipo"] != "factor de riesgo").astype(int)
new["_o"] = new["clasificacion"].map(ORDER).fillna(5)
return new.sort_values(["horizonte_meses", "_t", "_o", "OR_recurrencia"], ascending=[True, True, True, False])[COLUMNS].round(4)
-153
View File
@@ -1,153 +0,0 @@
"""CaMa's recurrence analysis as a scenario: the dataflow from the two external cohorts to the registered model, its results and
its routines. Each node is one stage of Luis's scripts (`prep`, `modeling`, `factors`, `calculator`); the training machinery
(`models.dags.training.train`) saves what the nodes `fitted_model`, `metrics`, `routines` and `population` give. The figures the
dashboard shows are in `population["recurrencia"]`.
"""
import numpy as np
import pandas as pd
import statsmodels.api as sm
from models.cama.recurrence import calculator as calc
from models.cama.recurrence import factors as fac
from models.cama.recurrence import modeling
from models.cama.recurrence.prep import FILES, PREPARE, Prepared
from models.cama.recurrence.source import data_folder
from models.cama.recurrence.steps import run_steps # noqa: F401 (the CLI's own steps: not a node)
COHORTS = ("metabric", "scanb")
def prepared(recurrence: dict) -> dict[str, Prepared]:
"""Each cohort as one table of categories with its covariates (`prep`)."""
folder = data_folder(recurrence["data_dir"])
return {name: PREPARE[name](str(folder / FILES[name]), recurrence["v_max"]) for name in COHORTS}
def fits(prepared: dict[str, Prepared], recurrence: dict) -> dict[str, modeling.CohortModels]:
"""The LR and the HBN at each horizon of each cohort, with their AUC (`modeling`)."""
base = {k: recurrence[k] for k in ("seed", "bdeu_ess", "max_parents", "alpha_in", "alpha_out", "alpha_prefilter")}
return {name: modeling.fit_cohort(name, prepared[name], list(recurrence["horizons"]),
modeling.FitSettings(n_bootstrap=recurrence[f"n_bootstrap_{name}"], **base)) for name in COHORTS}
def factors_table(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> pd.DataFrame:
"""The classified risk factors of both cohorts at each horizon (`factors`)."""
return pd.concat([fac.risk_factors(n, prepared[n], fits[n], list(recurrence["horizons"]), recurrence["alpha"], recurrence["freq_min"])
for n in COHORTS], ignore_index=True)
def calculators(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict[str, tuple[list[dict], pd.DataFrame]]:
"""The figure of each scenario of each cohort and the table of their points (`calculator`)."""
s = calc.CalculatorSettings(seed=recurrence["seed"], n_boot=recurrence["n_boot_calc"], min_events=recurrence["min_events"],
cap_months=recurrence["cap_months"], bdeu_ess=recurrence["bdeu_ess"], ks_seconds=recurrence["ks_seconds"])
return {n: calc.calculator(n, prepared[n], fits[n], list(recurrence["horizons"]), s) for n in COHORTS}
def scenario_factors(prepared: dict[str, Prepared], factors_table: pd.DataFrame, recurrence: dict) -> dict[str, pd.DataFrame]:
"""The risk factors that make up each scenario (`calculator.scenario_risk_factors`): the summary of both cohorts."""
summaries = [calc.scenario_risk_factors(n, prepared[n], factors_table, list(recurrence["horizons"]))[1] for n in COHORTS]
return {"resumen": pd.concat(summaries, ignore_index=True)}
class RecurrenceModel:
"""The recurrence models of one cohort fitted on all of it: at each horizon the logistic regression on the terms the
stepwise chose and the Bayesian network's table over the parents it chose. `predict_proba(X)` is the recurrence probability
at each horizon, the mean of the two models; `X` has the cohort's covariates as categories (the unknown, "Desconocido")."""
def __init__(self, cohort: str, horizons: list[int], covariates: list[str], tables: dict):
self.cohort, self.horizons, self.covariates, self.tables_ = cohort, horizons, covariates, tables
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
out = np.zeros((len(X), len(self.horizons)))
for j, H in enumerate(self.horizons):
t = self.tables_[str(H)]
p_lr = np.full(len(X), t["lr_prior"])
if t["lr_terms"]:
dummies = pd.get_dummies(X[self.covariates].astype(str)).astype(float).reindex(columns=t["lr_terms"], fill_value=0.0)
p_lr = 1 / (1 + np.exp(-(t["lr_constant"] + dummies.values @ np.asarray(t["lr_coefficients"]))))
parents, cpt = t["hbn_parents"], t["hbn_cpt"]
p_hbn = np.full(len(X), t["hbn_prior"]) if not parents else np.array(
[cpt.get(tuple(row), t["hbn_prior"]) for row in X[parents].astype(str).values])
out[:, j] = (p_lr + p_hbn) / 2
return out
def _tables(prepared: Prepared, fitted: modeling.CohortModels, horizons: list[int], bdeu_ess: int) -> dict:
"""What `RecurrenceModel` keeps from the fit on the whole cohort, per horizon."""
f = modeling._Fitter(prepared, modeling.FitSettings(bdeu_ess=bdeu_ess))
tables = {}
for H in horizons:
coh = f.at_horizon(H)
mh = fitted.models[str(H)]
terms, parents = mh["terminos_lr"], mh["padres_hbn"]
entry = {"lr_prior": float(coh["y"].mean()), "lr_terms": terms, "lr_constant": 0.0, "lr_coefficients": [],
"hbn_parents": parents, "hbn_prior": float(coh["y"].mean()), "hbn_cpt": {}}
if terms:
X = f.encode(coh)[terms]
model = f.logit(coh["y"], X)
if model is not None:
entry["lr_constant"], entry["lr_coefficients"] = float(model.params["const"]), [float(model.params[t]) for t in terms]
if parents:
table = f.bn_table(coh)
alpha = bdeu_ess / (2 * int(np.prod([table[p].nunique() for p in parents])))
g = table.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
entry["hbn_cpt"] = {(k if isinstance(k, tuple) else (k,)): float((r.n1 + alpha) / (r.n + 2 * alpha)) for k, r in g.iterrows()}
tables[str(H)] = entry
return tables
def fitted_model(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> RecurrenceModel:
"""The model that is saved: METABRIC's, the larger of the two cohorts' external references for the covariates both share."""
return RecurrenceModel("metabric", list(recurrence["horizons"]), prepared["metabric"].covariates,
_tables(prepared["metabric"], fits["metabric"], list(recurrence["horizons"]), recurrence["bdeu_ess"]))
def metrics(fits: dict[str, modeling.CohortModels]) -> dict:
"""Numbers only: each cohort's AUC by internal validation and by bootstrap, per horizon and model, and its Cox C-index."""
found = {}
for name, fit in fits.items():
for _, r in fit.auc.iterrows():
if r["horizonte_meses"] == "completo":
found[f"{name}.c_index_cox"] = float(r["AUC_validacion_interna"])
continue
tag = f"{name}.auc_{r['modelo']}_{int(r['horizonte_meses'])}m"
found[tag] = float(r["AUC_validacion_interna"])
found[f"{tag}_bootstrap"] = float(r["AUC_bootstrap_medio"])
return found
def routines(prepared: dict[str, Prepared], fits: dict[str, modeling.CohortModels], recurrence: dict) -> dict:
"""The five routine records the registry's promotion reads (ML-01a)."""
return {
"MUESTREO": {"cohortes": {n: {"pacientes": len(p.cohort), "recaidas": int(p.cohort["evento"].sum()), "covariables": len(p.covariates),
"eliminadas_por_colinealidad": p.eliminated} for n, p in prepared.items()},
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres", "origen": "METABRIC y SCAN-B (externas)"},
"DATOS_FALTANTES": {"criterio": "el dato faltante es una categoría más («Desconocido»); no se imputa ni se descarta",
"desconocidos_por_covariable": {n: {c: float((p.cohort[c] == "Desconocido").mean()) for c in p.covariates} for n, p in prepared.items()}},
"METODO_ANALITICO": {"modelos": "regresión logística con selección stepwise y red bayesiana con padres del desenlace por BDeu, uno por horizonte",
"horizontes_meses": recurrence["horizons"], "alfa_entrada": recurrence["alpha_in"], "alfa_salida": recurrence["alpha_out"],
"ess_bdeu": recurrence["bdeu_ess"], "maximo_de_padres": recurrence["max_parents"], "cox_penalizado": 0.05,
"combinacion": "promedio de la LR y la HBN"},
"BALANCE_CLASES": {"aplica": False, "motivo": "cada horizonte usa las pacientes con recaída hasta el horizonte o libres de ella después; no se rebalancea"},
"CONFIANZA_SALIDA": {"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por bootstrap",
"replicas": {"metabric": recurrence["n_bootstrap_metabric"], "scanb": recurrence["n_bootstrap_scanb"], "calculadora": recurrence["n_boot_calc"]},
"eventos_minimos_por_escenario": recurrence["min_events"]},
}
def population(calculators: dict, fits: dict[str, modeling.CohortModels], factors_table: pd.DataFrame, scenario_factors: dict,
recurrence: dict) -> dict:
"""What the version publishes under `analisis/`: `recurrencia`, the figure of each scenario of each cohort the dashboard
draws, and `recurrencia_desarrollo`, the tables behind them."""
figures = [r for n in COHORTS for r in calculators[n][0]]
points = pd.concat([calculators[n][1] for n in COHORTS], ignore_index=True)
auc = pd.concat([fits[n].auc for n in COHORTS], ignore_index=True)
def table(df: pd.DataFrame) -> dict:
df = df.replace([np.inf, -np.inf], np.nan).astype(object)
return {"columnas": [str(c) for c in df.columns], "filas": df.where(df.notna(), None).to_dict("records")}
return {"recurrencia": {"version": 1, "horizons_months": list(recurrence["horizons"]), "escenarios": figures},
"recurrencia_desarrollo": {"version": 1, "tablas": {"auc": table(auc), "factores_riesgo": table(factors_table),
"calculadora": table(points), "escenarios_resumen": table(scenario_factors["resumen"])}}}
+396 -27
View File
@@ -1,33 +1,402 @@
# CaMa recurrence analysis: the risk of recurrence by clinical scenario, from two external cohorts (METABRIC and SCAN-B).
# Trained from governance on the files in `data/`; the scenarios' figures are what the dashboard shows. Its covariates are the
# cohorts' own; the hospital's patient is placed in the scenarios her covariates meet.
# CaMa recurrence: the METABRIC and SCAN-B analyses of Luis as one scenario. Each cohort has its own covariates, categories and
# clinical scenarios, as in his scripts; the cohorts are not pooled.
domain = "cama"
scenario = "recurrence"
cohort = "cama/externa"
outcome = "recurrencia"
external = true # trained on files, not on a dbt cohort of the platform
modules = ["models.cama.recurrence.model"]
description = """\
Análisis de recurrencia: probabilidad de que la enfermedad regrese a los 12, 36 y 60 meses por escenario clínico, con una \
regresión logística y una red bayesiana por horizonte, entrenadas en dos cohortes externas (METABRIC y SCAN-B). Pendiente \
de validación clínica."""
requirements = ["pandas", "numpy", "scipy", "scikit-learn", "statsmodels", "pgmpy", "lifelines", "mpmath"]
cohort = "cama/cohorte_total"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "mpmath"]
settings_tables = ["modeling", "calculator", "variables"]
description = """
Recurrencia del cáncer de mama a 12, 36 y 60 meses desde el diagnóstico: regresión logística y red bayesiana, combinadas, \
sobre las variables de las cohortes METABRIC y SCAN-B; una figura por escenario clínico."""
[config.recurrence]
data_dir = "" # empty: the `data/` folder of this package
horizons = [12, 36, 60] # months
v_max = 0.80 # Cramér's V from which of two covariates the one with more unknowns is dropped
[config]
horizons_months = [12, 36, 60]
# ---- settings of the stages (Luis's scripts 03, 04 and 05) ----
[modeling]
seed = 42
unknown_label = "Desconocido"
cramer_v_max = 0.80 # of a pair of non-treatment covariates with V >= this, the one with more unknowns is dropped
alpha_prefilter = 0.10 # univariate prefilter of the logistic regression
alpha_in = 0.10 # stepwise: p to enter
alpha_out = 0.15 # stepwise: p to leave
bdeu_ess = 10
max_parents = 6
alpha_in = 0.10
alpha_out = 0.15
alpha_prefilter = 0.10
alpha = 0.05 # the risk factors' significance
freq_min = 0.80 # the bootstrap's stability criterion
n_bootstrap_metabric = 100
n_bootstrap_scanb = 40
n_boot_calc = 200 # replicas of each scenario's interval
min_events = 15 # recurrences a scenario needs to be drawn
cap_months = 72 # the figure's time axis
ks_seconds = 60 # time budget of each fractional Weibull fit
test_share = 0.30 # the 70/30 split of the AUC
[calculator]
min_events = 15 # a scenario is drawn only with at least this many recurrences
bootstrap_replicas = 200
cap_months = 72 # the curves are drawn dotted past the follow-up up to here
fractional_weibull_budget_s = 60
# ---- the variable dictionary ----
# `rules` read the timeline (`source` = the study of the catalog, `codes` its values; `ge`/`lt` bound a number) and give
# the category; `missing` is the category when no rule holds (the unknown is one more category, never imputed).
# `<cohort>.column` is the source file's column; `<cohort>.values` maps its values to the codes the loader sends;
# `<cohort>.labels` renames the rules' category where the source names it differently (neutral label = source label);
# `[variables.X.<cohort>]` replaces the rules for a variable whose categories differ between the cohorts.
[variables]
window_days_after_index = 365
[variables.index]
id_column = "paciente"
months_column = "tiempo_meses"
event_column = "evento"
death_source = "defuncion"
birth_source = "nacimiento"
recurrence_source = "recurrencia"
last_contact_source = "ultimo_contacto"
days_per_month = 30.4375
[variables.cohorts.metabric]
file = "brca_metabric_clinical_data.tsv"
id = "Patient ID"
months = "Relapse Free Status (Months)"
event = "Relapse Free Status" # "1:Recurred" is the event; rows without status or months are dropped
event_prefix = "1"
diagnosis_age = "Age at Diagnosis" # years
sex_filter = {}
diagnosis_month_day = "07-01"
diagnosis_year = 2000 # METABRIC records no year: a fixed one, the follow-up runs from it
# Per covariate, the source columns and category cuts as the preparation script defines them.
[variables.cohorts.scanb]
file = "scanb_clinical_metadata.txt"
id = "PatientName"
months = "RFI_days" # days, divided by days_per_month
months_divisor = 30.4375
event = "RFI_event"
sex_filter = { column = "Gender", value = "F" }
diagnosis_age = "Age_5year_bin" # the bin's lower edge; the age is that value minus 2, as in the script
diagnosis_age_offset = -2
diagnosis_month_day = "07-01"
diagnosis_year_column = "dxYear"
# Cuts shared by both cohorts (pd.cut with the right edge open).
[variables.Edad]
cuts = [0, 45, 60, 75, 200]
labels = ["<45", "45-59", "60-74", "75+"]
missing = "Desconocido"
[variables.Tamano_tumor]
bronze = "BiopsiaMama.bx_tamano_tumor_mm"
source = "tamano_tumor_mm"
cuts = [0, 20.01, 50.01, 10000]
labels = ["<=20 mm", "21-50 mm", ">50 mm"]
missing = "Desconocido"
metabric = { column = "Tumor Size" }
scanb = { column = "TumorSize_mm" }
[variables.Ganglios_positivos]
bronze = "BiopsiaMama.bx_ganglios_positivos"
source = "ganglios_positivos"
cuts = [0, 1, 4, 1000]
labels = ["0", "1-3", "4+"]
missing = "Desconocido"
metabric = { column = "Lymph nodes examined positive" }
scanb = { column = "NodeMetSpec", number_values = { "NodeNegative" = 0, "SubMicroMet" = 0, "1to3" = 2, "4toX" = 6 } }
[variables.Grado_histologico]
bronze = "BiopsiaMama.bx_grado_nottingham"
rules = [
{ source = "grado_nottingham", codes = ["G1"], then = "1" },
{ source = "grado_nottingham", codes = ["G2"], then = "2" },
{ source = "grado_nottingham", codes = ["G3"], then = "3" },
]
missing = "Desconocido"
metabric = { column = "Neoplasm Histologic Grade", values = { "1.0" = "G1", "2.0" = "G2", "3.0" = "G3" } }
scanb = { column = "NHG", values = { "Grade1" = "G1", "Grade2" = "G2", "Grade3" = "G3" } }
[variables.Receptor_estrogeno]
bronze = "BiopsiaMama.bx_receptor_estrogeno"
rules = [
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "ER Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "ER", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.Receptor_progesterona]
bronze = "BiopsiaMama.bx_receptor_progesterona"
rules = [
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positive" },
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "PR Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
scanb = { column = "PR", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" } }
[variables.HER2]
bronze = "BiopsiaMama.bx_her2_fish"
rules = [
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positive" },
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negative" },
{ source = "her2", codes = ["H3"], then = "Positive" },
{ source = "her2", codes = ["H0", "H1"], then = "Negative" },
]
missing = "Desconocido"
metabric = { column = "HER2 Status", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
scanb = { column = "HER2", values = { "Positive" = "POSITIVO", "Negative" = "NEGATIVO" }, bronze_source = "her2_fish" }
[variables.Tipo_histologico]
bronze = "BiopsiaMama.bx_tipo_histologico"
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Breast Invasive Ductal Carcinoma" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Breast Mixed Ductal and Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Breast Invasive Lobular Carcinoma" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Invasive Breast Carcinoma" },
{ source = "tipo_histologico", codes = ["8480/3"], then = "Breast Invasive Mixed Mucinous Carcinoma" },
{ source = "tipo_histologico", codes = ["8000/3"], then = "Breast" },
{ source = "tipo_histologico", codes = ["9120/3"], then = "Breast Angiosarcoma" },
{ source = "tipo_histologico", codes = ["8575/3"], then = "Metaplastic Breast Cancer" },
]
missing = "Desconocido"
metabric = { column = "Cancer Type Detailed", values = { "Breast Invasive Ductal Carcinoma" = "8500/3", "Breast Mixed Ductal and Lobular Carcinoma" = "8522/3", "Breast Invasive Lobular Carcinoma" = "8520/3", "Invasive Breast Carcinoma" = "8010/3", "Breast Invasive Mixed Mucinous Carcinoma" = "8480/3", "Breast" = "8000/3", "Breast Angiosarcoma" = "9120/3", "Metaplastic Breast Cancer" = "8575/3" } }
[variables.Tipo_histologico.scanb]
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal" },
{ source = "tipo_histologico", codes = ["8520/3"], then = "Lobular" },
{ source = "tipo_histologico", codes = ["8522/3"], then = "Ductal-Lobular" },
{ source = "tipo_histologico", codes = ["8523/3"], then = "Ductal-Other" },
{ source = "tipo_histologico", codes = ["8010/3"], then = "Other" },
]
column = "Histology"
values = { "Ductal" = "8500/3", "Lobular" = "8520/3", "Ductal-Lobular" = "8522/3", "Ductal-Other" = "8523/3", "Other" = "8010/3" }
[variables.Estado_menopausico]
bronze = "Paciente.pac_estado_menopausico"
rules = [
{ source = "estado_menopausico", codes = ["POSMENOPAUSIA"], then = "Post" },
{ source = "estado_menopausico", codes = ["PREMENOPAUSIA"], then = "Pre" },
]
missing = "Desconocido"
metabric = { column = "Inferred Menopausal State", values = { "Post" = "POSMENOPAUSIA", "Pre" = "PREMENOPAUSIA" } }
scanb = { column = "MenopauseStatus_bin", values = { "Postmenopausal" = "POSMENOPAUSIA", "Premenopausal" = "PREMENOPAUSIA" }, labels = { "Post" = "Postmenopausal", "Pre" = "Premenopausal" } }
[variables.Lateralidad]
bronze = "BiopsiaMama.bx_lateralidad"
rules = [
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Left" },
{ source = "lateralidad", codes = ["DERECHA"], then = "Right" },
]
missing = "Desconocido"
metabric = { column = "Primary Tumor Laterality", values = { "Left" = "IZQUIERDA", "Right" = "DERECHA" } }
scanb = { column = "Laterality", values = { "LEFT" = "IZQUIERDA", "RIGHT" = "DERECHA" }, labels = { "Left" = "LEFT", "Right" = "RIGHT" } }
# Treatments. The category is the source's own, as the scenarios of each cohort name them.
[variables.Cirugia]
treatment = "cirugia"
rules = [
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL"], then = "MASTECTOMY" },
{ source = "cirugia", codes = ["SEGMENTECTOMIA"], then = "BREAST CONSERVING" },
]
missing = "Desconocido"
metabric = { column = "Type of Breast Surgery", values = { "MASTECTOMY" = "MASTECTOMIA_TOTAL", "BREAST CONSERVING" = "SEGMENTECTOMIA" } }
scanb = { column = "SurgeryType", values = { "Mastectomy" = "MASTECTOMIA_TOTAL", "Lumpectomy" = "SEGMENTECTOMIA" }, labels = { "MASTECTOMY" = "Mastectomy", "BREAST CONSERVING" = "Lumpectomy" } }
[variables.Quimioterapia]
treatment = "quimioterapia"
rules = [
{ source = "quimioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "quimioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Chemotherapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Chemotherapy", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Radioterapia]
treatment = "radioterapia"
rules = [
{ source = "radioterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "radioterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Radio Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Radiation", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
[variables.Hormonoterapia]
treatment = "hormonoterapia"
rules = [
{ source = "hormonoterapia", codes = ["ADYUVANTE"], then = "YES" },
{ source = "hormonoterapia", codes = ["NINGUNA"], then = "NO" },
]
missing = "Desconocido"
metabric = { column = "Hormone Therapy", values = { "YES" = "ADYUVANTE" }, absent = "NINGUNA" }
scanb = { column = "Endocrine", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA", labels = { "YES" = "Yes", "NO" = "No" } }
# ---- METABRIC only ----
[variables.Carga_mutacional]
bronze = "Paciente.pac_carga_mutacional"
source = "carga_mutacional"
terciles = true # the cohort's own terciles of the mutation count
labels = ["baja", "media", "alta"]
missing = "Desconocido"
metabric = { column = "Mutation Count" }
[variables.Subtipo_PAM50]
bronze = "Paciente.pac_pam50"
rules = [
{ source = "pam50", codes = ["LUMA"], then = "LumA" },
{ source = "pam50", codes = ["LUMB"], then = "LumB" },
{ source = "pam50", codes = ["HER2"], then = "Her2" },
{ source = "pam50", codes = ["BASAL"], then = "Basal" },
{ source = "pam50", codes = ["CLAUDIN_LOW"], then = "claudin-low" },
{ source = "pam50", codes = ["NORMAL"], then = "Normal" },
{ source = "pam50", codes = ["NC"], then = "NC" },
]
missing = "Desconocido"
metabric = { column = "Pam50 + Claudin-low subtype", values = { "LumA" = "LUMA", "LumB" = "LUMB", "Her2" = "HER2", "Basal" = "BASAL", "claudin-low" = "CLAUDIN_LOW", "Normal" = "NORMAL", "NC" = "NC" } }
[variables.Celularidad]
bronze = "Paciente.pac_celularidad"
rules = [
{ source = "celularidad", codes = ["ALTA"], then = "High" },
{ source = "celularidad", codes = ["MODERADA"], then = "Moderate" },
{ source = "celularidad", codes = ["BAJA"], then = "Low" },
]
missing = "Desconocido"
metabric = { column = "Cellularity", values = { "High" = "ALTA", "Moderate" = "MODERADA", "Low" = "BAJA" } }
[variables.Cluster_integrativo]
bronze = "Paciente.pac_cluster_integrativo"
rules = [
{ source = "cluster_integrativo", codes = ["IC1"], then = "1" },
{ source = "cluster_integrativo", codes = ["IC2"], then = "2" },
{ source = "cluster_integrativo", codes = ["IC3"], then = "3" },
{ source = "cluster_integrativo", codes = ["IC4ERP"], then = "4ER+" },
{ source = "cluster_integrativo", codes = ["IC4ERN"], then = "4ER-" },
{ source = "cluster_integrativo", codes = ["IC5"], then = "5" },
{ source = "cluster_integrativo", codes = ["IC6"], then = "6" },
{ source = "cluster_integrativo", codes = ["IC7"], then = "7" },
{ source = "cluster_integrativo", codes = ["IC8"], then = "8" },
{ source = "cluster_integrativo", codes = ["IC9"], then = "9" },
{ source = "cluster_integrativo", codes = ["IC10"], then = "10" },
]
missing = "Desconocido"
metabric = { column = "Integrative Cluster", values = { "1" = "IC1", "2" = "IC2", "3" = "IC3", "4ER+" = "IC4ERP", "4ER-" = "IC4ERN", "5" = "IC5", "6" = "IC6", "7" = "IC7", "8" = "IC8", "9" = "IC9", "10" = "IC10" } }
# ---- SCAN-B only ----
[variables.Ki67]
bronze = "Paciente.pac_ki67_categoria"
rules = [
{ source = "ki67_categoria", codes = ["BAJO"], then = "Low" },
{ source = "ki67_categoria", codes = ["INTERMEDIO"], then = "Intermediate" },
{ source = "ki67_categoria", codes = ["ALTO"], then = "High" },
]
missing = "Desconocido"
scanb = { column = "Ki67", values = { "Low" = "BAJO", "Intermediate" = "INTERMEDIO", "High" = "ALTO" } }
[variables.Subtipo_clinico]
bronze = "Paciente.pac_subtipo_clinico"
rules = [
{ source = "subtipo_clinico", codes = ["LUMINAL_A"], then = "Luminal A" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_NEG"], then = "Luminal B HER2-" },
{ source = "subtipo_clinico", codes = ["LUMINAL_B_HER2_POS"], then = "Luminal B HER2+" },
{ source = "subtipo_clinico", codes = ["BASAL_LIKE"], then = "Basal-like" },
{ source = "subtipo_clinico", codes = ["NO_LUMINAL_HER2_POS"], then = "Non-luminal HER2+" },
{ source = "subtipo_clinico", codes = ["LUMINAL_NO_DETERMINADO"], then = "Luminal undetermined" },
{ source = "subtipo_clinico", codes = ["RE_NEG_NO_DETERMINADO"], then = "ER- undetermined" },
]
missing = "Desconocido"
scanb = { column = "ClinicalSubtype", values = { "Luminal A" = "LUMINAL_A", "Luminal B HER2-" = "LUMINAL_B_HER2_NEG", "Luminal B HER2+" = "LUMINAL_B_HER2_POS", "Basal-like" = "BASAL_LIKE", "Non-luminal HER2+" = "NO_LUMINAL_HER2_POS", "Luminal undetermined" = "LUMINAL_NO_DETERMINADO", "ER- undetermined" = "RE_NEG_NO_DETERMINADO" } }
[variables.Estadio_clinico]
bronze = "NotaMedica.nm_estadio_clinico"
rules = [
{ source = "estadio_clinico", codes = ["E0"], then = "0" },
{ source = "estadio_clinico", codes = ["EI"], then = "1" },
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "2" },
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "3" },
]
missing = "Desconocido"
scanb = { column = "tnm_ClinicalStage", values = { "0" = "E0", "1" = "EI", "2" = "EIIA", "3" = "EIIIA" } }
[variables.AntiHER2]
treatment = "anti_her2"
rules = [
{ source = "anti_her2", codes = ["ADYUVANTE"], then = "Yes" },
{ source = "anti_her2", codes = ["NINGUNA"], then = "No" },
]
missing = "Desconocido"
scanb = { column = "AntiHER2", values = { "Yes" = "ADYUVANTE" }, absent = "NINGUNA" }
# ---- which variables each cohort's model is designed on (before the Cramér's-V pruning) ----
[cohorts.metabric]
name = "METABRIC"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Carga_mutacional", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Subtipo_PAM50", "Tipo_histologico", "Celularidad", "Estado_menopausico",
"Cluster_integrativo", "Lateralidad", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
[cohorts.scanb]
name = "SCAN-B"
covariates = ["Edad", "Tamano_tumor", "Ganglios_positivos", "Grado_histologico", "Receptor_estrogeno",
"Receptor_progesterona", "HER2", "Ki67", "Subtipo_clinico", "Tipo_histologico", "Estado_menopausico", "Lateralidad",
"Estadio_clinico", "Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
treatment = ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"]
# ---- the clinical scenarios (SUBGRUPOS of `05_calculadora.py`): a conjunction of covariate categories ----
[[cohorts.metabric.scenarios]]
name = "RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.metabric.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.metabric.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.metabric.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.metabric.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.metabric.scenarios]]
name = "Basal (PAM50)"
when = { Subtipo_PAM50 = ["Basal"] }
[[cohorts.metabric.scenarios]]
name = "HER2 (PAM50)"
when = { Subtipo_PAM50 = ["Her2"] }
[[cohorts.metabric.scenarios]]
name = "Luminal B (PAM50)"
when = { Subtipo_PAM50 = ["LumB"] }
[[cohorts.metabric.scenarios]]
name = "RE+ · 1-3 ganglios · cirugía conservadora"
when = { Receptor_estrogeno = ["Positive"], Ganglios_positivos = ["1-3"], Cirugia = ["BREAST CONSERVING"] }
[[cohorts.metabric.scenarios]]
name = "RE− · grado 3"
when = { Receptor_estrogeno = ["Negative"], Grado_histologico = ["3"] }
[[cohorts.scanb.scenarios]]
name = "Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)"
when = { Subtipo_clinico = ["Luminal A"], Ganglios_positivos = ["0"], Tamano_tumor = ["<=20 mm"] }
[[cohorts.scanb.scenarios]]
name = "Ganglios 4+"
when = { Ganglios_positivos = ["4+"] }
[[cohorts.scanb.scenarios]]
name = "Tumor >50 mm"
when = { Tamano_tumor = [">50 mm"] }
[[cohorts.scanb.scenarios]]
name = "< 45 años"
when = { Edad = ["<45"] }
[[cohorts.scanb.scenarios]]
name = "≥ 75 años"
when = { Edad = ["75+"] }
[[cohorts.scanb.scenarios]]
name = "Basal-like"
when = { Subtipo_clinico = ["Basal-like"] }
[[cohorts.scanb.scenarios]]
name = "HER2+ (luminal B HER2+ o no luminal)"
when = { Subtipo_clinico = ["Luminal B HER2+", "Non-luminal HER2+"] }
[[cohorts.scanb.scenarios]]
name = "Luminal B HER2−"
when = { Subtipo_clinico = ["Luminal B HER2-"] }
[[cohorts.scanb.scenarios]]
name = "Luminal · 1-3 ganglios · lumpectomía"
when = { Subtipo_clinico = ["Luminal A", "Luminal B HER2-"], Ganglios_positivos = ["1-3"], Cirugia = ["Lumpectomy"] }
[[cohorts.scanb.scenarios]]
name = "Grado 3"
when = { Grado_histologico = ["3"] }
-194
View File
@@ -1,194 +0,0 @@
"""The recurrence models of one cohort: at each horizon the logistic regression (stepwise) and the Bayesian network (the
BDeu-greedy parents of the outcome), their AUC by internal validation and by bootstrap, how often each covariate enters the
bootstrap's regressions and the parents, and the penalised Cox model's concordance. Ported from `03_modelado.py` without its
figures. The selected terms and parents of each horizon are what the risk factors and the calculator read.
"""
import warnings
from dataclasses import dataclass
import numpy as np
import pandas as pd
import statsmodels.api as sm
from lifelines import CoxPHFitter
from lifelines.utils import concordance_index
from pgmpy.estimators import BDeu
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from models.cama.recurrence.prep import Prepared
@dataclass(frozen=True)
class FitSettings:
seed: int = 42
n_bootstrap: int = 100
bdeu_ess: int = 10
max_parents: int = 6
alpha_in: float = 0.10
alpha_out: float = 0.15
alpha_prefilter: float = 0.10
@dataclass(frozen=True, eq=False)
class CohortModels:
models: dict[str, dict] # by horizon: the LR terms, the HBN parents and how often each entered the bootstrap
auc: pd.DataFrame
c_index: float
class _Fitter:
def __init__(self, prepared: Prepared, settings: FitSettings):
self.covariates, self.s, self.total = prepared.covariates, settings, prepared.cohort
def encode(self, df: pd.DataFrame) -> pd.DataFrame:
X = pd.get_dummies(df[self.covariates], drop_first=True).astype(float)
return X.loc[:, X.nunique() > 1]
@staticmethod
def logit(y, X):
try:
return sm.Logit(y, sm.add_constant(X)).fit(disp=0, method="bfgs", maxiter=300)
except Exception:
return None
def prefilter(self, X, y) -> list[str]:
keep = []
for c in X.columns:
m = self.logit(y, X[[c]])
if m is not None and m.pvalues[c] < self.s.alpha_prefilter:
keep.append(c)
return keep
def stepwise(self, X, y) -> list[str]:
included = []
for _ in range(200):
changed, best, best_p = False, None, self.s.alpha_in
for c in [c for c in X.columns if c not in included]:
m = self.logit(y, X[included + [c]])
if m is not None and m.pvalues[c] < best_p:
best, best_p = c, m.pvalues[c]
if best is not None:
included.append(best)
changed = True
if included:
m = self.logit(y, X[included])
if m is not None:
p = m.pvalues.drop("const")
if p.max() > self.s.alpha_out:
included.remove(p.idxmax())
changed = True
if not changed:
break
return included
def lr(self, train: pd.DataFrame, test: pd.DataFrame):
X_all = self.encode(pd.concat([train, test]))
X_tr, X_te = X_all.loc[train.index], X_all.loc[test.index]
X_tr = X_tr.loc[:, X_tr.nunique() > 1]
X_te = X_te[X_tr.columns]
candidates = self.prefilter(X_tr, train["y"])
selected = self.stepwise(X_tr[candidates], train["y"]) if candidates else []
if not selected:
return None, [], np.full(len(test), train["y"].mean())
model = self.logit(train["y"], X_tr[selected])
return model, selected, model.predict(sm.add_constant(X_te[selected], has_constant="add")).values
def variable_of(self, term: str) -> str:
return next((c for c in sorted(self.covariates, key=len, reverse=True) if term.startswith(c + "_")), term)
def parents(self, train: pd.DataFrame) -> list[str]:
score = BDeu(train, equivalent_sample_size=self.s.bdeu_ess)
parents, current = [], score.local_score("outcome", [])
while len(parents) < self.s.max_parents:
best, gain = None, 0
for c in self.covariates:
if c in parents:
continue
g = score.local_score("outcome", parents + [c]) - current
if g > gain:
best, gain = c, g
if best is None:
break
parents.append(best)
current += gain
return parents
def hbn(self, train: pd.DataFrame, test: pd.DataFrame, parents: list[str]) -> np.ndarray:
if not parents:
return np.full(len(test), (train["outcome"] == "1").mean())
q = int(np.prod([train[p].nunique() for p in parents]))
alpha = self.s.bdeu_ess / (2 * q)
g = train.groupby(parents)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
overall = (train["outcome"] == "1").mean()
table = {(k if isinstance(k, tuple) else (k,)): (r.n1 + alpha) / (r.n + 2 * alpha) for k, r in g.iterrows()}
return np.array([table.get(k, overall) for k in map(tuple, test[parents].values)])
def bn_table(self, df: pd.DataFrame) -> pd.DataFrame:
t = df[self.covariates].astype(str).copy()
t["outcome"] = df["y"].astype(int).astype(str)
return t
def at_horizon(self, H: int) -> pd.DataFrame:
recurs = (self.total["evento"] == 1) & (self.total["tiempo_meses"] <= H)
free = self.total["tiempo_meses"] > H
d = self.total[recurs | free].reset_index(drop=True)
d["y"] = ((d["evento"] == 1) & (d["tiempo_meses"] <= H)).astype(int)
return d
def fit_cohort(name: str, prepared: Prepared, horizons: list[int], settings: FitSettings) -> CohortModels:
"""The LR and the HBN at each horizon, their AUC and the bootstrap's, and the Cox model's concordance."""
warnings.filterwarnings("ignore")
f, s = _Fitter(prepared, settings), settings
total = prepared.cohort
cox_df = pd.get_dummies(total[["tiempo_meses", "evento"] + f.covariates], columns=f.covariates, drop_first=True).astype(float)
cox_df = cox_df.loc[:, cox_df.nunique() > 1]
tr, te = train_test_split(cox_df, test_size=0.3, random_state=s.seed, stratify=cox_df["evento"])
ok = [c for c in tr.columns if c in ("tiempo_meses", "evento") or 10 <= tr[c].sum() <= len(tr) - 10]
tr, te = tr[ok], te[ok]
cox = CoxPHFitter(penalizer=0.05).fit(tr, "tiempo_meses", "evento", fit_options={"step_size": 0.5})
c_index = float(concordance_index(te["tiempo_meses"], -cox.predict_partial_hazard(te), te["evento"]))
rows, models = [], {}
for H in horizons:
coh = f.at_horizon(H)
tr_idx, te_idx = train_test_split(coh.index, test_size=0.3, random_state=s.seed, stratify=coh["y"])
train, test = coh.loc[tr_idx], coh.loc[te_idx]
_, selected, p_lr = f.lr(train, test)
auc_lr = roc_auc_score(test["y"], p_lr)
bn_train, bn_test = f.bn_table(train), f.bn_table(test)
parents = f.parents(bn_train)
auc_hbn = roc_auc_score(test["y"], f.hbn(bn_train, bn_test, parents))
rng = np.random.default_rng(s.seed)
aucs, count_lr, count_hbn, n_rep = [], {}, {}, 0
for b in range(s.n_bootstrap):
boot = coh.iloc[rng.integers(0, len(coh), len(coh))].reset_index(drop=True)
try:
b_train, b_test = train_test_split(boot, test_size=0.3, random_state=s.seed + b, stratify=boot["y"])
m, _, p = f.lr(b_train, b_test)
a_lr = roc_auc_score(b_test["y"], p)
bt, be = f.bn_table(b_train), f.bn_table(b_test)
pa = f.parents(bt)
a_h = roc_auc_score(b_test["y"], f.hbn(bt, be, pa))
except Exception:
continue
aucs.append((a_lr, a_h))
n_rep += 1
if m is not None:
for v in {f.variable_of(t) for t in m.params.drop("const").index}:
count_lr[v] = count_lr.get(v, 0) + 1
for v in pa:
count_hbn[v] = count_hbn.get(v, 0) + 1
aucs = np.array(aucs) if aucs else np.full((1, 2), np.nan)
for j, (label, auc) in enumerate([("LR", auc_lr), ("HBN", auc_hbn)]):
rows.append({"cohorte": name, "horizonte_meses": H, "modelo": label, "n_modelo": len(coh), "recurrencias": int(coh["y"].sum()),
"AUC_validacion_interna": auc, "AUC_bootstrap_medio": np.nanmean(aucs[:, j]),
"AUC_bootstrap_IC95_inf": np.nanpercentile(aucs[:, j], 2.5), "AUC_bootstrap_IC95_sup": np.nanpercentile(aucs[:, j], 97.5),
"replicas_bootstrap": n_rep})
models[str(H)] = {"terminos_lr": list(selected), "padres_hbn": parents, "n_replicas": n_rep,
"seleccion_lr": count_lr, "seleccion_hbn": count_hbn,
"arcos_hbn": [[p, "outcome"] for p in parents]}
rows.append({"cohorte": name, "horizonte_meses": "completo", "modelo": "Cox penalizado (C-index)", "n_modelo": len(total),
"recurrencias": int(total["evento"].sum()), "AUC_validacion_interna": c_index})
return CohortModels(models, pd.DataFrame(rows).round(4), c_index)
-36
View File
@@ -1,36 +0,0 @@
"""A hospital patient in the recurrence analysis' terms: her covariates as the external cohorts name them, and the scenarios
(subgroups defined by covariates) she belongs to. What the hospital does not report (nodes, subtype, surgery...) is not given, so
a scenario that needs it does not include her."""
import numpy as np
import pandas as pd
from models.cama.recurrence import prep
POSITIVE = {"POSITIVO": "Positive", "NEGATIVO": "Negative"}
HER2 = {"H3": "Positive", "H0": "Negative", "H1": "Negative"} # 2+ is equivocal: not given
def _bin(value, cuts: list, labels: list) -> str | None:
if value is None or pd.isna(value):
return None
return str(pd.cut([float(value)], cuts, labels=labels, right=False)[0])
def covariates_of(row: pd.Series) -> dict[str, str]:
"""The covariates of one labelled member (`models.cama.survival.live.members`) that the cohorts also have."""
found = {
"Edad": _bin(row.get("age_years"), prep.AGE_CUTS, prep.AGE_LABELS),
"Tamano_tumor": _bin(row.get("size_mm"), prep.SIZE_CUTS, prep.SIZE_LABELS),
"Grado_histologico": {"G1": "1", "G2": "2", "G3": "3"}.get(row.get("grade")),
"Receptor_estrogeno": POSITIVE.get(row.get("er")),
"Receptor_progesterona": POSITIVE.get(row.get("pr")),
"HER2": HER2.get(row.get("her2")),
}
return {k: v for k, v in found.items() if v is not None}
def matching(scenarios: list[dict], covariates: dict[str, str]) -> list[dict]:
"""The scenarios whose every condition her covariates meet, the larger first within each cohort."""
met = [s for s in scenarios if all(var in covariates and covariates[var] in values for var, values in s["condiciones"].items())]
return sorted(met, key=lambda s: (s["cohorte"], -s["n"]))
-108
View File
@@ -1,108 +0,0 @@
"""The recurrence analysis' data: the two external cohorts (METABRIC and SCAN-B) as one table each, the covariates as
categories with the unknowns as one more, and the redundant covariates (Cramér's V at or above the limit) dropped. Ported
from `01_preparacion_metabric.py` and `02_preparacion_scanb.py`.
"""
from dataclasses import dataclass
import numpy as np
import pandas as pd
from scipy.stats import chi2_contingency
DAYS_PER_MONTH = 30.4375
AGE_CUTS, AGE_LABELS = [0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]
SIZE_CUTS, SIZE_LABELS = [0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]
NODE_CUTS, NODE_LABELS = [0, 1, 4, 1e3], ["0", "1-3", "4+"]
@dataclass(frozen=True, eq=False)
class Prepared:
cohort: pd.DataFrame # paciente, tiempo_meses, evento and the covariates
covariates: list[str]
treatment: list[str]
eliminated: list[str]
def _unknown(s: pd.Series) -> pd.Series:
return s.astype("object").where(s.notna(), "Desconocido").astype(str)
def _cut(s: pd.Series, cuts: list, labels: list) -> pd.Series:
return _unknown(pd.cut(s, cuts, labels=labels, right=False).astype("object"))
def cramer_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b)
chi2 = chi2_contingency(table, correction=False)[0]
k = min(table.shape) - 1
return float(np.sqrt(chi2 / (table.values.sum() * k))) if k > 0 else 0.0
def _drop_collinear(out: pd.DataFrame, covariates: list[str], treatment: list[str], v_max: float) -> tuple[list[str], list[str]]:
"""Of each pair of non-treatment covariates with V at or above `v_max`, the one with more unknowns goes."""
covariates, eliminated = list(covariates), []
candidates = [c for c in covariates if c not in treatment]
pairs = sorted(((cramer_v(out[a], out[b]), a, b) for i, a in enumerate(candidates) for b in candidates[i + 1:]), reverse=True)
for v, a, b in pairs:
if v < v_max:
break
if a in eliminated or b in eliminated:
continue
drop = a if (out[a] == "Desconocido").mean() >= (out[b] == "Desconocido").mean() else b
eliminated.append(drop)
covariates.remove(drop)
return covariates, eliminated
def _finish(out: pd.DataFrame, fixed: list[str], treatment: list[str], v_max: float) -> Prepared:
covariates = [c for c in out.columns if c not in fixed]
covariates, eliminated = _drop_collinear(out, covariates, treatment, v_max)
return Prepared(out[[*fixed, *covariates]], covariates, [c for c in treatment if c in covariates], eliminated)
def prepare_metabric(path: str, v_max: float) -> Prepared:
d = pd.read_csv(path, sep="\t")
d = d.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["Patient ID"]})
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float)
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int)
out["Edad"] = _cut(d["Age at Diagnosis"], AGE_CUTS, AGE_LABELS)
out["Tamano_tumor"] = _cut(d["Tumor Size"], SIZE_CUTS, SIZE_LABELS)
out["Ganglios_positivos"] = _cut(d["Lymph nodes examined positive"], NODE_CUTS, NODE_LABELS)
out["Grado_histologico"] = _unknown(d["Neoplasm Histologic Grade"].map({1.0: "1", 2.0: "2", 3.0: "3"}))
mutations = d["Mutation Count"]
q = mutations.quantile([1 / 3, 2 / 3]).values
out["Carga_mutacional"] = _cut(mutations, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], ["baja", "media", "alta"])
for name, column in [("Receptor_estrogeno", "ER Status"), ("Receptor_progesterona", "PR Status"), ("HER2", "HER2 Status"),
("Subtipo_PAM50", "Pam50 + Claudin-low subtype"), ("Tipo_histologico", "Cancer Type Detailed"),
("Celularidad", "Cellularity"), ("Estado_menopausico", "Inferred Menopausal State"),
("Cluster_integrativo", "Integrative Cluster"), ("Lateralidad", "Primary Tumor Laterality"),
("Cirugia", "Type of Breast Surgery"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radio Therapy"), ("Hormonoterapia", "Hormone Therapy")]:
out[name] = _unknown(d[column])
return _finish(out, ["paciente", "tiempo_meses", "evento"], ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], v_max)
def prepare_scanb(path: str, v_max: float) -> Prepared:
d = pd.read_csv(path, sep="\t", low_memory=False)
d = d[d["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["PatientName"]})
out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH
out["evento"] = d["RFI_event"].astype(int)
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int)
out["Edad"] = _cut(d["Age_5year_bin"].astype(float) - 2, AGE_CUTS, AGE_LABELS)
out["Tamano_tumor"] = _cut(d["TumorSize_mm"], SIZE_CUTS, SIZE_LABELS)
out["Ganglios_positivos"] = _unknown(d["NodeMetSpec"].map({"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}))
out["Grado_histologico"] = _unknown(d["NHG"].map({"Grade1": "1", "Grade2": "2", "Grade3": "3"}))
for name, column in [("Receptor_estrogeno", "ER"), ("Receptor_progesterona", "PR"), ("HER2", "HER2"), ("Ki67", "Ki67"),
("Subtipo_clinico", "ClinicalSubtype"), ("Tipo_histologico", "Histology"),
("Estado_menopausico", "MenopauseStatus_bin"), ("Lateralidad", "Laterality"),
("Estadio_clinico", "tnm_ClinicalStage"), ("Cirugia", "SurgeryType"), ("Quimioterapia", "Chemotherapy"),
("Radioterapia", "Radiation"), ("Hormonoterapia", "Endocrine"), ("AntiHER2", "AntiHER2")]:
out[name] = _unknown(d[column])
return _finish(out, ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], v_max)
PREPARE = {"metabric": prepare_metabric, "scanb": prepare_scanb}
FILES = {"metabric": "brca_metabric_clinical_data.tsv", "scanb": "scanb_clinical_metadata.txt"}
-42
View File
@@ -1,42 +0,0 @@
"""The recurrence analysis' training data: two files on disk, not a cohort of the platform. It takes the part of a cohort source
(`models.io.storage.CohortSource`) for the training run: the reference the version is traced to, which is the hash of the files."""
import hashlib
from dataclasses import dataclass
from pathlib import Path
import pandas as pd
from models.cama.recurrence.prep import FILES
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG
from models.io.registry import REFERENCE_SOURCE
PACKAGE_DATA = Path(__file__).parent / "data"
URL = "cama/externa/metabric+scanb"
def data_folder(configured: str) -> Path:
return Path(configured) if configured else PACKAGE_DATA
@dataclass
class ExternalCohorts:
"""The METABRIC and SCAN-B files of a folder."""
folder: Path = PACKAGE_DATA
armado_id: int | None = None
def sha256(self) -> str:
digest = hashlib.sha256()
for name in sorted(FILES.values()):
digest.update((self.folder / name).read_bytes())
return digest.hexdigest()
def frame(self) -> pd.DataFrame:
return pd.DataFrame()
def lineage(self) -> dict[str, str]:
return {"url": URL, "files": ",".join(sorted(FILES.values())), "sha256": self.sha256()}
def reference(self) -> dict[str, str]:
return {COHORT_URL_TAG: URL, COHORT_SOURCE_TAG: REFERENCE_SOURCE, COHORT_BUILD_TAG: self.sha256()}
-31
View File
@@ -1,31 +0,0 @@
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
import argparse
import sys
def run_steps(args: argparse.Namespace) -> int:
"""`models run cama recurrence --train --promote`: this scenario trains on its files, not on a cohort build."""
from models.__main__ import _promote_step
from models.cama.recurrence.source import ExternalCohorts, data_folder
from models.dags.training import Scenario, find_trained, train
if args.export or args.estimate or args.store or args.version:
print("cama/recurrence trains on its external cohorts: only --train and --promote apply", file=sys.stderr)
return 2
scenario = Scenario.load("cama", "recurrence")
source = ExternalCohorts(data_folder(scenario.config["recurrence"]["data_dir"]))
environment = args.environment.upper()
version = find_trained(scenario, source, environment)
if args.train:
if version:
print(f"already trained: version {version}, from {source.lineage()['sha256'][:12]}")
else:
version = train(scenario, source, environment)
print(f"trained: version {version}, from {source.lineage()['sha256'][:12]}")
if args.promote:
if not version:
print(f"no {environment} version trained: use --train", file=sys.stderr)
return 1
return _promote_step(args, version)
return 0
@@ -9,7 +9,6 @@ likelihood on monthly counts of events and censorings (`tabla_eventos`), by Neld
import time
from functools import lru_cache
import mpmath as mp
import numpy as np
from scipy.optimize import minimize
from scipy.special import gammaln
@@ -17,6 +16,7 @@ from scipy.special import gammaln
@lru_cache(maxsize=256)
def _coefs(rho, m, l, N, dps):
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
mp.mp.dps = dps
rho, m, l = mp.mpf(rho), mp.mpf(m), mp.mpf(l)
c = [mp.mpf(1)]
@@ -37,6 +37,7 @@ def _log_terms(az, rho, m, l, N):
def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
"""The Kilbas-Saigo function E_{rho,m,l}(z) at each `z`: the plain series when its terms stay small, else a polynomial
in `mpmath` with as many digits as the largest term needs; NaN where even that is out of reach."""
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
z = np.atleast_1d(np.asarray(z, float))
rho, m, l = float(rho), float(m), float(l)
out = np.full(z.shape, np.nan)
@@ -80,6 +81,7 @@ def kilbas_saigo(z, rho, m, l, tol=1e-18, logmax_cap=300.0, nmax=40000):
def S_ks(t, k, alpha, beta, lam, tau1=None, tau2=None):
"""The fractional Weibull's survival function at `t`; NaN outside its parameter region."""
import mpmath as mp # imported here: a module-level mpmath can't be stored with the model
tau1 = lam if tau1 is None else tau1
tau2 = lam if tau2 is None else tau2
t = np.atleast_1d(np.asarray(t, float))
+121
View File
@@ -0,0 +1,121 @@
"""CaMa survival as a registered scenario: from the cohort's long frame to a fitted model, its metrics and the routines'
records. The six stages of the pipeline (`run.py`) are the analysis; the scenario runs the first, the depuration, over the
members' variables and fits the interval models of the survival stage (`seer_model.fit`).
Nodes: `recoded` (the dictionary applied to the cohort), `depurated` (stage 01), `fitted_model`, `metrics` and `routines`.
The cohort's own index, the first invasive biopsy, is `models.steps.indexing`'s (`[config.index]`).
"""
import tempfile
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.seer_survival import run, variables
from models.cama.seer_survival import seer_model as sm_
from models.cama.seer_survival import survival_curves as sc
from models.cama.seer_survival import survival_models as fits
from models.cama.seer_survival.settings import Settings, load
RECODED_FILE = "dataframe_recodificado.csv"
def settings() -> Settings:
return load()
def dictionary() -> dict:
return variables.load()
def recoded(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame:
"""One row per member, in the columns of the variable dictionary."""
return variables.recode(cohort, dictionary)
def depurated(recoded: pd.DataFrame, settings: Settings) -> pd.DataFrame:
"""Stage 01 over the members: the frame without the variables the depuration drops."""
with tempfile.TemporaryDirectory() as folder:
path = Path(folder)
recoded.to_csv(path / RECODED_FILE, index=False)
run.run_depuration(path / RECODED_FILE, path / "sin_mapa.json", path, settings)
return pd.read_csv(path / run.DEPURATED, dtype=str, keep_default_na=False)
def fitted_model(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, settings: Settings,
index: dict) -> sm_.SeerSurvivalModel:
return sm_.fit(recoded, depurated, dictionary, settings.survival, index)
def metrics(fitted_model: sm_.SeerSurvivalModel) -> dict:
state = fitted_model.fit_state
return {"members": state.members, "deaths": state.deaths, "covariates": len(state.design.covariates),
"replicas": len(state.replicas),
**{f"weight_lr_interval_{i + 1}": float(w) for i, w in enumerate(state.weights)}}
def sampling(recoded: pd.DataFrame, fitted_model: sm_.SeerSurvivalModel, index_attrition: list, prior_observation: dict,
dictionary: dict) -> dict:
"""MUESTREO: who could be used (the index and each rule's attrition, their prior history), the follow-up and the
resampling."""
s, state = fitted_model.survival, fitted_model.fit_state
return {"method": "toda la cohorte indexada en su primera biopsia invasora; sin partición: la validación es de las "
f"predicciones fuera de muestra en {s.stack_folds} pliegues y de las réplicas bootstrap",
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"members": state.members, "deaths": state.deaths, "follow_up_cap_months": s.cap_months,
"bootstrap_replicas": len(state.replicas), "stack_folds": s.stack_folds}
def missing_data(recoded: pd.DataFrame, dictionary: dict) -> dict:
"""DATOS_FALTANTES: how many members lack each variable (its `missing` category), and what is done about it."""
counts = {}
for name in variables.variable_names(dictionary):
spec = dictionary[name]
if spec.get("internal"):
continue
counts[name] = int((recoded[variables.column_of(name, spec)] == spec["missing"]).sum())
return {"method": "un dato ausente es la categoría `missing` de su variable en el diccionario; nadie se excluye",
"members": len(recoded), "missing_by_variable": counts}
def analytic_method(fitted_model: sm_.SeerSurvivalModel) -> dict:
"""METODO_ANALITICO: the LR coefficients and the HBN's parents of each interval, and the weights that combine them."""
s, state = fitted_model.survival, fitted_model.fit_state
design = state.design
names = [f"{c}={k}" for c in design.covariates for k in design.sorted_categories[c][1:]]
intervals = []
for (a, b), fit, weight in zip(zip([0] + list(s.horizons[:-1]), s.horizons), state.point, state.weights):
intervals.append({"interval_months": [int(a), int(b)], "weight_lr": float(weight),
"intercept": float(fit.intercept), "coefficients": dict(zip(names, map(float, fit.coef))),
"hbn_parents": [design.covariates[j] for j in fit.parents]})
return {"method": "regresión logística y red bayesiana con tabla de probabilidad por intervalo, combinadas con el peso "
"que maximiza la verosimilitud fuera de muestra", "covariates": design.covariates, "intervals": intervals}
def class_balance(fitted_model: sm_.SeerSurvivalModel, depurated: pd.DataFrame) -> dict:
"""BALANCE_CLASES: the members at risk and the deaths of each interval; none is reweighted but the half weight of a
censoring inside an interval."""
s = fitted_model.survival
frame = sc.survival_frame(depurated, s)
months, event = frame.df["meses_int"].values, frame.df["evento"].values
rows = []
for a, b in zip([0] + list(s.horizons[:-1]), s.horizons):
at_risk = months >= a
rows.append({"interval_months": [int(a), int(b)], "at_risk": int(at_risk.sum()),
"deaths": int((event & at_risk & (months < b)).sum()),
"censored": int(((~event) & at_risk & (months < b)).sum())})
return {"method": "las clases se usan en su proporción observada; una censura dentro de un intervalo pesa la mitad",
"intervals": rows}
def output_confidence(fitted_model: sm_.SeerSurvivalModel) -> dict:
"""CONFIANZA_SALIDA: the survival at each horizon of the members of each decile of predicted survival, out of sample,
against the Kaplan-Meier of those members."""
return {"method": "calibración fuera de muestra: supervivencia predicha contra Kaplan-Meier, por deciles",
"deciles": fitted_model.fit_state.calibration}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict, output_confidence: dict) -> dict:
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
+391 -2
View File
@@ -1,10 +1,32 @@
# CaMa SEER survival pipeline: settings of each stage. Paths are never here: they enter the DAG as inputs.
domain = "cama"
scenario = "seer_survival"
cohort = "cama/cohorte_total"
outcome = "survival_18m"
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "statsmodels", "pgmpy", "cloudpickle"]
modules = ["models.cama.seer_survival.model", "models.steps.indexing"]
# The tables whose values make a version a different one (with `[config]`): the depuration, the survival stage's settings
# and the variable dictionary.
settings_tables = ["depuration", "survival", "variables"]
description = """
Supervivencia del cáncer de mama a 6, 12 y 18 meses desde el diagnóstico (primera biopsia con carcinoma invasor): \
regresión logística y red bayesiana por intervalo, combinadas, sobre las variables del diccionario del modelo; \
entrenado y validado con los datos de SEER."""
# The dataflow's config (`with_config`).
[config]
horizons_years = [0.5, 1.0, 1.5]
[config.index]
kind = "primera_biopsia_invasora"
observacion_previa_minima_dias = 0
[depuration]
exclude = ["Outcome_cat"] # never analysed or touched
auto_extra = ["Age_group", "Tumor_group"] # included when present
extra_cols = []
protected = [] # e.g. ["Estadio_cat"]: never dropped
protected = ["Estadio_cat", "Subtipo_molecular_cat", "Tratamiento_quirurgico_cat"] # the axes of the clinical scenarios: never dropped
prefer = ["Tumor_group", "Age_group"] # on a tie or duplicate, the one listed here wins (the project's own groupings)
drop_raw_sources = true # also drop the raw SEER column of a dropped variable
unknown_label = "Desconocido"
@@ -151,7 +173,111 @@ xlim_sub = [] # e.g. [0, 72] to hide the extrapolation; empty
[survival.ylim_sub] # manual zoom of the y axis per subgroup, e.g. "Estadio I" = [0.97, 1.0]
# The subgroups of the survival curves, and the risk factors of each, are the clinical scenarios of `scenarios.py`.
# The clinical scenarios, in the doctors' terms: every condition must hold. A condition names a variable of the
# dictionary (`Edad`: the age in years, the start of its band) and tests `contains` (the category has this text), `in` (it
# is one of these) or, for the age, `ge` / `lt`.
[[survival.subgroups]]
name = "HER2+ · ≥60 años · estadio III–IV (Alto)"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2+" },
{ variable = "Edad", ge = 60 },
{ variable = "Estadio", in = ["III", "IV"] }
]
[[survival.subgroups]]
name = "HER2+ · <60 años · estadio 0–II (Bajo)"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2+" },
{ variable = "Edad", lt = 60 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
]
[[survival.subgroups]]
name = "Estadio IV"
conditions = [
{ variable = "Estadio", in = ["IV"] }
]
[[survival.subgroups]]
name = "Estadio I"
conditions = [
{ variable = "Estadio", in = ["I"] }
]
[[survival.subgroups]]
name = "≥ 75 años"
conditions = [
{ variable = "Edad", ge = 75 }
]
[[survival.subgroups]]
name = "< 45 años"
conditions = [
{ variable = "Edad", lt = 45 }
]
[[survival.subgroups]]
name = "Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Edad", lt = 45 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[[survival.subgroups]]
name = "HER2− · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[[survival.subgroups]]
name = "HER2+ · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2+" },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[[survival.subgroups]]
name = "Jóvenes (<45) · estadio 0–II"
conditions = [
{ variable = "Edad", lt = 45 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
]
[[survival.subgroups]]
name = "Jóvenes (<45) · HER2−"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Edad", lt = 45 }
]
[[survival.subgroups]]
name = "Triple negativo (HR−/HER2−) · estadio 0–II"
conditions = [
{ variable = "Subtipo_molecular", contains = "HR-/HER2-" },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] }
]
[[survival.subgroups]]
name = "≥ 65 años · HER2− · estadio 0–II · cirugía conservadora"
conditions = [
{ variable = "Subtipo_molecular", contains = "HER2-" },
{ variable = "Edad", ge = 65 },
{ variable = "Estadio", in = ["0 (in situ)", "I", "II"] },
{ variable = "Tratamiento_quirurgico", in = ["Conservadora"] }
]
[figure]
# The scenario figure computed on request (`SeerSurvivalModel.figure_record`): the seconds the fractional Weibull may take,
# the least members and deaths a scenario needs to be drawn, and the bootstrap replicas applied (empty: all of the model's).
ks_max_seconds = 30
min_members = 30
min_deaths = 5
n_boot = 100
[risk_factors]
# A category is a risk factor from four criteria: c1 the multivariable OR in the natural population (95 % CI not
@@ -263,3 +389,266 @@ Microcalcificaciones_cat = "Microcalcificaciones"
Multifocalidad_cat = "Multifocalidad"
BRCA_cat = "BRCA"
HER2_IHQ_cat = "HER2_IHQ"
# ----------------------------------------------------------------------------------------------------------------------
# The variable dictionary. One table per variable of the model: the column it makes, how its category is read from a
# patient's timeline (`rules`, in order, the first that holds; `missing` when none does) and, for the SEER load, where the
# SEER category is stored in CaMa's bronze (`seer`). A rule is one condition or a `when` list that must all hold; a
# condition names a timeline `source` (the `tipo` of the patient's latest event of that kind) or an earlier `variable`,
# and tests `codes` (the value is one of them), `present` (there is such an event), or `ge` / `lt` (the number).
# ----------------------------------------------------------------------------------------------------------------------
[variables]
window_days_after_index = 365 # the events from the index on that still describe the patient at diagnosis and treatment
[variables.index]
id_column = "Patient_ID"
year_column = "Year_of_diagnosis"
age_column = "Age_recode_with_1_year_olds_and_90"
age_band_years = 5
age_open_from = 90
age_label = "{low}-{high} years"
age_open_label = "{low}+ years"
age_unknown = "Otros (agrupado)"
months_column = "Survival_months"
vital_column = "Vital_status_recode_study_cutoff_used"
alive = "Alive"
dead = "Dead"
days_per_month = 30.4375
death_source = "defuncion"
birth_source = "nacimiento"
# SEER's calendar dates are not recorded: the diagnosis is the 1st of July of its year, the birth the middle of the age
# band, the death the diagnosis plus the survival months, the last contact of the living the same.
seer_diagnosis_month_day = "07-01"
seer_age_open_value = 92
[variables.Estadio]
rules = [
{ source = "estadio_clinico", codes = ["E0"], then = "0 (in situ)" },
{ source = "estadio_clinico", codes = ["EI"], then = "I" },
{ source = "estadio_clinico", codes = ["EIIA", "EIIB"], then = "II" },
{ source = "estadio_clinico", codes = ["EIIIA", "EIIIB", "EIIIC"], then = "III" },
{ source = "estadio_clinico", codes = ["EIV"], then = "IV" },
]
missing = "Desconocido"
seer = { bronze = "NotaMedica.nm_estadio_clinico", values = { "0 (in situ)" = "E0", "I" = "EI", "II" = "EIIA", "III" = "EIIIA", "IV" = "EIV" } }
[variables.Grado_histologico]
rules = [
{ source = "grado_nottingham", codes = ["G1"], then = "G1" },
{ source = "grado_nottingham", codes = ["G2"], then = "G2" },
{ source = "grado_nottingham", codes = ["G3"], then = "G3" },
]
missing = "Desconocido"
seer = { bronze = "BiopsiaMama.bx_grado_nottingham", values = { "G1" = "G1", "G2" = "G2", "G3" = "G3" } }
[variables.Receptor_estrogeno]
rules = [
{ source = "receptor_estrogeno", codes = ["POSITIVO"], then = "Positivo" },
{ source = "receptor_estrogeno", codes = ["NEGATIVO"], then = "Negativo" },
]
missing = "Desconocido"
seer = { bronze = "BiopsiaMama.bx_receptor_estrogeno", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } }
[variables.Receptor_progesterona]
rules = [
{ source = "receptor_progesterona", codes = ["POSITIVO"], then = "Positivo" },
{ source = "receptor_progesterona", codes = ["NEGATIVO"], then = "Negativo" },
]
missing = "Desconocido"
seer = { bronze = "BiopsiaMama.bx_receptor_progesterona", values = { "Positivo" = "POSITIVO", "Negativo" = "NEGATIVO" } }
# HER2 is positive or negative by the FISH when there is one, else by the immunohistochemistry (3+ positive, 0 and 1+
# negative, 2+ equivocal).
[variables.HER2_estado]
internal = true
rules = [
{ source = "her2_fish", codes = ["POSITIVO"], then = "Positivo" },
{ source = "her2_fish", codes = ["NEGATIVO"], then = "Negativo" },
{ source = "her2", codes = ["H3"], then = "Positivo" },
{ source = "her2", codes = ["H0", "H1"], then = "Negativo" },
]
missing = "Desconocido"
seer = { from = "Subtipo_molecular", bronze = "BiopsiaMama.bx_her2_fish", values = { "HR+/HER2+" = "POSITIVO", "HR-/HER2+" = "POSITIVO", "HR+/HER2-" = "NEGATIVO", "HR-/HER2-" = "NEGATIVO" } }
[variables.HER2_IHQ]
rules = [
{ source = "her2", codes = ["H0"], then = "0" },
{ source = "her2", codes = ["H1"], then = "1+" },
{ source = "her2", codes = ["H2"], then = "2+" },
{ source = "her2", codes = ["H3"], then = "3+" },
]
missing = "Sin dato"
seer = { bronze = "BiopsiaMama.bx_her2", values = { "0" = "H0", "1+" = "H1", "2+" = "H2", "3+" = "H3" } }
[variables.HR_estado]
internal = true
rules = [
{ when = [{ variable = "Receptor_estrogeno", codes = ["Positivo"] }], then = "HR+" },
{ when = [{ variable = "Receptor_progesterona", codes = ["Positivo"] }], then = "HR+" },
{ when = [{ variable = "Receptor_estrogeno", codes = ["Negativo"] }, { variable = "Receptor_progesterona", codes = ["Negativo"] }], then = "HR-" },
]
missing = "Desconocido"
[variables.Subtipo_molecular]
rules = [
{ when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR+/HER2-" },
{ when = [{ variable = "HR_estado", codes = ["HR+"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR+/HER2+" },
{ when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Positivo"] }], then = "HR-/HER2+" },
{ when = [{ variable = "HR_estado", codes = ["HR-"] }, { variable = "HER2_estado", codes = ["Negativo"] }], then = "HR-/HER2-" },
]
missing = "Desconocido"
[variables.Tipo_histologico]
rules = [
{ source = "tipo_histologico", codes = ["8500/3"], then = "Ductal (NST)" },
{ source = "tipo_histologico", codes = ["8520/3", "8521/3"], then = "Lobulillar" },
{ source = "tipo_histologico", codes = ["8522/3", "8523/3"], then = "Ductal-lobulillar mixto" },
{ source = "tipo_histologico", codes = ["8480/3"], then = "Mucinoso" },
{ source = "tipo_histologico", codes = ["8211/3", "8201/3"], then = "Tubular / cribiforme" },
{ source = "tipo_histologico", codes = ["8050/3", "8503/3", "8504/3"], then = "Papilar" },
{ source = "tipo_histologico", codes = ["8507/3"], then = "Micropapilar" },
{ source = "tipo_histologico", codes = ["8540/3", "8541/3", "8543/3"], then = "Paget" },
{ source = "tipo_histologico", codes = ["8510/3"], then = "Medular" },
{ source = "tipo_histologico", codes = ["8530/3"], then = "Inflamatorio" },
{ source = "tipo_histologico", present = true, then = "Otros" },
]
missing = "SIN MAPEAR"
seer = { bronze = "BiopsiaMama.bx_tipo_histologico", values = { "Ductal (NST)" = "8500/3", "Lobulillar" = "8520/3", "Ductal-lobulillar mixto" = "8522/3", "Mucinoso" = "8480/3", "Tubular / cribiforme" = "8211/3", "Papilar" = "8503/3", "Micropapilar" = "8507/3", "Paget" = "8541/3", "Medular" = "8510/3", "Inflamatorio" = "8530/3", "Otros" = "8575/3" } }
[variables.Localizacion_mama]
rules = [
{ source = "localizacion", codes = ["C500"], then = "Pezón" },
{ source = "localizacion", codes = ["C501"], then = "Porción central" },
{ source = "localizacion", codes = ["C502", "C503"], then = "Cuadrantes internos" },
{ source = "localizacion", codes = ["C504", "C505"], then = "Cuadrantes externos" },
{ source = "localizacion", codes = ["C506"], then = "Cola axilar" },
{ source = "localizacion", codes = ["C508"], then = "Lesión solapada" },
{ source = "localizacion", codes = ["C509"], then = "Mama NOS" },
]
missing = "Mama NOS"
seer = { bronze = "BiopsiaMama.bx_localizacion", values = { "Pezón" = "C500", "Porción central" = "C501", "Cuadrantes internos" = "C502", "Cuadrantes externos" = "C504", "Cola axilar" = "C506", "Lesión solapada" = "C508", "Mama NOS" = "C509" } }
[variables.Lateralidad]
rules = [
{ source = "lateralidad", codes = ["DERECHA"], then = "Derecha" },
{ source = "lateralidad", codes = ["IZQUIERDA"], then = "Izquierda" },
]
missing = "Otra / no especificada"
seer = { bronze = "BiopsiaMama.bx_lateralidad", values = { "Derecha" = "DERECHA", "Izquierda" = "IZQUIERDA" } }
[variables.Metastasis]
rules = [
{ source = "metastasis", codes = ["M1"], then = "Con metástasis" },
]
missing = "Sin metástasis"
seer = { bronze = "NotaMedica.nm_metastasis", values = { "Con metástasis" = "M1", "Sin metástasis" = "M0" } }
# The tumour size in millimetres: its category and the raw column the age and tumour groupings of stage 02 read.
[variables.Tamano_tumor]
source = "tamano_tumor_mm"
rules = [
{ source = "tamano_tumor_mm", lt = 21, then = "T1 (<=20 mm)" },
{ source = "tamano_tumor_mm", ge = 21, lt = 51, then = "T2 (21-50 mm)" },
{ source = "tamano_tumor_mm", ge = 51, then = "T3+ (>50 mm)" },
]
missing = "Desconocido"
raw_column = "Tumor_Size_Over_Time_Recode_1988"
raw_format = "{:03.0f}"
raw_missing = "Unknown or size unreasonable (includes any tumor sizes 401-989)"
seer = { bronze = "BiopsiaMama.bx_tamano_tumor_mm", number = "Tumor_Size_Over_Time_Recode_1988", unknown = ["Unknown or size unreasonable (includes any tumor sizes 401-989)", "Otros (agrupado)"], microscopic = ["990 (microscopic focus)"], microscopic_mm = 1 }
[variables.Ganglios_positivos]
rules = [
{ source = "ganglios_positivos", lt = 1, then = "0" },
{ source = "ganglios_positivos", ge = 1, lt = 4, then = "1-3" },
{ source = "ganglios_positivos", ge = 4, lt = 10, then = "4-9" },
{ source = "ganglios_positivos", ge = 10, then = "10+" },
]
missing = "0"
seer = { bronze = "BiopsiaMama.bx_ganglios_positivos", number_values = { "0" = 0, "1-3" = 2, "4-9" = 6, "10+" = 12 } }
[variables.Invasion_linfovascular]
rules = [{ source = "invasion_linfovascular", codes = ["PRESENTE"], then = "Si" }]
missing = "No"
seer = { bronze = "BiopsiaMama.bx_invasion_linfovascular", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } }
[variables.Multifocalidad]
rules = [{ source = "multifocalidad", codes = ["PRESENTE"], then = "Si" }]
missing = "No"
seer = { bronze = "BiopsiaMama.bx_multifocalidad", values = { "Si" = "PRESENTE", "No" = "AUSENTE" } }
[variables.Margenes]
rules = [
{ source = "margenes", codes = ["LIBRES"], then = "Negativos" },
{ source = "margenes", codes = ["CERCANOS", "AFECTADOS"], then = "Positivos" },
{ source = "margenes", codes = ["SIN_CIRUGIA"], then = "Sin cirugia" },
]
missing = "Sin dato"
seer = { bronze = "BiopsiaMama.bx_margenes", values = { "Negativos" = "LIBRES", "Positivos" = "AFECTADOS", "Sin cirugia" = "SIN_CIRUGIA" } }
[variables.Densidad_BIRADS]
rules = [
{ source = "densidad_mamaria", codes = ["A"], then = "A" },
{ source = "densidad_mamaria", codes = ["B"], then = "B" },
{ source = "densidad_mamaria", codes = ["C"], then = "C" },
{ source = "densidad_mamaria", codes = ["D"], then = "D" },
]
missing = "B"
seer = { bronze = "Mastografia.mast_densidad", values = { "A" = "A", "B" = "B", "C" = "C", "D" = "D" } }
[variables.Masa_espiculada]
rules = [{ source = "margen_masa", codes = ["ESPICULADO"], then = "Si" }]
missing = "No"
seer = { bronze = "Mastografia.mast_margen_masa", values = { "Si" = "ESPICULADO" } }
[variables.Microcalcificaciones]
rules = [{ source = "tipo_hallazgo", codes = ["CALCIFICACIONES"], then = "Si" }]
missing = "No"
seer = { bronze = "Mastografia.mast_tipo_hallazgo", values = { "Si" = "CALCIFICACIONES" } }
[variables.BRCA]
rules = [
{ source = "brca1", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA1" },
{ source = "brca2", codes = ["PATOGENICA", "PROBABLEMENTE_PATOGENICA"], then = "BRCA2" },
]
missing = "Negativo"
seer = { bronze = "Paciente.pac_brca1", values = { "BRCA1" = "PATOGENICA", "Negativo" = "NEGATIVO" }, also = { bronze = "Paciente.pac_brca2", values = { "BRCA2" = "PATOGENICA", "Negativo" = "NEGATIVO" } } }
[variables.Estado_civil]
rules = [
{ source = "estado_civil", codes = ["SOLTERA", "CASADA", "UNION_LIBRE"], then = "Con pareja" },
{ source = "estado_civil", codes = ["SEPARADA", "DIVORCIADA", "VIUDA"], then = "Sin pareja" },
]
missing = "Desconocido"
seer = { bronze = "Paciente.pac_estado_civil", values = { "Con pareja" = "CASADA", "Sin pareja" = "DIVORCIADA" } }
[variables.Race]
column = "Race_recode_White_Black_Other"
rules = [
{ source = "raza", codes = ["BLANCA"], then = "White" },
{ source = "raza", codes = ["NEGRA"], then = "Black" },
{ source = "raza", codes = ["OTRA"], then = "Other (American Indian/AK Native, Asian/Pacific Islander)" },
]
missing = "Unknown"
seer = { bronze = "Paciente.pac_raza", values = { "White" = "BLANCA", "Black" = "NEGRA", "Other (American Indian/AK Native, Asian/Pacific Islander)" = "OTRA" } }
[variables.Tratamiento_quirurgico]
rules = [
{ source = "cirugia", codes = ["ESCISIONAL", "SEGMENTECTOMIA"], then = "Conservadora" },
{ source = "cirugia", codes = ["MASTECTOMIA_TOTAL", "MASTECTOMIA_RADICAL_MODIFICADA"], then = "Mastectomía" },
{ source = "cirugia", codes = ["SIN_CIRUGIA"], then = "Ninguna" },
{ source = "cirugia", codes = ["DESTRUCCION_LOCAL"], then = "Destrucción local" },
{ source = "cirugia", codes = ["CIRUGIA_NO_ESPECIFICADA"], then = "Cirugía NOS" },
]
missing = "Desconocido"
seer = { treatment = "cirugia", values = { "Conservadora" = "SEGMENTECTOMIA", "Mastectomía" = "MASTECTOMIA_TOTAL", "Ninguna" = "SIN_CIRUGIA", "Destrucción local" = "DESTRUCCION_LOCAL", "Cirugía NOS" = "CIRUGIA_NO_ESPECIFICADA" } }
[variables.Radioterapia]
rules = [{ source = "radioterapia", present = true, then = "Sí" }]
missing = "No o desconocido"
seer = { treatment = "radioterapia", values = { "Sí" = "ADYUVANTE" } }
[variables.Quimioterapia]
rules = [{ source = "quimioterapia", present = true, then = "Sí" }]
missing = "No o desconocido"
seer = { treatment = "quimioterapia", values = { "Sí" = "ADYUVANTE" } }
+3 -4
View File
@@ -53,12 +53,11 @@ STAGES = [
Stage("05", lambda d, s: run.run_survival(d / run.DEPURATED, d, s), (run.DEPURATED,),
("curva_supervivencia_KM_KS_LR_HBN.png", "curva_supervivencia_puntos_LR_HBN.csv",
"subgrupos_puntos_LR_HBN.csv", "subgrupos_KM_Weibull_fraccional.csv"),
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "scenarios.py", "settings.py", "run.py")),
("survival_curves.py", "survival_models.py", "fractional_weibull.py", "settings.py", "run.py")),
Stage("06", lambda d, s: run.run_risk_factors(d / run.NATURAL, d, settings=s),
(run.NATURAL, "seleccion_bootstrap.csv", "hbn_arcos.csv"),
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv",
"escenarios_factores_riesgo.csv", "escenarios_resumen.csv"),
("risk_factors.py", "risk_factor_stats.py", "scenarios.py", "settings.py", "run.py")),
("factores_riesgo.csv", "factores_riesgo_resumen_variables.csv", "asociaciones_tratamiento.csv"),
("risk_factors.py", "risk_factor_stats.py", "settings.py", "run.py")),
]
+1 -75
View File
@@ -15,7 +15,6 @@ import numpy as np
import pandas as pd
from models.cama.seer_survival import risk_factor_stats as stats
from models.cama.seer_survival import scenarios
from models.cama.seer_survival.settings import RiskFactorSettings
CRITERIA = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
@@ -206,16 +205,13 @@ def risk_variable_summary(risk_classification: Classification) -> pd.DataFrame:
def risk_treatment_associations(risk_data: pd.DataFrame, risk_follow_up: FollowUp, risk_intrinsic: list[str],
risk_treatment: list[str], risk_factors: RiskFactorSettings) -> pd.DataFrame | None:
"""The treatment variables' adjusted associations with death, descriptive and not classified (confounding by
indication); None when there are none
or none of them varies."""
indication); None when there are none."""
if not risk_treatment:
return None
variables = risk_intrinsic + risk_treatment
tr = stats.fit_odds(risk_data, risk_follow_up.death, variables)
tr["variable"] = [stats.variable_of(t, variables) for t in tr["termino"]]
tr = tr[tr["variable"].isin(risk_treatment)].copy()
if tr.empty:
return None
tr["categoria"] = [t[len(v) + 1:] for t, v in zip(tr["termino"], tr["variable"])]
tr["referencia"] = [stats.reference(risk_data, v) for v in tr["variable"]]
tr["p_ajustado_BH"] = stats.benjamini_hochberg(tr["p"])
@@ -234,73 +230,3 @@ def risk_criteria(risk_classification: Classification, risk_bootstrap_frequency:
"horizonte_meses": risk_factors.horizon, "tope_meses": risk_factors.cap_months,
"replicas_bootstrap_validas": int(risk_bootstrap_frequency.n_replicas),
"criterios_evaluados": risk_classification.criteria, "variables_tratamiento_excluidas": risk_treatment}
# ---------------------------------------------------------------- the risk factors of each clinical scenario
PCT_DEFINING = 0.95 # the category is in at least this share of the scenario: it defines it
PCT_MAJORITY = 0.50
PCT_PRESENT = 0.10
@dataclass(frozen=True, eq=False)
class ScenarioFactors:
details: pd.DataFrame # per scenario and classified category: its share of the scenario and of the cohort
summary: pd.DataFrame # per scenario: the risk factors, protectors and treatments that define it or are most of it
def _presence(share: float) -> str:
if share >= PCT_DEFINING:
return "definitoria"
if share >= PCT_MAJORITY:
return "mayoritaria"
return "presente" if share >= PCT_PRESENT else "minoritaria"
def risk_scenario_masks(risk_natural: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each clinical scenario's mask over the natural population (`scenarios.masks`), on its raw columns."""
return scenarios.masks(risk_natural.drop(columns=[c for c in ("Age_group", "Tumor_group") if c in risk_natural.columns]))
def risk_scenario_factors(risk_classification: Classification, risk_treatment_associations: pd.DataFrame | None,
risk_data: pd.DataFrame, risk_scenario_masks: dict[str, np.ndarray]) -> ScenarioFactors:
"""Which of the classified risk factors, protectors and treatment associations make up each clinical scenario: a
category that is nearly all of a scenario defines it, one that is most of it describes it."""
table = risk_classification.table
classified = table[table["clasificacion"].str.contains("robusto|sugerente")].copy()
classified["tipo"] = classified["clasificacion"].str.split().str[0]
if risk_treatment_associations is not None and len(risk_treatment_associations):
treatment = risk_treatment_associations.copy()
treatment["clasificacion"], treatment["tipo"] = "tratamiento (no se clasifica)", "tratamiento"
classified = pd.concat([classified, treatment], ignore_index=True)
details, summary = [], []
for name, mask in risk_scenario_masks.items():
size = int(mask.sum())
if size == 0:
continue
definition = scenarios.describe(scenarios.SCENARIOS[name]) if name in scenarios.SCENARIOS else ""
rows = []
for _, r in classified.iterrows():
share = float((risk_data[r["variable"]][mask] == r["categoria"]).mean())
rows.append({"escenario": name, "definicion": definition, "n_escenario": size,
"tipo": r["tipo"], "variable": r["variable"], "categoria": r["categoria"], "clasificacion": r["clasificacion"],
"OR_muerte": r["OR_muerte"], "IC95_inf": r["IC95_inf"], "IC95_sup": r["IC95_sup"], "delta_S18": r["delta_S18"],
"pct_en_escenario": share, "pct_en_cohorte": float((risk_data[r["variable"]] == r["categoria"]).mean()),
"presencia": _presence(share)})
found = pd.DataFrame(rows, columns=["escenario", "definicion", "n_escenario", "tipo", "variable", "categoria", "clasificacion",
"OR_muerte", "IC95_inf", "IC95_sup", "delta_S18", "pct_en_escenario", "pct_en_cohorte", "presencia"])
details.append(found[found["pct_en_escenario"] >= PCT_PRESENT])
def listed(kind, levels):
part = found[(found["tipo"] == kind) & (found["presencia"].isin(levels))]
return "; ".join(f"{a}={b} ({c.split()[-1] if kind != 'tratamiento' else 'asociacion'}, {p:.0%})"
for a, b, c, p in zip(part["variable"], part["categoria"], part["clasificacion"], part["pct_en_escenario"]))
row = {"escenario": name, "definicion": definition, "n_escenario": size}
for kind in ("riesgo", "protector", "tratamiento"):
row[f"{kind}_definitorios"] = listed(kind, ["definitoria"])
row[f"{kind}_mayoritarios"] = listed(kind, ["mayoritaria"])
row["n_factores_riesgo_incluidos"] = int(((found["tipo"] == "riesgo") & found["presencia"].isin(["definitoria", "mayoritaria"])).sum())
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
summary.append(row)
return ScenarioFactors(pd.concat(details, ignore_index=True).round(4) if details else pd.DataFrame(), pd.DataFrame(summary))
+4 -6
View File
@@ -11,7 +11,7 @@ from pathlib import Path
import numpy as np
from hamilton import driver
from models.cama.seer_survival import (balancing, bootstrap, categorization, depuration, modeling, resampling,
from models.cama.seer_survival import (variables, balancing, bootstrap, categorization, depuration, modeling, resampling,
risk_factors, survival_curves)
from models.cama.seer_survival.settings import Settings, load
@@ -166,7 +166,7 @@ def run_survival(depurated_csv: str, output_dir: str, settings: Settings | None
dr = driver.Builder().with_modules(survival_curves).build()
r = dr.execute(["sv_table", "sv_main_figure", "sv_weights_cohort", "sv_sub_figures", "sv_sub_fits_table",
"sv_sub_points_table", "sv_sub_weights_table", "sv_age_test"],
inputs={"depurated_csv": str(depurated_csv), "survival": s})
inputs={"depurated_csv": str(depurated_csv), "survival": s, "dictionary": variables.load()})
r["sv_table"].to_csv(out / f"curva_supervivencia_puntos_LR_HBN{suffix}.csv", index=False)
r["sv_main_figure"].savefig(out / f"curva_supervivencia_KM_KS_LR_HBN{suffix}.png", dpi=200)
if r["sv_weights_cohort"] is not None:
@@ -193,15 +193,13 @@ def run_risk_factors(natural_csv: str, output_dir: str, bootstrap_selection_csv:
inputs = {"natural_csv": str(natural_csv),
"bootstrap_selection_csv": str(bootstrap_selection_csv or out / "seleccion_bootstrap.csv"),
"hbn_arcs_csv": str(hbn_arcs_csv or out / "hbn_arcos.csv"), "risk_factors": settings.risk_factors}
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria",
"risk_scenario_factors"], inputs=inputs)
r = dr.execute(["risk_factors_table", "risk_variable_summary", "risk_treatment_associations", "risk_criteria"],
inputs=inputs)
r["risk_factors_table"].to_csv(out / "factores_riesgo.csv", index=False)
r["risk_variable_summary"].to_csv(out / "factores_riesgo_resumen_variables.csv")
if r["risk_treatment_associations"] is not None:
r["risk_treatment_associations"].to_csv(out / "asociaciones_tratamiento.csv", index=False)
_dump(out / "factores_riesgo_criterios.json", r["risk_criteria"])
r["risk_scenario_factors"].details.to_csv(out / "escenarios_factores_riesgo.csv", index=False)
r["risk_scenario_factors"].summary.to_csv(out / "escenarios_resumen.csv", index=False)
return r
-116
View File
@@ -1,116 +0,0 @@
"""The clinical scenarios of the survival analysis: the subgroups whose curves stage 5 draws and whose risk factors stage 6
lists. Each is a set of conditions over the cohort's raw columns (age, stage, molecular subtype, surgery); the columns are
found by keyword, so a cohort without one of them has no patient in the scenarios that need it. Ported from
`escenarios_clinicos.py`.
"""
import re
import numpy as np
import pandas as pd
def find_col(df: pd.DataFrame, keywords) -> str | None:
for col in df.columns:
d = col.lower().replace("_", " ")
if any(k in d for k in keywords):
return col
return None
def _age(v) -> float:
m = re.search(r"\d+", str(v))
return float(m.group()) if m else np.nan
def _stage(v) -> float:
u = str(v).upper().replace("STAGE", "").strip()
if u.startswith("0") or u == "IS":
return 0
for prefix, value in [("IV", 4), ("4", 4), ("III", 3), ("3", 3), ("II", 2), ("2", 2), ("I", 1), ("1", 1)]:
if u.startswith(prefix):
return value
return np.nan
def _age_column(df: pd.DataFrame) -> str | None:
candidates = [c for c in df.columns if re.match(r"^age(\b|$)", c.lower().replace("_", " ").strip())]
if not candidates:
return None
return sorted(candidates, key=lambda c: (0 if "recode" in c.lower() else 1 if c.lower() == "age" else 2))[0]
def values_by_axis(df: pd.DataFrame) -> dict[str, pd.Series]:
col_stage = "Estadio_cat" if "Estadio_cat" in df.columns else find_col(df, ["estadio", "stage"])
col_subtype = "Subtipo_molecular_cat" if "Subtipo_molecular_cat" in df.columns else find_col(df, ["subtipo", "subtype"])
col_surgery = "Tratamiento_quirurgico_cat" if "Tratamiento_quirurgico_cat" in df.columns else find_col(df, ["quirurg", "surg"])
col_age = _age_column(df)
n = len(df)
return {
"edad": df[col_age].map(_age).astype(float) if col_age else pd.Series(np.nan, index=df.index),
"estadio": df[col_stage].map(_stage) if col_stage else pd.Series(np.nan, index=df.index),
"subtipo": df[col_subtype].astype(str) if col_subtype else pd.Series([""] * n, index=df.index),
"cirugia": df[col_surgery].astype(str).str.lower() if col_surgery else pd.Series([""] * n, index=df.index),
}
AGE_BELOW = lambda x: ("edad", "<", x)
AGE_FROM = lambda x: ("edad", ">=", x)
STAGE_0_II = ("estadio", "en", [0, 1, 2])
STAGE_III_IV = ("estadio", "en", [3, 4])
HER2_POS = ("subtipo", "contiene", "HER2+")
HER2_NEG = ("subtipo", "contiene", "HER2-")
TRIPLE_NEG = ("subtipo", "contiene", "HR-/HER2-")
CONSERVATIVE = ("cirugia", "contiene", "conserv")
SCENARIOS = {
"HER2+ · ≥60 años · estadio III–IV (Alto)": [HER2_POS, AGE_FROM(60), STAGE_III_IV],
"HER2+ · <60 años · estadio 0–II (Bajo)": [HER2_POS, AGE_BELOW(60), STAGE_0_II],
"Estadio IV": [("estadio", "en", [4])],
"Estadio I": [("estadio", "en", [1])],
"≥ 75 años": [AGE_FROM(75)],
"< 45 años": [AGE_BELOW(45)],
"Jóvenes (<45) · HER2− · estadio 0–II · cirugía conservadora": [AGE_BELOW(45), HER2_NEG, STAGE_0_II, CONSERVATIVE],
"HER2− · estadio 0–II · cirugía conservadora": [HER2_NEG, STAGE_0_II, CONSERVATIVE],
"HER2+ · estadio 0–II · cirugía conservadora": [HER2_POS, STAGE_0_II, CONSERVATIVE],
"Jóvenes (<45) · estadio 0–II": [AGE_BELOW(45), STAGE_0_II],
"Jóvenes (<45) · HER2−": [AGE_BELOW(45), HER2_NEG],
"Triple negativo (HR−/HER2−) · estadio 0–II": [TRIPLE_NEG, STAGE_0_II],
"≥ 65 años · HER2− · estadio 0–II · cirugía conservadora": [AGE_FROM(65), HER2_NEG, STAGE_0_II, CONSERVATIVE],
}
STAGE_LABEL = {0: "0", 1: "I", 2: "II", 3: "III", 4: "IV"}
def describe(conditions) -> str:
parts = []
for axis, op, value in conditions:
if axis == "edad":
parts.append(f"edad {op} {value:g}")
elif axis == "estadio":
parts.append("estadio " + "/".join(STAGE_LABEL[v] for v in value))
elif axis == "subtipo":
parts.append(f"subtipo {value}")
elif axis == "cirugia":
parts.append("cirugía conservadora")
return "; ".join(parts)
def masks(df: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each scenario's mask over the cohort: every condition must hold."""
values = values_by_axis(df)
out = {}
for name, conditions in SCENARIOS.items():
mask = pd.Series(True, index=df.index)
for axis, op, value in conditions:
s = values[axis]
if op == "<":
mask &= (s < value).fillna(False)
elif op == ">=":
mask &= (s >= value).fillna(False)
elif op == "en":
mask &= s.isin(value)
else:
mask &= s.str.contains(value, regex=False)
out[name] = mask.values.astype(bool)
return out
+138
View File
@@ -0,0 +1,138 @@
"""SEER's recoded file as CaMa import files: one CSV per bronze entity, named by the fields the import schemas take, to be
uploaded through the platform's import like any other source.
python -m models.cama.seer_survival.seer_import RECODED.csv OUT_DIR
What goes where is the dictionary's (`[variables.*.seer]` of `model.toml`): each SEER category is stored as the catalog
value the dictionary names, and read back as the same category. SEER records no calendar dates: the diagnosis is a fixed
day of its year, the birth the middle of the age band, the death (or, for the living, the last contact) the diagnosis
plus the survival months; the months stay exact.
"""
import argparse
from datetime import timedelta
from pathlib import Path
import pandas as pd
from models.cama.seer_survival import variables
ENTITIES = {"Paciente": "pacientes", "BiopsiaMama": "biopsias", "Mastografia": "mastografias",
"NotaMedica": "notas", "TratamientoMama": "tratamientos"}
FEMALE = "Femenino"
def _age_years(label: str, index: dict) -> float | None:
"""The middle of an age band ("60-64 years" -> 62.5); the open band's own value; None without a number."""
head = str(label).split(" ")[0]
if head.endswith("+"):
return float(index["seer_age_open_value"])
low, _, high = head.partition("-")
if not (low.isdigit() and high.isdigit()):
return None
return (int(low) + int(high) + 1) / 2
def _number(text, spec: dict) -> float | None:
text = str(text)
if text in spec["microscopic"]:
return float(spec["microscopic_mm"])
return float(text) if text.replace(".", "", 1).isdigit() else None
def convert(recoded: pd.DataFrame, dictionary: dict) -> dict[str, pd.DataFrame]:
index = dictionary["index"]
ages = recoded[index["age_column"]].map(lambda v: _age_years(v, index))
frame = recoded[ages.notna()].copy()
ages = ages[ages.notna()]
months = pd.to_numeric(frame[index["months_column"]]).astype(int)
dead = frame[index["vital_column"]].eq(index["dead"])
day = pd.to_timedelta(months * index["days_per_month"], unit="D").dt.round("D")
diagnosis = frame[index["year_column"]].astype(int).map(lambda y: pd.Timestamp(variables.diagnosis_date(y, dictionary)))
birth = diagnosis - pd.to_timedelta((ages * 365.25).round(), unit="D")
ident = frame[index["id_column"]].astype(str)
date = lambda s: s.dt.strftime("%Y-%m-%d")
tables = {name: pd.DataFrame({"pac_id_hospital": ident}) for name in ENTITIES}
tables["Paciente"]["pac_sexo"] = FEMALE
tables["Paciente"]["pac_fecha_nacimiento"] = date(birth)
tables["Paciente"]["pac_fecha_defuncion"] = date(diagnosis + day).where(dead)
tables["BiopsiaMama"]["bx_fecha_solicitud"] = date(diagnosis)
tables["BiopsiaMama"]["bx_fecha_reporte"] = date(diagnosis)
tables["Mastografia"]["mast_fecha_toma"] = date(diagnosis)
tables["Mastografia"]["mast_fecha_reporte"] = date(diagnosis)
for name in variables.variable_names(dictionary):
spec = dictionary[name]
seer = spec.get("seer")
if not seer or "treatment" in seer:
continue
origin = seer.get("from", name)
category = frame[variables.column_of(origin, dictionary[origin])]
for target in (seer, seer.get("also")):
if not target:
continue
entity, column = target["bronze"].split(".")
if "number" in seer:
tables[entity][column] = frame[seer["number"]].map(lambda v: _number(v, seer))
elif "number_values" in seer:
tables[entity][column] = category.map(seer["number_values"])
else:
tables[entity][column] = category.map(target["values"])
# A biopsy is invasive unless the stage says in situ.
stage = frame[variables.column_of("Estadio", dictionary["Estadio"])]
in_situ = [k for k, v in dictionary["Estadio"]["seer"]["values"].items() if v == "E0"]
tables["BiopsiaMama"]["bx_grado_histologico"] = stage.isin(in_situ).map(
{True: "CARCINOMA_IN_SITU", False: "CARCINOMA_INVASOR"})
# A receptor status the subtype contradicts follows the subtype (the model reads the subtype from the receptors).
subtype = frame[variables.column_of("Subtipo_molecular", dictionary["Subtipo_molecular"])]
positive_hr = subtype.str.startswith("HR+")
negative_hr = subtype.str.startswith("HR-")
bx = tables["BiopsiaMama"]
no_positive = ~((bx["bx_receptor_estrogeno"] == "POSITIVO") | (bx["bx_receptor_progesterona"] == "POSITIVO"))
bx.loc[positive_hr & no_positive, "bx_receptor_estrogeno"] = "POSITIVO"
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
bx.loc[negative_hr & bx[column].isna(), column] = "NEGATIVO"
for column in ("bx_receptor_estrogeno", "bx_receptor_progesterona"):
bx.loc[negative_hr & (bx[column] == "POSITIVO"), column] = "NEGATIVO"
notes = tables["NotaMedica"]
notes["nm_id_hospital"] = ident + "-dx"
notes["nm_fecha"] = date(diagnosis)
notes["nm_tipo_nota"] = "CONSULTA"
follow_up = pd.DataFrame({"pac_id_hospital": ident, "nm_id_hospital": ident + "-seg", "nm_fecha": date(diagnosis + day),
"nm_tipo_nota": "CONSULTA"})[~dead.to_numpy()]
tables["NotaMedica"] = pd.concat([notes, follow_up], ignore_index=True)
treatments = []
for name in variables.variable_names(dictionary):
seer = dictionary[name].get("seer", {})
if "treatment" not in seer:
continue
category = frame[variables.column_of(name, dictionary[name])]
values = category.map(seer["values"])
rows = pd.DataFrame({"pac_id_hospital": ident, "trat_tipo": seer["treatment"], "trat_fecha": date(diagnosis),
"trat_detalle": values})[values.notna()]
if seer["treatment"] == "cirugia":
rows["trat_lateralidad"] = bx["bx_lateralidad"].reindex(rows.index)
treatments.append(rows)
tables["TratamientoMama"] = pd.concat(treatments, ignore_index=True)
return tables
def main(argv=None) -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("recoded")
ap.add_argument("out_dir")
args = ap.parse_args(argv)
recoded = pd.read_csv(args.recoded, dtype=str, low_memory=False)
out = Path(args.out_dir)
out.mkdir(parents=True, exist_ok=True)
for entity, table in convert(recoded, variables.load()).items():
table.to_csv(out / f"{ENTITIES[entity]}.csv", index=False)
if __name__ == "__main__":
main()
+225
View File
@@ -0,0 +1,225 @@
"""The registered CaMa survival model: the dictionary, the covariates the depuration kept, and the interval models of the
survival stage (LR and HBN per interval, the weights that combine them, and the replicas that give their intervals), fitted
on a cohort and kept. It scores any cohort's members from their timelines, and draws a clinical scenario's figure
(`figure_record`): Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the LR / HBN / combined
survival at the horizons with a bootstrap interval.
The fitted state is plain arrays and dictionaries; `rehydrate` puts a saved model's state into the current class, so a
version trained earlier is scored by today's code.
"""
import time
from dataclasses import dataclass, field
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import survival_curves as sc
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival import variables
from models.cama.seer_survival.settings import SurvivalSettings
from models.steps import indexing
NO_CATEGORY = "NA"
def figure_settings() -> dict:
"""`[figure]` of `model.toml`: what `figure_record` takes besides the scenario."""
import tomllib
return tomllib.loads(variables.TOML.read_text(encoding="utf-8"))["figure"]
@dataclass(frozen=True, eq=False)
class Design:
"""The covariates' coding the fits were made with: each covariate's categories sorted (the dummies drop the first) and in
order of first appearance (the HBN's integer codes), so any frame is coded as the training cohort was."""
covariates: list[str]
sorted_categories: dict[str, list[str]]
appearance: dict[str, list[str]]
@classmethod
def of(cls, frame: sc.SurvivalFrame) -> "Design":
df = frame.df
return cls(list(frame.covariates), {c: sorted(df[c].unique()) for c in frame.covariates},
{c: list(pd.factorize(df[c])[1]) for c in frame.covariates})
@property
def levels(self) -> np.ndarray:
return np.array([len(self.appearance[c]) for c in self.covariates])
def encode(self, df: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
"""(dummies, integer codes); a category the training cohort never had is coded as its reference."""
dummies, codes = [], []
for c in self.covariates:
values = df[c].fillna(NO_CATEGORY).astype(str).str.strip()
dummies += [(values == k).to_numpy(np.float32) for k in self.sorted_categories[c][1:]]
position = {k: i for i, k in enumerate(self.appearance[c])}
codes.append(values.map(position).fillna(0).astype(int).to_numpy())
return np.column_stack(dummies), np.column_stack(codes)
@dataclass
class Fit:
"""What `fit` leaves: the point fits, the bootstrap replicas' fits, the weights of the combination (the cohort's and each
configured scenario's) and what the cohort was."""
point: list
replicas: list
weights: np.ndarray
scenario_weights: dict
design: Design
members: int
deaths: int
calibration: list = field(default_factory=list)
class SeerSurvivalModel(BaseEstimator):
"""Scores a cohort's long frame (`predict_proba`: per member, in `pac_id` order, the risk of dying by each horizon)."""
def __init__(self, dictionary=None, survival=None, index=None, fit_state=None, kept=None, horizons_years=None):
self.dictionary = dictionary
self.survival = survival
self.index = index
self.fit_state = fit_state
self.kept = kept
self.horizons_years = horizons_years
@classmethod
def rehydrate(cls, saved) -> "SeerSurvivalModel":
"""The current class holding a saved model's state."""
model = cls.__new__(cls)
model.__dict__.update(saved.__dict__)
return model
# ------------------------------------------------------------------ from the timeline to the design
def recode(self, cohort: pd.DataFrame, *, indexed: bool = False) -> pd.DataFrame:
"""One row per member in the columns the dictionary makes; the cohort is re-indexed at the first invasive biopsy
unless it already is."""
if not indexed and self.index:
cohort = indexing.cohort(cohort, {}, self.index)
return variables.recode(cohort, self.dictionary)
def frame(self, recoded: pd.DataFrame) -> sc.SurvivalFrame:
"""The recoded members as the survival stage reads them, restricted to the covariates the depuration kept."""
columns = [c for c in recoded.columns if c in self.kept or not c.endswith("_cat")]
frame = sc.survival_frame(recoded[columns], self.survival)
covariates = [c for c in self.fit_state.design.covariates]
for c in covariates:
if c not in frame.df.columns:
frame.df[c] = NO_CATEGORY
return sc.SurvivalFrame(frame.df, covariates, frame.age_col, frame.numeric_cols)
def _survival(self, frame: sc.SurvivalFrame, weights=None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
design = self.fit_state.design
X_dum, X_int = design.encode(frame.df)
P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels)
W = self.fit_state.weights if weights is None else weights
return np.cumprod(P_lr, axis=1), np.cumprod(P_hb, axis=1), sm.mix(P_lr, P_hb, W)
def predict_proba(self, cohort: pd.DataFrame) -> np.ndarray:
recoded = self.recode(cohort)
frame = self.frame(recoded)
combined = self._survival(frame)[2]
order = np.argsort(recoded[self.dictionary["index"]["id_column"]].to_numpy())
return 1 - combined[order]
def predict(self, cohort: pd.DataFrame) -> np.ndarray:
return self.predict_proba(cohort)
# ------------------------------------------------------------------ a scenario's figure
def scenario_names(self) -> list[str]:
return [spec["name"] for spec in self.survival.subgroups]
def scenario_masks(self, frame: sc.SurvivalFrame) -> dict[str, np.ndarray]:
return sc.sv_masks(frame, self.survival, self.dictionary)
def figure_record(self, frame: sc.SurvivalFrame, scenario: str, *, ks_max_seconds: float = 30.0, n_boot: int | None = None,
min_members: int = 30, min_deaths: int = 5, extrapolate_months: int | None = None) -> dict:
"""The figure of one scenario over the members of `frame`; `None` for the parts a scenario with too few members or
deaths cannot support. The interval of each point is the percentile of the replicas' mean survival over members
resampled with replacement."""
s = self.survival
masks = self.scenario_masks(frame)
mask = masks[scenario]
df = frame.df[mask]
deaths = int(df["evento"].sum())
record = {"scenario": scenario, "members": int(len(df)), "deaths": deaths, "horizons": list(s.horizons), "points": []}
if len(df) < min_members or deaths < min_deaths:
return {**record, "drawable": False}
months, events = df["meses_int"].values, df["evento"].values
horizon = max(s.months_max, max(s.horizons))
S, lo, hi = fw.km_curva(months, events, horizon)
d, c = fw.tabla_eventos(months, events)
weibull = fw.ajustar_weibull(d, c)
fractional = fw.ajustar_ks(d, c, k_fijo=sc._fixed_k(weibull, s), lam_ref=weibull["lam"], max_seg=ks_max_seconds)
reach = extrapolate_months or s.months_extrapolated
grid = np.arange(0, reach + 1, dtype=float)
record.update(drawable=True, months=list(range(horizon + 1)), km={"S": S.tolist(), "lo": lo.tolist(), "hi": hi.tolist()},
curve_months=grid.tolist(),
weibull={"k": float(weibull["k"]), "S": np.asarray(weibull["S"](grid)).tolist()},
fractional={"k": float(fractional["k"]), "alpha": float(fractional["alpha"]), "beta": float(fractional["beta"]),
"S": np.asarray(fractional["S"](grid)).tolist()})
weights = self.fit_state.scenario_weights.get(scenario, self.fit_state.weights)
design = self.fit_state.design
X_dum, X_int = design.encode(df)
rng = np.random.default_rng(s.seed + 1)
replicas = self.fit_state.replicas[: n_boot if n_boot is not None else len(self.fit_state.replicas)]
started, boots = time.monotonic(), []
P_lr, P_hb = sm.apply_intervals(self.fit_state.point, X_dum, X_int, design.levels)
point = [np.cumprod(P_lr, axis=1).mean(0), np.cumprod(P_hb, axis=1).mean(0), sm.mix(P_lr, P_hb, weights).mean(0)]
for fits in replicas:
pick = rng.integers(0, len(df), len(df))
Pl, Ph = sm.apply_intervals(fits, X_dum[pick], X_int[pick], design.levels)
boots.append(np.concatenate([np.cumprod(Pl, axis=1).mean(0), np.cumprod(Ph, axis=1).mean(0),
sm.mix(Pl, Ph, weights).mean(0)]))
ic = np.percentile(np.array(boots), [2.5, 97.5], axis=0) if boots else np.full((2, 3 * len(s.horizons)), np.nan)
for j, name in enumerate(("LR", "HBN", "COMB")):
for i, h in enumerate(s.horizons):
k = j * len(s.horizons) + i
record["points"].append({"model": name, "months": int(h), "S": float(point[j][i]),
"low": float(ic[0, k]), "high": float(ic[1, k])})
record["seconds"] = round(time.monotonic() - started, 2)
return record
def fit(recoded: pd.DataFrame, depurated: pd.DataFrame, dictionary: dict, survival: SurvivalSettings, index: dict | None,
n_boot: int | None = None, on_progress=None) -> SeerSurvivalModel:
"""The model fitted on `recoded` members (all the dictionary's columns) whose covariates are those of `depurated`."""
s = survival
kept = [c for c in depurated.columns if c.endswith("_cat")]
frame = sc.survival_frame(depurated, s)
cohort = sc.sv_cohort(frame, s)
N = len(cohort.months)
everyone = np.arange(N)
oof_lr, oof_hb = sm.out_of_fold(cohort, s, N)
weights = sm.stacking_weights(cohort, s, np.ones(N, bool), oof_lr, oof_hb)["w_LR"].values
point = sm.fit_intervals(cohort, s, everyone)
reference = [f.parents for f in point] if s.hbn_parents == "fijos" else None
masks = sc.sv_masks(frame, s, dictionary)
scenario_weights = {name: sm.stacking_weights(cohort, s, mask, oof_lr, oof_hb)["w_LR"].values for name, mask in masks.items()}
rng = np.random.default_rng(s.seed)
replicas = []
for r in range(s.n_boot if n_boot is None else n_boot):
replicas.append(sm.fit_intervals(cohort, s, rng.integers(0, N, N), reference))
if on_progress:
on_progress(r + 1)
out_of_sample = sm.mix(oof_lr, oof_hb, weights)
horizon = len(s.horizons) - 1
deciles = pd.qcut(pd.Series(out_of_sample[:, horizon]).rank(method="first"), 10, labels=False)
calibration = []
for q in range(10):
pick = (deciles == q).to_numpy()
curve, _, _ = fw.km_curva(cohort.months[pick], cohort.event[pick], int(s.horizons[-1]))
calibration.append({"decile": q + 1, "members": int(pick.sum()),
"predicted": {str(h): float(out_of_sample[pick, i].mean()) for i, h in enumerate(s.horizons)},
"observed": {str(h): float(curve[int(h)]) for h in s.horizons}})
state = Fit(point, replicas, weights, scenario_weights, Design.of(frame), N, int(frame.df["evento"].sum()), calibration)
horizons = [h / 12 for h in s.horizons]
return SeerSurvivalModel(dictionary, s, index, state, kept, horizons)
+3 -1
View File
@@ -148,6 +148,7 @@ class SurvivalSettings:
ks_sub_max_seconds: int
xlim_sub: tuple[float, ...]
ylim_sub: dict
subgroups: tuple[dict, ...]
@property
def file_suffix(self) -> str:
@@ -211,5 +212,6 @@ def load(path: Path = TOML) -> Settings:
categorization=_group(CategorizationSettings, raw["categorization"]),
bootstrap=_group(BootstrapSettings, raw["bootstrap"]),
modeling=_group(ModelingSettings, raw["modeling"]),
survival=_group(SurvivalSettings, raw["survival"]),
survival=_group(SurvivalSettings, {**raw["survival"],
"subgroups": tuple(raw["survival"]["subgroups"])}),
risk_factors=_group(RiskFactorSettings, raw["risk_factors"]))
+28 -5
View File
@@ -16,8 +16,8 @@ from matplotlib.figure import Figure
from sklearn.linear_model import LogisticRegression
from models.cama.seer_survival import fractional_weibull as fw
from models.cama.seer_survival import scenarios
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival import variables
from models.cama.seer_survival.settings import SurvivalSettings
STYLE = {"LR": ("#1f77b4", "o", "LR"), "HBN": ("#2a9d8f", "s", "HBN"), "COMB": ("#6a3d9a", "D", "LR + HBN combinado")}
@@ -82,10 +82,14 @@ def _age_midpoint(v):
# ---------------------------------------------------------------- the cohort
def sv_frame(depurated_csv: str, survival: SurvivalSettings) -> SurvivalFrame:
return survival_frame(pd.read_csv(depurated_csv, dtype=str), survival)
def survival_frame(df: pd.DataFrame, survival: SurvivalSettings) -> SurvivalFrame:
"""The cohort with follow-up truncated at `cap_months` (later deaths count as alive), its covariates and, when no
categorical age column exists, the grouped age `Edad_cat`."""
s = survival
df = pd.read_csv(depurated_csv, dtype=str)
df = df.copy()
col_months, col_vital = _find_col(df, ["survival months"]), _find_col(df, ["vital status"])
assert col_months and col_vital, "No se encontraron las columnas de meses de seguimiento y estado vital en el CSV."
df["meses"] = pd.to_numeric(df[col_months], errors="coerce")
@@ -323,9 +327,28 @@ def sv_main_figure(sv_frame: SurvivalFrame, sv_km: KaplanMeier, sv_adjusted: np.
# ---------------------------------------------------------------- subgroups
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings) -> dict[str, np.ndarray]:
"""Each clinical scenario's mask over the cohort (`scenarios.masks`): every condition of the scenario must hold."""
return scenarios.masks(sv_frame.df)
def sv_masks(sv_frame: SurvivalFrame, survival: SurvivalSettings, dictionary: dict) -> dict[str, np.ndarray]:
"""Each scenario's mask over the cohort: every condition of its spec must hold."""
df = sv_frame.df
masks = {}
for spec in survival.subgroups:
mask = np.ones(len(df), bool)
for condition in spec["conditions"]:
name = condition["variable"]
if name == "Edad":
values = df["_edad"].astype(float)
else:
values = df[variables.column_of(name, dictionary[name])].astype(str)
if "contains" in condition:
mask &= values.str.contains(condition["contains"], regex=False).to_numpy()
if "in" in condition:
mask &= values.isin(condition["in"]).to_numpy()
if "ge" in condition:
mask &= (values >= condition["ge"]).to_numpy()
if "lt" in condition:
mask &= (values < condition["lt"]).to_numpy()
masks[spec["name"]] = mask
return masks
def sv_sub_weights(sv_cohort: sm.Cohort, sv_masks: dict, sv_oof: Oof | None,
+51 -47
View File
@@ -137,57 +137,22 @@ def predict_horizon(c: Cohort, s: SurvivalSettings, idx, h, mode, parents=None):
return lr.predict_proba(c.X_dum[idx])[:, 1], predict_hbn(mod, c.X_int[idx], c.levels), list(mod[0])
class ConstantProbability:
"""What stands in for a logistic regression in an interval where everyone at risk had the same outcome (nobody
died in it, or everybody did): the same probability for every patient, with `predict_proba`'s two columns."""
def __init__(self, p: float):
self.p = float(p)
def predict_proba(self, X):
return np.column_stack([np.full(len(X), 1 - self.p), np.full(len(X), self.p)])
def _fit_lr(X, y, w):
"""The unpenalized LR of an interval, or a constant when there is nothing to tell apart."""
if len(y) == 0:
return ConstantProbability(1.0)
if y.min() == y.max():
return ConstantProbability(float(y[0]))
return LogisticRegression(C=1e6, max_iter=500).fit(X, y, sample_weight=w)
def fit_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None):
"""Per interval, `(LR, HBN)` fitted on the patients of `idx` alive at its start: what a model keeps to score
patients it never saw (`predict_intervals`)."""
m, e = c.months[idx], c.event[idx]
fitted = []
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
sel = np.where(m >= a)[0] # alive at the start of the interval
if len(sel) == 0:
fitted.append((ConstantProbability(1.0), ([], np.array([1.0]))))
continue
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = survives the interval
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censored within the interval: half a risk
lr = _fit_lr(c.X_dum[idx][sel], y, w)
mod = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
fitted.append((lr, mod))
return fitted
def predict_intervals(fitted, X_dum, X_int, levels):
"""Per interval, the probability of surviving it by the LR and by the HBN, for the rows of `X_dum` and `X_int`, and
the HBN's parents of each interval."""
P_lr = [lr.predict_proba(X_dum)[:, 1] for lr, _ in fitted]
P_hb = [predict_hbn(mod, X_int, levels) for _, mod in fitted]
return np.column_stack(P_lr), np.column_stack(P_hb), [list(mod[0]) for _, mod in fitted]
def interval_predictions(c: Cohort, s: SurvivalSettings, idx, parents=None, test=None):
"""Per interval, the probability of surviving it for the `test` patients (default `idx`) by LR and HBN, fitted on the
patients of `idx` alive at its start; and the HBN's parents of each interval."""
test = idx if test is None else test
return predict_intervals(fit_intervals(c, s, idx, parents), c.X_dum[test], c.X_int[test], c.levels)
m, e = c.months[idx], c.event[idx]
P_lr, P_hb, pads = [], [], []
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
sel = np.where(m >= a)[0] # alive at the start of the interval
y = np.where(e[sel] & (m[sel] < b), 0, 1) # 1 = survives the interval
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0) # censored within the interval: half a risk
lr = LogisticRegression(C=1e6, max_iter=500).fit(c.X_dum[idx][sel], y, sample_weight=w)
mod = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
P_lr.append(lr.predict_proba(c.X_dum[test])[:, 1])
P_hb.append(predict_hbn(mod, c.X_int[test], c.levels))
pads.append(list(mod[0]))
return np.column_stack(P_lr), np.column_stack(P_hb), pads
def patient_survival(c: Cohort, s: SurvivalSettings, idx, mode, parents=None):
@@ -279,3 +244,42 @@ def adjusted_curve(c: Cohort, idx, T: int, step: int) -> np.ndarray:
S_b.append(S_i.mean())
S_b = np.minimum.accumulate(np.array(S_b))
return np.exp(np.interp(np.arange(T + 1), borders, np.log(np.maximum(S_b, 1e-12))))
# ---------------------------------------------------------------- fitted models that can be kept and applied later
@dataclass(frozen=True, eq=False)
class IntervalFit:
"""One interval's fitted LR (coefficients, intercept) and HBN (parents and the table of P(survives | parents))."""
coef: np.ndarray
intercept: float
parents: list[int]
cpt: np.ndarray
def fit_intervals(c: Cohort, s: SurvivalSettings, idx, parents=None) -> list[IntervalFit]:
"""The per-interval LR and HBN `interval_predictions` fits on the patients of `idx`, kept instead of applied."""
m, e = c.months[idx], c.event[idx]
fits = []
for i, (a, b) in enumerate(zip(c.borders[:-1], c.borders[1:])):
sel = np.where(m >= a)[0]
y = np.where(e[sel] & (m[sel] < b), 0, 1)
w = np.where((~e[sel]) & (m[sel] < b), 0.5, 1.0)
lr = LogisticRegression(C=1e6, max_iter=500).fit(c.X_dum[idx][sel], y, sample_weight=w)
chosen, cpt = fit_hbn(c.X_int[idx][sel], c.levels, y, w, s, c.fixed_parents, None if parents is None else parents[i])
fits.append(IntervalFit(lr.coef_[0].copy(), float(lr.intercept_[0]), list(chosen), cpt))
return fits
def apply_intervals(fits: list[IntervalFit], X_dum: np.ndarray, X_int: np.ndarray, levels) -> tuple[np.ndarray, np.ndarray]:
"""(LR, HBN): each patient's probability of surviving each interval."""
P_lr = np.column_stack([1 / (1 + np.exp(-(X_dum @ f.coef + f.intercept))) for f in fits])
P_hb = np.column_stack([predict_hbn((f.parents, f.cpt), X_int, levels) for f in fits])
return P_lr, P_hb
def mix(P_lr: np.ndarray, P_hb: np.ndarray, weights) -> np.ndarray:
"""The combined survival at each horizon: each interval's LR and HBN probabilities mixed by `weights`, accumulated."""
W = np.asarray(weights)[None, :]
return np.cumprod(W * P_lr + (1 - W) * P_hb, axis=1)
+167
View File
@@ -0,0 +1,167 @@
"""The variable dictionary (`[variables]` of `model.toml`) applied to a cohort's events: one row per patient with the
columns the six stages read (the `_cat` columns, the age band, the tumour size, the diagnosis year, the follow-up and the
vital status). Nothing about a variable is written here: its rules, categories and the columns it makes are the
dictionary's.
A cohort is the long frame of `COHORT_SCHEMA`: one row per member and event, with the member's `fecha_indice`. A
variable reads the latest event of each `source` (`tipo`) up to `window_days_after_index` after the index; its rules
are tried in order and the first that holds gives the category, `missing` when none does.
"""
import tomllib
from datetime import date, timedelta
from pathlib import Path
import numpy as np
import pandas as pd
TOML = Path(__file__).with_name("model.toml")
def load(path: Path = TOML) -> dict:
return tomllib.loads(Path(path).read_text(encoding="utf-8"))["variables"]
def variable_names(dictionary: dict) -> list[str]:
return [n for n, v in dictionary.items() if isinstance(v, dict) and "rules" in v]
def output_columns(dictionary: dict) -> list[str]:
"""The columns the dictionary makes, in its order: every variable that is not internal, the tumour's raw size, the
age band and the follow-up columns."""
index = dictionary["index"]
columns = [index["id_column"], index["year_column"], index["age_column"]]
for name in variable_names(dictionary):
spec = dictionary[name]
if spec.get("internal"):
continue
columns.append(column_of(name, spec))
if "raw_column" in spec:
columns.append(spec["raw_column"])
return columns + [index["months_column"], index["vital_column"]]
def column_of(name: str, spec: dict) -> str:
return spec.get("column", f"{name}_cat")
def _latest(events: pd.DataFrame, source: str, numeric: bool) -> pd.Series:
"""Each patient's latest event of this kind (by date, then source id): its value, indexed by `pac_id`."""
rows = events[events["tipo"] == source]
if numeric:
rows = rows[rows["valor_numerico"].notna()]
column = "valor_numerico"
else:
rows = rows[rows["valor_codigo"].notna()]
column = "valor_codigo"
rows = rows.sort_values(["fecha", "fuente_id"], kind="stable")
return rows.groupby("pac_id")[column].last()
def _present(events: pd.DataFrame, source: str) -> pd.Series:
return pd.Series(True, index=events.loc[events["tipo"] == source, "pac_id"].unique())
class Reader:
"""Evaluates conditions over the patients' events, caching each source's per-patient value."""
def __init__(self, events: pd.DataFrame, patients: pd.Index, made: dict[str, pd.Series]):
self.events, self.patients, self.made = events, patients, made
self._cache: dict[tuple, pd.Series] = {}
def value(self, source: str, numeric: bool) -> pd.Series:
key = (source, numeric)
if key not in self._cache:
self._cache[key] = _latest(self.events, source, numeric).reindex(self.patients)
return self._cache[key]
def present(self, source: str) -> pd.Series:
key = (source, "present")
if key not in self._cache:
self._cache[key] = _present(self.events, source).reindex(self.patients, fill_value=False).astype(bool)
return self._cache[key]
def holds(self, condition: dict) -> np.ndarray:
if "variable" in condition:
return self.made[condition["variable"]].isin(condition["codes"]).to_numpy()
source = condition["source"]
if condition.get("present"):
return self.present(source).to_numpy()
if "codes" in condition:
return self.value(source, False).isin(condition["codes"]).to_numpy()
number = self.value(source, True)
ok = number.notna()
if "ge" in condition:
ok &= number >= condition["ge"]
if "lt" in condition:
ok &= number < condition["lt"]
return ok.to_numpy()
def category_of(spec: dict, reader: Reader) -> pd.Series:
out = pd.Series(spec["missing"], index=reader.patients, dtype=object)
decided = np.zeros(len(reader.patients), bool)
for rule in spec["rules"]:
conditions = rule["when"] if "when" in rule else [rule]
holds = np.ones(len(reader.patients), bool)
for condition in conditions:
holds &= reader.holds(condition)
take = holds & ~decided
out[take] = rule["then"]
decided |= take
return out
def _band(age: pd.Series, index: dict) -> pd.Series:
width, open_from = index["age_band_years"], index["age_open_from"]
low = (np.floor(age / width) * width).clip(lower=0)
closed = [index["age_label"].format(low=int(a), high=int(a) + width - 1) if pd.notna(a) else None for a in low]
opened = index["age_open_label"].format(low=open_from)
label = pd.Series(closed, index=age.index, dtype=object)
label[age >= open_from] = opened
return label.fillna(index["age_unknown"])
def recode(cohort: pd.DataFrame, dictionary: dict) -> pd.DataFrame:
"""One row per patient of the cohort, in the columns of `output_columns`."""
index = dictionary["index"]
window = timedelta(days=int(dictionary["window_days_after_index"]))
frame = cohort.copy()
frame["fecha"] = pd.to_datetime(frame["fecha"])
frame["fecha_indice"] = pd.to_datetime(frame["fecha_indice"])
patients = pd.Index(sorted(frame["pac_id"].unique()), name="pac_id")
start = frame.groupby("pac_id")["fecha_indice"].first().reindex(patients)
visible = frame[frame["fecha"] <= frame["pac_id"].map(start) + window]
reader = Reader(visible, patients, {})
for name in variable_names(dictionary):
reader.made[name] = category_of(dictionary[name], reader)
birth = frame[frame["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
death = frame[frame["tipo"] == index["death_source"]].groupby("pac_id")["fecha"].min().reindex(patients)
last = frame.groupby("pac_id")["fecha"].max().reindex(patients)
end = death.fillna(last)
days = (end - start).dt.days
age = (start - birth).dt.days / 365.25
result = pd.DataFrame(index=patients)
result[index["id_column"]] = patients.to_numpy()
result[index["year_column"]] = start.dt.year.astype(str)
result[index["age_column"]] = _band(age, index)
for name in variable_names(dictionary):
spec = dictionary[name]
if spec.get("internal"):
continue
result[column_of(name, spec)] = reader.made[name]
if "raw_column" in spec:
size = reader.value(spec["source"], True)
result[spec["raw_column"]] = [spec["raw_format"].format(v) if pd.notna(v) else spec["raw_missing"]
for v in size]
result[index["months_column"]] = (days / index["days_per_month"]).round().astype(int).astype(str)
result[index["vital_column"]] = np.where(death.notna(), index["dead"], index["alive"])
return result[output_columns(dictionary)].reset_index(drop=True)
def diagnosis_date(year: int, dictionary: dict) -> date:
month, day = dictionary["index"]["seer_diagnosis_month_day"].split("-")
return date(int(year), int(month), int(day))
View File
-119
View File
@@ -1,119 +0,0 @@
"""The SEER development stages over the cohort a run trains on: what the dashboard shows as the model's development.
The members are written as the pipeline's recoded file (`models.cama.seer_survival`, stages 01 to 06): the depuration of
redundant variables, the balanced cohort and its age and tumor categorization, the stepwise logistic regression and the
Bayesian network with their comparison, the bootstrap, the survival curves of the subgroups and the risk factors. Their
tables and figures are the version's `analisis/desarrollo.json`. Stage and treatment are not in the hospital's data yet, so
they enter as `Desconocido` and the record names them; a stage that cannot run publishes its error and the others go on.
"""
import base64
import dataclasses
import tempfile
import traceback
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.survival.estimator import molecular_subtype
UNAVAILABLE = ("Estadio_cat", "Tratamiento_quirurgico_cat", "Radioterapia_cat", "Quimioterapia_cat")
# What the dashboard reads: the file written by a stage, under the name it is published with.
TABLES = {
"or_lr_balanceada.csv": "or_lr_balanceada", "hbn_arcos.csv": "hbn_arcos",
"metricas_diferenciacion.csv": "metricas_diferenciacion", "auc_validacion_interna.csv": "auc_validacion_interna",
"seleccion_bootstrap.csv": "seleccion_bootstrap", "auc_bootstrap.csv": "auc_bootstrap",
"factores_riesgo.csv": "factores_riesgo", "factores_riesgo_resumen_variables.csv": "factores_riesgo_variables",
"escenarios_resumen.csv": "escenarios_resumen", "escenarios_factores_riesgo.csv": "escenarios_factores_riesgo",
"subgrupos_KM_Weibull_fraccional.csv": "subgrupos_weibull", "subgrupos_puntos_LR_HBN.csv": "subgrupos_puntos",
"prueba_edad_resumen.csv": "prueba_edad", "comparacion_cortes_edad.csv": "cortes_edad",
"comparacion_cortes_tumor.csv": "cortes_tumor", "pesos_combinacion_cohorte.csv": "pesos_combinacion",
}
MAX_ROWS = 60
MAX_FIGURE_BYTES = 400_000
def _recoded_frame(labelled_members: pd.DataFrame) -> pd.DataFrame:
"""The members as the pipeline's recoded file: its raw SEER columns (year, age level, months, vital status, tumor
size) and the categorical ones, each unknown value `Desconocido`."""
lm = labelled_members
age = lm["age_years"].fillna(lm["age_years"].median()).to_numpy()
lower = (np.floor(age / 5) * 5).astype(int)
frame = pd.DataFrame({
"Year of diagnosis": pd.to_datetime(lm["fecha_indice"]).dt.year.astype(str),
"Age recode with <1 year olds": [f"{v}-{v + 4} years" if v < 85 else "85+ years" for v in lower],
"Survival months": lm["months"].astype(float).astype(str),
"Vital status recode (study cutoff used)": np.where(lm["event"], "Dead", "Alive"),
"Tumor size summary (mm)": lm["size_mm"].map(lambda v: "" if pd.isna(v) else str(int(v))),
})
for column, source in (("Tipo_histologico_cat", "histologic_type"), ("Grado_histologico_cat", "grade"),
("Receptor_estrogeno_cat", "er"), ("Receptor_progesterona_cat", "pr"),
("HER2_IHQ_cat", "her2"), ("Ki67_cat", "ki67_group")):
frame[column] = lm[source].fillna("Desconocido").astype(str).to_numpy()
frame["Subtipo_molecular_cat"] = molecular_subtype(lm).to_numpy() # the scenarios of stage 5 and 6 read the subtype
for column in UNAVAILABLE:
frame[column] = "Desconocido"
return frame
def _seer_settings(development: dict):
"""The pipeline's own settings with this model's budget (`[config.desarrollo]`) and its Ki-67 column, which the
SEER dictionary does not have."""
from models.cama.seer_survival.settings import load
s = load()
m = s.modeling
modeling = dataclasses.replace(
m, canonical_map={**m.canonical_map, "Ki67_cat": "Ki67"}, categorical_order=(*m.categorical_order, "Ki67"),
tier_tumor=(*m.tier_tumor, "Ki67"), n_bootstrap_run=development["n_bootstrap"],
bootstrap_max_seconds=development["bootstrap_max_seconds"], bootstrap_restarts=development["bootstrap_restarts"],
n_splits_prop=development["n_splits_proposals"], proposals_max_seconds=development["proposals_max_seconds"],
n_restarts=development["restarts"])
return dataclasses.replace(
s, modeling=modeling, depuration=dataclasses.replace(s.depuration, null_perm=development["null_perm"]),
balancing=dataclasses.replace(s.balancing, exclude_censored_years=False))
def _records(path: Path) -> dict:
"""The table as `{"columnas": [...], "filas": [...]}`: the columns in the file's order, which JSON objects do not keep."""
table = pd.read_csv(path)
if table.columns[0].startswith("Unnamed"):
table = table.rename(columns={table.columns[0]: "indice"})
table = table.head(MAX_ROWS).replace([np.inf, -np.inf], np.nan).astype(object)
return {"columnas": [str(c) for c in table.columns], "filas": table.where(table.notna(), None).to_dict("records")}
def development(labelled_members: pd.DataFrame, desarrollo: dict) -> dict:
"""`{"desarrollo": record}`, or `{}` when `[config.desarrollo]` has `enabled = false`."""
if not desarrollo.get("enabled", True):
return {}
from models.cama.seer_survival import pipeline # the `seer-survival` extra: scoring a member does not need it
errors, log = {}, []
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp)
_recoded_frame(labelled_members).to_csv(out / pipeline.RECODED, index=False)
(out / pipeline.COLUMN_MAP).write_text("{}", encoding="utf-8")
settings = _seer_settings(desarrollo)
for stage in pipeline.STAGES:
try:
log += pipeline.run_pipeline(out, only=[stage.id], everything=True, settings=settings)
except Exception as error:
errors[stage.id] = f"{type(error).__name__}: {error}"
log.append((stage.id, "error", 0))
traceback.print_exc()
tables = {name: _records(out / file) for file, name in TABLES.items() if (out / file).exists()}
figures = {}
for path in sorted(out.rglob("*.png")):
raw = path.read_bytes()
if len(raw) <= MAX_FIGURE_BYTES:
figures[path.stem] = base64.b64encode(raw).decode("ascii")
return {"desarrollo": {
"version": 1, "n": int(len(labelled_members)), "etapas": [{"etapa": s, "estado": e, "segundos": t} for s, e, t in log],
"errores": errors, "variables_no_disponibles": list(UNAVAILABLE), "tablas": tables, "figuras": figures}}
def population(population_curves: dict, development: dict) -> dict:
"""Everything the version publishes about its cohort, by file name under `analisis/`: the curves and the development."""
return {**population_curves, **development}
-203
View File
@@ -1,203 +0,0 @@
"""What the CaMa survival model is made of: the member table a build's events give, and the interval survival estimator.
`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index
and rules leave get their covariates at the index (age group, the biopsy report's histological type, Nottingham grade,
ER, PR, HER2 and Ki-67 band, read from the report's results within `result_days` of the index) and the index date; the
rest keep their row, empty. `IntervalSurvival` fits, per interval of `survival.horizons`, a logistic regression and a
Bayesian network with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`),
stacks them with out-of-sample weights and scores a patient's survival to each horizon as the product of the intervals'.
The registered model is `Pipeline([MemberFeatures, IntervalSurvival])`, so it takes a build's long frame.
Everything the registered model needs when it scores is in this package, which the registry pickles by value.
"""
import json
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.io.contracts import DAYS_PER_YEAR
from models.steps import indexing
UNKNOWN = "NA"
DAYS_PER_MONTH = 30.4375
INDEX_COLUMN = "fecha_indice_modelo"
NUMERIC = ["age_years", "size_mm", "ki67_pct"] # the covariates before banding: the SEER development stages band them themselves
FEATURES = ["age_group", "histologic_type", "grade", "er", "pr", "her2", "ki67_group", "size_group"]
RESULTS = {"tipo_histologico": "histologic_type", "grado_nottingham": "grade", "receptor_estrogeno": "er",
"receptor_progesterona": "pr", "her2": "her2"}
WINDOW_KEYS = ("recruitment_start", "recruitment_end")
DEFAULT_SIZE_CUTS = (20, 50) # mm: T1 up to 20, T2 up to 50, T3 above
EPOCH = pd.Timestamp("1970-01-01")
def molecular_subtype(labelled: pd.DataFrame) -> pd.Series:
"""The SEER subtype string (`HR+/HER2-`...) from the receptors: hormone-positive when either is, HER2-positive at 3+ and
negative at 0 and 1+; an equivocal (2+) or missing HER2 leaves the subtype unknown, so it is in no HER2 scenario."""
hr_positive = (labelled["er"] == "POSITIVO") | (labelled["pr"] == "POSITIVO")
hr_known = labelled["er"].isin(["POSITIVO", "NEGATIVO"]) | labelled["pr"].isin(["POSITIVO", "NEGATIVO"])
her2 = labelled["her2"].map({"H3": "+", "H0": "-", "H1": "-"})
subtype = np.where(hr_known & her2.notna(), np.where(hr_positive, "HR+", "HR-") + "/HER2" + her2.fillna(""), "Desconocido")
return pd.Series(subtype, index=labelled.index)
def survival_settings(table: dict) -> SurvivalSettings:
"""`SurvivalSettings` from a `[config.survival]` table: lists become tuples, an unknown key is an error."""
return SurvivalSettings(**{key: tuple(value) if isinstance(value, list) else value for key, value in table.items()})
def _band(values: pd.Series, cuts: list) -> pd.Series:
"""The values in the bands the cuts make: `<c1`, `c1-(c2-1)`, ..., `≥cn`; empty where the value is."""
edges = [-np.inf, *cuts, np.inf]
labels = [f"<{cuts[0]}", *[f"{a}-{b - 1}" for a, b in zip(cuts[:-1], cuts[1:])], f"≥{cuts[-1]}"]
return pd.cut(values, edges, right=False, labels=labels).astype(object)
def _dated(cohort: pd.DataFrame) -> pd.DataFrame:
return cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
def member_table(cohort: pd.DataFrame, age_cuts: list, ki67_cuts: list, result_days: int,
size_cuts: list | None = None) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice` and the covariates in `FEATURES`,
empty where the build has no such result near the index."""
frame = _dated(cohort)
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
members["age_group"] = _band(members["age_years"], age_cuts)
near = frame[(frame["fecha"] - frame["fecha_indice"]).dt.days.between(-7, result_days)]
near = near.sort_values(["fecha", "fuente_id"])
for tipo, name in RESULTS.items():
members[name] = near[near["tipo"] == tipo].groupby("pac_id")["valor_codigo"].first().reindex(members.index)
ki67 = near[near["tipo"] == "ki67_pct"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
members["ki67_group"] = _band(ki67, ki67_cuts)
size = near[near["tipo"] == "tamano_tumor_mm"].groupby("pac_id")["valor_numerico"].first().reindex(members.index)
members["size_group"] = _band(size, size_cuts or DEFAULT_SIZE_CUTS)
members["size_mm"], members["ki67_pct"] = size, ki67
return members[["fecha_indice", *FEATURES, *NUMERIC]]
def outcome_table(cohort: pd.DataFrame, cutoff, cap_months: int) -> pd.DataFrame:
"""One row per member of an indexed frame, indexed by `pac_id`: whole months from the index to her death or, if she
has none by the cut-off, to the cut-off (`months`), and whether she died (`event`). Follow-up is cut at
`cap_months`: a later death counts as alive."""
frame = _dated(cohort)
index = frame.groupby("pac_id")["fecha_indice"].first()
death = frame[frame["tipo"] == "defuncion"].groupby("pac_id")["fecha"].min().reindex(index.index)
cutoff = pd.Timestamp(cutoff)
died = (death.notna() & (death <= cutoff)).to_numpy()
end = death.where(died, cutoff)
months = np.floor((end - index).dt.days.to_numpy() / DAYS_PER_MONTH).astype(int).clip(min=0)
if cap_months:
died = died & (months < cap_months)
months = np.minimum(months, cap_months)
return pd.DataFrame({"months": months, "event": died}, index=index.index)
def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None):
"""The covariates as the interval models take them: `(X_dum, X_int, categories, dummy_columns)`. With no `categories`
they are learned from `frame` (the first appearance of each value, the first alphabetical level of each covariate
as the dummies' reference); with them, `frame` is coded as the fitted model coded its training rows, and a value it
never saw takes the unknown category."""
frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str)
if categories is None:
dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns)
categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES}
columns = []
for name in FEATURES:
codes = pd.Categorical(frame[name], categories=categories[name]).codes
fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0
columns.append(np.where(codes < 0, fallback, codes))
X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32)
return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns
def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings: SurvivalSettings):
"""The pipeline's `Cohort` of these members, with the categories and dummy columns it was coded by."""
X_dum, X_int, categories, dummy_columns = encode(features)
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
return cohort, categories, dummy_columns
class MemberFeatures(TransformerMixin, BaseEstimator):
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
def __init__(self, index=None, window=None, age_cuts=(45, 60, 75), ki67_cuts=(14, 20), result_days=30,
size_cuts=DEFAULT_SIZE_CUTS):
self.index = index
self.window = window
self.age_cuts = age_cuts
self.ki67_cuts = ki67_cuts
self.result_days = result_days
self.size_cuts = size_cuts
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
table = member_table(indexed, list(self.age_cuts), list(self.ki67_cuts), self.result_days, list(self.size_cuts)) \
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
return table[[*FEATURES, INDEX_COLUMN]]
class IntervalSurvival(BaseEstimator):
"""The stage-5 interval survival of the SEER pipeline as an estimator: per interval, LR and HBN stacked; the survival
to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with `months` and
`event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With
`INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member
without one) and her mortality is empty too."""
def __init__(self, survival=None, horizons_years=(0.5, 1.0, 1.5)):
self.survival = survival
self.horizons_years = horizons_years
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
s = survival_settings(self.survival)
if [h / 12 for h in s.horizons] != list(self.horizons_years):
raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ")
cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s)
everyone = np.arange(len(X))
if s.combine_active and len(X) >= 2 * s.stack_folds:
weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X)))
self.weights_ = weights["w_LR"].to_numpy()
self.stacking_ = weights.to_dict("records")
else:
self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), []
self.fitted_ = sm.fit_intervals(cohort, s, everyone, None)
self.levels_ = cohort.levels
return self
def interval_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's probability of surviving each interval, given she is alive at its start."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb
def survival_proba(self, X: pd.DataFrame) -> np.ndarray:
"""Each member's survival to each horizon."""
return np.cumprod(self.interval_proba(X), axis=1)
def component_survival(self, X: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each member's survival to each horizon by the logistic regression, by the Bayesian network and by their
stacked combination (`survival_proba`)."""
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
return {"LR": np.cumprod(P_lr, axis=1), "HBN": np.cumprod(P_hb, axis=1), "COMB": self.survival_proba(X)}
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
mortality = 1.0 - self.survival_proba(X)
if INDEX_COLUMN not in X.columns:
return mortality
dates = pd.to_datetime(X[INDEX_COLUMN])
member = dates.notna().to_numpy()
mortality[~member] = np.nan
return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality])
-116
View File
@@ -1,116 +0,0 @@
"""The survival figure of a clinical scenario, scored with the model in production over the data ingested so far.
Training and tuning happen in governance; here the production version is only applied. The scenarios are the subgroups of
the SEER pipeline (`models.cama.seer_survival.scenarios`: an age, a stage, a molecular subtype, a surgery); the members of one
share a figure, and a patient sees the figure of each scenario she belongs to. The record is the one the training run
publishes for the whole cohort (`population`), for the scenario's members: the Kaplan-Meier curve of what happened to them
with its Greenwood band, the survival the model predicts for them (their mean at each horizon by the logistic regression, the
Bayesian network and their combination, with a 95 % interval from resampling the members), and the Weibull fits the SEER
pipeline makes to that prediction. Nothing is fitted on the scenario and nothing is stored.
"""
from types import SimpleNamespace
import numpy as np
import pandas as pd
from models.cama.seer_survival import scenarios
from models.cama.seer_survival import survival_curves as luis
from models.cama.survival import population
from models.cama.survival.estimator import FEATURES, IntervalSurvival, molecular_subtype, survival_settings
from models.dags.training import Scenario, dataflow
MIN_MEMBERS = 30
MIN_EVENTS = 5
REPLICAS = 200
SEED = 42
WHOLE = "Toda la cohorte"
class QueryError(ValueError):
"""The scenario cannot be answered; the message says why, in the reader's language."""
def rehydrate(model) -> IntervalSurvival:
"""The fitted model as the current `IntervalSurvival` code runs it. A version's saved model carries its class as it was
when it was trained; its fitted state (`fitted_`, `weights_`, the codings) is what makes it that version, so that state
is put in the current class and its methods are the code's."""
current = IntervalSurvival.__new__(IntervalSurvival)
current.__dict__.update(model.__dict__)
return current
def members(scenario: Scenario, frame: pd.DataFrame, lineage: dict) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates and follow-up (the scenario's `labelled_members`)."""
dr = dataflow(*scenario.modules, config=scenario.config)
return dr.execute(["labelled_members"], inputs={"source_cohort": frame, "cohort_lineage": lineage})["labelled_members"]
def scenario_masks(labelled: pd.DataFrame) -> dict[str, np.ndarray]:
"""Each scenario's mask over the members. The age and the subtype are the hospital's; stage and surgery are not reported
yet, so a scenario that needs them has no member."""
raw = pd.DataFrame({"Age": labelled["age_years"].to_numpy(), "Subtipo_molecular_cat": molecular_subtype(labelled).to_numpy()}, index=labelled.index)
return scenarios.masks(raw)
def answerable(labelled: pd.DataFrame, mask: np.ndarray) -> bool:
return int(mask.sum()) >= MIN_MEMBERS and int(labelled["event"].to_numpy()[mask].sum()) >= MIN_EVENTS
def patient_scenarios(labelled: pd.DataFrame, pac_id: int) -> list[str]:
"""The scenarios `pac_id` belongs to and that have enough members to draw; the whole cohort when she is in none."""
row = np.flatnonzero(labelled["pac_id"].to_numpy() == pac_id)
if len(row) == 0:
raise QueryError("La paciente no está en la cohorte del modelo.")
found = [name for name, mask in scenario_masks(labelled).items() if mask[row[0]] and answerable(labelled, mask)]
return found or [WHOLE]
def monthly(survival: np.ndarray, horizons: list[int], months: int) -> np.ndarray:
"""Each member's survival month by month from 0 to `months`: log-linear between the horizons, which is a constant hazard
in each interval, and past the last one with the hazard of the last interval."""
borders = np.array([0, *horizons], float)
log = np.log(np.clip(np.column_stack([np.ones(len(survival)), survival]), 1e-12, 1.0))
grid = np.arange(months + 1, dtype=float)
out = np.empty((len(survival), len(grid)))
slope = (log[:, -1] - log[:, -2]) / (borders[-1] - borders[-2])
for i in range(len(survival)):
out[i] = np.where(grid > borders[-1], log[i, -1] + slope[i] * (grid - borders[-1]), np.interp(grid, borders, log[i]))
return np.minimum.accumulate(np.exp(out), axis=1)
def curves(scenario: Scenario, model, labelled: pd.DataFrame, name: str | None) -> dict:
"""The `curvas` record of the members of scenario `name` (`None` or `WHOLE`: everyone) scored with `model` (the fitted
`IntervalSurvival`). `QueryError` for an unknown scenario or one with too few members to say anything."""
if name in (None, WHOLE):
mask = np.ones(len(labelled), bool)
else:
masks = scenario_masks(labelled)
if name not in masks:
raise QueryError(f"No hay un escenario clínico «{name}».")
mask = masks[name]
if not answerable(labelled, mask):
raise QueryError(f"El escenario tiene {int(mask.sum())} pacientes y {int(labelled['event'].to_numpy()[mask].sum())} defunciones; "
f"se necesitan al menos {MIN_MEMBERS} y {MIN_EVENTS}.")
selected = labelled[mask].reset_index(drop=True)
s = survival_settings(scenario.config["survival"])
horizons, cap = list(s.horizons), max(s.cap_months, max(s.horizons))
predicted = model.component_survival(selected[FEATURES])
resample = np.random.default_rng(SEED).integers(0, len(selected), (REPLICAS, len(selected)))
points = {}
for series in population.SERIES:
low, high = np.percentile(predicted[series][resample].mean(axis=1), [2.5, 97.5], axis=0)
points[series] = {"S": predicted[series].mean(axis=0).tolist(), "low": low.tolist(), "high": high.tolist()}
followed, died = selected["months"].to_numpy(int), selected["event"].to_numpy(bool)
S, low, high = luis.fw.km_curva(np.minimum(followed, cap), died & (followed < cap), cap)
adjusted = monthly(predicted["COMB"], horizons, cap).mean(axis=0)
classic, fractional = luis._fit_to_curve(adjusted, len(selected), s, s.ks_max_seconds)
grid = np.arange(0, cap + population.GRID_STEP, population.GRID_STEP)
return {"version": population.RECORD_VERSION, "escenario": name or WHOLE, "n": int(len(selected)),
"events": int((died & (followed < cap)).sum()), "median_follow_up_months": float(np.median(followed)),
"horizons_months": horizons, "months_max": cap, "bootstrap_replicas": REPLICAS,
"km": {"months": list(range(cap + 1)), "S": S.tolist(), "low": low.tolist(), "high": high.tolist()},
"km_adjusted": {"months": list(range(len(adjusted))), "S": adjusted.tolist()},
"weibull": {"t": grid.tolist(), "S": np.asarray(classic["S"](grid), float).tolist()},
"weibull_fractional": {"t": grid.tolist(), "S": np.asarray(fractional["S"](grid), float).tolist()},
"points": points, "etiquetas": scenario.config.get("etiquetas", {})}
-221
View File
@@ -1,221 +0,0 @@
"""CaMa survival prototype: the mortality of a woman with an invasive carcinoma at 6, 12 and 18 months from the first
invasive biopsy report.
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
`[config.index]`): the index is the first biopsy report graded invasive. Each member's covariates are the results of
that report (histological type, Nottingham grade, ER, PR, HER2, Ki-67, lesion size) and her age at the index; her outcome is the
months from the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts
the follow-up). The fit is the SEER pipeline's interval survival (`models.cama.seer_survival.survival_models`): per
interval a logistic regression and a Bayesian network, stacked. A member without a result has it as a category of its
own, as the pipeline does with its unknowns.
The split, the metrics and the routines (ML-01a) are here; the temporal split is `models.steps.model_fitting`'s.
`fitted_model` puts `MemberFeatures` in front of the fitted estimator, so the registered model is one scikit-learn
`Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through loaders, and
registering is the driver's saver (`models.dags.training`).
"""
import json
from datetime import date
import numpy as np
import pandas as pd
import pandera.pandas as pandera
from hamilton.function_modifiers import extract_fields
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival import estimator
from models.cama.survival.estimator import FEATURES, IntervalSurvival, MemberFeatures
from models.steps import model_fitting
LABELLED_MEMBERS = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"months": pandera.Column(int, pandera.Check.ge(0)),
"event": pandera.Column(bool),
**{name: pandera.Column(nullable=True) for name in FEATURES}},
name="labelled members")
def cohort_cutoff(cohort_lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file, and a member without a death is followed to it."""
return date.fromisoformat(cohort_lineage["datos_as_of"])
def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSettings:
"""The pipeline's survival settings; its horizons, in months, must be `horizons_years`."""
settings = estimator.survival_settings(survival)
if [h / 12 for h in settings.horizons] != list(horizons_years):
raise ValueError(f"survival.horizons {list(settings.horizons)} and horizons_years {horizons_years} differ")
return settings
def member_features(cohort: pd.DataFrame, age_cuts: list[int], ki67_cuts: list[int], result_days: int,
size_cuts: list[int]) -> pd.DataFrame:
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates."""
return estimator.member_table(cohort, age_cuts, ki67_cuts, result_days, size_cuts)
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""One row per member, by `pac_id`: months of follow-up and whether she died in them."""
return estimator.outcome_table(cohort, cohort_cutoff, survival_settings.cap_months)
@checked_frame(LABELLED_MEMBERS)
def labelled_members(member_features: pd.DataFrame, member_outcomes: pd.DataFrame) -> pd.DataFrame:
"""Every member of the indexed cohort with her covariates, her follow-up and whether she died."""
return member_features.join(member_outcomes).reset_index()
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> dict:
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event")
def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival:
"""The interval survival fitted on the training members."""
return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]])
def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray:
"""The test members' probability of surviving each interval, given they are alive at its start."""
return fitted_survival.interval_proba(test_set[FEATURES])
def _interval_outcomes(frame: pd.DataFrame, borders: list[int], probabilities: np.ndarray) -> pd.DataFrame:
"""One row per member and interval she was at risk in: the model's probability of surviving it, whether she did
(`survived`) and its weight (a censoring inside the interval counts half, as in the fit)."""
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
rows = []
for j, (a, b) in enumerate(zip(borders[:-1], borders[1:])):
at_risk = months >= a
died = event & (months < b)
rows.append(pd.DataFrame({"interval": f"{a}-{b}", "p": probabilities[at_risk, j],
"survived": (~died[at_risk]).astype(float),
"weight": np.where((~event & (months < b))[at_risk], 0.5, 1.0)}))
return pd.concat(rows, ignore_index=True)
def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray:
"""The training members' mortality at each horizon (apparent performance: they are what the model was fitted on)."""
return fitted_survival.predict_proba(train_set[FEATURES])
def _known_status_auc(frame: pd.DataFrame, mortality: np.ndarray, horizon_months: int, column: int) -> dict:
"""The AUC of the mortality at one horizon among the members whose status there is known (died before it, or
followed to it), and how many they are; empty without both outcomes in at least 20 members."""
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
died = event & (months < horizon_months)
known = died | (months >= horizon_months)
if known.sum() < 20 or len(np.unique(died[known])) < 2:
return {}
return {"auc": float(roc_auc_score(died[known], mortality[known, column])), "n": int(known.sum())}
def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray,
train_mortality: np.ndarray, survival_settings: SurvivalSettings, fitted_survival: IntervalSurvival) -> dict:
"""Aggregates only: the members and deaths in each part and, over the member-intervals of the test members (every
month they were followed, not only the members whose status at a horizon is known), their number, the observed and
expected survival, the weighted Brier score and, with both outcomes, the AUC. A temporal split leaves the newest
members little follow-up, so a metric at one horizon would be of the few that died. The `auc_train_*` are the
apparent discrimination at each horizon, on the members the model was fitted on: they say the covariates were
used, not how it will do on new patients."""
found = {"n_train": len(train_set), "n_test": len(test_set), "events_train": int(train_set["event"].sum()),
"events_test": int(test_set["event"].sum())}
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
found["n_member_intervals_test"] = len(pairs)
if len(pairs):
w, y, p = pairs["weight"].to_numpy(), pairs["survived"].to_numpy(), pairs["p"].to_numpy()
found.update(observed_survival=float(np.average(y, weights=w)), expected_survival=float(np.average(p, weights=w)),
brier_interval=float(np.average((p - y) ** 2, weights=w)))
if len(np.unique(y)) == 2:
found["auc_interval"] = float(roc_auc_score(y, p, sample_weight=w))
for column, months in enumerate(survival_settings.horizons):
apparent = _known_status_auc(train_set, train_mortality, months, column)
if apparent:
found[f"auc_train_{months}m"], found[f"n_known_train_{months}m"] = apparent["auc"], apparent["n"]
for row, months in zip(fitted_survival.stacking_, survival_settings.horizons):
found[f"stack_w_lr_{months}m"] = float(row["w_LR"])
return found
def _dates(frame: pd.DataFrame) -> dict:
if frame.empty:
return {"n": 0}
return {"n": len(frame), "first_index_date": str(frame["fecha_indice"].min()),
"last_index_date": str(frame["fecha_indice"].max())}
def sampling(index_attrition: list, prior_observation: dict, train_set: pd.DataFrame, test_set: pd.DataFrame,
train_fraction: float) -> dict:
"""MUESTREO: who could be used (the scenario's index and rules, step by step, and their prior history), and how
they were split."""
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
"train_fraction": train_fraction, "train": _dates(train_set), "test": _dates(test_set)}
def missing_data(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""DATOS_FALTANTES: how many members lacked each covariate, and what was done about it."""
def missing(frame: pd.DataFrame) -> dict:
return {name: int(frame[name].isna().sum()) for name in FEATURES}
return {"method": "un resultado ausente es una categoría más (NA); no se imputa ni se descarta al miembro",
"train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_survival: IntervalSurvival, survival_settings: SurvivalSettings) -> dict:
"""METODO_ANALITICO: the intervals, how the two models are stacked and which covariates the network kept."""
s = survival_settings
return {"method": "supervivencia por intervalos: regresión logística y red bayesiana (CPT tabular) por intervalo, "
"combinadas con pesos fuera de muestra; la supervivencia es el producto de los intervalos",
"intervals_months": [0, *s.horizons], "censoring": s.censoring, "cap_months": s.cap_months,
"hbn_ess": s.hbn_ess, "hbn_max_parents": s.hbn_max_parents, "covariates": FEATURES,
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
for row in fitted_survival.stacking_],
"hbn_parents": [[FEATURES[j] for j in model[0]] for _, model in fitted_survival.fitted_]}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
"""BALANCE_CLASES: deaths and members followed without one in each part; the classes are used as observed."""
def counts(frame: pd.DataFrame) -> dict:
return {"muertes": int(frame["event"].sum()), "sin muerte": int((~frame["event"]).sum())}
return {"method": "ninguno: no se remuestrea ni se pondera por clase; una censura dentro de un intervalo pesa medio "
"riesgo", "train": counts(train_set), "test": counts(test_set)}
def output_confidence(test_set: pd.DataFrame, test_interval_survival: np.ndarray, survival_settings: SurvivalSettings,
calibration_bins: int = 5) -> dict:
"""CONFIANZA_SALIDA: over the test members' member-intervals, the predicted survival of the interval against the
observed one, by quantiles."""
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
if len(pairs) == 0 or pairs["p"].nunique() < 2:
return {"method": "calibración en la prueba: sin dispersión suficiente para formar cuantiles", "n": len(pairs)}
bins = pd.qcut(pairs["p"], q=min(calibration_bins, pairs["p"].nunique()), duplicates="drop")
table = pairs.assign(py=pairs["p"] * pairs["weight"], sy=pairs["survived"] * pairs["weight"]).groupby(
bins, observed=True).agg(n=("p", "size"), w=("weight", "sum"), py=("py", "sum"), sy=("sy", "sum"))
return {"method": "calibración en la prueba por intervalo: supervivencia media prevista contra observada, por "
"cuantiles de los miembro-intervalos",
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.py / row.w),
"observed_rate": float(row.sy / row.w)} for interval, row in table.iterrows()]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
ki67_cuts: list[int], result_days: int, size_cuts: list[int]) -> Pipeline:
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), tuple(ki67_cuts), result_days, tuple(size_cuts))),
("survival", fitted_survival)])
-92
View File
@@ -1,92 +0,0 @@
domain = "cama"
scenario = "survival"
cohort = "cama/cohorte_total"
outcome = "muerte"
# What a registered version needs to load and predict, pinned to the installed versions when it's logged.
requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
# The modules whose functions are the graph's nodes, in `with_modules`.
modules = ["models.cama.survival.model", "models.cama.survival.population", "models.cama.survival.development", "models.steps.indexing"]
description = """
Prototipo: mortalidad por cualquier causa a los 6, 12 y 18 meses del primer reporte de biopsia con carcinoma invasor, \
a partir de la edad y de los resultados de ese reporte (tipo histológico, grado de Nottingham, receptores de estrógeno \
y de progesterona, HER2, Ki-67 y tamaño de la lesión). Supervivencia por intervalos del pipeline SEER (regresión logística y red bayesiana \
combinadas). Sin estadio, tratamiento ni validación clínica; la defunción se conoce solo si el hospital la registra."""
[config]
train_fraction = 0.7
# The model's horizons, in years; `survival.horizons` are the same in months.
horizons_years = [0.5, 1.0, 1.5]
# Covariate bands: the age at the index, in years, the Ki-67 percentage and the lesion size in millimetres (T1, T2, T3).
age_cuts = [45, 60, 75]
ki67_cuts = [14, 20]
size_cuts = [20, 50]
# A report's results count for the index when they are dated up to this many days after it (and a week before).
result_days = 30
# The scenario's index and rules, over its source cohort (models/steps/indexing.py). The recruitment window is the
# source cohort's.
[config.index]
kind = "primera_biopsia_invasora"
event_grades = ["CARCINOMA_INVASOR"]
# PROVISIONAL (sin_definir): the data are left-truncated; 0 keeps everyone.
observacion_previa_minima_dias = 0
# The SEER pipeline's interval survival (models/cama/seer_survival/survival_models.py), with its settings.
[config.desarrollo]
# The SEER development stages (depuration, balancing, LR and HBN, bootstrap, subgroups, risk factors) over the cohort,
# with the pipeline's own budgets (`models/cama/seer_survival/model.toml`). The bootstrap and the proposals stop at their
# time caps and use what they have. One adaptation: `exclude_censored_years` is off, because this follow-up is short and
# would leave every year out of the outcome.
enabled = true
null_perm = 100
n_bootstrap = 60
bootstrap_max_seconds = 2700
bootstrap_restarts = 3
n_splits_proposals = 5
proposals_max_seconds = 3600
restarts = 10
[config.survival]
age_mode = "categorizada"
include_age = true
age_cuts = [45, 60, 75]
hbn_fixed_parents = ["histologic_type", "age_group"] # the SEER pipeline's expert parents that this data has (its stage and treatment are not reported yet); empty = learn them by the BDeu score
hbn_age_parent = false # the grouped age is already in `hbn_fixed_parents`
hbn_parents = "fijos" # as the SEER pipeline: the parents learned on the cohort are kept in the bootstrap
covariates = []
horizons = [6, 12, 18] # months
censoring = "riesgo" # a model per interval using all the follow-up
combine = true # one LR + HBN indicator, per-interval stacking weights
show_individual = false
stack_folds = 5
stack_shrink = 20
n_boot = 100
n_boot_sub = 100
seed = 42
hbn_ess = 1000
hbn_max_parents = 5
k_ident = "clasico"
curves = "ajustada"
adjust_step = 3
show_raw_km = true
ylim_main = []
inset_zoom = false
inset_months = 18
cap_months = 24 # follow-up is cut here: a later death counts as alive
min_events_sub = 5
ks_max_seconds = 120
ks_sub_max_seconds = 180
xlim_sub = []
ylim_sub = {}
# What the dashboard's survival chart says, in the clinicians' words (provisional: to be defined with them). The record a
# training run publishes carries these, so changing one is a setting and a new run.
[config.etiquetas]
# The wording of the survival figure, as the SEER pipeline's own chart has it; to be defined with the clinicians.
titulo = "Supervivencia después del primer reporte de biopsia con carcinoma invasor"
eje_x = "Meses desde el diagnóstico"
eje_y = "Supervivencia S(t)"
km_crudo = "Kaplan-Meier (IC 95 % Greenwood)"
weibull = "Weibull"
weibull_fraccional = "Weibull fraccional"
puntos = "LR + HBN combinado (IC 95 % bootstrap)"
-115
View File
@@ -1,115 +0,0 @@
"""The population results of a training run, what the dashboard draws: the survival of the whole cohort and the model's
survival at each horizon.
Over every member of the indexed cohort (not only the training part), with the SEER pipeline's stage-5 routines
(`models.cama.seer_survival`): the Kaplan-Meier curve with its Greenwood interval, the covariate-adjusted curve (the
mean of the members' interval survival), the classic and the fractional (Kilbas-Saigo) Weibull fitted to it, and the
mean survival at each horizon by the logistic regression, the Bayesian network and their stacked combination, each with
a 95 % bootstrap interval. The record is the version's `analisis/curvas.json` (`models.io.tracking.TrainingRun.log_analysis`),
which the WebApi serves from the production version. The labels the chart carries come from `[config.etiquetas]`, so
the clinicians' wording is a setting, not code.
"""
import numpy as np
import pandas as pd
from models.cama.seer_survival import survival_curves as luis
from models.cama.seer_survival import survival_models as sm
from models.cama.seer_survival.settings import SurvivalSettings
from models.cama.survival.estimator import FEATURES, UNKNOWN
SERIES = ("LR", "HBN", "COMB")
GRID_STEP = 0.25 # months between the points of a fitted curve
RECORD_VERSION = 1
def survival_frame(labelled_members: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.SurvivalFrame:
"""The members as the pipeline's stage 5 takes its cohort: follow-up truncated at `cap_months` (a later death counts as
alive) and the covariates as categories."""
s, lm = survival_settings, labelled_members
df = pd.DataFrame({"meses": lm["months"].astype(float).to_numpy(), "evento": lm["event"].to_numpy(bool)})
df["meses_int"] = df["meses"].astype(int)
if s.cap_months:
df["evento"] = df["evento"] & (df["meses_int"] < s.cap_months)
df["meses_int"] = np.minimum(df["meses_int"], s.cap_months)
for name in FEATURES:
df[name] = lm[name].fillna(UNKNOWN).astype(str).str.strip().to_numpy()
return luis.SurvivalFrame(df, list(FEATURES), None, [])
def curve_cohort(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> sm.Cohort:
"""The members coded as the stage-5 models take them (`survival_curves.sv_cohort`)."""
return luis.sv_cohort(survival_frame, survival_settings)
def km_raw(survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> luis.KaplanMeier:
"""Kaplan-Meier with the Greenwood interval (`survival_curves.sv_km`)."""
return luis.sv_km(survival_frame, survival_settings)
def km_curve(km_raw: luis.KaplanMeier) -> dict:
"""Kaplan-Meier from the index to `months_max`, with its interval, as the record carries it."""
return {"months": list(range(km_raw.T + 1)), "S": km_raw.S.tolist(), "low": km_raw.lo.tolist(), "high": km_raw.hi.tolist()}
def adjusted_km(curve_cohort: sm.Cohort, km_raw: luis.KaplanMeier, survival_settings: SurvivalSettings) -> np.ndarray:
"""The covariate-adjusted survival curve, month by month (`survival_curves.sv_adjusted`)."""
return luis.sv_adjusted(curve_cohort, km_raw, survival_settings)
def population_weights(curve_cohort: sm.Cohort, survival_settings: SurvivalSettings) -> pd.DataFrame:
"""The stacking of LR and HBN over the whole cohort: per interval, the weight of the LR (`sv_weights_cohort`)."""
return luis.sv_weights_cohort(curve_cohort, luis.sv_oof(curve_cohort, survival_settings), survival_settings)
def luis_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, survival_settings: SurvivalSettings) -> luis.Points:
"""The mean survival at each horizon by LR, HBN and the combination, fitted on every member (`sv_points`)."""
return luis.sv_points(curve_cohort, population_weights, survival_settings)
def point_estimates(luis_points: luis.Points) -> dict:
return {"LR": luis_points.lr, "HBN": luis_points.hbn, "COMB": luis_points.combined}
def bootstrap_points(curve_cohort: sm.Cohort, population_weights: pd.DataFrame, luis_points: luis.Points,
survival_settings: SurvivalSettings) -> np.ndarray:
"""One row per replica: the mean survival at each horizon of LR, HBN and the combination, refitted on a resample, the
HBN's parents kept or learned again as `hbn_parents` says (`sv_bootstrap`)."""
return luis.sv_bootstrap(curve_cohort, population_weights, luis_points, survival_settings)
def weibull_fits(adjusted_km: np.ndarray, survival_frame: luis.SurvivalFrame, survival_settings: SurvivalSettings) -> dict:
"""The classic and the fractional Weibull fitted to the adjusted curve as if it came from as many members as the
cohort has (`survival_curves._fit_to_curve`), evaluated on a grid of months, with their parameters."""
classic, fractional = luis._fit_to_curve(adjusted_km, len(survival_frame.df), survival_settings, survival_settings.ks_max_seconds)
grid = np.arange(0, len(adjusted_km) - 1 + GRID_STEP, GRID_STEP)
parameters = lambda fit: {key: float(fit[key]) for key in ("k", "alpha", "beta", "lam", "nll") if key in fit}
return {"t": grid.tolist(), "classic": np.asarray(classic["S"](grid), float).tolist(),
"fractional": np.asarray(fractional["S"](grid), float).tolist(),
"parameters": {"classic": parameters(classic), "fractional": parameters(fractional)}}
def population_curves(labelled_members: pd.DataFrame, km_curve: dict, adjusted_km: np.ndarray, weibull_fits: dict,
point_estimates: dict, bootstrap_points: np.ndarray, population_weights: pd.DataFrame,
survival_settings: SurvivalSettings, etiquetas: dict) -> dict:
"""What a version publishes about its cohort, by file name under `analisis/`: `curvas`, the record the dashboard
draws (the figure's curves, its points and their intervals, and the labels)."""
horizons = list(survival_settings.horizons)
low, high = np.nanpercentile(bootstrap_points, [2.5, 97.5], axis=0)
points = {}
for j, name in enumerate(SERIES):
columns = slice(j * len(horizons), (j + 1) * len(horizons))
points[name] = {"S": [float(v) for v in point_estimates[name]], "low": [float(v) for v in low[columns]],
"high": [float(v) for v in high[columns]]}
months, events = labelled_members["months"], labelled_members["event"]
return {"curvas": {
"version": RECORD_VERSION, "n": int(len(labelled_members)), "events": int(events.sum()),
"median_follow_up_months": float(months.median()), "horizons_months": horizons,
"months_max": km_curve["months"][-1], "bootstrap_replicas": int(survival_settings.n_boot),
"km": km_curve, "km_adjusted": {"months": list(range(len(adjusted_km))), "S": adjusted_km.tolist()},
"weibull": {"t": weibull_fits["t"], "S": weibull_fits["classic"]},
"weibull_fractional": {"t": weibull_fits["t"], "S": weibull_fits["fractional"]},
"weibull_parameters": weibull_fits["parameters"], "points": points,
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
for row in population_weights.to_dict("records")],
"etiquetas": etiquetas}}
+3 -9
View File
@@ -28,19 +28,13 @@ def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float]) -> pd.DataFrame:
"""One row per member (in `pac_id` order, as the model gives them) and horizon. A model that decides its own index
date (`models.steps.indexing`) gives it as one more first column, in days since 1970-01-01, with the members it
leaves out empty: their rows are dropped and the rest are dated by it, not by the cohort's index."""
"""One row per member (in `pac_id` order, as the model gives them) and horizon."""
members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable")
if probabilities.ndim != 2 or len(probabilities) != len(members):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members")
risks, dates = probabilities[:, -len(horizons):], members["fecha_indice"].to_numpy()
if probabilities.shape[1] == len(horizons) + 1:
decided = ~np.isnan(probabilities[:, 0])
members, risks = members[decided], risks[decided]
dates = pd.to_datetime(probabilities[decided, 0], unit="D").date
risks = probabilities[:, -len(horizons):]
return pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
"fecha_indice": np.repeat(dates, len(horizons)),
"fecha_indice": np.repeat(members["fecha_indice"].to_numpy(), len(horizons)),
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
"probabilidad": risks.ravel().astype(float)})
+8 -5
View File
@@ -47,6 +47,8 @@ class Scenario:
config: dict
folder: Path
requirements: tuple[str, ...] = ()
# Tables of `model.toml` outside `[config]` that still make a version a different one (`settings_tables`).
tables: dict | None = None
@classmethod
def from_toml(cls, path: str | Path) -> "Scenario":
@@ -55,7 +57,8 @@ class Scenario:
return cls(domain=found["domain"], scenario=found["scenario"], cohort=found["cohort"],
outcome=found["outcome"], description=found.get("description", ""),
modules=tuple(import_module(name) for name in found["modules"]), config=found["config"],
folder=path.parent, requirements=tuple(found.get("requirements", ())))
folder=path.parent, requirements=tuple(found.get("requirements", ())),
tables={name: found[name] for name in found.get("settings_tables", ())} or None)
@classmethod
def load(cls, domain: str, scenario: str) -> "Scenario":
@@ -67,7 +70,8 @@ class Scenario:
return cls.from_toml(Path(package.__file__).parent / "model.toml")
def config_sha256(self) -> str:
return hashlib.sha256(json.dumps(self.config, sort_keys=True, default=str).encode()).hexdigest()
content = self.config if not self.tables else {"config": self.config, **self.tables}
return hashlib.sha256(json.dumps(content, sort_keys=True, default=str).encode()).hexdigest()
def dataflow(*modules: ModuleType, config: dict, materializers=()) -> driver.Driver:
@@ -78,9 +82,8 @@ 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, the population results and the
# reports' pages when the dataflow has them.
SAVED = {"fitted_model", "metrics", "routines", "population", "reports"}
# What the saver receives: the fitted model and its metrics, and the routines' records when the dataflow has them.
SAVED = {"fitted_model", "metrics", "routines"}
def external_inputs(dr: driver.Driver) -> tuple[set[str], set[str]]:
+2 -8
View File
@@ -6,10 +6,8 @@ anything runs and nothing in the model imports MLflow:
- `from_.cohort_source(target="cohort", source=...)` and `from_.cohort_source_lineage(target="cohort_lineage",
source=...)`: the build's long frame and its lineage, from any `models.io.storage` source (the database or a file).
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines", "population",
"reports"], ...)`: records each routine (ML-01a, `TrainingRun.log_routine`), the dataflow's `population` as the
version's `analisis/` files and its `reports` as its `reportes/` pages when it has them (`TrainingRun.log_analysis`,
`TrainingRun.log_report`), logs the fitted model in the open `TrainingRun` (`tracking`),
- `to.registered_model(id="registered_model", dependencies=["fitted_model", "metrics", "routines"], ...)`: records
each routine (ML-01a, `TrainingRun.log_routine`), logs the fitted model in the open `TrainingRun` (`tracking`),
records the metrics and the config, closes the run, and registers and describes the version (`registry`). Its value
is the version's metadata. A dataflow without `routines` still trains and registers, but the registry won't promote
it (`ROUTINE_KINDS`).
@@ -116,10 +114,6 @@ class RegisteredModelSaver(DataSaver):
model, metrics = data["fitted_model"], _numbers(data["metrics"])
for kind, record in data.get("routines", {}).items():
self.run.log_routine(kind, record)
for name, record in data.get("population", {}).items():
self.run.log_analysis(name, record)
for name, page in data.get("reports", {}).items():
self.run.log_report(name, page)
packages = _own_packages(model)
for package in packages:
cloudpickle.register_pickle_by_value(package)
+3 -7
View File
@@ -236,10 +236,7 @@ class ModelRegistry:
# A reference cohort outside the platform (TEA's EEG baselines), identified by the hash of its listing.
reference = mv.tags.get(COHORT_BUILD_TAG) if mv.tags.get(COHORT_SOURCE_TAG) == REFERENCE_SOURCE else None
metrics = run.data.metrics
# ML-01a: the training run is itself the registered routine; its records (`TrainingRun.log_routine`) are
# reported, not required, since not every model has each of `ROUTINE_KINDS` (a prevalence-incidence mixture
# has no class balance or classifier calibration).
recorded = [kind.value for kind in ROUTINE_KINDS if kind.value in self.routines(mv.run_id)]
missing = [kind.value for kind in ROUTINE_KINDS if kind.value not in self.routines(mv.run_id)]
sha = mv.tags.get(MODEL_SHA_TAG, "")
if armado is not None:
cohort_detail = f"huella {armado['huella'][:12]}"
@@ -261,9 +258,8 @@ class ModelRegistry:
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
PromotionCheck("ML-01a", "rutina registrada por la corrida de entrenamiento", bool(run.info.run_id),
f"corrida {run.info.run_id[:12]}; registros de rutina: {len(recorded)} de {len(ROUTINE_KINDS)}"
+ (f" ({', '.join(recorded)})" if recorded else "")),
PromotionCheck("ML-01a", "rutinas registradas por la corrida de entrenamiento", not missing,
f"faltan: {', '.join(missing)}" if missing else f"{len(ROUTINE_KINDS)} de {len(ROUTINE_KINDS)}"),
PromotionCheck("ML-01b", "modelo guardado por la corrida de entrenamiento", bool(sha), sha[:12]),
]
-12
View File
@@ -50,8 +50,6 @@ from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
MODEL_PATH = "model"
ROUTINES_PATH = "rutinas"
ANALYSIS_PATH = "analisis"
REPORTS_PATH = "reportes"
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
@@ -193,16 +191,6 @@ class TrainingRun:
that too (for instance a class balance of "none"), so the run still says what happened."""
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, indent=1, default=str), routine_path(kind))
def log_analysis(self, name: str, record: dict[str, Any]) -> None:
"""What the run found about its cohort, a JSON file `analisis/<name>.json` that the version publishes: the
population results a dashboard draws, which are not a prediction of any member."""
self.client.log_text(self.run_id, json.dumps(record, ensure_ascii=False, default=str), f"{ANALYSIS_PATH}/{name}.json")
def log_report(self, name: str, page: str) -> None:
"""A page the run wrote about its cohort, `reportes/<name>.html` (self-contained: its scripts inside), which the
version keeps for whoever reviews it. Like `log_analysis`, aggregates only."""
self.client.log_text(self.run_id, page, f"{REPORTS_PATH}/{name}.html")
def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str:
"""Saves `model` under the run's `model` folder, tags the run with its `modelo_sha` and returns it.
Once per run. `signature` describes columns and types only: no input example, so no patient data
+1 -15
View File
@@ -85,9 +85,6 @@ 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
@@ -124,18 +121,7 @@ class JupyterRenderer(NotebookRenderer):
@staticmethod
def _page(exporter, node) -> str:
"""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)
body, _ = exporter(embed_images=True).from_notebook_node(node)
return body
-67
View File
@@ -1,67 +0,0 @@
"""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()))
+28 -18
View File
@@ -17,10 +17,6 @@ Kinds:
later colposcopy; out, in order: `biopsia_sin_resultado`, `cin2_hasta_el_indice`, `antecedente_cacu`,
`histerectomia`, `tratamiento_previo`, `sin_referencia`, `sin_cotest` (k ≥ 1).
- `primera_biopsia_invasora` (CaMa survival): the first biopsy report graded in `event_grades` (`CARCINOMA_INVASOR`),
if it falls in the window; out, in order: `sin_nacimiento` (no birth date, so no age), `defuncion_hasta_el_indice`
(a death on or before the index, which leaves no time to the event).
Every kind ends with `observacion_previa_insuficiente`: out if the days observed before the index are fewer than
`observacion_previa_minima_dias` (default 0, so nobody; owner, 2026-11-20). The data are left-truncated: a rule on
earlier events ("no CIN2+ before the index", "first colposcopy", the referral year) reads only what was recorded, so
@@ -28,6 +24,9 @@ earlier events ("no CIN2+ before the index", "first colposcopy", the referral ye
with enough history makes them valid without changing code. Observation starts, for now, at the patient's first
event in the frame (the platform's `periodo_observacion` doesn't reach the pipeline).
- `primera_biopsia_invasora` (CaMa): the first biopsy reported as invasive carcinoma, if it falls in the window; no
rules. The cohort is read whole, not patient by patient (`VECTORIZED`).
A scenario without `[config.index]` keeps its cohort's own index.
"""
@@ -128,22 +127,25 @@ def _post_colposcopy(events: list[dict], index: dict) -> tuple[date | None, list
return fecha, flags
def _first_invasive_biopsy(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]:
"""The CaMa survival index and, per rule, whether it flags the patient."""
grades = set(index["event_grades"])
reports = sorted((e for e in events if e["tipo"] == "biopsia" and e["valor_codigo"] in grades),
key=lambda e: (e["fecha"], e["fuente_id"]))
if not reports or not _in_window(reports[0]["fecha"], index):
return None, []
fecha = reports[0]["fecha"]
return fecha, [
("sin_nacimiento", not any(e["tipo"] == "nacimiento" for e in events)),
("defuncion_hasta_el_indice", any(e["tipo"] == "defuncion" and e["fecha"] <= fecha for e in events)),
]
KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposcopy}
KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposcopy,
"primera_biopsia_invasora": _first_invasive_biopsy}
def _first_invasive_biopsy(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
"""(members, attrition) of the kind `primera_biopsia_invasora`, from the whole frame."""
biopsies = cohort[(cohort["tipo"] == "biopsia") & (cohort["valor_codigo"] == index.get("invasive_code", "CARCINOMA_INVASOR"))]
first = pd.to_datetime(biopsies["fecha"]).groupby(biopsies["pac_id"]).min()
start, end = index.get("recruitment_start"), index.get("recruitment_end")
inside = pd.Series(True, index=first.index)
if start is not None:
inside &= first >= pd.Timestamp(start)
if end is not None:
inside &= first < pd.Timestamp(end)
members = first[inside].rename("fecha_indice").dt.date.rename_axis("pac_id").reset_index()
return members, [("pacientes", int(cohort["pac_id"].nunique())), ("indexed", len(members))]
# Kinds read from the whole frame: (cohort, index) -> (members, attrition), for cohorts too large to take apart by patient.
VECTORIZED = {"primera_biopsia_invasora": _first_invasive_biopsy}
def _events(cohort: pd.DataFrame) -> dict[int, list[dict]]:
@@ -161,6 +163,8 @@ def _prior_days(rows: list[dict], fecha: date) -> int:
def _indexed_members(cohort: pd.DataFrame, index: dict) -> tuple[pd.DataFrame, list[tuple[str, int]]]:
"""(members, attrition): one row per member (`pac_id`, `fecha_indice`), and how many are left after the index and
after each rule, in order; each rule is charged only for those it removes from what it receives."""
if index["kind"] in VECTORIZED:
return VECTORIZED[index["kind"]](cohort, index)
rule, minimum = KINDS[index["kind"]], int(index.get("observacion_previa_minima_dias", 0))
events = _events(cohort)
found = {}
@@ -207,6 +211,12 @@ def prior_observation(source_cohort: pd.DataFrame, cohort_lineage: dict, index:
if not index:
return {}
members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index))
if index["kind"] in VECTORIZED:
first = pd.to_datetime(source_cohort["fecha"]).groupby(source_cohort["pac_id"]).min()
days = (pd.to_datetime(members["fecha_indice"]) - first.reindex(members["pac_id"]).to_numpy()).dt.days.astype(float)
return {"members": len(days), "under_365_days": int((days < 365).sum()),
"median_days": None if days.empty else float(days.median()),
"threshold_days": int(index.get("observacion_previa_minima_dias", 0))}
events = _events(source_cohort)
days = pd.Series([_prior_days(events[int(p)], f) for p, f in members.itertuples(index=False)], dtype=float)
return {"members": len(days), "under_365_days": int((days < 365).sum()),
-10
View File
@@ -38,14 +38,6 @@ seer-survival = [
"networkx>=3.0",
"mpmath>=1.3",
"matplotlib>=3.8",
"lifelines>=0.28", # the recurrence analysis' penalised Cox model (`models.cama.recurrence`)
]
# The population curves of a survival training run (`models.cama.survival.population`): the fractional Weibull's series;
# plotly for the CaCu survival scenario's subgroup page.
survival-curves = [
"scipy>=1.11",
"mpmath>=1.3",
"plotly>=5.18", # the CaCu survival scenario's subgroup report page (`models.cacu.survival.report`)
]
seer-survival-dca = ["dcurves>=1.1"]
@@ -70,11 +62,9 @@ dev = [
"scipy>=1.11",
"statsmodels>=0.14",
"pgmpy>=1.0",
"lifelines>=0.28",
"networkx>=3.0",
"mpmath>=1.3",
"matplotlib>=3.8",
"plotly>=5.18",
"nbclient>=0.10",
"nbconvert>=7.16",
"ipykernel>=6.29",
-282
View File
@@ -1,282 +0,0 @@
"""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
+1 -82
View File
@@ -7,7 +7,6 @@ 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
@@ -162,8 +161,7 @@ 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"}
# `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"}
assert optional == {"index"} # from the config; a scenario without one keeps its cohort's index
def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame):
@@ -280,82 +278,3 @@ 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
-172
View File
@@ -1,172 +0,0 @@
"""CaMa's recurrence analysis (`models.cama.recurrence`): the two external cohorts as Luis's preparation reads them, the whole
dataflow over small synthetic cohorts with the same columns (the figures of the scenarios, the tables, the routines the registry
asks for and the saved model), and the model's prediction. Fixtures: `files`, METABRIC- and SCAN-B-shaped files of 700 patients
each whose recurrence depends on grade, size and estrogen receptor, in a temporary folder.
"""
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from models.cama.recurrence import prep
from models.cama.recurrence.model import RecurrenceModel
from models.cama.recurrence.source import PACKAGE_DATA, ExternalCohorts
from models.dags.training import Scenario, dataflow
N = 700
def _risk(rng, grade, size, er_positive):
return 0.012 * np.exp(0.8 * (grade - 2) + 0.5 * (size > 30) - 0.5 * er_positive)
@pytest.fixture(scope="module")
def files(tmp_path_factory) -> Path:
"""Two files shaped like METABRIC's TSV and SCAN-B's metadata, recurrence exponential in months and faster with a high grade,
a large tumor and no estrogen receptor; 10 % of the SCAN-B rows are men, which the preparation leaves out."""
rng = np.random.default_rng(5)
folder = tmp_path_factory.mktemp("externas")
grade = rng.choice([1, 2, 3], N, p=[0.2, 0.45, 0.35])
size = rng.gamma(4, 7, N)
er = rng.random(N) < 0.7
months = rng.exponential(1 / _risk(rng, grade, size, er))
followed = np.minimum(months, rng.uniform(30, 150, N))
event = months <= followed
common = lambda: rng.choice(["Positive", "Negative"], N, p=[0.5, 0.5])
pd.DataFrame({
"Patient ID": [f"M{i}" for i in range(N)], "Relapse Free Status": np.where(event, "1:Recurred", "0:Not Recurred"),
"Relapse Free Status (Months)": followed, "Age at Diagnosis": rng.normal(60, 12, N).clip(25, 90), "Tumor Size": size,
"Lymph nodes examined positive": rng.integers(0, 9, N), "Neoplasm Histologic Grade": grade.astype(float),
"Mutation Count": rng.integers(1, 12, N), "ER Status": np.where(er, "Positive", "Negative"), "PR Status": common(),
"HER2 Status": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
"Pam50 + Claudin-low subtype": rng.choice(["LumA", "LumB", "Basal", "Her2"], N), "Cancer Type Detailed": rng.choice(["Ductal", "Lobular"], N),
"Cellularity": rng.choice(["High", "Moderate", "Low"], N), "Inferred Menopausal State": rng.choice(["Post", "Pre"], N),
"Integrative Cluster": rng.choice(list("12345"), N), "Primary Tumor Laterality": rng.choice(["Left", "Right"], N),
"Type of Breast Surgery": rng.choice(["MASTECTOMY", "BREAST CONSERVING"], N), "Chemotherapy": rng.choice(["YES", "NO"], N),
"Radio Therapy": rng.choice(["YES", "NO"], N), "Hormone Therapy": rng.choice(["YES", "NO"], N),
}).to_csv(folder / prep.FILES["metabric"], sep="\t", index=False)
days = followed * prep.DAYS_PER_MONTH
pd.DataFrame({
"PatientName": [f"S{i}" for i in range(N)], "Gender": np.where(rng.random(N) < 0.1, "M", "F"), "RFI_event": event.astype(int),
"RFI_days": days, "OS_event": rng.integers(0, 2, N), "Age_5year_bin": rng.choice([42, 47, 52, 57, 62, 67, 72, 77], N),
"TumorSize_mm": size, "NodeMetSpec": rng.choice(["NodeNegative", "1to3", "4toX"], N), "NHG": np.array(["Grade1", "Grade2", "Grade3"])[grade - 1],
"ER": np.where(er, "Positive", "Negative"), "PR": common(), "HER2": rng.choice(["Positive", "Negative"], N, p=[0.15, 0.85]),
"Ki67": rng.choice(["High", "Low"], N), "ClinicalSubtype": rng.choice(["Luminal A", "Basal-like", "Luminal B HER2-"], N),
"Histology": rng.choice(["Ductal", "Lobular"], N), "MenopauseStatus_bin": rng.choice(["Post", "Pre"], N), "Laterality": rng.choice(["Left", "Right"], N),
"tnm_ClinicalStage": rng.choice(["I", "II", "III"], N), "SurgeryType": rng.choice(["Mastectomy", "Lumpectomy"], N),
"Chemotherapy": rng.choice(["Yes", "No"], N), "Radiation": rng.choice(["Yes", "No"], N), "Endocrine": rng.choice(["Yes", "No"], N),
"AntiHER2": rng.choice(["Yes", "No"], N),
}).to_csv(folder / prep.FILES["scanb"], sep="\t", index=False)
return folder
def test_the_real_cohorts_are_read_as_the_preparation_scripts_read_them():
"""Pins down: METABRIC gives 2,380 patients with time and status of recurrence (964 recurrences) and SCAN-B 8,847 women, with
the covariates as categories (the unknowns one more) and a redundant covariate dropped from each. Fails if a column is read
differently, a patient with no follow-up is kept, or the collinearity rule drops other covariates."""
metabric = prep.prepare_metabric(str(PACKAGE_DATA / prep.FILES["metabric"]), 0.80)
scanb = prep.prepare_scanb(str(PACKAGE_DATA / prep.FILES["scanb"]), 0.80)
assert (len(metabric.cohort), int(metabric.cohort["evento"].sum())) == (2380, 964)
assert len(scanb.cohort) == 8847 and "Gender" not in scanb.cohort
assert metabric.eliminated == ["HER2"] and "HER2" not in metabric.covariates
assert set(scanb.eliminated) == {"Receptor_estrogeno", "HER2", "Receptor_progesterona"}
assert set(metabric.cohort["Edad"]) <= {"<45", "45-59", "60-74", "75+", "Desconocido"}
assert metabric.treatment == ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"]
def test_the_dataflow_gives_the_figures_the_tables_the_routines_and_the_model(files):
"""Pins down: the dataflow over small cohorts gives a figure for each scenario with enough recurrences (the Kaplan-Meier with
its band, both Weibull and the combined recurrence-free probability at each horizon with its interval), the tables behind
them, the five routines the registry asks for and a model whose probabilities are in [0, 1]. Fails if a stage stops
feeding the next, the figures lose a curve or a routine is missing."""
scenario = Scenario.load("cama", "recurrence")
config = {"recurrence": {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2,
"n_bootstrap_scanb": 2, "n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}}
dr = dataflow(*scenario.modules, config=config)
r = dr.execute(["population", "metrics", "routines", "fitted_model", "prepared"])
figures = r["population"]["recurrencia"]["escenarios"]
assert figures and {f["cohorte"] for f in figures} <= {"metabric", "scanb"}
one = figures[0]
assert set(one) >= {"escenario", "condiciones", "n", "recaidas", "km", "weibull", "weibull_fractional", "points"}
comb = one["points"]["COMB"]
assert len(comb["S"]) == 2 and all(lo <= s <= hi + 1e-9 for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
assert len(one["km"]["S"]) == len(one["km"]["low"]) == one["observado_hasta"] + 1
assert {"auc", "factores_riesgo", "calculadora", "escenarios_resumen"} <= set(r["population"]["recurrencia_desarrollo"]["tablas"])
assert set(r["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
assert r["metrics"] and all(isinstance(v, float) for v in r["metrics"].values())
assert len(r["prepared"]["scanb"].cohort) < N # the men are left out
model: RecurrenceModel = r["fitted_model"]
p = model.predict_proba(r["prepared"]["metabric"].cohort.head(50))
assert p.shape == (50, 2) and ((p >= 0) & (p <= 1)).all()
def test_the_external_cohorts_are_the_versions_reference_and_the_files_are_hashed(files):
"""Pins down: the reference the version is traced to is the hash of the two files, as a reference source and not a platform
build, and a different file is a different reference. Fails if a change in the data does not change the reference (a retrain
would then be skipped) or the version cannot be promoted for want of a cohort link."""
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
from models.io.registry import REFERENCE_SOURCE
source = ExternalCohorts(files)
before = source.reference()[COHORT_BUILD_TAG]
(files / prep.FILES["metabric"]).write_text((files / prep.FILES["metabric"]).read_text() + "\n")
assert source.reference()[COHORT_SOURCE_TAG] == REFERENCE_SOURCE and len(before) == 64
assert ExternalCohorts(files).reference()[COHORT_BUILD_TAG] != before
def test_a_version_trains_registers_and_publishes_its_figures(files, mlflow_tracking):
"""Pins down: training the scenario on its files registers a PROD version that carries the figures the dashboard draws
(`analisis/recurrencia.json`), the tables, the routines, the metrics and the saved model, linked to the files' hash, so that
only the human reports stand between it and promotion. Fails if the version cannot be saved, loses its figures, or fails a
promotion check that is not the reports."""
import dataclasses
import json
from models.dags.training import train
from models.io.registry import registry
scenario = Scenario.load("cama", "recurrence")
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
scenario = dataclasses.replace(scenario, config={"recurrence": tiny})
version = train(scenario, ExternalCohorts(files), "PROD")
_, figures = registry.artifact("cama", "recurrence", version, "analisis/recurrencia.json")
_, tables = registry.artifact("cama", "recurrence", version, "analisis/recurrencia_desarrollo.json")
assert json.loads(figures)["escenarios"] and "auc" in json.loads(tables)["tablas"]
checks = {c.code: c.passed for c in registry.checks("cama", "recurrence", version)}
assert all(checks[code] for code in ("ML-02", "ML-03", "ML-01a", "ML-01b"))
assert not checks["MLD-01b"] and not checks["MLD-03"] # the reports are the human gate
def test_the_cli_trains_and_leaves_the_version_waiting_for_its_reports(files, mlflow_tracking, monkeypatch, capsys):
"""Pins down: `models run cama recurrence --train --promote` (what a governance job runs) trains the version, says "trained", then
refuses to promote it for want of its reports with the message the job reads ("not promoted, missing") and exit code 1; run
again it finds the version already trained. Fails if the entry point cannot run (a missing import), trains twice, or
promotes without the human reports."""
import argparse
import dataclasses
from models.cama.recurrence.steps import run_steps
scenario = Scenario.load("cama", "recurrence")
tiny = {**scenario.config["recurrence"], "data_dir": str(files), "horizons": [12, 36], "n_bootstrap_metabric": 2, "n_bootstrap_scanb": 2,
"n_boot_calc": 3, "min_events": 5, "ks_seconds": 2, "max_parents": 3}
monkeypatch.setattr(Scenario, "load", classmethod(lambda cls, domain, name: dataclasses.replace(scenario, config={"recurrence": tiny})))
args = argparse.Namespace(export=False, estimate=False, store=False, version=None, train=True, promote=True, environment="prod",
domain="cama", scenario="recurrence")
first = run_steps(args)
out = capsys.readouterr()
second = run_steps(args)
again = capsys.readouterr()
assert first == 1 and "trained: version 1" in out.out and "not promoted, missing" in out.err
assert second == 1 and "already trained: version 1" in again.out
-103
View File
@@ -1,103 +0,0 @@
"""The SEER survival pipeline's stages: depuration (01) and bootstrapping (03), on small synthetic frames."""
import dataclasses
import json
import numpy as np
import pandas as pd
import pytest
from models.cama.seer_survival import depuration, depuration_stats as stats, run
from models.cama.seer_survival.settings import BootstrapSettings, Settings, load
@pytest.fixture
def settings() -> Settings:
s = load()
return dataclasses.replace(s, depuration=dataclasses.replace(s.depuration, null_perm=5))
@pytest.fixture
def recoded() -> pd.DataFrame:
"""`B_cat` repeats `A_cat` under other labels; `Tumor_group` repeats `T_cat` and is the preferred of the two; `C_cat`
and `D_cat` are independent; `Outcome_cat` is never touched."""
rng = np.random.default_rng(1)
n = 600
a = rng.choice(list("abcd"), n)
t = rng.choice(["t1", "t2", "t3"], n)
return pd.DataFrame({
"A_cat": a, "B_cat": pd.Series(a).map({"a": "w", "b": "x", "c": "y", "d": "z"}).values, "raw_b": a,
"T_cat": t, "Tumor_group": pd.Series(t).map({"t1": "g1", "t2": "g2", "t3": "g3"}).values,
"C_cat": rng.choice(["u", "v", "w"], n), "D_cat": rng.choice(["p", "q"], n),
"Outcome_cat": rng.choice(["0", "1"], n)})
def test_the_duplicate_is_dropped_with_its_raw_column_and_the_preferred_one_is_kept(tmp_path, settings, recoded):
recoded.to_csv(tmp_path / "recoded.csv", index=False)
(tmp_path / "map.json").write_text(json.dumps({"B_cat": "raw_b"}))
r = run.run_depuration(tmp_path / "recoded.csv", tmp_path / "map.json", tmp_path, settings, generated_at="t")
assert sorted(r["elimination"].dropped["variable"]) == ["B_cat", "T_cat"]
assert set(r["elimination"].dropped["paso"]) == {"A duplicada"}
out = pd.read_csv(tmp_path / run.DEPURATED, dtype=str)
assert list(out.columns) == ["A_cat", "Tumor_group", "C_cat", "D_cat", "Outcome_cat"]
kept = json.loads((tmp_path / run.DEPURATION_DIR / "variables_conservadas.json").read_text())
assert kept["crudas_eliminadas"] == ["raw_b"]
for name in ("calibracion_U_pares.csv", "calibracion_umbrales.json", "variables_eliminadas.csv"):
assert (tmp_path / run.DEPURATION_DIR / name).exists()
def test_the_analysis_leaves_out_excluded_and_constant_columns(settings, recoded):
recoded["K_cat"] = "same"
frame = depuration.analysis_frame(recoded, settings.depuration)
assert "Outcome_cat" not in frame and "K_cat" not in frame and "raw_b" not in frame
assert "Tumor_group" in frame
def test_a_protected_variable_is_never_dropped(settings, recoded):
s = dataclasses.replace(settings.depuration, protected=("B_cat",))
frame = depuration.analysis_frame(recoded, s)
t = stats.Thresholds(s.dup_u, s.u_redund, s.gvif_drop, s.cluster_method, 0.5, 0.5, False)
dropped = stats.eliminate(frame, list(frame.columns), t, s)
assert "B_cat" not in set(dropped["variable"]) and "A_cat" in set(dropped["variable"])
def test_theil_u_of_a_relabelled_copy_is_one_and_of_independent_variables_near_zero(recoded):
U = stats.theil_u_matrix(recoded, ["A_cat", "B_cat", "C_cat"])
assert U.loc["A_cat", "B_cat"] == pytest.approx(1.0) and U.loc["B_cat", "A_cat"] == pytest.approx(1.0)
assert U.loc["A_cat", "C_cat"] < 0.05
def test_auto_thresholds_take_the_calibrations_suggestions(settings, recoded):
s = dataclasses.replace(settings.depuration, thresholds_auto=True)
frame = depuration.analysis_frame(recoded, s)
c = stats.calibrate(frame, list(frame.columns), s, "t")
t = stats.thresholds_in_use(c, s)
assert t.auto and t.u_redund == c.u_suggestion["U"] and t.dup_u == c.dup_u_suggested
def test_calibration_needs_two_variables(settings):
frame = pd.DataFrame({"A_cat": ["a", "b"] * 50})
with pytest.raises(ValueError, match="al menos 2"):
stats.calibrate(frame, ["A_cat"], settings.depuration, "t")
def test_unknown_settings_are_refused(tmp_path):
bad = tmp_path / "model.toml"
bad.write_text("[depuration]\nnope = 1\n[bootstrap]\nn_bootstrap = 1\nrandom_state = 0\n")
with pytest.raises(ValueError, match="unknown settings"):
load(bad)
def test_the_bootstrap_indices_are_reproducible_and_within_the_rows(tmp_path):
pd.DataFrame({"x": range(50)}).to_csv(tmp_path / "balanced.csv", index=False)
s = dataclasses.replace(load(), bootstrap=BootstrapSettings(n_bootstrap=7, random_state=3))
first = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"]
again = run.run_bootstrap(tmp_path / "balanced.csv", tmp_path, s)["bootstrap_indices"]
assert first.shape == (7, 50) and first.min() >= 0 and first.max() < 50
assert np.array_equal(first, again) and np.array_equal(np.load(tmp_path / run.BOOTSTRAP_INDICES), first)
meta = json.loads((tmp_path / run.BOOTSTRAP_METADATA).read_text())
assert (meta["n_filas"], meta["n_bootstrap"], meta["random_state"]) == (50, 7, 3)
-301
View File
@@ -1,301 +0,0 @@
"""The numeric cores of the SEER survival pipeline's stages 02, 04, 05 and 06, and its runner, on small synthetic data."""
import os
import time
import numpy as np
import pandas as pd
import pytest
from models.cama.seer_survival import (balancing_stats, categorization_stats as cs, fractional_weibull as fw, hbn,
lr_selection, pipeline, risk_factor_stats as rf, survival_models as sm)
from models.cama.seer_survival import risk_factors, scenarios
from models.cama.seer_survival.settings import load
# ---------------------------------------------------------------- settings
def test_every_stage_has_its_settings():
s = load()
assert s.balancing.mca_variant in ("con_edad", "sin_edad")
assert "Biología + tratamiento" in {s.categorization.age_final}
assert set(s.categorization.proposals) >= {"P1_actual", "P6_clinico_fijo", "P7_cuantiles"}
assert s.modeling.canonical_map["Age_group"] == "Edad"
assert len(scenarios.SCENARIOS) == 13 and s.survival.combine_active and s.survival.months_max == 24
assert s.risk_factors.treatment == ("Tratamiento_quirurgico", "Radioterapia", "Quimioterapia")
# ---------------------------------------------------------------- 02a balancing
def test_age_midpoints():
mid = balancing_stats.age_midpoint
assert mid("40-44 years") == 42 and mid("85+ years") == 90 and mid("05") == 5 and np.isnan(mid("unknown"))
def test_the_outcome_treats_censoring_and_incomplete_years_as_unknown():
s = load().balancing
labels = {"m": "Survival months", "v": "Vital status", "y": "Year of diagnosis"}
df = pd.DataFrame({"m": ["30", "5", "5", "30", "40"], "v": ["Alive", "Dead", "Alive", "Dead", "Alive"],
"y": ["2000", "2000", "2000", "2001", "2001"]})
# alive with 5 months is censored: unknown; year 2000 has 1 of 3 censored (> 10 %), so the whole year leaves
assert np.isnan(balancing_stats.outcome_values(df, labels, s)).tolist() == [True, True, True, False, False]
assert balancing_stats.outcome_values(df, labels, s)[3:].tolist() == [1.0, 1.0]
keep = balancing_stats.outcome_values(df, labels, s.__class__(**{**s.__dict__, "exclude_censored_years": False}))
assert keep[0] == 1.0 and keep[1] == 0.0 and np.isnan(keep[2]) # only the censored patient stays unknown
def test_the_undersampling_keeps_every_death_and_the_survivors_nearest_to_them():
F = np.array([[0.0], [0.1], [5.0], [9.0], [0.2], [8.0]])
outcome = np.array([0, 1, 1, 1, 0, 1]) # 0 = death (minority): rows 0 and 4
keep, dist = balancing_stats.select_informed_undersample(F, outcome, 0, 1, target_ratio=1.0)
assert keep.tolist() == [True, True, True, False, True, False] # 2 deaths + the 2 nearest survivors
assert dist[1] == pytest.approx(0.1) and dist[3] == pytest.approx(8.8)
# ---------------------------------------------------------------- 02b categorization
def _axis_frame(rng_seed=0):
"""Ten levels; the category mix flips between level 4 and 5 (the only real boundary)."""
rng = np.random.default_rng(rng_seed)
levels = [f"{i:02d}" for i in range(10)]
rows = []
for i, level in enumerate(levels):
for _ in range(300):
p = 0.9 if i < 5 else 0.1
rows.append({"lvl": level, "X_cat": "a" if rng.random() < p else "b",
"Y_cat": "u" if rng.random() < (0.85 if i < 5 else 0.15) else "v"})
return pd.DataFrame(rows), levels
def test_segmentation_finds_the_one_boundary_where_the_composition_flips():
df, levels = _axis_frame()
axis = cs.Axis.of(df, "lvl", levels, list(range(10)), "corte_x")
s = load().categorization
result = cs.segment(df, axis, ["X", "Y"], {}, s, min_n=100)
assert result.bounds == [5] and result.segments == [(0, 5), (5, 10)]
assert result.effect_sizes["cambio_medio"].iloc[0] > 0.7
assert cs.level_to_group(result.segments, levels)["00"] == "00 a 04"
def test_small_segments_are_merged_into_the_most_similar_neighbour():
counts = {"c": pd.DataFrame([[50, 0], [50, 0], [0, 50], [0, 50], [45, 5]], columns=["a", "b"])}
segs, log = cs.fix_small_segments(counts, np.array([50, 50, 50, 50, 50]), [2, 4], 5, min_n=80)
assert all(sum(50 for _ in range(a, b)) >= 80 for a, b in segs) and log
def test_configurations_are_every_combination_of_blocks():
configs = cs.configurations({"outcome": ["Outcome"], "biología": ["A", "B"], "tratamiento": ["T"]})
assert set(configs) == {"Solo outcome", "Solo biología", "Solo tratamiento", "Outcome + biología",
"Outcome + tratamiento", "Biología + tratamiento", "Outcome + biología + tratamiento"}
assert configs["Biología + tratamiento"] == ["A", "B", "T"]
def test_tumor_sizes_and_levels():
assert cs.tumor_size_mm("023") == 23.0 and np.isnan(cs.tumor_size_mm("000")) and np.isnan(cs.tumor_size_mm("999"))
assert cs.tumor_bin_label(23.0, 5, 100) == "021-025 mm" and cs.tumor_bin_label(101.0, 5, 100) == ">100 mm"
levels, mids = cs.tumor_levels(5, 100)
assert levels[0] == "001-005 mm" and levels[-1] == ">100 mm" and len(levels) == len(mids) == 21 and mids[0] == 3.0
def test_quantile_and_clinical_cuts_partition_the_axis():
assert cs.quantile_bounds(np.array([10, 10, 10, 10, 10, 10, 10, 10]), 4) == [2, 4, 6]
segs = cs.segments_from_bounds([3, 3, 0, 99, 5], 8)
assert segs == [(0, 3), (3, 5), (5, 8)]
def test_sensitivity_and_specificity_at_a_cut():
idx = np.array([0, 0, 1, 1, 2, 2, 3, 3])
death = np.array([0, 0, 0, 1, 0, 1, 1, 1], bool)
r = cs.sens_spec_at_cut(idx, death, 2)
assert r["lado_alto_riesgo"] == "arriba del corte" and r["sensibilidad"] == 0.75 and r["especificidad"] == 0.75
def test_the_overlap_of_identical_distributions_is_one():
a = pd.Series(["x", "y", "x", "y"])
assert cs.overlap_coefficient(a, a, ["x", "y"]) == 1.0
assert cs.overlap_coefficient(pd.Series(["x"] * 4), pd.Series(["y"] * 4), ["x", "y"]) == 0.0
# ---------------------------------------------------------------- 04 modeling
def test_the_stepwise_keeps_the_signal_and_drops_the_noise():
rng = np.random.default_rng(3)
n = 1500
signal, noise = rng.normal(size=n), rng.normal(size=n)
y = pd.Series((rng.random(n) < 1 / (1 + np.exp(-2 * signal))).astype(int))
X = pd.DataFrame({"signal": signal, "noise": noise, "noise2": rng.normal(size=n)})
assert lr_selection.stepwise_selection(X, y) == ["signal"]
def test_the_prefilter_sorts_by_chi_square_and_caps_the_columns():
rng = np.random.default_rng(4)
y = pd.Series(rng.integers(0, 2, 800))
X = pd.DataFrame({"weak": ((y.values + (rng.random(800) < 0.4)) > 0).astype(float),
"strong": ((y.values + (rng.random(800) < 0.05)) > 0).astype(float),
"none": rng.integers(0, 2, 800).astype(float)})
assert lr_selection.prefiltered_columns(X, y, 0.10, 40) == ["strong", "weak"]
assert lr_selection.prefiltered_columns(X, y, 0.10, 1) == ["strong"]
def test_the_temporal_tiers_order_demography_tumor_treatment_outcome():
s = load().modeling
tiers = hbn.temporal_order(["Estadio", "Edad", "Radioterapia", "outcome", "Rara"], s)
assert tiers == [["Rara"], ["Edad"], ["Estadio"], ["Radioterapia"], ["outcome"]]
# ---------------------------------------------------------------- 05 survival
def test_the_classic_weibull_fit_recovers_its_parameters():
rng = np.random.default_rng(5)
t = 80.0 * rng.weibull(1.4, 6000)
months = np.minimum(np.floor(t).astype(int), 40)
event = t < 40
d, c = fw.tabla_eventos(months, event)
w = fw.ajustar_weibull(d, c)
assert w["k"] == pytest.approx(1.4, abs=0.15) and w["lam"] == pytest.approx(80.0, rel=0.12)
def test_the_fractional_weibull_is_a_valid_survival_function():
t = np.array([0.0, 1.0, 5.0, 12.0, 24.0])
S = fw.S_ks(t, k=1.0, alpha=1.0, beta=0.5, lam=60.0)
assert S[0] == 1.0 and np.all(np.diff(S) <= 1e-12) and np.all((S >= 0) & (S <= 1))
assert fw.kilbas_saigo([0.0], 1.0, 1.0, 0.0)[0] == 1.0
assert np.all(np.isnan(fw.S_ks(t, k=0.5, alpha=0.4, beta=1.0, lam=60.0))) # k + alpha <= 1: out of region
def test_kaplan_meier_with_no_censoring_is_the_survivor_fraction():
months = np.array([1, 1, 2, 3, 3, 3, 5, 5, 6, 6])
S, lo, hi = fw.km_curva(months, np.ones(10, bool), 6)
assert S[:7].tolist() == pytest.approx([1.0, 1.0, 0.8, 0.7, 0.4, 0.4, 0.2]) # S[m]: alive at the start of month m
assert np.all(lo <= S + 1e-12) and np.all(S <= hi + 1e-12)
def test_the_censoring_weights():
m, e = np.array([2, 5, 8, 12]), np.array([True, False, True, False])
known, y, w = sm.censoring_weights(m, e, 6, "excluir")
assert known.tolist() == [True, False, True, True] and y.tolist() == [0, 0, 1, 1] and w.tolist() == [1, 1, 1, 1]
assert sm.censoring_weights(m, e, 6, "ipcw")[2].min() >= 1.0
def test_the_stacking_weight_follows_the_better_model_and_shrinks_with_few_deaths():
rng = np.random.default_rng(6)
n = 2000
c = sm.Cohort(months=np.full(n, 20), event=np.zeros(n, bool), X_dum=np.zeros((n, 1)), X_int=np.zeros((n, 1), int),
levels=np.array([1]), borders=[0, 6], fixed_parents=None)
truth = rng.random(n) < 0.7 # survives the interval
c = sm.Cohort(np.where(truth, 20, 3), ~truth, c.X_dum, c.X_int, c.levels, c.borders, None)
good = np.where(truth, 0.9, 0.2)[:, None]
bad = np.full((n, 1), 0.7)
s = load().survival
t = sm.stacking_weights(c, s, np.ones(n, bool), good, bad)
assert t["w_LR"].iloc[0] > 0.9 and t["w_LR_sin_contraer"].iloc[0] >= t["w_LR"].iloc[0]
assert t["decision"].iloc[0] in ("solo LR", "mezcla")
def test_the_fixed_hbn_parents_are_found_by_keyword_and_age_is_added():
s = load().survival
cov = ["Estadio_cat", "Tipo_histologico_cat", "Tratamiento_quirurgico_cat", "Quimioterapia_cat", "Radioterapia_cat",
"Edad_cat", "Race"]
assert sm.fixed_parent_indices(cov, s) == [0, 1, 2, 3, 4, 5]
with pytest.raises(AssertionError, match="Estadio"):
sm.fixed_parent_indices(["Edad_cat"], s)
# ---------------------------------------------------------------- 06 risk factors
def test_benjamini_hochberg():
p = [0.01, 0.04, 0.03, 0.005]
assert rf.benjamini_hochberg(p).tolist() == pytest.approx([0.02, 0.04, 0.04, 0.02])
def test_the_odds_of_a_risky_category_are_above_one_and_its_survival_lower():
rng = np.random.default_rng(7)
n = 4000
stage = rng.choice(["I", "IV"], n, p=[0.7, 0.3])
death = (rng.random(n) < np.where(stage == "IV", 0.5, 0.1)).astype(int)
data = pd.DataFrame({"Estadio": stage, "Sexo": rng.choice(["f", "m"], n)})
t = rf.fit_odds(data, death, ["Estadio", "Sexo"])
row = t[t["termino"] == "Estadio_IV"].iloc[0]
assert row["OR_muerte"] > 5 and row["IC95_inf"] > 1 and rf.reference(data, "Estadio") == "I"
months = np.where(death == 1, 8, 24)
d = rf.survival_difference(data, months, death.astype(bool), "Estadio", "IV", "I", 18)
assert d["delta_S18"] < -0.2 and d["delta_IC95_sup"] < 0 and d["n_categoria"] == int((stage == "IV").sum())
# ---------------------------------------------------------------- the runner
def test_a_stage_is_current_only_when_its_outputs_are_newer_than_its_code_and_inputs(tmp_path):
stage = next(e for e in pipeline.STAGES if e.id == "03")
assert not pipeline.is_current(stage, tmp_path) # no outputs
for name in stage.requires + stage.produces:
(tmp_path / name).write_text("x")
future = time.time() + 3600
for name in stage.produces:
os.utime(tmp_path / name, (future, future))
assert pipeline.is_current(stage, tmp_path)
os.utime(tmp_path / stage.requires[0], (future + 10, future + 10)) # the input changed after the outputs
assert not pipeline.is_current(stage, tmp_path)
(tmp_path / stage.produces[0]).write_text("") # an empty output is no output
assert not pipeline.is_current(stage, tmp_path)
def test_the_runner_names_the_missing_inputs_and_logs_each_stage(tmp_path, monkeypatch):
with pytest.raises(FileNotFoundError, match="faltan entradas"):
pipeline.run_pipeline(tmp_path, only=["01"])
ran = []
stage = pipeline.Stage("99", lambda d, s: ran.append("ok"), (), ("out.csv",), ())
monkeypatch.setattr(pipeline, "STAGES", [stage, pipeline.Stage("98", lambda d, s: ran.append("again"), (), (), ())])
pipeline.run_pipeline(tmp_path, settings=object())
assert ran == ["ok", "again"]
(tmp_path / "out.csv").write_text("x")
log = pipeline.run_pipeline(tmp_path, settings=object())
assert [row[:2] for row in log] == [("99", "saltada"), ("98", "ok")] # 99's output is current; 98 has none to check
assert (tmp_path / pipeline.LOG).read_text().splitlines()[0] == "etapa,estado,segundos"
def test_treatment_associations_are_none_when_no_treatment_variable_varies():
"""Pins down: a cohort where every treatment column is a single category (as when the hospital reports none) gives
no associations, as the docstring says, and not a missing-columns error. Fails if the empty case is formatted."""
from models.cama.seer_survival import risk_factors
from models.cama.seer_survival.settings import load
rng = np.random.default_rng(8)
n = 300
data = pd.DataFrame({"Grado": rng.choice(["G1", "G3"], n), "Radioterapia": "Desconocido"})
follow = risk_factors.FollowUp(death=pd.Series(rng.integers(0, 2, n)), months=pd.Series(rng.uniform(1, 20, n)),
event=pd.Series(rng.integers(0, 2, n)))
assert risk_factors.risk_treatment_associations(data, follow, ["Grado"], ["Radioterapia"], load().risk_factors) is None
def test_a_scenario_holds_the_patients_who_meet_every_condition_and_none_without_the_column():
"""Pins down: a scenario's mask is the patients who meet all its conditions over the raw columns (age from the age column,
stage, subtype and surgery by keyword), and a cohort without a column has nobody in the scenarios that need it. Fails if
a condition is dropped, an age edge moves, or a missing column makes a scenario include everyone."""
raw = pd.DataFrame({"Age recode": ["30-34 years", "60-64 years", "75-79 years", "60-64 years"],
"Stage": ["IIA", "IIIB", "IV", "I"], "Subtype (HER2+)": ["HER2+", "HER2+", "HER2-", "HER2+"]})
found = scenarios.masks(raw)
assert found["< 45 años"].tolist() == [True, False, False, False]
assert found["≥ 75 años"].tolist() == [False, False, True, False]
assert found["Estadio IV"].tolist() == [False, False, True, False]
assert found["HER2+ · ≥60 años · estadio III–IV (Alto)"].tolist() == [False, True, False, False]
assert not found["HER2− · estadio 0–II · cirugía conservadora"].any() # no surgery column: nobody
assert not scenarios.masks(raw[["Age recode"]])["Estadio I"].any() # no stage column: nobody
def test_the_risk_factors_of_a_scenario_are_the_classified_categories_most_of_it_shares():
"""Pins down: a classified risk factor that nearly all of a scenario has is listed as defining it, a protector that most
has as most of it, and one that few have is left out. Fails if the shares are taken over the cohort instead of the
scenario, or a category under the presence floor is listed."""
table = pd.DataFrame({"variable": ["Grado", "Grado", "Subtipo"], "categoria": ["G3", "G1", "A"], "clasificacion": ["riesgo robusto", "protector sugerente", "riesgo robusto"],
"OR_muerte": [2.0, 0.5, 3.0], "IC95_inf": [1.2, 0.3, 1.1], "IC95_sup": [3.0, 0.9, 5.0], "delta_S18": [-0.1, 0.05, -0.2]})
data = pd.DataFrame({"Grado": ["G3"] * 10 + ["G1"] * 6 + ["G3"] * 4, "Subtipo": ["A"] * 1 + ["B"] * 19})
mask = np.array([True] * 10 + [False] * 10) # the scenario: the first ten, all grade 3 and one of subtype A
classification = risk_factors.Classification(table, ["c1"])
found = risk_factors.risk_scenario_factors(classification, None, data, {"Grado 3": mask})
row = found.summary.iloc[0]
assert "Grado=G3" in row["riesgo_definitorios"] and row["n_factores_riesgo_incluidos"] == 1
assert set(found.details["variable"]) == {"Grado", "Subtipo"} # subtype A is 10 % of the scenario: present
assert found.details[found.details["categoria"] == "G1"].empty # no scenario member has G1
-515
View File
@@ -1,515 +0,0 @@
"""What this module covers: `models.cama.survival`: the index it takes from the total cohort (the first invasive biopsy
report, with its rules), the covariates and outcome it derives from a build's events, the interval survival estimator
(that it scores unseen categories and intervals without deaths, and that grade and ER move the mortality the way the
data say), that the dataflow reaches its metrics and routines without MLflow, that training registers a version with
its lineage and estimating with it dates each risk by the model's own index.
Fixtures: `cohort_frame`, a long frame of 240 members of the total cohort whose death depends on the grade and on ER,
with members that must be left out; `cohort_file`, that frame as a build's Parquet file with its lineage (the window
in its parameters); `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
import json
from datetime import date, datetime, timedelta, timezone
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.cama.survival import estimator
from models.cama.survival.estimator import FEATURES, INDEX_COLUMN, IntervalSurvival, MemberFeatures
from models.dags.estimation import estimate
from models.dags.training import Scenario, dataflow, find_trained, train
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.storage import CohortFile, read_cohort, read_metadata
from models.steps import indexing
CUTOFF = date(2026, 1, 1)
SCENARIO = Scenario.load("cama", "survival")
CONFIG = SCENARIO.config
WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": CUTOFF.isoformat()}
LINEAGE = {"url": "cama/cohorte_total", "datos_as_of": CUTOFF.isoformat(), "parametros": json.dumps(WINDOW)}
N = 240
def _row(pac_id, when, tipo, valor=None, numero=None, source="biopsiamama", source_id=None, first=None):
return {"pac_id": pac_id, "fecha_indice": first or when, "fecha": when,
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": source,
"fuente_id": source_id or f"{pac_id}-{tipo}"}
def _report(pac_id, index, grade="G2", er="POSITIVO", her2="H1", ki67=18.0, first=None, size=30.0):
"""The invasive biopsy report of `pac_id` on `index`, with its results."""
key = f"B{pac_id}"
rows = [_row(pac_id, index, "biopsia", "CARCINOMA_INVASOR", source_id=key, first=first),
_row(pac_id, index, "tipo_histologico", "DUCTAL_INFILTRANTE", source_id=key, first=first),
_row(pac_id, index, "grado_nottingham", grade, source_id=key, first=first),
_row(pac_id, index, "receptor_estrogeno", er, source_id=key, first=first),
_row(pac_id, index, "receptor_progesterona", er, source_id=key, first=first),
_row(pac_id, index, "her2", her2, source_id=key, first=first),
_row(pac_id, index, "ki67_pct", numero=ki67, source_id=key, first=first),
_row(pac_id, index, "tamano_tumor_mm", numero=size, source_id=key, first=first)]
return rows
def _person(pac_id, born, first, died=None):
rows = [_row(pac_id, born, "nacimiento", source="persona", first=first)]
if died:
rows.append(_row(pac_id, died, "defuncion", source="persona", first=first))
return rows
@pytest.fixture(scope="module")
def cohort_frame():
"""240 members, each with her birth, an invasive biopsy report in 2024-01..2025-06 (grade 1 to 3, ER positive or
negative) and, if she dies by the cut-off, her death: exponential in months, faster with grade 3 and without ER.
Members 241 to 245 must be left out: a benign biopsy only, no birth date, a death before the report, a report
before the window, and an invasive report after the cut-off."""
rng = np.random.default_rng(3)
rows = []
for pac_id in range(1, N + 1):
index = date(2024, 1, 1) + timedelta(days=int(rng.integers(0, 546)))
grade, er = str(rng.choice(["G1", "G2", "G3"])), str(rng.choice(["POSITIVO", "NEGATIVO"]))
rate = 0.012 * np.exp(1.3 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
died = index + timedelta(days=int(rng.exponential(1 / rate) * 30.4375))
rows += _person(pac_id, date(1960, 1, 1) + timedelta(days=pac_id * 30), index - timedelta(days=10),
died if died <= CUTOFF else None)
rows += _report(pac_id, index, grade, er, first=index - timedelta(days=10))
first = date(2025, 1, 1)
rows += [_row(241, first, "biopsia", "BENIGNO", source_id="B241", first=first)]
rows += _report(242, first, first=first)
rows += _person(243, date(1960, 1, 1), first, died=first - timedelta(days=20)) + _report(243, first, first=first)
rows += _person(244, date(1960, 1, 1), date(2010, 1, 1)) + _report(244, date(2010, 3, 1), first=date(2010, 1, 1))
rows += _person(245, date(1960, 1, 1), first) + _report(245, date(2026, 3, 1), first=first)
return pd.DataFrame(rows, columns=SCHEMA.names)
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 3's file, with the lineage a dbt build gives."""
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
path = tmp_path / "3.parquet"
pq.write_table(table.replace_schema_metadata({**LINEAGE, "armado_id": "3"}), path)
return path
def _indexed(frame):
return indexing.cohort(frame, LINEAGE, CONFIG["index"])
def test_the_index_is_the_first_invasive_biopsy_report_and_its_rules_leave_out_who_cannot_be_followed(cohort_frame):
"""Pins down: members 1 to 240 are indexed at their invasive report; a benign biopsy has no index (241), a missing
birth date (242), a death before the report (243) and a report outside the window (244, and 245 after the cut-off
window end) leave the cohort, each charged to its own rule. Fails if the kind stops reading the grade, the window
or either rule."""
attrition = dict(indexing.index_attrition(cohort_frame, LINEAGE, CONFIG["index"]))
assert attrition["pacientes"] == N + 5 and attrition["indexed"] == N + 3
assert attrition["sin_nacimiento"] == N + 2 and attrition["defuncion_hasta_el_indice"] == N + 1
members = _indexed(cohort_frame)["pac_id"].unique()
assert set(members) == set(range(1, N + 1)) | {245}
reindexed = _indexed(cohort_frame).groupby("pac_id")["fecha_indice"].first()
assert reindexed[1] == cohort_frame[(cohort_frame["pac_id"] == 1) & (cohort_frame["tipo"] == "biopsia")]["fecha"].iloc[0]
def test_covariates_are_the_index_reports_results(cohort_frame):
"""Pins down: the covariates are the results of the report on the index date: type, grade, ER, PR, HER2 and the
Ki-67 band; a grade reported a year later does not replace them, and the age group is the age at the index. Fails
if the covariates read another report or window, or the age is taken at another date."""
one = cohort_frame[cohort_frame["pac_id"] == 1]
later = pd.DataFrame([_row(1, date(2025, 12, 1), "grado_nottingham", "G1" if one[one["tipo"] == "grado_nottingham"][
"valor_codigo"].iloc[0] != "G1" else "G3", first=one["fecha_indice"].iloc[0])], columns=SCHEMA.names)
table = estimator.member_table(_indexed(pd.concat([one, later])), CONFIG["age_cuts"], CONFIG["ki67_cuts"],
CONFIG["result_days"], CONFIG["size_cuts"])
row = table.loc[1]
reported = one[one["tipo"] == "grado_nottingham"]["valor_codigo"].iloc[0]
assert (row["histologic_type"], row["grade"], row["her2"], row["ki67_group"], row["size_group"]) == (
"DUCTAL_INFILTRANTE", reported, "H1", "14-19", "20-49")
assert row["er"] == one[one["tipo"] == "receptor_estrogeno"]["valor_codigo"].iloc[0] == row["pr"]
born, index = date(1960, 1, 1) + timedelta(days=30), table.loc[1, "fecha_indice"].date()
age = (index - born).days / 365.25
assert row["age_group"] == ("<45" if age < 45 else "45-59" if age < 60 else "60-74" if age < 75 else "≥75")
def test_the_outcome_is_the_months_to_death_or_to_the_cutoff_cut_at_the_cap(cohort_frame):
"""Pins down: a member who dies in follow-up has her whole months to the death and `event`; one without a death is
followed to the cut-off without it; a death after `cap_months` counts as alive at the cap. Fails if the months, the
censoring date or the cap change."""
rows = (_person(1, date(1960, 1, 1), date(2024, 1, 1), died=date(2024, 8, 10)) + _report(1, date(2024, 1, 1))
+ _person(2, date(1960, 1, 1), date(2025, 1, 1)) + _report(2, date(2025, 1, 1))
+ _person(3, date(1960, 1, 1), date(2023, 1, 1), died=date(2025, 11, 1)) + _report(3, date(2023, 1, 1)))
frame = pd.DataFrame(rows, columns=SCHEMA.names)
table = estimator.outcome_table(frame, CUTOFF, cap_months=24)
assert table.loc[1].tolist() == [7, True] # 2024-01-01 to 2024-08-10: 222 days
assert table.loc[2].tolist() == [11, False] # 2025-01-01 to the cut-off: 365 days, 11.99 whole months
assert table.loc[3].tolist() == [24, False] # dies after 24 months: alive at the cap
@pytest.fixture(scope="module")
def labelled(cohort_frame):
"""The 240 indexed members with their covariates and outcome, as the dataflow labels them."""
indexed = _indexed(cohort_frame)
indexed = indexed[indexed["pac_id"] <= N]
features = estimator.member_table(indexed, CONFIG["age_cuts"], CONFIG["ki67_cuts"], CONFIG["result_days"], CONFIG["size_cuts"])
return features.join(estimator.outcome_table(indexed, CUTOFF, 24)).reset_index()
def test_grade_and_er_move_the_mortality_the_way_the_data_say(labelled):
"""Pins down: fitted on members whose death depends on grade 3 and on no ER, the estimator gives grade 3 a higher
mortality at every horizon than grade 1, and the mortality grows with the horizon and stays in 0 to 1. Fails if the
fit stops using the covariates or the survival stops being a product of the intervals."""
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
labelled[["months", "event"]])
probe = labelled[FEATURES].iloc[[0, 0]].copy()
probe["grade"] = ["G1", "G3"]
probe["er"] = "POSITIVO"
mortality = model.predict_proba(probe)
assert mortality.shape == (2, 3) and ((0 <= mortality) & (mortality <= 1)).all()
assert (mortality[1] > mortality[0]).all() and (np.diff(mortality, axis=1) >= 0).all()
def test_a_category_unseen_in_training_and_an_interval_without_deaths_are_scored(labelled):
"""Pins down: a grade the model never saw scores as unknown rather than failing, and a cohort where nobody dies in
the last interval still fits (a constant stands for the logistic regression). Fails if either raises."""
early = labelled.assign(event=labelled["event"] & (labelled["months"] < 12))
model = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(early[FEATURES],
early[["months", "event"]])
unseen = labelled[FEATURES].iloc[[0]].assign(grade="G9")
mortality = model.predict_proba(unseen)
assert np.isfinite(mortality).all()
assert mortality[0, 2] - mortality[0, 1] < 0.05 # nobody died in 12-18 months: only the network's smoothing remains
def test_the_pipeline_takes_the_total_cohort_and_scores_only_who_the_index_leaves(cohort_frame, labelled):
"""Pins down: the registered shape (`MemberFeatures` then the estimator) takes the unindexed frame, gives one row
per member of the frame, and leaves empty the members the scenario leaves out, with the model's index date first for
the rest. Fails if scoring stops indexing the build as training did."""
from sklearn.pipeline import Pipeline
fitted = IntervalSurvival(CONFIG["survival"], tuple(CONFIG["horizons_years"])).fit(labelled[FEATURES],
labelled[["months", "event"]])
pipeline = Pipeline([("members", MemberFeatures(dict(CONFIG["index"]), WINDOW, tuple(CONFIG["age_cuts"]),
tuple(CONFIG["ki67_cuts"]), CONFIG["result_days"], tuple(CONFIG["size_cuts"]))),
("survival", fitted)])
scored = pipeline.predict_proba(cohort_frame)
assert scored.shape == (N + 5, 4)
assert np.isnan(scored[N:N + 4, 0]).all() and not np.isnan(scored[:N, 0]).any()
assert not np.isnan(scored[N + 4, 0]) # member 245: indexed (her report is in the window), scored
def test_the_dataflow_reaches_its_metrics_and_routines_without_mlflow(cohort_frame):
"""Pins down: from the source cohort and its lineage the graph gives metrics that are numbers, and the five routine
records the registry checks before promoting. Fails if a node stops producing its record or a metric is not a
number."""
dr = dataflow(*SCENARIO.modules, config=CONFIG)
result = dr.execute(["metrics", "routines", "index_attrition"],
inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})
assert all(isinstance(v, (int, float)) for v in result["metrics"].values())
assert result["metrics"]["n_train"] + result["metrics"]["n_test"] == N + 1
assert set(result["routines"]) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES",
"CONFIANZA_SALIDA"}
json.dumps(result["routines"])
def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking,
tmp_path):
"""Pins down: training on a build's file registers a version; estimating with it writes one row per scored member
and horizon, dated by the model's index (the report), not by the cohort's, with the members the scenario leaves out
absent. Fails if the version cannot score a build or the estimate keeps the cohort's index date."""
version = train(SCENARIO, CohortFile(cohort_file))
output = tmp_path / "estimate.parquet"
resolved, wrote = estimate(SCENARIO, CohortFile(cohort_file), output, version)
assert wrote and resolved.version == version and find_trained(SCENARIO, CohortFile(cohort_file)) == version
risks = pq.read_table(output).to_pandas()
assert set(risks["horizonte_anios"]) == {0.5, 1.0, 1.5}
assert set(risks["pac_id"]) == set(range(1, N + 1)) | {245}
frame = read_cohort(cohort_file)
report = frame[(frame["tipo"] == "biopsia") & (frame["pac_id"] == 1)]["fecha"].iloc[0]
assert risks[risks["pac_id"] == 1]["fecha_indice"].iloc[0] == report
assert read_metadata(output)["desenlace"] == "muerte"
@pytest.fixture(scope="module")
def population_record(cohort_frame):
"""The `curvas` record the dataflow publishes for the 240 indexed members, with a small bootstrap to stay quick."""
config = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}}
dr = dataflow(*SCENARIO.modules, config=config)
return dr.execute(["population_curves"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["population_curves"]["curvas"]
def test_the_population_record_has_the_figures_curves_points_and_labels(population_record):
"""Pins down: the record the dashboard draws has the Kaplan-Meier with its band, the adjusted curve, both Weibull
curves, LR, HBN and combined points at 6, 12 and 18 months each with a 95 % interval, and the labels from the
settings. Fails if a curve or a series is missing, a curve rises, a band does not hold its curve, an interval is
inverted, or the labels stop coming from `[config.etiquetas]`."""
r = population_record
assert r["horizons_months"] == [6, 12, 18] and r["n"] == N + 1 and r["events"] > 20
km = r["km"]
assert km["months"][0] == 0 and km["S"][0] == 1.0 and np.all(np.diff(km["S"]) <= 1e-12)
assert all(lo <= s <= hi for lo, s, hi in zip(km["low"], km["S"], km["high"]))
for curve in (r["km_adjusted"]["S"], r["weibull"]["S"], r["weibull_fractional"]["S"]):
assert curve[0] == pytest.approx(1.0, abs=1e-6) and np.all(np.diff(curve) <= 1e-9)
assert set(r["points"]) == {"LR", "HBN", "COMB"}
for series in r["points"].values():
assert len(series["S"]) == 3 and all(0 <= lo <= hi <= 1 for lo, hi in zip(series["low"], series["high"]))
assert series["S"] == sorted(series["S"], reverse=True)
assert r["etiquetas"]["eje_x"] == CONFIG["etiquetas"]["eje_x"]
json.dumps(r)
def test_a_version_publishes_its_population_record(cohort_file, mlflow_tracking):
"""Pins down: training registers the `analisis/curvas.json` file with the version, and it is the record the dataflow
built. Fails if the saver stops logging a dataflow's `population`."""
from models.io.registry import registry
version = train(SCENARIO, CohortFile(cohort_file))
files = [f["path"] for f in registry.artifacts("cama", "survival", version)]
name, content = registry.artifact("cama", "survival", version, "analisis/curvas.json")
record = json.loads(content)
assert "analisis/curvas.json" in files and name == "curvas.json"
assert record["horizons_months"] == [6, 12, 18] and set(record["points"]) == {"LR", "HBN", "COMB"}
@pytest.fixture(scope="module")
def development_record(cohort_frame):
"""The `desarrollo` record the dataflow publishes for the 240 indexed members, with the smallest budget."""
config = {**CONFIG, "desarrollo": {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}}
dr = dataflow(*SCENARIO.modules, config=config)
return dr.execute(["development"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["development"]["desarrollo"]
def test_a_stage_that_cannot_run_on_the_cohort_is_recorded_and_does_not_stop_the_others(development_record):
"""Pins down: on a cohort whose covariates barely vary (the 240 members here) the SEER stages that need variation
publish their error in the record and the run still produces it, with every stage listed. Fails if one stage's
exception escapes the node, which would stop a version from training."""
assert [e["etapa"] for e in development_record["etapas"]] == ["01", "02", "03", "04", "05", "06"]
assert set(development_record["errores"]) <= {"01", "02", "03", "04", "05", "06"}
assert "Estadio_cat" in development_record["variables_no_disponibles"]
def test_the_development_stages_publish_their_tables_and_figures_on_a_varied_cohort():
"""Pins down: on 600 members with varied covariates all six SEER stages run and publish their tables and figures.
Fails if a stage errors on a cohort of this shape or stops writing what the dashboard reads."""
from models.cama.survival import development as dev
rng = np.random.default_rng(11)
n = 600
grade = rng.choice(["G1", "G2", "G3"], n, p=[0.2, 0.5, 0.3])
er = rng.choice(["POSITIVO", "NEGATIVO"], n, p=[0.7, 0.3])
risk = 0.03 * np.exp(1.0 * (grade == "G3") - 0.6 * (er == "POSITIVO"))
months = np.minimum(rng.exponential(1 / risk), 30).round()
members = pd.DataFrame({
"fecha_indice": pd.to_datetime("2024-01-01") + pd.to_timedelta(rng.integers(0, 540, n), unit="D"),
"months": months.astype(int), "event": rng.random(n) < 1 - np.exp(-risk * 24),
"age_years": rng.normal(58, 12, n).clip(25, 90), "size_mm": rng.integers(5, 70, n).astype(float),
"histologic_type": rng.choice(["8500/3", "8520/3"], n, p=[0.85, 0.15]), "grade": grade, "er": er,
"pr": rng.choice(["POSITIVO", "NEGATIVO"], n), "her2": rng.choice(["H0", "H1", "H2", "H3"], n),
"ki67_group": rng.choice(["<14", "14-19", "≥20"], n)})
members["months"] = np.where(members["event"], np.minimum(members["months"], 23), 24)
settings = {**CONFIG["desarrollo"], "null_perm": 5, "n_bootstrap": 4, "bootstrap_max_seconds": 30,
"proposals_max_seconds": 20, "restarts": 1, "n_splits_proposals": 2, "bootstrap_restarts": 2}
r = dev.development(members, settings)["desarrollo"]
assert r["errores"] == {}, r["errores"]
assert {"or_lr_balanceada", "hbn_arcos", "subgrupos_weibull", "prueba_edad"} <= set(r["tablas"])
arcs = r["tablas"]["hbn_arcos"]
assert arcs["columnas"] == list(arcs["filas"][0]) and len(arcs["columnas"]) > 1
assert r["figuras"] and all(isinstance(v, str) for v in r["figuras"].values())
def _stage_five_table(csv_path, survival):
"""The table of the SEER pipeline's stage 5 for the main curve (`sv_table`): its own nodes over a CSV of the cohort."""
from hamilton import driver
from models.cama.seer_survival import survival_curves
dr = driver.Builder().with_modules(survival_curves).build()
return dr.execute(["sv_table"], inputs={"depurated_csv": str(csv_path), "survival": survival})["sv_table"]
@pytest.fixture(scope="module")
def members_frame(cohort_frame):
"""The 240 indexed members, labelled (covariates, follow-up, death), as the figure's nodes take them."""
return dataflow(*SCENARIO.modules, config=SCENARIO.config).execute(
["labelled_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": LINEAGE})["labelled_members"]
def test_the_published_figure_is_the_seer_pipelines_stage_five_on_the_same_members(members_frame, tmp_path):
"""Pins down: the Kaplan-Meier curve, the adjusted curve, the stacking weights, the points of LR, HBN and their
combination and their bootstrap interval in the published record are those that `models.cama.seer_survival`'s own stage 5
(`run_survival`, on a CSV of the same members and the same settings) gives. Fails if the record's code path stops being
the pipeline's, which would make the dashboard's figure another model's."""
import dataclasses
from models.cama.survival import estimator
survival = {**CONFIG["survival"], "n_boot": 6, "ks_max_seconds": 5}
config = {**CONFIG, "survival": survival}
ours = dataflow(*SCENARIO.modules, config=config).execute(
["population_curves"], inputs={"source_cohort": pd.DataFrame(), "cohort_lineage": {}},
overrides={"labelled_members": members_frame})["population_curves"]["curvas"]
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
for name in estimator.FEATURES:
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
csv.to_csv(tmp_path / "depurado.csv", index=False)
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
for model in ("LR", "HBN", "COMB"):
rows = theirs[theirs["modelo"] == model]
assert ours["points"][model]["S"] == pytest.approx(rows["S"].tolist(), abs=1e-9)
assert ours["points"][model]["low"] == pytest.approx(rows["IC_inf"].tolist(), abs=1e-9)
assert ours["points"][model]["high"] == pytest.approx(rows["IC_sup"].tolist(), abs=1e-9)
km = theirs[theirs["modelo"] == "COMB"]
assert [ours["km"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_crudo"].tolist(), abs=1e-9)
assert [ours["km_adjusted"]["S"][m] for m in (6, 12, 18)] == pytest.approx(km["KM_ajustada"].tolist(), abs=1e-9)
def test_the_production_model_predicts_what_the_pipelines_points_say(members_frame, tmp_path):
"""Pins down: the `IntervalSurvival` a version in production is (the model that scores each patient) gives, averaged over
the members it was fitted on, the survival at each horizon that the pipeline's stage 5 gives for LR, HBN and their
combination, exactly (the same data, the same settings). Fails if the model that scores patients drifts from the model whose
figure is published."""
import dataclasses
from models.cama.survival import estimator
from models.cama.survival.estimator import IntervalSurvival
survival = {**CONFIG["survival"], "n_boot": 0}
model = IntervalSurvival(survival, tuple(h / 12 for h in survival["horizons"])).fit(
members_frame[estimator.FEATURES], members_frame[["months", "event"]])
mean_combined = model.survival_proba(members_frame[estimator.FEATURES]).mean(axis=0)
csv = pd.DataFrame({"Survival months": members_frame["months"].astype(int).astype(str),
"Vital status recode (study cutoff used)": members_frame["event"].map({True: "Dead", False: "Alive"})})
for name in estimator.FEATURES:
csv[f"{name}_cat"] = members_frame[name].fillna("NA").astype(str)
csv.to_csv(tmp_path / "depurado.csv", index=False)
fixed = tuple(f"{n}_cat" for n in survival["hbn_fixed_parents"])
luis = dataclasses.replace(estimator.survival_settings(survival), hbn_fixed_parents=fixed)
theirs = _stage_five_table(tmp_path / "depurado.csv", luis)
assert mean_combined == pytest.approx(theirs[theirs["modelo"] == "COMB"]["S"].tolist(), abs=1e-6)
@pytest.fixture(scope="module")
def production_model(members_frame):
"""A model fitted on the 240 members: what a version in production is when the dashboard scores a selection."""
return IntervalSurvival(CONFIG["survival"], tuple(h / 12 for h in CONFIG["survival"]["horizons"])).fit(
members_frame[FEATURES], members_frame[["months", "event"]])
def test_the_live_figure_scores_a_scenarios_members_with_the_production_model(members_frame, production_model, monkeypatch):
"""Pins down: the record of a scenario is for its members only (their count and deaths), its points are the model's mean
survival for them at the model's horizons with an interval around it, and nothing is refitted (the same scenario twice gives
the same record). Fails if the scenario's mask is ignored, or the scenario changes the model's horizons."""
from models.cama.survival import live
young = np.arange(len(members_frame)) < 120
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Primeras 120": young})
everyone = live.curves(SCENARIO, production_model, members_frame, None)
first = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
again = live.curves(SCENARIO, production_model, members_frame, "Primeras 120")
assert everyone["n"] == len(members_frame) and everyone["escenario"] == "Toda la cohorte" and everyone["horizons_months"] == [6, 12, 18]
assert first["n"] == 120 and first["escenario"] == "Primeras 120" and first["points"] == again["points"]
comb = first["points"]["COMB"]
assert all(lo <= s <= hi for lo, s, hi in zip(comb["low"], comb["S"], comb["high"]))
assert len(first["km_adjusted"]["S"]) == first["months_max"] + 1 and len(first["weibull_fractional"]["S"]) == len(first["weibull"]["S"])
def test_a_patient_sees_the_scenarios_she_belongs_to_or_the_whole_cohort(members_frame, monkeypatch):
"""Pins down: a patient's scenarios are those whose mask holds her and that have enough members to draw; in none, the whole
cohort; and a patient outside the cohort is refused. Fails if a scenario too small to draw is offered, or a patient in no
scenario is left with nothing."""
from models.cama.survival import live
first, last = int(members_frame["pac_id"].iloc[0]), int(members_frame["pac_id"].iloc[-1])
inside = np.arange(len(members_frame)) < 100
tiny = np.arange(len(members_frame)) < 3
monkeypatch.setattr(live, "scenario_masks", lambda labelled: {"Grande": inside, "Diminuto": tiny})
assert live.patient_scenarios(members_frame, first) == ["Grande"] # in both; the tiny one has too few to draw
assert live.patient_scenarios(members_frame, last) == ["Toda la cohorte"] # in neither
with pytest.raises(live.QueryError):
live.patient_scenarios(members_frame, 10**9)
def test_the_scenarios_use_the_hospitals_age_and_subtype_and_none_that_needs_a_stage(members_frame):
"""Pins down: the scenario masks use the age in years and a subtype derived from the receptors (hormone receptors and
HER2 3+ / 0-1+), and a scenario that needs the stage or the surgery, which the hospital does not report, has no member.
Fails if a stage scenario includes everyone, or the subtype ignores the receptors."""
from models.cama.seer_survival import scenarios
from models.cama.survival import live
n = len(members_frame)
frame = members_frame.assign(er=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "POSITIVO"], n),
pr=np.resize(["POSITIVO", "NEGATIVO", "NEGATIVO", "NEGATIVO"], n),
her2=np.resize(["H1", "H3", "H0", "H2"], n))
found = live.molecular_subtype(frame).iloc[:4].tolist()
masks = live.scenario_masks(frame)
assert found == ["HR+/HER2-", "HR-/HER2+", "HR-/HER2-", "Desconocido"] # HER2 2+ is equivocal: unknown
assert set(masks) == set(scenarios.SCENARIOS)
assert not masks["Estadio IV"].any() and not masks["Triple negativo (HR−/HER2−) · estadio 0–II"].any()
@pytest.mark.parametrize("name", ["No existe", "Estadio IV"])
def test_a_scenario_that_cannot_be_answered_says_why(members_frame, production_model, name):
"""Pins down: an unknown scenario and one with too few members to say anything (every stage scenario, with the stage not
reported) are each a `QueryError` with a message. Fails if either runs and draws a meaningless figure or fails with an
unreadable error."""
from models.cama.survival import live
with pytest.raises(live.QueryError):
live.curves(SCENARIO, production_model, members_frame, name)
def test_the_monthly_curve_passes_through_the_horizons_and_never_rises():
"""Pins down: the month-by-month survival equals the model's at each horizon, starts at 1, never rises, and goes on past
the last horizon at the last interval's rate. Fails if the interpolation misses a horizon or the curve can go up."""
from models.cama.survival import live
curve = live.monthly(np.array([[0.9, 0.8, 0.6]]), [6, 12, 18], 24)[0]
assert curve[0] == 1.0 and curve[6] == pytest.approx(0.9) and curve[12] == pytest.approx(0.8) and curve[18] == pytest.approx(0.6)
assert (np.diff(curve) <= 1e-12).all() and curve[24] < curve[18]
def test_a_saved_model_whose_class_is_older_still_scores_with_the_current_code(members_frame, production_model):
"""Pins down: the fitted state of a model, put in an object of a class without the current methods (what loading a saved
model from before a code change gives), scores the same as the model itself once rehydrated. Fails if the live figure
depends on the class a version was saved with, which makes every older version unusable after a change."""
from types import SimpleNamespace
from models.cama.survival import live
stale = SimpleNamespace(**production_model.__dict__)
again = live.rehydrate(stale).component_survival(members_frame[FEATURES])
for name, expected in production_model.component_survival(members_frame[FEATURES]).items():
assert again[name] == pytest.approx(expected)
+13 -20
View File
@@ -21,7 +21,7 @@ def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_track
with pytest.raises(PromotionBlocked) as blocked:
registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01a", "ML-01b"}
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
@@ -57,28 +57,21 @@ def test_lineage_lists_every_stored_file_and_each_routine_record(production_read
assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8}
def test_promotion_needs_the_model_the_training_run_itself_saved(governance_db, cacu_db, mlflow_tracking):
"""A run that saved no model is not promoted, whatever else is in order. Fails if the ML-01b check stops requiring
`modelo_sha`."""
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=None, model=False)
@pytest.mark.parametrize("routines, model, failing", [
([ArtifactKind.MUESTREO], True, "ML-01a"),
(None, False, "ML-01b"),
])
def test_promotion_needs_what_the_training_run_itself_recorded(governance_db, cacu_db, mlflow_tracking, routines, model,
failing):
"""A run that skipped routine records, or saved no model, is not promoted, whatever else is in order. Fails if
the ML-01a check stops requiring every kind in `ROUTINE_KINDS` or the ML-01b check stops requiring `modelo_sha`."""
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=routines, model=model)
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
interpretability_report_uri="i")
failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed]
assert [check.code for check in failed] == ["ML-01b"]
@pytest.mark.parametrize("routines, recorded", [([], "0 de 5"), ([ArtifactKind.MUESTREO], "1 de 5 (MUESTREO)")])
def test_the_training_run_is_the_registered_routine_and_its_records_are_reported(governance_db, cacu_db,
mlflow_tracking, routines, recorded):
"""ML-01a: the version's training run is the registered routine, so a model without some routine records (a
prevalence-incidence mixture has no class balance) can still be promoted; the check reports which records the
run holds. Fails if ML-01a goes back to requiring every kind in `ROUTINE_KINDS`, or stops reporting them."""
run = trained_run("cacu", "parcial", armado("huella-x"), {"auc": 0.8}, routines=routines, model=True)
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
interpretability_report_uri="i")
checks = {check.code: check for check in registry.checks("cacu", "parcial", version)}
assert checks["ML-01a"].passed and recorded in checks["ML-01a"].detail
assert all(check.passed for check in checks.values())
assert [check.code for check in failed] == [failing]
if failing == "ML-01a":
assert "DATOS_FALTANTES" in failed[0].detail
def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready):
-21
View File
@@ -1,21 +0,0 @@
"""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
@@ -1,36 +0,0 @@
"""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)