Limpiar los avisos de estilo

This commit is contained in:
2026-12-04 09:12:15 -06:00
parent 37c6f242f9
commit bfc964a2bb
6 changed files with 344 additions and 172 deletions
+101 -45
View File
@@ -46,14 +46,25 @@ COHORTS = {
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
}
CODES = { # platform code -> the current platform's
"NILM": "NORMAL", "LSIL": "LIEBG", "HSIL": "LIEAG", "carcinoma": "CARCINOMA",
"normal": "NORMAL", "no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA",
"post_treatment": "POST_TRATAMIENTO", "post_colposcopy": "POST_COLPOSCOPIA",
"pre_colposcopy": "PRE_COLPOSCOPIA", "case": "CASO", "satisfactory": "SATISFACTORIO",
"NILM": "NORMAL",
"LSIL": "LIEBG",
"HSIL": "LIEAG",
"carcinoma": "CARCINOMA",
"normal": "NORMAL",
"no_data": "SIN_DATO",
"no_biopsy": "SIN_BIOPSIA",
"post_treatment": "POST_TRATAMIENTO",
"post_colposcopy": "POST_COLPOSCOPIA",
"pre_colposcopy": "PRE_COLPOSCOPIA",
"case": "CASO",
"satisfactory": "SATISFACTORIO",
"unsatisfactory": "INSATISFACTORIO",
} # fmt: skip
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
"result": "citologia_alto_grado"} # fmt: skip
}
STRATA = {
"age_group": "grupo_edad",
"follow_up_status": "estatus_seguimiento",
"result": "citologia_alto_grado",
}
NEW_STRATA = {"round", "subsequent_history"} # CACU_EU7: Phase 6 and the declared history
# Declared difference: the follow-up status is now what preceded each sample, not what preceded
# the period's start, so these two split the same patients differently.
@@ -68,8 +79,10 @@ CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_gra
def _patients(q) -> dict[str, int]:
"""Each person's patient id in the hospital (for comparing only)."""
with sqlite3.connect(HOSPITAL / "hospital_cacu.db") as con:
number = {n.replace("-", ""): p for p, n in con.execute(
"select pac_id, pac_id_hospital from paciente")} # fmt: skip
number = {
n.replace("-", ""): p
for p, n in con.execute("select pac_id, pac_id_hospital from paciente")
}
rows = q("select distinct person_id, record_number from bronze.staged__identity")
return {person: number[record] for person, record in rows}
@@ -86,9 +99,12 @@ def _report(entry: dict, measure: str) -> tuple:
code = s["code"][0]
name = code["coding"][0]["code"] if "coding" in code else code["text"]
name = CATEGORY.get(measure, "banda") if name == "category" else STRATA.get(name, name)
strata[name] = {CODES.get(x["value"]["text"], x["value"]["text"]): {
p["code"]["coding"][0]["code"]: p["count"] for p in x["population"]}
for x in s.get("stratum", [])} # fmt: skip
strata[name] = {
CODES.get(x["value"]["text"], x["value"]["text"]): {
p["code"]["coding"][0]["code"]: p["count"] for p in x["population"]
}
for x in s.get("stratum", [])
}
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
@@ -106,16 +122,19 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
found = {(patient[p], str(d)) for p, d in q(sql)}
frame = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / theirs / "dbt" / "1.parquet")
frame["fecha_indice"] = frame["fecha_indice"].astype(str)
assert found == set(frame[["pac_id", "fecha_indice"]].drop_duplicates()
.itertuples(index=False, name=None)), ours # fmt: skip
assert found == set(
frame[["pac_id", "fecha_indice"]].drop_duplicates().itertuples(index=False, name=None)
), ours
current = json.loads((REFERENCE / "models.json").read_text())
post_colposcopy = current["cin2_pim_post_colposcopy"]["version"]["metrics"]
members = q("select count(*) from gold.cacu_cohort_post_colposcopy where excluded_by is null")
# Declared difference: here the referral is the cytology linked to the colposcopy, and a
# low grade one counts only with a positive HPV; the current platform took any result of
# the year before. Whoever leaves for that reason is the whole difference.
ungraded = q("select count(*) from gold.cacu_cohort_post_colposcopy "
"where excluded_by = 'referral_not_graded'")[0][0] # fmt: skip
ungraded = q(
"select count(*) from gold.cacu_cohort_post_colposcopy "
"where excluded_by = 'referral_not_graded'"
)[0][0]
theirs = post_colposcopy["n_train"] + post_colposcopy["n_test"]
print("post-colposcopy members", members[0][0], "ungraded", ungraded, "current", theirs)
assert members[0][0] <= theirs <= members[0][0] + ungraded
@@ -127,8 +146,11 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
for measure in [e["resource"] for e in measures["entry"]]:
if measure["name"] not in reference: # Phase 6's (tests/test_cacu_new_measures.py)
continue
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
params = {
"measure": measure["id"],
"reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON,
}
found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
name = measure["name"]
@@ -151,7 +173,8 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
mine, was = old.pop("estatus_seguimiento", {}), dict(b[3])
theirs_status = was.pop("estatus_seguimiento", {})
assert sum(v["initial-population"] for v in mine.values()) == sum(
v["initial-population"] for v in theirs_status.values()), where # fmt: skip
v["initial-population"] for v in theirs_status.values()
), where
assert a[0] == b[0] and old == was, where
else:
assert a[0] == b[0] and old == b[3], where
@@ -184,29 +207,49 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
# Risks: the champions score their cohorts with the current models' predictions.
wait_for(api, ok(api.post("/models/cacu/score"))["run_id"])
for name in names:
risks = pd.DataFrame(q(
"select person_id, index_date, horizon_years, probability, ci_low, ci_high "
f"from gold.cacu_risk where model = 'cacu.{name}'"
), columns=["person_id", "index_date", "horizon_years", "probability", "ci_low",
"ci_high"]) # fmt: skip
risks = pd.DataFrame(
q(
"select person_id, index_date, horizon_years, probability, ci_low, ci_high "
f"from gold.cacu_risk where model = 'cacu.{name}'"
),
columns=[
"person_id",
"index_date",
"horizon_years",
"probability",
"ci_low",
"ci_high",
],
)
risks["pac_id"] = risks["person_id"].map(patient)
expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
if name == "cin2_pim_post_colposcopy": # fixed: scored at her own index
cohort = q("select person_id, index_date from gold.cacu_cohort_post_colposcopy "
"where excluded_by is null") # fmt: skip
cohort = q(
"select person_id, index_date from gold.cacu_cohort_post_colposcopy "
"where excluded_by is null"
)
assert set(map(tuple, risks[["person_id", "index_date"]].astype(str).values)) == {
(p, str(d)) for p, d in cohort} # fmt: skip
(p, str(d)) for p, d in cohort
}
continue
if name in HPV_GATED: # nobody the current platform did not score
assert set(zip(risks["pac_id"], risks["horizon_years"])) <= set(
zip(expected["pac_id"], expected["horizonte_anios"])), name # fmt: skip
assert set(zip(risks["pac_id"], risks["horizon_years"], strict=False)) <= set(
zip(expected["pac_id"], expected["horizonte_anios"], strict=False)
), name
continue
both = risks.merge(expected, left_on=["pac_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], how="outer",
indicator=True) # fmt: skip
both = risks.merge(
expected,
left_on=["pac_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"],
how="outer",
indicator=True,
)
assert (both["_merge"] == "both").all(), name
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
for ours, theirs in [
("probability", "probabilidad"),
("ci_low", "ic_bajo"),
("ci_high", "ic_alto"),
]:
if theirs in both:
np.testing.assert_allclose(both[ours].astype(float), both[theirs], rtol=1e-6)
@@ -219,9 +262,13 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
page = json.loads((REFERENCE / "pages.json").read_text())
theirs = page["/cacu/seguimiento?page_size=200"]["body"]
window, cutoff = theirs["ventana"], theirs["corte"]
params = [("follow-up-window", window["meses"]), ("follow-up-cutoff", cutoff),
("_count", 20), ("_revinclude", "DiagnosticReport:subject"),
("_include:iterate", "DiagnosticReport:result")] # fmt: skip
params = [
("follow-up-window", window["meses"]),
("follow-up-cutoff", cutoff),
("_count", 20),
("_revinclude", "DiagnosticReport:subject"),
("_include:iterate", "DiagnosticReport:result"),
]
ours = follow_up(pages(api, "/cacu/fhir/Patient", params), window["desde"], cutoff)
assert [r["cytology"]["date"] for r in ours] == [
i["ultima_citologia"]["fecha"] for i in theirs["items"]
@@ -232,21 +279,30 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
cytology, hpv, biopsy = row["cytology"], row["hpv"], row["biopsy"]
shown = {
"estatus": CODES[row["status"]],
"ultima_citologia": {"fecha": cytology["date"],
"bethesda": CODES.get(cytology["result"], cytology["result"]),
"calidad": CODES.get(cytology["adequacy"])},
"ultimo_vph": hpv and {"fecha": hpv["date"], "genotipo_16_18": hpv["types_16_18"],
"resultado": "POSITIVO" if hpv["positive"] else "NEGATIVO"},
"ultima_citologia": {
"fecha": cytology["date"],
"bethesda": CODES.get(cytology["result"], cytology["result"]),
"calidad": CODES.get(cytology["adequacy"]),
},
"ultimo_vph": hpv
and {
"fecha": hpv["date"],
"genotipo_16_18": hpv["types_16_18"],
"resultado": "POSITIVO" if hpv["positive"] else "NEGATIVO",
},
"dias_toma_diagnostico": row["days_to_diagnosis"],
"ultima_biopsia": biopsy and {
"ultima_biopsia": biopsy
and {
"fecha": biopsy["date"],
"grado": CODES.get(biopsy["histology"], biopsy["histology"]),
},
} # fmt: skip
}
item = expected[patient[row["person"]]]
if patient[row["person"]] == 198: # fixed: one horizon (120 days), not 180
assert (shown["estatus"], item["estatus"]["codigo"]) == (
"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA") # fmt: skip
"PRE_COLPOSCOPIA",
"POST_COLPOSCOPIA",
)
shown["estatus"] = "POST_COLPOSCOPIA"
status = item["estatus"]["codigo"]
# Declared difference: after colposcopy only once she has a cytology taken after it.
+17 -16
View File
@@ -16,8 +16,9 @@ def _patient_reads(monkeypatch, exists=True):
monkeypatch.setattr(
fhir.reads,
"rows",
lambda domain, kind, **params: ([{"person_id": params["id"]}] if exists else [])
if kind == "person" else [],
lambda domain, kind, **params: (
([{"person_id": params["id"]}] if exists else []) if kind == "person" else []
),
)
@@ -27,19 +28,21 @@ def test_patient_eligibility_operation_returns_reasons_and_applies_filters(monke
def report(scenario, person_id, *, cutoff):
calls.append((scenario, person_id, cutoff))
return pd.DataFrame([{
"scenario": "surveillance",
"person_id": person_id,
"index_date": date(2025, 2, 1),
"index_sample_id": "sample-1",
"criterion": "hysterectomy",
"eligible": False,
}])
return pd.DataFrame(
[
{
"scenario": "surveillance",
"person_id": person_id,
"index_date": date(2025, 2, 1),
"index_sample_id": "sample-1",
"criterion": "hysterectomy",
"eligible": False,
}
]
)
monkeypatch.setattr(fhir.gold_reads, "cacu_eligibility_report", report)
response = fhir.cacu_eligibility(
Domain.CACU, "patient-1", "surveillance", date(2025, 2, 15)
)
response = fhir.cacu_eligibility(Domain.CACU, "patient-1", "surveillance", date(2025, 2, 15))
assert response.status_code == 200
assert response.media_type == fhir.FHIR_JSON
@@ -62,9 +65,7 @@ def test_patient_eligibility_reports_stale_gold_as_fhir_conflict(monkeypatch):
raise gold.GoldSchemaError("rebuild gold.cacu_eligibility")
monkeypatch.setattr(fhir.gold_reads, "cacu_eligibility_report", outdated)
response = fhir.cacu_eligibility(
Domain.CACU, "patient-1", None, date(2025, 2, 15)
)
response = fhir.cacu_eligibility(Domain.CACU, "patient-1", None, date(2025, 2, 15))
assert response.status_code == 409
assert response.media_type == fhir.FHIR_JSON
+10 -5
View File
@@ -12,14 +12,19 @@ def test_development_models_and_superseded_risks_are_not_served(monkeypatch):
for person in ("free", "lesion")
for model in ("cacu.cin2_pim", "cacu.cin2_logistic", "cacu.survival")
]
history = [{"person_id": "lesion", "date": "2025-06-01", "type": "biopsy",
"value_code": "HSIL"}] # fmt: skip
history = [
{"person_id": "lesion", "date": "2025-06-01", "type": "biopsy", "value_code": "HSIL"}
]
monkeypatch.setattr(
fhir.reads, "rows",
fhir.reads,
"rows",
lambda domain, kind, **params: stored if kind == "risk" else history,
) # fmt: skip
)
found = fhir._risks(Domain.CACU, ["free", "lesion"], date(2025, 12, 31))
assert [(r["person_id"], r["model"]) for r in found] == [
("free", "cacu.cin2_pim"), ("free", "cacu.survival"), ("lesion", "cacu.survival")] # fmt: skip
("free", "cacu.cin2_pim"),
("free", "cacu.survival"),
("lesion", "cacu.survival"),
]
+6 -2
View File
@@ -30,8 +30,12 @@ PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cama.json"
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
NEW = {"CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO", "CAMA_DIAS_RESULTADO_BIOPSIA", "CAMA_TIPO_HISTOLOGICO",
"CAMA_TIPO_HISTOLOGICO_BIRADS"} # focused tests of new measures in the integrator
NEW = {
"CAMA_DIAS_DIAGNOSTICO_TRATAMIENTO",
"CAMA_DIAS_RESULTADO_BIOPSIA",
"CAMA_TIPO_HISTOLOGICO",
"CAMA_TIPO_HISTOLOGICO_BIRADS",
} # focused tests of new measures in the integrator
CODES = { # platform code -> the current platform's
**{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")},
"4A": "B4", "4B": "B4", "4C": "B4",
+2 -1
View File
@@ -51,7 +51,8 @@ def test_metadata_is_served_with_the_nci_reference_on_or_off(client, monkeypatch
for param in resource.get("searchParam", []):
assert param["type"], param
assert param["name"] not in OPERATION_PARAMETERS, (
f"{resource['type']}: {param['name']} belongs to the operation, not to a search")
f"{resource['type']}: {param['name']} belongs to the operation, not to a search"
)
def test_the_flag_does_not_change_what_the_statement_declares(client, monkeypatch):