diff --git a/models/cacu/cin2_logistic/model.py b/models/cacu/cin2_logistic/model.py index e6aa402..15339b4 100644 --- a/models/cacu/cin2_logistic/model.py +++ b/models/cacu/cin2_logistic/model.py @@ -101,9 +101,11 @@ def _dates(frame: pd.DataFrame) -> dict: def sampling(windowed_outcomes: pd.DataFrame, train_set: pd.DataFrame, test_set: pd.DataFrame, - train_fraction: float) -> dict: - """MUESTREO: who could be used, and how they were split.""" + train_fraction: float, index_attrition: list, prior_observation: dict) -> 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, "members": len(windowed_outcomes), "left_out_unknown_outcome": int((~windowed_outcomes["known"]).sum()), "train": _dates(train_set), "test": _dates(test_set)} diff --git a/models/cacu/cin2_logistic/model.toml b/models/cacu/cin2_logistic/model.toml index d0c00f6..b88a73c 100644 --- a/models/cacu/cin2_logistic/model.toml +++ b/models/cacu/cin2_logistic/model.toml @@ -5,7 +5,7 @@ outcome = "cin2_12m" # 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_logistic.model", "models.steps.model_fitting"] +modules = ["models.cacu.cin2_logistic.model", "models.steps.model_fitting", "models.steps.indexing"] description = """ Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \ a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \ @@ -21,3 +21,13 @@ predictor_columns = ["bethesda", "vph", "vph_16_18"] # window leaves no member with a complete window; 1 year leaves 5,231 known members, 162 with the event. horizons_years = [1.0] event_grades = ["LIEAG", "CIS", "CARCINOMA"] + +# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance +# cohort, applied in the pipeline. The recruitment window is the source cohort's. +[config.index] +kind = "primera_citologia" +event_grades = ["LIEAG", "CIS", "CARCINOMA"] + +# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded; +# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20). +observacion_previa_minima_dias = 0 \ No newline at end of file diff --git a/models/cacu/cin2_pim/model.toml b/models/cacu/cin2_pim/model.toml index fbddbe0..23e6191 100644 --- a/models/cacu/cin2_pim/model.toml +++ b/models/cacu/cin2_pim/model.toml @@ -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"] +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 \ @@ -38,6 +38,15 @@ history = {} # KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and # the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma # has no KPNC row: it goes with the high-grade and malignant results. +# The scenario's index and rules, over its source cohort (models/steps/indexing.py): the same as dbt's surveillance +# cohort, applied in the pipeline. The recruitment window is the source cohort's. +[config.index] +kind = "primera_citologia" +event_grades = ["LIEAG", "CIS", "CARCINOMA"] +# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded; +# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20). +observacion_previa_minima_dias = 0 + [config.cytology] NILM = ["NORMAL"] ASC-US = ["ASC-US"] diff --git a/models/cacu/cin2_pim_post_colposcopy/model.toml b/models/cacu/cin2_pim_post_colposcopy/model.toml index 290a106..cfb2378 100644 --- a/models/cacu/cin2_pim_post_colposcopy/model.toml +++ b/models/cacu/cin2_pim_post_colposcopy/model.toml @@ -1,10 +1,10 @@ domain = "cacu" scenario = "cin2_pim_post_colposcopy" -cohort = "cacu/cohorte_post_colposcopia_visita_1" +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"] +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 \ @@ -26,6 +26,20 @@ strata = ["referral_grade"] incidence_features = ["cytology", "hpv_positive"] # KPNC groups the post-colposcopy cytology in three: NILM, ASC-US/LSIL and high grade (ASC-H, AGC, HSIL+). +# The scenario's index and rules over the total cohort (models/steps/indexing.py), the same as dbt's +# cacu/cohorte_post_colposcopia_visita_1 (Cheung et al. 2020): the first surveillance visit with a cotest after the +# first colposcopy's result, before any later colposcopy. PROVISIONAL: a colposcopy without a biopsy order is below +# CIN2. The recruitment window is the source cohort's (the surveillance cohort's). +[config.index] +kind = "post_colposcopia" +visita = 1 +event_grades = ["LIEAG", "CIS", "CARCINOMA"] +referral_lookback_days = 365 +hysterectomy_cie = ["Z907"] +# PROVISIONAL (sin_definir): the data are left-truncated, so rules on earlier events read only what was recorded; +# 0 keeps everyone. Raise it once the population starts with enough history (S-CPS-20). +observacion_previa_minima_dias = 0 + [config.cytology] NILM = ["NORMAL"] "ASC-US/LSIL" = ["ASC-US", "LIEBG"] diff --git a/models/dags/training.py b/models/dags/training.py index 79666e8..57e810e 100644 --- a/models/dags/training.py +++ b/models/dags/training.py @@ -117,7 +117,8 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> plain = dataflow(*scenario.modules, config=scenario.config) required, _ = external_inputs(plain) loaders = [loader(target=target, source=source) for target, loader in - (("cohort", from_.cohort_source), ("cohort_lineage", from_.cohort_source_lineage)) + (("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source), + ("cohort_lineage", from_.cohort_source_lineage)) if target in required] produced = {v.name for v in plain.list_available_variables() if not v.is_external_input} saver = to.registered_model(id=REGISTERED_MODEL, dependencies=sorted(SAVED & produced), diff --git a/models/io/storage.py b/models/io/storage.py index 5e046e9..cc26d4a 100644 --- a/models/io/storage.py +++ b/models/io/storage.py @@ -354,6 +354,7 @@ class KitBuild: return {"url": build.url, "version": build.version, "armado_id": str(build.armado_id), "producer": "kit", "datos_as_of": build.datos_as_of.isoformat(), "n_members": str(build.n_miembros), "known_until": self.known_until().isoformat() if self.known_until() else "", + "parametros": getattr(getattr(self.cohorts, "get", lambda _: None)(self.build_id), "parametros", None) or "{}", "read_at": datetime.now(timezone.utc).isoformat()} def reference(self) -> dict[str, str]: diff --git a/models/steps/indexing.py b/models/steps/indexing.py new file mode 100644 index 0000000..97bc523 --- /dev/null +++ b/models/steps/indexing.py @@ -0,0 +1,195 @@ +"""Each scenario's index and its rules, over a cohort's long frame (`COHORT_SCHEMA`), usually `cacu/cohorte_total`. + +A cohort gives every patient's events; a scenario says from when it predicts (the index) and who is out given that +index. `[config.index]` of its `model.toml` names the kind and its rules. A scenario that lists this module gets its +source cohort as `source_cohort`; the node `cohort` gives that frame re-indexed (`fecha_indice` is the scenario's) +with only the members left, and `index_attrition` how many each step leaves. The recruitment window is the source +cohort's (its build's parameters), unless the config sets one. The rules are dbt's (`Transformation/models/cacu/cohorts/`, `macros/cacu_post_colposcopy.sql`), in the same +order and with the same names, so the two can be compared before either is retired. + +Kinds: + +- `primera_citologia` (surveillance): the first cytology sample, if it falls in the window; out: a biopsy with the + outcome before the index (`prior_event`), an index sample with no cytology or HPV result (`no_index_result`). +- `post_colposcopia` (visit `visita`): the first colposcopy's episode, its result known at the last report of the + biopsies ordered that day (PROVISIONAL: without a biopsy order it is below CIN2, which assumes the colposcopic + impression misses no CIN2+); index at that result (`visita = 0`) or at the k-th cytology sample after it, before any + later colposcopy; out, in order: `biopsia_sin_resultado`, `cin2_hasta_el_indice`, `antecedente_cacu`, + `histerectomia`, `tratamiento_previo`, `sin_referencia`, `sin_cotest` (k ≥ 1). + +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 +"none before" means "none observed". The rules are kept as written; raising the threshold when the population starts +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). + +A scenario without `[config.index]` keeps its cohort's own index. +""" + +import json +from collections import defaultdict +from datetime import date + +import pandas as pd + +RESULT_TYPES = ("bethesda", "glandular", "vph") +POST_COLPOSCOPY_RULES = ("biopsia_sin_resultado", "cin2_hasta_el_indice", "antecedente_cacu", "histerectomia", + "tratamiento_previo", "sin_referencia", "sin_cotest") + + +def _key(e: dict) -> tuple: + return e["fuente_tabla"], e["fuente_id"] + + +def _in_window(fecha: date, index: dict) -> bool: + start, end = index.get("recruitment_start"), index.get("recruitment_end") + return (start is None or fecha >= date.fromisoformat(start)) and (end is None or fecha < date.fromisoformat(end)) + + +def _results(events: list[dict], sample: dict) -> dict: + """The sample's Bethesda, glandular and HPV codes (first non-null of each).""" + return {t: next((e["valor_codigo"] for e in events if e["tipo"] == t and _key(e) == _key(sample) + and e["valor_codigo"] is not None), None) for t in RESULT_TYPES} + + +def _first_cytology(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]: + """The surveillance index and, per rule, whether it flags the patient.""" + samples = sorted((e for e in events if e["tipo"] == "citologia"), key=lambda e: (e["fecha"], e["fuente_id"])) + if not samples or not _in_window(samples[0]["fecha"], index): + return None, [] + sample, grades = samples[0], set(index["event_grades"]) + found = _results(events, sample) + return sample["fecha"], [ + ("prior_event", any(e["tipo"] == "biopsia" and e["fecha"] < sample["fecha"] and e["valor_codigo"] in grades + for e in events)), + ("no_index_result", all(v is None for v in found.values())), + ] + + +def _colposcopy_episode(events: list[dict]) -> dict | None: + """The first colposcopy, when its result is known and how many of that day's biopsy orders have no report.""" + colposcopies = sorted((e for e in events if e["tipo"] == "colposcopia"), + key=lambda e: (e["fecha"], e["fuente_tabla"], e["fuente_id"])) + if not colposcopies: + return None + first = colposcopies[0] + orders = {_key(e) for e in events if e["tipo"] == "orden_biopsia" and e["fecha"] == first["fecha"]} + reports = [e for e in events if e["tipo"] == "biopsia" and _key(e) in orders] + return {"colposcopy": first, "result_date": max((e["fecha"] for e in reports), default=first["fecha"]), + "unreported_orders": len(orders - {_key(e) for e in reports})} + + +def _surveillance_visits(events: list[dict], episode: dict) -> list[dict]: + """The cytology samples after the colposcopy's result is known, before any later colposcopy, in order.""" + result = episode["result_date"] + closing = min((e["fecha"] for e in events if e["tipo"] == "colposcopia" and e["fecha"] > result), default=None) + return sorted((e for e in events if e["tipo"] == "citologia" and e["fecha"] > result + and (closing is None or e["fecha"] < closing)), key=lambda e: (e["fecha"], e["fuente_id"])) + + +def _post_colposcopy(events: list[dict], index: dict) -> tuple[date | None, list[tuple[str, bool]]]: + """The index of visit `index["visita"]` and, per rule, whether it flags the patient.""" + k = int(index["visita"]) + episode = _colposcopy_episode(events) + if episode is None: + return None, [] + if k == 0: + sample, fecha = None, episode["result_date"] + else: + visits = _surveillance_visits(events, episode) + if len(visits) < k: + return None, [] + sample, fecha = visits[k - 1], visits[k - 1]["fecha"] + if not _in_window(fecha, index): + return None, [] + grades, hysterectomy = set(index["event_grades"]), set(index["hysterectomy_cie"]) + colposcopy, lookback = episode["colposcopy"]["fecha"], int(index["referral_lookback_days"]) + + def up_to(test): + return any(e["fecha"] <= fecha and test(e) for e in events) + + flags = [ + ("biopsia_sin_resultado", episode["unreported_orders"] > 0), + ("cin2_hasta_el_indice", up_to(lambda e: e["tipo"] == "biopsia" and e["valor_codigo"] in grades)), + ("antecedente_cacu", up_to(lambda e: e["tipo"] == "antecedente")), + ("histerectomia", up_to(lambda e: e["tipo"] == "nota_medica" and e["valor_codigo"] in hysterectomy)), + ("tratamiento_previo", up_to(lambda e: e["tipo"] == "tratamiento")), + ("sin_referencia", not any(e["tipo"] in RESULT_TYPES and e["valor_codigo"] is not None + and 0 <= (colposcopy - e["fecha"]).days <= lookback for e in events)), + ] + if k >= 1: + found = _results(events, sample) + flags.append(("sin_cotest", found["vph"] is None or (found["bethesda"] is None and found["glandular"] is None))) + return fecha, flags + + +KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposcopy} + + +def _events(cohort: pd.DataFrame) -> dict[int, list[dict]]: + events = defaultdict(list) + for e in cohort.to_dict("records"): + events[int(e["pac_id"])].append(e) + return events + + +def _prior_days(rows: list[dict], fecha: date) -> int: + """Days observed before the index: from the patient's first event in the frame.""" + return (fecha - min(e["fecha"] for e in rows)).days + + +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.""" + rule, minimum = KINDS[index["kind"]], int(index.get("observacion_previa_minima_dias", 0)) + events = _events(cohort) + found = {} + for pac_id, rows in sorted(events.items()): + fecha, flags = rule(rows, index) + if fecha is not None: + flags = [*flags, ("observacion_previa_insuficiente", _prior_days(rows, fecha) < minimum)] + found[pac_id] = (fecha, flags) + left = {pac_id: flags for pac_id, (fecha, flags) in found.items() if fecha is not None} + attrition = [("pacientes", len(found)), ("indexed", len(left))] + names = [name for name, _ in next(iter(left.values()), [])] + for position, name in enumerate(names): + left = {pac_id: flags for pac_id, flags in left.items() if not flags[position][1]} + attrition.append((name, len(left))) + members = pd.DataFrame([(pac_id, found[pac_id][0]) for pac_id in left], columns=["pac_id", "fecha_indice"]) + return members, attrition + + +def _with_window(cohort_lineage: dict, index: dict) -> dict: + """The index config with the source cohort's recruitment window (its build's `parametros`), unless the config + sets its own: the window lives once, in the cohort's dbt vars.""" + parameters = json.loads(cohort_lineage.get("parametros") or "{}") + return {**{k: parameters[k] for k in ("recruitment_start", "recruitment_end") if k in parameters}, **index} + + +def cohort(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> pd.DataFrame: + """The source cohort's long frame re-indexed by the scenario (`[config.index]`): only its members, each with the + scenario's `fecha_indice`. Without an index config, the source cohort as it is.""" + if not index: + return source_cohort + members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index)) + return (source_cohort.drop(columns="fecha_indice").merge(members, on="pac_id")[list(source_cohort.columns)] + .reset_index(drop=True)) + + +def index_attrition(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> list: + """How many are left after the scenario's index and each of its rules; empty without an index config.""" + return _indexed_members(source_cohort, _with_window(cohort_lineage, index))[1] if index else [] + + +def prior_observation(source_cohort: pd.DataFrame, cohort_lineage: dict, index: dict | None = None) -> dict: + """How much history the scenario's members had before their index (aggregates only): how many, how many with + under a year, and the median days. Shows the weight of left truncation while the threshold is 0.""" + if not index: + return {} + members, _ = _indexed_members(source_cohort, _with_window(cohort_lineage, index)) + 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()), + "median_days": None if days.empty else float(days.median()), + "threshold_days": int(index.get("observacion_previa_minima_dias", 0))} diff --git a/tests/cacu/test_cin2_logistic.py b/tests/cacu/test_cin2_logistic.py index c36c539..ce1b921 100644 --- a/tests/cacu/test_cin2_logistic.py +++ b/tests/cacu/test_cin2_logistic.py @@ -151,13 +151,13 @@ def test_split_trains_on_the_oldest_index_dates(cohort_frame): def test_the_graph_takes_exactly_its_config_and_the_cohort(): - """Pins down the driver's external inputs: the loaders' `cohort` and `cohort_lineage` and the config's keys, and + """Pins down the driver's external inputs: the loaders' `source_cohort` (re-indexed into `cohort` by the scenario's index) 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 node) and becomes an input, or a module added to the driver rewires a parameter.""" required, optional = training.external_inputs(dataflow(*SCENARIO.modules, config=CONFIG)) - assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"} - assert optional == {"calibration_bins", "classifier", "max_iter", "split_order", "target_column"} + assert required == {"source_cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"} + assert optional == {"calibration_bins", "classifier", "index", "max_iter", "split_order", "target_column"} def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame): @@ -168,7 +168,7 @@ def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame): lineage = {"datos_as_of": CUTOFF.isoformat()} found = dataflow(*SCENARIO.modules, config=CONFIG).execute( ["metrics", "fitted_model", "test_set", "test_probabilities"], - inputs={"cohort": cohort_frame, "cohort_lineage": lineage}) + inputs={"source_cohort": cohort_frame, "cohort_lineage": lineage}) assert found["metrics"]["n_train"] == 14 and found["metrics"]["n_test"] == 6 probabilities = found["fitted_model"].predict_proba(cohort_frame) diff --git a/tests/cacu/test_cin2_pim.py b/tests/cacu/test_cin2_pim.py index b4353a3..b1027ff 100644 --- a/tests/cacu/test_cin2_pim.py +++ b/tests/cacu/test_cin2_pim.py @@ -28,19 +28,22 @@ SCENARIO = training.Scenario.load("cacu", "cin2_pim") CONFIG = SCENARIO.config -def _row(pac_id, index, days, tipo, valor=None): +def _row(pac_id, index, days, tipo, valor=None, sample=None): return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days), "conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "medicion", "tipo": tipo, "codigo": tipo, "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": "t", - "fuente_id": f"{pac_id}-{tipo}-{days}"} + "fuente_id": sample or f"{pac_id}-{tipo}-{days}"} -def _visit(pac_id, index, day, bethesda, vph): - return [_row(pac_id, index, day, "bethesda", bethesda), _row(pac_id, index, day, "vph", vph)] +def _visit(pac_id, index, day, bethesda, vph, sample=None): + return [_row(pac_id, index, day, "bethesda", bethesda, sample), _row(pac_id, index, day, "vph", vph, sample)] def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()): - rows = [_row(pac_id, index, 0, "citologia"), *_visit(pac_id, index, 7, bethesda, vph)] + """The index sample (its Bethesda and HPV results share its source row, as in the timeline), later visits and + biopsies.""" + sample = f"S{pac_id}" + rows = [_row(pac_id, index, 0, "citologia", sample=sample), *_visit(pac_id, index, 7, bethesda, vph, sample)] rows += [row for day, b, v in visits for row in _visit(pac_id, index, day, b, v)] return rows + [_row(pac_id, index, day, "biopsia", grade) for day, grade in biopsies] @@ -150,15 +153,15 @@ def test_patient_6_referred_and_lost_carries_no_information(): def test_the_graph_takes_exactly_its_config_and_the_cohort(): - """Pins down the driver's external inputs: the loader's `cohort` and the config's keys, and - nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input, + """Pins down the driver's external inputs: the loaders' `source_cohort` and `cohort_lineage` (the scenario's index + re-indexes the first into `cohort`) and the config's keys, and nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input, or a module added to the driver rewires a parameter.""" required, optional = training.external_inputs(training.dataflow(*SCENARIO.modules, config=CONFIG)) - assert required == {"cohort", "cytology", "event_grades", "history", "horizons_years", "incidence", + assert required == {"source_cohort", "cohort_lineage", "cytology", "event_grades", "history", "horizons_years", "incidence", "incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata", "train_fraction"} - assert optional == set() + 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): @@ -166,7 +169,7 @@ def test_the_dataflow_gives_metrics_at_every_horizon(cohort_frame): rate at the index visit is near the observed one. Fails if a horizon is dropped, a metric isn't a number, or the fit stops recovering the prevalence.""" found = training.dataflow(*SCENARIO.modules, config=CONFIG).execute( - ["metrics"], inputs={"cohort": cohort_frame})["metrics"] + ["metrics"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["metrics"] assert found["n_train"] == 210 and found["n_test"] == 90 assert {f"n_known_{h:g}y" for h in CONFIG["horizons_years"]} <= set(found) @@ -202,7 +205,7 @@ def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort """Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN (not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up.""" members = training.dataflow(*SCENARIO.modules, config=CONFIG).execute( - ["interval_coded_members"], inputs={"cohort": cohort_frame})["interval_coded_members"] + ["interval_coded_members"], inputs={"source_cohort": cohort_frame, "cohort_lineage": {}})["interval_coded_members"] only_negative = members[members["hpv_positive"] == 0] mixture = model.PrevalenceIncidenceMixture(CONFIG["horizons_years"], ("cytology",), ("hpv_positive",), CONFIG["incidence"], {"cytology": list(CONFIG["cytology"])}).fit( @@ -271,7 +274,7 @@ def test_the_post_colposcopy_scenario_runs_on_the_shared_dataflow(cohort_frame): frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names) found = training.dataflow(*POST_COLPOSCOPY.modules, config=POST_COLPOSCOPY.config).execute( - ["metrics"], inputs={"cohort": frame})["metrics"] + ["metrics"], inputs={"source_cohort": frame, "cohort_lineage": {}})["metrics"] 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" diff --git a/tests/test_indexing.py b/tests/test_indexing.py new file mode 100644 index 0000000..1417643 --- /dev/null +++ b/tests/test_indexing.py @@ -0,0 +1,184 @@ +"""What this module covers: `models.steps.indexing`, each scenario's index and rules over a cohort's long frame: the +surveillance index, the post-colposcopy episode, its numbered visits, the index of each visit, each rule in its order +and the attrition, the re-indexed frame and the recruitment window taken from the source cohort. The cases are those +of dbt's unit tests (`cacu_post_colposcopy.yml`, `cacu_surveillance.yml`), which the pipeline must match. + +Fixtures: none; each test builds its rows with `_row`. +""" + +import json +from datetime import date, timedelta + +import pandas as pd +import pytest + +from models.io.contracts import COHORT_SCHEMA +from models.steps import indexing + +RULES = {"event_grades": ["LIEAG", "CIS", "CARCINOMA"], "referral_lookback_days": 365, "hysterectomy_cie": ["Z907"]} +COLPOSCOPY = date(2025, 1, 10) + + +def _row(pac_id, tipo, fecha, valor=None, fuente_id="a", fuente_tabla="t"): + return {"pac_id": pac_id, "fecha_indice": date(2020, 1, 1), "fecha": fecha, "conocida_en": None, "clase": "x", + "tipo": tipo, "codigo": tipo, "valor_codigo": valor, "valor_numerico": None, "fuente_tabla": fuente_tabla, + "fuente_id": f"{pac_id}{fuente_id}"} + + +def _after(days): + return COLPOSCOPY + timedelta(days=days) + + +def _visit(pac_id, days, name, hpv="NEGATIVO", pap="NORMAL"): + rows = [_row(pac_id, "citologia", _after(days), fuente_id=name)] + rows += [_row(pac_id, "vph", _after(days + 10), hpv, fuente_id=name)] if hpv else [] + return rows + ([_row(pac_id, "bethesda", _after(days + 12), pap, fuente_id=name)] if pap else []) + + +def _patient(pac_id, *extra, referral=True, biopsy="LIEBG"): + """A referral 30 days before the colposcopy, a biopsy ordered there and reported 20 days later (`biopsy`; None: + none ordered) and cotest visits at 200 and 560 days.""" + rows = [_row(pac_id, "colposcopia", COLPOSCOPY, fuente_id="c")] + rows += [_row(pac_id, "bethesda", _after(-30), "ASC-US", fuente_id="r")] if referral else [] + if biopsy: + rows += [_row(pac_id, "orden_biopsia", COLPOSCOPY, fuente_id="o"), + _row(pac_id, "biopsia", _after(20), biopsy, fuente_id="o")] + return rows + _visit(pac_id, 200, "v1") + _visit(pac_id, 560, "v2", hpv="POSITIVO") + list(extra) + + +def _frame(rows): + return pd.DataFrame(rows, columns=COHORT_SCHEMA.names) + + +def _post(rows, k, **window): + return indexing._indexed_members(_frame(rows), {"kind": "post_colposcopia", "visita": k, **RULES, **window}) + + +def test_the_result_date_is_the_last_report_of_the_colposcopys_biopsies(): + """Pins down, as dbt's episode unit test: the later of two reports of biopsies ordered on the first colposcopy's + day; a later colposcopy's biopsy doesn't count; with no order the colposcopy's day; an order with no report is + counted. Fails if the episode takes a later colposcopy or another day's biopsy.""" + rows = [_row(1, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o1"), + _row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o2"), _row(1, "biopsia", _after(10), "LIEBG", fuente_id="o1"), + _row(1, "biopsia", _after(21), "NEGATIVO", fuente_id="o2"), _row(1, "colposcopia", _after(150), fuente_id="c2"), + _row(1, "orden_biopsia", _after(150), fuente_id="o3"), _row(1, "biopsia", _after(170), "LIEBG", fuente_id="o3")] + + episode = indexing._colposcopy_episode(rows) + no_biopsy = indexing._colposcopy_episode([_row(2, "colposcopia", COLPOSCOPY)]) + unreported = indexing._colposcopy_episode([_row(3, "colposcopia", COLPOSCOPY), _row(3, "orden_biopsia", COLPOSCOPY, fuente_id="o")]) + + assert (episode["result_date"], episode["unreported_orders"]) == (_after(21), 0) + assert (no_biopsy["result_date"], no_biopsy["unreported_orders"]) == (COLPOSCOPY, 0) + assert (unreported["result_date"], unreported["unreported_orders"]) == (COLPOSCOPY, 1) + + +def test_visits_follow_the_result_and_stop_at_the_next_colposcopy(): + """Pins down, as dbt's visits unit test: a sample on the colposcopy's day or before its result isn't a visit; the + two after it are visits 1 and 2; one after a second colposcopy isn't. Fails if visits start before the result or + continue after a re-referral.""" + rows = [_row(1, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o"), + _row(1, "biopsia", _after(21), "NEGATIVO", fuente_id="o"), _row(1, "citologia", COLPOSCOPY, fuente_id="a"), + _row(1, "citologia", _after(10), fuente_id="b"), _row(1, "citologia", _after(170), fuente_id="c1"), + _row(1, "citologia", _after(370), fuente_id="d"), _row(1, "colposcopia", _after(415), fuente_id="c2"), + _row(1, "citologia", _after(600), fuente_id="e")] + + found = indexing._surveillance_visits(rows, indexing._colposcopy_episode(rows)) + + assert [v["fuente_id"] for v in found] == ["1c1", "1d"] + + +@pytest.mark.parametrize("k, index", [(0, _after(20)), (1, _after(200))]) +def test_each_visit_has_its_own_index(k, index): + """Pins down: visit 0 is indexed when the biopsy is reported, visit 1 at its sample. Fails if a cohort takes + another visit or the colposcopy's own date when a biopsy was reported later.""" + members, _ = _post(_patient(1), k) + + assert members.values.tolist() == [[1, index]] + + +def test_the_window_applies_to_the_scenarios_index(): + """Pins down: the recruitment window is checked on the scenario's index (visit 1 at 200 days), not on the first + event. Fails if the window is read off another date.""" + inside, _ = _post(_patient(1), 1, recruitment_start=_after(100).isoformat()) + outside, _ = _post(_patient(1), 1, recruitment_start=_after(300).isoformat()) + + assert (len(inside), len(outside)) == (1, 0) + + +def test_sin_cotest_needs_hpv_and_cytology_of_the_index_sample(): + """Pins down, as dbt's unit test: a visit with HPV and Bethesda stays; HPV alone or cytology alone is flagged; an + HPV of another sample doesn't count. Fails if either result alone, or another sample's, counts as a cotest.""" + def first_visit(pac_id, **kw): + return [r for r in _patient(pac_id) if not r["fuente_id"].endswith(("v1", "v2"))] + _visit(pac_id, 200, "v1", **kw) + rows = (first_visit(1) + first_visit(2, pap=None) + first_visit(3, hpv=None) + first_visit(4, hpv=None) + + [_row(4, "vph", _after(100), "POSITIVO", fuente_id="z")]) + + members, attrition = _post(rows, 1) + + assert members["pac_id"].tolist() == [1] and attrition[-2:] == [("sin_cotest", 1), ("observacion_previa_insuficiente", 1)] + + +def test_rules_in_order_with_attrition(): + """Pins down the order and each rule, as dbt: an unreported order (1), CIN2+ found by the colposcopy (2), a cancer + history note (3), a hysterectomy ICD-10 (4), a treatment (5), no referral in the year before the colposcopy (6); + patient 7 stays; visit 0 has no `sin_cotest`. Fails if a rule, its date bound or the order changes.""" + rows = (_patient(1, _row(1, "orden_biopsia", COLPOSCOPY, fuente_id="o9")) + _patient(2, biopsy="LIEAG") + + _patient(3, _row(3, "antecedente", _after(-400), fuente_id="n")) + + _patient(4, _row(4, "nota_medica", _after(-400), "Z907", fuente_id="n")) + + _patient(5, _row(5, "tratamiento", _after(15), fuente_id="n")) + _patient(6, referral=False) + + _patient(7, _row(7, "nota_medica", _after(-400), "N871", fuente_id="n"))) + + members, attrition = _post(rows, 0) + + assert members["pac_id"].tolist() == [7] + assert attrition == [("pacientes", 7), ("indexed", 7), ("biopsia_sin_resultado", 6), ("cin2_hasta_el_indice", 5), + ("antecedente_cacu", 4), ("histerectomia", 3), ("tratamiento_previo", 2), ("sin_referencia", 1), + ("observacion_previa_insuficiente", 1)] + + +def test_surveillance_index_and_rules_as_dbt(): + """Pins down the surveillance kind, as dbt's surveillance cohort: the first sample is the index; a CIN2+ biopsy + before it (`prior_event`) and an index sample without any result (`no_index_result`) are out; a glandular-only + result counts. Fails if the index takes a later sample or a rule changes.""" + def sample(pac_id, day, *results): + return [_row(pac_id, "citologia", _after(day), fuente_id=f"s{day}")] + [ + _row(pac_id, tipo, _after(day + 7), valor, fuente_id=f"s{day}") for tipo, valor in results] + rows = (sample(1, 0, ("bethesda", "NORMAL")) + sample(1, 300, ("bethesda", "LIEBG")) + + sample(2, 0, ("vph", "POSITIVO")) + [_row(2, "biopsia", _after(-10), "LIEAG")] + + sample(3, 0) + sample(4, 0, ("glandular", "AGC"))) + + members, attrition = indexing._indexed_members(_frame(rows), {"kind": "primera_citologia", **RULES}) + + assert members.values.tolist() == [[1, _after(0)], [4, _after(0)]] + assert attrition == [("pacientes", 4), ("indexed", 4), ("prior_event", 3), ("no_index_result", 2), + ("observacion_previa_insuficiente", 2)] + + +def test_the_node_reindexes_the_frame_with_the_source_cohorts_window(): + """Pins down `cohort`: only the scenario's members, each with the scenario's `fecha_indice`, every event kept; + the window from the source build's `parametros`; without `[config.index]` the source as it is. Fails if the frame + keeps the source's index dates, drops events, or the window isn't the source cohort's.""" + source = _frame(_patient(1) + _patient(2, referral=False)) + lineage = {"parametros": json.dumps({"recruitment_start": "2024-01-01", "recruitment_end": "2027-01-01"})} + index = {"kind": "post_colposcopia", "visita": 1, **RULES} + + reindexed = indexing.cohort(source, lineage, index) + closed = indexing.cohort(source, {"parametros": json.dumps({"recruitment_end": "2025-01-01"})}, index) + + assert set(reindexed["pac_id"]) == {1} and set(reindexed["fecha_indice"]) == {_after(200)} + assert len(reindexed) == (source["pac_id"] == 1).sum() + assert closed.empty and indexing.cohort(source, lineage, None) is source + + +def test_prior_observation_is_a_threshold_on_the_days_before_the_index(): + """Pins down the left-truncation rule: with the default 0 nobody is out; with 230 days, patient 1 (first event 30 + days before her colposcopy, visit 1 at 200 days: 230 days observed) stays and with 231 she is out; the summary + counts members with under a year of history. Fails if the days are counted from another date, the bound flips, + or the default stops being 0.""" + rows = _patient(1) + + assert len(_post(rows, 1)[0]) == 1 + assert len(_post(rows, 1, observacion_previa_minima_dias=230)[0]) == 1 + assert len(_post(rows, 1, observacion_previa_minima_dias=231)[0]) == 0 + summary = indexing.prior_observation(_frame(rows), {}, {"kind": "post_colposcopia", "visita": 1, **RULES}) + assert summary == {"members": 1, "under_365_days": 1, "median_days": 230.0, "threshold_days": 0}