Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1feedad79a | |||
| da14e4ea8e | |||
| fe1f284e00 | |||
| d392cc02a5 | |||
| 8a860c698f | |||
| 6e6c5bb81b | |||
| d27319ad1f | |||
| b5480e8bbb | |||
| dbbea0b16e | |||
| 76e88d0779 |
@@ -0,0 +1,234 @@
|
||||
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her
|
||||
index date. NaN is missing: an absent value is never 0. No model reads these; they are
|
||||
there for when one does.
|
||||
|
||||
Only what was available at the index is read (see `visible`): the index sample's results,
|
||||
reported after it, are missing when the index is the sample day.
|
||||
|
||||
Inputs are the gold timeline with its `evidence_date` and `source_available_at`
|
||||
(persistance.gold.evidence_timelines) and, for the form fields gold does not carry, the
|
||||
wide silver cytology (persistance.gold.cervical_forms)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu, catalog
|
||||
from models.cacu.features import _referral_grade, _worst, prepared
|
||||
from models.cacu.specs import _REFERRAL
|
||||
from models.survival import age_group, band
|
||||
|
||||
# What was done to her before the index: the index day's own is left out, as it may be
|
||||
# (or follow from) the outcome.
|
||||
PROCEDURES = ("biopsy", "biopsy_order", "colposcopy", "treatment", "diagnosis", "history")
|
||||
EXAM_FIELDS = ("gynecologic_condition", "presenting_symptom", "cervix_appearance")
|
||||
GENOTYPES = cacu.HPV_GENOTYPE_FIELDS
|
||||
EVIDENCE_TABLE = "cacu_eligibility_evidence"
|
||||
|
||||
|
||||
def _codes(field: str) -> list[str]:
|
||||
return list(catalog.studies()["cervical_cytology"].fields[field].codes)
|
||||
|
||||
|
||||
FINDINGS = tuple(
|
||||
name for name, f in catalog.studies()["cervical_cytology"].fields.items()
|
||||
if name.startswith("finding_") and f.type == "boolean"
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _day(values: pd.Series) -> pd.Series:
|
||||
"""The calendar day of dates or ISO timestamps (as written); empty stays NaT."""
|
||||
return pd.to_datetime(values.astype("string").str[:10], format="%Y-%m-%d")
|
||||
|
||||
|
||||
def visible(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each member's events available at her index, with her index date:
|
||||
|
||||
- dated (a result: reported) and, if it has one, clinically dated by the index;
|
||||
- `source_available_at`, when the source gave it, by the index day. When it gave none,
|
||||
the event's date stands, except for standalone eligibility evidence, dated by its
|
||||
clinical onset: that is left out, as the cohort rules do;
|
||||
- procedures and diagnoses strictly before the index day.
|
||||
|
||||
`known_at` (when the platform loaded it) is not read."""
|
||||
found = events.drop(columns="index_date", errors="ignore").merge(
|
||||
members[["person_id", "index_date"]], on="person_id"
|
||||
)
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
date, clinical = _day(found["date"]), _day(found["evidence_date"])
|
||||
available = _day(found["source_available_at"])
|
||||
keep = (date <= index) & (clinical.isna() | (clinical <= index))
|
||||
undated = available.isna() & (found["source_table"] != EVIDENCE_TABLE)
|
||||
keep &= undated | (available <= index)
|
||||
earlier = (date < index) & (clinical.isna() | (clinical < index))
|
||||
hysterectomy = (found["type"] == "gynecologic_condition") & (
|
||||
found["value_code"] == "hysterectomy"
|
||||
)
|
||||
keep &= earlier | ~(found["type"].isin(PROCEDURES) | hysterectomy)
|
||||
return prepared(found[keep])
|
||||
|
||||
|
||||
def _flag(known: pd.Series, true: pd.Series) -> pd.Series:
|
||||
"""1.0 / 0.0 where `known`, NaN elsewhere."""
|
||||
return pd.Series(np.where(known, true.astype(float), np.nan), index=known.index)
|
||||
|
||||
|
||||
def _one_hot(values: pd.Series, prefix: str, codes: list[str]) -> dict[str, pd.Series]:
|
||||
"""One column per code; a value that is none of them is missing, not 0 in all."""
|
||||
known = values.isin(codes)
|
||||
return {f"{prefix}__{code}": _flag(known, values == code) for code in codes}
|
||||
|
||||
|
||||
def _present(events: pd.DataFrame, people: pd.Index) -> pd.Series:
|
||||
"""1 when recorded; NaN otherwise (no record does not show it never happened)."""
|
||||
return pd.Series(np.where(people.isin(events["person_id"]), 1.0, np.nan), index=people)
|
||||
|
||||
|
||||
def _latest(events: pd.DataFrame, kind: str, people: pd.Index) -> pd.Series:
|
||||
"""Each member's latest recorded value of one kind of event."""
|
||||
found = events[(events["type"] == kind) & events["value_code"].notna()]
|
||||
found = found.sort_values(["date", "source_id"], kind="stable")
|
||||
return found.groupby("person_id")["value_code"].last().reindex(people)
|
||||
|
||||
|
||||
def _latest_bethesda(events: pd.DataFrame, people: pd.Index) -> pd.Series:
|
||||
"""The result of her latest report; the most severe when that day has several."""
|
||||
codes = _codes("result")
|
||||
found = events[(events["type"] == "bethesda") & events["value_code"].isin(codes)]
|
||||
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
|
||||
# severity is the order of the KPNC categories, not the catalog's
|
||||
severity = {name: [name] for names in cacu.KPNC.values() for name in names if name in codes}
|
||||
return _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
|
||||
|
||||
|
||||
def _age(events: pd.DataFrame, members: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
cuts = [low for low, _ in cacu.AGE_GROUPS] + [cacu.AGE_GROUPS[-1][1] + 1]
|
||||
keyed = members.set_index("person_id", drop=False)
|
||||
keyed = keyed.assign(index_date=pd.to_datetime(keyed["index_date"]))
|
||||
found = age_group(events, keyed, cuts)
|
||||
labels = list(band(pd.Series([cuts[0] - 1, *cuts]), cuts))
|
||||
return _one_hot(found, "age", labels)
|
||||
|
||||
|
||||
def _cytology(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
result = _latest_bethesda(events, people)
|
||||
columns = _one_hot(result, "bethesda", _codes("result"))
|
||||
for name, codes in cacu.PROCEDURE_CYTOLOGY.items():
|
||||
columns[f"cytology_{name}"] = _flag(result.notna(), result.isin(codes))
|
||||
return columns
|
||||
|
||||
|
||||
def _hpv(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
columns = {}
|
||||
for kind in ("hpv", *GENOTYPES):
|
||||
value = _latest(events, kind, people)
|
||||
columns[f"{kind}_positive"] = _flag(
|
||||
value.isin(["positive", "negative"]), value == "positive"
|
||||
)
|
||||
# From the two genotypes of one sample, not gold's `hpv_16_18`: that is 0 when one is
|
||||
# negative and the other was not reported.
|
||||
found = events[events["type"].isin(GENOTYPES) & events["value_code"].notna()]
|
||||
wide = found.pivot_table(
|
||||
index=["person_id", "date", "source_id"], columns="type", values="value_code",
|
||||
aggfunc="first",
|
||||
).reindex(columns=list(GENOTYPES)) # fmt: skip
|
||||
latest = wide.sort_index().reset_index().drop_duplicates("person_id", keep="last")
|
||||
latest = latest.set_index("person_id").reindex(people)[list(GENOTYPES)]
|
||||
positive = (latest == "positive").any(axis=1)
|
||||
both_negative = (latest == "negative").all(axis=1)
|
||||
columns["hpv_16_or_18_positive"] = _flag(positive | both_negative, positive)
|
||||
return columns
|
||||
|
||||
|
||||
def _history(events: pd.DataFrame, people: pd.Index) -> dict[str, pd.Series]:
|
||||
of = {kind: events[events["type"] == kind] for kind in (*PROCEDURES, "cytology")}
|
||||
columns = {
|
||||
"prior_cytology_sample": _present(
|
||||
of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]], people
|
||||
),
|
||||
"prior_biopsy_order": _present(of["biopsy_order"], people),
|
||||
"prior_biopsy_report": _present(of["biopsy"], people),
|
||||
"prior_colposcopy": _present(of["colposcopy"], people),
|
||||
"prior_treatment": _present(of["treatment"], people),
|
||||
"prior_diagnosis_note": _present(of["diagnosis"], people),
|
||||
"history_cancer_icd10": _present(of["history"], people),
|
||||
"history_hysterectomy": _present(
|
||||
events[(events["type"] == "gynecologic_condition")
|
||||
& (events["value_code"] == "hysterectomy")], people
|
||||
),
|
||||
} # fmt: skip
|
||||
|
||||
rank = {grade: i for i, grade in enumerate(cacu.BIOPSY_SEVERITY)}
|
||||
worst = of["biopsy"]["value_code"].map(rank).groupby(of["biopsy"]["person_id"]).max()
|
||||
worst = worst.reindex(people)
|
||||
for name, grade in (("lsil_plus", "LSIL"), ("hsil_plus", "HSIL"), ("carcinoma", "carcinoma")):
|
||||
columns[f"prior_biopsy_{name}"] = _flag(worst.notna(), worst >= rank[grade])
|
||||
|
||||
persons = pd.Series(people, index=people)
|
||||
if events["type"].eq("colposcopy").any():
|
||||
grade = _referral_grade(events, persons, _REFERRAL | {"cytology": cacu.KPNC_3})
|
||||
else:
|
||||
grade = pd.Series(None, index=people, dtype=object)
|
||||
columns["referral_high_grade"] = _flag(grade.notna(), grade == "high")
|
||||
return columns
|
||||
|
||||
|
||||
def _forms(forms: pd.DataFrame | None, members: pd.DataFrame) -> dict[str, pd.Series]:
|
||||
"""The cytology form's fields gold does not carry. Silver keeps no
|
||||
`source_available_at` for them: what the sample form says counts from the sample day,
|
||||
what the report says from the report day."""
|
||||
people = pd.Index(members["person_id"])
|
||||
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
|
||||
*FINDINGS] # fmt: skip
|
||||
if forms is None:
|
||||
forms = pd.DataFrame(columns=columns)
|
||||
found = forms[columns].merge(members[["person_id", "index_date"]], on="person_id")
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
|
||||
sampled = found[(_day(found["sample_date"]) <= index) & found["screening_history"].notna()]
|
||||
sampled = sampled.sort_values("sample_date", key=_day, kind="stable")
|
||||
history = sampled.groupby("person_id")["screening_history"].last().reindex(people)
|
||||
|
||||
reported = found[(_day(found["report_date"]) <= index) & (_day(found["sample_date"]) <= index)]
|
||||
reported = reported.assign(r=_day(reported["report_date"]), s=_day(reported["sample_date"]))
|
||||
# Her latest report, whole: a finding it does not state is unknown, whatever older
|
||||
# reports said.
|
||||
report = reported.sort_values(["r", "s"], kind="stable").drop_duplicates(
|
||||
"person_id", keep="last"
|
||||
)
|
||||
report = report.set_index("person_id").reindex(people)
|
||||
|
||||
out = _one_hot(history, "screening_history", _codes("screening_history"))
|
||||
adequacy = report["adequacy"]
|
||||
out["sample_unsatisfactory"] = _flag(
|
||||
adequacy.isin(_codes("adequacy")), adequacy == "unsatisfactory"
|
||||
)
|
||||
for name in FINDINGS:
|
||||
value = report[name]
|
||||
out[name] = _flag(value.notna(), value.eq(True))
|
||||
return out
|
||||
|
||||
|
||||
def encode(events: pd.DataFrame, forms: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
"""One row per member of `events` (`person_id`, `index_date`): every encoder's column,
|
||||
0.0, 1.0 or NaN. `events` needs `evidence_date` and `source_available_at`; without
|
||||
`forms` their columns are all missing."""
|
||||
missing = {"evidence_date", "source_available_at"} - set(events.columns)
|
||||
if missing:
|
||||
raise ValueError(f"timeline without availability columns: {', '.join(sorted(missing))}")
|
||||
members = events[["person_id", "index_date"]].drop_duplicates().reset_index(drop=True)
|
||||
if members["person_id"].duplicated().any():
|
||||
raise ValueError("one index date per person")
|
||||
people = pd.Index(members["person_id"], name="person_id")
|
||||
seen = visible(events, members)
|
||||
|
||||
columns = _age(seen, members)
|
||||
columns |= _cytology(seen, people)
|
||||
columns |= _hpv(seen, people)
|
||||
exam = seen[seen["source_table"] == "cervical_cytology"]
|
||||
for field in EXAM_FIELDS:
|
||||
columns |= _one_hot(_latest(exam, field, people), field, _codes(field))
|
||||
columns |= _history(seen, people)
|
||||
columns |= _forms(forms, members)
|
||||
|
||||
values = {name: column.to_numpy(dtype=float) for name, column in columns.items()}
|
||||
return pd.concat([members, pd.DataFrame(values)], axis=1)
|
||||
+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
|
||||
|
||||
+45
-4
@@ -149,9 +149,20 @@ class Fit:
|
||||
up[k] += step
|
||||
down[k] -= step
|
||||
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
|
||||
covariance = np.nan_to_num(self.covariance, nan=0.0)
|
||||
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
|
||||
return self.risk(X, Z, years), np.maximum(variance, 0.0)
|
||||
free = np.isfinite(np.diag(self.covariance))
|
||||
variance = np.full((len(X), len(years)), np.nan)
|
||||
block = self.covariance[np.ix_(free, free)]
|
||||
if block.size and np.isfinite(block).all() and np.allclose(block, block.T):
|
||||
try:
|
||||
positive = bool(np.all(np.linalg.eigvalsh(block) > 0))
|
||||
except np.linalg.LinAlgError:
|
||||
positive = False
|
||||
if positive:
|
||||
values = np.einsum("kij,kl,lij->ij", gradient[free], block, gradient[free])
|
||||
affected = np.any(np.abs(gradient[~free]) > 1e-10, axis=0)
|
||||
valid = ~affected & np.isfinite(values) & (values >= 0)
|
||||
variance[valid] = values[valid]
|
||||
return self.risk(X, Z, years), variance
|
||||
|
||||
|
||||
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
|
||||
@@ -258,8 +269,38 @@ class Mixture(BaseEstimator):
|
||||
point, variance = self.fits_[key].risk_with_variance(
|
||||
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
||||
)
|
||||
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
|
||||
relative = np.where(np.isfinite(variance),
|
||||
np.sqrt(variance) / np.maximum(point, 1e-300), np.nan)
|
||||
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
|
||||
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
|
||||
out[index[placed]] = band[inverse.ravel()]
|
||||
return out
|
||||
|
||||
def variance_diagnostics(self, X: pd.DataFrame) -> dict:
|
||||
"""Per stratum covariance properties and input rows without a complete interval."""
|
||||
h = len(self.horizons_years)
|
||||
result = []
|
||||
for key, index in self._groups(X):
|
||||
f = self.fits_.get(key)
|
||||
predictions = self.predict(X.iloc[index])
|
||||
missing = np.isnan(predictions[:, h:]).any(axis=1)
|
||||
entry = {"stratum": [str(v) for v in key], "rows": len(index),
|
||||
"rows_without_interval": int(missing.sum())}
|
||||
if f is None:
|
||||
entry.update(status="unseen_stratum", frozen_parameters=[], negative_variances=[])
|
||||
else:
|
||||
diagonal = np.diag(f.covariance)
|
||||
frozen = np.flatnonzero(np.abs(f.params) >= FROZEN).tolist()
|
||||
negative = np.flatnonzero(np.isfinite(diagonal) & (diagonal < 0)).tolist()
|
||||
free = np.isfinite(diagonal)
|
||||
block = f.covariance[np.ix_(free, free)]
|
||||
try:
|
||||
positive = bool(block.size and np.isfinite(block).all()
|
||||
and np.allclose(block, block.T)
|
||||
and (np.linalg.eigvalsh(block) > 0).all())
|
||||
except np.linalg.LinAlgError:
|
||||
positive = False
|
||||
entry.update(status="positive_definite" if positive else "not_estimable",
|
||||
frozen_parameters=frozen, negative_variances=negative)
|
||||
result.append(entry)
|
||||
return {"strata": result, "horizons_years": list(self.horizons_years)}
|
||||
|
||||
+59
-1
@@ -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):
|
||||
@@ -72,7 +129,8 @@ def _label(feature: str, value) -> str:
|
||||
|
||||
|
||||
def _band(curve, variance) -> tuple[list, list]:
|
||||
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
|
||||
relative = np.where(np.isfinite(variance),
|
||||
np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan)
|
||||
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
||||
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
||||
|
||||
|
||||
+20
-6
@@ -2,6 +2,7 @@
|
||||
the prevalence-incidence mixture or a logistic regression. Training and scoring read the
|
||||
patient timelines of the spec's cohort (see features)."""
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Literal
|
||||
|
||||
@@ -20,9 +21,19 @@ 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:
|
||||
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, predictors=()) -> pd.DataFrame:
|
||||
"""One row per patient and horizon; patients the model can't score are left out."""
|
||||
h = len(horizons)
|
||||
scored = ~np.isnan(risks[:, :h]).any(axis=1)
|
||||
@@ -38,7 +49,10 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
|
||||
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
||||
else:
|
||||
frame["ci_low"] = frame["ci_high"] = np.nan
|
||||
return frame[OUTPUT]
|
||||
frame["input_values"] = np.repeat([
|
||||
json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str)
|
||||
for row in members[list(predictors)].to_dict("records")], h)
|
||||
return frame[[*OUTPUT, "input_values"]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -110,7 +124,7 @@ class Pim:
|
||||
events = events.assign(index_date=events["person_id"].map(chosen))
|
||||
members = f.index_results(events, self.cytology, self._history())
|
||||
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||
return _rows(members, mixture.predict(members[self.features]), self.horizons)
|
||||
return _rows(members, mixture.predict(members[self.features]), self.horizons, self.features)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -156,14 +170,14 @@ class Logistic:
|
||||
members = f.index_sample(f.prepared(events), list(self.predictors))
|
||||
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||
p = model.predict_proba(members[list(self.predictors)])[:, 1]
|
||||
return _rows(members, p[:, None], (self.years,))
|
||||
return _rows(members, p[:, None], (self.years,), self.predictors)
|
||||
|
||||
|
||||
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""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 +214,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:
|
||||
@@ -69,9 +71,14 @@ class Jobs:
|
||||
"technical_validation": self.technical_validation(spec, metrics, data),
|
||||
"interpretability": self.interpretability(spec, fitted, data),
|
||||
}
|
||||
if hasattr(fitted, "variance_diagnostics"):
|
||||
found["variance_diagnostics"] = fitted.variance_diagnostics(
|
||||
data["coded"][spec.features])
|
||||
# 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)
|
||||
|
||||
+53
-2
@@ -341,7 +341,7 @@ class Spec:
|
||||
masks = scenario_masks(members, self.scenarios)
|
||||
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
|
||||
for i in range(n)] # fmt: skip
|
||||
return pd.DataFrame({
|
||||
result = pd.DataFrame({
|
||||
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
||||
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
|
||||
"horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
|
||||
@@ -350,6 +350,11 @@ class Spec:
|
||||
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
|
||||
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
|
||||
})[OUTPUT] # fmt: skip
|
||||
if self.cohort.startswith("cacu_"):
|
||||
result["input_values"] = np.repeat([
|
||||
json.dumps({k: None if pd.isna(v) else v for k, v in row.items()}, default=str)
|
||||
for row in members[list(self.features)].to_dict("records")], h)
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reports (curves)
|
||||
@@ -430,6 +435,32 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def _combination_curves(spec: Spec, members: pd.DataFrame) -> list[dict]:
|
||||
"""Kaplan-Meier of the members who share every covariate value: the one curve a patient with
|
||||
those values is shown. Fewer than MIN_SCENARIO_EVENTS deaths: counts and why, no curve."""
|
||||
from models import curves
|
||||
|
||||
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
|
||||
keys = spec._combinations(members)
|
||||
found = []
|
||||
for values, rows in keys.groupby(list(spec.features), sort=True).indices.items():
|
||||
values = values if isinstance(values, tuple) else (values,)
|
||||
entry = {"valores": dict(zip(spec.features, values, strict=True)), "n": len(rows),
|
||||
"fallecidos": int(event[rows].sum())} # fmt: skip
|
||||
if entry["fallecidos"] < MIN_SCENARIO_EVENTS:
|
||||
entry["reason"] = "insufficient_deaths"
|
||||
else:
|
||||
until = int(months[rows].max())
|
||||
km = curves.kaplan_meier(months[rows], event[rows], until)
|
||||
entry["km"] = {
|
||||
"months": list(range(until + 1)),
|
||||
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)},
|
||||
"interval": {"available": True, "level": 0.95, "method": "greenwood_log_log"},
|
||||
}
|
||||
found.append(entry)
|
||||
return found
|
||||
|
||||
|
||||
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
|
||||
Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
|
||||
@@ -487,7 +518,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 +540,26 @@ 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"
|
||||
report["km_combinaciones"] = _combination_curves(spec, members)
|
||||
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
|
||||
@@ -0,0 +1,129 @@
|
||||
"""The binary encoders read only what was available at the index, and never turn an
|
||||
absent value into 0."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cacu.encoders import FINDINGS, encode
|
||||
|
||||
INDEX = "2025-06-10"
|
||||
|
||||
|
||||
def event(day, kind, code=None, person="p1", table="cervical_cytology", sample=None,
|
||||
clinical=None, available=None): # fmt: skip
|
||||
return {
|
||||
"person_id": person, "index_date": INDEX, "date": day, "type": kind,
|
||||
"value_code": code, "value_num": np.nan, "source_table": table,
|
||||
"source_id": sample or day, "evidence_date": clinical, "source_available_at": available,
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def form(sample, report, person="p1", **fields):
|
||||
empty = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
|
||||
return {"person_id": person, "sample_date": sample, "report_date": report} | empty | fields
|
||||
|
||||
|
||||
def row(events, forms=None, person="p1"):
|
||||
found = encode(pd.DataFrame(events), None if forms is None else pd.DataFrame(forms))
|
||||
return found.set_index("person_id").loc[person].drop("index_date").astype(float)
|
||||
|
||||
|
||||
def test_nothing_known_is_all_missing():
|
||||
found = row([event(INDEX, "cytology", "satisfactory")])
|
||||
assert found.isna().all()
|
||||
|
||||
|
||||
def test_values_and_missing():
|
||||
found = row([
|
||||
event("1980-06-11", "birth", table="person"),
|
||||
event("2025-01-15", "bethesda", "LSIL", sample="2025-01-10"),
|
||||
event("2025-01-15", "hpv", "positive", sample="2025-01-10"),
|
||||
event("2025-01-15", "hpv_16", "negative", sample="2025-01-10"),
|
||||
event(INDEX, "cervix_appearance", "lesion"),
|
||||
event(INDEX, "presenting_symptom", "not-a-code"),
|
||||
]) # fmt: skip
|
||||
assert found["age__35-44"] == 1 and found["age__45-54"] == 0
|
||||
assert found["bethesda__LSIL"] == 1 and found["bethesda__HSIL"] == 0
|
||||
assert found["cytology_ascus_plus"] == 1 and found["cytology_hsil_plus"] == 0
|
||||
assert found["hpv_positive"] == 1 and found["hpv_16_positive"] == 0
|
||||
assert np.isnan(found["hpv_18_positive"])
|
||||
# one genotype negative and the other unreported is unknown, not negative
|
||||
assert np.isnan(found["hpv_16_or_18_positive"])
|
||||
assert found["cervix_appearance__lesion"] == 1 and found["cervix_appearance__healthy"] == 0
|
||||
assert found.filter(like="presenting_symptom").isna().all() # ambiguous value
|
||||
assert found.filter(like="prior_").isna().all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("positive, other, expected", [
|
||||
("positive", None, 1.0), ("negative", "negative", 0.0), ("negative", "positive", 1.0),
|
||||
]) # fmt: skip
|
||||
def test_genotypes_combined(positive, other, expected):
|
||||
events = [event("2025-01-15", "hpv_16", positive)]
|
||||
if other:
|
||||
events.append(event("2025-01-15", "hpv_18", other))
|
||||
assert row(events)["hpv_16_or_18_positive"] == expected
|
||||
|
||||
|
||||
def test_nothing_later_than_the_index_is_read():
|
||||
base = [event(INDEX, "cytology", "satisfactory")]
|
||||
later = [
|
||||
event("2025-06-20", "bethesda", "HSIL", sample=INDEX), # the index sample's report
|
||||
event("2025-06-20", "hpv", "positive", sample=INDEX),
|
||||
event("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
|
||||
event("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
|
||||
# procedures of the index day may be the outcome
|
||||
event(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
|
||||
event(INDEX, "colposcopy", table="clinical_note"),
|
||||
event(INDEX, "treatment", table="clinical_note"),
|
||||
event("2025-08-01", "history", table="clinical_note"),
|
||||
# standalone evidence without an availability date: its onset says nothing of it
|
||||
event("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence"),
|
||||
] # fmt: skip
|
||||
forms = [form(INDEX, "2025-06-20", adequacy="unsatisfactory", finding_atrophy=True)]
|
||||
pd.testing.assert_series_equal(row(base + later, forms), row(base))
|
||||
|
||||
|
||||
def test_available_by_the_index_day_is_read():
|
||||
found = row([
|
||||
event("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
|
||||
event("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence", available="2024-01-01"),
|
||||
]) # fmt: skip
|
||||
assert found["cytology_hsil_plus"] == 1 and found["history_hysterectomy"] == 1
|
||||
|
||||
|
||||
def test_prior_procedures_and_referral():
|
||||
found = row([
|
||||
event("2025-01-15", "bethesda", "HSIL", sample="2025-01-10"),
|
||||
event("2025-03-01", "colposcopy", table="clinical_note"),
|
||||
event("2025-03-01", "biopsy_order", table="cervical_biopsy"),
|
||||
event("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
|
||||
]) # fmt: skip
|
||||
assert found["prior_colposcopy"] == 1 and found["prior_biopsy_order"] == 1
|
||||
assert found["prior_biopsy_lsil_plus"] == 1 and found["prior_biopsy_hsil_plus"] == 0
|
||||
assert found["referral_high_grade"] == 1
|
||||
assert np.isnan(found["prior_treatment"])
|
||||
|
||||
|
||||
def test_form_fields_come_from_the_latest_report():
|
||||
forms = [
|
||||
form("2024-01-10", "2024-01-20", screening_history="never", finding_atrophy=True),
|
||||
form("2025-01-10", "2025-01-20", adequacy="satisfactory", finding_candida=1),
|
||||
]
|
||||
found = row([event(INDEX, "cytology")], forms)
|
||||
assert found["screening_history__never"] == 1
|
||||
assert found["sample_unsatisfactory"] == 0 and found["finding_candida"] == 1
|
||||
assert np.isnan(found["finding_atrophy"])
|
||||
|
||||
|
||||
def test_members_are_kept_apart():
|
||||
events = [event("2025-01-15", "hpv", "positive"), event(INDEX, "cytology", person="p2")]
|
||||
assert np.isnan(row(events, person="p2")["hpv_positive"])
|
||||
|
||||
|
||||
def test_a_timeline_without_availability_is_refused():
|
||||
events = pd.DataFrame([event(INDEX, "cytology")]).drop(columns="source_available_at")
|
||||
with pytest.raises(ValueError, match="source_available_at"):
|
||||
encode(events)
|
||||
@@ -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"
|
||||
@@ -78,12 +81,16 @@ def test_predictions_match_the_current_models(name):
|
||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
||||
("ci_high", "ic_alto")]: # fmt: skip
|
||||
if theirs in both:
|
||||
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
|
||||
# Older reference intervals include non-estimable covariance estimates. Preserve
|
||||
# parity for point estimates and for intervals that remain estimable.
|
||||
comparable = both[ours].notna() if ours != "probability" else np.ones(len(both), bool)
|
||||
np.testing.assert_allclose(both.loc[comparable, ours], both.loc[comparable, theirs],
|
||||
rtol=RTOL, atol=0)
|
||||
if spec.method != "logistic regression":
|
||||
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,12 +106,13 @@ 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
|
||||
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
|
||||
found = spec.predict(model, events)
|
||||
assert all(set(json.loads(value)) == set(spec.features) for value in found['input_values'])
|
||||
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
||||
both = found.merge(reference, left_on=["person_id", "horizon_years"],
|
||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
||||
@@ -113,6 +121,25 @@ 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)
|
||||
combined = report["km_combinaciones"]
|
||||
assert sum(c["n"] for c in combined) == len(pd.concat([data["train"], data["test"]]))
|
||||
for c in combined:
|
||||
assert set(c["valores"]) == set(spec.features)
|
||||
assert ("km" in c) == (c["fallecidos"] >= survival.MIN_SCENARIO_EVENTS)
|
||||
(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
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import json
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu.specs import _rows
|
||||
|
||||
|
||||
def test_each_scored_horizon_keeps_the_inputs_of_its_patient():
|
||||
members = pd.DataFrame([
|
||||
{"person_id": "a", "index_date": "2026-01-01", "cytology": "NILM", "hpv": 0},
|
||||
{"person_id": "b", "index_date": "2026-02-01", "cytology": "HSIL", "hpv": 1},
|
||||
])
|
||||
result = _rows(members, np.array([[0.1, 0.2], [0.3, 0.4]]), (0, 5),
|
||||
("cytology", "hpv"))
|
||||
assert [json.loads(v) for v in result.input_values] == [
|
||||
{"cytology": "NILM", "hpv": 0}, {"cytology": "NILM", "hpv": 0},
|
||||
{"cytology": "HSIL", "hpv": 1}, {"cytology": "HSIL", "hpv": 1}]
|
||||
@@ -0,0 +1,40 @@
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cacu.pim import Fit, ISpline, Mixture
|
||||
|
||||
|
||||
def test_unestimable_covariances_never_produce_zero_width_intervals():
|
||||
baseline = ISpline((0.0, 1.0, 2.0), 2)
|
||||
params = np.zeros(1 + baseline.n_params)
|
||||
X, Z = np.ones((1, 1)), np.empty((1, 0))
|
||||
good = Fit(1, 0, baseline, params, np.eye(len(params)), 0, True)
|
||||
assert np.isfinite(good.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||
for covariance in (np.full((len(params), len(params)), np.nan),
|
||||
-np.eye(len(params)), np.zeros((len(params), len(params)))):
|
||||
broken = Fit(1, 0, baseline, params, covariance, 0, True)
|
||||
assert np.isnan(broken.risk_with_variance(X, Z, [0, 1])[1]).all()
|
||||
|
||||
|
||||
def test_frozen_parameter_only_invalidates_horizons_it_affects():
|
||||
baseline = ISpline((0.0, 1.0, 2.0), 2)
|
||||
params = np.zeros(1 + baseline.n_params)
|
||||
covariance = np.eye(len(params))
|
||||
covariance[1, :] = np.nan
|
||||
covariance[:, 1] = np.nan
|
||||
fitted = Fit(1, 0, baseline, params, covariance, 0, True)
|
||||
variance = fitted.risk_with_variance(np.ones((1, 1)), np.empty((1, 0)), [0, 1])[1]
|
||||
assert np.isfinite(variance[0, 0])
|
||||
assert np.isnan(variance[0, 1])
|
||||
|
||||
|
||||
def test_diagnostics_count_rows_without_intervals():
|
||||
baseline = ISpline((0.0, 1.0, 2.0), 2)
|
||||
params = np.zeros(1 + baseline.n_params)
|
||||
model = Mixture((0, 1), (), (), {})
|
||||
model.fits_ = {(): Fit(1, 0, baseline, params, -np.eye(len(params)), 0, True)}
|
||||
model.seen_ = {(): {}}
|
||||
report = model.variance_diagnostics(pd.DataFrame(index=range(2)))
|
||||
assert report['strata'][0]['rows_without_interval'] == 2
|
||||
assert report['strata'][0]['negative_variances']
|
||||
assert report['strata'][0]['status'] == 'not_estimable'
|
||||
Reference in New Issue
Block a user