Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e670a48f52 | |||
| 16edc9f034 | |||
| 34d3f4cb72 | |||
| a9529153a0 | |||
| 5fe1f5e975 | |||
| 0138de8ab6 | |||
| 39b923db09 | |||
| 047446a1aa | |||
| 42aa6df6dd | |||
| 2883757071 | |||
| 0697e84559 | |||
| f98dac86e3 | |||
| 3ebf34fdff | |||
| ebb3fea787 | |||
| 9666596ab0 | |||
| 0d7b85f1f7 | |||
| ba8816fcfa | |||
| af8fe28850 | |||
| d1e74792a4 | |||
| 257e12b63c | |||
| 230e73f314 | |||
| 6b6f1c757d | |||
| 2304cae6b7 | |||
| 83b393a1f0 | |||
| 08c430af35 | |||
| d533d358c4 | |||
| ba81ab811f | |||
| dd54f9a5ab | |||
| ed3c09222a | |||
| 18845f4719 | |||
| d68952bc6e | |||
| 4f308b4125 | |||
| 43651cf43d | |||
| e6ff145a60 | |||
| 033c38649a | |||
| 5ffa927f41 | |||
| 50eb097134 | |||
| 5a11bb1555 | |||
| e9ccad7f69 | |||
| 027ba274a7 | |||
| eb92e77be7 | |||
| 1eea97254a | |||
| c224163a3d | |||
| 98467c5bc7 | |||
| b77c22168c | |||
| d3a02178d1 | |||
| 72cd19219a | |||
| de58f0db59 |
+3
-3
@@ -1,12 +1,12 @@
|
||||
[submodule "WebApi"]
|
||||
path = WebApi
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApi.git
|
||||
url = ../WebApi.git
|
||||
branch = rebuild
|
||||
[submodule "WebApp"]
|
||||
path = WebApp
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/WebApp.git
|
||||
url = ../WebApp.git
|
||||
branch = rebuild
|
||||
[submodule "models"]
|
||||
path = models
|
||||
url = ssh://git@10.0.10.41:2222/ISSSTELEON/models.git
|
||||
url = ../models.git
|
||||
branch = rebuild
|
||||
|
||||
@@ -33,6 +33,12 @@ INDEX_SAMPLE_DAYS = 30 # results this many days after the index sample still de
|
||||
PREVALENT_WINDOW_DAYS = 6 * 365.25 / 12 # an outcome this soon was there at the index
|
||||
DAYS_PER_YEAR = 365.25
|
||||
|
||||
HPV_GENOTYPE_FIELDS = ("hpv_16", "hpv_18")
|
||||
SECOND_VISIT_FIELDS = (
|
||||
"bethesda", "glandular", "hpv", *HPV_GENOTYPE_FIELDS,
|
||||
"gynecologic_condition", "presenting_symptom", "cervix_appearance",
|
||||
) # fmt: skip
|
||||
|
||||
# Recruitment windows (start inclusive, end exclusive).
|
||||
RECRUITMENT = ("2018-01-01", "2027-01-01")
|
||||
POST_TREATMENT_RECRUITMENT = ("2024-01-01", "2027-01-01")
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Which of a patient's model risks still apply at a cut-off day (pure). A risk estimated
|
||||
before something that has since happened is not shown; the models still learn from it."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from datetime import date
|
||||
|
||||
from core import cacu
|
||||
from core.cacu.measures import as_day
|
||||
|
||||
SURVIVAL = "cacu.survival" # the only model that applies once she has cancer
|
||||
POST_TREATMENT = "cacu.cin2_pim_post_treatment"
|
||||
|
||||
|
||||
def withheld(history: Iterable[dict], cutoff: date) -> tuple[date, date | None, str | None]:
|
||||
"""From her biopsies and treatments (`date`, `type`, `value_code`) up to the cut-off:
|
||||
the day from which a post-treatment estimate applies (`date.max`: none does), her last
|
||||
treatment, and why other estimates are withheld (None: nothing is withheld)."""
|
||||
found = [(as_day(h["date"]), h["type"], h.get("value_code")) for h in history]
|
||||
found = [f for f in found if f[0] <= cutoff]
|
||||
cancer = [day for day, kind, value in found if kind == "biopsy" and value in cacu.CASE]
|
||||
if cancer:
|
||||
return date.max, None, f"Diagnóstico de cáncer el {min(cancer)}."
|
||||
lesion = max(((day, value) for day, kind, value in found
|
||||
if kind == "biopsy" and value in cacu.CIN2_PLUS), default=None) # fmt: skip
|
||||
treated = max((day for day, kind, _ in found if kind == "treatment"), default=None)
|
||||
if lesion and (treated is None or treated < lesion[0]):
|
||||
return date.max, None, f"Diagnóstico {lesion[1]} el {lesion[0]}, sin tratamiento posterior."
|
||||
if treated:
|
||||
return treated, treated, f"Tratamiento el {treated}: solo aplica el riesgo postratamiento."
|
||||
return date.min, None, None
|
||||
|
||||
|
||||
def current(risks: Iterable[dict], history: Iterable[dict], cutoff: date) -> list[dict]:
|
||||
"""The rows of `gold.cacu_risk` that still apply to one patient at the cut-off."""
|
||||
since, treated, reason = withheld(history, cutoff)
|
||||
if reason is None:
|
||||
return list(risks)
|
||||
return [r for r in risks if r["model"] == SURVIVAL
|
||||
or (treated is not None and r["model"] == POST_TREATMENT
|
||||
and as_day(r["index_date"]) >= since)] # fmt: skip
|
||||
+26
-14
@@ -162,9 +162,12 @@ MEASURES = {m.id: m for m in [
|
||||
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"))),
|
||||
r[c] is not None for c in ("hpv", "hpv_16", "hpv_18")),
|
||||
strata=(AGE, STATUS, ("round", round_of))),
|
||||
facts={"report_known_at": ("hpv", "hpv_16", "hpv_18", "report_date")},
|
||||
description="Reportes de VPH, por fecha de toma."),
|
||||
description="Reportes de VPH, por fecha de toma. Cuenta reportes, no pacientes; la edad y "
|
||||
"el estatus son los de la paciente al inicio del periodo y la ronda es la de "
|
||||
"la muestra del reporte."),
|
||||
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",
|
||||
@@ -178,11 +181,13 @@ MEASURES = {m.id: m for m in [
|
||||
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",
|
||||
ppv("CACU_VPP_COLPOSCOPIA", "Tasa de confirmación histopatológica de referencia a colposcopía",
|
||||
"colposcopy",
|
||||
lambda r: True),
|
||||
ppv("CACU_VPP_BIOPSIA", "Valor predictivo positivo de la biopsia", "biopsy",
|
||||
ppv("CACU_VPP_BIOPSIA", "Tasa de confirmación histopatológica de referencia a 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",
|
||||
Measure("CACU_TIEMPO_DIAGNOSTICO_CIE10", "Días de tamizaje a primer diagnóstico por CIE-10",
|
||||
"samples",
|
||||
Duration("days_sample_diagnosis", "diagnosis_date", "sample_date",
|
||||
cacu.SAMPLE_TO_DIAGNOSIS_DAYS, units=NO_HISTORY,
|
||||
@@ -192,37 +197,44 @@ MEASURES = {m.id: m for m in [
|
||||
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",
|
||||
Measure("CACU_EU_TIEMPO_REPORTE",
|
||||
"Días de toma de citología a resultado", "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",
|
||||
Measure("CACU_DIAS_TOMA_DIAGNOSTICO", "Días de tamizaje a primer 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",
|
||||
Measure("CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA",
|
||||
"Días de tamizaje a diagnóstico tras biopsia", "samples",
|
||||
Duration("days_sample_biopsy_diagnosis", "biopsy_diagnosis_date", "sample_date",
|
||||
H["sample_to_biopsy"] + H["biopsy_to_diagnosis"],
|
||||
units=lambda r: r["history"] == 0 and r.get("biopsy_date") is not None),
|
||||
"decrease"),
|
||||
Measure("CACU_DIAS_TOMA_TRATAMIENTO", "Días 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",
|
||||
Measure("CACU_DIAS_DIAGNOSTICO_TRATAMIENTO", "Días 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",
|
||||
Measure("CACU_DIAS_TOMA_COLPOSCOPIA", "Días 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",
|
||||
Measure("CACU_DIAS_TOMA_BIOPSIA", "Días 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",
|
||||
Measure("CACU_DIAS_RESULTADO_COLPOSCOPIA", "Días 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",
|
||||
Measure("CACU_DIAS_COLPOSCOPIA_BIOPSIA", "Días 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",
|
||||
Measure("CACU_DIAS_BIOPSIA_DIAGNOSTICO", "Días 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),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,327 @@
|
||||
"""The NCI/ASCCP CIN3+ reference risks of a cytology, looked up exactly and traced (experimental).
|
||||
|
||||
`resolve` finds the scenario one cytology belongs to by the information the platform holds by a
|
||||
cut-off, then the one row of the reference tables (`nci_risk_tables.json`) that names it. It
|
||||
never approximates: a result with no row, an unverified equivalence, a history the platform cannot
|
||||
demonstrate or a scenario not implemented ends in a state that says why, and a value the tables
|
||||
leave blank is "not published", not zero. `compare` sets an institutional model beside a reference
|
||||
risk only when the two measure the same thing.
|
||||
|
||||
This is research, not a recommendation: the tables' management column is not read, the workbook's
|
||||
provenance is not verified and nothing here is validated clinically."""
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
from core import cacu
|
||||
|
||||
RESOURCE = Path(__file__).with_name("nci_risk_tables.json")
|
||||
|
||||
# Every state a resolution ends in, and what it means.
|
||||
STATES = {
|
||||
"resolved": "one published row names the scenario",
|
||||
"not_published": "the row exists and the tables leave its risk blank",
|
||||
"missing_data": "a datum the scenario needs is not in the platform by the cut-off",
|
||||
"history_not_demonstrable": "the tables need a past history the platform cannot demonstrate",
|
||||
"not_applicable": "the patient is outside the tables' applicability",
|
||||
"contradictory": "the results contradict each other",
|
||||
"ambiguous": "more than one record or row could be the one",
|
||||
"scenario_not_implemented": "the scenario belongs to a table this version does not resolve",
|
||||
"unverifiable_correspondence": "the platform's record and the table's category are not "
|
||||
"verifiably the same thing",
|
||||
"no_published_row": "the tables publish no row for this combination",
|
||||
}
|
||||
|
||||
AGE_RANGE = (25, 65)
|
||||
HISTORY_DAYS = 5 * 366 # "approximately 5 years": the interval within which a negative test counts
|
||||
|
||||
# The platform's cytology as the tables' vocabulary. AGC is not in the platform's catalog.
|
||||
CYTOLOGY = {"NILM": "NILM", "ASC-US": "ASC-US", "LSIL": "LSIL", "ASC-H": "ASC-H",
|
||||
"HSIL": "HSIL+", "CIS": "HSIL+"} # fmt: skip
|
||||
# A table category made of several results, by the tables' own definition (the high-grade results
|
||||
# are ASC-H, AGC and HSIL+; ASC-US/LSIL is the pair). Never a fallback for another category.
|
||||
GROUPS = {"High Grade": {"ASC-H", "AGC", "HSIL+"}, "ASC-US/LSIL": {"ASC-US", "LSIL"}}
|
||||
# A biopsy's histology as the colposcopy table names it.
|
||||
BIOPSY = {"normal": "<CIN1", "LSIL": "CIN1", "carcinoma": "Cancer"}
|
||||
# Correspondences the platform cannot confirm, with why; an analyst who verifies one turns it off.
|
||||
UNVERIFIED = {
|
||||
"hpv_positive_row": "the screening table lists HPV-positive beside HPV16+ and HPV16-, HPV18+; "
|
||||
"whether its HPV-positive row is all positives or the other types is not "
|
||||
"stated in the sources read",
|
||||
"hsil_cin2_cin3": "the platform's HSIL biopsy does not separate CIN2 from CIN3",
|
||||
"cis_ais": "the platform's carcinoma in situ is not told from adenocarcinoma in situ",
|
||||
}
|
||||
|
||||
|
||||
@cache
|
||||
def tables() -> dict:
|
||||
return json.loads(RESOURCE.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _day(value) -> date | None:
|
||||
return None if value is None else date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def _age(birth, on: date) -> int | None:
|
||||
born = _day(birth)
|
||||
return None if born is None else on.year - born.year - ((on.month, on.day) < (born.month, born.day))
|
||||
|
||||
|
||||
def hpv_category(cytology: dict) -> tuple[str | None, str | None]:
|
||||
"""(the tables' current-HPV category, a reason it cannot be one). Genotypes follow the tables'
|
||||
hierarchy: type 16, else type 18."""
|
||||
hpv, h16, h18 = cytology.get("hpv"), cytology.get("hpv_16"), cytology.get("hpv_18")
|
||||
if hpv is None:
|
||||
return None, "missing_hpv"
|
||||
if not hpv:
|
||||
return ("HPV-negative", None) if not (h16 or h18) else (None, "contradictory_hpv")
|
||||
if h16:
|
||||
return "HPV16+", None
|
||||
if h18 and h16 is not None:
|
||||
return "HPV16-, HPV18+", None
|
||||
return None, "hpv_positive_row"
|
||||
|
||||
|
||||
def _rows(table: str, **key) -> list[dict]:
|
||||
return [r for r in tables()["rows"] if r["table"] == table
|
||||
and all(r["key"].get(k) == v for k, v in key.items())] # fmt: skip
|
||||
|
||||
|
||||
def _row(table: str, cytology_label: str, **key) -> tuple[list[dict], str | None]:
|
||||
"""The row of `table` for a cytology category: the category itself, else the table's own group
|
||||
that holds it. Returns the rows found and how (`exact` or `table_group`)."""
|
||||
exact = _rows(table, cytology=cytology_label, **key)
|
||||
if exact:
|
||||
return exact, "exact"
|
||||
held = [r for r in _rows(table, **key) if cytology_label in GROUPS.get(r["key"]["cytology"], ())]
|
||||
return held, "table_group" if held else None
|
||||
|
||||
|
||||
def _outcome(status: str, reasons: list[str], **more) -> dict:
|
||||
return {"status": status, "reasons": reasons, "scenario": None, "row": None, "horizons": [],
|
||||
"used": [], "assumptions": [], **more} # fmt: skip
|
||||
|
||||
|
||||
def _horizons(row: dict) -> list[dict]:
|
||||
return [{"years": int(years), "risk": risk, "published": risk is not None,
|
||||
"percent": row["risks_percent"][years]} for years, risk in row["risks"].items()] # fmt: skip
|
||||
|
||||
|
||||
def _valid(cytology: dict) -> bool:
|
||||
return cytology.get("result") is not None and cytology.get("adequacy") != "unsatisfactory"
|
||||
|
||||
|
||||
def resolve(facts: dict, cutoff: date, sample: date | None = None) -> dict:
|
||||
"""The reference risk of her cytology of `sample` (else her latest) by `cutoff`, using only what
|
||||
was reported by then. `facts`: birth_date; cytologies (sample_date, report_date, result,
|
||||
adequacy, hpv, hpv_16, hpv_18, gynecologic_condition); biopsies (request_date, report_date,
|
||||
histology, cytology_sample_date, the sample its own record names); events (type, date) of the
|
||||
platform's timeline."""
|
||||
known = [c for c in facts.get("cytologies", [])
|
||||
if _day(c["sample_date"]) <= cutoff and (_day(c.get("report_date")) or date.max) <= cutoff
|
||||
and _valid(c)] # fmt: skip
|
||||
known.sort(key=lambda c: _day(c["sample_date"]))
|
||||
if sample is not None:
|
||||
found = [c for c in known if _day(c["sample_date"]) == sample]
|
||||
if not found:
|
||||
return _outcome("missing_data", ["sample_not_reported_by_cutoff"], cutoff=cutoff)
|
||||
index = found[-1]
|
||||
elif known:
|
||||
index = known[-1]
|
||||
else:
|
||||
return _outcome("missing_data", ["no_cytology_reported_by_cutoff"], cutoff=cutoff)
|
||||
when = _day(index["sample_date"])
|
||||
base = {"cutoff": cutoff, "index": {"sample_date": when, "report_date": _day(index.get("report_date")),
|
||||
"result": index["result"]}} # fmt: skip
|
||||
|
||||
def out(status, reasons, **more):
|
||||
return _outcome(status, reasons, **base, **more)
|
||||
|
||||
age = _age(facts.get("birth_date"), when)
|
||||
base["age"] = age
|
||||
if age is None:
|
||||
return out("missing_data", ["no_birth_date"])
|
||||
if not AGE_RANGE[0] <= age <= AGE_RANGE[1]:
|
||||
return out("not_applicable", ["age_outside_25_65"])
|
||||
category = CYTOLOGY.get(index["result"])
|
||||
if category is None:
|
||||
return out("no_published_row", ["cytology_not_in_tables"])
|
||||
|
||||
biopsies = [b for b in facts.get("biopsies", []) if (_day(b.get("report_date")) or date.max) <= cutoff]
|
||||
named = [b for b in biopsies if _day(b.get("cytology_sample_date")) == when]
|
||||
after = [e for e in facts.get("events", []) if when < _day(e["date"]) <= cutoff
|
||||
and e["type"] in ("colposcopy", "treatment")] # fmt: skip
|
||||
if named:
|
||||
return _colposcopy_results(facts, index, category, named, out, cutoff)
|
||||
if after or any(when < _day(b["request_date"]) <= cutoff for b in facts.get("biopsies", [])):
|
||||
return out("unverifiable_correspondence", ["procedure_after_without_named_referral"])
|
||||
return _screening(facts, index, category, when, out)
|
||||
|
||||
|
||||
def _screening(facts: dict, index: dict, category: str, when: date, out) -> dict:
|
||||
"""The screening table: a cotest-negative past history, the current HPV and cytology."""
|
||||
before = [e for e in facts.get("events", []) if _day(e["date"]) <= when
|
||||
and e["type"] in ("colposcopy", "treatment")] # fmt: skip
|
||||
if before or any(_day(b["request_date"]) <= when for b in facts.get("biopsies", [])):
|
||||
return out("scenario_not_implemented", ["colposcopy_or_treatment_before"])
|
||||
if any((b.get("histology") in cacu.CIN2_PLUS) and (_day(b.get("report_date")) or date.max) <= when
|
||||
for b in facts.get("biopsies", [])):
|
||||
return out("not_applicable", ["registered_cin2_plus_before"])
|
||||
if any(c.get("gynecologic_condition") == "hysterectomy" and _day(c["sample_date"]) <= when
|
||||
for c in facts.get("cytologies", [])):
|
||||
return out("not_applicable", ["hysterectomy_declared"])
|
||||
hpv, why = hpv_category(index)
|
||||
if why in ("missing_hpv", "contradictory_hpv"):
|
||||
return out("missing_data" if why == "missing_hpv" else "contradictory", [why])
|
||||
if why == "hpv_positive_row":
|
||||
return out("unverifiable_correspondence", [why], assumptions=[UNVERIFIED[why]])
|
||||
earlier = sorted((c for c in facts.get("cytologies", [])
|
||||
if _day(c["sample_date"]) < when and (_day(c.get("report_date")) or date.max) <= when
|
||||
and _valid(c)), key=lambda c: _day(c["sample_date"])) # fmt: skip
|
||||
# a registered history is a past test with its HPV; its absence is not "no history"
|
||||
withhpv = [c for c in earlier if c.get("hpv") is not None]
|
||||
if not withhpv:
|
||||
return out("history_not_demonstrable", ["no_earlier_test_registered"])
|
||||
last = withhpv[-1]
|
||||
if (when - _day(last["sample_date"])).days > HISTORY_DAYS:
|
||||
return out("history_not_demonstrable", ["earlier_test_older_than_5_years"])
|
||||
if last["hpv"] or last["result"] != "NILM":
|
||||
return out("scenario_not_implemented", ["history_is_a_surveillance_scenario"])
|
||||
if len(withhpv) > 1 and (withhpv[-2]["hpv"] or withhpv[-2]["result"] != "NILM") \
|
||||
and (_day(last["sample_date"]) - _day(withhpv[-2]["sample_date"])).days <= HISTORY_DAYS: # fmt: skip
|
||||
return out("scenario_not_implemented", ["history_is_a_surveillance_scenario"])
|
||||
rows, via = _row("screening", category, history="Cotest-negative", hpv=hpv)
|
||||
scenario = {"table": "screening", "label": "Tamizaje", "key": {"history": "Cotest-negative", "hpv": hpv,
|
||||
"cytology": category}} # fmt: skip
|
||||
return _found(rows, via, scenario, out, used=[
|
||||
_used("earlier cotest", last), _used("current cotest", index)])
|
||||
|
||||
|
||||
def _flag(value) -> bool | None:
|
||||
"""A result stored as 0 or 1 as the boolean it is; unknown stays unknown."""
|
||||
return None if value is None else bool(value)
|
||||
|
||||
|
||||
def _used(label: str, c: dict) -> dict:
|
||||
return {"label": label, "sample_date": _day(c["sample_date"]), "report_date": _day(c.get("report_date")),
|
||||
"result": c.get("result"), "hpv": _flag(c.get("hpv")), "hpv_16": _flag(c.get("hpv_16")),
|
||||
"hpv_18": _flag(c.get("hpv_18"))} # fmt: skip
|
||||
|
||||
|
||||
def _found(rows: list[dict], via: str | None, scenario: dict, out, used: list[dict]) -> dict:
|
||||
if not rows:
|
||||
return out("no_published_row", ["no_row_for_the_combination"], scenario=scenario, used=used)
|
||||
if len(rows) > 1:
|
||||
return out("ambiguous", ["several_rows"], scenario=scenario, used=used)
|
||||
row = rows[0]
|
||||
reference = {"sheet": row["sheet"], "row": row["row"], "official_check": row.get("official_check")}
|
||||
horizons = _horizons(row)
|
||||
status = "resolved" if row["published"] else "not_published"
|
||||
return out(status, [] if row["published"] else ["risk_blank_in_the_tables"], scenario=scenario,
|
||||
row=reference, horizons=horizons, matched_via=via, used=used)
|
||||
|
||||
|
||||
def _colposcopy_results(facts: dict, index: dict, category: str, named: list[dict], out, cutoff) -> dict:
|
||||
"""After colposcopy: the referral screening result and the biopsy that names it. Its horizons are
|
||||
one and five years, not immediate."""
|
||||
if len(named) > 1:
|
||||
return out("ambiguous", ["several_biopsies_name_the_cytology"])
|
||||
biopsy = named[0]
|
||||
when = _day(index["sample_date"])
|
||||
if index.get("hpv") is None and category in ("ASC-US", "LSIL", "NILM"):
|
||||
return out("missing_data", ["missing_hpv"])
|
||||
referral = None
|
||||
if category in ("ASC-H", "HSIL+"):
|
||||
referral = category
|
||||
elif index.get("hpv") and category in ("ASC-US", "LSIL"):
|
||||
referral = f"HPV-positive {category}"
|
||||
elif index.get("hpv") and category == "NILM":
|
||||
earlier = [c for c in facts.get("cytologies", []) if _day(c["sample_date"]) < when and _valid(c)
|
||||
and (_day(c.get("report_date")) or date.max) <= when] # fmt: skip
|
||||
earlier.sort(key=lambda c: _day(c["sample_date"]))
|
||||
if earlier and earlier[-1].get("hpv") and earlier[-1]["result"] == "NILM":
|
||||
referral = "HPV-positive NILM x2"
|
||||
histology = biopsy.get("histology")
|
||||
if referral is None and histology != "carcinoma":
|
||||
return out("no_published_row", ["not_a_referral_result_in_the_tables"])
|
||||
if histology in ("HSIL", "CIS"):
|
||||
reason = "hsil_cin2_cin3" if histology == "HSIL" else "cis_ais"
|
||||
return out("unverifiable_correspondence", [reason], assumptions=[UNVERIFIED[reason]])
|
||||
label = BIOPSY.get(histology)
|
||||
if label is None:
|
||||
return out("missing_data", ["biopsy_without_histology"])
|
||||
# the tables give the histologies they cannot price (cancer here) one row for any referral
|
||||
referral = None if label == "Cancer" else referral
|
||||
scenario = {"table": "colposcopy_results", "label": "Resultado de colposcopía",
|
||||
"key": {"referral": referral, "biopsy": label}}
|
||||
rows = _rows("colposcopy_results", referral=referral, biopsy=label)
|
||||
result = _found(rows, "exact", scenario, out, used=[
|
||||
_used("referral cotest", index),
|
||||
{"label": "biopsy", "request_date": _day(biopsy["request_date"]),
|
||||
"report_date": _day(biopsy.get("report_date")), "histology": histology}]) # fmt: skip
|
||||
result["evaluation_date"] = _day(biopsy.get("report_date"))
|
||||
return result
|
||||
|
||||
|
||||
# -- comparison with the institutional models --------------------------------------------------
|
||||
|
||||
# What each institutional CaCu model estimates, as its code and spec say (models/cacu/specs.py).
|
||||
# `population_verified` stays false: no model has been shown to share the tables' population.
|
||||
MODELS = {
|
||||
"cacu.cin2_pim": {"outcome": "CIN2+", "index": "last screening cytology"},
|
||||
"cacu.cancer_pim": {"outcome": "cancer", "index": "last screening cytology"},
|
||||
"cacu.cin2_logistic": {"outcome": "CIN2+ within one year", "index": "index sample"},
|
||||
"cacu.cin2_pim_post_colposcopy": {"outcome": "CIN2+", "index": "first colposcopy"},
|
||||
"cacu.cin2_pim_post_treatment": {"outcome": "CIN2+", "index": "treatment"},
|
||||
"cacu.survival": {"outcome": "not stated as a histology outcome", "index": "first biopsy carcinoma"},
|
||||
}
|
||||
REASONS = {
|
||||
"no_institutional_model": "no institutional model has scored her",
|
||||
"outcome_differs": "the model's outcome is not the table's (CIN3+)",
|
||||
"unknown_model": "the model's outcome is not registered for comparison",
|
||||
"horizon_not_published_by_model": "the model publishes no prediction at this horizon",
|
||||
"index_date_differs": "the model's index date is not the evaluated cytology's",
|
||||
"population_not_verified": "the model's population and scenario are not verified to match the table's",
|
||||
"no_reference": "the tables give no risk at this horizon",
|
||||
}
|
||||
|
||||
|
||||
def compare(resolution: dict, assessments: list[dict], registry: dict | None = None) -> list[dict]:
|
||||
"""Per reference horizon and institutional model, the difference in percentage points
|
||||
(institutional minus reference) when the two are the same estimate, else why not.
|
||||
`assessments`: model (code), title, index_date, predictions (years, p, low, high)."""
|
||||
registry = MODELS if registry is None else registry
|
||||
found = []
|
||||
for h in resolution["horizons"]:
|
||||
base = {"years": h["years"], "reference": h["risk"]}
|
||||
if not assessments:
|
||||
found.append({**base, "model": None, "institutional": None, "status": "not_comparable",
|
||||
"difference_pp": None, "reasons": ["no_institutional_model"]})
|
||||
for a in assessments:
|
||||
kind = registry.get(a["model"])
|
||||
asked = next((p for p in a["predictions"] if p["years"] == h["years"]), None)
|
||||
why = []
|
||||
if h["risk"] is None:
|
||||
why.append("no_reference")
|
||||
if kind is None:
|
||||
why.append("unknown_model")
|
||||
elif kind["outcome"] != tables()["outcome"]["code"]:
|
||||
why.append("outcome_differs")
|
||||
if asked is None:
|
||||
why.append("horizon_not_published_by_model")
|
||||
if _day(a.get("index_date")) != resolution.get("evaluation_date", resolution["index"]["sample_date"]):
|
||||
why.append("index_date_differs")
|
||||
if not (kind or {}).get("population_verified"):
|
||||
why.append("population_not_verified")
|
||||
row = {**base, "model": a["model"], "title": a.get("title"),
|
||||
"institutional": None if asked is None else asked["p"],
|
||||
"interval": None if asked is None or asked.get("low") is None
|
||||
else [asked["low"], asked["high"]], "outcome": (kind or {}).get("outcome")} # fmt: skip
|
||||
if why:
|
||||
found.append({**row, "status": "not_comparable", "difference_pp": None, "reasons": why})
|
||||
else:
|
||||
diff = round((asked["p"] - h["risk"]) * 100, 2)
|
||||
found.append({**row, "status": "comparable", "difference_pp": diff, "reasons": []})
|
||||
return found
|
||||
@@ -0,0 +1,322 @@
|
||||
"""The risk series a patient's record can choose to draw, each with its source, version,
|
||||
outcome, variables and published intervals (experimental; pure but for reading the books).
|
||||
|
||||
Series are shown side by side and never subtracted here. A source that cannot be matched to her
|
||||
by what the platform holds gives a series with its reasons and no number."""
|
||||
|
||||
import hashlib
|
||||
from collections.abc import Iterable
|
||||
from datetime import date
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
|
||||
from core.cacu import reference_risk as reference
|
||||
from core.risk_workbooks import read_workbook
|
||||
|
||||
ENROLLMENT = Path(__file__).with_name("nci_source_workbooks") / "1_Enrollment Table.xlsx"
|
||||
OUTCOMES = ("CIN2+", "CIN3+", "cancer")
|
||||
NO_HISTORY = ("Sin prueba previa registrada en la plataforma: no demuestra que no exista. "
|
||||
"Se usa la tabla de ingreso del NCI.") # fmt: skip
|
||||
|
||||
|
||||
@cache
|
||||
def enrollment() -> tuple[list[dict], str]:
|
||||
"""The enrollment book's rows and the SHA-256 of the file they were read from."""
|
||||
return read_workbook(ENROLLMENT), hashlib.sha256(ENROLLMENT.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def _series(identifier: str, source: str, outcome: str, label: str, points=(), **more) -> dict:
|
||||
return {"id": identifier, "source": source, "outcome": outcome, "label": label,
|
||||
"points": list(points), "status": "resolved" if points else "unresolved",
|
||||
"reasons": [], "assumptions": [], "version": None, "method": None, **more} # fmt: skip
|
||||
|
||||
|
||||
def _enrollment_match(facts: dict, resolution: dict) -> tuple[dict | None, list[str]]:
|
||||
"""Her HPV and cytology as the enrollment book names them, or why they cannot be."""
|
||||
reasons = resolution["reasons"]
|
||||
if reasons not in (["no_earlier_test_registered"], ["hpv_positive_row"]):
|
||||
return None, reasons or ["history_is_registered"]
|
||||
index = resolution["index"]
|
||||
day = index["sample_date"]
|
||||
tests = [c for c in facts["cytologies"] if c.get("hpv") is not None]
|
||||
if any(str(c["sample_date"])[:10] < str(day) for c in tests):
|
||||
return None, ["history_is_registered"]
|
||||
now = next((c for c in tests if str(c["sample_date"])[:10] == str(day)), None)
|
||||
if now is None:
|
||||
return None, ["missing_hpv"]
|
||||
return {"hpv": "HPV-positive" if now["hpv"] else "HPV-negative",
|
||||
"pap": reference.CYTOLOGY[index["result"]]}, [] # fmt: skip
|
||||
|
||||
|
||||
def nci_enrollment(facts: dict, resolution: dict) -> list[dict]:
|
||||
rows, version = enrollment()
|
||||
variables, reasons = _enrollment_match(facts, resolution)
|
||||
found = []
|
||||
for outcome in OUTCOMES:
|
||||
points, label = [], "Tabla de ingreso"
|
||||
if variables:
|
||||
label = f"VPH: {variables['hpv']} · Citología: {variables['pap']}"
|
||||
for row in rows:
|
||||
if row["variables"] == variables and row["estimates"][0]["outcome"] == outcome:
|
||||
points = [_point(e["horizon_years"], e["value"], e["confidence_interval"])
|
||||
for e in row["estimates"] if e["value"] is not None] # fmt: skip
|
||||
found.append(_series(
|
||||
f"nci-enrollment-{outcome}", "NCI (tabla de ingreso)", outcome, label, points,
|
||||
reasons=reasons if variables is None else [] if points else ["no_published_row"],
|
||||
assumptions=[NO_HISTORY] if points else [], version=f"sha256:{version}",
|
||||
)) # fmt: skip
|
||||
return found
|
||||
|
||||
|
||||
def _point(years, probability, interval: dict | None = None) -> dict:
|
||||
interval = interval or {}
|
||||
return {"years": years, "probability": probability, "low": interval.get("lower"),
|
||||
"high": interval.get("upper"), "level": interval.get("level")} # fmt: skip
|
||||
|
||||
|
||||
def nci_master(resolution: dict) -> list[dict]:
|
||||
"""The CIN3+ reference the record already resolves (no intervals are published in it)."""
|
||||
table = reference.tables()
|
||||
scenario = resolution.get("scenario") or {}
|
||||
label = " · ".join(str(v) for v in scenario.get("key", {}).values() if v is not None)
|
||||
points = [_point(h["years"], h["risk"]) for h in resolution["horizons"] if h["published"]]
|
||||
return [_series("nci-master-CIN3+", "NCI (tabla maestra)", "CIN3+",
|
||||
label or "Tabla maestra", points, reasons=resolution["reasons"],
|
||||
version=f"sha256:{table['source']['sha256']}")] # fmt: skip
|
||||
|
||||
|
||||
BOOKS = Path(__file__).with_name("nci_source_workbooks")
|
||||
POST_COLPO = "17_Post_Colpo.xlsx"
|
||||
POST_TREATMENT = (
|
||||
"23_Post_Treatment General.xlsx", "24_Post_Treatment_1visit_nostratifiedPre.xlsx",
|
||||
"25_Post_Treatment_1visit_stratifiedPre.xlsx", "26_Post_Treatment_2-3visit.xlsx",
|
||||
)
|
||||
|
||||
|
||||
@cache
|
||||
def workbook(name: str) -> tuple[list[dict], str]:
|
||||
path = BOOKS / name
|
||||
return read_workbook(path), hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def _post_sample(facts: dict, resolution: dict, cutoff: date):
|
||||
"""One reported index sample, only within the established NCI age range."""
|
||||
if resolution.get("age") is None:
|
||||
return None, "missing_or_ineligible_age"
|
||||
if not reference.AGE_RANGE[0] <= resolution["age"] <= reference.AGE_RANGE[1]:
|
||||
return None, "age_outside_25_65"
|
||||
index = resolution.get("index") or {}
|
||||
day = reference._day(index.get("sample_date"))
|
||||
if day is None:
|
||||
return None, "missing_index_sample"
|
||||
found = [c for c in facts.get("cytologies", [])
|
||||
if reference._day(c.get("sample_date")) == day
|
||||
and reference._day(c.get("report_date")) is not None
|
||||
and reference._day(c["report_date"]) <= cutoff and reference._valid(c)]
|
||||
if len(found) != 1:
|
||||
return None, "missing_or_ambiguous_index_sample"
|
||||
sample = found[0]
|
||||
if any(c.get("gynecologic_condition") == "hysterectomy"
|
||||
and (reference._day(c.get("sample_date")) or date.max) <= day
|
||||
for c in facts.get("cytologies", [])):
|
||||
return None, "hysterectomy_declared"
|
||||
if sample.get("hpv") is None:
|
||||
return None, "missing_hpv"
|
||||
if not sample["hpv"] and (sample.get("hpv_16") or sample.get("hpv_18")):
|
||||
return None, "contradictory_hpv"
|
||||
return sample, None
|
||||
|
||||
|
||||
def _pap(value: str, high: str) -> str | None:
|
||||
if value == "NILM":
|
||||
return "NILM"
|
||||
if value in ("ASC-US", "LSIL"):
|
||||
return "ASC-US/LSIL"
|
||||
if value in ("ASC-H", "HSIL", "CIS"):
|
||||
return high
|
||||
return None
|
||||
|
||||
|
||||
def _book_series(name: str, identifier: str, variables: dict | None, reason: str | None,
|
||||
*, sheet: str | None = None) -> list[dict]:
|
||||
rows, version = workbook(name)
|
||||
matched = [r for r in rows if r["variables"] == variables and
|
||||
(sheet is None or r["sheet"] == sheet)] if variables else []
|
||||
label = " · ".join(f"{k}: {v}" for k, v in variables.items()) if variables else name
|
||||
if len(matched) == 1:
|
||||
label += f" · Hoja {matched[0]['sheet']}, fila {matched[0]['row']}"
|
||||
result = []
|
||||
for outcome in OUTCOMES:
|
||||
points = []
|
||||
why = reason
|
||||
if len(matched) == 1:
|
||||
points = [_point(e["horizon_years"], e["value"], e["confidence_interval"])
|
||||
for e in matched[0]["estimates"] if e["outcome"] == outcome
|
||||
and e["value"] is not None]
|
||||
why = None if points else "outcome_or_estimate_not_published"
|
||||
elif variables:
|
||||
why = "several_source_rows" if matched else "no_published_row"
|
||||
result.append(_series(f"nci-{identifier}-{outcome}", f"NCI ({name})", outcome,
|
||||
label, points, reasons=[why] if why else [],
|
||||
version=f"sha256:{version}"))
|
||||
return result
|
||||
|
||||
|
||||
def nci_post_colposcopy(facts: dict, resolution: dict, cutoff: date) -> list[dict]:
|
||||
sample, reason = _post_sample(facts, resolution, cutoff)
|
||||
variables = None
|
||||
if sample:
|
||||
day = reference._day(sample["sample_date"])
|
||||
biopsies = [b for b in facts.get("biopsies", [])
|
||||
if reference._day(b.get("report_date")) is not None
|
||||
and reference._day(b["report_date"]) < day]
|
||||
pending = [b for b in facts.get("biopsies", [])
|
||||
if reference._day(b.get("request_date")) is not None
|
||||
and reference._day(b["request_date"]) < day
|
||||
and (reference._day(b.get("report_date")) or date.max) >= day]
|
||||
treatments = [e for e in facts.get("events", []) if e.get("type") == "treatment"
|
||||
and reference._day(e.get("date")) is not None
|
||||
and reference._day(e["date"]) <= day]
|
||||
if treatments:
|
||||
reason = "treatment_before_index"
|
||||
elif pending:
|
||||
reason = "prior_biopsy_pending_at_index"
|
||||
elif len(biopsies) != 1:
|
||||
reason = "missing_or_ambiguous_prior_biopsy"
|
||||
else:
|
||||
b = biopsies[0]
|
||||
request = reference._day(b.get("request_date"))
|
||||
referral_day = reference._day(b.get("cytology_sample_date"))
|
||||
referral = [c for c in facts.get("cytologies", [])
|
||||
if referral_day is not None
|
||||
and reference._day(c.get("sample_date")) == referral_day
|
||||
and reference._day(c.get("report_date")) is not None and request is not None
|
||||
and reference._day(c["report_date"]) <= request and reference._valid(c)]
|
||||
visits = [c for c in facts.get("cytologies", [])
|
||||
if reference._day(b["report_date"]) <
|
||||
(reference._day(c.get("sample_date")) or date.min) < day]
|
||||
colposcopies = [e for e in facts.get("events", []) if e.get("type") == "colposcopy"
|
||||
and reference._day(e.get("date")) is not None
|
||||
and referral_day is not None
|
||||
and request is not None and reference._day(e["date"]) == request]
|
||||
if visits:
|
||||
reason = "intermediate_visit_not_supported"
|
||||
elif b.get("histology") not in ("normal", "LSIL"):
|
||||
reason = "biopsy_not_demonstrably_below_cin2"
|
||||
elif len(referral) != 1:
|
||||
reason = "missing_or_ambiguous_referral"
|
||||
elif not colposcopies:
|
||||
reason = "colposcopy_not_documented"
|
||||
elif not (referral_day < request <= reference._day(b["report_date"])):
|
||||
reason = "invalid_biopsy_chronology"
|
||||
else:
|
||||
r = referral[0]
|
||||
pre = ("High Grade" if r["result"] in ("ASC-H", "HSIL", "CIS") else
|
||||
"Low Grade" if r["result"] in ("ASC-US", "LSIL") and r.get("hpv") else None)
|
||||
pap = _pap(sample["result"], "ASC-H/AGC/HSIL+")
|
||||
if pre is None or pap is None:
|
||||
reason = "referral_or_cytology_category_not_verified"
|
||||
else:
|
||||
hpv = "HPV-positive" if sample["hpv"] else "HPV-negative"
|
||||
variables = {"Pre-Colpo Test Result": pre, "Colpo/Biopsy": "<CIN2",
|
||||
"Post-Colpo Test Result [4]": hpv,
|
||||
"Post-Colpo Test Result [5]": pap}
|
||||
return _book_series(POST_COLPO, "post-colposcopy", variables, reason)
|
||||
|
||||
|
||||
def nci_post_treatment(facts: dict, resolution: dict, cutoff: date) -> list[dict]:
|
||||
sample, reason = _post_sample(facts, resolution, cutoff)
|
||||
variables, sheet = None, None
|
||||
if sample:
|
||||
day = reference._day(sample["sample_date"])
|
||||
treatments = [e for e in facts.get("events", [])
|
||||
if e.get("type") == "treatment" and reference._day(e.get("date"))
|
||||
and reference._day(e["date"]) < day]
|
||||
if len(treatments) != 1:
|
||||
reason = "missing_or_ambiguous_treatment"
|
||||
else:
|
||||
treatment = reference._day(treatments[0]["date"])
|
||||
biopsies = [b for b in facts.get("biopsies", [])
|
||||
if reference._day(b.get("request_date")) is not None
|
||||
and reference._day(b.get("report_date")) is not None
|
||||
and reference._day(b["request_date"]) <=
|
||||
reference._day(b["report_date"]) < treatment]
|
||||
visits = [c for c in facts.get("cytologies", [])
|
||||
if treatment < (reference._day(c.get("sample_date")) or date.min) <= day
|
||||
and reference._day(c.get("report_date")) is not None
|
||||
and reference._day(c["report_date"]) <= cutoff and reference._valid(c)]
|
||||
visits.sort(key=lambda c: reference._day(c["sample_date"]))
|
||||
if len(biopsies) != 1:
|
||||
reason = "missing_or_ambiguous_pretreatment_biopsy"
|
||||
elif (reference._day(treatments[0].get("biopsy_request_date")) !=
|
||||
reference._day(biopsies[0]["request_date"])):
|
||||
reason = "treatment_biopsy_link_not_verified"
|
||||
elif biopsies[0].get("histology") not in ("normal", "LSIL"):
|
||||
reason = "pretreatment_cin2_cin3_not_distinguishable"
|
||||
elif any(reference._day(c["report_date"]) > day for c in visits[:-1]):
|
||||
reason = "previous_result_not_available_by_index"
|
||||
elif len({reference._day(c["sample_date"]) for c in visits}) != len(visits):
|
||||
reason = "ambiguous_visits_same_day"
|
||||
elif len(visits) == 1:
|
||||
grade = "CIN1" if biopsies[0]["histology"] == "LSIL" else "<CIN1"
|
||||
pap = _pap(sample["result"], "High Grade")
|
||||
pap = "ASCUS/LSIL" if pap == "ASC-US/LSIL" else pap
|
||||
if pap:
|
||||
sign = "+" if sample["hpv"] else "-"
|
||||
variables = {"Biopsy Before Treatment": grade,
|
||||
"Post-Treatment Test Result": f"{pap} & HPV{sign}"}
|
||||
sheet = "Post Treatment 1 visit"
|
||||
else:
|
||||
reason = "cytology_category_not_verified"
|
||||
elif len(visits) in (2, 3):
|
||||
if any(c.get("hpv") is None for c in visits):
|
||||
reason = "missing_hpv_in_followup"
|
||||
elif any(c.get("hpv") or c.get("hpv_16") or c.get("hpv_18") for c in visits):
|
||||
reason = "positive_or_contradictory_followup"
|
||||
else:
|
||||
category = ("cotest negative" if all(c["result"] == "NILM" for c in visits)
|
||||
else "HPV-")
|
||||
variables = {"Biopsy Before Treatment": "<CIN2"}
|
||||
for i in range(1, len(visits) + 1):
|
||||
suffix = " (Current Test Result)" if i == len(visits) else ""
|
||||
variables[f"Post-Treatment {i} Test Result{suffix}"] = category
|
||||
sheet = f"Post Treatment {len(visits)} visits"
|
||||
else:
|
||||
reason = "number_of_followup_visits_not_supported"
|
||||
result = _book_series(POST_TREATMENT[0], "post-treatment-general", variables, reason,
|
||||
sheet=sheet)
|
||||
# These books require CIN3 before treatment; HSIL in the platform does not distinguish CIN2
|
||||
# from CIN3, and treatment alone cannot establish the histology.
|
||||
for i, name in enumerate(POST_TREATMENT[1:], start=24):
|
||||
result += _book_series(name, f"post-treatment-{i}", None,
|
||||
"pretreatment_cin3_not_distinguishable")
|
||||
return result
|
||||
|
||||
|
||||
def institutional(risks: Iterable[dict], cutoff: date, title) -> list[dict]:
|
||||
"""One series per model, from its latest index date by the cut-off. `risks` are already the
|
||||
ones that still apply (core.cacu.currency); survival is not a risk of disease."""
|
||||
latest: dict[str, list[dict]] = {}
|
||||
for r in risks:
|
||||
index = str(r["index_date"])[:10]
|
||||
if r["model"] == "cacu.survival" or index > cutoff.isoformat():
|
||||
continue
|
||||
held = latest.get(r["model"], [])
|
||||
if not held or index > str(held[0]["index_date"])[:10]:
|
||||
latest[r["model"]] = [r]
|
||||
elif index == str(held[0]["index_date"])[:10]:
|
||||
held.append(r)
|
||||
return [_series(
|
||||
model, "Institucional", "cancer" if "cancer" in model else "CIN2+", title(model),
|
||||
[_point(int(r["horizon_years"]), r["probability"],
|
||||
{"lower": r["ci_low"], "upper": r["ci_high"],
|
||||
"level": None if r["ci_low"] is None else 0.95})
|
||||
for r in sorted(rows, key=lambda r: r["horizon_years"])],
|
||||
version=f"v{rows[0]['version']}",
|
||||
) for model, rows in sorted(latest.items())] # fmt: skip
|
||||
|
||||
|
||||
def series(facts: dict, resolution: dict, risks: Iterable[dict], cutoff: date, title) -> list[dict]:
|
||||
return [*institutional(risks, cutoff, title), *nci_enrollment(facts, resolution),
|
||||
*nci_master(resolution), *nci_post_colposcopy(facts, resolution, cutoff),
|
||||
*nci_post_treatment(facts, resolution, cutoff)] # fmt: skip
|
||||
@@ -0,0 +1,48 @@
|
||||
"""What gold can demonstrate about the stages after a cytology (colposcopy, biopsy, diagnosis):
|
||||
each stage's state and where its day comes from. The route's days are in `gold.cacu_samples`;
|
||||
the sources and the biopsy's record are read beside them (`persistance.fhir`).
|
||||
|
||||
States (the stage's day is published whatever its state; a stage with no day has none):
|
||||
- `recorded`: a biopsy whose own record names the cytology it came from;
|
||||
- `inferred`: dated by association: colposcopy and diagnosis are always so (silver has no
|
||||
record of them: notes and biopsy orders date them), a biopsy only when its record does not
|
||||
name the cytology;
|
||||
- `pending`: a biopsy requested, with no report by the cut-off;
|
||||
- `ambiguous`: a biopsy reported before it was requested (an impossible order).
|
||||
Nothing is inferred beyond that: no request for a colposcopy or a diagnosis is known, so those
|
||||
stages are never `pending`, and no rule dates a colposcopy or a diagnosis twice, so they are
|
||||
never `ambiguous`.
|
||||
|
||||
Sources: `clinical-note` and `biopsy-order` for a colposcopy (a colposcopy-clinic note, or a
|
||||
biopsy ordered at the visit), `clinical-note` for a diagnosis, `biopsy-record` (the record names
|
||||
the cytology) or `date-association` (dates do) for a biopsy."""
|
||||
|
||||
STATES = ("recorded", "inferred", "pending", "ambiguous")
|
||||
SOURCES = ("clinical-note", "biopsy-order", "biopsy-record", "date-association")
|
||||
|
||||
|
||||
def stage_facts(row: dict) -> dict[str, tuple[str, list[str]]]:
|
||||
"""Stage name -> (state, sources) for one sample, from its route row: the days
|
||||
(`colposcopy`, `biopsy`, `diagnosis`, as known by the cut-off), the biopsy's first request
|
||||
and `link`, `reported` (its first report by the cut-off), `backwards` (a reported biopsy older than
|
||||
its request) and the sources that
|
||||
date the colposcopy and the diagnosis (`colposcopy_note`, `colposcopy_biopsy`,
|
||||
`diagnosis_note`)."""
|
||||
out: dict[str, tuple[str, list[str]]] = {}
|
||||
if row.get("colposcopy"):
|
||||
found = [s for s, flag in (("clinical-note", row.get("colposcopy_note")),
|
||||
("biopsy-order", row.get("colposcopy_biopsy"))) if flag] # fmt: skip
|
||||
out["colposcopy"] = ("inferred", found)
|
||||
if row.get("diagnosis"):
|
||||
out["diagnosis"] = ("inferred", ["clinical-note"] if row.get("diagnosis_note") else [])
|
||||
if row.get("requested"):
|
||||
source = {"recorded": "biopsy-record", "inferred": "date-association"}.get(
|
||||
row.get("link") or "") # fmt: skip
|
||||
sources = [source] if source else []
|
||||
if row.get("backwards"):
|
||||
out["biopsy"] = ("ambiguous", sources)
|
||||
elif not row.get("reported"):
|
||||
out["biopsy"] = ("pending", sources)
|
||||
elif row.get("biopsy"): # reported but out of the route's horizon: no day, no state
|
||||
out["biopsy"] = ("recorded" if row.get("link") == "recorded" else "inferred", sources)
|
||||
return out
|
||||
@@ -52,6 +52,11 @@ def biopsy_histology(row: dict) -> str:
|
||||
return row["histology"] or NO_DATA
|
||||
|
||||
|
||||
def should_be_biopsied(row: dict) -> bool:
|
||||
"""A reported mammogram whose BI-RADS asks for a biopsy (the confirmation's denominator)."""
|
||||
return reported(row) and row["birads"] in cama.SUSPICIOUS
|
||||
|
||||
|
||||
def four_to_six(row: dict) -> bool:
|
||||
return reported(row) and row["birads"] in cama.BIRADS_4_TO_6
|
||||
|
||||
@@ -102,13 +107,30 @@ MEASURES = {m.id: m for m in [
|
||||
Measure("CAMA_EU38A", "Días de la toma de la mastografía a su resultado", "mammograms",
|
||||
Duration("days_sample_report", "report_date", "exam_date", H["sample_to_report"],
|
||||
unit="mammogram_id", date="exam_date"), "decrease", facts=REPORT),
|
||||
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Tiempo de tamizaje a diagnóstico", "mammograms",
|
||||
Measure("CAMA_DIAS_TOMA_DIAGNOSTICO", "Días de tamizaje a diagnóstico", "mammograms",
|
||||
Duration("days_sample_diagnosis", "diagnosis_date", "exam_date", H["to_diagnosis"],
|
||||
units=NO_HISTORY, unit="mammogram_id", date="exam_date"),
|
||||
"decrease", facts=DIAGNOSIS),
|
||||
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Tiempo de resultado a diagnóstico", "mammograms",
|
||||
Measure("CAMA_DIAS_RESULTADO_DIAGNOSTICO", "Días de resultado a diagnóstico", "mammograms",
|
||||
Duration("days_report_diagnosis", "report_diagnosis_date", "report_date",
|
||||
H["to_diagnosis"], units=NO_HISTORY, unit="mammogram_id",
|
||||
date="report_date"),
|
||||
"decrease", known="report_known_at"),
|
||||
# Pending the analysts' validation (LOTE-3-CAMA-REBUILD.md): the biopsy is the one whose
|
||||
# request names the mammogram, the first reported if several; the horizon is the
|
||||
# diagnosis's, as no other is set.
|
||||
Measure("CAMA_DIAS_RESULTADO_BIOPSIA",
|
||||
"Días de resultado de mastografía a resultado de biopsia", "mammogram_first_biopsy",
|
||||
Duration("days_report_biopsy", "biopsy_report_date", "report_date", H["to_diagnosis"],
|
||||
units=should_be_biopsied, unit="mammogram_id", date="report_date"),
|
||||
"decrease", facts=REPORT | {"biopsy_known_at": ("biopsy_report_date",
|
||||
"days_report_biopsy")},
|
||||
description=(
|
||||
"PROVISIONAL, pendiente de validación metodológica de los analistas. Días del "
|
||||
"reporte de la mastografía (BI-RADS 4, 4A, 4B, 4C o 5) al reporte de la primera "
|
||||
"biopsia reportada cuya solicitud nombra esa mastografía; sin vínculo explícito "
|
||||
"no hay medición. Horizonte de 180 días reutilizado del tramo a diagnóstico "
|
||||
"(no hay uno propio). Por decidir: fuente real del vínculo, cohorte, selección "
|
||||
"con varias biopsias, horizonte, historia de cáncer y fechas inconsistentes."
|
||||
)),
|
||||
]} # fmt: skip
|
||||
|
||||
@@ -61,6 +61,7 @@ class Study(BaseModel):
|
||||
key: list[str] # fields that, with the person, identify one study instance
|
||||
events: dict[EventClass, Event]
|
||||
fields: dict[str, FieldDef]
|
||||
ingest_only: bool = False
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _consistent(self):
|
||||
@@ -99,7 +100,8 @@ def files() -> dict[str, list[str]]:
|
||||
|
||||
def of_domain(domain: str) -> list[str]:
|
||||
"""The studies a domain serves: its own and the common ones."""
|
||||
return [*files().get(domain, []), *files().get("common", [])]
|
||||
return [name for name in [*files().get(domain, []), *files().get("common", [])]
|
||||
if not studies()[name].ingest_only] # fmt: skip
|
||||
|
||||
|
||||
@cache
|
||||
|
||||
@@ -1,4 +1,16 @@
|
||||
# Cervical cancer screening.
|
||||
cacu_eligibility_evidence:
|
||||
title: Evidencia clínica para elegibilidad CaCu
|
||||
ingest_only: true
|
||||
key: [evidence_id]
|
||||
events:
|
||||
encounter: {date: evidence_date}
|
||||
fields:
|
||||
evidence_id: {type: text, event: encounter, title: Referencia en origen, required: true}
|
||||
evidence_date: {type: date, event: encounter, title: Fecha clínica}
|
||||
evidence_type: {type: text, event: encounter, title: Tipo de evidencia, required: true}
|
||||
evidence_code: {type: text, event: encounter, title: Código clínico, required: true}
|
||||
|
||||
cervical_cytology:
|
||||
title: Citología cervical
|
||||
key: [sample_date]
|
||||
|
||||
+202
-2
@@ -16,6 +16,7 @@ from fhir.resources.R4B.diagnosticreport import DiagnosticReport
|
||||
from fhir.resources.R4B.encounter import Encounter
|
||||
from fhir.resources.R4B.measure import Measure
|
||||
from fhir.resources.R4B.observation import Observation
|
||||
from fhir.resources.R4B.parameters import Parameters
|
||||
from fhir.resources.R4B.patient import Patient
|
||||
from fhir.resources.R4B.procedure import Procedure
|
||||
from fhir.resources.R4B.resource import Resource
|
||||
@@ -36,6 +37,28 @@ _IDS = uuid.uuid5(uuid.NAMESPACE_URL, BASE)
|
||||
|
||||
# Local code systems: code -> display (Spanish, as the screens show them).
|
||||
CODE_SYSTEMS: dict[str, tuple[str, dict[str, str]]] = {
|
||||
"cacu-eligibility-scenario": ("Escenarios de elegibilidad CaCu", {
|
||||
"surveillance": "Vigilancia", "pre_colposcopy": "Precolposcopia",
|
||||
"post_colposcopy": "Postcolposcopia",
|
||||
"post_colposcopy_second_visit": "Segunda visita postcolposcopia",
|
||||
"post_treatment": "Postratamiento", "survival": "Supervivencia",
|
||||
}),
|
||||
"cacu-exclusion-criterion": ("Criterios de exclusión CaCu", {
|
||||
"hysterectomy": "Histerectomía previa al índice",
|
||||
"under_18": "Edad menor de 18 años al índice",
|
||||
"prior_outcome": "Resultado CIN2+ previo al índice",
|
||||
"no_index_result": "Sin resultado de citología o VPH en la visita índice",
|
||||
"unreported_biopsy": "Biopsia solicitada sin resultado",
|
||||
"outcome_by_index": "Resultado CIN2+ hasta la visita índice",
|
||||
"cancer_history": "Antecedente de cáncer cervicouterino",
|
||||
"prior_treatment": "Tratamiento previo a la visita índice",
|
||||
"no_referral": "Sin resultado que sustente la referencia a colposcopia",
|
||||
"no_cotest": "Sin cotest de citología y VPH en la visita índice",
|
||||
"no_pretreatment_biopsy": "Sin biopsia previa al tratamiento en el periodo requerido",
|
||||
"outcome_before_index": "Resultado CIN2+ entre tratamiento e índice",
|
||||
"no_birth_date": "Fecha de nacimiento desconocida",
|
||||
"died_by_index": "Defunción en o antes de la visita índice",
|
||||
}),
|
||||
"cacu-procedure": ("Procedimientos de CaCu", {
|
||||
"colposcopy": "Colposcopia", "treatment": "Tratamiento",
|
||||
}),
|
||||
@@ -97,16 +120,25 @@ CODE_SYSTEMS["catalog-field"] = ("Campos de los estudios", {
|
||||
# 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
|
||||
# Extensions an element may carry more than once (one per period type, one per source).
|
||||
REPEATED = {"period-type", "stage-colposcopy-source", "stage-biopsy-source", "stage-diagnosis-source"}
|
||||
|
||||
# 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"]),
|
||||
"ic-estado": ("code", ["RiskAssessment.prediction"]),
|
||||
"ic-metodo": ("code", ["RiskAssessment.prediction"]),
|
||||
"ic-nivel": ("decimal", ["RiskAssessment.prediction"]),
|
||||
"q1": ("decimal", DURATIONS),
|
||||
"q3": ("decimal", DURATIONS),
|
||||
"corte-conocimiento": ("dateTime", ["MeasureReport"]),
|
||||
"period-type": ("code", ["Measure"]),
|
||||
"follow-up-status": ("Coding", ["Patient"]),
|
||||
"follow-up-priority": ("Coding", ["Patient"]),
|
||||
"first-hysterectomy-recorded": ("date", ["Patient"]),
|
||||
# why some of her model risks are not shown at the cut-off (core.cacu.currency)
|
||||
"risk-withheld": ("string", ["Patient"]),
|
||||
"report-date": ("date", ["DiagnosticReport"]),
|
||||
"days-to-diagnosis": ("integer", ["DiagnosticReport"]),
|
||||
# what followed a cytology: colposcopy and diagnosis are inferred; `biopsy-link` says
|
||||
@@ -116,6 +148,14 @@ EXTENSIONS: dict[str, tuple[str, list[str]]] = {
|
||||
"biopsy-date": ("date", ["DiagnosticReport"]),
|
||||
"biopsy-link": ("code", ["DiagnosticReport"]),
|
||||
"diagnosis-date": ("date", ["DiagnosticReport"]),
|
||||
# the state of each stage and where its day comes from (core.cacu.stages): recorded, inferred,
|
||||
# pending or ambiguous; sources are repeated, one per source
|
||||
"stage-colposcopy-state": ("code", ["DiagnosticReport"]),
|
||||
"stage-colposcopy-source": ("code", ["DiagnosticReport"]),
|
||||
"stage-biopsy-state": ("code", ["DiagnosticReport"]),
|
||||
"stage-biopsy-source": ("code", ["DiagnosticReport"]),
|
||||
"stage-diagnosis-state": ("code", ["DiagnosticReport"]),
|
||||
"stage-diagnosis-source": ("code", ["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
|
||||
@@ -174,6 +214,12 @@ _REPORT_FACTS = {"days": "days-to-diagnosis", "colposcopy": "colposcopy-date",
|
||||
|
||||
def report_facts(row: dict) -> list[dict]:
|
||||
found = []
|
||||
if "requested" in row or "colposcopy_note" in row: # CaCu: what the route's stages are
|
||||
from core.cacu.stages import stage_facts
|
||||
|
||||
for stage, (state, sources) in stage_facts(row).items():
|
||||
found.append(ext(f"stage-{stage}-state", "code", state))
|
||||
found += [ext(f"stage-{stage}-source", "code", s) for s in sources]
|
||||
for column, name in _REPORT_FACTS.items():
|
||||
if (value := row.get(column)) is not None:
|
||||
kind = EXTENSIONS[name][0]
|
||||
@@ -205,6 +251,12 @@ def patient(row: dict, status_system: str | None = None) -> Patient:
|
||||
priority = coding("follow-up-priority", row["priority"])
|
||||
found["extension"].append(ext("follow-up-priority", "Coding", priority))
|
||||
found.setdefault("extension", []).extend(_tea_listed(row))
|
||||
if row.get("first_hysterectomy"):
|
||||
found["extension"].append(
|
||||
ext("first-hysterectomy-recorded", "date", _day(row["first_hysterectomy"]))
|
||||
)
|
||||
if row.get("risk_withheld"):
|
||||
found["extension"].append(ext("risk-withheld", "string", row["risk_withheld"]))
|
||||
if not found["extension"]:
|
||||
del found["extension"]
|
||||
if row.get("names"):
|
||||
@@ -387,6 +439,13 @@ def risk_assessment(row: dict, horizons: Iterable[dict]) -> RiskAssessment:
|
||||
bounds = (("ic-bajo", "ci_low"), ("ic-alto", "ci_high"))
|
||||
interval = [ext(name, "decimal", h[key]) for name, key in bounds
|
||||
if h.get(key) is not None] # fmt: skip
|
||||
if row["model"] == "cacu.survival":
|
||||
available = h.get("ci_low") is not None and h.get("ci_high") is not None
|
||||
interval.append(ext("ic-estado", "code", "available" if available else "unavailable"))
|
||||
if available:
|
||||
interval.append(ext("ic-metodo", "code", h.get("ci_method") or "unknown"))
|
||||
if h.get("ci_level") is not None:
|
||||
interval.append(ext("ic-nivel", "decimal", h["ci_level"]))
|
||||
predictions.append({
|
||||
"probabilityDecimal": h["probability"],
|
||||
"whenRange": {"high": {"value": h["horizon_years"], "unit": "a", "system": UCUM,
|
||||
@@ -501,8 +560,7 @@ def extensions() -> list[StructureDefinition]:
|
||||
"baseDefinition": "http://hl7.org/fhir/StructureDefinition/Extension",
|
||||
"derivation": "constraint",
|
||||
"differential": {"element": [
|
||||
{"id": "Extension", "path": "Extension", "max": "*" if name == "period-type"
|
||||
else "1"},
|
||||
{"id": "Extension", "path": "Extension", "max": "*" if name in REPEATED else "1"},
|
||||
{"id": "Extension.extension", "path": "Extension.extension", "max": "0"},
|
||||
{"id": "Extension.url", "path": "Extension.url", "fixedUri": url},
|
||||
{"id": "Extension.value[x]", "path": "Extension.value[x]", "min": 1,
|
||||
@@ -542,3 +600,145 @@ def conformance() -> list[Resource]:
|
||||
"""Everything our resources declare: what the validator loads, and what the
|
||||
CapabilityStatement points to."""
|
||||
return [*code_systems(), *extensions(), *search_parameters()]
|
||||
|
||||
|
||||
# --- the NCI reference comparison (experimental) ------------------------------------------------
|
||||
|
||||
|
||||
def _part(name: str, kind: str, value=None, parts: list | None = None) -> dict:
|
||||
"""A Parameters part: a named value of the given kind (code, string, date, integer, decimal,
|
||||
boolean) or named parts; nothing when it has neither (FHIR allows no empty part)."""
|
||||
found: dict = {"name": name}
|
||||
if parts is not None:
|
||||
kept = [p for p in parts if p]
|
||||
if not kept:
|
||||
return {}
|
||||
found["part"] = kept
|
||||
elif value is not None:
|
||||
found[f"value{kind[0].upper()}{kind[1:]}"] = (
|
||||
value.isoformat() if isinstance(value, date) and kind == "date" else value)
|
||||
else:
|
||||
return {}
|
||||
return found
|
||||
|
||||
|
||||
def reference_risk(resolution: dict, comparison: list[dict], source: dict) -> Parameters:
|
||||
"""One patient's NCI reference resolution as a Parameters (the result of the $reference-risk
|
||||
operation): the state and its reasons, the scenario and the row it came from, what was used, each
|
||||
horizon's reference risk and, per institutional model, the comparison. Nothing here is stored: a
|
||||
state with no risk has no reference part, and a blank risk is not zero."""
|
||||
p = _part
|
||||
index = resolution.get("index") or {}
|
||||
scenario = resolution.get("scenario")
|
||||
row = resolution.get("row")
|
||||
parts = [
|
||||
p("status", "code", resolution["status"]),
|
||||
*[p("reason", "code", r) for r in resolution["reasons"]],
|
||||
p("experimental", "boolean", True),
|
||||
p("cutoff", "date", resolution["cutoff"]),
|
||||
p("source", "string", None, [
|
||||
p("id", "string", source["id"]), p("file", "string", source["source"]["file"]),
|
||||
p("sha256", "string", source["source"]["sha256"]),
|
||||
p("outcome", "code", source["outcome"]["code"]),
|
||||
p("status", "string", source["status"])]),
|
||||
]
|
||||
if index:
|
||||
parts.append(p("index", "string", None, [
|
||||
p("sample-date", "date", index.get("sample_date")),
|
||||
p("report-date", "date", index.get("report_date")),
|
||||
p("result", "code", index.get("result")),
|
||||
p("age", "integer", resolution.get("age"))]))
|
||||
if resolution.get("evaluation_date"):
|
||||
parts.append(p("evaluation-date", "date", resolution["evaluation_date"]))
|
||||
if scenario:
|
||||
parts.append(p("scenario", "string", None, [
|
||||
p("table", "code", scenario["table"]), p("label", "string", scenario["label"]),
|
||||
*[p("key", "string", None, [p("name", "code", k), p("value", "string", v)])
|
||||
for k, v in scenario["key"].items() if v is not None]]))
|
||||
if row:
|
||||
parts.append(p("row", "string", None, [
|
||||
p("sheet", "string", row["sheet"]), p("number", "integer", row["row"]),
|
||||
p("official-check", "code", row.get("official_check")),
|
||||
p("matched-via", "code", resolution.get("matched_via"))]))
|
||||
for u in resolution.get("used", []):
|
||||
parts.append(p("used", "string", None, [
|
||||
p(k.replace("_", "-"), "date" if k.endswith("date") else "string", v if k.endswith("date")
|
||||
else None if v is None else str(v)) for k, v in u.items() if v is not None]))
|
||||
parts += [p("assumption", "string", a) for a in resolution.get("assumptions", [])]
|
||||
for h in resolution.get("horizons", []):
|
||||
mine = [c for c in comparison if c["years"] == h["years"]]
|
||||
parts.append(p("horizon", "string", None, [
|
||||
p("years", "integer", h["years"]),
|
||||
p("published", "boolean", h["published"]),
|
||||
p("reference", "decimal", h["risk"]),
|
||||
*[p("comparison", "string", None, [
|
||||
p("model", "code", c.get("model")), p("title", "string", c.get("title")),
|
||||
p("outcome", "string", c.get("outcome")),
|
||||
p("institutional", "decimal", c.get("institutional")),
|
||||
p("institutional-low", "decimal", (c.get("interval") or [None, None])[0]),
|
||||
p("institutional-high", "decimal", (c.get("interval") or [None, None])[1]),
|
||||
p("status", "code", c["status"]),
|
||||
p("difference-pp", "decimal", c.get("difference_pp")),
|
||||
*[p("reason", "code", r) for r in c["reasons"]]]) for c in mine]]))
|
||||
return Parameters.model_validate({"resourceType": "Parameters",
|
||||
"parameter": [x for x in parts if x]})
|
||||
|
||||
|
||||
def risk_series(series: list[dict], patient_id: str, cutoff: date) -> Parameters:
|
||||
"""The risk series of one patient (core.cacu.risk_series): probabilities as stored or
|
||||
published, not rounded; a series without a number says why."""
|
||||
p = _part
|
||||
parts = [p("patient", "Reference", {"reference": f"Patient/{patient_id}"}),
|
||||
p("cutoff", "date", cutoff), p("experimental", "boolean", True)] # fmt: skip
|
||||
for s in series:
|
||||
parts.append(p("series", "string", None, [
|
||||
p("id", "string", s["id"]), p("source", "string", s["source"]),
|
||||
p("version", "string", s["version"]), p("outcome", "string", s["outcome"]),
|
||||
p("label", "string", s["label"]), p("status", "code", s["status"]),
|
||||
*[p("reason", "code", r) for r in s["reasons"]],
|
||||
*[p("assumption", "string", a) for a in s["assumptions"]],
|
||||
*[p("point", "string", None, [
|
||||
p("years", "integer", point["years"]),
|
||||
p("probability", "decimal", point["probability"]),
|
||||
p("low", "decimal", point["low"]), p("high", "decimal", point["high"]),
|
||||
p("level", "decimal", point["level"])]) for point in s["points"]]]))
|
||||
return Parameters.model_validate({"resourceType": "Parameters",
|
||||
"parameter": [x for x in parts if x]})
|
||||
|
||||
|
||||
def cacu_eligibility(rows: Iterable[dict], patient_id: str, cutoff: date) -> Parameters:
|
||||
"""Eligibility of one patient's indexed CaCu candidates, with each detected reason."""
|
||||
candidates: dict[tuple, dict] = {}
|
||||
for row in rows:
|
||||
key = (row["scenario"], row["index_date"], row.get("index_sample_id"))
|
||||
candidate = candidates.setdefault(key, {
|
||||
"scenario": row["scenario"], "index_date": row["index_date"],
|
||||
"sample_id": row.get("index_sample_id"), "eligible": bool(row["eligible"]),
|
||||
"criteria": [],
|
||||
})
|
||||
if row.get("criterion") is not None:
|
||||
candidate["criteria"].append(row["criterion"])
|
||||
|
||||
p = _part
|
||||
|
||||
def coding(system_name: str, code: str) -> dict:
|
||||
title, codes = CODE_SYSTEMS[system_name]
|
||||
return {"system": f"{CODES}{system_name}", "code": code,
|
||||
"display": codes.get(code, title)}
|
||||
|
||||
parts = [
|
||||
p("status", "code", "evaluated" if candidates else "no_candidate"),
|
||||
p("patient", "Reference", {"reference": f"Patient/{patient_id}"}),
|
||||
p("cutoff", "date", cutoff),
|
||||
]
|
||||
for key in sorted(candidates, key=lambda item: tuple(str(value) for value in item)):
|
||||
candidate = candidates[key]
|
||||
parts.append(p("candidate", "string", None, [
|
||||
p("scenario", "Coding", coding("cacu-eligibility-scenario", candidate["scenario"])),
|
||||
p("index-date", "date", candidate["index_date"]),
|
||||
p("index-sample-id", "string", candidate["sample_id"]),
|
||||
p("eligible", "boolean", candidate["eligible"]),
|
||||
*[p("criterion", "Coding", coding("cacu-exclusion-criterion", reason))
|
||||
for reason in sorted(set(candidate["criteria"]))],
|
||||
]))
|
||||
return Parameters.model_validate({"resourceType": "Parameters", "parameter": parts})
|
||||
|
||||
+158
-6
@@ -11,18 +11,23 @@ target holds the row saying why.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from collections.abc import Iterable
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
|
||||
from core import catalog, concept_map
|
||||
from core.fhir import CODES
|
||||
from core.pipeline import RECORD
|
||||
from core.pipeline import FIELD_EVIDENCE, RECORD
|
||||
from core.schema import IDENTIFIER_SYSTEMS
|
||||
|
||||
STUDY = CODES + "study"
|
||||
FIELD = CODES + "catalog-field"
|
||||
EVIDENCE = "cacu_eligibility_evidence"
|
||||
FINAL_RESULTS = {"final", "amended", "corrected"}
|
||||
|
||||
|
||||
def record(sender: str, reference: str) -> str:
|
||||
@@ -48,6 +53,28 @@ def _entries(bundle: dict) -> dict[str, dict]:
|
||||
return found
|
||||
|
||||
|
||||
def combined(bundles: Iterable[dict]) -> dict:
|
||||
"""Latest resources for one sender, with Bundle-local references made canonical."""
|
||||
def reference(item: dict, named: dict) -> dict:
|
||||
target = named.get(item.get("reference"))
|
||||
if target is None:
|
||||
return item
|
||||
return {**item, "reference": f"{target['resourceType']}/{target['id']}"}
|
||||
|
||||
latest = {}
|
||||
for bundle in bundles:
|
||||
named = _entries(bundle)
|
||||
for ref, resource in resources(bundle).items():
|
||||
resource = resource.copy()
|
||||
for field in ("subject", "encounter"):
|
||||
if resource.get(field):
|
||||
resource[field] = reference(resource[field], named)
|
||||
if resource["resourceType"] == "DiagnosticReport" and resource.get("result"):
|
||||
resource["result"] = [reference(item, named) for item in resource["result"]]
|
||||
latest[ref] = resource
|
||||
return {"entry": [{"resource": resource} for resource in latest.values()]}
|
||||
|
||||
|
||||
def _translated(maps: Iterable[ConceptMap], coding: dict, system: str) -> str | None:
|
||||
"""A coding as a code of `system`: as it is when already there, else through the maps."""
|
||||
if coding.get("system") == system:
|
||||
@@ -97,6 +124,98 @@ def _value(observation: dict, f: catalog.FieldDef, maps) -> Any:
|
||||
return None
|
||||
|
||||
|
||||
# The day of a record is the one in Monterrey, whatever zone the sender wrote it in.
|
||||
LOCAL = ZoneInfo("America/Monterrey")
|
||||
|
||||
|
||||
def _source_time(value: str | None) -> str | None:
|
||||
"""Keep a complete date or write a zoned timestamp in Monterrey time.
|
||||
|
||||
Partial dates and timestamps without a zone cannot establish a safe day cut-off.
|
||||
They remain unknown rather than being completed or assigned a local timezone.
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
if len(value) == 10:
|
||||
return date.fromisoformat(value).isoformat()
|
||||
stamp = datetime.fromisoformat(value)
|
||||
if stamp.tzinfo is not None:
|
||||
return stamp.astimezone(LOCAL).isoformat(timespec="microseconds")
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _clinical_day(value: str | None) -> str | None:
|
||||
"""Use the same Monterrey day for clinical and availability timestamps."""
|
||||
normalized = _source_time(value)
|
||||
return normalized[:10] if normalized else None
|
||||
|
||||
|
||||
def _evidence(ref: str, clinical: str | None, available: str | None) -> dict:
|
||||
return {
|
||||
"source_ref": ref,
|
||||
"source_clinical_date": _clinical_day(clinical),
|
||||
"source_available_at": _source_time(available),
|
||||
}
|
||||
|
||||
|
||||
def _report_observations(sent: dict, named: dict) -> set[str]:
|
||||
return {
|
||||
o["id"]
|
||||
for r in sent.values() if r["resourceType"] == "DiagnosticReport"
|
||||
for item in r.get("result", [])
|
||||
if (o := named.get(item.get("reference", ""))) is not None
|
||||
and o["resourceType"] == "Observation"
|
||||
}
|
||||
|
||||
|
||||
def _standalone_evidence(sent: dict, named: dict, sender: str, maps) -> list[dict]:
|
||||
linked = _report_observations(sent, named)
|
||||
exams = catalog.studies()["cervical_cytology"].fields["gynecologic_condition"]
|
||||
icd10 = catalog.systems()["icd-10"].url
|
||||
out = []
|
||||
for ref, r in sent.items():
|
||||
kind = r["resourceType"]
|
||||
if kind == "Condition":
|
||||
verification = _codings(r.get("verificationStatus"))
|
||||
if verification and not any(c.get("code") == "confirmed" for c in verification):
|
||||
continue
|
||||
codes = (_translated(maps, c, icd10) for c in _codings(r.get("code")))
|
||||
value = next((code for code in codes if code), None)
|
||||
clinical = r.get("onsetDateTime") or (r.get("onsetPeriod") or {}).get("end")
|
||||
available = r.get("recordedDate")
|
||||
event = "condition"
|
||||
elif kind == "Observation":
|
||||
if (r["id"] in linked or r.get("encounter")
|
||||
or r.get("status") not in FINAL_RESULTS):
|
||||
continue
|
||||
if not any(_translated(maps, c, FIELD) == "cervical_cytology.gynecologic_condition"
|
||||
for c in _codings(r.get("code"))):
|
||||
continue
|
||||
value = _value(r, exams, maps)
|
||||
if value not in exams.codes:
|
||||
continue
|
||||
clinical = (r.get("effectiveDateTime") or r.get("effectiveInstant")
|
||||
or (r.get("effectivePeriod") or {}).get("end"))
|
||||
available = r.get("issued")
|
||||
event = "gynecologic_condition"
|
||||
else:
|
||||
continue
|
||||
if value:
|
||||
evidence = _evidence(f"{sender}|{ref}", clinical, available)
|
||||
out.append({
|
||||
RECORD: record(sender, ref),
|
||||
"evidence_id": evidence["source_ref"],
|
||||
"evidence_date": evidence["source_clinical_date"],
|
||||
"evidence_type": event,
|
||||
"evidence_code": value,
|
||||
FIELD_EVIDENCE: json.dumps({"evidence_code": evidence}),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()) -> list[dict]:
|
||||
"""The Bundle's rows of one entity: `identity` (each Patient, and each report's
|
||||
subject), `death` (Patients who died), or a study of the catalog (each report or
|
||||
@@ -111,18 +230,25 @@ def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()
|
||||
if entity == "identity":
|
||||
out = [{**identity(r), RECORD: record(sender, ref)}
|
||||
for ref, r in sent.items() if r["resourceType"] == "Patient"] # fmt: skip
|
||||
linked = _report_observations(sent, named)
|
||||
for ref, r in sent.items():
|
||||
if r["resourceType"] in ("DiagnosticReport", "Encounter") and (p := subject(r)):
|
||||
kind = r["resourceType"]
|
||||
standalone = kind == "Observation" and r["id"] not in linked and not r.get("encounter")
|
||||
if (standalone or kind in ("DiagnosticReport", "Encounter", "Condition")) and (
|
||||
p := subject(r)
|
||||
):
|
||||
out.append({**identity(p), RECORD: record(sender, ref)})
|
||||
return out
|
||||
if entity == "death":
|
||||
return [{"death_date": r["deceasedDateTime"][:10], RECORD: record(sender, ref)}
|
||||
for ref, r in sent.items()
|
||||
if r["resourceType"] == "Patient" and r.get("deceasedDateTime")] # fmt: skip
|
||||
if entity == EVIDENCE:
|
||||
return _standalone_evidence(sent, named, sender, maps)
|
||||
|
||||
spec = catalog.studies()[entity]
|
||||
kind = "DiagnosticReport" if "report" in spec.events else "Encounter"
|
||||
root = next(e for e in spec.events.values() if e.parent is None)
|
||||
root_name, root = next((n, e) for n, e in spec.events.items() if e.parent is None)
|
||||
out = []
|
||||
for ref, r in sent.items():
|
||||
if r["resourceType"] != kind:
|
||||
@@ -130,28 +256,54 @@ def rows(bundle: dict, entity: str, sender: str, maps: Iterable[ConceptMap] = ()
|
||||
code = r.get("code") if kind == "DiagnosticReport" else (r.get("type") or [None])[0]
|
||||
if not any(_translated(maps, c, STUDY) == entity for c in _codings(code)):
|
||||
continue
|
||||
if r.get("status") == "entered-in-error": # annulled: nothing of it is used
|
||||
continue
|
||||
row: dict[str, Any] = {RECORD: record(sender, ref)}
|
||||
start = r.get("effectiveDateTime") if kind == "DiagnosticReport" else (
|
||||
(r.get("period") or {}).get("start")) # fmt: skip
|
||||
if kind == "DiagnosticReport":
|
||||
start = r.get("effectiveDateTime") or (r.get("effectivePeriod") or {}).get("start")
|
||||
else:
|
||||
start = (r.get("period") or {}).get("start")
|
||||
if start:
|
||||
row[root.date] = start[:10]
|
||||
release = None
|
||||
# A preliminary report is a sample still waiting for its result.
|
||||
pending = r.get("status") == "preliminary"
|
||||
if kind == "DiagnosticReport":
|
||||
reported = next((x.get("valueDate") for x in r.get("extension", [])
|
||||
if x.get("url", "").endswith("/report-date")), None) # fmt: skip
|
||||
reported = reported or (r.get("issued") or "")[:10] or None
|
||||
if reported:
|
||||
if r.get("status") in FINAL_RESULTS | {"appended"}:
|
||||
release = r.get("issued") or reported
|
||||
if reported and not pending:
|
||||
row[spec.events["report"].date] = reported
|
||||
results = [named.get(x.get("reference", "")) for x in r.get("result", [])]
|
||||
else:
|
||||
mine = {ref, *(k for k, v in named.items() if v is r)}
|
||||
results = [o for o in sent.values() if o["resourceType"] == "Observation"
|
||||
and (o.get("encounter") or {}).get("reference") in mine] # fmt: skip
|
||||
evidence = {}
|
||||
for o in filter(None, results):
|
||||
if o.get("resourceType") != "Observation" or o.get("status") == "entered-in-error":
|
||||
continue
|
||||
if o.get("subject") and subject(o) is not subject(r):
|
||||
continue
|
||||
for coding in _codings(o.get("code")):
|
||||
name = _translated(maps, coding, FIELD) or ""
|
||||
study, _, field = name.partition(".")
|
||||
if study == entity and field in spec.fields:
|
||||
# of a preliminary report or value, only what the sample itself says
|
||||
unfinished = pending or o.get("status") == "preliminary"
|
||||
if unfinished and spec.fields[field].event != root_name:
|
||||
break
|
||||
row[field] = _value(o, spec.fields[field], maps)
|
||||
clinical = (o.get("effectiveDateTime") or o.get("effectiveInstant")
|
||||
or (o.get("effectivePeriod") or {}).get("end") or start)
|
||||
available = (o.get("issued") or release
|
||||
if o.get("status") in FINAL_RESULTS else None)
|
||||
evidence[field] = _evidence(f"{sender}|Observation/{o['id']}", clinical,
|
||||
available)
|
||||
break
|
||||
if evidence:
|
||||
row[FIELD_EVIDENCE] = json.dumps(evidence)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
@@ -20,6 +20,9 @@ TITLES: dict[str, str] = {
|
||||
"tea.eeg-ados2": "Relación del EEG con el ADOS-2",
|
||||
}
|
||||
|
||||
# Trained and scored to test and develop, compared in Gobernanza: never a patient's risk.
|
||||
DEVELOPMENT = frozenset({"cacu.cin2_logistic"})
|
||||
|
||||
|
||||
def title(model: str) -> str:
|
||||
"""`model` (`<domain>.<name>`) as the pages name it."""
|
||||
|
||||
@@ -358,6 +358,7 @@ class Pipeline(BaseModel):
|
||||
RECORD = "_record" # the source row every row comes from (hash of that row)
|
||||
HELD = "_held" # why a row may not reach silver (list of reasons) or None
|
||||
QUOTES = "_quotes" # what text each LLM value was read from
|
||||
FIELD_EVIDENCE = "_field_evidence" # source dates and reference for individual values
|
||||
|
||||
|
||||
def matches(node: Route, row: dict[str, Any]) -> bool:
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Versioned, source-preserving representation of published risk table rows.
|
||||
|
||||
This module represents source data; it does not infer patient variables or compare models.
|
||||
"""
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
FORMAT_VERSION = "1.0.0"
|
||||
|
||||
|
||||
def source_estimate(*, outcome: str, horizon_years: int, value: float | None,
|
||||
unit: str, file: str, sheet: str, row: int,
|
||||
lower: float | None = None, upper: float | None = None,
|
||||
confidence_level: float | None = None,
|
||||
confidence_method: str | None = None) -> dict:
|
||||
"""Represent one explicit workbook estimate; callers must identify its source unit."""
|
||||
if outcome not in {"CIN2+", "CIN3+", "cancer"}:
|
||||
raise ValueError("unsupported outcome")
|
||||
if unit not in {"fraction", "percent"}:
|
||||
raise ValueError("unit must be fraction or percent")
|
||||
scale = 100 if unit == "percent" else 1
|
||||
|
||||
def probability(number):
|
||||
return None if number is None else number / scale
|
||||
|
||||
interval = None
|
||||
if lower is not None or upper is not None:
|
||||
interval = {"lower": probability(lower), "upper": probability(upper),
|
||||
"level": confidence_level, "method": confidence_method}
|
||||
return {
|
||||
"outcome": outcome, "horizon_years": horizon_years, "measure": "probability",
|
||||
"value": probability(value), "confidence_interval": interval,
|
||||
"source": {"file": file, "sheet": sheet, "row": row, "unit": unit,
|
||||
"value": value, "lower": lower, "upper": upper},
|
||||
}
|
||||
|
||||
|
||||
def nci_reference_table(source: dict) -> dict:
|
||||
"""Adapt the existing NCI extract without deriving missing estimates or intervals."""
|
||||
rows = []
|
||||
for row in source["rows"]:
|
||||
estimates = []
|
||||
for horizon in source["horizons_years"][row["table"]]:
|
||||
key = str(horizon)
|
||||
estimates.append({
|
||||
"outcome": source["outcome"]["code"],
|
||||
"horizon_years": horizon,
|
||||
"measure": "probability",
|
||||
"value": row["risks"][key],
|
||||
"confidence_interval": None,
|
||||
})
|
||||
rows.append({
|
||||
"scenario": row["table"],
|
||||
"variables": deepcopy(row["key"]),
|
||||
"outcome": deepcopy(source["outcome"]),
|
||||
"estimates": estimates,
|
||||
"source_row": deepcopy(row),
|
||||
})
|
||||
return {
|
||||
"format_version": FORMAT_VERSION,
|
||||
"source_id": source["id"],
|
||||
"source_version": source["source"].get("sha256"),
|
||||
"source_metadata": deepcopy({k: v for k, v in source.items() if k != "rows"}),
|
||||
"rows": rows,
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Reads the published NCI risk workbooks into `core.risk_tables` estimates (stdlib only).
|
||||
|
||||
The unit of each book is declared in `UNITS`, checked against its own case counts: a header's
|
||||
"(%)" cannot be trusted. A book not listed there is refused.
|
||||
|
||||
Two layouts. Wide books (post-colposcopy, post-treatment): the variables are the columns before
|
||||
`N`, and each estimate is a `<outcome> <horizon> risk (%)` column, with its `SE`,
|
||||
`LL95` and `UL95` columns beside it when published. All in percent but the general
|
||||
post-treatment book, whose values are fractions under "(%)" headers.
|
||||
The enrollment book is long: one row per
|
||||
outcome and combination, with `CR.<year>`, `LL95.<year>` and `UL95.<year>` as fractions (its
|
||||
headers name no unit; its values are fractions).
|
||||
|
||||
Nothing is derived, clipped or filled in: a blank estimate stays None (not zero), a limit below
|
||||
zero stays as published, and the interval method is None because the books do not name it."""
|
||||
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
from core.risk_tables import source_estimate
|
||||
|
||||
NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
|
||||
REL = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
|
||||
OUTCOMES = {"cin2+": "CIN2+", "cin3+": "CIN3+", "cancer": "cancer"}
|
||||
RISK = re.compile(r"(CIN2\+|CIN3\+|CANCER)\s+(Immediate|\d+\s*year)\s+risk", re.I)
|
||||
LONG = re.compile(r"CR\.(\d+)")
|
||||
UNITS = {
|
||||
"1_Enrollment Table.xlsx": "fraction",
|
||||
"17_Post_Colpo.xlsx": "percent",
|
||||
"23_Post_Treatment General.xlsx": "fraction", # its headers say (%): they are not
|
||||
"24_Post_Treatment_1visit_nostratifiedPre.xlsx": "percent",
|
||||
"25_Post_Treatment_1visit_stratifiedPre.xlsx": "percent",
|
||||
"26_Post_Treatment_2-3visit.xlsx": "percent",
|
||||
}
|
||||
|
||||
|
||||
def _column(reference: str) -> int:
|
||||
number = 0
|
||||
for letter in re.match(r"[A-Z]+", reference).group():
|
||||
number = number * 26 + ord(letter) - ord("A") + 1
|
||||
return number
|
||||
|
||||
|
||||
def _sheets(path: Path):
|
||||
"""Each sheet's name and rows: (row number, {column number: text})."""
|
||||
with zipfile.ZipFile(path) as book:
|
||||
shared = []
|
||||
if "xl/sharedStrings.xml" in book.namelist():
|
||||
shared = ["".join(t.text or "" for t in item.iter(f"{NS}t"))
|
||||
for item in ET.fromstring(book.read("xl/sharedStrings.xml"))] # fmt: skip
|
||||
targets = {r.get("Id"): r.get("Target")
|
||||
for r in ET.fromstring(book.read("xl/_rels/workbook.xml.rels"))} # fmt: skip
|
||||
for sheet in ET.fromstring(book.read("xl/workbook.xml")).iter(f"{NS}sheet"):
|
||||
target = targets[sheet.get(REL)].lstrip("/").removeprefix("xl/")
|
||||
rows = []
|
||||
for row in ET.fromstring(book.read(f"xl/{target}")).iter(f"{NS}row"):
|
||||
cells = {}
|
||||
for cell in row.findall(f"{NS}c"):
|
||||
value = cell.find(f"{NS}v")
|
||||
if value is None:
|
||||
text = "".join(t.text or "" for t in cell.iter(f"{NS}t"))
|
||||
elif cell.get("t") == "s":
|
||||
text = shared[int(value.text)]
|
||||
else:
|
||||
text = value.text
|
||||
if text and text.strip():
|
||||
cells[_column(cell.get("r"))] = text.strip()
|
||||
if cells:
|
||||
rows.append((int(row.get("r")), cells))
|
||||
yield sheet.get("name"), rows
|
||||
|
||||
|
||||
def _number(cells: dict, column: int | None, where: str) -> float | None:
|
||||
text = cells.get(column)
|
||||
if text is None or text in {".", "-", "NA"}:
|
||||
return None
|
||||
try:
|
||||
return float(text)
|
||||
except ValueError:
|
||||
raise ValueError(f"{where}, column {column}: not a number: {text!r}") from None
|
||||
|
||||
|
||||
def _wide(file: str, sheet: str, rows: list):
|
||||
header = rows[0][1]
|
||||
first = min(c for c, name in header.items() if name == "N")
|
||||
risks = [] # (outcome, years, value column, lower column, upper column)
|
||||
for column, name in sorted(header.items()):
|
||||
if found := RISK.search(name):
|
||||
horizon = found[2].lower()
|
||||
beside = {header.get(column + i, "").split()[0].upper(): column + i
|
||||
for i in (1, 2, 3) if header.get(column + i, "").upper()
|
||||
.startswith(("SE", "LL95", "UL95"))} # fmt: skip
|
||||
risks.append((OUTCOMES[found[1].lower()],
|
||||
0 if horizon == "immediate" else int(horizon.split()[0]), column,
|
||||
beside.get("LL95"), beside.get("UL95"))) # fmt: skip
|
||||
for number, cells in rows[1:]:
|
||||
# a total or a footnote has no combination of variables and no estimate
|
||||
variable_headers = [header[c] for c in sorted(header) if c < first and header[c] != "%"]
|
||||
# A workbook may repeat a heading for separate variables (book 17 uses it for
|
||||
# both HPV and cytology). Keep both source columns instead of silently replacing one.
|
||||
variables = {(f"{header[c]} [{c}]" if variable_headers.count(header[c]) > 1 else header[c]):
|
||||
cells[c] for c in sorted(header) if c < first and c in cells
|
||||
and header[c] != "%"} # fmt: skip
|
||||
if not variables or not any(column in cells for _, _, column, _, _ in risks):
|
||||
continue
|
||||
where = f"{file} / {sheet} / row {number}"
|
||||
estimates = []
|
||||
for outcome, years, column, low, high in risks:
|
||||
lower, upper = _number(cells, low, where), _number(cells, high, where)
|
||||
estimates.append(source_estimate(
|
||||
outcome=outcome, horizon_years=years, value=_number(cells, column, where),
|
||||
unit=UNITS[file], file=file, sheet=sheet, row=number, lower=lower, upper=upper,
|
||||
confidence_level=None if low is None else 0.95,
|
||||
)) # fmt: skip
|
||||
yield {"file": file, "sheet": sheet, "row": number, "variables": variables,
|
||||
"estimates": estimates} # fmt: skip
|
||||
|
||||
|
||||
def _long(file: str, sheet: str, rows: list):
|
||||
header = rows[0][1]
|
||||
at = {name: column for column, name in header.items()}
|
||||
horizons = sorted(int(m[1]) for name in at if (m := LONG.fullmatch(name)))
|
||||
carried: dict[int, str] = {} # the outcome and HPV result, written once for rows under them
|
||||
for number, cells in rows[1:]:
|
||||
for name in ("disease", "hpv"):
|
||||
if at[name] in cells:
|
||||
carried[at[name]] = cells[at[name]]
|
||||
cells = {**carried, **cells}
|
||||
where = f"{file} / {sheet} / row {number}"
|
||||
outcome = OUTCOMES[cells[at["disease"]].lower()]
|
||||
estimates = [source_estimate(
|
||||
outcome=outcome, horizon_years=year, value=_number(cells, at[f"CR.{year}"], where),
|
||||
unit=UNITS[file], file=file, sheet=sheet, row=number,
|
||||
lower=_number(cells, at.get(f"LL95.{year}"), where),
|
||||
upper=_number(cells, at.get(f"UL95.{year}"), where),
|
||||
confidence_level=0.95 if f"LL95.{year}" in at else None,
|
||||
) for year in horizons] # fmt: skip
|
||||
yield {"file": file, "sheet": sheet, "row": number,
|
||||
"variables": {name: cells[at[name]] for name in ("hpv", "pap")},
|
||||
"estimates": estimates} # fmt: skip
|
||||
|
||||
|
||||
def read_workbook(path: Path) -> list[dict]:
|
||||
"""Every published row of a workbook, in order, with its file, sheet and row."""
|
||||
if path.name not in UNITS:
|
||||
raise ValueError(f"{path.name}: its unit has not been verified")
|
||||
found = []
|
||||
for sheet, rows in _sheets(path):
|
||||
reader = _long if "disease" in rows[0][1].values() else _wide
|
||||
found += reader(path.name, sheet, rows)
|
||||
return found
|
||||
@@ -0,0 +1,110 @@
|
||||
{% macro cacu_prior_outcome(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
|
||||
and e.date <= {{ as_of() }} and e.date < {{ cohort }}.index_date
|
||||
and e.value_code in {{ sql_list(var('cacu').cin2_plus) }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_no_index_result(cohort) -%}
|
||||
not exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id
|
||||
and e.type in ('bethesda', 'glandular', 'hpv') and e.value_code is not null
|
||||
and e.source_table = {{ cohort }}.source_table
|
||||
and e.source_id = {{ cohort }}.source_id and e.date <= {{ as_of() }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_unreported_biopsy(cohort) -%}
|
||||
{{ cohort }}.unreported > 0
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_outcome_by_index(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
|
||||
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
|
||||
and e.value_code in {{ sql_list(var('cacu').cin2_plus) }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_cancer_history(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'history'
|
||||
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_prior_treatment(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'treatment'
|
||||
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_no_referral(cohort) -%}
|
||||
not exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id
|
||||
and e.type in ('bethesda', 'glandular', 'hpv') and e.value_code is not null
|
||||
and e.date <= {{ as_of() }}
|
||||
and e.date <= {{ cohort }}.colposcopy_date
|
||||
and {{ days_between('e.date', cohort ~ '.colposcopy_date') }}
|
||||
<= {{ var('cacu').referral_lookback_days }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_no_cotest(cohort) -%}
|
||||
(not exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'hpv'
|
||||
and e.value_code is not null and e.source_table = {{ cohort }}.source_table
|
||||
and e.source_id = {{ cohort }}.source_id and e.date <= {{ as_of() }}
|
||||
) or not exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type in ('bethesda', 'glandular')
|
||||
and e.value_code is not null and e.source_table = {{ cohort }}.source_table
|
||||
and e.source_id = {{ cohort }}.source_id and e.date <= {{ as_of() }}
|
||||
))
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_no_pretreatment_biopsy(cohort) -%}
|
||||
not exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
|
||||
and e.value_code is not null and e.date <= {{ cohort }}.treatment_date
|
||||
and e.date <= {{ as_of() }}
|
||||
and {{ days_between('e.date', cohort ~ '.treatment_date') }}
|
||||
<= {{ var('cacu').post_treatment_lookback_days }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_outcome_before_index(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'biopsy'
|
||||
and e.date > {{ cohort }}.treatment_date and e.date < {{ cohort }}.index_date
|
||||
and e.date <= {{ as_of() }}
|
||||
and e.value_code in {{ sql_list(var('cacu').cin2_plus) }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_no_birth_date(cohort) -%}
|
||||
not exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'birth'
|
||||
and e.date <= {{ as_of() }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_died_by_index(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as e
|
||||
where e.person_id = {{ cohort }}.person_id and e.type = 'death'
|
||||
and e.date <= {{ cohort }}.index_date and e.date <= {{ as_of() }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,42 @@
|
||||
{% macro cacu_hysterectomy_exam(event) -%}
|
||||
{{ event }}.type = 'gynecologic_condition'
|
||||
and {{ event }}.value_code = 'hysterectomy'
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_hysterectomy_by_index(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as exam
|
||||
where exam.person_id = {{ cohort }}.person_id
|
||||
and exam.evidence_date < {{ cohort }}.index_date
|
||||
and {{ cacu_available_by_index('exam', cohort ~ '.index_date') }}
|
||||
and {{ cacu_hysterectomy_exam('exam') }}
|
||||
)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_available_by_index(evidence, index_date) -%}
|
||||
{{ return(adapter.dispatch('cacu_available_by_index', 'isssteleon')(evidence, index_date)) }}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro default__cacu_available_by_index(evidence, index_date) -%}
|
||||
substr(cast({{ evidence }}.source_available_at as {{ dbt.type_string() }}), 1, 10)
|
||||
<= substr(cast({{ index_date }} as {{ dbt.type_string() }}), 1, 10)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro sqlserver__cacu_available_by_index(evidence, index_date) -%}
|
||||
substring(cast({{ evidence }}.source_available_at as {{ dbt.type_string() }}), 1, 10)
|
||||
<= substring(cast({{ index_date }} as {{ dbt.type_string() }}), 1, 10)
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_common_exclusion_cases(cohort) -%}
|
||||
when {{ cacu_hysterectomy_by_index(cohort) }} then 'hysterectomy'
|
||||
when {{ cacu_under_18_by_index(cohort) }} then 'under_18'
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro cacu_under_18_by_index(cohort) -%}
|
||||
exists (
|
||||
select 1 from {{ ref('cacu_events') }} as birth
|
||||
where birth.person_id = {{ cohort }}.person_id and birth.type = 'birth'
|
||||
and birth.date <= {{ cohort }}.index_date
|
||||
and {{ age_years('birth.date', cohort ~ '.index_date') }} < 18
|
||||
)
|
||||
{%- endmacro %}
|
||||
@@ -0,0 +1,100 @@
|
||||
{% macro cacu_post_colposcopy_index(visit, require_biopsy_report=true) %}
|
||||
{% set p = var('cacu') %}
|
||||
with known as (
|
||||
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
|
||||
),
|
||||
|
||||
colposcopies as (
|
||||
select
|
||||
person_id, date,
|
||||
row_number() over (partition by person_id order by date, source_table, source_id) as n
|
||||
from known
|
||||
where type = 'colposcopy'
|
||||
),
|
||||
|
||||
first_colposcopy as (
|
||||
select person_id, date as colposcopy_date from colposcopies where n = 1
|
||||
),
|
||||
|
||||
orders as (
|
||||
select distinct o.person_id, o.source_table, o.source_id
|
||||
from known as o
|
||||
join first_colposcopy as f on f.person_id = o.person_id and o.date = f.colposcopy_date
|
||||
where o.type = 'biopsy_order'
|
||||
),
|
||||
|
||||
reports as (
|
||||
select r.person_id, r.date, r.source_table, r.source_id
|
||||
from known as r
|
||||
join orders as o
|
||||
on o.person_id = r.person_id and o.source_table = r.source_table and o.source_id = r.source_id
|
||||
where r.type = 'biopsy'
|
||||
),
|
||||
|
||||
episode as (
|
||||
select
|
||||
f.person_id,
|
||||
f.colposcopy_date,
|
||||
coalesce((select max(r.date) from reports as r where r.person_id = f.person_id),
|
||||
f.colposcopy_date) as result_date
|
||||
{% if require_biopsy_report %}
|
||||
, (select count(*) from orders as o
|
||||
where o.person_id = f.person_id and not exists (
|
||||
select 1 from reports as r
|
||||
where r.person_id = o.person_id and r.source_table = o.source_table
|
||||
and r.source_id = o.source_id)) as unreported
|
||||
{% endif %}
|
||||
from first_colposcopy as f
|
||||
),
|
||||
|
||||
closed as (
|
||||
select
|
||||
ep.*,
|
||||
(select min(c.date) from known as c
|
||||
where c.person_id = ep.person_id and c.type = 'colposcopy'
|
||||
and c.date > ep.result_date) as closing_date
|
||||
from episode as ep
|
||||
),
|
||||
|
||||
visits as (
|
||||
select
|
||||
s.person_id, s.date, s.source_table, s.source_id,
|
||||
row_number() over (partition by s.person_id order by s.date, s.source_id) as n
|
||||
from known as s
|
||||
join closed as ep on ep.person_id = s.person_id
|
||||
where s.type = 'cytology' and s.date > ep.result_date
|
||||
and (ep.closing_date is null or s.date < ep.closing_date)
|
||||
),
|
||||
|
||||
indexed as (
|
||||
select ep.*, v.date as index_date, v.source_table, v.source_id,
|
||||
prior.date as previous_date, prior.source_table as previous_source_table,
|
||||
prior.source_id as previous_source_id
|
||||
from closed as ep
|
||||
join visits as v on v.person_id = ep.person_id and v.n = {{ visit }}
|
||||
left join visits as prior on prior.person_id = v.person_id and prior.n = v.n - 1
|
||||
where v.date >= '{{ p.recruitment[0] }}' and v.date < '{{ p.recruitment[1] }}'
|
||||
)
|
||||
|
||||
select
|
||||
i.person_id,
|
||||
'post_colposcopy' as scenario,
|
||||
i.index_date,
|
||||
i.source_table, i.source_id,
|
||||
i.previous_date, i.previous_source_table, i.previous_source_id,
|
||||
i.source_table as index_source_table, i.source_id as index_source_id,
|
||||
i.colposcopy_date,
|
||||
{% if require_biopsy_report %}i.unreported{% else %}0{% endif %} as unreported,
|
||||
case
|
||||
{{ cacu_common_exclusion_cases('i') }}
|
||||
{% if require_biopsy_report %}
|
||||
when {{ cacu_unreported_biopsy('i') }} then 'unreported_biopsy'
|
||||
{% endif %}
|
||||
when {{ cacu_outcome_by_index('i') }} then 'outcome_by_index'
|
||||
when {{ cacu_cancer_history('i') }} then 'cancer_history'
|
||||
when {{ cacu_prior_treatment('i') }} then 'prior_treatment'
|
||||
when {{ cacu_no_referral('i') }} then 'no_referral'
|
||||
when {{ cacu_no_cotest('i') }} then 'no_cotest'
|
||||
end as excluded_by
|
||||
from indexed as i
|
||||
{% endmacro %}
|
||||
@@ -0,0 +1,46 @@
|
||||
{% macro cacu_surveillance_index(visit=1, before_referral=false) %}
|
||||
{% set p = var('cacu') %}
|
||||
with known as (
|
||||
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
|
||||
),
|
||||
|
||||
samples as (
|
||||
select
|
||||
person_id, date, source_table, source_id,
|
||||
row_number() over (partition by person_id order by date, source_id) as n
|
||||
from known as s
|
||||
where type = 'cytology'
|
||||
{% if before_referral %}
|
||||
and not exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = s.person_id and e.type in ('colposcopy', 'biopsy')
|
||||
and e.date <= s.date
|
||||
)
|
||||
{% endif %}
|
||||
),
|
||||
|
||||
indexed as (
|
||||
select v.person_id, v.date as index_date, v.source_table, v.source_id,
|
||||
prior.date as previous_date, prior.source_table as previous_source_table,
|
||||
prior.source_id as previous_source_id
|
||||
from samples as v
|
||||
left join samples as prior on prior.person_id = v.person_id and prior.n = v.n - 1
|
||||
where v.n = {{ visit }}
|
||||
and v.date >= '{{ p.recruitment[0] }}' and v.date < '{{ p.recruitment[1] }}'
|
||||
)
|
||||
|
||||
select
|
||||
i.person_id,
|
||||
'{{ "pre_colposcopy" if before_referral else "surveillance" }}' as scenario,
|
||||
i.index_date,
|
||||
i.source_table, i.source_id,
|
||||
i.previous_date, i.previous_source_table, i.previous_source_id,
|
||||
i.source_table as index_source_table, i.source_id as index_source_id,
|
||||
cast(null as date) as colposcopy_date, cast(0 as integer) as unreported,
|
||||
case
|
||||
{{ cacu_common_exclusion_cases('i') }}
|
||||
when {{ cacu_prior_outcome('i') }} then 'prior_outcome'
|
||||
when {{ cacu_no_index_result('i') }} then 'no_index_result'
|
||||
end as excluded_by
|
||||
from indexed as i
|
||||
{% endmacro %}
|
||||
@@ -15,3 +15,12 @@
|
||||
{% macro as_of() -%}
|
||||
'{{ var("as_of", run_started_at.strftime("%Y-%m-%d")) }}'
|
||||
{%- endmacro %}
|
||||
|
||||
{# Completed years on a date; the ISO month and day determine whether the birthday has passed. #}
|
||||
{% macro age_years(birth, on_date) -%}
|
||||
(cast(substr(cast({{ on_date }} as {{ dbt.type_string() }}), 1, 4) as integer)
|
||||
- cast(substr(cast({{ birth }} as {{ dbt.type_string() }}), 1, 4) as integer)
|
||||
- case when substr(cast({{ on_date }} as {{ dbt.type_string() }}), 6, 5)
|
||||
< substr(cast({{ birth }} as {{ dbt.type_string() }}), 6, 5)
|
||||
then 1 else 0 end)
|
||||
{%- endmacro %}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
end exclusive), up to the as-of date. Out (`excluded_by`): no birth date (no age at the
|
||||
index), a death on or before the index.
|
||||
#}
|
||||
{% macro first_biopsy_cohort(events, grades, recruitment) %}
|
||||
{% macro first_biopsy_cohort(events, grades, recruitment, cacu_rules=false) %}
|
||||
with timeline as (
|
||||
select * from {{ ref(events) }} where date <= {{ as_of() }}
|
||||
),
|
||||
@@ -27,8 +27,13 @@ death as (
|
||||
select
|
||||
i.person_id, i.index_date,
|
||||
case
|
||||
{% if cacu_rules %}
|
||||
when {{ cacu_no_birth_date('i') }} then 'no_birth_date'
|
||||
when {{ cacu_died_by_index('i') }} then 'died_by_index'
|
||||
{% else %}
|
||||
when b.person_id is null then 'no_birth_date'
|
||||
when d.date <= i.index_date then 'died_by_index'
|
||||
{% endif %}
|
||||
end as excluded_by
|
||||
from indexed as i
|
||||
left join birth as b on b.person_id = i.person_id
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
One study, wide: one row per study instance (person and the study's key), one column per
|
||||
field of the catalog (core.catalog), from the long `silver.observation`. `known_at` is when
|
||||
anything of the instance was first known, `<event>_known_at` when its event was (a report can
|
||||
arrive loads after its sample). A subquery, for
|
||||
arrive loads after its sample). Opt-in `timestamped_fields` expose source dates,
|
||||
reference and ingestion time of the specific value. A subquery, for
|
||||
`from {{ pivot('cervical_cytology') }} as c`, or a whole model.
|
||||
#}
|
||||
{% macro pivot(study) -%}
|
||||
{% macro pivot(study, timestamped_fields=[]) -%}
|
||||
{%- set s = var('catalog')[study] -%}
|
||||
(
|
||||
select
|
||||
@@ -25,6 +26,12 @@
|
||||
{%- set mine = s.fields | dictsort | selectattr('1.event', 'equalto', event) | map('first') | list %}
|
||||
min(case when field in {{ sql_list(mine) }} then known_at end) as {{ event }}_known_at,
|
||||
{%- endfor %}
|
||||
{%- for field in timestamped_fields %}
|
||||
min(case when field = '{{ field }}' then field_known_at end) as {{ field }}_known_at,
|
||||
{%- for column in ['source_clinical_date', 'source_available_at', 'source_ref'] %}
|
||||
max(case when field = '{{ field }}' then {{ column }} end) as {{ field }}_{{ column }},
|
||||
{%- endfor %}
|
||||
{%- endfor %}
|
||||
max(rows_merged) as rows_merged
|
||||
from {{ ref('observation') }}
|
||||
where study = '{{ study }}'
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
version: 2
|
||||
|
||||
models:
|
||||
- name: cacu_eligibility
|
||||
description: >-
|
||||
One row per indexed candidate and detected exclusion criterion. Eligible candidates
|
||||
have a null criterion; multiple common criteria produce multiple rows.
|
||||
columns:
|
||||
- name: scenario
|
||||
description: Cohort scenario at the indexed visit.
|
||||
- name: person_id
|
||||
description: Stable patient identifier.
|
||||
- name: index_date
|
||||
description: Clinical date used as the visit cutoff.
|
||||
- name: index_sample_id
|
||||
description: Sample key when the candidate is based on a visit feature row.
|
||||
- name: criterion
|
||||
description: Exclusion criterion; null means the candidate is eligible.
|
||||
- name: eligible
|
||||
description: Whether the candidate has no detected exclusion criteria.
|
||||
- name: cacu_follow_up
|
||||
columns:
|
||||
- name: person_id
|
||||
|
||||
@@ -9,116 +9,8 @@
|
||||
cytology or HPV result in the REFERRAL_LOOKBACK_DAYS before the colposcopy (no_referral);
|
||||
an index sample without both a cytology and an HPV result (no_cotest).
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
with known as (
|
||||
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
|
||||
),
|
||||
|
||||
colposcopies as (
|
||||
select
|
||||
person_id, date,
|
||||
row_number() over (partition by person_id order by date, source_table, source_id) as n
|
||||
from known
|
||||
where type = 'colposcopy'
|
||||
),
|
||||
|
||||
first_colposcopy as (
|
||||
select person_id, date as colposcopy_date from colposcopies where n = 1
|
||||
),
|
||||
|
||||
orders as (
|
||||
select distinct o.person_id, o.source_table, o.source_id
|
||||
from known as o
|
||||
join first_colposcopy as f on f.person_id = o.person_id and o.date = f.colposcopy_date
|
||||
where o.type = 'biopsy_order'
|
||||
),
|
||||
|
||||
reports as (
|
||||
select r.person_id, r.date, r.source_table, r.source_id
|
||||
from known as r
|
||||
join orders as o
|
||||
on o.person_id = r.person_id and o.source_table = r.source_table and o.source_id = r.source_id
|
||||
where r.type = 'biopsy'
|
||||
),
|
||||
|
||||
episode as (
|
||||
select
|
||||
f.person_id,
|
||||
f.colposcopy_date,
|
||||
coalesce((select max(r.date) from reports as r where r.person_id = f.person_id),
|
||||
f.colposcopy_date) as result_date,
|
||||
(select count(*) from orders as o
|
||||
where o.person_id = f.person_id and not exists (
|
||||
select 1 from reports as r
|
||||
where r.person_id = o.person_id and r.source_table = o.source_table
|
||||
and r.source_id = o.source_id)) as unreported
|
||||
from first_colposcopy as f
|
||||
),
|
||||
|
||||
closed as (
|
||||
select
|
||||
ep.*,
|
||||
(select min(c.date) from known as c
|
||||
where c.person_id = ep.person_id and c.type = 'colposcopy'
|
||||
and c.date > ep.result_date) as closing_date
|
||||
from episode as ep
|
||||
),
|
||||
|
||||
visits as (
|
||||
select
|
||||
s.person_id, s.date, s.source_table, s.source_id,
|
||||
row_number() over (partition by s.person_id order by s.date, s.source_id) as n
|
||||
from known as s
|
||||
join closed as ep on ep.person_id = s.person_id
|
||||
where s.type = 'cytology' and s.date > ep.result_date
|
||||
and (ep.closing_date is null or s.date < ep.closing_date)
|
||||
),
|
||||
|
||||
indexed as (
|
||||
select ep.*, v.date as index_date, v.source_table, v.source_id
|
||||
from closed as ep
|
||||
join visits as v on v.person_id = ep.person_id and v.n = {{ p.post_colposcopy_visit }}
|
||||
where v.date >= '{{ p.recruitment[0] }}' and v.date < '{{ p.recruitment[1] }}'
|
||||
)
|
||||
|
||||
select
|
||||
i.person_id,
|
||||
i.index_date,
|
||||
case
|
||||
when i.unreported > 0 then 'unreported_biopsy'
|
||||
when exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'biopsy' and e.date <= i.index_date
|
||||
and e.value_code in {{ sql_list(p.cin2_plus) }}
|
||||
) then 'outcome_by_index'
|
||||
when exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'history' and e.date <= i.index_date
|
||||
) then 'cancer_history'
|
||||
when exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'note' and e.date <= i.index_date
|
||||
and e.value_code in {{ sql_list(p.hysterectomy_icd10) }}
|
||||
) then 'hysterectomy'
|
||||
when exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'treatment' and e.date <= i.index_date
|
||||
) then 'prior_treatment'
|
||||
when not exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular', 'hpv')
|
||||
and e.value_code is not null and e.date <= i.colposcopy_date
|
||||
and {{ days_between('e.date', 'i.colposcopy_date') }} <= {{ p.referral_lookback_days }}
|
||||
) then 'no_referral'
|
||||
when not exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'hpv' and e.value_code is not null
|
||||
and e.source_table = i.source_table and e.source_id = i.source_id
|
||||
) or not exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular')
|
||||
and e.value_code is not null
|
||||
and e.source_table = i.source_table and e.source_id = i.source_id
|
||||
) then 'no_cotest'
|
||||
end as excluded_by
|
||||
from indexed as i
|
||||
select person_id, index_date, index_source_table, index_source_id, colposcopy_date,
|
||||
unreported, excluded_by
|
||||
from (
|
||||
{{ cacu_post_colposcopy_index(var('cacu').post_colposcopy_visit) }}
|
||||
) as cohort
|
||||
|
||||
@@ -36,24 +36,13 @@ indexed as (
|
||||
select
|
||||
i.person_id,
|
||||
i.index_date,
|
||||
i.source_table as index_source_table,
|
||||
i.source_id as index_source_id,
|
||||
i.treatment_date,
|
||||
case
|
||||
when not exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'biopsy' and e.value_code is not null
|
||||
and e.date <= i.treatment_date
|
||||
and {{ days_between('e.date', 'i.treatment_date') }} <= {{ p.post_treatment_lookback_days }}
|
||||
) then 'no_pretreatment_biopsy'
|
||||
when exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'biopsy'
|
||||
and e.date > i.treatment_date and e.date < i.index_date
|
||||
and e.value_code in {{ sql_list(p.cin2_plus) }}
|
||||
) then 'outcome_before_index'
|
||||
when not exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular', 'hpv')
|
||||
and e.source_table = i.source_table and e.source_id = i.source_id
|
||||
and e.value_code is not null
|
||||
) then 'no_index_result'
|
||||
{{ cacu_common_exclusion_cases('i') }}
|
||||
when {{ cacu_no_pretreatment_biopsy('i') }} then 'no_pretreatment_biopsy'
|
||||
when {{ cacu_outcome_before_index('i') }} then 'outcome_before_index'
|
||||
when {{ cacu_no_index_result('i') }} then 'no_index_result'
|
||||
end as excluded_by
|
||||
from indexed as i
|
||||
|
||||
@@ -3,39 +3,8 @@
|
||||
the recruitment window. Out, in order: an outcome biopsy (CIN2+) before the index
|
||||
(prior_outcome); an index sample with no cytology or HPV result (no_index_result).
|
||||
#}
|
||||
{% set p = var('cacu') %}
|
||||
with known as (
|
||||
select * from {{ ref('cacu_events') }} where date <= {{ as_of() }}
|
||||
),
|
||||
|
||||
samples as (
|
||||
select
|
||||
person_id, date, source_table, source_id,
|
||||
row_number() over (partition by person_id order by date, source_id) as n
|
||||
from known
|
||||
where type = 'cytology'
|
||||
),
|
||||
|
||||
indexed as (
|
||||
select person_id, date as index_date, source_table, source_id
|
||||
from samples
|
||||
where n = 1 and date >= '{{ p.recruitment[0] }}' and date < '{{ p.recruitment[1] }}'
|
||||
)
|
||||
|
||||
select
|
||||
i.person_id,
|
||||
i.index_date,
|
||||
case
|
||||
when exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type = 'biopsy' and e.date < i.index_date
|
||||
and e.value_code in {{ sql_list(p.cin2_plus) }}
|
||||
) then 'prior_outcome'
|
||||
when not exists (
|
||||
select 1 from known as e
|
||||
where e.person_id = i.person_id and e.type in ('bethesda', 'glandular', 'hpv')
|
||||
and e.source_table = i.source_table and e.source_id = i.source_id
|
||||
and e.value_code is not null
|
||||
) then 'no_index_result'
|
||||
end as excluded_by
|
||||
from indexed as i
|
||||
select person_id, index_date, source_table as index_source_table,
|
||||
source_id as index_source_id, excluded_by
|
||||
from (
|
||||
{{ cacu_surveillance_index() }}
|
||||
) as cohort
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
{# Survival: indexed at the first biopsy reported as carcinoma or carcinoma in situ (core.cacu CASE). #}
|
||||
{% set p = var('cacu') %}
|
||||
{{ first_biopsy_cohort('cacu_events', p.case, p.recruitment) }}
|
||||
select i.person_id, i.index_date,
|
||||
case {{ cacu_common_exclusion_cases('i') }}
|
||||
else i.excluded_by end as excluded_by
|
||||
from (
|
||||
{{ first_biopsy_cohort('cacu_events', p.case, p.recruitment, cacu_rules=true) }}
|
||||
) as i
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
{# One row per indexed candidate and every applicable exclusion criterion. #}
|
||||
with candidates as (
|
||||
select 'surveillance' as scenario, person_id, index_date,
|
||||
cast(null as {{ dbt.type_string() }}) as index_sample_id,
|
||||
index_source_table as source_table, index_source_id as source_id,
|
||||
cast(null as date) as colposcopy_date, cast(null as date) as treatment_date,
|
||||
cast(0 as integer) as unreported
|
||||
from {{ ref('cacu_cohort_surveillance') }}
|
||||
|
||||
union all
|
||||
select 'pre_colposcopy', person_id, index_date, index_sample_id,
|
||||
'cervical_cytology', index_sample_id,
|
||||
colposcopy_date, cast(null as date), cast(0 as integer)
|
||||
from {{ ref('cacu_second_visit_features') }} where scenario = 'pre_colposcopy'
|
||||
|
||||
union all
|
||||
select 'post_colposcopy', person_id, index_date,
|
||||
index_source_id, index_source_table, index_source_id,
|
||||
colposcopy_date, cast(null as date), unreported
|
||||
from {{ ref('cacu_cohort_post_colposcopy') }}
|
||||
|
||||
union all
|
||||
select 'post_colposcopy_second_visit', person_id, index_date, index_sample_id,
|
||||
'cervical_cytology', index_sample_id,
|
||||
colposcopy_date, cast(null as date), cast(0 as integer)
|
||||
from {{ ref('cacu_second_visit_features') }} where scenario = 'post_colposcopy'
|
||||
|
||||
union all
|
||||
select 'post_treatment', person_id, index_date,
|
||||
index_source_id, index_source_table, index_source_id,
|
||||
cast(null as date), treatment_date, cast(0 as integer)
|
||||
from {{ ref('cacu_cohort_post_treatment') }}
|
||||
|
||||
union all
|
||||
select 'survival', person_id, index_date,
|
||||
cast(null as {{ dbt.type_string() }}), cast(null as {{ dbt.type_string() }}),
|
||||
cast(null as {{ dbt.type_string() }}), cast(null as date), cast(null as date),
|
||||
cast(0 as integer)
|
||||
from {{ ref('cacu_cohort_survival') }}
|
||||
),
|
||||
|
||||
reasons as (
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'hysterectomy' as criterion
|
||||
from candidates as c where {{ cacu_hysterectomy_by_index('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'under_18'
|
||||
from candidates as c where {{ cacu_under_18_by_index('c') }}
|
||||
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'prior_outcome'
|
||||
from candidates as c
|
||||
where c.scenario in ('surveillance', 'pre_colposcopy')
|
||||
and {{ cacu_prior_outcome('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_index_result'
|
||||
from candidates as c
|
||||
where c.scenario in ('surveillance', 'pre_colposcopy', 'post_treatment')
|
||||
and {{ cacu_no_index_result('c') }}
|
||||
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'unreported_biopsy'
|
||||
from candidates as c
|
||||
where c.scenario = 'post_colposcopy' and {{ cacu_unreported_biopsy('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'outcome_by_index'
|
||||
from candidates as c
|
||||
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
|
||||
and {{ cacu_outcome_by_index('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'cancer_history'
|
||||
from candidates as c
|
||||
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
|
||||
and {{ cacu_cancer_history('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'prior_treatment'
|
||||
from candidates as c
|
||||
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
|
||||
and {{ cacu_prior_treatment('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_referral'
|
||||
from candidates as c
|
||||
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
|
||||
and {{ cacu_no_referral('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_cotest'
|
||||
from candidates as c
|
||||
where c.scenario in ('post_colposcopy', 'post_colposcopy_second_visit')
|
||||
and {{ cacu_no_cotest('c') }}
|
||||
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_pretreatment_biopsy'
|
||||
from candidates as c
|
||||
where c.scenario = 'post_treatment' and {{ cacu_no_pretreatment_biopsy('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'outcome_before_index'
|
||||
from candidates as c
|
||||
where c.scenario = 'post_treatment' and {{ cacu_outcome_before_index('c') }}
|
||||
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'no_birth_date'
|
||||
from candidates as c where c.scenario = 'survival' and {{ cacu_no_birth_date('c') }}
|
||||
union all
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, 'died_by_index'
|
||||
from candidates as c where c.scenario = 'survival' and {{ cacu_died_by_index('c') }}
|
||||
),
|
||||
|
||||
distinct_reasons as (
|
||||
select distinct scenario, person_id, index_date, index_sample_id, criterion from reasons
|
||||
)
|
||||
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id, r.criterion,
|
||||
false as eligible
|
||||
from candidates as c
|
||||
join distinct_reasons as r
|
||||
on r.scenario = c.scenario and r.person_id = c.person_id and r.index_date = c.index_date
|
||||
and (r.index_sample_id = c.index_sample_id or
|
||||
(r.index_sample_id is null and c.index_sample_id is null))
|
||||
|
||||
union all
|
||||
|
||||
select c.scenario, c.person_id, c.index_date, c.index_sample_id,
|
||||
cast(null as {{ dbt.type_string() }}) as criterion, true as eligible
|
||||
from candidates as c
|
||||
where not exists (
|
||||
select 1 from distinct_reasons as r
|
||||
where r.scenario = c.scenario and r.person_id = c.person_id and r.index_date = c.index_date
|
||||
and (r.index_sample_id = c.index_sample_id or
|
||||
(r.index_sample_id is null and c.index_sample_id is null))
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
{# Independent evidence uses the timeline's columns for candidate eligibility queries. #}
|
||||
select person_id, evidence_date as date, evidence_code_known_at as known_at,
|
||||
evidence_type as type,
|
||||
case when evidence_type = 'condition' then replace(evidence_code, '.', '')
|
||||
else evidence_code end as value_code,
|
||||
cast(null as {{ dbt.type_float() }}) as value_num,
|
||||
'cacu_eligibility_evidence' as source_table, evidence_id as source_id,
|
||||
evidence_date, evidence_code_source_available_at as source_available_at,
|
||||
evidence_code_source_ref as source_ref
|
||||
from {{ pivot('cacu_eligibility_evidence', timestamped_fields=['evidence_code']) }} as evidence
|
||||
@@ -3,6 +3,8 @@
|
||||
dated when they were reported; a cytology's results and a biopsy's order and report share
|
||||
their source (`source_table`, `source_id`), so a model can tell which sample a result
|
||||
belongs to.
|
||||
For eligibility inputs, `evidence_date` and `source_available_at` preserve the source's
|
||||
clinical and documentation times. `known_at` remains a platform ingestion timestamp.
|
||||
|
||||
Procedures silver has no record of are inferred from notes and biopsies (core.cacu):
|
||||
- diagnosis: a note with a diagnosis ICD-10 by a diagnosing specialty;
|
||||
@@ -25,7 +27,8 @@ biopsy as (
|
||||
|
||||
note as (
|
||||
select
|
||||
person_id, note_date, specialty, known_at,
|
||||
person_id, note_date, specialty, known_at, icd10_known_at, icd10_source_clinical_date,
|
||||
icd10_source_available_at, icd10_source_ref,
|
||||
replace(icd10, '.', '') as icd10,
|
||||
{{ plain_upper('reason') }} as reason,
|
||||
{{ plain_upper('diagnosis_text') }} as diagnosis_text,
|
||||
@@ -96,6 +99,16 @@ events as (
|
||||
select person_id, sample_date, known_at, 'cytology', adequacy, null,
|
||||
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
|
||||
from cytology
|
||||
{% for field, availability in [
|
||||
('gynecologic_condition', 'gynecologic_condition_known_at'),
|
||||
('presenting_symptom', 'sample_known_at'),
|
||||
('cervix_appearance', 'sample_known_at')
|
||||
] %}
|
||||
union all
|
||||
select person_id, sample_date, {{ availability }}, '{{ field }}', {{ field }}, null,
|
||||
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
|
||||
from cytology where {{ field }} is not null
|
||||
{% endfor %}
|
||||
union all
|
||||
select person_id, report_date, known_at, 'bethesda', result, null,
|
||||
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
|
||||
@@ -105,6 +118,13 @@ events as (
|
||||
case when hpv then 'positive' else 'negative' end, null,
|
||||
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
|
||||
from cytology where hpv is not null and report_date is not null
|
||||
{% for genotype in p.hpv_genotype_fields %}
|
||||
union all
|
||||
select person_id, report_date, report_known_at, '{{ genotype }}',
|
||||
case when {{ genotype }} then 'positive' else 'negative' end, null,
|
||||
'cervical_cytology', cast(sample_date as {{ dbt.type_string() }})
|
||||
from cytology where {{ genotype }} is not null and report_date is not null
|
||||
{% endfor %}
|
||||
union all
|
||||
select person_id, report_date, known_at, 'hpv_16_18', null,
|
||||
case when hpv_16 or hpv_18 then 1.0 else 0.0 end,
|
||||
@@ -121,9 +141,14 @@ events as (
|
||||
from biopsy where histology is not null and report_date is not null
|
||||
|
||||
union all
|
||||
select person_id, note_date, known_at, 'note', icd10, null, 'clinical_note', source_id
|
||||
select person_id, note_date, case when icd10 is null then known_at else icd10_known_at end,
|
||||
'note', icd10, null, 'clinical_note', source_id
|
||||
from note
|
||||
union all
|
||||
select person_id, note_date, icd10_known_at, 'gynecologic_condition', 'hysterectomy', null,
|
||||
'clinical_note', source_id
|
||||
from note where icd10 in {{ sql_list(p.hysterectomy_icd10) }}
|
||||
union all
|
||||
select person_id, note_date, known_at, 'diagnosis', null, null, 'clinical_note', source_id
|
||||
from diagnosis
|
||||
union all
|
||||
@@ -137,6 +162,52 @@ events as (
|
||||
union all
|
||||
select person_id, date, known_at, 'colposcopy', null, null, source_table, source_id
|
||||
from colposcopy
|
||||
),
|
||||
|
||||
source_dates as (
|
||||
{% for table, relation, procedure_day, columns in [
|
||||
('cervical_cytology', 'cytology', 'sample_date', [
|
||||
('gynecologic_condition', 'gynecologic_condition'), ('bethesda', 'result'),
|
||||
('hpv', 'hpv'), ('hpv_16', 'hpv_16'), ('hpv_18', 'hpv_18')
|
||||
]),
|
||||
('cervical_biopsy', 'biopsy', 'request_date', [('biopsy', 'histology')]),
|
||||
('clinical_note', 'note', none, [
|
||||
('note', 'icd10'), ('gynecologic_condition', 'icd10'), ('diagnosis', 'icd10'),
|
||||
('history', 'icd10'), ('treatment', 'icd10')
|
||||
])
|
||||
] %}
|
||||
{% for event, field in columns %}
|
||||
{% if not (loop.first and table == 'cervical_cytology') %}union all{% endif %}
|
||||
select person_id, '{{ table }}' as source_table,
|
||||
{% if procedure_day %}cast({{ procedure_day }} as {{ dbt.type_string() }})
|
||||
{% else %}source_id{% endif %} as source_id,
|
||||
'{{ event }}' as type, {{ field }}_source_clinical_date as evidence_date,
|
||||
{{ field }}_source_available_at as source_available_at, {{ field }}_source_ref as source_ref
|
||||
from {{ relation }} where {{ field }} is not null
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
)
|
||||
|
||||
select * from events where date is not null
|
||||
select e.*, coalesce(s.evidence_date, e.date) as evidence_date,
|
||||
s.source_available_at, s.source_ref
|
||||
from events as e
|
||||
left join source_dates as s
|
||||
on s.person_id = e.person_id and s.source_table = e.source_table
|
||||
and s.source_id = e.source_id and s.type = e.type
|
||||
where e.date is not null
|
||||
|
||||
union all
|
||||
|
||||
select person_id,
|
||||
date, known_at,
|
||||
case when (type = 'condition' and value_code in {{ sql_list(p.hysterectomy_icd10) }})
|
||||
or (type = 'gynecologic_condition' and value_code = 'hysterectomy')
|
||||
then 'gynecologic_condition'
|
||||
else type end as type,
|
||||
case when (type = 'condition' and value_code in {{ sql_list(p.hysterectomy_icd10) }})
|
||||
or (type = 'gynecologic_condition' and value_code = 'hysterectomy')
|
||||
then 'hysterectomy'
|
||||
else value_code end as value_code,
|
||||
value_num, source_table, source_id,
|
||||
evidence_date, source_available_at, source_ref
|
||||
from {{ ref('cacu_eligibility_evidence') }}
|
||||
|
||||
@@ -10,7 +10,8 @@ select
|
||||
then e.date end) as first_case,
|
||||
min(case when e.type = 'treatment' then e.date end) as first_treatment,
|
||||
min(case when e.type = 'colposcopy' then e.date end) as first_colposcopy,
|
||||
min(case when e.type = 'history' then e.date end) as first_history
|
||||
min(case when e.type = 'history' then e.date end) as first_history,
|
||||
min(case when {{ cacu_hysterectomy_exam('e') }} then e.date end) as first_hysterectomy
|
||||
from {{ ref('person') }} as p
|
||||
left join {{ ref('cacu_events') }} as e on e.person_id = p.person_id
|
||||
group by p.person_id
|
||||
|
||||
@@ -91,6 +91,7 @@ select
|
||||
then {{ days_between('rc.date', 'bx.date') }}
|
||||
end as days_colposcopy_biopsy,
|
||||
bd.date as biopsy_diagnosis_date,
|
||||
{{ days_between('s.sample_date', 'bd.date') }} as days_sample_biopsy_diagnosis,
|
||||
{{ days_between('bx.date', 'bd.date') }} as days_biopsy_diagnosis
|
||||
from sample as s
|
||||
left join {{ ref('cacu_follow_up') }} as f on f.person_id = s.person_id
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
{#
|
||||
One row per patient and scenario. Visit two is the index; visit one comes from
|
||||
the same scenario. Use only results from visit one reported by the index sample
|
||||
date. Visit two's results may arrive later, through the build's data cut-off.
|
||||
#}
|
||||
{% set fields = var('cacu').second_visit_fields %}
|
||||
{% set results = ['bethesda', 'glandular', 'hpv'] + var('cacu').hpv_genotype_fields %}
|
||||
|
||||
with pre as (
|
||||
{{ cacu_surveillance_index(visit=2, before_referral=true) }}
|
||||
),
|
||||
|
||||
post as (
|
||||
{{ cacu_post_colposcopy_index(visit=2, require_biopsy_report=false) }}
|
||||
),
|
||||
|
||||
candidates as (
|
||||
select * from pre
|
||||
union all
|
||||
select * from post
|
||||
),
|
||||
|
||||
visits as (
|
||||
select c.scenario, c.person_id, c.index_date, c.previous_date, c.source_table, c.source_id,
|
||||
c.previous_source_table, c.previous_source_id,
|
||||
c.colposcopy_date, c.excluded_by
|
||||
from candidates as c
|
||||
),
|
||||
|
||||
matched as (
|
||||
select v.person_id, v.scenario, v.index_date, v.previous_date, v.colposcopy_date,
|
||||
v.excluded_by,
|
||||
v.source_id as index_sample_id, v.previous_source_id as previous_sample_id,
|
||||
e.type, e.value_code, e.date,
|
||||
case when e.source_table = v.source_table and e.source_id = v.source_id
|
||||
then 'index' else 'previous' end as visit
|
||||
from visits as v
|
||||
left join {{ ref('cacu_events') }} as e
|
||||
on v.excluded_by is null and e.person_id = v.person_id
|
||||
and e.type in {{ sql_list(fields) }}
|
||||
and e.date <= {{ as_of() }}
|
||||
and ((e.source_table = v.source_table and e.source_id = v.source_id)
|
||||
or (e.source_table = v.previous_source_table and e.source_id = v.previous_source_id
|
||||
and e.date <= v.index_date))
|
||||
)
|
||||
|
||||
select person_id, scenario, index_date, index_sample_id, previous_date, previous_sample_id,
|
||||
colposcopy_date,
|
||||
{{ as_of() }} as data_cutoff, excluded_by,
|
||||
max(case when visit = 'index' and type in {{ sql_list(results) }} then date end)
|
||||
as index_result_date
|
||||
{% for visit in ['previous', 'index'] %}
|
||||
{% for field in fields %}
|
||||
, max(case when visit = '{{ visit }}' and type = '{{ field }}' then value_code end)
|
||||
as {{ visit }}_{{ field }}
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
from matched
|
||||
group by person_id, scenario, index_date, index_sample_id, previous_date, previous_sample_id,
|
||||
colposcopy_date, excluded_by
|
||||
@@ -1,11 +1,17 @@
|
||||
{#
|
||||
One row per mammogram and each reported biopsy it led to (one row with no biopsy when it led
|
||||
to none): what the measures that follow a mammogram to its biopsy count over.
|
||||
to none): what the measures that follow a mammogram to its biopsy count over. The biopsy is
|
||||
the one whose request names the mammogram (`cama_biopsies`); none is matched by dates.
|
||||
`days_report_biopsy`: days from the mammogram's report to the biopsy's report; empty when
|
||||
either date is missing, and when the biopsy was reported before the mammogram (inconsistent).
|
||||
#}
|
||||
select
|
||||
m.*,
|
||||
b.biopsy_id, b.report_date as biopsy_report_date, b.histology, b.histology_rank,
|
||||
b.report_known_at as biopsy_known_at
|
||||
b.report_known_at as biopsy_known_at,
|
||||
case
|
||||
when b.report_date >= m.report_date then {{ days_between('m.report_date', 'b.report_date') }}
|
||||
end as days_report_biopsy
|
||||
from {{ ref('cama_mammograms') }} as m
|
||||
left join {{ ref('cama_biopsies') }} as b
|
||||
on b.mammogram_id = m.mammogram_id and b.report_date is not null
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- cervical_biopsy, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('cervical_biopsy') }} as p
|
||||
select * from {{ pivot('cervical_biopsy', timestamped_fields=['histology']) }} as p
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- cervical_cytology, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('cervical_cytology') }} as p
|
||||
select * from {{ pivot('cervical_cytology', timestamped_fields=[
|
||||
'gynecologic_condition', 'result', 'hpv', 'hpv_16', 'hpv_18'
|
||||
]) }} as p
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{{ config(materialized='table') }}
|
||||
{#- clinical_note, wide (one row per instance): what gold and the API read. -#}
|
||||
select * from {{ pivot('clinical_note') }} as p
|
||||
select * from {{ pivot('clinical_note', timestamped_fields=['icd10']) }} as p
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
- rows of one instance are one record: values that complement each other are merged; a
|
||||
field with two different values is a conflict, and the whole instance stays out until a
|
||||
reviewer rejects the wrong row;
|
||||
- an instance is known from when its first row was (`known_at`).
|
||||
- an instance is known from when its first row was (`known_at`);
|
||||
- `field_known_at` is ingestion time. Source dates come from one accepted contributor.
|
||||
#}
|
||||
{%- if not staged_exists('staged__observation') %}
|
||||
select
|
||||
@@ -18,11 +19,22 @@ select
|
||||
cast(null as {{ dbt.type_boolean() }}) as value_bool,
|
||||
cast(null as date) as value_date,
|
||||
cast(null as {{ dbt.type_timestamp() }}) as known_at,
|
||||
cast(null as {{ dbt.type_timestamp() }}) as field_known_at,
|
||||
cast(null as date) as source_clinical_date,
|
||||
cast(null as {{ dbt.type_string() }}) as source_available_at,
|
||||
cast(null as {{ dbt.type_string() }}) as source_ref,
|
||||
0 as rows_merged
|
||||
where 1 = 0
|
||||
{%- else %}
|
||||
{% set source_metadata = [('source_clinical_date', 'date'),
|
||||
('source_available_at', dbt.type_string()),
|
||||
('source_ref', dbt.type_string())] %}
|
||||
with accepted as (
|
||||
select * from {{ source('bronze', 'staged__observation') }} as s
|
||||
select s.*
|
||||
{%- for column, kind in source_metadata if not staged_has_column('staged__observation', column) %}
|
||||
, cast(null as {{ kind }}) as {{ column }}
|
||||
{%- endfor %}
|
||||
from {{ source('bronze', 'staged__observation') }} as s
|
||||
where s.person_id is not null
|
||||
{%- if staged_exists('review_log') %}
|
||||
and not exists (
|
||||
@@ -32,12 +44,28 @@ with accepted as (
|
||||
{%- endif %}
|
||||
),
|
||||
|
||||
ranked_evidence as (
|
||||
select *, row_number() over (
|
||||
partition by person_id, study, instance, field
|
||||
order by case when source_available_at is null then 1 else 0 end,
|
||||
source_available_at,
|
||||
case when source_clinical_date is null then 1 else 0 end,
|
||||
source_clinical_date, _record, _index
|
||||
) as evidence_rank
|
||||
from accepted
|
||||
where value_text is not null or value_num is not null
|
||||
or value_date is not null or value_bool is not null
|
||||
),
|
||||
|
||||
cells as (
|
||||
select
|
||||
person_id, study, instance, field,
|
||||
max(value_text) as value_text, count(distinct value_text) as n_text,
|
||||
max(value_num) as value_num, count(distinct value_num) as n_num,
|
||||
max(value_date) as value_date, count(distinct value_date) as n_date,
|
||||
min(case when value_text is not null or value_num is not null
|
||||
or value_date is not null or value_bool is not null
|
||||
then known_at end) as field_known_at,
|
||||
max(case when value_bool then 1 else 0 end) as bool_any,
|
||||
min(case when value_bool then 1 else 0 end) as bool_all,
|
||||
count(value_bool) as n_bool
|
||||
@@ -64,10 +92,14 @@ select
|
||||
c.value_text, c.value_num,
|
||||
case when c.n_bool = 0 then null else c.bool_any = 1 end as value_bool,
|
||||
c.value_date,
|
||||
i.known_at, i.rows_merged
|
||||
i.known_at, c.field_known_at, i.rows_merged,
|
||||
e.source_clinical_date, e.source_available_at, e.source_ref
|
||||
from cells as c
|
||||
join instances as i
|
||||
on i.person_id = c.person_id and i.study = c.study and i.instance = c.instance
|
||||
left join ranked_evidence as e
|
||||
on e.person_id = c.person_id and e.study = c.study and e.instance = c.instance
|
||||
and e.field = c.field and e.evidence_rank = 1
|
||||
where not exists (
|
||||
select 1 from conflicted as x
|
||||
where x.person_id = c.person_id and x.study = c.study and x.instance = c.instance
|
||||
|
||||
@@ -15,7 +15,7 @@ PERSONS = """
|
||||
group by person_id) as d on d.person_id = p.person_id{join}
|
||||
"""
|
||||
CACU_PERSONS = PERSONS.format(
|
||||
extra=", f.first_case, f.first_treatment, f.first_colposcopy",
|
||||
extra=", f.first_case, f.first_treatment, f.first_colposcopy, f.first_hysterectomy",
|
||||
join=" left join gold.cacu_follow_up as f on f.person_id = p.person_id",
|
||||
)
|
||||
CAMA_PERSONS = PERSONS.format(extra="", join="")
|
||||
@@ -43,6 +43,12 @@ COMMON = {
|
||||
where person_id in :persons and date <= :cutoff and type in :types
|
||||
order by person_id, date, type
|
||||
""",
|
||||
# Biopsies and treatments, which say whether a model's risk still applies.
|
||||
"risk_history": """
|
||||
select person_id, date, type, value_code from gold.{domain}_events
|
||||
where person_id in :persons and type in ('biopsy', 'treatment')
|
||||
order by person_id, date
|
||||
""",
|
||||
"risk": """
|
||||
select model, version, person_id, index_date, horizon_years, probability, ci_low,
|
||||
ci_high, scenarios, scored_at
|
||||
@@ -67,7 +73,8 @@ READS = {
|
||||
order by w.recent desc, x.person_id
|
||||
""",
|
||||
# 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.
|
||||
# request, and its report) and her diagnosis, with the days to it, and what shows where
|
||||
# each stage comes from (core.cacu.stages).
|
||||
"route": """
|
||||
select s.person_id, s.sample_date,
|
||||
case when s.history = 0 and s.diagnosis_date <= :cutoff
|
||||
@@ -75,15 +82,51 @@ READS = {
|
||||
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
|
||||
b.requested, b.link, b.reported, b.backwards,
|
||||
case when exists (select 1 from gold.cacu_events as e
|
||||
where e.person_id = s.person_id and e.type = 'colposcopy'
|
||||
and e.date = s.colposcopy_date
|
||||
and e.source_table = 'clinical_note')
|
||||
then 1 else 0 end as colposcopy_note,
|
||||
case when exists (select 1 from gold.cacu_events as e
|
||||
where e.person_id = s.person_id and e.type = 'colposcopy'
|
||||
and e.date = s.colposcopy_date
|
||||
and e.source_table = 'cervical_biopsy')
|
||||
then 1 else 0 end as colposcopy_biopsy,
|
||||
case when exists (select 1 from gold.cacu_events as e
|
||||
where e.person_id = s.person_id and e.type = 'diagnosis'
|
||||
and e.date = s.diagnosis_date
|
||||
and e.source_table = 'clinical_note')
|
||||
then 1 else 0 end as diagnosis_note
|
||||
from gold.cacu_samples as s
|
||||
left join (select person_id, sample_date, min(date) as requested, min(link) as link
|
||||
left join (select person_id, sample_date, min(date) as requested, min(link) as link,
|
||||
min(case when report_date <= :cutoff then report_date end) as reported,
|
||||
max(case when report_date <= :cutoff and report_date < date
|
||||
then 1 else 0 end) as backwards
|
||||
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
|
||||
""",
|
||||
# What the NCI reference comparison reads of one patient (core.cacu.reference_risk): her
|
||||
# cytologies, her biopsies with the sample each one names, and her colposcopies and treatments.
|
||||
"reference_cytologies": """
|
||||
select person_id, sample_date, report_date, result, adequacy, hpv, hpv_16, hpv_18,
|
||||
gynecologic_condition
|
||||
from silver.cervical_cytology where person_id in :persons
|
||||
order by person_id, sample_date
|
||||
""",
|
||||
"reference_biopsies": """
|
||||
select person_id, request_date, report_date, histology, cytology_sample_date
|
||||
from silver.cervical_biopsy where person_id in :persons
|
||||
order by person_id, request_date
|
||||
""",
|
||||
"reference_events": """
|
||||
select distinct person_id, date, type from gold.cacu_events
|
||||
where person_id in :persons and type in ('colposcopy', 'treatment')
|
||||
order by person_id, date, type
|
||||
""",
|
||||
},
|
||||
"tea": {
|
||||
"person": TEA_PERSONS + " where p.person_id = :id",
|
||||
|
||||
@@ -1,15 +1,31 @@
|
||||
"""What the models read from gold, and the risk batches they write back."""
|
||||
|
||||
from collections.abc import Sequence
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
import dlt
|
||||
import pandas as pd
|
||||
from sqlalchemy import inspect, text
|
||||
|
||||
from core.cacu import SECOND_VISIT_FIELDS
|
||||
from persistance.destination import engine, platform
|
||||
|
||||
TIMELINE = ["person_id", "index_date", "date", "type", "value_code", "value_num",
|
||||
"source_table", "source_id", "record_number"] # fmt: skip
|
||||
SECOND_VISIT_KEYS = (
|
||||
"person_id", "scenario", "index_date", "index_sample_id", "previous_date",
|
||||
"previous_sample_id", "data_cutoff", "excluded_by", "index_result_date",
|
||||
) # fmt: skip
|
||||
SECOND_VISIT_PREDICTORS = tuple(
|
||||
f"{visit}_{field}" for visit in ("previous", "index") for field in SECOND_VISIT_FIELDS
|
||||
)
|
||||
CACU_ELIGIBILITY_COLUMNS = {
|
||||
"scenario", "person_id", "index_date", "index_sample_id", "criterion", "eligible"
|
||||
}
|
||||
|
||||
|
||||
class GoldSchemaError(RuntimeError):
|
||||
"""Gold has not been updated to the schema required by a CaCu reader."""
|
||||
|
||||
|
||||
def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFrame:
|
||||
@@ -32,6 +48,13 @@ def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFra
|
||||
return found.astype({"value_num": float})[TIMELINE]
|
||||
|
||||
|
||||
def people(events: str, as_of: date) -> int:
|
||||
"""How many people have any event in `gold.<events>` up to `as_of`."""
|
||||
sql = text(f"select count(distinct person_id) from gold.{events} where date <= :as_of")
|
||||
with engine().connect() as con:
|
||||
return con.execute(sql, {"as_of": as_of.isoformat()}).scalar_one()
|
||||
|
||||
|
||||
def person_numbers() -> dict[str, str]:
|
||||
"""Each person's record numbers as the link node compared them (for checks and reviews)."""
|
||||
sql = text("select distinct person_id, record_number from bronze.staged__identity "
|
||||
@@ -40,6 +63,77 @@ def person_numbers() -> dict[str, str]:
|
||||
return dict(con.execute(sql).fetchall())
|
||||
|
||||
|
||||
def cacu_second_visit_features(
|
||||
scenario: str,
|
||||
person_id: str | None = None,
|
||||
*,
|
||||
predictors: Sequence[str] | None = None,
|
||||
include_excluded: bool = False,
|
||||
) -> pd.DataFrame:
|
||||
"""Read the requested predictors plus row keys for a cohort or one candidate."""
|
||||
chosen = SECOND_VISIT_PREDICTORS if predictors is None else tuple(dict.fromkeys(predictors))
|
||||
unknown = set(chosen).difference(SECOND_VISIT_PREDICTORS)
|
||||
if unknown:
|
||||
raise ValueError(f"Unknown CaCu predictors: {', '.join(sorted(unknown))}")
|
||||
columns = ", ".join((*SECOND_VISIT_KEYS, *chosen))
|
||||
person_filter = "and person_id = :person_id" if person_id is not None else ""
|
||||
eligibility_filter = "" if include_excluded else "and excluded_by is null"
|
||||
sql = text(f"""
|
||||
select {columns} from gold.cacu_second_visit_features
|
||||
where scenario = :scenario {person_filter} {eligibility_filter}
|
||||
order by person_id
|
||||
""")
|
||||
with engine().connect() as con:
|
||||
return pd.read_sql(sql, con, params={"scenario": scenario, "person_id": person_id})
|
||||
|
||||
|
||||
def cacu_eligibility_report(
|
||||
scenario: str | None = None,
|
||||
person_id: str | None = None,
|
||||
*,
|
||||
cutoff: date | None = None,
|
||||
) -> pd.DataFrame:
|
||||
"""Candidates and every exclusion reason detected for their indexed visit.
|
||||
|
||||
Eligible candidates have one row with a null `criterion`; candidates with multiple
|
||||
reasons have one row per reason. The required relation and columns are checked before
|
||||
querying so an old gold installation gets an actionable error rather than SQL failure.
|
||||
"""
|
||||
with engine().connect() as con:
|
||||
inspector = inspect(con)
|
||||
relation = "cacu_eligibility"
|
||||
if not inspector.has_table(relation, schema="gold"):
|
||||
raise GoldSchemaError(
|
||||
"CaCu eligibility gold is not materialized; rebuild gold.cacu_eligibility."
|
||||
)
|
||||
found = {column["name"] for column in inspector.get_columns(relation, schema="gold")}
|
||||
missing = CACU_ELIGIBILITY_COLUMNS.difference(found)
|
||||
if missing:
|
||||
names = ", ".join(sorted(missing))
|
||||
raise GoldSchemaError(
|
||||
f"CaCu eligibility gold schema is outdated (missing {names}); "
|
||||
"rebuild gold.cacu_eligibility."
|
||||
)
|
||||
filters = []
|
||||
params = {}
|
||||
if scenario is not None:
|
||||
filters.append("scenario = :scenario")
|
||||
params["scenario"] = scenario
|
||||
if person_id is not None:
|
||||
filters.append("person_id = :person_id")
|
||||
params["person_id"] = person_id
|
||||
if cutoff is not None:
|
||||
filters.append("index_date <= :cutoff")
|
||||
params["cutoff"] = cutoff.isoformat()
|
||||
where = f"where {' and '.join(filters)}" if filters else ""
|
||||
sql = text(f"""
|
||||
select scenario, person_id, index_date, index_sample_id, criterion, eligible
|
||||
from gold.{relation} {where}
|
||||
order by scenario, person_id, index_date, index_sample_id, criterion
|
||||
""")
|
||||
return pd.read_sql(sql, con, params=params)
|
||||
|
||||
|
||||
SCORES = "model_scores"
|
||||
|
||||
|
||||
|
||||
@@ -35,6 +35,15 @@ READS = {
|
||||
"mammograms": "select * from gold.cama_mammograms",
|
||||
"biopsies": "select * from gold.cama_biopsies where report_date is not null",
|
||||
"mammogram_biopsies": "select * from gold.cama_mammogram_biopsies",
|
||||
# One row per mammogram: its first reported biopsy (ties: the lowest id), or the row
|
||||
# with none. The biopsy is the one whose request names the mammogram.
|
||||
"mammogram_first_biopsy": """
|
||||
select * from (
|
||||
select *, row_number() over (
|
||||
partition by mammogram_id order by biopsy_report_date, biopsy_id) as nth
|
||||
from gold.cama_mammogram_biopsies
|
||||
) as x where nth = 1
|
||||
""",
|
||||
},
|
||||
"tea": {
|
||||
"screening": "select * from gold.tea_screening",
|
||||
|
||||
@@ -35,6 +35,8 @@ OBSERVATION = {
|
||||
"value_num": {"data_type": "double", "nullable": True},
|
||||
"value_bool": {"data_type": "bool", "nullable": True},
|
||||
"value_date": {"data_type": "date", "nullable": True},
|
||||
"source_clinical_date": {"data_type": "date", "nullable": True},
|
||||
"source_available_at": _text(), "source_ref": _text(),
|
||||
**_BOOKKEEPING,
|
||||
} # fmt: skip
|
||||
# One row per held record of a study: why, and its values as they came.
|
||||
|
||||
+1
-1
Submodule WebApi updated: bd06a31d52...0b1393ad23
+1
-1
Submodule WebApp updated: fe4dd55452...c08a0b8874
@@ -0,0 +1,44 @@
|
||||
# Fechas, estados FHIR y elegibilidad con información insuficiente
|
||||
|
||||
## Fechas de evidencia
|
||||
|
||||
El día de la evidencia normalizada es el local de Monterrey (`America/Monterrey`), tanto para la
|
||||
fecha clínica de un instante con zona como para su disponibilidad (issue #32). Una fecha completa
|
||||
sin hora conserva su día. Un año, año-mes, fecha inválida o fecha y hora sin zona no identifica un
|
||||
día verificable: la fuente se guarda sin fecha y gold usa la fecha del evento como respaldo.
|
||||
|
||||
## Estados FHIR
|
||||
|
||||
`entered-in-error`: no se usa nada del reporte u observación anulados. `preliminary`: se conserva
|
||||
la toma, sin resultado ni fecha de reporte (pendiente). Falta comprobar que una anulación posterior
|
||||
retire un resultado ya cargado como final.
|
||||
|
||||
## Propuesta: información insuficiente
|
||||
|
||||
Actualmente, una evidencia de histerectomía anterior al índice sin disponibilidad de origen no
|
||||
cumple la condición de exclusión; el candidato puede aparecer elegible. Esa ausencia no demuestra
|
||||
que la paciente sea elegible. Propuesta, sin activar:
|
||||
|
||||
1. Evaluar por candidato y fecha índice: si existe evidencia clínicamente anterior sin fecha de
|
||||
disponibilidad comprobable, y no hay otro criterio que ya excluya, informar
|
||||
`insufficient_information`.
|
||||
2. Mantener `excluded` si existe un criterio de exclusión comprobado y, además, exponer la
|
||||
incertidumbre como motivo independiente. `eligible` solo cuando los criterios requeridos
|
||||
puedan evaluarse suficientemente.
|
||||
3. Extender cada `candidate` de `$eligibility` con `eligibility-status` (`eligible`, `excluded`,
|
||||
`insufficient_information`) y repetir `uncertainty` con código
|
||||
`hysterectomy_source_availability_unknown`. Mantener `eligible` por compatibilidad solo tras
|
||||
definir su versión y transición; un booleano no representa tres estados sin ambigüedad.
|
||||
|
||||
Ejemplo del fragmento FHIR propuesto (no publicado por la API actual):
|
||||
|
||||
```json
|
||||
{"name":"candidate","part":[
|
||||
{"name":"eligibility-status","valueCode":"insufficient_information"},
|
||||
{"name":"uncertainty","valueCode":"hysterectomy_source_availability_unknown"}
|
||||
]}
|
||||
```
|
||||
|
||||
Falta decidir qué hacer cuando la fecha clínica también es desconocida y cómo reconciliar
|
||||
fuentes contradictorias. La cohorte, el reporte de deserción, la predicción y la ficha deben
|
||||
consumir la misma decisión antes de activar este contrato.
|
||||
+1
-1
Submodule models updated: 1a1ea5c7a9...8a860c698f
@@ -201,6 +201,7 @@ def pathology_report(p: dict, b: dict) -> bytes:
|
||||
|
||||
p: surname_first (name as the report prints it), age, sex (F/M).
|
||||
b: requested (date), reported (date), time (HH:MM), physician, number (P-25-000000),
|
||||
mammogram (date of the mammogram it came from, when the request names it),
|
||||
clinical (clinical diagnosis), specimen, macroscopic, organ, diagnosis, pathologist,
|
||||
pathologist_id."""
|
||||
pdf = _pdf()
|
||||
@@ -230,9 +231,10 @@ def pathology_report(p: dict, b: dict) -> bytes:
|
||||
pdf.line(40, 208, 572, 208)
|
||||
pdf.set_font("helvetica", "", 8)
|
||||
pdf.set_xy(40, 218)
|
||||
summary = f"MASTOGRAFÍA DEL {_dmy(b['mammogram'])}" if b.get("mammogram") else "no referido"
|
||||
pdf.multi_cell(
|
||||
532, 10,
|
||||
"Notas Clínicas\nTiempo de evolución: no referido. Resumen Clínico: no referido. "
|
||||
f"Notas Clínicas\nTiempo de evolución: no referido. Resumen Clínico: {summary}. "
|
||||
f"Diagnóstico Clínico: {b['clinical']}.\n\nEspecimen\n1 - {b['specimen']}\n"
|
||||
f"Descripción Macroscópica:\n{b['macroscopic']}\n\nSe incluye total del especimen en "
|
||||
"un cassette.\n\nNo estudios previos",
|
||||
|
||||
@@ -356,9 +356,36 @@ CAUSE = {"cervical": ("TUMOR MALIGNO DEL CUELLO DEL ÚTERO", "C53.9"),
|
||||
None: ("INFARTO AGUDO DEL MIOCARDIO", "I21.9")} # fmt: skip
|
||||
|
||||
|
||||
def mammogram_of_biopsies(bundle: dict) -> dict[str, str]:
|
||||
"""The exam date of the mammogram each breast biopsy came from, by the biopsy's request
|
||||
date. Synthea keeps one encounter open from a mammogram to the biopsy it leads to, so a
|
||||
biopsy report and its mammogram's report name the same encounter: that is the source's own
|
||||
link. An encounter with no mammogram, or with two, names none (nothing is inferred)."""
|
||||
by_encounter: dict[str, dict[str, list[str]]] = {}
|
||||
for entry in bundle["entry"]:
|
||||
r = entry["resource"]
|
||||
code = (r.get("code") or {}).get("coding", [{}])[0].get("code")
|
||||
encounter = (r.get("encounter") or {}).get("reference")
|
||||
if r["resourceType"] == "DiagnosticReport" and encounter and code in STUDY_LINK:
|
||||
by_encounter.setdefault(encounter, {}).setdefault(code, []).append(
|
||||
r["effectiveDateTime"][:10]
|
||||
)
|
||||
found: dict[str, set[str]] = {}
|
||||
for studies in by_encounter.values():
|
||||
exams = set(studies.get("mammography", []))
|
||||
if len(studies.get("mammography", [])) == 1:
|
||||
for requested in studies.get("breast_biopsy", []):
|
||||
found.setdefault(requested, set()).update(exams)
|
||||
return {requested: exams.pop() for requested, exams in found.items() if len(exams) == 1}
|
||||
|
||||
|
||||
STUDY_LINK = ("mammography", "breast_biopsy")
|
||||
|
||||
|
||||
def people_and_studies(bundles: list[dict]) -> dict[str, dict]:
|
||||
"""Each Synthea patient's birth date, and her studies as platform rows (core.fhir_in):
|
||||
a biopsy Synthea sent as several same-day reports is one study."""
|
||||
a biopsy Synthea sent as several same-day reports is one study, which names the
|
||||
mammogram it came from (`mammogram_exam_date`) when the source does."""
|
||||
people = {}
|
||||
for bundle in bundles:
|
||||
patient = next(
|
||||
@@ -373,7 +400,11 @@ def people_and_studies(bundles: list[dict]) -> dict[str, dict]:
|
||||
merged.setdefault(r["request_date"], {}).update(
|
||||
{k: v for k, v in r.items() if v is not None}
|
||||
)
|
||||
rows = list(merged.values())
|
||||
origin = mammogram_of_biopsies(bundle)
|
||||
rows = [
|
||||
{**r, "mammogram_exam_date": origin[requested]} if requested in origin else r
|
||||
for requested, r in merged.items()
|
||||
]
|
||||
studies[entity] = [{k: v for k, v in r.items() if not k.startswith("_")} for r in rows]
|
||||
if any(studies.values()):
|
||||
people[patient["id"]] = {"birth_date": _d(patient["birthDate"]), "studies": studies,
|
||||
@@ -737,6 +768,9 @@ def build(
|
||||
)
|
||||
}
|
||||
values = {k: v for k, v in values.items() if v is not None}
|
||||
if r.get("mammogram_exam_date"): # the request names its mammogram
|
||||
report["mammogram"] = _d(r["mammogram_exam_date"])
|
||||
values["mammogram_exam_date"] = r["mammogram_exam_date"]
|
||||
side = rng.choice(("IZQUIERDA", "DERECHA"))
|
||||
if r["histology"] == "benign":
|
||||
lines = [
|
||||
|
||||
+2
-1
@@ -148,6 +148,7 @@
|
||||
"patterns": {
|
||||
"request_date": "solicitud:\\s*(\\d{2}/\\d{2}/\\d{4})",
|
||||
"report_date": "reporte:\\s*(\\d{2}/\\d{2}/\\d{4})",
|
||||
"mammogram_exam_date": "res[uú]men cl[ií]nico:\\s*mastograf[ií]a del (\\d{2}/\\d{2}/\\d{4})",
|
||||
"histology": "biopsia:[\\s\\S]{0,300}?(negativo para malignidad|in situ|infiltrante)",
|
||||
"histologic_type": "\\((\\d{4}/\\d)\\)",
|
||||
"grade": "nottingham\\):\\s*(\\d)",
|
||||
@@ -158,7 +159,7 @@
|
||||
"size_mm": "tama[ñn]o tumoral:\\s*(\\d+)\\s*mm", "positive_nodes": "ganglios linf[aá]ticos positivos:\\s*(\\d+)",
|
||||
"stage": "estadio cl[ií]nico\\s+([0-9IVlO|]{1,4}[ABC]?)\\b"},
|
||||
"concept_map": "erick_site",
|
||||
"formats": {"request_date": "%d/%m/%Y", "report_date": "%d/%m/%Y"}},
|
||||
"formats": {"request_date": "%d/%m/%Y", "report_date": "%d/%m/%Y", "mammogram_exam_date": "%d/%m/%Y"}},
|
||||
|
||||
{"id": "mchat_forms", "kind": "route", "label": "Formatos M-CHAT", "inputs": ["text"], "when": [{"column": "text", "op": "matches", "value": "(?i)cuestionario m-chat"}]},
|
||||
{"id": "ados2_reports", "kind": "route", "label": "Reportes ADOS-2", "inputs": ["text"], "when": [{"column": "text", "op": "matches", "value": "(?i)informe de evaluaci[oó]n ados-2"}]},
|
||||
|
||||
+3
-1
@@ -8,6 +8,7 @@
|
||||
{"id": "cytology", "kind": "fhir", "label": "Citología", "inputs": ["inbox"], "entity": "cervical_cytology"},
|
||||
{"id": "biopsy", "kind": "fhir", "label": "Biopsia", "inputs": ["inbox"], "entity": "cervical_biopsy"},
|
||||
{"id": "notes", "kind": "fhir", "label": "Notas médicas", "inputs": ["inbox"], "entity": "clinical_note"},
|
||||
{"id": "evidence", "kind": "fhir", "label": "Evidencia clínica CaCu", "inputs": ["inbox"], "entity": "cacu_eligibility_evidence"},
|
||||
|
||||
{"id": "persons", "kind": "link", "label": "Quién es quién", "inputs": ["who"],
|
||||
"fields": ["record_number", "curp", "nss", "full_name", "birth_date", "sex"]},
|
||||
@@ -15,6 +16,7 @@
|
||||
{"id": "deaths_out", "kind": "target", "label": "Defunciones", "inputs": ["deaths", "persons"], "entity": "death"},
|
||||
{"id": "cytology_out", "kind": "target", "label": "Citologías", "inputs": ["cytology", "persons"], "entity": "cervical_cytology"},
|
||||
{"id": "biopsy_out", "kind": "target", "label": "Biopsias", "inputs": ["biopsy", "persons"], "entity": "cervical_biopsy"},
|
||||
{"id": "notes_out", "kind": "target", "label": "Notas médicas", "inputs": ["notes", "persons"], "entity": "clinical_note"}
|
||||
{"id": "notes_out", "kind": "target", "label": "Notas médicas", "inputs": ["notes", "persons"], "entity": "clinical_note"},
|
||||
{"id": "evidence_out", "kind": "target", "label": "Evidencia clínica CaCu", "inputs": ["evidence", "persons"], "entity": "cacu_eligibility_evidence"}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.measures import MEASURES
|
||||
from core.measures import Period, evaluate
|
||||
from persistance import destination, silver
|
||||
|
||||
|
||||
def test_real_gold_sample_model_feeds_both_diagnosis_intervals(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
|
||||
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
|
||||
monkeypatch.setenv("DBT_TARGET", "sqlite")
|
||||
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
|
||||
destination.engine.cache_clear()
|
||||
engine = destination.engine()
|
||||
try:
|
||||
with engine.begin() as con:
|
||||
con.exec_driver_sql("create table silver.person (person_id text, birth_date date)")
|
||||
con.exec_driver_sql("insert into silver.person values ('p', '1980-01-01')")
|
||||
con.exec_driver_sql("create table silver.cervical_cytology (person_id text, sample_date date, report_date date, result text, adequacy text, known_at text, report_known_at text, screening_history text, hpv boolean, hpv_16 boolean, hpv_18 boolean)")
|
||||
con.exec_driver_sql("insert into silver.cervical_cytology values ('p', '2026-01-01', '2026-01-05', 'NILM', null, null, null, null, null, null, null)")
|
||||
con.exec_driver_sql("create table gold.cacu_events (person_id text, date date, type text, source_id text, value_code text)")
|
||||
con.exec_driver_sql("insert into gold.cacu_events values ('p', '2026-01-11', 'diagnosis', 'a', null), ('p', '2026-01-11', 'note', 'a', 'N87'), ('p', '2026-02-11', 'diagnosis', 'b', null), ('p', '2026-02-11', 'note', 'b', 'C53')")
|
||||
con.exec_driver_sql("create table gold.cacu_procedures (person_id text, type text, sample_date date, report_date date)")
|
||||
con.exec_driver_sql("insert into gold.cacu_procedures values ('p', 'biopsy', '2026-01-01', '2026-02-01')")
|
||||
con.exec_driver_sql("create table gold.cacu_follow_up (person_id text, first_history date, first_case date, first_treatment date, first_colposcopy date)")
|
||||
con.exec_driver_sql("insert into gold.cacu_follow_up values ('p', null, null, null, null)")
|
||||
silver.build(['cacu_samples'], as_of=date(2026, 12, 31))
|
||||
with engine.connect() as con:
|
||||
row = dict(con.exec_driver_sql('select * from gold.cacu_samples').mappings().one())
|
||||
assert row['days_sample_diagnosis'] == 10
|
||||
assert row['days_sample_biopsy_diagnosis'] == 41
|
||||
period = Period.parse('2026-S1')
|
||||
result = evaluate(MEASURES['CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA'], [row], period,
|
||||
event_cutoff=date(2026, 12, 31))
|
||||
assert result.score == 41
|
||||
finally:
|
||||
engine.dispose()
|
||||
destination.engine.cache_clear()
|
||||
@@ -0,0 +1,25 @@
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.measures import MEASURES
|
||||
from core.measures import Period, evaluate
|
||||
|
||||
|
||||
def test_diagnosis_intervals_use_different_dates_and_require_biopsy():
|
||||
rows = [
|
||||
{"sample_id": "a", "sample_date": "2026-01-01", "history": 0,
|
||||
"diagnosis_date": "2026-01-11", "days_sample_diagnosis": 10,
|
||||
"biopsy_date": "2026-02-01", "biopsy_diagnosis_date": "2026-02-11",
|
||||
"days_sample_biopsy_diagnosis": 41},
|
||||
{"sample_id": "b", "sample_date": "2026-01-01", "history": 0,
|
||||
"diagnosis_date": "2026-01-21", "days_sample_diagnosis": 20,
|
||||
"biopsy_date": None, "biopsy_diagnosis_date": None,
|
||||
"days_sample_biopsy_diagnosis": None},
|
||||
]
|
||||
period = Period.parse("2026-S1")
|
||||
first = evaluate(MEASURES["CACU_DIAS_TOMA_DIAGNOSTICO"], rows, period,
|
||||
event_cutoff=date(2026, 12, 31))
|
||||
after = evaluate(MEASURES["CACU_DIAS_TOMA_DIAGNOSTICO_POST_BIOPSIA"], rows, period,
|
||||
event_cutoff=date(2026, 12, 31))
|
||||
assert first.populations["measure-observation"] == 2
|
||||
assert after.populations["measure-observation"] == 1
|
||||
assert after.score == 41
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Every exclusion reason of a candidate, and the clinical and source cut-offs behind them."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from persistance import destination, gold, silver
|
||||
|
||||
COHORTS = [
|
||||
"cacu_second_visit_features",
|
||||
"cacu_cohort_surveillance",
|
||||
"cacu_cohort_post_colposcopy",
|
||||
"cacu_cohort_post_treatment",
|
||||
"cacu_cohort_survival",
|
||||
]
|
||||
|
||||
|
||||
def _event(person, day, kind, value=None, table="cervical_cytology", source=None):
|
||||
return (person, day, kind, value, table, source or day, None, None)
|
||||
|
||||
|
||||
def _sample(person, day):
|
||||
return _event(person, day, "cytology", "satisfactory")
|
||||
|
||||
|
||||
def _result(person, day):
|
||||
return _event(person, day, "bethesda", "NILM")
|
||||
|
||||
|
||||
def _birth(person, day):
|
||||
return _event(person, day, "birth", table="person", source=person)
|
||||
|
||||
|
||||
def _note(person, day, kind):
|
||||
return _event(person, day, kind, table="clinical_note", source=f"{kind}-{day}")
|
||||
|
||||
|
||||
def _biopsy(person, day, value, order):
|
||||
return _event(person, day, "biopsy", value, "cervical_biopsy", order)
|
||||
|
||||
|
||||
def _hysterectomy(person, day, available):
|
||||
return (person, day, "gynecologic_condition", "hysterectomy", "cervical_cytology", day,
|
||||
day, available) # fmt: skip
|
||||
|
||||
|
||||
def _events():
|
||||
visit = "2025-02-10"
|
||||
|
||||
def indexed(person):
|
||||
return [_sample(person, visit), _result(person, visit)]
|
||||
|
||||
return [
|
||||
# Surveillance: four reasons on one candidate.
|
||||
_birth("many", "2010-01-01"),
|
||||
_hysterectomy("many", "2025-01-01", "2025-01-02"),
|
||||
_biopsy("many", "2025-01-05", "HSIL", "o-many"),
|
||||
_sample("many", visit),
|
||||
# Age on the index date.
|
||||
*indexed("age17"), _birth("age17", "2007-02-11"),
|
||||
*indexed("age18"), _birth("age18", "2007-02-10"),
|
||||
*indexed("noage"),
|
||||
# Clinical date and source availability against the index.
|
||||
*indexed("same_day"), _hysterectomy("same_day", visit, visit),
|
||||
*indexed("later"), _hysterectomy("later", "2025-02-11", "2025-02-11"),
|
||||
*indexed("late_source"), _hysterectomy("late_source", "2025-02-01", "2025-02-11"),
|
||||
*indexed("no_source"), _hysterectomy("no_source", "2025-02-01", None),
|
||||
*indexed("on_time"), _hysterectomy("on_time", "2025-02-01", "2025-02-10T23:00:00+00:00"),
|
||||
# Post-colposcopy: every scenario reason at once, for the first and second visit.
|
||||
_note("colpo", "2025-03-10", "colposcopy"),
|
||||
_event("colpo", "2025-03-10", "biopsy_order", table="cervical_biopsy", source="o-open"),
|
||||
_event("colpo", "2025-03-10", "biopsy_order", table="cervical_biopsy", source="o-done"),
|
||||
_biopsy("colpo", "2025-03-15", "HSIL", "o-done"),
|
||||
_note("colpo", "2025-03-20", "history"),
|
||||
_note("colpo", "2025-03-22", "treatment"),
|
||||
_sample("colpo", "2025-04-10"),
|
||||
_sample("colpo", "2025-05-10"),
|
||||
# Post-treatment: no biopsy before it, an outcome after it, no result at the index.
|
||||
_note("treated", "2025-03-01", "treatment"),
|
||||
_biopsy("treated", "2025-05-01", "HSIL", "o-treated"),
|
||||
_sample("treated", "2025-10-05"),
|
||||
# Survival: died by the index and no birth date.
|
||||
_biopsy("case", "2025-02-10", "carcinoma", "o-case"),
|
||||
_event("case", "2025-02-01", "death", table="person", source="case"),
|
||||
# Two index dates of one patient, with the evidence dated between them.
|
||||
_sample("twice", "2025-01-10"), _result("twice", "2025-01-10"),
|
||||
_hysterectomy("twice", "2025-02-01", "2025-02-01"),
|
||||
_sample("twice", "2025-03-10"), _result("twice", "2025-03-10"),
|
||||
] # fmt: skip
|
||||
|
||||
|
||||
def test_each_candidate_reports_all_its_reasons_once(tmp_path, monkeypatch):
|
||||
"""Pins multiple reasons per scenario, the index cut-offs, age 17/18 and cohort priority."""
|
||||
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
|
||||
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
|
||||
monkeypatch.setenv("DBT_TARGET", "sqlite")
|
||||
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
|
||||
destination.engine.cache_clear()
|
||||
engine = destination.engine()
|
||||
|
||||
try:
|
||||
with engine.begin() as con:
|
||||
con.exec_driver_sql("create table silver.person (person_id text)")
|
||||
con.exec_driver_sql(
|
||||
"create table gold.cacu_events (person_id text, date date, type text, "
|
||||
"value_code text, source_table text, source_id text, evidence_date date, "
|
||||
"source_available_at text, source_ref text)"
|
||||
)
|
||||
con.exec_driver_sql(
|
||||
"insert into gold.cacu_events (person_id, date, type, value_code, source_table, "
|
||||
"source_id, evidence_date, source_available_at) values (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
_events(),
|
||||
)
|
||||
|
||||
silver.build([*COHORTS, "cacu_eligibility"], as_of=date(2025, 11, 1))
|
||||
found = gold.cacu_eligibility_report()
|
||||
|
||||
key = ["scenario", "person_id", "index_date", "index_sample_id", "criterion"]
|
||||
assert not found.duplicated(key).any()
|
||||
# A candidate is either eligible, with one empty row, or excluded by its reasons.
|
||||
for _, rows in found.groupby(key[:4], dropna=False):
|
||||
if rows["eligible"].astype(bool).any():
|
||||
assert len(rows) == 1 and rows["criterion"].isna().all()
|
||||
else:
|
||||
assert rows["criterion"].notna().all()
|
||||
|
||||
def reasons(scenario, person):
|
||||
rows = found[(found["scenario"] == scenario) & (found["person_id"] == person)]
|
||||
assert len(rows), f"no {scenario} candidate for {person}"
|
||||
return set(rows["criterion"].dropna())
|
||||
|
||||
assert reasons("surveillance", "many") == {
|
||||
"hysterectomy", "under_18", "prior_outcome", "no_index_result"} # fmt: skip
|
||||
assert reasons("surveillance", "age17") == {"under_18"}
|
||||
for person in ("age18", "noage", "same_day", "later", "late_source", "no_source"):
|
||||
assert reasons("surveillance", person) == set(), person
|
||||
assert reasons("surveillance", "on_time") == {"hysterectomy"}
|
||||
|
||||
colposcopy = {"outcome_by_index", "cancer_history", "prior_treatment", "no_referral",
|
||||
"no_cotest"} # fmt: skip
|
||||
assert reasons("post_colposcopy", "colpo") == colposcopy | {"unreported_biopsy"}
|
||||
assert reasons("post_colposcopy_second_visit", "colpo") == colposcopy
|
||||
assert reasons("post_treatment", "treated") == {
|
||||
"no_pretreatment_biopsy", "outcome_before_index", "no_index_result"} # fmt: skip
|
||||
assert reasons("survival", "case") == {"died_by_index", "no_birth_date"}
|
||||
|
||||
assert reasons("surveillance", "twice") == set()
|
||||
assert reasons("pre_colposcopy", "twice") == {"hysterectomy"}
|
||||
|
||||
# The cohorts keep one reason each, in the order they had before.
|
||||
with engine.connect() as con:
|
||||
for cohort, person, first in (
|
||||
("surveillance", "many", "hysterectomy"),
|
||||
("post_colposcopy", "colpo", "unreported_biopsy"),
|
||||
("post_treatment", "treated", "no_pretreatment_biopsy"),
|
||||
("survival", "case", "no_birth_date"),
|
||||
):
|
||||
assert con.exec_driver_sql(
|
||||
f"select excluded_by from gold.cacu_cohort_{cohort} where person_id = ?",
|
||||
(person,),
|
||||
).scalar_one() == first, cohort
|
||||
finally:
|
||||
engine.dispose()
|
||||
destination.engine.cache_clear()
|
||||
@@ -0,0 +1,70 @@
|
||||
"""FHIR Parameters for a patient's cohort eligibility and all detected reasons."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core import fhir
|
||||
|
||||
|
||||
def test_cacu_eligibility_groups_reasons_by_indexed_candidate():
|
||||
rows = [
|
||||
{
|
||||
"scenario": "surveillance",
|
||||
"index_date": date(2025, 2, 1),
|
||||
"index_sample_id": "sample-1",
|
||||
"criterion": criterion,
|
||||
"eligible": False,
|
||||
}
|
||||
for criterion in ("under_18", "hysterectomy")
|
||||
] + [
|
||||
{
|
||||
"scenario": "survival",
|
||||
"index_date": date(2025, 3, 1),
|
||||
"index_sample_id": None,
|
||||
"criterion": None,
|
||||
"eligible": True,
|
||||
}
|
||||
]
|
||||
|
||||
body = fhir.cacu_eligibility(rows, "patient-1", date(2025, 3, 1)).model_dump(
|
||||
mode="json", exclude_none=True
|
||||
)
|
||||
parameters = {part["name"]: part for part in body["parameter"]}
|
||||
assert body["resourceType"] == "Parameters"
|
||||
assert parameters["status"]["valueCode"] == "evaluated"
|
||||
assert parameters["patient"]["valueReference"]["reference"] == "Patient/patient-1"
|
||||
assert parameters["cutoff"]["valueDate"] == "2025-03-01"
|
||||
|
||||
candidates = [p for p in body["parameter"] if p["name"] == "candidate"]
|
||||
assert len(candidates) == 2
|
||||
surveillance = candidates[0]["part"]
|
||||
values = {p["name"]: p for p in surveillance if p["name"] != "criterion"}
|
||||
reasons = [p["valueCoding"]["code"] for p in surveillance if p["name"] == "criterion"]
|
||||
assert values["scenario"]["valueCoding"]["code"] == "surveillance"
|
||||
assert values["index-sample-id"]["valueString"] == "sample-1"
|
||||
assert values["eligible"]["valueBoolean"] is False
|
||||
assert reasons == ["hysterectomy", "under_18"]
|
||||
assert reasons[0] in fhir.CODE_SYSTEMS["cacu-exclusion-criterion"][1]
|
||||
|
||||
survival = candidates[1]["part"]
|
||||
assert next(p for p in survival if p["name"] == "eligible")["valueBoolean"] is True
|
||||
assert not [p for p in survival if p["name"] == "criterion"]
|
||||
|
||||
|
||||
def test_cacu_eligibility_reports_when_no_candidate_exists():
|
||||
body = fhir.cacu_eligibility([], "patient-1", date(2025, 3, 1)).model_dump(
|
||||
mode="json", exclude_none=True
|
||||
)
|
||||
assert {p["name"]: p for p in body["parameter"]}["status"]["valueCode"] == "no_candidate"
|
||||
|
||||
|
||||
def test_cacu_eligibility_code_systems_are_publishable():
|
||||
systems = {resource.id: resource for resource in fhir.code_systems()}
|
||||
assert systems["cacu-eligibility-scenario"].url.endswith(
|
||||
"/CodeSystem/cacu-eligibility-scenario"
|
||||
)
|
||||
assert systems["cacu-exclusion-criterion"].url.endswith(
|
||||
"/CodeSystem/cacu-exclusion-criterion"
|
||||
)
|
||||
assert "hysterectomy" in {
|
||||
concept.code for concept in systems["cacu-exclusion-criterion"].concept
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
"""The cohort eligibility reader checks gold's contract and supports patient queries."""
|
||||
|
||||
import pytest
|
||||
|
||||
from persistance import destination, gold
|
||||
|
||||
|
||||
def test_cacu_eligibility_report_checks_schema_and_filters(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
|
||||
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
|
||||
monkeypatch.setenv("DBT_TARGET", "sqlite")
|
||||
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
|
||||
destination.engine.cache_clear()
|
||||
engine = destination.engine()
|
||||
|
||||
try:
|
||||
with pytest.raises(gold.GoldSchemaError, match="not materialized"):
|
||||
gold.cacu_eligibility_report("pre_colposcopy", "patient-1")
|
||||
|
||||
with engine.begin() as con:
|
||||
con.exec_driver_sql(
|
||||
"create table gold.cacu_eligibility (person_id text, scenario text)"
|
||||
)
|
||||
with pytest.raises(gold.GoldSchemaError, match="schema is outdated"):
|
||||
gold.cacu_eligibility_report()
|
||||
|
||||
with engine.begin() as con:
|
||||
con.exec_driver_sql("drop table gold.cacu_eligibility")
|
||||
con.exec_driver_sql(
|
||||
"create table gold.cacu_eligibility (scenario text, person_id text, "
|
||||
"index_date date, index_sample_id text, criterion text, eligible boolean)"
|
||||
)
|
||||
con.exec_driver_sql(
|
||||
"insert into gold.cacu_eligibility values "
|
||||
"('pre_colposcopy', 'patient-1', '2025-01-01', 'sample-1', 'hysterectomy', 0), "
|
||||
"('pre_colposcopy', 'patient-1', '2025-01-01', 'sample-1', 'under_18', 0), "
|
||||
"('pre_colposcopy', 'patient-2', '2025-02-01', 'sample-2', null, 1), "
|
||||
"('post_colposcopy', 'patient-1', '2025-03-01', null, 'outcome_by_index', 0)"
|
||||
)
|
||||
|
||||
found = gold.cacu_eligibility_report("pre_colposcopy", "patient-1")
|
||||
assert found["criterion"].tolist() == ["hysterectomy", "under_18"]
|
||||
assert found["eligible"].tolist() == [False, False]
|
||||
assert len(gold.cacu_eligibility_report("pre_colposcopy")) == 3
|
||||
finally:
|
||||
destination.engine.cache_clear()
|
||||
@@ -0,0 +1,130 @@
|
||||
"""Source evidence dates through the CaCu FHIR and document targets, staging and gold."""
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
from core import catalog, fhir_in
|
||||
from core.pipeline import RECORD, Fhir, Target
|
||||
from models.graph import run_fhir, run_target
|
||||
from persistance import destination, gold, nodes, silver
|
||||
|
||||
|
||||
def _coding(system, code):
|
||||
return {"coding": [{"system": system, "code": code}]}
|
||||
|
||||
|
||||
def _bundle(*resources):
|
||||
return {"resourceType": "Bundle", "type": "collection", "entry": [
|
||||
{"resource": resource} for resource in resources
|
||||
]} # fmt: skip
|
||||
|
||||
|
||||
def test_cacu_source_dates_survive_late_import_and_missing_release(tmp_path, monkeypatch):
|
||||
"""Replays independent resources, a linked result and extracted notes through gold."""
|
||||
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
|
||||
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
|
||||
monkeypatch.setenv("DLT_DATA_DIR", str(tmp_path / "dlt"))
|
||||
monkeypatch.setenv("DBT_TARGET", "sqlite")
|
||||
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
|
||||
destination.engine.cache_clear()
|
||||
engine = destination.engine()
|
||||
subject = {"reference": "Patient/p1"}
|
||||
patient = {"resourceType": "Patient", "id": "p1", "birthDate": "1980-01-01"}
|
||||
observation = {
|
||||
"resourceType": "Observation", "id": "hpv", "subject": subject, "status": "final",
|
||||
"code": _coding(fhir_in.FIELD, "cervical_cytology.hpv"), "valueBoolean": True,
|
||||
"effectiveDateTime": "2025-01-05", "issued": "2025-01-18T12:00:00-06:00",
|
||||
} # fmt: skip
|
||||
report = {
|
||||
"resourceType": "DiagnosticReport", "id": "c1", "subject": subject, "status": "final",
|
||||
"effectiveDateTime": "2025-01-04", "issued": "2025-01-10T15:00:00Z",
|
||||
"code": _coding(fhir_in.STUDY, "cervical_cytology"),
|
||||
"result": [{"reference": "Observation/hpv"}],
|
||||
} # fmt: skip
|
||||
condition = {
|
||||
"resourceType": "Condition", "id": "dx", "subject": subject,
|
||||
"code": _coding(catalog.systems()["icd-10"].url, "Z90.7"),
|
||||
"onsetDateTime": "2025-01-02", "recordedDate": "2025-01-12",
|
||||
} # fmt: skip
|
||||
exam = {
|
||||
"resourceType": "Observation", "id": "exam", "subject": subject, "status": "final",
|
||||
"code": _coding(fhir_in.FIELD, "cervical_cytology.gynecologic_condition"),
|
||||
"valueCodeableConcept": _coding(catalog.systems()["gynecologic-condition"].url,
|
||||
"hysterectomy"),
|
||||
"effectiveDateTime": "2025-01-03", "meta": {"lastUpdated": "2025-01-10T13:00:00Z"},
|
||||
} # fmt: skip
|
||||
|
||||
try:
|
||||
nodes.write("hospital", "inbox", [
|
||||
{"doc": json.dumps(_bundle(patient, report)), "received_at": "2025-02-19"},
|
||||
{"doc": json.dumps(_bundle(observation, condition, exam)), "received_at": "2025-02-20"},
|
||||
])
|
||||
kinds = {
|
||||
"persons": "link", "notes": "extract", "cervical_cytology": "fhir",
|
||||
fhir_in.EVIDENCE: "fhir",
|
||||
}
|
||||
run_fhir("hospital", Fhir(id="identity", label="Identity", inputs=["inbox"],
|
||||
entity="identity"))
|
||||
linked = {row[RECORD] for row in nodes.rows("hospital", "identity")}
|
||||
assert fhir_in.record("hospital", "Condition/dx") in linked
|
||||
assert fhir_in.record("hospital", "Observation/exam") in linked
|
||||
nodes.write("hospital", "persons", [
|
||||
{RECORD: record, "person_id": "p1"} for record in sorted(linked | {"signed-note"})
|
||||
])
|
||||
nodes.stage("identity", "hospital", "persons", [{
|
||||
RECORD: "patient", "person_id": "p1", "record_number": "TEST-P1",
|
||||
"birth_date": date(1980, 1, 1),
|
||||
}], silver.identity_columns())
|
||||
for entity in ("cervical_cytology", fhir_in.EVIDENCE):
|
||||
run_fhir("hospital", Fhir(id=entity, label=entity, inputs=["inbox"], entity=entity))
|
||||
run_target("hospital", Target(id=f"{entity}_out", label=entity,
|
||||
inputs=[entity, "persons"], entity=entity), kinds)
|
||||
nodes.write("hospital", "notes", [{
|
||||
RECORD: "signed-note", "note_date": "2025-01-12",
|
||||
"specialty": "family_medicine", "icd10": "Z90.7",
|
||||
}])
|
||||
run_target("hospital", Target(id="notes_out", label="Notes",
|
||||
inputs=["notes", "persons"], entity="clinical_note"), kinds)
|
||||
|
||||
silver.build(
|
||||
["+cacu_events", "+cacu_eligibility_evidence", "+cacu_eligibility"],
|
||||
as_of=date(2025, 2, 21),
|
||||
)
|
||||
eligibility = gold.cacu_eligibility_report("surveillance", "p1")
|
||||
# The hysterectomy onset predates the index, but the FHIR Condition was recorded
|
||||
# after it, so it cannot exclude the patient at that visit.
|
||||
assert "hysterectomy" not in eligibility["criterion"].tolist()
|
||||
with engine.connect() as con:
|
||||
normalized = con.exec_driver_sql(
|
||||
"select type, value_code, evidence_date, source_available_at "
|
||||
"from gold.cacu_events where type = 'gynecologic_condition' "
|
||||
"and value_code = 'hysterectomy' order by evidence_date"
|
||||
).all()
|
||||
assert normalized == [
|
||||
("gynecologic_condition", "hysterectomy", "2025-01-02", "2025-01-12"),
|
||||
("gynecologic_condition", "hysterectomy", "2025-01-03", None),
|
||||
("gynecologic_condition", "hysterectomy", "2025-01-12", "2025-01-12"),
|
||||
]
|
||||
found = con.exec_driver_sql(
|
||||
"select date, evidence_date, source_available_at, source_ref, known_at "
|
||||
"from gold.cacu_events where type in ('hpv', 'note') "
|
||||
"union all select date, evidence_date, source_available_at, source_ref, known_at "
|
||||
"from gold.cacu_eligibility_evidence"
|
||||
).all()
|
||||
dates = {row[3]: row[:3] for row in found}
|
||||
assert dates == {
|
||||
"hospital|Observation/hpv": ("2025-01-10", "2025-01-05",
|
||||
"2025-01-18T12:00:00.000000-06:00"),
|
||||
"hospital|Condition/dx": ("2025-01-02", "2025-01-02", "2025-01-12"),
|
||||
"hospital|Observation/exam": ("2025-01-03", "2025-01-03", None),
|
||||
"signed-note": ("2025-01-12", "2025-01-12", "2025-01-12"),
|
||||
}
|
||||
assert all(str(row[4])[:10] > "2025-02-20" for row in found)
|
||||
# A Jan 15 evaluation uses what was documented by the source, even with a late import.
|
||||
assert {ref for ref, (_, clinical, available) in dates.items()
|
||||
if clinical < "2025-01-15" and available and available[:10] <= "2025-01-15"} == {
|
||||
"hospital|Condition/dx", "signed-note",
|
||||
}
|
||||
finally:
|
||||
engine.dispose()
|
||||
destination.engine.cache_clear()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Cervical exam observations and HPV genotypes reach the CaCu model input."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from models.cacu.features import index_sample, prepared
|
||||
from persistance import destination, gold, silver
|
||||
|
||||
|
||||
def test_cervical_exam_fields_are_readable_from_the_cohort_index_sample(tmp_path, monkeypatch):
|
||||
"""Pins sample-linked exam codes, field availability and separate HPV genotypes."""
|
||||
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
|
||||
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
|
||||
monkeypatch.setenv("DBT_TARGET", "sqlite")
|
||||
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
|
||||
destination.engine.cache_clear()
|
||||
engine = destination.engine()
|
||||
fields = {
|
||||
"gynecologic_condition": "hysterectomy",
|
||||
"presenting_symptom": "abnormal_bleeding",
|
||||
"cervix_appearance": "lesion",
|
||||
}
|
||||
condition_known_at = "2026-02-20 15:45:00"
|
||||
|
||||
try:
|
||||
with engine.begin() as con:
|
||||
con.exec_driver_sql(
|
||||
"create table bronze.staged__identity (person_id text, record_number text, "
|
||||
"birth_date date, sex text, known_at datetime, _held text)"
|
||||
)
|
||||
con.exec_driver_sql(
|
||||
"insert into bronze.staged__identity "
|
||||
"values ('p1', 'test-record', '1980-01-01', 'female', '2026-01-01', null)"
|
||||
)
|
||||
con.exec_driver_sql(
|
||||
"create table bronze.staged__observation (person_id text, study text, "
|
||||
"instance text, field text, value_text text, value_num real, value_bool boolean, "
|
||||
"value_date date, known_at datetime, _record text, _index integer)"
|
||||
)
|
||||
con.execute(
|
||||
text(
|
||||
"insert into bronze.staged__observation "
|
||||
"(person_id, study, instance, field, value_text, value_date, value_bool, "
|
||||
"known_at, _record, _index) "
|
||||
"values ('p1', 'cervical_cytology', :day, :field, :code, :value_date, "
|
||||
":value_bool, coalesce(:known_at, :day), :day, 0)"
|
||||
),
|
||||
[
|
||||
dict(
|
||||
day="2026-02-10", field=field, code=code, value_date=None, value_bool=None,
|
||||
known_at=condition_known_at if field == "gynecologic_condition" else None,
|
||||
)
|
||||
for field, code in fields.items()
|
||||
]
|
||||
+ [
|
||||
dict(
|
||||
day=day, field="sample_date", code=None, value_date=day, value_bool=None,
|
||||
known_at=None,
|
||||
)
|
||||
for day in ("2026-02-10", "2026-03-10")
|
||||
]
|
||||
+ [
|
||||
dict(
|
||||
day=day, field=field, code=None, value_date=when, value_bool=value,
|
||||
known_at=None,
|
||||
)
|
||||
for day, field, when, value in (
|
||||
("2026-02-10", "report_date", "2026-02-15", None),
|
||||
("2026-02-10", "hpv_16", None, True),
|
||||
("2026-02-10", "hpv_18", None, False),
|
||||
("2026-03-10", "report_date", "2026-03-15", None),
|
||||
("2026-03-10", "hpv_18", None, True),
|
||||
)
|
||||
],
|
||||
)
|
||||
con.exec_driver_sql(
|
||||
"insert into bronze.staged__observation "
|
||||
"(person_id, study, instance, field, value_text, value_date, "
|
||||
"known_at, _record, _index) "
|
||||
"values ('p1', 'clinical_note', 'note-1', ?, ?, ?, ?, ?, 0)",
|
||||
[
|
||||
("note_date", None, "2026-02-11", "2026-02-11", "note-header"),
|
||||
("specialty", "family_medicine", None, "2026-02-11", "note-header"),
|
||||
("icd10", "Z90.7", None, "2026-02-21 11:30:00", "note-code"),
|
||||
],
|
||||
)
|
||||
|
||||
# Simulate an installation staged before provenance columns existed.
|
||||
with engine.connect() as con:
|
||||
legacy = {row[1] for row in con.exec_driver_sql(
|
||||
"pragma bronze.table_info(staged__observation)")}
|
||||
assert "source_available_at" not in legacy
|
||||
silver.build(["+cacu_eligibility", "+cacu_cohort_total"], as_of=date(2026, 4, 1))
|
||||
with engine.connect() as con:
|
||||
upgraded = {row[1] for row in con.exec_driver_sql(
|
||||
"pragma silver.table_info(cervical_cytology)")}
|
||||
assert {"gynecologic_condition_source_clinical_date",
|
||||
"gynecologic_condition_source_available_at",
|
||||
"gynecologic_condition_source_ref"} <= upgraded
|
||||
events = gold.timelines("cacu_events", "cacu_cohort_total", date(2026, 4, 1))
|
||||
exam = events[
|
||||
events["type"].isin(fields) & (events["source_table"] == "cervical_cytology")
|
||||
]
|
||||
assert len(exam) == len(fields)
|
||||
assert set(exam["source_table"]) == {"cervical_cytology"}
|
||||
assert set(exam["source_id"]) == {"2026-02-10"}
|
||||
assert set(exam["date"].astype(str)) == {"2026-02-10"}
|
||||
eligibility = gold.cacu_eligibility_report("surveillance")
|
||||
assert {"scenario", "criterion", "eligible"}.issubset(eligibility.columns)
|
||||
assert not eligibility.empty
|
||||
# The examination evidence is on the index day and the note is later, so neither
|
||||
# is a prior hysterectomy available at this index.
|
||||
assert "hysterectomy" not in eligibility["criterion"].tolist()
|
||||
with engine.connect() as con:
|
||||
evidence = con.exec_driver_sql(
|
||||
"select date, known_at, type, value_code, source_table, source_id, "
|
||||
"source_available_at "
|
||||
"from gold.cacu_events "
|
||||
"where (type = 'gynecologic_condition' and value_code = 'hysterectomy') "
|
||||
"or (type = 'note' and value_code = 'Z907') order by date"
|
||||
).all()
|
||||
assert evidence[0] == (
|
||||
"2026-02-10", condition_known_at, "gynecologic_condition", "hysterectomy",
|
||||
"cervical_cytology", "2026-02-10", None,
|
||||
)
|
||||
assert evidence[1:] == [
|
||||
(
|
||||
"2026-02-11",
|
||||
"2026-02-21 11:30:00",
|
||||
"note",
|
||||
"Z907",
|
||||
"clinical_note",
|
||||
"2026-02-11|family_medicine",
|
||||
None,
|
||||
),
|
||||
(
|
||||
"2026-02-11",
|
||||
"2026-02-21 11:30:00",
|
||||
"gynecologic_condition",
|
||||
"hysterectomy",
|
||||
"clinical_note",
|
||||
"2026-02-11|family_medicine",
|
||||
None,
|
||||
),
|
||||
]
|
||||
|
||||
genotypes = events[events["type"].isin(("hpv_16", "hpv_18"))]
|
||||
assert set(genotypes[["source_id", "type", "value_code"]].itertuples(index=False)) == {
|
||||
("2026-02-10", "hpv_16", "positive"),
|
||||
("2026-02-10", "hpv_18", "negative"),
|
||||
("2026-03-10", "hpv_18", "positive"),
|
||||
}
|
||||
expected = fields | {"hpv_16": "positive", "hpv_18": "negative"}
|
||||
model_input = index_sample(prepared(events), list(expected))
|
||||
assert model_input.iloc[0][list(expected)].to_dict() == expected
|
||||
finally:
|
||||
engine.dispose()
|
||||
destination.engine.cache_clear()
|
||||
@@ -0,0 +1,18 @@
|
||||
"""The day of FHIR evidence: its precision and its zone."""
|
||||
|
||||
import pytest
|
||||
|
||||
from core import fhir_in
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("value", "expected"), [
|
||||
("2025", None), ("2025-02", None), ("2025-02-03", "2025-02-03"),
|
||||
("2025-02-03T23:30:00", None),
|
||||
("2025-02-03T23:30:00-06:00", "2025-02-03"),
|
||||
("2025-02-04T01:30:00+06:00", "2025-02-03"),
|
||||
("2025-02-04T03:00:00Z", "2025-02-03"),
|
||||
])
|
||||
def test_evidence_days_share_the_monterrey_cutoff(value, expected):
|
||||
evidence = fhir_in._evidence("source", value, value)
|
||||
assert evidence["source_clinical_date"] == expected
|
||||
assert (evidence["source_available_at"] or "")[:10] == (expected or "")
|
||||
@@ -122,3 +122,42 @@ def test_a_duration_by_code_scores_each_code():
|
||||
"no_data": 28,
|
||||
}
|
||||
assert len(fhir.EXTENSIONS["q1"][1]) == 2
|
||||
|
||||
|
||||
def test_hpv_reports_by_genotype_cross_age_status_and_round_without_changing_the_count():
|
||||
def report(person, taken, birth, history, hpv, h16, h18, **more):
|
||||
return {
|
||||
"sample_id": f"{person}|{taken}", "person_id": person, "sample_date": taken,
|
||||
"report_date": "2026-03-01", "birth_date": birth, "screening_history": history,
|
||||
"hpv": hpv, "hpv_16": h16, "hpv_18": h18, "known_at": "2026-01-01",
|
||||
"report_known_at": "2026-01-01", "first_case": None, "first_treatment": None,
|
||||
"first_colposcopy": None, **more,
|
||||
} # fmt: skip
|
||||
|
||||
rows = [
|
||||
report("a", "2026-02-01", "1990-01-01", "never", False, False, False),
|
||||
report("a", "2026-04-01", "1990-01-01", "never", True, True, False), # same patient: 2 reports
|
||||
report("b", "2026-02-01", "1970-01-01", "2_years", True, False, False),
|
||||
report("c", "2026-02-01", "1980-01-01", "never", True, None, False, first_colposcopy="2025-12-01"),
|
||||
report("d", "2026-02-01", "1980-01-01", None, True, False, True),
|
||||
] # fmt: skip
|
||||
plain = ran("CACU_VPH_GENOTIPO", rows)
|
||||
assert plain.populations["initial-population"] == 5 # reports, not patients
|
||||
assert plain.strata["category"] == {
|
||||
"negative": {"initial-population": 1},
|
||||
"positive_16": {"initial-population": 1},
|
||||
"positive_other": {"initial-population": 1},
|
||||
"positive_incomplete": {"initial-population": 1},
|
||||
"positive_18": {"initial-population": 1},
|
||||
}
|
||||
# every report is in exactly one group of each stratifier
|
||||
for name in ("age_group", "follow_up_status", "round"):
|
||||
assert sum(c["initial-population"] for c in plain.strata[name].values()) == 5
|
||||
assert plain.strata["round"] == {
|
||||
"initial": {"initial-population": 2}, # a's two reports: she never had a screening
|
||||
"subsequent": {"initial-population": 2}, # b's history; c is past colposcopy
|
||||
"no_data": {"initial-population": 1}, # d has no history and no colposcopy
|
||||
}
|
||||
assert plain.strata["follow_up_status"]["post_colposcopy"] == {"initial-population": 1}
|
||||
assert plain.crossed[("round", "category")][("initial", "negative")] == {"initial-population": 1}
|
||||
assert plain.crossed[("round", "category")][("no_data", "positive_18")] == {"initial-population": 1}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""NCI post-procedure series read real workbook rows without guessing missing facts."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from core import fhir
|
||||
from core.cacu import reference_risk, risk_series
|
||||
from core.risk_workbooks import read_workbook
|
||||
|
||||
CUT = date(2026, 12, 31)
|
||||
|
||||
|
||||
def sample(day, result, hpv):
|
||||
return {"sample_date": day, "report_date": day, "result": result, "adequacy": None,
|
||||
"hpv": hpv, "hpv_16": None, "hpv_18": None, "gynecologic_condition": None}
|
||||
|
||||
|
||||
def facts(histology="normal", *, treated=False):
|
||||
return {
|
||||
"birth_date": "1980-01-01",
|
||||
"cytologies": [sample("2025-01-01", "ASC-US", True),
|
||||
sample("2025-06-01", "NILM", False)],
|
||||
"biopsies": [{"request_date": "2025-02-01", "report_date": "2025-02-10",
|
||||
"histology": histology, "cytology_sample_date": "2025-01-01"}],
|
||||
"events": [{"date": "2025-02-01", "type": "colposcopy"}] +
|
||||
([{"date": "2025-03-01", "type": "treatment",
|
||||
"biopsy_request_date": "2025-02-01"}] if treated else []),
|
||||
}
|
||||
|
||||
|
||||
def by_id(rows):
|
||||
return {r["id"]: r for r in rows}
|
||||
|
||||
|
||||
def test_postcolpo_book_retains_hpv_and_cytology_columns():
|
||||
row = read_workbook(risk_series.BOOKS / risk_series.POST_COLPO)[0]
|
||||
assert row["variables"]["Post-Colpo Test Result [4]"] == "HPV-negative"
|
||||
assert row["variables"]["Post-Colpo Test Result [5]"] == "NILM"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("histology", ["normal", "LSIL"])
|
||||
def test_postcolpo_all_outcomes_match_exact_workbook_row(histology):
|
||||
data = facts(histology)
|
||||
resolution = reference_risk.resolve(data, CUT)
|
||||
found = by_id(risk_series.nci_post_colposcopy(data, resolution, CUT))
|
||||
row = read_workbook(risk_series.BOOKS / risk_series.POST_COLPO)[0]
|
||||
for outcome in ("CIN2+", "CIN3+", "cancer"):
|
||||
series = found[f"nci-post-colposcopy-{outcome}"]
|
||||
assert series["status"] == "resolved"
|
||||
point = next(p for p in series["points"] if p["years"] == 5)
|
||||
estimate = next(e for e in row["estimates"]
|
||||
if e["outcome"] == outcome and e["horizon_years"] == 5)
|
||||
assert point["probability"] == estimate["value"]
|
||||
assert point["low"] == estimate["confidence_interval"]["lower"]
|
||||
assert "HPV-negative" in found["nci-post-colposcopy-CIN2+"]["label"]
|
||||
assert fhir.risk_series(list(found.values()), "p", CUT)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("histology", ["HSIL", "CIS", "carcinoma", None])
|
||||
def test_postcolpo_never_assumes_high_grade_biopsy_is_below_cin2(histology):
|
||||
data = facts(histology)
|
||||
found = risk_series.nci_post_colposcopy(data, reference_risk.resolve(data, CUT), CUT)
|
||||
assert all(s["status"] == "unresolved" and not s["points"] for s in found)
|
||||
|
||||
|
||||
def test_postcolpo_requires_explicit_referral_and_no_treatment():
|
||||
data = facts()
|
||||
data["biopsies"][0]["cytology_sample_date"] = None
|
||||
found = risk_series.nci_post_colposcopy(data, reference_risk.resolve(data, CUT), CUT)
|
||||
assert all(s["reasons"] == ["missing_or_ambiguous_referral"] for s in found)
|
||||
data = facts(treated=True)
|
||||
found = risk_series.nci_post_colposcopy(data, reference_risk.resolve(data, CUT), CUT)
|
||||
assert all(s["reasons"] == ["treatment_before_index"] for s in found)
|
||||
|
||||
|
||||
def test_post_treatment_cin1_uses_fraction_and_cin3_books_unresolved():
|
||||
data = facts("LSIL", treated=True)
|
||||
found = by_id(risk_series.nci_post_treatment(data, reference_risk.resolve(data, CUT), CUT))
|
||||
target = found["nci-post-treatment-general-CIN3+"]
|
||||
assert target["status"] == "resolved"
|
||||
row = next(r for r in read_workbook(risk_series.BOOKS / risk_series.POST_TREATMENT[0])
|
||||
if r["sheet"] == "Post Treatment 1 visit" and r["row"] == 8)
|
||||
estimate = next(e for e in row["estimates"] if e["outcome"] == "CIN3+"
|
||||
and e["horizon_years"] == 5)
|
||||
assert next(p for p in target["points"] if p["years"] == 5)["probability"] == estimate["value"]
|
||||
assert estimate["source"]["unit"] == "fraction"
|
||||
assert found["nci-post-treatment-general-CIN2+"]["reasons"] == [
|
||||
"outcome_or_estimate_not_published"]
|
||||
assert all(found[f"nci-post-treatment-{n}-CIN2+"]["status"] == "unresolved"
|
||||
for n in (24, 25, 26))
|
||||
|
||||
|
||||
def test_post_treatment_hsil_cannot_be_mapped_to_cin2_or_cin3():
|
||||
data = facts("HSIL", treated=True)
|
||||
found = risk_series.nci_post_treatment(data, reference_risk.resolve(data, CUT), CUT)
|
||||
assert all(s["status"] == "unresolved" and not s["points"] for s in found)
|
||||
|
||||
|
||||
def test_post_treatment_requires_a_documented_link_not_just_chronology():
|
||||
data = facts("LSIL", treated=True)
|
||||
del data["events"][-1]["biopsy_request_date"]
|
||||
found = risk_series.nci_post_treatment(data, reference_risk.resolve(data, CUT), CUT)
|
||||
general = [s for s in found if s["id"].startswith("nci-post-treatment-general")]
|
||||
assert all(s["reasons"] == ["treatment_biopsy_link_not_verified"] for s in general)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("visit_count", [2, 3])
|
||||
def test_post_treatment_negative_visits_match_book_23(visit_count):
|
||||
data = facts("normal", treated=True)
|
||||
data["cytologies"] = [data["cytologies"][0]] + [
|
||||
sample(f"2025-{month:02d}-01", "NILM", False) for month in range(4, 4 + visit_count)
|
||||
]
|
||||
found = by_id(risk_series.nci_post_treatment(data, reference_risk.resolve(data, CUT), CUT))
|
||||
target = found["nci-post-treatment-general-CIN3+"]
|
||||
assert target["status"] == "resolved"
|
||||
assert f"Post Treatment {visit_count} visits" in target["label"]
|
||||
|
||||
|
||||
def test_pending_biopsy_prevents_postcolposcopy_match():
|
||||
data = facts()
|
||||
data["biopsies"].append({"request_date": "2025-03-01", "report_date": None,
|
||||
"histology": None, "cytology_sample_date": "2025-01-01"})
|
||||
found = risk_series.nci_post_colposcopy(data, reference_risk.resolve(data, CUT), CUT)
|
||||
assert all(s["reasons"] == ["prior_biopsy_pending_at_index"] for s in found)
|
||||
@@ -0,0 +1,290 @@
|
||||
"""The NCI/ASCCP reference risks: the resource, the exact resolution, and the comparison. The facts are
|
||||
made-up fixtures (never patients); the numbers are the workbook's, checked against the NCI's files."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from core.cacu import reference_risk as ref
|
||||
|
||||
CUTOFF = date(2026, 12, 31)
|
||||
|
||||
|
||||
def cytology(day, result="NILM", hpv=False, h16=None, h18=None, reported=None, **more):
|
||||
return {"sample_date": day, "report_date": reported or day, "result": result, "adequacy": None,
|
||||
"hpv": hpv, "hpv_16": h16, "hpv_18": h18, **more} # fmt: skip
|
||||
|
||||
|
||||
def facts(*cytologies, birth="1980-01-01", biopsies=(), events=()):
|
||||
return {"birth_date": birth, "cytologies": list(cytologies), "biopsies": list(biopsies),
|
||||
"events": list(events)} # fmt: skip
|
||||
|
||||
|
||||
def risks(resolved):
|
||||
return {h["years"]: h["risk"] for h in resolved["horizons"]}
|
||||
|
||||
|
||||
# -- the resource --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_five_tables_are_read_whole_and_each_row_keeps_its_place_in_the_workbook():
|
||||
t = ref.tables()
|
||||
assert t["row_counts"] == {"screening": 68, "surveillance": 57, "colposcopy_results": 16,
|
||||
"post_colposcopy": 32, "post_treatment": 11} # fmt: skip
|
||||
assert len(t["rows"]) == 184 == sum(t["row_counts"].values())
|
||||
assert t["source"]["sha256"] == "91728862df7ee2c443775a0e3722d86eef7a639aa7a7f6af558277106c6c6016"
|
||||
assert t["status"].startswith("experimental")
|
||||
seen = {(r["sheet"], r["row"]) for r in t["rows"]}
|
||||
assert len(seen) == 184 # no row twice
|
||||
keys = [(r["table"], tuple(r["key"].items())) for r in t["rows"]]
|
||||
assert len(set(keys)) == 184 # no clinical key twice
|
||||
|
||||
|
||||
def test_horizons_are_those_each_sheet_publishes_and_the_colposcopy_sheet_has_no_immediate_risk():
|
||||
t = ref.tables()
|
||||
by_table = {r["table"]: sorted(r["risks"], key=int) for r in t["rows"]}
|
||||
assert by_table == {"screening": ["0", "5"], "surveillance": ["0", "5"], "colposcopy_results": ["1", "5"],
|
||||
"post_colposcopy": ["0", "5"], "post_treatment": ["0", "5"]} # fmt: skip
|
||||
assert t["horizons_years"]["colposcopy_results"] == [1, 5]
|
||||
|
||||
|
||||
def test_zero_is_a_value_and_a_blank_cell_is_not():
|
||||
rows = {(r["sheet"][0], r["row"]): r for r in ref.tables()["rows"]}
|
||||
zero = rows[("1", 2)] # no history, HPV-negative, NILM: 0 % immediate, 0.12 % at five years
|
||||
assert zero["risks"] == {"0": 0.0, "5": 0.0012} and zero["published"]
|
||||
blank = rows[("1", 15)]
|
||||
assert blank["risks"] == {"0": None, "5": None} and not blank["published"]
|
||||
assert rows[("3", 14)]["risks"] == {"1": None, "5": None} # CIN2 after colposcopy: no risk published
|
||||
|
||||
|
||||
def test_values_match_the_nci_files_row_by_row_and_the_exceptions_are_known():
|
||||
from collections import Counter
|
||||
|
||||
verdicts = Counter(r["official_check"] for r in ref.tables()["rows"])
|
||||
assert verdicts == {"match": 166, "match_within_0.01": 4, "not_found_in_official": 13, "differs": 1}
|
||||
by = {(r["sheet"][0], r["row"]): r for r in ref.tables()["rows"]}
|
||||
for place in (("1", 2), ("1", 21), ("1", 49), ("3", 2), ("4", 13)):
|
||||
assert by[place]["official_check"] == "match"
|
||||
assert ref.tables()["official_comparison"]["files"]["screening"]["modified"].startswith("2025-01-15")
|
||||
|
||||
|
||||
# -- resolution ------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_cotest_negative_history_and_a_current_cotest_resolve_to_one_exact_row():
|
||||
found = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", "ASC-US", hpv=False)),
|
||||
CUTOFF) # fmt: skip
|
||||
assert found["status"] == "resolved" and found["matched_via"] == "exact"
|
||||
assert found["scenario"]["key"] == {"history": "Cotest-negative", "hpv": "HPV-negative",
|
||||
"cytology": "ASC-US"} # fmt: skip
|
||||
assert risks(found) == {0: 0.0001, 5: 0.0027}
|
||||
assert found["row"]["sheet"] == "1 - Screening" and found["row"]["row"] == 50
|
||||
assert found["row"]["official_check"] == "match"
|
||||
assert [u["label"] for u in found["used"]] == ["earlier cotest", "current cotest"]
|
||||
|
||||
|
||||
def test_a_real_zero_is_a_risk_of_zero_not_an_absence():
|
||||
found = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", "NILM")), CUTOFF)
|
||||
assert found["status"] == "resolved"
|
||||
assert risks(found)[0] == 0.0 and found["horizons"][0]["published"] is True
|
||||
assert risks(found)[5] == 0.0008
|
||||
|
||||
|
||||
def test_genotypes_follow_the_tables_hierarchy_and_other_positives_are_not_guessed():
|
||||
back = cytology("2023-03-01")
|
||||
sixteen = ref.resolve(facts(back, cytology("2026-03-01", "NILM", True, True, False)), CUTOFF)
|
||||
assert sixteen["status"] == "resolved" and sixteen["scenario"]["key"]["hpv"] == "HPV16+"
|
||||
eighteen = ref.resolve(facts(back, cytology("2026-03-01", "NILM", True, False, True)), CUTOFF)
|
||||
assert eighteen["scenario"]["key"]["hpv"] == "HPV16-, HPV18+"
|
||||
other = ref.resolve(facts(back, cytology("2026-03-01", "NILM", True, False, False)), CUTOFF)
|
||||
assert (other["status"], other["reasons"]) == ("unverifiable_correspondence", ["hpv_positive_row"])
|
||||
assert other["horizons"] == [] and other["assumptions"]
|
||||
unknown = ref.resolve(facts(back, cytology("2026-03-01", "NILM", True)), CUTOFF)
|
||||
assert unknown["reasons"] == ["hpv_positive_row"] # genotypes not reported: not an HPV-negative nor 16/18
|
||||
clash = ref.resolve(facts(back, cytology("2026-03-01", "NILM", False, True)), CUTOFF)
|
||||
assert clash["status"] == "contradictory"
|
||||
|
||||
|
||||
def test_a_high_grade_result_uses_the_tables_own_group_only_where_the_table_has_no_row_for_it():
|
||||
back = cytology("2023-03-01")
|
||||
found = ref.resolve(facts(back, cytology("2026-03-01", "HSIL", True, True, False)), CUTOFF)
|
||||
assert found["status"] == "resolved" and found["matched_via"] == "table_group"
|
||||
assert found["row"]["row"] == 65 and found["scenario"]["key"]["cytology"] == "HSIL+"
|
||||
exact = ref.resolve(facts(back, cytology("2026-03-01", "HSIL", False)), CUTOFF)
|
||||
assert exact["matched_via"] == "exact" and exact["row"]["row"] == 54 # a HSIL+ row exists: no group
|
||||
|
||||
|
||||
def test_no_history_is_not_proven_by_an_empty_record_nor_by_a_declared_first_screening():
|
||||
alone = ref.resolve(facts(cytology("2026-03-01", "NILM", screening_history="never")), CUTOFF)
|
||||
assert (alone["status"], alone["reasons"]) == ("history_not_demonstrable", ["no_earlier_test_registered"])
|
||||
old = ref.resolve(facts(cytology("2018-01-01"), cytology("2026-03-01")), CUTOFF)
|
||||
assert old["reasons"] == ["earlier_test_older_than_5_years"]
|
||||
only_cytology = ref.resolve(facts({**cytology("2023-03-01"), "hpv": None}, cytology("2026-03-01")), CUTOFF)
|
||||
assert only_cytology["status"] == "history_not_demonstrable" # an earlier cytology without HPV is no cotest
|
||||
|
||||
|
||||
def test_insufficient_data_missing_hpv_age_and_registered_exclusions():
|
||||
assert ref.resolve(facts(), CUTOFF)["status"] == "missing_data"
|
||||
no_hpv = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", hpv=None)), CUTOFF)
|
||||
assert (no_hpv["status"], no_hpv["reasons"]) == ("missing_data", ["missing_hpv"])
|
||||
young = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01"), birth="2005-01-01"), CUTOFF)
|
||||
assert (young["status"], young["reasons"]) == ("not_applicable", ["age_outside_25_65"])
|
||||
assert ref.resolve(facts(cytology("2026-03-01"), birth=None), CUTOFF)["status"] == "missing_data"
|
||||
cin2 = {"request_date": "2025-01-01", "report_date": "2025-02-01", "histology": "HSIL", "cytology_sample_date": None}
|
||||
prior = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01"), biopsies=[cin2]), CUTOFF)
|
||||
assert prior["status"] == "scenario_not_implemented" # a colposcopy was before: not the screening table
|
||||
declared = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", gynecologic_condition="hysterectomy")), CUTOFF)
|
||||
assert declared["reasons"] == ["hysterectomy_declared"]
|
||||
|
||||
|
||||
def test_other_histories_and_scenarios_are_named_not_approximated():
|
||||
abnormal = ref.resolve(facts(cytology("2023-03-01", "LSIL", False), cytology("2026-03-01")), CUTOFF)
|
||||
assert (abnormal["status"], abnormal["reasons"]) == ("scenario_not_implemented", ["history_is_a_surveillance_scenario"])
|
||||
twice = ref.resolve(facts(cytology("2021-03-01", "NILM", True), cytology("2023-03-01"), cytology("2026-03-01")), CUTOFF)
|
||||
assert twice["reasons"] == ["history_is_a_surveillance_scenario"] # the test before the last was HPV-positive
|
||||
unlisted = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", "ASC-US", True, True, False)), CUTOFF)
|
||||
assert unlisted["status"] == "resolved" # HPV16+ and ASC-US is a published row
|
||||
|
||||
|
||||
def test_nothing_after_the_cutoff_is_used():
|
||||
late = facts(cytology("2023-03-01"), cytology("2026-03-01", "ASC-US", reported="2026-04-01"))
|
||||
before = ref.resolve(late, date(2026, 3, 15))
|
||||
assert before["index"]["sample_date"] == date(2023, 3, 1) # the later result was not reported yet
|
||||
assert before["status"] == "history_not_demonstrable"
|
||||
after = ref.resolve(late, date(2026, 4, 1))
|
||||
assert after["index"]["sample_date"] == date(2026, 3, 1) and after["status"] == "resolved"
|
||||
asked = ref.resolve(late, date(2026, 3, 15), sample=date(2026, 3, 1))
|
||||
assert (asked["status"], asked["reasons"]) == ("missing_data", ["sample_not_reported_by_cutoff"])
|
||||
# a biopsy reported after the cut-off is not a referral result yet: the cytology is still a screening one
|
||||
biopsy = {"request_date": "2026-04-05", "report_date": "2026-04-20", "histology": "normal", "cytology_sample_date": "2026-03-01"}
|
||||
early = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01"), biopsies=[biopsy]), date(2026, 4, 10))
|
||||
assert early["status"] == "unverifiable_correspondence" # requested before the cut-off, not reported: no result to use
|
||||
|
||||
|
||||
# -- colposcopy results ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def referral(histology, **more):
|
||||
return {"request_date": "2026-03-20", "report_date": "2026-04-05", "histology": histology,
|
||||
"cytology_sample_date": "2026-03-01", **more} # fmt: skip
|
||||
|
||||
|
||||
def test_a_biopsy_that_names_its_cytology_gives_the_one_and_five_year_risks_not_an_immediate_one():
|
||||
base = facts(cytology("2026-03-01", "ASC-H", False), biopsies=[referral("LSIL")])
|
||||
found = ref.resolve(base, CUTOFF)
|
||||
assert found["status"] == "resolved"
|
||||
assert found["scenario"]["key"] == {"referral": "ASC-H", "biopsy": "CIN1"}
|
||||
assert risks(found) == {1: 0.0136, 5: 0.0557} and "0" not in {str(h["years"]) for h in found["horizons"]}
|
||||
assert found["evaluation_date"] == date(2026, 4, 5)
|
||||
pos = ref.resolve(facts(cytology("2026-03-01", "ASC-US", True), biopsies=[referral("normal")]), CUTOFF)
|
||||
assert pos["scenario"]["key"] == {"referral": "HPV-positive ASC-US", "biopsy": "<CIN1"}
|
||||
assert risks(pos) == {1: 0.0049, 5: 0.0318}
|
||||
|
||||
|
||||
def test_a_referral_needs_its_hpv_two_consecutive_positives_for_nilm_and_a_histology_the_tables_can_tell():
|
||||
nilm = facts(cytology("2025-03-01", "NILM", True), cytology("2026-03-01", "NILM", True), biopsies=[referral("normal")])
|
||||
assert ref.resolve(nilm, CUTOFF)["scenario"]["key"]["referral"] == "HPV-positive NILM x2"
|
||||
once = facts(cytology("2026-03-01", "NILM", True), biopsies=[referral("normal")])
|
||||
assert ref.resolve(once, CUTOFF)["status"] == "no_published_row"
|
||||
unknown = facts(cytology("2026-03-01", "LSIL", None), biopsies=[referral("normal")])
|
||||
assert ref.resolve(unknown, CUTOFF)["reasons"] == ["missing_hpv"]
|
||||
hsil = ref.resolve(facts(cytology("2026-03-01", "ASC-H", False), biopsies=[referral("HSIL")]), CUTOFF)
|
||||
assert (hsil["status"], hsil["reasons"]) == ("unverifiable_correspondence", ["hsil_cin2_cin3"])
|
||||
cancer = ref.resolve(facts(cytology("2026-03-01", "ASC-H", False), biopsies=[referral("carcinoma")]), CUTOFF)
|
||||
assert (cancer["status"], cancer["reasons"]) == ("not_published", ["risk_blank_in_the_tables"])
|
||||
assert [h["risk"] for h in cancer["horizons"]] == [None, None]
|
||||
twice = facts(cytology("2026-03-01", "ASC-H", False), biopsies=[referral("normal"), referral("LSIL", request_date="2026-03-25")])
|
||||
assert ref.resolve(twice, CUTOFF)["status"] == "ambiguous"
|
||||
|
||||
|
||||
def test_a_procedure_the_records_do_not_tie_to_the_cytology_is_not_a_confirmed_referral():
|
||||
loose = referral("normal", cytology_sample_date=None)
|
||||
found = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", "ASC-H", False), biopsies=[loose]), CUTOFF)
|
||||
assert (found["status"], found["reasons"]) == ("unverifiable_correspondence", ["procedure_after_without_named_referral"])
|
||||
inferred = facts(cytology("2023-03-01"), cytology("2026-03-01"), events=[{"type": "colposcopy", "date": "2026-03-20"}])
|
||||
assert ref.resolve(inferred, CUTOFF)["status"] == "unverifiable_correspondence"
|
||||
|
||||
|
||||
# -- comparison ------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def assessment(model, years=(0, 5), index="2026-03-01", p=0.1):
|
||||
return {"model": model, "title": model, "index_date": index,
|
||||
"predictions": [{"years": y, "p": p, "low": p - 0.02, "high": p + 0.02} for y in years]} # fmt: skip
|
||||
|
||||
|
||||
def resolved():
|
||||
return ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", "ASC-US")), CUTOFF)
|
||||
|
||||
|
||||
def test_no_institutional_model_leaves_the_reference_alone():
|
||||
found = ref.compare(resolved(), [])
|
||||
assert [(c["years"], c["reference"], c["status"], c["institutional"]) for c in found] == [
|
||||
(0, 0.0001, "not_comparable", None), (5, 0.0027, "not_comparable", None)] # fmt: skip
|
||||
assert all(c["reasons"] == ["no_institutional_model"] for c in found)
|
||||
|
||||
|
||||
def test_a_model_of_another_outcome_horizon_or_index_is_not_compared_and_no_difference_is_made_up():
|
||||
why = lambda model, **kw: [c["reasons"] for c in ref.compare(resolved(), [assessment(model, **kw)])] # noqa: E731
|
||||
assert why("cacu.cin2_pim")[0] == ["outcome_differs", "population_not_verified"]
|
||||
assert why("cacu.cancer_pim")[1] == ["outcome_differs", "population_not_verified"]
|
||||
assert why("cacu.cin2_pim", years=(1, 3)) == [
|
||||
["outcome_differs", "horizon_not_published_by_model", "population_not_verified"]] * 2
|
||||
assert why("cacu.cin2_pim", index="2025-01-01")[0][1] == "index_date_differs"
|
||||
assert why("cacu.unknown")[0][0] == "unknown_model"
|
||||
assert all(c["difference_pp"] is None for c in ref.compare(resolved(), [assessment("cacu.cin2_pim")]))
|
||||
|
||||
|
||||
def test_a_one_year_prediction_is_never_set_against_the_immediate_risk():
|
||||
registry = {"fixture.cin3": {"outcome": "CIN3+", "population_verified": True}}
|
||||
found = ref.compare(resolved(), [assessment("fixture.cin3", years=(1, 5))], registry)
|
||||
immediate, five = found
|
||||
assert immediate["years"] == 0 and immediate["status"] == "not_comparable"
|
||||
assert immediate["reasons"] == ["horizon_not_published_by_model"]
|
||||
assert five["status"] == "comparable"
|
||||
|
||||
|
||||
def test_the_difference_is_institutional_minus_reference_in_points_and_only_with_a_verified_equivalence():
|
||||
registry = {"fixture.cin3": {"outcome": "CIN3+", "population_verified": True}}
|
||||
found = ref.compare(resolved(), [assessment("fixture.cin3", p=0.0127)], registry)
|
||||
five = found[1]
|
||||
assert five["status"] == "comparable" and five["reference"] == 0.0027
|
||||
assert five["difference_pp"] == pytest.approx(1.0) # (1.27 % - 0.27 %)
|
||||
assert found[0]["difference_pp"] == pytest.approx(1.26) # (1.27 % - the immediate reference 0.01 %)
|
||||
low = ref.compare(resolved(), [assessment("fixture.cin3", p=0.0)], registry)[1]
|
||||
assert low["difference_pp"] == pytest.approx(-0.27)
|
||||
# the same estimate with the model's real registry entry: never comparable
|
||||
real = ref.compare(resolved(), [assessment("cacu.cin2_pim")])
|
||||
assert all(c["status"] == "not_comparable" for c in real)
|
||||
assert set(ref.MODELS) >= {"cacu.cin2_pim", "cacu.cancer_pim", "cacu.cin2_logistic"}
|
||||
assert all(not m.get("population_verified") for m in ref.MODELS.values())
|
||||
|
||||
|
||||
# -- the FHIR result -------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def parts(parameters, name):
|
||||
return [p for p in parameters.parameter if p.name == name]
|
||||
|
||||
|
||||
def test_the_parameters_carry_the_state_the_trace_and_a_zero_as_a_zero_but_no_value_for_a_blank():
|
||||
from core import fhir
|
||||
|
||||
found = ref.resolve(facts(cytology("2023-03-01"), cytology("2026-03-01", "NILM")), CUTOFF)
|
||||
made = fhir.reference_risk(found, ref.compare(found, []), ref.tables())
|
||||
assert parts(made, "status")[0].valueCode == "resolved"
|
||||
assert parts(made, "experimental")[0].valueBoolean is True
|
||||
assert parts(made, "source")[0].part[1].valueString == "Master_NCI_Risk_Table.xlsx"
|
||||
horizons = parts(made, "horizon")
|
||||
assert [next(x for x in h.part if x.name == "years").valueInteger for h in horizons] == [0, 5]
|
||||
immediate = {x.name: x for x in horizons[0].part}
|
||||
assert immediate["reference"].valueDecimal == 0 and immediate["published"].valueBoolean is True
|
||||
assert [x.name for x in horizons[0].part if x.name == "comparison"] == ["comparison"] # no model: said so
|
||||
blank = ref.resolve(facts(cytology("2026-03-01", "ASC-H", False), biopsies=[referral("carcinoma")]), CUTOFF)
|
||||
made = fhir.reference_risk(blank, [], ref.tables())
|
||||
assert parts(made, "status")[0].valueCode == "not_published"
|
||||
assert all(x.name != "reference" for h in parts(made, "horizon") for x in h.part)
|
||||
gone = ref.resolve(facts(), CUTOFF)
|
||||
made = fhir.reference_risk(gone, [], ref.tables())
|
||||
assert parts(made, "horizon") == [] and parts(made, "reason")[0].valueCode == "no_cytology_reported_by_cutoff"
|
||||
assert parts(made, "scenario") == [] and parts(made, "row") == []
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Which model risks still apply after a diagnosis or a treatment (issue 30)."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.currency import current, withheld
|
||||
|
||||
MODELS = ["cacu.cin2_pim", "cacu.cancer_pim", "cacu.cin2_pim_post_treatment", "cacu.survival"]
|
||||
RISKS = [{"model": m, "index_date": "2025-06-01"} for m in MODELS]
|
||||
|
||||
|
||||
def _kept(history, cutoff=date(2026, 1, 1)):
|
||||
return {r["model"] for r in current(RISKS, history, cutoff)}
|
||||
|
||||
|
||||
def _biopsy(day, value):
|
||||
return {"date": day, "type": "biopsy", "value_code": value}
|
||||
|
||||
|
||||
def _treatment(day):
|
||||
return {"date": day, "type": "treatment", "value_code": None}
|
||||
|
||||
|
||||
def test_risks_by_what_happened_by_the_cut_off():
|
||||
assert _kept([]) == set(MODELS)
|
||||
assert _kept([_biopsy("2025-07-01", "LSIL")]) == set(MODELS)
|
||||
assert _kept([_biopsy("2025-07-01", "HSIL")]) == {"cacu.survival"}
|
||||
assert _kept([_biopsy("2025-07-01", "CIS"), _treatment("2025-08-01")]) == {"cacu.survival"}
|
||||
# after the cut-off it is not known yet; on the cut-off day it is
|
||||
assert _kept([_biopsy("2026-01-02", "HSIL")]) == set(MODELS)
|
||||
assert _kept([_biopsy("2026-01-01", "HSIL")]) == {"cacu.survival"}
|
||||
|
||||
|
||||
def test_a_treated_patient_keeps_only_a_post_treatment_estimate_made_after_it():
|
||||
after = {"cacu.cin2_pim_post_treatment", "cacu.survival"}
|
||||
assert _kept([_biopsy("2025-01-01", "HSIL"), _treatment("2025-02-01")]) == after
|
||||
assert _kept([_treatment("2025-02-01")]) == after # a low-grade lesion treated
|
||||
assert _kept([_treatment("2025-07-01")]) == {"cacu.survival"} # estimate older than it
|
||||
# a high-grade lesion again after the treatment
|
||||
assert _kept([_treatment("2025-02-01"), _biopsy("2025-09-01", "HSIL")]) == {"cacu.survival"}
|
||||
|
||||
|
||||
def test_the_reason_names_what_happened_and_its_day():
|
||||
assert withheld([], date(2026, 1, 1))[2] is None
|
||||
assert "2025-07-01" in withheld([_biopsy("2025-07-01", "HSIL")], date(2026, 1, 1))[2]
|
||||
@@ -0,0 +1,49 @@
|
||||
"""The selectable risk series: matched by the platform's data, never invented."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core import fhir
|
||||
from core.cacu import reference_risk as reference
|
||||
from core.cacu import risk_series
|
||||
|
||||
CUT = date(2026, 1, 1)
|
||||
|
||||
|
||||
def _cytology(day, result="NILM", hpv=1):
|
||||
return {"sample_date": day, "report_date": day, "result": result, "adequacy": None,
|
||||
"hpv": hpv, "hpv_16": None, "hpv_18": None, "gynecologic_condition": None} # fmt: skip
|
||||
|
||||
|
||||
def _find(cytologies):
|
||||
facts = {"birth_date": "1985-01-01", "cytologies": cytologies, "biopsies": [], "events": []}
|
||||
resolution = reference.resolve(facts, CUT)
|
||||
return risk_series.series(facts, resolution, [], CUT, str)
|
||||
|
||||
|
||||
def test_enrollment_series_carry_intervals_and_their_assumption():
|
||||
found = {s["id"]: s for s in _find([_cytology("2025-06-01", "NILM", 0)])}
|
||||
for outcome in ("CIN2+", "CIN3+", "cancer"):
|
||||
series = found[f"nci-enrollment-{outcome}"]
|
||||
assert series["status"] == "resolved" and series["assumptions"]
|
||||
assert series["label"] == "VPH: HPV-negative · Citología: NILM"
|
||||
assert all(p["low"] <= p["probability"] <= p["high"] for p in series["points"])
|
||||
|
||||
|
||||
def test_a_registered_history_leaves_the_enrollment_series_without_a_number():
|
||||
found = _find([_cytology("2024-06-01"), _cytology("2025-06-01")])
|
||||
mine = [s for s in found if s["id"].startswith("nci-enrollment")]
|
||||
assert mine and all(s["status"] == "unresolved" and not s["points"] and s["reasons"]
|
||||
for s in mine) # fmt: skip
|
||||
|
||||
|
||||
def test_institutional_series_take_the_latest_index_and_serialize():
|
||||
risks = [{"model": model, "version": 2, "index_date": day, "horizon_years": 5,
|
||||
"probability": p, "ci_low": None, "ci_high": None}
|
||||
for model, day, p in (("cacu.cin2_pim", "2024-01-01", 0.5),
|
||||
("cacu.cin2_pim", "2025-01-01", 0.123456),
|
||||
("cacu.survival", "2025-01-01", 0.9))] # fmt: skip
|
||||
(series,) = risk_series.institutional(risks, CUT, str)
|
||||
assert (series["outcome"], series["points"][0]["probability"]) == ("CIN2+", 0.123456)
|
||||
assert series["points"][0]["level"] is None
|
||||
body = fhir.risk_series([series], "p", CUT).model_dump_json()
|
||||
assert "0.123456" in body
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Second-visit features over the gold timeline, including a single-patient read."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from pandas import isna
|
||||
from pandas.testing import assert_frame_equal
|
||||
|
||||
from core import fhir
|
||||
from persistance import destination, gold, silver
|
||||
|
||||
|
||||
def test_second_visit_features_use_the_two_samples_from_each_scenario(tmp_path, monkeypatch):
|
||||
"""Pins sample IDs, biopsy eligibility, age and hysterectomy exclusions, and reader parity."""
|
||||
monkeypatch.setenv("ISSSTELEON_DATA", str(tmp_path))
|
||||
monkeypatch.setenv("PLATFORM_DATABASE_URL", f"sqlite:///{tmp_path / 'platform.db'}")
|
||||
monkeypatch.setenv("DBT_TARGET", "sqlite")
|
||||
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
|
||||
destination.engine.cache_clear()
|
||||
engine = destination.engine()
|
||||
|
||||
def sample(day, report, appearance, result, hpv, person="p1"):
|
||||
return [
|
||||
(person, day, "cytology", "satisfactory", "cervical_cytology", day),
|
||||
(person, day, "cervix_appearance", appearance, "cervical_cytology", day),
|
||||
(person, report, "bethesda", result, "cervical_cytology", day),
|
||||
(person, report, "hpv", hpv, "cervical_cytology", day),
|
||||
]
|
||||
|
||||
def after_colposcopy(person, biopsy):
|
||||
return [
|
||||
*sample("2025-01-10", "2025-01-15", "lesion", "LSIL", "positive", person),
|
||||
(person, "2025-03-10", "colposcopy", None, "clinical_note", "note-1"),
|
||||
(person, "2025-03-10", "biopsy_order", None, "cervical_biopsy", "order-1"),
|
||||
*(
|
||||
[(person, "2025-03-15", "biopsy", biopsy, "cervical_biopsy", "order-1")]
|
||||
if biopsy
|
||||
else []
|
||||
),
|
||||
*sample("2025-04-10", "2025-04-15", "lesion", "ASC-US", "positive", person),
|
||||
*sample("2025-05-10", "2025-05-15", "healthy", "NILM", "negative", person),
|
||||
]
|
||||
|
||||
def both_scenarios(person):
|
||||
return [
|
||||
*after_colposcopy(person, "normal"),
|
||||
*sample("2025-02-10", "2025-02-15", "healthy", "NILM", "negative", person),
|
||||
]
|
||||
|
||||
def hysterectomy(person, day):
|
||||
return (person, day, "gynecologic_condition", "hysterectomy", "cervical_cytology", day)
|
||||
|
||||
try:
|
||||
with engine.begin() as con:
|
||||
con.exec_driver_sql("create table silver.person (person_id text)")
|
||||
con.exec_driver_sql("insert into silver.person values ('p7')")
|
||||
con.exec_driver_sql(
|
||||
"create table gold.cacu_events (person_id text, date date, type text, "
|
||||
"value_code text, source_table text, source_id text, evidence_date date, "
|
||||
"source_available_at text, source_ref text)"
|
||||
)
|
||||
con.exec_driver_sql(
|
||||
"insert into gold.cacu_events "
|
||||
"(person_id, date, type, value_code, source_table, source_id) "
|
||||
"values (?, ?, ?, ?, ?, ?)",
|
||||
[
|
||||
*sample("2025-01-10", "2025-01-15", "lesion", "LSIL", "positive"),
|
||||
*sample("2025-02-10", "2025-02-15", "healthy", "NILM", "negative"),
|
||||
("p1", "2025-01-15", "hpv_16", "positive", "cervical_cytology", "2025-01-10"),
|
||||
("p1", "2025-01-15", "hpv_18", "negative", "cervical_cytology", "2025-01-10"),
|
||||
("p1", "2025-02-15", "hpv_18", "negative", "cervical_cytology", "2025-02-10"),
|
||||
("p1", "2025-03-10", "colposcopy", None, "clinical_note", "note-1"),
|
||||
hysterectomy("p1", "2025-03-20"),
|
||||
*sample("2025-04-10", "2025-06-15", "lesion", "ASC-US", "positive"),
|
||||
*sample("2025-05-10", "2025-05-15", "healthy", "NILM", "negative"),
|
||||
*sample("2025-07-10", "2025-07-15", "not_seen", "ASC-H", "positive"),
|
||||
("p2", "2025-02-10", "cytology", "satisfactory", "cervical_cytology", "p2-1"),
|
||||
("p2", "2025-02-20", "biopsy_order", None, "cervical_biopsy", "p2-order"),
|
||||
("p2", "2025-03-10", "cytology", "satisfactory", "cervical_cytology", "p2-2"),
|
||||
("p2", "2025-03-15", "bethesda", "NILM", "cervical_cytology", "p2-2"),
|
||||
*after_colposcopy("p3", "normal"),
|
||||
*after_colposcopy("p4", "HSIL"),
|
||||
*after_colposcopy("p5", "carcinoma"),
|
||||
*after_colposcopy("p6", None),
|
||||
*both_scenarios("p7"),
|
||||
hysterectomy("p7", "2025-01-09"),
|
||||
hysterectomy("p10", "2025-02-10"),
|
||||
("p7", "2025-06-01", "treatment", None, "clinical_note", "note-2"),
|
||||
("p7", "2025-06-05", "biopsy", "carcinoma", "cervical_biopsy", "order-2"),
|
||||
*sample("2025-10-05", "2025-10-10", "healthy", "NILM", "negative", "p7"),
|
||||
*both_scenarios("p8"),
|
||||
("p8", "2007-05-11", "birth", None, "person", "p8"),
|
||||
*both_scenarios("p9"),
|
||||
("p9", "2007-02-10", "birth", None, "person", "p9"),
|
||||
hysterectomy("p9", "2025-07-10"),
|
||||
(
|
||||
"p11", "2025-01-10", "cytology", "satisfactory",
|
||||
"cervical_cytology", "2025-01-10",
|
||||
),
|
||||
("p11", "2025-01-15", "bethesda", "LSIL", "cervical_cytology", "2025-01-10"),
|
||||
("p11", "2025-01-15", "hpv", "positive", "cervical_cytology", "2025-01-10"),
|
||||
("p11", "2025-03-10", "colposcopy", None, "clinical_note", "note-11"),
|
||||
("p11", "2025-03-10", "biopsy_order", None, "cervical_biopsy", "order-11"),
|
||||
("p11", "2025-03-15", "biopsy", "normal", "cervical_biopsy", "order-11"),
|
||||
(
|
||||
"p11", "2025-04-10", "cytology", "satisfactory",
|
||||
"cervical_cytology", "2025-04-10",
|
||||
),
|
||||
(
|
||||
"p11", "2025-04-10", "cervix_appearance", "lesion",
|
||||
"cervical_cytology", "2025-04-10",
|
||||
),
|
||||
("p11", "2025-06-15", "bethesda", "ASC-US", "cervical_cytology", "2025-04-10"),
|
||||
("p11", "2025-06-15", "hpv", "positive", "cervical_cytology", "2025-04-10"),
|
||||
(
|
||||
"p11", "2025-05-10", "cytology", "satisfactory",
|
||||
"cervical_cytology", "2025-05-10",
|
||||
),
|
||||
(
|
||||
"p11", "2025-05-10", "cervix_appearance", "healthy",
|
||||
"cervical_cytology", "2025-05-10",
|
||||
),
|
||||
("p11", "2025-05-15", "bethesda", "NILM", "cervical_cytology", "2025-05-10"),
|
||||
("p11", "2025-05-15", "hpv", "negative", "cervical_cytology", "2025-05-10"),
|
||||
("p10", "2025-02-10", "cytology", "satisfactory", "cervical_cytology", "p10-2"),
|
||||
("p10", "2025-02-10", "cytology", "satisfactory", "cervical_cytology", "p10-1"),
|
||||
("p10", "2025-02-15", "bethesda", "NILM", "cervical_cytology", "p10-2"),
|
||||
],
|
||||
)
|
||||
con.exec_driver_sql(
|
||||
"update gold.cacu_events set evidence_date = date, source_available_at = date "
|
||||
"where type = 'gynecologic_condition' and value_code = 'hysterectomy'"
|
||||
)
|
||||
|
||||
silver.build(
|
||||
[
|
||||
"cacu_second_visit_features",
|
||||
"cacu_cohort_surveillance",
|
||||
"cacu_cohort_post_colposcopy",
|
||||
"cacu_cohort_post_treatment",
|
||||
"cacu_cohort_survival",
|
||||
"cacu_follow_up",
|
||||
],
|
||||
as_of=date(2025, 11, 1),
|
||||
)
|
||||
pre = gold.cacu_second_visit_features("pre_colposcopy")
|
||||
post = gold.cacu_second_visit_features("post_colposcopy")
|
||||
assert pre["person_id"].tolist() == ["p1", "p10", "p2", "p9"]
|
||||
assert post["person_id"].tolist() == ["p11", "p3", "p6", "p9"]
|
||||
assert tuple(pre.loc[0, ["previous_sample_id", "index_sample_id"]]) == (
|
||||
"2025-01-10",
|
||||
"2025-02-10",
|
||||
)
|
||||
same_day = pre.loc[pre["person_id"] == "p10"].iloc[0]
|
||||
assert str(same_day["previous_date"]) == str(same_day["index_date"]) == "2025-02-10"
|
||||
assert (same_day["previous_sample_id"], same_day["index_sample_id"]) == ("p10-1", "p10-2")
|
||||
assert tuple(
|
||||
post.loc[
|
||||
post["person_id"] == "p3", ["previous_sample_id", "index_sample_id"]
|
||||
].iloc[0]
|
||||
) == (
|
||||
"2025-04-10",
|
||||
"2025-05-10",
|
||||
)
|
||||
assert tuple(pre.loc[0, ["previous_cervix_appearance", "index_cervix_appearance"]]) == (
|
||||
"lesion",
|
||||
"healthy",
|
||||
)
|
||||
assert pre.loc[0, "previous_bethesda"] == "LSIL"
|
||||
predictors = ["index_hpv_18", "previous_hpv_16", "index_hpv_16", "previous_hpv_18"]
|
||||
selected = gold.cacu_second_visit_features("pre_colposcopy", "p1", predictors=predictors)
|
||||
assert list(selected.columns) == [*gold.SECOND_VISIT_KEYS, *predictors]
|
||||
assert selected.loc[0, predictors].tolist() == ["negative", "positive", None, "negative"]
|
||||
with pytest.raises(ValueError, match="Unknown CaCu predictors"):
|
||||
gold.cacu_second_visit_features("pre_colposcopy", predictors=["unknown"])
|
||||
p11_post = post.loc[post["person_id"] == "p11"].iloc[0]
|
||||
assert p11_post["previous_cervix_appearance"] == "lesion"
|
||||
assert isna(p11_post["previous_bethesda"])
|
||||
assert p11_post["index_hpv"] == "negative"
|
||||
assert str(p11_post["index_result_date"]) == "2025-05-15"
|
||||
assert_frame_equal(
|
||||
post.loc[post["person_id"] == "p3"].reset_index(drop=True),
|
||||
gold.cacu_second_visit_features("post_colposcopy", "p3"),
|
||||
)
|
||||
p1_before_evidence = gold.cacu_second_visit_features(
|
||||
"pre_colposcopy", "p1", include_excluded=True
|
||||
)
|
||||
p1_after_evidence = gold.cacu_second_visit_features(
|
||||
"post_colposcopy", "p1", include_excluded=True
|
||||
)
|
||||
assert isna(p1_before_evidence.iloc[0]["excluded_by"])
|
||||
assert p1_after_evidence.iloc[0]["excluded_by"] == "hysterectomy"
|
||||
for scenario in ("pre_colposcopy", "post_colposcopy"):
|
||||
for person, reason in (("p7", "hysterectomy"), ("p8", "under_18")):
|
||||
row = gold.cacu_second_visit_features(scenario, person, include_excluded=True)
|
||||
assert row.loc[0, "excluded_by"] == reason
|
||||
assert row.loc[0, "index_hpv"] is None
|
||||
with engine.connect() as con:
|
||||
for cohort, first_index in (
|
||||
("cacu_cohort_surveillance", "2025-01-10"),
|
||||
("cacu_cohort_post_colposcopy", "2025-04-10"),
|
||||
):
|
||||
index = con.exec_driver_sql(
|
||||
f"select index_date from gold.{cohort} where person_id = 'p1'"
|
||||
).scalar_one()
|
||||
assert str(index) == first_index
|
||||
pending = con.exec_driver_sql(
|
||||
"select excluded_by from gold.cacu_cohort_post_colposcopy where person_id = 'p6'"
|
||||
).scalar_one()
|
||||
assert pending == "unreported_biopsy"
|
||||
same_day_hysterectomy = con.exec_driver_sql(
|
||||
"select excluded_by from gold.cacu_cohort_surveillance where person_id = 'p10'"
|
||||
).scalar_one()
|
||||
assert same_day_hysterectomy != "hysterectomy"
|
||||
for cohort in ("surveillance", "post_colposcopy", "post_treatment", "survival"):
|
||||
reason = con.exec_driver_sql(
|
||||
f"select excluded_by from gold.cacu_cohort_{cohort} where person_id = 'p7'"
|
||||
).scalar_one()
|
||||
assert reason == "hysterectomy"
|
||||
row = (
|
||||
con.exec_driver_sql("select * from gold.cacu_follow_up where person_id = 'p7'")
|
||||
.mappings()
|
||||
.one()
|
||||
)
|
||||
(recorded,) = fhir.patient(row).extension
|
||||
assert recorded.url.endswith("/first-hysterectomy-recorded")
|
||||
assert str(recorded.valueDate) == "2025-01-09"
|
||||
finally:
|
||||
engine.dispose()
|
||||
destination.engine.cache_clear()
|
||||
@@ -0,0 +1,80 @@
|
||||
"""The stages of a cytology's route: what gold demonstrates of each, and where it comes from."""
|
||||
|
||||
from core import fhir
|
||||
from core.cacu.stages import stage_facts
|
||||
|
||||
ROUTE = {
|
||||
"colposcopy": "2026-02-01", "colposcopy_note": 1, "colposcopy_biopsy": 0,
|
||||
"diagnosis": "2026-03-01", "diagnosis_note": 1,
|
||||
"requested": "2026-02-01", "link": "recorded", "reported": "2026-02-20",
|
||||
"biopsy": "2026-02-20", "backwards": 0,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def test_a_recorded_biopsy_and_the_inferred_colposcopy_and_diagnosis_with_their_sources():
|
||||
assert stage_facts(ROUTE) == {
|
||||
"colposcopy": ("inferred", ["clinical-note"]),
|
||||
"diagnosis": ("inferred", ["clinical-note"]),
|
||||
"biopsy": ("recorded", ["biopsy-record"]),
|
||||
}
|
||||
both = {**ROUTE, "colposcopy_biopsy": 1}
|
||||
assert stage_facts(both)["colposcopy"] == ("inferred", ["clinical-note", "biopsy-order"])
|
||||
ordered = {**ROUTE, "colposcopy_note": 0, "colposcopy_biopsy": 1}
|
||||
assert stage_facts(ordered)["colposcopy"] == ("inferred", ["biopsy-order"])
|
||||
|
||||
|
||||
def test_a_biopsy_linked_by_dates_is_inferred_and_one_not_reported_by_the_cut_off_is_pending():
|
||||
by_dates = {**ROUTE, "link": "inferred"}
|
||||
assert stage_facts(by_dates)["biopsy"] == ("inferred", ["date-association"])
|
||||
pending = {**ROUTE, "reported": None, "biopsy": None}
|
||||
assert stage_facts(pending)["biopsy"] == ("pending", ["biopsy-record"])
|
||||
|
||||
|
||||
def test_a_biopsy_reported_before_it_was_requested_is_ambiguous_and_nothing_else_is():
|
||||
backwards = {**ROUTE, "backwards": 1}
|
||||
assert stage_facts(backwards)["biopsy"] == ("ambiguous", ["biopsy-record"])
|
||||
assert {k: v[0] for k, v in stage_facts(backwards).items()} == {
|
||||
"colposcopy": "inferred", "diagnosis": "inferred", "biopsy": "ambiguous"} # fmt: skip
|
||||
|
||||
|
||||
def test_what_is_not_known_has_no_state_and_nothing_is_asked_for_colposcopy_or_diagnosis():
|
||||
assert stage_facts({}) == {}
|
||||
only_sample = {"requested": None, "colposcopy": None, "diagnosis": None}
|
||||
assert stage_facts(only_sample) == {}
|
||||
# reported, but outside the route's horizon: no day, so no state (it is not pending)
|
||||
outside = {**ROUTE, "biopsy": None}
|
||||
assert "biopsy" not in stage_facts(outside)
|
||||
# a stage with no known source says so with an empty list, never an invented one
|
||||
assert stage_facts({"colposcopy": "2026-02-01"})["colposcopy"] == ("inferred", [])
|
||||
assert not any(s == "pending" for s, _ in stage_facts({**ROUTE, "requested": None}).values())
|
||||
|
||||
|
||||
def test_the_report_carries_each_state_and_one_source_extension_per_source():
|
||||
both = {**ROUTE, "colposcopy_biopsy": 1}
|
||||
found = [(e["url"].rsplit("/", 1)[1], e["valueCode"]) for e in fhir.report_facts(both)
|
||||
if e["url"].rsplit("/", 1)[1].startswith("stage-")] # fmt: skip
|
||||
assert found == [
|
||||
("stage-colposcopy-state", "inferred"),
|
||||
("stage-colposcopy-source", "clinical-note"),
|
||||
("stage-colposcopy-source", "biopsy-order"),
|
||||
("stage-diagnosis-state", "inferred"),
|
||||
("stage-diagnosis-source", "clinical-note"),
|
||||
("stage-biopsy-state", "recorded"),
|
||||
("stage-biopsy-source", "biopsy-record"),
|
||||
]
|
||||
# the days and the link are published
|
||||
names = {e["url"].rsplit("/", 1)[1] for e in fhir.report_facts(both)}
|
||||
assert {"colposcopy-date", "biopsy-date", "biopsy-link", "diagnosis-date"} <= names
|
||||
assert all(n in fhir.EXTENSIONS for n in names)
|
||||
# a domain without a route (CaMa) gets none of them
|
||||
assert not [e for e in fhir.report_facts({"days": 3}) if "stage-" in e["url"]]
|
||||
|
||||
|
||||
def test_the_extensions_a_report_repeats_are_declared_repeatable():
|
||||
# a source is published once per source, so its definition must allow more than one
|
||||
by_name = {d.id: d for d in fhir.extensions()}
|
||||
cardinality = {n: by_name[n].differential.element[0].max for n in fhir.EXTENSIONS}
|
||||
for stage in ("colposcopy", "biopsy", "diagnosis"):
|
||||
assert cardinality[f"stage-{stage}-source"] == "*"
|
||||
assert cardinality[f"stage-{stage}-state"] == "1"
|
||||
assert cardinality["biopsy-link"] == "1"
|
||||
@@ -0,0 +1,118 @@
|
||||
"""CaMa's time from a mammogram's report to its biopsy's report (CAMA_DIAS_RESULTADO_BIOPSIA),
|
||||
its rules over made-up gold rows (`persistance.measures`' `mammogram_first_biopsy`: one row per
|
||||
mammogram, with the biopsy whose request names it), and what the same link does to the two
|
||||
measures that already followed a mammogram to its biopsy, whose rules are not touched."""
|
||||
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
from core.cama.measures import MEASURES
|
||||
from core.measures import Period, evaluate
|
||||
|
||||
S1 = Period.parse("2026-S1")
|
||||
CUTOFF = date(2026, 12, 31)
|
||||
TIME = MEASURES["CAMA_DIAS_RESULTADO_BIOPSIA"]
|
||||
|
||||
|
||||
def mammogram(name, birads="4A", report="2026-02-10", biopsy=None, days=None, grade="benign"):
|
||||
"""One row: a reported mammogram and, when its request named it, its first biopsy report."""
|
||||
return {
|
||||
"mammogram_id": name, "person_id": name, "exam_date": "2026-02-05", "report_date": report,
|
||||
"birads": birads, "birads_rank": 5, "known_at": "2026-02-05",
|
||||
"report_known_at": "2026-02-10", "biopsy_known_at": "2026-03-01" if biopsy else None,
|
||||
"biopsy_id": f"{name}|b" if biopsy else None, "biopsy_report_date": biopsy,
|
||||
"days_report_biopsy": days, "histology": grade if biopsy else None,
|
||||
"histology_rank": 1 if biopsy else None,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def ran(measure, rows, **kw):
|
||||
return evaluate(measure, rows, S1, event_cutoff=kw.pop("cutoff", CUTOFF), **kw)
|
||||
|
||||
|
||||
def test_the_days_are_the_biopsy_reports_from_the_mammogram_report_with_their_quartiles():
|
||||
rows = [
|
||||
mammogram("a", biopsy="2026-02-20", days=10),
|
||||
mammogram("b", biopsy="2026-02-24", days=14),
|
||||
mammogram("c", biopsy="2026-03-02", days=20),
|
||||
mammogram("d", biopsy="2026-03-10", days=28),
|
||||
]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations == {"initial-population": 4, "measure-observation": 4}
|
||||
assert found.score == 17.0 and found.score_extensions == {"q1": 13.0, "q3": 22.0}
|
||||
assert found.unit == "d"
|
||||
|
||||
|
||||
def test_a_biopsy_reported_the_day_of_the_mammogram_report_is_a_valid_zero():
|
||||
found = ran(TIME, [mammogram("a", biopsy="2026-02-10", days=0)])
|
||||
assert found.populations["measure-observation"] == 1
|
||||
assert found.score == 0.0 # a zero is a value, not an absence
|
||||
|
||||
|
||||
def test_a_mammogram_with_no_linked_biopsy_is_in_the_population_but_not_measured():
|
||||
# reported long enough ago for a biopsy to be missing, not pending
|
||||
rows = [mammogram("a", biopsy="2026-02-20", days=10), mammogram("b", report="2026-02-10")]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations == {"initial-population": 2, "measure-observation": 1}
|
||||
assert found.score == 10.0
|
||||
|
||||
|
||||
def test_a_biopsy_still_within_the_horizon_is_pending_not_missing():
|
||||
rows = [mammogram("a", report="2026-06-20")] # no biopsy reported yet
|
||||
soon = ran(TIME, rows, cutoff=date(2026, 9, 1)) # 73 days on: it may still come
|
||||
assert soon.populations["initial-population"] == 0
|
||||
late = ran(TIME, rows, cutoff=date(2026, 12, 31)) # 194 days on: it is missing
|
||||
assert late.populations == {"initial-population": 1, "measure-observation": 0}
|
||||
|
||||
|
||||
def test_inconsistent_or_missing_dates_leave_the_unit_unmeasured():
|
||||
rows = [
|
||||
mammogram("a", biopsy="2026-02-01", days=None), # biopsy reported before the mammogram
|
||||
mammogram("b", biopsy=None, days=None), # request named it, no report yet
|
||||
mammogram("c", report=None, biopsy="2026-02-20", days=None), # mammogram not reported
|
||||
mammogram("d", biopsy="2026-02-20", days=10),
|
||||
]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations["measure-observation"] == 1 and found.score == 10.0
|
||||
|
||||
|
||||
def test_only_mammograms_that_should_be_biopsied_count():
|
||||
rows = [
|
||||
mammogram("a", birads="4A", biopsy="2026-02-20", days=10),
|
||||
mammogram("b", birads="5", biopsy="2026-02-22", days=12),
|
||||
mammogram("c", birads="6", biopsy="2026-02-24", days=14), # already confirmed by biopsy
|
||||
mammogram("d", birads="2", biopsy="2026-02-26", days=16),
|
||||
]
|
||||
found = ran(TIME, rows)
|
||||
assert found.populations["measure-observation"] == 2 and found.score == 11.0
|
||||
|
||||
|
||||
def test_a_biopsy_reported_after_the_cutoff_or_not_yet_known_is_not_counted():
|
||||
rows = [mammogram("a", biopsy="2026-02-20", days=10)]
|
||||
early = ran(TIME, rows, cutoff=date(2026, 2, 15))
|
||||
assert early.populations["measure-observation"] == 0
|
||||
before = datetime(2026, 2, 25, tzinfo=UTC) # the report became known on 2026-03-01
|
||||
asked = ran(TIME, rows, as_of=before)
|
||||
assert asked.populations["measure-observation"] == 0
|
||||
|
||||
|
||||
def test_the_explicit_link_gives_the_confirmation_its_numerator_without_touching_its_rule():
|
||||
confirmation = MEASURES["CAMA_CONFIRMACION_BIRADS45"]
|
||||
linked = [mammogram("a", biopsy="2026-02-20", days=10), mammogram("b", biopsy="2026-03-02")]
|
||||
unlinked = [mammogram("a"), mammogram("b")]
|
||||
got = ran(confirmation, linked).populations
|
||||
assert (got["numerator"], got["denominator"]) == (2, 2)
|
||||
got = ran(confirmation, unlinked).populations
|
||||
assert (got["numerator"], got["denominator"]) == (0, 2)
|
||||
|
||||
|
||||
def test_the_explicit_link_gives_the_histopathology_its_results_instead_of_no_biopsy():
|
||||
histology = MEASURES["CAMA_HISTOPATOLOGIA_BIRADS"]
|
||||
rows = [mammogram("a", biopsy="2026-02-20", grade="invasive"), mammogram("b", birads="5")]
|
||||
found = ran(histology, rows)
|
||||
assert {k: v["initial-population"] for k, v in found.strata["category"].items()} == {
|
||||
"invasive": 1, "no_biopsy": 1} # fmt: skip
|
||||
cells = found.crossed["birads", "category"]
|
||||
assert cells["4A", "invasive"]["initial-population"] == 1
|
||||
assert cells["5", "no_biopsy"]["initial-population"] == 1
|
||||
nothing = ran(histology, [mammogram("a"), mammogram("b", birads="5")])
|
||||
assert list(nothing.strata["category"]) == ["no_biopsy"]
|
||||
@@ -0,0 +1,47 @@
|
||||
"""A preliminary result is a sample awaiting its result; an annulled one is not used."""
|
||||
|
||||
import pytest
|
||||
|
||||
from core import catalog, fhir_in
|
||||
|
||||
|
||||
def _coding(system, code):
|
||||
return {"coding": [{"system": system, "code": code}]}
|
||||
|
||||
|
||||
def _rows(report_status, observation_status):
|
||||
observation = {"resourceType": "Observation", "id": "o", "status": observation_status,
|
||||
"code": _coding(fhir_in.FIELD, "cervical_cytology.hpv"), "valueBoolean": True}
|
||||
report = {"resourceType": "DiagnosticReport", "id": "r", "status": report_status,
|
||||
"code": _coding(fhir_in.STUDY, "cervical_cytology"),
|
||||
"effectiveDateTime": "2025-02-01", "issued": "2025-02-05T12:00:00Z",
|
||||
"result": [{"reference": "Observation/o"}]}
|
||||
bundle = {"entry": [{"resource": report}, {"resource": observation}]}
|
||||
return fhir_in.rows(bundle, "cervical_cytology", "hospital")
|
||||
|
||||
|
||||
def _dates(row):
|
||||
events = catalog.studies()["cervical_cytology"].events
|
||||
return row.get(events["sample"].date), row.get(events["report"].date)
|
||||
|
||||
|
||||
def test_a_final_result_is_used():
|
||||
(row,) = _rows("final", "final")
|
||||
assert row["hpv"] is True
|
||||
assert _dates(row) == ("2025-02-01", "2025-02-05")
|
||||
|
||||
|
||||
def test_a_preliminary_report_keeps_the_sample_and_waits_for_the_result():
|
||||
(row,) = _rows("preliminary", "preliminary")
|
||||
assert "hpv" not in row
|
||||
assert _dates(row) == ("2025-02-01", None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["preliminary", "entered-in-error"])
|
||||
def test_a_value_that_is_not_final_is_not_used(status):
|
||||
(row,) = _rows("final", status)
|
||||
assert "hpv" not in row
|
||||
|
||||
|
||||
def test_an_annulled_report_is_not_used():
|
||||
assert _rows("entered-in-error", "final") == []
|
||||
@@ -0,0 +1,47 @@
|
||||
"""The common representation must preserve every source row and horizon."""
|
||||
|
||||
import pytest
|
||||
|
||||
from core.cacu.reference_risk import tables
|
||||
from core.risk_tables import FORMAT_VERSION, nci_reference_table, source_estimate
|
||||
|
||||
|
||||
def test_nci_table_preserves_rows_horizons_values_and_provenance():
|
||||
source = tables()
|
||||
result = nci_reference_table(source)
|
||||
assert result["format_version"] == FORMAT_VERSION
|
||||
assert result["source_version"] == source["source"]["sha256"]
|
||||
assert len(result["rows"]) == len(source["rows"])
|
||||
for converted, original in zip(result["rows"], source["rows"], strict=True):
|
||||
assert converted["source_row"] == original
|
||||
assert converted["variables"] == original["key"]
|
||||
assert converted["outcome"]["code"] == "CIN3+"
|
||||
estimates = {str(e["horizon_years"]): e["value"] for e in converted["estimates"]}
|
||||
assert estimates == original["risks"]
|
||||
assert all(e["outcome"] == "CIN3+" for e in converted["estimates"])
|
||||
assert all(e["confidence_interval"] is None for e in converted["estimates"])
|
||||
|
||||
|
||||
def test_nci_adapter_keeps_zero_and_missing_distinct():
|
||||
result = nci_reference_table(tables())
|
||||
values = [estimate["value"] for row in result["rows"] for estimate in row["estimates"]]
|
||||
assert 0 in values
|
||||
assert None in values
|
||||
|
||||
|
||||
@pytest.mark.parametrize("outcome", ["CIN2+", "CIN3+", "cancer"])
|
||||
def test_source_units_outcomes_and_interval_are_explicit(outcome):
|
||||
common = dict(outcome=outcome, horizon_years=5, file="source.xlsx", sheet="Risk", row=2,
|
||||
confidence_level=0.95)
|
||||
fraction = source_estimate(**common, value=0.12, lower=0.1, upper=0.14, unit="fraction")
|
||||
percent = source_estimate(**common, value=12, lower=10, upper=14, unit="percent")
|
||||
assert fraction["value"] == percent["value"] == 0.12
|
||||
assert fraction["confidence_interval"] == percent["confidence_interval"]
|
||||
assert percent["source"]["unit"] == "percent"
|
||||
assert percent["source"]["row"] == 2
|
||||
|
||||
|
||||
def test_unknown_units_are_rejected():
|
||||
with pytest.raises(ValueError):
|
||||
source_estimate(outcome="CIN2+", horizon_years=0, value=1, unit="unknown",
|
||||
file="source.xlsx", sheet="Risk", row=2)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""The published workbooks as estimates: units, outcomes, provenance and blanks."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from core.risk_workbooks import UNITS, read_workbook
|
||||
|
||||
BOOKS = Path(__file__).parents[1] / "Core/core/cacu/nci_source_workbooks"
|
||||
|
||||
|
||||
def _row(file: str, sheet: str | None = None, row: int = 2) -> dict:
|
||||
return next(r for r in read_workbook(BOOKS / file)
|
||||
if r["row"] == row and sheet in (None, r["sheet"])) # fmt: skip
|
||||
|
||||
|
||||
def test_every_book_reads_into_probabilities_inside_their_intervals():
|
||||
assert {p.name for p in BOOKS.glob("*.xlsx")} == set(UNITS)
|
||||
for name in UNITS:
|
||||
estimates = [e for r in read_workbook(BOOKS / name) for e in r["estimates"]]
|
||||
assert estimates
|
||||
for e in estimates:
|
||||
if e["value"] is None:
|
||||
continue
|
||||
assert 0 <= e["value"] <= 1, e["source"]
|
||||
i = e["confidence_interval"]
|
||||
if i and None not in (i["lower"], i["upper"]):
|
||||
assert i["lower"] - 1e-9 <= e["value"] <= i["upper"] + 1e-9, e["source"]
|
||||
assert (i["level"], i["method"]) == (0.95, None)
|
||||
|
||||
|
||||
def test_each_book_is_read_in_its_verified_unit():
|
||||
"""Cumulative risk at five years is near the share of cases: a wrong unit is 100x off."""
|
||||
# 98 CIN3 or worse of 199, under a "(%)" header: a fraction
|
||||
general = _row("23_Post_Treatment General.xlsx", "Post Treatment 1 visit", 25)
|
||||
five = next(e for e in general["estimates"]
|
||||
if (e["outcome"], e["horizon_years"]) == ("CIN3+", 5)) # fmt: skip
|
||||
assert 0.5 < five["value"] < 0.75
|
||||
assert five["source"]["unit"] == "fraction"
|
||||
percent = _row("17_Post_Colpo.xlsx")["estimates"][0]
|
||||
assert percent["value"] == pytest.approx(percent["source"]["value"] / 100)
|
||||
|
||||
|
||||
def test_long_book_carries_its_outcome_and_hpv_down_and_keeps_provenance():
|
||||
first, second = _row("1_Enrollment Table.xlsx"), _row("1_Enrollment Table.xlsx", row=3)
|
||||
assert second["variables"] == {"hpv": "HPV-negative", "pap": "ASC-US"}
|
||||
assert second["estimates"][0]["outcome"] == first["estimates"][0]["outcome"] == "CIN2+"
|
||||
assert second["estimates"][0]["source"]["row"] == 3
|
||||
|
||||
|
||||
def test_a_blank_estimate_stays_blank_and_an_unknown_book_is_refused(tmp_path):
|
||||
book = read_workbook(BOOKS / "24_Post_Treatment_1visit_nostratifiedPre.xlsx")
|
||||
assert any(e["value"] is None for r in book for e in r["estimates"])
|
||||
with pytest.raises(ValueError, match="not been verified"):
|
||||
read_workbook(tmp_path / "other.xlsx")
|
||||
@@ -0,0 +1,78 @@
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from joblib import parallel_config
|
||||
|
||||
from core import fhir
|
||||
from models import survival
|
||||
from models.cacu.specs import MODELS as CACU
|
||||
from models.cama.specs import MODELS as CAMA
|
||||
|
||||
|
||||
@pytest.mark.parametrize("spec", [CACU["survival"], CAMA["survival"]])
|
||||
def test_report_interval_contract_and_cama_compatibility(spec, monkeypatch):
|
||||
monkeypatch.setattr(survival, "BOOTSTRAP", 2)
|
||||
monkeypatch.setattr(survival, "risk_factor_report", lambda *args: {})
|
||||
monkeypatch.setattr(survival, "_scenario_curves", lambda *args: {
|
||||
"km": {"S": [1.0], "low": [0.9], "high": [1.0]},
|
||||
"weibull": {"S": [1.0]}, "weibull_fractional": {"S": [1.0]},
|
||||
})
|
||||
columns = set(spec.features) | set(spec.scenario_columns)
|
||||
members = pd.DataFrame({c: ["unknown"] * 8 for c in columns})
|
||||
members["months"] = [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
members["event"] = [True] * 6 + [False] * 2
|
||||
|
||||
class Model:
|
||||
weights_ = np.repeat(0.5, len(spec.borders) - 1)
|
||||
fitted_ = [(None, ([], None))] * (len(spec.borders) - 1)
|
||||
|
||||
def fit(self, *args):
|
||||
return self
|
||||
|
||||
def survival(self, rows):
|
||||
return np.full((len(rows), len(spec.borders) - 1), 0.8)
|
||||
|
||||
monkeypatch.setattr(survival.Spec, "_model", lambda self: Model())
|
||||
# Force one scenario to be drawn and one to be omitted, independent of their clinical labels.
|
||||
monkeypatch.setattr(survival, "scenario_masks", lambda members, scenarios: {
|
||||
"drawn": np.ones(len(members), dtype=bool),
|
||||
"few": np.arange(len(members)) == 0,
|
||||
})
|
||||
spec = __import__("dataclasses").replace(spec, scenarios={"drawn": (), "few": ()})
|
||||
with parallel_config(backend="sequential"):
|
||||
report = survival.interpretability(spec, Model(), {"train": members})
|
||||
scenario = report["escenarios"][0]
|
||||
omitted = report["escenarios_sin_curvas"][0]
|
||||
if spec.cohort.startswith("cacu_"):
|
||||
assert scenario["km"]["interval"] == {
|
||||
"available": True, "level": 0.95, "method": "greenwood_log_log"}
|
||||
assert scenario["weibull"]["interval"]["available"] is False
|
||||
assert scenario["weibull_fractional"]["interval"]["available"] is False
|
||||
assert scenario["points"]["COMB"]["interval"]["method"] == "bootstrap_percentile"
|
||||
assert omitted["reason"] == "insufficient_deaths"
|
||||
assert report["predicted"]["interval"]["level"] == 0.95
|
||||
else:
|
||||
assert "interval" not in scenario["km"]
|
||||
assert "reason" not in omitted
|
||||
|
||||
|
||||
def test_fhir_survival_intervals_are_explicit_without_inventing_metadata():
|
||||
row = {"model": "cacu.survival", "version": 1, "person_id": "p",
|
||||
"index_date": date(2025, 1, 1), "scored_at": "2025-01-02T00:00:00Z"}
|
||||
result = fhir.risk_assessment(row, [
|
||||
{"horizon_years": 1, "probability": 0.2, "ci_low": 0.1, "ci_high": 0.4},
|
||||
{"horizon_years": 5, "probability": 0.3, "ci_low": None, "ci_high": None},
|
||||
]).model_dump(mode="json", exclude_none=True)
|
||||
ext = [{e["url"].rsplit("/", 1)[-1]: e for e in p["extension"]}
|
||||
for p in result["prediction"]]
|
||||
assert ext[0]["ic-metodo"]["valueCode"] == "unknown"
|
||||
assert "ic-nivel" not in ext[0]
|
||||
assert ext[1]["ic-estado"]["valueCode"] == "unavailable"
|
||||
assert "ic-bajo" not in ext[1]
|
||||
# Complementing mortality reverses the endpoints of its confidence interval.
|
||||
low = 1 - ext[0]["ic-alto"]["valueDecimal"]
|
||||
high = 1 - ext[0]["ic-bajo"]["valueDecimal"]
|
||||
assert low == pytest.approx(0.6)
|
||||
assert high == pytest.approx(0.9)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""The synthetic site names the mammogram a breast biopsy came from only when its source does:
|
||||
Synthea keeps one encounter open from a mammogram to the biopsy it leads to, so the two
|
||||
reports name the same encounter. Nothing is matched by dates."""
|
||||
|
||||
from synthetic import site
|
||||
|
||||
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
||||
|
||||
|
||||
def report(code, day, encounter, name):
|
||||
return {
|
||||
"resource": {
|
||||
"resourceType": "DiagnosticReport", "id": name,
|
||||
"code": {"coding": [{"system": STUDY, "code": code}]},
|
||||
"effectiveDateTime": f"{day}T14:00:00+00:00",
|
||||
"encounter": {"reference": encounter},
|
||||
}
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def bundle(*reports):
|
||||
patient = {"resource": {"resourceType": "Patient", "id": "p", "birthDate": "1970-01-01"}}
|
||||
return {"entry": [patient, *reports]}
|
||||
|
||||
|
||||
def test_a_biopsy_names_the_mammogram_of_its_encounter():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
report("mammography", "2024-05-12", "urn:e0", "m0"), # an earlier one, another encounter
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {"2026-05-25": "2026-05-12"}
|
||||
|
||||
|
||||
def test_same_day_reports_of_one_biopsy_name_one_mammogram():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b2"), # a second report, same day
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {"2026-05-25": "2026-05-12"}
|
||||
|
||||
|
||||
def test_a_biopsy_with_no_mammogram_in_its_encounter_names_none():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e2", "b1"), # near in time, not the same one
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {}
|
||||
|
||||
|
||||
def test_an_encounter_with_two_mammograms_names_none():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("mammography", "2026-05-13", "urn:e1", "m2"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
)
|
||||
assert site.mammogram_of_biopsies(b) == {}
|
||||
|
||||
|
||||
def test_a_biopsy_with_no_encounter_names_none():
|
||||
b = {"entry": [{"resource": {
|
||||
"resourceType": "DiagnosticReport", "id": "b",
|
||||
"code": {"coding": [{"system": STUDY, "code": "breast_biopsy"}]},
|
||||
"effectiveDateTime": "2026-05-25T14:00:00+00:00"}}]} # fmt: skip
|
||||
assert site.mammogram_of_biopsies(b) == {}
|
||||
|
||||
|
||||
def test_the_study_rows_carry_the_link_and_the_other_biopsies_do_not():
|
||||
b = bundle(
|
||||
report("mammography", "2026-05-12", "urn:e1", "m1"),
|
||||
report("breast_biopsy", "2026-05-25", "urn:e1", "b1"),
|
||||
report("breast_biopsy", "2026-09-01", "urn:e9", "b9"), # no mammogram in its encounter
|
||||
)
|
||||
found = site.people_and_studies([b])["p"]["studies"]["breast_biopsy"]
|
||||
assert {r["request_date"]: r.get("mammogram_exam_date") for r in found} == {
|
||||
"2026-05-25": "2026-05-12", "2026-09-01": None} # fmt: skip
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Inspect a registered CaCu model's predictors or reconstruct them for a saved score."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
from sqlalchemy import text
|
||||
|
||||
from models.cacu import features
|
||||
from models.cacu.specs import MODELS, Logistic, Pim
|
||||
from models.survival import Spec
|
||||
from persistance import fhir
|
||||
from persistance.destination import engine
|
||||
|
||||
|
||||
def registered_spec(model: str, version: int) -> Logistic | Pim | Spec:
|
||||
artifact = mlflow.pyfunc.load_model(f"models:/cacu.{model}/{version}")
|
||||
spec = getattr(artifact.unwrap_python_model(), "spec", None)
|
||||
if not isinstance(spec, (Logistic, Pim, Spec)) or spec.name != model:
|
||||
raise ValueError("La versión no contiene una especificación CaCu compatible.")
|
||||
return spec
|
||||
|
||||
|
||||
def predictors(spec: Logistic | Pim | Spec) -> list[str]:
|
||||
return list(spec.predictors if isinstance(spec, Logistic) else spec.features)
|
||||
|
||||
|
||||
def patient_timeline(person_id: str, index: str, cutoff: date) -> pd.DataFrame:
|
||||
sql = text("""
|
||||
select e.*, :index_date as index_date,
|
||||
(select min(i.record_number) from bronze.staged__identity as i
|
||||
where i.person_id = e.person_id) as record_number
|
||||
from gold.cacu_events as e
|
||||
where e.person_id = :person_id and e.date <= :cutoff
|
||||
order by e.date, e.source_table, e.source_id
|
||||
""")
|
||||
with engine().connect() as con:
|
||||
return pd.read_sql(
|
||||
sql, con, params={"person_id": person_id, "index_date": index, "cutoff": cutoff}
|
||||
)
|
||||
|
||||
|
||||
def reconstructed_inputs(spec: Logistic | Pim | Spec, events: pd.DataFrame) -> dict:
|
||||
selected = predictors(spec)
|
||||
if isinstance(spec, Spec):
|
||||
members = spec.members(events)
|
||||
elif isinstance(spec, Pim):
|
||||
members = features.index_results(features.prepared(events), spec.cytology, spec._history())
|
||||
else:
|
||||
members = features.index_sample(features.prepared(events), selected)
|
||||
if len(members) != 1:
|
||||
raise ValueError("La consulta debe producir las variables de una sola paciente.")
|
||||
return json.loads(members[selected].to_json(orient="records"))[0]
|
||||
|
||||
|
||||
def patient_inputs(
|
||||
spec: Logistic | Pim | Spec,
|
||||
model: str,
|
||||
version: int,
|
||||
person_id: str,
|
||||
index_date: date | None,
|
||||
) -> dict:
|
||||
scored = [
|
||||
row for row in fhir.rows("cacu", "risk", persons=[person_id])
|
||||
if row["model"] == f"cacu.{model}" and row["version"] == version
|
||||
and (index_date is None or str(row["index_date"])[:10] == index_date.isoformat())
|
||||
] # fmt: skip
|
||||
if not scored:
|
||||
raise ValueError("No hay una estimación guardada para esa paciente, versión y fecha.")
|
||||
score = max(scored, key=lambda row: (str(row["index_date"]), str(row["scored_at"])))
|
||||
index = str(score["index_date"])[:10]
|
||||
cutoff = date.fromisoformat(str(score["scored_at"])[:10])
|
||||
events = patient_timeline(person_id, index, cutoff)
|
||||
if events.empty:
|
||||
raise ValueError("La capa gold no contiene eventos para reconstruir la estimación.")
|
||||
return {
|
||||
"model": f"cacu.{model}",
|
||||
"version": version,
|
||||
"person_id": person_id,
|
||||
"index_date": index,
|
||||
"cutoff_used": cutoff.isoformat(),
|
||||
"status": "reconstructed",
|
||||
"values": reconstructed_inputs(spec, events),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
fields = commands.add_parser("fields", help="Lista los predictores de una versión.")
|
||||
patient = commands.add_parser("patient", help="Reconstruye los valores de una estimación.")
|
||||
for command in (fields, patient):
|
||||
command.add_argument("model", choices=MODELS)
|
||||
command.add_argument("version", type=int)
|
||||
patient.add_argument("person_id")
|
||||
patient.add_argument("--index-date", type=date.fromisoformat)
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
spec = registered_spec(args.model, args.version)
|
||||
if args.command == "fields":
|
||||
result = {
|
||||
"model": f"cacu.{args.model}",
|
||||
"version": args.version,
|
||||
"predictors": predictors(spec),
|
||||
}
|
||||
else:
|
||||
result = patient_inputs(spec, args.model, args.version, args.person_id, args.index_date)
|
||||
except (ValueError, mlflow.exceptions.MlflowException) as error:
|
||||
parser.exit(1, f"{error}\n")
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/bin/sh
|
||||
# Datos sintéticos de CaCu: Synthea los genera y entran solo por la API (puerta FHIR);
|
||||
# después este mismo script dispara entrenamiento, promoción y puntuación (nada de eso
|
||||
# corre solo). Sin valor clínico.
|
||||
#
|
||||
# tools/cargar_cacu.sh http://10.0.10.41:5711 [mujeres=3000] [pasos=synthea,train,promote,score]
|
||||
#
|
||||
# promote exige los reportes de PROMOTION_REPORTS del despliegue. Una demo sin validación
|
||||
# clínica se levanta con PROMOTION_REPORTS=technical_validation,interpretability en .env.
|
||||
set -eu
|
||||
API=${1:?uso: $0 URL_API [mujeres] [pasos]}
|
||||
WOMEN=${2:-3000}
|
||||
STEPS=${3:-synthea,train,promote,score}
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
OUT=${SYNTHEA_OUT:-$HOME/isssteleon-data/synthea-cacu-$WOMEN}
|
||||
IMAGE=${SYNTHEA_IMAGE:-isssteleon-synthea:local}
|
||||
|
||||
case ",$STEPS," in *,synthea,*)
|
||||
if [ ! -d "$OUT/fhir" ]; then
|
||||
docker image inspect "$IMAGE" >/dev/null 2>&1 ||
|
||||
docker build -t "$IMAGE" --target test "$ROOT"
|
||||
mkdir -p "$OUT"
|
||||
# El jar de la imagen solo lo lee root: corre como root y devuelve la salida al usuario.
|
||||
docker run --rm -v "$OUT:/out" -w /out \
|
||||
-v "$ROOT/tests/fixtures/synthea/modules:/modules:ro" "$IMAGE" \
|
||||
sh -c 'java -jar /opt/synthea/synthea.jar "$@"; s=$?; chown -R "$0" /out; exit $s' \
|
||||
"$(id -u):$(id -g)" -p "$WOMEN" -s 7 -cs 7 -g F -a 25-64 \
|
||||
-r 20261130 -e 20261130 -d /modules -m cervical_screening \
|
||||
--exporter.baseDirectory /out --exporter.fhir.export true \
|
||||
--exporter.hospital.fhir.export false \
|
||||
--exporter.practitioner.fhir.export false >"$OUT/synthea.log"
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
cd "$ROOT"
|
||||
exec uv run python tools/load_site.py --api "$API" --domain cacu \
|
||||
--synthea "$OUT/fhir" --batch "${BATCH:-2000}" --steps "$STEPS"
|
||||
+29
-12
@@ -9,7 +9,11 @@ its own pipelines in Conectar instead.
|
||||
|
||||
Steps (all by default, in this order; `--steps` picks some): maps, erick, tea, synthea,
|
||||
analyze, train, promote, score, association. Each waits for its runs and stops on a failed
|
||||
one, so a long load can be resumed from the step that failed. Times are printed per step."""
|
||||
one, so a long load can be resumed from the step that failed. Times are printed per step.
|
||||
|
||||
`--domain cacu` loads one domain only: its Synthea women through its own door, and training,
|
||||
promotion and scoring of that domain, leaving out the development-only models
|
||||
(tools/cargar_cacu.sh generates the women and runs this)."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
@@ -19,7 +23,7 @@ from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from core.models import TITLES
|
||||
from core.models import DEVELOPMENT, TITLES
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURES = ROOT / "tests" / "fixtures"
|
||||
@@ -34,6 +38,7 @@ FIRST = {
|
||||
for domain in ("cacu", "cama", "tea")
|
||||
} # fmt: skip
|
||||
DONE = ("SUCCESS", "FAILURE", "CANCELED")
|
||||
DOORS = {"cacu": "fhir_door.json", "cama": "fhir_door_cama.json"}
|
||||
|
||||
|
||||
class Site:
|
||||
@@ -83,10 +88,11 @@ def tea(site: Site, args) -> None:
|
||||
|
||||
|
||||
def synthea(site: Site, args) -> None:
|
||||
"""Synthea's CaMa women through the FHIR door, `--batch` patients per Bundle; each post
|
||||
starts the sender's pipeline, and the next waits for it."""
|
||||
"""Synthea's women (CaMa unless `--domain`) through the FHIR door, `--batch` patients
|
||||
per Bundle; each post starts the sender's pipeline, and the next waits for it."""
|
||||
domain = args.domain or "cama"
|
||||
site.call("PUT", "/ingest/pipelines/synthea",
|
||||
json=_pipeline("fhir_door_cama.json", sender="synthea")) # fmt: skip
|
||||
json=_pipeline(DOORS[domain], sender="synthea")) # fmt: skip
|
||||
files = sorted(Path(args.synthea).expanduser().glob("*.json"))
|
||||
for start in range(args.skip, len(files), args.batch):
|
||||
entries = []
|
||||
@@ -95,7 +101,7 @@ def synthea(site: Site, args) -> None:
|
||||
bundle = {"resourceType": "Bundle", "type": "transaction", "entry": entries}
|
||||
t = time.monotonic()
|
||||
posted = site.http.post(
|
||||
"/cama/fhir", params={"sender": "synthea"}, json=bundle, timeout=3600
|
||||
f"/{domain}/fhir", params={"sender": "synthea"}, json=bundle, timeout=3600
|
||||
) # a large Bundle on a busy host
|
||||
if posted.status_code != 202:
|
||||
sys.exit(f"FHIR door: {posted.status_code} {posted.text[:500]}")
|
||||
@@ -109,31 +115,41 @@ def analyze(site: Site, args) -> None:
|
||||
site.wait(site.call("POST", "/models/tea/analyze")["run_id"], "TEA analysis")
|
||||
|
||||
|
||||
def _domains(site: Site) -> list[str]:
|
||||
return site.call("GET", "/domains")
|
||||
def _domains(site: Site, args) -> list[str]:
|
||||
return [args.domain] if args.domain else site.call("GET", "/domains")
|
||||
|
||||
|
||||
def _models(domain: str, args) -> list[str]:
|
||||
skipped = DEVELOPMENT if args.domain else ()
|
||||
return [name for name in FIRST[domain] if f"{domain}.{name}" not in skipped]
|
||||
|
||||
|
||||
def train(site: Site, args) -> None:
|
||||
for domain in _domains(site):
|
||||
body = {"models": FIRST[domain]}
|
||||
for domain in _domains(site, args):
|
||||
body = {"models": _models(domain, args)}
|
||||
site.wait(site.call("POST", f"/models/{domain}/train", json=body)["run_id"],
|
||||
f"{domain} training") # fmt: skip
|
||||
|
||||
|
||||
def promote(site: Site, args, only: tuple[str, str] | None = None) -> None:
|
||||
"""Each model's latest version becomes its champion (the reports the site requires)."""
|
||||
for domain in _domains(site):
|
||||
for domain in _domains(site, args):
|
||||
for model in site.call("GET", f"/models/{domain}"):
|
||||
name = model["name"]
|
||||
if only and (domain, name) != only or not only and (domain, name) == ASSOCIATION:
|
||||
continue
|
||||
if args.domain and name not in _models(domain, args):
|
||||
continue
|
||||
found = site.call("GET", f"/models/{domain}/{name}/versions")
|
||||
if not found: # no such patients: the model was not trained
|
||||
print(f" {domain}.{name}: no version, not promoted", flush=True)
|
||||
continue
|
||||
latest = max(v["version"] for v in found)
|
||||
site.call("POST", f"/models/{domain}/{name}/versions/{latest}/promote")
|
||||
|
||||
|
||||
def score(site: Site, args) -> None:
|
||||
for domain in _domains(site):
|
||||
for domain in _domains(site, args):
|
||||
site.wait(site.call("POST", f"/models/{domain}/score")["run_id"], f"{domain} scoring")
|
||||
|
||||
|
||||
@@ -153,6 +169,7 @@ def main() -> None:
|
||||
parser.add_argument("--hospital", default="/data/hospital",
|
||||
help="the synthetic hospitals' folder as the platform sees it") # fmt: skip
|
||||
parser.add_argument("--synthea", help="Synthea's FHIR Bundles (one file per patient)")
|
||||
parser.add_argument("--domain", choices=sorted(DOORS), help="load this domain only")
|
||||
parser.add_argument("--batch", type=int, default=2000)
|
||||
parser.add_argument("--skip", type=int, default=0,
|
||||
help="Synthea patients already posted (to resume that step)") # fmt: skip
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Builds the reference resource of CaCu's NCI risk comparison (`core/cacu/nci_risk_tables.json`)
|
||||
from the team's workbook of the NCI/ASCCP CIN3+ risk tables, and checks it against the NCI's own
|
||||
downloadable tables when those are at hand.
|
||||
|
||||
python tools/nci_risk_tables.py WORKBOOK.xlsx --out Core/core/cacu/nci_risk_tables.json \
|
||||
[--official DIR_WITH_THE_FIVE_NCI_XLSX]
|
||||
|
||||
The workbook is read once, here; the platform reads only the JSON. Every row keeps its sheet and
|
||||
row, its clinical keys as the workbook writes them after trimming spaces (`raw`) and as the
|
||||
platform's vocabulary names them (`key`), and its risks as published (percent, two decimals) and
|
||||
as probabilities. The workbook's `Management` column (a recommendation) is not imported.
|
||||
Needs openpyxl (a development tool; the platform does not).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
OUTCOME = {"code": "CIN3+", "label": "CIN3 o más grave (CIN3+)"}
|
||||
SOURCE = {
|
||||
"title": "Master NCI risk table (CIN3+ immediate, 1-year and 5-year risks)",
|
||||
"origin": "Workbook provided by the team; its provenance is not verified. It is not a copy of "
|
||||
"the ASCCP application and is not known to be current.",
|
||||
"official_pages": [
|
||||
"https://dceg.cancer.gov/research/cancer-types/cervix/enduring-guidelines",
|
||||
"https://pmc.ncbi.nlm.nih.gov/articles/PMC7147416/",
|
||||
"https://pmc.ncbi.nlm.nih.gov/articles/PMC7147417/",
|
||||
],
|
||||
"reuse": "The NCI states its risk estimates are in the public domain in the United States and asks "
|
||||
"for credit to the NCI as the source.",
|
||||
}
|
||||
|
||||
# sheet -> (table id, key columns by name, risk columns -> horizon in years)
|
||||
TABLES = {
|
||||
"1 - Screening": ("screening", ["history", "hpv", "cytology"], {3: 0, 4: 5}),
|
||||
"2 - Surveillance": ("surveillance", ["previous_two", "history", "hpv", "cytology"], {4: 0, 5: 5}),
|
||||
"3 - Colposcopy Results": ("colposcopy_results", ["referral", "biopsy"], {2: 1, 3: 5}),
|
||||
"4 - Post Colpo Surveillance": (
|
||||
"post_colposcopy", ["pre_colposcopy", "post_colposcopy_history", "hpv", "cytology"], {4: 0, 5: 5}),
|
||||
"5 - Post Treatment Surveillance": (
|
||||
"post_treatment", ["biopsy_before_treatment", "hpv", "cytology"], {3: 0, 4: 5}),
|
||||
}
|
||||
# the workbook's spellings -> the vocabulary of the resource (spaces trimmed first)
|
||||
ALIASES = {"HPV16-,18+": "HPV16-, HPV18+", "-": None}
|
||||
# the NCI files' spellings of the same labels, for the check only
|
||||
OFFICIAL_ALIASES = {"ASC-US, LSIL": "ASC-US/LSIL", "ASC_US": "ASC-US", "ASCUS": "ASC-US",
|
||||
"HPV-negative/ASCUS/LSIL": "HPV-negative/ASC-US/LSIL",
|
||||
"HPV-positive NILM x2": "HPV-positive NILM", "CIN 2 or 3": "CIN3"}
|
||||
OFFICIAL_FILES = { # first header cells of each NCI file -> table
|
||||
"Referral Screen Result": "colposcopy_results",
|
||||
"Test Result Before Biopsy": "post_treatment",
|
||||
"Pre-Colpo Test Result": "post_colposcopy",
|
||||
"PAST HISTORY (previous 2)": "surveillance",
|
||||
"PAST HISTORY (most recent)": "screening",
|
||||
}
|
||||
|
||||
|
||||
def text(value):
|
||||
if value is None:
|
||||
return None
|
||||
found = " ".join(str(value).split())
|
||||
return ALIASES.get(found, found) or None
|
||||
|
||||
|
||||
def read(path: Path) -> list[dict]:
|
||||
rows = []
|
||||
book = openpyxl.load_workbook(path, data_only=True)
|
||||
for sheet, (table, keys, risks) in TABLES.items():
|
||||
for number, cells in enumerate(book[sheet].iter_rows(values_only=True), start=1):
|
||||
if number == 1:
|
||||
continue
|
||||
raw = dict(zip(keys, [text(c) for c in cells[: len(keys)]], strict=True))
|
||||
published = {h: cells[c] for c, h in risks.items()}
|
||||
rows.append({
|
||||
"table": table, "sheet": sheet, "row": number, "key": raw, "raw": [
|
||||
None if c is None else str(c) for c in cells[: len(keys)]],
|
||||
"risks_percent": {str(h): v for h, v in published.items()},
|
||||
"risks": {str(h): None if v is None else round(v / 100, 6) for h, v in published.items()},
|
||||
"published": all(v is not None for v in published.values()),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def official(folder: Path) -> dict[str, dict]:
|
||||
"""The NCI files by table: key -> (CIN3+ risk at each horizon, percent)."""
|
||||
found = {}
|
||||
for path in sorted(folder.glob("*.xlsx")):
|
||||
sheet = openpyxl.load_workbook(path, data_only=True).worksheets[0]
|
||||
table_rows = list(sheet.iter_rows(values_only=True))
|
||||
header = [str(h) if h else "" for h in table_rows[0]]
|
||||
table = next((t for h, t in OFFICIAL_FILES.items() if h in header[:3]), None)
|
||||
# the file that has "PAST HISTORY (most recent)" first is screening; surveillance also has
|
||||
# "(previous 2)" before it
|
||||
if "PAST HISTORY (previous 2)" in header[:3]:
|
||||
table = "surveillance"
|
||||
if table is None:
|
||||
continue
|
||||
end = header.index("N")
|
||||
wanted = {0: "CIN3+ Immediate risk", 1: "CIN3+ 1 year risk", 5: "CIN3+ 5 year risk"}
|
||||
columns = {h: next((i for i, name in enumerate(header) if name.startswith(label)), None)
|
||||
for h, label in wanted.items()} # fmt: skip
|
||||
out = {}
|
||||
for cells in table_rows[1:]:
|
||||
if cells[0] is None:
|
||||
continue
|
||||
key = tuple(OFFICIAL_ALIASES.get(" ".join(str(c).split()), " ".join(str(c).split()))
|
||||
if c is not None else None for c in cells[1:end])
|
||||
out[key] = {h: cells[i] for h, i in columns.items() if i is not None}
|
||||
found[table] = {"file": path.name, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
|
||||
"rows": out, "modified": str(
|
||||
openpyxl.load_workbook(path).properties.modified)} # fmt: skip
|
||||
return found
|
||||
|
||||
|
||||
def check(rows: list[dict], reference: dict[str, dict]) -> dict:
|
||||
"""Each row against the NCI file of its table; the verdicts are counted."""
|
||||
counts: dict[str, int] = {}
|
||||
for row in rows:
|
||||
table = reference.get(row["table"])
|
||||
verdict = "no_official_file"
|
||||
if table:
|
||||
keys = [OFFICIAL_ALIASES.get(v, v) if v else None for v in row["key"].values()]
|
||||
if row["table"] == "post_treatment": # the NCI file has one more key column, empty
|
||||
keys = [None, *keys]
|
||||
keys += [None] * (len(next(iter(table["rows"]))) - len(keys))
|
||||
found = table["rows"].get(tuple(keys))
|
||||
if found is None:
|
||||
verdict = "not_found_in_official"
|
||||
else:
|
||||
got = [found.get(int(h)) for h in row["risks_percent"]]
|
||||
want = list(row["risks_percent"].values())
|
||||
blank = all(v is None or v != v for v in got) and all(v is None for v in want)
|
||||
if blank:
|
||||
verdict = "blank_in_both"
|
||||
elif any(v is None or v != v for v in got) or any(v is None for v in want):
|
||||
verdict = "differs"
|
||||
elif all(abs(g - w) < 1e-9 + 0.0051 for g, w in zip(got, want, strict=True)):
|
||||
exact = all(abs(g - w) < 0.005 for g, w in zip(got, want, strict=True))
|
||||
verdict = "match" if exact else "match_within_0.01"
|
||||
else:
|
||||
verdict = "differs"
|
||||
row["official_check"] = verdict
|
||||
counts[verdict] = counts.get(verdict, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("workbook", type=Path)
|
||||
parser.add_argument("--out", type=Path, required=True)
|
||||
parser.add_argument("--official", type=Path, help="folder with the NCI's five downloadable tables")
|
||||
args = parser.parse_args()
|
||||
rows = read(args.workbook)
|
||||
book = openpyxl.load_workbook(args.workbook)
|
||||
comparison = None
|
||||
if args.official:
|
||||
reference = official(args.official)
|
||||
comparison = {"files": {t: {k: v for k, v in f.items() if k != "rows"}
|
||||
for t, f in reference.items()},
|
||||
"verdicts": check(rows, reference)} # fmt: skip
|
||||
resource = {
|
||||
"id": "nci-cin3plus-master-2022-04-04",
|
||||
"status": "experimental: not validated clinically or methodologically",
|
||||
"source": {**SOURCE, "file": args.workbook.name,
|
||||
"sha256": hashlib.sha256(args.workbook.read_bytes()).hexdigest(),
|
||||
"workbook_created": str(book.properties.created),
|
||||
"workbook_modified": str(book.properties.modified)},
|
||||
"outcome": OUTCOME, "unit": "percent (two decimals) in the workbook; probabilities here",
|
||||
"population": {"age_years": [25, 65], "note": "The NCI's tables are for ages 25 to 65 (KPNC, "
|
||||
"2003 to 2017); the workbook itself does not state it."},
|
||||
"horizons_years": {"screening": [0, 5], "surveillance": [0, 5], "colposcopy_results": [1, 5],
|
||||
"post_colposcopy": [0, 5], "post_treatment": [0, 5]},
|
||||
"row_counts": {t: sum(r["table"] == t for r in rows) for t, _, _ in TABLES.values()},
|
||||
"official_comparison": comparison, "rows": rows,
|
||||
}
|
||||
args.out.write_text(json.dumps(resource, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
||||
print(json.dumps({"rows": len(rows), "per_table": resource["row_counts"],
|
||||
"official": comparison["verdicts"] if comparison else None}, indent=1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user