diff --git a/models/steps/indexing.py b/models/steps/indexing.py index 9447af1..0191e93 100644 --- a/models/steps/indexing.py +++ b/models/steps/indexing.py @@ -150,17 +150,30 @@ KINDS = {"primera_citologia": _first_cytology, "post_colposcopia": _post_colposc 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() + """(members, attrition) of the kind `primera_biopsia_invasora`, from the whole frame: the first biopsy reported with + one of the scenario's `event_grades`, if it falls in the window, then the rules of the per-patient version.""" + grades = set(index.get("event_grades") or [index.get("invasive_code", "CARCINOMA_INVASOR")]) + dated = cohort.assign(fecha=pd.to_datetime(cohort["fecha"])) + biopsies = dated[(dated["tipo"] == "biopsia") & (dated["valor_codigo"].isin(grades))] + first = biopsies.groupby("pac_id")["fecha"].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))] + first = first[inside] + attrition = [("pacientes", int(cohort["pac_id"].nunique())), ("indexed", len(first))] + first = first[first.index.isin(dated.loc[dated["tipo"] == "nacimiento", "pac_id"])] + attrition.append(("sin_nacimiento", len(first))) + death = dated[dated["tipo"] == "defuncion"].groupby("pac_id")["fecha"].min().reindex(first.index) + first = first[~death.le(first).to_numpy()] + attrition.append(("defuncion_hasta_el_indice", len(first))) + prior_days = (first - dated.groupby("pac_id")["fecha"].min().reindex(first.index)).dt.days + first = first[(prior_days >= int(index.get("observacion_previa_minima_dias", 0))).to_numpy()] + attrition.append(("observacion_previa_insuficiente", len(first))) + members = first.rename("fecha_indice").dt.date.rename_axis("pac_id").reset_index() + return members, attrition # Kinds read from the whole frame: (cohort, index) -> (members, attrition), for cohorts too large to take apart by patient. diff --git a/tests/test_indexing.py b/tests/test_indexing.py index 1417643..f6c5d66 100644 --- a/tests/test_indexing.py +++ b/tests/test_indexing.py @@ -170,6 +170,31 @@ def test_the_node_reindexes_the_frame_with_the_source_cohorts_window(): assert closed.empty and indexing.cohort(source, lineage, None) is source +def test_the_first_invasive_biopsy_index_reads_the_scenarios_event_grades_and_applies_its_rules(): + """Pins down `primera_biopsia_invasora` over the whole frame: the index is the first biopsy reported with one of the + scenario's `event_grades` (CaCu's CIS and carcinoma, CaMa's invasive carcinoma), a grade of another scenario does + not index, and without `event_grades` the CaMa code is the default; then, in order, the patient with no birth date + and the one who died on or before the biopsy are out, each charged in the attrition. Fails if the index looks for + one fixed code, so that CaCu's survival has no members, if a grade outside the list indexes, or if a rule stops + applying.""" + birth = [_row(pac, "nacimiento", date(1980, 1, 1)) for pac in (1, 2, 3, 5)] + rows = [*birth, _row(1, "biopsia", date(2025, 3, 1), "CIS"), _row(1, "biopsia", date(2025, 1, 1), "LIEAG"), + _row(2, "biopsia", date(2025, 6, 1), "CARCINOMA"), _row(3, "biopsia", date(2025, 7, 1), "CARCINOMA_INVASOR"), + _row(4, "biopsia", date(2025, 8, 1), "CARCINOMA"), + _row(5, "biopsia", date(2025, 9, 1), "CIS"), _row(5, "defuncion", date(2025, 9, 1))] + + def indexed(**index): + members, attrition = indexing._indexed_members(_frame(rows), {"kind": "primera_biopsia_invasora", **index}) + return members.values.tolist(), attrition + + members, attrition = indexed(event_grades=["CIS", "CARCINOMA"]) + assert members == [[1, date(2025, 3, 1)], [2, date(2025, 6, 1)]] + assert attrition == [("pacientes", 5), ("indexed", 4), ("sin_nacimiento", 3), ("defuncion_hasta_el_indice", 2), + ("observacion_previa_insuficiente", 2)] + assert indexed(event_grades=["CARCINOMA_INVASOR"])[0] == [[3, date(2025, 7, 1)]] + assert indexed()[0] == [[3, date(2025, 7, 1)]] + + 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