From b5480e8bbb934134c312c8a718575e50022fcac9 Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 2 Dec 2026 17:03:54 -0600 Subject: [PATCH] =?UTF-8?q?Guardar=20la=20deserci=C3=B3n=20de=20cada=20coh?= =?UTF-8?q?orte=20CaCu=20junto=20al=20modelo=20entrenado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/cacu/jobs.py | 15 +++++++++++++- models/cacu/reports.py | 39 ++++++++++++++++++++++++++++++++++++ models/jobs.py | 4 ++++ tests/test_cacu_attrition.py | 31 ++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 tests/test_cacu_attrition.py diff --git a/models/cacu/jobs.py b/models/cacu/jobs.py index f4e20d5..4bd5243 100644 --- a/models/cacu/jobs.py +++ b/models/cacu/jobs.py @@ -1,8 +1,21 @@ """CaCu's training and scoring jobs (models.jobs) over its models and reports.""" +from datetime import date + from models.cacu import reports from models.cacu.specs import MODELS from models.jobs import Jobs +from persistance import gold -JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability) + +def attrition(spec, as_of: date) -> dict | None: + """The attrition of the spec's cohort; None when eligibility doesn't list that cohort.""" + scenario = reports.COHORT_SCENARIOS.get(spec.cohort) + if scenario is None: + return None + rows = gold.cacu_eligibility_report(scenario, cutoff=as_of) + return reports.attrition(spec.cohort, rows, gold.people("cacu_events", as_of), as_of) + + +JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability, attrition) train, score = JOBS.train, JOBS.score diff --git a/models/cacu/reports.py b/models/cacu/reports.py index a1183fb..c10a485 100644 --- a/models/cacu/reports.py +++ b/models/cacu/reports.py @@ -9,6 +9,8 @@ validation, is a document the clinical team adds). Both are data the governance For the logistic regression, its coefficients and calibration by risk decile. """ +from datetime import date + import numpy as np import pandas as pd from scipy.stats import norm @@ -23,6 +25,43 @@ BOOTSTRAP = 200 SEED = 20261122 Z = norm.ppf(0.975) +# The scenario of gold.cacu_eligibility that lists each cohort's candidates. +COHORT_SCENARIOS = { + "cacu_cohort_surveillance": "surveillance", + "cacu_cohort_post_colposcopy": "post_colposcopy", + "cacu_cohort_post_treatment": "post_treatment", + "cacu_cohort_survival": "survival", +} +# Reasons that a result still to arrive could lift. +AWAITING = {"unreported_biopsy", "no_index_result"} + + +def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict: + """Who a cohort lost and why, up to `as_of`. `rows`: its candidates' eligibility report (one + row per candidate and reason). A candidate with several reasons counts once in `excluded` + and once in each reason; `pending` are the excluded whose every reason awaits a result.""" + rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()] + key = ["person_id", "index_date", "index_sample_id"] + candidates = rows[key].drop_duplicates() + excluded = rows[rows["criterion"].notna()] + reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set) + pending = int(sum(found <= AWAITING for found in reasons)) + return { + "cohort": cohort, + "scenario": COHORT_SCENARIOS[cohort], + "as_of": as_of.isoformat(), + "people": people, + "without_candidate": people - int(candidates["person_id"].nunique()), + "candidates": len(candidates), + "eligible": len(candidates) - len(reasons), + "excluded": len(reasons), + "pending": pending, + "by_reason": { + str(reason): int(count) + for reason, count in excluded["criterion"].value_counts().sort_index().items() + }, + } + def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict: if isinstance(spec, survival.Spec): diff --git a/models/jobs.py b/models/jobs.py index bba87d6..c405b37 100644 --- a/models/jobs.py +++ b/models/jobs.py @@ -35,6 +35,8 @@ class Jobs: models: dict technical_validation: Callable[..., dict] interpretability: Callable[..., dict] + # (spec, as_of) -> who the model's cohort lost, kept beside the reports; None: not kept + attrition: Callable[..., dict | None] | None = None @property def events(self) -> str: @@ -72,6 +74,8 @@ class Jobs: # Bootstraps ran on joblib's worker pool: release it now, or the job's process waits # for its idle workers to time out (5 minutes) before it can end. get_reusable_executor().shutdown(wait=True) + if self.attrition and (lost := self.attrition(spec, as_of)) is not None: + found = {**found, "attrition": lost} # not one of the reports promotion asks for params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()} model = Predictor(spec, fitted) return registry.register(self.registered(name), model, params, metrics, found) diff --git a/tests/test_cacu_attrition.py b/tests/test_cacu_attrition.py new file mode 100644 index 0000000..8407534 --- /dev/null +++ b/tests/test_cacu_attrition.py @@ -0,0 +1,31 @@ +"""Attrition of a CaCu cohort: candidates, eligible, pending and reasons, each counted once.""" + +from datetime import date + +import pandas as pd + +from models.cacu import reports + + +def test_a_candidate_with_two_reasons_is_excluded_once(): + """Pins the totals, the pending rule, the people without a candidate and the as-of cut.""" + rows = pd.DataFrame( + [ + ("eligible", "2025-01-01", None, None), + ("two", "2025-01-01", None, "hysterectomy"), + ("two", "2025-01-01", None, "under_18"), + ("waiting", "2025-01-01", None, "no_index_result"), + ("waiting_and_out", "2025-01-01", None, "no_index_result"), + ("waiting_and_out", "2025-01-01", None, "prior_outcome"), + ("after", "2025-07-01", None, "hysterectomy"), + ], + columns=["person_id", "index_date", "index_sample_id", "criterion"], + ) + + found = reports.attrition("cacu_cohort_surveillance", rows, 10, date(2025, 6, 30)) + + assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3) + assert (found["pending"], found["without_candidate"]) == (1, 6) + assert found["by_reason"] == { + "hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1, + } # fmt: skip