diff --git a/README.md b/README.md index bb63029..5dfd432 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ WebApi. | `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_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). The death is the timeline's `defuncion` event, which CaCu's dbt timeline doesn't emit yet. | | `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `/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-[-]`): 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-[-]` 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. | diff --git a/models/cacu/survival/__init__.py b/models/cacu/survival/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/models/cacu/survival/estimator.py b/models/cacu/survival/estimator.py new file mode 100644 index 0000000..4468266 --- /dev/null +++ b/models/cacu/survival/estimator.py @@ -0,0 +1,156 @@ +"""What the CaCu survival model is made of: the member table a build's events give, and the interval survival estimator. + +`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index +and rules leave get their covariates and the index date; the rest keep their row, empty. The index is the diagnosis +(provisionally the first biopsy reported as invasive carcinoma) and the covariates are the member's most recent +observations up to it: her age group at the index, the cytology of her latest sample (KPNC's categories, the more severe +of its squamous and glandular results) and her latest HPV result. `IntervalSurvival` is CaMa's +(`models.cama.survival.estimator`): per interval of `survival.horizons`, a logistic regression and a Bayesian network +with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`), stacked with +out-of-sample weights; a patient's survival to each horizon is the product of the intervals'. + +DUPLICATED (issue #9): `encode`, `interval_cohort` and `IntervalSurvival` are CaMa's with the covariates as `FEATURES` +of this module instead of CaMa's; CaMa's read its own `FEATURES` as a module constant, so they can't be reused without +changing CaMa. The outcome (`outcome_table`) and the settings (`survival_settings`) are CaMa's, imported. +""" + +import json + +import numpy as np +import pandas as pd +from sklearn.base import BaseEstimator, TransformerMixin + +from models.cama.seer_survival import survival_models as sm +from models.cama.survival.estimator import EPOCH, INDEX_COLUMN, UNKNOWN, WINDOW_KEYS, _band, survival_settings +from models.io.contracts import DAYS_PER_YEAR +from models.steps import indexing + +FEATURES = ["age_group", "cytology", "hpv"] +NUMERIC = ["age_years"] # the age before banding + + +def _latest_cytology(prior: pd.DataFrame, cytology: dict) -> pd.Series: + """Per `pac_id`, KPNC's category of her latest cytology sample: the more severe of its squamous and glandular + results; None when no result falls in a category.""" + severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values} + results = prior[prior["tipo"].isin(["bethesda", "glandular"]) & prior["valor_codigo"].notna()] + latest = results[results["fecha"] == results.groupby("pac_id")["fecha"].transform("max")] + ranks = latest["valor_codigo"].map(severity).groupby(latest["pac_id"]).max() + names = list(cytology) + return ranks.map(lambda rank: None if pd.isna(rank) else names[int(rank)]) + + +def member_table(cohort: pd.DataFrame, age_cuts: list, cytology: dict) -> pd.DataFrame: + """One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice`, the covariates in `FEATURES` and the + age in years. Each covariate is the member's most recent observation up to the index (the index day included): her + age at the index from her `nacimiento`, her latest cytology sample's category (`_latest_cytology`) and her latest HPV + result; empty where the build has none.""" + frame = cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"])) + members = frame.groupby("pac_id")["fecha_indice"].first().to_frame() + birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index) + members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR + members["age_group"] = _band(members["age_years"], age_cuts) + prior = frame[frame["fecha"] <= frame["fecha_indice"]] + members["cytology"] = _latest_cytology(prior, cytology).reindex(members.index).astype(object) + hpv = prior[(prior["tipo"] == "vph") & prior["valor_codigo"].notna()].sort_values(["fecha", "fuente_id"]) + members["hpv"] = hpv.groupby("pac_id")["valor_codigo"].last().reindex(members.index) + members = members.astype({"cytology": object, "hpv": object}) + return members[["fecha_indice", *FEATURES, *NUMERIC]] + + +def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None): + """CaMa's `encode` over this module's `FEATURES` (DUPLICATED, issue #9): `(X_dum, X_int, categories, dummy_columns)`. + With no `categories` they are learned from `frame`; with them, a value the fit never saw takes the unknown + category.""" + frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str) + if categories is None: + dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns) + categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES} + columns = [] + for name in FEATURES: + codes = pd.Categorical(frame[name], categories=categories[name]).codes + fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0 + columns.append(np.where(codes < 0, fallback, codes)) + X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32) + return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns + + +def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings): + """CaMa's `interval_cohort` over this module's `FEATURES` (DUPLICATED, issue #9).""" + X_dum, X_int, categories, dummy_columns = encode(features) + cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int, + X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings)) + return cohort, categories, dummy_columns + + +class MemberFeatures(TransformerMixin, BaseEstimator): + """A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`, + the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing.""" + + def __init__(self, index=None, window=None, age_cuts=(35, 45, 55), cytology=None): + self.index = index + self.window = window + self.age_cuts = age_cuts + self.cytology = cytology + + def fit(self, X, y=None): + return self + + def transform(self, X: pd.DataFrame) -> pd.DataFrame: + everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id") + indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index) + table = member_table(indexed, list(self.age_cuts), self.cytology) \ + if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC]) + table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN}) + return table[[*FEATURES, INDEX_COLUMN]] + + +class IntervalSurvival(BaseEstimator): + """CaMa's `IntervalSurvival` over this module's `FEATURES` (DUPLICATED, issue #9): per interval, LR and HBN stacked; + the survival to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with + `months` and `event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With + `INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member + without one) and her mortality is empty too.""" + + def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0)): + self.survival = survival + self.horizons_years = horizons_years + + def fit(self, X: pd.DataFrame, y: pd.DataFrame): + s = survival_settings(self.survival) + if [h / 12 for h in s.horizons] != list(self.horizons_years): + raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ") + cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s) + everyone = np.arange(len(X)) + if s.combine_active and len(X) >= 2 * s.stack_folds: + weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X))) + self.weights_ = weights["w_LR"].to_numpy() + self.stacking_ = weights.to_dict("records") + else: + self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), [] + self.fitted_ = sm.fit_intervals(cohort, s, everyone, None) + self.levels_ = cohort.levels + return self + + def interval_proba(self, X: pd.DataFrame) -> np.ndarray: + """Each member's probability of surviving each interval, given she is alive at its start.""" + X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_) + P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_) + return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb + + def survival_proba(self, X: pd.DataFrame) -> np.ndarray: + """Each member's survival to each horizon.""" + return np.cumprod(self.interval_proba(X), axis=1) + + def predict_proba(self, X: pd.DataFrame) -> np.ndarray: + mortality = 1.0 - self.survival_proba(X) + if INDEX_COLUMN not in X.columns: + return mortality + dates = pd.to_datetime(X[INDEX_COLUMN]) + member = dates.notna().to_numpy() + mortality[~member] = np.nan + return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality]) + + +__all__ = ["FEATURES", "INDEX_COLUMN", "IntervalSurvival", "MemberFeatures", "WINDOW_KEYS", "encode", "interval_cohort", + "member_table"] diff --git a/models/cacu/survival/model.py b/models/cacu/survival/model.py new file mode 100644 index 0000000..6f810ed --- /dev/null +++ b/models/cacu/survival/model.py @@ -0,0 +1,150 @@ +"""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 +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_]} + + +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)]) diff --git a/models/cacu/survival/model.toml b/models/cacu/survival/model.toml new file mode 100644 index 0000000..c5de318 --- /dev/null +++ b/models/cacu/survival/model.toml @@ -0,0 +1,86 @@ +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.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"] diff --git a/models/cacu/survival/population.py b/models/cacu/survival/population.py new file mode 100644 index 0000000..a02cf19 --- /dev/null +++ b/models/cacu/survival/population.py @@ -0,0 +1,86 @@ +"""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) -> dict: + """What the saver publishes under `analisis/`: the curves only (CaMa adds its SEER development stages, which need + covariates CaCu doesn't have).""" + return population_curves diff --git a/tests/cacu/test_cacu_survival.py b/tests/cacu/test_cacu_survival.py new file mode 100644 index 0000000..32c3798 --- /dev/null +++ b/tests/cacu/test_cacu_survival.py @@ -0,0 +1,223 @@ +"""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"} + assert optional == {"calibration_bins"} # `index` is required: the registered model re-indexes a build with it + + +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 + assert "analisis/curvas.json" in [f["path"] for f in registry.artifacts("cacu", "survival", version)] + 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"