diff --git a/models/cacu/reports.py b/models/cacu/reports.py index c10a485..4014b1b 100644 --- a/models/cacu/reports.py +++ b/models/cacu/reports.py @@ -34,6 +34,16 @@ COHORT_SCENARIOS = { } # Reasons that a result still to arrive could lift. AWAITING = {"unreported_biopsy", "no_index_result"} +# Clinical categories, not execution order: a candidate may belong to several stages. +REASON_STAGE = { + "hysterectomy": "eligibility", "under_18": "eligibility", + "no_birth_date": "eligibility", "died_by_index": "eligibility", + "prior_outcome": "history", "outcome_by_index": "history", + "cancer_history": "history", "prior_treatment": "history", + "outcome_before_index": "history", "no_pretreatment_biopsy": "history", + "no_referral": "index", "no_cotest": "index", + "no_index_result": "index", "unreported_biopsy": "index", +} def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict: @@ -46,6 +56,7 @@ def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict excluded = rows[rows["criterion"].notna()] reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set) pending = int(sum(found <= AWAITING for found in reasons)) + stages = excluded.assign(stage=excluded["criterion"].map(REASON_STAGE).fillna("unknown")) return { "cohort": cohort, "scenario": COHORT_SCENARIOS[cohort], @@ -60,6 +71,13 @@ def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict str(reason): int(count) for reason, count in excluded["criterion"].value_counts().sort_index().items() }, + "by_stage": { + str(stage): len(group[key].drop_duplicates()) + for stage, group in stages.groupby("stage", sort=True) + }, + "stage_by_reason": {str(reason): REASON_STAGE.get(str(reason), "unknown") + for reason in sorted(excluded["criterion"].unique())}, + "stage_counts_overlap": True, } diff --git a/tests/test_cacu_attrition.py b/tests/test_cacu_attrition.py index 8407534..18f5b8e 100644 --- a/tests/test_cacu_attrition.py +++ b/tests/test_cacu_attrition.py @@ -29,3 +29,6 @@ def test_a_candidate_with_two_reasons_is_excluded_once(): assert found["by_reason"] == { "hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1, } # fmt: skip + assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2} + assert found["stage_by_reason"]["no_index_result"] == "index" + assert found["stage_counts_overlap"] is True