CaCu: procedures with their cytology and histology, seven measures, the cytology form's fields
ci / python (push) Successful in 51m44s
ci / web (push) Successful in 16m59s

This commit is contained in:
Roberto Treviño
2026-11-30 23:32:01 -06:00
parent 4ddbabd90c
commit 2fe5301fd1
22 changed files with 1277 additions and 53 deletions
+11
View File
@@ -40,6 +40,7 @@ POST_TREATMENT_INDEX_AFTER_DAYS = 90 # the index cytology comes this long after
POST_TREATMENT_LOOKBACK_DAYS = 365 # a biopsy result this long before treatment is required
POST_COLPOSCOPY_VISIT = 1 # index: the k-th surveillance cytology after the colposcopy result
REFERRAL_LOOKBACK_DAYS = 365 # results this long before colposcopy are why she was referred
CYTOLOGY_BEFORE_DAYS = 365 # a procedure's cytology was reported this long before at most
HYSTERECTOMY_ICD10 = ["Z907"]
# Inferred procedures, from clinical notes (ICD-10 without the dot).
@@ -70,6 +71,16 @@ ABNORMAL = ["ASC-US", "ASC-H", "LSIL", "HSIL", "CIS"] # IND1
HIGH_GRADE = ["ASC-H", "HSIL", "CIS"] # cytology that should be confirmed by biopsy
DETECTION = ["HSIL", "CIS", "carcinoma"] # biopsy grades counted as detected (EU13)
BIOPSY_SEVERITY = ["normal", "LSIL", "HSIL", "CIS", "carcinoma"] # least to most severe
# The PPVs of a procedure: groups of its cytology (each holds the more severe squamous ones)
# and of its histology; the first histology group is the score's.
PROCEDURE_CYTOLOGY = {
"ascus_plus": ["ASC-US", "LSIL", "ASC-H", "HSIL", "CIS"],
"lsil_plus": ["LSIL", "ASC-H", "HSIL", "CIS"],
"hsil_plus": ["HSIL", "CIS"],
}
PROCEDURE_HISTOLOGY = {
"cin1_plus": ["LSIL", *CIN2_PLUS], "cin2_plus": CIN2_PLUS, "carcinoma": CANCER,
} # fmt: skip
AGE_GROUPS = [(25, 34), (35, 44), (45, 54), (55, 64)] # plus "<25" and "65+"
RISK_BAND_MODEL = "cacu.cin2_pim" # whose risk at the index visit is banded (surveillance)
RISK_BANDS = [("low", 0.04), ("intermediate", 0.25), ("high", None)] # below each cut
+1 -1
View File
@@ -15,7 +15,7 @@ DEFAULT_HORIZON = 5.0
WINDOWS = cacu.FOLLOW_UP_WINDOWS
STATUS_SYSTEM = "cacu-follow-up-status"
PROCEDURES = ("colposcopy", "treatment")
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"} # days from the sample to its diagnosis
REPORT_FACTS = {"cervical_cytology": "route"} # what followed the sample
def status(row: dict, cutoff: date) -> str:
+112 -1
View File
@@ -63,6 +63,80 @@ def histology(row: dict) -> str:
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))
@@ -76,7 +150,44 @@ MEASURES = {m.id: m for m in [
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))),
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,
+72
View File
@@ -7,6 +7,49 @@ cervical_cytology:
report: {date: report_date, parent: sample}
fields:
sample_date: {type: date, event: sample, title: Fecha de toma, required: true}
screening_history:
type: code
event: sample
title: Detección de cáncer de cérvix
system: cervical-screening-history
codes:
never: Primera vez en la vida
within_1_year: Un año o menos
2_years: Dos años
3_or_more_years: Tres o más años
gynecologic_condition:
type: code
event: sample
title: Condición ginecoobstétrica a la detección
system: gynecologic-condition
codes:
postpartum: Puerperio posparto o posaborto
pregnant: Embarazo actual
iud: DIU in situ
hormonal_treatment: Tratamiento hormonal
other_treatment: Otro tratamiento ginecológico
postmenopausal: Posmenopausia
hysterectomy: Histerectomía
not_applicable: No aplica
presenting_symptom:
type: code
event: sample
title: Actualmente presenta
system: presenting-symptom
codes:
discharge: Flujo
vulvar_itching: Prurito o ardor vulvar
abnormal_bleeding: Sangrado anormal
none: Ninguno
cervix_appearance:
type: code
event: sample
title: A la exploración se observa
system: cervix-appearance
codes:
healthy: Cuello sano
lesion: Cuello anormal con lesión
not_seen: No se observa cuello
report_date: {type: date, event: report, title: Fecha de reporte}
adequacy:
type: code
@@ -29,6 +72,35 @@ cervical_cytology:
hpv: {type: boolean, event: report, title: VPH de alto riesgo}
hpv_16: {type: boolean, event: report, title: VPH 16}
hpv_18: {type: boolean, event: report, title: VPH 18}
# What the cytologist adds in words. A finding is true when stated, otherwise unknown.
findings: {type: text, event: report, title: Hallazgos adicionales}
finding_inflammation: {type: boolean, event: report, title: "Hallazgo: inflamación"}
finding_reactive: {type: boolean, event: report, title: "Hallazgo: cambios reactivos"}
finding_vaginosis: {type: boolean, event: report, title: "Hallazgo: cambio en la flora sugestiva de vaginosis bacteriana"}
finding_candida: {type: boolean, event: report, title: "Hallazgo: microorganismos micóticos morfológicamente compatibles con Candida sp"}
finding_bacillary_cytolysis: {type: boolean, event: report, title: "Hallazgo: aumento de la flora bacilar con citólisis de las células intermedias"}
finding_cytolysis: {type: boolean, event: report, title: "Hallazgo: citólisis de las células intermedias"}
finding_trichomonas: {type: boolean, event: report, title: "Hallazgo: trichomonas vaginalis"}
finding_leptothrix: {type: boolean, event: report, title: "Hallazgo: microorganismos bacterianos morfológicamente compatibles con Leptothrix"}
finding_actinomyces: {type: boolean, event: report, title: "Hallazgo: microorganismos morfológicamente compatibles con Actinomyces sp"}
finding_actinomyces_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con Actinomyces sp"}
finding_herpes_changes: {type: boolean, event: report, title: "Hallazgo: cambios celulares compatibles con virus herpes simple"}
finding_tubular_metaplasia: {type: boolean, event: report, title: "Hallazgo: metaplasia escamosa tubular"}
finding_keratotic: {type: boolean, event: report, title: "Hallazgo: cambios queratósicos"}
finding_pregnancy: {type: boolean, event: report, title: "Hallazgo: cambios asociados al embarazo"}
finding_atrophy: {type: boolean, event: report, title: "Hallazgo: atrofia"}
finding_hypoestrogenism: {type: boolean, event: report, title: "Hallazgo: hipoestrogenismo"}
finding_radiotherapy: {type: boolean, event: report, title: "Hallazgo: efecto de radioterapia"}
finding_iud_changes: {type: boolean, event: report, title: "Hallazgo: cambios compatibles con presencia de dispositivo intrauterino"}
finding_glandular_cells: {type: boolean, event: report, title: "Hallazgo: células glandulares post-histerectomía"}
finding_bacteria: {type: boolean, event: report, title: "Hallazgo: bacterias"}
finding_herpes_image: {type: boolean, event: report, title: "Hallazgo: imagen del virus del herpes"}
finding_fungi: {type: boolean, event: report, title: "Hallazgo: hongos"}
finding_radiation: {type: boolean, event: report, title: "Hallazgo: radiación"}
finding_repair: {type: boolean, event: report, title: "Hallazgo: reparación"}
finding_iud_effect: {type: boolean, event: report, title: "Hallazgo: efecto del DIU"}
finding_endometrial_cells: {type: boolean, event: report, title: "Hallazgo: presencia de células endometriales en pacientes de 40 años o más"}
finding_none: {type: boolean, event: report, title: "Hallazgo: ninguno"}
cervical_biopsy:
title: Biopsia cervical
+12
View File
@@ -6,6 +6,18 @@ bethesda:
who-cervical-histology:
url: https://isssteleon.org/fhir/CodeSystem/who-cervical-histology
title: Clasificación OMS de lesiones cervicales (histología)
cervical-screening-history:
url: https://isssteleon.org/fhir/CodeSystem/cervical-screening-history
title: Detección de cáncer de cérvix
gynecologic-condition:
url: https://isssteleon.org/fhir/CodeSystem/gynecologic-condition
title: Condición ginecoobstétrica a la detección
presenting-symptom:
url: https://isssteleon.org/fhir/CodeSystem/presenting-symptom
title: Actualmente presenta
cervix-appearance:
url: https://isssteleon.org/fhir/CodeSystem/cervix-appearance
title: A la exploración se observa
bi-rads:
url: https://isssteleon.org/fhir/CodeSystem/bi-rads
title: BI-RADS
+33 -3
View File
@@ -66,7 +66,10 @@ CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
"measure-stratifier": ("Estratos de indicadores", {
"category": "Categoría", "age_group": "Grupo de edad",
"follow_up_status": "Estatus de seguimiento", "result": "Citología de alto grado",
"birads": "BI-RADS de la mastografía",
"birads": "BI-RADS de la mastografía", "diagnosis_code": "Diagnóstico CIE-10",
"cytology": "Citología previa", "hpv": "VPH de la citología previa",
"level": "Histología confirmada", "round": "Tamizaje inicial o subsecuente",
"hpv_16": "VPH 16", "hpv_18": "VPH 18",
}),
"risk-model": ("Modelos de riesgo", {}), # open: a model's name is its code
} # fmt: skip
@@ -91,18 +94,28 @@ CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
f"{n}.{f}": d.title for n, s in catalog.studies().items() for f, d in s.fields.items()
}) # fmt: skip
# Where a duration is scored: the whole, and each stratum with a score of its own.
DURATIONS = ["MeasureReport.group.measureScore",
"MeasureReport.group.stratifier.stratum.measureScore"] # fmt: skip
# Our extensions: name -> (value type, the elements they extend).
EXTENSIONS: dict[str, tuple[str, list[str]]] = {
"ic-bajo": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"ic-alto": ("decimal", ["MeasureReport.group.measureScore", "RiskAssessment.prediction"]),
"q1": ("decimal", ["MeasureReport.group.measureScore"]),
"q3": ("decimal", ["MeasureReport.group.measureScore"]),
"q1": ("decimal", DURATIONS),
"q3": ("decimal", DURATIONS),
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
"period-type": ("code", ["Measure"]),
"follow-up-status": ("Coding", ["Patient"]),
"follow-up-priority": ("Coding", ["Patient"]),
"report-date": ("date", ["DiagnosticReport"]),
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
# what followed a cytology: colposcopy and diagnosis are inferred; `biopsy-link` says
# whether the biopsy's record names the cytology (recorded) or its dates do (inferred)
"colposcopy-date": ("date", ["DiagnosticReport"]),
"biopsy-request-date": ("date", ["DiagnosticReport"]),
"biopsy-date": ("date", ["DiagnosticReport"]),
"biopsy-link": ("code", ["DiagnosticReport"]),
"diagnosis-date": ("date", ["DiagnosticReport"]),
# a clinical scenario of the model's report the person falls in (its curves)
"escenario-clinico": ("string", ["RiskAssessment"]),
# a child on TEA's list: her age group, case, EEG and scores
@@ -153,6 +166,21 @@ def ext(name: str, value_type: str, value) -> dict:
return {"url": EXTENSION + name, f"value{value_type[0].upper()}{value_type[1:]}": value}
# A report's facts (a domain's `REPORT_FACTS` read): their column -> the extension.
_REPORT_FACTS = {"days": "days-to-diagnosis", "colposcopy": "colposcopy-date",
"requested": "biopsy-request-date", "biopsy": "biopsy-date",
"link": "biopsy-link", "diagnosis": "diagnosis-date"} # fmt: skip
def report_facts(row: dict) -> list[dict]:
found = []
for column, name in _REPORT_FACTS.items():
if (value := row.get(column)) is not None:
kind = EXTENSIONS[name][0]
found.append(ext(name, kind, {"integer": int, "date": _day}.get(kind, str)(value)))
return found
def subject(person_id: str) -> dict:
return {"reference": f"Patient/{person_id}"}
@@ -439,6 +467,8 @@ def measure(m, domain: str) -> Measure:
"extension": [ext("period-type", "code", p) for p in m.periods],
"group": [group],
} # fmt: skip
if m.description:
found["description"] = m.description
if m.improvement:
found["improvementNotation"] = {"coding": [{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
+73 -26
View File
@@ -99,8 +99,13 @@ def age_group(birth, at: date, groups: list[tuple[int, int]]) -> str:
return f"<{lowest}" if age < lowest else f"{highest + 1}+"
# A stratum: its name and the value a row takes in a period.
Stratum = tuple[str, Callable[[dict, "Period"], str]]
# A stratum: its name and the value a row takes in a period; a list when it takes several (its
# groups overlap) or none.
Stratum = tuple[str, Callable[[dict, "Period"], "str | list[str]"]]
def groups(value: "str | list[str]") -> list[str]:
return [value] if isinstance(value, str) else value
@dataclass(frozen=True)
@@ -115,6 +120,8 @@ class Result:
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = field(
default_factory=dict
)
# A stratum value's own score: (stratum, value) -> score, its extensions and unit.
scores: dict[tuple[str, str], tuple[float, dict[str, float], str]] = field(default_factory=dict)
def wilson(k: int, n: int) -> tuple[float, float]:
@@ -127,11 +134,15 @@ def wilson(k: int, n: int) -> tuple[float, float]:
@dataclass(frozen=True)
class Proportion:
"""Units with a row dated in the period that meets `denominator` and, of them, those
with such a row that also meets `numerator`; with a Wilson 95% interval."""
with such a row that also meets `numerator`; with a Wilson 95% interval. With `order`, a
unit counts with one row only, the one it ranks highest. `levels` are other numerators
over the same denominator: the stratifier `level`."""
numerator: Callable[[dict], bool]
strata: tuple[Stratum, ...] = ()
denominator: Callable[[dict], bool] = lambda row: True
order: Callable[[dict], tuple] | None = None
levels: tuple[tuple[str, Callable[[dict], bool]], ...] = ()
unit: str = "person_id"
date: str = "sample_date"
kind: str = "proportion"
@@ -140,6 +151,8 @@ class Proportion:
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
mine = [r for r in rows if r[self.date] in period and self.denominator(r)]
if self.order:
mine = list({r[self.unit]: r for r in sorted(mine, key=self.order)}.values())
den = {r[self.unit]: r for r in mine}
num = {r[self.unit] for r in mine if self.numerator(r)}
found = {"initial-population": len(den), "denominator": len(den), "numerator": len(num)}
@@ -147,14 +160,19 @@ class Proportion:
for name, stratum in self.strata:
values: dict[str, dict[str, int]] = {}
for unit, row in den.items():
cell = values.setdefault(
stratum(row, period),
{"initial-population": 0, "denominator": 0, "numerator": 0},
)
cell["initial-population"] += 1
cell["denominator"] += 1
cell["numerator"] += unit in num
for value in groups(stratum(row, period)):
cell = values.setdefault(
value, {"initial-population": 0, "denominator": 0, "numerator": 0}
)
cell["initial-population"] += 1
cell["denominator"] += 1
cell["numerator"] += unit in num
strata[name] = values
if self.levels and den:
strata["level"] = {
level: {**found, "numerator": len({r[self.unit] for r in mine if meets(r)})}
for level, meets in self.levels
}
if not den:
return Result(found, strata=strata)
low, high = wilson(len(num), len(den))
@@ -195,21 +213,30 @@ class Composition:
for name, stratum in (("category", lambda row, p: self.category(row)), *self.strata):
values: dict[str, dict[str, int]] = {}
for row in chosen.values():
value = stratum(row, period)
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
for value in groups(stratum(row, period)):
values.setdefault(value, {"initial-population": 0})["initial-population"] += 1
strata[name] = values
crossed: dict[tuple[str, str], dict[tuple[str, str], dict[str, int]]] = {}
for name, stratum in self.strata: # each also by category
pairs: dict[tuple[str, str], dict[str, int]] = {}
for row in chosen.values():
key = (stratum(row, period), self.category(row))
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
for value in groups(stratum(row, period)):
key = (value, self.category(row))
pairs.setdefault(key, {"initial-population": 0})["initial-population"] += 1
crossed[(name, "category")] = pairs
n = len(chosen)
return Result({"initial-population": n, "measure-observation": n}, strata=strata,
crossed=crossed) # fmt: skip
def quartiles(values: list[float]) -> tuple[float, dict[str, float]]:
"""The median, and the quartiles as score extensions."""
if len(values) == 1:
return values[0], {"q1": values[0], "q3": values[0]}
q1, median, q3 = statistics.quantiles(values, n=4, method="inclusive")
return median, {"q1": q1, "q3": q3}
@dataclass(frozen=True)
class Duration:
"""Days from `start` to `end` per unit (`value`), within `horizon` days. A unit whose
@@ -222,6 +249,7 @@ class Duration:
horizon: int
units: Callable[[dict], bool] = lambda row: True
ended: str | None = None
strata: tuple[Stratum, ...] = ()
unit: str = "sample_id"
date: str = "sample_date"
kind: str = "continuous-variable"
@@ -231,6 +259,7 @@ class Duration:
def evaluate(self, rows: list[dict], period: Period, cutoff: date) -> Result:
measured, initial = [], 0
grouped: dict[str, dict[str, list[float]]] = {name: {} for name, _ in self.strata}
for row in {r[self.unit]: r for r in rows}.values():
if row[self.date] not in period or not self.units(row):
continue
@@ -238,6 +267,9 @@ class Duration:
has = row.get(self.value) is not None and end is not None and end <= cutoff
if has:
measured.append(float(row[self.value]))
for name, stratum in self.strata:
for value in groups(stratum(row, period)):
grouped[name].setdefault(value, []).append(measured[-1])
stop = as_day(row.get(self.ended)) if self.ended else None
done = has or (stop is not None and stop <= cutoff)
pending = not done and (cutoff - as_day(row[self.start])).days < self.horizon
@@ -245,11 +277,14 @@ class Duration:
found = {"initial-population": initial, "measure-observation": len(measured)}
if not measured:
return Result(found)
if len(measured) == 1:
q1 = median = q3 = measured[0]
else:
q1, median, q3 = statistics.quantiles(measured, n=4, method="inclusive")
return Result(found, median, {"q1": q1, "q3": q3}, unit="d")
median, spread = quartiles(measured)
return Result(
found, median, spread, unit="d",
strata={name: {v: {"measure-observation": len(days)} for v, days in values.items()}
for name, values in grouped.items()},
scores={(name, v): (*quartiles(days), "d")
for name, values in grouped.items() for v, days in values.items()},
) # fmt: skip
@dataclass(frozen=True)
@@ -399,6 +434,9 @@ class Measure:
# Facts a row carries that became known apart from the row itself: their `known_at`
# column -> the columns they fill. Asked `as_of` before then, the row has them empty.
facts: dict[str, tuple[str, ...]] = field(default_factory=dict)
# The same by the event cutoff: a date column -> the columns it dates.
dated: dict[str, tuple[str, ...]] = field(default_factory=dict)
description: str | None = None
def evaluate(
@@ -412,6 +450,10 @@ def evaluate(
count to `event_cutoff` (default: `as_of`'s day, or today)."""
as_of = _moment(as_of)
cutoff = event_cutoff or (as_of or datetime.now(UTC)).date()
if measure.dated:
rows = [{**row, **dict.fromkeys(c for day, cols in measure.dated.items()
if (as_day(row.get(day)) or cutoff) > cutoff
for c in (day, *cols))} for row in rows] # fmt: skip
if as_of is None: # every row and fact is known
return measure.rule.evaluate(rows if isinstance(rows, list) else list(rows), period, cutoff)
@@ -458,6 +500,14 @@ def _population(code: str, count: int) -> dict:
return {"code": {"coding": [{"system": POPULATION, "code": code}]}, "count": count}
def _score(value: float, extensions: dict[str, float], unit: str | None) -> dict:
return {
"value": value,
**({"unit": unit} if unit else {}),
"extension": [{"url": EXTENSION + k, "valueDecimal": v} for k, v in extensions.items()],
}
def report(
measure: Measure, period: Period, result: Result, as_of: datetime | None
) -> MeasureReport:
@@ -467,19 +517,16 @@ def report(
"population": [_population(c, n) for c, n in result.populations.items()],
}
if result.score is not None:
group["measureScore"] = {
"value": result.score,
**({"unit": result.unit} if result.unit else {}),
"extension": [{"url": EXTENSION + k, "valueDecimal": v}
for k, v in result.score_extensions.items()],
} # fmt: skip
group["measureScore"] = _score(result.score, result.score_extensions, result.unit)
elif measure.rule.kind == "composition": # a cohort scores its count
group["measureScore"] = {"value": result.populations["initial-population"]}
if result.strata:
group["stratifier"] = [
{"id": name, "code": [stratifier_code(name)],
"stratum": [{"value": {"text": value},
"population": [_population(c, n) for c, n in cells.items()]}
"population": [_population(c, n) for c, n in cells.items()],
**({"measureScore": _score(*result.scores[name, value])}
if (name, value) in result.scores else {})}
for value, cells in sorted(values.items())]}
for name, values in result.strata.items()
] + [
+1 -1
View File
@@ -400,7 +400,7 @@ def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
target holds it with the reason."""
if not isinstance(raw, str):
return raw
raw = raw.strip()
raw = _SPACE.sub(" ", raw.strip()) # a value read across a line break is one value
raw = codes.get(field, {}).get(raw.casefold(), raw)
fmt = node.formats.get(field)
if fmt and fmt.startswith("dateparser:"):
@@ -0,0 +1,75 @@
{#
One row per colposcopy day and per biopsy of a patient, with the cytology that led to it and
the histology that answers it.
- The cytology: the one the biopsy's record names (`link` recorded), else her latest valid
one reported before the procedure, at most CYTOLOGY_BEFORE_DAYS before (inferred).
- A colposcopy's histology: the most severe reported of the biopsies requested from that day
and within the colposcopy_to_biopsy horizon.
cacu_events also dates a colposcopy at the report of a biopsy taken at it: not a day of one.
#}
{% set p = var('cacu') %}
with biopsy as (
select
person_id, request_date as date, cytology_sample_date as recorded, report_date, histology,
known_at, report_known_at,
case
{%- for grade in p.biopsy_severity %}
when histology = '{{ grade }}' then {{ loop.index }}
{%- endfor %}
else 0
end as severity
from {{ ref('cervical_biopsy') }}
),
colposcopy as (
select person_id, date, min(known_at) as known_at
from {{ ref('cacu_events') }}
where type = 'colposcopy'
and not (source_table = 'cervical_biopsy' and source_id <> cast(date as {{ dbt.type_string() }}))
group by person_id, date
),
answered as (
select
c.person_id, c.date, b.report_date, b.histology, b.report_known_at,
row_number() over (partition by c.person_id, c.date
order by b.severity desc, b.report_date, b.date) as n
from colposcopy as c
join biopsy as b on b.person_id = c.person_id and b.date >= c.date
where b.histology is not null and b.report_date is not null
and {{ days_between('c.date', 'b.date') }} <= {{ p.horizons.colposcopy_to_biopsy }}
),
procedures as (
select 'biopsy' as type, person_id, date, recorded, report_date, histology,
known_at, report_known_at
from biopsy
union all
select 'colposcopy', c.person_id, c.date, null, a.report_date, a.histology,
c.known_at, a.report_known_at
from colposcopy as c
left join answered as a on a.person_id = c.person_id and a.date = c.date and a.n = 1
),
referred as (
select
x.type, x.person_id, x.date, c.sample_date,
row_number() over (partition by x.type, x.person_id, x.date
order by c.sample_date desc, c.report_date desc) as n
from procedures as x
join {{ ref('cervical_cytology') }} as c on c.person_id = x.person_id
where c.result is not null and coalesce(c.adequacy, '') <> 'unsatisfactory'
and c.sample_date < x.date and c.report_date < x.date
and {{ days_between('c.report_date', 'x.date') }} <= {{ p.cytology_before_days }}
)
select
{{ dbt.concat(['x.person_id', "'|'", 'cast(x.date as ' ~ dbt.type_string() ~ ')']) }} as procedure_id,
x.type, x.person_id, x.date,
coalesce(x.recorded, r.sample_date) as sample_date,
case when x.recorded is not null then 'recorded'
when r.sample_date is not null then 'inferred' end as link,
x.report_date, x.histology, x.known_at, x.report_known_at
from procedures as x
left join referred as r
on r.type = x.type and r.person_id = x.person_id and r.date = x.date and r.n = 1
@@ -2,8 +2,8 @@
BIOPSY_SEVERITY, from 1; -1 a report without a grade, 0 a grade outside it). #}
{% set p = var('cacu') %}
select
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.cytology_sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.request_date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
{{ dbt.concat(['b.person_id', "'|'", 'cast(b.date as ' ~ dbt.type_string() ~ ')']) }} as biopsy_id,
b.report_date, b.histology, b.known_at,
case
when b.histology is null then -1
@@ -12,5 +12,5 @@ select
{%- endfor %}
else 0
end as severity
from {{ ref('cervical_biopsy') }} as b
where b.cytology_sample_date is not null
from {{ ref('cacu_procedures') }} as b
where b.type = 'biopsy' and b.sample_date is not null
@@ -12,6 +12,7 @@
with sample as (
select
c.person_id, c.sample_date, c.report_date, c.result, c.adequacy, c.known_at,
c.report_known_at, c.screening_history, c.hpv, c.hpv_16, c.hpv_18,
case when c.result is not null then c.report_date end as result_date,
{{ dbt.concat(['c.person_id', "'|'", 'cast(c.sample_date as ' ~ dbt.type_string() ~ ')']) }} as sample_id,
p.birth_date
@@ -29,13 +30,23 @@ events as (select * from {{ ref('cacu_events') }}),
biopsy as (
select s.sample_id, min(b.report_date) as date
from sample as s
join {{ ref('cervical_biopsy') }} as b
on b.person_id = s.person_id and b.cytology_sample_date = s.sample_date
join {{ ref('cacu_procedures') }} as b
on b.type = 'biopsy' and b.person_id = s.person_id and b.sample_date = s.sample_date
where b.report_date > s.sample_date
and {{ days_between('s.sample_date', 'b.report_date') }} < {{ h.sample_to_biopsy }}
group by s.sample_id
),
diagnosis_code as ( -- the ICD-10 of the note that dates the diagnosis
select d.sample_id, count(distinct n.value_code) as codes, min(n.value_code) as code
from diagnosis as d
join sample as s on s.sample_id = d.sample_id
join events as e on e.person_id = s.person_id and e.type = 'diagnosis' and e.date = d.date
join events as n on n.person_id = e.person_id and n.type = 'note' and n.date = e.date
and n.source_id = e.source_id
group by d.sample_id
),
diagnosis_treatment as (
select d.sample_id, min(e.date) as date
from diagnosis as d
@@ -62,6 +73,7 @@ select
f.first_colposcopy,
{{ days_between('s.sample_date', 's.result_date') }} as days_sample_result,
dx.date as diagnosis_date,
case when dc.codes > 1 then 'several' else dc.code end as diagnosis_code,
{{ days_between('s.sample_date', 'dx.date') }} as days_sample_diagnosis,
tx.date as treatment_date,
{{ days_between('s.sample_date', 'tx.date') }} as days_sample_treatment,
@@ -83,6 +95,7 @@ select
from sample as s
left join {{ ref('cacu_follow_up') }} as f on f.person_id = s.person_id
left join diagnosis as dx on dx.sample_id = s.sample_id
left join diagnosis_code as dc on dc.sample_id = s.sample_id
left join treatment as tx on tx.sample_id = s.sample_id
left join diagnosis_treatment as dt on dt.sample_id = s.sample_id
left join colposcopy as col on col.sample_id = s.sample_id
+17 -5
View File
@@ -66,11 +66,23 @@ READS = {
group by person_id) as w on w.person_id = x.person_id
order by w.recent desc, x.person_id
""",
# Days from a sample to its diagnosis, when known by the cut-off (gold).
"diagnosis_days": """
select person_id, sample_date, days_sample_diagnosis as days
from gold.cacu_samples
where person_id in :persons and history = 0 and diagnosis_date <= :cutoff
# What followed each sample by the cut-off (gold): her colposcopy, her biopsy (its first
# request, and its report) and her diagnosis, with the days to it.
"route": """
select s.person_id, s.sample_date,
case when s.history = 0 and s.diagnosis_date <= :cutoff
then s.days_sample_diagnosis end as days,
case when s.diagnosis_date <= :cutoff then s.diagnosis_date end as diagnosis,
case when s.colposcopy_date <= :cutoff then s.colposcopy_date end as colposcopy,
case when s.biopsy_date <= :cutoff then s.biopsy_date end as biopsy,
b.requested, b.link
from gold.cacu_samples as s
left join (select person_id, sample_date, min(date) as requested, min(link) as link
from gold.cacu_procedures
where type = 'biopsy' and date <= :cutoff and person_id in :persons
group by person_id, sample_date) as b
on b.person_id = s.person_id and b.sample_date = s.sample_date
where s.person_id in :persons
""",
},
"tea": {
+10
View File
@@ -13,6 +13,16 @@ READS = {
from gold.cacu_samples as s
left join gold.cacu_sample_biopsies as b on b.sample_id = s.sample_id
""",
"procedures": """
select p.*, s.result, s.hpv, s.hpv_16, s.hpv_18, s.screening_history,
s.report_known_at as cytology_known_at,
f.first_case, f.first_treatment, f.first_colposcopy
from gold.cacu_procedures as p
left join gold.cacu_samples as s
on s.person_id = p.person_id and s.sample_date = p.sample_date
left join gold.cacu_follow_up as f on f.person_id = p.person_id
where p.type = :type
""",
"risk": """
select c.person_id, coalesce(r.index_date, c.index_date) as index_date,
r.probability, r.scored_at as known_at
+1 -1
Submodule WebApi updated: d92d1697b8...bd06a31d52
+1 -1
Submodule WebApp updated: 053679c817...fe4dd55452
+1 -1
Submodule models updated: 77350b8fec...1a1ea5c7a9
+78
View File
@@ -0,0 +1,78 @@
"""What the cytology form records beside its result, and a made-up answer to it."""
import random
# The cytology form's boxes 2 to 5 (field -> code -> as printed) and the cytologist's findings.
BOXES = {
"screening_history": {
"never": "PRIMERA VEZ EN LA VIDA",
"within_1_year": "UN AÑO O MENOS",
"2_years": "2 AÑOS",
"3_or_more_years": "3 O MÁS AÑOS",
},
"gynecologic_condition": {
"postpartum": "PUERPERIO POSTPARTO O POSTABORTO",
"pregnant": "EMBARAZO ACTUAL",
"iud": "DIU IN SITU",
"hormonal_treatment": "TRATAMIENTO HORMONAL",
"other_treatment": "OTRO TRATAMIENTO GINECOLÓGICO",
"postmenopausal": "POST MENOPAUSIA",
"hysterectomy": "HISTERECTOMÍA",
"not_applicable": "NO APLICA",
},
"presenting_symptom": {
"discharge": "FLUJO",
"vulvar_itching": "PRURITO O ARDOR VULVAR",
"abnormal_bleeding": "SANGRADO ANORMAL",
"none": "NINGUNO",
},
"cervix_appearance": {
"healthy": "CUELLO SANO",
"lesion": "CUELLO ANORMAL CON LESIÓN",
"not_seen": "NO SE OBSERVA CUELLO",
},
}
CYTOLOGY_FINDINGS = {
"finding_inflammation": "Inflamación",
"finding_reactive": "Cambios reactivos",
"finding_vaginosis": "Cambio en la flora sugestiva de vaginosis bacteriana",
"finding_candida": "Microorganismos micóticos morfológicamente compatibles con Candida sp",
"finding_bacillary_cytolysis": (
"Aumento de la flora bacilar con citólisis de las células intermedias"
),
"finding_cytolysis": "Citólisis de las células intermedias",
"finding_trichomonas": "Trichomonas vaginalis",
"finding_leptothrix": "Microorganismos bacterianos morfológicamente compatibles con Leptothrix",
"finding_actinomyces": "Microorganismos morfológicamente compatibles con Actinomyces sp",
"finding_actinomyces_changes": "Cambios celulares compatibles con Actinomyces sp",
"finding_herpes_changes": "Cambios celulares compatibles con virus herpes simple",
"finding_tubular_metaplasia": "Metaplasia escamosa tubular",
"finding_keratotic": "Cambios queratósicos",
"finding_pregnancy": "Cambios asociados al embarazo",
"finding_atrophy": "Atrofia",
"finding_hypoestrogenism": "Hipoestrogenismo",
"finding_radiotherapy": "Efecto de radioterapia",
"finding_iud_changes": "Cambios compatibles con presencia de dispositivo intrauterino",
"finding_glandular_cells": "Células glandulares post-histerectomía",
"finding_bacteria": "Bacterias",
"finding_herpes_image": "Imagen del virus del herpes",
"finding_fungi": "Hongos",
"finding_radiation": "Radiación",
"finding_repair": "Reparación",
"finding_iud_effect": "Efecto del DIU",
"finding_endometrial_cells": "Presencia de células endometriales en pacientes de 40 años o más",
"finding_none": "Ninguno",
}
def answers(rng: random.Random) -> tuple[dict, dict]:
"""The fields the form answers, and each box as printed; one or two findings, or none."""
found = rng.sample(list(CYTOLOGY_FINDINGS)[:-1], rng.choice((0, 1, 1, 2)))
found = found or ["finding_none"] * rng.choice((0, 1))
if sum(len(CYTOLOGY_FINDINGS[f]) for f in found) > 95: # what fits one line of the form
found = found[:1]
boxes = {field: rng.choice(list(codes)) for field, codes in BOXES.items()}
printed = {field: BOXES[field][code] for field, code in boxes.items()}
printed["findings"] = " ".join(f"{CYTOLOGY_FINDINGS[f]}." for f in found)
stated = {"findings": printed["findings"]} if found else {}
return {**boxes, **stated, **dict.fromkeys(found, True)}, printed
+3 -1
View File
@@ -61,7 +61,7 @@ def cytology_form(p: dict, c: dict) -> bytes:
p: full_name, employee, agency, age, birth_date (date), phone.
c: requested (date), received (date), interpreted (date), detection, conditions,
presents, explores, nurse, adequacy, lesion (POSITIVO/NEGATIVO), epithelial (SI/NO),
squamous, invasive (SI/NO), glandular, observations, reader, reader_id."""
squamous, invasive (SI/NO), glandular, findings, observations, reader, reader_id."""
pdf = _pdf()
pdf.set_font("helvetica", "B", 15)
pdf.set_text_color(*GREEN)
@@ -110,6 +110,8 @@ def cytology_form(p: dict, c: dict) -> bytes:
_box(pdf, 50, y, 256, 36, left, lv)
_box(pdf, 306, y, 256, 36, right, rv)
y += 36
_box(pdf, 50, y, 512, 36, "16.- HALLAZGOS ADICIONALES:", c["findings"])
y += 36
_box(pdf, 50, y, 512, 70, value="Observaciones: " + c["observations"], size=7.5)
pdf.set_font("helvetica", "", 8.5)
+9 -5
View File
@@ -32,7 +32,7 @@ import sqlalchemy as sa
from core import catalog, fhir_in
from core.tea import RESTRICTED_REPETITIVE_ITEMS, SOCIAL_AFFECT_ITEMS
from synthetic import erick, pdfs
from synthetic import cytology_form, erick, pdfs
STUDIES = (
"cervical_cytology",
@@ -519,6 +519,7 @@ def build(
people = {k: p for k, p in people.items() if any(p["studies"].values())}
ids = sorted(people)
names = _names(ids, random.Random(f"{seed}-names"), {i: people[i]["sex"] for i in ids})
form_rng = random.Random(f"{seed}-form")
# Namesakes: the woman with the most pathology reports (a scan can misread the name on
# any one of them) takes the name of a woman with none, so a report fits both.
reports = {
@@ -602,14 +603,15 @@ def build(
person, identity = _institute(p, taken, rng, i in sloppy)
result = r.get("result")
satisfactory = r.get("adequacy") == "satisfactory"
answered, printed = cytology_form.answers(form_rng)
form = { # dated as the real forms are: FECHA is filled in days after reception
"requested": max(taken, reported - timedelta(days=rng.randint(2, 6))),
"received": taken,
"interpreted": reported,
"detection": rng.choice(("PRIMERA VEZ", "SUBSECUENTE")),
"conditions": rng.choice(("NINGUNA", "USO DE DIU", "POSTMENOPAUSIA")),
"presents": rng.choice(("ASINTOMÁTICA", "FLUJO TRANSVAGINAL")),
"explores": rng.choice(("CÉRVIX DE ASPECTO NORMAL", "ECTROPIÓN")),
"detection": printed["screening_history"],
"conditions": printed["gynecologic_condition"],
"presents": printed["presenting_symptom"],
"explores": printed["cervix_appearance"],
"nurse": rng.choice(NURSES),
"adequacy": "SATISFACTORIO" if satisfactory else "INSATISFACTORIO",
"lesion": "" if not result else "NEGATIVO" if result == "NILM" else "POSITIVO",
@@ -617,6 +619,7 @@ def build(
"squamous": SQUAMOUS.get(result, ""),
"invasive": "NO" if result else "",
"glandular": "NINGUNA" if result else "",
"findings": printed["findings"],
"observations": "MUESTRA INSUFICIENTE, SE SOLICITA NUEVA TOMA."
if not satisfactory
else "Negativo para lesión intraepitelial o malignidad."
@@ -630,6 +633,7 @@ def build(
"report_date": str(reported),
"adequacy": r.get("adequacy"),
"result": result,
**answered,
}
scanned = rng.random() < 0.1
blob = erick.cytology_form(person, form)
+591
View File
@@ -224,6 +224,348 @@
"equivalence": "equivalent"
}
]
},
{
"code": "INFLAMACIÓN",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "INFLAMACION",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIOS REACTIVOS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIO EN LA FLORA SUGESTIVA DE VAGINOSIS BACTERIANA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "MICROORGANISMOS MICÓTICOS MORFOLÓGICAMENTE COMPATIBLES CON CANDIDA SP",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "MICROORGANISMOS MICOTICOS MORFOLOGICAMENTE COMPATIBLES CON CANDIDA SP",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "AUMENTO DE LA FLORA BACILAR CON CITÓLISIS DE LAS CÉLULAS INTERMEDIAS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "AUMENTO DE LA FLORA BACILAR CON CITOLISIS DE LAS CELULAS INTERMEDIAS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CITÓLISIS DE LAS CÉLULAS INTERMEDIAS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CITOLISIS DE LAS CELULAS INTERMEDIAS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "TRICHOMONAS VAGINALIS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "MICROORGANISMOS BACTERIANOS MORFOLÓGICAMENTE COMPATIBLES CON LEPTOTHRIX",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "MICROORGANISMOS BACTERIANOS MORFOLOGICAMENTE COMPATIBLES CON LEPTOTHRIX",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "MICROORGANISMOS MORFOLÓGICAMENTE COMPATIBLES CON ACTINOMYCES SP",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "MICROORGANISMOS MORFOLOGICAMENTE COMPATIBLES CON ACTINOMYCES SP",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIOS CELULARES COMPATIBLES CON ACTINOMYCES SP",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIOS CELULARES COMPATIBLES CON VIRUS HERPES SIMPLE",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "METAPLASIA ESCAMOSA TUBULAR",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIOS QUERATÓSICOS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIOS QUERATOSICOS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIOS ASOCIADOS AL EMBARAZO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "ATROFIA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "HIPOESTROGENISMO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "EFECTO DE RADIOTERAPIA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CAMBIOS COMPATIBLES CON PRESENCIA DE DISPOSITIVO INTRAUTERINO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CÉLULAS GLANDULARES POST-HISTERECTOMÍA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "CELULAS GLANDULARES POST-HISTERECTOMIA",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "BACTERIAS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "IMAGEN DEL VIRUS DEL HERPES",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "HONGOS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "RADIACIÓN",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "RADIACION",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "REPARACIÓN",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "REPARACION",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "EFECTO DEL DIU",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRESENCIA DE CÉLULAS ENDOMETRIALES EN PACIENTES DE 40 AÑOS O MÁS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "PRESENCIA DE CELULAS ENDOMETRIALES EN PACIENTES DE 40 ANOS O MAS",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
},
{
"code": "NINGUNO",
"target": [
{
"code": "true",
"equivalence": "equivalent"
}
]
}
]
},
@@ -1831,6 +2173,255 @@
]
}
]
},
{
"source": "urn:isssteleon:site:erick_site",
"target": "https://isssteleon.org/fhir/CodeSystem/cervical-screening-history",
"element": [
{
"code": "PRIMERA VEZ EN LA VIDA",
"target": [
{
"code": "never",
"equivalence": "equivalent"
}
]
},
{
"code": "UN AÑO O MENOS",
"target": [
{
"code": "within_1_year",
"equivalence": "equivalent"
}
]
},
{
"code": "UN ANO O MENOS",
"target": [
{
"code": "within_1_year",
"equivalence": "equivalent"
}
]
},
{
"code": "2 AÑOS",
"target": [
{
"code": "2_years",
"equivalence": "equivalent"
}
]
},
{
"code": "2 ANOS",
"target": [
{
"code": "2_years",
"equivalence": "equivalent"
}
]
},
{
"code": "3 O MÁS AÑOS",
"target": [
{
"code": "3_or_more_years",
"equivalence": "equivalent"
}
]
},
{
"code": "3 O MAS ANOS",
"target": [
{
"code": "3_or_more_years",
"equivalence": "equivalent"
}
]
}
]
},
{
"source": "urn:isssteleon:site:erick_site",
"target": "https://isssteleon.org/fhir/CodeSystem/gynecologic-condition",
"element": [
{
"code": "PUERPERIO POSTPARTO O POSTABORTO",
"target": [
{
"code": "postpartum",
"equivalence": "equivalent"
}
]
},
{
"code": "EMBARAZO ACTUAL",
"target": [
{
"code": "pregnant",
"equivalence": "equivalent"
}
]
},
{
"code": "DIU IN SITU",
"target": [
{
"code": "iud",
"equivalence": "equivalent"
}
]
},
{
"code": "TRATAMIENTO HORMONAL",
"target": [
{
"code": "hormonal_treatment",
"equivalence": "equivalent"
}
]
},
{
"code": "OTRO TRATAMIENTO GINECOLÓGICO",
"target": [
{
"code": "other_treatment",
"equivalence": "equivalent"
}
]
},
{
"code": "OTRO TRATAMIENTO GINECOLOGICO",
"target": [
{
"code": "other_treatment",
"equivalence": "equivalent"
}
]
},
{
"code": "POST MENOPAUSIA",
"target": [
{
"code": "postmenopausal",
"equivalence": "equivalent"
}
]
},
{
"code": "HISTERECTOMÍA",
"target": [
{
"code": "hysterectomy",
"equivalence": "equivalent"
}
]
},
{
"code": "HISTERECTOMIA",
"target": [
{
"code": "hysterectomy",
"equivalence": "equivalent"
}
]
},
{
"code": "NO APLICA",
"target": [
{
"code": "not_applicable",
"equivalence": "equivalent"
}
]
}
]
},
{
"source": "urn:isssteleon:site:erick_site",
"target": "https://isssteleon.org/fhir/CodeSystem/presenting-symptom",
"element": [
{
"code": "FLUJO",
"target": [
{
"code": "discharge",
"equivalence": "equivalent"
}
]
},
{
"code": "PRURITO O ARDOR VULVAR",
"target": [
{
"code": "vulvar_itching",
"equivalence": "equivalent"
}
]
},
{
"code": "SANGRADO ANORMAL",
"target": [
{
"code": "abnormal_bleeding",
"equivalence": "equivalent"
}
]
},
{
"code": "NINGUNO",
"target": [
{
"code": "none",
"equivalence": "equivalent"
}
]
}
]
},
{
"source": "urn:isssteleon:site:erick_site",
"target": "https://isssteleon.org/fhir/CodeSystem/cervix-appearance",
"element": [
{
"code": "CUELLO SANO",
"target": [
{
"code": "healthy",
"equivalence": "equivalent"
}
]
},
{
"code": "CUELLO ANORMAL CON LESIÓN",
"target": [
{
"code": "lesion",
"equivalence": "equivalent"
}
]
},
{
"code": "CUELLO ANORMAL CON LESION",
"target": [
{
"code": "lesion",
"equivalence": "equivalent"
}
]
},
{
"code": "NO SE OBSERVA CUELLO",
"target": [
{
"code": "not_seen",
"equivalence": "equivalent"
}
]
}
]
}
]
}
+33 -1
View File
@@ -59,7 +59,39 @@
"sample_date": "fecha de recepci[oó]n:[\\s—–-]*(\\d{2}/\\d{2}/\\d{4})",
"report_date": "interpretaci[oó]n:[\\s\\S]{0,80}?(\\d{2}/\\d{2}/\\d{4})",
"adequacy": "\\b(insatisfactorio|satisfactorio)\\b",
"result": "\\b(negativo|asc-us|asc-h|lesi[oó]n (?:intraepitelial escamosa )?de bajo grado|lesi[oó]n (?:intraepitelial escamosa )?de alto grado|carcinoma in situ)\\b"},
"result": "\\b(negativo|asc-us|asc-h|lesi[oó]n (?:intraepitelial escamosa )?de bajo grado|lesi[oó]n (?:intraepitelial escamosa )?de alto grado|carcinoma in situ)\\b",
"screening_history": "detecci[oó]n de c[aá]ncer de c[eé]rvix[\\s\\S]{0,110}?\\b(primera\\s+vez\\s+en\\s+la\\s+vida|3\\s+o\\s+m[áa]s\\s+a[ñn]os|un\\s+a[ñn]o\\s+o\\s+menos|2\\s+a[ñn]os)\\b",
"gynecologic_condition": "condiciones gineco-?obst[eé]tricas[\\s\\S]{0,110}?\\b(puerperio\\s+postparto\\s+o\\s+postaborto|otro\\s+tratamiento\\s+ginecol[óo]gico|tratamiento\\s+hormonal|embarazo\\s+actual|post\\s+menopausia|histerectom[íi]a|diu\\s+in\\s+situ|no\\s+aplica)\\b",
"presenting_symptom": "actualmente presenta[\\s\\S]{0,110}?\\b(prurito\\s+o\\s+ardor\\s+vulvar|sangrado\\s+anormal|ninguno|flujo)\\b",
"cervix_appearance": "a la exploraci[oó]n se observa[\\s\\S]{0,110}?\\b(cuello\\s+anormal\\s+con\\s+lesi[óo]n|no\\s+se\\s+observa\\s+cuello|cuello\\s+sano)\\b",
"findings": "hallazgos adicionales:\\s*(?!observaciones)([^\\n]+)",
"finding_inflammation": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(inflamaci[óo]n)(?:\\s+(?:leve|moderada|severa))?\\s*[.;]",
"finding_reactive": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+reactivos)\\s*[.;]",
"finding_vaginosis": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambio\\s+en\\s+la\\s+flora\\s+sugestiva\\s+de\\s+vaginosis\\s+bacteriana)\\s*[.;]",
"finding_candida": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(microorganismos\\s+mic[óo]ticos\\s+morfol[óo]gicamente\\s+compatibles\\s+con\\s+candida\\s+sp)\\s*[.;]",
"finding_bacillary_cytolysis": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(aumento\\s+de\\s+la\\s+flora\\s+bacilar\\s+con\\s+cit[óo]lisis\\s+de\\s+las\\s+c[ée]lulas\\s+intermedias)\\s*[.;]",
"finding_cytolysis": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cit[óo]lisis\\s+de\\s+las\\s+c[ée]lulas\\s+intermedias)\\s*[.;]",
"finding_trichomonas": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(trichomonas\\s+vaginalis)\\s*[.;]",
"finding_leptothrix": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(microorganismos\\s+bacterianos\\s+morfol[óo]gicamente\\s+compatibles\\s+con\\s+leptothrix)\\s*[.;]",
"finding_actinomyces": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(microorganismos\\s+morfol[óo]gicamente\\s+compatibles\\s+con\\s+actinomyces\\s+sp)\\s*[.;]",
"finding_actinomyces_changes": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+celulares\\s+compatibles\\s+con\\s+actinomyces\\s+sp)\\s*[.;]",
"finding_herpes_changes": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+celulares\\s+compatibles\\s+con\\s+virus\\s+herpes\\s+simple)\\s*[.;]",
"finding_tubular_metaplasia": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(metaplasia\\s+escamosa\\s+tubular)\\s*[.;]",
"finding_keratotic": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+querat[óo]sicos)\\s*[.;]",
"finding_pregnancy": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+asociados\\s+al\\s+embarazo)\\s*[.;]",
"finding_atrophy": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(atrofia)\\s*[.;]",
"finding_hypoestrogenism": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(hipoestrogenismo)\\s*[.;]",
"finding_radiotherapy": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(efecto\\s+de\\s+radioterapia)\\s*[.;]",
"finding_iud_changes": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(cambios\\s+compatibles\\s+con\\s+presencia\\s+de\\s+dispositivo\\s+intrauterino)\\s*[.;]",
"finding_glandular_cells": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(c[ée]lulas\\s+glandulares\\s+post\\-histerectom[íi]a)\\s*[.;]",
"finding_bacteria": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(bacterias)\\s*[.;]",
"finding_herpes_image": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(imagen\\s+del\\s+virus\\s+del\\s+herpes)\\s*[.;]",
"finding_fungi": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(hongos)\\s*[.;]",
"finding_radiation": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(radiaci[óo]n)\\s*[.;]",
"finding_repair": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(reparaci[óo]n)\\s*[.;]",
"finding_iud_effect": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(efecto\\s+del\\s+diu)\\s*[.;]",
"finding_endometrial_cells": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(presencia\\s+de\\s+c[ée]lulas\\s+endometriales\\s+en\\s+pacientes\\s+de\\s+40\\s+a[ñn]os\\s+o\\s+m[áa]s)\\s*[.;]",
"finding_none": "hallazgos adicionales:(?:[^:]*?[.;])?\\s*(ninguno)\\s*[.;]"},
"concept_map": "erick_site",
"formats": {"sample_date": "%d/%m/%Y", "report_date": "%d/%m/%Y"}},
{"id": "hpv", "kind": "extract", "label": "VPH", "inputs": ["hpv_orders"],
+124
View File
@@ -0,0 +1,124 @@
"""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, "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", screening_history="never"),
procedure("b", "2026-02-01", "normal", "2026-02-10", screening_history="2_years"),
procedure(
"c",
"2026-02-01",
"normal",
"2026-02-10",
screening_history="never",
first_colposcopy="2025-06-01",
), # 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