Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 76e88d0779 | |||
| 8548eb8d9e | |||
| 1a1ea5c7a9 |
@@ -115,6 +115,13 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
||||
key = ["person_id", "source_table", "source_id"]
|
||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||
[*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()]
|
||||
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||
has = has.reindex(columns=list(RESULTS))
|
||||
|
||||
+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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -32,7 +32,7 @@ FIELDS = {
|
||||
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
||||
"eeg": ("study_date", "lab_record_id", "edf"),
|
||||
} # fmt: skip
|
||||
BOOLS = {"hpv", "hpv_16", "hpv_18"}
|
||||
BOOLS = {f for s in catalog.studies().values() for f, d in s.fields.items() if d.type == "boolean"}
|
||||
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user