218 lines
11 KiB
Python
218 lines
11 KiB
Python
"""Phase 6's CaCu measures, their rules over made-up gold rows."""
|
|
|
|
from datetime import UTC, date, datetime
|
|
|
|
from core import fhir
|
|
from core.cacu.measures import MEASURES, biopsy_answer, hpv_genotype
|
|
from core.measures import Period, evaluate, report
|
|
|
|
S1 = Period.parse("2026-S1")
|
|
CUTOFF = date(2026, 12, 31)
|
|
|
|
|
|
def procedure(person, day, histology=None, reported=None, **more):
|
|
return {
|
|
"procedure_id": f"{person}|{day}", "person_id": person, "date": day,
|
|
"sample_date": "2026-01-05", "result": "HSIL", "hpv": None, "hpv_16": None, "hpv_18": None,
|
|
"screening_history": None, "detection": None, "histology": histology, "report_date": reported,
|
|
|
|
"known_at": "2026-01-01", "report_known_at": "2026-01-01",
|
|
"cytology_known_at": "2026-01-01",
|
|
"first_case": None, "first_treatment": None, "first_colposcopy": None, **more,
|
|
} # fmt: skip
|
|
|
|
|
|
def ran(measure, rows, **kw):
|
|
return evaluate(MEASURES[measure], rows, S1, event_cutoff=kw.pop("cutoff", CUTOFF), **kw)
|
|
|
|
|
|
def cell(result, stratum, value):
|
|
c = result.strata[stratum][value]
|
|
return c["numerator"], c["denominator"]
|
|
|
|
|
|
def test_a_patient_counts_once_with_her_first_procedure_that_counts():
|
|
rows = [
|
|
procedure("a", "2026-02-01"), # a biopsy without a report doesn't count
|
|
procedure("a", "2026-03-01", "normal", "2026-03-10"),
|
|
procedure("a", "2026-04-01", "HSIL", "2026-04-10"),
|
|
procedure("b", "2026-02-01", "HSIL", "2026-02-10", first_case="2025-01-01"), # a case
|
|
]
|
|
found = ran("CACU_VPP_BIOPSIA", rows).populations
|
|
assert (found["numerator"], found["denominator"]) == (0, 1)
|
|
found = ran("CACU_VPP_COLPOSCOPIA", rows).populations
|
|
assert (found["numerator"], found["denominator"]) == (0, 1)
|
|
|
|
|
|
def test_levels_share_the_denominator_and_cytology_groups_overlap():
|
|
rows = [
|
|
procedure("a", "2026-02-01", "LSIL", "2026-02-10", result="ASC-US"),
|
|
procedure("b", "2026-02-01", "HSIL", "2026-02-10", hpv=True, hpv_16=True, hpv_18=False),
|
|
procedure("c", "2026-02-01", "carcinoma", "2026-02-10", result=None, sample_date=None),
|
|
procedure("d", "2026-02-01", "normal", "2026-02-10", result="NILM"),
|
|
]
|
|
found = ran("CACU_VPP_BIOPSIA", rows)
|
|
assert [cell(found, "level", k) for k in ("cin1_plus", "cin2_plus", "carcinoma")] == [
|
|
(3, 4), (2, 4), (1, 4)] # fmt: skip
|
|
assert cell(found, "cytology", "ascus_plus") == (2, 2)
|
|
assert cell(found, "cytology", "hsil_plus") == (1, 1)
|
|
assert cell(found, "cytology", "no_data") == (1, 1) # and NILM is in no group
|
|
assert cell(found, "hpv", "positive") == cell(found, "hpv", "hpv_16") == (1, 1)
|
|
assert found.score == 0.75
|
|
assert report(MEASURES["CACU_VPP_BIOPSIA"], S1, found, None)
|
|
|
|
|
|
def test_rounds():
|
|
rows = [
|
|
procedure("a", "2026-02-01", "normal", "2026-02-10", detection="initial"),
|
|
procedure("b", "2026-02-01", "normal", "2026-02-10", detection="subsequent"),
|
|
procedure(
|
|
"c",
|
|
"2026-02-01",
|
|
"normal",
|
|
"2026-02-10",
|
|
detection="subsequent",
|
|
), # fmt: skip
|
|
procedure("d", "2026-02-01", "normal", "2026-02-10"),
|
|
]
|
|
found = ran("CACU_VPP_BIOPSIA", rows).strata["round"]
|
|
assert {k: v["denominator"] for k, v in found.items()} == {
|
|
"initial": 1, "subsequent": 2, "no_data": 1} # fmt: skip
|
|
|
|
|
|
def test_a_report_counts_once_it_is_known_and_dated_by_the_cutoff():
|
|
late = procedure("a", "2026-02-01", "HSIL", "2026-05-01", report_known_at="2026-06-01")
|
|
for kw in ({"cutoff": date(2026, 4, 1)}, {"as_of": datetime(2026, 5, 15, tzinfo=UTC)}):
|
|
assert ran("CACU_VPP_COLPOSCOPIA", [late], **kw).populations["numerator"] == 0
|
|
answers = ran("CACU_BIOPSIA_SOLICITUD_CONFIRMACION", [late], **kw).strata["category"]
|
|
assert list(answers) == ["pending"]
|
|
as_of = datetime(2026, 5, 15, tzinfo=UTC)
|
|
assert not ran("CACU_BIOPSIA_RESULTADOS", [late], as_of=as_of).populations["initial-population"]
|
|
assert ran("CACU_VPP_COLPOSCOPIA", [late]).populations["numerator"] == 1
|
|
|
|
|
|
def test_biopsy_answers_and_hpv_genotypes():
|
|
answers = [biopsy_answer(procedure("a", "2026-02-01", *x)) for x in (
|
|
(None, None), ("HSIL", "2026-01-01"), (None, "2026-03-01"), ("HSIL", "2026-03-01"),
|
|
("LSIL", "2026-03-01"))] # fmt: skip
|
|
assert answers == ["pending", "inconsistent", "no_grade", "high_grade", "below_high_grade"]
|
|
said = lambda *v: hpv_genotype(dict(zip(("hpv", "hpv_16", "hpv_18"), v, strict=True))) # noqa: E731
|
|
assert said(False, False, False) == "negative"
|
|
assert said(None, False, None) == "no_result" # a genotype's negative is not a negative HPV
|
|
assert said(None, True, None) == said(False, True, False) == "inconsistent"
|
|
assert said(True, None, False) == "positive_incomplete"
|
|
assert said(True, True, True) == "positive_16_18"
|
|
assert said(True, False, False) == "positive_other"
|
|
|
|
|
|
def test_a_duration_by_code_scores_each_code():
|
|
rows = [
|
|
{"sample_id": str(i), "sample_date": "2026-02-01", "history": 0, "known_at": None,
|
|
"diagnosis_date": "2026-03-01", "days_sample_diagnosis": days, "diagnosis_code": code}
|
|
for i, (days, code) in enumerate([(10, "N870"), (20, "N870"), (28, None)])
|
|
] # fmt: skip
|
|
found = ran("CACU_TIEMPO_DIAGNOSTICO_CIE10", rows)
|
|
assert found.scores["diagnosis_code", "N870"] == (15.0, {"q1": 12.5, "q3": 17.5}, "d")
|
|
(by_code,) = (
|
|
report(MEASURES["CACU_TIEMPO_DIAGNOSTICO_CIE10"], S1, found, None).group[0].stratifier
|
|
)
|
|
assert {s.value.text: s.measureScore.value for s in by_code.stratum} == {
|
|
"N870": 15,
|
|
"no_data": 28,
|
|
}
|
|
assert len(fhir.EXTENSIONS["q1"][1]) == 2
|
|
|
|
|
|
def test_hpv_reports_by_genotype_cross_age_status_and_round_without_changing_the_count():
|
|
def report(person, taken, birth, history, hpv, h16, h18, **more):
|
|
return {
|
|
"sample_id": f"{person}|{taken}", "person_id": person, "sample_date": taken,
|
|
"report_date": "2026-03-01", "birth_date": birth, "screening_history": history,
|
|
"detection": history and ("initial" if history == "never" else "subsequent"),
|
|
"hpv": hpv, "hpv_16": h16, "hpv_18": h18, "known_at": "2026-01-01",
|
|
"report_known_at": "2026-01-01", "first_case": None, "first_treatment": None,
|
|
"first_colposcopy": None, **more,
|
|
} # fmt: skip
|
|
|
|
rows = [
|
|
report("a", "2026-02-01", "1990-01-01", "never", False, False, False),
|
|
report("a", "2026-04-01", "1990-01-01", "never", True, True, False), # same patient: 2 reports
|
|
report("b", "2026-02-01", "1970-01-01", "2_years", True, False, False),
|
|
report("c", "2026-02-01", "1980-01-01", "never", True, None, False,
|
|
first_colposcopy="2025-12-01", first_postcolposcopy_cytology="2025-12-15",
|
|
detection="subsequent"),
|
|
report("d", "2026-02-01", "1980-01-01", None, True, False, True),
|
|
] # fmt: skip
|
|
plain = ran("CACU_VPH_GENOTIPO", rows)
|
|
assert plain.populations["initial-population"] == 5 # reports, not patients
|
|
assert plain.strata["category"] == {
|
|
"negative": {"initial-population": 1},
|
|
"positive_16": {"initial-population": 1},
|
|
"positive_other": {"initial-population": 1},
|
|
"positive_incomplete": {"initial-population": 1},
|
|
"positive_18": {"initial-population": 1},
|
|
}
|
|
# every report is in exactly one group of each stratifier
|
|
for name in ("age_group", "follow_up_status", "round"):
|
|
assert sum(c["initial-population"] for c in plain.strata[name].values()) == 5
|
|
assert plain.strata["round"] == {
|
|
"initial": {"initial-population": 2}, # a's two reports: she never had a screening
|
|
"subsequent": {"initial-population": 2}, # b's history; c is past colposcopy
|
|
"no_data": {"initial-population": 1}, # d has no history and no colposcopy
|
|
}
|
|
assert plain.strata["follow_up_status"]["post_colposcopy"] == {"initial-population": 1}
|
|
assert plain.crossed[("round", "category")][("initial", "negative")] == {"initial-population": 1}
|
|
assert plain.crossed[("round", "category")][("no_data", "positive_18")] == {"initial-population": 1}
|
|
|
|
|
|
def test_result_age_stratum_uses_completed_years_at_period_start():
|
|
from core.cacu.measures import results_age_group
|
|
from core.measures import Period
|
|
|
|
period = Period.parse('2025-03')
|
|
assert results_age_group({'birth_date': '2010-03-02'}, period) == []
|
|
assert results_age_group({'birth_date': '2010-03-01'}, period) == '<25'
|
|
assert results_age_group({'birth_date': '2000-03-02'}, period) == '<25'
|
|
assert results_age_group({'birth_date': '2000-03-01'}, period) == '25-34'
|
|
assert results_age_group({'birth_date': None}, period) == 'no_data'
|
|
|
|
|
|
def sample(person, birth, history, result="NILM", **extra):
|
|
return {
|
|
"person_id": person, "sample_id": person, "sample_date": "2026-02-01",
|
|
"report_date": "2026-02-10", "birth_date": birth, "screening_history": history,
|
|
"detection": history and ("initial" if history == "never" else "subsequent"),
|
|
"result": result, "valid": 1, "hpv": True, "hpv_16": False, "hpv_18": False,
|
|
"known_at": "2026-02-01", "report_known_at": "2026-02-10",
|
|
"first_case": None, "first_treatment": None, "first_colposcopy": None,
|
|
"first_postcolposcopy_cytology": None, **extra,
|
|
}
|
|
|
|
|
|
def test_under_age_threshold_remains_in_totals_for_both_result_measures():
|
|
rows = [sample("young", "2011-01-02", "never"), sample("old", "2011-01-01", "never")]
|
|
for measure in ("CACU_EU7", "CACU_VPH_GENOTIPO"):
|
|
found = ran(measure, rows)
|
|
assert found.populations["initial-population"] == 2
|
|
assert found.strata["age_group"]["<25"]["initial-population"] == 1
|
|
assert sum(v["initial-population"] for v in found.strata["category"].values()) == 2
|
|
|
|
|
|
def test_form_history_breakdown_is_a_subset_of_subsequent_round():
|
|
rows = [
|
|
sample("initial", "1990-01-01", "never"),
|
|
sample("one", "1990-01-01", "within_1_year"),
|
|
sample("two", "1990-01-01", "2_years"),
|
|
sample("three", "1990-01-01", "3_or_more_years"),
|
|
sample("unknown", "1990-01-01", None, detection="subsequent"), # past colposcopy
|
|
sample("conflict", "1990-01-01", "never", detection="subsequent"),
|
|
]
|
|
for measure in ("CACU_EU7", "CACU_VPH_GENOTIPO"):
|
|
found = ran(measure, rows)
|
|
assert found.strata["round"]["initial"]["initial-population"] == 1
|
|
assert found.strata["round"]["subsequent"]["initial-population"] == 5
|
|
assert {k: v["initial-population"] for k, v in found.strata["subsequent_history"].items()} == {
|
|
"within_1_year": 1, "2_years": 1, "3_or_more_years": 1,
|
|
"no_data": 1, "never": 1,
|
|
}
|