Limpiar los avisos de estilo
This commit is contained in:
+101
-45
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user