Compare commits

..

1 Commits

Author SHA1 Message Date
edgar 55fa6ddd9f Cover CaCu cytology fields in the silver gate
Adapted to rebuild, preserving its existing fields. Based on 1f0d38d, 7b6ffe1, 1dc681f, 8908184, 0fcbe95 and a93292f.
2026-11-30 16:00:32 -06:00
33 changed files with 284 additions and 1561 deletions
-85
View File
@@ -1,85 +0,0 @@
"""Firth, FLIC and FLAC from edgar/camodels, commit 2392d54fd4a3942b56dae803906586bc65600728."""
import warnings
import numpy as np
from scipy.optimize import brentq
from scipy.special import expit
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.exceptions import ConvergenceWarning
SOLVER = dict(max_iter=200, gtol=1e-6, xtol=1e-6)
class ConvergenceError(RuntimeError):
"""Raised when the remaining Newton step fails the convergence check."""
def solve_logistic(X, y, sample_weight=None, penalty_weight=0.5):
"""Fit logistic regression and return the fitted solver and leverages.
Check the remaining Newton step directly because numerical precision can
affect the solver's convergence flag.
"""
y = np.asarray(y)
if y.ndim != 1 or not (np.isin(y, [0, 1]).all() and (y == 0).any() and (y == 1).any()):
raise ValueError("The outcome must contain only 0 and 1, with both classes present.")
y = y.astype(int, copy=False)
from firthmodels import FirthLogisticRegression
with warnings.catch_warnings():
warnings.simplefilter("ignore", ConvergenceWarning)
model = FirthLogisticRegression(penalty_weight=penalty_weight, **SOLVER).fit(
X, y, sample_weight=sample_weight
)
design = np.column_stack([np.ones(len(y)), X])
weights = np.ones(len(y)) if sample_weight is None else sample_weight
p = expit(model.intercept_ + X @ model.coef_)
w = weights * p * (1 - p)
info = design.T @ (w[:, None] * design)
h = w * np.einsum("ij,ji->i", design, np.linalg.solve(info, design.T))
score = design.T @ (weights * (y - p) + penalty_weight * h * (1 - 2 * p))
step = np.abs(np.linalg.solve(info, score)).max()
if not np.isfinite(step) or step >= 1e-4:
raise ConvergenceError(f"The fit did not converge (remaining Newton step {step:.2g}).")
return model, h
class FirthFamily(ClassifierMixin, BaseEstimator):
"""Estimate binary outcome probabilities using Firth, FLIC, or FLAC."""
def __init__(self, method="firth"):
self.method = method
def fit(self, X, y):
"""Fit the selected method to a binary outcome."""
if self.method not in ("firth", "flic", "flac"):
raise ValueError(
f"Unknown method {self.method!r}. Expected 'firth', 'flic', or 'flac'."
)
X = np.asarray(X, float)
firth, h = solve_logistic(X, y)
y = np.asarray(y, int)
self.classes_ = np.array([0, 1])
self.coef_, self.intercept_ = firth.coef_.copy(), float(firth.intercept_)
if self.method == "flic":
eta = X @ self.coef_
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50, xtol=1e-12)
elif self.method == "flac":
# Pseudo-observations use both outcomes, each with half the leverage.
g = np.repeat([0, 1, 1], len(y))
self.X_aug_ = np.column_stack([np.tile(X, (3, 1)), g])
self.y_aug_ = np.concatenate([y, y, 1 - y])
self.w_aug_ = np.concatenate([np.ones(len(y)), h / 2, h / 2])
ml, _ = solve_logistic(self.X_aug_, self.y_aug_, self.w_aug_, penalty_weight=0)
# Predict on original observations, where the indicator is zero.
self.coef_, self.intercept_ = ml.coef_[:-1].copy(), float(ml.intercept_)
return self
def predict_proba(self, X):
"""Return probabilities for classes 0 and 1 in that order."""
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
return np.column_stack([1 - p, p])
-193
View File
@@ -1,193 +0,0 @@
"""Nested, exhaustive evaluation of a bounded set of CaCu binary encoders.
Development only. Selection, coverage screening, rank checks and imputation use training
partitions only. Methods follow edgar/camodels commit 2392d54fd4a3942b56dae803906586bc65600728.
"""
import itertools
import math
import time
import numpy as np
import pandas as pd
from scipy.special import expit as expit
from scipy.special import logit
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, log_loss, roc_auc_score
from sklearn.model_selection import LeaveOneOut, StratifiedKFold
from models.cacu.development_firth import FirthFamily
METHODS = ("firth", "flic", "flac")
def _candidates(X, coverage, limit):
eligible = []
for name in sorted(X.columns):
col = pd.to_numeric(X[name], errors="coerce")
known = col.dropna()
if len(known) / len(X) >= coverage and set(known.unique()) == {0, 1}:
eligible.append((name, col.notna().mean()))
# Perfectly identical or complementary observed columns are not distinguishable.
chosen = []
for name, _ in sorted(eligible, key=lambda item: (-item[1], item[0])):
a = X[name]
if any(
((a == X[other]) | (a.isna() & X[other].isna())).all()
or ((a == 1 - X[other]) | (a.isna() & X[other].isna())).all()
for other in chosen
):
continue
chosen.append(name)
if len(chosen) == limit:
break
return chosen
def _matrix(train, test, columns):
tr = train[list(columns)].to_numpy(dtype=float)
te = test[list(columns)].to_numpy(dtype=float)
if tr.shape[1] and np.isnan(tr).all(axis=0).any():
raise ValueError("predictor absent in training partition")
median = np.nanmedian(tr, axis=0) if tr.shape[1] else np.array([])
tr, te = np.where(np.isnan(tr), median, tr), np.where(np.isnan(te), median, te)
if np.linalg.matrix_rank(np.column_stack([np.ones(len(tr)), tr])) < len(columns) + 1:
raise ValueError("collinear predictors in training partition")
return tr, te
def _predict(train, y, test, columns, method):
tr, te = _matrix(train, test, columns)
if not columns:
return np.repeat(np.mean(y), len(test))
return FirthFamily(method).fit(tr, y).predict_proba(te)[:, 1]
def _metrics(y, probability):
y, p = np.asarray(y), np.asarray(probability)
valid = np.isfinite(p)
if valid.sum() != len(y) or len(np.unique(y)) != 2:
return {
"auc": None,
"brier": None,
"calibration_intercept": None,
"calibration_slope": None,
"log_loss": None,
}
logits = logit(np.clip(p, 1e-12, 1 - 1e-12)).reshape(-1, 1)
calibration = LogisticRegression(C=1e6).fit(logits, y)
return {
"auc": float(roc_auc_score(y, p)),
"brier": float(brier_score_loss(y, p)),
"calibration_intercept": float(calibration.intercept_[0]),
"calibration_slope": float(calibration.coef_[0, 0]),
"log_loss": float(log_loss(y, p, labels=[0, 1])),
}
def evaluate(
X: pd.DataFrame,
y,
*,
coverage=0.7,
candidate_limit=5,
subset_limit=2,
outer_folds=3,
inner_folds=2,
seed=17,
max_fits=100000,
):
"""Evaluate Firth/FLIC/FLAC with nested stratified CV and nested leave-one-out.
A fixed upper bound (default five candidates, pairs at most) permits at most 16 subsets
including the intercept. Each method selects a subset by inner out-of-fold log loss for
every outer split; all attempted subsets and failures are recorded.
"""
X = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce")
y = np.asarray(y)
if len(X) != len(y) or not np.isin(y, [0, 1]).all():
raise ValueError("one known binary outcome is required per row")
if min(np.bincount(y.astype(int), minlength=2)) < max(outer_folds, inner_folds + 1):
raise ValueError("insufficient members of each outcome for nested CV and LOOCV")
if not 1 <= candidate_limit <= 8 or not 1 <= subset_limit <= candidate_limit:
raise ValueError("candidate and subset limits exceed the supported bounds")
max_subsets = sum(
math.comb(candidate_limit, k) for k in range(min(candidate_limit, subset_limit) + 1)
)
estimated_fits = (outer_folds + len(X)) * len(METHODS) * (max_subsets * inner_folds + 1)
if estimated_fits > max_fits:
raise ValueError(f"estimated {estimated_fits} fits exceeds configured limit {max_fits}")
attempted, outputs = [], {}
started = time.monotonic()
plans = {
"cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed).split(X, y),
"loocv": LeaveOneOut().split(X, y),
}
for plan, splits in plans.items():
predictions = {m: np.full(len(X), np.nan) for m in METHODS}
selected = {m: [] for m in METHODS}
for fold, (train_idx, test_idx) in enumerate(splits):
train, test, ytrain = X.iloc[train_idx], X.iloc[test_idx], y[train_idx].astype(int)
candidates = _candidates(train, coverage, candidate_limit)
subsets = [()] + [
c
for size in range(1, min(len(candidates), subset_limit) + 1)
for c in itertools.combinations(candidates, size)
]
inner = list(
StratifiedKFold(inner_folds, shuffle=True, random_state=seed).split(train, ytrain)
)
for method in METHODS:
ranking = []
for columns in subsets:
probs = np.full(len(train), np.nan)
error = None
try:
for a, b in inner:
probs[b] = _predict(
train.iloc[a], ytrain[a], train.iloc[b], columns, method
)
loss = float(log_loss(ytrain, probs, labels=[0, 1]))
ranking.append((loss, len(columns), columns))
except (ValueError, np.linalg.LinAlgError, RuntimeError) as exc:
loss, error = None, type(exc).__name__
attempted.append(
{
"validation": plan,
"fold": fold,
"method": method,
"variables": list(columns),
"inner_log_loss": loss,
"error": error,
}
)
_, _, best = min(ranking)
selected[method].append(list(best))
try:
predictions[method][test_idx] = _predict(train, ytrain, test, best, method)
except (ValueError, np.linalg.LinAlgError, RuntimeError):
pass
outputs[plan] = {
m: {
"metrics": _metrics(y, predictions[m]),
"selected": selected[m],
"unscored": int(np.isnan(predictions[m]).sum()),
"stability": {
name: sum(name in cols for cols in selected[m]) for name in X.columns
},
}
for m in METHODS
}
return {
"development_only": True,
"candidate_limit": candidate_limit,
"subset_limit": subset_limit,
"coverage_minimum": coverage,
"max_subsets": max_subsets,
"maximum_fits": estimated_fits,
"estimated_seconds_at_50ms_per_fit": estimated_fits * 0.05,
"elapsed_seconds": time.monotonic() - started,
"source": "edgar/camodels@2392d54fd4a3942b56dae803906586bc65600728",
"attempts": attempted,
"validation": outputs,
}
-234
View File
@@ -1,234 +0,0 @@
"""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", "CIN2"), ("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)
+3 -17
View File
@@ -48,8 +48,7 @@ def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) ->
def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None): def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = None):
"""Per patient: the cytology category and HPV result of her index sample (the first """Per patient: the cytology category and HPV result of her index sample (the first
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
when `history` asks for it. A patient without an HPV result is left out: she is not when `history` asks for it."""
evaluated, never read as negative."""
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)] near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
wide = near.sort_values("date", kind="stable").pivot_table( wide = near.sort_values("date", kind="stable").pivot_table(
index="person_id", columns="type", values="value_code", aggfunc="first" index="person_id", columns="type", values="value_code", aggfunc="first"
@@ -60,10 +59,8 @@ def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = N
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy() members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy() members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
if history: if history:
# graded in gold, from the cytology linked to her colposcopy members[history["feature"]] = _referral_grade(events, members["person_id"], history)
grades = events[events["type"] == "referral_grade"].groupby("person_id")["value_code"] return members
members[history["feature"]] = members["person_id"].map(grades.first()).astype(object)
return members[wide["hpv"].notna().to_numpy()].reset_index(drop=True)
def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame: def _negatives(events: pd.DataFrame, d: pd.Series, grades: list[str]) -> pd.DataFrame:
@@ -118,17 +115,6 @@ 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))
+1 -14
View File
@@ -1,21 +1,8 @@
"""CaCu's training and scoring jobs (models.jobs) over its models and reports.""" """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 import reports
from models.cacu.specs import MODELS from models.cacu.specs import MODELS
from models.jobs import Jobs 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 train, score = JOBS.train, JOBS.score
+4 -57
View File
@@ -149,20 +149,9 @@ class Fit:
up[k] += step up[k] += step
down[k] -= step down[k] -= step
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step) gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
free = np.isfinite(np.diag(self.covariance)) covariance = np.nan_to_num(self.covariance, nan=0.0)
variance = np.full((len(X), len(years)), np.nan) variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
block = self.covariance[np.ix_(free, free)] return self.risk(X, Z, years), np.maximum(variance, 0.0)
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: def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
@@ -262,8 +251,6 @@ class Mixture(BaseEstimator):
continue continue
members = X.iloc[index] members = X.iloc[index]
placed = self._placed(members, self.seen_[key]) placed = self._placed(members, self.seen_[key])
if not placed.any(): # nobody to score: they keep no value
continue
prevalence, incidence = self._design(members[placed], self.seen_[key]) prevalence, incidence = self._design(members[placed], self.seen_[key])
design = np.column_stack([prevalence, incidence]) design = np.column_stack([prevalence, incidence])
unique, inverse = np.unique(design, axis=0, return_inverse=True) unique, inverse = np.unique(design, axis=0, return_inverse=True)
@@ -271,48 +258,8 @@ class Mixture(BaseEstimator):
point, variance = self.fits_[key].risk_with_variance( point, variance = self.fits_[key].risk_with_variance(
unique[:, :n_x], unique[:, n_x:], self.horizons_years unique[:, :n_x], unique[:, n_x:], self.horizons_years
) )
relative = np.where( relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
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), 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 np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
out[index[placed]] = band[inverse.ravel()] out[index[placed]] = band[inverse.ravel()]
return out 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)}
+1 -70
View File
@@ -9,8 +9,6 @@ validation, is a document the clinical team adds). Both are data the governance
For the logistic regression, its coefficients and calibration by risk decile. For the logistic regression, its coefficients and calibration by risk decile.
""" """
from datetime import date
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from scipy.stats import norm from scipy.stats import norm
@@ -25,71 +23,6 @@ BOOTSTRAP = 200
SEED = 20261122 SEED = 20261122
Z = norm.ppf(0.975) 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",
"referral_not_graded": "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: def technical_validation(spec: Pim | Logistic | survival.Spec, metrics: dict, data: dict) -> dict:
if isinstance(spec, survival.Spec): if isinstance(spec, survival.Spec):
@@ -139,9 +72,7 @@ def _label(feature: str, value) -> str:
def _band(curve, variance) -> tuple[list, list]: def _band(curve, variance) -> tuple[list, list]:
relative = np.where( relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
np.isfinite(variance), np.sqrt(variance) / np.maximum(curve, 1e-300), np.nan
)
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(), return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
+6 -31
View File
@@ -2,7 +2,6 @@
the prevalence-incidence mixture or a logistic regression. Training and scoring read the the prevalence-incidence mixture or a logistic regression. Training and scoring read the
patient timelines of the spec's cohort (see features).""" patient timelines of the spec's cohort (see features)."""
import json
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Literal from typing import Literal
@@ -21,19 +20,9 @@ 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, predictors=()) -> pd.DataFrame: def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
"""One row per patient and horizon; patients the model can't score are left out.""" """One row per patient and horizon; patients the model can't score are left out."""
h = len(horizons) h = len(horizons)
scored = ~np.isnan(risks[:, :h]).any(axis=1) scored = ~np.isnan(risks[:, :h]).any(axis=1)
@@ -49,14 +38,7 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, predictors=()) ->
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel() frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
else: else:
frame["ci_low"] = frame["ci_high"] = np.nan frame["ci_low"] = frame["ci_high"] = np.nan
frame["input_values"] = np.repeat( return frame[OUTPUT]
[
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) @dataclass(frozen=True)
@@ -128,7 +110,7 @@ class Pim:
events = events.assign(index_date=events["person_id"].map(chosen)) events = events.assign(index_date=events["person_id"].map(chosen))
members = f.index_results(events, self.cytology, self._history()) members = f.index_results(events, self.cytology, self._history())
members = members.sort_values("person_id", kind="stable").reset_index(drop=True) members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
return _rows(members, mixture.predict(members[self.features]), self.horizons, self.features) return _rows(members, mixture.predict(members[self.features]), self.horizons)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -174,14 +156,14 @@ class Logistic:
members = f.index_sample(f.prepared(events), list(self.predictors)) members = f.index_sample(f.prepared(events), list(self.predictors))
members = members.sort_values("person_id", kind="stable").reset_index(drop=True) members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
p = model.predict_proba(members[list(self.predictors)])[:, 1] p = model.predict_proba(members[list(self.predictors)])[:, 1]
return _rows(members, p[:, None], (self.years,), self.predictors) return _rows(members, p[:, None], (self.years,))
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: 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 """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, SURVIVAL_AGE_CUTS) found["age_group"] = age_group(events, members, (35, 45, 55))
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}
@@ -215,16 +197,9 @@ MODELS = {
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL), incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS, Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")), cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
# Hidden (core.models.HIDDEN): CIN3+ needs biopsies graded apart from CIN2.
Pim("cin3_pim", "cacu_cohort_surveillance", cacu.CIN3_PLUS, cacu.KPNC,
strata=("hpv_positive",), incidence_features=("cytology",),
predict_at="last_screening_cytology"),
Pim("cin3_pim_post_colposcopy", "cacu_cohort_post_colposcopy", cacu.CIN3_PLUS,
cacu.KPNC_3, strata=("referral_grade",),
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
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, scenarios=SURVIVAL_SCENARIOS), interval_level=0.95),
] ]
} # fmt: skip } # fmt: skip
+29 -12
View File
@@ -1,9 +1,11 @@
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned """CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months,
from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic
gives the recurrence-free probability of clinical scenarios with bootstrap intervals and regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated
survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports (cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios
gives the tables and figures.""" with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by
four criteria (factors); reports gives the tables and figures. The saved model is METABRIC's,
refitted on each whole horizon cohort."""
from dataclasses import dataclass from dataclasses import dataclass
@@ -13,7 +15,15 @@ import pandas as pd
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
SOURCES = ("metabric", "scanb")
HORIZONS = modeling.HORIZONS # months HORIZONS = modeling.HORIZONS # months
SAVED = "metabric"
def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame:
"""The source's cohort table, from its dataset's rows: fixed columns, then its
covariates as categories."""
return cohorts.prepare(source, rows).frame
@dataclass @dataclass
@@ -49,21 +59,28 @@ class Recurrence:
return pd.DataFrame(out, index=X.index) return pd.DataFrame(out, index=X.index)
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""Both reference cohorts' models, validation, calculator and risk factors, from their
datasets' rows; the saved model is METABRIC's.
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
stability criterion, are then missing)."""
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
return fit(found, SAVED, "metabric+scanb", bootstrap)
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""The model of the site's own cohort (models.cama.recurrence.site), its metrics and its """The same, on the site's own cohort (models.cama.recurrence.site)."""
reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
factors' stability criterion, are then missing)."""
from models.cama.recurrence import site from models.cama.recurrence import site
return fit({"site": site.prepare(rows)}, "site", "site", return fit({"site": site.prepare(rows)}, "site", "site", bootstrap)
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
def fit(found: dict, saved: str, label: str, def fit(found: dict, saved: str, label: str,
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: # fmt: skip
"""The models of each prepared cohort, their validation, calculator and risk factors; """The models of each prepared cohort, their validation, calculator and risk factors;
the `saved` cohort's is the model kept.""" the `saved` cohort's is the model kept."""
sources = list(found) sources = list(found)
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
try: try:
fits = modeling.fit(found, n_bootstrap) fits = modeling.fit(found, n_bootstrap)
drawn = {s: calculator.calculator(fits[s]) for s in sources} drawn = {s: calculator.calculator(fits[s]) for s in sources}
+42 -3
View File
@@ -21,6 +21,45 @@ RESAMPLES = 200
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
CAP_MONTHS = 72 # the Weibull curves' extent CAP_MONTHS = 72 # the Weibull curves' extent
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"}
# Each scenario: covariate -> the categories it takes (AND across covariates).
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
},
} # fmt: skip
SCENARIOS["site"] = SCENARIOS["scanb"] # the site's cohort is described as SCAN-B's
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]: def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
@@ -104,10 +143,10 @@ def _curves(months, event, observed):
} }
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]: def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]:
"""The figure record of each scenario with enough recurrences, and its table rows.""" """The figure record of each scenario with enough recurrences, and its table rows."""
source = fitted.cohort.source source = fitted.cohort.source
scenarios = fitted.cohort.scenarios scenarios = SCENARIOS[source] if scenarios is None else scenarios
risk = Risk(fitted) risk = Risk(fitted)
found = masks(fitted.cohort.frame, scenarios) found = masks(fitted.cohort.frame, scenarios)
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
@@ -130,7 +169,7 @@ def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
records.append( records.append(
{ {
"cohorte": source, "cohorte": source,
"cohorte_nombre": fitted.cohort.label, "cohorte_nombre": LABELS[source],
"escenario": name, "escenario": name,
"condiciones": scenarios[name], "condiciones": scenarios[name],
"n": n, "n": n,
+88 -9
View File
@@ -1,8 +1,10 @@
"""A cohort as one table of categories: the patients with a known recurrence time and status, """Each reference cohort as one table of categories, from its dataset as the platform loaded
their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their covariates it (the `cama_reference` pipeline: every value as written, column names as dlt names them,
as text. A missing or out-of-range value is a category of its own (UNKNOWN); nothing is imputed `line` the order the file is published in): the patients with a known recurrence time and
or dropped for it. Of each pair of nearly redundant covariates (Cramér's V >= V_MAX), the one status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their
with more unknowns is dropped.""" covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN);
nothing is imputed or dropped for it. Of each pair of nearly redundant covariates (Cramér's
V >= V_MAX), the one with more unknowns is dropped."""
from dataclasses import dataclass from dataclasses import dataclass
@@ -12,7 +14,6 @@ from scipy.stats.contingency import association
UNKNOWN = "Desconocido" UNKNOWN = "Desconocido"
V_MAX = 0.80 V_MAX = 0.80
DAYS_PER_MONTH = 30.4375 DAYS_PER_MONTH = 30.4375
HORIZONS = (12, 36, 60) # months
# Bands, closed on the left: [a, b). # Bands, closed on the left: [a, b).
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
@@ -20,6 +21,37 @@ SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"]) NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
GRADES = {"1": "1", "2": "2", "3": "3"} GRADES = {"1": "1", "2": "2", "3": "3"}
FIXED = {
"metabric": ["paciente", "tiempo_meses", "evento"],
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
}
TREATMENT = {
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
}
# Covariates taken as they come (our name: the dataset's column).
PASSTHROUGH = {
"metabric": {
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
"Estado_menopausico": "inferred_menopausal_state",
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
},
"scanb": {
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
},
} # fmt: skip
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
def _number(s: pd.Series) -> pd.Series: def _number(s: pd.Series) -> pd.Series:
return pd.to_numeric(s, errors="coerce") return pd.to_numeric(s, errors="coerce")
@@ -34,6 +66,47 @@ def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object)) return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
return rows.sort_values("line", kind="stable").reset_index(drop=True)
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
d = d.reset_index(drop=True)
out = pd.DataFrame({"paciente": d["patient_id"]})
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
load = _number(d["mutation_count"])
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
for name, column in PASSTHROUGH["metabric"].items():
out[name] = _text(d[column])
return out
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows)
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
out = pd.DataFrame({"paciente": d["patient_name"]})
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
out["evento"] = rfi.astype(int)
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
for name, column in PASSTHROUGH["scanb"].items():
out[name] = _text(d[column])
return out
def cramers_v(a: pd.Series, b: pd.Series) -> float: def cramers_v(a: pd.Series, b: pd.Series) -> float:
table = pd.crosstab(a, b).to_numpy() table = pd.crosstab(a, b).to_numpy()
return association(table, method="cramer") if min(table.shape) > 1 else 0.0 return association(table, method="cramer") if min(table.shape) > 1 else 0.0
@@ -70,15 +143,21 @@ class Cohort:
covariates: list[str] covariates: list[str]
treatment: list[str] treatment: list[str]
eliminated: list[str] eliminated: list[str]
label: str # as the reports name it
scenarios: dict # the clinical scenarios drawn: name -> covariate -> its categories
sampling: dict # how its patients were chosen (the MUESTREO record)
@property @property
def intrinsic(self) -> list[str]: def intrinsic(self) -> list[str]:
return [c for c in self.covariates if c not in self.treatment] return [c for c in self.covariates if c not in self.treatment]
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
fixed, treatment = FIXED[source], TREATMENT[source]
covariates = [c for c in full.columns if c not in fixed]
dropped = collinear(full, [c for c in covariates if c not in treatment])
kept = [c for c in covariates if c not in dropped]
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped)
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame: def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
"""The patients whose status at `horizon` months is known (a recurrence by then, or """The patients whose status at `horizon` months is known (a recurrence by then, or
followed past it), with `y` = recurred by then.""" followed past it), with `y` = recurred by then."""
+2 -2
View File
@@ -8,7 +8,7 @@ import numpy as np
import pandas as pd import pandas as pd
from models import factors as rated from models import factors as rated
from models.cama.recurrence.calculator import masks from models.cama.recurrence.calculator import SCENARIOS, masks
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
from models.cama.recurrence.modeling import CohortFit from models.cama.recurrence.modeling import CohortFit
from models.factors import FREQ_MIN, ORDER from models.factors import FREQ_MIN, ORDER
@@ -102,7 +102,7 @@ def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
"""Per scenario and horizon, the classified factors and treatments nearly all of its """Per scenario and horizon, the classified factors and treatments nearly all of its
patients have (definitorios) or most have (mayoritarios).""" patients have (definitorios) or most have (mayoritarios)."""
frame, source = fitted.cohort.frame, fitted.cohort.source frame, source = fitted.cohort.frame, fitted.cohort.source
scenarios = fitted.cohort.scenarios scenarios = SCENARIOS[source]
found = rated.classified(factors[factors["cohorte"] == source]) found = rated.classified(factors[factors["cohorte"] == source])
rows = [] rows = []
for name, mask in masks(frame, scenarios).items(): for name, mask in masks(frame, scenarios).items():
+3 -2
View File
@@ -20,9 +20,10 @@ from pgmpy.structure_score import BDeu
from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon from models.cama.recurrence.cohorts import Cohort, at_horizon
from models.factors import variable_of from models.factors import variable_of
HORIZONS = (12, 36, 60) # months
SEED = 42 SEED = 42
TEST_SIZE = 0.3 TEST_SIZE = 0.3
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
@@ -31,7 +32,7 @@ ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
MAX_STEPS = 200 MAX_STEPS = 200
COX_PENALIZER = 0.05 COX_PENALIZER = 0.05
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
N_BOOTSTRAP = {"site": 40} N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
# ---------------------------------------------------------------- logistic regression # ---------------------------------------------------------------- logistic regression
+12 -1
View File
@@ -95,6 +95,17 @@ def metrics(auc: list[dict]) -> dict[str, float]:
return found return found
REFERENCE_SAMPLING = {
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
"origen": "METABRIC y SCAN-B (externas)",
}
SITE_SAMPLING = {
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
"libre de ella hasta su defunción o la fecha de corte",
"origen": "la sede (sus propias pacientes)",
}
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict: def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
"""The five routine records a promotion reads.""" """The five routine records a promotion reads."""
return { return {
@@ -108,7 +119,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
} }
for s, c in cohorts.items() for s, c in cohorts.items()
}, },
**next(iter(cohorts.values())).sampling, **(SITE_SAMPLING if "site" in cohorts else REFERENCE_SAMPLING),
}, },
"DATOS_FALTANTES": { "DATOS_FALTANTES": {
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); " "criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
+1 -38
View File
@@ -30,30 +30,6 @@ TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip "Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"] FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
TREATMENT = ["Cirugia", *TREATMENTS] TREATMENT = ["Cirugia", *TREATMENTS]
# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates).
SCENARIOS = {
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
"HER2+ (luminal B HER2+ o no luminal)": {
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
"Luminal · 1-3 ganglios · lumpectomía": {
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["Lumpectomy"]},
"Grado 3": {"Grado_histologico": ["3"]},
} # fmt: skip
MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted
SAMPLING = {
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
"libre de ella hasta su defunción o la fecha de corte",
"origen": "la sede (sus propias pacientes)",
}
def subtype(er, pr, her2, ki67) -> str: def subtype(er, pr, her2, ki67) -> str:
@@ -121,18 +97,6 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
return out.reset_index(drop=True) return out.reset_index(drop=True)
def scarce(rows: pd.DataFrame) -> str | None:
"""Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS
patients recurred by it, or known free of it), or None."""
for h in cohorts.HORIZONS:
y = cohorts.at_horizon(rows, h)["y"]
fewest = min(int(y.sum()), int((y == 0).sum()))
if fewest < MIN_PER_CLASS:
return (f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, "
f"{MIN_PER_CLASS} of each needed") # fmt: skip
return None
def prepare(rows: pd.DataFrame) -> Cohort: def prepare(rows: pd.DataFrame) -> Cohort:
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates """The site's cohort as a reference cohort is prepared: the nearly redundant covariates
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
@@ -142,5 +106,4 @@ def prepare(rows: pd.DataFrame) -> Cohort:
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT]) dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
kept = [c for c in covariates if c not in dropped] kept = [c for c in covariates if c not in dropped]
treatment = [c for c in TREATMENT if c in kept] treatment = [c for c in TREATMENT if c in kept]
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio", return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped)
SCENARIOS, SAMPLING) # fmt: skip
+5 -7
View File
@@ -9,7 +9,8 @@
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`. Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients - Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math (`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py).""" (proved on METABRIC and SCAN-B by models/tests/test_recurrence.py); slow (its bootstraps
take minutes), so it trains only when asked for by name."""
from dataclasses import dataclass, field from dataclasses import dataclass, field
from datetime import date from datetime import date
@@ -95,18 +96,15 @@ class SiteRecurrence:
name: str name: str
cohort: str = "cama_cohort_recurrence" cohort: str = "cama_cohort_recurrence"
slow: bool = True
reports: bool = True # it writes its own reports (models.jobs) reports: bool = True # it writes its own reports (models.jobs)
method: str = field(default="stepwise logistic regression + Bayesian network", init=False) method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
def train(self, events, as_of=None) -> tuple: def train(self, events, as_of=None) -> tuple:
from models.cama import recurrence from models.cama import recurrence
from models.cama.recurrence import site from models.cama.recurrence import site
from models.jobs import EmptyCohort
rows = site.frame(events, as_of or date.today()) return recurrence.train_site(site.frame(events, as_of or date.today()))
if reason := site.scarce(rows):
raise EmptyCohort(f"cama.recurrence: {reason}")
return recurrence.train_site(rows)
def predict(self, model, events) -> pd.DataFrame: def predict(self, model, events) -> pd.DataFrame:
from models.cama.recurrence import calculator, site from models.cama.recurrence import calculator, site
@@ -114,7 +112,7 @@ class SiteRecurrence:
members = site.frame(events, date.today()) members = site.frame(events, date.today())
found = model.predict(members) found = model.predict(members)
index = events.groupby("person_id")["index_date"].first() index = events.groupby("person_id")["index_date"].first()
masks = calculator.masks(members, site.SCENARIOS) masks = calculator.masks(members, calculator.SCENARIOS["site"])
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
for i in range(len(members))] # fmt: skip for i in range(len(members))] # fmt: skip
rows = [] rows = []
+2 -62
View File
@@ -43,7 +43,7 @@ def _jobs(domain: str):
class Training(dg.Config): class Training(dg.Config):
domain: str domain: str
models: list[str] = [] # default: every model of the domain models: list[str] = [] # default: every model of the domain but the slow ones
as_of: str | None = None # the date the data are taken up to (default: today) as_of: str | None = None # the date the data are taken up to (default: today)
@@ -90,50 +90,6 @@ def score():
score_models() score_models()
class CacuDevelopmentEvaluation(dg.Config):
as_of: str
max_fits: int = 100000
@dg.op
def evaluate_cacu_development(
context: dg.OpExecutionContext, config: CacuDevelopmentEvaluation
) -> str:
"""Opt-in research evaluation only: no registered model, promotion or patient scores."""
import mlflow
import pandas as pd
from core import cacu
from models.cacu import encoders, features
from models.cacu.development_selection import evaluate
from persistance import gold, registry
as_of = date.fromisoformat(config.as_of)
cohort = "cacu_cohort_surveillance"
events = gold.evidence_timelines("cacu_events", cohort, as_of)
if events.empty:
raise EmptyCohort(f"no eligible patients in {cohort}")
encoded = encoders.encode(events, gold.cervical_forms(cohort))
outcome = features.windowed_outcome(
features.prepared(events), cacu.CIN2_PLUS, 1.0, pd.Timestamp(as_of)
)
rows = encoded.merge(outcome, on="person_id", validate="one_to_one")
rows = rows[rows["known"]].reset_index(drop=True)
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
report = evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
report.update(cohort=cohort, as_of=as_of.isoformat(), outcome="CIN2+ at one year")
mlflow.set_experiment(registry.EXPERIMENT)
with mlflow.start_run(run_name="cacu.cin2_firth_development") as run:
mlflow.log_dict(report, "reports/development_evaluation.json")
context.log.info("Development evaluation logged as %s", run.info.run_id)
return run.info.run_id
@dg.job
def cacu_development_evaluation():
evaluate_cacu_development()
class Analysis(dg.Config): class Analysis(dg.Config):
domain: str domain: str
@@ -151,19 +107,6 @@ def analyze():
analyze_studies() 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+", *silver.NCI_REFERENCES])
context.log.info("silver and gold rebuilt")
@dg.job(tags=WRITES)
def rebuild():
build_gold()
@dg.op @dg.op
def make_backup(context: dg.OpExecutionContext) -> str: def make_backup(context: dg.OpExecutionContext) -> str:
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay.""" """The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
@@ -188,7 +131,4 @@ nightly = (
else [] else []
) )
defs = dg.Definitions( defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
jobs=[ingest, train, score, analyze, rebuild, backup, cacu_development_evaluation],
schedules=nightly,
)
+10 -25
View File
@@ -24,7 +24,6 @@ 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,
@@ -185,11 +184,14 @@ def run_map(p: str, node: Map):
def run_fhir(p: str, node: Fhir): def run_fhir(p: str, node: Fhir):
"""Resolve a sender's references across the Bundles accumulated at its source.""" """Each Bundle's rows of the node's entity; a resource sent again is its latest."""
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 []
stored = sorted(nodes.rows(p, node.inputs[0]), key=lambda r: str(r.get("received_at") or "")) found: dict[str, dict] = {}
bundle = fhir_in.combined(json.loads(row[node.column]) for row in stored) for row in nodes.rows(p, node.inputs[0]):
return nodes.write(p, node.id, fhir_in.rows(bundle, node.entity, p, maps)) 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()))
def run_join(p: str, node: Join): def run_join(p: str, node: Join):
@@ -423,9 +425,6 @@ def run_link(p: str, node: Link):
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set() orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex) # no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set() undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
# Answers are kept by record; a person is known by any of hers, whatever joined since.
whose = persons.set_index("unique_id")["cluster_id"].to_dict()
answered = {frozenset(whose.get(r, r) for r in e) for e in decided}
lone = set() # persons whose identifier is carried by one record only lone = set() # persons whose identifier is carried by one record only
for f in ids: for f in ids:
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size() carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
@@ -440,7 +439,7 @@ def run_link(p: str, node: Link):
very same identifier on a record that says nothing else (a scan read only in part).""" very same identifier on a record that says nothing else (a scan read only in part)."""
a, b = r.unique_id_l, r.unique_id_r a, b = r.unique_id_l, r.unique_id_r
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known] sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
if frozenset((a, b)) in answered or any( if frozenset((a, b)) in decided or any(
pd.notna(x) and pd.notna(y) and x != y for x, y in sides pd.notna(x) and pd.notna(y) and x != y for x, y in sides
): ):
return None return None
@@ -484,7 +483,6 @@ 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):
@@ -505,20 +503,9 @@ 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:
provenance = evidence.get(name) observations.append({**base, "instance": instance, "field": 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)
@@ -543,7 +530,5 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
RUNNERS[node.kind](pipeline_id, node) RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done") log(f"{node.id} ({node.kind}) done")
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}): if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
silver.build( silver.build(["silver+"]) # every entity (empty if never staged) and what derives
["silver+", *silver.NCI_REFERENCES]
) # every entity (empty if never staged) and what derives
log(f"silver and gold, from {', '.join(entities)}") log(f"silver and gold, from {', '.join(entities)}")
+10 -14
View File
@@ -11,7 +11,6 @@ import mlflow.pyfunc
import pandas as pd import pandas as pd
from joblib.externals.loky import get_reusable_executor from joblib.externals.loky import get_reusable_executor
from core.cacu import visibility
from persistance import gold, registry from persistance import gold, registry
@@ -36,20 +35,19 @@ class Jobs:
models: dict models: dict
technical_validation: Callable[..., dict] technical_validation: Callable[..., dict]
interpretability: 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 @property
def events(self) -> str: def events(self) -> str:
return f"{self.domain}_events" return f"{self.domain}_events"
def routine(self) -> list[str]: def routine(self) -> list[str]:
"""The models a train run takes when none is named: all but the hidden ones.""" """The models a train run takes when none is named: all but the slow ones."""
return [n for n in self.models if visibility.model(self.registered(n))] return [n for n, s in self.models.items() if not getattr(s, "slow", False)]
def scored(self) -> list[str]: def scored(self) -> list[str]:
"""The models a score run takes when none is named: all but the hidden ones.""" """The models a score run takes when none is named: all of them (only training is
return self.routine() slow)."""
return list(self.models)
def registered(self, name: str) -> str: def registered(self, name: str) -> str:
return f"{self.domain}.{name}" return f"{self.domain}.{name}"
@@ -58,7 +56,9 @@ class Jobs:
"""A new registered version of the model, trained on its cohort's timelines up to """A new registered version of the model, trained on its cohort's timelines up to
`as_of` (default: today), with its metrics and its two generated reports.""" `as_of` (default: today), with its metrics and its two generated reports."""
spec, as_of = self.models[name], as_of or date.today() spec, as_of = self.models[name], as_of or date.today()
if getattr(spec, "reports", False): # trained on its cohort, with its own reports if spec.cohort is None: # trained on reference data: it writes its own reports
fitted, metrics, found = spec.train(None, as_of)
elif getattr(spec, "reports", False): # trained on its cohort, with its own reports
events = gold.timelines(self.events, spec.cohort, as_of) events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty: if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}") raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
@@ -72,15 +72,9 @@ class Jobs:
"technical_validation": self.technical_validation(spec, metrics, data), "technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, 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 # 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. # for its idle workers to time out (5 minutes) before it can end.
get_reusable_executor().shutdown(wait=True) 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()} params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
model = Predictor(spec, fitted) model = Predictor(spec, fitted)
return registry.register(self.registered(name), model, params, metrics, found) return registry.register(self.registered(name), model, params, metrics, found)
@@ -88,6 +82,8 @@ class Jobs:
def score(self, name: str) -> int | None: def score(self, name: str) -> int | None:
"""The champion's risks for today's members of the model's cohort, saved as its risk """The champion's risks for today's members of the model's cohort, saved as its risk
batch; None when the model has no champion yet.""" batch; None when the model has no champion yet."""
if self.models[name].cohort is None: # scores no patient
return None
found = registry.champion(self.registered(name)) found = registry.champion(self.registered(name))
if found is None: if found is None:
return None return None
+2 -78
View File
@@ -341,7 +341,7 @@ class Spec:
masks = scenario_masks(members, self.scenarios) masks = scenario_masks(members, self.scenarios)
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
for i in range(n)] # fmt: skip for i in range(n)] # fmt: skip
result = pd.DataFrame({ return pd.DataFrame({
"person_id": np.repeat(members["person_id"].to_numpy(), h), "person_id": np.repeat(members["person_id"].to_numpy(), h),
"index_date": np.repeat(members["index_date"].dt.date.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), "horizon_years": np.tile(np.asarray(self.horizons, dtype=float), n),
@@ -350,15 +350,6 @@ class Spec:
"ci_high": np.array([e[1] for e in ends], dtype=float).ravel(), "ci_high": np.array([e[1] for e in ends], dtype=float).ravel(),
"scenarios": np.repeat(np.asarray(scenarios, dtype=object), h), "scenarios": np.repeat(np.asarray(scenarios, dtype=object), h),
})[OUTPUT] # fmt: skip })[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) # ---------------------------------------------------------------- reports (curves)
@@ -439,43 +430,6 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
} # fmt: skip } # fmt: skip
def _combination_curves(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> list[dict]:
"""The curves of the members who share every covariate value, the ones a patient with those
values is shown: Kaplan-Meier, Weibull, fractional Weibull and the model's points for those
values (its bootstrap band where training saw them). Fewer than MIN_SCENARIO_EVENTS deaths:
counts and why, no curve."""
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
keys = spec._combinations(members)
intervals = getattr(model, "intervals_", {})
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:
entry |= _scenario_curves(months[rows], event[rows], spec.cap_months)
point = {"S": model.survival(members.iloc[rows[:1]])[0].tolist()}
band = intervals.get(values)
if band: # kept as mortality: survival's limits are its complements, swapped
point |= {"low": [1 - v for v in band[1]], "high": [1 - v for v in band[0]]}
point["interval"] = {"available": bool(band),
"level": spec.interval_level if band else None,
"method": "bootstrap_percentile" if band else None} # fmt: skip
entry["points"] = {"COMB": point}
entry["horizons_months"] = list(spec.borders[1:])
entry["km"]["interval"] = {
"available": True,
"level": 0.95,
"method": "greenwood_log_log",
}
for name in ("weibull", "weibull_fractional"):
entry[name]["interval"] = {"available": False, "level": None, "method": None}
found.append(entry)
return found
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict: def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a """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 Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
@@ -533,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 for n, m in masks.items() if n not in drawn] # fmt: skip
combinations = spec._combinations(train).value_counts().reset_index(name="members") combinations = spec._combinations(train).value_counts().reset_index(name="members")
survival = model.survival(combinations.replace(UNKNOWN, None)) survival = model.survival(combinations.replace(UNKNOWN, None))
report = { return {
"model": spec.name, "model": spec.name,
"kind": "curves", "kind": "curves",
"curves": curves, "curves": curves,
@@ -555,36 +509,6 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS, "min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
**risk_factor_report(spec, model, members), **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, model, members)
return report
# ---------------------------------------------------------------- risk factors # ---------------------------------------------------------------- risk factors
-1
View File
@@ -24,7 +24,6 @@ dependencies = [
"edfio>=0.4.18", "edfio>=0.4.18",
"statsmodels>=0.15.0", "statsmodels>=0.15.0",
"pgmpy>=1.1.2", "pgmpy>=1.1.2",
"firthmodels>=0.8.2",
] ]
[project.optional-dependencies] [project.optional-dependencies]
-135
View File
@@ -1,135 +0,0 @@
"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a
`Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written,
column names as dlt names them, `line` the order the file is published in)."""
import pandas as pd
from models.cama import recurrence
from models.cama.recurrence import site
from models.cama.recurrence.cohorts import (
AGE,
DAYS_PER_MONTH,
GRADES,
NODES,
SIZE,
Cohort,
_band,
_number,
_text,
collinear,
)
SOURCES = ("metabric", "scanb")
SAVED = "metabric"
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
SAMPLING = {
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
"origen": "METABRIC y SCAN-B (externas)",
}
SCENARIOS = {
"metabric": {
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
"Tamano_tumor": ["<=20 mm"]},
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
"< 45 años": {"Edad": ["<45"]},
"≥ 75 años": {"Edad": ["75+"]},
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
"RE+ · 1-3 ganglios · cirugía conservadora": {
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
"Cirugia": ["BREAST CONSERVING"]},
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
},
"scanb": site.SCENARIOS,
} # fmt: skip
FIXED = {
"metabric": ["paciente", "tiempo_meses", "evento"],
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
}
TREATMENT = {
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
}
# Covariates taken as they come (our name: the dataset's column).
PASSTHROUGH = {
"metabric": {
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
"Estado_menopausico": "inferred_menopausal_state",
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
},
"scanb": {
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
},
} # fmt: skip
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
return rows.sort_values("line", kind="stable").reset_index(drop=True)
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
d = d.reset_index(drop=True)
out = pd.DataFrame({"paciente": d["patient_id"]})
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
load = _number(d["mutation_count"])
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
for name, column in PASSTHROUGH["metabric"].items():
out[name] = _text(d[column])
return out
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
d = _in_order(rows)
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
out = pd.DataFrame({"paciente": d["patient_name"]})
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
out["evento"] = rfi.astype(int)
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
for name, column in PASSTHROUGH["scanb"].items():
out[name] = _text(d[column])
return out
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
fixed, treatment = FIXED[source], TREATMENT[source]
covariates = [c for c in full.columns if c not in fixed]
dropped = collinear(full, [c for c in covariates if c not in treatment])
kept = [c for c in covariates if c not in dropped]
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped,
LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple:
"""Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept."""
found = {s: prepare(s, raws[s]) for s in SOURCES}
return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {})
-34
View File
@@ -1,34 +0,0 @@
"""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
-94
View File
@@ -1,94 +0,0 @@
import numpy as np
import pandas as pd
import pytest
from models.cacu.development_firth import FirthFamily
from models.cacu.development_selection import METHODS, _candidates, _matrix, evaluate
@pytest.mark.parametrize("method", METHODS)
def test_methods_fit_simulated_data(method):
X = np.array([[0], [0], [0], [1], [1], [1], [2], [2], [2], [3], [3], [3]], float)
y = np.array([0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0])
prediction = FirthFamily(method).fit(X, y).predict_proba(X)[:, 1]
assert np.isfinite(prediction).all() and ((prediction > 0) & (prediction < 1)).all()
def test_candidates_and_imputation_use_only_training_rows():
train = pd.DataFrame(
{"a": [0.0, 1.0, np.nan, 1.0], "copy": [0.0, 1.0, np.nan, 1.0], "absent": [np.nan] * 4}
)
assert _candidates(train, 0.7, 5) == ["a"]
a, b = _matrix(train, pd.DataFrame({"a": [np.nan]}), ["a"])
assert b[0, 0] == np.nanmedian(a[:, 0]) == 1
def test_nested_cv_and_loocv_record_every_attempt():
X = pd.DataFrame({"a": [0, 0, 1, 1, 0, 1, 0, 1], "b": [0, 1, 0, 1, 1, 0, 0, 1]})
y = np.array([0, 1, 0, 1, 0, 1, 1, 0])
report = evaluate(X, y, candidate_limit=2, subset_limit=2, outer_folds=2, inner_folds=2)
assert report["development_only"] and report["max_subsets"] == 4
assert set(report["validation"]) == {"cv", "loocv"}
assert {a["method"] for a in report["attempts"]} == set(METHODS)
assert all("variables" in a and "error" in a for a in report["attempts"])
assert all(len(report["validation"]["loocv"][m]["selected"]) == len(X) for m in METHODS)
def test_budget_rejects_large_loocv_before_fitting():
X = pd.DataFrame({"a": [0, 1] * 10})
with pytest.raises(ValueError, match="exceeds configured limit"):
evaluate(X, [0, 1] * 10, candidate_limit=2, subset_limit=2, max_fits=1)
def test_development_job_is_not_a_production_score():
from core.models import DEVELOPMENT
from models.definitions import defs
assert "cacu.cin2_firth_development" in DEVELOPMENT
job = defs.get_job_def("cacu_development_evaluation")
assert job.name == "cacu_development_evaluation"
def test_development_job_writes_evaluation_to_isolated_mlflow(tmp_path, monkeypatch):
import dagster as dg
import mlflow
from mlflow.tracking._tracking_service import utils as tracking_utils
from models.cacu import development_selection, encoders, features
from models.definitions import CacuDevelopmentEvaluation, evaluate_cacu_development
from persistance import gold
monkeypatch.setenv("MLFLOW_TRACKING_URI", (tmp_path / "mlruns").as_uri())
monkeypatch.setenv("MLFLOW_ALLOW_FILE_STORE", "true")
monkeypatch.setattr(tracking_utils, "_tracking_uri", tracking_utils._tracking_uri)
mlflow.set_tracking_uri((tmp_path / "mlruns").as_uri())
patients = [str(i) for i in range(8)]
events = pd.DataFrame(
{"person_id": patients, "date": ["2025-01-01"] * 8, "index_date": ["2025-01-01"] * 8}
)
encoded = pd.DataFrame(
{
"person_id": patients,
"index_date": ["2025-01-01"] * 8,
"factor": [0, 0, 1, 1, 0, 1, 0, 1],
}
)
outcomes = pd.DataFrame(
{"person_id": patients, "known": [True] * 8, "y": [0, 1, 0, 1, 0, 1, 1, 0]}
)
monkeypatch.setattr(gold, "evidence_timelines", lambda *a: events)
monkeypatch.setattr(gold, "cervical_forms", lambda *a: pd.DataFrame())
monkeypatch.setattr(encoders, "encode", lambda *a: encoded)
monkeypatch.setattr(features, "windowed_outcome", lambda *a: outcomes)
real = development_selection.evaluate
monkeypatch.setattr(
development_selection,
"evaluate",
lambda X, y, **kw: real(
X, y, candidate_limit=1, subset_limit=1, outer_folds=2, inner_folds=2, **kw
),
)
with dg.build_op_context() as context:
run_id = evaluate_cacu_development(context, CacuDevelopmentEvaluation(as_of="2026-01-01"))
artifacts = mlflow.MlflowClient().list_artifacts(run_id, "reports")
assert [a.path for a in artifacts] == ["reports/development_evaluation.json"]
-129
View File
@@ -1,129 +0,0 @@
"""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)
-16
View File
@@ -1,16 +0,0 @@
import pandas as pd
from core import cacu
from models.cacu import features as f
def test_without_an_hpv_result_she_is_not_evaluated():
day = pd.Timestamp("2025-01-01")
rows = [(p, day, day, "bethesda", "NILM") for p in ("negative", "positive", "none")]
rows += [("negative", day, day, "hpv", "negative"), ("positive", day, day, "hpv", "positive")]
events = pd.DataFrame(rows, columns=["person_id", "index_date", "date", "type", "value_code"])
found = f.index_results(events, cacu.KPNC)
assert dict(zip(found["person_id"], found["hpv_positive"], strict=False)) == {
"negative": 0.0,
"positive": 1.0,
}
+3 -53
View File
@@ -13,12 +13,7 @@ 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 core import cacu
from models import curves, survival
from models.cacu import reports
from models.cacu.features import days, prepared
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"
@@ -60,27 +55,11 @@ def timelines(cohort: str) -> pd.DataFrame:
return found return found
def hpv_missing_as_the_current_platform_read_it(events: pd.DataFrame) -> pd.DataFrame:
"""Changed on purpose: the rewrite does not evaluate a patient without an HPV result at the
index; the current platform read it as negative. Standing in a result that is not positive
here keeps the rest of the computation compared."""
index = events.groupby("person_id", as_index=False).first()
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
has = events[(events["type"] == "hpv") & near]
missing = index[~index["person_id"].isin(has["person_id"])]
assumed = missing.assign(
date=missing["index_date"], type="hpv", value_code="assumed"
) # not positive, and not a negative visit
return pd.concat([events, assumed[events.columns]], ignore_index=True)
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment", @pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
"cin2_logistic"]) # fmt: skip "cin2_logistic"]) # fmt: skip
def test_predictions_match_the_current_models(name): def test_predictions_match_the_current_models(name):
spec = MODELS[name] spec = MODELS[name]
events = timelines(COHORTS[spec.cohort]) events = timelines(COHORTS[spec.cohort])
if spec.method != "logistic regression":
events = hpv_missing_as_the_current_platform_read_it(events)
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else () args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
model, metrics, _ = spec.train(events, *args) model, metrics, _ = spec.train(events, *args)
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet") reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
@@ -99,17 +78,12 @@ def test_predictions_match_the_current_models(name):
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"), for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip ("ci_high", "ic_alto")]: # fmt: skip
if theirs in both: if theirs in both:
# Older reference intervals include non-estimable covariance estimates. Preserve np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
# 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": if spec.method != "logistic regression":
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_and_publishes_patient_scenarios(monkeypatch): def test_survival_matches_the_current_model_with_its_index_fixed():
"""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."""
@@ -125,13 +99,12 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk
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, data = spec.train(events, pd.Timestamp(REFERENCE_CUTOFF).date()) model, metrics, _ = 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
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
found = spec.predict(model, events) 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") reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"], both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
@@ -140,29 +113,6 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk
("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)
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)
if "km" in c:
assert {"weibull", "weibull_fractional", "points"} <= set(c)
point = c["points"]["COMB"]
assert len(point["S"]) == len(c["horizons_months"]) == len(spec.borders) - 1
(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
-22
View File
@@ -1,22 +0,0 @@
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},
]
-51
View File
@@ -1,51 +0,0 @@
"""A reviewer's "they are different people" is about the persons: it holds when more records
join one of them, whichever record the person is known by afterwards."""
import json
import sqlite3
PEOPLE = [("1001", "ANA LOPEZ RUIZ", "1980-01-01"), ("2002", "BEATRIZ MORA DIAZ", "1980-01-01")]
PEOPLE += [(f"9{k:03d}", f"PERSONA {k} DE RELLENO", f"19{50 + k}-0{1 + k % 9}-11")
for k in range(30)] # fmt: skip
def graph(db) -> dict:
fields = {"record_number": "num", "full_name": "nombre", "birth_date": "nac", "nss": "nss"}
return {"nodes": [
{"id": "people", "kind": "source", "source": "dlt.sources.sql_database:sql_table",
"args": {"credentials": f"sqlite:///{db}", "table": "people"}},
{"id": "identity", "kind": "map", "inputs": ["people"], "fields": fields},
{"id": "persons", "kind": "link", "inputs": ["identity"], "fields": list(fields)},
]} # fmt: skip
def insert(db, rows) -> None:
with sqlite3.connect(db) as con:
con.execute(
"create table if not exists people "
"(id integer primary key, num text, nombre text, nac text, nss text)"
)
con.executemany("insert into people (num, nombre, nac, nss) values (?, ?, ?, ?)", rows)
def test_an_answer_outlives_the_record_a_person_was_known_by(platform, tmp_path):
db, drawn = tmp_path / "people.db", tmp_path / "pipeline.json"
insert(db, [(*p, None) for p in PEOPLE])
drawn.write_text(json.dumps(graph(db)))
platform.save("pipelines", "site", drawn)
platform.ingest()
queue = "select person, candidate from bronze.n__site__persons__review"
((a, b),) = platform.query(queue)
platform.run("python", "-c", "from persistance import nodes; "
f"nodes.decide_persons({a!r}, {b!r}, False, 'reviewer')") # fmt: skip
platform.ingest()
assert platform.query(queue) == []
# Forty more documents of each woman: whichever of her records her person was known by,
# one of these is (almost surely) it now.
insert(db, [(num, None, None, f"{num}{k:07d}") for num in ("1001", "2002") for k in range(40)])
platform.ingest()
lowest = "select min(_record) from bronze.n__site__persons where record_number = '{}'"
known = {platform.query(lowest.format(n))[0][0] for n in ("1001", "2002")}
assert known != {a, b}
assert platform.query(queue) == []
-15
View File
@@ -1,15 +0,0 @@
"""A stratum in which no row is at a level the fit saw gives no value, not an error."""
import numpy as np
import pandas as pd
from models.cacu.pim import Mixture
def test_rows_only_at_unseen_levels_are_left_without_a_risk():
X = pd.DataFrame({"cytology": ["NILM", "NILM", "ASC-US", "ASC-US"] * 10})
y = pd.DataFrame({"c": [0, 1] * 20, "l": [1.0, 0.0] * 20, "r": [np.inf, 0.0] * 20})
y.loc[::5, ["c", "l", "r"]] = [-999, 0.5, 2.0]
mixture = Mixture((1, 5), ["cytology"], (), {"cytology": ["NILM", "ASC-US", "High Grade"]})
mixture.fit(X, y)
assert np.isnan(mixture.predict(pd.DataFrame({"cytology": ["High Grade"]}))).all()
-43
View File
@@ -1,43 +0,0 @@
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"
+11 -11
View File
@@ -25,7 +25,6 @@ from pathlib import Path
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import pytest import pytest
import recurrence_reference as reference
from joblib.externals.loky import get_reusable_executor from joblib.externals.loky import get_reusable_executor
from scipy.special import gammaln from scipy.special import gammaln
@@ -72,14 +71,14 @@ def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
# Each cohort's rows as the pipeline loaded them (one source node per cohort). # Each cohort's rows as the pipeline loaded them (one source node per cohort).
out = folder / "datasets.pkl" out = folder / "datasets.pkl"
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; " platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
f"pd.to_pickle({{s: pd.DataFrame(nodes.rows('cama_reference', s)) " "from models.cama import recurrence; pd.to_pickle({s: pd.DataFrame(nodes.rows("
f"for s in {reference.SOURCES!r}}}, {str(out)!r})") # fmt: skip f"'cama_reference', s)) for s in recurrence.SOURCES}}, {str(out)!r})") # fmt: skip
return pd.read_pickle(out) return pd.read_pickle(out)
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
def prepared(raws): def prepared(raws):
return {s: reference.prepare(s, raw) for s, raw in raws.items()} return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
@@ -156,7 +155,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float):
# ---------------------------------------------------------------- fast # ---------------------------------------------------------------- fast
def test_cohorts(prepared): def test_cohorts(prepared, raws):
sampling = _json("rutinas/MUESTREO.json")["cohortes"] sampling = _json("rutinas/MUESTREO.json")["cohortes"]
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"] missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
for source, c in prepared.items(): for source, c in prepared.items():
@@ -165,17 +164,18 @@ def test_cohorts(prepared):
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"] assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
assert c.covariates == list(missing[source]) assert c.covariates == list(missing[source])
assert cohorts.unknown_shares(c) == missing[source] assert cohorts.unknown_shares(c) == missing[source]
pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame)
assert prepared["metabric"].covariates == VERSION["model"]["covariates"] assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
def test_routines(prepared): def test_routines(prepared):
found = reports.routines(prepared, reference.N_BOOTSTRAP) found = reports.routines(prepared, modeling.N_BOOTSTRAP)
for name, record in found.items(): for name, record in found.items():
assert record == _json(f"rutinas/{name}.json"), name assert record == _json(f"rutinas/{name}.json"), name
def test_c_index_and_internal_auc(fits): def test_c_index_and_internal_auc(fits):
rows = [r for s in reference.SOURCES for r in reports.auc_rows(fits[s])] rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False) assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
metrics = reports.metrics(rows) metrics = reports.metrics(rows)
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k} assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
@@ -206,7 +206,7 @@ def test_saved_model(fits):
def test_calculator(fits): def test_calculator(fits):
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance.""" """All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
records, rows = [], [] records, rows = [], []
for source in reference.SOURCES: for source in recurrence.SOURCES:
found = calculator.calculator(fits[source]) found = calculator.calculator(fits[source])
records += found[0] records += found[0]
rows += found[1] rows += found[1]
@@ -220,12 +220,12 @@ def test_calculator(fits):
def test_risk_factors(fits): def test_risk_factors(fits):
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them).""" """All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
table = pd.concat( table = pd.concat(
[factors.risk_factors(fits[s], _reference_selection(s)) for s in reference.SOURCES], [factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
ignore_index=True, ignore_index=True,
) )
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"], _same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
FACTOR_TOLERANCE) # fmt: skip FACTOR_TOLERANCE) # fmt: skip
summary = [r for s in reference.SOURCES for r in factors.scenario_summary(fits[s], table)] summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"]) assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
@@ -262,7 +262,7 @@ def test_fractional_weibull_solver_matches_the_series():
@pytest.mark.slow @pytest.mark.slow
@slow @slow
def test_train_reproduces_v1(raws): def test_train_reproduces_v1(raws):
model, metrics, found = reference.train(raws, bootstrap=True) model, metrics, found = recurrence.train(raws, bootstrap=True)
assert metrics == VERSION["metrics"] assert metrics == VERSION["metrics"]
for h in recurrence.HORIZONS: for h in recurrence.HORIZONS:
mine = model.tables[h] mine = model.tables[h]
+49 -3
View File
@@ -17,9 +17,55 @@ from datetime import date
from core import catalog from core import catalog
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number") ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number")
GYN = (
"gyn_puerperium",
"gyn_pregnancy",
"gyn_iud",
"gyn_hormonal_treatment",
"gyn_other_treatment",
"gyn_postmenopause",
"gyn_hysterectomy",
"gyn_not_applicable",
)
PRESENTS = (
"presents_discharge",
"presents_vulvar_pruritus",
"presents_abnormal_bleeding",
"presents_none",
)
CYTO = (
"cyto_inflammation",
"cyto_reactive_changes",
"cyto_bacterial_vaginosis_flora",
"cyto_candida",
"cyto_bacillary_flora_cytolysis",
"cyto_intermediate_cytolysis",
"cyto_trichomonas",
"cyto_leptothrix",
"cyto_actinomyces_organisms",
"cyto_actinomyces_changes",
"cyto_herpes_simplex_changes",
"cyto_squamous_tubular_metaplasia",
"cyto_keratotic_changes",
"cyto_pregnancy_changes",
"cyto_atrophy",
"cyto_hypoestrogenism",
"cyto_radiotherapy_effect",
"cyto_iud_changes",
"cyto_post_hysterectomy_glandular_cells",
"cyto_bacteria",
"cyto_herpes_image",
"cyto_fungi",
"cyto_radiation",
"cyto_repair",
"cyto_iud_effect",
"cyto_endometrial_cells_40_plus",
"cyto_findings_none",
)
FIELDS = { FIELDS = {
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16", "cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
"hpv_18"), "cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
"hpv_18", "cyto_findings_text", *CYTO),
"cervical_biopsy": ("request_date", "report_date", "histology"), "cervical_biopsy": ("request_date", "report_date", "histology"),
"mammography": ("exam_date", "report_date", "adequacy", "birads"), "mammography": ("exam_date", "report_date", "adequacy", "birads"),
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade", "breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
@@ -32,7 +78,7 @@ FIELDS = {
"ados2": ("evaluation_date", "module", *ADOS2_SCORES), "ados2": ("evaluation_date", "module", *ADOS2_SCORES),
"eeg": ("study_date", "lab_record_id", "edf"), "eeg": ("study_date", "lab_record_id", "edf"),
} # fmt: skip } # fmt: skip
BOOLS = {f for s in catalog.studies().values() for f, d in s.fields.items() if d.type == "boolean"} BOOLS = {"hpv", "hpv_16", "hpv_18", *GYN, *PRESENTS, *CYTO}
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES} NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}