Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ed086bcbc | |||
| e2487062ae | |||
| 20a92a01e6 | |||
| 20651b8d17 | |||
| 69f5c20e2f | |||
| e3c700a1ad | |||
| 0c8ca048df | |||
| a2a9eb7af3 | |||
| 1a1ea5c7a9 | |||
| 77350b8fec | |||
| a9945bc021 | |||
| 3a749ba8d1 | |||
| f369e8f2eb | |||
| f3f79831bf | |||
| 43207fa3a5 | |||
| 7e8e8b44d8 | |||
| 5c781f2a52 | |||
| 8e9da2c73a | |||
| 53e6f77c9e | |||
| 924f662a21 | |||
| 1a46a5ba73 | |||
| 61eb3a30d0 | |||
| 0c78f8cf7d | |||
| 385cc5b80b |
@@ -0,0 +1,161 @@
|
||||
"""Development only (an opt-in Dagster job; nothing registered, promoted or scored): which of
|
||||
the binary encoders (models.cacu.encoders) predict CIN2+ at one year, by Firth's logistic
|
||||
regression and its FLIC and FLAC corrections, chosen and judged by nested stratified
|
||||
cross-validation and nested leave-one-out. Selection, coverage, rank checks and imputation
|
||||
see training partitions only."""
|
||||
|
||||
import itertools
|
||||
import math
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from firthmodels import FirthLogisticRegression
|
||||
from scipy.optimize import brentq
|
||||
from scipy.special import expit, logit
|
||||
from sklearn.base import BaseEstimator, ClassifierMixin, clone
|
||||
from sklearn.impute import SimpleImputer
|
||||
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, cross_val_predict
|
||||
from sklearn.pipeline import make_pipeline
|
||||
|
||||
METHODS = ("firth", "flic", "flac")
|
||||
FAILED = (ValueError, np.linalg.LinAlgError, RuntimeError)
|
||||
|
||||
|
||||
def firth(X, y, weights=None, penalty=0.5):
|
||||
"""A converged Firth fit (penalty 0: maximum likelihood) and its leverages."""
|
||||
model = FirthLogisticRegression(penalty_weight=penalty, max_iter=200, gtol=1e-6, xtol=1e-6)
|
||||
model.fit(X, y, sample_weight=weights)
|
||||
if not model.converged_:
|
||||
raise RuntimeError("the Firth fit did not converge")
|
||||
design = np.column_stack([np.ones(len(y)), X])
|
||||
p = expit(model.intercept_ + X @ model.coef_)
|
||||
w = (np.ones(len(y)) if weights is None else weights) * p * (1 - p)
|
||||
information = design.T @ (w[:, None] * design)
|
||||
return model, w * np.einsum("ij,ji->i", design, np.linalg.solve(information, design.T))
|
||||
|
||||
|
||||
class Firth(ClassifierMixin, BaseEstimator):
|
||||
"""Firth; FLIC (its intercept refit so the mean prediction is the outcome's); FLAC
|
||||
(refit by maximum likelihood with pseudo-observations weighted by half the leverage)."""
|
||||
|
||||
def __init__(self, method: str = "firth"):
|
||||
self.method = method
|
||||
|
||||
def fit(self, X, y):
|
||||
X, y = np.asarray(X, float), np.asarray(y, int)
|
||||
if np.linalg.matrix_rank(np.column_stack([np.ones(len(X)), X])) < X.shape[1] + 1:
|
||||
raise ValueError("collinear predictors in the training partition")
|
||||
model, h = firth(X, y)
|
||||
self.classes_, self.coef_, self.intercept_ = np.array([0, 1]), model.coef_, model.intercept_
|
||||
if self.method == "flic":
|
||||
eta = X @ self.coef_
|
||||
self.intercept_ = brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
elif self.method == "flac":
|
||||
augmented = np.column_stack([np.tile(X, (3, 1)), np.repeat([0, 1, 1], len(y))])
|
||||
plain, _ = firth(augmented, np.r_[y, y, 1 - y], np.r_[np.ones(len(y)), h / 2, h / 2],
|
||||
penalty=0) # fmt: skip
|
||||
self.coef_, self.intercept_ = plain.coef_[:-1], plain.intercept_
|
||||
return self
|
||||
|
||||
def predict_proba(self, X):
|
||||
p = expit(self.intercept_ + np.asarray(X, float) @ self.coef_)
|
||||
return np.column_stack([1 - p, p])
|
||||
|
||||
|
||||
def same(a: pd.Series, b: pd.Series) -> bool:
|
||||
return bool(((a == b) | (a.isna() & b.isna())).all())
|
||||
|
||||
|
||||
def candidates(X: pd.DataFrame, coverage: float, limit: int) -> list[str]:
|
||||
"""Binary columns known for `coverage` of the rows, best covered first, without one
|
||||
identical or complementary to another, at most `limit`."""
|
||||
known = X.notna().mean()
|
||||
found = []
|
||||
for name in sorted(X, key=lambda n: (-known[n], n)):
|
||||
values = set(X[name].dropna().unique())
|
||||
if known[name] < coverage or values != {0, 1}:
|
||||
continue
|
||||
if not any(same(X[name], X[o]) or same(X[name], 1 - X[o]) for o in found):
|
||||
found.append(name)
|
||||
if len(found) == limit:
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def predicted(train, y, test, columns, method, cv=None) -> np.ndarray:
|
||||
"""The probabilities for `test` (or, with `cv`, out of fold for `train`)."""
|
||||
if not columns:
|
||||
return np.repeat(np.mean(y), len(train) if cv else len(test))
|
||||
model = make_pipeline(SimpleImputer(strategy="median"), Firth(method))
|
||||
if cv is not None:
|
||||
return cross_val_predict(model, train[list(columns)], y, cv=cv,
|
||||
method="predict_proba")[:, 1] # fmt: skip
|
||||
return clone(model).fit(train[list(columns)], y).predict_proba(test[list(columns)])[:, 1]
|
||||
|
||||
|
||||
def metrics(y, p) -> dict:
|
||||
names = ("auc", "brier", "calibration_intercept", "calibration_slope", "log_loss")
|
||||
if not np.isfinite(p).all() or len(np.unique(y)) != 2:
|
||||
return dict.fromkeys(names)
|
||||
calibration = LogisticRegression(C=1e6).fit(logit(np.clip(p, 1e-12, 1 - 1e-12))[:, None], y)
|
||||
return dict(zip(names, map(float, (
|
||||
roc_auc_score(y, p), brier_score_loss(y, p), calibration.intercept_[0],
|
||||
calibration.coef_[0, 0], log_loss(y, p, labels=[0, 1]))), strict=True)) # fmt: skip
|
||||
|
||||
|
||||
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=100_000) -> dict: # fmt: skip
|
||||
"""Per method and validation (3-fold CV, leave-one-out): the subset each outer split
|
||||
chooses by inner out-of-fold log loss, the outer predictions' metrics, and every subset
|
||||
tried (with why it failed)."""
|
||||
X, y = X.reset_index(drop=True).apply(pd.to_numeric, errors="coerce"), np.asarray(y, int)
|
||||
if min(np.bincount(y, minlength=2)) < max(outer_folds, inner_folds + 1):
|
||||
raise ValueError("too few of each outcome for nested CV and leave-one-out")
|
||||
subsets_max = sum(math.comb(candidate_limit, k) for k in range(subset_limit + 1))
|
||||
fits = (outer_folds + len(X)) * len(METHODS) * (subsets_max * inner_folds + 1)
|
||||
if fits > max_fits:
|
||||
raise ValueError(f"estimated {fits} fits exceeds the limit {max_fits}")
|
||||
started, attempts, validation = time.monotonic(), [], {}
|
||||
inner = StratifiedKFold(inner_folds, shuffle=True, random_state=seed)
|
||||
plans = {"cv": StratifiedKFold(outer_folds, shuffle=True, random_state=seed),
|
||||
"loocv": LeaveOneOut()} # fmt: skip
|
||||
for plan, outer in plans.items():
|
||||
p = {m: np.full(len(X), np.nan) for m in METHODS}
|
||||
chosen = {m: [] for m in METHODS}
|
||||
for fold, (a, b) in enumerate(outer.split(X, y)):
|
||||
train, test = X.iloc[a], X.iloc[b]
|
||||
names = candidates(train, coverage, candidate_limit)
|
||||
subsets = [c for k in range(min(len(names), subset_limit) + 1)
|
||||
for c in itertools.combinations(names, k)] # fmt: skip
|
||||
for method in METHODS:
|
||||
ranked = []
|
||||
for columns in subsets:
|
||||
loss = error = None
|
||||
try:
|
||||
oof = predicted(train, y[a], None, columns, method, cv=inner)
|
||||
loss = float(log_loss(y[a], oof, labels=[0, 1]))
|
||||
ranked.append((loss, len(columns), columns))
|
||||
except FAILED as e:
|
||||
error = type(e).__name__
|
||||
attempts.append({"validation": plan, "fold": fold, "method": method,
|
||||
"variables": list(columns), "inner_log_loss": loss,
|
||||
"error": error}) # fmt: skip
|
||||
best = min(ranked)[2]
|
||||
chosen[method].append(list(best))
|
||||
try:
|
||||
p[method][b] = predicted(train, y[a], test, best, method)
|
||||
except FAILED:
|
||||
pass
|
||||
validation[plan] = {m: {
|
||||
"metrics": metrics(y, p[m]), "selected": chosen[m],
|
||||
"unscored": int(np.isnan(p[m]).sum()),
|
||||
"stability": {n: sum(n in c for c in chosen[m]) for n in X},
|
||||
} for m in METHODS} # fmt: skip
|
||||
return {"development_only": True, "candidate_limit": candidate_limit,
|
||||
"subset_limit": subset_limit, "coverage_minimum": coverage,
|
||||
"max_subsets": subsets_max, "maximum_fits": fits,
|
||||
"elapsed_seconds": time.monotonic() - started, "attempts": attempts,
|
||||
"validation": validation} # fmt: skip
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Binary (0/1) encoders of every variable the platform holds for a CaCu patient at her index
|
||||
date, for development (models.cacu.development): NaN is missing, an absent value is never 0.
|
||||
|
||||
Only what was available at the index is read (`visible`). Inputs: the gold timeline with its
|
||||
`evidence_date` and `source_available_at` (persistance.gold.evidence_timelines) and, for the
|
||||
form fields gold doesn't carry, the cytology forms (persistance.gold.cervical_forms)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu, catalog
|
||||
from models.cacu.features import _worst, prepared
|
||||
from models.survival import age_group, band
|
||||
|
||||
# What was done to her before the index; the index day's own may be (or follow) the outcome.
|
||||
PROCEDURES = ("biopsy", "biopsy_order", "colposcopy", "treatment", "diagnosis", "history")
|
||||
EXAM_FIELDS = ("gynecologic_condition", "presenting_symptom", "cervix_appearance")
|
||||
EVIDENCE = "cacu_eligibility_evidence"
|
||||
FORM = catalog.studies()["cervical_cytology"].fields
|
||||
FINDINGS = tuple(n for n, f in FORM.items() if n.startswith("finding_") and f.type == "boolean")
|
||||
|
||||
|
||||
def codes(field: str) -> list[str]:
|
||||
return list(FORM[field].codes)
|
||||
|
||||
|
||||
def day(values: pd.Series) -> pd.Series:
|
||||
return pd.to_datetime(values.astype("string").str[:10], format="%Y-%m-%d")
|
||||
|
||||
|
||||
def visible(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Her events available at her index: dated and clinically dated by it, made available
|
||||
by it when the source says when (else by its date; standalone evidence then left out, as
|
||||
the cohorts do), and procedures and a hysterectomy strictly before it. When the platform
|
||||
loaded it (`known_at`) isn't read."""
|
||||
found = events.drop(columns="index_date", errors="ignore").merge(
|
||||
members[["person_id", "index_date"]], on="person_id") # fmt: skip
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
date, clinical, available = (day(found[c]) for c in ("date", "evidence_date",
|
||||
"source_available_at")) # fmt: skip
|
||||
keep = (date <= index) & (clinical.isna() | (clinical <= index))
|
||||
keep &= (available.isna() & (found["source_table"] != EVIDENCE)) | (available <= index)
|
||||
before = (date < index) & (clinical.isna() | (clinical < index))
|
||||
done = found["type"].isin(PROCEDURES) | (found["value_code"] == "hysterectomy")
|
||||
return prepared(found[keep & (before | ~done)])
|
||||
|
||||
|
||||
def flag(known: pd.Series, true: pd.Series) -> pd.Series:
|
||||
return pd.Series(np.where(known, true.astype(float), np.nan), index=known.index)
|
||||
|
||||
|
||||
def one_hot(values: pd.Series, prefix: str, of: list[str]) -> dict[str, pd.Series]:
|
||||
"""A column per code; a value that is none of them is missing, not 0 in all."""
|
||||
return {f"{prefix}__{c}": flag(values.isin(of), values == c) for c in of}
|
||||
|
||||
|
||||
def present(events: pd.DataFrame, people: pd.Index) -> pd.Series:
|
||||
"""1 when recorded, else missing (no record doesn't 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:
|
||||
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 results(seen: pd.DataFrame, members: pd.DataFrame, people: pd.Index) -> dict:
|
||||
"""Her age group, her latest cytology (its worst result that day) and HPV results."""
|
||||
cuts = [low for low, _ in cacu.AGE_GROUPS] + [cacu.AGE_GROUPS[-1][1] + 1]
|
||||
keyed = members.set_index("person_id", drop=False)
|
||||
ages = age_group(seen, keyed.assign(index_date=pd.to_datetime(keyed["index_date"])), cuts)
|
||||
out = one_hot(ages, "age", list(band(pd.Series([cuts[0] - 1, *cuts]), cuts)))
|
||||
found = seen[(seen["type"] == "bethesda") & seen["value_code"].isin(codes("result"))]
|
||||
found = found[found["date"] == found.groupby("person_id")["date"].transform("max")]
|
||||
severity = {n: [n] for names in cacu.KPNC.values() for n in names if n in codes("result")}
|
||||
result = _worst(found.set_index("person_id")["value_code"], severity).reindex(people)
|
||||
out |= one_hot(result, "bethesda", codes("result"))
|
||||
out |= {f"cytology_{name}": flag(result.notna(), result.isin(of))
|
||||
for name, of in cacu.PROCEDURE_CYTOLOGY.items()} # fmt: skip
|
||||
for kind in ("hpv", *cacu.HPV_GENOTYPE_FIELDS):
|
||||
value = latest(seen, kind, people)
|
||||
out[f"{kind}_positive"] = flag(value.isin(["positive", "negative"]), value == "positive")
|
||||
# from one sample's two genotypes: positive if either is, negative only if both are
|
||||
typed = seen[seen["type"].isin(cacu.HPV_GENOTYPE_FIELDS) & seen["value_code"].notna()]
|
||||
wide = typed.pivot_table(index=["person_id", "date", "source_id"], columns="type",
|
||||
values="value_code", aggfunc="first") # fmt: skip
|
||||
wide = wide.reindex(columns=cacu.HPV_GENOTYPE_FIELDS).sort_index().reset_index()
|
||||
last = wide.drop_duplicates("person_id", keep="last").set_index("person_id").reindex(people)
|
||||
positive = (last[cacu.HPV_GENOTYPE_FIELDS] == "positive").any(axis=1)
|
||||
negative = (last[cacu.HPV_GENOTYPE_FIELDS] == "negative").all(axis=1)
|
||||
out["hpv_16_or_18_positive"] = flag(positive | negative, positive)
|
||||
return out
|
||||
|
||||
|
||||
def history(seen: pd.DataFrame, people: pd.Index) -> dict:
|
||||
"""What was done to her before, the worst biopsy, and her referral's grade (the last
|
||||
sample before her first colposcopy, as gold links it)."""
|
||||
of = {kind: seen[seen["type"] == kind] for kind in (*PROCEDURES, "cytology")}
|
||||
sampled = of["cytology"][of["cytology"]["date"] < of["cytology"]["index_date"]]
|
||||
removed = seen[(seen["type"] == "gynecologic_condition")
|
||||
& (seen["value_code"] == "hysterectomy")] # fmt: skip
|
||||
out = {"prior_cytology_sample": present(sampled, people),
|
||||
**{f"prior_{n}": present(of[k], people) for n, k in (
|
||||
("biopsy_order", "biopsy_order"), ("biopsy_report", "biopsy"),
|
||||
("colposcopy", "colposcopy"), ("treatment", "treatment"),
|
||||
("diagnosis_note", "diagnosis"))},
|
||||
"history_cancer_icd10": present(of["history"], people),
|
||||
"history_hysterectomy": present(removed, 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")):
|
||||
out[f"prior_biopsy_{name}"] = flag(worst.notna(), worst >= rank[grade])
|
||||
first = of["colposcopy"].groupby("person_id")["date"].min()
|
||||
graded = seen[seen["type"].isin(["bethesda", "glandular"]) & seen["value_code"].notna()]
|
||||
graded = graded[graded["date"] < graded["person_id"].map(first)]
|
||||
graded = graded[graded["date"] == graded.groupby("person_id")["date"].transform("max")]
|
||||
referral = _worst(graded.set_index("person_id")["value_code"], cacu.KPNC_3).reindex(people)
|
||||
out["referral_high_grade"] = flag(referral.notna(), referral == "High Grade")
|
||||
return out
|
||||
|
||||
|
||||
def forms(found: pd.DataFrame | None, members: pd.DataFrame, people: pd.Index) -> dict:
|
||||
"""The form's fields gold doesn't carry: what the sample form says counts from the
|
||||
sample day, the latest report (whole: what it doesn't state is unknown) from its day."""
|
||||
columns = ["person_id", "sample_date", "report_date", "screening_history", "adequacy",
|
||||
*FINDINGS] # fmt: skip
|
||||
found = (pd.DataFrame(columns=columns) if found is None else found[columns]).merge(
|
||||
members[["person_id", "index_date"]], on="person_id") # fmt: skip
|
||||
index = pd.to_datetime(found["index_date"]).dt.normalize()
|
||||
found = found.assign(s=day(found["sample_date"]), r=day(found["report_date"]))
|
||||
told = found[(found["s"] <= index) & found["screening_history"].notna()].sort_values("s")
|
||||
said = told.groupby("person_id")["screening_history"].last().reindex(people)
|
||||
report = found[(found["r"] <= index) & (found["s"] <= index)].sort_values(["r", "s"])
|
||||
report = report.drop_duplicates("person_id", keep="last").set_index("person_id")
|
||||
report = report.reindex(people)
|
||||
out = one_hot(said, "screening_history", codes("screening_history"))
|
||||
adequacy = report["adequacy"]
|
||||
out["sample_unsatisfactory"] = flag(adequacy.isin(codes("adequacy")),
|
||||
adequacy == "unsatisfactory") # fmt: skip
|
||||
return out | {n: flag(report[n].notna(), report[n].eq(True)) for n in FINDINGS}
|
||||
|
||||
|
||||
def encode(events: pd.DataFrame, cytology_forms: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
"""One row per member (`person_id`, `index_date`, one index each) with every encoder's
|
||||
column: 0.0, 1.0 or NaN."""
|
||||
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)
|
||||
exam = seen[seen["source_table"] == "cervical_cytology"]
|
||||
columns = {**results(seen, members, people), **history(seen, people),
|
||||
**forms(cytology_forms, members, people)} # fmt: skip
|
||||
for field in EXAM_FIELDS:
|
||||
columns |= one_hot(latest(exam, field, people), field, codes(field))
|
||||
values = {name: column.to_numpy(dtype=float) for name, column in columns.items()}
|
||||
return pd.concat([members, pd.DataFrame(values)], axis=1)
|
||||
+11
-19
@@ -30,25 +30,11 @@ def _worst(codes: pd.Series, cytology: dict) -> pd.Series:
|
||||
return worst.map(lambda r: None if np.isnan(r) else names[int(r)]).astype(object)
|
||||
|
||||
|
||||
def _referral_grade(events: pd.DataFrame, persons: pd.Series, history: dict) -> pd.Series:
|
||||
"""Why she was referred: the worst result in the year before her first colposcopy."""
|
||||
first = events[events["type"] == "colposcopy"].groupby("person_id")["date"].min()
|
||||
before = (events["person_id"].map(first) - events["date"]).dt.days
|
||||
near = events[before.between(0, history["lookback_days"])]
|
||||
codes = near[near["type"].isin(["bethesda", "glandular"])].set_index("person_id")["value_code"]
|
||||
worst = _worst(codes, history["cytology"]).reindex(persons).to_numpy()
|
||||
hpv = near[(near["type"] == "hpv") & (near["value_code"] == "positive")]
|
||||
positive = persons.isin(hpv["person_id"])
|
||||
grade = np.where(np.isin(worst, history["high"]), "high", np.where(
|
||||
np.isin(worst, history["low"]) | (np.isin(worst, history["low_if_hpv_positive"])
|
||||
& positive.to_numpy()), "low", None)) # fmt: skip
|
||||
return pd.Series(grade, index=persons.index, dtype=object)
|
||||
|
||||
|
||||
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
|
||||
result of each kind within INDEX_SAMPLE_DAYS of the index), and the referral grade
|
||||
when `history` asks for it."""
|
||||
(gold's, from the cytology linked to her colposcopy) when `history` asks for it. One
|
||||
without an HPV result is left out: not evaluated, never read as negative."""
|
||||
near = events[days(events).between(0, cacu.INDEX_SAMPLE_DAYS) & events["type"].isin(RESULTS)]
|
||||
wide = near.sort_values("date", kind="stable").pivot_table(
|
||||
index="person_id", columns="type", values="value_code", aggfunc="first"
|
||||
@@ -59,8 +45,9 @@ def index_results(events: pd.DataFrame, cytology: dict, history: dict | None = N
|
||||
members["cytology"] = _worst(codes, cytology).reindex(members["person_id"]).to_numpy()
|
||||
members["hpv_positive"] = (wide["hpv"] == "positive").astype(float).to_numpy()
|
||||
if history:
|
||||
members[history["feature"]] = _referral_grade(events, members["person_id"], history)
|
||||
return members
|
||||
grades = events[events["type"] == history["feature"]].groupby("person_id")["value_code"]
|
||||
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:
|
||||
@@ -110,11 +97,16 @@ def interval_coded(events: pd.DataFrame, grades: list[str], cytology: dict,
|
||||
|
||||
|
||||
def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
||||
"""Per patient never referred: her latest sample with both a cytology and an HPV result."""
|
||||
"""Per patient never referred: her latest sample with both a cytology and an HPV result,
|
||||
before any hysterectomy her cytology forms record."""
|
||||
referred = set(events.loc[events["type"].isin(REFERRED), "person_id"])
|
||||
key = ["person_id", "source_table", "source_id"]
|
||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||
[*key, "date"]] # fmt: skip
|
||||
removed = events[(events["type"] == "gynecologic_condition")
|
||||
& (events["value_code"] == "hysterectomy")] # fmt: skip
|
||||
since = samples["person_id"].map(removed.groupby("person_id")["date"].min())
|
||||
samples = samples[since.isna() | (samples["date"] < since)]
|
||||
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||
has = has.reindex(columns=list(RESULTS))
|
||||
|
||||
+13
-2
@@ -1,8 +1,19 @@
|
||||
"""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, with who
|
||||
each cohort lost (gold.cacu_eligibility, the scenario named after the cohort)."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from models.cacu import reports
|
||||
from models.cacu.specs import MODELS
|
||||
from models.jobs import Jobs
|
||||
from persistance import gold
|
||||
|
||||
JOBS = Jobs("cacu", MODELS, reports.technical_validation, reports.interpretability)
|
||||
|
||||
def attrition(spec, as_of: date) -> dict:
|
||||
scenario = spec.cohort.removeprefix("cacu_cohort_")
|
||||
rows = gold.eligibility(scenario, as_of)
|
||||
return reports.attrition(spec.cohort, scenario, 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
|
||||
|
||||
+37
-5
@@ -140,8 +140,16 @@ class Fit:
|
||||
for t in years
|
||||
]) # fmt: skip
|
||||
|
||||
def estimable(self) -> tuple[np.ndarray, bool]:
|
||||
"""The estimated (not frozen) parameters; whether their covariance is positive definite."""
|
||||
free = np.isfinite(np.diag(self.covariance))
|
||||
block = self.covariance[np.ix_(free, free)]
|
||||
finite = bool(block.size and np.isfinite(block).all() and np.allclose(block, block.T))
|
||||
return free, finite and bool((np.linalg.eigvalsh(block) > 0).all())
|
||||
|
||||
def risk_with_variance(self, X, Z, years) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""Risk and its delta-method variance (central-difference gradient)."""
|
||||
"""Risk and its delta-method variance (central-difference gradient); the variance is
|
||||
unknown (NaN) where the covariance isn't proper or a frozen parameter moves it."""
|
||||
gradient = np.empty((len(self.params), len(X), len(years)))
|
||||
for k, value in enumerate(self.params):
|
||||
step = 1e-5 * max(1.0, abs(value))
|
||||
@@ -149,9 +157,15 @@ class Fit:
|
||||
up[k] += step
|
||||
down[k] -= step
|
||||
gradient[k] = (self.risk(X, Z, years, up) - self.risk(X, Z, years, down)) / (2 * step)
|
||||
covariance = np.nan_to_num(self.covariance, nan=0.0)
|
||||
variance = np.einsum("kij,kl,lij->ij", gradient, covariance, gradient)
|
||||
return self.risk(X, Z, years), np.maximum(variance, 0.0)
|
||||
variance = np.full((len(X), len(years)), np.nan)
|
||||
free, proper = self.estimable()
|
||||
if proper:
|
||||
block = self.covariance[np.ix_(free, free)]
|
||||
found = np.einsum("kij,kl,lij->ij", gradient[free], block, gradient[free])
|
||||
moved = np.any(np.abs(gradient[~free]) > 1e-10, axis=0)
|
||||
known = ~moved & np.isfinite(found) & (found >= 0)
|
||||
variance[known] = found[known]
|
||||
return self.risk(X, Z, years), variance
|
||||
|
||||
|
||||
def fit(c, l, r, X, Z, baseline: ISpline, w) -> Fit:
|
||||
@@ -251,6 +265,8 @@ class Mixture(BaseEstimator):
|
||||
continue
|
||||
members = X.iloc[index]
|
||||
placed = self._placed(members, self.seen_[key])
|
||||
if not placed.any(): # nobody it can place
|
||||
continue
|
||||
prevalence, incidence = self._design(members[placed], self.seen_[key])
|
||||
design = np.column_stack([prevalence, incidence])
|
||||
unique, inverse = np.unique(design, axis=0, return_inverse=True)
|
||||
@@ -258,8 +274,24 @@ class Mixture(BaseEstimator):
|
||||
point, variance = self.fits_[key].risk_with_variance(
|
||||
unique[:, :n_x], unique[:, n_x:], self.horizons_years
|
||||
)
|
||||
relative = np.where(point > 0, np.sqrt(variance) / np.maximum(point, 1e-300), 0.0)
|
||||
relative = np.sqrt(variance) / np.maximum(point, 1e-300) # NaN: no interval
|
||||
band = np.column_stack([point, np.clip(point * np.exp(-z * relative), 0, 1),
|
||||
np.clip(point * np.exp(z * relative), 0, 1)]) # fmt: skip
|
||||
out[index[placed]] = band[inverse.ravel()]
|
||||
return out
|
||||
|
||||
def variance_diagnostics(self, X: pd.DataFrame) -> dict:
|
||||
"""Per stratum: its covariance's state and how many rows of `X` get no interval."""
|
||||
h, found = len(self.horizons_years), []
|
||||
for key, index in self._groups(X):
|
||||
missing = np.isnan(self.predict(X.iloc[index])[:, h:]).any(axis=1)
|
||||
f = self.fits_.get(key)
|
||||
d, params = (np.diag(f.covariance), f.params) if f else (np.array([]), np.array([]))
|
||||
status = "unseen_stratum" if f is None else (
|
||||
"positive_definite" if f.estimable()[1] else "not_estimable") # fmt: skip
|
||||
negative = np.flatnonzero(np.isfinite(d) & (d < 0)).tolist()
|
||||
found.append({"stratum": [str(v) for v in key], "rows": len(index),
|
||||
"rows_without_interval": int(missing.sum()), "status": status,
|
||||
"frozen_parameters": np.flatnonzero(np.abs(params) >= FROZEN).tolist(),
|
||||
"negative_variances": negative}) # fmt: skip
|
||||
return {"strata": found, "horizons_years": list(self.horizons_years)}
|
||||
|
||||
+35
-1
@@ -19,6 +19,15 @@ from models.cacu.pim import Mixture
|
||||
from models.cacu.specs import Logistic, Pim
|
||||
|
||||
GRID_STEP = 0.1 # years between points of a curve
|
||||
# Reasons a result still to arrive could lift, and the clinical stage of each (a candidate
|
||||
# may be excluded at several).
|
||||
AWAITING = {"unreported_biopsy", "no_index_result"}
|
||||
STAGES = {"eligibility": ("hysterectomy", "under_18", "no_birth_date", "died_by_index"),
|
||||
"history": ("prior_outcome", "outcome_by_index", "cancer_history", "prior_treatment",
|
||||
"outcome_before_index", "no_pretreatment_biopsy"),
|
||||
"index": ("no_referral", "referral_not_graded", "no_cotest", "no_index_result",
|
||||
"unreported_biopsy")} # fmt: skip
|
||||
STAGE = {reason: stage for stage, reasons in STAGES.items() for reason in reasons}
|
||||
BOOTSTRAP = 200
|
||||
SEED = 20261122
|
||||
Z = norm.ppf(0.975)
|
||||
@@ -72,7 +81,7 @@ def _label(feature: str, value) -> str:
|
||||
|
||||
|
||||
def _band(curve, variance) -> tuple[list, list]:
|
||||
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
|
||||
relative = np.sqrt(variance) / np.maximum(curve, 1e-300) # NaN where it can't be had
|
||||
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
|
||||
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
|
||||
|
||||
@@ -170,3 +179,28 @@ def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
|
||||
],
|
||||
}, # fmt: skip
|
||||
}
|
||||
|
||||
|
||||
def attrition(cohort: str, scenario: str, rows: pd.DataFrame, people: int, as_of) -> dict:
|
||||
"""Who a cohort lost and why by `as_of`. `rows`: its candidates' eligibility (one per
|
||||
candidate and reason). A candidate with several reasons is excluded once and counted in
|
||||
each reason; `pending`: the excluded whose every reason awaits a result."""
|
||||
key = ["person_id", "index_date", "index_sample_id"]
|
||||
rows = rows[rows["index_date"].astype(str).str[:10] <= as_of.isoformat()]
|
||||
candidates = rows[key].drop_duplicates()
|
||||
excluded = rows[rows["criterion"].notna()]
|
||||
reasons = excluded.groupby(key, dropna=False)["criterion"].agg(set)
|
||||
stages = excluded.assign(stage=excluded["criterion"].map(STAGE).fillna("unknown"))
|
||||
return {
|
||||
"cohort": cohort, "scenario": scenario, "as_of": as_of.isoformat(), "people": people,
|
||||
"without_candidate": people - candidates["person_id"].nunique(),
|
||||
"candidates": len(candidates), "eligible": len(candidates) - len(reasons),
|
||||
"excluded": len(reasons), "pending": int(sum(r <= AWAITING for r in reasons)),
|
||||
"by_reason": {str(r): int(n) for r, n in
|
||||
excluded["criterion"].value_counts().sort_index().items()},
|
||||
"by_stage": {str(s): len(g[key].drop_duplicates())
|
||||
for s, g in stages.groupby("stage", sort=True)},
|
||||
"stage_by_reason": {str(r): STAGE.get(r, "unknown")
|
||||
for r in sorted(excluded["criterion"].unique())},
|
||||
"stage_counts_overlap": True, # one candidate may be out at several stages
|
||||
} # fmt: skip
|
||||
|
||||
+28
-13
@@ -15,15 +15,17 @@ from sklearn.preprocessing import OneHotEncoder
|
||||
from core import cacu
|
||||
from models.cacu import features as f
|
||||
from models.cacu.pim import Mixture
|
||||
from models.survival import Spec, age_group
|
||||
from models.survival import Spec, age_group, band, inputs
|
||||
|
||||
HORIZONS = (0.0, 1.0, 2.0, 3.0, 4.0, 5.0)
|
||||
TRAIN_FRACTION = 0.7
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
|
||||
"input_values"] # fmt: skip
|
||||
|
||||
|
||||
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."""
|
||||
def _rows(members: pd.DataFrame, risks: np.ndarray, horizons, read) -> pd.DataFrame:
|
||||
"""One row per patient and horizon, with what her estimate `read`; patients the model
|
||||
can't score are left out."""
|
||||
h = len(horizons)
|
||||
scored = ~np.isnan(risks[:, :h]).any(axis=1)
|
||||
members, risks = members[scored], risks[scored]
|
||||
@@ -33,6 +35,7 @@ def _rows(members: pd.DataFrame, risks: np.ndarray, horizons) -> pd.DataFrame:
|
||||
"index_date": np.repeat(pd.to_datetime(members["index_date"]).dt.date.to_numpy(), h),
|
||||
"horizon_years": np.tile(np.asarray(horizons, dtype=float), n),
|
||||
"probability": risks[:, :h].ravel(),
|
||||
"input_values": inputs(members, read, h),
|
||||
}) # fmt: skip
|
||||
if risks.shape[1] == 3 * h:
|
||||
frame["ci_low"], frame["ci_high"] = risks[:, h : 2 * h].ravel(), risks[:, 2 * h :].ravel()
|
||||
@@ -61,7 +64,7 @@ class Pim:
|
||||
return ["cytology", "hpv_positive"] + ([self.history["feature"]] if self.history else [])
|
||||
|
||||
def _history(self) -> dict | None:
|
||||
return self.history and {**self.history, "cytology": self.cytology}
|
||||
return self.history
|
||||
|
||||
def train(self, events: pd.DataFrame, as_of=None) -> tuple[Mixture, dict, dict]:
|
||||
"""The fitted mixture, its metrics on the held-out latest patients, and the coded
|
||||
@@ -110,7 +113,8 @@ class Pim:
|
||||
events = events.assign(index_date=events["person_id"].map(chosen))
|
||||
members = f.index_results(events, self.cytology, self._history())
|
||||
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||
return _rows(members, mixture.predict(members[self.features]), self.horizons)
|
||||
return _rows(members, mixture.predict(members[self.features]), self.horizons,
|
||||
self.features) # fmt: skip
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -156,14 +160,14 @@ class Logistic:
|
||||
members = f.index_sample(f.prepared(events), list(self.predictors))
|
||||
members = members.sort_values("person_id", kind="stable").reset_index(drop=True)
|
||||
p = model.predict_proba(members[list(self.predictors)])[:, 1]
|
||||
return _rows(members, p[:, None], (self.years,))
|
||||
return _rows(members, p[:, None], (self.years,), self.predictors)
|
||||
|
||||
|
||||
def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Each member's most recent observations up to her index (that day included): her age
|
||||
group, the KPNC category of her latest cytology result and her latest HPV result."""
|
||||
found = pd.DataFrame(index=members.index)
|
||||
found["age_group"] = age_group(events, members, (35, 45, 55))
|
||||
found["age_group"] = age_group(events, members, SURVIVAL_AGE_CUTS)
|
||||
prior = events[events["date"] <= events["index_date"]]
|
||||
names = list(cacu.KPNC)
|
||||
severity = {code: rank for rank, codes in enumerate(cacu.KPNC.values()) for code in codes}
|
||||
@@ -177,10 +181,14 @@ def survival_covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataF
|
||||
return found.astype(object)
|
||||
|
||||
|
||||
_REFERRAL = {
|
||||
"feature": "referral_grade", "lookback_days": cacu.REFERRAL_LOOKBACK_DAYS,
|
||||
"levels": ["low", "high"], "low": ["ASC-US/LSIL"], "low_if_hpv_positive": ["NILM"],
|
||||
"high": ["High Grade"],
|
||||
_REFERRAL = {"feature": "referral_grade", "levels": ["low", "high"]} # graded in gold
|
||||
SURVIVAL_AGE_CUTS = (35, 45, 55)
|
||||
# The clinical scenarios survival's report draws, and her record with them.
|
||||
SURVIVAL_SCENARIOS = {
|
||||
**{f"Edad al diagnóstico · {g} años": (("age_group", "==", g),)
|
||||
for g in band(pd.Series([0, *SURVIVAL_AGE_CUTS]), list(SURVIVAL_AGE_CUTS))},
|
||||
**{f"Citología · {g}": (("cytology", "==", g),) for g in cacu.KPNC},
|
||||
"VPH positivo": (("hpv", "==", "positive"),), "VPH negativo": (("hpv", "==", "negative"),),
|
||||
} # fmt: skip
|
||||
|
||||
MODELS = {
|
||||
@@ -197,9 +205,16 @@ MODELS = {
|
||||
incidence_features=("cytology", "hpv_positive"), history=_REFERRAL),
|
||||
Pim("cin2_pim_post_treatment", "cacu_cohort_post_treatment", cacu.CIN2_PLUS,
|
||||
cacu.KPNC_3, strata=(), incidence_features=("cytology", "hpv_positive")),
|
||||
# Hidden (core.models.HIDDEN): CIN3+ needs biopsies that tell CIN3 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),
|
||||
Spec("survival", "cacu_cohort_survival", ("age_group", "cytology", "hpv"),
|
||||
survival_covariates, borders=(0, 12, 36, 60), cap_months=60,
|
||||
interval_level=0.95),
|
||||
interval_level=0.95, scenarios=SURVIVAL_SCENARIOS),
|
||||
]
|
||||
} # fmt: skip
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months,
|
||||
learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
|
||||
published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic
|
||||
regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated
|
||||
(cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios
|
||||
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."""
|
||||
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned
|
||||
from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian
|
||||
network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator
|
||||
gives the recurrence-free probability of clinical scenarios with bootstrap intervals and
|
||||
survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports
|
||||
gives the tables and figures."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
@@ -15,15 +13,7 @@ import pandas as pd
|
||||
|
||||
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
||||
|
||||
SOURCES = ("metabric", "scanb")
|
||||
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
|
||||
@@ -59,27 +49,35 @@ class Recurrence:
|
||||
return pd.DataFrame(out, index=X.index)
|
||||
|
||||
|
||||
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
||||
"""Both cohorts' models, validation, calculator and risk factors, from their datasets'
|
||||
rows.
|
||||
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}
|
||||
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
|
||||
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
|
||||
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
|
||||
|
||||
return fit({"site": site.prepare(rows)}, "site", "site",
|
||||
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
|
||||
|
||||
|
||||
def fit(found: dict, saved: str, label: str,
|
||||
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
||||
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
||||
the `saved` cohort's is the model kept."""
|
||||
sources = list(found)
|
||||
try:
|
||||
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}
|
||||
finally:
|
||||
joblib.externals.loky.get_reusable_executor().shutdown(wait=True)
|
||||
table = pd.concat([factors.risk_factors(fits[s]) for s in SOURCES], ignore_index=True)
|
||||
summary = [row for s in SOURCES for row in factors.scenario_summary(fits[s], table)]
|
||||
auc = [row for s in SOURCES for row in reports.auc_rows(fits[s])]
|
||||
points = [row for s in SOURCES for row in drawn[s][1]]
|
||||
saved = fits[SAVED]
|
||||
model = Recurrence(SAVED, HORIZONS, saved.cohort.covariates, modeling.tables(saved))
|
||||
table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True)
|
||||
summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)]
|
||||
auc = [row for s in sources for row in reports.auc_rows(fits[s])]
|
||||
points = [row for s in sources for row in drawn[s][1]]
|
||||
kept = fits[saved]
|
||||
model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept))
|
||||
technical = {
|
||||
"model": "recurrence",
|
||||
"cohort": "metabric+scanb",
|
||||
"cohort": label,
|
||||
"method": "stepwise logistic regression + Bayesian network (BDeu), averaged",
|
||||
"rutinas": reports.routines(found, n_bootstrap),
|
||||
"recurrencia_desarrollo": reports.development(auc, table, points, summary),
|
||||
@@ -87,7 +85,7 @@ def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurr
|
||||
interpretability = {
|
||||
"model": "recurrence",
|
||||
"kind": "scenarios",
|
||||
"recurrencia": reports.figures([r for s in SOURCES for r in drawn[s][0]]),
|
||||
"recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
|
||||
}
|
||||
reports_ = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return model, reports.metrics(auc), reports_
|
||||
|
||||
@@ -21,44 +21,6 @@ RESAMPLES = 200
|
||||
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
|
||||
CAP_MONTHS = 72 # the Weibull curves' extent
|
||||
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
|
||||
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
||||
@@ -142,10 +104,10 @@ def _curves(months, event, observed):
|
||||
}
|
||||
|
||||
|
||||
def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]:
|
||||
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
|
||||
"""The figure record of each scenario with enough recurrences, and its table rows."""
|
||||
source = fitted.cohort.source
|
||||
scenarios = SCENARIOS[source] if scenarios is None else scenarios
|
||||
scenarios = fitted.cohort.scenarios
|
||||
risk = Risk(fitted)
|
||||
found = masks(fitted.cohort.frame, scenarios)
|
||||
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
|
||||
@@ -168,7 +130,7 @@ def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[d
|
||||
records.append(
|
||||
{
|
||||
"cohorte": source,
|
||||
"cohorte_nombre": LABELS[source],
|
||||
"cohorte_nombre": fitted.cohort.label,
|
||||
"escenario": name,
|
||||
"condiciones": scenarios[name],
|
||||
"n": n,
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
"""Each reference cohort as one table of categories, from its dataset as the platform loaded
|
||||
it (the `cama_reference` pipeline: every value as written, column names as dlt names them,
|
||||
`line` the order the file is published in): the patients with a known recurrence time and
|
||||
status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their
|
||||
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."""
|
||||
"""A cohort as one table of categories: the patients with a known recurrence time and status,
|
||||
their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their 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
|
||||
|
||||
@@ -14,6 +12,7 @@ from scipy.stats.contingency import association
|
||||
UNKNOWN = "Desconocido"
|
||||
V_MAX = 0.80
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
HORIZONS = (12, 36, 60) # months
|
||||
|
||||
# Bands, closed on the left: [a, b).
|
||||
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
||||
@@ -21,37 +20,6 @@ SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
|
||||
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
||||
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:
|
||||
return pd.to_numeric(s, errors="coerce")
|
||||
@@ -66,47 +34,6 @@ def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
|
||||
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:
|
||||
table = pd.crosstab(a, b).to_numpy()
|
||||
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
||||
@@ -143,21 +70,15 @@ class Cohort:
|
||||
covariates: list[str]
|
||||
treatment: 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
|
||||
def intrinsic(self) -> list[str]:
|
||||
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:
|
||||
"""The patients whose status at `horizon` months is known (a recurrence by then, or
|
||||
followed past it), with `y` = recurred by then."""
|
||||
|
||||
@@ -1,35 +1,20 @@
|
||||
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has.
|
||||
|
||||
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
|
||||
most frequent category by four criteria: (1) its adjusted odds ratio's 95 % CI excludes 1 and
|
||||
its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least FREQ_MIN of
|
||||
the time; (3) its covariate is a parent of the HBN; (4) its Kaplan-Meier recurrence-free
|
||||
survival at the horizon differs from the reference's (95 % CI) in the odds ratio's direction.
|
||||
"Robusto" needs (1) and three criteria, "sugerente" two. Treatments get their odds ratios,
|
||||
adjusted for the intrinsic covariates, but no class: they are associations, not effects."""
|
||||
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has
|
||||
(the criteria in `models.factors`, all four evaluated: the stepwise LRs' bootstrap gives (2),
|
||||
the horizon's HBN parents give (3))."""
|
||||
|
||||
import warnings
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from scipy.stats import false_discovery_control
|
||||
|
||||
from models.cama.recurrence.calculator import SCENARIOS, masks
|
||||
from models import factors as rated
|
||||
from models.cama.recurrence.calculator import masks
|
||||
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
||||
from models.cama.recurrence.modeling import CohortFit, variable_of
|
||||
from models.curves import life_table
|
||||
from models.cama.recurrence.modeling import CohortFit
|
||||
from models.factors import FREQ_MIN, ORDER
|
||||
|
||||
ALPHA = 0.05
|
||||
FREQ_MIN = 0.80
|
||||
Z = 1.96
|
||||
ORDER = {
|
||||
"riesgo robusto": 0,
|
||||
"protector robusto": 1,
|
||||
"riesgo sugerente": 2,
|
||||
"protector sugerente": 3,
|
||||
"no concluyente": 4,
|
||||
}
|
||||
OR = "OR_recurrencia"
|
||||
SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S")
|
||||
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||
COLUMNS = [
|
||||
"cohorte",
|
||||
@@ -39,16 +24,14 @@ COLUMNS = [
|
||||
"categoria",
|
||||
"referencia",
|
||||
"n_categoria",
|
||||
"OR_recurrencia",
|
||||
OR,
|
||||
"IC95_inf",
|
||||
"IC95_sup",
|
||||
"p",
|
||||
"p_ajustado_BH",
|
||||
"freq_seleccion_bootstrap",
|
||||
"en_manta_markov",
|
||||
"S_libre_categoria",
|
||||
"S_libre_referencia",
|
||||
"delta_S",
|
||||
*SURVIVAL,
|
||||
"delta_IC95_inf",
|
||||
"delta_IC95_sup",
|
||||
"c1_or",
|
||||
@@ -58,39 +41,7 @@ COLUMNS = [
|
||||
"criterios_cumplidos",
|
||||
"clasificacion",
|
||||
]
|
||||
# Scenario presence: the share of the scenario's patients in the category.
|
||||
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
|
||||
DESCRIBING = ("definitoria", "mayoritaria")
|
||||
|
||||
|
||||
def km_at(months, event, horizon) -> tuple[float, float]:
|
||||
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
|
||||
d, _, n = life_table(months, event)
|
||||
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
|
||||
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
|
||||
last = min(horizon, len(d) - 1) + 1
|
||||
S = float(np.prod(q[:last]))
|
||||
return S, S * float(np.sqrt(np.sum(v[:last])))
|
||||
|
||||
|
||||
def _odds_ratios(data: pd.DataFrame, y, variables, reference) -> pd.DataFrame:
|
||||
"""Logistic GLM on every category but each covariate's reference (constant and
|
||||
duplicated dummies dropped): odds ratios with Wald 95 % CI and p."""
|
||||
X = pd.get_dummies(data[variables]).astype(float)
|
||||
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
X = X.loc[:, ~X.T.duplicated()]
|
||||
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ci = np.exp(m.conf_int().loc[X.columns])
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"termino": X.columns,
|
||||
"OR_recurrencia": np.exp(m.params[X.columns].to_numpy()),
|
||||
"IC95_inf": ci[0].to_numpy(),
|
||||
"IC95_sup": ci[1].to_numpy(),
|
||||
"p": m.pvalues[X.columns].to_numpy(),
|
||||
}
|
||||
)
|
||||
DESCRIBING = rated.DESCRIBING
|
||||
|
||||
|
||||
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
|
||||
@@ -103,72 +54,23 @@ def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.Data
|
||||
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
|
||||
|
||||
def complete(table, variables):
|
||||
"""Each term's covariate, category, BH p and survival difference to its reference."""
|
||||
table = table.reset_index(drop=True)
|
||||
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
|
||||
table["categoria"] = [
|
||||
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
|
||||
]
|
||||
table["referencia"] = table["variable"].map(reference)
|
||||
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
|
||||
rows = []
|
||||
for v, cat, ref in zip(
|
||||
table["variable"], table["categoria"], table["referencia"], strict=True
|
||||
):
|
||||
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == ref).to_numpy()
|
||||
(sa, ea), (sb, eb) = (
|
||||
km_at(months[a], event[a], horizon),
|
||||
km_at(months[b], event[b], horizon),
|
||||
)
|
||||
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
|
||||
rows.append(
|
||||
{
|
||||
"n_categoria": int(a.sum()),
|
||||
"S_libre_categoria": sa,
|
||||
"S_libre_referencia": sb,
|
||||
"delta_S": delta,
|
||||
"delta_IC95_inf": delta - Z * se,
|
||||
"delta_IC95_sup": delta + Z * se,
|
||||
}
|
||||
)
|
||||
return pd.concat([table, pd.DataFrame(rows)], axis=1)
|
||||
return rated.complete(table, variables, reference, everyone, months, event, horizon,
|
||||
SURVIVAL) # fmt: skip
|
||||
|
||||
intrinsic, treatment = cohort.intrinsic, cohort.treatment
|
||||
tab = complete(_odds_ratios(data, y, intrinsic, reference), intrinsic)
|
||||
risk = tab["OR_recurrencia"] > 1
|
||||
tab["direccion"] = np.where(risk, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
|
||||
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
|
||||
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab["delta_S"]) == np.where(risk, -1, 1))
|
||||
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), intrinsic)
|
||||
hz = fitted.horizons[horizon]
|
||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
|
||||
lambda v: np.nan if selection is None else selection.get(v, 0.0)
|
||||
)
|
||||
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
|
||||
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents)
|
||||
criteria = ["c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia"]
|
||||
tab["criterios_cumplidos"] = tab[criteria].astype(bool).sum(axis=1)
|
||||
tab["clasificacion"] = [
|
||||
"no aplica (categoria desconocida)"
|
||||
if cat == UNKNOWN
|
||||
else f"{d} robusto"
|
||||
if c1 and k >= 3
|
||||
else f"{d} sugerente"
|
||||
if k >= 2
|
||||
else "no concluyente"
|
||||
for cat, d, c1, k in zip(
|
||||
tab["categoria"],
|
||||
tab["direccion"],
|
||||
tab["c1_or"],
|
||||
tab["criterios_cumplidos"],
|
||||
strict=True,
|
||||
)
|
||||
]
|
||||
tab = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN)
|
||||
tab["tipo"] = "factor de riesgo"
|
||||
if treatment:
|
||||
both = intrinsic + treatment
|
||||
tr = _odds_ratios(data, y, both, reference)
|
||||
of = tr["termino"].map(lambda x: variable_of(x, both))
|
||||
tr = rated.odds_ratios(data, y, both, reference, OR)
|
||||
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
||||
tr = complete(
|
||||
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
|
||||
)
|
||||
@@ -191,72 +93,26 @@ def risk_factors(fitted: CohortFit, selection: dict | None = None) -> pd.DataFra
|
||||
tab = pd.concat(found, ignore_index=True)
|
||||
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
||||
tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5)
|
||||
keys = ["horizonte_meses", "_kind", "_order", "OR_recurrencia"]
|
||||
keys = ["horizonte_meses", "_kind", "_order", OR]
|
||||
tab = tab.sort_values(keys, ascending=[True, True, True, False])
|
||||
return tab[COLUMNS].round(4)
|
||||
|
||||
|
||||
def _presence(share: float) -> str:
|
||||
if share >= DEFINING:
|
||||
return "definitoria"
|
||||
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
|
||||
|
||||
|
||||
def _listing(part: pd.DataFrame) -> str:
|
||||
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
|
||||
`asociacion`."""
|
||||
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
|
||||
part["clasificacion"].str.split().str[-1]) # fmt: skip
|
||||
return "; ".join(
|
||||
f"{v}={c} ({s}, {p:.0%})"
|
||||
for v, c, s, p in zip(
|
||||
part["variable"], part["categoria"], strength, part["share"], strict=True
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
|
||||
"""Per scenario and horizon, the classified factors and treatments nearly all of its
|
||||
patients have (definitorios) or most have (mayoritarios)."""
|
||||
frame, source = fitted.cohort.frame, fitted.cohort.source
|
||||
scenarios = SCENARIOS[source]
|
||||
found = factors[
|
||||
(factors["cohorte"] == source)
|
||||
& factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")
|
||||
]
|
||||
kind = np.where(
|
||||
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
|
||||
)
|
||||
found = found.assign(tipo_efecto=kind)
|
||||
scenarios = fitted.cohort.scenarios
|
||||
found = rated.classified(factors[factors["cohorte"] == source])
|
||||
rows = []
|
||||
for name, mask in masks(frame, scenarios).items():
|
||||
if not mask.any() or found.empty:
|
||||
continue
|
||||
share = [
|
||||
float((frame.loc[mask, v] == c).mean())
|
||||
for v, c in zip(found["variable"], found["categoria"], strict=True)
|
||||
]
|
||||
detail = found.assign(share=share, presence=[_presence(s) for s in share])
|
||||
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
|
||||
for h in fitted.horizons:
|
||||
d = detail[detail["horizonte_meses"] == h]
|
||||
row = {
|
||||
"cohorte": source,
|
||||
"escenario": name,
|
||||
"definicion": definition,
|
||||
"n_escenario": int(mask.sum()),
|
||||
"horizonte_meses": h,
|
||||
}
|
||||
for k in ("riesgo", "protector", "tratamiento"):
|
||||
for level, label in (
|
||||
("definitoria", "definitorios"),
|
||||
("mayoritaria", "mayoritarios"),
|
||||
):
|
||||
row[f"{k}_{label}"] = _listing(
|
||||
d[(d["tipo_efecto"] == k) & (d["presence"] == level)]
|
||||
)
|
||||
included = (d["tipo_efecto"] == "riesgo") & d["presence"].isin(DESCRIBING)
|
||||
row["n_factores_riesgo_incluidos"] = int(included.sum())
|
||||
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
|
||||
rows.append(row)
|
||||
rows.append({
|
||||
"cohorte": source, "escenario": name, "definicion": definition,
|
||||
"n_escenario": int(mask.sum()), "horizonte_meses": h,
|
||||
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
|
||||
}) # fmt: skip
|
||||
return rows
|
||||
|
||||
@@ -20,9 +20,9 @@ from pgmpy.structure_score import BDeu
|
||||
from sklearn.metrics import roc_auc_score
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
from models.cama.recurrence.cohorts import Cohort, at_horizon
|
||||
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
|
||||
from models.factors import variable_of
|
||||
|
||||
HORIZONS = (12, 36, 60) # months
|
||||
SEED = 42
|
||||
TEST_SIZE = 0.3
|
||||
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
|
||||
@@ -31,7 +31,7 @@ ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
|
||||
MAX_STEPS = 200
|
||||
COX_PENALIZER = 0.05
|
||||
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
|
||||
N_BOOTSTRAP = {"metabric": 100, "scanb": 40}
|
||||
N_BOOTSTRAP = {"site": 40}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- logistic regression
|
||||
@@ -203,12 +203,6 @@ def c_index(cohort: Cohort) -> float:
|
||||
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
|
||||
|
||||
|
||||
def variable_of(term: str, covariates: list[str]) -> str:
|
||||
"""The covariate a dummy belongs to (the longest name it starts with)."""
|
||||
found = [c for c in covariates if term.startswith(c + "_")]
|
||||
return max(found, key=len) if found else term
|
||||
|
||||
|
||||
@dataclass
|
||||
class Horizon:
|
||||
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
|
||||
|
||||
@@ -15,7 +15,6 @@ from models.cama.recurrence.modeling import (
|
||||
ESS,
|
||||
HORIZONS,
|
||||
MAX_PARENTS,
|
||||
N_BOOTSTRAP,
|
||||
CohortFit,
|
||||
)
|
||||
|
||||
@@ -109,8 +108,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
||||
}
|
||||
for s, c in cohorts.items()
|
||||
},
|
||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
||||
"origen": "METABRIC y SCAN-B (externas)",
|
||||
**next(iter(cohorts.values())).sampling,
|
||||
},
|
||||
"DATOS_FALTANTES": {
|
||||
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
|
||||
@@ -137,7 +135,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
||||
"salida": "probabilidad libre de recaída por escenario y horizonte con IC 95 % por "
|
||||
"bootstrap",
|
||||
"replicas": {
|
||||
**{s: n_bootstrap.get(s, 0) for s in N_BOOTSTRAP},
|
||||
**{s: n_bootstrap.get(s, 0) for s in cohorts},
|
||||
"calculadora": RESAMPLES,
|
||||
},
|
||||
"eventos_minimos_por_escenario": MIN_EVENTS,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""The site's own recurrence cohort (the `site` source of models.cama.recurrence): the CaMa
|
||||
timelines of `gold.cama_cohort_recurrence`, indexed at each patient's first invasive biopsy
|
||||
report, as one table in the shape of SCAN-B's (the clinical cohort the old model learned
|
||||
from), so the same fits, calculator and risk factors run on it.
|
||||
|
||||
- Time and event: months from the index to her first recurrence (any site) after it, else to
|
||||
her death, else to the cut-off (the site records its recurrences: a patient without one is
|
||||
taken as free of it up to then); `muerte_sin_recaida` when she died without one.
|
||||
- Covariates, from the index report's results (a week before to RESULT_DAYS after) and the
|
||||
first course of treatment (TREATMENT_DAYS), as categories (missing: UNKNOWN):
|
||||
age, size and positive nodes in SCAN-B's bands, grade, ER, PR, HER2, Ki-67 (< 20 % or
|
||||
more), histologic type, stage group, and the clinical subtype by the St. Gallen surrogate:
|
||||
Luminal A (HR+, HER2−, Ki-67 < 20 %), Luminal B HER2− (Ki-67 ≥ 20 %), Luminal B HER2+,
|
||||
Non-luminal HER2+ and Basal-like (triple negative), as SCAN-B names them."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.cama.recurrence import cohorts
|
||||
from models.cama.recurrence.cohorts import UNKNOWN, Cohort, _band, _text, collinear
|
||||
|
||||
RESULT_DAYS = 30
|
||||
TREATMENT_DAYS = 365
|
||||
KI67_HIGH = 20.0 # %, St. Gallen's cut between Luminal A and Luminal B
|
||||
STAGE_GROUP = {"0": "0", "I": "I", "IA": "I", "IB": "I", "II": "II", "IIA": "II", "IIB": "II",
|
||||
"III": "III", "IIIA": "III", "IIIB": "III", "IIIC": "III", "IV": "IV"} # fmt: skip
|
||||
RECEPTOR = {"positive": "Positive", "negative": "Negative"}
|
||||
SURGERY = {"breast_conserving_surgery": "Lumpectomy", "mastectomy": "Mastectomy"}
|
||||
TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
|
||||
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
|
||||
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
||||
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:
|
||||
"""The St. Gallen surrogate of the intrinsic subtype, as SCAN-B names it."""
|
||||
hormone = "positive" in (er, pr)
|
||||
if her2 == "positive":
|
||||
return "Luminal B HER2+" if hormone else "Non-luminal HER2+"
|
||||
if her2 != "negative":
|
||||
return UNKNOWN
|
||||
if not hormone:
|
||||
return "Basal-like" if er == "negative" and pr == "negative" else UNKNOWN
|
||||
if ki67 is None or ki67 != ki67:
|
||||
return UNKNOWN
|
||||
return "Luminal A" if ki67 < KI67_HIGH else "Luminal B HER2-"
|
||||
|
||||
|
||||
def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
|
||||
"""One row per member: her time, event and covariates, as `cohorts.prepare` gives a
|
||||
reference cohort's."""
|
||||
events = events.assign(date=pd.to_datetime(events["date"]),
|
||||
index_date=pd.to_datetime(events["index_date"])) # fmt: skip
|
||||
members = events.groupby("person_id")["index_date"].first()
|
||||
days = (events["date"] - events["index_date"]).dt.days
|
||||
cut = pd.Timestamp(as_of)
|
||||
after = events[(days > 0) & (events["date"] <= cut)]
|
||||
first_recurrence = after[after["type"] == "recurrence"].groupby("person_id")["date"].min()
|
||||
death = events[(events["type"] == "death") & (events["date"] <= cut)]
|
||||
death = death.groupby("person_id")["date"].min().reindex(members.index)
|
||||
end = first_recurrence.reindex(members.index).fillna(death).fillna(cut)
|
||||
out = pd.DataFrame(index=members.index)
|
||||
out["paciente"] = members.index
|
||||
out["tiempo_meses"] = (end - members).dt.days / cohorts.DAYS_PER_MONTH
|
||||
out["evento"] = first_recurrence.reindex(members.index).notna().astype(int)
|
||||
out["muerte_sin_recaida"] = (death.notna() & (out["evento"] == 0)).astype(int)
|
||||
|
||||
near = events[days.between(-7, RESULT_DAYS)].sort_values(["date", "source_id"])
|
||||
code = lambda kind: near[near["type"] == kind].groupby("person_id")["value_code"].first() # noqa: E731
|
||||
number = lambda kind: near[near["type"] == kind].groupby("person_id")["value_num"].first() # noqa: E731
|
||||
birth = events[events["type"] == "birth"].groupby("person_id")["date"].min()
|
||||
age = (members - birth.reindex(members.index)).dt.days / 365.25
|
||||
out["Edad"] = _band(age, *cohorts.AGE)
|
||||
out["Tamano_tumor"] = _band(number("size_mm").reindex(members.index), *cohorts.SIZE)
|
||||
out["Ganglios_positivos"] = _band(number("positive_nodes").reindex(members.index),
|
||||
*cohorts.NODES) # fmt: skip
|
||||
out["Grado_histologico"] = _text(code("grade").reindex(members.index).map(cohorts.GRADES))
|
||||
receptors = {k: code(k).reindex(members.index) for k in ("er", "pr", "her2")}
|
||||
ki67 = number("ki67_pct").reindex(members.index)
|
||||
out["Receptor_estrogeno"] = _text(receptors["er"].map(RECEPTOR))
|
||||
out["Receptor_progesterona"] = _text(receptors["pr"].map(RECEPTOR))
|
||||
out["HER2"] = _text(receptors["her2"].map(RECEPTOR))
|
||||
high = np.where(ki67 < KI67_HIGH, f"<{KI67_HIGH:g}%", f">={KI67_HIGH:g}%")
|
||||
out["Ki67"] = _text(pd.Series(np.where(ki67.isna(), None, high), index=members.index))
|
||||
out["Subtipo_clinico"] = [subtype(*a) for a in zip(
|
||||
receptors["er"], receptors["pr"], receptors["her2"], ki67, strict=True)] # fmt: skip
|
||||
out["Tipo_histologico"] = _text(code("histologic_type").reindex(members.index))
|
||||
out["Estadio_clinico"] = _text(code("stage").reindex(members.index).map(STAGE_GROUP))
|
||||
course = events[(events["type"] == "treatment") & days.between(0, TREATMENT_DAYS)]
|
||||
given = course.groupby("person_id")["value_code"].agg(set).reindex(members.index)
|
||||
given = given.apply(lambda g: g if isinstance(g, set) else set())
|
||||
out["Cirugia"] = given.apply(
|
||||
lambda g: next((SURGERY[s] for s in reversed(SURGERY) if s in g), "None")
|
||||
)
|
||||
for name, kind in TREATMENTS.items():
|
||||
out[name] = given.apply(lambda g, k=kind: "Yes" if k in g else "No")
|
||||
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:
|
||||
"""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
|
||||
scenarios name patients by them (the subtype, built from the receptors and Ki-67, is
|
||||
redundant by construction)."""
|
||||
covariates = [c for c in rows.columns if c not in FIXED]
|
||||
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
|
||||
kept = [c for c in covariates if c not in dropped]
|
||||
treatment = [c for c in TREATMENT if c in kept]
|
||||
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
|
||||
SCENARIOS, SAMPLING) # fmt: skip
|
||||
+35
-25
@@ -7,17 +7,16 @@
|
||||
known at it. A patient who dies before her treatment counts as untreated (immortal-time
|
||||
bias), which the technical report states.
|
||||
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 two public reference
|
||||
cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the
|
||||
`cama_reference` pipeline, not on the hospital's patients; slow (its bootstraps take a
|
||||
quarter of an hour), so it trains only when asked for by name."""
|
||||
- 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
|
||||
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py)."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models.survival import DAYS_PER_YEAR, Spec, age_group, band
|
||||
from persistance import nodes
|
||||
from models.survival import DAYS_PER_YEAR, OUTPUT, SCENARIO_SEPARATOR, Spec, age_group, band
|
||||
|
||||
# The index report's results (timeline types), read from a week before to RESULT_DAYS after.
|
||||
RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
|
||||
@@ -89,33 +88,43 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReferenceRecurrence:
|
||||
"""The recurrence model over the reference cohorts the `pipeline` loaded: one source node
|
||||
per cohort, named as the cohort."""
|
||||
class SiteRecurrence:
|
||||
"""The recurrence model on the site's own patients (models.cama.recurrence.site): the
|
||||
cohort's timelines in, its fits, calculator and risk factors out, with its own reports;
|
||||
each member scored at 12, 36 and 60 months, with the clinical scenarios she falls in."""
|
||||
|
||||
name: str
|
||||
pipeline: str = "cama_reference"
|
||||
cohort: None = None # trains on no gold cohort, and scores no patient
|
||||
slow: bool = True
|
||||
cohort: str = "cama_cohort_recurrence"
|
||||
reports: bool = True # it writes its own reports (models.jobs)
|
||||
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
|
||||
|
||||
def train(self, events, as_of=None) -> tuple:
|
||||
from models.cama import recurrence
|
||||
from models.cama.recurrence import site
|
||||
from models.jobs import EmptyCohort
|
||||
|
||||
model, metrics, reports = recurrence.train(self.datasets())
|
||||
return model, metrics, reports
|
||||
|
||||
def datasets(self) -> dict[str, pd.DataFrame]:
|
||||
"""Each reference cohort's rows, as the pipeline loaded them."""
|
||||
from models.cama import recurrence
|
||||
|
||||
found = {s: pd.DataFrame(nodes.rows(self.pipeline, s)) for s in recurrence.SOURCES}
|
||||
if any(r.empty for r in found.values()):
|
||||
raise LookupError(f"load the reference cohorts first (pipeline {self.pipeline})")
|
||||
return found
|
||||
rows = 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:
|
||||
return model.predict(events)
|
||||
from models.cama.recurrence import calculator, site
|
||||
|
||||
members = site.frame(events, date.today())
|
||||
found = model.predict(members)
|
||||
index = events.groupby("person_id")["index_date"].first()
|
||||
masks = calculator.masks(members, site.SCENARIOS)
|
||||
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
|
||||
for i in range(len(members))] # fmt: skip
|
||||
rows = []
|
||||
for i, person in enumerate(members["paciente"]):
|
||||
for h in model.horizons:
|
||||
rows.append({"person_id": person,
|
||||
"index_date": pd.Timestamp(index[person]).date(),
|
||||
"horizon_years": h / 12, "probability": found[f"recurrence_{h}m"][i],
|
||||
"ci_low": None, "ci_high": None, "scenarios": named[i]}) # fmt: skip
|
||||
return pd.DataFrame(rows, columns=OUTPUT)
|
||||
|
||||
|
||||
MODELS = {
|
||||
@@ -146,6 +155,7 @@ MODELS = {
|
||||
cap_months=24,
|
||||
scenarios=SCENARIOS,
|
||||
scenario_columns=("age",),
|
||||
treatments=("surgery", "chemotherapy", "radiotherapy"),
|
||||
notes=(
|
||||
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
|
||||
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
|
||||
@@ -153,5 +163,5 @@ MODELS = {
|
||||
"efecto protector del tratamiento aparece mayor de lo que es.",
|
||||
),
|
||||
),
|
||||
"recurrence": ReferenceRecurrence("recurrence"),
|
||||
"recurrence": SiteRecurrence("recurrence"),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Where long batches run (the EEG analysis, measuring a reference cohort). Where Dask is
|
||||
installed (the `dask` extra, for testing on a cluster) they run on the scheduler at
|
||||
DASK_SCHEDULER_ADDRESS, or on a Dask cluster of this machine's cores. Without it (the
|
||||
product) joblib runs them on local processes. BATCH_JOBS caps how many run at once: each
|
||||
task carries its data (a recording), so a cap paces a slow link."""
|
||||
|
||||
import os
|
||||
from collections.abc import Callable, Iterable
|
||||
from importlib.util import find_spec
|
||||
from typing import Any
|
||||
|
||||
from joblib import Parallel, delayed
|
||||
|
||||
|
||||
def jobs() -> int:
|
||||
"""How many tasks run at once: BATCH_JOBS, or every core (or worker)."""
|
||||
return int(os.environ.get("BATCH_JOBS", "-1"))
|
||||
|
||||
|
||||
def run(task: Callable, arguments: Iterable[tuple]) -> list[Any]:
|
||||
"""`task(*a)` for each tuple of `arguments`, results in their order. The arguments are
|
||||
drawn as tasks start, so at most `jobs()` of them are held at once."""
|
||||
if find_spec("distributed") is None:
|
||||
return Parallel(n_jobs=jobs())(delayed(task)(*a) for a in arguments)
|
||||
from distributed import Client, LocalCluster, as_completed
|
||||
|
||||
address = os.environ.get("DASK_SCHEDULER_ADDRESS")
|
||||
# one process per core, no dashboard port to collide with (8787 is often taken)
|
||||
where = address or LocalCluster(threads_per_worker=1, dashboard_address=None)
|
||||
try:
|
||||
with Client(where) as client:
|
||||
limit = jobs() if jobs() > 0 else sum(client.nthreads().values())
|
||||
pending = iter(enumerate(arguments))
|
||||
results: dict[int, Any] = {}
|
||||
order: dict[Any, int] = {}
|
||||
|
||||
def submit() -> Any | None:
|
||||
if (item := next(pending, None)) is None:
|
||||
return None
|
||||
future = client.submit(task, *item[1], pure=False)
|
||||
order[future] = item[0]
|
||||
return future
|
||||
|
||||
running = as_completed([f for f in (submit() for _ in range(limit)) if f])
|
||||
for done in running:
|
||||
results[order.pop(done)] = done.result()
|
||||
if (future := submit()) is not None:
|
||||
running.add(future)
|
||||
return [results[i] for i in range(len(results))]
|
||||
finally:
|
||||
if not address:
|
||||
where.close()
|
||||
+103
-149
@@ -1,45 +1,19 @@
|
||||
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
||||
|
||||
import hashlib
|
||||
import importlib
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
import os
|
||||
from datetime import date
|
||||
|
||||
import dagster as dg
|
||||
|
||||
from core.domains import Domain
|
||||
from models import execution, graph
|
||||
from models import draft, graph
|
||||
from models.jobs import EmptyCohort
|
||||
from models.tea import jobs as tea_jobs
|
||||
from persistance import bundle, cluster, config_log, eeg, silver
|
||||
from persistance import backup as backups
|
||||
from persistance import config_log, silver
|
||||
|
||||
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
||||
|
||||
|
||||
class ExecutionConfig(dg.Config):
|
||||
"""Where a heavy op's work runs: the fields of `persistance.cluster.Execution`."""
|
||||
|
||||
mode: str | None = None # Dagster's config has no Literal: `model()` checks it
|
||||
scheduler: str | None = None
|
||||
|
||||
def model(self) -> cluster.Execution:
|
||||
return cluster.Execution(**self.model_dump())
|
||||
|
||||
|
||||
class ScopeConfig(dg.Config):
|
||||
"""Which EEGs an analysis takes: the fields of `persistance.eeg.Scope`."""
|
||||
|
||||
mode: str = "pending" # Dagster's config has no Literal: `model()` checks it
|
||||
n: int | None = None
|
||||
ids: list[str] = []
|
||||
|
||||
def model(self) -> eeg.Scope:
|
||||
return eeg.Scope(**self.model_dump()) # validates
|
||||
|
||||
|
||||
class PipelineRun(dg.Config):
|
||||
pipeline: str
|
||||
version: int | None = None # default: the latest saved
|
||||
@@ -59,6 +33,28 @@ def ingest():
|
||||
run_pipeline()
|
||||
|
||||
|
||||
class DraftRun(dg.Config):
|
||||
pipeline: str
|
||||
run: bool = True # False: drawn and saved only (a large site, read later)
|
||||
|
||||
|
||||
@dg.op
|
||||
def draft_pipeline(context: dg.OpExecutionContext, config: DraftRun) -> int:
|
||||
"""Automático: the whole pipeline drafted from its sources, saved as a new version and
|
||||
run (unless `run` is off). Returns that version."""
|
||||
drafted = draft.draft(config.pipeline, log=context.log.info)
|
||||
version = config_log.save(config.pipeline, drafted)
|
||||
context.log.info(f"{config.pipeline} v{version}: {len(drafted.nodes)} nodes drafted")
|
||||
if config.run:
|
||||
graph.run(config.pipeline, drafted, log=context.log.info)
|
||||
return version
|
||||
|
||||
|
||||
@dg.job(name="draft", tags=WRITES)
|
||||
def draft_job():
|
||||
draft_pipeline()
|
||||
|
||||
|
||||
def _jobs(domain: str):
|
||||
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
|
||||
try:
|
||||
@@ -69,9 +65,8 @@ def _jobs(domain: str):
|
||||
|
||||
class Training(dg.Config):
|
||||
domain: str
|
||||
models: list[str] = [] # default: every model of the domain but the slow ones
|
||||
models: list[str] = [] # default: every model of the domain
|
||||
as_of: str | None = None # the date the data are taken up to (default: today)
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
|
||||
|
||||
@dg.op
|
||||
@@ -80,15 +75,14 @@ def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
|
||||
jobs = _jobs(config.domain)
|
||||
as_of = date.fromisoformat(config.as_of) if config.as_of else None
|
||||
found = {}
|
||||
with execution.running(context, config.execution.model()):
|
||||
for name in config.models or jobs.JOBS.routine():
|
||||
try:
|
||||
found[name] = jobs.train(name, as_of)
|
||||
except EmptyCohort as e: # the site has no such patients; the others still train
|
||||
found[name] = None
|
||||
context.log.warning(f"{e}: not trained")
|
||||
continue
|
||||
context.log.info(f"{config.domain}.{name}: version {found[name]}")
|
||||
for name in config.models or jobs.JOBS.routine():
|
||||
try:
|
||||
found[name] = jobs.train(name, as_of)
|
||||
except EmptyCohort as e: # the site has no such patients; the others still train
|
||||
found[name] = None
|
||||
context.log.warning(f"{e}: not trained")
|
||||
continue
|
||||
context.log.info(f"{config.domain}.{name}: version {found[name]}")
|
||||
return found
|
||||
|
||||
|
||||
@@ -120,14 +114,12 @@ def score():
|
||||
|
||||
class Analysis(dg.Config):
|
||||
domain: str
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
|
||||
|
||||
@dg.op
|
||||
def analyze_studies(context: dg.OpExecutionContext, config: Analysis) -> int:
|
||||
"""The domain's studies a model reads whole (TEA: each EEG not analysed yet)."""
|
||||
with execution.running(context, config.execution.model()):
|
||||
found = _jobs(config.domain).analyze()
|
||||
found = _jobs(config.domain).analyze()
|
||||
context.log.info(f"{config.domain}: {found} analysed")
|
||||
return found
|
||||
|
||||
@@ -137,119 +129,81 @@ def analyze():
|
||||
analyze_studies()
|
||||
|
||||
|
||||
class TeaAnalysis(dg.Config):
|
||||
scope: ScopeConfig = ScopeConfig()
|
||||
execution: ExecutionConfig = ExecutionConfig()
|
||||
class Development(dg.Config):
|
||||
as_of: str
|
||||
max_fits: int = 100_000
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_analyze_studies(context: dg.OpExecutionContext, config: TeaAnalysis) -> dict:
|
||||
"""The EEGs in scope, analysed in the chosen execution. Bronze is written after the last
|
||||
study, so a cancel during the analysis leaves it as it was."""
|
||||
with execution.running(context, config.execution.model()):
|
||||
found = tea_jobs.analyze(config.scope.model(), rebuild_gold=False)
|
||||
context.log.info(f"{found} EEGs analysed (scope {config.scope.mode})")
|
||||
return {"analysed": found}
|
||||
def evaluate_cacu_development(context: dg.OpExecutionContext, config: Development) -> str:
|
||||
"""Opt-in research (models.cacu.development): which encoders predict CIN2+ at one year
|
||||
in the surveillance cohort; logged to MLflow, nothing registered, promoted or scored."""
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu
|
||||
from models.cacu import development, encoders, features
|
||||
from persistance import gold, registry
|
||||
|
||||
@dg.op
|
||||
def tea_score_curves(context: dg.OpExecutionContext, analysed: dict) -> dict:
|
||||
"""Each age curve's champion scores every analysed EEG."""
|
||||
found = tea_jobs.score_curves()
|
||||
for name, version in found.items():
|
||||
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
||||
return {"scored": found}
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_relate_ados2(context: dg.OpExecutionContext, scored: dict) -> dict:
|
||||
"""The ADOS-2 association champion scores the EEGs (a seam: nothing until Phase 2)."""
|
||||
version = tea_jobs.relate()
|
||||
context.log.info("ados2_association: " + (f"version {version}" if version else "no champion"))
|
||||
return {"ados2_association": version}
|
||||
|
||||
|
||||
@dg.op
|
||||
def tea_build_gold(context: dg.OpExecutionContext, related: dict) -> dict:
|
||||
"""Gold's TEA tables rebuilt from bronze. A cancel here stops dbt between models, so gold
|
||||
may be partly rebuilt until the next successful run (dbt replaces each model whole)."""
|
||||
silver.build(tea_jobs.GOLD_SELECT)
|
||||
context.log.info("gold rebuilt")
|
||||
return {"built": tea_jobs.GOLD_SELECT}
|
||||
|
||||
|
||||
@dg.job(tags={**WRITES, "domain": "tea"})
|
||||
def tea_eeg():
|
||||
"""Analyse the EEGs in scope, score the age curves, relate ADOS-2, rebuild gold."""
|
||||
tea_build_gold(tea_relate_ados2(tea_score_curves(tea_analyze_studies())))
|
||||
|
||||
|
||||
def pending_eegs() -> bool:
|
||||
return bool(eeg.pending())
|
||||
|
||||
|
||||
def after_ingest(run_id: str, has_pending: Callable[[], bool]) -> dg.RunRequest | dg.SkipReason:
|
||||
"""A `tea_eeg` run for an ingest that left EEGs to analyse; otherwise a skip."""
|
||||
if not has_pending():
|
||||
return dg.SkipReason("the ingest brought no EEG to analyse")
|
||||
return dg.RunRequest(
|
||||
run_key=f"after-ingest-{run_id}",
|
||||
run_config={"ops": {"tea_analyze_studies": {"config": {"scope": {"mode": "pending"}}}}},
|
||||
tags={"domain": "tea", "triggered_by": run_id},
|
||||
)
|
||||
|
||||
|
||||
@dg.run_status_sensor(
|
||||
name="tea_eeg_after_ingest",
|
||||
run_status=dg.DagsterRunStatus.SUCCESS,
|
||||
monitored_jobs=[ingest],
|
||||
request_job=tea_eeg,
|
||||
minimum_interval_seconds=10,
|
||||
default_status=dg.DefaultSensorStatus.RUNNING,
|
||||
)
|
||||
def tea_eeg_after_ingest(context: dg.RunStatusSensorContext):
|
||||
return after_ingest(context.dagster_run.run_id, pending_eegs)
|
||||
|
||||
|
||||
class BundleImport(dg.Config):
|
||||
domain: str
|
||||
sha256: str
|
||||
|
||||
|
||||
@dg.op
|
||||
def import_bundle_files(context: dg.OpExecutionContext, config: BundleImport) -> dict:
|
||||
path = bundle.staged(config.sha256)
|
||||
try:
|
||||
data = path.read_bytes()
|
||||
if hashlib.sha256(data).hexdigest() != config.sha256:
|
||||
raise bundle.BundleError("the staged file's SHA-256 does not match the run config")
|
||||
result = bundle.import_(Domain(config.domain), data)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
manifest = json.loads(archive.read(bundle.MANIFEST))
|
||||
skipped = set(result.skipped)
|
||||
sources = sorted(
|
||||
(item["name"], item["version"])
|
||||
for item in manifest["versions"]
|
||||
if (item["name"], item["version"]) not in skipped
|
||||
)
|
||||
for (_, source), (name, version) in zip(sources, result.imported, strict=True):
|
||||
context.log.info(f"{name}: source v{source} -> version {version}")
|
||||
for name, version in result.skipped:
|
||||
context.log.warning(f"{name} v{version}: already registered, skipped")
|
||||
return {
|
||||
"imported": [list(item) for item in result.imported],
|
||||
"skipped": [list(item) for item in result.skipped],
|
||||
}
|
||||
as_of, cohort = date.fromisoformat(config.as_of), "cacu_cohort_surveillance"
|
||||
events = gold.evidence_timelines("cacu_events", cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"nobody in {cohort}")
|
||||
outcome = features.windowed_outcome(features.prepared(events), cacu.CIN2_PLUS, 1.0,
|
||||
pd.Timestamp(as_of)) # fmt: skip
|
||||
rows = encoders.encode(events, gold.cervical_forms(cohort)).merge(outcome, on="person_id")
|
||||
rows = rows[rows["known"]].reset_index(drop=True)
|
||||
X = rows.drop(columns=["person_id", "index_date", "known", "y"])
|
||||
report = development.evaluate(X, rows["y"].to_numpy(), max_fits=config.max_fits)
|
||||
report |= {"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(f"development evaluation logged as {run.info.run_id}")
|
||||
return run.info.run_id
|
||||
|
||||
|
||||
@dg.job
|
||||
def import_bundle():
|
||||
import_bundle_files()
|
||||
def cacu_development_evaluation():
|
||||
evaluate_cacu_development()
|
||||
|
||||
|
||||
defs = dg.Definitions(
|
||||
jobs=[ingest, train, score, analyze, tea_eeg, import_bundle], sensors=[tea_eeg_after_ingest]
|
||||
@dg.op
|
||||
def build_gold(context: dg.OpExecutionContext) -> None:
|
||||
"""Silver and all that derives from it, with the deployed code: an ingest's end without
|
||||
ingesting (after deploying a version that changes the tables)."""
|
||||
silver.build(["silver+"])
|
||||
context.log.info("silver and gold rebuilt")
|
||||
|
||||
|
||||
@dg.job(tags=WRITES)
|
||||
def rebuild():
|
||||
build_gold()
|
||||
|
||||
|
||||
@dg.op
|
||||
def make_backup(context: dg.OpExecutionContext) -> str:
|
||||
"""The data folder into BACKUP_DIR (persistance.backup); the newest BACKUP_KEEP stay."""
|
||||
folder = backups.create()
|
||||
context.log.info(f"backup {folder}")
|
||||
return str(folder)
|
||||
|
||||
|
||||
@dg.job(tags=WRITES) # holds the writing slot: nothing writes while it copies
|
||||
def backup():
|
||||
make_backup()
|
||||
|
||||
|
||||
# Nightly by default; BACKUP_SCHEDULE is a cron expression (empty: no schedule).
|
||||
nightly = (
|
||||
[
|
||||
dg.ScheduleDefinition(
|
||||
job=backup, cron_schedule=cron, default_status=dg.DefaultScheduleStatus.RUNNING
|
||||
)
|
||||
] # fmt: skip
|
||||
if (cron := os.environ.get("BACKUP_SCHEDULE", "30 2 * * *"))
|
||||
else []
|
||||
)
|
||||
|
||||
JOBS = [ingest, draft_job, train, score, analyze, rebuild, backup, cacu_development_evaluation]
|
||||
defs = dg.Definitions(jobs=JOBS, schedules=nightly)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Automático: a whole pipeline drafted from the sources an operator connected. Each source
|
||||
is loaded and its files read as a run would; documents are drafted by layout
|
||||
(models.draft.documents), tables by column (models.draft.tables); one link node gathers
|
||||
every record's identity and one target per study saves it. The model only fills typed
|
||||
slots that code checks; who is the same patient stays with the reviewers."""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
|
||||
from core.pipeline import ENTITY_TITLES, Link, Pipeline, Read, Target
|
||||
from models import graph
|
||||
from models.draft import documents, fields, tables
|
||||
from persistance import config_log, files, nodes
|
||||
|
||||
FILE_KEY = re.compile(r"^[0-9a-f]{64}$") # a kept file's key (persistance.files)
|
||||
SCANNED = 50 # rows looked at to tell a column of files
|
||||
|
||||
|
||||
class Draft:
|
||||
"""The nodes drafted so far, their ids unique, and the site's codes found."""
|
||||
|
||||
def __init__(self, pipeline_id: str, sources: list):
|
||||
self.pipeline_id, self.nodes = pipeline_id, list(sources)
|
||||
self.identity: list[str] = []
|
||||
self.studies: dict[str, list[str]] = {}
|
||||
self.codes = fields.Codes(pipeline_id)
|
||||
|
||||
def id(self, text: str) -> str:
|
||||
plain = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()
|
||||
base = re.sub(r"[^a-z0-9]+", "_", plain).strip("_")[:34] or "nodo"
|
||||
base = base if base[0].isalpha() else f"n_{base}"[:34]
|
||||
taken, found, n = {n.id for n in self.nodes}, base, 1
|
||||
while found in taken:
|
||||
n += 1
|
||||
found = f"{base}_{n}"
|
||||
return found
|
||||
|
||||
def add(self, node):
|
||||
self.nodes.append(node)
|
||||
return node
|
||||
|
||||
def finish(self) -> Pipeline:
|
||||
"""The site's codes saved as its ConceptMap, one link node, a target per study."""
|
||||
if not self.identity:
|
||||
raise ValueError("nothing read says whom a record is about: nothing to link")
|
||||
if (found := self.codes.concept_map()) is not None:
|
||||
config_log.save(self.codes.map_id, found, "concept_maps")
|
||||
link = self.add(Link(id=self.id("personas"), label="Quién es quién",
|
||||
inputs=self.identity)) # fmt: skip
|
||||
for entity, inputs in self.studies.items():
|
||||
self.add(Target(id=self.id(f"guardar_{entity}"), label=ENTITY_TITLES[entity],
|
||||
inputs=[*inputs, link.id], entity=entity)) # fmt: skip
|
||||
return Pipeline(nodes=self.nodes)
|
||||
|
||||
|
||||
def file_columns(rows: list[dict]) -> list[str]:
|
||||
"""Columns whose values are kept files (a source keeps each file once and passes its key)."""
|
||||
found = []
|
||||
for column in sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")}):
|
||||
values = {r.get(column) for r in rows[:SCANNED]} - {None}
|
||||
if values and all(isinstance(v, str) and FILE_KEY.match(v) for v in values):
|
||||
if files.known(values):
|
||||
found.append(column)
|
||||
return found
|
||||
|
||||
|
||||
def draft(pipeline_id: str, log: Callable[[str], None] = print) -> Pipeline:
|
||||
"""The pipeline Automático draws from a saved pipeline made of sources only."""
|
||||
_, saved = config_log.get(pipeline_id)
|
||||
sources = [n for n in saved.nodes if n.kind == "source"]
|
||||
if not sources or len(sources) != len(saved.nodes):
|
||||
raise ValueError("Automático starts from a pipeline that holds only its sources")
|
||||
d = Draft(pipeline_id, sources)
|
||||
for source in sources:
|
||||
nodes.run_source(pipeline_id, source)
|
||||
rows = list(nodes.rows(pipeline_id, source.id))
|
||||
log(f"{source.id}: {len(rows)} rows")
|
||||
found = file_columns(rows)
|
||||
for column in found:
|
||||
read = d.add(Read(id=d.id(f"texto_{source.id}"), label="Texto de cada documento",
|
||||
inputs=[source.id], column=column)) # fmt: skip
|
||||
graph.run_read(pipeline_id, read)
|
||||
documents.draft(d, read, list(nodes.rows(pipeline_id, read.id)), log)
|
||||
if not found:
|
||||
tables.draft(d, source, rows, log)
|
||||
return d.finish()
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Documents (a column of files, read to text): grouped by layout, each layout named by the
|
||||
model with the studies it reports and the phrases that mark it and each of them (a route,
|
||||
and a route under it for a study only some of its documents report: the organ a
|
||||
pathology report is about, a note that records a death), and read for each study (joined
|
||||
to the documents it answers, if it needs them: joins) and for whom it is about (extract
|
||||
nodes, with patterns for when no model answers). What no layout claims goes to the
|
||||
unrecognised route, for a reviewer."""
|
||||
|
||||
import dataclasses
|
||||
import re
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass
|
||||
|
||||
from core.drafting import LAYOUT, layout_schema, studies_text
|
||||
from core.pipeline import ENTITY_TITLES, Condition, Extract, Join, Read, Route, ground
|
||||
from models import graph
|
||||
from models.draft import fields, joins
|
||||
from models.draft.joins import Kind
|
||||
from models.draft.layouts import (
|
||||
LOOSE,
|
||||
condition,
|
||||
diverse,
|
||||
kinds_of,
|
||||
layouts,
|
||||
marks,
|
||||
phrase,
|
||||
printed_line,
|
||||
shared_words,
|
||||
spread,
|
||||
)
|
||||
from persistance import llm
|
||||
|
||||
SAMPLE = 2000 # documents grouped by layout at most (grouping compares every pair)
|
||||
SHOWN = 8 # documents of a layout the model is shown to name its studies
|
||||
PER_STUDY = 3 # documents of a study the model reads for where each field is written
|
||||
CHARS = 3000 # of each document shown to name a layout (its title and labels come first)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Layout:
|
||||
label: str
|
||||
marker: str
|
||||
members: list[dict] = dataclasses.field(default_factory=list)
|
||||
everyone: list[dict] = dataclasses.field(default_factory=list)
|
||||
route: Route | None = None
|
||||
|
||||
|
||||
def draft(d, read: Read, rows: list[dict], log) -> None:
|
||||
"""Routes, extracts (and joins) and the unrecognised route for one read node's
|
||||
documents."""
|
||||
documents = sorted((r for r in rows if r.get("text")), key=lambda r: r["_record"])
|
||||
sample = spread(documents, SAMPLE)
|
||||
groups: dict[int, list[dict]] = {}
|
||||
for row, group in zip(sample, layouts([r["text"] for r in sample]), strict=True):
|
||||
if group >= 0:
|
||||
groups.setdefault(group, []).append(row)
|
||||
answers = []
|
||||
for members in groups.values():
|
||||
shown = diverse(members, SHOWN)
|
||||
text = "\n\n".join(f"=== Documento {i} ===\n{r['text'][:CHARS]}"
|
||||
for i, r in enumerate(shown, 1)) # fmt: skip
|
||||
try:
|
||||
answer = llm.ask(LAYOUT.format(studies=studies_text()), text, layout_schema(len(shown)))
|
||||
except llm.Unreadable as e: # left undrawn: a person draws its route
|
||||
log(f"layout of {len(members)} left out, the model's answer: {e}")
|
||||
continue
|
||||
answers.append((answer, members, shown))
|
||||
found, kinds = {}, {}
|
||||
for answer, members, shown in answers:
|
||||
entities = {s["entity"] for s in answer["studies"]}
|
||||
others = [r for a, m, _ in answers if not entities & {s["entity"] for s in a["studies"]}
|
||||
for r in m] # fmt: skip
|
||||
marker = " ".join(answer["marker"].split())
|
||||
marker = phrase(marker, members, others) or printed_line(
|
||||
members, [r for _, m, _ in answers if m is not members for r in m]
|
||||
)
|
||||
log(f"layout of {len(members)}: «{marker}» {sorted(entities) or 'no study'}")
|
||||
if marker is None or not entities:
|
||||
continue
|
||||
layout = found.setdefault(marker.casefold(), Layout(answer["label"], marker))
|
||||
layout.members.extend(members)
|
||||
for one in answer["studies"]:
|
||||
claimed = {i for o in answer["studies"] if o is not one for i in o["documents"]}
|
||||
if (sub := apart(one, shown, claimed, log, members)) is False:
|
||||
continue
|
||||
kind = kinds.setdefault((marker.casefold(), one["entity"], (sub or "").casefold()),
|
||||
Kind(one["entity"], one["label"], sub or "", [],
|
||||
layout=layout)) # fmt: skip
|
||||
kind.members.extend(r for r in members if not sub or marks(sub, r["text"]))
|
||||
routes(d, read, documents, list(found.values()), list(kinds.values()))
|
||||
for kind in kinds.values():
|
||||
d.studies.setdefault(kind.entity, []).append(study(d, kind, list(kinds.values()), log))
|
||||
for layout in found.values():
|
||||
shown = [(r["text"], r) for r in diverse(layout.members, PER_STUDY)]
|
||||
texts = [r["text"] for r in layout.everyone]
|
||||
d.identity.append(extract(d, layout.route, layout.route.id, "identity", "text",
|
||||
reading("identity", shown), texts)) # fmt: skip
|
||||
d.add(Route(id=d.id("no_reconocidos"), label="Documentos no reconocidos",
|
||||
inputs=[read.id], otherwise=True)) # fmt: skip
|
||||
|
||||
|
||||
def apart(study: dict, shown: list[dict], claimed: set[int], log, layout=()) -> str | None | bool:
|
||||
"""What marks the documents of a layout that report `study`: None when all of them do,
|
||||
or when those the model left out report no other study (`claimed`: those another does;
|
||||
the model is not asked to be exhaustive), a phrase found in each of those it named and
|
||||
in none of the others, False when no such phrase is found (the study is left out)."""
|
||||
named = {i for i in study["documents"] if 1 <= i <= len(shown)}
|
||||
if not named:
|
||||
return False
|
||||
if not (set(range(1, len(shown) + 1)) - named) & claimed:
|
||||
return None
|
||||
mine = [r for i, r in enumerate(shown, 1) if i in named]
|
||||
rest = [r for i, r in enumerate(shown, 1) if i not in named]
|
||||
if found := phrase(" ".join((study["marker"] or "").split()), mine, rest, share=1.0):
|
||||
return found
|
||||
if found := shared_words(mine, rest, study["label"], layout, only=True):
|
||||
return found # the study's own name: what a person would route by
|
||||
telling = lambda line: (-kinds_of(line, shown), len(line)) # noqa: E731
|
||||
line = printed_line(mine, rest, share=1.0, rank=telling)
|
||||
if line and kinds_of(line, shown) < len(shown): # a value others share: no one's name
|
||||
return line
|
||||
if found := shared_words(mine, rest, study["label"], layout):
|
||||
return found
|
||||
log(f"{study['label']}: nothing marks its documents apart from the layout's others")
|
||||
return False
|
||||
|
||||
|
||||
def routes(d, read: Read, documents, found: list[Layout], kinds: list[Kind]) -> None:
|
||||
"""A route per layout, and under it one per study only some of its documents report;
|
||||
two named alike are told apart by what marks them."""
|
||||
routed = [*found, *(k for k in kinds if k.marker)]
|
||||
named, seen = Counter(x.label.casefold() for x in routed), Counter()
|
||||
for x in routed:
|
||||
if named[x.label.casefold()] > 1:
|
||||
seen[x.label.casefold()] += 1
|
||||
said = x.marker[:40] + ("…" if len(x.marker) > 40 else "")
|
||||
x.label += (
|
||||
f" {seen[x.label.casefold()]}" if x.marker.startswith(LOOSE) else f" · {said}"
|
||||
)
|
||||
for layout in found:
|
||||
layout.route = d.add(Route(id=d.id(layout.label), label=layout.label, inputs=[read.id],
|
||||
when=[Condition(**condition(layout.marker))])) # fmt: skip
|
||||
layout.everyone = [r for r in documents if marks(layout.marker, r["text"])]
|
||||
for kind in kinds:
|
||||
kind.route, kind.everyone = kind.layout.route, kind.layout.everyone
|
||||
if kind.marker:
|
||||
kind.route = d.add(Route(id=d.id(kind.label), label=kind.label,
|
||||
inputs=[kind.layout.route.id],
|
||||
when=[Condition(**condition(kind.marker))])) # fmt: skip
|
||||
kind.everyone = [r for r in kind.everyone if marks(kind.marker, r["text"])]
|
||||
|
||||
|
||||
def study(d, kind: Kind, kinds: list[Kind], log) -> str:
|
||||
"""The extract node of a kind's study; on a join with the kind that pairs with it when,
|
||||
reading both, the model takes a field the study requires from the other document (an
|
||||
outsourced report's sample date is the order's, not the report's own date)."""
|
||||
shown = diverse(kind.members, PER_STUDY)
|
||||
read = reading(kind.entity, [(r["text"], r) for r in shown])
|
||||
texts = [r["text"] for r in kind.everyone]
|
||||
if found := joins.partner(kind, kinds):
|
||||
other, column = found
|
||||
node = Join(
|
||||
id=d.id(f"{kind.route.id}_con_{other.route.id}"),
|
||||
label=f"{kind.label} con {other.label}",
|
||||
inputs=[kind.route.id, other.route.id],
|
||||
on=[(column, column)],
|
||||
how="left",
|
||||
)
|
||||
paired = [(t, r) for t, r in joins.joined(node, kind.members, other)
|
||||
if joins.apart_from(r, other)] # fmt: skip
|
||||
pairs = spread(paired, PER_STUDY) or joins.joined(node, shown, other)
|
||||
again = reading(kind.entity, pairs)
|
||||
if taken := joins.taken(kind.entity, again, [r for _, r in pairs], other):
|
||||
log(f"{kind.label}: read with {other.label} (same {column}): {taken} is in it")
|
||||
d.add(node)
|
||||
texts = [t for t, _ in joins.joined(node, kind.everyone, other)]
|
||||
return extract(d, node, kind.route.id, kind.entity, joins.text_columns(other),
|
||||
again, texts) # fmt: skip
|
||||
log(f"{kind.label}: pairs with {other.label} (same {column}), needs nothing of it")
|
||||
return extract(d, kind.route, kind.route.id, kind.entity, "text", read, texts)
|
||||
|
||||
|
||||
def reading(entity: str, shown: list[tuple[str, dict]]) -> list[tuple[str, dict, dict]]:
|
||||
"""What the model reads of `entity` in each text, only what the text says: (text,
|
||||
values, the text each was read from)."""
|
||||
out = []
|
||||
for text, row in shown:
|
||||
try:
|
||||
answered = ground(graph.answer(entity, text, "", graph.images(row)), text)
|
||||
except llm.Unreadable: # nothing read from this one
|
||||
answered = []
|
||||
values, quotes, _ = answered[0] if answered else ({}, {}, [])
|
||||
kept = {f: v for f, v in values.items() if v is not None}
|
||||
out.append((text, kept, {f: quotes[f] for f in kept}))
|
||||
return out
|
||||
|
||||
|
||||
def extract(d, source, name: str, entity: str, column, read, texts: list[str]) -> str:
|
||||
"""An extract node of `entity` on `source`'s rows: the model's reading of a few of them
|
||||
gives each field's pattern (and the site's codes), kept if it checks out."""
|
||||
patterns, formats = fields.rules(entity, [(t, v) for t, v, _ in read], d.codes)
|
||||
for field, pattern in patterns.items():
|
||||
if fields.coded(entity, field):
|
||||
raws = set()
|
||||
for text in texts:
|
||||
if found := re.search(pattern, text, re.IGNORECASE):
|
||||
raws.add(" ".join(found.group(1).split()))
|
||||
d.codes.ask(entity, field, raws)
|
||||
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
||||
node = Extract(id=d.id(f"{entity}_{name}"), label=f"{title} ({source.label})",
|
||||
inputs=[source.id], column=column, entity=entity, method="auto",
|
||||
patterns=patterns, formats=formats,
|
||||
concept_map=d.codes.for_node(entity, patterns)) # fmt: skip
|
||||
return d.add(node).id
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Where each field is written, checked against the documents: the model proposes a pattern
|
||||
per field from a few documents and the values it read there; a pattern is kept only when
|
||||
it captures those very values (through its date format and the site's codes). And the
|
||||
site's codes in platform terms, gathered into one ConceptMap."""
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
|
||||
from core import catalog, concept_map
|
||||
from core.drafting import CODES, PATTERNS, codes_schema, is_date, patterns_schema
|
||||
from core.pipeline import Extract, convert
|
||||
from core.schema import ENTITIES
|
||||
from persistance import llm
|
||||
|
||||
DATE_FORMATS = ("%d/%m/%Y", "%Y-%m-%d", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d", "%m/%d/%Y")
|
||||
MANY_CODES = 200 # distinct values of a coded column asked about at most
|
||||
|
||||
|
||||
def _plain(value) -> str:
|
||||
return " ".join(str(value).split()).casefold()
|
||||
|
||||
|
||||
def _same(got, want) -> bool:
|
||||
"""A captured value, converted, is the value the model read (dates, numbers, text)."""
|
||||
got = got.isoformat() if hasattr(got, "isoformat") else got
|
||||
try:
|
||||
return float(got) == float(want)
|
||||
except (TypeError, ValueError):
|
||||
return _plain(got) == _plain(want)
|
||||
|
||||
|
||||
def _code(value) -> str:
|
||||
"""A model's value as a code: booleans as the platform's yes/no codes."""
|
||||
return str(value).lower() if isinstance(value, bool) else str(value)
|
||||
|
||||
|
||||
def target(entity: str, field: str) -> tuple[str | None, set[str] | None]:
|
||||
"""The system a field of this study takes codes from (None: not coded) and its allowed
|
||||
codes (None: any of the system's)."""
|
||||
if entity == "identity":
|
||||
return (concept_map.GENDER, {"female", "male"}) if field == "sex" else (None, set())
|
||||
found = catalog.studies()[entity].fields[field]
|
||||
if found.type == "boolean":
|
||||
return concept_map.BOOLEAN, {"true", "false"}
|
||||
if found.type == "code":
|
||||
return catalog.systems()[found.system].url, set(found.codes) or None
|
||||
return None, set()
|
||||
|
||||
|
||||
def coded(entity: str, field: str) -> bool:
|
||||
return target(entity, field)[0] is not None
|
||||
|
||||
|
||||
class Codes:
|
||||
"""The site's codes found so far: (study, field) -> site value (case ignored) ->
|
||||
platform code."""
|
||||
|
||||
def __init__(self, map_id: str):
|
||||
self.map_id, self.found = map_id, {}
|
||||
|
||||
def known(self, entity: str, field: str, raw: str) -> bool:
|
||||
allowed = target(entity, field)[1]
|
||||
mapped = self.found.get((entity, field), {})
|
||||
return raw.casefold() in mapped or (allowed is not None and raw in allowed)
|
||||
|
||||
def add(self, entity: str, field: str, raw: str, code: str) -> None:
|
||||
if not raw.strip():
|
||||
return # nothing written is no code
|
||||
self.found.setdefault((entity, field), {})[raw.casefold()] = code
|
||||
|
||||
def table(self) -> dict[tuple[str, str], dict[str, str]]:
|
||||
return self.found
|
||||
|
||||
def ask(self, entity: str, field: str, raws: set[str]) -> None:
|
||||
"""What the platform code is of each value the site writes for `field` that isn't
|
||||
one already."""
|
||||
new = sorted(r for r in raws if r and not self.known(entity, field, r))[:MANY_CODES]
|
||||
if not new:
|
||||
return
|
||||
allowed = target(entity, field)[1]
|
||||
title = ENTITIES[entity].model_fields[field].title or field
|
||||
system = CODES.format(title=title, codes=", ".join(sorted(allowed)) if allowed else "any")
|
||||
try:
|
||||
answer = llm.ask(system, "\n".join(new), codes_schema(new, sorted(allowed or ())))
|
||||
except llm.Unreadable: # left uncoded: the run holds them for a reviewer
|
||||
return
|
||||
for item in answer["codes"]:
|
||||
if item["code"] is not None and (allowed is None or item["code"] in allowed):
|
||||
self.add(entity, field, item["raw"], item["code"])
|
||||
|
||||
def for_node(self, entity: str, fields) -> str | None:
|
||||
return self.map_id if any((entity, f) in self.found for f in fields) else None
|
||||
|
||||
def concept_map(self) -> ConceptMap | None:
|
||||
"""One group per platform system the codes go to; None when there are none."""
|
||||
groups: dict[str, list] = {}
|
||||
for (entity, field), codes in self.found.items():
|
||||
system = target(entity, field)[0]
|
||||
for raw, code in sorted(codes.items()):
|
||||
element = {"code": raw, "target": [{"code": code, "equivalence": "equivalent"}]}
|
||||
if element not in groups.setdefault(system, []):
|
||||
groups[system].append(element)
|
||||
if not groups:
|
||||
return None
|
||||
found = ConceptMap.model_validate({
|
||||
"resourceType": "ConceptMap", "status": "active", "id": self.map_id.replace("_", "-"),
|
||||
"title": f"{self.map_id}: los códigos del sitio, como los leyó Automático",
|
||||
"group": [{"source": f"urn:isssteleon:site:{self.map_id}", "target": t, "element": e}
|
||||
for t, e in groups.items()],
|
||||
}) # fmt: skip
|
||||
if problems := concept_map.problems(found):
|
||||
raise ValueError(f"drafted codes refused: {problems}")
|
||||
return found
|
||||
|
||||
|
||||
def rules(entity: str, read: list[tuple[str, dict]], codes: Codes) -> tuple[dict, dict]:
|
||||
"""Patterns and date formats for the fields the model read in these documents (text,
|
||||
values): one per field, kept only if it captures every value read."""
|
||||
fields = sorted({f for _, values in read for f in values})
|
||||
if not fields:
|
||||
return {}, {}
|
||||
shown = "\n\n---\n\n".join(
|
||||
f"{text}\n\nVALUES: " + "; ".join(f"{f} = {v}" for f, v in values.items())
|
||||
for text, values in read
|
||||
)
|
||||
try:
|
||||
proposed = llm.ask(PATTERNS, shown, patterns_schema(fields))
|
||||
except llm.Unreadable: # no patterns: these fields are read by the model alone
|
||||
return {}, {}
|
||||
patterns, formats = {}, {}
|
||||
for field in fields:
|
||||
rule = proposed.get(field) or {}
|
||||
fmt = rule.get("format") if is_date(entity, field) else None
|
||||
if checks(entity, field, rule.get("pattern") or "", fmt, read, codes):
|
||||
patterns[field] = rule["pattern"]
|
||||
if fmt:
|
||||
formats[field] = fmt
|
||||
return patterns, formats
|
||||
|
||||
|
||||
def checks(entity, field, pattern, fmt, read, codes: Codes) -> bool:
|
||||
try:
|
||||
if re.compile(pattern, re.IGNORECASE).groups != 1:
|
||||
return False
|
||||
except re.error:
|
||||
return False
|
||||
probe = Extract(id="probe", column="text", entity=entity, formats={field: fmt} if fmt else {})
|
||||
pairs = {}
|
||||
for text, values in read:
|
||||
if field not in values:
|
||||
continue
|
||||
found = re.search(pattern, text, re.IGNORECASE)
|
||||
if not found or not (found.group(1) or "").strip():
|
||||
return False # where the model read a value, the pattern takes text
|
||||
raw, want = " ".join(found.group(1).split()), values[field]
|
||||
if coded(entity, field):
|
||||
pairs.setdefault(raw.casefold(), set()).add(_code(want))
|
||||
elif not _same(convert(probe, field, raw, {}), want):
|
||||
return False
|
||||
if any(len(v) > 1 for v in pairs.values()):
|
||||
return False # one written value, two meanings: the pattern takes the wrong text
|
||||
for raw, (code,) in pairs.items():
|
||||
if raw != code.casefold():
|
||||
codes.add(entity, field, raw, code)
|
||||
return True
|
||||
|
||||
|
||||
def date_format(values: list) -> str | None:
|
||||
"""The strptime format every written date of a column parses with (None: they are
|
||||
dates already, or none fits)."""
|
||||
written = [v.strip() for v in values if isinstance(v, str) and v.strip()]
|
||||
for fmt in DATE_FORMATS:
|
||||
if written and all(_parses(v, fmt) for v in written):
|
||||
return fmt
|
||||
return None
|
||||
|
||||
|
||||
def _parses(value: str, fmt: str) -> bool:
|
||||
try:
|
||||
datetime.strptime(value, fmt)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,99 @@
|
||||
"""A kind of document that leaves a date its study requires to another (an outsourced
|
||||
lab's report leaves the sample's date to the order it answers) is read together with
|
||||
it: the kind of the same source a column both carry pairs each of its documents with, one
|
||||
to one. The pairing is kept only if the model, reading both, takes such a field from the
|
||||
other document."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from core.pipeline import Join, Route, grounded, join
|
||||
from core.schema import ENTITIES
|
||||
from models.graph import FILE, READ_COLUMNS
|
||||
|
||||
PAIRED = 0.5 # share of a kind's documents that must find exactly one partner
|
||||
|
||||
|
||||
@dataclass
|
||||
class Kind:
|
||||
"""Documents of a layout that report one study (all of the layout's, or those `marker`
|
||||
sets apart): their route, those sampled, all of them."""
|
||||
|
||||
entity: str
|
||||
label: str
|
||||
marker: str
|
||||
members: list[dict] # those sampled
|
||||
everyone: list[dict] = field(default_factory=list)
|
||||
route: Route | None = None
|
||||
layout: object = None # the layout these documents are of (documents.Layout)
|
||||
|
||||
|
||||
def required(entity: str) -> set[str]:
|
||||
return {f for f, info in ENTITIES[entity].model_fields.items() if info.is_required()}
|
||||
|
||||
|
||||
def _keys(row: dict) -> dict:
|
||||
"""The columns of a row that may pair it: the source's own, never its text or file."""
|
||||
return {
|
||||
c: v
|
||||
for c, v in row.items()
|
||||
if not c.startswith("_") and c not in READ_COLUMNS and c != FILE
|
||||
and isinstance(v, str | int) and v != ""
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def partner(kind: Kind, kinds: list[Kind]) -> tuple[Kind, str] | None:
|
||||
"""The other kind and the column that pair most of this kind's documents with exactly
|
||||
one document each (never with themselves); None if none pairs half."""
|
||||
best = None
|
||||
for other in kinds:
|
||||
if other is kind or not kind.everyone:
|
||||
continue
|
||||
index: dict[tuple[str, object], set] = {}
|
||||
for row in other.everyone:
|
||||
for c, v in _keys(row).items():
|
||||
index.setdefault((c, v), set()).add(row["_record"])
|
||||
paired: dict[str, int] = {}
|
||||
for row in kind.everyone:
|
||||
for c, v in _keys(row).items():
|
||||
if len(index.get((c, v), set()) - {row["_record"]}) == 1:
|
||||
paired[c] = paired.get(c, 0) + 1
|
||||
for c, n in paired.items():
|
||||
share = n / len(kind.everyone)
|
||||
if share >= PAIRED and (best is None or share > best[0]):
|
||||
best = (share, other, c)
|
||||
return (best[1], best[2]) if best else None
|
||||
|
||||
|
||||
def joined(node: Join, rows: list[dict], other: Kind) -> list[tuple[str, dict]]:
|
||||
"""Each row with its partner's text before its own, as the extract node will read it."""
|
||||
columns = text_columns(other)
|
||||
return [("\n".join(str(r[c]) for c in columns if r.get(c)), r)
|
||||
for r in join(node, rows, other.everyone, other.route.id)] # fmt: skip
|
||||
|
||||
|
||||
def apart_from(row: dict, other: Kind) -> bool:
|
||||
"""A joined row whose partner is another document (a file holding both the order and
|
||||
the report pairs with itself: it needs no join)."""
|
||||
return row.get(f"_record__{other.route.id}") not in (None, row["_record"])
|
||||
|
||||
|
||||
def taken(entity: str, read, rows: list[dict], other: Kind) -> set[str]:
|
||||
"""Fields the study requires that the model, reading a document with its partner, took
|
||||
from the partner's text (not its own) in most of the documents that have one."""
|
||||
theirs_column = text_columns(other)[0]
|
||||
partnered = [(quotes, row) for (_, _, quotes), row in zip(read, rows, strict=True)
|
||||
if row.get(theirs_column) and apart_from(row, other)] # fmt: skip
|
||||
found = set()
|
||||
for name in required(entity):
|
||||
theirs = sum(
|
||||
name in quotes and grounded(quotes[name], row[theirs_column])
|
||||
and not grounded(quotes[name], row["text"])
|
||||
for quotes, row in partnered
|
||||
) # fmt: skip
|
||||
if partnered and theirs * 2 > len(partnered):
|
||||
found.add(name)
|
||||
return found
|
||||
|
||||
|
||||
def text_columns(other: Kind) -> list[str]:
|
||||
return [f"text__{other.route.id}", "text"]
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Documents told apart by their layout (the words a form prints), the documents of a
|
||||
layout the model is shown (as unlike each other as they come, so a rare kind of note is
|
||||
among them), and the phrases that mark documents (what a route tests)."""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from collections import Counter
|
||||
|
||||
import numpy as np
|
||||
from sklearn.cluster import AgglomerativeClustering
|
||||
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
|
||||
|
||||
DISTANCE = 0.5 # cosine distance under which two documents share a layout
|
||||
COVERED = 0.9 # share of a layout's documents its marker must be found in
|
||||
WORDS = r"(?u)\b[^\W\d_]{3,}\b" # words, never numbers: a layout, not its values
|
||||
LINE = re.compile(r"^(?=.*[^\W\d_]{4})[^\d]{8,}$") # a printed label: words, no values
|
||||
LOOSE = "(?i)" # a marker written as a pattern (op `matches`), not a phrase (`contains`)
|
||||
ACCENTED = {"a": "aá", "e": "eé", "i": "ií", "o": "oó", "u": "uúü", "n": "nñ"}
|
||||
GAP = r"\W+(?:[^\W_]+\W+){0,2}?" # up to two words the model left out (DERECHA)
|
||||
|
||||
|
||||
def layouts(texts: list[str]) -> list[int]:
|
||||
"""A layout number per document: documents that print mostly the same words (a form's
|
||||
labels) share one. Words seen in a single document (a name) don't count."""
|
||||
if len(texts) < 2:
|
||||
return [0] * len(texts)
|
||||
try:
|
||||
words = CountVectorizer(token_pattern=WORDS, binary=True, min_df=2).fit_transform(texts)
|
||||
except ValueError: # no word in two documents: nothing to tell them apart by
|
||||
return [0] * len(texts)
|
||||
found = [-1] * len(texts)
|
||||
worded = [i for i in range(len(texts)) if words[i].nnz]
|
||||
if len(worded) < 2:
|
||||
return [0 if i in worded else -1 for i in range(len(texts))]
|
||||
groups = AgglomerativeClustering(
|
||||
n_clusters=None, metric="cosine", linkage="average", distance_threshold=DISTANCE
|
||||
).fit_predict(words[worded].toarray())
|
||||
for i, group in zip(worded, groups, strict=True):
|
||||
found[i] = int(group)
|
||||
return found
|
||||
|
||||
|
||||
def diverse(rows: list[dict], n: int) -> list[dict]:
|
||||
"""`n` of a layout's documents, each the least like those already taken (the first, the
|
||||
most typical): what sets a few documents apart (an organ, a death) is among them."""
|
||||
if len(rows) <= n:
|
||||
return rows
|
||||
try:
|
||||
x = TfidfVectorizer(token_pattern=WORDS).fit_transform([r["text"] for r in rows])
|
||||
except ValueError:
|
||||
return spread(rows, n)
|
||||
alike = (x @ x.T).toarray()
|
||||
taken = [int(alike.sum(axis=1).argmax())]
|
||||
nearest = alike[taken[0]].copy()
|
||||
while len(taken) < n:
|
||||
nearest[taken] = np.inf
|
||||
taken.append(int(nearest.argmin()))
|
||||
nearest = np.maximum(nearest, alike[taken[-1]])
|
||||
return [rows[i] for i in sorted(taken)]
|
||||
|
||||
|
||||
def spread(items: list, n: int) -> list:
|
||||
"""`n` items from first to last."""
|
||||
if len(items) <= n:
|
||||
return items
|
||||
return [items[round(i * (len(items) - 1) / (n - 1))] for i in range(n)]
|
||||
|
||||
|
||||
def marks(marker: str, text: str) -> bool:
|
||||
"""As the route will test it (core.pipeline.matches: `contains`, or `matches`)."""
|
||||
if marker.startswith(LOOSE):
|
||||
return re.search(marker, text) is not None
|
||||
return marker.casefold() in text.casefold()
|
||||
|
||||
|
||||
def condition(marker: str) -> dict:
|
||||
"""The route condition that tests a marker."""
|
||||
return {"column": "text", "op": "matches" if marker.startswith(LOOSE) else "contains",
|
||||
"value": marker} # fmt: skip
|
||||
|
||||
|
||||
def loose(phrase: str | None, least: int = 2) -> str | None:
|
||||
"""A phrase the model wrote as a pattern its document may write a little apart: its
|
||||
words in order, accents either way, up to two words between them ("MAMA, BIOPSIA"
|
||||
finds "MAMA DERECHA, BIOPSIA:")."""
|
||||
words = re.findall(r"[^\W_]+", phrase or "")
|
||||
if len(words) < least:
|
||||
return None
|
||||
|
||||
def letter(c: str) -> str:
|
||||
bare = unicodedata.normalize("NFD", c.casefold())[0]
|
||||
return f"[{ACCENTED[bare]}]" if bare in ACCENTED else re.escape(c)
|
||||
|
||||
return LOOSE + r"\b" + GAP.join("".join(letter(c) for c in w) for w in words) + r"\b"
|
||||
|
||||
|
||||
def phrase(marker: str | None, members, others, share=COVERED) -> str | None:
|
||||
"""The model's marker as written if it holds, else written loosely if that holds."""
|
||||
for found in (marker, loose(marker)):
|
||||
if found and holds(found, members, others, share):
|
||||
return found
|
||||
return None
|
||||
|
||||
|
||||
def kinds_of(line: str, documents: list[dict]) -> int:
|
||||
"""How many different lines these documents print under this line's label (`ÓRGANO:
|
||||
MAMA` → the organs): few for what tells studies apart, many for a diagnosis."""
|
||||
label = line.split(":", 1)[0].strip().casefold() if ":" in line else None
|
||||
if label is None:
|
||||
return 2 # a line some print and others don't
|
||||
return len({x.strip().casefold() for r in documents for x in r["text"].splitlines()
|
||||
if x.strip().casefold().startswith(label + ":")}) # fmt: skip
|
||||
|
||||
|
||||
def holds(marker: str | None, members: list[dict], others: list[dict], share=COVERED) -> bool:
|
||||
"""A marker found in (nearly) all of these documents and in none of the others."""
|
||||
if not marker or len(marker) < 4:
|
||||
return False
|
||||
covered = sum(marks(marker, r["text"]) for r in members) / len(members)
|
||||
return covered >= share and not any(marks(marker, r["text"]) for r in others)
|
||||
|
||||
|
||||
def printed_line(members: list[dict], others: list[dict], share=COVERED, rank=None) -> str | None:
|
||||
"""The wordiest line printed in (nearly) all of these documents and in none of the
|
||||
others (a form's label): the marker when the model's isn't (a title the printer
|
||||
overstrikes reads "DDDDEEEE" in the text layer, so the title the model sees is not
|
||||
in the text)."""
|
||||
counts = Counter(
|
||||
line for r in members for line in {x.strip() for x in r["text"].splitlines()}
|
||||
if LINE.match(line)
|
||||
) # fmt: skip
|
||||
candidates = [line for line, n in counts.items() if n / len(members) >= share]
|
||||
readable = lambda line: (len(re.findall(WORDS, line)), len(line)) # noqa: E731
|
||||
for line in sorted(candidates, key=rank or readable, reverse=True):
|
||||
if holds(line, members, others, share):
|
||||
return line
|
||||
return None
|
||||
|
||||
|
||||
def bare(word: str) -> str:
|
||||
return "".join(c for c in unicodedata.normalize("NFD", word.casefold()) if c.isalpha())
|
||||
|
||||
|
||||
def shared_words(members: list[dict], others: list[dict], first="", layout=(), most=3, only=False):
|
||||
"""The fewest words, in order, all of these documents write and none of the others,
|
||||
accents and case aside (a breast biopsy writes MAMA, whichever side): when no line
|
||||
marks them. Words of `first` (the study's name) are tried before the others (`only`:
|
||||
those alone); a word only one of the `layout`'s documents writes (a name) is never one."""
|
||||
words = re.findall(r"[^\W\d_]+", members[0]["text"])
|
||||
preferred = {bare(w) for w in re.findall(r"[^\W\d_]+", first)}
|
||||
written = Counter(w for r in layout or [*members, *others]
|
||||
for w in {bare(x) for x in re.findall(r"[^\W\d_]+", r["text"])}) # fmt: skip
|
||||
for n in range(1, most + 1):
|
||||
grams = [words[i : i + n] for i in range(len(words) - n + 1)]
|
||||
grams = [g for g in grams if sum(map(len, g)) >= 4 and all(written[bare(w)] > 1 for w in g)]
|
||||
grams.sort(key=lambda g: not all(bare(w) in preferred for w in g)) # stable
|
||||
grams = [g for g in grams if not only or all(bare(w) in preferred for w in g)]
|
||||
for gram in grams:
|
||||
if holds(found := loose(" ".join(gram), least=1), members, others, 1.0):
|
||||
return found
|
||||
return None
|
||||
@@ -0,0 +1,60 @@
|
||||
"""A table (columns, no files): the model says which column holds each fact about whom a
|
||||
row is about and each field of the studies its rows report; dates get the format all of
|
||||
a column's values parse with, and coded columns their values in platform terms."""
|
||||
|
||||
import json
|
||||
|
||||
from core.drafting import TABLE, is_date, studies_text, table_schema
|
||||
from core.pipeline import ENTITY_TITLES, Map, Source
|
||||
from core.schema import ENTITIES
|
||||
from models.draft import fields
|
||||
from persistance import llm
|
||||
|
||||
SHOWN = 15 # rows the model sees
|
||||
SCANNED = 2000 # rows whose values give the date formats and the codes
|
||||
LONG = 80 # characters of a value shown
|
||||
|
||||
|
||||
def _shown(value):
|
||||
text = value if isinstance(value, str) else json.dumps(value, default=str)
|
||||
return text[:LONG]
|
||||
|
||||
|
||||
def draft(d, source: Source, rows: list[dict], log) -> None:
|
||||
"""One map node for identity and one per study the table reports."""
|
||||
columns = sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")})
|
||||
if not columns:
|
||||
return
|
||||
shown = "\n".join(json.dumps({c: _shown(r.get(c)) for c in columns}, ensure_ascii=False)
|
||||
for r in rows[:SHOWN]) # fmt: skip
|
||||
try:
|
||||
answer = llm.ask(TABLE.format(studies=studies_text()), f"{columns}\n{shown}",
|
||||
table_schema(columns)) # fmt: skip
|
||||
except llm.Unreadable as e: # left undrawn: a person maps it
|
||||
log(f"{source.id} left out, the model's answer: {e}")
|
||||
return
|
||||
wanted = [("identity", answer["identity"])]
|
||||
wanted += [(s["entity"], s["fields"]) for s in answer["studies"]]
|
||||
for entity, held in wanted:
|
||||
mapped = {h["field"]: h["column"] for h in held
|
||||
if h["field"] in ENTITIES[entity].model_fields} # fmt: skip
|
||||
if not mapped:
|
||||
continue
|
||||
node = mapping(d, source, entity, mapped, rows[:SCANNED])
|
||||
(d.identity if entity == "identity" else d.studies.setdefault(entity, [])).append(node)
|
||||
log(f"{source.id}: {entity} from {sorted(mapped.values())}")
|
||||
|
||||
|
||||
def mapping(d, source: Source, entity: str, mapped: dict[str, str], rows: list[dict]) -> str:
|
||||
formats = {}
|
||||
for field, column in mapped.items():
|
||||
values = [r.get(column) for r in rows]
|
||||
if is_date(entity, field) and (fmt := fields.date_format(values)):
|
||||
formats[field] = fmt
|
||||
elif fields.coded(entity, field):
|
||||
d.codes.ask(entity, field, {str(v).strip() for v in values if v not in (None, "")})
|
||||
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
||||
node = Map(id=d.id(f"{source.id}_{entity}"), label=f"{title} ({source.label or source.id})",
|
||||
inputs=[source.id], fields=mapped, formats=formats,
|
||||
concept_map=d.codes.for_node(entity, mapped)) # fmt: skip
|
||||
return d.add(node).id
|
||||
@@ -1,404 +0,0 @@
|
||||
"""The one way a heavy op spreads work over cores or machines: `map(fn, items)` returns the
|
||||
results in input order whatever the mode (in this process, on local worker processes, on a
|
||||
remote Dask scheduler). While it runs, a monitor thread reports progress: a JSON run tag the
|
||||
API reads at once (Dagster shows op metadata only when the op returns, so the tag is the live
|
||||
channel) and one throttled log line per tenth of the work. Ops never touch Dask themselves.
|
||||
|
||||
`with running(context, execution):` makes a Dagster op's context the ambient one, so that
|
||||
`map` calls inside the block report on that run, share one cluster, and leave a summary in the
|
||||
op's output metadata."""
|
||||
|
||||
import contextvars
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from datetime import UTC, datetime
|
||||
from itertools import islice
|
||||
|
||||
import dagster as dg
|
||||
import psutil
|
||||
|
||||
from persistance import cluster
|
||||
from persistance.cluster import (
|
||||
PROGRESS_TAG,
|
||||
ClusterVersionError,
|
||||
Execution,
|
||||
ExecutionError,
|
||||
Health,
|
||||
Options,
|
||||
Progress,
|
||||
Resolved,
|
||||
Tasks,
|
||||
Worker,
|
||||
health,
|
||||
options,
|
||||
resolve,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ClusterVersionError",
|
||||
"Execution",
|
||||
"ExecutionError",
|
||||
"Health",
|
||||
"Options",
|
||||
"Progress",
|
||||
"Resolved",
|
||||
"health",
|
||||
"map",
|
||||
"options",
|
||||
"resolve",
|
||||
"running",
|
||||
]
|
||||
|
||||
SAMPLE_S = 2.0
|
||||
_SINGLE_THREAD = {
|
||||
"OMP_NUM_THREADS": "1",
|
||||
"OPENBLAS_NUM_THREADS": "1",
|
||||
"MKL_NUM_THREADS": "1",
|
||||
}
|
||||
|
||||
|
||||
class Eta:
|
||||
"""Seconds left, from an exponentially smoothed rate of items per second."""
|
||||
|
||||
def __init__(self, alpha: float = 0.3, min_done: int = 3):
|
||||
self.alpha, self.min_done = alpha, min_done
|
||||
self.rate: float | None = None
|
||||
self._last: tuple[float, int] | None = None
|
||||
|
||||
def update(self, elapsed_s: float, done: int) -> None:
|
||||
last, self._last = self._last, (elapsed_s, done)
|
||||
if last is None or elapsed_s <= last[0]:
|
||||
return
|
||||
rate = (done - last[1]) / (elapsed_s - last[0])
|
||||
self.rate = rate if self.rate is None else self.alpha * rate + (1 - self.alpha) * self.rate
|
||||
|
||||
def eta_s(self, total: int) -> float | None:
|
||||
done = self._last[1] if self._last else 0
|
||||
if done < self.min_done or not self.rate or self.rate <= 0:
|
||||
return None
|
||||
return max(0, total - done) / self.rate
|
||||
|
||||
|
||||
class _Ambient:
|
||||
"""What `running` shares with the `map` calls in its block."""
|
||||
|
||||
def __init__(self, context, execution: Execution | None):
|
||||
self.context, self.execution = context, execution
|
||||
self.client = None
|
||||
self.cluster = None
|
||||
self.phases: list[dict] = []
|
||||
self.peak_cpu_pct = 0.0
|
||||
self.peak_memory_bytes = 0
|
||||
|
||||
def close(self) -> None:
|
||||
_close(self.client, self.cluster)
|
||||
self.client = self.cluster = None
|
||||
|
||||
|
||||
_ambient: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
|
||||
"execution_ambient", default=None
|
||||
)
|
||||
|
||||
|
||||
def _close(client, local_cluster) -> None:
|
||||
"""Close what this module opened; a remote scheduler is only disconnected from."""
|
||||
for closable in (client, local_cluster):
|
||||
if closable is not None:
|
||||
try:
|
||||
closable.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _counts(dask_scheduler) -> dict:
|
||||
"""Run on the scheduler: how many tasks are in each state."""
|
||||
counts: dict = {}
|
||||
for task in dask_scheduler.tasks.values():
|
||||
counts[task.state] = counts.get(task.state, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def _connect(resolved: Resolved, workers: int | None):
|
||||
"""A client on the chosen Dask cluster and the local cluster it started, if any."""
|
||||
from distributed import Client, LocalCluster
|
||||
|
||||
if resolved.mode == "local":
|
||||
local = LocalCluster(
|
||||
n_workers=cluster.local_workers(workers),
|
||||
threads_per_worker=1,
|
||||
processes=True,
|
||||
memory_limit=cluster.memory_per_worker(),
|
||||
dashboard_address=None,
|
||||
env=_SINGLE_THREAD,
|
||||
)
|
||||
try:
|
||||
return Client(local), local
|
||||
except BaseException:
|
||||
_close(None, local)
|
||||
raise
|
||||
try:
|
||||
client = Client(resolved.scheduler, timeout=10)
|
||||
except Exception as e:
|
||||
raise ExecutionError(f"cannot reach the Dask scheduler {resolved.scheduler}: {e}") from e
|
||||
detail = cluster.versions_error(client)
|
||||
if detail is not None:
|
||||
_close(client, None)
|
||||
raise ClusterVersionError(
|
||||
f"Dask workers differ from this server: {detail}. "
|
||||
"Rebuild the worker image from the same commit."
|
||||
)
|
||||
return client, None
|
||||
|
||||
|
||||
class _Monitor:
|
||||
"""Samples one `map` every `SAMPLE_S` seconds and reports it."""
|
||||
|
||||
def __init__(self, ambient, resolved, phase, total, log, client):
|
||||
self.ambient, self.resolved, self.phase = ambient, resolved, phase
|
||||
self.total, self.log, self.client = total, log, client
|
||||
self.done = 0
|
||||
self.started = time.monotonic()
|
||||
self.eta = Eta()
|
||||
self.tasks: Tasks | None = None
|
||||
self.last_tenth = 0
|
||||
self.peak_cpu = 0.0
|
||||
self.peak_memory = 0
|
||||
self._lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||||
self._process = psutil.Process()
|
||||
|
||||
def item_done(self) -> None:
|
||||
with self._lock:
|
||||
self.done += 1
|
||||
|
||||
def start(self) -> None:
|
||||
self.report(force_log=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self, *, final: bool) -> None:
|
||||
self._stop.set()
|
||||
self._thread.join()
|
||||
if final:
|
||||
self.report(force_log=True)
|
||||
|
||||
def _loop(self) -> None:
|
||||
while not self._stop.wait(SAMPLE_S):
|
||||
self.report()
|
||||
|
||||
def _cluster_state(self) -> list[Worker]:
|
||||
if self.client is None:
|
||||
cpu = self._process.cpu_percent()
|
||||
self.peak_cpu = max(self.peak_cpu, cpu)
|
||||
self.peak_memory = max(self.peak_memory, self._process.memory_info().rss)
|
||||
return []
|
||||
workers = []
|
||||
try:
|
||||
info = self.client.scheduler_info()["workers"]
|
||||
for w in info.values():
|
||||
m = w.get("metrics", {})
|
||||
workers.append(
|
||||
Worker(
|
||||
name=str(w.get("name", "")),
|
||||
cpu_pct=float(m.get("cpu", 0.0)),
|
||||
memory_bytes=int(m.get("memory", 0)),
|
||||
memory_limit=w.get("memory_limit"),
|
||||
executing=int(m.get("executing", 0)),
|
||||
threads=int(w.get("nthreads", 1)),
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
return []
|
||||
try:
|
||||
counts = self.client.run_on_scheduler(_counts)
|
||||
self.tasks = Tasks(**{k: counts.get(k, 0) for k in Tasks.model_fields})
|
||||
except Exception:
|
||||
pass # a failed sample keeps the previous one
|
||||
self.peak_cpu = max(self.peak_cpu, sum(w.cpu_pct for w in workers))
|
||||
self.peak_memory = max(self.peak_memory, sum(w.memory_bytes for w in workers))
|
||||
return workers
|
||||
|
||||
def report(self, *, force_log: bool = False) -> None:
|
||||
workers = self._cluster_state()
|
||||
with self._lock:
|
||||
done = self.done
|
||||
elapsed = time.monotonic() - self.started
|
||||
self.eta.update(elapsed, done)
|
||||
progress = Progress(
|
||||
phase=self.phase,
|
||||
done=done,
|
||||
total=self.total,
|
||||
elapsed_s=round(elapsed, 1),
|
||||
eta_s=self.eta.eta_s(self.total),
|
||||
mode=self.resolved.mode,
|
||||
scheduler=self.resolved.scheduler,
|
||||
workers=workers,
|
||||
tasks=self.tasks,
|
||||
updated_at=datetime.now(UTC).isoformat(timespec="seconds"),
|
||||
)
|
||||
tenth = done * 10 // self.total
|
||||
if force_log or tenth > self.last_tenth:
|
||||
self.last_tenth = tenth
|
||||
self.log(f"{self.phase}: {done}/{self.total}")
|
||||
context = self.ambient.context if self.ambient else None
|
||||
if context is not None:
|
||||
context.instance.add_run_tags(
|
||||
context.run_id, {PROGRESS_TAG: progress.model_dump_json()}
|
||||
)
|
||||
|
||||
|
||||
def _default_log(ambient) -> Callable[[str], None]:
|
||||
return ambient.context.log.info if ambient and ambient.context else print
|
||||
|
||||
|
||||
def _run_sync(fn, iterator, monitor, on_error):
|
||||
results = []
|
||||
for item in iterator:
|
||||
try:
|
||||
results.append(fn(item))
|
||||
except Exception as e:
|
||||
if on_error is None:
|
||||
raise
|
||||
results.append(on_error(item, e))
|
||||
monitor.item_done()
|
||||
return results
|
||||
|
||||
|
||||
def _run_dask(fn, iterator, client, monitor, on_error):
|
||||
from distributed import as_completed
|
||||
|
||||
threads = sum(w["nthreads"] for w in client.scheduler_info()["workers"].values()) or 1
|
||||
limit = max(4, 2 * threads)
|
||||
results: dict[int, object] = {}
|
||||
pending: dict = {} # future -> (index, item)
|
||||
completed = as_completed([])
|
||||
numbered = enumerate(iterator)
|
||||
try:
|
||||
while True:
|
||||
for index, item in islice(numbered, max(0, limit - len(pending))):
|
||||
future = client.submit(fn, item, pure=False, retries=1)
|
||||
pending[future] = (index, item)
|
||||
completed.add(future)
|
||||
if not pending:
|
||||
break
|
||||
future = next(completed)
|
||||
index, item = pending.pop(future)
|
||||
try:
|
||||
results[index] = future.result()
|
||||
except Exception as e:
|
||||
if on_error is None:
|
||||
raise
|
||||
results[index] = on_error(item, e)
|
||||
monitor.item_done()
|
||||
except BaseException:
|
||||
try:
|
||||
client.cancel(list(pending), force=True)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return [results[i] for i in range(len(results))]
|
||||
|
||||
|
||||
def map[T, R]( # noqa: A001 - the module's public name, as in `execution.map`
|
||||
fn: Callable[[T], R],
|
||||
items: Iterable[T],
|
||||
*,
|
||||
execution: Execution | None = None,
|
||||
log: Callable[[str], None] | None = None,
|
||||
phase: str = "working",
|
||||
total: int | None = None,
|
||||
workers: int | None = None,
|
||||
on_error: Callable[[T, Exception], R] | None = None,
|
||||
) -> list[R]:
|
||||
"""Apply `fn` to every item and return the results in input order.
|
||||
|
||||
`fn` is a module-level function of one item returning something picklable, and must give
|
||||
the same result for the same item: then every mode returns equal lists. `items` may be a
|
||||
lazy generator; at most `max(4, 2 * threads)` items are loaded and unfinished at once.
|
||||
`total` is needed only when `items` has no length. `phase` is the lowercase code the
|
||||
WebApp shows. `workers` overrides the local worker count (a cluster shared inside
|
||||
`running` keeps the count it started with). A failed item takes `on_error(item, error)`
|
||||
as its result, or, without it, the error propagates after the rest is cancelled."""
|
||||
ambient = _ambient.get()
|
||||
if execution is None and ambient is not None:
|
||||
execution = ambient.execution
|
||||
resolved = resolve(execution)
|
||||
log = log or _default_log(ambient)
|
||||
if total is None:
|
||||
try:
|
||||
total = len(items) # type: ignore[arg-type]
|
||||
except TypeError:
|
||||
raise ValueError("total is needed when items has no length") from None
|
||||
iterator = iter(items)
|
||||
if total == 0:
|
||||
return []
|
||||
monitor = None
|
||||
client, local = (ambient.client, None) if ambient else (None, None)
|
||||
opened_here = False
|
||||
ok = False
|
||||
try:
|
||||
if resolved.mode != "sync" and client is None:
|
||||
client, local = _connect(resolved, workers)
|
||||
if ambient is not None:
|
||||
ambient.client, ambient.cluster = client, local
|
||||
else:
|
||||
opened_here = True
|
||||
monitor = _Monitor(ambient, resolved, phase, total, log, client)
|
||||
monitor.start()
|
||||
if resolved.mode == "sync":
|
||||
results = _run_sync(fn, iterator, monitor, on_error)
|
||||
else:
|
||||
results = _run_dask(fn, iterator, client, monitor, on_error)
|
||||
ok = True
|
||||
return results
|
||||
finally:
|
||||
if monitor is not None:
|
||||
monitor.stop(final=ok)
|
||||
if ambient is not None:
|
||||
ambient.phases.append(
|
||||
{
|
||||
"phase": phase,
|
||||
"done": monitor.done,
|
||||
"total": total,
|
||||
"elapsed_s": round(time.monotonic() - monitor.started, 1),
|
||||
}
|
||||
)
|
||||
ambient.peak_cpu_pct = max(ambient.peak_cpu_pct, monitor.peak_cpu)
|
||||
ambient.peak_memory_bytes = max(ambient.peak_memory_bytes, monitor.peak_memory)
|
||||
if opened_here:
|
||||
_close(client, local)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def running(context: dg.OpExecutionContext, execution: Execution | None = None) -> Iterator[None]:
|
||||
"""Make `context` and `execution` the ambient ones for the `map` calls in the block; on
|
||||
exit close the shared cluster and leave the run's figures in the op's output metadata."""
|
||||
ambient = _Ambient(context, execution)
|
||||
token = _ambient.set(ambient)
|
||||
failed = True
|
||||
try:
|
||||
yield
|
||||
failed = False
|
||||
finally:
|
||||
_ambient.reset(token)
|
||||
ambient.close()
|
||||
try:
|
||||
resolved = resolve(execution)
|
||||
context.add_output_metadata(
|
||||
{
|
||||
"mode": dg.MetadataValue.text(resolved.mode),
|
||||
"scheduler": (
|
||||
dg.MetadataValue.text(resolved.scheduler)
|
||||
if resolved.scheduler
|
||||
else dg.MetadataValue.null()
|
||||
),
|
||||
"phases": dg.MetadataValue.json(ambient.phases),
|
||||
"peak_cpu_pct": dg.MetadataValue.float(ambient.peak_cpu_pct),
|
||||
"peak_memory_bytes": dg.MetadataValue.int(ambient.peak_memory_bytes),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
if not failed:
|
||||
raise
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Risk factors of an outcome, shared by CaMa recurrence and the interval survival models.
|
||||
|
||||
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
|
||||
most frequent category by up to four criteria: (1) its adjusted odds ratio's 95 % CI excludes
|
||||
1 and its Benjamini-Hochberg p < ALPHA; (2) its covariate enters the bootstrap LRs at least
|
||||
FREQ_MIN of the time; (3) its covariate is in the outcome's Markov blanket in the HBN; (4) its
|
||||
Kaplan-Meier survival at the horizon differs from the reference's (95 % CI) in the odds ratio's
|
||||
direction. A criterion the model cannot evaluate is left out. "Robusto" needs (1) and three
|
||||
criteria (all of them when fewer than three are evaluated), "sugerente" two. Treatments get
|
||||
their odds ratios, adjusted for the intrinsic covariates, but no class: they are associations,
|
||||
not effects. Each clinical scenario then lists the classified factors nearly all of its
|
||||
patients have (definitorios) or most have (mayoritarios)."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from scipy.stats import false_discovery_control
|
||||
|
||||
from models.curves import life_table
|
||||
|
||||
ALPHA = 0.05
|
||||
FREQ_MIN = 0.80
|
||||
Z = 1.96
|
||||
CRITERIA = ("c1_or", "c2_estabilidad", "c3_manta_markov", "c4_supervivencia")
|
||||
ORDER = {
|
||||
"riesgo robusto": 0,
|
||||
"protector robusto": 1,
|
||||
"riesgo sugerente": 2,
|
||||
"protector sugerente": 3,
|
||||
"no concluyente": 4,
|
||||
}
|
||||
UNKNOWN_CLASS = "no aplica (categoria desconocida)"
|
||||
# Scenario presence: the share of the scenario's patients in the category.
|
||||
DEFINING, MAJORITY, PRESENT = 0.95, 0.50, 0.10
|
||||
DESCRIBING = ("definitoria", "mayoritaria")
|
||||
|
||||
|
||||
def variable_of(term: str, covariates: list[str]) -> str:
|
||||
"""The covariate a dummy belongs to (the longest name it starts with)."""
|
||||
found = [c for c in covariates if term.startswith(c + "_")]
|
||||
return max(found, key=len) if found else term
|
||||
|
||||
|
||||
def km_at(months, event, horizon) -> tuple[float, float]:
|
||||
"""Kaplan-Meier survival at the end of month `horizon`, and its Greenwood SE."""
|
||||
d, _, n = life_table(months, event)
|
||||
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
|
||||
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
|
||||
last = min(horizon, len(d) - 1) + 1
|
||||
S = float(np.prod(q[:last]))
|
||||
return S, S * float(np.sqrt(np.sum(v[:last])))
|
||||
|
||||
|
||||
def odds_ratios(data: pd.DataFrame, y, variables, reference, name: str) -> pd.DataFrame:
|
||||
"""Logistic GLM on every category but each covariate's reference (constant and
|
||||
duplicated dummies dropped): odds ratios (column `name`) with Wald 95 % CI and p."""
|
||||
X = pd.get_dummies(data[variables]).astype(float)
|
||||
X = X.drop(columns=[f"{v}_{reference[v]}" for v in variables])
|
||||
X = X.loc[:, X.nunique() > 1]
|
||||
X = X.loc[:, ~X.T.duplicated()]
|
||||
m = sm.GLM(y, sm.add_constant(X), family=sm.families.Binomial()).fit()
|
||||
ci = np.exp(m.conf_int().loc[X.columns])
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"termino": X.columns,
|
||||
name: np.exp(m.params[X.columns].to_numpy()),
|
||||
"IC95_inf": ci[0].to_numpy(),
|
||||
"IC95_sup": ci[1].to_numpy(),
|
||||
"p": m.pvalues[X.columns].to_numpy(),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def complete(table: pd.DataFrame, variables, reference: dict, everyone: pd.DataFrame,
|
||||
months, event, horizon: int, names: tuple[str, str, str]) -> pd.DataFrame: # fmt: skip
|
||||
"""Each term's covariate, category, BH p and Kaplan-Meier difference to its reference at
|
||||
`horizon` over `everyone` (`names`: the category's, the reference's and the difference's
|
||||
survival columns)."""
|
||||
table = table.reset_index(drop=True)
|
||||
table["variable"] = [variable_of(x, variables) for x in table["termino"]]
|
||||
table["categoria"] = [
|
||||
x[len(v) + 1 :] for x, v in zip(table["termino"], table["variable"], strict=True)
|
||||
]
|
||||
table["referencia"] = table["variable"].map(reference)
|
||||
table["p_ajustado_BH"] = false_discovery_control(table["p"]) if len(table) else []
|
||||
category, ref, delta_name = names
|
||||
rows = []
|
||||
for v, cat, r in zip(table["variable"], table["categoria"], table["referencia"], strict=True):
|
||||
a, b = (everyone[v] == cat).to_numpy(), (everyone[v] == r).to_numpy()
|
||||
sa, ea = km_at(months[a], event[a], horizon)
|
||||
sb, eb = km_at(months[b], event[b], horizon)
|
||||
delta, se = sa - sb, np.sqrt(ea**2 + eb**2)
|
||||
rows.append({
|
||||
"n_categoria": int(a.sum()), category: sa, ref: sb, delta_name: delta,
|
||||
"delta_IC95_inf": delta - Z * se, "delta_IC95_sup": delta + Z * se,
|
||||
}) # fmt: skip
|
||||
return pd.concat([table, pd.DataFrame(rows, columns=["n_categoria", category, ref, delta_name,
|
||||
"delta_IC95_inf", "delta_IC95_sup"])],
|
||||
axis=1) # fmt: skip
|
||||
|
||||
|
||||
def classify(tab: pd.DataFrame, or_name: str, delta_name: str, unknown: str,
|
||||
evaluated: tuple[str, ...] = CRITERIA) -> pd.DataFrame: # fmt: skip
|
||||
"""c1 and c4 from the table, then each category's class; c2 and c3 must already be set
|
||||
for the criteria `evaluated`."""
|
||||
risk = tab[or_name] > 1
|
||||
tab["direccion"] = np.where(risk, "riesgo", "protector")
|
||||
tab["c1_or"] = ((tab["IC95_inf"] > 1) | (tab["IC95_sup"] < 1)) & (tab["p_ajustado_BH"] < ALPHA)
|
||||
excludes_zero = (tab["delta_IC95_sup"] < 0) | (tab["delta_IC95_inf"] > 0)
|
||||
tab["c4_supervivencia"] = excludes_zero & (np.sign(tab[delta_name]) == np.where(risk, -1, 1))
|
||||
tab["criterios_cumplidos"] = tab[list(evaluated)].astype(bool).sum(axis=1)
|
||||
robust = min(3, len(evaluated))
|
||||
tab["clasificacion"] = [
|
||||
UNKNOWN_CLASS
|
||||
if cat == unknown
|
||||
else f"{d} robusto"
|
||||
if c1 and k >= robust
|
||||
else f"{d} sugerente"
|
||||
if k >= 2
|
||||
else "no concluyente"
|
||||
for cat, d, c1, k in zip(
|
||||
tab["categoria"],
|
||||
tab["direccion"],
|
||||
tab["c1_or"],
|
||||
tab["criterios_cumplidos"],
|
||||
strict=True,
|
||||
)
|
||||
]
|
||||
return tab
|
||||
|
||||
|
||||
def presence(share: float) -> str:
|
||||
if share >= DEFINING:
|
||||
return "definitoria"
|
||||
return "mayoritaria" if share >= MAJORITY else "presente" if share >= PRESENT else "minoritaria"
|
||||
|
||||
|
||||
def listing(part: pd.DataFrame) -> str:
|
||||
"""`variable=category (strength, share)`, `;`-separated; a treatment's strength is
|
||||
`asociacion`."""
|
||||
strength = np.where(part["tipo_efecto"] == "tratamiento", "asociacion",
|
||||
part["clasificacion"].str.split().str[-1]) # fmt: skip
|
||||
return "; ".join(
|
||||
f"{v}={c} ({s}, {p:.0%})"
|
||||
for v, c, s, p in zip(
|
||||
part["variable"], part["categoria"], strength, part["share"], strict=True
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def classified(factors: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The factors a scenario can list (classified ones and treatments), with `tipo_efecto`:
|
||||
riesgo, protector or tratamiento."""
|
||||
found = factors[factors["clasificacion"].str.contains("robusto|sugerente|tratamiento")]
|
||||
kind = np.where(
|
||||
found["tipo"] == "tratamiento", "tratamiento", found["clasificacion"].str.split().str[0]
|
||||
)
|
||||
return found.assign(tipo_efecto=kind)
|
||||
|
||||
|
||||
def scenario_row(frame: pd.DataFrame, mask: np.ndarray, found: pd.DataFrame) -> dict:
|
||||
"""What one scenario's patients (`mask` over `frame`) have of the `classified` factors:
|
||||
the listings by kind and presence, and how many risk factors describe it."""
|
||||
share = [
|
||||
float((frame.loc[mask, v] == c).mean())
|
||||
for v, c in zip(found["variable"], found["categoria"], strict=True)
|
||||
]
|
||||
detail = found.assign(share=share, presence=[presence(s) for s in share])
|
||||
row = {}
|
||||
for k in ("riesgo", "protector", "tratamiento"):
|
||||
for level, label in (("definitoria", "definitorios"), ("mayoritaria", "mayoritarios")):
|
||||
row[f"{k}_{label}"] = listing(
|
||||
detail[(detail["tipo_efecto"] == k) & (detail["presence"] == level)]
|
||||
)
|
||||
included = (detail["tipo_efecto"] == "riesgo") & detail["presence"].isin(DESCRIBING)
|
||||
row["n_factores_riesgo_incluidos"] = int(included.sum())
|
||||
row["incluye_factor_riesgo"] = row["n_factores_riesgo_incluidos"] > 0
|
||||
return row
|
||||
+179
-80
@@ -1,27 +1,28 @@
|
||||
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
||||
places what the targets staged into silver."""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import unicodedata
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from functools import cache
|
||||
|
||||
import duckdb
|
||||
import ocrmypdf
|
||||
import pandas as pd
|
||||
import pdfplumber
|
||||
import pikepdf
|
||||
import splink.comparison_library as cl
|
||||
from markitdown import MarkItDown
|
||||
from openai import OpenAI, OpenAIError
|
||||
from splink import Linker, SettingsCreator, block_on
|
||||
from splink.backends.duckdb import DuckDBAPI
|
||||
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||
|
||||
from core import catalog, concept_map, fhir_in
|
||||
from core.drafting import extract_prompt
|
||||
from core.pipeline import (
|
||||
FIELD_EVIDENCE,
|
||||
HELD,
|
||||
IDENTIFIERS,
|
||||
QUOTES,
|
||||
@@ -43,14 +44,31 @@ from core.pipeline import (
|
||||
matches,
|
||||
validate,
|
||||
)
|
||||
from persistance import config_log, files, nodes, silver
|
||||
from models import suggest
|
||||
from persistance import config_log, files, llm, nodes, silver
|
||||
|
||||
MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer
|
||||
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
|
||||
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
|
||||
FILE = "_file" # the read file's key (persistance.files): its pages, for a model that sees
|
||||
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
||||
"text": {"data_type": "text", "nullable": True},
|
||||
"ocr": {"data_type": "bool"},
|
||||
"error": {"data_type": "text", "nullable": True},
|
||||
"format": {"data_type": "text", "nullable": True},
|
||||
}
|
||||
ROW_COLUMNS = {**READ_COLUMNS, FILE: {"data_type": "text", "nullable": True}}
|
||||
|
||||
|
||||
def file_format(content: bytes) -> str:
|
||||
"""What kind of file this is, from its first bytes, so a route can tell a PDF from an
|
||||
EEG recording in the same column: pdf, edf (EDF and EDF+: a fixed ASCII header whose
|
||||
version is "0"), or other (whatever MarkItDown reads)."""
|
||||
if content.startswith(b"%PDF"):
|
||||
return "pdf"
|
||||
head = content[:256]
|
||||
if len(head) == 256 and head[:8] == b"0 " and head[184:192].strip().isdigit():
|
||||
return "edf"
|
||||
return "other"
|
||||
|
||||
|
||||
@cache
|
||||
@@ -64,52 +82,94 @@ def _lines(text: str) -> str:
|
||||
|
||||
|
||||
def _text(content: bytes) -> str:
|
||||
"""PDFs through pdfplumber's layout mode, which keeps a table's rows on one line each
|
||||
(spacing within a line collapsed); every other format through MarkItDown."""
|
||||
if content.startswith(b"%PDF"):
|
||||
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
||||
return _lines("\n".join(page.extract_text(layout=True) or "" for page in pdf.pages))
|
||||
"""Files other than PDFs, through MarkItDown."""
|
||||
return _reader().convert_stream(io.BytesIO(content)).text_content
|
||||
|
||||
|
||||
def _pdf_pages(content: bytes) -> list[str]:
|
||||
"""Each page's text layer, through pdfplumber's layout mode, which keeps a table's rows
|
||||
on one line each (spacing within a line collapsed)."""
|
||||
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
||||
return [_lines(page.extract_text(layout=True) or "") for page in pdf.pages]
|
||||
|
||||
|
||||
def _ocr_pages(content: bytes, numbers: list[int]) -> list[str]:
|
||||
"""Tesseract's text (OCRmyPDF's sidecar, from the deskewed page) of these pages only,
|
||||
copied into a PDF of their own: a typed page keeps its own text layer."""
|
||||
source, scans = pikepdf.open(io.BytesIO(content)), pikepdf.new()
|
||||
for n in numbers:
|
||||
scans.pages.append(source.pages[n])
|
||||
pages, sidecar = io.BytesIO(), io.BytesIO()
|
||||
scans.save(pages)
|
||||
pages.seek(0)
|
||||
ocrmypdf.ocr(
|
||||
pages, io.BytesIO(), language="spa", force_ocr=True, output_type="pdf", optimize=0,
|
||||
progress_bar=False, jobs=1, deskew=True, sidecar=sidecar,
|
||||
) # fmt: skip
|
||||
found = sidecar.getvalue().decode().split("\f")
|
||||
return [_lines(found[i]) if i < len(found) else "" for i in range(len(numbers))]
|
||||
|
||||
|
||||
def read_file(content: bytes) -> dict:
|
||||
"""Text of one file, and whether OCR was needed. An unreadable file keeps its error."""
|
||||
"""Text of one file, its format, and whether OCR was needed. An unreadable file keeps
|
||||
its error; a signal recording (EDF) has no text to read."""
|
||||
kind = file_format(content)
|
||||
if kind == "edf":
|
||||
return {"text": None, "ocr": False, "error": None, "format": kind}
|
||||
return {**_read_text(content), "format": kind}
|
||||
|
||||
|
||||
def _read_text(content: bytes) -> dict:
|
||||
"""The file's text; a PDF page by page, OCR only on the pages without a text layer (a
|
||||
typed form whose second page is a scan, say)."""
|
||||
try:
|
||||
found = _text(content)
|
||||
ocr = content.startswith(b"%PDF") and len(found.split()) < MIN_WORDS
|
||||
if ocr: # Tesseract's own text (OCRmyPDF's sidecar), from the deskewed page
|
||||
text = io.BytesIO()
|
||||
ocrmypdf.ocr(
|
||||
io.BytesIO(content), io.BytesIO(), language="spa", skip_text=True,
|
||||
output_type="pdf", optimize=0, progress_bar=False, jobs=1, deskew=True,
|
||||
sidecar=text,
|
||||
) # fmt: skip
|
||||
found = _lines(text.getvalue().decode())
|
||||
return {"text": found, "ocr": ocr, "error": None}
|
||||
if not content.startswith(b"%PDF"):
|
||||
return {"text": _text(content), "ocr": False, "error": None}
|
||||
pages = _pdf_pages(content)
|
||||
scanned = [i for i, page in enumerate(pages) if len(page.split()) < MIN_WORDS]
|
||||
if scanned:
|
||||
for i, page in zip(scanned, _ocr_pages(content, scanned), strict=True):
|
||||
pages[i] = page
|
||||
return {"text": "\n".join(p for p in pages if p), "ocr": bool(scanned), "error": None}
|
||||
except Exception as e: # noqa: BLE001 - an unreadable file is recorded, not fatal
|
||||
return {"text": None, "ocr": False, "error": f"{type(e).__name__}: {e}"}
|
||||
|
||||
|
||||
def run_read(p: str, node: Read):
|
||||
"""The input's rows with the file column replaced by its text; each file read once."""
|
||||
"""The input's rows with their file's text and format beside the file column (which
|
||||
keeps the file, for a study that takes the file itself: an EEG's recording); each file
|
||||
read once."""
|
||||
rows = list(nodes.rows(p, node.inputs[0]))
|
||||
for row in rows: # the source kept the file; the row carries its hash
|
||||
row["key"] = row.pop(node.column) or None
|
||||
row["key"] = row.get(node.column) or None
|
||||
keys = {r["key"] for r in rows} - {None}
|
||||
found = nodes.cached("read_cache", keys)
|
||||
new = {k: files.content(k) for k in keys - set(found)}
|
||||
with ProcessPoolExecutor() as pool:
|
||||
read = dict(zip(new, pool.map(read_file, new.values()), strict=True))
|
||||
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()], READ_COLUMNS)
|
||||
found |= read
|
||||
legacy = [k for k, r in found.items() if r.get("format") is None] # read before formats
|
||||
for k in legacy:
|
||||
found[k]["format"] = file_format(files.content(k) or b"")
|
||||
nodes.remember("read_cache", [{"key": k, **{c: found[k][c] for c in READ_COLUMNS}}
|
||||
for k in legacy], READ_COLUMNS) # fmt: skip
|
||||
new = sorted(keys - set(found))
|
||||
with ProcessPoolExecutor() as pool: # a batch of files in memory at a time, each kept
|
||||
for start in range(0, len(new), READ_BATCH):
|
||||
batch = new[start : start + READ_BATCH]
|
||||
read = dict(zip(batch, pool.map(read_file, (files.content(k) for k in batch)),
|
||||
strict=True)) # fmt: skip
|
||||
nodes.remember("read_cache", [{"key": k, **r} for k, r in read.items()],
|
||||
READ_COLUMNS) # fmt: skip
|
||||
found |= read
|
||||
for row in rows:
|
||||
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
||||
row[FILE] = row.pop("key")
|
||||
result = found.get(row[FILE], {"text": None, "ocr": False, "error": "empty"})
|
||||
row |= {k: result[k] for k in READ_COLUMNS}
|
||||
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||
return nodes.write(p, node.id, rows, ROW_COLUMNS)
|
||||
|
||||
|
||||
def run_route(p: str, node: Route):
|
||||
return nodes.write(p, node.id, [r for r in nodes.rows(p, node.inputs[0]) if matches(node, r)])
|
||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||
"""The input's rows the route takes; an `otherwise` route, those `others` don't."""
|
||||
rows = nodes.rows(p, node.inputs[0])
|
||||
taken = [r for r in rows if matches(node, r) and not any(matches(o, r) for o in others)]
|
||||
return nodes.write(p, node.id, taken)
|
||||
|
||||
|
||||
def _codes(node: Map | Extract, fields) -> dict[str, dict[str, str]]:
|
||||
@@ -127,14 +187,12 @@ def run_map(p: str, node: Map):
|
||||
|
||||
|
||||
def run_fhir(p: str, node: Fhir):
|
||||
"""Each Bundle's rows of the node's entity; a resource sent again is its latest."""
|
||||
"""The node's entity from every Bundle at its source, as one: a resource sent again is
|
||||
its latest, and one Bundle may name what another sent."""
|
||||
maps = [config_log.concept_map(node.concept_map)] if node.concept_map else []
|
||||
found: dict[str, dict] = {}
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
bundle = json.loads(row[node.column])
|
||||
for r in fhir_in.rows(bundle, node.entity, p, maps):
|
||||
found[r[RECORD]] = r
|
||||
return nodes.write(p, node.id, list(found.values()))
|
||||
sent = sorted(nodes.rows(p, node.inputs[0]), key=lambda r: str(r.get("received_at") or ""))
|
||||
bundle = fhir_in.combined(json.loads(row[node.column]) for row in sent)
|
||||
return nodes.write(p, node.id, fhir_in.rows(bundle, node.entity, p, maps))
|
||||
|
||||
|
||||
def run_join(p: str, node: Join):
|
||||
@@ -142,57 +200,50 @@ def run_join(p: str, node: Join):
|
||||
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
||||
|
||||
|
||||
@cache
|
||||
def _llm() -> tuple[OpenAI, str] | None:
|
||||
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
|
||||
if not (url := os.environ.get("LLM_URL")):
|
||||
return None
|
||||
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
|
||||
try:
|
||||
client.models.list()
|
||||
except OpenAIError:
|
||||
return None
|
||||
return client, os.environ["LLM_MODEL"]
|
||||
def page_images(content: bytes, pages: int = 2) -> list[bytes]:
|
||||
"""The first pages of a PDF as PNG pictures, for a model that reads images (a scan's
|
||||
OCR text misses what the picture still shows)."""
|
||||
out = []
|
||||
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
||||
for page in pdf.pages[:pages]:
|
||||
picture = io.BytesIO()
|
||||
page.to_image(resolution=110).original.save(picture, format="PNG")
|
||||
out.append(picture.getvalue())
|
||||
return out
|
||||
|
||||
|
||||
PROMPT = (
|
||||
"Extract every {entity} record stated in the document. For each field give its value "
|
||||
"in the schema's terms and `quote`: the exact text of the document it was read from, "
|
||||
"copied character by character. Leave out fields the document does not state.{hints}"
|
||||
)
|
||||
def images(row: dict) -> list[bytes]:
|
||||
"""A scanned document's pages as pictures, when the model reads them."""
|
||||
if not (row.get("ocr") and row.get(FILE) and llm.vision()):
|
||||
return []
|
||||
content = files.content(row[FILE])
|
||||
return page_images(content) if content and file_format(content) == "pdf" else []
|
||||
|
||||
|
||||
def _ask_llm(node: Extract, text: str) -> dict:
|
||||
client, model = _llm()
|
||||
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
|
||||
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
|
||||
if found := nodes.cached("llm_cache", {key}):
|
||||
return json.loads(found[key]["answer"])
|
||||
reply = client.chat.completions.create(
|
||||
model=model, temperature=0, seed=7,
|
||||
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
||||
response_format={"type": "json_schema", "json_schema": {
|
||||
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
|
||||
) # fmt: skip
|
||||
answer = reply.choices[0].message.content
|
||||
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
||||
return json.loads(answer)
|
||||
def answer(entity: str, text: str, hints: str = "", pictures: list[bytes] = ()) -> dict:
|
||||
"""The model's records of `entity` in `text`, each value with the text it was read
|
||||
from (the same question for the same document is asked once)."""
|
||||
return llm.ask(extract_prompt(entity, hints), text, answer_schema(entity), pictures)
|
||||
|
||||
|
||||
def run_extract(p: str, node: Extract):
|
||||
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
|
||||
use_llm = node.method == "llm" or (node.method == "auto" and llm.available())
|
||||
codes = _codes(node, node.patterns)
|
||||
out = []
|
||||
for row in nodes.rows(p, node.inputs[0]):
|
||||
text = node.text(row)
|
||||
if use_llm:
|
||||
found = ground(_ask_llm(node, text), text)
|
||||
try:
|
||||
found = ground(answer(node.entity, text, node.hints, images(row)), text)
|
||||
except llm.Unreadable as e: # this document waits for a reviewer, not the run
|
||||
found = [({}, {}, [f"the model's answer could not be read: {e}"])]
|
||||
elif node.patterns:
|
||||
found = apply_patterns(node, text, codes)
|
||||
else:
|
||||
found = [({}, {}, ["no LLM answering and no patterns set"])]
|
||||
taken = {f: row[c] for f, c in node.columns.items() if row.get(c) is not None}
|
||||
for index, (values, quotes, held) in enumerate(found or [({}, {}, ["nothing found"])]):
|
||||
out.append({**values, RECORD: row[RECORD], "_index": index,
|
||||
out.append({**values, **taken, RECORD: row[RECORD], "_index": index,
|
||||
QUOTES: json.dumps(quotes, ensure_ascii=False),
|
||||
HELD: json.dumps(held) if held else None}) # fmt: skip
|
||||
return nodes.write(p, node.id, out)
|
||||
@@ -256,6 +307,28 @@ def _identities(p: str, node: Link) -> tuple[pd.DataFrame, dict[str, str], dict[
|
||||
return frame[["unique_id", *present]], sources, written
|
||||
|
||||
|
||||
def _distinct(records: pd.DataFrame, rules: list[str], judged: set[str]) -> pd.Series:
|
||||
"""Each record's stand-in: one record per identity that the rules join to itself (a
|
||||
patient's 24 reports carrying one record number are one row to compare, not 24² pairs).
|
||||
A record a reviewer judged stands for itself, and so does one the rules would not join
|
||||
to an identical record (nothing compared was read, say)."""
|
||||
fields = [c for c in records.columns if c != "unique_id"]
|
||||
key = records[fields].astype(object).where(records[fields].notna(), None)
|
||||
same = pd.Series(list(key.itertuples(index=False, name=None)), index=records.index)
|
||||
stand_in = records.groupby(same, sort=False)["unique_id"].transform("first")
|
||||
stand_in = stand_in.where(~records["unique_id"].isin(judged), records["unique_id"])
|
||||
joined = set()
|
||||
if rules:
|
||||
con = duckdb.connect()
|
||||
con.register("candidates", records[records["unique_id"].isin(set(stand_in))])
|
||||
joins = " or ".join(f"({r})" for r in rules)
|
||||
joined = set(con.sql(
|
||||
f"select l.unique_id from candidates l join candidates r"
|
||||
f" on l.unique_id = r.unique_id where {joins}"
|
||||
).df()["unique_id"]) # fmt: skip
|
||||
return stand_in.where(stand_in.isin(joined), records["unique_id"])
|
||||
|
||||
|
||||
def _persons(records: pd.DataFrame, edges: pd.DataFrame, db: DuckDBAPI) -> pd.DataFrame:
|
||||
clusters = cluster_pairwise_predictions_at_threshold(
|
||||
records[["unique_id"]], edges, db, "unique_id", "unique_id_l", "unique_id_r"
|
||||
@@ -274,22 +347,25 @@ def run_link(p: str, node: Link):
|
||||
rules = [r for r in node.rules or node.default_rules()
|
||||
if all(f"l.{f}" not in r or f in fields for f in node.fields)] # fmt: skip
|
||||
comparisons = [_comparison(f) for f in fields]
|
||||
decided = nodes.person_decisions()
|
||||
stand_in = _distinct(records, rules, set().union(*decided))
|
||||
distinct = records[records["unique_id"].isin(set(stand_in))]
|
||||
db = DuckDBAPI()
|
||||
linker = Linker(
|
||||
db.register(records),
|
||||
db.register(distinct),
|
||||
SettingsCreator(link_type="dedupe_only", comparisons=comparisons,
|
||||
blocking_rules_to_generate_predictions=rules),
|
||||
log_level=None,
|
||||
) # fmt: skip
|
||||
decided = nodes.person_decisions()
|
||||
sure = linker.inference.deterministic_link().as_pandas_dataframe()
|
||||
pairs = {frozenset(e) for e in zip(sure.unique_id_l, sure.unique_id_r, strict=True)}
|
||||
pairs = {e for e in pairs if decided.get(e, True)} | {e for e, same in decided.items() if same}
|
||||
known = set(records.unique_id)
|
||||
known = set(distinct.unique_id)
|
||||
edges = pd.DataFrame(
|
||||
[sorted(e) for e in pairs if e <= known], columns=["unique_id_l", "unique_id_r"]
|
||||
)
|
||||
persons = _persons(records, edges, db)
|
||||
cluster = _persons(distinct, edges, db).set_index("unique_id")["cluster_id"]
|
||||
persons = records.assign(cluster_id=stand_in.map(cluster).to_numpy())
|
||||
|
||||
facts = [f for f in ("birth_date", "sex") if f in fields]
|
||||
spread = persons.groupby("cluster_id")[facts].nunique() if facts else pd.DataFrame()
|
||||
@@ -342,6 +418,9 @@ def run_link(p: str, node: Link):
|
||||
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)
|
||||
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
|
||||
for f in ids:
|
||||
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
||||
@@ -356,7 +435,7 @@ def run_link(p: str, node: Link):
|
||||
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
|
||||
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
||||
if frozenset((a, b)) in decided or any(
|
||||
if frozenset((a, b)) in answered or any(
|
||||
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
||||
):
|
||||
return None
|
||||
@@ -392,6 +471,15 @@ def run_link(p: str, node: Link):
|
||||
return nodes.write(p, f"{node.id}__review", queue)
|
||||
|
||||
|
||||
def provenance(study, clean, field, record: str) -> dict:
|
||||
"""Where a value comes from when its source doesn't say: the day of its event, made
|
||||
available with the study's report (its own event's day without one)."""
|
||||
day = getattr(clean, study.events[field.event].date)
|
||||
available = getattr(clean, study.events["report"].date) if "report" in study.events else day
|
||||
return {"source_ref": record, "source_clinical_date": day and str(day),
|
||||
"source_available_at": available and str(available)} # fmt: skip
|
||||
|
||||
|
||||
def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
"""Rows of one study into silver's staging, each given its person by the link node:
|
||||
a clean row becomes one observation per field it has (long), keyed by its study
|
||||
@@ -420,9 +508,11 @@ def run_target(p: str, node: Target, kinds: dict[str, str]):
|
||||
continue
|
||||
clean = model.model_validate(values)
|
||||
instance = json.dumps([str(getattr(clean, k)) for k in model.key])
|
||||
sent = json.loads(row.get(FIELD_EVIDENCE) or "{}")
|
||||
for name, field in study.fields.items():
|
||||
if (value := getattr(clean, name)) is not None:
|
||||
observations.append({**base, "instance": instance, "field": name,
|
||||
source = sent.get(name) or provenance(study, clean, field, row[RECORD])
|
||||
observations.append({**base, **source, "instance": instance, "field": name,
|
||||
catalog.value_column(field): value}) # fmt: skip
|
||||
nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
|
||||
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
|
||||
@@ -439,9 +529,18 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
|
||||
for node in pipeline.order():
|
||||
if node.kind == "target":
|
||||
run_target(pipeline_id, node, kinds)
|
||||
elif node.kind == "route" and node.otherwise:
|
||||
others = [n for n in pipeline.nodes if n.kind == "route" and n.id != node.id
|
||||
and n.inputs == node.inputs and not n.otherwise] # fmt: skip
|
||||
run_route(pipeline_id, node, others)
|
||||
else:
|
||||
RUNNERS[node.kind](pipeline_id, node)
|
||||
log(f"{node.id} ({node.kind}) done")
|
||||
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
||||
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
||||
log(f"silver and gold, from {', '.join(entities)}")
|
||||
links = [n.id for n in pipeline.nodes if n.kind == "link"]
|
||||
if links and llm.available(): # the model's reading beside what waits for reviewers
|
||||
for link in links:
|
||||
suggest.persons(pipeline_id, link)
|
||||
log(f"suggestions for review: {', '.join(links)}")
|
||||
|
||||
+18
-11
@@ -11,6 +11,7 @@ import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
|
||||
from core import models
|
||||
from persistance import gold, registry
|
||||
|
||||
|
||||
@@ -35,14 +36,17 @@ class Jobs:
|
||||
models: dict
|
||||
technical_validation: Callable[..., dict]
|
||||
interpretability: Callable[..., dict]
|
||||
# (spec, as_of) -> who the model's cohort lost and why, kept beside its reports (not one
|
||||
# promotion asks for); None: not kept
|
||||
attrition: Callable[..., dict | None] | None = None
|
||||
|
||||
@property
|
||||
def events(self) -> str:
|
||||
return f"{self.domain}_events"
|
||||
|
||||
def routine(self) -> list[str]:
|
||||
"""The models a train or score run takes when none is named: all but the slow ones."""
|
||||
return [n for n, s in self.models.items() if not getattr(s, "slow", False)]
|
||||
"""The models a run takes when none is named: all but the hidden ones."""
|
||||
return [n for n in self.models if self.registered(n) not in models.HIDDEN]
|
||||
|
||||
def registered(self, name: str) -> str:
|
||||
return f"{self.domain}.{name}"
|
||||
@@ -51,20 +55,25 @@ class Jobs:
|
||||
"""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."""
|
||||
spec, as_of = self.models[name], as_of or date.today()
|
||||
if spec.cohort is None: # trained on reference data: it writes its own reports
|
||||
fitted, metrics, found = spec.train(None, as_of)
|
||||
else:
|
||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||
fitted, metrics, data = spec.train(events, as_of)
|
||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||
if events.empty:
|
||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||
fitted, metrics, found = spec.train(events, as_of)
|
||||
if not getattr(spec, "reports", False): # else trained with its own reports
|
||||
data = found
|
||||
found = {
|
||||
"technical_validation": self.technical_validation(spec, metrics, data),
|
||||
"interpretability": self.interpretability(spec, fitted, data),
|
||||
}
|
||||
if hasattr(fitted, "variance_diagnostics"): # where its intervals can't be had
|
||||
found["variance_diagnostics"] = fitted.variance_diagnostics(
|
||||
data["coded"][spec.features]
|
||||
)
|
||||
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
|
||||
# for its idle workers to time out (5 minutes) before it can end.
|
||||
get_reusable_executor().shutdown(wait=True)
|
||||
if self.attrition and (lost := self.attrition(spec, as_of)) is not None:
|
||||
found["attrition"] = lost
|
||||
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
|
||||
model = Predictor(spec, fitted)
|
||||
return registry.register(self.registered(name), model, params, metrics, found)
|
||||
@@ -72,8 +81,6 @@ class Jobs:
|
||||
def score(self, name: str) -> int | None:
|
||||
"""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."""
|
||||
if self.models[name].cohort is None: # scores no patient
|
||||
return None
|
||||
found = registry.champion(self.registered(name))
|
||||
if found is None:
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""The model's reading of what a link node leaves to reviewers, shown beside each case:
|
||||
whether a person and a possible owner are one patient, and which record of a torn person
|
||||
belongs to someone else, each with its reason. A suggestion decides nothing: reviewers
|
||||
still answer every case (persistance.nodes)."""
|
||||
|
||||
import json
|
||||
|
||||
from core.drafting import SAME_PERSON, TORN, same_person_schema, torn_schema
|
||||
from core.pipeline import HELD, RECORD
|
||||
from persistance import llm, nodes
|
||||
|
||||
PAIRS, TORN_PERSONS = "__suggestions", "__torn_suggestions"
|
||||
|
||||
|
||||
def _side(row: dict, prefix: str) -> dict:
|
||||
return {k.removeprefix(prefix): v for k, v in row.items()
|
||||
if k.startswith(prefix) and v is not None} # fmt: skip
|
||||
|
||||
|
||||
def _ask(system: str, text: str, schema: dict, unsure: dict) -> dict:
|
||||
"""The model's suggestion; an answer it couldn't give says so to the reviewer."""
|
||||
try:
|
||||
return llm.ask(system, text, schema)
|
||||
except llm.Unreadable:
|
||||
return {**unsure, "reason": "El modelo no dio una respuesta legible para este caso."}
|
||||
|
||||
|
||||
def persons(pipeline_id: str, link: str) -> None:
|
||||
"""Suggestions for the link node's queue (pairs) and its torn persons."""
|
||||
pairs = []
|
||||
for row in nodes.rows(pipeline_id, f"{link}__review"):
|
||||
case = {"a": _side(row, "person_"), "b": _side(row, "candidate_"), "why": row["reason"]}
|
||||
text = json.dumps(case, default=str, ensure_ascii=False)
|
||||
answer = _ask(SAME_PERSON, text, same_person_schema(), {"same": None})
|
||||
pairs.append({"person": row["person"], "candidate": row["candidate"],
|
||||
"same": answer["same"], "reason": answer["reason"]}) # fmt: skip
|
||||
nodes.write(pipeline_id, f"{link}{PAIRS}", pairs)
|
||||
torn: dict[str, list[dict]] = {}
|
||||
for row in nodes.rows(pipeline_id, link):
|
||||
if "disagree" in (row.get(HELD) or ""):
|
||||
record = {k: v for k, v in row.items() if not k.startswith("_") and v is not None}
|
||||
torn.setdefault(row["person_id"], []).append({**record, "id": row[RECORD]})
|
||||
found = []
|
||||
for person, records in torn.items():
|
||||
text = json.dumps(records, default=str, ensure_ascii=False)
|
||||
answer = _ask(TORN, text, torn_schema([r["id"] for r in records]), {"record": None})
|
||||
found.append({"person": person, "record": answer["record"], "reason": answer["reason"]})
|
||||
nodes.write(pipeline_id, f"{link}{TORN_PERSONS}", found)
|
||||
+121
-2
@@ -9,6 +9,8 @@ deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missi
|
||||
category of its own (UNKNOWN).
|
||||
"""
|
||||
|
||||
import json
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
from itertools import pairwise
|
||||
|
||||
@@ -220,7 +222,18 @@ class IntervalSurvival(BaseEstimator):
|
||||
# ---------------------------------------------------------------- a model over gold timelines
|
||||
|
||||
TRAIN_FRACTION = 0.7
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high"]
|
||||
|
||||
|
||||
def inputs(members: pd.DataFrame, columns, repeat: int) -> np.ndarray:
|
||||
"""What each member's estimate read (JSON, unknown as null), once per horizon."""
|
||||
rows = members[list(columns)].astype(object).where(members[list(columns)].notna(), None)
|
||||
found = [json.dumps(row, default=str) for row in rows.to_dict("records")]
|
||||
return np.repeat(np.asarray(found, dtype=object), repeat)
|
||||
|
||||
|
||||
OUTPUT = ["person_id", "index_date", "horizon_years", "probability", "ci_low", "ci_high",
|
||||
"scenarios", "input_values"] # fmt: skip
|
||||
SCENARIO_SEPARATOR = " | " # between the names of a member's clinical scenarios
|
||||
|
||||
|
||||
def split(members: pd.DataFrame, train_fraction: float) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
@@ -265,6 +278,8 @@ class Spec:
|
||||
# "in", value) on the members' covariates and `scenario_columns` (kept for them only).
|
||||
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
|
||||
scenario_columns: tuple[str, ...] = ()
|
||||
# Features that are treatments: their odds ratios are reported as associations, unclassified.
|
||||
treatments: tuple[str, ...] = ()
|
||||
|
||||
@property
|
||||
def horizons(self) -> tuple[float, ...]:
|
||||
@@ -324,13 +339,17 @@ class Spec:
|
||||
return model, metrics, {"train": train, "test": test}
|
||||
|
||||
def predict(self, model: IntervalSurvival, events: pd.DataFrame) -> pd.DataFrame:
|
||||
"""One row per member and horizon: her mortality by it, and its interval when kept."""
|
||||
"""One row per member and horizon: her mortality by it, its interval when kept, and
|
||||
the clinical scenarios of the report she falls in (the curves her record draws)."""
|
||||
members = self.members(events)
|
||||
mortality = 1.0 - model.survival(members)
|
||||
n, h = len(members), len(self.horizons)
|
||||
empty = ([np.nan] * h, [np.nan] * h)
|
||||
ends = [model.intervals_.get(tuple(c), empty)
|
||||
for c in self._combinations(members).itertuples(index=False)] # fmt: skip
|
||||
masks = scenario_masks(members, self.scenarios)
|
||||
scenarios = [SCENARIO_SEPARATOR.join(name for name, m in masks.items() if m[i]) or None
|
||||
for i in range(n)] # fmt: skip
|
||||
return pd.DataFrame({
|
||||
"person_id": np.repeat(members["person_id"].to_numpy(), h),
|
||||
"index_date": np.repeat(members["index_date"].dt.date.to_numpy(), h),
|
||||
@@ -338,6 +357,8 @@ class Spec:
|
||||
"probability": mortality.ravel(),
|
||||
"ci_low": np.array([e[0] 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),
|
||||
"input_values": inputs(members, self.features, h),
|
||||
})[OUTPUT] # fmt: skip
|
||||
|
||||
|
||||
@@ -496,4 +517,102 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
||||
"escenarios": scenarios,
|
||||
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
|
||||
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
|
||||
**risk_factor_report(spec, model, members),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- risk factors
|
||||
|
||||
FACTOR_COLUMNS = (
|
||||
"tipo", "variable", "categoria", "referencia", "n_categoria", "OR_muerte", "IC95_inf",
|
||||
"IC95_sup", "p", "p_ajustado_BH", "en_manta_markov", "S_categoria", "S_referencia",
|
||||
"delta_S", "delta_IC95_inf", "delta_IC95_sup", "c1_or", "c3_manta_markov",
|
||||
"c4_supervivencia", "criterios_cumplidos", "clasificacion",
|
||||
) # fmt: skip
|
||||
SURVIVAL_COLUMNS = ("S_categoria", "S_referencia", "delta_S")
|
||||
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||
# The model has no variable selection to resample, so stability (2) is not evaluated.
|
||||
EVALUATED = ("c1_or", "c3_manta_markov", "c4_supervivencia")
|
||||
|
||||
|
||||
def risk_factors(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> pd.DataFrame:
|
||||
"""The members' risk factors of death by the last horizon (`models.factors`, as the
|
||||
SEER-trained original rates them): odds ratios of dying before it, among those dead before
|
||||
it or followed past it; Kaplan-Meier at it over the same members (follow-up cut at
|
||||
`cap_months`); the Markov blanket is the HBN's parents in any interval."""
|
||||
from models import factors as rated
|
||||
|
||||
horizon = spec.borders[-1]
|
||||
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
|
||||
died = event & (months < horizon)
|
||||
known = died | (months >= horizon)
|
||||
data = spec._combinations(members)[known].reset_index(drop=True)
|
||||
y, months, event = died[known].astype(int), months[known], event[known]
|
||||
empty = pd.DataFrame(columns=list(FACTOR_COLUMNS))
|
||||
if len(data) == 0 or y.min() == y.max():
|
||||
return empty
|
||||
features = list(spec.features)
|
||||
treatment = [f for f in features if f in spec.treatments]
|
||||
intrinsic = [f for f in features if f not in spec.treatments]
|
||||
reference = {v: data[v].value_counts().idxmax() for v in features}
|
||||
blanket = {features[j] for _, (parents, _) in model.fitted_ for j in parents}
|
||||
|
||||
def complete(table, variables):
|
||||
return rated.complete(table, variables, reference, data, months, event, horizon,
|
||||
SURVIVAL_COLUMNS) # fmt: skip
|
||||
|
||||
with warnings.catch_warnings(), np.errstate(over="ignore", divide="ignore"):
|
||||
warnings.simplefilter("ignore") # rank-deficient designs, unbounded odds ratios
|
||||
try:
|
||||
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, "OR_muerte"),
|
||||
intrinsic) # fmt: skip
|
||||
except (np.linalg.LinAlgError, ValueError):
|
||||
return empty
|
||||
tab["c2_estabilidad"] = np.nan
|
||||
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(blanket)
|
||||
tab = rated.classify(tab, "OR_muerte", "delta_S", UNKNOWN, EVALUATED)
|
||||
tab["tipo"] = "factor de riesgo"
|
||||
if treatment:
|
||||
both = intrinsic + treatment
|
||||
try:
|
||||
tr = rated.odds_ratios(data, y, both, reference, "OR_muerte")
|
||||
except (np.linalg.LinAlgError, ValueError):
|
||||
tr = None
|
||||
if tr is not None:
|
||||
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
||||
tr = complete(tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)],
|
||||
treatment) # fmt: skip
|
||||
tr["tipo"], tr["clasificacion"] = "tratamiento", TREATMENT_CLASS
|
||||
tab = pd.concat([tab, tr], ignore_index=True)
|
||||
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
||||
tab["_order"] = tab["clasificacion"].map(rated.ORDER).fillna(5)
|
||||
tab = tab.sort_values(["_kind", "_order", "OR_muerte"], ascending=[True, True, False])
|
||||
return tab[list(FACTOR_COLUMNS)].round(4).reset_index(drop=True)
|
||||
|
||||
|
||||
def scenario_factors(spec: Spec, members: pd.DataFrame, table: pd.DataFrame) -> list[dict]:
|
||||
"""Per clinical scenario, the classified factors and treatments nearly all of its
|
||||
members have (definitorios) or most have (mayoritarios)."""
|
||||
from models import factors as rated
|
||||
|
||||
found = rated.classified(table) if len(table) else table
|
||||
data = spec._combinations(members)
|
||||
rows = []
|
||||
for name, mask in scenario_masks(members, spec.scenarios).items():
|
||||
if not mask.any() or found.empty:
|
||||
continue
|
||||
rows.append({
|
||||
"escenario": name, "condiciones": [list(c) for c in spec.scenarios[name]],
|
||||
"n_escenario": int(mask.sum()), **rated.scenario_row(data, mask, found),
|
||||
}) # fmt: skip
|
||||
return rows
|
||||
|
||||
|
||||
def risk_factor_report(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> dict:
|
||||
"""The interpretability report's risk factors: the table and each scenario's summary."""
|
||||
table = risk_factors(spec, model, members)
|
||||
rows = json.loads(table.to_json(orient="records")) # NaN as null, numpy types as JSON
|
||||
return {
|
||||
"factores_riesgo": {"horizonte_meses": spec.borders[-1], "filas": rows},
|
||||
"factores_escenarios": scenario_factors(spec, members, table),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"""The EEG–ADOS-2 association (core.tea.association says what it relates): per biomarker,
|
||||
zone and outcome, how a child's deviation from the age curve (z) goes with an altered
|
||||
ADOS-2 item or a high CSS, adjusted for age and module.
|
||||
|
||||
- An item: Firth's penalised logistic regression of "altered" on z (the principal model),
|
||||
with a cumulative-logit model of the item's level as sensitivity; the CSS, and a composite
|
||||
of items with too few events (by how many are altered), the other way round.
|
||||
- q: Benjamini–Hochberg within each biomarker, exploratory pairs apart.
|
||||
- A child's probability: the principal model at her z (Firth's with the FLIC intercept, so
|
||||
its probabilities average to the observed rate), and the reference child's (z = 0, the
|
||||
cohort's mean age, the commonest module).
|
||||
A child the association was fitted on is scored by the model refitted without her
|
||||
(leave-one-out); spikes enter as present or not over a group of zones (`spikes_any`), and an
|
||||
estimate on fewer than MIN_EVENTS children with (or without) the event is flagged. The
|
||||
models are models.tea.logit's."""
|
||||
|
||||
import hashlib
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from statsmodels.stats.multitest import multipletests
|
||||
|
||||
from core.tea import association as spec
|
||||
from core.tea.reasons import INSUFFICIENT_DATA
|
||||
from models.tea.eeg.spindles import ZONES
|
||||
from models.tea.logit import firth, firth_fit, ordinal, ordinal_fit, probability, rows
|
||||
|
||||
|
||||
def item_scores(frame: pd.DataFrame, number: int) -> pd.Series:
|
||||
"""Item `number`'s algorithm score for each child whose module administers it."""
|
||||
name, modules = spec.ITEMS[number]
|
||||
if name not in frame or "module" not in frame:
|
||||
return pd.Series(np.nan, index=frame.index)
|
||||
v = pd.to_numeric(frame[name], errors="coerce")
|
||||
v = v.where(~v.isin(spec.NOT_APPLICABLE), 0).clip(upper=2)
|
||||
return v.where(frame["module"].isin(modules))
|
||||
|
||||
|
||||
def has_items(frame: pd.DataFrame) -> bool:
|
||||
scores = pd.concat([item_scores(frame, n) for n in spec.ITEMS], axis=1)
|
||||
return int(scores.notna().any(axis=1).sum()) >= spec.MIN_ITEM_CHILDREN
|
||||
|
||||
|
||||
def _state(model: str, t: pd.DataFrame, pair: dict) -> dict | None:
|
||||
"""Only the scoring state of a pair's model refitted on `t` (leave-one-out)."""
|
||||
try:
|
||||
if model == "firth":
|
||||
fitted = firth_fit(rows(t, "_yes", pair["predictor"]), "_yes", pair["predictor"])
|
||||
return fitted and fitted[-1]
|
||||
fitted = ordinal_fit(rows(t, "_level", pair["predictor"]), "_level", pair["predictor"],
|
||||
_high(pair)) # fmt: skip
|
||||
return fitted[-1] if isinstance(fitted, tuple) else None
|
||||
except (np.linalg.LinAlgError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _guarded(fit, *args) -> dict:
|
||||
try:
|
||||
return fit(*args)
|
||||
except (np.linalg.LinAlgError, ValueError) as error:
|
||||
model = "firth" if fit is firth else "ordinal"
|
||||
return {"model": model, "n": 0, "reason": f"singular design ({type(error).__name__})"}
|
||||
|
||||
|
||||
def _high(pair: dict) -> int:
|
||||
return {"composite": 1, "domain": spec.CSS_HIGH}.get(pair["kind"], spec.ALTERED)
|
||||
|
||||
|
||||
def outcome(t: pd.DataFrame, pair: dict) -> tuple[pd.Series, pd.Series]:
|
||||
"""(event, level): the CSS high, or any of the items altered; the level is the CSS, the
|
||||
item's score or how many of the items are altered."""
|
||||
if pair["kind"] == "domain":
|
||||
css = pd.to_numeric(t["css"] if "css" in t else np.nan, errors="coerce")
|
||||
css = pd.Series(css, index=t.index)
|
||||
return (css >= spec.CSS_HIGH).astype(float).where(css.notna()), css
|
||||
scores = pd.concat([item_scores(t, n) for n in spec.outcome_items(pair)], axis=1)
|
||||
complete = scores.notna().all(axis=1)
|
||||
altered = (scores >= spec.ALTERED).sum(axis=1).astype(float).where(complete)
|
||||
level = altered if pair["kind"] == "composite" else scores.iloc[:, 0]
|
||||
return (altered >= 1).astype(float).where(complete), level
|
||||
|
||||
|
||||
def _fit_pair(d: pd.DataFrame, pair: dict) -> dict:
|
||||
"""A pair's principal and sensitivity models: the CSS and a composite with too few events
|
||||
by its level (the cumulative logit), an item by whether it is altered (Firth); an
|
||||
estimate on fewer than MIN_EVENTS children with (or without) the event is flagged."""
|
||||
used = d[["_yes", pair["predictor"]]].dropna()
|
||||
events = int(used["_yes"].sum())
|
||||
without = len(used) - events
|
||||
short = min(events, without) < spec.MIN_EVENTS
|
||||
counted = short and pair["kind"] == "composite"
|
||||
binary = _guarded(firth, d, "_yes", pair["predictor"])
|
||||
graded = _guarded(ordinal, d, "_level", pair["predictor"], _high(pair))
|
||||
principal, sensitivity = ((graded, binary) if pair["kind"] == "domain" or counted
|
||||
else (binary, graded)) # fmt: skip
|
||||
if short and principal.get("odds_ratio") is not None:
|
||||
note = (f"{INSUFFICIENT_DATA}{events} con evento y {without} sin evento "
|
||||
f"(mínimo {spec.MIN_EVENTS})") # fmt: skip
|
||||
if counted:
|
||||
note += "; se usa el número de reactivos alterados"
|
||||
principal = {**principal, "reason": note}
|
||||
return {**pair, "principal": principal, "sensitivity": sensitivity}
|
||||
|
||||
|
||||
def spikes_any(features: dict) -> dict[str, float]:
|
||||
"""Whether the EEG shows any spike while asleep over each group of zones (NaN when no
|
||||
minute or electrode of the group was read), from the spikes' rates by electrode."""
|
||||
minutes = features.get("minutes") or 0
|
||||
out = {}
|
||||
for group, zones in spec.SPIKE_GROUPS.items():
|
||||
rates = [features.get(f"electrode_{e}") for z in zones for e in ZONES[z]]
|
||||
counts = [r * minutes for r in rates if r is not None]
|
||||
out[f"spikes_any_{group}"] = (float(any(n > 0 for n in counts))
|
||||
if minutes > 0 and counts else np.nan) # fmt: skip
|
||||
return out
|
||||
|
||||
|
||||
def _key(key) -> str:
|
||||
return hashlib.sha256(str(key).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
|
||||
"""Every pair's principal and sensitivity models and its q (Benjamini–Hochberg within
|
||||
each biomarker, exploratory pairs apart): what the association is."""
|
||||
if level == "auto":
|
||||
level = "item" if has_items(cohort) else "domain"
|
||||
tested, rows = spec.pairs(level), []
|
||||
for pair in tested:
|
||||
if pair["predictor"] not in cohort:
|
||||
continue
|
||||
d = cohort.copy()
|
||||
d[pair["predictor"]] = pd.to_numeric(d[pair["predictor"]], errors="coerce").replace(
|
||||
[np.inf, -np.inf], np.nan) # fmt: skip
|
||||
d["_yes"], d["_level"] = outcome(d, pair)
|
||||
rows.append(_fit_pair(d, pair))
|
||||
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
|
||||
families = np.array([r["biomarker"] for r in rows])
|
||||
tested_rows = np.array([r["kind"] != "exploratory" for r in rows], bool)
|
||||
q = np.full(len(rows), np.nan)
|
||||
for b in dict.fromkeys(families):
|
||||
mine = (families == b) & np.isfinite(p) & tested_rows
|
||||
if mine.any():
|
||||
q[mine] = multipletests(p[mine], method="fdr_bh")[1].round(5)
|
||||
for r, v in zip(rows, q, strict=True):
|
||||
r["q"] = None if np.isnan(v) else float(v)
|
||||
return {"version": spec.VERSION, "level": level, "n": len(cohort), "rows": rows,
|
||||
"pairs": tested, "keys": sorted(_key(k) for k in cohort.get("key", []))} # fmt: skip
|
||||
|
||||
|
||||
def check(fitted: dict) -> dict:
|
||||
"""A saved association this version can score (one fitted before it must be retrained)."""
|
||||
if fitted.get("version") != spec.VERSION:
|
||||
raise ValueError(f"association {fitted.get('version', '0.1.0')} was fitted before "
|
||||
f"{spec.VERSION}: retrain it") # fmt: skip
|
||||
return fitted
|
||||
|
||||
|
||||
def _event(pair: dict) -> str:
|
||||
return f"alguno >={spec.ALTERED}" if pair["kind"] == "composite" else f">={_high(pair)}"
|
||||
|
||||
|
||||
def associations(fitted: dict) -> list[dict]:
|
||||
"""One row per pair: what the governance report and the record show."""
|
||||
out = []
|
||||
for r in fitted["rows"]:
|
||||
f, s = r["principal"], r["sensitivity"]
|
||||
ratio, other = f.get("odds_ratio"), s.get("odds_ratio")
|
||||
out.append({
|
||||
"biomarker": r["biomarker"], "zone": r["zone"], "kind": r["kind"],
|
||||
"outcome": r["outcome"], "outcome_code": spec.outcome_code(r), "event": _event(r),
|
||||
"model": f["model"], "n": f["n"], "odds_ratio": ratio, "ci_low": f.get("ci_low"),
|
||||
"ci_high": f.get("ci_high"), "p": f.get("p"), "q": r["q"],
|
||||
"sens_model": s["model"], "sens_odds_ratio": other,
|
||||
"same_direction": None if ratio is None or other is None
|
||||
else bool(np.sign(ratio - 1) == np.sign(other - 1)),
|
||||
"reason": f.get("reason", ""),
|
||||
}) # fmt: skip
|
||||
return out
|
||||
|
||||
|
||||
def _scored(t: pd.DataFrame, fitted: dict, pair: dict) -> tuple[np.ndarray, float]:
|
||||
"""Each child's probability under the pair's principal model; a child the association
|
||||
was fitted on, under the model refitted without her (leave-one-out)."""
|
||||
f = pair["principal"]
|
||||
found, reference = probability(f["model"], f["state"], t)
|
||||
keys = set(fitted.get("keys", ()))
|
||||
child = t["person"] if "person" in t else t["key"]
|
||||
trained = t["key"].map(_key).isin(keys).to_numpy()
|
||||
for name in child[trained].unique():
|
||||
own = (child == name).to_numpy()
|
||||
state = _state(f["model"], t[trained & ~own], pair)
|
||||
found[own] = np.nan if state is None else probability(f["model"], state, t[own])[0]
|
||||
return found, reference
|
||||
|
||||
|
||||
def score(fitted: dict, cohort: pd.DataFrame) -> list[dict]:
|
||||
"""Each child's probability under every estimated pair, and the reference child's."""
|
||||
out = []
|
||||
for r in check(fitted)["rows"]:
|
||||
if r["principal"].get("odds_ratio") is None or r["predictor"] not in cohort:
|
||||
continue
|
||||
t = cohort
|
||||
for n in spec.outcome_items(r):
|
||||
t = t[t["module"].isin(spec.ITEMS[n][1])]
|
||||
t = t[pd.to_numeric(t[r["predictor"]], errors="coerce").notna()].copy()
|
||||
if not len(t):
|
||||
continue
|
||||
t["_yes"], t["_level"] = outcome(t, r)
|
||||
found, reference = _scored(t, fitted, r)
|
||||
for key, z, p in zip(t["key"], t[r["predictor"]].to_numpy(float), found, strict=True):
|
||||
if np.isfinite(p):
|
||||
out.append({"key": key, "biomarker": r["biomarker"], "zone": r["zone"],
|
||||
"outcome_code": spec.outcome_code(r), "z": float(z),
|
||||
"probability": round(float(p), 4),
|
||||
"reference_probability": round(reference, 4)}) # fmt: skip
|
||||
return out
|
||||
+31
-28
@@ -1,10 +1,13 @@
|
||||
"""One EEG, from its EDF bytes: whether it can be analysed and, if so, its five metrics.
|
||||
"""One EEG, from its EDF bytes: whether it can be analysed (and why not) and its four metrics.
|
||||
|
||||
analysis = analyze(edf_bytes, birth_date)
|
||||
|
||||
Validation (`checks.py`) gives the verdict, level and every check. A valid EEG is prepared
|
||||
(`preprocess.py`), its windows get a state and a stage (`sleep.py`), and the metrics are
|
||||
measured (`biomarkers.py`) along with the features the age baselines score (`curves.py`).
|
||||
(`preprocess.py`), its windows get a state (`sleep.py`), and the metrics are measured
|
||||
(`biomarkers.py`) along with the features the age baselines score (`curves.py`), why a metric
|
||||
was not measured (`core.tea.reasons.METRIC_REASONS`) and the minutes the spike gate left out
|
||||
(`REJECTED_MINUTES`, with the stable start as `start_s`); an EEG not valid has every metric,
|
||||
none measured, for `invalid-eeg`.
|
||||
|
||||
The age is the EDF header's (recording start minus birth date) when it has both dates, else the
|
||||
recording start minus `birth_date`. `analyze` never raises: a failure is an `Analysis` with
|
||||
@@ -17,6 +20,7 @@ import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
|
||||
from core.tea.reasons import METRIC_REASONS, REJECTED_MINUTES
|
||||
from models.tea.eeg import biomarkers, checks, preprocess, read, sleep
|
||||
|
||||
DAYS_PER_MONTH = 30.4375
|
||||
@@ -35,6 +39,7 @@ class Metric:
|
||||
class Analysis:
|
||||
valid: bool | None
|
||||
level: str
|
||||
reasons: list[str] # why it is not valid (checks.Validation.reasons)
|
||||
age_months: float | None
|
||||
clean_fraction: float | None
|
||||
bad_channels: int | None
|
||||
@@ -43,9 +48,8 @@ class Analysis:
|
||||
line_noise_db: float | None
|
||||
sleep: bool | None
|
||||
checks: list[dict] # code, electrode, value, text, unit, low, high, decisive, abnormal
|
||||
metrics: list[Metric] # posterior_rhythm, spindles_n2, spindles_n3, paroxysmal_spikes,
|
||||
# anteroposterior_gradient
|
||||
features: dict[str, dict[str, float]] # by scenario (`curves.SCENARIOS`), None missing
|
||||
metrics: list[Metric] # biomarkers.CODES
|
||||
features: dict[str, dict] # by scenario (`curves.SCENARIOS`), None missing; and the reasons
|
||||
error: str | None
|
||||
|
||||
|
||||
@@ -53,6 +57,16 @@ def _number(v) -> float | None:
|
||||
return float(v) if v is not None and math.isfinite(v) else None
|
||||
|
||||
|
||||
def _result(out: dict, measured: biomarkers.Measured, **fields) -> Analysis:
|
||||
metrics = [Metric(code, _number(value), {k: _number(v) for k, v in electrodes.items()},
|
||||
{k: _number(v) for k, v in zones.items()})
|
||||
for code, (value, electrodes, zones) in measured.metrics.items()] # fmt: skip
|
||||
features = {s: {k: _number(v) for k, v in f.items()} for s, f in measured.features.items()}
|
||||
features[METRIC_REASONS] = measured.reasons
|
||||
features[REJECTED_MINUTES] = {k: _number(v) for k, v in measured.rejected.items()}
|
||||
return Analysis(**out | dict(metrics=metrics, features=features) | fields)
|
||||
|
||||
|
||||
def _error(exc: Exception) -> str:
|
||||
message = re.sub(r"(/|[A-Za-z]:\\)[^\s'\"]*", "<path>", str(exc))[:300]
|
||||
return f"{type(exc).__name__}: {message}"
|
||||
@@ -64,12 +78,14 @@ def analyze(
|
||||
*,
|
||||
age_months: float | None = None,
|
||||
mains_hz: float = MAINS_HZ,
|
||||
keep_flat: bool = False,
|
||||
) -> Analysis:
|
||||
"""`age_months` overrides the age (a reference cohort's table); `mains_hz` is the frequency
|
||||
of the recording's mains, which only validation's notch follows (`preprocess.NOTCH_HZ`)."""
|
||||
of the recording's mains; `keep_flat` keeps a reference study's one flat electrode."""
|
||||
out = dict(
|
||||
valid=None,
|
||||
level=checks.NOT_ANALYZABLE,
|
||||
reasons=[],
|
||||
age_months=age_months,
|
||||
clean_fraction=None,
|
||||
bad_channels=None,
|
||||
@@ -87,9 +103,8 @@ def analyze(
|
||||
rec = read.read(edf)
|
||||
except read.FileNotValid as exc:
|
||||
verdict = checks.file_not_valid(str(exc))
|
||||
return Analysis(
|
||||
**out | dict(valid=False, clean_fraction=0.0, bad_channels=0, checks=verdict.checks)
|
||||
)
|
||||
return _result(out, biomarkers.invalid(), valid=False, reasons=verdict.reasons,
|
||||
clean_fraction=0.0, bad_channels=0, checks=verdict.checks) # fmt: skip
|
||||
if age_months is None:
|
||||
header = read.age_months(rec.start, rec.birthday, DAYS_PER_MONTH)
|
||||
given = read.age_months(rec.start, birth_date, DAYS_PER_MONTH)
|
||||
@@ -100,6 +115,7 @@ def analyze(
|
||||
out.update(
|
||||
valid=verdict.valid,
|
||||
level=verdict.level,
|
||||
reasons=verdict.reasons,
|
||||
clean_fraction=verdict.clean_pct / 100,
|
||||
bad_channels=len(verdict.bad),
|
||||
channels=len(rec.names) or None,
|
||||
@@ -108,25 +124,12 @@ def analyze(
|
||||
checks=verdict.checks,
|
||||
)
|
||||
if not verdict.valid:
|
||||
return Analysis(**out)
|
||||
prep = preprocess.prepare(rec, verdict.bad)
|
||||
return _result(out, biomarkers.invalid())
|
||||
prep = preprocess.prepare(rec, verdict.bad, mains_hz, keep_flat=keep_flat)
|
||||
notes = sleep.note_intervals(prep.annotations, prep.duration_s)
|
||||
states = sleep.states(prep, notes, age)
|
||||
staged = sleep.stages(prep, states)
|
||||
metrics, features = biomarkers.measure(prep, states, staged, notes)
|
||||
out.update(
|
||||
sleep=bool((states == "sleep").any()),
|
||||
metrics=[
|
||||
Metric(
|
||||
code,
|
||||
_number(value),
|
||||
{k: _number(v) for k, v in electrodes.items()},
|
||||
{k: _number(v) for k, v in zones.items()},
|
||||
)
|
||||
for code, (value, electrodes, zones) in metrics.items()
|
||||
],
|
||||
features={s: {k: _number(v) for k, v in f.items()} for s, f in features.items()},
|
||||
)
|
||||
return Analysis(**out)
|
||||
measured = biomarkers.measure(prep, states, notes)
|
||||
measured.rejected["start_s"] = preprocess.stable_start(rec)
|
||||
return _result(out, measured, sleep=bool((states == "sleep").any()))
|
||||
except Exception as exc: # noqa: BLE001 -- one unreadable EDF must not stop a batch
|
||||
return Analysis(**out | dict(error=_error(exc)))
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""The five metrics of a valid EEG, their per-electrode and per-zone values, and the features
|
||||
each age baseline scores (by scenario, `curves.SCENARIOS`).
|
||||
"""The four metrics of an EEG, their per-electrode and per-zone values, the features each age
|
||||
baseline scores (by scenario, `curves.SCENARIOS`) and why a metric was not measured (its reason:
|
||||
few-wake-windows, no-dominant-peak, no-sleep, few-electrodes, no-spindles; invalid-eeg for every
|
||||
metric of an EEG not valid).
|
||||
|
||||
Posterior rhythm: over at least 15 wake windows, the dominant 3-14 Hz peak of each posterior
|
||||
electrode's mean periodogram (O1, O2, P3, P4); the median over those with a peak, if 2 or more.
|
||||
@@ -8,10 +10,13 @@ Anteroposterior gradient: over at least 15 sleep windows, the median delta (0.5-
|
||||
each electrode (symmetric Hann, |FFT|²), and the Theil-Sen slope of its log10 against the
|
||||
electrode's front-back position (6 electrodes at least).
|
||||
|
||||
Spindles in N2 and N3 (`spindles.py`): density, per zone, and enhancement per electrode.
|
||||
Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode and per zone, against the minutes.
|
||||
Spindles in NREM sleep (`spindles.py`): density, per zone, and enhancement per electrode, noting
|
||||
a posterior rhythm near sigma. Paroxysmal spikes (`spikes.py`): rate in sleep, per electrode
|
||||
and per zone, against the minutes; awake, and the minutes the gate left out by reason.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
|
||||
import numpy as np
|
||||
from scipy.fft import rfft, rfftfreq
|
||||
from scipy.signal.windows import hann
|
||||
@@ -22,49 +27,58 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
from models.tea.eeg.sleep import POSTERIOR
|
||||
|
||||
MIN_WINDOWS = 15
|
||||
MIN_GRADIENT_ELECTRODES = 6
|
||||
INVALID = "invalid-eeg"
|
||||
FRONT_BACK = {
|
||||
"Fp1": 0.95, "Fp2": 0.95, "F7": 0.59, "F3": 0.53, "Fz": 0.50, "F4": 0.53, "F8": 0.59,
|
||||
"T3": 0.0, "C3": 0.0, "Cz": 0.0, "C4": 0.0, "T4": 0.0, "T5": -0.59, "P3": -0.53,
|
||||
"Pz": -0.50, "P4": -0.53, "T6": -0.59, "O1": -0.95, "O2": -0.95,
|
||||
} # fmt: skip
|
||||
CODES = (
|
||||
"posterior_rhythm",
|
||||
"spindles_n2",
|
||||
"spindles_n3",
|
||||
"paroxysmal_spikes",
|
||||
"anteroposterior_gradient",
|
||||
)
|
||||
CODES = ("posterior_rhythm", "spindles", "paroxysmal_spikes", "anteroposterior_gradient")
|
||||
|
||||
|
||||
def _segments(prep: Prepared, names, states, state) -> list[np.ndarray] | None:
|
||||
"""The gap-free 4 s windows labelled `state`, (channels, samples) each; None under 15."""
|
||||
@dataclass(frozen=True)
|
||||
class Measured:
|
||||
metrics: dict[str, tuple[float, dict, dict]] # code -> (value, electrodes, zones)
|
||||
features: dict[str, dict[str, float]] # by scenario
|
||||
reasons: dict[str, str] # code -> why it was not measured
|
||||
rejected: dict[str, float] # minutes the spike gate left out, by reason
|
||||
|
||||
|
||||
def _segments(prep: Prepared, names, states, state) -> tuple[list[np.ndarray], int]:
|
||||
"""The gap-free 4 s windows labelled `state`, (channels, samples) each, and how many
|
||||
windows bear the label."""
|
||||
starts = [s for s, label in zip(prep.starts, states, strict=True) if label == state]
|
||||
if len(starts) < MIN_WINDOWS or not names:
|
||||
return None
|
||||
x, n = prep.data(names), int(round(WINDOW_S * prep.fs))
|
||||
found = []
|
||||
for a in (int(round(float(s) * prep.fs)) for s in starts):
|
||||
for a in (int(round(float(s) * prep.fs)) for s in starts if names):
|
||||
if a + n <= len(x) and np.isfinite(x[a : a + n]).all():
|
||||
found.append(x[a : a + n].T)
|
||||
return found or None
|
||||
return found, len(starts)
|
||||
|
||||
|
||||
def posterior_rhythm(prep: Prepared, states) -> float:
|
||||
def posterior_rhythm(prep: Prepared, states) -> tuple[float, str | None]:
|
||||
names = prep.columns(POSTERIOR)
|
||||
segments = _segments(prep, names, states, "wake")
|
||||
if segments is None:
|
||||
return np.nan
|
||||
segments, windows = _segments(prep, names, states, "wake")
|
||||
if windows < MIN_WINDOWS:
|
||||
return np.nan, "few-wake-windows"
|
||||
if not segments:
|
||||
return np.nan, "no-dominant-peak"
|
||||
f, power = signals.periodograms(np.stack(segments), prep.fs)
|
||||
peaks = [signals.dominant_peak(f, power[:, k].mean(axis=0)) for k in range(len(names))]
|
||||
found = [hz for hz, _, ok in peaks if ok]
|
||||
return float(np.median(found)) if len(found) >= 2 else np.nan
|
||||
return (float(np.median(found)), None) if len(found) >= 2 else (np.nan, "no-dominant-peak")
|
||||
|
||||
|
||||
def delta_gradient(prep: Prepared, states) -> float:
|
||||
def delta_gradient(prep: Prepared, states) -> tuple[float, str | None]:
|
||||
names = [c for c in prep.names if c in FRONT_BACK]
|
||||
segments = _segments(prep, names, states, "sleep")
|
||||
if segments is None:
|
||||
return np.nan
|
||||
segments, windows = _segments(prep, names, states, "sleep")
|
||||
if windows < MIN_WINDOWS:
|
||||
return np.nan, "no-sleep"
|
||||
if len(names) < MIN_GRADIENT_ELECTRODES:
|
||||
return np.nan, "few-electrodes"
|
||||
if not segments:
|
||||
return np.nan, "no-sleep"
|
||||
stack = np.stack(segments)
|
||||
n = stack.shape[-1]
|
||||
f = rfftfreq(n, 1 / prep.fs)
|
||||
@@ -73,41 +87,50 @@ def delta_gradient(prep: Prepared, states) -> float:
|
||||
log_power = np.log10(np.maximum(delta, 1e-30))
|
||||
y = np.array([FRONT_BACK[c] for c in names])
|
||||
finite = np.isfinite(log_power)
|
||||
return float(theilslopes(log_power[finite], y[finite])[0]) if finite.sum() >= 6 else np.nan
|
||||
if finite.sum() < MIN_GRADIENT_ELECTRODES:
|
||||
return np.nan, "few-electrodes"
|
||||
return float(theilslopes(log_power[finite], y[finite])[0]), None
|
||||
|
||||
|
||||
def measure(prep: Prepared, states, staged, intervals) -> tuple[dict, dict]:
|
||||
"""(metrics: code -> (value, electrodes, zones), features by scenario)."""
|
||||
metrics, features = {}, {}
|
||||
rhythm = posterior_rhythm(prep, states)
|
||||
def invalid() -> Measured:
|
||||
"""An EEG not valid: no metric, each for that reason."""
|
||||
return Measured({c: (np.nan, {}, {}) for c in CODES}, {}, dict.fromkeys(CODES, INVALID), {})
|
||||
|
||||
|
||||
def measure(prep: Prepared, states, intervals) -> Measured:
|
||||
metrics, features, reasons = {}, {}, {}
|
||||
rhythm, reasons["posterior_rhythm"] = posterior_rhythm(prep, states)
|
||||
metrics["posterior_rhythm"] = (rhythm, {}, {})
|
||||
features["eeg-posterior-rhythm"] = {"value": rhythm}
|
||||
for stage in ("N2", "N3"):
|
||||
found = spindles.detect(prep, staged, stage)
|
||||
value, zones = spindles.density(found)
|
||||
electrodes = spindles.enhancement(prep, found, states)
|
||||
metrics[f"spindles_{stage.lower()}"] = (value, electrodes, zones)
|
||||
features[f"eeg-spindles-{stage.lower()}"] = {
|
||||
"value": value,
|
||||
**{f"zone_{z}": v for z, v in zones.items()},
|
||||
}
|
||||
features[f"eeg-spindle-topography-{stage.lower()}"] = {
|
||||
f"electrode_{e}": v for e, v in electrodes.items()
|
||||
}
|
||||
found = spikes.detect(prep, states, intervals)
|
||||
if found is None:
|
||||
nan = dict.fromkeys
|
||||
found = spikes.Spikes(
|
||||
np.nan, nan(spikes.ELECTRODES, np.nan), nan(spindles.ZONES, np.nan), 0.0
|
||||
)
|
||||
metrics["paroxysmal_spikes"] = (found.rate, found.electrodes, found.zones)
|
||||
found = replace(spindles.detect(prep, states), rhythm_near_sigma=spindles.near_sigma(rhythm))
|
||||
value, zones = spindles.density(found)
|
||||
electrodes = spindles.enhancement(prep, found, states)
|
||||
metrics["spindles"] = (value, electrodes, zones)
|
||||
features["eeg-spindles"] = {"value": value, **{f"zone_{z}": v for z, v in zones.items()},
|
||||
"rhythm_near_sigma": float(found.rhythm_near_sigma)} # fmt: skip
|
||||
features["eeg-spindle-topography"] = {f"electrode_{e}": v for e, v in electrodes.items()}
|
||||
if np.isnan(value):
|
||||
reasons["spindles"] = "no-sleep" if found.minutes < spindles.MIN_MINUTES else "no-spindles"
|
||||
spiked = spikes.detect(prep, states, intervals)
|
||||
if spiked is None:
|
||||
reasons["paroxysmal_spikes"] = "few-electrodes"
|
||||
recorded = {z: sum(e in prep.names for e in m) for z, m in spindles.ZONES.items()}
|
||||
spiked = spikes.Spikes(np.nan, dict.fromkeys(spikes.ELECTRODES, np.nan),
|
||||
dict.fromkeys(spindles.ZONES, np.nan), 0.0, {}, np.nan, 0.0,
|
||||
recorded) # fmt: skip
|
||||
elif np.isnan(spiked.rate):
|
||||
reasons["paroxysmal_spikes"] = "no-sleep"
|
||||
metrics["paroxysmal_spikes"] = (spiked.rate, spiked.electrodes, spiked.zones)
|
||||
features["eeg-spikes"] = {
|
||||
"value": found.rate,
|
||||
**{f"electrode_{e}": v for e, v in found.electrodes.items()},
|
||||
**{f"zone_{z}": v for z, v in found.zones.items()},
|
||||
"minutes": found.minutes,
|
||||
}
|
||||
gradient = delta_gradient(prep, states)
|
||||
"value": spiked.rate,
|
||||
**{f"electrode_{e}": v for e, v in spiked.electrodes.items()},
|
||||
**{f"zone_{z}": v for z, v in spiked.zones.items()},
|
||||
"minutes": spiked.minutes, "awake_rate": spiked.awake_rate,
|
||||
"awake_minutes": spiked.awake_minutes,
|
||||
**{f"zone_electrodes_{z}": n for z, n in spiked.zone_electrodes.items()},
|
||||
} # fmt: skip
|
||||
gradient, reasons["anteroposterior_gradient"] = delta_gradient(prep, states)
|
||||
metrics["anteroposterior_gradient"] = (gradient, {}, {})
|
||||
features["eeg-gradient"] = {"value": gradient}
|
||||
return {code: metrics[code] for code in CODES}, features
|
||||
reasons = {code: why for code, why in reasons.items() if why}
|
||||
return Measured({code: metrics[code] for code in CODES}, features, reasons, spiked.rejected)
|
||||
|
||||
+36
-31
@@ -37,6 +37,8 @@ MAX_BAD_SCALP = 2
|
||||
MIN_SCALP = 12
|
||||
MAX_LINE_DB = 45.0
|
||||
NOT_ANALYZABLE = "not_analyzable"
|
||||
LEVELS = {NOT_ANALYZABLE: "No analizable", "partial": "Parcial",
|
||||
"no_ear_reference": "Sin referencia auricular", "complete": "Completo"} # fmt: skip
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -47,10 +49,7 @@ class Validation:
|
||||
clean_pct: float
|
||||
line_db: float
|
||||
checks: list[dict] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def ears_usable(self) -> bool:
|
||||
return all(ear not in self.bad for ear in ("A1", "A2"))
|
||||
reasons: list[str] = field(default_factory=list) # why it is not valid
|
||||
|
||||
|
||||
def check(
|
||||
@@ -80,7 +79,7 @@ def check(
|
||||
|
||||
def file_not_valid(reason: str) -> Validation:
|
||||
rows = [check("file", text=reason, decisive=True, abnormal=True)]
|
||||
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows)
|
||||
return Validation(False, NOT_ANALYZABLE, {}, 0.0, np.nan, rows, ["invalid-file"])
|
||||
|
||||
|
||||
def _filtered(x, fs, mains_hz, lo, hi):
|
||||
@@ -91,14 +90,14 @@ def _temporal(v: np.ndarray) -> list[tuple[str, str]]:
|
||||
"""Rules on a channel's raw samples: (code, reason)."""
|
||||
finite = v[np.isfinite(v)]
|
||||
if len(finite) < 10 or np.std(finite) < 0.5:
|
||||
return [("dead-channel", "dead channel")]
|
||||
return [("dead-channel", "Canal muerto")]
|
||||
out = []
|
||||
if np.mean(np.abs(np.diff(finite)) < 1e-9) > 0.5:
|
||||
out.append(("frozen", "frozen"))
|
||||
out.append(("frozen", "Señal congelada"))
|
||||
if np.mean(np.abs(finite) > 0.98 * np.max(np.abs(finite))) > 0.001:
|
||||
out.append(("saturated", "saturated"))
|
||||
out.append(("saturated", "Señal saturada"))
|
||||
if np.isinf(v).any():
|
||||
out.append(("inf-values", "Inf values"))
|
||||
out.append(("inf-values", "Valores infinitos"))
|
||||
return out
|
||||
|
||||
|
||||
@@ -166,9 +165,7 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
||||
"""Channel -> [(code, reason)] of every channel some rule flags."""
|
||||
x, fs, names, kinds = rec.x, rec.fs, list(rec.names), rec.kinds()
|
||||
reasons = {name: _temporal(x[:, i]) for i, name in enumerate(names)}
|
||||
dead = {
|
||||
name for name, found in reasons.items() if found[:1] == [("dead-channel", "dead channel")]
|
||||
}
|
||||
dead = {name for name, found in reasons.items() if found and found[0][0] == "dead-channel"}
|
||||
notched = signals.notch(x, fs, mains_hz)
|
||||
y45 = signals.bandpass(notched, fs, 0.5, min(45.0, fs / 2 * 0.9))
|
||||
y40 = signals.bandpass(notched, fs, 1.0, 40.0)
|
||||
@@ -184,34 +181,38 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
||||
found, k = reasons[name], kinds[name]
|
||||
if missing[i] > missing.min() + 0.02:
|
||||
excess = 100 * (missing[i] - missing.min())
|
||||
found.append(("own-gaps", f"own gaps ({excess:.1f}% more than the rest)"))
|
||||
found.append(
|
||||
("own-gaps", f"Interrupciones del canal ({excess:.1f} % más que el resto)")
|
||||
)
|
||||
if name in dead:
|
||||
continue
|
||||
if k == "eeg" and name in bridges:
|
||||
found.append(("bridge", f"bridge with {bridges[name]}"))
|
||||
found.append(("bridge", f"Puente con {bridges[name]}"))
|
||||
if k in ("eeg", "ear") and np.isfinite(ratio[i]) and ratio[i] > 4.0:
|
||||
found.append(("amplitude", f"amplitude {ratio[i]:.1f} x the scalp median"))
|
||||
found.append(
|
||||
("amplitude", f"Amplitud {ratio[i]:.1f} veces la mediana del cuero cabelludo")
|
||||
)
|
||||
if name in ears and ears[name][1] > 0.2 and ears[name][0] < 0.5 * ears[name][1]:
|
||||
c, e = ears[name]
|
||||
found.append(
|
||||
(
|
||||
"does-not-correlate",
|
||||
f"does not correlate with its neighbours ({c:.2f} vs {e:.2f})",
|
||||
f"Sin correlación con los vecinos ({c:.2f} frente a {e:.2f})",
|
||||
)
|
||||
)
|
||||
if np.isfinite(low[i]) and low[i] > 0.10:
|
||||
found.append(
|
||||
(
|
||||
"intermittent-contact",
|
||||
f"intermittent contact ({100 * low[i]:.0f}% of blocks silent)",
|
||||
f"Contacto intermitente ({100 * low[i]:.0f} % de bloques sin señal)",
|
||||
)
|
||||
)
|
||||
if k in ("eeg", "ear") and np.isfinite(burst[i]) and burst[i] > 0.05:
|
||||
found.append(
|
||||
(
|
||||
"intermittent-bursts",
|
||||
f"intermittent contact by bursts "
|
||||
f"({100 * burst[i]:.0f}% of blocks above 4 x the montage)",
|
||||
f"Contacto intermitente por ráfagas "
|
||||
f"({100 * burst[i]:.0f} % de bloques por encima de 4 veces el montaje)",
|
||||
)
|
||||
)
|
||||
if k in ("eog", "ecg"):
|
||||
@@ -220,18 +221,19 @@ def bad_channels(rec: Recording, mains_hz: float) -> dict[str, list[tuple[str, s
|
||||
found.append(
|
||||
(
|
||||
"aux-amplitude",
|
||||
f"amplitude {np.sqrt(np.mean(v**2)):.0f} uV, "
|
||||
f"out of range even for {k.upper()}",
|
||||
f"Amplitud {np.sqrt(np.mean(v**2)):.0f} µV, "
|
||||
f"fuera de rango incluso para {k.upper()}",
|
||||
)
|
||||
)
|
||||
return {name: found for name, found in reasons.items() if found}
|
||||
|
||||
|
||||
def window_qc(y: np.ndarray, fs: float) -> list[tuple[float, float, str]]:
|
||||
def window_qc(y: np.ndarray, fs: float, start_s: float = 0.0) -> list[tuple[float, float, str]]:
|
||||
"""Back-to-back 4 s windows of a filtered scalp signal: (start s, end s, verdict), the
|
||||
verdict `gap`, `suspect` or `clean`."""
|
||||
n = int(4 * fs)
|
||||
lines = signals.fixed_lines(y, fs, f_max=44.0)
|
||||
verdict `gap`, `suspect` or `clean`; its fixed lines are sought after `start_s` (when 30 s
|
||||
or more remain)."""
|
||||
n, start = int(4 * fs), int(start_s * fs)
|
||||
lines = signals.fixed_lines(y[start:] if len(y) - start > 30 * fs else y, fs, f_max=44.0)
|
||||
starts = list(range(0, len(y) - n + 1, n))
|
||||
segments = [y[a : a + n] for a in starts]
|
||||
whole = [bool(np.isfinite(s).all()) for s in segments]
|
||||
@@ -315,7 +317,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
check(
|
||||
"internal-coverage",
|
||||
value=coverage,
|
||||
unit="fraction",
|
||||
unit="fracción",
|
||||
low=MIN_COVERAGE,
|
||||
abnormal=coverage < MIN_COVERAGE,
|
||||
decisive=True,
|
||||
@@ -323,7 +325,7 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
check(
|
||||
"bad-scalp-triage",
|
||||
value=float(len(triaged)),
|
||||
unit="electrodes",
|
||||
unit="electrodos",
|
||||
high=float(MAX_BAD_SCALP),
|
||||
abnormal=len(triaged) > MAX_BAD_SCALP,
|
||||
decisive=True,
|
||||
@@ -331,12 +333,12 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
check(
|
||||
"usable-scalp",
|
||||
value=float(len(usable)),
|
||||
unit="electrodes",
|
||||
unit="electrodos",
|
||||
low=float(MIN_SCALP),
|
||||
abnormal=len(usable) < MIN_SCALP,
|
||||
decisive=True,
|
||||
),
|
||||
check("triage-level", text=level, abnormal=level == NOT_ANALYZABLE, decisive=True),
|
||||
check("triage-level", text=LEVELS[level], abnormal=level == NOT_ANALYZABLE, decisive=True),
|
||||
]
|
||||
if np.isfinite(line):
|
||||
rows.append(
|
||||
@@ -344,6 +346,9 @@ def validate(rec: Recording, mains_hz: float) -> Validation:
|
||||
"line-noise", value=line, unit="dB", high=MAX_LINE_DB, abnormal=line > MAX_LINE_DB
|
||||
)
|
||||
)
|
||||
valid = level != NOT_ANALYZABLE and clean_pct >= MIN_CLEAN_PCT and len(usable) >= MIN_SCALP
|
||||
failed = {"triage-not-analyzable": level == NOT_ANALYZABLE,
|
||||
"few-clean-minutes": clean_pct < MIN_CLEAN_PCT,
|
||||
"few-electrodes": len(usable) < MIN_SCALP} # fmt: skip
|
||||
reasons = [reason for reason, fails in failed.items() if fails]
|
||||
bad = {name: [reason for _, reason in found] for name, found in flagged.items()}
|
||||
return Validation(valid, level, bad, clean_pct, line, rows)
|
||||
return Validation(not reasons, level, bad, clean_pct, line, rows, reasons)
|
||||
|
||||
+71
-46
@@ -1,7 +1,7 @@
|
||||
"""Age baselines: each metric's value (and per electrode and zone) against children of the same
|
||||
age in a reference cohort.
|
||||
|
||||
Seven scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
|
||||
Five scenarios (`SCENARIOS`), each trained on its feature table (one row per valid reference
|
||||
study: the scenario's features from `Analysis.features` plus `age_months`). Every feature gets
|
||||
its own baseline, plain JSON-able data (`train`), scored by `score`:
|
||||
|
||||
@@ -14,7 +14,9 @@ its own baseline, plain JSON-able data (`train`), scored by `score`:
|
||||
minute (16 to 37 months) and its dispersion between children (negative binomial by moments,
|
||||
Poisson without excess). A value is a count in the child's own minutes (`exposure`): z from
|
||||
the mid-p tail of that many or more, clipped to ±8; outside +1 when P(N >= n) < 0.05; p5,
|
||||
median and p95 are the rates at those quantiles of the count in those minutes.
|
||||
median and p95 are the rates at those quantiles of the count in those minutes. A zone's rate
|
||||
is per minute and electrode: its exposure is its minutes times its electrodes recorded.
|
||||
A value without a score says why (`reason`): no-age, age-out-of-range or no-exposure.
|
||||
"""
|
||||
|
||||
import math
|
||||
@@ -31,22 +33,21 @@ MIN_EFFECTIVE = 30
|
||||
COUNT_AGES = (16.0, 37.0)
|
||||
Z_MAX = 8.0
|
||||
EXPOSURE = "minutes"
|
||||
NOT_MEASURES = ("age_months", EXPOSURE, "rhythm_near_sigma") # in a table, not baselines
|
||||
SCORE_FIELDS = ("z", "outside", "p5", "median", "p95")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Scenario:
|
||||
metric: str # the metric code it scores
|
||||
parts: tuple[str, ...] # of the metric: "value", "electrodes", "zones"
|
||||
stage: str | None = None
|
||||
counts: bool = False # a count against the `minutes` feature, not centile curves
|
||||
|
||||
|
||||
SCENARIOS = {
|
||||
"eeg-posterior-rhythm": Scenario("posterior_rhythm", ("value",)),
|
||||
"eeg-spindles-n2": Scenario("spindles_n2", ("value", "zones"), "N2"),
|
||||
"eeg-spindle-topography-n2": Scenario("spindles_n2", ("electrodes",), "N2"),
|
||||
"eeg-spindles-n3": Scenario("spindles_n3", ("value", "zones"), "N3"),
|
||||
"eeg-spindle-topography-n3": Scenario("spindles_n3", ("electrodes",), "N3"),
|
||||
"eeg-spindles": Scenario("spindles", ("value", "zones")),
|
||||
"eeg-spindle-topography": Scenario("spindles", ("electrodes",)),
|
||||
"eeg-spikes": Scenario("paroxysmal_spikes", ("value", "electrodes", "zones"), counts=True),
|
||||
"eeg-gradient": Scenario("anteroposterior_gradient", ("value",)),
|
||||
}
|
||||
@@ -81,7 +82,10 @@ def _curve(values: np.ndarray, ages: np.ndarray) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> dict:
|
||||
def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray,
|
||||
electrodes: np.ndarray) -> dict: # fmt: skip
|
||||
"""A zone's rate per minute and electrode: its count over its minutes x electrodes."""
|
||||
exposure = exposure * electrodes
|
||||
n = np.round(values * exposure)
|
||||
keep = np.isfinite(n) & np.isfinite(exposure) & (exposure > 0)
|
||||
keep &= (ages >= COUNT_AGES[0]) & (ages < COUNT_AGES[1])
|
||||
@@ -101,15 +105,21 @@ def _count_rate(values: np.ndarray, ages: np.ndarray, exposure: np.ndarray) -> d
|
||||
|
||||
|
||||
def train(features: pd.DataFrame, scenario: str) -> dict:
|
||||
"""Feature -> baseline, for every feature of the scenario's table (`age_months` and the
|
||||
count's `minutes` excepted)."""
|
||||
"""Feature -> baseline, for every measure of the scenario's table (NOT_MEASURES, a zone's
|
||||
electrodes and the awake spikes excepted)."""
|
||||
counts = SCENARIOS[scenario].counts
|
||||
ages = features["age_months"].to_numpy(float)
|
||||
out = {}
|
||||
for name in features.columns.drop(["age_months", EXPOSURE], errors="ignore"):
|
||||
for name in features.columns.drop(list(NOT_MEASURES), errors="ignore"):
|
||||
if name.startswith(("zone_electrodes_", "awake_")):
|
||||
continue
|
||||
values = pd.to_numeric(features[name]).to_numpy(float)
|
||||
if counts:
|
||||
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float))
|
||||
column = f"zone_electrodes_{name.removeprefix('zone_')}"
|
||||
electrodes = np.ones(len(features))
|
||||
if name.startswith("zone_") and column in features:
|
||||
electrodes = pd.to_numeric(features[column]).fillna(1).to_numpy(float)
|
||||
out[name] = _count_rate(values, ages, features[EXPOSURE].to_numpy(float), electrodes)
|
||||
else:
|
||||
out[name] = _curve(values, ages)
|
||||
return out
|
||||
@@ -119,51 +129,64 @@ def _number(v) -> float | None:
|
||||
return float(v) if v is not None and math.isfinite(v) else None
|
||||
|
||||
|
||||
def _score_curve(baseline: dict, value: float, age: float) -> dict:
|
||||
def _unscored(reason: str | None = None) -> dict:
|
||||
"""No score, and why: no-age, age-out-of-range, no-exposure (None: no value)."""
|
||||
return {**dict.fromkeys(SCORE_FIELDS), "reason": reason}
|
||||
|
||||
|
||||
def centiles(baseline: dict, age_months: float) -> dict:
|
||||
"""A curve's centiles at an age (None outside the curve)."""
|
||||
curve = pd.DataFrame(baseline["curve"]).astype(float).dropna()
|
||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
if not len(curve) or not age > 0:
|
||||
return out
|
||||
log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(np.array([age]))[0])
|
||||
names = [name for name in QUANTILES if name in curve]
|
||||
if curve.empty or not age_months > 0:
|
||||
return dict.fromkeys(QUANTILES)
|
||||
log_ages, at = np.log(curve["age_months"].to_numpy()), float(np.log(age_months))
|
||||
if not log_ages.min() <= at <= log_ages.max():
|
||||
return out
|
||||
q = {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in QUANTILES}
|
||||
return dict.fromkeys(QUANTILES)
|
||||
return {name: float(np.interp(at, log_ages, curve[name].to_numpy())) for name in names}
|
||||
|
||||
|
||||
def _score_curve(baseline: dict, value: float, age: float) -> dict:
|
||||
q = centiles(baseline, age)
|
||||
if q["median"] is None:
|
||||
return _unscored("age-out-of-range")
|
||||
side = q["median"] - q["p5"] if value < q["median"] else q["p95"] - q["median"]
|
||||
z = (value - q["median"]) / (side / 1.645) if side > 0 else None
|
||||
outside = -1 if value < q["p5"] else 1 if value > q["p95"] else 0
|
||||
return {
|
||||
"z": _number(z),
|
||||
"outside": outside,
|
||||
"p5": q["p5"],
|
||||
"median": q["median"],
|
||||
"p95": q["p95"],
|
||||
}
|
||||
return {"z": _number(z), "outside": outside, "p5": q["p5"], "median": q["median"],
|
||||
"p95": q["p95"], "reason": None} # fmt: skip
|
||||
|
||||
|
||||
def _score_count(baseline: dict, value: float, age: float, exposure: float | None) -> dict:
|
||||
out = dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
def _score_count(baseline: dict, value: float, age: float, exposure: float | None,
|
||||
electrodes: float) -> dict: # fmt: skip
|
||||
rate, k = baseline["rate"], baseline["k"]
|
||||
lo, hi = baseline["ages"]
|
||||
if exposure is None or not math.isfinite(rate) or not (exposure > 0 and lo <= age < hi):
|
||||
return out
|
||||
n, mu = float(np.round(value * exposure)), rate * exposure
|
||||
if not lo <= age < hi:
|
||||
return _unscored("age-out-of-range")
|
||||
if exposure is None or not math.isfinite(rate) or not exposure > 0 or not electrodes > 0:
|
||||
return _unscored("no-exposure")
|
||||
n, mu = float(np.round(value * exposure)), rate * exposure * electrodes
|
||||
law = stats.poisson(mu) if k is None else stats.nbinom(k, k / (k + mu))
|
||||
tail, at = law.sf(n - 1), law.pmf(n)
|
||||
z = float(np.clip(stats.norm.ppf(1 - (tail - at / 2)), -Z_MAX, Z_MAX))
|
||||
p5, median, p95 = (float(law.ppf(p)) / exposure for p in (0.05, 0.5, 0.95))
|
||||
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95}
|
||||
return {"z": z, "outside": 1 if tail < 0.05 else 0, "p5": p5, "median": median, "p95": p95,
|
||||
"reason": None} # fmt: skip
|
||||
|
||||
|
||||
def score(
|
||||
baseline: dict, value: float | None, age_months: float | None, exposure: float | None = None
|
||||
) -> dict:
|
||||
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age; None where the value, the
|
||||
age or the baseline's coverage is missing."""
|
||||
def score(baseline: dict, value: float | None, age_months: float | None,
|
||||
exposure: float | None = None, electrodes: float | None = None) -> dict: # fmt: skip
|
||||
"""z, outside (-1/0/+1), p5, median, p95 of a value at an age, and the reason when it has
|
||||
none; a count against its minutes (`exposure`) and, a zone's, its electrodes."""
|
||||
value, age_months = _number(value), _number(age_months)
|
||||
if value is None or age_months is None:
|
||||
return dict.fromkeys(("z", "outside", "p5", "median", "p95"))
|
||||
if value is None:
|
||||
return _unscored()
|
||||
if age_months is None:
|
||||
return _unscored("no-age")
|
||||
if baseline["kind"] == "count_rate":
|
||||
return _score_count(baseline, value, age_months, _number(exposure))
|
||||
electrodes = _number(electrodes)
|
||||
return _score_count(baseline, value, age_months, _number(exposure),
|
||||
1.0 if electrodes is None else electrodes) # fmt: skip
|
||||
return _score_curve(baseline, value, age_months)
|
||||
|
||||
|
||||
@@ -177,15 +200,17 @@ def deviations(models: dict[str, dict], analysis) -> dict[str, dict]:
|
||||
model, metric = models.get(name), metrics.get(scenario.metric)
|
||||
if model is None or metric is None:
|
||||
continue
|
||||
exposure = analysis.features[name].get(EXPOSURE) if scenario.counts else None
|
||||
features = analysis.features.get(name, {})
|
||||
exposure = features.get(EXPOSURE) if scenario.counts else None
|
||||
for part in scenario.parts:
|
||||
if part == "value":
|
||||
out[metric.code]["value"] = score(
|
||||
model["value"], metric.value, analysis.age_months, exposure
|
||||
)
|
||||
else:
|
||||
out[metric.code][part] = {
|
||||
key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure)
|
||||
for key, v in getattr(metric, part).items()
|
||||
}
|
||||
continue
|
||||
out[metric.code][part] = {
|
||||
key: score(model[PREFIX[part] + key], v, analysis.age_months, exposure,
|
||||
features.get(f"zone_electrodes_{key}") if part == "zones" else None)
|
||||
for key, v in getattr(metric, part).items()
|
||||
} # fmt: skip
|
||||
return out
|
||||
|
||||
@@ -1,26 +1,35 @@
|
||||
"""A valid EEG ready for the processes: bad channels out, mains removed, 0.5-100 Hz, average
|
||||
reference, and the 4 s / 2 s window grid with the stretches QC judged not clean.
|
||||
|
||||
The mains notch runs when the line stands at least 6 dB over its neighbourhood on the kept scalp
|
||||
channels. Its frequency is always `NOTCH_HZ` (60), whatever the mains the validation was given:
|
||||
the reference cohort (50 Hz mains) was built that way, so its curves only hold if it stays so.
|
||||
The QC behind the unclean spans is the validation's window rule on the post-notch kept scalp
|
||||
channels at 0.5-45 Hz.
|
||||
The mains notch (at the recording's mains) runs when the line stands at least 6 dB over its
|
||||
neighbourhood on the kept scalp channels. A reference study's one flat electrode can be kept
|
||||
(`keep_flat`), outside QC. The QC behind the unclean spans is the validation's window rule on the
|
||||
kept scalp channels with every mains harmonic notched (IIR, Q 30) at 0.5-45 Hz; everything
|
||||
before the stable start (`stable_start`) is unclean too.
|
||||
|
||||
Stable start: on back-to-back 10 s blocks of the scalp channels, the first block from which at
|
||||
least 90 % of the rest (6 blocks or more) stay under twice the median spread of the recording's
|
||||
second half; a later note of the recording's start (start record, inicio...) or the last note
|
||||
of its set-up (impedances, montage, calibration...) moves it there.
|
||||
"""
|
||||
|
||||
import unicodedata
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
from models.tea.eeg import signals
|
||||
from models.tea.eeg.checks import window_qc
|
||||
from models.tea.eeg.read import Recording
|
||||
|
||||
NOTCH_HZ = 60.0
|
||||
NOTCH_MIN_DB = 6.0
|
||||
WINDOW_S = 4.0
|
||||
STEP_S = 2.0
|
||||
START_MARKS = ("start record", "inicio", "comienzo", "begin record", "recording on",
|
||||
"start of record") # fmt: skip
|
||||
SETUP_MARKS = ("impedanc", "montaje", "montage", "electrod", "calibrac", "colocac", "prueba")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -44,12 +53,54 @@ class Prepared:
|
||||
return self.x[:, [self.names.index(name) for name in names]]
|
||||
|
||||
|
||||
def prepare(rec: Recording, bad) -> Prepared:
|
||||
scalp = [name for name in rec.of("eeg") if name not in bad]
|
||||
def _plain(text) -> str:
|
||||
return "".join(c for c in unicodedata.normalize("NFD", str(text))
|
||||
if unicodedata.category(c) != "Mn").lower() # fmt: skip
|
||||
|
||||
|
||||
def stable_start(rec: Recording) -> float:
|
||||
"""Seconds from which the recording settles (module docstring)."""
|
||||
x = rec.x[:, [rec.names.index(name) for name in rec.of("eeg")]]
|
||||
n = int(10 * rec.fs)
|
||||
blocks = [x[a : a + n] for a in range(0, len(x) - n + 1, n)]
|
||||
rms = np.array([np.median(np.std(b, axis=0)) if np.isfinite(b).all() else np.nan
|
||||
for b in blocks]) # fmt: skip
|
||||
finite = np.isfinite(rms)
|
||||
if finite.sum() < 12:
|
||||
return 0.0
|
||||
limit = 2.0 * np.median(rms[finite][finite.sum() // 2 :])
|
||||
start = 0.0
|
||||
for i in np.flatnonzero(finite):
|
||||
rest = rms[i:][np.isfinite(rms[i:])]
|
||||
if len(rest) >= 6 and np.mean(rest <= limit) >= 0.9:
|
||||
start = i * n / rec.fs
|
||||
break
|
||||
mark = None
|
||||
for onset, _, text in sorted(rec.annotations, key=lambda a: a[0]):
|
||||
if any(m in _plain(text) for m in START_MARKS):
|
||||
mark = onset
|
||||
break
|
||||
if any(m in _plain(text) for m in SETUP_MARKS):
|
||||
mark = onset
|
||||
return float(mark) if mark is not None and mark >= start else start
|
||||
|
||||
|
||||
def _harmonics_notched(x: np.ndarray, fs: float, mains_hz: float) -> np.ndarray:
|
||||
nyquist = fs / 2 * 0.98
|
||||
sos = np.vstack([np.hstack(signal.iirnotch(k * mains_hz, 30.0, fs))
|
||||
for k in range(1, 100) if k * mains_hz < nyquist]) # fmt: skip
|
||||
minimum = max(3 * (len(sos) * 2 + 1), int(fs))
|
||||
return signals.by_runs(x, lambda run: signal.sosfiltfilt(sos, run, axis=0), minimum)
|
||||
|
||||
|
||||
def prepare(rec: Recording, bad, mains_hz: float, keep_flat: bool = False) -> Prepared:
|
||||
eeg = rec.of("eeg")
|
||||
flat = [n for n in eeg if not np.nanstd(rec.x[:, rec.names.index(n)]) > 0.5]
|
||||
keep = flat if keep_flat and len(flat) == 1 else []
|
||||
scalp = [name for name in eeg if name not in bad or name in keep]
|
||||
x = rec.x[:, [rec.names.index(name) for name in scalp]]
|
||||
if np.nanmedian(signals.line_db(x, rec.fs, NOTCH_HZ)) >= NOTCH_MIN_DB:
|
||||
x = signals.notch(x, rec.fs, NOTCH_HZ, width=1.5)
|
||||
gaps = ~np.isfinite(x).all(axis=1)
|
||||
if np.nanmedian(signals.line_db(x, rec.fs, mains_hz)) >= NOTCH_MIN_DB:
|
||||
x = signals.notch(x, rec.fs, mains_hz, width=1.5)
|
||||
y = signals.bandpass(x, rec.fs, 0.5, 100.0)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore", RuntimeWarning) # the mean of a gap's row
|
||||
@@ -57,10 +108,10 @@ def prepare(rec: Recording, bad) -> Prepared:
|
||||
# Kept as the reference analysis read it from MNE: through volts and back, column-major in
|
||||
# memory (the layout decides the order of float sums along time).
|
||||
referenced = np.asfortranarray(referenced * 1e-6 * 1e6)
|
||||
qc = signals.bandpass(x, rec.fs, 0.5, 45.0)
|
||||
qc[gaps] = np.nan
|
||||
unclean = tuple(
|
||||
(float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs) if v != "clean"
|
||||
)
|
||||
raw = rec.x[:, [rec.names.index(name) for name in scalp if name not in keep]]
|
||||
qc = signals.bandpass(_harmonics_notched(raw, rec.fs, mains_hz), rec.fs, 0.5, 45.0)
|
||||
start = stable_start(rec)
|
||||
unclean = tuple((float(t0), float(t1) - float(t0)) for t0, t1, v in window_qc(qc, rec.fs, start)
|
||||
if v != "clean" or t0 < start) # fmt: skip
|
||||
starts = np.arange(0.0, rec.duration_s - WINDOW_S + 1e-9, STEP_S)
|
||||
return Prepared(referenced, tuple(scalp), rec.fs, starts, unclean, rec.annotations)
|
||||
|
||||
+47
-3
@@ -75,14 +75,58 @@ class Recording:
|
||||
return [name for name in self.names if kind(name) in kinds]
|
||||
|
||||
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
@dataclass(frozen=True)
|
||||
class Header:
|
||||
"""What an EDF's header says of its patient and recording (EDF+ fields; None when not
|
||||
given)."""
|
||||
|
||||
patient_code: str | None
|
||||
sex: str | None
|
||||
birthdate: date | None
|
||||
start_date: date | None
|
||||
record_code: str | None
|
||||
duration_s: float | None
|
||||
channels: int
|
||||
|
||||
|
||||
def _open(edf: bytes) -> edfio.Edf:
|
||||
if len(edf) < 256:
|
||||
raise FileNotValid("file too short to be an EDF (header < 256 bytes)")
|
||||
try:
|
||||
signals = edfio.read_edf(edf, lazy_load_data=True).signals
|
||||
opened = edfio.read_edf(edf, lazy_load_data=True)
|
||||
except Exception as exc: # noqa: BLE001 -- any parse failure means the same
|
||||
raise FileNotValid(f"not a readable EDF/EDF+ header ({type(exc).__name__})") from None
|
||||
if int(edf[236:244]) > opened.num_data_records:
|
||||
raise FileNotValid("the EDF signal data is truncated")
|
||||
return opened
|
||||
|
||||
|
||||
def _given(read) -> object | None:
|
||||
"""An EDF+ subfield, None when not given ('X' or not compliant)."""
|
||||
try:
|
||||
value = read()
|
||||
except ValueError:
|
||||
return None
|
||||
return None if value in ("", "X") else value
|
||||
|
||||
|
||||
def header(edf: bytes) -> Header:
|
||||
opened = _open(edf)
|
||||
start = _given(lambda: opened.recording.startdate)
|
||||
return Header(
|
||||
patient_code=_given(lambda: opened.patient.code),
|
||||
sex=sex if (sex := _given(lambda: opened.patient.sex)) in ("F", "M") else None,
|
||||
birthdate=_given(lambda: opened.patient.birthdate),
|
||||
start_date=None if start == UNKNOWN_START else start,
|
||||
record_code=_given(lambda: opened.recording.hospital_administration_code),
|
||||
duration_s=opened.duration,
|
||||
channels=opened.num_signals,
|
||||
)
|
||||
|
||||
|
||||
def _kept(edf: bytes) -> list[tuple[str, str]]:
|
||||
"""(label, name) of the channels to read: recognised, at the majority rate, first of each."""
|
||||
signals = _open(edf).signals
|
||||
if not signals:
|
||||
raise FileNotValid("the EDF declares zero signals")
|
||||
named = [(s.label, normalize(s.label), float(s.sampling_frequency)) for s in signals]
|
||||
|
||||
+20
-21
@@ -1,41 +1,38 @@
|
||||
"""The reference cohort the age baselines are trained on: HK1K, the Helsinki EEGs (public),
|
||||
children of 16 to 36 months, recorded on 50 Hz mains.
|
||||
"""A reference cohort the age baselines can be trained on (a folder of EDFs of children of 16
|
||||
to 36 months, such as HK1K, the Helsinki EEGs) instead of the site's own.
|
||||
|
||||
`listing` pairs each EDF under a folder with its age from the cohort's table (first column the
|
||||
file name, second the age in years; months = years x 12 to one decimal); keys are positions in
|
||||
path order, never file names. `measure` analyses each study as a hospital EEG (at the cohort's
|
||||
mains, with the table's age) in the cluster's workers; `tables` gives each scenario's training table
|
||||
from the valid studies.
|
||||
`listing` pairs each EDF under a folder with its age from the cohort's table (`path`, relative
|
||||
to the folder, and `age` in months, kept to one decimal); keys are the folder's name and a
|
||||
position in path order, never file names. `measure` analyses each study as a hospital EEG (at
|
||||
the cohort's mains, with the table's age, keeping a single flat electrode) in worker
|
||||
processes; `tables` gives each scenario's training table from the valid studies.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from models import execution
|
||||
from models import cluster
|
||||
from models.tea.eeg.analysis import analyze
|
||||
from models.tea.eeg.curves import SCENARIOS
|
||||
|
||||
NAME = "hk1k"
|
||||
MAINS_HZ = 50.0
|
||||
AGES = (16.0, 36.0)
|
||||
|
||||
|
||||
def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path, float]]:
|
||||
"""(key, path, age in months) of each EDF with an age within `ages`."""
|
||||
table = pd.read_csv(ages_table)
|
||||
years = dict(zip(table.iloc[:, 0].astype(str), table.iloc[:, 1].astype(float), strict=True))
|
||||
months = dict(zip(table["path"].astype(str), table["age"].astype(float), strict=True))
|
||||
found = []
|
||||
for path in sorted(p for p in Path(folder).rglob("*") if p.suffix.lower() == ".edf"):
|
||||
age = round(float(years[path.name] * 12), 1) if path.name in years else None
|
||||
age = months.get(path.relative_to(folder).as_posix())
|
||||
if age is not None and age == age and ages[0] <= age <= ages[1]:
|
||||
found.append((path, age))
|
||||
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
||||
found.append((path, round(age, 1)))
|
||||
return [(f"{Path(folder).name}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
|
||||
|
||||
|
||||
def _one(study: tuple[str, Path, float, float]) -> dict:
|
||||
key, path, age, mains_hz = study
|
||||
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=mains_hz)
|
||||
def _one(key: str, edf: bytes, age: float, mains_hz: float) -> dict:
|
||||
a = analyze(edf, age_months=age, mains_hz=mains_hz, keep_flat=True)
|
||||
return {
|
||||
"key": key,
|
||||
"age_months": age,
|
||||
@@ -45,10 +42,12 @@ def _one(study: tuple[str, Path, float, float]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def measure(studies, workers: int | None = None, mains_hz: float = MAINS_HZ) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order."""
|
||||
items = [(k, p, a, mains_hz) for k, p, a in studies]
|
||||
return execution.map(_one, items, phase="measuring_reference", workers=workers)
|
||||
def measure(studies, mains_hz: float) -> list[dict]:
|
||||
"""Each study's verdict and features, in listing order, each a task on the cluster
|
||||
(models.cluster)."""
|
||||
# each task carries its recording: workers see no local folder
|
||||
return cluster.run(_one, ((key, Path(path).read_bytes(), age, mains_hz)
|
||||
for key, path, age in studies)) # fmt: skip
|
||||
|
||||
|
||||
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
|
||||
|
||||
@@ -3,13 +3,12 @@
|
||||
Signals are `(samples, channels)` float64 arrays in µV with NaN in gaps (EDF+ `BAD*` notes). A
|
||||
filter runs on each gap-free run of rows separately; a run shorter than the filter's minimum
|
||||
stays NaN. The Butterworth filters are SciPy's (`butter` + `sosfiltfilt` with its default edge
|
||||
padding) and the periodograms MNE's (`psd_array_welch`, one Hann window per segment). The mains
|
||||
padding) and so are the periodograms (`periodogram`, a symmetric Hann window). The mains
|
||||
notch, the fixed-line search and the dominant peak are small rules of their own: no library
|
||||
computes the same thing (MNE's notch filters change the signal by microvolts).
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from mne.time_frequency import psd_array_welch
|
||||
from scipy import signal
|
||||
from scipy.ndimage import median_filter
|
||||
|
||||
@@ -85,9 +84,8 @@ def line_db(x: np.ndarray, fs: float, f0: float) -> np.ndarray:
|
||||
def periodograms(segments: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""One Hann periodogram (density, mean removed) of each segment along the last axis:
|
||||
`(..., n)` -> `(frequencies, (..., n // 2 + 1))`."""
|
||||
n = segments.shape[-1]
|
||||
power, f = psd_array_welch(segments, fs, n_fft=n, n_per_seg=n, window="hann", verbose="error")
|
||||
return f, power
|
||||
window = np.hanning(segments.shape[-1])
|
||||
return signal.periodogram(segments, fs, window=window, detrend="constant", axis=-1)
|
||||
|
||||
|
||||
def fixed_lines(x: np.ndarray, fs: float, f_max: float) -> list[float]:
|
||||
|
||||
+37
-82
@@ -1,9 +1,11 @@
|
||||
"""The state of each grid window (wake, drowsy, sleep) and, in sleep, its stage (N2, N3).
|
||||
"""The state of each grid window: wake, drowsy or sleep.
|
||||
|
||||
Notes: a note's state is the first whose words its text contains (lower case, accents removed,
|
||||
ñ kept); it lasts its duration or, without one, until the next note with a state or 60 s;
|
||||
pieces under 1 s are dropped and the stretches between notes are `unmarked`. Crying, movement,
|
||||
disconnection, photic stimulation and hyperventilation are masked.
|
||||
Notes: a note's state is the first whose cues its text holds (lower case, accents removed, ñ
|
||||
read as n): a cue is a word prefix (`hipervent`) or, for short ones, a whole word (`hv`, `n2`);
|
||||
a note that ends something (off, fin, end, stop) has none. It lasts its duration or, without
|
||||
one, until the next note with a state or 60 s; pieces under 1 s are dropped and the stretches
|
||||
between notes are `unmarked`. Crying, movement, disconnection, photic stimulation and
|
||||
hyperventilation are masked.
|
||||
|
||||
State: every 4 s window (2 s step) not touching a gap, the mask or a QC span gets five
|
||||
features from one Hann periodogram per channel: delta/beta, relative alpha, central sigma,
|
||||
@@ -11,13 +13,10 @@ muscle (20-40 / theta+alpha) and the prominence of the posterior peak. Each is s
|
||||
the HK1K reference (`data/hk1k_state.json`, the posterior rhythm's median a line on log age),
|
||||
and their weighted mean, clipped to ±6, is cut into wake / drowsy / sleep. A window with no
|
||||
posterior electrode leaves that feature out of the mean.
|
||||
|
||||
Stage: slow waves (0.5-4 Hz; a negative half-wave of 0.125-1 s followed by a positive one, 0.5-2
|
||||
s in all, 75-300 µV peak to peak) on F3, F4, Fz; a sleep window is N3 when they cover at least
|
||||
20 % of the 30 s centred on it, else N2.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
|
||||
@@ -27,18 +26,29 @@ from models.tea.eeg import signals
|
||||
from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
|
||||
REFERENCE = json.loads((Path(__file__).parent / "data" / "hk1k_state.json").read_text())
|
||||
NOTE_WORDS = {
|
||||
"photic": ("fotic", "photic", "flash", "estimulacion luminosa"),
|
||||
"hyperventilation": ("hv", "hipervent", "hypervent"),
|
||||
"eyes_open": ("ojos abiertos", "eyes open", "oa"),
|
||||
"eyes_closed": ("ojos cerrados", "eyes closed", "oc"),
|
||||
"sleep": ("sueno", "dormido", "sleep", "somnol", "husos", "spindle", "fase i", "fase ii",
|
||||
"n1", "n2", "n3"),
|
||||
"awake": ("despierta", "despierto", "arousal", "vigilia"),
|
||||
"crying": ("llanto", "llora", "cry"),
|
||||
"movement": ("movimiento", "movement", "artefacto de movimiento"),
|
||||
"feeding": ("come", "alimenta", "biberon", "lactancia"),
|
||||
} # fmt: skip
|
||||
# (state, its word prefixes, its whole words), in the order a note is matched
|
||||
NOTE_WORDS = [
|
||||
("photic", ("fotic", "photic", "flash", "estimulacion luminosa"), ()),
|
||||
("hyperventilation", ("hipervent", "hypervent"), ("hv",)),
|
||||
("eyes_open", ("ojos abiertos", "eyes open", "open eyes", "opens eyes", "abre ojos",
|
||||
"abre los ojos", "abrio ojos", "abrio los ojos", "apertura de ojos",
|
||||
"apertura ocular"), ("oa", "eo")),
|
||||
("eyes_closed", ("ojos cerrados", "eyes closed", "close eyes", "closes eyes", "eyes shut",
|
||||
"cierra ojos", "cierra los ojos", "cerro ojos", "cerro los ojos",
|
||||
"cierre de ojos", "cierre ocular"), ("oc", "ec")),
|
||||
("sleep", ("sueno", "dormido", "dormida", "sleep", "asleep", "somnol", "husos", "spindle"),
|
||||
("fase i", "fase ii", "fase iii", "n1", "n2", "n3")),
|
||||
("awake", ("despierta", "despierto", "arousal", "vigilia"), ()),
|
||||
("crying", ("llanto", "llora", "cry"), ()),
|
||||
("movement", ("movimiento", "movement", "artefacto de movimiento"), ()),
|
||||
("feeding", ("alimenta", "biberon", "lactancia"), ("come", "comer", "comio", "comiendo")),
|
||||
] # fmt: skip
|
||||
END = re.compile(r"\b(off|fin|end|stop)\b")
|
||||
PATTERNS = [
|
||||
(state, re.compile("|".join([*(rf"\b{re.escape(p)}" for p in prefixes),
|
||||
*(rf"\b{re.escape(w)}\b" for w in words)])))
|
||||
for state, prefixes, words in NOTE_WORDS
|
||||
] # fmt: skip
|
||||
EXCLUDED = ("crying", "movement", "disconnection")
|
||||
MASKED = (*EXCLUDED, "photic", "hyperventilation")
|
||||
STATES = np.array(["wake", "drowsy", "sleep"], dtype=object)
|
||||
@@ -46,18 +56,14 @@ BANDS = {"delta": (0.5, 4), "theta": (4, 8), "alpha": (8, 13), "sigma": (11, 16)
|
||||
"beta": (16, 30), "high": (20, 40)} # fmt: skip
|
||||
POSTERIOR = ("O1", "O2", "P3", "P4")
|
||||
CENTRAL = ("C3", "C4", "Cz")
|
||||
FRONTAL = ("F3", "F4", "Fz")
|
||||
|
||||
|
||||
def note_state(text: str) -> str | None:
|
||||
kept = str(text or "").replace("ñ", "\0").replace("Ñ", "\1")
|
||||
plain = "".join(
|
||||
c for c in unicodedata.normalize("NFD", kept) if unicodedata.category(c) != "Mn"
|
||||
)
|
||||
plain = plain.replace("\0", "ñ").replace("\1", "Ñ").lower().strip()
|
||||
return next(
|
||||
(state for state, words in NOTE_WORDS.items() if any(w in plain for w in words)), None
|
||||
)
|
||||
plain = "".join(c for c in unicodedata.normalize("NFD", str(text or ""))
|
||||
if unicodedata.category(c) != "Mn").lower().strip() # fmt: skip
|
||||
if END.search(plain):
|
||||
return None
|
||||
return next((state for state, pattern in PATTERNS if pattern.search(plain)), None)
|
||||
|
||||
|
||||
def note_intervals(annotations, duration_s: float) -> list[tuple[float, float, str]]:
|
||||
@@ -122,6 +128,7 @@ def _features(prep: Prepared, masked: np.ndarray) -> tuple[list[int], dict[str,
|
||||
if not starts:
|
||||
return [], {}
|
||||
f, power = signals.periodograms(np.stack([x[a : a + n].T for a in starts]), fs)
|
||||
power *= fs * (np.hanning(n) ** 2).sum() / 2 # the reference's scale (hk1k_state.json)
|
||||
band = {b: power[..., (f >= lo) & (f < hi)].sum(axis=-1) for b, (lo, hi) in BANDS.items()}
|
||||
total = np.maximum(band["delta"] + band["theta"] + band["alpha"] + band["beta"], 1e-12)
|
||||
central = [names.index(c) for c in CENTRAL if c in names] or list(range(min(3, len(names))))
|
||||
@@ -169,55 +176,3 @@ def states(prep: Prepared, intervals, age_months: float | None) -> np.ndarray:
|
||||
by_start = dict(zip(np.round(np.array(starts) / prep.fs, 2), labels, strict=True))
|
||||
out[:] = [by_start.get(round(float(s), 2), "") for s in prep.starts]
|
||||
return out
|
||||
|
||||
|
||||
def slow_waves(y: np.ndarray, fs: float) -> list[tuple[float, float]]:
|
||||
"""(onset s, duration s) of the slow waves of one channel."""
|
||||
y = signals.bandpass(np.asarray(y, float).reshape(-1, 1), fs, 0.5, 4.0)[:, 0]
|
||||
sign = np.sign(y)
|
||||
sign[sign == 0] = 1
|
||||
crossings = np.flatnonzero(np.diff(sign) != 0) + 1
|
||||
waves = []
|
||||
for j, c0 in enumerate(crossings):
|
||||
if not y[c0] < 0:
|
||||
continue
|
||||
if j + 2 >= len(crossings):
|
||||
break
|
||||
c1, c2 = crossings[j + 1], crossings[j + 2]
|
||||
negative, total = (c1 - c0) / fs, (c2 - c0) / fs
|
||||
if not (0.125 <= negative <= 1.0 and 0.5 <= total <= 2.0):
|
||||
continue
|
||||
p2p = float(np.max(y[c1:c2]) - float(np.min(y[c0:c1])))
|
||||
if 75.0 <= p2p <= 300.0:
|
||||
waves.append((round(c0 / fs, 3), round(total, 3)))
|
||||
return waves
|
||||
|
||||
|
||||
def _merged(waves: list[tuple[float, float]]) -> np.ndarray:
|
||||
if not waves:
|
||||
return np.empty((0, 2))
|
||||
a = np.array([onset for onset, _ in waves])
|
||||
b = a + np.array([length for _, length in waves])
|
||||
order = np.argsort(a)
|
||||
out = [[a[order[0]], b[order[0]]]]
|
||||
for i in order[1:]:
|
||||
if a[i] <= out[-1][1]:
|
||||
out[-1][1] = max(out[-1][1], b[i])
|
||||
else:
|
||||
out.append([a[i], b[i]])
|
||||
return np.array(out)
|
||||
|
||||
|
||||
def stages(prep: Prepared, labels: np.ndarray) -> np.ndarray:
|
||||
"""`N3` or `N2` per sleep window (`` elsewhere)."""
|
||||
waves = [w for c in prep.columns(FRONTAL) for w in slow_waves(prep.data([c])[:, 0], prep.fs)]
|
||||
covered = _merged(waves)
|
||||
out = np.full(len(prep.starts), "", dtype=object)
|
||||
for k, (start, label) in enumerate(zip(prep.starts, labels, strict=True)):
|
||||
if label != "sleep":
|
||||
continue
|
||||
t0, t1 = start + WINDOW_S / 2 - 15.0, start + WINDOW_S / 2 + 15.0
|
||||
overlap = np.clip(np.minimum(covered[:, 1], t1) - np.maximum(covered[:, 0], t0), 0, None)
|
||||
coverage = min(overlap.sum() / max(t1 - t0, 1e-9), 1.0) if len(covered) else 0.0
|
||||
out[k] = "N3" if round(coverage, 4) >= 0.20 else "N2"
|
||||
return out
|
||||
|
||||
+71
-29
@@ -4,7 +4,10 @@ the clean minutes of sleep.
|
||||
Gate: back-to-back 2 s windows of the 10-20 channels; a window is left out with a gap, in an
|
||||
excluded note (crying, movement, disconnection) or across two notes, with muscle (20-45 / 4-13 Hz
|
||||
power, fixed lines out, over 1.5) or frozen signal. Large transients are kept: a discharge is
|
||||
one. Each kept window adds its 2 s to the state of its midpoint.
|
||||
one. Each kept window adds its 2 s to the state of its midpoint; each left out adds its minutes
|
||||
to each reason (gap, state, mixed-states, muscle, frozen). A time takes the state of the grid
|
||||
window holding it or, outside every one, that of the nearest within 30 s (`transition` when
|
||||
the windows on either side differ).
|
||||
|
||||
Candidate (per channel, 1-70 Hz): a strict local maximum of |y| over 3 x the channel's MAD,
|
||||
20-200 ms wide at half height above the ±500 ms median (search bounded to ±150 ms), with both
|
||||
@@ -16,8 +19,9 @@ and width. A useful discharge has field and is not a vertex wave (asleep, max on
|
||||
slow after-wave over 3 MADs), a POSTS (asleep, O1/O2, positive, over 80 ms) or ocular (max on
|
||||
Fp1/Fp2/F7/F8 with no posterior channel in it, or opposite signs in a left/right pair).
|
||||
|
||||
Rate: useful discharges in sleep per sleep minute (rounded to 2) to 3 decimals; per electrode
|
||||
(its own maxima) and per zone (its electrodes' sum), per unrounded minute to 4 decimals.
|
||||
Rate: useful discharges in sleep per sleep minute to 3 decimals, and awake (wake or drowsy) per
|
||||
awake minute; per electrode (its own maxima) and per zone (its electrodes' sum, with how many
|
||||
it has), per minute to 4 decimals.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
@@ -33,12 +37,13 @@ from models.tea.eeg.spindles import ZONES
|
||||
|
||||
ELECTRODES = tuple(NEIGHBOURS)
|
||||
GATE_S = 2.0
|
||||
INHERIT_S = 30.0
|
||||
VERTEX = ("Cz", "Fz", "Pz")
|
||||
POSTS = ("O1", "O2")
|
||||
OCULAR = ("Fp1", "Fp2", "F7", "F8")
|
||||
POSTERIOR = {"P3", "P4", "Pz", "O1", "O2", "T5", "T6"}
|
||||
LEFT_RIGHT = (("Fp1", "Fp2"), ("F7", "F8"), ("F3", "F4"))
|
||||
ASLEEP = ("N2", "N3", "sleep")
|
||||
ASLEEP = ("sleep",)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -47,6 +52,31 @@ class Spikes:
|
||||
electrodes: dict[str, float]
|
||||
zones: dict[str, float]
|
||||
minutes: float # clean sleep minutes, the rate's exposure
|
||||
rejected: dict[str, float] # minutes the gate left out, by reason
|
||||
awake_rate: float
|
||||
awake_minutes: float
|
||||
zone_electrodes: dict[str, int] # per zone, its electrodes recorded
|
||||
|
||||
|
||||
def _states(labelled, duration_s: float) -> np.ndarray:
|
||||
"""The state every 0.5 s: its window's, or the nearest window's within INHERIT_S."""
|
||||
t = np.arange(0.0, duration_s, 0.5)
|
||||
out = np.full(len(t), "unlabelled", dtype=object)
|
||||
for t0, t1, label in labelled:
|
||||
out[(out == "unlabelled") & (t0 <= t) & (t < t1)] = label
|
||||
direct = np.flatnonzero(out != "unlabelled")
|
||||
if not len(direct):
|
||||
return out
|
||||
missing = np.flatnonzero((out == "unlabelled") & (t >= t[direct[0]]))
|
||||
j = np.searchsorted(direct, missing)
|
||||
before, after = direct[np.maximum(j - 1, 0)], direct[np.minimum(j, len(direct) - 1)]
|
||||
to_before = np.where(j > 0, t[missing] - t[before], np.inf)
|
||||
to_after = np.where(j < len(direct), t[after] - t[missing], np.inf)
|
||||
labels = np.where(to_before <= to_after, out[before], out[after])
|
||||
labels[(j > 0) & (j < len(direct)) & (out[before] != out[after])] = "transition"
|
||||
close = np.minimum(to_before, to_after) <= INHERIT_S
|
||||
out[missing[close]] = labels[close]
|
||||
return out
|
||||
|
||||
|
||||
def _mad(v: np.ndarray) -> float:
|
||||
@@ -56,29 +86,34 @@ def _mad(v: np.ndarray) -> float:
|
||||
return float(np.median(np.abs(v - np.median(v))) * 1.4826) or np.nan
|
||||
|
||||
|
||||
def _gate(x: np.ndarray, fs: float, intervals) -> list[tuple[float, float]]:
|
||||
"""(start, end) s of the 2 s windows the detector reads."""
|
||||
def _gate(x: np.ndarray, fs: float, intervals) -> tuple[list[tuple[float, float]], dict]:
|
||||
"""(start, end) s of the 2 s windows the detector reads, and the minutes left out by
|
||||
reason."""
|
||||
n = int(GATE_S * fs)
|
||||
top = min(45, fs / 2 * 0.9)
|
||||
lines = signals.fixed_lines(x, fs, f_max=top)
|
||||
f = np.fft.rfftfreq(n, 1 / fs)
|
||||
taper = np.hanning(n)[:, None]
|
||||
kept = []
|
||||
kept, rejected = [], {}
|
||||
for a in range(0, len(x) - n + 1, n):
|
||||
t0, t1 = a / fs, a / fs + GATE_S
|
||||
state, mixed = window_note(t0, t1, intervals)
|
||||
segment = x[a : a + n]
|
||||
if not np.isfinite(segment).all() or state in EXCLUDED or mixed:
|
||||
continue
|
||||
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
|
||||
power = power.mean(axis=1)
|
||||
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
||||
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
||||
muscle = float(high / max(low, 1e-12))
|
||||
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
|
||||
if not (muscle > 1.5 or frozen > 0.5):
|
||||
reasons = ["gap"]
|
||||
if np.isfinite(segment).all():
|
||||
power = np.abs(np.fft.rfft((segment - segment.mean(axis=0)) * taper, axis=0)) ** 2
|
||||
power = power.mean(axis=1)
|
||||
high = signals.band_power(f, power, 20, top, lines, include_hi=True)
|
||||
low = signals.band_power(f, power, 4, 13, lines, include_hi=True)
|
||||
frozen = float(np.mean(np.abs(np.diff(segment, axis=0)) < 1e-9))
|
||||
failed = {"state": state in EXCLUDED, "mixed-states": mixed,
|
||||
"muscle": high / max(low, 1e-12) > 1.5, "frozen": frozen > 0.5} # fmt: skip
|
||||
reasons = [reason for reason, fails in failed.items() if fails]
|
||||
if not reasons:
|
||||
kept.append((round(t0, 2), round(t1, 2)))
|
||||
return kept
|
||||
for reason in reasons:
|
||||
rejected[reason] = rejected.get(reason, 0.0) + GATE_S / 60.0
|
||||
return kept, {reason: round(minutes, 4) for reason, minutes in rejected.items()}
|
||||
|
||||
|
||||
def _flanks(y: np.ndarray, i: int, fs: float) -> tuple[float, float]:
|
||||
@@ -189,20 +224,23 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
||||
if label in ("wake", "drowsy", "sleep")
|
||||
]
|
||||
|
||||
grid = _states(labelled, prep.duration_s)
|
||||
|
||||
def state_at(t: np.ndarray) -> np.ndarray:
|
||||
"""The state of the first labelled window holding each time."""
|
||||
out, open_ = np.full(len(t), "unlabelled", dtype=object), np.ones(len(t), bool)
|
||||
for t0, t1, label in labelled:
|
||||
hit = open_ & (t0 <= t) & (t < t1)
|
||||
out[hit], open_ = label, open_ & ~hit
|
||||
out = np.full(len(t), "unlabelled", dtype=object)
|
||||
index = np.floor(t / 0.5).astype(int)
|
||||
inside = (t >= 0) & (index < len(grid))
|
||||
out[inside] = grid[index[inside]]
|
||||
return out
|
||||
|
||||
gate = _gate(x, fs, intervals)
|
||||
gate, rejected = _gate(x, fs, intervals)
|
||||
minutes = {}
|
||||
middles = state_at(np.array([(t0 + t1) / 2.0 for t0, t1 in gate]))
|
||||
for (t0, t1), state in zip(gate, middles, strict=True):
|
||||
minutes[state] = minutes.get(state, 0.0) + (t1 - t0) / 60.0
|
||||
sleep_minutes = float(sum(minutes.get(s, 0.0) for s in ("sleep",)))
|
||||
sleep_minutes = float(minutes.get("sleep", 0.0))
|
||||
awake_minutes = float(minutes.get("wake", 0.0) + minutes.get("drowsy", 0.0))
|
||||
awake = 0
|
||||
counts = dict.fromkeys(channels, 0)
|
||||
candidates = [row for j, c in enumerate(channels) for row in _candidates(x[:, j], fs, c)]
|
||||
if candidates and gate:
|
||||
@@ -215,18 +253,22 @@ def detect(prep: Prepared, states: np.ndarray, intervals) -> Spikes | None:
|
||||
if len(c):
|
||||
c = c.assign(field=_field(c), state=state_at(c.t.to_numpy()))
|
||||
found = _merge(c)
|
||||
found = found[found.useful & (found.field > 0) & (found.state == "sleep")]
|
||||
found = found[found.useful & (found.field > 0)]
|
||||
awake = int(found.state.isin(("wake", "drowsy")).sum())
|
||||
found = found[found.state == "sleep"]
|
||||
for channel, n in found.channel.value_counts().items():
|
||||
counts[channel] = int(n)
|
||||
rounded = round(sleep_minutes, 2)
|
||||
rate = round(sum(counts.values()) / rounded, 3) if rounded > 0 else np.nan
|
||||
rate = round(sum(counts.values()) / sleep_minutes, 3) if sleep_minutes > 0 else np.nan
|
||||
awake_rate = round(awake / awake_minutes, 3) if awake_minutes > 0 else np.nan
|
||||
electrodes = {
|
||||
e: round(counts[e] / sleep_minutes, 4) if sleep_minutes > 0 and e in counts else np.nan
|
||||
for e in ELECTRODES
|
||||
}
|
||||
zones = {}
|
||||
zones, zone_electrodes = {}, {}
|
||||
for zone, members in ZONES.items():
|
||||
present = [e for e in members if e in counts]
|
||||
zone_electrodes[zone] = len(present)
|
||||
total = sum(counts[e] for e in present)
|
||||
zones[zone] = round(total / sleep_minutes, 4) if present and sleep_minutes > 0 else np.nan
|
||||
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4))
|
||||
return Spikes(rate, electrodes, zones, round(sleep_minutes, 4), rejected, awake_rate,
|
||||
round(awake_minutes, 4), zone_electrodes) # fmt: skip
|
||||
|
||||
+23
-15
@@ -1,10 +1,10 @@
|
||||
"""Sleep spindles of one stage (N2 or N3): their density, per zone, and the enhancement of the
|
||||
"""Sleep spindles (NREM sleep, unstaged): their density, per zone, and the enhancement of the
|
||||
sigma envelope per electrode.
|
||||
|
||||
Detection runs on the frontal, central and parietal electrodes over the windows of the stage
|
||||
(only when they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
|
||||
Detection runs on the frontal, central and parietal electrodes over the sleep windows (only when
|
||||
they add up to a minute). The 11-16 Hz envelope (|Hilbert|, 0.2 s moving mean) sets
|
||||
per channel a core threshold, max(p95, 3 x median), and an extent one, max(p70, 1.6 x median),
|
||||
from the stage's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
|
||||
from the sleep's own samples; a spindle is an extent stretch with a core sample, 0.5-3 s (longer
|
||||
ones cut in 3 s pieces), whose sigma power stands 1.5 x over the 5-30 Hz flanks, whose
|
||||
instantaneous frequency stays in 10-17 Hz half the time with an 11-16 Hz median, and whose
|
||||
envelope peaks 3 x over the median.
|
||||
@@ -12,7 +12,8 @@ envelope peaks 3 x over the median.
|
||||
Density: spindles per minute and searched channel (NaN when none were found); per zone, the
|
||||
zone's spindles per minute and searched electrode. Enhancement: spindles overlapping in time are
|
||||
one episode; per electrode, the median over episodes of the unsmoothed envelope's maximum within
|
||||
the episode ± 0.25 s, over the median envelope in sleep.
|
||||
the episode ± 0.25 s, over the median envelope in sleep. A posterior rhythm within 1.5 Hz of the
|
||||
sigma band (`near_sigma`) is noted: its alpha can pass for spindles.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
@@ -25,6 +26,8 @@ from models.tea.eeg.preprocess import WINDOW_S, Prepared
|
||||
|
||||
CHANNELS = ("Fp1", "Fp2", "F3", "F4", "Fz", "F7", "F8", "C3", "C4", "Cz", "P3", "P4", "Pz")
|
||||
SIGMA = (11.0, 16.0)
|
||||
RHYTHM_MARGIN_HZ = 1.5
|
||||
MIN_MINUTES = 1
|
||||
ZONES = {
|
||||
"frontal_left": ("Fp1", "F3", "F7"),
|
||||
"frontal_right": ("Fp2", "F4", "F8"),
|
||||
@@ -41,7 +44,12 @@ ZONES = {
|
||||
class Spindles:
|
||||
events: list[tuple[float, float, str]] # (onset s, duration s, channel)
|
||||
minutes: float
|
||||
channels: list[str] # the channels searched (none when under a minute of the stage)
|
||||
channels: list[str] # the channels searched (none when under a minute of sleep)
|
||||
rhythm_near_sigma: bool = False
|
||||
|
||||
|
||||
def near_sigma(posterior_rhythm: float) -> bool:
|
||||
return bool(posterior_rhythm > SIGMA[0] - RHYTHM_MARGIN_HZ)
|
||||
|
||||
|
||||
def _envelope(x: np.ndarray, fs: float) -> tuple[np.ndarray, np.ndarray]:
|
||||
@@ -92,31 +100,31 @@ def _is_spindle(x: np.ndarray, y: np.ndarray, fs: float) -> bool:
|
||||
return SIGMA[0] <= float(np.median(in_band)) <= SIGMA[1]
|
||||
|
||||
|
||||
def detect(prep: Prepared, staged: np.ndarray, stage: str) -> Spindles:
|
||||
"""The spindles in the grid windows staged `stage`."""
|
||||
def detect(prep: Prepared, states: np.ndarray) -> Spindles:
|
||||
"""The spindles in the grid windows in sleep."""
|
||||
fs, n = prep.fs, int(WINDOW_S * prep.fs)
|
||||
asleep = np.zeros(len(prep.x), bool)
|
||||
for start, s in zip(prep.starts, staged, strict=True):
|
||||
if s == stage:
|
||||
for start, state in zip(prep.starts, states, strict=True):
|
||||
if state == "sleep":
|
||||
a = int(round(float(start) * fs))
|
||||
asleep[a : a + n] = True
|
||||
minutes = float(asleep.sum() / fs / 60)
|
||||
names = prep.columns([c for c in prep.names if c in CHANNELS])
|
||||
if minutes < 1 or not names:
|
||||
if minutes < MIN_MINUTES or not names:
|
||||
return Spindles([], minutes, [])
|
||||
x = prep.data(names)
|
||||
y, envelope = _envelope(x, fs)
|
||||
events = []
|
||||
for i, name in enumerate(names):
|
||||
in_stage = np.where(asleep, envelope[:, i], np.nan)
|
||||
values = in_stage[np.isfinite(in_stage)]
|
||||
in_sleep = np.where(asleep, envelope[:, i], np.nan)
|
||||
values = in_sleep[np.isfinite(in_sleep)]
|
||||
if len(values) < fs * 30:
|
||||
continue
|
||||
median = float(np.median(values)) or 1e-9
|
||||
core = max(float(np.percentile(values, 95)), 3 * median)
|
||||
extent = max(float(np.percentile(values, 70)), 1.6 * median)
|
||||
finite = np.isfinite(in_stage)
|
||||
for a, b in _segments(finite & (in_stage > core), finite & (in_stage > extent), fs):
|
||||
finite = np.isfinite(in_sleep)
|
||||
for a, b in _segments(finite & (in_sleep > core), finite & (in_sleep > extent), fs):
|
||||
if _is_spindle(x[a:b, i], y[a:b, i], fs) and np.nanmax(envelope[a:b, i]) / median >= 3:
|
||||
events.append((round(a / fs, 3), round((b - a) / fs, 3), name))
|
||||
return Spindles(events, minutes, names)
|
||||
|
||||
+157
-75
@@ -1,34 +1,34 @@
|
||||
"""TEA's jobs: the analysis of the hospital's EEGs, and its models, the seven age curves
|
||||
(models.tea.eeg.curves), trained on the reference cohort of TEA_REFERENCE_DIR (its EDFs and
|
||||
its ages table, TEA_REFERENCE_AGES) and scoring every analysed EEG against the child's age.
|
||||
|
||||
Measuring the reference cohort takes long (each study is analysed as a hospital EEG), so its
|
||||
features are kept in TEA_REFERENCE_CACHE, a JSON file named by the cohort's hash: a file set
|
||||
or ages table that changes is measured again."""
|
||||
(models.tea.eeg.curves), trained on the site's own reference group (the valid EEGs of the
|
||||
children whose diagnosis ruled TEA out, persistance.eeg.ruled_out) and scoring every
|
||||
analysed EEG against the child's age. The math is the old platform's, proved on its HK1K
|
||||
cohort by models/tests/test_eeg.py."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pandas as pd
|
||||
|
||||
from models import execution
|
||||
from core.tea import ados2
|
||||
from core.tea import association as relation
|
||||
from models import cluster
|
||||
from models.jobs import EmptyCohort
|
||||
from models.tea import association
|
||||
from models.tea.eeg import analysis, curves, reference
|
||||
from persistance import eeg, registry, silver
|
||||
|
||||
MODELS = curves.SCENARIOS
|
||||
CURVES = curves.SCENARIOS # what the tea_eeg job scores; MODELS may grow in Phase 2
|
||||
CURVES = curves.SCENARIOS
|
||||
ASSOCIATION = "eeg-ados2" # trained on the champion curves' z: after they are promoted
|
||||
MODELS = [*CURVES, ASSOCIATION]
|
||||
GOLD = "tea_eeg_metrics" # what scoring rebuilds (the other domains: <domain>_risk)
|
||||
GOLD_SELECT = ["tea_eeg_analyses+", "tea_eeg_metrics+"] # what a rebuild of TEA's gold selects
|
||||
|
||||
|
||||
class Baseline(mlflow.pyfunc.PythonModel):
|
||||
"""An age curve as MLflow serves it: (value, age_months, exposure) rows in, their z,
|
||||
outside, p5, median and p95 out, for one of its features."""
|
||||
"""An age curve as MLflow serves it: (value, age_months, exposure, electrodes) rows in,
|
||||
their z, outside, p5, median, p95 and reason out, for one of its features."""
|
||||
|
||||
def __init__(self, scenario: str, baseline: dict):
|
||||
self.scenario, self.baseline = scenario, baseline
|
||||
@@ -37,46 +37,23 @@ class Baseline(mlflow.pyfunc.PythonModel):
|
||||
feature = (params or {}).get("feature", "value")
|
||||
rows = model_input.to_dict("records")
|
||||
return pd.DataFrame([curves.score(self.baseline[feature], r.get("value"),
|
||||
r.get("age_months"), r.get("exposure"))
|
||||
r.get("age_months"), r.get("exposure"),
|
||||
r.get("electrodes"))
|
||||
for r in rows]) # fmt: skip
|
||||
|
||||
|
||||
def _analyze(item: tuple[str, date | None, bytes]) -> tuple[str, analysis.Analysis]:
|
||||
edf, birth, signal = item
|
||||
return edf, analysis.analyze(signal, birth)
|
||||
|
||||
|
||||
def analyze(scope: eeg.Scope | None = None, *, rebuild_gold: bool = True) -> int:
|
||||
"""The EEGs in scope (default: those not analysed yet), analysed in the ambient
|
||||
execution; then, unless told not to, gold's TEA tables are rebuilt. Bronze is written
|
||||
once, after the last study, so a cancelled run leaves it as it was."""
|
||||
rows = eeg.select(scope or eeg.Scope())
|
||||
items = ((r["edf"], r["birth_date"], eeg.signal(r["edf"])) for r in rows) # lazy: bytes travel
|
||||
found = dict(execution.map(_analyze, items, phase="analyzing", total=len(rows)))
|
||||
def analyze() -> int:
|
||||
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
|
||||
pending = eeg.pending()
|
||||
done = cluster.run(
|
||||
analysis.analyze, ((eeg.signal(r["edf"]), r["birth_date"]) for r in pending)
|
||||
) # one task per EEG
|
||||
found = dict(zip((r["edf"] for r in pending), done, strict=True))
|
||||
eeg.save_analyses(found)
|
||||
if rebuild_gold:
|
||||
silver.build(GOLD_SELECT)
|
||||
silver.build(["tea_eeg_analyses+", "tea_eeg_metrics+"])
|
||||
return len(found)
|
||||
|
||||
|
||||
def _reference() -> tuple[str, list[dict]]:
|
||||
"""The reference cohort's hash and each study's verdict and features, cached."""
|
||||
folder = Path(os.environ["TEA_REFERENCE_DIR"])
|
||||
ages = Path(os.environ.get("TEA_REFERENCE_AGES", folder / "anon_codex_age_sex.csv"))
|
||||
studies = reference.listing(folder, ages)
|
||||
digest = hashlib.sha256("\n".join(f"{p.name}|{a}" for _, p, a in studies).encode()).hexdigest()
|
||||
cache = os.environ.get("TEA_REFERENCE_CACHE")
|
||||
path = Path(cache) / f"{reference.NAME}-{digest[:16]}.json" if cache else None
|
||||
if path and path.exists():
|
||||
return digest, json.loads(path.read_text())
|
||||
measured = reference.measure(studies)
|
||||
measured = [{**m, "key": str(m["key"])} for m in measured]
|
||||
if path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(measured))
|
||||
return digest, measured
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Jobs:
|
||||
"""The domain's model jobs (models.definitions): every curve is routine."""
|
||||
@@ -84,6 +61,9 @@ class Jobs:
|
||||
def routine(self) -> list[str]:
|
||||
return list(MODELS)
|
||||
|
||||
def scored(self) -> list[str]:
|
||||
return list(MODELS) # the curves, then the association on their scores
|
||||
|
||||
|
||||
JOBS = Jobs()
|
||||
|
||||
@@ -93,40 +73,43 @@ def registered(name: str) -> str:
|
||||
|
||||
|
||||
def train(name: str, as_of: date | None = None) -> int:
|
||||
"""A new version of one age curve, trained on the reference cohort's valid studies,
|
||||
with its two reports: the cohort it learned from, and its centile curves."""
|
||||
digest, measured = _reference()
|
||||
if name == ASSOCIATION:
|
||||
return _train_association(as_of)
|
||||
return _train_curve(name, as_of)
|
||||
|
||||
|
||||
def _train_curve(name: str, as_of: date | None = None) -> int:
|
||||
"""A new version of one age curve, trained on the site's reference group as known on
|
||||
`as_of` (today by default), with its two reports: the group it learned from, and its
|
||||
centile curves."""
|
||||
day = as_of or date.today()
|
||||
measured = eeg.ruled_out(day)
|
||||
if not measured:
|
||||
raise EmptyCohort(f"{name}: no valid EEG of a child with TEA ruled out by {day}")
|
||||
digest = hashlib.sha256("\n".join(m["key"] for m in measured).encode()).hexdigest()
|
||||
table = reference.tables(measured)[name]
|
||||
baseline = curves.train(table, name)
|
||||
valid = [m for m in measured if m["valid"] and m["error"] is None]
|
||||
ages = [m["age_months"] for m in measured]
|
||||
technical = {
|
||||
"model": name, "method": "age curves (weighted centiles on log age)",
|
||||
"cohort": reference.NAME, "cohort_sha256": digest, "studies": len(measured),
|
||||
"valid_studies": len(valid),
|
||||
"ages_months": [min(m["age_months"] for m in valid), max(m["age_months"] for m in valid)],
|
||||
"features": sorted(baseline),
|
||||
"cohort": "site: children with TEA ruled out", "cohort_sha256": digest, "as_of": str(day),
|
||||
"studies": len(measured), "valid_studies": len(measured),
|
||||
"ages_months": [min(ages), max(ages)], "features": sorted(baseline),
|
||||
} # fmt: skip
|
||||
interpretability = {"model": name, "kind": "age_curves", "curves": baseline}
|
||||
metrics = {"n_reference": float(len(valid)), "features": float(len(baseline))}
|
||||
params = {"cohort": reference.NAME, "cohort_sha256": digest}
|
||||
metrics = {"n_reference": float(len(measured)), "features": float(len(baseline))}
|
||||
params = {"cohort": "ruled_out", "cohort_sha256": digest, "as_of": str(day)}
|
||||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return registry.register(registered(name), Baseline(name, baseline), params, metrics, reports)
|
||||
|
||||
|
||||
def score_curves() -> dict[str, int | None]:
|
||||
"""The version of each age curve's champion that scored, None without a champion."""
|
||||
return {name: score(name) for name in CURVES}
|
||||
|
||||
|
||||
def relate() -> int | None:
|
||||
"""The ADOS-2 association: scores every analysed EEG with the `ados2_association`
|
||||
champion (Phase 2). Returns the version that scored, None when the model has no champion.
|
||||
It writes bronze only (ASSOCIATION_SCORES); the gold rebuild is the job's last step, not
|
||||
this one's. Until Phase 2 exists it does nothing."""
|
||||
return None
|
||||
|
||||
|
||||
def score(name: str) -> int | None:
|
||||
if name == ASSOCIATION:
|
||||
return _score_association()
|
||||
return _score_curve(name)
|
||||
|
||||
|
||||
def _score_curve(name: str) -> int | None:
|
||||
"""The champion curve's scores of every analysed EEG: the metric's value, and each
|
||||
electrode and zone it measures; None without a champion."""
|
||||
found = registry.champion(registered(name))
|
||||
@@ -134,15 +117,14 @@ def score(name: str) -> int | None:
|
||||
return None
|
||||
version, model = found
|
||||
baseline = model.unwrap_python_model().baseline
|
||||
scenario, label = MODELS[name], f"{registered(name)}/{version}"
|
||||
scenario, label = CURVES[name], f"{registered(name)}/{version}"
|
||||
rows = []
|
||||
for one in eeg.analysed():
|
||||
metric = next((m for m in one["metrics"] if m["code"] == scenario.metric), None)
|
||||
if metric is None:
|
||||
continue
|
||||
exposure = (
|
||||
(one["features"].get(name) or {}).get(curves.EXPOSURE) if scenario.counts else None
|
||||
)
|
||||
features = one["features"].get(name) or {}
|
||||
exposure = features.get(curves.EXPOSURE) if scenario.counts else None
|
||||
for part in scenario.parts:
|
||||
sites = {"": metric["value"]} if part == "value" else metric[part]
|
||||
prefix = "" if part == "value" else curves.PREFIX[part]
|
||||
@@ -150,9 +132,109 @@ def score(name: str) -> int | None:
|
||||
feature = "value" if part == "value" else prefix + site
|
||||
if feature not in baseline:
|
||||
continue
|
||||
s = curves.score(baseline[feature], value, one["age_months"], exposure)
|
||||
electrodes = features.get(f"zone_electrodes_{site}") if part == "zones" else None
|
||||
s = curves.score(baseline[feature], value, one["age_months"], exposure, electrodes)
|
||||
rows.append({"key": f"{one['edf']}|{name}|{part}|{site}", "edf": one["edf"],
|
||||
"scenario": name, "model": label, "metric": scenario.metric,
|
||||
"part": part, "site": site or None, **s}) # fmt: skip
|
||||
eeg.save_scores(name, rows)
|
||||
return version
|
||||
|
||||
|
||||
class Association(mlflow.pyfunc.PythonModel):
|
||||
"""The fitted association as MLflow serves it: a cohort in, each child's probabilities."""
|
||||
|
||||
def __init__(self, fitted: dict):
|
||||
self.fitted = fitted
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
|
||||
return pd.DataFrame(association.score(self.fitted, model_input))
|
||||
|
||||
|
||||
def association_cohort(as_of: date | None = None) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""(fit, scored): every valid EEG of a child with an ADOS-2 (known by `as_of`), her age,
|
||||
module, items, CSS, the z of each biomarker and whether it shows spikes; fitted on each
|
||||
child's first EEG with any, every EEG scored (her own refitted without her)."""
|
||||
day = str(as_of) if as_of else None
|
||||
rows = []
|
||||
for r in eeg.association_inputs(relation.BIOMARKERS):
|
||||
a = r["ados2"]
|
||||
evaluated = str(a["evaluation_date"])[:10] if a.get("evaluation_date") else None
|
||||
if day and (r["study_date"] > day or (evaluated and evaluated > day)):
|
||||
continue
|
||||
css = None
|
||||
if evaluated and r["birth_date"]:
|
||||
row = {**a, "evaluation_date": date.fromisoformat(evaluated)}
|
||||
scored = ados2.score(row, date.fromisoformat(r["birth_date"]))
|
||||
css = scored and scored.css
|
||||
spikes = json.loads(r["features"] or "{}").get("eeg-spikes", {})
|
||||
rows.append({"key": r["edf"], "person": r["person_id"], "age_months": r["age_months"],
|
||||
"module": a.get("module"), "css": css,
|
||||
**{n: a.get(n) for n, _ in relation.ITEMS.values()},
|
||||
**{k: v for k, v in r.items() if k.startswith("z_")},
|
||||
**association.spikes_any(spikes)}) # fmt: skip
|
||||
scored = pd.DataFrame(rows)
|
||||
if scored.empty:
|
||||
return scored, scored
|
||||
predictors = [c for c in scored.columns if c.startswith(("z_", "spikes_any_"))]
|
||||
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
|
||||
return scored[with_z].drop_duplicates("person").reset_index(drop=True), scored
|
||||
|
||||
|
||||
def _train_association(as_of: date | None = None) -> int:
|
||||
"""A new version of the association, fitted on the site's children, with its reports:
|
||||
the cohort and pairs it estimated, and the pairs themselves."""
|
||||
fit, _ = association_cohort(as_of)
|
||||
if fit.empty:
|
||||
raise EmptyCohort(f"{ASSOCIATION}: no child with an ADOS-2 and a scored EEG")
|
||||
fitted = association.fit(fit)
|
||||
pairs = association.associations(fitted)
|
||||
estimated = [p for p in pairs if p["odds_ratio"] is not None]
|
||||
technical = {
|
||||
"model": ASSOCIATION, "version": relation.VERSION,
|
||||
"method": "Firth logistic (items) / cumulative logit (CSS, and composites with few "
|
||||
"events), adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg "
|
||||
"q within each biomarker; each child scored leave-one-out",
|
||||
"cohort": "site: children with an ADOS-2 and a valid EEG",
|
||||
"as_of": str(as_of or date.today()),
|
||||
"children": int(fitted["n"]), "level": fitted["level"], "pairs": len(pairs),
|
||||
"estimated": len(estimated), "clear": sum(1 for p in estimated if (p["q"] or 1) < 0.05),
|
||||
} # fmt: skip
|
||||
interpretability = {"model": ASSOCIATION, "kind": "associations", "level": fitted["level"],
|
||||
"children": int(fitted["n"]), "rows": pairs} # fmt: skip
|
||||
metrics = {"children": float(fitted["n"]), "estimated": float(len(estimated))}
|
||||
params = {"level": fitted["level"], "as_of": str(as_of or date.today())}
|
||||
reports = {"technical_validation": technical, "interpretability": interpretability}
|
||||
return registry.register(registered(ASSOCIATION), Association(fitted), params, metrics, reports)
|
||||
|
||||
|
||||
def _score_association() -> int | None:
|
||||
"""The champion association's probabilities for every scored EEG; None without one."""
|
||||
found = registry.champion(registered(ASSOCIATION))
|
||||
if found is None:
|
||||
return None
|
||||
version, model = found
|
||||
fitted = model.unwrap_python_model().fitted
|
||||
label = f"{registered(ASSOCIATION)}/{version}"
|
||||
_, scored = association_cohort()
|
||||
kept = ("biomarker", "zone", "kind", "outcome_code", "event", "n", "odds_ratio", "ci_low",
|
||||
"ci_high", "p", "q", "sens_odds_ratio", "same_direction", "reason") # fmt: skip
|
||||
pairs = [{**{k: p[k] for k in kept}, "model": label,
|
||||
"key": f"{label}|{p['biomarker']}|{p['zone']}|{p['outcome_code']}",
|
||||
"metric": relation.BIOMARKERS[p["biomarker"]], "principal": p["model"],
|
||||
"sensitivity": p["sens_model"]}
|
||||
for p in association.associations(fitted) if p["odds_ratio"] is not None] # fmt: skip
|
||||
observed: dict[str, dict] = {} # what her ADOS-2 shows: an item's score, how many of a
|
||||
if not scored.empty: # composite's items are altered, or the CSS
|
||||
for r in fitted["rows"]:
|
||||
level = association.outcome(scored, r)[1].tolist()
|
||||
observed[relation.outcome_code(r)] = dict(zip(scored["key"], level, strict=True))
|
||||
scores = []
|
||||
for one in association.score(fitted, scored) if not scored.empty else []:
|
||||
seen = observed.get(one["outcome_code"], {}).get(one["key"])
|
||||
pair = f"{one['biomarker']}|{one['zone']}|{one['outcome_code']}"
|
||||
shown = None if seen is None or seen != seen else float(seen)
|
||||
scores.append({**one, "edf": one["key"], "model": label, "key": f"{one['key']}|{pair}",
|
||||
"observed": shown}) # fmt: skip
|
||||
eeg.save_association(label, pairs, scores)
|
||||
return version
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
"""The two models the EEG–ADOS-2 association fits (models.tea.association), adjusted for
|
||||
age and module (core.tea.association.ADJUST):
|
||||
|
||||
- Firth's penalised logistic regression of an event (its odds ratio, a 95 % profile-
|
||||
likelihood interval and a likelihood-ratio p); its probabilities with the FLIC intercept, so
|
||||
they average to the observed rate;
|
||||
- the cumulative logit of a level, P(level >= high) its probability.
|
||||
Each fit keeps a scoring `state`: what `probability` needs, for any child and the reference
|
||||
child (z = 0, the cohort's mean age, the commonest module)."""
|
||||
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import optimize, stats
|
||||
from scipy.special import expit
|
||||
|
||||
from core.tea.association import ADJUST
|
||||
|
||||
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
|
||||
MIN_ROWS = 8
|
||||
TOO_FEW = "too few data or no variation"
|
||||
SEPARATION = "does not converge (separation)"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Design:
|
||||
"""The columns of one model: intercept, the predictor, the numeric adjustments centred on
|
||||
the cohort's mean and each categorical one against its commonest level."""
|
||||
|
||||
predictor: str
|
||||
numeric: dict[str, float] = field(default_factory=dict)
|
||||
categorical: dict[str, list[str]] = field(default_factory=dict)
|
||||
reference: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
@classmethod
|
||||
def of(cls, t: pd.DataFrame, predictor: str) -> "Design":
|
||||
d = cls(predictor)
|
||||
for a in (a for a in ADJUST if a in t):
|
||||
v = t[a]
|
||||
if pd.api.types.is_numeric_dtype(v):
|
||||
if v.astype(float).std() > 0:
|
||||
d.numeric[a] = float(v.astype(float).mean())
|
||||
continue
|
||||
commonest = v.value_counts().index[0]
|
||||
levels = [x for x in sorted(set(v) - {commonest}) if 0 < (v == x).sum() < len(v)]
|
||||
if levels:
|
||||
d.categorical[a], d.reference[a] = [str(x) for x in levels], str(commonest)
|
||||
return d
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return [
|
||||
"intercept",
|
||||
self.predictor,
|
||||
*self.numeric,
|
||||
*(f"{a}={x}" for a, levels in self.categorical.items() for x in levels),
|
||||
]
|
||||
|
||||
def matrix(self, t: pd.DataFrame) -> np.ndarray:
|
||||
cols = [np.ones(len(t)), t[self.predictor].to_numpy(float)]
|
||||
cols += [t[a].to_numpy(float) - mean for a, mean in self.numeric.items()]
|
||||
known = np.ones(len(t), bool)
|
||||
for a, levels in self.categorical.items():
|
||||
v = t[a].astype(str)
|
||||
cols += [(v == x).to_numpy(float) for x in levels]
|
||||
known &= v.isin({self.reference[a], *levels}).to_numpy() & t[a].notna().to_numpy()
|
||||
X = np.column_stack(cols)
|
||||
X[~known] = np.nan
|
||||
return X
|
||||
|
||||
def state(self) -> dict:
|
||||
return {
|
||||
"predictor": self.predictor,
|
||||
"numeric": self.numeric,
|
||||
"categorical": self.categorical,
|
||||
"reference": self.reference,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_state(cls, s: dict) -> "Design":
|
||||
return cls(
|
||||
s["predictor"],
|
||||
dict(s["numeric"]),
|
||||
{k: list(v) for k, v in s["categorical"].items()},
|
||||
dict(s["reference"]),
|
||||
)
|
||||
|
||||
|
||||
# Firth: the log-likelihood penalised by half the log-determinant of the information.
|
||||
def _penalised(b, X, y) -> float:
|
||||
eta = X @ b
|
||||
w = expit(eta) * (1 - expit(eta))
|
||||
sign, logdet = np.linalg.slogdet(X.T @ (X * w[:, None]))
|
||||
return -np.inf if sign <= 0 else float(np.sum(y * eta - np.logaddexp(0, eta)) + logdet / 2)
|
||||
|
||||
|
||||
def _gradient(b, X, y):
|
||||
"""The penalised score and the information at `b`."""
|
||||
p = expit(X @ b)
|
||||
w = p * (1 - p)
|
||||
info = X.T @ (X * w[:, None])
|
||||
leverage = np.einsum("ij,jk,ik->i", X, np.linalg.inv(info), X) * w
|
||||
return X.T @ (y - p + leverage * (0.5 - p)), info
|
||||
|
||||
|
||||
def _newton(X, y, max_iter=200, tol=1e-10):
|
||||
"""Newton–Raphson on the penalised likelihood, halving a step that lowers it."""
|
||||
b = np.zeros(X.shape[1])
|
||||
best = _penalised(b, X, y)
|
||||
for _ in range(max_iter):
|
||||
score, info = _gradient(b, X, y)
|
||||
step, t = np.linalg.solve(info, score), 1.0
|
||||
while t > 1e-8:
|
||||
trial = _penalised(b + t * step, X, y)
|
||||
if trial >= best - 1e-12:
|
||||
break
|
||||
t /= 2
|
||||
b, best = b + t * step, trial
|
||||
if np.max(np.abs(t * step)) < tol:
|
||||
break
|
||||
return b, best
|
||||
|
||||
|
||||
def _firth_profile(value, j, X, y, start) -> float:
|
||||
"""The penalised likelihood maximised with coefficient `j` held at `value`."""
|
||||
free = [k for k in range(X.shape[1]) if k != j]
|
||||
|
||||
def negative(bf):
|
||||
b = np.empty(X.shape[1])
|
||||
b[free], b[j] = bf, value
|
||||
v = _penalised(b, X, y)
|
||||
if not np.isfinite(v):
|
||||
return 1e10, np.zeros(len(free))
|
||||
return -v, -_gradient(b, X, y)[0][free]
|
||||
|
||||
return -float(optimize.minimize(negative, start[free], jac=True, method="BFGS").fun)
|
||||
|
||||
|
||||
def _interval(profile, centre, maximum, scale) -> tuple[float, float]:
|
||||
"""Where twice the profile's drop from its maximum crosses chi²(1)'s 95th percentile, on
|
||||
each side of `centre`, searched in steps of `scale` (infinite if never)."""
|
||||
drop = lambda v: 2 * (maximum - profile(v)) - CHI2_95 # noqa: E731
|
||||
limits = []
|
||||
for sign in (-1, 1):
|
||||
previous, limit = centre, sign * np.inf
|
||||
for k in range(1, 80):
|
||||
v = centre + sign * scale * k
|
||||
if drop(v) > 0:
|
||||
limit = optimize.brentq(drop, min(previous, v), max(previous, v))
|
||||
break
|
||||
previous = v
|
||||
limits.append(limit)
|
||||
return limits[0], limits[1]
|
||||
|
||||
|
||||
def _summary(model, n, coef, low, high, p, design, state, **extra) -> dict:
|
||||
return {
|
||||
"model": model,
|
||||
"n": n,
|
||||
"coef": round(float(coef), 4),
|
||||
"odds_ratio": round(float(np.exp(coef)), 4),
|
||||
"ci_low": round(float(np.exp(low)), 4),
|
||||
"ci_high": round(float(np.exp(high)), 4),
|
||||
"p": round(p, 5),
|
||||
"adjusted_for": ", ".join(design.names[2:]),
|
||||
"reason": "",
|
||||
**extra,
|
||||
"state": {"design": design.state(), **state},
|
||||
}
|
||||
|
||||
|
||||
def rows(t: pd.DataFrame, outcome: str, predictor: str) -> pd.DataFrame:
|
||||
return t[[outcome, predictor, *(a for a in ADJUST if a in t)]].dropna()
|
||||
|
||||
|
||||
def firth_fit(d: pd.DataFrame, outcome: str, predictor: str):
|
||||
"""Firth's fit on complete rows `d`: the design, its matrix, the coefficients, the
|
||||
penalised maximum and the scoring state (FLIC: the intercept refitted so the
|
||||
probabilities add up to the events); None when it can't be fitted."""
|
||||
y = d[outcome].to_numpy(float)
|
||||
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
|
||||
return None
|
||||
design = Design.of(d, predictor)
|
||||
X = design.matrix(d)
|
||||
b, top = _newton(X, y)
|
||||
eta = X[:, 1:] @ b[1:]
|
||||
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
|
||||
state = {"design": design.state(), "beta": [float(v) for v in b[1:]],
|
||||
"intercept": float(intercept)} # fmt: skip
|
||||
return design, X, y, b, top, state
|
||||
|
||||
|
||||
def firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
|
||||
d = rows(t, outcome, predictor)
|
||||
out = {"model": "firth", "n": len(d), "events": int(d[outcome].sum())}
|
||||
if (fitted := firth_fit(d, outcome, predictor)) is None:
|
||||
return {**out, "reason": TOO_FEW}
|
||||
design, X, y, b, top, state = fitted
|
||||
se = float(np.sqrt(np.linalg.inv(_gradient(b, X, y)[1])[1, 1]))
|
||||
profile = lambda v: _firth_profile(v, 1, X, y, b) # noqa: E731
|
||||
low, high = _interval(profile, b[1], top, max(se, 0.05))
|
||||
p = float(stats.chi2.sf(max(2 * (top - profile(0.0)), 0.0), 1))
|
||||
return _summary("firth", len(d), b[1], low, high, p, design, state, events=int(y.sum()))
|
||||
|
||||
|
||||
# The cumulative logit: P(level > k) = expit(eta - theta_k), thresholds kept increasing.
|
||||
def _ordinal_nll(par, X, y, K) -> float:
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
eta = X @ par[K - 1 :]
|
||||
n = len(y)
|
||||
cdf = np.c_[np.zeros(n), expit(theta[None, :] - eta[:, None]), np.ones(n)]
|
||||
return -float(
|
||||
np.sum(np.log(np.clip(cdf[np.arange(n), y + 1] - cdf[np.arange(n), y], 1e-300, None)))
|
||||
)
|
||||
|
||||
|
||||
def _cumulative(X, y, K, fixed=None):
|
||||
start = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
|
||||
if fixed is None:
|
||||
r = optimize.minimize(lambda q: _ordinal_nll(q, X, y, K), start, method="BFGS")
|
||||
return r.x, float(r.fun)
|
||||
j, value = fixed
|
||||
free = [k for k in range(len(start)) if k != K - 1 + j]
|
||||
|
||||
def nll(q):
|
||||
par = np.empty(len(start))
|
||||
par[free], par[K - 1 + j] = q, value
|
||||
return _ordinal_nll(par, X, y, K)
|
||||
|
||||
return None, float(optimize.minimize(nll, start[free], method="BFGS").fun)
|
||||
|
||||
|
||||
def ordinal_fit(d: pd.DataFrame, outcome: str, predictor: str, high: float):
|
||||
"""The cumulative logit's fit on complete rows `d` (None when it can't be fitted, or
|
||||
when it separates): the design, its matrix, levels, the parameters, the minimum and the
|
||||
scoring state (P(level >= high))."""
|
||||
levels = np.sort(d[outcome].unique())
|
||||
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
|
||||
return None
|
||||
design = Design.of(d, predictor)
|
||||
X, K = design.matrix(d)[:, 1:], len(levels)
|
||||
y = np.searchsorted(levels, d[outcome].to_numpy())
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
par, nll = _cumulative(X, y, K)
|
||||
if abs(par[K - 1]) > 20:
|
||||
return "separation"
|
||||
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
|
||||
k = int(np.searchsorted(levels, high))
|
||||
inside = 0 < k < K
|
||||
state = {"design": design.state(), "beta": [float(v) for v in par[K - 1 :]],
|
||||
"threshold": float(theta[k - 1]) if inside else None,
|
||||
"always": None if inside else float(k == 0)} # fmt: skip
|
||||
return design, X, y, K, par, nll, state
|
||||
|
||||
|
||||
def ordinal(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
|
||||
d = rows(t, outcome, predictor)
|
||||
out = {"model": "ordinal", "n": len(d), "levels": int(d[outcome].nunique())}
|
||||
fitted = ordinal_fit(d, outcome, predictor, high)
|
||||
if fitted is None or fitted == "separation":
|
||||
return {**out, "reason": TOO_FEW if fitted is None else SEPARATION}
|
||||
design, X, y, K, par, nll, state = fitted
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
profile = lambda v: -_cumulative(X, y, K, fixed=(0, v))[1] # noqa: E731
|
||||
low, high_ = _interval(profile, par[K - 1], -nll, 0.1)
|
||||
if not (np.isfinite(low) and np.isfinite(high_)):
|
||||
return {**out, "reason": SEPARATION}
|
||||
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
|
||||
return _summary("ordinal", len(d), par[K - 1], low, high_, p, design, state, levels=K)
|
||||
|
||||
|
||||
def probability(model: str, state: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
|
||||
"""Each child's probability of the outcome under a fitted state, and the reference
|
||||
child's (z = 0, the cohort's mean age, the commonest module)."""
|
||||
X = Design.from_state(state["design"]).matrix(t)
|
||||
if model == "firth":
|
||||
return (expit(state["intercept"] + X[:, 1:] @ np.asarray(state["beta"])),
|
||||
float(expit(state["intercept"]))) # fmt: skip
|
||||
if state["threshold"] is None:
|
||||
always = state["always"]
|
||||
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, always), always
|
||||
return (1 - expit(state["threshold"] - X[:, 1:] @ np.asarray(state["beta"])),
|
||||
float(1 - expit(state["threshold"]))) # fmt: skip
|
||||
+7
-1
@@ -9,10 +9,11 @@ dependencies = [
|
||||
"dagster",
|
||||
"dagster-webserver",
|
||||
"mlflow-skinny",
|
||||
"openai>=3.59.0",
|
||||
"splink>=5.0.0",
|
||||
"duckdb>=2.0.1",
|
||||
"markitdown[docx,xlsx]>=0.1.9",
|
||||
"ocrmypdf>=17.14.2",
|
||||
"pikepdf>=10.0",
|
||||
"pdfplumber>=0.11.11",
|
||||
"scikit-learn>=1.9.1",
|
||||
"scipy>=1.18.1",
|
||||
@@ -22,8 +23,13 @@ dependencies = [
|
||||
"edfio>=0.4.18",
|
||||
"statsmodels>=0.15.0",
|
||||
"pgmpy>=1.1.2",
|
||||
"firthmodels>=0.8.2",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
# Where a Dask cluster runs the long batches (testing here); the product runs without it.
|
||||
dask = ["dask[distributed]>=2026.8.0,<2026.9"] # as the testing cluster runs
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12,<0.13"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""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 {})
|
||||
@@ -1,215 +0,0 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from core.domains import Domain, part
|
||||
from persistance import bundle, config, registry
|
||||
|
||||
DOMAIN = Domain.TEA
|
||||
NAME = "tea.curve_x"
|
||||
|
||||
|
||||
class Model(mlflow.pyfunc.PythonModel):
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
|
||||
def predict(self, context, model_input: pd.DataFrame, params=None):
|
||||
return model_input.assign(score=self.value)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def stores(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||
|
||||
def use(name):
|
||||
path = tmp_path / name
|
||||
path.mkdir(exist_ok=True)
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{path}/a.db")
|
||||
monkeypatch.chdir(path)
|
||||
|
||||
use("a")
|
||||
return use
|
||||
|
||||
|
||||
def _register(value=1, clinical=True):
|
||||
version = registry.register(
|
||||
NAME,
|
||||
Model(value),
|
||||
{"scenario": "curve"},
|
||||
{"n_reference": 10},
|
||||
{"technical_validation": {"a": 1}, "interpretability": {"b": 2}},
|
||||
tags={"source": "test", "bundle.source_version": "stale"},
|
||||
)
|
||||
if clinical:
|
||||
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
|
||||
return version
|
||||
|
||||
|
||||
def _trust(data):
|
||||
sha = hashlib.sha256(data).hexdigest()
|
||||
with bundle.trusted_file().open("a") as file:
|
||||
file.write(f"\n# approved\n {sha.upper()} \n")
|
||||
return sha
|
||||
|
||||
|
||||
def _entries(data):
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
return {name: archive.read(name) for name in archive.namelist()}
|
||||
|
||||
|
||||
def _zip(entries):
|
||||
stream = io.BytesIO()
|
||||
with zipfile.ZipFile(stream, "w") as archive:
|
||||
for name, data in entries.items():
|
||||
archive.writestr(name, data)
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
def test_export_is_deterministic(stores):
|
||||
registry.promote(NAME, _register())
|
||||
first, second = bundle.export(DOMAIN), bundle.export(DOMAIN)
|
||||
assert first.data == second.data
|
||||
assert first.sha256 == second.sha256 == hashlib.sha256(first.data).hexdigest()
|
||||
with zipfile.ZipFile(io.BytesIO(first.data)) as archive:
|
||||
assert archive.namelist() == sorted(archive.namelist())
|
||||
for info in archive.infolist():
|
||||
assert info.date_time == bundle.EPOCH
|
||||
assert info.compress_type == zipfile.ZIP_DEFLATED
|
||||
assert info.external_attr == 0o644 << 16
|
||||
assert info.create_system == 3
|
||||
|
||||
|
||||
def test_layout_and_manifest_hold_every_file_hash(stores):
|
||||
_register()
|
||||
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
||||
manifest = json.loads(entries.pop("manifest.json"))
|
||||
assert (manifest["format"], manifest["domain"]) == (1, "tea")
|
||||
(item,) = manifest["versions"]
|
||||
assert (item["name"], item["version"]) == (NAME, 1)
|
||||
prefix = "models/tea.curve_x/v1/"
|
||||
assert prefix + "meta.json" in entries
|
||||
assert prefix + "model/MLmodel" in entries
|
||||
assert prefix + "reports/clinical_validation.txt" in entries
|
||||
assert item["files"] == {key: hashlib.sha256(data).hexdigest() for key, data in entries.items()}
|
||||
meta = json.loads(entries.pop(prefix + "meta.json"))
|
||||
content = {key.removeprefix(prefix): data for key, data in entries.items()}
|
||||
assert meta["content_sha256"] == item["content_sha256"] == bundle.content_sha256(content)
|
||||
|
||||
|
||||
def test_selection_champion_latest_all(stores):
|
||||
for value in (1, 2, 3):
|
||||
_register(value)
|
||||
with pytest.raises(bundle.Empty, match="nothing to export"):
|
||||
bundle.export(DOMAIN)
|
||||
registry.promote(NAME, 2)
|
||||
assert bundle.export(DOMAIN).versions == [(NAME, 2)]
|
||||
assert bundle.export(DOMAIN, ["curve_x"], "latest").versions == [(NAME, 3)]
|
||||
assert bundle.export(DOMAIN, versions="all").versions == [(NAME, 1), (NAME, 2), (NAME, 3)]
|
||||
with pytest.raises(bundle.BundleError, match="no tea model missing"):
|
||||
bundle.export(DOMAIN, ["missing"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("clinical", [True, False])
|
||||
def test_roundtrip_registers_candidates_with_lineage(stores, clinical):
|
||||
_register()
|
||||
source_version = _register(2, clinical=clinical)
|
||||
source = registry.snapshot(NAME, source_version)
|
||||
inputs = pd.DataFrame({"value": [0]})
|
||||
prediction = mlflow.pyfunc.load_model(f"models:/{NAME}/{source_version}").predict(inputs)
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
stores("b")
|
||||
_trust(exported.data)
|
||||
assert bundle.import_(DOMAIN, exported.data) == bundle.Imported(
|
||||
exported.sha256, [(NAME, 1)], []
|
||||
)
|
||||
target = registry.snapshot(NAME, 1)
|
||||
pd.testing.assert_frame_equal(
|
||||
mlflow.pyfunc.load_model(f"models:/{NAME}/1").predict(inputs),
|
||||
prediction,
|
||||
)
|
||||
assert target.params == source.params
|
||||
assert target.metrics == source.metrics
|
||||
assert target.reports == source.reports
|
||||
assert target.tags == {
|
||||
"source": "test",
|
||||
"bundle.sha256": exported.sha256,
|
||||
"bundle.source_name": NAME,
|
||||
"bundle.source_version": "2",
|
||||
"bundle.content_sha256": json.loads(_entries(exported.data)["manifest.json"])["versions"][
|
||||
0
|
||||
]["content_sha256"],
|
||||
}
|
||||
assert registry.champion_version(NAME) is None
|
||||
if clinical:
|
||||
registry.promote(NAME, 1)
|
||||
assert registry.champion_version(NAME) == 1
|
||||
else:
|
||||
with pytest.raises(registry.MissingReports, match="clinical_validation"):
|
||||
registry.promote(NAME, 1)
|
||||
|
||||
|
||||
def test_importing_twice_is_a_conflict_and_partial_imports_skip(stores):
|
||||
_register()
|
||||
single = bundle.export(DOMAIN, versions="latest")
|
||||
_register(2)
|
||||
both = bundle.export(DOMAIN, versions="all")
|
||||
stores("b")
|
||||
_trust(single.data)
|
||||
_trust(both.data)
|
||||
assert bundle.import_(DOMAIN, single.data).imported == [(NAME, 1)]
|
||||
with pytest.raises(bundle.Conflict, match="every version is already registered"):
|
||||
bundle.import_(DOMAIN, single.data)
|
||||
result = bundle.import_(DOMAIN, both.data)
|
||||
assert result.imported == [(NAME, 2)]
|
||||
assert result.skipped == [(NAME, 1)]
|
||||
|
||||
|
||||
def test_tampered_bundles_are_refused(stores):
|
||||
_register()
|
||||
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
||||
path = "models/tea.curve_x/v1/model/MLmodel"
|
||||
manifest = json.loads(entries["manifest.json"])
|
||||
|
||||
def with_manifest(**fields):
|
||||
return entries | {"manifest.json": json.dumps(manifest | fields).encode()}
|
||||
|
||||
cases = [
|
||||
(_zip(entries | {path: entries[path][:-1] + b"!"}), "content does not match the manifest"),
|
||||
(_zip(entries | {"extra": b""}), "files in the bundle do not match the manifest"),
|
||||
(_zip({k: v for k, v in entries.items() if k != path}), "files in the bundle do not match"),
|
||||
(_zip(entries | {"../x": b""}), r"unsafe bundle path: \.\./x"),
|
||||
(_zip(with_manifest(format=2)), "bundle format 2, this platform reads 1"),
|
||||
(_zip(with_manifest(domain="cacu")), "bundle is for cacu, not tea"),
|
||||
(b"hello", "not a bundle"),
|
||||
]
|
||||
for data, message in cases:
|
||||
_trust(data)
|
||||
with pytest.raises(bundle.BundleError, match=message):
|
||||
bundle.import_(DOMAIN, data)
|
||||
|
||||
|
||||
def test_guard_runs_on_export_and_on_import(stores, monkeypatch):
|
||||
_register()
|
||||
hook = part(DOMAIN, "bundle")
|
||||
monkeypatch.setattr(hook, "guard", lambda version: [])
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
_trust(exported.data)
|
||||
monkeypatch.setattr(hook, "guard", lambda version: ["problem"])
|
||||
for operation in (
|
||||
lambda: bundle.export(DOMAIN, versions="latest"),
|
||||
lambda: bundle.import_(DOMAIN, exported.data),
|
||||
):
|
||||
with pytest.raises(bundle.BundleError, match=r"tea\.curve_x v1: problem"):
|
||||
operation()
|
||||
|
||||
|
||||
def test_import_refuses_an_untrusted_digest(stores):
|
||||
_register()
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
with pytest.raises(bundle.BundleError, match=f"bundle {exported.sha256} is not trusted"):
|
||||
bundle.import_(DOMAIN, exported.data)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""The opt-in development evaluation (models.cacu.development): Firth and its FLIC and FLAC
|
||||
corrections, and the nested selection that never looks outside its training partition."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from models.cacu.development import METHODS, Firth, candidates, evaluate
|
||||
|
||||
|
||||
def data(n=60, seed=0):
|
||||
rng = np.random.default_rng(seed)
|
||||
X = pd.DataFrame({"a": rng.integers(0, 2, n), "b": rng.integers(0, 2, n)}, dtype=float)
|
||||
X.loc[:5, "a"] = np.nan
|
||||
X["not_a"], X["sparse"], X["counts"] = 1 - X["a"], np.nan, rng.integers(0, 5, n)
|
||||
y = (rng.random(n) < 0.15 + 0.5 * X["b"]).astype(int).to_numpy()
|
||||
return X, y
|
||||
|
||||
|
||||
def test_flic_matches_the_outcome_rate_and_flac_stays_near_firth():
|
||||
X, y = data()
|
||||
fitted = {m: Firth(m).fit(X[["b"]], y).predict_proba(X[["b"]])[:, 1] for m in METHODS}
|
||||
assert fitted["flic"].sum() == pytest.approx(y.sum())
|
||||
assert np.abs(fitted["flac"] - fitted["firth"]).max() < 0.05
|
||||
with pytest.raises(ValueError, match="collinear"):
|
||||
Firth().fit(np.column_stack([X["b"], X["b"]]), y)
|
||||
|
||||
|
||||
def test_candidates_are_known_binary_and_distinguishable():
|
||||
X, _ = data()
|
||||
assert candidates(X, 0.7, 5) == ["b", "a"] # not_a is a's complement; the rest aren't 0/1
|
||||
assert candidates(X, 0.95, 5) == ["b"]
|
||||
|
||||
|
||||
def test_nested_selection_reports_every_method_validation_and_attempt():
|
||||
X, y = data()
|
||||
found = evaluate(X, y)
|
||||
assert found["development_only"] and found["max_subsets"] == 16
|
||||
for plan in ("cv", "loocv"):
|
||||
for method in METHODS:
|
||||
result = found["validation"][plan][method]
|
||||
assert result["unscored"] == 0 and set(result["metrics"]) >= {"auc", "brier"}
|
||||
assert all(set(chosen) <= {"a", "b"} for chosen in result["selected"])
|
||||
assert {a["method"] for a in found["attempts"]} == set(METHODS)
|
||||
with pytest.raises(ValueError, match="exceeds"):
|
||||
evaluate(X, y, max_fits=10)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""The development encoders (models.cacu.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"
|
||||
SAMPLE = "2025-01-10"
|
||||
|
||||
|
||||
def ev(date, kind, code=None, *, person="p1", table="cervical_cytology", source=None,
|
||||
clinical=None, available=None) -> dict: # fmt: skip
|
||||
return {"person_id": person, "index_date": INDEX, "date": date, "type": kind,
|
||||
"value_code": code, "value_num": np.nan, "source_table": table,
|
||||
"source_id": source or date, "evidence_date": clinical,
|
||||
"source_available_at": available} # fmt: skip
|
||||
|
||||
|
||||
def encoded(events, forms=None, person="p1") -> pd.Series:
|
||||
blank = dict.fromkeys(("screening_history", "adequacy", *FINDINGS))
|
||||
forms = None if forms is None else pd.DataFrame([blank | f for f in forms])
|
||||
found = encode(pd.DataFrame(events), forms).set_index("person_id")
|
||||
return found.loc[person].drop("index_date").astype(float)
|
||||
|
||||
|
||||
def test_an_unknown_value_is_missing_never_zero():
|
||||
assert encoded([ev(INDEX, "cytology", "satisfactory")]).isna().all()
|
||||
found = encoded([
|
||||
ev("1980-06-11", "birth", table="person"),
|
||||
*(ev("2025-01-15", k, c, source=SAMPLE) for k, c in (
|
||||
("bethesda", "LSIL"), ("hpv", "positive"), ("hpv_16", "negative"))),
|
||||
ev(INDEX, "cervix_appearance", "lesion"), ev(INDEX, "presenting_symptom", "other?"),
|
||||
]) # fmt: skip
|
||||
assert (found["age__35-44"], found["age__45-54"]) == (1, 0)
|
||||
assert (found["bethesda__LSIL"], found["bethesda__HSIL"]) == (1, 0)
|
||||
assert (found["cytology_ascus_plus"], found["cytology_hsil_plus"]) == (1, 0)
|
||||
assert (found["hpv_positive"], found["hpv_16_positive"]) == (1, 0)
|
||||
assert np.isnan(found["hpv_18_positive"])
|
||||
assert np.isnan(found["hpv_16_or_18_positive"]) # one negative, the other unreported
|
||||
assert (found["cervix_appearance__lesion"], found["cervix_appearance__healthy"]) == (1, 0)
|
||||
assert found.filter(like="presenting_symptom").isna().all() # not one of its codes
|
||||
assert found.filter(like="prior_").isna().all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hpv_16, hpv_18, expected", [
|
||||
("positive", None, 1.0), ("negative", "negative", 0.0),
|
||||
("negative", "positive", 1.0)]) # fmt: skip
|
||||
def test_genotypes_of_one_sample(hpv_16, hpv_18, expected):
|
||||
events = [ev("2025-01-15", "hpv_16", hpv_16)]
|
||||
events += [ev("2025-01-15", "hpv_18", hpv_18)] if hpv_18 else []
|
||||
assert encoded(events)["hpv_16_or_18_positive"] == expected
|
||||
|
||||
|
||||
def test_what_was_not_available_at_the_index_is_not_read():
|
||||
base = [ev(INDEX, "cytology", "satisfactory")]
|
||||
later = [
|
||||
ev("2025-06-20", "bethesda", "HSIL", source=INDEX), # the index sample's report
|
||||
ev("2025-06-20", "hpv", "positive", source=INDEX),
|
||||
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-11T08:00:00-06:00"),
|
||||
ev("2025-06-01", "hpv", "positive", clinical="2025-07-01"),
|
||||
# the index day's procedures may be the outcome
|
||||
ev(INDEX, "biopsy", "carcinoma", table="cervical_biopsy"),
|
||||
ev(INDEX, "colposcopy", table="clinical_note"),
|
||||
ev(INDEX, "treatment", table="clinical_note"),
|
||||
ev("2025-08-01", "history", table="clinical_note"),
|
||||
# standalone evidence with no availability: its onset says nothing of when it was known
|
||||
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence"),
|
||||
] # fmt: skip
|
||||
forms = [{"person_id": "p1", "sample_date": INDEX, "report_date": "2025-06-20",
|
||||
"adequacy": "unsatisfactory", "finding_atrophy": True}] # fmt: skip
|
||||
pd.testing.assert_series_equal(encoded(base + later, forms), encoded(base))
|
||||
found = encoded([
|
||||
ev("2025-06-01", "bethesda", "HSIL", available="2025-06-10T23:00:00-06:00"),
|
||||
ev("2020-01-01", "gynecologic_condition", "hysterectomy",
|
||||
table="cacu_eligibility_evidence", available="2024-01-01"),
|
||||
]) # fmt: skip
|
||||
assert (found["cytology_hsil_plus"], found["history_hysterectomy"]) == (1, 1)
|
||||
|
||||
|
||||
def test_prior_procedures_and_the_referral_grade():
|
||||
found = encoded([
|
||||
ev("2025-01-15", "bethesda", "HSIL", source=SAMPLE),
|
||||
ev("2025-03-01", "colposcopy", table="clinical_note"),
|
||||
ev("2025-03-01", "biopsy_order", table="cervical_biopsy"),
|
||||
ev("2025-03-10", "biopsy", "LSIL", table="cervical_biopsy"),
|
||||
]) # fmt: skip
|
||||
assert (found["prior_colposcopy"], found["prior_biopsy_order"]) == (1, 1)
|
||||
assert (found["prior_biopsy_lsil_plus"], found["prior_biopsy_hsil_plus"]) == (1, 0)
|
||||
assert found["referral_high_grade"] == 1 and np.isnan(found["prior_treatment"])
|
||||
|
||||
|
||||
def test_the_form_is_read_from_its_latest_report_whole():
|
||||
forms = [
|
||||
{"person_id": "p1", "sample_date": "2024-01-10", "report_date": "2024-01-20",
|
||||
"screening_history": "never", "finding_atrophy": True},
|
||||
{"person_id": "p1", "sample_date": SAMPLE, "report_date": "2025-01-20",
|
||||
"adequacy": "satisfactory", "finding_candida": 1},
|
||||
] # fmt: skip
|
||||
found = encoded([ev(INDEX, "cytology")], forms)
|
||||
assert found["screening_history__never"] == 1
|
||||
assert (found["sample_unsatisfactory"], found["finding_candida"]) == (0, 1)
|
||||
assert np.isnan(found["finding_atrophy"])
|
||||
|
||||
|
||||
def test_members_apart_and_a_timeline_without_availability_refused():
|
||||
events = [ev("2025-01-15", "hpv", "positive"), ev(INDEX, "cytology", person="p2")]
|
||||
assert np.isnan(encoded(events, person="p2")["hpv_positive"])
|
||||
with pytest.raises(KeyError, match="source_available_at"):
|
||||
encode(pd.DataFrame([ev(INDEX, "cytology")]).drop(columns="source_available_at"))
|
||||
@@ -5,6 +5,9 @@ gives the current model's predictions.
|
||||
Fixed on purpose, so left out of the comparison:
|
||||
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
|
||||
(1970-01-01 for everyone); the rewrite returns the index sample's date.
|
||||
- A patient without an HPV result at the index is not evaluated; the current models read it
|
||||
as negative, so a result that is not positive stands in for it here.
|
||||
- An interval whose covariance can't be estimated is unknown, not the current platform's.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -14,6 +17,8 @@ import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from core import cacu
|
||||
from models.cacu.features import days, prepared
|
||||
from models.cacu.specs import MODELS
|
||||
|
||||
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
|
||||
@@ -55,11 +60,23 @@ def timelines(cohort: str) -> pd.DataFrame:
|
||||
return found
|
||||
|
||||
|
||||
def assumed_hpv(events: pd.DataFrame) -> pd.DataFrame:
|
||||
"""A not-positive HPV result (nor a negative one) at the index of whoever has none."""
|
||||
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
|
||||
tested = events.loc[(events["type"] == "hpv") & near.to_numpy(), "person_id"]
|
||||
index = events.groupby("person_id", as_index=False).first()
|
||||
missing = index[~index["person_id"].isin(tested)]
|
||||
assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed")
|
||||
return pd.concat([events, assumed[events.columns]], ignore_index=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
|
||||
"cin2_logistic"]) # fmt: skip
|
||||
def test_predictions_match_the_current_models(name):
|
||||
spec = MODELS[name]
|
||||
events = timelines(COHORTS[spec.cohort])
|
||||
if spec.method != "logistic regression":
|
||||
events = assumed_hpv(events)
|
||||
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
|
||||
model, metrics, _ = spec.train(events, *args)
|
||||
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
||||
@@ -78,7 +95,9 @@ def test_predictions_match_the_current_models(name):
|
||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
||||
("ci_high", "ic_alto")]: # fmt: skip
|
||||
if theirs in both:
|
||||
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
|
||||
kept = both[ours].notna() | (ours == "probability") # estimable intervals
|
||||
np.testing.assert_allclose(both.loc[kept, ours], both.loc[kept, theirs], rtol=RTOL,
|
||||
atol=0) # fmt: skip
|
||||
if spec.method != "logistic regression":
|
||||
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
|
||||
|
||||
@@ -105,6 +124,7 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
|
||||
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
|
||||
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
|
||||
found = spec.predict(model, events)
|
||||
assert all(set(json.loads(v)) == set(spec.features) for v in found["input_values"])
|
||||
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
|
||||
both = found.merge(reference, left_on=["person_id", "horizon_years"],
|
||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""What CaCu training keeps besides the models: who each cohort lost and why; that a patient
|
||||
without HPV is not evaluated; and that the mixture never makes up a risk or an interval it
|
||||
can't estimate (unseen levels, improper covariances, frozen parameters)."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from core import cacu
|
||||
from models.cacu import features, reports
|
||||
from models.cacu.pim import Fit, ISpline, Mixture
|
||||
|
||||
BASELINE = ISpline((0.0, 1.0, 2.0), 2)
|
||||
PARAMS = np.zeros(1 + BASELINE.n_params)
|
||||
X1, Z0 = np.ones((1, 1)), np.empty((1, 0))
|
||||
|
||||
|
||||
def fit(covariance) -> Fit:
|
||||
return Fit(1, 0, BASELINE, PARAMS, covariance, 0.0, True)
|
||||
|
||||
|
||||
def test_a_candidate_out_for_two_reasons_is_excluded_once():
|
||||
rows = pd.DataFrame([
|
||||
("eligible", "2025-01-01", None), ("two", "2025-01-01", "hysterectomy"),
|
||||
("two", "2025-01-01", "under_18"), ("waiting", "2025-01-01", "no_index_result"),
|
||||
("both", "2025-01-01", "no_index_result"), ("both", "2025-01-01", "prior_outcome"),
|
||||
("after", "2025-07-01", "hysterectomy"),
|
||||
], columns=["person_id", "index_date", "criterion"]).assign(index_sample_id=None) # fmt: skip
|
||||
found = reports.attrition("cacu_cohort_surveillance", "surveillance", rows, 10,
|
||||
date(2025, 6, 30)) # fmt: skip
|
||||
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"
|
||||
|
||||
|
||||
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 = features.index_results(events, cacu.KPNC)
|
||||
assert dict(zip(found["person_id"], found["hpv_positive"], strict=True)) == {
|
||||
"negative": 0.0, "positive": 1.0} # fmt: skip
|
||||
|
||||
|
||||
def test_rows_only_at_unseen_levels_get_no_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()
|
||||
|
||||
|
||||
def test_an_improper_covariance_gives_no_interval_never_a_zero_width_one():
|
||||
assert np.isfinite(fit(np.eye(len(PARAMS))).risk_with_variance(X1, Z0, [0, 1])[1]).all()
|
||||
n = len(PARAMS)
|
||||
for covariance in (np.full((n, n), np.nan), -np.eye(n), np.zeros((n, n))):
|
||||
assert np.isnan(fit(covariance).risk_with_variance(X1, Z0, [0, 1])[1]).all()
|
||||
frozen = np.eye(n)
|
||||
frozen[1, :] = frozen[:, 1] = np.nan # a frozen parameter moves only some horizons
|
||||
variance = fit(frozen).risk_with_variance(X1, Z0, [0, 1])[1]
|
||||
assert np.isfinite(variance[0, 0]) and np.isnan(variance[0, 1])
|
||||
|
||||
|
||||
def test_diagnostics_count_the_rows_without_an_interval():
|
||||
model = Mixture((0, 1), (), (), {})
|
||||
model.fits_, model.seen_ = {(): fit(-np.eye(len(PARAMS)))}, {(): {}}
|
||||
(stratum,) = model.variance_diagnostics(pd.DataFrame(index=range(2)))["strata"]
|
||||
assert stratum["rows_without_interval"] == 2 and stratum["negative_variances"]
|
||||
assert stratum["status"] == "not_estimable"
|
||||
@@ -0,0 +1,77 @@
|
||||
"""What Automático checks without asking the model: documents grouped by the words their
|
||||
layout prints, a proposed pattern kept only when it captures what the model read, a
|
||||
column's date format, and the site's codes as a ConceptMap the platform accepts."""
|
||||
|
||||
from core import concept_map
|
||||
from core.drafting import codes_schema, layout_schema, table_schema
|
||||
from models.draft import fields
|
||||
from models.draft.layouts import layouts
|
||||
|
||||
FORM = (
|
||||
"SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: {date}\n"
|
||||
"Calidad de la muestra: SATISFACTORIO\nResultado: {result}\nObservaciones: ninguna"
|
||||
)
|
||||
MAMMOGRAM = (
|
||||
"REPORTE DE MASTOGRAFÍA BILATERAL\nPaciente: {name}\nFecha del estudio: {date}\n"
|
||||
"Hallazgos: densidad mamaria tipo B, sin masas\nBI-RADS: 2"
|
||||
)
|
||||
|
||||
|
||||
def test_documents_of_one_layout_group_together_whoever_they_are_about():
|
||||
texts = [
|
||||
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
||||
MAMMOGRAM.format(name="LUISA ORTIZ MENA", date="11/04/2025"),
|
||||
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
||||
MAMMOGRAM.format(name="MARTA SOLÍS GIL", date="01/07/2025"),
|
||||
FORM.format(name="EVA RUIZ CANO", date="20/08/2025", result="ASC-US"),
|
||||
]
|
||||
found = layouts(texts)
|
||||
assert found[0] == found[2] == found[4] != found[1] == found[3]
|
||||
|
||||
|
||||
def test_a_pattern_is_kept_only_if_it_captures_the_values_read():
|
||||
texts = [
|
||||
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
||||
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
||||
]
|
||||
read = [
|
||||
(texts[0], {"sample_date": "2025-03-02", "result": "NILM"}),
|
||||
(texts[1], {"sample_date": "2025-06-15", "result": "LSIL"}),
|
||||
]
|
||||
codes = fields.Codes("sitio")
|
||||
entity = "cervical_cytology"
|
||||
date = r"recepci[oó]n:\s*(\d{2}/\d{2}/\d{4})"
|
||||
assert fields.checks(entity, "sample_date", date, "%d/%m/%Y", read, codes)
|
||||
assert not fields.checks(entity, "sample_date", date, "%m/%d/%Y", read, codes) # 15th month
|
||||
assert not fields.checks(entity, "sample_date", r"(\d{2}/\d{2})", None, read, codes)
|
||||
assert not fields.checks(entity, "sample_date", r"recepci[oó]n:", None, read, codes) # no group
|
||||
assert not fields.checks(entity, "result", r"resultado:(\s*)", None, read, codes) # nothing
|
||||
# A coded field: what the site writes becomes its ConceptMap, unless it is the code.
|
||||
assert fields.checks(entity, "result", r"resultado:\s*(\S+)", None, read, codes)
|
||||
assert codes.table() == {(entity, "result"): {"negativo": "NILM"}}
|
||||
# A pattern taking text that means two things is the wrong text.
|
||||
assert not fields.checks(entity, "result", r"(calidad)", None, read, fields.Codes("x"))
|
||||
found = codes.concept_map()
|
||||
assert concept_map.problems(found) == []
|
||||
assert concept_map.table([found], "result") == {"negativo": "NILM"}
|
||||
|
||||
|
||||
def test_a_columns_dates_get_the_format_every_value_parses_with():
|
||||
assert fields.date_format(["02/03/2025", "15/06/2025"]) == "%d/%m/%Y"
|
||||
assert fields.date_format(["2025-03-02", None]) == "%Y-%m-%d"
|
||||
assert fields.date_format(["mañana"]) is None
|
||||
|
||||
|
||||
def test_answers_are_held_to_the_platforms_terms():
|
||||
layout = layout_schema(3)["$defs"]["Study"]["properties"]
|
||||
assert (
|
||||
"cervical_cytology" in layout["entity"]["enum"]
|
||||
and "identity" not in layout["entity"]["enum"]
|
||||
)
|
||||
assert layout["documents"]["items"]["enum"] == [1, 2, 3]
|
||||
codes = codes_schema(["NEGATIVO", "BAJO GRADO"], ["NILM", "LSIL"])
|
||||
one = codes["$defs"]["Code"]["properties"]
|
||||
assert one["raw"]["enum"] == ["NEGATIVO", "BAJO GRADO"]
|
||||
assert {"enum": ["NILM", "LSIL"], "type": "string"} in one["code"]["anyOf"]
|
||||
table = table_schema(["num", "nombre"])
|
||||
assert table["$defs"]["Who"]["properties"]["column"]["enum"] == ["num", "nombre"]
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Automático's judgements that need no model: a layout whose title the text layer
|
||||
garbles is still marked by a line it prints, and a report that leaves its sample's date to
|
||||
the order it answers is paired with that order by the column both carry."""
|
||||
|
||||
from core.pipeline import Join, Route
|
||||
from models.draft.joins import Kind, apart_from, joined, partner
|
||||
from models.draft.layouts import printed_line
|
||||
|
||||
HPV = (
|
||||
"No.Proceso {n}\nPaciente {name}\nDDDDEEEETTTTEEEECCCCCCCCIIIIOOOONNNN\n"
|
||||
"ESPECIMEN: CEPILLADO CERVICOVAGINAL\nVVVVPPPPHHHH . . . . . NNNNEEEEGGGG"
|
||||
)
|
||||
FORM = "SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: 0{n}/03/2025"
|
||||
|
||||
|
||||
def row(record: str, text: str, order) -> dict:
|
||||
return {"_record": record, "_file": f"{record:0>64}", "text": text, "format": "pdf",
|
||||
"orden_servicio_id": order, "tipo": "resultado"} # fmt: skip
|
||||
|
||||
|
||||
def test_a_layout_is_marked_by_a_line_only_it_prints():
|
||||
hpv = [row(f"h{n}", HPV.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
||||
forms = [row(f"c{n}", FORM.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
||||
assert printed_line(hpv, forms) == "ESPECIMEN: CEPILLADO CERVICOVAGINAL"
|
||||
assert printed_line(forms, forms[:1] + hpv) is None # what it prints, another prints too
|
||||
|
||||
|
||||
def test_a_report_is_read_with_the_order_the_same_column_pairs_it_with():
|
||||
reports = Kind("cervical_cytology", "VPH", "cervicovaginal", [],
|
||||
[row(f"h{n}", HPV.format(n=n, name="X"), n) for n in range(4)]) # fmt: skip
|
||||
orders = Kind("cervical_cytology", "Citología", "citología", [],
|
||||
[row(f"c{n}", FORM.format(n=n, name="X"), n) for n in range(1, 6)]) # fmt: skip
|
||||
# `tipo` and `format` pair every document with every other: they pair nothing.
|
||||
assert partner(reports, [reports, orders]) == (orders, "orden_servicio_id")
|
||||
orders.route = Route(id="citologia", label="Citología", inputs=["texto"])
|
||||
node = Join(id="vph_con_citologia", inputs=["vph", "citologia"],
|
||||
on=[("orden_servicio_id", "orden_servicio_id")], how="left") # fmt: skip
|
||||
found = dict((r["_record"], t) for t, r in joined(node, reports.everyone, orders))
|
||||
assert found["h1"].startswith("SOLICITUD DE CITOLOGÍA") and "Proceso 1" in found["h1"]
|
||||
assert found["h0"].startswith("No.Proceso 0") # no order: its own text alone
|
||||
assert apart_from(next(r for _, r in joined(node, reports.everyone, orders)
|
||||
if r["_record"] == "h1"), orders) # fmt: skip
|
||||
both = row("c1", FORM.format(n=1, name="X") + "\n" + HPV.format(n=1, name="X"), 1)
|
||||
(_, itself), = joined(node, [both], Kind("cervical_cytology", "", "", [], [both],
|
||||
orders.route)) # fmt: skip
|
||||
assert not apart_from(itself, orders) # one file, order and report: paired with itself
|
||||
lone = Kind("cervical_cytology", "VPH", "x", [], reports.everyone[:1])
|
||||
assert partner(lone, [lone, orders]) is None
|
||||
@@ -0,0 +1,72 @@
|
||||
"""One layout, several studies: the model is shown a layout's documents as unlike each
|
||||
other as they come (so the one note that records a death is among them), and a study only
|
||||
some of them report is kept only with a phrase that marks those and none of the others."""
|
||||
|
||||
from models.draft.documents import apart
|
||||
from models.draft.layouts import diverse, marks
|
||||
|
||||
NOTE = "INFORME MÉDICO\nNOMBRE: {name}\nMOTIVO DE LA CONSULTA: {why}\nPLAN: {plan}"
|
||||
ROUTINE = [
|
||||
NOTE.format(name=f"PACIENTE {n}", why="control anual", plan="cita en un año") for n in range(20)
|
||||
]
|
||||
DEATH = NOTE.format(name="PACIENTE 99", why="NOTA DE DEFUNCIÓN: falleció en urgencias",
|
||||
plan="certificado de defunción, causa: choque séptico") # fmt: skip
|
||||
PATHOLOGY = "ESTUDIO PATOLÓGICO\nNOMBRE: {name}\nÓRGANO: {organ}\nDIAGNÓSTICO: {dx}"
|
||||
|
||||
|
||||
def docs(texts: list[str]) -> list[dict]:
|
||||
return [{"_record": str(i), "text": t} for i, t in enumerate(texts)]
|
||||
|
||||
|
||||
def test_the_one_unlike_note_is_among_those_shown():
|
||||
notes = docs(ROUTINE[:10] + [DEATH] + ROUTINE[10:])
|
||||
assert any("DEFUNCIÓN" in r["text"] for r in diverse(notes, 3))
|
||||
assert len(diverse(notes, 30)) == len(notes)
|
||||
|
||||
|
||||
def test_a_study_some_documents_report_is_kept_with_what_marks_them():
|
||||
shown = docs([PATHOLOGY.format(name="A", organ="CÉRVIX", dx="NIC 2"),
|
||||
PATHOLOGY.format(name="B", organ="MAMA", dx="CARCINOMA DUCTAL"),
|
||||
PATHOLOGY.format(name="C", organ="CÉRVIX", dx="NIC 1")]) # fmt: skip
|
||||
log = []
|
||||
cervix = {"label": "Biopsia cervical", "documents": [1, 3], "marker": "ÓRGANO: CÉRVIX"}
|
||||
assert apart(cervix, shown, {2}, log.append) == "ÓRGANO: CÉRVIX"
|
||||
# The model's phrase marks the wrong documents: a printed line that does is taken.
|
||||
breast = {"label": "Biopsia de mama", "documents": [2], "marker": "DIAGNÓSTICO"}
|
||||
assert apart(breast, shown, {1, 3}, log.append) == "ÓRGANO: MAMA"
|
||||
# A study the model gives all but one, the one no other study claims: all of them.
|
||||
assert apart({**cervix, "documents": [1, 3]}, shown, set(), log.append) is None
|
||||
every = {"label": "Patología", "documents": [1, 2, 3], "marker": "ESTUDIO"}
|
||||
assert apart(every, shown, set(), log.append) is None # all of them: the layout's own route
|
||||
assert apart({**every, "documents": []}, shown, set(), log.append) is False
|
||||
alike = {"label": "x", "documents": [1], "marker": None} # nothing sets A apart from C
|
||||
assert apart(alike, shown, {3}, log.append) is False and log
|
||||
|
||||
|
||||
def test_a_phrase_the_model_tidied_still_finds_what_the_document_writes():
|
||||
organs = ["CÉRVIX", "MAMA DERECHA", "CERVIX", "MAMA IZQUIERDA"]
|
||||
shown = docs([PATHOLOGY.format(name=n, organ=f"{o}, BIOPSIA:", dx="X")
|
||||
for n, o in zip("ABCD", organs, strict=True)]) # fmt: skip
|
||||
breast = {"label": "Biopsia de mama", "documents": [2, 4], "marker": "MAMA, BIOPSIA"}
|
||||
found = apart(breast, shown, {1, 3}, print)
|
||||
assert [marks(found, r["text"]) for r in shown] == [False, True, False, True]
|
||||
cervix = {"label": "Biopsia cervical", "documents": [1, 3], "marker": "CÉRVIX, BIOPSIA"}
|
||||
found = apart(cervix, shown, {2, 4}, print) # written without its accent in C
|
||||
assert [marks(found, r["text"]) for r in shown] == [True, False, True, False]
|
||||
|
||||
|
||||
def test_a_study_no_line_marks_is_marked_by_the_words_its_documents_share():
|
||||
"""Each side writes its own specimen line (MAMA DERECHA, MAMA IZQUIERDA) and the model
|
||||
names the documents without a phrase: the word they all write marks them."""
|
||||
cervix = "ESTUDIO PATOLOGICO\nNOMBRE: {n}\n1 - BIOPSIA DIRIGIDA POR COLPOSCOPIA DE {c}"
|
||||
breast = "ESTUDIO PATOLOGICO\nNOMBRE: {n}\nDx: {dx}\n1 - BIOPSIA CON AGUJA DE CORTE DE {s}"
|
||||
shown = docs([cervix.format(n="A", c="CÉRVIX"), cervix.format(n="B", c="CERVIX"),
|
||||
breast.format(n="C", dx="CA DE MAMA", s="MAMA DERECHA"),
|
||||
breast.format(n="D", dx="NÓDULO MAMARIO", s="MAMA IZQUIERDA")]) # fmt: skip
|
||||
mama = {"label": "Biopsia de mama", "documents": [3, 4], "marker": None}
|
||||
found = apart(mama, shown, {1, 2}, print)
|
||||
assert [marks(found, r["text"]) for r in shown] == [False, False, True, True]
|
||||
assert "M" in found and "AGUJA" not in found # the study's own word, before any other
|
||||
cervical = {"label": "Biopsia cervical", "documents": [1, 2], "marker": None}
|
||||
found = apart(cervical, shown, {3, 4}, print) # CÉRVIX and CERVIX alike
|
||||
assert [marks(found, r["text"]) for r in shown] == [True, True, False, False]
|
||||
+1
-1
@@ -263,7 +263,7 @@ def test_metric_values(analyses):
|
||||
|
||||
def _measure_reference():
|
||||
studies = reference.listing(HELSINKI, HELSINKI / "anon_codex_age_sex.csv")
|
||||
measured = reference.measure(studies, WORKERS)
|
||||
measured = reference.measure(studies)
|
||||
CACHE.parent.mkdir(parents=True, exist_ok=True)
|
||||
CACHE.write_text(json.dumps({"cohort": reference.NAME, "studies": measured}))
|
||||
return measured
|
||||
|
||||
@@ -1,380 +0,0 @@
|
||||
"""`execution.map` returns the same list in every mode, spreads lazy input without loading it
|
||||
all, fails fast when the cluster is wrong, cleans up after a cancel, and reports progress on
|
||||
the Dagster run. Remote tests need a scheduler: set `DASK_TEST_SCHEDULER` and
|
||||
`DASK_EXPECTED_WORKERS` (the compose `test` profile does)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import cloudpickle
|
||||
import dagster as dg
|
||||
import numpy as np
|
||||
import psutil
|
||||
import pytest
|
||||
|
||||
from models import execution
|
||||
from models.execution import Execution, ExecutionError, Progress
|
||||
from persistance import cluster
|
||||
|
||||
cloudpickle.register_pickle_by_value(sys.modules[__name__])
|
||||
|
||||
|
||||
def by_value(fn):
|
||||
"""Mark a worker function so that Dask ships its code, not its name: the scheduler
|
||||
unpickles task graphs too, and has no test module (Dask wraps `fn` in a task, which
|
||||
hides the by-value registration above from it)."""
|
||||
fn.__module__ = "__main__"
|
||||
return fn
|
||||
|
||||
|
||||
@by_value
|
||||
def square(x):
|
||||
return int(x) ** 2
|
||||
|
||||
|
||||
@by_value
|
||||
def numeric(x):
|
||||
rng = np.random.default_rng(x)
|
||||
return float(np.linalg.norm(rng.normal(size=(20, 20)) @ rng.normal(size=(20, 20))))
|
||||
|
||||
|
||||
@by_value
|
||||
def slow(x):
|
||||
time.sleep(0.2)
|
||||
return x
|
||||
|
||||
|
||||
@by_value
|
||||
def sleep_forever(x):
|
||||
time.sleep(60)
|
||||
|
||||
|
||||
@by_value
|
||||
def fail_on_three(x):
|
||||
if x == 3:
|
||||
raise RuntimeError("three")
|
||||
return x
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def env(monkeypatch):
|
||||
for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
monkeypatch.setenv("DASK_LOCAL_WORKERS", "2")
|
||||
|
||||
|
||||
def fake_context():
|
||||
context = SimpleNamespace(run_id="r1", logs=[], tags=[], metadata=[])
|
||||
context.log = SimpleNamespace(info=context.logs.append)
|
||||
context.instance = SimpleNamespace(add_run_tags=lambda run, tags: context.tags.append(tags))
|
||||
context.add_output_metadata = context.metadata.append
|
||||
return context
|
||||
|
||||
|
||||
def test_resolve_defaults_and_allow_list(monkeypatch):
|
||||
assert execution.resolve().mode == "local"
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
assert execution.resolve().mode == "sync"
|
||||
with pytest.raises(ExecutionError):
|
||||
execution.resolve(Execution(mode="remote"))
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786,tcp://b:8786")
|
||||
assert execution.resolve(Execution(mode="remote")).scheduler == "tcp://a:8786"
|
||||
assert execution.resolve(Execution(mode="remote", scheduler="b:8786")).scheduler == (
|
||||
"tcp://b:8786"
|
||||
)
|
||||
assert execution.options().schedulers == ["tcp://a:8786", "tcp://b:8786"]
|
||||
|
||||
|
||||
def test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode(monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786")
|
||||
with pytest.raises(ExecutionError, match="not in DASK_SCHEDULERS"):
|
||||
execution.resolve(Execution(mode="remote", scheduler="c:8786"))
|
||||
with pytest.raises(ExecutionError, match="only goes with remote"):
|
||||
execution.resolve(Execution(mode="local", scheduler="a:8786"))
|
||||
with pytest.raises(ExecutionError, match="not host:port"):
|
||||
cluster.normalize("http://a:1")
|
||||
|
||||
|
||||
def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
lines = []
|
||||
assert execution.map(square, range(5), log=lines.append) == [0, 1, 4, 9, 16]
|
||||
assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5"
|
||||
|
||||
|
||||
def test_map_empty_items_starts_nothing(monkeypatch):
|
||||
import distributed
|
||||
|
||||
def boom(*a, **k):
|
||||
raise AssertionError("a cluster was started")
|
||||
|
||||
monkeypatch.setattr(distributed, "LocalCluster", boom)
|
||||
assert execution.map(square, []) == []
|
||||
assert execution.map(square, iter([]), total=0) == []
|
||||
|
||||
|
||||
def test_map_local_equals_sync(monkeypatch):
|
||||
items = list(range(12))
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
expected = execution.map(numeric, items, log=lambda s: None)
|
||||
monkeypatch.setenv("EXECUTION_MODE", "local")
|
||||
assert execution.map(numeric, items, log=lambda s: None) == expected
|
||||
|
||||
|
||||
def test_map_lazy_items_are_not_all_loaded_at_once():
|
||||
state = {"loaded": 0, "finished": 0, "peak": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
def generate():
|
||||
for i in range(30):
|
||||
with lock:
|
||||
state["loaded"] += 1
|
||||
state["peak"] = max(state["peak"], state["loaded"] - state["finished"])
|
||||
yield i
|
||||
|
||||
class Counting:
|
||||
def __init__(self):
|
||||
self.n = 0
|
||||
|
||||
out = []
|
||||
real = execution._Monitor.item_done
|
||||
|
||||
def item_done(self):
|
||||
with lock:
|
||||
state["finished"] += 1
|
||||
real(self)
|
||||
|
||||
execution._Monitor.item_done = item_done
|
||||
try:
|
||||
out = execution.map(slow, generate(), total=30, log=lambda s: None)
|
||||
finally:
|
||||
execution._Monitor.item_done = real
|
||||
assert out == list(range(30))
|
||||
assert state["peak"] <= max(4, 2 * 2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["sync", "local"])
|
||||
def test_map_on_error_converts_a_failed_item(monkeypatch, mode):
|
||||
monkeypatch.setenv("EXECUTION_MODE", mode)
|
||||
out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None)
|
||||
assert out == [0, 1, 2, -3, 4, 5]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["sync", "local"])
|
||||
def test_map_raises_without_on_error(monkeypatch, mode):
|
||||
monkeypatch.setenv("EXECUTION_MODE", mode)
|
||||
with pytest.raises(RuntimeError, match="three"):
|
||||
execution.map(fail_on_three, range(6), log=lambda s: None)
|
||||
|
||||
|
||||
def test_eta_smoothing_and_threshold():
|
||||
eta = execution.Eta(alpha=0.3, min_done=3)
|
||||
eta.update(0.0, 0)
|
||||
eta.update(1.0, 2)
|
||||
assert eta.eta_s(10) is None # fewer than 3 done
|
||||
eta.update(2.0, 4)
|
||||
assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0)
|
||||
eta.update(3.0, 8) # a faster burst: 4 items/s
|
||||
assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0)
|
||||
assert eta.eta_s(10) == pytest.approx(2 / eta.rate)
|
||||
|
||||
|
||||
def test_progress_tag_and_log_lines_inside_running(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
context = fake_context()
|
||||
with execution.running(context):
|
||||
execution.map(square, range(6), phase="analyzing")
|
||||
first, last = (Progress.model_validate_json(t[execution.PROGRESS_TAG]) for t in
|
||||
(context.tags[0], context.tags[-1])) # fmt: skip
|
||||
assert first.done == 0 and last.done == last.total == 6 and last.phase == "analyzing"
|
||||
assert context.logs[0] == "analyzing: 0/6" and context.logs[-1] == "analyzing: 6/6"
|
||||
summary = context.metadata[-1]
|
||||
assert set(summary) == {"mode", "scheduler", "phases", "peak_cpu_pct", "peak_memory_bytes"}
|
||||
|
||||
|
||||
def test_no_tag_outside_running(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
context = fake_context()
|
||||
execution.map(square, range(3), log=context.logs.append)
|
||||
assert context.tags == [] and context.logs
|
||||
|
||||
|
||||
def test_version_mismatch_fails_before_any_task(monkeypatch):
|
||||
import distributed
|
||||
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "x:8786")
|
||||
submitted = []
|
||||
|
||||
class SpyClient:
|
||||
def __init__(self, *a, **k):
|
||||
self.closed = False
|
||||
|
||||
def submit(self, *a, **k):
|
||||
submitted.append(a)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
monkeypatch.setattr(distributed, "Client", SpyClient)
|
||||
monkeypatch.setattr(cluster, "versions_error", lambda client: "numpy 1.0 vs 2.0")
|
||||
with pytest.raises(execution.ClusterVersionError, match="numpy 1.0 vs 2.0"):
|
||||
execution.map(square, range(3), execution=Execution(mode="remote"))
|
||||
assert submitted == []
|
||||
|
||||
|
||||
CANCEL_SCRIPT = textwrap.dedent(
|
||||
"""
|
||||
import signal, sys
|
||||
from models import execution
|
||||
from models.execution import Execution
|
||||
|
||||
def stop(*a):
|
||||
raise KeyboardInterrupt
|
||||
|
||||
def sleep_forever(x):
|
||||
import time
|
||||
time.sleep(60)
|
||||
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
import cloudpickle
|
||||
cloudpickle.register_pickle_by_value(sys.modules["__main__"])
|
||||
execution.map(sleep_forever, range({n}), log=lambda s: print(s, flush=True),
|
||||
execution=Execution(mode="{mode}"))
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def run_cancelled(mode, n):
|
||||
"""Start a `map` of sleepers in a subprocess, send SIGTERM after its first line."""
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, "-c", CANCEL_SCRIPT.format(n=n, mode=mode)],
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
env={**os.environ, "DASK_LOCAL_WORKERS": "2"},
|
||||
)
|
||||
assert proc.stdout.readline().startswith("working: 0/")
|
||||
time.sleep(3) # the cluster is up and the tasks are submitted
|
||||
return proc
|
||||
|
||||
|
||||
def test_local_cancel_leaves_no_worker_processes():
|
||||
proc = run_cancelled("local", 4)
|
||||
children = psutil.Process(proc.pid).children(recursive=True)
|
||||
assert children
|
||||
proc.send_signal(signal.SIGTERM)
|
||||
proc.wait(timeout=30)
|
||||
deadline = time.time() + 20
|
||||
while time.time() < deadline and any(c.is_running() and c.status() != "zombie"
|
||||
for c in children): # fmt: skip
|
||||
time.sleep(0.5)
|
||||
assert not [c for c in children if c.is_running() and c.status() != "zombie"]
|
||||
|
||||
|
||||
def test_health_sync_and_local(monkeypatch):
|
||||
sync = execution.health(Execution(mode="sync"))
|
||||
assert sync.reachable and sync.workers == 1 and sync.threads == 1
|
||||
local = execution.health(Execution(mode="local"))
|
||||
assert local.reachable and local.workers == 2 and local.versions_ok is None
|
||||
|
||||
|
||||
def test_health_unreachable_remote(monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
|
||||
started = time.time()
|
||||
h = execution.health(Execution(mode="remote"))
|
||||
assert not h.reachable and h.error and time.time() - started < 15
|
||||
|
||||
|
||||
def test_health_rejects_unlisted_scheduler(monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
|
||||
with pytest.raises(ExecutionError):
|
||||
execution.health(Execution(mode="remote", scheduler="tcp://127.0.0.1:2"))
|
||||
with pytest.raises(ExecutionError):
|
||||
execution.health(Execution(mode="sync"), reference="../x")
|
||||
|
||||
|
||||
def test_progress_reaches_the_dagster_run():
|
||||
@dg.op
|
||||
def analyze(context) -> dg.Nothing:
|
||||
with execution.running(context, Execution(mode="sync")):
|
||||
execution.map(square, range(6), phase="analyzing")
|
||||
|
||||
@dg.op(ins={"start": dg.In(dg.Nothing)})
|
||||
def after(context):
|
||||
pass
|
||||
|
||||
@dg.job
|
||||
def two():
|
||||
after(analyze())
|
||||
|
||||
instance = dg.DagsterInstance.ephemeral()
|
||||
result = two.execute_in_process(instance=instance)
|
||||
assert result.success
|
||||
tags = instance.get_run_by_id(result.run_id).tags
|
||||
progress = Progress.model_validate_json(tags[execution.PROGRESS_TAG])
|
||||
assert (progress.done, progress.total, progress.phase) == (6, 6, "analyzing")
|
||||
event = next(e for e in result.events_for_node("analyze") if e.is_successful_output)
|
||||
assert "mode" in event.event_specific_data.metadata
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def scheduler():
|
||||
address = os.environ.get("DASK_TEST_SCHEDULER")
|
||||
if not address:
|
||||
pytest.skip("DASK_TEST_SCHEDULER is not set")
|
||||
expected = int(os.environ["DASK_EXPECTED_WORKERS"])
|
||||
os.environ["DASK_SCHEDULERS"] = address
|
||||
deadline = time.time() + 60
|
||||
while time.time() < deadline:
|
||||
if execution.health(Execution(mode="remote", scheduler=address)).workers == expected:
|
||||
return cluster.normalize(address)
|
||||
time.sleep(1)
|
||||
pytest.fail(f"the scheduler never showed {expected} workers")
|
||||
|
||||
|
||||
def test_map_remote_equals_sync(scheduler, monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
|
||||
items = list(range(12))
|
||||
expected = execution.map(numeric, items, execution=Execution(mode="sync"), log=print)
|
||||
remote = execution.map(numeric, items, execution=Execution(mode="remote"), log=print)
|
||||
assert remote == expected
|
||||
|
||||
|
||||
def test_health_remote(scheduler, monkeypatch):
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
|
||||
h = execution.health(Execution(mode="remote"))
|
||||
assert h.reachable and h.workers == h.expected_workers == 2
|
||||
assert h.versions_ok and h.latency_ms > 0 and h.dashboard_ok
|
||||
|
||||
|
||||
def test_remote_cancel_cancels_futures(scheduler, monkeypatch):
|
||||
from distributed import Client
|
||||
|
||||
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
|
||||
proc = run_cancelled("remote", 8)
|
||||
proc.send_signal(signal.SIGTERM)
|
||||
proc.wait(timeout=30)
|
||||
with Client(scheduler, timeout=10) as client:
|
||||
deadline = time.time() + 20
|
||||
processing = None
|
||||
while time.time() < deadline:
|
||||
processing = client.run_on_scheduler(execution._counts).get("processing", 0)
|
||||
if processing == 0:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
assert processing == 0
|
||||
assert client.scheduler_info()["workers"]
|
||||
|
||||
|
||||
def test_progress_json_is_stable(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
context = fake_context()
|
||||
with execution.running(context):
|
||||
execution.map(square, range(2))
|
||||
assert json.loads(context.tags[-1][execution.PROGRESS_TAG])["mode"] == "sync"
|
||||
@@ -0,0 +1,51 @@
|
||||
"""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) == []
|
||||
+13
-12
@@ -25,6 +25,7 @@ from pathlib import Path
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
import recurrence_reference as reference
|
||||
from joblib.externals.loky import get_reusable_executor
|
||||
from scipy.special import gammaln
|
||||
|
||||
@@ -68,16 +69,17 @@ def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
|
||||
drawn.write_text(PIPELINE.read_text().replace("{reference}", str(RAW)))
|
||||
platform.save("pipelines", "cama_reference", drawn)
|
||||
platform.ingest("cama_reference")
|
||||
# What the training job reads (models.cama.specs), from that platform.
|
||||
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
||||
out = folder / "datasets.pkl"
|
||||
platform.run("python", "-c", "import pandas as pd; from models.cama.specs import MODELS; "
|
||||
f"pd.to_pickle(MODELS['recurrence'].datasets(), {str(out)!r})") # fmt: skip
|
||||
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
||||
f"pd.to_pickle({{s: pd.DataFrame(nodes.rows('cama_reference', s)) "
|
||||
f"for s in {reference.SOURCES!r}}}, {str(out)!r})") # fmt: skip
|
||||
return pd.read_pickle(out)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def prepared(raws):
|
||||
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
|
||||
return {s: reference.prepare(s, raw) for s, raw in raws.items()}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -154,7 +156,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float):
|
||||
# ---------------------------------------------------------------- fast
|
||||
|
||||
|
||||
def test_cohorts(prepared, raws):
|
||||
def test_cohorts(prepared):
|
||||
sampling = _json("rutinas/MUESTREO.json")["cohortes"]
|
||||
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
|
||||
for source, c in prepared.items():
|
||||
@@ -163,18 +165,17 @@ def test_cohorts(prepared, raws):
|
||||
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
||||
assert c.covariates == list(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"]
|
||||
|
||||
|
||||
def test_routines(prepared):
|
||||
found = reports.routines(prepared, modeling.N_BOOTSTRAP)
|
||||
found = reports.routines(prepared, reference.N_BOOTSTRAP)
|
||||
for name, record in found.items():
|
||||
assert record == _json(f"rutinas/{name}.json"), name
|
||||
|
||||
|
||||
def test_c_index_and_internal_auc(fits):
|
||||
rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
|
||||
rows = [r for s in reference.SOURCES for r in reports.auc_rows(fits[s])]
|
||||
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
|
||||
metrics = reports.metrics(rows)
|
||||
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
||||
@@ -205,7 +206,7 @@ def test_saved_model(fits):
|
||||
def test_calculator(fits):
|
||||
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
||||
records, rows = [], []
|
||||
for source in recurrence.SOURCES:
|
||||
for source in reference.SOURCES:
|
||||
found = calculator.calculator(fits[source])
|
||||
records += found[0]
|
||||
rows += found[1]
|
||||
@@ -219,12 +220,12 @@ def test_calculator(fits):
|
||||
def test_risk_factors(fits):
|
||||
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
||||
table = pd.concat(
|
||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
|
||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in reference.SOURCES],
|
||||
ignore_index=True,
|
||||
)
|
||||
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
||||
FACTOR_TOLERANCE) # fmt: skip
|
||||
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
||||
summary = [r for s in reference.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
||||
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
||||
|
||||
|
||||
@@ -261,7 +262,7 @@ def test_fractional_weibull_solver_matches_the_series():
|
||||
@pytest.mark.slow
|
||||
@slow
|
||||
def test_train_reproduces_v1(raws):
|
||||
model, metrics, found = recurrence.train(raws, bootstrap=True)
|
||||
model, metrics, found = reference.train(raws, bootstrap=True)
|
||||
assert metrics == VERSION["metrics"]
|
||||
for h in recurrence.HORIZONS:
|
||||
mine = model.tables[h]
|
||||
|
||||
+13
-7
@@ -6,7 +6,8 @@ one SQL Server table, the institute's forms beside what outsourced labs send bac
|
||||
is a document of its own on its cytology's order; pathology comes scanned, the name surname
|
||||
first and no birth date; some forms say "MA." for María or misspell the name and leave the
|
||||
employee number out; some HPV reports were re-issued the other way; two women share a name.
|
||||
Medical notes (the colposcopy clinic's, oncology's) and death notes are the institute's forms.
|
||||
Medical notes (the colposcopy clinic's, oncology's, neurology's), death notes and TEA's
|
||||
M-CHAT, ADOS-2 and EEG reports are the institute's forms.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -15,19 +16,24 @@ from datetime import date
|
||||
|
||||
from core import catalog
|
||||
|
||||
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number")
|
||||
FIELDS = {
|
||||
"cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
|
||||
"hpv_18"),
|
||||
"cervical_biopsy": ("request_date", "report_date", "histology"),
|
||||
"mammography": ("exam_date", "report_date", "adequacy", "birads"),
|
||||
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
|
||||
"er", "pr", "her2", "ki67_pct", "size_mm", "stage"),
|
||||
"er", "pr", "her2", "ki67_pct", "size_mm", "positive_nodes", "stage"),
|
||||
"breast_treatment": ("start_date", "kind"),
|
||||
"breast_recurrence": ("diagnosis_date", "site"),
|
||||
"clinical_note": ("note_date", "specialty", "icd10"),
|
||||
"death": ("death_date",),
|
||||
"mchat": ("screening_date", "score"),
|
||||
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
||||
"eeg": ("study_date", "lab_record_id", "edf"),
|
||||
} # fmt: skip
|
||||
BOOLS = {"hpv", "hpv_16", "hpv_18"}
|
||||
NUMBERS = {"ki67_pct", "size_mm"}
|
||||
BOOLS = {f for s in catalog.studies().values() for f, d in s.fields.items() if d.type == "boolean"}
|
||||
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
||||
|
||||
|
||||
def value(field, v):
|
||||
@@ -104,7 +110,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
|
||||
# the documents say is read (a scan's columns can come back out of order, and a value its
|
||||
# pattern doesn't find is left out, never guessed). A scan can misread one valid code as
|
||||
# another ("IIA" as "IA"), which nothing in the text betrays: at most 1% of a scan's
|
||||
# values, each listed.
|
||||
# values (one, on a site too small for a rate), each listed.
|
||||
at = {r["where"]: r for r in truth}
|
||||
place = {r: f"ResultadoSubrogado:{i}"
|
||||
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
|
||||
@@ -118,7 +124,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
|
||||
):
|
||||
got = next((v for v in values if v is not None), None)
|
||||
mine.setdefault(record, {})[field] = value(field, got)
|
||||
assert mine, entity
|
||||
assert mine or not any(said(r, entity) for r in truth), entity
|
||||
stated = read = scanned = 0
|
||||
missed: Counter = Counter()
|
||||
wrong = []
|
||||
@@ -134,7 +140,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
|
||||
stated, read = stated + len(truly), read + len(got)
|
||||
missed.update(set(truly) - set(got))
|
||||
assert read >= 0.95 * stated, (entity, read, stated, missed)
|
||||
assert len(wrong) <= 0.01 * scanned, (entity, wrong)
|
||||
assert len(wrong) <= max(1, 0.01 * scanned), (entity, wrong)
|
||||
|
||||
# A row a rule held because of a value (a scan misread) is held because it is wrong:
|
||||
# never loaded, and a reviewer sees it.
|
||||
|
||||
@@ -180,3 +180,32 @@ def test_the_models_points_are_the_survival_of_the_cases_it_learned_from(trained
|
||||
original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")]
|
||||
gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max()
|
||||
print(f"{e['escenario']}: {TRAIN_FRACTION:.0%} training, gap to the original {gap:.3f}")
|
||||
|
||||
|
||||
# The original's names for the categories both rate alike (stage, grade, receptors).
|
||||
SAME = {
|
||||
("Estadio", "IV"): ("stage", "IV"), ("Estadio", "III"): ("stage", "III"),
|
||||
("Estadio", "II"): ("stage", "II"), ("Estadio", "0 (in situ)"): ("stage", "0"),
|
||||
("Grado_histologico", "G3"): ("grade", "3"), ("Grado_histologico", "G1"): ("grade", "1"),
|
||||
("Receptor_progesterona", "Negativo"): ("pr", "negative"),
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
def test_risk_factors_rate_as_the_originals(trained):
|
||||
"""The risk factors of death by 18 months (models.factors, as `06_factores_riesgo.py`)
|
||||
on the same SEER cases: the same direction for every category both rate, the same class
|
||||
for stage and grade, odds ratios within 20 % and 18-month survival within 0.05. The
|
||||
original also rates the stability of its stepwise selection and reads the Markov blanket
|
||||
of a learned network; the platform's model has neither stepwise selection nor PR among
|
||||
its network's parents, so PR negative is "sugerente" here and "robusto" there."""
|
||||
spec, model, _, data = trained
|
||||
members = pd.concat([data["train"], data["test"]]).reset_index(drop=True)
|
||||
ours = survival.risk_factors(spec, model, members).set_index(["variable", "categoria"])
|
||||
theirs = _original("factores_riesgo.csv").set_index(["variable", "categoria"])
|
||||
for key, mine in SAME.items():
|
||||
a, b = theirs.loc[key], ours.loc[mine]
|
||||
assert b["clasificacion"].split()[0] == a["clasificacion"].split()[0], key
|
||||
if key[0] != "Receptor_progesterona":
|
||||
assert b["clasificacion"] == a["clasificacion"], key
|
||||
assert b["OR_muerte"] == pytest.approx(a["OR_muerte"], rel=0.2), key
|
||||
assert b["S_categoria"] == pytest.approx(a["S18_categoria"], abs=0.05), key
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
"""The tea_eeg job's graph, its sensor and the config classes, in process (no EEG data)."""
|
||||
|
||||
import dagster as dg
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from models import definitions
|
||||
from models.definitions import (
|
||||
ExecutionConfig,
|
||||
ScopeConfig,
|
||||
after_ingest,
|
||||
defs,
|
||||
tea_eeg,
|
||||
tea_eeg_after_ingest,
|
||||
)
|
||||
from models.tea import jobs as tea_jobs
|
||||
from persistance import cluster, eeg
|
||||
|
||||
|
||||
def _config(scope: dict) -> dict:
|
||||
return {"ops": {"tea_analyze_studies": {"config": {
|
||||
"scope": scope, "execution": {"mode": "sync"}}}}} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def calls(monkeypatch):
|
||||
log = []
|
||||
|
||||
def analyze(scope=None, *, rebuild_gold=True):
|
||||
log.append(("analyze", scope, rebuild_gold))
|
||||
return 2
|
||||
|
||||
monkeypatch.setattr(tea_jobs, "analyze", analyze)
|
||||
monkeypatch.setattr(tea_jobs, "score_curves", lambda: log.append(("score",)) or {"c": 3})
|
||||
monkeypatch.setattr(tea_jobs, "relate", lambda: log.append(("relate",)))
|
||||
monkeypatch.setattr(definitions.silver, "build", lambda sel: log.append(("build", sel)))
|
||||
return log
|
||||
|
||||
|
||||
def test_tea_eeg_runs_the_four_steps_in_order(calls):
|
||||
result = tea_eeg.execute_in_process(
|
||||
instance=dg.DagsterInstance.ephemeral(), run_config=_config({"mode": "first_n", "n": 2})
|
||||
)
|
||||
assert result.success
|
||||
assert [c[0] for c in calls] == ["analyze", "score", "relate", "build"]
|
||||
assert calls[0][1].n == 2 and calls[0][2] is False
|
||||
assert calls[3][1] == tea_jobs.GOLD_SELECT
|
||||
assert result.output_for_node("tea_analyze_studies") == {"analysed": 2}
|
||||
assert result.output_for_node("tea_score_curves") == {"scored": {"c": 3}}
|
||||
assert result.output_for_node("tea_relate_ados2") == {"ados2_association": None}
|
||||
assert result.output_for_node("tea_build_gold") == {"built": tea_jobs.GOLD_SELECT}
|
||||
|
||||
|
||||
def test_a_failing_analysis_stops_the_graph(calls, monkeypatch):
|
||||
def boom(scope=None, *, rebuild_gold=True):
|
||||
raise RuntimeError("no signal")
|
||||
|
||||
monkeypatch.setattr(tea_jobs, "analyze", boom)
|
||||
result = tea_eeg.execute_in_process(
|
||||
instance=dg.DagsterInstance.ephemeral(),
|
||||
run_config=_config({"mode": "pending"}),
|
||||
raise_on_error=False,
|
||||
)
|
||||
assert not result.success
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_a_bad_scope_fails_before_any_work(calls):
|
||||
result = tea_eeg.execute_in_process(
|
||||
instance=dg.DagsterInstance.ephemeral(),
|
||||
run_config=_config({"mode": "first_n"}),
|
||||
raise_on_error=False,
|
||||
)
|
||||
assert not result.success
|
||||
assert calls == []
|
||||
failure = next(e for e in result.all_events if e.is_step_failure)
|
||||
assert "first_n needs n" in str(failure.event_specific_data.error)
|
||||
|
||||
|
||||
def test_scope_validation():
|
||||
assert eeg.Scope().mode == "pending"
|
||||
assert eeg.Scope(mode="first_n", n=3).n == 3
|
||||
good = "p1|2024-05-06"
|
||||
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
|
||||
bad = [
|
||||
{"mode": "first_n"},
|
||||
{"mode": "first_n", "n": 0},
|
||||
{"mode": "first_n", "n": 2, "ids": [good]},
|
||||
{"mode": "ids"},
|
||||
{"mode": "ids", "ids": [good], "n": 1},
|
||||
{"mode": "ids", "ids": ["nobar"]},
|
||||
{"mode": "ids", "ids": ["p|2024-5-6"]},
|
||||
{"mode": "ids", "ids": ["|2024-05-06"]},
|
||||
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
|
||||
{"mode": "pending", "n": 1},
|
||||
{"mode": "pending", "ids": [good]},
|
||||
{"mode": "other"},
|
||||
{"extra": 1},
|
||||
]
|
||||
for kwargs in bad:
|
||||
with pytest.raises(ValidationError):
|
||||
eeg.Scope(**kwargs)
|
||||
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
|
||||
with pytest.raises(ValidationError, match="first_n needs n"):
|
||||
ScopeConfig(mode="first_n").model()
|
||||
|
||||
|
||||
def test_config_mirrors_match_the_shared_models():
|
||||
for config, shared in ((ScopeConfig, eeg.Scope), (ExecutionConfig, cluster.Execution)):
|
||||
assert list(config.model_fields) == list(shared.model_fields)
|
||||
for name, field in shared.model_fields.items():
|
||||
assert config.model_fields[name].default == field.default, name
|
||||
# a wrong value still reaches the shared model's validation
|
||||
with pytest.raises(ValidationError):
|
||||
ExecutionConfig(mode="cloud").model()
|
||||
with pytest.raises(ValidationError):
|
||||
ScopeConfig(mode="all").model()
|
||||
|
||||
|
||||
def test_after_ingest_requests_a_run_only_with_pending_eegs():
|
||||
skip = after_ingest("r1", lambda: False)
|
||||
assert isinstance(skip, dg.SkipReason)
|
||||
request = after_ingest("r1", lambda: True)
|
||||
assert isinstance(request, dg.RunRequest)
|
||||
assert request.run_key == "after-ingest-r1"
|
||||
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
|
||||
assert scope == {"mode": "pending"}
|
||||
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
|
||||
|
||||
|
||||
def test_definitions_load_with_every_job_and_the_sensor():
|
||||
dg.Definitions.validate_loadable(defs)
|
||||
names = {j.name for j in defs.jobs}
|
||||
assert names >= {"ingest", "train", "score", "analyze", "tea_eeg"}
|
||||
assert tea_eeg_after_ingest.default_status == dg.DefaultSensorStatus.RUNNING
|
||||
|
||||
|
||||
def test_relate_is_a_no_op_until_phase_2():
|
||||
assert tea_jobs.relate() is None
|
||||
Reference in New Issue
Block a user