Compare commits

..

17 Commits

Author SHA1 Message Date
edgar 55fa6ddd9f Cover CaCu cytology fields in the silver gate
Adapted to rebuild, preserving its existing fields. Based on 1f0d38d, 7b6ffe1, 1dc681f, 8908184, 0fcbe95 and a93292f.
2026-11-30 16:00:32 -06:00
Roberto Treviño 3a749ba8d1 A nightly Dagster job backs up the data folder 2026-11-29 12:38:56 -06:00
Roberto Treviño f369e8f2eb Survival rates its scenarios' risk factors as Luis's code does; recurrence shares the factor code 2026-11-29 12:38:56 -06:00
Roberto Treviño f3f79831bf Each domain's jobs name the models a score run takes 2026-11-29 07:03:08 -06:00
Roberto Treviño 43207fa3a5 Scoring runs every champion, slow models too 2026-11-29 06:43:08 -06:00
Roberto Treviño 7e8e8b44d8 Silver checks the site's recurrences and positive nodes 2026-11-29 01:50:23 -06:00
Roberto Treviño 5c781f2a52 The recurrence report names the site's own cohort 2026-11-29 01:20:40 -06:00
Roberto Treviño 8e9da2c73a The site cohort keeps redundant covariates for its scenarios 2026-11-29 00:41:24 -06:00
Roberto Treviño 53e6f77c9e Every model trains on the site: EEG age curves on the children with TEA ruled out, recurrence on the site's patients (St. Gallen subtype), and the EEG–ADOS-2 association 2026-11-28 21:28:36 -06:00
Roberto Treviño 924f662a21 Survival scores name the report's clinical scenarios each patient falls in 2026-11-28 09:29:59 -06:00
Roberto Treviño 1a46a5ba73 Link each distinct identity once, not every pair of a patient's records 2026-11-28 01:17:40 -06:00
Roberto Treviño 61eb3a30d0 Read works through files a batch at a time and keeps each batch 2026-11-27 22:29:23 -06:00
Roberto Treviño 0c78f8cf7d OCR only on the pages without text; otherwise routes; batches on Dask through its own API 2026-11-27 19:17:49 -06:00
Roberto Treviño 385cc5b80b Read keeps the file and says its format; extract takes fields from columns; EEG batches carry their recording, on Dask where it is installed 2026-11-27 16:25:01 -06:00
Roberto Treviño 3546269eaf Review queues a scan read only in part, and an undated name one typo from a person 2026-11-27 14:02:08 -06:00
Roberto Treviño 7b9ae69de2 CaCu models record the outcomes each split holds 2026-11-27 11:05:28 -06:00
Roberto Treviño 4ff4a3a7d8 A person nothing names is held for review; a scan may misread one valid code as another 2026-11-27 08:46:05 -06:00
23 changed files with 1407 additions and 377 deletions
+5
View File
@@ -80,6 +80,9 @@ class Pim:
found = {
"n_train": len(train),
"n_test": len(test),
# outcomes, prevalent or incident, each split learned from or was judged on
"events_train": float(((train["c"] == 1) | np.isfinite(train["r"])).sum()),
"events_test": float(((test["c"] == 1) | np.isfinite(test["r"])).sum()),
"neg_loglik": mixture.neg_loglik_,
"converged": float(mixture.converged_),
}
@@ -139,6 +142,8 @@ class Logistic:
metrics = {
"n_train": len(train),
"n_test": len(test),
"events_train": float(train["y"].sum()),
"events_test": float(test["y"].sum()),
"auc": float(roc_auc_score(test["y"], p)),
"brier": float(brier_score_loss(test["y"], p)),
"positive_rate_train": float(train["y"].mean()),
+26 -11
View File
@@ -60,26 +60,41 @@ class Recurrence:
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.
"""Both reference cohorts' models, validation, calculator and risk factors, from their
datasets' rows; the saved model is METABRIC's.
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
stability criterion, are then missing)."""
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
return fit(found, SAVED, "metabric+scanb", bootstrap)
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""The same, on the site's own cohort (models.cama.recurrence.site)."""
from models.cama.recurrence import site
return fit({"site": site.prepare(rows)}, "site", "site", bootstrap)
def fit(found: dict, saved: str, label: str,
bootstrap: bool = True) -> 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)
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
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 +102,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_
+2 -1
View File
@@ -21,7 +21,7 @@ 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"}
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"}
# Each scenario: covariate -> the categories it takes (AND across covariates).
SCENARIOS = {
@@ -59,6 +59,7 @@ SCENARIOS = {
"Grado 3": {"Grado_histologico": ["3"]},
},
} # fmt: skip
SCENARIOS["site"] = SCENARIOS["scanb"] # the site's cohort is described as SCAN-B's
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
+24 -168
View File
@@ -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 import factors as rated
from models.cama.recurrence.calculator import SCENARIOS, 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)
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
+2 -7
View File
@@ -21,6 +21,7 @@ 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.factors import variable_of
HORIZONS = (12, 36, 60) # months
SEED = 42
@@ -31,7 +32,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 = {"metabric": 100, "scanb": 40, "site": 40}
# ---------------------------------------------------------------- logistic regression
@@ -203,12 +204,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
+13 -4
View File
@@ -15,7 +15,6 @@ from models.cama.recurrence.modeling import (
ESS,
HORIZONS,
MAX_PARENTS,
N_BOOTSTRAP,
CohortFit,
)
@@ -96,6 +95,17 @@ def metrics(auc: list[dict]) -> dict[str, float]:
return found
REFERENCE_SAMPLING = {
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
"origen": "METABRIC y SCAN-B (externas)",
}
SITE_SAMPLING = {
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
"libre de ella hasta su defunción o la fecha de corte",
"origen": "la sede (sus propias pacientes)",
}
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
"""The five routine records a promotion reads."""
return {
@@ -109,8 +119,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)",
**(SITE_SAMPLING if "site" in cohorts else REFERENCE_SAMPLING),
},
"DATOS_FALTANTES": {
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
@@ -137,7 +146,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,
+109
View File
@@ -0,0 +1,109 @@
"""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]
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 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)
+32 -24
View File
@@ -7,17 +7,17 @@
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); slow (its bootstraps
take minutes), so it trains only when asked for by name."""
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 +89,40 @@ 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
cohort: str = "cama_cohort_recurrence"
slow: bool = True
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
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
return recurrence.train_site(site.frame(events, as_of or date.today()))
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, calculator.SCENARIOS["site"])
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 +153,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 +161,5 @@ MODELS = {
"efecto protector del tratamiento aparece mayor de lo que es.",
),
),
"recurrence": ReferenceRecurrence("recurrence"),
"recurrence": SiteRecurrence("recurrence"),
}
+52
View File
@@ -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()
+28 -2
View File
@@ -1,12 +1,14 @@
"""Dagster code location: every heavy step of the platform is a job defined here."""
import importlib
import os
from datetime import date
import dagster as dg
from models import graph
from models.jobs import EmptyCohort
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)
@@ -76,7 +78,7 @@ class Scoring(dg.Config):
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
jobs = _jobs(config.domain)
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.routine()}
found = {name: jobs.score(name) for name in config.models or jobs.JOBS.scored()}
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
@@ -105,4 +107,28 @@ def analyze():
analyze_studies()
defs = dg.Definitions(jobs=[ingest, train, score, analyze])
@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 []
)
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
+178
View File
@@ -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
+139 -37
View File
@@ -10,9 +10,11 @@ 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
@@ -45,14 +47,28 @@ from core.pipeline import (
)
from persistance import config_log, files, 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)
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},
}
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
def _reader() -> MarkItDown:
return MarkItDown()
@@ -64,52 +80,93 @@ 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 |= {k: result[k] for k in READ_COLUMNS}
return nodes.write(p, node.id, rows, READ_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]]:
@@ -191,8 +248,9 @@ def run_extract(p: str, node: Extract):
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 +314,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"
@@ -267,38 +347,46 @@ def run_link(p: str, node: Link):
"""Persons: records the node's rules join (Splink deterministic linking), joined or kept
apart by reviewers' decisions. A person whose records disagree on birth date or sex is
held. Persons that may be one (identifiers one typo apart, or the same birth date) and
don't contradict each other are queued for review, with Splink's probability."""
don't contradict each other are queued for review, with Splink's probability. A person
with nothing that names her (no name, birth date or record number read) is held too."""
records, sources, written = _identities(p, node)
fields = [c for c in records.columns if c != "unique_id"]
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()
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
held = json.dumps(["records of this person disagree on birth date or sex"])
# Nothing that names her was read (a scan's name line misread, say): nobody to join.
read = persons.groupby("cluster_id")[[f for f in fields if f != "sex"]].count().sum(axis=1)
nameless = set(read[read == 0].index)
why = {c: "records of this person disagree on birth date or sex" for c in torn}
why |= {c: "no name, birth date or record number was read" for c in nameless - torn}
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, "_source", *fields)}
stable = nodes.stable_persons(persons.groupby("cluster_id")["unique_id"].apply(list).to_dict())
linked = [
{RECORD: r.unique_id, "person_id": stable[r.cluster_id], "_source": sources[r.unique_id],
HELD: held if r.cluster_id in torn else None,
HELD: json.dumps([why[r.cluster_id]]) if r.cluster_id in why else None,
**{f: getattr(r, f) for f in fields},
**({"full_name": written[r.unique_id]} if r.unique_id in written else {})}
for r in persons.itertuples()
@@ -335,6 +423,8 @@ def run_link(p: str, node: Link):
known = [f for f in ("birth_date", "sex") if f in fields]
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()
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()
@@ -344,15 +434,23 @@ def run_link(p: str, node: Link):
"""(the person to settle, a possible owner), or None when the pair is implausible:
they contradict each other, or one typo apart is all they share (with sequential
record numbers every patient has such neighbours) unless one side has no
demographics and the other's identifier stands on a single record."""
demographics and the other's identifier stands on a single record. Names one typo
apart are rare: an undated side (a misread pathology scan) is always queued; so is the
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(
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
):
return None
if not reasons[int(r.match_key)].endswith("typo apart"):
reason = reasons[int(r.match_key)]
if not reason.endswith("typo apart"):
return a, b
field = reason.removesuffix(" one typo apart")
if getattr(r, f"{field}_l") == getattr(r, f"{field}_r"): # the very same identifier
return (a, b) if a in undated or b not in undated else (b, a)
if field == "full_name" and (a in undated) != (b in undated):
return (a, b) if a in undated else (b, a) # names are rarely one typo apart
if a in orphan and b in lone:
return a, b
if b in orphan and a in lone:
@@ -424,6 +522,10 @@ 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")
+11 -1
View File
@@ -41,9 +41,14 @@ class Jobs:
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."""
"""The models a train 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)]
def scored(self) -> list[str]:
"""The models a score run takes when none is named: all of them (only training is
slow)."""
return list(self.models)
def registered(self, name: str) -> str:
return f"{self.domain}.{name}"
@@ -53,6 +58,11 @@ class Jobs:
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)
elif getattr(spec, "reports", False): # trained on its cohort, with its own reports
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)
else:
events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty:
+111 -2
View File
@@ -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,9 @@ class IntervalSurvival(BaseEstimator):
# ---------------------------------------------------------------- a model over gold timelines
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",
"scenarios"] # 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 +269,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 +330,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 +348,7 @@ 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),
})[OUTPUT] # fmt: skip
@@ -496,4 +507,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),
}
+389
View File
@@ -0,0 +1,389 @@
"""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; its
odds ratio, a 95 % profile-likelihood interval and a likelihood-ratio p), with a
cumulative-logit model of the item's level as sensitivity; the CSS the other way round.
- q: Benjamini–Hochberg within each biomarker.
- 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).
The old platform's `ados2_association` 0.1.0, reproduced (tests/test_tea_association.py)."""
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 statsmodels.stats.multitest import multipletests
from core.tea import association as spec
CHI2_95 = float(stats.chi2.ppf(0.95, 1))
MIN_ROWS = 8
TOO_FEW = "too few data or no variation"
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
@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 spec.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 _firth_fit(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 firth(t: pd.DataFrame, outcome: str, predictor: str) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
y = d[outcome].to_numpy(float)
out = {"model": "firth", "n": len(d), "events": int(y.sum())}
if len(d) < MIN_ROWS or y.sum() < 2 or y.sum() > len(y) - 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW}
design = Design.of(d, predictor)
X = design.matrix(d)
b, top = _firth_fit(X, y)
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))
# FLIC: the intercept refitted so the probabilities add up to the events.
eta = X[:, 1:] @ b[1:]
intercept = optimize.brentq(lambda a: expit(a + eta).sum() - y.sum(), -50, 50)
state = {"beta": [float(v) for v in b[1:]], "intercept": float(intercept)}
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 _ordinal_fit(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(t: pd.DataFrame, outcome: str, predictor: str, high: float) -> dict:
d = t[[outcome, predictor, *(a for a in spec.ADJUST if a in t)]].dropna()
levels = np.sort(d[outcome].unique())
out = {"model": "ordinal", "n": len(d), "levels": len(levels)}
if len(d) < MIN_ROWS or len(levels) < 2 or d[predictor].std() == 0:
return {**out, "reason": TOO_FEW}
design = Design.of(d, predictor)
X = design.matrix(d)[:, 1:]
K = len(levels)
y = np.searchsorted(levels, d[outcome].to_numpy())
with warnings.catch_warnings():
warnings.simplefilter("ignore")
par, nll = _ordinal_fit(X, y, K)
beta = par[K - 1 :]
if abs(beta[0]) > 20:
return {**out, "reason": "does not converge (separation)"}
profile = lambda v: -_ordinal_fit(X, y, K, fixed=(0, v))[1] # noqa: E731
low, high_ = _interval(profile, beta[0], -nll, 0.1)
p = float(stats.chi2.sf(max(2 * (-nll - profile(0.0)), 0.0), 1))
theta = np.cumsum(np.r_[par[0], np.exp(par[1 : K - 1])])
k = int(np.searchsorted(levels, high))
inside = 0 < k < K
state = {
"beta": [float(v) for v in beta],
"threshold": float(theta[k - 1]) if inside else None,
"always": None if inside else float(k == 0),
}
return _summary("ordinal", len(d), beta[0], low, high_, p, design, state, levels=K)
def probability(fit: dict, t: pd.DataFrame) -> tuple[np.ndarray, float]:
"""Each child's probability of the outcome under `fit`, and the reference child's."""
s = fit["state"]
X = Design.from_state(s["design"]).matrix(t)
if fit["model"] == "firth":
return expit(s["intercept"] + X[:, 1:] @ np.asarray(s["beta"])), float(
expit(s["intercept"])
)
if s["threshold"] is None:
return np.where(np.isnan(X[:, 1:]).any(axis=1), np.nan, s["always"]), s["always"]
return (
1 - expit(s["threshold"] - X[:, 1:] @ np.asarray(s["beta"])),
float(1 - expit(s["threshold"])),
)
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 fit(cohort: pd.DataFrame, level: str = "auto") -> dict:
"""Every pair's principal and sensitivity models and its q: what the association is."""
if level == "auto":
level = "item" if has_items(cohort) else "domain"
rows = []
for pair in spec.pairs(level):
if pair["predictor"] not in cohort:
continue
d = cohort.copy()
d[pair["predictor"]] = d[pair["predictor"]].replace([np.inf, -np.inf], np.nan)
if pair["kind"] == "item":
d["_level"] = item_scores(cohort, pair["outcome"])
d["_yes"] = (d["_level"] >= spec.ALTERED).astype(float).where(d["_level"].notna())
principal = _guarded(firth, d, "_yes", pair["predictor"])
sensitivity = _guarded(ordinal, d, "_level", pair["predictor"], spec.ALTERED)
else:
d["_level"] = pd.to_numeric(cohort.get("css"), errors="coerce")
d["_yes"] = (d["_level"] >= spec.CSS_HIGH).astype(float).where(d["_level"].notna())
principal = _guarded(ordinal, d, "_level", pair["predictor"], spec.CSS_HIGH)
sensitivity = _guarded(firth, d, "_yes", pair["predictor"])
rows.append({**pair, "principal": principal, "sensitivity": sensitivity})
p = np.array([r["principal"].get("p", np.nan) for r in rows], float)
biomarkers = np.array([r["biomarker"] for r in rows])
q = np.full(len(rows), np.nan)
for b in dict.fromkeys(biomarkers):
mine = (biomarkers == b) & np.isfinite(p)
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 {"level": level, "n": len(cohort), "rows": rows}
def outcome_code(row: dict) -> str:
return spec.item_code(row["outcome"]) if row["kind"] == "item" else spec.CSS
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": outcome_code(r),
"event": f">={spec.ALTERED if r['kind'] == 'item' else spec.CSS_HIGH}",
"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", ""),
}
)
return out
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 fitted["rows"]:
f = r["principal"]
if f.get("odds_ratio") is None or r["predictor"] not in cohort:
continue
t = cohort
if r["kind"] == "item":
t = cohort[cohort["module"].isin(spec.ITEMS[r["outcome"]][1])]
t = t[t[r["predictor"]].notna()]
if not len(t):
continue
found, reference = probability(f, t)
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": outcome_code(r),
"z": float(z),
"probability": round(float(p), 4),
"reference_probability": round(reference, 4),
}
)
return out
+8 -10
View File
@@ -8,12 +8,11 @@ mains, with the table's age) in worker processes; `tables` gives each scenario's
from the valid studies.
"""
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import pandas as pd
from models import cluster
from models.tea.eeg.analysis import analyze
from models.tea.eeg.curves import SCENARIOS
@@ -34,9 +33,8 @@ def listing(folder: Path, ages_table: Path, ages=AGES) -> list[tuple[str, Path,
return [(f"{NAME}-{k:04d}", path, age) for k, (path, age) in enumerate(found, 1)]
def _one(study: tuple[str, Path, float]) -> dict:
key, path, age = study
a = analyze(Path(path).read_bytes(), age_months=age, mains_hz=MAINS_HZ)
def _one(key: str, edf: bytes, age: float) -> dict:
a = analyze(edf, age_months=age, mains_hz=MAINS_HZ)
return {
"key": key,
"age_months": age,
@@ -46,11 +44,11 @@ def _one(study: tuple[str, Path, float]) -> dict:
}
def measure(studies, workers: int = 4) -> list[dict]:
"""Each study's verdict and features, in listing order."""
context = multiprocessing.get_context("spawn")
with ProcessPoolExecutor(workers, mp_context=context) as pool:
return list(pool.map(_one, studies))
def measure(studies) -> 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) for key, path, age in studies))
def tables(measured: list[dict]) -> dict[str, pd.DataFrame]:
+143 -48
View File
@@ -1,27 +1,27 @@
"""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 joblib import Parallel, delayed
from joblib.externals.loky import get_reusable_executor
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
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)
@@ -40,39 +40,18 @@ class Baseline(mlflow.pyfunc.PythonModel):
for r in rows]) # fmt: skip
def _analyze(edf: str, birth) -> tuple[str, analysis.Analysis]:
return edf, analysis.analyze(eeg.signal(edf), birth)
def analyze() -> int:
"""Every hospital EEG not analysed yet; then gold's TEA tables are rebuilt."""
pending = eeg.pending()
found = dict(Parallel(n_jobs=-1)(delayed(_analyze)(r["edf"], r["birth_date"])
for r in pending)) # fmt: skip
get_reusable_executor().shutdown(wait=True)
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)
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, workers=os.cpu_count() or 4)
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."""
@@ -80,6 +59,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()
@@ -89,27 +71,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(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))
@@ -117,7 +115,7 @@ 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)
@@ -139,3 +137,100 @@ def score(name: str) -> int | None:
"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 and the z of each biomarker; fitted on each child's first EEG with
any z, every EEG scored."""
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)}
css, _ = ados2.score(row, date.fromisoformat(r["birth_date"]))
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_")}}) # fmt: skip
scored = pd.DataFrame(rows)
if scored.empty:
return scored, scored
predictors = [c for c in scored.columns if c.startswith("z_")]
with_z = scored[predictors].notna().any(axis=1) if predictors else scored["key"].isna()
fit = scored[with_z].drop_duplicates("person").reset_index(drop=True)
return fit.drop(columns=["person"]), scored.drop(columns=["person"])
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, "method": "Firth logistic (items) / cumulative logit (CSS), "
"adjusted for age and module; profile-likelihood 95 % CI; Benjamini–Hochberg q",
"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, or the CSS
if not scored.empty:
keys = scored["key"].tolist()
for n in relation.ITEMS:
items = association.item_scores(scored, n).tolist()
observed[relation.item_code(n)] = dict(zip(keys, items, strict=True))
observed[relation.CSS] = dict(zip(keys, scored["css"].tolist(), 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
+6
View File
@@ -11,8 +11,10 @@ dependencies = [
"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",
@@ -24,6 +26,10 @@ dependencies = [
"pgmpy>=1.1.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"
+1 -1
View File
@@ -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
+6 -18
View File
@@ -27,15 +27,8 @@ def graph(tmp: Path, hospital_tables: dict[str, list[str]], site_url: str) -> di
return {
"nodes": nodes
+ [
table("archivos", site_url, "ArchivosUni", schema="dbo"),
table("subrogados", site_url, "ResultadosSubrogados", schema="dbo"),
{"id": "archivos_text", "kind": "read", "inputs": ["archivos"], "column": "archivo"},
{
"id": "subrogados_text",
"kind": "read",
"inputs": ["subrogados"],
"column": "archivo",
},
table("resultados", site_url, "ResultadoSubrogado", schema="dbo"),
{"id": "text", "kind": "read", "inputs": ["resultados"], "column": "archivo"},
]
}
@@ -58,13 +51,8 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, t
by_place = {}
for r in truth:
by_place.setdefault(r["where"].split(":")[0], []).append(r)
documents = len(by_place["ArchivosUni"]) + len(by_place["ResultadosSubrogados"])
expected = {
"archivos": len(by_place["ArchivosUni"]),
"subrogados": len(by_place["ResultadosSubrogados"]),
"archivos_text": len(by_place["ArchivosUni"]),
"subrogados_text": len(by_place["ResultadosSubrogados"]),
}
documents = len(truth)
expected = {"resultados": documents, "text": documents}
for name, names in tables.items():
with sqlite3.connect(tmp_path / f"hospital_{name}.db") as con:
for t in names:
@@ -87,8 +75,8 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, site, t
assert query(corrected) == [("64000",)]
space = re.compile(r"\s+")
for table, node in (("ArchivosUni", "archivos"), ("ResultadosSubrogados", "subrogados")):
read = query(f"select id, text, ocr, error from bronze.n__site__{node}_text")
for table in ("ResultadoSubrogado",):
read = query("select id, text, ocr, error from bronze.n__site__text")
assert [error for *_, error in read if error is not None] == []
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
for r in by_place[table]:
+4 -3
View File
@@ -68,10 +68,11 @@ 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; "
"from models.cama import recurrence; pd.to_pickle({s: pd.DataFrame(nodes.rows("
f"'cama_reference', s)) for s in recurrence.SOURCES}}, {str(out)!r})") # fmt: skip
return pd.read_pickle(out)
+89 -40
View File
@@ -2,10 +2,12 @@
can trust, and everything the platform can't decide alone is put in front of a reviewer.
The source hides its answers the way the real one does (synthetic.site): one PDF per study in
two SQL Server tables, the institute's forms and what outsourced labs send back; an HPV result
one SQL Server table, the institute's forms beside what outsourced labs send back; an HPV result
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, neurology's), death notes and TEA's
M-CHAT, ADOS-2 and EEG reports are the institute's forms.
"""
import json
@@ -14,25 +16,52 @@ from datetime import date
from core import catalog
GYN = ("gyn_puerperium", "gyn_pregnancy", "gyn_iud",
"gyn_hormonal_treatment", "gyn_other_treatment",
"gyn_postmenopause", "gyn_hysterectomy", "gyn_not_applicable")
PRESENTS = ("presents_discharge", "presents_vulvar_pruritus",
"presents_abnormal_bleeding", "presents_none")
CYTO = ("cyto_inflammation", "cyto_reactive_changes",
"cyto_bacterial_vaginosis_flora", "cyto_candida",
"cyto_bacillary_flora_cytolysis", "cyto_intermediate_cytolysis",
"cyto_trichomonas", "cyto_leptothrix",
"cyto_actinomyces_organisms", "cyto_actinomyces_changes",
"cyto_herpes_simplex_changes", "cyto_squamous_tubular_metaplasia",
"cyto_keratotic_changes", "cyto_pregnancy_changes",
"cyto_atrophy", "cyto_hypoestrogenism",
"cyto_radiotherapy_effect", "cyto_iud_changes",
"cyto_post_hysterectomy_glandular_cells",
"cyto_bacteria", "cyto_herpes_image",
"cyto_fungi", "cyto_radiation",
"cyto_repair", "cyto_iud_effect",
"cyto_endometrial_cells_40_plus", "cyto_findings_none")
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number")
GYN = (
"gyn_puerperium",
"gyn_pregnancy",
"gyn_iud",
"gyn_hormonal_treatment",
"gyn_other_treatment",
"gyn_postmenopause",
"gyn_hysterectomy",
"gyn_not_applicable",
)
PRESENTS = (
"presents_discharge",
"presents_vulvar_pruritus",
"presents_abnormal_bleeding",
"presents_none",
)
CYTO = (
"cyto_inflammation",
"cyto_reactive_changes",
"cyto_bacterial_vaginosis_flora",
"cyto_candida",
"cyto_bacillary_flora_cytolysis",
"cyto_intermediate_cytolysis",
"cyto_trichomonas",
"cyto_leptothrix",
"cyto_actinomyces_organisms",
"cyto_actinomyces_changes",
"cyto_herpes_simplex_changes",
"cyto_squamous_tubular_metaplasia",
"cyto_keratotic_changes",
"cyto_pregnancy_changes",
"cyto_atrophy",
"cyto_hypoestrogenism",
"cyto_radiotherapy_effect",
"cyto_iud_changes",
"cyto_post_hysterectomy_glandular_cells",
"cyto_bacteria",
"cyto_herpes_image",
"cyto_fungi",
"cyto_radiation",
"cyto_repair",
"cyto_iud_effect",
"cyto_endometrial_cells_40_plus",
"cyto_findings_none",
)
FIELDS = {
"cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS,
"cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16",
@@ -40,12 +69,17 @@ FIELDS = {
"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", *GYN, *PRESENTS, *CYTO}
NUMBERS = {"ki67_pct", "size_mm"}
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
def value(field, v):
@@ -77,17 +111,27 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
# Persons: nobody is merged with somebody else, except the two women of one name, joined
# by a pathology report (it shows no birth date) and held (torn) until a reviewer says
# whose report it is.
# A person nothing names (a scan whose name line wasn't read) is held as well: there is
# nobody to join her to.
members: dict[str, set] = {}
held, person_of = set(), {}
for record, person, why in q("select _record, person_id, _held from bronze.n__site__persons"):
held, nameless, named, person_of = set(), set(), set(), {}
for record, person, why, *identifiers in q(
"select _record, person_id, _held, full_name, birth_date, record_number "
"from bronze.n__site__persons"
):
members.setdefault(person, set()).add(of[record])
person_of[record] = person
if why:
if any(identifiers):
named.add(person)
if why and "no name" in why:
nameless.add(person)
elif why:
held.add(person)
assert nameless == set(members) - named, nameless
torn = {p for p, who in members.items() if len(who) > 1}
assert len(torn) == 1 and torn == held, (torn, held)
assert members[next(iter(torn))] == set(site.meta["namesakes"])
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn}
patient = {p: next(iter(who)) for p, who in members.items() if p not in torn | nameless}
# Every woman split into several persons (a misspelled form, say) is in the review
# queue, joined by candidates.
@@ -108,15 +152,14 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
frontier -= reached
assert persons <= reached, (x, persons)
# Every value accepted from a document is what the document says; and most of what 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).
# Every value accepted from a typed document is what the document says; and most of what
# 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 (one, on a site too small for a rate), each listed.
at = {r["where"]: r for r in truth}
place = {
r: f"ArchivosUni:{i}" for i, r in q("select id, _record from bronze.n__site__archivos")
}
place |= {r: f"ResultadosSubrogados:{i}"
for i, r in q("select id, _record from bronze.n__site__subrogados")} # fmt: skip
place = {r: f"ResultadoSubrogado:{i}"
for i, r in q("select id, _record from bronze.n__site__resultados")} # fmt: skip
record_of = {w: r for r, w in place.items()}
accepted: dict[str, dict[str, dict]] = {} # study -> record -> fields (from silver's long rows)
for entity in FIELDS:
@@ -127,23 +170,29 @@ 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
stated = read = 0
assert mine or not any(said(r, entity) for r in truth), entity
stated = read = scanned = 0
missed: Counter = Counter()
wrong = []
for record, got in mine.items():
t = at[place[record]]
if not t.get("flipped"):
truly = {f: v for f, v in said(t, entity).items() if v is not None}
assert got == {f: value(f, truly.get(f)) for f in got}, (t["where"], got)
differ = {f: (v, value(f, truly.get(f))) for f, v in got.items()
if v != value(f, truly.get(f))} # fmt: skip
assert t.get("scanned") or not differ, (t["where"], differ)
wrong += [(t["where"], differ)] if differ else []
scanned += len(got) if t.get("scanned") else 0
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) <= 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.
misread = set()
for record, entity, raw in q("select _record, study, _raw from bronze.staged__held"):
if record in place and person_of.get(record) not in torn:
if record in place and person_of.get(record) not in torn | nameless:
t, got = at[place[record]], json.loads(raw)
truly = said(t, entity)
assert {f: value(f, got.get(f)) for f in truly} != {
@@ -160,7 +209,7 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
for r in truth:
record = record_of[r["where"]]
got = accepted[entity].get(record)
if got is None or person_of[record] in torn or record in misread:
if got is None or person_of[record] in torn | nameless or record in misread:
continue
at_key = (person_of[record], *(got.get(k) for k in key))
merged.setdefault(at_key, {}).update(got)
@@ -170,6 +219,6 @@ def test_a_site_becomes_silver_and_review_gets_the_rest(platform, site, tmp_path
for k, row in merged.items() if k not in disputed} # fmt: skip
rows = q(f"select person_id, {', '.join(fields)} from silver.{entity}")
got = {(p, *(value(f, v) for f, v in zip(fields, values, strict=True)))
for p, *values in rows if p not in torn} # fmt: skip
for p, *values in rows if p not in torn | nameless} # fmt: skip
assert got == expected, (entity, sorted(got - expected, key=str)[:4],
sorted(expected - got, key=str)[:4]) # fmt: skip
+29
View File
@@ -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