Files read by hash; fractional Weibull solved and fitted to convergence; recurrence reads its reference cohorts from the platform

This commit is contained in:
Roberto Treviño
2026-11-26 14:25:53 -06:00
parent f305cdd044
commit 76eb8cc8af
8 changed files with 258 additions and 211 deletions
+13 -15
View File
@@ -1,10 +1,11 @@
"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months, """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 learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
files. Per cohort and horizon, a stepwise logistic regression and a Bayesian network (BDeu published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic
parents of the outcome) are fitted and validated (cohorts, modeling); a calculator gives the regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated
recurrence-free probability of clinical scenarios with bootstrap intervals and survival curves (cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios
(calculator, curves); risk factors are rated by four criteria (factors); reports gives the with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by
tables and figures. The saved model is METABRIC's, refitted on each whole horizon cohort.""" four criteria (factors); reports gives the tables and figures. The saved model is METABRIC's,
refitted on each whole horizon cohort."""
from dataclasses import dataclass from dataclasses import dataclass
@@ -19,14 +20,10 @@ HORIZONS = modeling.HORIZONS # months
SAVED = "metabric" SAVED = "metabric"
def cohort(source: str, raw: pd.DataFrame) -> pd.DataFrame: def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame:
"""The source's cohort table: fixed columns, then its covariates as categories.""" """The source's cohort table, from its dataset's rows: fixed columns, then its
return cohorts.prepare(source, raw).frame covariates as categories."""
return cohorts.prepare(source, rows).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)
@dataclass @dataclass
@@ -63,7 +60,8 @@ class Recurrence:
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: 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' Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
stability criterion, are then missing).""" stability criterion, are then missing)."""
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES} found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
+50 -45
View File
@@ -1,8 +1,10 @@
"""Each reference cohort's raw file as one table of categories: the patients with a known """Each reference cohort as one table of categories, from its dataset as the platform loaded
recurrence time and status, their time to recurrence (`tiempo_meses`), whether it happened it (the `cama_reference` pipeline: every value as written, column names as dlt names them,
(`evento`), and their covariates as text. A missing or out-of-range value is a category of its `line` the order the file is published in): the patients with a known recurrence time and
own (UNKNOWN); nothing is imputed or dropped for it. Of each pair of nearly redundant status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their
covariates (Cramér's V >= V_MAX), the one with more unknowns is dropped.""" covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN);
nothing is imputed or dropped for it. Of each pair of nearly redundant covariates (Cramér's
V >= V_MAX), the one with more unknowns is dropped."""
from dataclasses import dataclass from dataclasses import dataclass
@@ -17,9 +19,8 @@ DAYS_PER_MONTH = 30.4375
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"]) 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"]) SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"]) NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
GRADES = {1.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 = { FIXED = {
"metabric": ["paciente", "tiempo_meses", "evento"], "metabric": ["paciente", "tiempo_meses", "evento"],
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"], "scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
@@ -28,33 +29,32 @@ TREATMENT = {
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"], "metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"], "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 = { PASSTHROUGH = {
"metabric": { "metabric": {
"Receptor_estrogeno": "ER Status", "Receptor_progesterona": "PR Status", "Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
"HER2": "HER2 Status", "Subtipo_PAM50": "Pam50 + Claudin-low subtype", "HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
"Tipo_histologico": "Cancer Type Detailed", "Celularidad": "Cellularity", "Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
"Estado_menopausico": "Inferred Menopausal State", "Estado_menopausico": "inferred_menopausal_state",
"Cluster_integrativo": "Integrative Cluster", "Lateralidad": "Primary Tumor Laterality", "Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
"Cirugia": "Type of Breast Surgery", "Quimioterapia": "Chemotherapy", "Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
"Radioterapia": "Radio Therapy", "Hormonoterapia": "Hormone Therapy", "Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
}, },
"scanb": { "scanb": {
"Receptor_estrogeno": "ER", "Receptor_progesterona": "PR", "HER2": "HER2", "Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
"Ki67": "Ki67", "Subtipo_clinico": "ClinicalSubtype", "Tipo_histologico": "Histology", "Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
"Estado_menopausico": "MenopauseStatus_bin", "Lateralidad": "Laterality", "Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
"Estadio_clinico": "tnm_ClinicalStage", "Cirugia": "SurgeryType", "Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
"Quimioterapia": "Chemotherapy", "Radioterapia": "Radiation", "Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
"Hormonoterapia": "Endocrine", "AntiHER2": "AntiHER2", "Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
}, },
} # fmt: skip } # fmt: skip
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"} SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"} SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
def read(source: str, path) -> pd.DataFrame: def _number(s: pd.Series) -> pd.Series:
"""The raw file as its publisher distributes it (tab separated, pandas' NA tokens).""" return pd.to_numeric(s, errors="coerce")
return pd.read_csv(path, sep="\t", low_memory=False)
def _text(s: pd.Series) -> pd.Series: 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)) return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
def _metabric(raw: pd.DataFrame) -> pd.DataFrame: def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
d = raw.dropna(subset=["Relapse Free Status", "Relapse Free Status (Months)"]) 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) d = d.reset_index(drop=True)
out = pd.DataFrame({"paciente": d["Patient ID"]}) out = pd.DataFrame({"paciente": d["patient_id"]})
out["tiempo_meses"] = d["Relapse Free Status (Months)"].astype(float) out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
out["evento"] = d["Relapse Free Status"].str.startswith("1").astype(int) out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
out["Edad"] = _band(d["Age at Diagnosis"], *AGE) out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
out["Tamano_tumor"] = _band(d["Tumor Size"], *SIZE) out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
out["Ganglios_positivos"] = _band(d["Lymph nodes examined positive"], *NODES) out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
out["Grado_histologico"] = _text(d["Neoplasm Histologic Grade"].map(GRADES)) 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. # 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() q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6] edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"]) out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
@@ -86,17 +90,18 @@ def _metabric(raw: pd.DataFrame) -> pd.DataFrame:
return out return out
def _scanb(raw: pd.DataFrame) -> pd.DataFrame: def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
d = raw[raw["Gender"] == "F"].dropna(subset=["RFI_event", "RFI_days"]) d = _in_order(rows)
d = d.reset_index(drop=True) d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
out = pd.DataFrame({"paciente": d["PatientName"]}) rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
out["tiempo_meses"] = d["RFI_days"].astype(float) / DAYS_PER_MONTH out = pd.DataFrame({"paciente": d["patient_name"]})
out["evento"] = d["RFI_event"].astype(int) out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
out["muerte_sin_recaida"] = ((d["OS_event"] == 1) & (d["RFI_event"] == 0)).astype(int) out["evento"] = rfi.astype(int)
out["Edad"] = _band(d["Age_5year_bin"].astype(float) - 2, *AGE) # the 5-year bin's middle out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
out["Tamano_tumor"] = _band(d["TumorSize_mm"], *SIZE) out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
out["Ganglios_positivos"] = _text(d["NodeMetSpec"].map(SCANB_NODES)) out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
out["Grado_histologico"] = _text(d["NHG"].map(SCANB_GRADES)) 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(): for name, column in PASSTHROUGH["scanb"].items():
out[name] = _text(d[column]) out[name] = _text(d[column])
return out return out
+93 -100
View File
@@ -2,12 +2,13 @@
with its Greenwood band (log-log scale), and a classic and a fractional (Kilbas-Saigo) 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 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 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 import numpy as np
from scipy.optimize import minimize from scipy.optimize import minimize, minimize_scalar
from scipy.special import gammaln from scipy.special import beta as beta_function
from scipy.special import betainc, gammaln
Z = 1.96 Z = 1.96
INVALID = 1e12 # the likelihood outside a model's parameter region 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: def _nll(survival, d, c) -> float:
T = len(d) T = len(d)
S = survival(np.arange(0, T + 1, dtype=float)) both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
mid = survival(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))): if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
return INVALID return INVALID
p = np.clip(S[:-1] - S[1:], 1e-300, None) 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", method="Nelder-Mead",
options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000}, 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 best = r if best is None or r.fun < best.fun else best
k, lam = np.exp(best.x) k, lam = np.exp(best.x)
return float(k), float(lam) return float(k), float(lam)
@@ -71,118 +73,109 @@ def fit_weibull(d, c) -> tuple[float, float]:
# ---------------------------------------------------------------- fractional Weibull # ---------------------------------------------------------------- fractional Weibull
FLOAT_LOG_MAX = 12.0 # largest term a float sum tolerates (e^12: ~5 digits of 16 lost) STEPS = 800 # the solver's grid: its error falls as 1/STEPS^2 (~1e-7 here)
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
def _horner(coefficients: list[int], x: float, bits: int) -> float: class NotConverged(RuntimeError):
"""The polynomial at `x` in fixed point (integers scaled by 2^bits): exact Python pass
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))
def kilbas_saigo(z, rho, m, l) -> np.ndarray: # noqa: E741 def _converged(r, what: str):
"""E_{rho,m,l}(z) = sum_n c_n z^n, c_0 = 1, c_n = prod_{i<n} G(rho(mi+l)+1) / G(rho(mi+l+1)+1): if not r.success:
in floats while its terms stay small, else in mpmath with as many digits as the largest raise NotConverged(f"{what}: {r.message}")
term needs; NaN where even that is out of reach.""" return r
z = np.asarray(z, float)
i = np.arange(MAX_TERMS - 1)
log_c = np.concatenate( def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
[[0.0], np.cumsum(gammaln(rho * (m * i + l) + 1) - gammaln(rho * (m * i + l + 1) + 1))] """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)).
widest = log_c + np.arange(MAX_TERMS) * np.log(np.abs(z).max()) # the slowest to converge
past = np.flatnonzero((widest < TAIL) & (np.arange(MAX_TERMS) > widest.argmax())) Solved as its Volterra equation, S(t) = 1 - c/G(rho) int_0^t (t-u)^(rho-1) u^s S(u) du,
if len(past) == 0: by product integration in w = t^(rho+s), where S is a power series in z = c w and so
return np.full(len(z), np.nan) smooth: S is linear in w on each step, and the kernel's integrals against u^s and
n = int(past[0]) + 1 u^(s+rho+s) are exact (incomplete beta functions). The steps are even in log(1 + z):
with np.errstate(divide="ignore"): fine where S starts to fall, wide over its slow tail. No series, no extended precision."""
log_terms = ( t = np.atleast_1d(np.asarray(t, float))
log_c[None, :n] + np.arange(n)[None, :] * np.log(np.maximum(np.abs(z), 1e-300))[:, None] e = rho + s
) top = float(t.max()) if t.size else 0.0
peak = log_terms.max(axis=1) if top <= 0:
out = np.full(len(z), np.nan) return np.ones_like(t)
small = peak <= FLOAT_LOG_MAX w = np.expm1(np.linspace(0.0, np.log1p(c * top**e), STEPS + 1)) / c
signs = np.where(z[:, None] < 0, (-1.0) ** np.arange(n), 1.0) w[-1] = top**e
out[small] = (np.exp(log_terms[small]) * signs[small]).sum(axis=1) grid = w ** (1 / e)
rest = ~small & (peak <= MP_LOG_MAX) y = np.ones(STEPS + 1)
if rest.any(): kappa = c / np.exp(gammaln(rho))
digits = 30 + int(peak[rest].max() / 2.3) b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho)
bits = int(3.33 * digits) dw = np.diff(w)
with mp.workdps(digits): for n in range(1, STEPS + 1):
c = [mp.mpf(1)] x = grid[: n + 1] / grid[n]
for j in range(n - 1): i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x))
a = rho * (m * j + l) ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x))
c.append(c[-1] * mp.exp(mp.loggamma(a + 1) - mp.loggamma(a + rho + 1))) slope = (ie - w[:n] * i0) / dw[:n]
fixed = [int(mp.ldexp(x, bits)) for x in c] own, next_ = i0 - slope, slope # y_j's and y_(j+1)'s weights on step j
out[rest] = [_horner(fixed, x, bits) for x in z[rest]] known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n])
return out 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: 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)) t = np.atleast_1d(np.asarray(t, float))
s = k + alpha - 2 s = k + alpha - 2
if k + alpha <= 1 or s + beta <= 0: if k + alpha <= 1 or s + beta <= 0:
return np.full(t.shape, np.nan) return np.full(t.shape, np.nan)
scale = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) c = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) / lam ** (k + alpha + beta - 2)
S = np.ones_like(t) return np.clip(kilbas_saigo_survival(t, c, beta, s), 0.0, 1.0)
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)
def fit_fractional( def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]:
d, c, k: float, lam: float, budget: int = FRACTIONAL_EVALUATIONS """(rho, s, scale): the fractional Weibull is S(t) = g(z), z = scale (t/lambda)^(rho+s),
) -> tuple[float, ...]: with g the Kilbas-Saigo survival of order rho and power s at c = 1."""
"""(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, return beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)))
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 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 floor = max(0.0, 1.0 - k) + 1e-6
horizon = float(len(d)) top = len(d) + 0.5 # the latest month the likelihood reads (a censoring's half month)
calls = [0] 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): 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): def profile(p) -> tuple[float, float]:
calls[0] += 1 a, b = unpack(p)
a, b, scale = unpack(p) if k + a <= 1 or k + a + b <= 2:
if ( return INVALID, np.nan
k + a <= 1 rho, s, scale = _shape(k, a, b)
or k + a + b <= 2 e = rho + s
or not 1.0 <= scale <= 1e7 z_top = scale * top**e # lambda = 1 reaches the farthest
or (horizon / scale) ** (k + a + b - 2) > 300 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)
return INVALID # degenerate: the series would be huge and unstable
return _nll(lambda t: fractional(t, k, a, b, scale), d, c)
starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0, np.log(lam)]] def nll(log_lam: float) -> float:
starts += [ found = np.interp(np.log1p(scale * (months / np.exp(log_lam)) ** e), np.log1p(z), g)
[np.log(a0), np.log(b0 / (1 - b0)), np.log(l0)] return _nll(lambda t: found, d, c)
for l0 in (lam, 100.0, 500.0)
for a0 in (0.3, 1.0) coarse = np.linspace(*lambdas, 141)
for b0 in (0.5, 0.9) 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 best = None
for p0 in starts: for p0 in starts:
left = budget - calls[0] options = {"xatol": 1e-5, "fatol": 1e-8, "maxiter": 20_000, "maxfev": 20_000}
if left <= 0: r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
break r = _converged(r, "fractional Weibull")
r = minimize(
nll,
p0,
method="Nelder-Mead",
options={"xatol": 1e-5, "fatol": 1e-9, "maxiter": 1200, "maxfev": left},
)
best = r if best is None or r.fun < best.fun else best 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]))
+17 -14
View File
@@ -4,17 +4,16 @@
interval survival (models.survival) over the age at the index and that report's results. 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`. 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 - 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 cohorts (METABRIC and SCAN-B, models.cama.recurrence) that the platform loads with the
(CAMA_REFERENCE_DIR), not on the hospital's patients; slow (its bootstraps take over an `cama_reference` pipeline, not on the hospital's patients; slow (its bootstraps take a
hour), so it trains only when asked for by name.""" quarter of an hour), so it trains only when asked for by name."""
import os
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path
import pandas as pd import pandas as pd
from models.survival import Spec, age_group, band 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. # The index report's results (timeline types), read from a week before to RESULT_DAYS after.
RESULTS = ("histologic_type", "grade", "er", "pr", "her2") RESULTS = ("histologic_type", "grade", "er", "pr", "her2")
@@ -37,16 +36,13 @@ def covariates(events: pd.DataFrame, members: pd.DataFrame) -> pd.DataFrame:
return found 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) @dataclass(frozen=True)
class ReferenceRecurrence: 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 name: str
pipeline: str = "cama_reference"
cohort: None = None # trains on no gold cohort, and scores no patient cohort: None = None # trains on no gold cohort, and scores no patient
slow: bool = True slow: bool = True
method: str = field(default="stepwise logistic regression + Bayesian network", init=False) 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: def train(self, events, as_of=None) -> tuple:
from models.cama import recurrence from models.cama import recurrence
folder = Path(os.environ.get("CAMA_REFERENCE_DIR", "reference/cama")) model, metrics, reports = recurrence.train(self.datasets())
raws = {s: recurrence.read(s, folder / f) for s, f in REFERENCE_FILES.items()}
model, metrics, reports = recurrence.train(raws)
return model, metrics, reports 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: def predict(self, model, events) -> pd.DataFrame:
return model.predict(events) return model.predict(events)
+7 -16
View File
@@ -43,11 +43,9 @@ from core.pipeline import (
matches, matches,
validate, 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 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` READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
"text": {"data_type": "text", "nullable": True}, "text": {"data_type": "text", "nullable": True},
"ocr": {"data_type": "bool"}, "ocr": {"data_type": "bool"},
@@ -95,13 +93,11 @@ def read_file(content: bytes) -> dict:
def run_read(p: str, node: Read): 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 the file column replaced by its text; each file read once."""
rows = list(nodes.rows(p, node.inputs[0])) rows = list(nodes.rows(p, node.inputs[0]))
keys = {} for row in rows: # the source kept the file; the row carries its hash
for row in rows: row["key"] = row.pop(node.column) or None
content = row.pop(node.column) keys = {r["key"] for r in rows} - {None}
row["key"] = hashlib.sha256(content).hexdigest() if content else None found = nodes.cached("read_cache", keys)
keys[row["key"]] = content new = {k: files.content(k) for k in keys - set(found)}
found = nodes.cached("read_cache", set(keys) - {None})
new = {k: c for k, c in keys.items() if k and k not in found}
with ProcessPoolExecutor() as pool: with ProcessPoolExecutor() as pool:
read = dict(zip(new, pool.map(read_file, new.values()), strict=True)) 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) 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)} linked = {r[RECORD]: r for r in nodes.rows(p, link)}
person = {k: r["person_id"] for k, r in linked.items()} person = {k: r["person_id"] for k, r in linked.items()}
model, study = catalog.model(node.entity), catalog.studies()[node.entity] model, study = catalog.model(node.entity), catalog.studies()[node.entity]
observations, held_rows, files = [], [], {} observations, held_rows = [], []
kept = [n for n, f in study.fields.items() if f.type == "file"]
for i in (i for i in node.inputs if i != link): for i in (i for i in node.inputs if i != link):
for row in nodes.rows(p, i): 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} 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) held = json.loads(row.get(HELD) or "[]") + validate(node.entity, values)
if row[RECORD] not in person: if row[RECORD] not in person:
held.append("no identity linked to this record") 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: if (value := getattr(clean, name)) is not None:
observations.append({**base, "instance": instance, "field": name, observations.append({**base, "instance": instance, "field": name,
catalog.value_column(field): value}) # fmt: skip 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) nodes.stage("observation", p, node.id, observations, silver.OBSERVATION)
return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS) return nodes.stage("held", p, node.id, held_rows, silver.HELD_ROWS)
-1
View File
@@ -22,7 +22,6 @@ dependencies = [
"edfio>=0.4.18", "edfio>=0.4.18",
"statsmodels>=0.15.0", "statsmodels>=0.15.0",
"pgmpy>=1.1.2", "pgmpy>=1.1.2",
"mpmath>=1.4.1",
] ]
[build-system] [build-system]
+1 -1
View File
@@ -94,7 +94,7 @@ def test_a_site_reaches_bronze_once_and_its_documents_are_read(platform, tmp_pat
assert query(corrected) == [("64000",)] assert query(corrected) == [("64000",)]
read = query("select id, text, ocr, error from bronze.n__site__archivos_text") 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+") space = re.compile(r"\s+")
by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read} by_id = {i: (space.sub(" ", txt), ocr) for i, txt, ocr, _ in read}
for r in by_place["ArchivosUni"]: for r in by_place["ArchivosUni"]:
+77 -19
View File
@@ -1,37 +1,49 @@
"""CaMa recurrence reproduces v1 (MLflow run 0e5ea82e, the reference fixtures) from the two """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 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 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 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 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 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 on a rounding edge may land one unit away). The fractional Weibull is fitted to convergence;
stopped its fit on a 60-second wall clock): within FRACTIONAL_TOLERANCE of v1's curve. 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 The full bootstrap and the calculator (whose 40 fractional Weibull curves are fitted to
with RECURRENCE_SLOW=1; the default set takes about two minutes. 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 json
import os import os
import re
from pathlib import Path from pathlib import Path
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import pytest import pytest
from joblib.externals.loky import get_reusable_executor 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 import recurrence
from models.cama.recurrence import calculator, cohorts, curves, factors, modeling, reports from models.cama.recurrence import calculator, cohorts, curves, factors, modeling, reports
RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia")) RAW = Path(os.environ.get("CAMA_REFERENCE_DIR", Path.home() / "camaSupervivencia"))
V1 = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cama" / "recurrence" / "v1" 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 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( 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") 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 [] FIGURES = _json("analisis/recurrencia.json")["escenarios"] if V1.exists() else []
def _raws() -> dict[str, pd.DataFrame]: @pytest.fixture(scope="module")
return {s: recurrence.read(s, RAW / f) for s, f in cohorts.FILES.items()} 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") @pytest.fixture(scope="module")
def prepared(): def prepared(raws):
return {s: cohorts.prepare(s, raw) for s, raw in _raws().items()} return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
@pytest.fixture(scope="module") @pytest.fixture(scope="module")
@@ -64,7 +89,20 @@ def fits(prepared):
# ---------------------------------------------------------------- comparisons # ---------------------------------------------------------------- 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): 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) assert len(mine) == len(ref)
for i, (a, b) in enumerate(zip(mine, ref, strict=True)): for i, (a, b) in enumerate(zip(mine, ref, strict=True)):
assert a.keys() == b.keys(), i assert a.keys() == b.keys(), i
@@ -115,8 +153,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float):
# ---------------------------------------------------------------- fast # ---------------------------------------------------------------- fast
def test_cohorts(prepared): def test_cohorts(prepared, raws):
raws = _raws()
sampling = _json("rutinas/MUESTREO.json")["cohortes"] sampling = _json("rutinas/MUESTREO.json")["cohortes"]
missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"] missing = _json("rutinas/DATOS_FALTANTES.json")["desconocidos_por_covariable"]
for source, c in prepared.items(): for source, c in prepared.items():
@@ -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) assert found["recurrence_36m"].iloc[0] == pytest.approx((p_lr + p_hbn) / 2, abs=1e-15)
@pytest.mark.slow
@slow
def test_calculator(fits): def test_calculator(fits):
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance.""" """All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
records, rows = [], [] records, rows = [], []
@@ -185,15 +224,34 @@ def test_risk_factors(fits):
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"], _same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
FACTOR_TOLERANCE) # fmt: skip FACTOR_TOLERANCE) # fmt: skip
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)] summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
assert reports.table(summary) == DEVELOPMENT["escenarios_resumen"] assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
def test_fractional_weibull_reproduces_the_classic_one(): def test_fractional_weibull_reproduces_the_classic_one():
"""With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's.""" """With alpha = beta = 1 the Kilbas-Saigo survival is the classic Weibull's."""
t = np.linspace(0, 300, 61) t = np.linspace(0, 300, 61)
for k, lam in ((0.9, 476.0), (2.4, 233.6), (1.3, 60.0)): 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), found, want = curves.fractional(t, k, 1.0, 1.0, lam), curves.weibull(t, k, lam)
curves.weibull(t, k, lam), rtol=0, atol=1e-9) # fmt: skip 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 # ---------------------------------------------------------------- slow: the whole v1 run
@@ -201,8 +259,8 @@ def test_fractional_weibull_reproduces_the_classic_one():
@pytest.mark.slow @pytest.mark.slow
@slow @slow
def test_train_reproduces_v1(): def test_train_reproduces_v1(raws):
model, metrics, found = recurrence.train(_raws(), bootstrap=True) model, metrics, found = recurrence.train(raws, bootstrap=True)
assert metrics == VERSION["metrics"] assert metrics == VERSION["metrics"]
for h in recurrence.HORIZONS: for h in recurrence.HORIZONS:
mine = model.tables[h] mine = model.tables[h]
@@ -216,7 +274,7 @@ def test_train_reproduces_v1():
_same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"]) _same_rows(tables["calculadora"]["filas"], DEVELOPMENT["calculadora"]["filas"])
_same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"], _same_rows(tables["factores_riesgo"]["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
FACTOR_TOLERANCE) # fmt: skip FACTOR_TOLERANCE) # fmt: skip
assert tables["escenarios_resumen"] == DEVELOPMENT["escenarios_resumen"] assert tables["escenarios_resumen"] == _stages(DEVELOPMENT["escenarios_resumen"])
figures = found["interpretability"]["recurrencia"] figures = found["interpretability"]["recurrencia"]
assert figures["horizons_months"] == [12, 36, 60] assert figures["horizons_months"] == [12, 36, 60]
_check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE) _check_figures(figures["escenarios"], FRACTIONAL_TOLERANCE)