"""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_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 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}