Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8a860c698f | |||
| 6e6c5bb81b | |||
| d27319ad1f | |||
| b5480e8bbb | |||
| dbbea0b16e | |||
| 76e88d0779 |
+14
-1
@@ -1,8 +1,21 @@
|
||||
"""CaCu's training and scoring jobs (models.jobs) over its models and reports."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from models.cacu import reports
|
||||
from models.cacu.specs import MODELS
|
||||
from models.jobs import Jobs
|
||||
from persistance import gold
|
||||
|
||||
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
|
||||
|
||||
def attrition(spec, as_of: date) -> dict | None:
|
||||
"""The attrition of the spec's cohort; None when eligibility doesn't list that cohort."""
|
||||
scenario = reports.COHORT_SCENARIOS.get(spec.cohort)
|
||||
if scenario is None:
|
||||
return None
|
||||
rows = gold.cacu_eligibility_report(scenario, cutoff=as_of)
|
||||
return reports.attrition(spec.cohort, rows, gold.people("cacu_events", as_of), as_of)
|
||||
|
||||
|
||||
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability, attrition)
|
||||
train, score = JOBS.train, JOBS.score
|
||||
|
||||
@@ -9,6 +9,8 @@ validation, is a document the clinical team adds). Both are data the governance
|
||||
For the logistic regression, its coefficients and calibration by risk decile.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy.stats import norm
|
||||
@@ -23,6 +25,61 @@ BOOTSTRAP = 200
|
||||
SEED = 20261122
|
||||
Z = norm.ppf(0.975)
|
||||
|
||||
# The scenario of gold.cacu_eligibility that lists each cohort's candidates.
|
||||
COHORT_SCENARIOS = {
|
||||
"cacu_cohort_surveillance": "surveillance",
|
||||
"cacu_cohort_post_colposcopy": "post_colposcopy",
|
||||
"cacu_cohort_post_treatment": "post_treatment",
|
||||
"cacu_cohort_survival": "survival",
|
||||
}
|
||||
# Reasons that a result still to arrive could lift.
|
||||
AWAITING = {"unreported_biopsy", "no_index_result"}
|
||||
# Clinical categories, not execution order: a candidate may belong to several stages.
|
||||
REASON_STAGE = {
|
||||
"hysterectomy": "eligibility", "under_18": "eligibility",
|
||||
"no_birth_date": "eligibility", "died_by_index": "eligibility",
|
||||
"prior_outcome": "history", "outcome_by_index": "history",
|
||||
"cancer_history": "history", "prior_treatment": "history",
|
||||
"outcome_before_index": "history", "no_pretreatment_biopsy": "history",
|
||||
"no_referral": "index", "no_cotest": "index",
|
||||
"no_index_result": "index", "unreported_biopsy": "index",
|
||||
}
|
||||
|
||||
|
||||
def attrition(cohort: str, rows: pd.DataFrame, people: int, as_of: date) -> dict:
|
||||
"""Who a cohort lost and why, up to `as_of`. `rows`: its candidates' eligibility report (one
|
||||
row per candidate and reason). A candidate with several reasons counts once in `excluded`
|
||||
and once in each reason; `pending` are the excluded whose every reason awaits a result."""
|
||||
rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()]
|
||||
key = ["person_id", "index_date", "index_sample_id"]
|
||||
candidates = rows[key].drop_duplicates()
|
||||
excluded = rows[rows["criterion"].notna()]
|
||||
reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set)
|
||||
pending = int(sum(found <= AWAITING for found in reasons))
|
||||
stages = excluded.assign(stage=excluded["criterion"].map(REASON_STAGE).fillna("unknown"))
|
||||
return {
|
||||
"cohort": cohort,
|
||||
"scenario": COHORT_SCENARIOS[cohort],
|
||||
"as_of": as_of.isoformat(),
|
||||
"people": people,
|
||||
"without_candidate": people - int(candidates["person_id"].nunique()),
|
||||
"candidates": len(candidates),
|
||||
"eligible": len(candidates) - len(reasons),
|
||||
"excluded": len(reasons),
|
||||
"pending": pending,
|
||||
"by_reason": {
|
||||
str(reason): int(count)
|
||||
for reason, count in excluded["criterion"].value_counts().sort_index().items()
|
||||
},
|
||||
"by_stage": {
|
||||
str(stage): len(group[key].drop_duplicates())
|
||||
for stage, group in stages.groupby("stage", sort=True)
|
||||
},
|
||||
"stage_by_reason": {str(reason): REASON_STAGE.get(str(reason), "unknown")
|
||||
for reason in sorted(excluded["criterion"].unique())},
|
||||
"stage_counts_overlap": True,
|
||||
}
|
||||
|
||||
|
||||
def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
|
||||
if isinstance(spec, survival.Spec):
|
||||
|
||||
+12
-2
@@ -20,6 +20,16 @@ from models.survival import Spec, age_group
|
||||
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
|
||||
TRAIN_FRACTION = 0.7
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
||||
SURVIVAL_AGE_CUTS = (35, 45, 55)
|
||||
SURVIVAL_SCENARIOS = {
|
||||
**{
|
||||
f"Edad al diagnóstico · {group} años": (("age_group", "==", group),)
|
||||
for group in ("<35", "35-44", "45-54", "≥55")
|
||||
},
|
||||
**{f"Citología · {group}": (("cytology", "==", group),) for group in cacu.KPNC},
|
||||
"VPH positivo": (("hpv", "==", "positive"),),
|
||||
"VPH negativo": (("hpv", "==", "negative"),),
|
||||
}
|
||||
|
||||
|
||||
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
|
||||
@@ -163,7 +173,7 @@ def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataF
|
||||
"""Each member's most recent observations up to her index (that day included): her age
|
||||
group, the KPNC category of her latest cytology result and her latest HPV result."""
|
||||
found = pd.DataFrame(index=members.index)
|
||||
found["age_group"] = age_group(events, members, (35, 45, 55))
|
||||
found["age_group"] = age_group(events, members, SURVIVAL_AGE_CUTS)
|
||||
prior = events[events["date"] <= events["index_date"]]
|
||||
names = list(cacu.KPNC)
|
||||
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
|
||||
@@ -200,6 +210,6 @@ MODELS = {
|
||||
Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
|
||||
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
||||
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
||||
interval_level=0.95),
|
||||
interval_level=0.95, scenarios=SURVIVAL_SCENARIOS),
|
||||
]
|
||||
} # fmt: skip
|
||||
|
||||
+14
-1
@@ -107,6 +107,19 @@ def analyze():
|
||||
analyze_studies()
|
||||
|
||||
|
||||
@dg.op
|
||||
def build_gold(context: dg.OpExecutionContext) -> None:
|
||||
"""Silver and everything derived from it, with the deployed code: what an ingest ends
|
||||
with, without ingesting (after deploying a version that changes the tables)."""
|
||||
silver.build(["silver+"])
|
||||
context.log.info("silver and gold rebuilt")
|
||||
|
||||
|
||||
@dg.job(tags=WRITES)
|
||||
def rebuild():
|
||||
build_gold()
|
||||
|
||||
|
||||
@dg.op
|
||||
def make_backup(context: dg.OpExecutionContext) -> str:
|
||||
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
|
||||
@@ -131,4 +144,4 @@ nightly = (
|
||||
else []
|
||||
)
|
||||
|
||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
|
||||
defs = dg.Definitions(jobs=[ingest, train, score, analyze, rebuild, backup], schedules=nightly)
|
||||
|
||||
+18
-8
@@ -24,6 +24,7 @@ from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||
|
||||
from core import catalog, concept_map, fhir_in
|
||||
from core.pipeline import (
|
||||
FIELD_EVIDENCE,
|
||||
HELD,
|
||||
IDENTIFIERS,
|
||||
QUOTES,
|
||||
@@ -184,14 +185,11 @@ def run_map(p: str, node: Map):
|
||||
|
||||
|
||||
def run_fhir(p: str, node: Fhir):
|
||||
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
|
||||
"""Resolve a sender's references across the Bundles accumulated at its source."""
|
||||
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
|
||||
found: dict[str, dict] = {}
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
bundle = json.loads(row[node.column])
|
||||
for r in fhir_in.rows(bundle, node.entity, p, maps):
|
||||
found[r[RECORD]] = r
|
||||
return nodes.write(p, node.id, list(found.values()))
|
||||
stored = sorted(nodes.rows(p, node.inputs[0]), key=lambda r: str(r.get("received_at") or ""))
|
||||
bundle = fhir_in.combined(json.loads(row[node.column]) for row in stored)
|
||||
return nodes.write(p, node.id, fhir_in.rows(bundle, node.entity, p, maps))
|
||||
|
||||
|
||||
def run_join(p: str, node: Join):
|
||||
@@ -486,6 +484,7 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
linked = {r[RECORD]: r for r in nodes.rows(p, link)}
|
||||
person = {k: r["person_id"] for k, r in linked.items()}
|
||||
model, study = catalog.model(node.entity), catalog.studies()[node.entity]
|
||||
report = study.events.get("report")
|
||||
fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction
|
||||
observations, held_rows = [], []
|
||||
for i in (i for i in node.inputs if i != link):
|
||||
@@ -506,9 +505,20 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
continue
|
||||
clean = model.model_validate(values)
|
||||
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
|
||||
evidence = json.loads(row.get(FIELD_EVIDENCE) or "{}")
|
||||
for name, field in study.fields.items():
|
||||
if (value := getattr(clean, name)) is not None:
|
||||
observations.append({**base, "instance": instance, "field": name,
|
||||
provenance = evidence.get(name)
|
||||
if provenance is None:
|
||||
event_date = getattr(clean, study.events[field.event].date)
|
||||
# A dated report or note documents the values it contains.
|
||||
documented = getattr(clean, report.date) if report else event_date
|
||||
provenance = {
|
||||
"source_ref": row[RECORD],
|
||||
"source_clinical_date": str(event_date) if event_date else None,
|
||||
"source_available_at": str(documented) if documented else None,
|
||||
}
|
||||
observations.append({**base, **provenance, "instance": instance, "field": name,
|
||||
catalog.value_column(field): value}) # fmt: skip
|
||||
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
||||
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
||||
|
||||
@@ -35,6 +35,8 @@ class Jobs:
|
||||
models: dict
|
||||
technical_validation: Callable[..., dict]
|
||||
interpretability: Callable[..., dict]
|
||||
# (spec, as_of) -> who the model's cohort lost, kept beside the reports; None: not kept
|
||||
attrition: Callable[..., dict | None] | None = None
|
||||
|
||||
@property
|
||||
def events(self) -> str:
|
||||
@@ -72,6 +74,8 @@ class Jobs:
|
||||
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
|
||||
# for its idle workers to time out (5 minutes) before it can end.
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
if self.attrition and (lost := self.attrition(spec, as_of)) is not None:
|
||||
found = {**found, "attrition": lost} # not one of the reports promotion asks for
|
||||
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
|
||||
model = Predictor(spec, fitted)
|
||||
return registry.register(self.registered(name), model, params, metrics, found)
|
||||
|
||||
+20
-1
@@ -487,7 +487,7 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
for n, m in masks.items() if n not in drawn] # fmt: skip
|
||||
combinations = spec._combinations(train).value_counts().reset_index(name="members")
|
||||
survival = model.survival(combinations.replace(UNKNOWN, None))
|
||||
return {
|
||||
report = {
|
||||
"model": spec.name,
|
||||
"kind": "curves",
|
||||
"curves": curves,
|
||||
@@ -509,6 +509,25 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
|
||||
**risk_factor_report(spec, model, members),
|
||||
}
|
||||
if spec.cohort.startswith("cacu_"):
|
||||
for curve in report["curves"]:
|
||||
method = ("greenwood_log_log" if curve["name"].startswith("Kaplan-Meier")
|
||||
else "delta_method")
|
||||
curve["interval"] = {"available": True, "level": 0.95, "method": method}
|
||||
report["predicted"]["interval"] = {
|
||||
"available": True, "level": 0.95, "method": "bootstrap_percentile"}
|
||||
for combination in report["combinations"]:
|
||||
combination["interval"] = {"available": False, "level": None, "method": None}
|
||||
for scenario in report["escenarios"]:
|
||||
scenario["km"]["interval"] = {
|
||||
"available": True, "level": 0.95, "method": "greenwood_log_log"}
|
||||
for name in ("weibull", "weibull_fractional"):
|
||||
scenario[name]["interval"] = {"available": False, "level": None, "method": None}
|
||||
scenario["points"]["COMB"]["interval"] = {
|
||||
"available": True, "level": 0.95, "method": "bootstrap_percentile"}
|
||||
for scenario in report["escenarios_sin_curvas"]:
|
||||
scenario["reason"] = "insufficient_deaths"
|
||||
return report
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- risk factors
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Attrition of a CaCu cohort: candidates, eligible, pending and reasons, each counted once."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu import reports
|
||||
|
||||
|
||||
def test_a_candidate_with_two_reasons_is_excluded_once():
|
||||
"""Pins the totals, the pending rule, the people without a candidate and the as-of cut."""
|
||||
rows = pd.DataFrame(
|
||||
[
|
||||
("eligible", "2025-01-01", None, None),
|
||||
("two", "2025-01-01", None, "hysterectomy"),
|
||||
("two", "2025-01-01", None, "under_18"),
|
||||
("waiting", "2025-01-01", None, "no_index_result"),
|
||||
("waiting_and_out", "2025-01-01", None, "no_index_result"),
|
||||
("waiting_and_out", "2025-01-01", None, "prior_outcome"),
|
||||
("after", "2025-07-01", None, "hysterectomy"),
|
||||
],
|
||||
columns=["person_id", "index_date", "index_sample_id", "criterion"],
|
||||
)
|
||||
|
||||
found = reports.attrition("cacu_cohort_surveillance", rows, 10, date(2025, 6, 30))
|
||||
|
||||
assert (found["candidates"], found["eligible"], found["excluded"]) == (4, 1, 3)
|
||||
assert (found["pending"], found["without_candidate"]) == (1, 6)
|
||||
assert found["by_reason"] == {
|
||||
"hysterectomy": 1, "no_index_result": 2, "prior_outcome": 1, "under_18": 1,
|
||||
} # fmt: skip
|
||||
assert found["by_stage"] == {"eligibility": 1, "history": 1, "index": 2}
|
||||
assert found["stage_by_reason"]["no_index_result"] == "index"
|
||||
assert found["stage_counts_overlap"] is True
|
||||
@@ -13,7 +13,10 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from joblib import parallel_config
|
||||
|
||||
from models import curves, survival
|
||||
from models.cacu import reports
|
||||
from models.cacu.specs import MODELS
|
||||
|
||||
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
|
||||
@@ -83,7 +86,7 @@ def test_predictions_match_the_current_models(name):
|
||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
||||
|
||||
|
||||
def test_survival_matches_the_current_model_with_its_index_fixed():
|
||||
def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monkeypatch):
|
||||
"""Indexed at the first biopsy reported as carcinoma or carcinoma in situ (the current
|
||||
index read only invasive carcinoma, so it indexed nobody; the reference was captured with
|
||||
that fixed); out: no birth date, a death by the biopsy."""
|
||||
@@ -99,7 +102,7 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
|
||||
index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
|
||||
events = events.merge(index, left_on="person_id", right_index=True)
|
||||
|
||||
model, metrics, _ = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
||||
model, metrics, data = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date())
|
||||
current = json.loads((REFERENCE / "models.json").read_text())["survival"]["version"]
|
||||
for name in ("n_train", "n_test", "events_train", "events_test", "stack_w_lr_12m",
|
||||
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
|
||||
@@ -113,6 +116,20 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
|
||||
("ci_high", "ic_alto")]: # fmt: skip
|
||||
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True)
|
||||
|
||||
monkeypatch.setattr(survival, "BOOTSTRAP", 3)
|
||||
monkeypatch.setattr(curves, "fit_fractional", lambda d, c, k, lam: (1.0, 1.0, lam))
|
||||
with parallel_config(backend="sequential"):
|
||||
report = reports.interpretability(spec, model, data)
|
||||
(scenario,) = report["escenarios"]
|
||||
name = scenario["escenario"]
|
||||
assert name == "Citología · HSIL+"
|
||||
assert scenario["horizons_months"] == [12, 36, 60]
|
||||
km = scenario["km"]
|
||||
assert km["months"] and len(km["months"]) == len(km["low"]) == len(km["high"])
|
||||
scored = found.drop_duplicates("person_id")
|
||||
assert scored["scenarios"].str.contains(name, regex=False, na=False).sum() == scenario["n"]
|
||||
assert "VPH negativo" in {row["escenario"] for row in report["escenarios_sin_curvas"]}
|
||||
|
||||
|
||||
def test_a_cohort_the_site_lacks_is_reported_not_trained(monkeypatch):
|
||||
"""A site with no colposcopies has nobody in the post-colposcopy cohort: training that
|
||||
|
||||
Reference in New Issue
Block a user