Compare commits

...

3 Commits

4 changed files with 56 additions and 12 deletions
+7
View File
@@ -115,6 +115,13 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
key = ["person_id", "source_table", "source_id"] key = ["person_id", "source_table", "source_id"]
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred), samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
[*key, "date"]] # fmt: skip [*key, "date"]] # fmt: skip
hysterectomy = events.loc[
(events["source_table"] == "cervical_cytology")
& (events["type"] == "gynecologic_condition")
& (events["value_code"] == "hysterectomy")
].groupby("person_id")["date"].min()
recorded = samples["person_id"].map(hysterectomy)
samples = samples[recorded.isna() | (samples["date"] < recorded)]
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()] results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first") has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
has = has.reindex(columns=list(RESULTS)) has = has.reindex(columns=list(RESULTS))
+12 -2
View File
@@ -20,6 +20,16 @@ from models.survival import Spec, age_group
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0) HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
TRAIN_FRACTION = 0.7 TRAIN_FRACTION = 0.7
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"] 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: 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 """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.""" group, the KPNC category of her latest cytology result and her latest HPV result."""
found = pd.DataFrame(index=members.index) 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"]] prior = events[events["date"] <= events["index_date"]]
names = list(cacu.KPNC) names = list(cacu.KPNC)
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes} 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), Logistic("cin2_logistic", "cacu_cohort_surveillance", cacu.CIN2_PLUS),
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"), Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
survival_covariates, borders=(0, 12, 36, 60), cap_months=60, survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
interval_level=0.95), interval_level=0.95, scenarios=SURVIVAL_SCENARIOS),
] ]
} # fmt: skip } # fmt: skip
+18 -8
View File
@@ -24,6 +24,7 @@ from splink.clustering import cluster_pairwise_predictions_at_threshold
from core import catalog, concept_map, fhir_in from core import catalog, concept_map, fhir_in
from core.pipeline import ( from core.pipeline import (
FIELD_EVIDENCE,
HELD, HELD,
IDENTIFIERS, IDENTIFIERS,
QUOTES, QUOTES,
@@ -184,14 +185,11 @@ def run_map(p: str, node: Map):
def run_fhir(p: str, node: Fhir): 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 [] maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
found: dict[str, dict] = {} stored = sorted(nodes.rows(p, node.inputs[0]), key=lambda r: str(r.get("received_at") or ""))
for row in nodes.rows(p, node.inputs[0]): bundle = fhir_in.combined(json.loads(row[node.column]) for row in stored)
bundle = json.loads(row[node.column]) return nodes.write(p, node.id, fhir_in.rows(bundle, node.entity, p, maps))
for r in fhir_in.rows(bundle, node.entity, p, maps):
found[r[RECORD]] = r
return nodes.write(p, node.id, list(found.values()))
def run_join(p: str, node: Join): 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)} linked = {r[RECORD]: r for r in nodes.rows(p, link)}
person = {k: r["person_id"] for k, r in linked.items()} person = {k: r["person_id"] for k, r in linked.items()}
model, study = catalog.model(node.entity), catalog.studies()[node.entity] 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 fixed = nodes.corrections() # a reviewer's reading of a value wins over the extraction
observations, held_rows = [], [] observations, held_rows = [], []
for i in (i for i in node.inputs if i != link): 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 continue
clean = model.model_validate(values) clean = model.model_validate(values)
instance = json.dumps([str(getattr(clean, k)) for k in model.key]) 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(): for name, field in study.fields.items():
if (value := getattr(clean, name)) is not None: 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 catalog.value_column(field): value}) # fmt: skip
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
+19 -2
View File
@@ -13,7 +13,10 @@ from pathlib import Path
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import pytest import pytest
from joblib import parallel_config
from models import curves, survival
from models.cacu import reports
from models.cacu.specs import MODELS from models.cacu.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu" 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() 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 """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 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.""" 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)] index = index[index.index.isin(born) & ~(died.reindex(index.index) <= index)]
events = events.merge(index, left_on="person_id", right_index=True) 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"] 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", 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 "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 ("ci_high", "ic_alto")]: # fmt: skip
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, equal_nan=True) 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): 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 """A site with no colposcopies has nobody in the post-colposcopy cohort: training that