Files
ISSSTELEON/Core/core/cacu/measures.py
T
Roberto Treviño 2fe5301fd1
ci / python (push) Successful in 51m44s
ci / web (push) Successful in 16m59s
CaCu: procedures with their cytology and histology, seven measures, the cytology form's fields
2026-11-30 23:32:01 -06:00

234 lines
12 KiB
Python

"""CaCu's measures (`core.measures` evaluates them) and the follow-up status they stratify by."""
from datetime import date
from core import cacu
from core.measures import (
NO_BIOPSY,
NO_DATA,
Composition,
Duration,
Measure,
Proportion,
RiskBand,
age_group,
as_day,
desc,
)
def follow_up_status(row: dict, at: date, through: bool = False) -> str:
"""Where the patient was in her follow-up just before `at` (`through`: by the end of
`at`), from the first day of each step (`gold.cacu_follow_up`). A case already has
cancer; what follows her is survival."""
def by(first: str) -> bool:
day = as_day(row.get(first))
return day is not None and (day <= at if through else day < at)
for first, status in (("first_case", "case"), ("first_treatment", "post_treatment"),
("first_colposcopy", "post_colposcopy")): # fmt: skip
if by(first):
return status
return "pre_colposcopy"
def valid(row: dict) -> bool:
"""A cytology with a result, reported, of satisfactory (or unknown) adequacy."""
return row["result_date"] is not None and row.get("adequacy") != "unsatisfactory"
def latest(row: dict) -> tuple:
"""A patient's latest valid sample ranks highest."""
return valid(row), as_day(row["sample_date"]), row["sample_id"]
def latest_most_severe_biopsy(row: dict) -> tuple:
"""Her latest valid sample, then its most severe reported biopsy, the latest first."""
reported = row.get("biopsy_report_date") is not None
return (*latest(row), reported, row.get("severity") or 0,
desc(as_day(row.get("biopsy_report_date"))), desc(row.get("biopsy_id"))) # fmt: skip
def result(row: dict) -> str:
return row["result"] if valid(row) else NO_DATA
def histology(row: dict) -> str:
"""The chosen biopsy's histology (NO_BIOPSY without one reported)."""
if not valid(row):
return NO_DATA
if row.get("biopsy_report_date") is None:
return NO_BIOPSY
return row.get("histology") or NO_DATA
def case_before(row: dict) -> bool:
"""Whether she was a case already: at the procedure's cytology, or at it without one."""
return follow_up_status(row, as_day(row["sample_date"] or row["date"])) == "case"
def earliest(row: dict) -> tuple:
return -as_day(row["date"]).toordinal(), row["procedure_id"]
def groups_by_cytology(row: dict, p=None) -> list[str]:
if row["result"] is None:
return [NO_DATA]
return [g for g, results in cacu.PROCEDURE_CYTOLOGY.items() if row["result"] in results]
SIGN = {True: "positive", False: "negative"} # SQLite answers booleans as 1 and 0: the same keys
def groups_by_hpv(row: dict, p=None) -> list[str]:
"""Her HPV result and, apart, each genotype found (they overlap)."""
said = [SIGN[row["hpv"]]] if row["hpv"] in SIGN else []
return [*said, *(g for g in ("hpv_16", "hpv_18") if row[g])] or [NO_DATA]
def round_of(row: dict, p=None) -> str:
"""Subsequent: screened before, as her form says, or past colposcopy or treatment at the
sample. Initial: the first screening of her life."""
if row["sample_date"] is None:
return NO_DATA
if follow_up_status(row, as_day(row["sample_date"])) in ("post_colposcopy", "post_treatment"):
return "subsequent"
history = row["screening_history"]
return NO_DATA if history is None else "initial" if history == "never" else "subsequent"
def hpv_genotype(row: dict) -> str:
"""What an HPV report says, a null never read as a negative."""
hpv, found = row["hpv"], [g for g in ("16", "18") if row[f"hpv_{g}"]]
if not hpv:
return "inconsistent" if found else "no_result" if hpv is None else "negative"
if row["hpv_16"] is None or row["hpv_18"] is None:
return "positive_incomplete"
return "positive_" + ("_".join(found) or "other")
def biopsy_answer(row: dict) -> str:
"""What became of a biopsy requested, by its report."""
if row["report_date"] is None:
return "pending"
if as_day(row["report_date"]) < as_day(row["date"]):
return "inconsistent"
if row["histology"] is None:
return "no_grade"
return "high_grade" if row["histology"] in cacu.CIN2_PLUS else "below_high_grade"
def ppv(id: str, title: str, procedure: str, counted) -> Measure:
"""Of the patients with the procedure in the period (her first), those whose histology is
LIEBG or more; those already cases are left out."""
levels = tuple((name, lambda r, grades=grades: r["histology"] in grades)
for name, grades in cacu.PROCEDURE_HISTOLOGY.items()) # fmt: skip
return Measure(
id, title, "procedures",
Proportion(levels[0][1], denominator=lambda r: counted(r) and not case_before(r),
order=earliest, levels=levels, date="date",
strata=(("cytology", groups_by_cytology), ("hpv", groups_by_hpv),
("round", round_of))),
params={"type": procedure},
facts={"report_known_at": ("histology", "report_date"),
"cytology_known_at": ("result", "hpv", "hpv_16", "hpv_18")},
dated={"report_date": ("histology",)},
) # fmt: skip
H = cacu.HORIZONS
NO_HISTORY = lambda row: row["history"] == 0 # noqa: E731 -- no cervical cancer note before
AGE = ("age_group", lambda row, p: age_group(row.get("birth_date"), p.start, cacu.AGE_GROUPS))
STATUS = ("follow_up_status", lambda row, p: follow_up_status(row, p.start))
RESULT = ("result", lambda row, p: row["result"])
MEASURES = {m.id: m for m in [
Measure("IND1", "Pacientes con citología anormal", "samples",
Proportion(lambda r: r["result"] in cacu.ABNORMAL), "decrease", group="principal"),
Measure("CACU_EU13", "Tasa de detección histopatológica", "sample_biopsies",
Proportion(lambda r: r.get("histology") in cacu.DETECTION
and r.get("biopsy_report_date") is not None,
strata=(AGE, STATUS)), group="principal"),
Measure("CACU_EU7", "Pacientes evaluadas por resultado de citología", "samples",
Composition(latest, result, strata=(AGE, STATUS, ("round", round_of)))),
Measure("CACU_VPH", "Pacientes evaluadas por resultado de VPH", "samples",
Composition(lambda r: (as_day(r["sample_date"]), r["sample_id"]),
lambda r: SIGN[r["hpv"]],
where=lambda r: r["hpv"] is not None,
strata=(AGE, STATUS, ("round", round_of),
*((g, lambda r, p, g=g: SIGN.get(r[g], []))
for g in ("hpv_16", "hpv_18")))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18")}),
Measure("CACU_VPH_GENOTIPO", "Resultados de VPH por genotipo", "samples",
Composition(lambda r: (), hpv_genotype, unit="sample_id",
where=lambda r: r["report_date"] is not None and any(
r[c] is not None for c in ("hpv", "hpv_16", "hpv_18"))),
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18", "report_date")},
description="Reportes de VPH, por fecha de toma."),
Measure("CACU_BIOPSIA_RESULTADOS", "Resultados de biopsia cervical", "procedures",
Composition(lambda r: (), lambda r: r["histology"] or NO_DATA,
unit="procedure_id", date="report_date",
where=lambda r: r["report_date"] is not None),
params={"type": "biopsy"}, known="report_known_at",
description="Reportes de biopsia, por fecha de reporte."),
Measure("CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"Confirmación por solicitudes de biopsia", "procedures",
Composition(lambda r: (), biopsy_answer, unit="procedure_id", date="date"),
params={"type": "biopsy"},
facts={"report_known_at": ("histology", "report_date")},
dated={"report_date": ("histology",)},
description="Solicitudes de biopsia registradas, por fecha de solicitud."),
ppv("CACU_VPP_COLPOSCOPIA", "Valor predictivo positivo de la colposcopía", "colposcopy",
lambda r: True),
ppv("CACU_VPP_BIOPSIA", "Valor predictivo positivo de la biopsia", "biopsy",
lambda r: r["histology"] is not None and r["report_date"] is not None),
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Tiempo de tamizaje a diagnóstico por CIE-10",
"samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY,
strata=(("diagnosis_code",
lambda r, p: r["diagnosis_code"] or NO_DATA),)), "decrease"),
Measure("CACU_CONFIRMACION_CITOLOGIA", "Confirmación histopatológica", "sample_biopsies",
Composition(latest_most_severe_biopsy, histology,
admit=lambda r: valid(r) and r["result"] in cacu.HIGH_GRADE,
strata=(RESULT,))),
Measure("CACU_EU_TIEMPO_REPORTE", "Tiempo de toma a resultado de citología", "samples",
Duration("days_sample_result", "result_date", "sample_date", H["sample_to_report"],
ended="report_date"), "decrease"),
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "samples",
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Tiempo de tamizaje a tratamiento", "samples",
Duration("days_sample_treatment", "treatment_date", "sample_date",
H["sample_to_treatment"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Tiempo de diagnóstico a tratamiento", "samples",
Duration("days_diagnosis_treatment", "diagnosis_treatment_date", "diagnosis_date",
H["diagnosis_to_treatment"],
units=lambda r: r["history"] == 0 and r["diagnosis_date"] is not None),
"decrease"),
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Tiempo de toma de muestra a colposcopía", "samples",
Duration("days_sample_colposcopy", "colposcopy_date", "sample_date",
H["sample_to_colposcopy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_TOMA_BIOPSIA", "Tiempo de toma de muestra a resultado de biopsia", "samples",
Duration("days_sample_biopsy", "biopsy_date", "sample_date",
H["sample_to_biopsy"], units=NO_HISTORY), "decrease"),
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Tiempo de resultado a colposcopía", "samples",
Duration("days_result_colposcopy", "result_colposcopy_date", "result_date",
H["result_to_colposcopy"],
units=lambda r: r["history"] == 0 and r["result_date"] is not None),
"decrease"),
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Tiempo de colposcopía a biopsia", "samples",
Duration("days_colposcopy_biopsy", "biopsy_date", "result_colposcopy_date",
H["colposcopy_to_biopsy"],
units=lambda r: r["history"] == 0
and r["result_colposcopy_date"] is not None), "decrease"),
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Tiempo de biopsia a diagnóstico", "samples",
Duration("days_biopsy_diagnosis", "biopsy_diagnosis_date", "biopsy_date",
H["biopsy_to_diagnosis"],
units=lambda r: r["history"] == 0 and r["biopsy_date"] is not None),
"decrease"),
Measure("CACU_RIESGO_BANDA", "Banda de riesgo de CIN2+ en vigilancia", "risk",
RiskBand(tuple(cacu.RISK_BANDS)),
periods=("semester",), params={"model": cacu.RISK_BAND_MODEL}),
]} # fmt: skip