328 lines
18 KiB
Python
328 lines
18 KiB
Python
"""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
|