From 76eb8cc8aff9d99ede239ebebcb694fd778c0b30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o?= Date: Thu, 26 Nov 2026 14:25:53 -0600 Subject: [PATCH] Files read by hash; fractional Weibull solved and fitted to convergence; recurrence reads its reference cohorts from the platform --- models/cama/recurrence/__init__.py | 28 ++--- models/cama/recurrence/cohorts.py | 95 +++++++------- models/cama/recurrence/curves.py | 193 ++++++++++++++--------------- models/cama/specs.py | 31 ++--- models/graph.py | 23 ++-- pyproject.toml | 1 - tests/test_ingest.py | 2 +- tests/test_recurrence.py | 96 +++++++++++--- 8 files changed, 258 insertions(+), 211 deletions(-) diff --git a/models/cama/recurrence/__init__.py b/models/cama/recurrence/__init__.py index 52904d1..df4db1f 100644 --- a/models/cama/recurrence/__init__.py +++ b/models/cama/recurrence/__init__.py @@ -1,10 +1,11 @@ """CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months, -learned from two external reference cohorts, METABRIC and SCAN-B, read from their published -files. Per cohort and horizon, a stepwise logistic regression and a Bayesian network (BDeu -parents of the outcome) are fitted and validated (cohorts, modeling); a calculator gives the -recurrence-free probability of clinical scenarios with bootstrap intervals and survival curves -(calculator, curves); risk factors are rated by four criteria (factors); reports gives the -tables and figures. The saved model is METABRIC's, refitted on each whole horizon cohort.""" +learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their +published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic +regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated +(cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios +with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by +four criteria (factors); reports gives the tables and figures. The saved model is METABRIC's, +refitted on each whole horizon cohort.""" from dataclasses import dataclass @@ -19,14 +20,10 @@ HORIZONS = modeling.HORIZONS # months SAVED = "metabric" -def cohort(source: str, raw: pd.DataFrame) -> pd.DataFrame: - """The source's cohort table: fixed columns, then its covariates as categories.""" - return cohorts.prepare(source, raw).frame - - -def read(source: str, path) -> pd.DataFrame: - """The raw file as its publisher distributes it, as `cohort()` expects it.""" - return cohorts.read(source, path) +def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame: + """The source's cohort table, from its dataset's rows: fixed columns, then its + covariates as categories.""" + return cohorts.prepare(source, rows).frame @dataclass @@ -63,7 +60,8 @@ 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 raw files. + """Both cohorts' models, validation, calculator and risk factors, from their datasets' + rows. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors' stability criterion, are then missing).""" found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES} diff --git a/models/cama/recurrence/cohorts.py b/models/cama/recurrence/cohorts.py index ec9cb6b..21cffda 100644 --- a/models/cama/recurrence/cohorts.py +++ b/models/cama/recurrence/cohorts.py @@ -1,8 +1,10 @@ -"""Each reference cohort's raw file as one table of categories: the patients with a known -recurrence time and status, their time to recurrence (`tiempo_meses`), whether it happened -(`evento`), and their covariates as text. A missing or out-of-range value is a category of its -own (UNKNOWN); nothing is imputed or dropped for it. Of each pair of nearly redundant -covariates (Cramér's V >= V_MAX), the one with more unknowns is dropped.""" +"""Each reference cohort as one table of categories, from its dataset as the platform loaded +it (the `cama_reference` pipeline: every value as written, column names as dlt names them, +`line` the order the file is published in): the patients with a known recurrence time and +status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their +covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN); +nothing is imputed or dropped for it. Of each pair of nearly redundant covariates (Cramér's +V >= V_MAX), the one with more unknowns is dropped.""" from dataclasses import dataclass @@ -17,9 +19,8 @@ DAYS_PER_MONTH = 30.4375 AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"]) NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"]) -GRADES = {1.0: "1", 2.0: "2", 3.0: "3"} +GRADES = {"1": "1", "2": "2", "3": "3"} -FILES = {"metabric": "brca_metabric_clinical_data.tsv", "scanb": "scanb_clinical_metadata.txt"} FIXED = { "metabric": ["paciente", "tiempo_meses", "evento"], "scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"], @@ -28,33 +29,32 @@ TREATMENT = { "metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], "scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], } -# Covariates taken as they come (our name: the file's column). +# Covariates taken as they come (our name: the dataset's column). PASSTHROUGH = { "metabric": { - "Receptor_estrogeno": "ER Status", "Receptor_progesterona": "PR Status", - "HER2": "HER2 Status", "Subtipo_PAM50": "Pam50 + Claudin-low subtype", - "Tipo_histologico": "Cancer Type Detailed", "Celularidad": "Cellularity", - "Estado_menopausico": "Inferred Menopausal State", - "Cluster_integrativo": "Integrative Cluster", "Lateralidad": "Primary Tumor Laterality", - "Cirugia": "Type of Breast Surgery", "Quimioterapia": "Chemotherapy", - "Radioterapia": "Radio Therapy", "Hormonoterapia": "Hormone Therapy", + "Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status", + "HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype", + "Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity", + "Estado_menopausico": "inferred_menopausal_state", + "Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality", + "Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy", + "Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy", }, "scanb": { - "Receptor_estrogeno": "ER", "Receptor_progesterona": "PR", "HER2": "HER2", - "Ki67": "Ki67", "Subtipo_clinico": "ClinicalSubtype", "Tipo_histologico": "Histology", - "Estado_menopausico": "MenopauseStatus_bin", "Lateralidad": "Laterality", - "Estadio_clinico": "tnm_ClinicalStage", "Cirugia": "SurgeryType", - "Quimioterapia": "Chemotherapy", "Radioterapia": "Radiation", - "Hormonoterapia": "Endocrine", "AntiHER2": "AntiHER2", + "Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2", + "Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology", + "Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality", + "Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type", + "Quimioterapia": "chemotherapy", "Radioterapia": "radiation", + "Hormonoterapia": "endocrine", "AntiHER2": "anti_her2", }, } # fmt: skip SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"} SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"} -def read(source: str, path) -> pd.DataFrame: - """The raw file as its publisher distributes it (tab separated, pandas' NA tokens).""" - return pd.read_csv(path, sep="\t", low_memory=False) +def _number(s: pd.Series) -> pd.Series: + return pd.to_numeric(s, errors="coerce") def _text(s: pd.Series) -> pd.Series: @@ -66,18 +66,22 @@ def _band(s: pd.Series, edges: list, labels: list) -> pd.Series: return _text(pd.cut(s, edges, labels=labels, right=False).astype(object)) -def _metabric(raw: pd.DataFrame) -> pd.DataFrame: - d = raw.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]) +def _in_order(rows: pd.DataFrame) -> pd.DataFrame: + return rows.sort_values("line", kind="stable").reset_index(drop=True) + + +def _metabric(rows: pd.DataFrame) -> pd.DataFrame: + d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"]) d = d.reset_index(drop=True) - out = pd.DataFrame({"paciente": d["Patient ID"]}) - out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float) - out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int) - out["Edad"] = _band(d["Age at Diagnosis"], *AGE) - out["Tamano_tumor"] = _band(d["Tumor Size"], *SIZE) - out["Ganglios_positivos"] = _band(d["Lymph nodes examined positive"], *NODES) - out["Grado_histologico"] = _text(d["Neoplasm Histologic Grade"].map(GRADES)) + out = pd.DataFrame({"paciente": d["patient_id"]}) + out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"]) + out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int) + out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE) + out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE) + out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES) + out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES)) # Mutational load in tertiles of this cohort; a value on a cut falls in the lower band. - load = d["Mutation Count"] + load = _number(d["mutation_count"]) q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy() edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6] out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"]) @@ -86,17 +90,18 @@ def _metabric(raw: pd.DataFrame) -> pd.DataFrame: return out -def _scanb(raw: pd.DataFrame) -> pd.DataFrame: - d = raw[raw["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]) - d = d.reset_index(drop=True) - out = pd.DataFrame({"paciente": d["PatientName"]}) - out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH - out["evento"] = d["RFI_event"].astype(int) - out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int) - out["Edad"] = _band(d["Age_5year_bin"].astype(float) - 2, *AGE) # the 5-year bin's middle - out["Tamano_tumor"] = _band(d["TumorSize_mm"], *SIZE) - out["Ganglios_positivos"] = _text(d["NodeMetSpec"].map(SCANB_NODES)) - out["Grado_histologico"] = _text(d["NHG"].map(SCANB_GRADES)) +def _scanb(rows: pd.DataFrame) -> pd.DataFrame: + d = _in_order(rows) + d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True) + rfi, died = _number(d["rfi_event"]), _number(d["os_event"]) + out = pd.DataFrame({"paciente": d["patient_name"]}) + out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH + out["evento"] = rfi.astype(int) + out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int) + out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle + out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE) + out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES)) + out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES)) for name, column in PASSTHROUGH["scanb"].items(): out[name] = _text(d[column]) return out diff --git a/models/cama/recurrence/curves.py b/models/cama/recurrence/curves.py index 66380e4..31ad508 100644 --- a/models/cama/recurrence/curves.py +++ b/models/cama/recurrence/curves.py @@ -2,12 +2,13 @@ with its Greenwood band (log-log scale), and a classic and a fractional (Kilbas-Saigo) Weibull, both fitted by maximum likelihood on the monthly counts of recurrences and censorings (a recurrence in month m falls between S(m) and S(m+1); a censoring there -survives to m + 1/2). Fits start from several points and stop on iteration counts only.""" +survives to m + 1/2). Fits start from several points and run each to the optimizer's +convergence; one that doesn't converge is an error, not a curve.""" -import mpmath as mp import numpy as np -from scipy.optimize import minimize -from scipy.special import gammaln +from scipy.optimize import minimize, minimize_scalar +from scipy.special import beta as beta_function +from scipy.special import betainc, gammaln Z = 1.96 INVALID = 1e12 # the likelihood outside a model's parameter region @@ -41,8 +42,8 @@ def kaplan_meier(months, event, until: int): def _nll(survival, d, c) -> float: T = len(d) - S = survival(np.arange(0, T + 1, dtype=float)) - mid = survival(np.arange(T) + 0.5) + both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5])) + S, mid = both[: T + 1], both[T + 1 :] if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))): return INVALID p = np.clip(S[:-1] - S[1:], 1e-300, None) @@ -64,6 +65,7 @@ def fit_weibull(d, c) -> tuple[float, float]: method="Nelder-Mead", options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000}, ) + r = _converged(r, "Weibull") best = r if best is None or r.fun < best.fun else best k, lam = np.exp(best.x) return float(k), float(lam) @@ -71,118 +73,109 @@ def fit_weibull(d, c) -> tuple[float, float]: # ---------------------------------------------------------------- fractional Weibull -FLOAT_LOG_MAX = 12.0 # largest term a float sum tolerates (e^12: ~5 digits of 16 lost) -MP_LOG_MAX = 300.0 # beyond this the series is out of reach (NaN) -TAIL = -40.0 # the series is summed until its terms fall below e^TAIL -MAX_TERMS = 40_000 -# The fit's likelihood evaluations. v1 stopped on a 60 s wall clock instead; 100 evaluations -# cost at most a few seconds a scenario (later ones wander where the series is costly: 300 -# took up to 7 minutes) and land within 0.05 of v1's curves. -FRACTIONAL_EVALUATIONS = 100 +STEPS = 800 # the solver's grid: its error falls as 1/STEPS^2 (~1e-7 here) -def _horner(coefficients: list[int], x: float, bits: int) -> float: - """The polynomial at `x` in fixed point (integers scaled by 2^bits): exact Python - integers, an order of magnitude faster than mpmath's floats at the same precision.""" - X, acc = int(mp.ldexp(x, bits)), coefficients[-1] - for c in reversed(coefficients[:-1]): - acc = ((acc * X) >> bits) + c - return float(mp.ldexp(acc, -bits)) +class NotConverged(RuntimeError): + pass -def kilbas_saigo(z, rho, m, l) -> np.ndarray: # noqa: E741 - """E_{rho,m,l}(z) = sum_n c_n z^n, c_0 = 1, c_n = prod_{i widest.argmax())) - if len(past) == 0: - return np.full(len(z), np.nan) - n = int(past[0]) + 1 - with np.errstate(divide="ignore"): - log_terms = ( - log_c[None, :n] + np.arange(n)[None, :] * np.log(np.maximum(np.abs(z), 1e-300))[:, None] - ) - peak = log_terms.max(axis=1) - out = np.full(len(z), np.nan) - small = peak <= FLOAT_LOG_MAX - signs = np.where(z[:, None] < 0, (-1.0) ** np.arange(n), 1.0) - out[small] = (np.exp(log_terms[small]) * signs[small]).sum(axis=1) - rest = ~small & (peak <= MP_LOG_MAX) - if rest.any(): - digits = 30 + int(peak[rest].max() / 2.3) - bits = int(3.33 * digits) - with mp.workdps(digits): - c = [mp.mpf(1)] - for j in range(n - 1): - a = rho * (m * j + l) - c.append(c[-1] * mp.exp(mp.loggamma(a + 1) - mp.loggamma(a + rho + 1))) - fixed = [int(mp.ldexp(x, bits)) for x in c] - out[rest] = [_horner(fixed, x, bits) for x in z[rest]] - return out +def _converged(r, what: str): + if not r.success: + raise NotConverged(f"{what}: {r.message}") + return r + + +def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray: + """S(t) with S(0) = 1 and Caputo derivative D^rho S(t) = -c t^s S(t) (0 < rho <= 1, + s + rho > 0): the Kilbas-Saigo function E_{rho, 1+s/rho, s/rho}(-c t^(rho+s)). + + Solved as its Volterra equation, S(t) = 1 - c/G(rho) int_0^t (t-u)^(rho-1) u^s S(u) du, + by product integration in w = t^(rho+s), where S is a power series in z = c w and so + smooth: S is linear in w on each step, and the kernel's integrals against u^s and + u^(s+rho+s) are exact (incomplete beta functions). The steps are even in log(1 + z): + fine where S starts to fall, wide over its slow tail. No series, no extended precision.""" + t = np.atleast_1d(np.asarray(t, float)) + e = rho + s + top = float(t.max()) if t.size else 0.0 + if top <= 0: + return np.ones_like(t) + w = np.expm1(np.linspace(0.0, np.log1p(c * top**e), STEPS + 1)) / c + w[-1] = top**e + grid = w ** (1 / e) + y = np.ones(STEPS + 1) + kappa = c / np.exp(gammaln(rho)) + b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho) + dw = np.diff(w) + for n in range(1, STEPS + 1): + x = grid[: n + 1] / grid[n] + i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x)) + ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x)) + slope = (ie - w[:n] * i0) / dw[:n] + own, next_ = i0 - slope, slope # y_j's and y_(j+1)'s weights on step j + known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n]) + y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1]) + return np.interp(t**e, w, y) def fractional(t, k, alpha, beta, lam) -> np.ndarray: - """The Kilbas-Saigo Weibull's survival; NaN outside its parameter region.""" + """The fractional Weibull's survival (Kilbas-Saigo, with the classic Weibull as its + alpha = beta = 1 case); NaN outside its parameter region.""" t = np.atleast_1d(np.asarray(t, float)) s = k + alpha - 2 if k + alpha <= 1 or s + beta <= 0: return np.full(t.shape, np.nan) - scale = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) - S = np.ones_like(t) - pos = t > 0 - z = -scale * (t[pos] / lam) ** (k + alpha + beta - 2) - S[pos] = kilbas_saigo(z, beta, s / beta + 1, s / beta) - return np.clip(S, 0.0, 1.0) + c = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) / lam ** (k + alpha + beta - 2) + return np.clip(kilbas_saigo_survival(t, c, beta, s), 0.0, 1.0) -def fit_fractional( - d, c, k: float, lam: float, budget: int = FRACTIONAL_EVALUATIONS -) -> tuple[float, ...]: - """(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, - from the start that reproduces the classic fit (so it is never worse) and then a grid of - others, while `budget` likelihood evaluations last.""" +def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]: + """(rho, s, scale): the fractional Weibull is S(t) = g(z), z = scale (t/lambda)^(rho+s), + with g the Kilbas-Saigo survival of order rho and power s at c = 1.""" + return beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1))) + + +def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]: + """(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, by + maximum likelihood profiled over lambda: for each (alpha, beta), g is solved once over + every z the allowed lambdas (1 to 1e7) reach, and lambda is then fitted exactly on it. + (alpha, beta) is the best of a start at the classic fit (alpha = beta = 1, so it is + never worse) and a grid of others, each to Nelder-Mead's convergence.""" floor = max(0.0, 1.0 - k) + 1e-6 - horizon = float(len(d)) - calls = [0] + top = len(d) + 0.5 # the latest month the likelihood reads (a censoring's half month) + months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5]) + lambdas = (0.0, np.log(1e7)) def unpack(p): - return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1])), np.exp(p[2]) + return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1])) - def nll(p): - calls[0] += 1 - a, b, scale = unpack(p) - if ( - k + a <= 1 - or k + a + b <= 2 - or not 1.0 <= scale <= 1e7 - or (horizon / scale) ** (k + a + b - 2) > 300 - ): - return INVALID # degenerate: the series would be huge and unstable - return _nll(lambda t: fractional(t, k, a, b, scale), d, c) + def profile(p) -> tuple[float, float]: + a, b = unpack(p) + if k + a <= 1 or k + a + b <= 2: + return INVALID, np.nan + rho, s, scale = _shape(k, a, b) + e = rho + s + z_top = scale * top**e # lambda = 1 reaches the farthest + z = np.expm1(np.linspace(0.0, np.log1p(z_top), STEPS + 1)) + g = np.clip(kilbas_saigo_survival(z ** (1 / e), 1.0, rho, s), 0.0, 1.0) - starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0, np.log(lam)]] - starts += [ - [np.log(a0), np.log(b0 / (1 - b0)), np.log(l0)] - for l0 in (lam, 100.0, 500.0) - for a0 in (0.3, 1.0) - for b0 in (0.5, 0.9) - ] + def nll(log_lam: float) -> float: + found = np.interp(np.log1p(scale * (months / np.exp(log_lam)) ** e), np.log1p(z), g) + return _nll(lambda t: found, d, c) + + coarse = np.linspace(*lambdas, 141) + i = int(np.argmin([nll(x) for x in coarse])) + r = minimize_scalar(nll, bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]), + method="bounded", options={"xatol": 1e-9}) # fmt: skip + return float(r.fun), float(r.x) + + starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0]] + starts += [[np.log(a0), np.log(b0 / (1 - b0))] for a0 in (0.3, 1.0) for b0 in (0.5, 0.9)] best = None for p0 in starts: - left = budget - calls[0] - if left <= 0: - break - r = minimize( - nll, - p0, - method="Nelder-Mead", - options={"xatol": 1e-5, "fatol": 1e-9, "maxiter": 1200, "maxfev": left}, - ) + options = {"xatol": 1e-5, "fatol": 1e-8, "maxiter": 20_000, "maxfev": 20_000} + r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options) + r = _converged(r, "fractional Weibull") best = r if best is None or r.fun < best.fun else best - return tuple(float(x) for x in unpack(best.x)) + a, b = unpack(best.x) + return float(a), float(b), float(np.exp(profile(best.x)[1])) diff --git a/models/cama/specs.py b/models/cama/specs.py index 98843b6..c25c9bc 100644 --- a/models/cama/specs.py +++ b/models/cama/specs.py @@ -4,17 +4,16 @@ interval survival (models.survival) over the age at the index and that report's results. 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) read from a configured folder - (CAMA_REFERENCE_DIR), not on the hospital's patients; slow (its bootstraps take over an - hour), so it trains only when asked for by name.""" + 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.""" -import os from dataclasses import dataclass, field -from pathlib import Path import pandas as pd from models.survival import Spec, age_group, band +from persistance import nodes # The index report's results (timeline types), read from a week before to RESULT_DAYS after. RESULTS = ("histologic_type", "grade", "er", "pr", "her2") @@ -37,16 +36,13 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame: return found -# The reference cohorts' files, as their publishers distribute them. -REFERENCE_FILES = {"metabric": "brca_metabric_clinical_data.tsv", - "scanb": "scanb_clinical_metadata.txt"} # fmt: skip - - @dataclass(frozen=True) class ReferenceRecurrence: - """The recurrence model over the reference cohorts of `CAMA_REFERENCE_DIR`.""" + """The recurrence model over the reference cohorts the `pipeline` loaded: one source node + per cohort, named as the cohort.""" name: str + pipeline: str = "cama_reference" cohort: None = None # trains on no gold cohort, and scores no patient slow: bool = True method: str = field(default="stepwise logistic regression + Bayesian network", init=False) @@ -54,11 +50,18 @@ class ReferenceRecurrence: def train(self, events, as_of=None) -> tuple: from models.cama import recurrence - folder = Path(os.environ.get("CAMA_REFERENCE_DIR", "reference/cama")) - raws = {s: recurrence.read(s, folder / f) for s, f in REFERENCE_FILES.items()} - model, metrics, reports = recurrence.train(raws) + 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 + def predict(self, model, events) -> pd.DataFrame: return model.predict(events) diff --git a/models/graph.py b/models/graph.py index 712ed90..bdf105c 100644 --- a/models/graph.py +++ b/models/graph.py @@ -43,11 +43,9 @@ from core.pipeline import ( matches, validate, ) -from persistance import config_log, nodes, silver +from persistance import config_log, files, nodes, silver MIN_WORDS = 5 # fewer than this from a PDF means it has no text layer -# Files kept whole (catalog `file` fields), once each, keyed by their content hash. -FILES = {"key": {"data_type": "text"}, "content": {"data_type": "binary"}} READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error` "text": {"data_type": "text", "nullable": True}, "ocr": {"data_type": "bool"}, @@ -95,13 +93,11 @@ def read_file(content: bytes) -> dict: def run_read(p: str, node: Read): """The input's rows with the file column replaced by its text; each file read once.""" rows = list(nodes.rows(p, node.inputs[0])) - keys = {} - for row in rows: - content = row.pop(node.column) - row["key"] = hashlib.sha256(content).hexdigest() if content else None - keys[row["key"]] = content - found = nodes.cached("read_cache", set(keys) - {None}) - new = {k: c for k, c in keys.items() if k and k not in found} + for row in rows: # the source kept the file; the row carries its hash + row["key"] = row.pop(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) @@ -389,14 +385,10 @@ def run_target(p: str, node: Target, kinds: dict[str, str]): linked = {r[RECORD]: r for r in nodes.rows(p, link)} person = {k: r["person_id"] for k, r in linked.items()} model, study = catalog.model(node.entity), catalog.studies()[node.entity] - observations, held_rows, files = [], [], {} - kept = [n for n, f in study.fields.items() if f.type == "file"] + observations, held_rows = [], [] for i in (i for i in node.inputs if i != link): for row in nodes.rows(p, i): values = {f: row.get(f) for f in model.model_fields if row.get(f) is not None} - for name in (n for n in kept if n in values): # kept once, named by its hash - files[key := hashlib.sha256(values[name]).hexdigest()] = values[name] - values[name] = key held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values) if row[RECORD] not in person: held.append("no identity linked to this record") @@ -414,7 +406,6 @@ def run_target(p: str, node: Target, kinds: dict[str, str]): if (value := getattr(clean, name)) is not None: observations.append({**base, "instance": instance, "field": name, catalog.value_column(field): value}) # fmt: skip - nodes.remember("files", [{"key": k, "content": c} for k, c in files.items()], FILES) nodes.stage("observation", p, node.id, observations, silver.OBSERVATION) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) diff --git a/pyproject.toml b/pyproject.toml index 62646d0..744a4ea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,6 @@ dependencies = [ "edfio>=0.4.18", "statsmodels>=0.15.0", "pgmpy>=1.1.2", - "mpmath>=1.4.1", ] [build-system] diff --git a/tests/test_ingest.py b/tests/test_ingest.py index 2bf3fa5..0b674a3 100644 --- a/tests/test_ingest.py +++ b/tests/test_ingest.py @@ -94,7 +94,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat assert query(corrected) == [("64000",)] read = query("select id, text, ocr, error from bronze.n__site__archivos_text") - assert all(error is None for *_, error in read) + assert [error for *_, error in read if error is not None] == [] space = re.compile(r"\s+") by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read} for r in by_place["ArchivosUni"]: diff --git a/tests/test_recurrence.py b/tests/test_recurrence.py index a6d1132..9a29c1c 100644 --- a/tests/test_recurrence.py +++ b/tests/test_recurrence.py @@ -1,37 +1,49 @@ """CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two -published raw files (`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia). +published datasets, loaded by the platform's `cama_reference` pipeline (the files are in +`CAMA_REFERENCE_DIR`, default ~/camaSupervivencia). Tolerances: cohorts, terms, parents, CPT keys and every routine are exact; the saved model's constants, coefficients and CPT values are bit-identical (== on the floats); AUCs, C-indexes and bootstrap summaries equal v1's 4-decimal values; the calculator's table and its 4-decimal cells are equal, the figure points equal to 1e-12, the Kaplan-Meier curves and classic Weibull curves to 1e-12; risk-factor cells within 1.01e-4 (v1 stored them rounded to 4 places: a value -on a rounding edge may land one unit away). The fractional Weibull is not reproducible (v1 -stopped its fit on a 60-second wall clock): within FRACTIONAL_TOLERANCE of v1's curve. +on a rounding edge may land one unit away). The fractional Weibull is fitted to convergence; +v1 stopped its fit on a 60-second wall clock, short of it, so its curve is v1's within +FRACTIONAL_TOLERANCE, not equal. The fractional curve itself is a solver's, within +SOLVER_TOLERANCE of the exact series. -The full bootstrap (420 resampled fits, ~10 min on 8 cores) is marked `slow` and runs only -with RECURRENCE_SLOW=1; the default set takes about two minutes. +The full bootstrap and the calculator (whose 40 fractional Weibull curves are fitted to +convergence, a few minutes each) are marked `slow` and run only with RECURRENCE_SLOW=1 +(about an hour); the default set takes about two minutes. """ import json import os +import re from pathlib import Path import numpy as np import pandas as pd import pytest from joblib.externals.loky import get_reusable_executor +from scipy.special import gammaln +from conftest import _platform from models.cama import recurrence from models.cama.recurrence import calculator, cohorts, curves, factors, modeling, reports RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia")) V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1" -FRACTIONAL_TOLERANCE = 0.05 # max |S| difference to v1's fractional Weibull curve +# Max |S| difference to v1's fractional Weibull curve: v1 stopped its fit on a 60 s clock, +# short of the optimum this fit converges to (largest gap measured: 0.053). +FRACTIONAL_TOLERANCE = 0.06 +SOLVER_TOLERANCE = 1e-6 # max |S| error of the fractional Weibull's solver (~1e-7 measured) FACTOR_TOLERANCE = 1.01e-4 +FILES = ("brca_metabric_clinical_data.tsv", "scanb_clinical_metadata.txt") +PIPELINE = Path(__file__).parents[2] / "tests" / "fixtures" / "pipelines" / "cama_reference.json" pytestmark = pytest.mark.skipif( - not all((RAW / f).exists() for f in cohorts.FILES.values()), reason="no reference raw files" + not all((RAW / f).exists() for f in FILES), reason="no reference raw files" ) slow = pytest.mark.skipif(not os.environ.get("RECURRENCE_SLOW"), reason="RECURRENCE_SLOW unset") @@ -45,13 +57,26 @@ DEVELOPMENT = _json("analisis/recurrencia_desarrollo.json")["tablas"] if V1.exis FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else [] -def _raws() -> dict[str, pd.DataFrame]: - return {s: recurrence.read(s, RAW / f) for s, f in cohorts.FILES.items()} +@pytest.fixture(scope="module") +def raws(tmp_path_factory) -> dict[str, pd.DataFrame]: + """Both datasets as the platform loads them: the `cama_reference` pipeline into a fresh + platform, read back from its tables.""" + folder = tmp_path_factory.mktemp("platform") + platform = _platform("sqlite", folder) + drawn = folder / "pipeline.json" + 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. + 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 + return pd.read_pickle(out) @pytest.fixture(scope="module") -def prepared(): - return {s: cohorts.prepare(s, raw) for s, raw in _raws().items()} +def prepared(raws): + return {s: cohorts.prepare(s, raw) for s, raw in raws.items()} @pytest.fixture(scope="module") @@ -64,7 +89,20 @@ def fits(prepared): # ---------------------------------------------------------------- comparisons +# v1 read SCAN-B's clinical stage as a number, so its categories print as 0.0, 1.0...; the +# platform keeps the dataset's text (0, 1...). Same categories, in the same order. +STAGES = {f"{n}.0": str(n) for n in range(5)} + + +def _stages(table: dict) -> dict: + """v1's summary with the stages as the dataset writes them.""" + text = re.sub(r"Estadio_clinico=(\d)\.0", r"Estadio_clinico=\1", json.dumps(table)) + return json.loads(text) + + def _same_rows(mine: list[dict], ref: list[dict], tolerance: float = 0.0): + ref = [{**r, **{k: STAGES.get(r[k], r[k]) for k in ("categoria", "referencia") if k in r}} + if r.get("variable") == "Estadio_clinico" else r for r in ref] # fmt: skip assert len(mine) == len(ref) for i, (a, b) in enumerate(zip(mine, ref, strict=True)): assert a.keys() == b.keys(), i @@ -115,8 +153,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float): # ---------------------------------------------------------------- fast -def test_cohorts(prepared): - raws = _raws() +def test_cohorts(prepared, raws): sampling = _json("rutinas/MUESTREO.json")["cohortes"] missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"] for source, c in prepared.items(): @@ -162,6 +199,8 @@ def test_saved_model(fits): assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15) +@pytest.mark.slow +@slow def test_calculator(fits): """All 60 table rows, and the 20 figures but their fractional Weibull's tolerance.""" records, rows = [], [] @@ -185,15 +224,34 @@ def test_risk_factors(fits): _same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"], FACTOR_TOLERANCE) # fmt: skip summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)] - assert reports.table(summary) == DEVELOPMENT["escenarios_resumen"] + assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"]) def test_fractional_weibull_reproduces_the_classic_one(): """With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's.""" t = np.linspace(0, 300, 61) for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)): - np.testing.assert_allclose(curves.fractional(t, k, 1.0, 1.0, lam), - curves.weibull(t, k, lam), rtol=0, atol=1e-9) # fmt: skip + found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam) + np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE) + + +def _series(z: np.ndarray, rho: float, m: float, l: float, terms: int = 200) -> np.ndarray: # noqa: E741 + """E_{rho,m,l}(z) by its defining series, in floats: exact where |z| is small.""" + j = np.arange(terms - 1) + log_c = np.concatenate([[0.0], np.cumsum(gammaln(rho * (m * j + l) + 1) + - gammaln(rho * (m * j + l + 1) + 1))]) # fmt: skip + return (np.exp(log_c)[None, :] * z[:, None] ** np.arange(terms)[None, :]).sum(axis=1) + + +def test_fractional_weibull_solver_matches_the_series(): + """Where the series is exact in floats (|z| < 2), the solver gives it within its error.""" + t = np.linspace(0, 72, 289) + for k, a, b, lam in ((1.0, 0.5, 0.7, 80.0), (0.8, 0.9, 0.4, 150.0), (1.3, 0.3, 0.9, 60.0)): + s = k + a - 2 + z = -np.exp(gammaln(k + 1) - gammaln(k + a - 1)) * (t / lam) ** (k + a + b - 2) + assert np.abs(z).max() < 2 + found, want = curves.fractional(t, k, a, b, lam), _series(z, b, s / b + 1, s / b) + np.testing.assert_allclose(found, want, rtol=0, atol=SOLVER_TOLERANCE) # ---------------------------------------------------------------- slow: the whole v1 run @@ -201,8 +259,8 @@ def test_fractional_weibull_reproduces_the_classic_one(): @pytest.mark.slow @slow -def test_train_reproduces_v1(): - model, metrics, found = recurrence.train(_raws(), bootstrap=True) +def test_train_reproduces_v1(raws): + model, metrics, found = recurrence.train(raws, bootstrap=True) assert metrics == VERSION["metrics"] for h in recurrence.HORIZONS: mine = model.tables[h] @@ -216,7 +274,7 @@ def test_train_reproduces_v1(): _same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"]) _same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"], FACTOR_TOLERANCE) # fmt: skip - assert tables["escenarios_resumen"] == DEVELOPMENT["escenarios_resumen"] + assert tables["escenarios_resumen"] == _stages(DEVELOPMENT["escenarios_resumen"]) figures = found["interpretability"]["recurrencia"] assert figures["horizons_months"] == [12, 36, 60] _check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE)