Compare commits
8 Commits
7e8e8b44d8
...
rebuild
| Author | SHA1 | Date | |
|---|---|---|---|
| a2a9eb7af3 | |||
| 1a1ea5c7a9 | |||
| 77350b8fec | |||
| a9945bc021 | |||
| 3a749ba8d1 | |||
| f369e8f2eb | |||
| f3f79831bf | |||
| 43207fa3a5 |
@@ -1,11 +1,9 @@
|
|||||||
"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months,
|
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned
|
||||||
learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
|
from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian
|
||||||
published files (the `cama_reference` pipeline). Per cohort and horizon, a stepwise logistic
|
network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator
|
||||||
regression and a Bayesian network (BDeu parents of the outcome) are fitted and validated
|
gives the recurrence-free probability of clinical scenarios with bootstrap intervals and
|
||||||
(cohorts, modeling); a calculator gives the recurrence-free probability of clinical scenarios
|
survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports
|
||||||
with bootstrap intervals and survival curves (calculator, curves); risk factors are rated by
|
gives the tables and figures."""
|
||||||
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
|
||||||
|
|
||||||
@@ -15,15 +13,7 @@ import pandas as pd
|
|||||||
|
|
||||||
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
||||||
|
|
||||||
SOURCES = ("metabric", "scanb")
|
|
||||||
HORIZONS = modeling.HORIZONS # months
|
HORIZONS = modeling.HORIZONS # months
|
||||||
SAVED = "metabric"
|
|
||||||
|
|
||||||
|
|
||||||
def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
"""The source's cohort table, from its dataset's rows: fixed columns, then its
|
|
||||||
covariates as categories."""
|
|
||||||
return cohorts.prepare(source, rows).frame
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -59,28 +49,21 @@ class Recurrence:
|
|||||||
return pd.DataFrame(out, index=X.index)
|
return pd.DataFrame(out, index=X.index)
|
||||||
|
|
||||||
|
|
||||||
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
|
||||||
"""Both reference cohorts' models, validation, calculator and risk factors, from their
|
|
||||||
datasets' rows; the saved model is METABRIC's.
|
|
||||||
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
|
|
||||||
stability criterion, are then missing)."""
|
|
||||||
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
|
|
||||||
return fit(found, SAVED, "metabric+scanb", bootstrap)
|
|
||||||
|
|
||||||
|
|
||||||
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
||||||
"""The same, on the site's own cohort (models.cama.recurrence.site)."""
|
"""The model of the site's own cohort (models.cama.recurrence.site), its metrics and its
|
||||||
|
reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
|
||||||
|
factors' stability criterion, are then missing)."""
|
||||||
from models.cama.recurrence import site
|
from models.cama.recurrence import site
|
||||||
|
|
||||||
return fit({"site": site.prepare(rows)}, "site", "site", bootstrap)
|
return fit({"site": site.prepare(rows)}, "site", "site",
|
||||||
|
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
def fit(found: dict, saved: str, label: str,
|
def fit(found: dict, saved: str, label: str,
|
||||||
bootstrap: bool = True) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
||||||
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
||||||
the `saved` cohort's is the model kept."""
|
the `saved` cohort's is the model kept."""
|
||||||
sources = list(found)
|
sources = list(found)
|
||||||
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
|
|
||||||
try:
|
try:
|
||||||
fits = modeling.fit(found, n_bootstrap)
|
fits = modeling.fit(found, n_bootstrap)
|
||||||
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
||||||
|
|||||||
@@ -21,45 +21,6 @@ RESAMPLES = 200
|
|||||||
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
|
MIN_EVENTS = 15 # a scenario is drawn when it has this many recurrences
|
||||||
CAP_MONTHS = 72 # the Weibull curves' extent
|
CAP_MONTHS = 72 # the Weibull curves' extent
|
||||||
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
|
GRID_POINTS = 289 # 0 to CAP_MONTHS by quarter months
|
||||||
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B", "site": "Sitio"}
|
|
||||||
|
|
||||||
# Each scenario: covariate -> the categories it takes (AND across covariates).
|
|
||||||
SCENARIOS = {
|
|
||||||
"metabric": {
|
|
||||||
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
|
||||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
|
|
||||||
"Tamano_tumor": ["<=20 mm"]},
|
|
||||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
|
||||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
|
||||||
"< 45 años": {"Edad": ["<45"]},
|
|
||||||
"≥ 75 años": {"Edad": ["75+"]},
|
|
||||||
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
|
||||||
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
|
||||||
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
|
||||||
"RE+ · 1-3 ganglios · cirugía conservadora": {
|
|
||||||
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
|
|
||||||
"Cirugia": ["BREAST CONSERVING"]},
|
|
||||||
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
|
||||||
},
|
|
||||||
"scanb": {
|
|
||||||
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
|
||||||
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
|
|
||||||
"Tamano_tumor": ["<=20 mm"]},
|
|
||||||
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
|
||||||
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
|
||||||
"< 45 años": {"Edad": ["<45"]},
|
|
||||||
"≥ 75 años": {"Edad": ["75+"]},
|
|
||||||
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
|
||||||
"HER2+ (luminal B HER2+ o no luminal)": {
|
|
||||||
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
|
|
||||||
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
|
||||||
"Luminal · 1-3 ganglios · lumpectomía": {
|
|
||||||
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
|
|
||||||
"Cirugia": ["Lumpectomy"]},
|
|
||||||
"Grado 3": {"Grado_histologico": ["3"]},
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
SCENARIOS["site"] = SCENARIOS["scanb"] # the site's cohort is described as SCAN-B's
|
|
||||||
|
|
||||||
|
|
||||||
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
def masks(frame: pd.DataFrame, scenarios: dict) -> dict[str, np.ndarray]:
|
||||||
@@ -143,10 +104,10 @@ def _curves(months, event, observed):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[dict], list[dict]]:
|
def calculator(fitted: CohortFit) -> tuple[list[dict], list[dict]]:
|
||||||
"""The figure record of each scenario with enough recurrences, and its table rows."""
|
"""The figure record of each scenario with enough recurrences, and its table rows."""
|
||||||
source = fitted.cohort.source
|
source = fitted.cohort.source
|
||||||
scenarios = SCENARIOS[source] if scenarios is None else scenarios
|
scenarios = fitted.cohort.scenarios
|
||||||
risk = Risk(fitted)
|
risk = Risk(fitted)
|
||||||
found = masks(fitted.cohort.frame, scenarios)
|
found = masks(fitted.cohort.frame, scenarios)
|
||||||
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
|
rng = np.random.default_rng(SEED) # resamples drawn in order, refitted in parallel
|
||||||
@@ -169,7 +130,7 @@ def calculator(fitted: CohortFit, scenarios: dict | None = None) -> tuple[list[d
|
|||||||
records.append(
|
records.append(
|
||||||
{
|
{
|
||||||
"cohorte": source,
|
"cohorte": source,
|
||||||
"cohorte_nombre": LABELS[source],
|
"cohorte_nombre": fitted.cohort.label,
|
||||||
"escenario": name,
|
"escenario": name,
|
||||||
"condiciones": scenarios[name],
|
"condiciones": scenarios[name],
|
||||||
"n": n,
|
"n": n,
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
"""Each reference cohort as one table of categories, from its dataset as the platform loaded
|
"""A cohort as one table of categories: the patients with a known recurrence time and status,
|
||||||
it (the `cama_reference` pipeline: every value as written, column names as dlt names them,
|
their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their covariates
|
||||||
`line` the order the file is published in): the patients with a known recurrence time and
|
as text. A missing or out-of-range value is a category of its own (UNKNOWN); nothing is imputed
|
||||||
status, their time to recurrence (`tiempo_meses`), whether it happened (`evento`), and their
|
or dropped for it. Of each pair of nearly redundant covariates (Cramér's V >= V_MAX), the one
|
||||||
covariates as text. A missing or out-of-range value is a category of its own (UNKNOWN);
|
with more unknowns is dropped."""
|
||||||
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
|
||||||
|
|
||||||
@@ -14,6 +12,7 @@ from scipy.stats.contingency import association
|
|||||||
UNKNOWN = "Desconocido"
|
UNKNOWN = "Desconocido"
|
||||||
V_MAX = 0.80
|
V_MAX = 0.80
|
||||||
DAYS_PER_MONTH = 30.4375
|
DAYS_PER_MONTH = 30.4375
|
||||||
|
HORIZONS = (12, 36, 60) # months
|
||||||
|
|
||||||
# Bands, closed on the left: [a, b).
|
# Bands, closed on the left: [a, b).
|
||||||
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
AGE = ([0, 45, 60, 75, 200], ["<45", "45-59", "60-74", "75+"])
|
||||||
@@ -21,37 +20,6 @@ SIZE = ([0, 20.01, 50.01, 1e4], ["<=20 mm", "21-50 mm", ">50 mm"])
|
|||||||
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
NODES = ([0, 1, 4, 1e3], ["0", "1-3", "4+"])
|
||||||
GRADES = {"1": "1", "2": "2", "3": "3"}
|
GRADES = {"1": "1", "2": "2", "3": "3"}
|
||||||
|
|
||||||
FIXED = {
|
|
||||||
"metabric": ["paciente", "tiempo_meses", "evento"],
|
|
||||||
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
|
||||||
}
|
|
||||||
TREATMENT = {
|
|
||||||
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
|
|
||||||
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
|
|
||||||
}
|
|
||||||
# Covariates taken as they come (our name: the dataset's column).
|
|
||||||
PASSTHROUGH = {
|
|
||||||
"metabric": {
|
|
||||||
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
|
|
||||||
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
|
|
||||||
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
|
|
||||||
"Estado_menopausico": "inferred_menopausal_state",
|
|
||||||
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
|
|
||||||
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
|
|
||||||
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
|
|
||||||
},
|
|
||||||
"scanb": {
|
|
||||||
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
|
|
||||||
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
|
|
||||||
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
|
|
||||||
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
|
|
||||||
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
|
|
||||||
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
|
|
||||||
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
|
|
||||||
|
|
||||||
|
|
||||||
def _number(s: pd.Series) -> pd.Series:
|
def _number(s: pd.Series) -> pd.Series:
|
||||||
return pd.to_numeric(s, errors="coerce")
|
return pd.to_numeric(s, errors="coerce")
|
||||||
@@ -66,47 +34,6 @@ def _band(s: pd.Series, edges: list, labels: list) -> pd.Series:
|
|||||||
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
|
return _text(pd.cut(s, edges, labels=labels, right=False).astype(object))
|
||||||
|
|
||||||
|
|
||||||
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
return rows.sort_values("line", kind="stable").reset_index(drop=True)
|
|
||||||
|
|
||||||
|
|
||||||
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
|
|
||||||
d = d.reset_index(drop=True)
|
|
||||||
out = pd.DataFrame({"paciente": d["patient_id"]})
|
|
||||||
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
|
|
||||||
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
|
|
||||||
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
|
|
||||||
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
|
|
||||||
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
|
|
||||||
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
|
|
||||||
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
|
|
||||||
load = _number(d["mutation_count"])
|
|
||||||
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
|
|
||||||
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
|
|
||||||
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
|
|
||||||
for name, column in PASSTHROUGH["metabric"].items():
|
|
||||||
out[name] = _text(d[column])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
|
|
||||||
d = _in_order(rows)
|
|
||||||
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
|
|
||||||
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
|
|
||||||
out = pd.DataFrame({"paciente": d["patient_name"]})
|
|
||||||
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
|
|
||||||
out["evento"] = rfi.astype(int)
|
|
||||||
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
|
|
||||||
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
|
|
||||||
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
|
|
||||||
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
|
|
||||||
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
|
|
||||||
for name, column in PASSTHROUGH["scanb"].items():
|
|
||||||
out[name] = _text(d[column])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def cramers_v(a: pd.Series, b: pd.Series) -> float:
|
def cramers_v(a: pd.Series, b: pd.Series) -> float:
|
||||||
table = pd.crosstab(a, b).to_numpy()
|
table = pd.crosstab(a, b).to_numpy()
|
||||||
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
return association(table, method="cramer") if min(table.shape) > 1 else 0.0
|
||||||
@@ -143,21 +70,15 @@ class Cohort:
|
|||||||
covariates: list[str]
|
covariates: list[str]
|
||||||
treatment: list[str]
|
treatment: list[str]
|
||||||
eliminated: list[str]
|
eliminated: list[str]
|
||||||
|
label: str # as the reports name it
|
||||||
|
scenarios: dict # the clinical scenarios drawn: name -> covariate -> its categories
|
||||||
|
sampling: dict # how its patients were chosen (the MUESTREO record)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def intrinsic(self) -> list[str]:
|
def intrinsic(self) -> list[str]:
|
||||||
return [c for c in self.covariates if c not in self.treatment]
|
return [c for c in self.covariates if c not in self.treatment]
|
||||||
|
|
||||||
|
|
||||||
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
|
|
||||||
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
|
|
||||||
fixed, treatment = FIXED[source], TREATMENT[source]
|
|
||||||
covariates = [c for c in full.columns if c not in fixed]
|
|
||||||
dropped = collinear(full, [c for c in covariates if c not in treatment])
|
|
||||||
kept = [c for c in covariates if c not in dropped]
|
|
||||||
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped)
|
|
||||||
|
|
||||||
|
|
||||||
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
def at_horizon(frame: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
||||||
"""The patients whose status at `horizon` months is known (a recurrence by then, or
|
"""The patients whose status at `horizon` months is known (a recurrence by then, or
|
||||||
followed past it), with `y` = recurred by then."""
|
followed past it), with `y` = recurred by then."""
|
||||||
|
|||||||
@@ -1,35 +1,20 @@
|
|||||||
"""The risk factors of recurrence by each horizon, and the ones each calculator scenario has.
|
"""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),
|
||||||
Each category of an intrinsic covariate (not a treatment) is rated against its covariate's
|
the horizon's HBN parents give (3))."""
|
||||||
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."""
|
|
||||||
|
|
||||||
import warnings
|
import warnings
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import statsmodels.api as sm
|
|
||||||
from scipy.stats import false_discovery_control
|
|
||||||
|
|
||||||
from models.cama.recurrence.calculator import SCENARIOS, masks
|
from models import factors as rated
|
||||||
|
from models.cama.recurrence.calculator import masks
|
||||||
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
from models.cama.recurrence.cohorts import UNKNOWN, at_horizon
|
||||||
from models.cama.recurrence.modeling import CohortFit, variable_of
|
from models.cama.recurrence.modeling import CohortFit
|
||||||
from models.curves import life_table
|
from models.factors import FREQ_MIN, ORDER
|
||||||
|
|
||||||
ALPHA = 0.05
|
OR = "OR_recurrencia"
|
||||||
FREQ_MIN = 0.80
|
SURVIVAL = ("S_libre_categoria", "S_libre_referencia", "delta_S")
|
||||||
Z = 1.96
|
|
||||||
ORDER = {
|
|
||||||
"riesgo robusto": 0,
|
|
||||||
"protector robusto": 1,
|
|
||||||
"riesgo sugerente": 2,
|
|
||||||
"protector sugerente": 3,
|
|
||||||
"no concluyente": 4,
|
|
||||||
}
|
|
||||||
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
TREATMENT_CLASS = "tratamiento (no se clasifica; asociacion, no efecto causal)"
|
||||||
COLUMNS = [
|
COLUMNS = [
|
||||||
"cohorte",
|
"cohorte",
|
||||||
@@ -39,16 +24,14 @@ COLUMNS = [
|
|||||||
"categoria",
|
"categoria",
|
||||||
"referencia",
|
"referencia",
|
||||||
"n_categoria",
|
"n_categoria",
|
||||||
"OR_recurrencia",
|
OR,
|
||||||
"IC95_inf",
|
"IC95_inf",
|
||||||
"IC95_sup",
|
"IC95_sup",
|
||||||
"p",
|
"p",
|
||||||
"p_ajustado_BH",
|
"p_ajustado_BH",
|
||||||
"freq_seleccion_bootstrap",
|
"freq_seleccion_bootstrap",
|
||||||
"en_manta_markov",
|
"en_manta_markov",
|
||||||
"S_libre_categoria",
|
*SURVIVAL,
|
||||||
"S_libre_referencia",
|
|
||||||
"delta_S",
|
|
||||||
"delta_IC95_inf",
|
"delta_IC95_inf",
|
||||||
"delta_IC95_sup",
|
"delta_IC95_sup",
|
||||||
"c1_or",
|
"c1_or",
|
||||||
@@ -58,39 +41,7 @@ COLUMNS = [
|
|||||||
"criterios_cumplidos",
|
"criterios_cumplidos",
|
||||||
"clasificacion",
|
"clasificacion",
|
||||||
]
|
]
|
||||||
# Scenario presence: the share of the scenario's patients in the category.
|
DESCRIBING = rated.DESCRIBING
|
||||||
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(),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _horizon(fitted: CohortFit, horizon: int, selection: dict | None) -> pd.DataFrame:
|
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()
|
event = ((cohort.frame["evento"] == 1) & (t <= horizon)).to_numpy()
|
||||||
|
|
||||||
def complete(table, variables):
|
def complete(table, variables):
|
||||||
"""Each term's covariate, category, BH p and survival difference to its reference."""
|
return rated.complete(table, variables, reference, everyone, months, event, horizon,
|
||||||
table = table.reset_index(drop=True)
|
SURVIVAL) # fmt: skip
|
||||||
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)
|
|
||||||
|
|
||||||
intrinsic, treatment = cohort.intrinsic, cohort.treatment
|
intrinsic, treatment = cohort.intrinsic, cohort.treatment
|
||||||
tab = complete(_odds_ratios(data, y, intrinsic, reference), intrinsic)
|
tab = complete(rated.odds_ratios(data, y, intrinsic, reference, OR), 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))
|
|
||||||
hz = fitted.horizons[horizon]
|
hz = fitted.horizons[horizon]
|
||||||
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
|
tab["freq_seleccion_bootstrap"] = tab["variable"].map(
|
||||||
lambda v: np.nan if selection is None else selection.get(v, 0.0)
|
lambda v: np.nan if selection is None else selection.get(v, 0.0)
|
||||||
)
|
)
|
||||||
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
|
tab["c2_estabilidad"] = tab["freq_seleccion_bootstrap"] >= FREQ_MIN
|
||||||
tab["en_manta_markov"] = tab["c3_manta_markov"] = tab["variable"].isin(hz.split.parents)
|
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 = rated.classify(tab, OR, SURVIVAL[2], UNKNOWN)
|
||||||
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["tipo"] = "factor de riesgo"
|
tab["tipo"] = "factor de riesgo"
|
||||||
if treatment:
|
if treatment:
|
||||||
both = intrinsic + treatment
|
both = intrinsic + treatment
|
||||||
tr = _odds_ratios(data, y, both, reference)
|
tr = rated.odds_ratios(data, y, both, reference, OR)
|
||||||
of = tr["termino"].map(lambda x: variable_of(x, both))
|
of = tr["termino"].map(lambda x: rated.variable_of(x, both))
|
||||||
tr = complete(
|
tr = complete(
|
||||||
tr[of.isin(treatment) & ~tr["termino"].str.endswith("_" + UNKNOWN)], treatment
|
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 = pd.concat(found, ignore_index=True)
|
||||||
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
tab["_kind"] = (tab["tipo"] != "factor de riesgo").astype(int)
|
||||||
tab["_order"] = tab["clasificacion"].map(ORDER).fillna(5)
|
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])
|
tab = tab.sort_values(keys, ascending=[True, True, True, False])
|
||||||
return tab[COLUMNS].round(4)
|
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]:
|
def scenario_summary(fitted: CohortFit, factors: pd.DataFrame) -> list[dict]:
|
||||||
"""Per scenario and horizon, the classified factors and treatments nearly all of its
|
"""Per scenario and horizon, the classified factors and treatments nearly all of its
|
||||||
patients have (definitorios) or most have (mayoritarios)."""
|
patients have (definitorios) or most have (mayoritarios)."""
|
||||||
frame, source = fitted.cohort.frame, fitted.cohort.source
|
frame, source = fitted.cohort.frame, fitted.cohort.source
|
||||||
scenarios = SCENARIOS[source]
|
scenarios = fitted.cohort.scenarios
|
||||||
found = factors[
|
found = rated.classified(factors[factors["cohorte"] == source])
|
||||||
(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)
|
|
||||||
rows = []
|
rows = []
|
||||||
for name, mask in masks(frame, scenarios).items():
|
for name, mask in masks(frame, scenarios).items():
|
||||||
if not mask.any() or found.empty:
|
if not mask.any() or found.empty:
|
||||||
continue
|
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())
|
definition = "; ".join(f"{v} = {' / '.join(c)}" for v, c in scenarios[name].items())
|
||||||
for h in fitted.horizons:
|
for h in fitted.horizons:
|
||||||
d = detail[detail["horizonte_meses"] == h]
|
rows.append({
|
||||||
row = {
|
"cohorte": source, "escenario": name, "definicion": definition,
|
||||||
"cohorte": source,
|
"n_escenario": int(mask.sum()), "horizonte_meses": h,
|
||||||
"escenario": name,
|
**rated.scenario_row(frame, mask, found[found["horizonte_meses"] == h]),
|
||||||
"definicion": definition,
|
}) # fmt: skip
|
||||||
"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)
|
|
||||||
return rows
|
return rows
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ from pgmpy.structure_score import BDeu
|
|||||||
from sklearn.metrics import roc_auc_score
|
from sklearn.metrics import roc_auc_score
|
||||||
from sklearn.model_selection import train_test_split
|
from sklearn.model_selection import train_test_split
|
||||||
|
|
||||||
from models.cama.recurrence.cohorts import Cohort, at_horizon
|
from models.cama.recurrence.cohorts import HORIZONS, Cohort, at_horizon
|
||||||
|
from models.factors import variable_of
|
||||||
|
|
||||||
HORIZONS = (12, 36, 60) # months
|
|
||||||
SEED = 42
|
SEED = 42
|
||||||
TEST_SIZE = 0.3
|
TEST_SIZE = 0.3
|
||||||
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
|
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
|
||||||
@@ -31,7 +31,7 @@ ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
|
|||||||
MAX_STEPS = 200
|
MAX_STEPS = 200
|
||||||
COX_PENALIZER = 0.05
|
COX_PENALIZER = 0.05
|
||||||
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
|
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
|
||||||
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
|
N_BOOTSTRAP = {"site": 40}
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------- logistic regression
|
# ---------------------------------------------------------------- logistic regression
|
||||||
@@ -203,12 +203,6 @@ def c_index(cohort: Cohort) -> float:
|
|||||||
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
|
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
|
@dataclass
|
||||||
class Horizon:
|
class Horizon:
|
||||||
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
|
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
|
||||||
|
|||||||
@@ -95,17 +95,6 @@ def metrics(auc: list[dict]) -> dict[str, float]:
|
|||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
REFERENCE_SAMPLING = {
|
|
||||||
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
|
||||||
"origen": "METABRIC y SCAN-B (externas)",
|
|
||||||
}
|
|
||||||
SITE_SAMPLING = {
|
|
||||||
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
|
|
||||||
"libre de ella hasta su defunción o la fecha de corte",
|
|
||||||
"origen": "la sede (sus propias pacientes)",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
||||||
"""The five routine records a promotion reads."""
|
"""The five routine records a promotion reads."""
|
||||||
return {
|
return {
|
||||||
@@ -119,7 +108,7 @@ def routines(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict:
|
|||||||
}
|
}
|
||||||
for s, c in cohorts.items()
|
for s, c in cohorts.items()
|
||||||
},
|
},
|
||||||
**(SITE_SAMPLING if "site" in cohorts else REFERENCE_SAMPLING),
|
**next(iter(cohorts.values())).sampling,
|
||||||
},
|
},
|
||||||
"DATOS_FALTANTES": {
|
"DATOS_FALTANTES": {
|
||||||
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
|
"criterio": f"el dato faltante es una categoría más («{UNKNOWN}»); "
|
||||||
|
|||||||
@@ -30,6 +30,30 @@ TREATMENTS = {"Quimioterapia": "chemotherapy", "Radioterapia": "radiotherapy",
|
|||||||
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
|
"Hormonoterapia": "hormone_therapy", "AntiHER2": "anti_her2"} # fmt: skip
|
||||||
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
FIXED = ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"]
|
||||||
TREATMENT = ["Cirugia", *TREATMENTS]
|
TREATMENT = ["Cirugia", *TREATMENTS]
|
||||||
|
# The clinical scenarios drawn: covariate -> the categories it takes (AND across covariates).
|
||||||
|
SCENARIOS = {
|
||||||
|
"Luminal A · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||||
|
"Subtipo_clinico": ["Luminal A"], "Ganglios_positivos": ["0"],
|
||||||
|
"Tamano_tumor": ["<=20 mm"]},
|
||||||
|
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||||
|
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||||
|
"< 45 años": {"Edad": ["<45"]},
|
||||||
|
"≥ 75 años": {"Edad": ["75+"]},
|
||||||
|
"Basal-like": {"Subtipo_clinico": ["Basal-like"]},
|
||||||
|
"HER2+ (luminal B HER2+ o no luminal)": {
|
||||||
|
"Subtipo_clinico": ["Luminal B HER2+", "Non-luminal HER2+"]},
|
||||||
|
"Luminal B HER2−": {"Subtipo_clinico": ["Luminal B HER2-"]},
|
||||||
|
"Luminal · 1-3 ganglios · lumpectomía": {
|
||||||
|
"Subtipo_clinico": ["Luminal A", "Luminal B HER2-"], "Ganglios_positivos": ["1-3"],
|
||||||
|
"Cirugia": ["Lumpectomy"]},
|
||||||
|
"Grado 3": {"Grado_histologico": ["3"]},
|
||||||
|
} # fmt: skip
|
||||||
|
MIN_PER_CLASS = 10 # recurred, and free of it, at each horizon: fewer cannot be split and fitted
|
||||||
|
SAMPLING = {
|
||||||
|
"criterio": "pacientes con un primer reporte de biopsia invasiva; sin recaída registrada, "
|
||||||
|
"libre de ella hasta su defunción o la fecha de corte",
|
||||||
|
"origen": "la sede (sus propias pacientes)",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def subtype(er, pr, her2, ki67) -> str:
|
def subtype(er, pr, her2, ki67) -> str:
|
||||||
@@ -97,6 +121,18 @@ def frame(events: pd.DataFrame, as_of) -> pd.DataFrame:
|
|||||||
return out.reset_index(drop=True)
|
return out.reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def scarce(rows: pd.DataFrame) -> str | None:
|
||||||
|
"""Why the cohort is too small to learn from (a horizon with fewer than MIN_PER_CLASS
|
||||||
|
patients recurred by it, or known free of it), or None."""
|
||||||
|
for h in cohorts.HORIZONS:
|
||||||
|
y = cohorts.at_horizon(rows, h)["y"]
|
||||||
|
fewest = min(int(y.sum()), int((y == 0).sum()))
|
||||||
|
if fewest < MIN_PER_CLASS:
|
||||||
|
return (f"{int(y.sum())} recurred and {int((y == 0).sum())} free of it at {h} months, "
|
||||||
|
f"{MIN_PER_CLASS} of each needed") # fmt: skip
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def prepare(rows: pd.DataFrame) -> Cohort:
|
def prepare(rows: pd.DataFrame) -> Cohort:
|
||||||
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
|
"""The site's cohort as a reference cohort is prepared: the nearly redundant covariates
|
||||||
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
|
dropped (cohorts.collinear) from the model, though kept in the table, since the clinical
|
||||||
@@ -106,4 +142,5 @@ def prepare(rows: pd.DataFrame) -> Cohort:
|
|||||||
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
|
dropped = collinear(rows, [c for c in covariates if c not in TREATMENT])
|
||||||
kept = [c for c in covariates if c not in dropped]
|
kept = [c for c in covariates if c not in dropped]
|
||||||
treatment = [c for c in TREATMENT if c in kept]
|
treatment = [c for c in TREATMENT if c in kept]
|
||||||
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped)
|
return Cohort("site", rows[FIXED + kept + dropped], kept, treatment, dropped, "Sitio",
|
||||||
|
SCENARIOS, SAMPLING) # fmt: skip
|
||||||
|
|||||||
@@ -9,8 +9,7 @@
|
|||||||
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
|
Training and scoring read the timelines (gold `cama_events`) of `gold.cama_cohort_survival`.
|
||||||
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
|
- Recurrence: risk of recurrence at 12, 36 and 60 months, trained on the site's patients
|
||||||
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
|
(`gold.cama_cohort_recurrence`, models.cama.recurrence.site) with the old model's math
|
||||||
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py); slow (its bootstraps
|
(proved on METABRIC and SCAN-B by models/tests/test_recurrence.py)."""
|
||||||
take minutes), so it trains only when asked for by name."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import date
|
from datetime import date
|
||||||
@@ -96,15 +95,18 @@ class SiteRecurrence:
|
|||||||
|
|
||||||
name: str
|
name: str
|
||||||
cohort: str = "cama_cohort_recurrence"
|
cohort: str = "cama_cohort_recurrence"
|
||||||
slow: bool = True
|
|
||||||
reports: bool = True # it writes its own reports (models.jobs)
|
reports: bool = True # it writes its own reports (models.jobs)
|
||||||
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
|
method: str = field(default="stepwise logistic regression + Bayesian network", init=False)
|
||||||
|
|
||||||
def train(self, events, as_of=None) -> tuple:
|
def train(self, events, as_of=None) -> tuple:
|
||||||
from models.cama import recurrence
|
from models.cama import recurrence
|
||||||
from models.cama.recurrence import site
|
from models.cama.recurrence import site
|
||||||
|
from models.jobs import EmptyCohort
|
||||||
|
|
||||||
return recurrence.train_site(site.frame(events, as_of or date.today()))
|
rows = site.frame(events, as_of or date.today())
|
||||||
|
if reason := site.scarce(rows):
|
||||||
|
raise EmptyCohort(f"cama.recurrence: {reason}")
|
||||||
|
return recurrence.train_site(rows)
|
||||||
|
|
||||||
def predict(self, model, events) -> pd.DataFrame:
|
def predict(self, model, events) -> pd.DataFrame:
|
||||||
from models.cama.recurrence import calculator, site
|
from models.cama.recurrence import calculator, site
|
||||||
@@ -112,7 +114,7 @@ class SiteRecurrence:
|
|||||||
members = site.frame(events, date.today())
|
members = site.frame(events, date.today())
|
||||||
found = model.predict(members)
|
found = model.predict(members)
|
||||||
index = events.groupby("person_id")["index_date"].first()
|
index = events.groupby("person_id")["index_date"].first()
|
||||||
masks = calculator.masks(members, calculator.SCENARIOS["site"])
|
masks = calculator.masks(members, site.SCENARIOS)
|
||||||
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
|
named = [SCENARIO_SEPARATOR.join(n for n, m in masks.items() if m[i]) or None
|
||||||
for i in range(len(members))] # fmt: skip
|
for i in range(len(members))] # fmt: skip
|
||||||
rows = []
|
rows = []
|
||||||
@@ -153,6 +155,7 @@ MODELS = {
|
|||||||
cap_months=24,
|
cap_months=24,
|
||||||
scenarios=SCENARIOS,
|
scenarios=SCENARIOS,
|
||||||
scenario_columns=("age",),
|
scenario_columns=("age",),
|
||||||
|
treatments=("surgery", "chemotherapy", "radiotherapy"),
|
||||||
notes=(
|
notes=(
|
||||||
f"Tratamiento: el primer curso (convención de SEER), lo recibido en los "
|
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 "
|
f"{TREATMENT_DAYS} días tras el índice, tomado como conocido en él. Quien muere "
|
||||||
|
|||||||
+50
-4
@@ -1,12 +1,14 @@
|
|||||||
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
"""Dagster code location: every heavy step of the platform is a job defined here."""
|
||||||
|
|
||||||
import importlib
|
import importlib
|
||||||
|
import os
|
||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
import dagster as dg
|
import dagster as dg
|
||||||
|
|
||||||
from models import graph
|
from models import draft, graph
|
||||||
from models.jobs import EmptyCohort
|
from models.jobs import EmptyCohort
|
||||||
|
from persistance import backup as backups
|
||||||
from persistance import config_log, silver
|
from persistance import config_log, silver
|
||||||
|
|
||||||
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
|
||||||
@@ -31,6 +33,26 @@ def ingest():
|
|||||||
run_pipeline()
|
run_pipeline()
|
||||||
|
|
||||||
|
|
||||||
|
class DraftRun(dg.Config):
|
||||||
|
pipeline: str
|
||||||
|
|
||||||
|
|
||||||
|
@dg.op
|
||||||
|
def draft_pipeline(context: dg.OpExecutionContext, config: DraftRun) -> int:
|
||||||
|
"""Automático: the whole pipeline drafted from its sources, saved as a new version and
|
||||||
|
run. Returns that version."""
|
||||||
|
drafted = draft.draft(config.pipeline, log=context.log.info)
|
||||||
|
version = config_log.save(config.pipeline, drafted)
|
||||||
|
context.log.info(f"{config.pipeline} v{version}: {len(drafted.nodes)} nodes drafted")
|
||||||
|
graph.run(config.pipeline, drafted, log=context.log.info)
|
||||||
|
return version
|
||||||
|
|
||||||
|
|
||||||
|
@dg.job(name="draft", tags=WRITES)
|
||||||
|
def draft_job():
|
||||||
|
draft_pipeline()
|
||||||
|
|
||||||
|
|
||||||
def _jobs(domain: str):
|
def _jobs(domain: str):
|
||||||
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
|
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
|
||||||
try:
|
try:
|
||||||
@@ -41,7 +63,7 @@ def _jobs(domain: str):
|
|||||||
|
|
||||||
class Training(dg.Config):
|
class Training(dg.Config):
|
||||||
domain: str
|
domain: str
|
||||||
models: list[str] = [] # default: every model of the domain but the slow ones
|
models: list[str] = [] # default: every model of the domain
|
||||||
as_of: str | None = None # the date the data are taken up to (default: today)
|
as_of: str | None = None # the date the data are taken up to (default: today)
|
||||||
|
|
||||||
|
|
||||||
@@ -76,7 +98,7 @@ class Scoring(dg.Config):
|
|||||||
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
|
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
|
||||||
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
|
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
|
||||||
jobs = _jobs(config.domain)
|
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():
|
for name, version in found.items():
|
||||||
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
|
||||||
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
|
silver.build([getattr(jobs, "GOLD", f"{config.domain}_risk") + "+"])
|
||||||
@@ -105,4 +127,28 @@ def analyze():
|
|||||||
analyze_studies()
|
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, draft_job, train, score, analyze, backup], schedules=nightly)
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Automático: a whole pipeline drafted from the sources an operator connected. Each source
|
||||||
|
is loaded and its files read as a run would; documents are drafted by layout
|
||||||
|
(models.draft.documents), tables by column (models.draft.tables); one link node gathers
|
||||||
|
every record's identity and one target per study saves it. The model only fills typed
|
||||||
|
slots that code checks; who is the same patient stays with the reviewers."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
import unicodedata
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
from core.pipeline import ENTITY_TITLES, Link, Pipeline, Read, Target
|
||||||
|
from models import graph
|
||||||
|
from models.draft import documents, fields, tables
|
||||||
|
from persistance import config_log, files, nodes
|
||||||
|
|
||||||
|
FILE_KEY = re.compile(r"^[0-9a-f]{64}$") # a kept file's key (persistance.files)
|
||||||
|
SCANNED = 50 # rows looked at to tell a column of files
|
||||||
|
|
||||||
|
|
||||||
|
class Draft:
|
||||||
|
"""The nodes drafted so far, their ids unique, and the site's codes found."""
|
||||||
|
|
||||||
|
def __init__(self, pipeline_id: str, sources: list):
|
||||||
|
self.pipeline_id, self.nodes = pipeline_id, list(sources)
|
||||||
|
self.identity: list[str] = []
|
||||||
|
self.studies: dict[str, list[str]] = {}
|
||||||
|
self.codes = fields.Codes(pipeline_id)
|
||||||
|
|
||||||
|
def id(self, text: str) -> str:
|
||||||
|
plain = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()
|
||||||
|
base = re.sub(r"[^a-z0-9]+", "_", plain).strip("_")[:34] or "nodo"
|
||||||
|
base = base if base[0].isalpha() else f"n_{base}"[:34]
|
||||||
|
taken, found, n = {n.id for n in self.nodes}, base, 1
|
||||||
|
while found in taken:
|
||||||
|
n += 1
|
||||||
|
found = f"{base}_{n}"
|
||||||
|
return found
|
||||||
|
|
||||||
|
def add(self, node):
|
||||||
|
self.nodes.append(node)
|
||||||
|
return node
|
||||||
|
|
||||||
|
def finish(self) -> Pipeline:
|
||||||
|
"""The site's codes saved as its ConceptMap, one link node, a target per study."""
|
||||||
|
if not self.identity:
|
||||||
|
raise ValueError("nothing read says whom a record is about: nothing to link")
|
||||||
|
if (found := self.codes.concept_map()) is not None:
|
||||||
|
config_log.save(self.codes.map_id, found, "concept_maps")
|
||||||
|
link = self.add(Link(id=self.id("personas"), label="Quién es quién",
|
||||||
|
inputs=self.identity)) # fmt: skip
|
||||||
|
for entity, inputs in self.studies.items():
|
||||||
|
self.add(Target(id=self.id(f"guardar_{entity}"), label=ENTITY_TITLES[entity],
|
||||||
|
inputs=[*inputs, link.id], entity=entity)) # fmt: skip
|
||||||
|
return Pipeline(nodes=self.nodes)
|
||||||
|
|
||||||
|
|
||||||
|
def file_columns(rows: list[dict]) -> list[str]:
|
||||||
|
"""Columns whose values are kept files (a source keeps each file once and passes its key)."""
|
||||||
|
found = []
|
||||||
|
for column in sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")}):
|
||||||
|
values = {r.get(column) for r in rows[:SCANNED]} - {None}
|
||||||
|
if values and all(isinstance(v, str) and FILE_KEY.match(v) for v in values):
|
||||||
|
if files.known(values):
|
||||||
|
found.append(column)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def draft(pipeline_id: str, log: Callable[[str], None] = print) -> Pipeline:
|
||||||
|
"""The pipeline Automático draws from a saved pipeline made of sources only."""
|
||||||
|
_, saved = config_log.get(pipeline_id)
|
||||||
|
sources = [n for n in saved.nodes if n.kind == "source"]
|
||||||
|
if not sources or len(sources) != len(saved.nodes):
|
||||||
|
raise ValueError("Automático starts from a pipeline that holds only its sources")
|
||||||
|
d = Draft(pipeline_id, sources)
|
||||||
|
for source in sources:
|
||||||
|
nodes.run_source(pipeline_id, source)
|
||||||
|
rows = list(nodes.rows(pipeline_id, source.id))
|
||||||
|
log(f"{source.id}: {len(rows)} rows")
|
||||||
|
found = file_columns(rows)
|
||||||
|
for column in found:
|
||||||
|
read = d.add(Read(id=d.id(f"texto_{source.id}"), label="Texto de cada documento",
|
||||||
|
inputs=[source.id], column=column)) # fmt: skip
|
||||||
|
graph.run_read(pipeline_id, read)
|
||||||
|
documents.draft(d, read, list(nodes.rows(pipeline_id, read.id)), log)
|
||||||
|
if not found:
|
||||||
|
tables.draft(d, source, rows, log)
|
||||||
|
return d.finish()
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
"""Documents (a column of files, read to text): grouped by layout, each layout named by the
|
||||||
|
model with the study it reports and a phrase that marks it (a route), and read for that
|
||||||
|
study (joined to the documents it answers, if it needs them: joins) and for whom it is
|
||||||
|
about (two extract nodes, with patterns for when no model answers). What no layout claims
|
||||||
|
goes to the unrecognised route, for a reviewer."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
from sklearn.cluster import AgglomerativeClustering
|
||||||
|
from sklearn.feature_extraction.text import CountVectorizer
|
||||||
|
|
||||||
|
from core.drafting import LAYOUT, layout_schema, studies_text
|
||||||
|
from core.pipeline import ENTITY_TITLES, Condition, Extract, Join, Read, Route, ground
|
||||||
|
from models import graph
|
||||||
|
from models.draft import fields, joins
|
||||||
|
from models.draft.joins import Kind
|
||||||
|
from persistance import llm
|
||||||
|
|
||||||
|
SAMPLE = 300 # documents grouped by layout at most
|
||||||
|
PER_LAYOUT = 3 # documents of a layout the model reads
|
||||||
|
DISTANCE = 0.5 # cosine distance under which two documents share a layout
|
||||||
|
COVERED = 0.9 # share of a layout's documents its marker must be found in
|
||||||
|
WORDS = r"(?u)\b[^\W\d_]{3,}\b" # words, never numbers: a layout, not its values
|
||||||
|
LINE = re.compile(r"^(?=.*[^\W\d_]{4})[^\d]{8,}$") # a printed label: words, no values
|
||||||
|
|
||||||
|
|
||||||
|
def layouts(texts: list[str]) -> list[int]:
|
||||||
|
"""A layout number per document: documents that print mostly the same words (a form's
|
||||||
|
labels) share one. Words seen in a single document (a name) don't count."""
|
||||||
|
if len(texts) < 2:
|
||||||
|
return [0] * len(texts)
|
||||||
|
try:
|
||||||
|
words = CountVectorizer(token_pattern=WORDS, binary=True, min_df=2).fit_transform(texts)
|
||||||
|
except ValueError: # no word in two documents: nothing to tell them apart by
|
||||||
|
return [0] * len(texts)
|
||||||
|
found = [-1] * len(texts)
|
||||||
|
worded = [i for i in range(len(texts)) if words[i].nnz]
|
||||||
|
if len(worded) < 2:
|
||||||
|
return [0 if i in worded else -1 for i in range(len(texts))]
|
||||||
|
groups = AgglomerativeClustering(
|
||||||
|
n_clusters=None, metric="cosine", linkage="average", distance_threshold=DISTANCE
|
||||||
|
).fit_predict(words[worded].toarray())
|
||||||
|
for i, group in zip(worded, groups, strict=True):
|
||||||
|
found[i] = int(group)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _spread(items: list, n: int) -> list:
|
||||||
|
"""`n` items from first to last."""
|
||||||
|
if len(items) <= n:
|
||||||
|
return items
|
||||||
|
return [items[round(i * (len(items) - 1) / (n - 1))] for i in range(n)]
|
||||||
|
|
||||||
|
|
||||||
|
def _marks(marker: str, text: str) -> bool:
|
||||||
|
"""As the route will test it (core.pipeline.matches, `contains`)."""
|
||||||
|
return marker.casefold() in text.casefold()
|
||||||
|
|
||||||
|
|
||||||
|
def _holds(marker: str, members: list[dict], others: list[dict]) -> bool:
|
||||||
|
"""A marker found in nearly all of a layout's documents and in no other's."""
|
||||||
|
if len(marker) < 4:
|
||||||
|
return False
|
||||||
|
covered = sum(_marks(marker, r["text"]) for r in members) / len(members)
|
||||||
|
return covered >= COVERED and not any(_marks(marker, r["text"]) for r in others)
|
||||||
|
|
||||||
|
|
||||||
|
def printed_line(members: list[dict], others: list[dict]) -> str | None:
|
||||||
|
"""The wordiest line printed in nearly all of a layout's documents and in no other's
|
||||||
|
(a form's label): the marker when the model's isn't (a title the printer overstrikes
|
||||||
|
reads "DDDDEEEE" in the text layer, so the title the model sees is not in the text)."""
|
||||||
|
counts = Counter(
|
||||||
|
line for r in members for line in {x.strip() for x in r["text"].splitlines()}
|
||||||
|
if LINE.match(line)
|
||||||
|
) # fmt: skip
|
||||||
|
candidates = [line for line, n in counts.items() if n / len(members) >= COVERED]
|
||||||
|
readable = lambda line: (len(re.findall(WORDS, line)), len(line)) # noqa: E731
|
||||||
|
for line in sorted(candidates, key=readable, reverse=True):
|
||||||
|
if _holds(line, members, others):
|
||||||
|
return line
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def draft(d, read: Read, rows: list[dict], log) -> None:
|
||||||
|
"""Routes, extracts (and joins) and the unrecognised route for one read node's
|
||||||
|
documents."""
|
||||||
|
documents = sorted((r for r in rows if r.get("text")), key=lambda r: r["_record"])
|
||||||
|
sample = _spread(documents, SAMPLE)
|
||||||
|
groups: dict[int, list[dict]] = {}
|
||||||
|
for row, group in zip(sample, layouts([r["text"] for r in sample]), strict=True):
|
||||||
|
if group >= 0:
|
||||||
|
groups.setdefault(group, []).append(row)
|
||||||
|
answers = []
|
||||||
|
for members in groups.values():
|
||||||
|
text = "\n\n---\n\n".join(r["text"] for r in _spread(members, PER_LAYOUT))
|
||||||
|
answers.append((llm.ask(LAYOUT.format(studies=studies_text()), text, layout_schema()),
|
||||||
|
members)) # fmt: skip
|
||||||
|
named = [(a, m) for a, m in answers if a["entity"] != "none"]
|
||||||
|
found: dict[tuple[str, str], Kind] = {}
|
||||||
|
for answer, members in named:
|
||||||
|
entity, marker = answer["entity"], " ".join(answer["marker"].split())
|
||||||
|
others = [r for a, m in named if a["entity"] != entity for r in m]
|
||||||
|
if not _holds(marker, members, others):
|
||||||
|
rest = [r for _, m in answers if m is not members for r in m]
|
||||||
|
marker = printed_line(members, rest)
|
||||||
|
log(f"layout of {len(members)}: {entity} «{marker}»")
|
||||||
|
if marker is None:
|
||||||
|
continue
|
||||||
|
kind = found.setdefault((entity, marker.casefold()),
|
||||||
|
Kind(entity, answer["label"], marker, [])) # fmt: skip
|
||||||
|
kind.members.extend(members)
|
||||||
|
kinds = list(found.values())
|
||||||
|
labels = Counter(k.label.casefold() for k in kinds)
|
||||||
|
for kind in kinds: # two layouts the model names alike: each by what marks it
|
||||||
|
if labels[kind.label.casefold()] > 1:
|
||||||
|
kind.label = f"{kind.label} · {kind.marker[:40]}{'…' if len(kind.marker) > 40 else ''}"
|
||||||
|
for kind in kinds:
|
||||||
|
marked = Condition(column="text", op="contains", value=kind.marker)
|
||||||
|
kind.route = d.add(Route(id=d.id(kind.label), label=kind.label, inputs=[read.id],
|
||||||
|
when=[marked])) # fmt: skip
|
||||||
|
kind.everyone = [r for r in documents if _marks(kind.marker, r["text"])]
|
||||||
|
for kind in kinds:
|
||||||
|
d.studies.setdefault(kind.entity, []).append(study(d, kind, kinds, log))
|
||||||
|
shown = [(r["text"], r) for r in _spread(kind.members, PER_LAYOUT)]
|
||||||
|
texts = [r["text"] for r in kind.everyone]
|
||||||
|
d.identity.append(extract(d, kind.route, kind.route.id, "identity", "text",
|
||||||
|
reading("identity", shown), texts)) # fmt: skip
|
||||||
|
d.add(Route(id=d.id("no_reconocidos"), label="Documentos no reconocidos",
|
||||||
|
inputs=[read.id], otherwise=True)) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def study(d, kind: Kind, kinds: list[Kind], log) -> str:
|
||||||
|
"""The extract node of a kind's study; on a join with the kind that pairs with it when,
|
||||||
|
reading both, the model takes a field the study requires from the other document (an
|
||||||
|
outsourced report's sample date is the order's, not the report's own date)."""
|
||||||
|
shown = _spread(kind.members, PER_LAYOUT)
|
||||||
|
read = reading(kind.entity, [(r["text"], r) for r in shown])
|
||||||
|
texts = [r["text"] for r in kind.everyone]
|
||||||
|
if found := joins.partner(kind, kinds):
|
||||||
|
other, column = found
|
||||||
|
node = Join(
|
||||||
|
id=d.id(f"{kind.route.id}_con_{other.route.id}"),
|
||||||
|
label=f"{kind.label} con {other.label}",
|
||||||
|
inputs=[kind.route.id, other.route.id],
|
||||||
|
on=[(column, column)],
|
||||||
|
how="left",
|
||||||
|
)
|
||||||
|
pairs = joins.joined(node, shown, other)
|
||||||
|
again = reading(kind.entity, pairs)
|
||||||
|
if taken := joins.taken(kind.entity, again, [r for _, r in pairs], other):
|
||||||
|
log(f"{kind.label}: read with {other.label} (same {column}): {taken} is in it")
|
||||||
|
d.add(node)
|
||||||
|
texts = [t for t, _ in joins.joined(node, kind.everyone, other)]
|
||||||
|
return extract(d, node, kind.route.id, kind.entity, joins.text_columns(other),
|
||||||
|
again, texts) # fmt: skip
|
||||||
|
log(f"{kind.label}: pairs with {other.label} (same {column}), needs nothing of it")
|
||||||
|
return extract(d, kind.route, kind.route.id, kind.entity, "text", read, texts)
|
||||||
|
|
||||||
|
|
||||||
|
def reading(entity: str, shown: list[tuple[str, dict]]) -> list[tuple[str, dict, dict]]:
|
||||||
|
"""What the model reads of `entity` in each text, only what the text says: (text,
|
||||||
|
values, the text each was read from)."""
|
||||||
|
out = []
|
||||||
|
for text, row in shown:
|
||||||
|
answered = ground(graph.answer(entity, text, "", graph.images(row)), text)
|
||||||
|
values, quotes, _ = answered[0] if answered else ({}, {}, [])
|
||||||
|
kept = {f: v for f, v in values.items() if v is not None}
|
||||||
|
out.append((text, kept, {f: quotes[f] for f in kept}))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def extract(d, source, name: str, entity: str, column, read, texts: list[str]) -> str:
|
||||||
|
"""An extract node of `entity` on `source`'s rows: the model's reading of a few of them
|
||||||
|
gives each field's pattern (and the site's codes), kept if it checks out."""
|
||||||
|
patterns, formats = fields.rules(entity, [(t, v) for t, v, _ in read], d.codes)
|
||||||
|
for field, pattern in patterns.items():
|
||||||
|
if fields.coded(entity, field):
|
||||||
|
raws = set()
|
||||||
|
for text in texts:
|
||||||
|
if found := re.search(pattern, text, re.IGNORECASE):
|
||||||
|
raws.add(" ".join(found.group(1).split()))
|
||||||
|
d.codes.ask(entity, field, raws)
|
||||||
|
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
||||||
|
node = Extract(id=d.id(f"{entity}_{name}"), label=f"{title} ({source.label})",
|
||||||
|
inputs=[source.id], column=column, entity=entity, method="auto",
|
||||||
|
patterns=patterns, formats=formats,
|
||||||
|
concept_map=d.codes.for_node(entity, patterns)) # fmt: skip
|
||||||
|
return d.add(node).id
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
"""Where each field is written, checked against the documents: the model proposes a pattern
|
||||||
|
per field from a few documents and the values it read there; a pattern is kept only when
|
||||||
|
it captures those very values (through its date format and the site's codes). And the
|
||||||
|
site's codes in platform terms, gathered into one ConceptMap."""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||||
|
|
||||||
|
from core import catalog, concept_map
|
||||||
|
from core.drafting import CODES, PATTERNS, codes_schema, is_date, patterns_schema
|
||||||
|
from core.pipeline import Extract, convert
|
||||||
|
from core.schema import ENTITIES
|
||||||
|
from persistance import llm
|
||||||
|
|
||||||
|
DATE_FORMATS = ("%d/%m/%Y", "%Y-%m-%d", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d", "%m/%d/%Y")
|
||||||
|
MANY_CODES = 200 # distinct values of a coded column asked about at most
|
||||||
|
|
||||||
|
|
||||||
|
def _plain(value) -> str:
|
||||||
|
return " ".join(str(value).split()).casefold()
|
||||||
|
|
||||||
|
|
||||||
|
def _same(got, want) -> bool:
|
||||||
|
"""A captured value, converted, is the value the model read (dates, numbers, text)."""
|
||||||
|
got = got.isoformat() if hasattr(got, "isoformat") else got
|
||||||
|
try:
|
||||||
|
return float(got) == float(want)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return _plain(got) == _plain(want)
|
||||||
|
|
||||||
|
|
||||||
|
def _code(value) -> str:
|
||||||
|
"""A model's value as a code: booleans as the platform's yes/no codes."""
|
||||||
|
return str(value).lower() if isinstance(value, bool) else str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def target(entity: str, field: str) -> tuple[str | None, set[str] | None]:
|
||||||
|
"""The system a field of this study takes codes from (None: not coded) and its allowed
|
||||||
|
codes (None: any of the system's)."""
|
||||||
|
if entity == "identity":
|
||||||
|
return (concept_map.GENDER, {"female", "male"}) if field == "sex" else (None, set())
|
||||||
|
found = catalog.studies()[entity].fields[field]
|
||||||
|
if found.type == "boolean":
|
||||||
|
return concept_map.BOOLEAN, {"true", "false"}
|
||||||
|
if found.type == "code":
|
||||||
|
return catalog.systems()[found.system].url, set(found.codes) or None
|
||||||
|
return None, set()
|
||||||
|
|
||||||
|
|
||||||
|
def coded(entity: str, field: str) -> bool:
|
||||||
|
return target(entity, field)[0] is not None
|
||||||
|
|
||||||
|
|
||||||
|
class Codes:
|
||||||
|
"""The site's codes found so far: (study, field) -> site value (case ignored) ->
|
||||||
|
platform code."""
|
||||||
|
|
||||||
|
def __init__(self, map_id: str):
|
||||||
|
self.map_id, self.found = map_id, {}
|
||||||
|
|
||||||
|
def known(self, entity: str, field: str, raw: str) -> bool:
|
||||||
|
allowed = target(entity, field)[1]
|
||||||
|
mapped = self.found.get((entity, field), {})
|
||||||
|
return raw.casefold() in mapped or (allowed is not None and raw in allowed)
|
||||||
|
|
||||||
|
def add(self, entity: str, field: str, raw: str, code: str) -> None:
|
||||||
|
if not raw.strip():
|
||||||
|
return # nothing written is no code
|
||||||
|
self.found.setdefault((entity, field), {})[raw.casefold()] = code
|
||||||
|
|
||||||
|
def table(self) -> dict[tuple[str, str], dict[str, str]]:
|
||||||
|
return self.found
|
||||||
|
|
||||||
|
def ask(self, entity: str, field: str, raws: set[str]) -> None:
|
||||||
|
"""What the platform code is of each value the site writes for `field` that isn't
|
||||||
|
one already."""
|
||||||
|
new = sorted(r for r in raws if r and not self.known(entity, field, r))[:MANY_CODES]
|
||||||
|
if not new:
|
||||||
|
return
|
||||||
|
allowed = target(entity, field)[1]
|
||||||
|
title = ENTITIES[entity].model_fields[field].title or field
|
||||||
|
system = CODES.format(title=title, codes=", ".join(sorted(allowed)) if allowed else "any")
|
||||||
|
answer = llm.ask(system, "\n".join(new), codes_schema(new, sorted(allowed or ())))
|
||||||
|
for item in answer["codes"]:
|
||||||
|
if item["code"] is not None and (allowed is None or item["code"] in allowed):
|
||||||
|
self.add(entity, field, item["raw"], item["code"])
|
||||||
|
|
||||||
|
def for_node(self, entity: str, fields) -> str | None:
|
||||||
|
return self.map_id if any((entity, f) in self.found for f in fields) else None
|
||||||
|
|
||||||
|
def concept_map(self) -> ConceptMap | None:
|
||||||
|
"""One group per platform system the codes go to; None when there are none."""
|
||||||
|
groups: dict[str, list] = {}
|
||||||
|
for (entity, field), codes in self.found.items():
|
||||||
|
system = target(entity, field)[0]
|
||||||
|
for raw, code in sorted(codes.items()):
|
||||||
|
element = {"code": raw, "target": [{"code": code, "equivalence": "equivalent"}]}
|
||||||
|
if element not in groups.setdefault(system, []):
|
||||||
|
groups[system].append(element)
|
||||||
|
if not groups:
|
||||||
|
return None
|
||||||
|
found = ConceptMap.model_validate({
|
||||||
|
"resourceType": "ConceptMap", "status": "active", "id": self.map_id.replace("_", "-"),
|
||||||
|
"title": f"{self.map_id}: los códigos del sitio, como los leyó Automático",
|
||||||
|
"group": [{"source": f"urn:isssteleon:site:{self.map_id}", "target": t, "element": e}
|
||||||
|
for t, e in groups.items()],
|
||||||
|
}) # fmt: skip
|
||||||
|
if problems := concept_map.problems(found):
|
||||||
|
raise ValueError(f"drafted codes refused: {problems}")
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def rules(entity: str, read: list[tuple[str, dict]], codes: Codes) -> tuple[dict, dict]:
|
||||||
|
"""Patterns and date formats for the fields the model read in these documents (text,
|
||||||
|
values): one per field, kept only if it captures every value read."""
|
||||||
|
fields = sorted({f for _, values in read for f in values})
|
||||||
|
if not fields:
|
||||||
|
return {}, {}
|
||||||
|
shown = "\n\n---\n\n".join(
|
||||||
|
f"{text}\n\nVALUES: " + "; ".join(f"{f} = {v}" for f, v in values.items())
|
||||||
|
for text, values in read
|
||||||
|
)
|
||||||
|
proposed = llm.ask(PATTERNS, shown, patterns_schema(fields))
|
||||||
|
patterns, formats = {}, {}
|
||||||
|
for field in fields:
|
||||||
|
rule = proposed.get(field) or {}
|
||||||
|
fmt = rule.get("format") if is_date(entity, field) else None
|
||||||
|
if checks(entity, field, rule.get("pattern") or "", fmt, read, codes):
|
||||||
|
patterns[field] = rule["pattern"]
|
||||||
|
if fmt:
|
||||||
|
formats[field] = fmt
|
||||||
|
return patterns, formats
|
||||||
|
|
||||||
|
|
||||||
|
def checks(entity, field, pattern, fmt, read, codes: Codes) -> bool:
|
||||||
|
try:
|
||||||
|
if re.compile(pattern, re.IGNORECASE).groups != 1:
|
||||||
|
return False
|
||||||
|
except re.error:
|
||||||
|
return False
|
||||||
|
probe = Extract(id="probe", column="text", entity=entity, formats={field: fmt} if fmt else {})
|
||||||
|
pairs = {}
|
||||||
|
for text, values in read:
|
||||||
|
if field not in values:
|
||||||
|
continue
|
||||||
|
found = re.search(pattern, text, re.IGNORECASE)
|
||||||
|
if not found or not (found.group(1) or "").strip():
|
||||||
|
return False # where the model read a value, the pattern takes text
|
||||||
|
raw, want = " ".join(found.group(1).split()), values[field]
|
||||||
|
if coded(entity, field):
|
||||||
|
pairs.setdefault(raw.casefold(), set()).add(_code(want))
|
||||||
|
elif not _same(convert(probe, field, raw, {}), want):
|
||||||
|
return False
|
||||||
|
if any(len(v) > 1 for v in pairs.values()):
|
||||||
|
return False # one written value, two meanings: the pattern takes the wrong text
|
||||||
|
for raw, (code,) in pairs.items():
|
||||||
|
if raw != code.casefold():
|
||||||
|
codes.add(entity, field, raw, code)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def date_format(values: list) -> str | None:
|
||||||
|
"""The strptime format every written date of a column parses with (None: they are
|
||||||
|
dates already, or none fits)."""
|
||||||
|
written = [v.strip() for v in values if isinstance(v, str) and v.strip()]
|
||||||
|
for fmt in DATE_FORMATS:
|
||||||
|
if written and all(_parses(v, fmt) for v in written):
|
||||||
|
return fmt
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _parses(value: str, fmt: str) -> bool:
|
||||||
|
try:
|
||||||
|
datetime.strptime(value, fmt)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""A kind of document that leaves a date its study requires to another (an outsourced
|
||||||
|
lab's report leaves the sample's date to the order it answers) is read together with
|
||||||
|
it: the kind of the same source a column both carry pairs each of its documents with, one
|
||||||
|
to one. The pairing is kept only if the model, reading both, takes such a field from the
|
||||||
|
other document."""
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
from core.pipeline import Join, Route, grounded, join
|
||||||
|
from core.schema import ENTITIES
|
||||||
|
from models.graph import FILE, READ_COLUMNS
|
||||||
|
|
||||||
|
PAIRED = 0.5 # share of a kind's documents that must find exactly one partner
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Kind:
|
||||||
|
"""Documents of one layout: the study they report, their route, all of them."""
|
||||||
|
|
||||||
|
entity: str
|
||||||
|
label: str
|
||||||
|
marker: str
|
||||||
|
members: list[dict] # those sampled
|
||||||
|
everyone: list[dict] = field(default_factory=list)
|
||||||
|
route: Route | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def required(entity: str) -> set[str]:
|
||||||
|
return {f for f, info in ENTITIES[entity].model_fields.items() if info.is_required()}
|
||||||
|
|
||||||
|
|
||||||
|
def _keys(row: dict) -> dict:
|
||||||
|
"""The columns of a row that may pair it: the source's own, never its text or file."""
|
||||||
|
return {
|
||||||
|
c: v
|
||||||
|
for c, v in row.items()
|
||||||
|
if not c.startswith("_") and c not in READ_COLUMNS and c != FILE
|
||||||
|
and isinstance(v, str | int) and v != ""
|
||||||
|
} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def partner(kind: Kind, kinds: list[Kind]) -> tuple[Kind, str] | None:
|
||||||
|
"""The other kind and the column that pair most of this kind's documents with exactly
|
||||||
|
one document each (never with themselves); None if none pairs half."""
|
||||||
|
best = None
|
||||||
|
for other in kinds:
|
||||||
|
if other is kind or not kind.everyone:
|
||||||
|
continue
|
||||||
|
index: dict[tuple[str, object], set] = {}
|
||||||
|
for row in other.everyone:
|
||||||
|
for c, v in _keys(row).items():
|
||||||
|
index.setdefault((c, v), set()).add(row["_record"])
|
||||||
|
paired: dict[str, int] = {}
|
||||||
|
for row in kind.everyone:
|
||||||
|
for c, v in _keys(row).items():
|
||||||
|
if len(index.get((c, v), set()) - {row["_record"]}) == 1:
|
||||||
|
paired[c] = paired.get(c, 0) + 1
|
||||||
|
for c, n in paired.items():
|
||||||
|
share = n / len(kind.everyone)
|
||||||
|
if share >= PAIRED and (best is None or share > best[0]):
|
||||||
|
best = (share, other, c)
|
||||||
|
return (best[1], best[2]) if best else None
|
||||||
|
|
||||||
|
|
||||||
|
def joined(node: Join, rows: list[dict], other: Kind) -> list[tuple[str, dict]]:
|
||||||
|
"""Each row with its partner's text before its own, as the extract node will read it."""
|
||||||
|
columns = text_columns(other)
|
||||||
|
return [("\n".join(str(r[c]) for c in columns if r.get(c)), r)
|
||||||
|
for r in join(node, rows, other.everyone, other.route.id)] # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def taken(entity: str, read, rows: list[dict], other: Kind) -> set[str]:
|
||||||
|
"""Fields the study requires that the model, reading a document with its partner, took
|
||||||
|
from the partner's text (not its own) in most of the documents that have one."""
|
||||||
|
theirs_column = text_columns(other)[0]
|
||||||
|
partnered = [(quotes, row) for (_, _, quotes), row in zip(read, rows, strict=True)
|
||||||
|
if row.get(theirs_column)] # fmt: skip
|
||||||
|
found = set()
|
||||||
|
for name in required(entity):
|
||||||
|
theirs = sum(
|
||||||
|
name in quotes and grounded(quotes[name], row[theirs_column])
|
||||||
|
and not grounded(quotes[name], row["text"])
|
||||||
|
for quotes, row in partnered
|
||||||
|
) # fmt: skip
|
||||||
|
if partnered and theirs * 2 > len(partnered):
|
||||||
|
found.add(name)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def text_columns(other: Kind) -> list[str]:
|
||||||
|
return [f"text__{other.route.id}", "text"]
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""A table (columns, no files): the model says which column holds each fact about whom a
|
||||||
|
row is about and each field of the studies its rows report; dates get the format all of
|
||||||
|
a column's values parse with, and coded columns their values in platform terms."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from core.drafting import TABLE, is_date, studies_text, table_schema
|
||||||
|
from core.pipeline import ENTITY_TITLES, Map, Source
|
||||||
|
from core.schema import ENTITIES
|
||||||
|
from models.draft import fields
|
||||||
|
from persistance import llm
|
||||||
|
|
||||||
|
SHOWN = 15 # rows the model sees
|
||||||
|
SCANNED = 2000 # rows whose values give the date formats and the codes
|
||||||
|
LONG = 80 # characters of a value shown
|
||||||
|
|
||||||
|
|
||||||
|
def _shown(value):
|
||||||
|
text = value if isinstance(value, str) else json.dumps(value, default=str)
|
||||||
|
return text[:LONG]
|
||||||
|
|
||||||
|
|
||||||
|
def draft(d, source: Source, rows: list[dict], log) -> None:
|
||||||
|
"""One map node for identity and one per study the table reports."""
|
||||||
|
columns = sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")})
|
||||||
|
if not columns:
|
||||||
|
return
|
||||||
|
shown = "\n".join(json.dumps({c: _shown(r.get(c)) for c in columns}, ensure_ascii=False)
|
||||||
|
for r in rows[:SHOWN]) # fmt: skip
|
||||||
|
answer = llm.ask(TABLE.format(studies=studies_text()), f"{columns}\n{shown}",
|
||||||
|
table_schema(columns)) # fmt: skip
|
||||||
|
wanted = [("identity", answer["identity"])]
|
||||||
|
wanted += [(s["entity"], s["fields"]) for s in answer["studies"]]
|
||||||
|
for entity, held in wanted:
|
||||||
|
mapped = {h["field"]: h["column"] for h in held
|
||||||
|
if h["field"] in ENTITIES[entity].model_fields} # fmt: skip
|
||||||
|
if not mapped:
|
||||||
|
continue
|
||||||
|
node = mapping(d, source, entity, mapped, rows[:SCANNED])
|
||||||
|
(d.identity if entity == "identity" else d.studies.setdefault(entity, [])).append(node)
|
||||||
|
log(f"{source.id}: {entity} from {sorted(mapped.values())}")
|
||||||
|
|
||||||
|
|
||||||
|
def mapping(d, source: Source, entity: str, mapped: dict[str, str], rows: list[dict]) -> str:
|
||||||
|
formats = {}
|
||||||
|
for field, column in mapped.items():
|
||||||
|
values = [r.get(column) for r in rows]
|
||||||
|
if is_date(entity, field) and (fmt := fields.date_format(values)):
|
||||||
|
formats[field] = fmt
|
||||||
|
elif fields.coded(entity, field):
|
||||||
|
d.codes.ask(entity, field, {str(v).strip() for v in values if v not in (None, "")})
|
||||||
|
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
||||||
|
node = Map(id=d.id(f"{source.id}_{entity}"), label=f"{title} ({source.label or source.id})",
|
||||||
|
inputs=[source.id], fields=mapped, formats=formats,
|
||||||
|
concept_map=d.codes.for_node(entity, mapped)) # fmt: skip
|
||||||
|
return d.add(node).id
|
||||||
@@ -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
|
||||||
+39
-40
@@ -1,10 +1,8 @@
|
|||||||
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
||||||
places what the targets staged into silver."""
|
places what the targets staged into silver."""
|
||||||
|
|
||||||
import hashlib
|
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import os
|
|
||||||
import unicodedata
|
import unicodedata
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from concurrent.futures import ProcessPoolExecutor
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
@@ -17,12 +15,12 @@ import pdfplumber
|
|||||||
import pikepdf
|
import pikepdf
|
||||||
import splink.comparison_library as cl
|
import splink.comparison_library as cl
|
||||||
from markitdown import MarkItDown
|
from markitdown import MarkItDown
|
||||||
from openai import OpenAI, OpenAIError
|
|
||||||
from splink import Linker, SettingsCreator, block_on
|
from splink import Linker, SettingsCreator, block_on
|
||||||
from splink.backends.duckdb import DuckDBAPI
|
from splink.backends.duckdb import DuckDBAPI
|
||||||
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||||
|
|
||||||
from core import catalog, concept_map, fhir_in
|
from core import catalog, concept_map, fhir_in
|
||||||
|
from core.drafting import extract_prompt
|
||||||
from core.pipeline import (
|
from core.pipeline import (
|
||||||
HELD,
|
HELD,
|
||||||
IDENTIFIERS,
|
IDENTIFIERS,
|
||||||
@@ -45,16 +43,19 @@ from core.pipeline import (
|
|||||||
matches,
|
matches,
|
||||||
validate,
|
validate,
|
||||||
)
|
)
|
||||||
from persistance import config_log, files, nodes, silver
|
from models import suggest
|
||||||
|
from persistance import config_log, files, llm, nodes, silver
|
||||||
|
|
||||||
MIN_WORDS = 5 # fewer than this from a PDF page 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_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
|
||||||
|
FILE = "_file" # the read file's key (persistance.files): its pages, for a model that sees
|
||||||
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
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"},
|
||||||
"error": {"data_type": "text", "nullable": True},
|
"error": {"data_type": "text", "nullable": True},
|
||||||
"format": {"data_type": "text", "nullable": True},
|
"format": {"data_type": "text", "nullable": True},
|
||||||
}
|
}
|
||||||
|
ROW_COLUMNS = {**READ_COLUMNS, FILE: {"data_type": "text", "nullable": True}}
|
||||||
|
|
||||||
|
|
||||||
def file_format(content: bytes) -> str:
|
def file_format(content: bytes) -> str:
|
||||||
@@ -157,9 +158,10 @@ def run_read(p: str, node: Read):
|
|||||||
READ_COLUMNS) # fmt: skip
|
READ_COLUMNS) # fmt: skip
|
||||||
found |= read
|
found |= read
|
||||||
for row in rows:
|
for row in rows:
|
||||||
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
row[FILE] = row.pop("key")
|
||||||
|
result = found.get(row[FILE], {"text": None, "ocr": False, "error": "empty"})
|
||||||
row |= {k: result[k] for k in READ_COLUMNS}
|
row |= {k: result[k] for k in READ_COLUMNS}
|
||||||
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
return nodes.write(p, node.id, rows, ROW_COLUMNS)
|
||||||
|
|
||||||
|
|
||||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||||
@@ -199,51 +201,40 @@ def run_join(p: str, node: Join):
|
|||||||
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
||||||
|
|
||||||
|
|
||||||
@cache
|
def page_images(content: bytes, pages: int = 2) -> list[bytes]:
|
||||||
def _llm() -> tuple[OpenAI, str] | None:
|
"""The first pages of a PDF as PNG pictures, for a model that reads images (a scan's
|
||||||
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
|
OCR text misses what the picture still shows)."""
|
||||||
if not (url := os.environ.get("LLM_URL")):
|
out = []
|
||||||
return None
|
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
||||||
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
|
for page in pdf.pages[:pages]:
|
||||||
try:
|
picture = io.BytesIO()
|
||||||
client.models.list()
|
page.to_image(resolution=110).original.save(picture, format="PNG")
|
||||||
except OpenAIError:
|
out.append(picture.getvalue())
|
||||||
return None
|
return out
|
||||||
return client, os.environ["LLM_MODEL"]
|
|
||||||
|
|
||||||
|
|
||||||
PROMPT = (
|
def images(row: dict) -> list[bytes]:
|
||||||
"Extract every {entity} record stated in the document. For each field give its value "
|
"""A scanned document's pages as pictures, when the model reads them."""
|
||||||
"in the schema's terms and `quote`: the exact text of the document it was read from, "
|
if not (row.get("ocr") and row.get(FILE) and llm.vision()):
|
||||||
"copied character by character. Leave out fields the document does not state.{hints}"
|
return []
|
||||||
)
|
content = files.content(row[FILE])
|
||||||
|
return page_images(content) if content and file_format(content) == "pdf" else []
|
||||||
|
|
||||||
|
|
||||||
def _ask_llm(node: Extract, text: str) -> dict:
|
def answer(entity: str, text: str, hints: str = "", pictures: list[bytes] = ()) -> dict:
|
||||||
client, model = _llm()
|
"""The model's records of `entity` in `text`, each value with the text it was read
|
||||||
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
|
from (the same question for the same document is asked once)."""
|
||||||
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
|
return llm.ask(extract_prompt(entity, hints), text, answer_schema(entity), pictures)
|
||||||
if found := nodes.cached("llm_cache", {key}):
|
|
||||||
return json.loads(found[key]["answer"])
|
|
||||||
reply = client.chat.completions.create(
|
|
||||||
model=model, temperature=0, seed=7,
|
|
||||||
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
|
||||||
response_format={"type": "json_schema", "json_schema": {
|
|
||||||
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
|
|
||||||
) # fmt: skip
|
|
||||||
answer = reply.choices[0].message.content
|
|
||||||
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
|
||||||
return json.loads(answer)
|
|
||||||
|
|
||||||
|
|
||||||
def run_extract(p: str, node: Extract):
|
def run_extract(p: str, node: Extract):
|
||||||
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
|
use_llm = node.method == "llm" or (node.method == "auto" and llm.available())
|
||||||
codes = _codes(node, node.patterns)
|
codes = _codes(node, node.patterns)
|
||||||
out = []
|
out = []
|
||||||
for row in nodes.rows(p, node.inputs[0]):
|
for row in nodes.rows(p, node.inputs[0]):
|
||||||
text = node.text(row)
|
text = node.text(row)
|
||||||
if use_llm:
|
if use_llm:
|
||||||
found = ground(_ask_llm(node, text), text)
|
found = ground(answer(node.entity, text, node.hints, images(row)), text)
|
||||||
elif node.patterns:
|
elif node.patterns:
|
||||||
found = apply_patterns(node, text, codes)
|
found = apply_patterns(node, text, codes)
|
||||||
else:
|
else:
|
||||||
@@ -425,6 +416,9 @@ def run_link(p: str, node: Link):
|
|||||||
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
|
orphan = set(whole.unique_id[whole[facts].isna().all(axis=1)]) if facts else set()
|
||||||
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
|
# no birth date to tell her apart (a pathology scan: a name, misread or not, and a sex)
|
||||||
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
|
undated = set(whole.unique_id[whole["birth_date"].isna()]) if "birth_date" in fields else set()
|
||||||
|
# Answers are kept by record; a person is known by any of hers, whatever joined since.
|
||||||
|
whose = persons.set_index("unique_id")["cluster_id"].to_dict()
|
||||||
|
answered = {frozenset(whose.get(r, r) for r in e) for e in decided}
|
||||||
lone = set() # persons whose identifier is carried by one record only
|
lone = set() # persons whose identifier is carried by one record only
|
||||||
for f in ids:
|
for f in ids:
|
||||||
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
carried = persons.dropna(subset=[f]).groupby(["cluster_id", f]).size()
|
||||||
@@ -439,7 +433,7 @@ def run_link(p: str, node: Link):
|
|||||||
very same identifier on a record that says nothing else (a scan read only in part)."""
|
very same identifier on a record that says nothing else (a scan read only in part)."""
|
||||||
a, b = r.unique_id_l, r.unique_id_r
|
a, b = r.unique_id_l, r.unique_id_r
|
||||||
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
sides = [(getattr(r, f"{f}_l"), getattr(r, f"{f}_r")) for f in known]
|
||||||
if frozenset((a, b)) in decided or any(
|
if frozenset((a, b)) in answered or any(
|
||||||
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
pd.notna(x) and pd.notna(y) and x != y for x, y in sides
|
||||||
):
|
):
|
||||||
return None
|
return None
|
||||||
@@ -532,3 +526,8 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
|
|||||||
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
||||||
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
||||||
log(f"silver and gold, from {', '.join(entities)}")
|
log(f"silver and gold, from {', '.join(entities)}")
|
||||||
|
links = [n.id for n in pipeline.nodes if n.kind == "link"]
|
||||||
|
if links and llm.available(): # the model's reading beside what waits for reviewers
|
||||||
|
for link in links:
|
||||||
|
suggest.persons(pipeline_id, link)
|
||||||
|
log(f"suggestions for review: {', '.join(links)}")
|
||||||
|
|||||||
+7
-7
@@ -41,8 +41,12 @@ class Jobs:
|
|||||||
return f"{self.domain}_events"
|
return f"{self.domain}_events"
|
||||||
|
|
||||||
def routine(self) -> list[str]:
|
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 of them."""
|
||||||
return [n for n, s in self.models.items() if not getattr(s, "slow", False)]
|
return list(self.models)
|
||||||
|
|
||||||
|
def scored(self) -> list[str]:
|
||||||
|
"""The models a score run takes when none is named: all of them."""
|
||||||
|
return list(self.models)
|
||||||
|
|
||||||
def registered(self, name: str) -> str:
|
def registered(self, name: str) -> str:
|
||||||
return f"{self.domain}.{name}"
|
return f"{self.domain}.{name}"
|
||||||
@@ -51,9 +55,7 @@ class Jobs:
|
|||||||
"""A new registered version of the model, trained on its cohort's timelines up to
|
"""A new registered version of the model, trained on its cohort's timelines up to
|
||||||
`as_of` (default: today), with its metrics and its two generated reports."""
|
`as_of` (default: today), with its metrics and its two generated reports."""
|
||||||
spec, as_of = self.models[name], as_of or date.today()
|
spec, as_of = self.models[name], as_of or date.today()
|
||||||
if spec.cohort is None: # trained on reference data: it writes its own reports
|
if getattr(spec, "reports", False): # trained on its cohort, with its own reports
|
||||||
fitted, metrics, found = spec.train(None, as_of)
|
|
||||||
elif getattr(spec, "reports", False): # trained on its cohort, with its own reports
|
|
||||||
events = gold.timelines(self.events, spec.cohort, as_of)
|
events = gold.timelines(self.events, spec.cohort, as_of)
|
||||||
if events.empty:
|
if events.empty:
|
||||||
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
|
||||||
@@ -77,8 +79,6 @@ class Jobs:
|
|||||||
def score(self, name: str) -> int | None:
|
def score(self, name: str) -> int | None:
|
||||||
"""The champion's risks for today's members of the model's cohort, saved as its risk
|
"""The champion's risks for today's members of the model's cohort, saved as its risk
|
||||||
batch; None when the model has no champion yet."""
|
batch; None when the model has no champion yet."""
|
||||||
if self.models[name].cohort is None: # scores no patient
|
|
||||||
return None
|
|
||||||
found = registry.champion(self.registered(name))
|
found = registry.champion(self.registered(name))
|
||||||
if found is None:
|
if found is None:
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""The model's reading of what a link node leaves to reviewers, shown beside each case:
|
||||||
|
whether a person and a possible owner are one patient, and which record of a torn person
|
||||||
|
belongs to someone else, each with its reason. A suggestion decides nothing: reviewers
|
||||||
|
still answer every case (persistance.nodes)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from core.drafting import SAME_PERSON, TORN, same_person_schema, torn_schema
|
||||||
|
from core.pipeline import HELD, RECORD
|
||||||
|
from persistance import llm, nodes
|
||||||
|
|
||||||
|
PAIRS, TORN_PERSONS = "__suggestions", "__torn_suggestions"
|
||||||
|
|
||||||
|
|
||||||
|
def _side(row: dict, prefix: str) -> dict:
|
||||||
|
return {k.removeprefix(prefix): v for k, v in row.items()
|
||||||
|
if k.startswith(prefix) and v is not None} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def persons(pipeline_id: str, link: str) -> None:
|
||||||
|
"""Suggestions for the link node's queue (pairs) and its torn persons."""
|
||||||
|
pairs = []
|
||||||
|
for row in nodes.rows(pipeline_id, f"{link}__review"):
|
||||||
|
case = {"a": _side(row, "person_"), "b": _side(row, "candidate_"), "why": row["reason"]}
|
||||||
|
text = json.dumps(case, default=str, ensure_ascii=False)
|
||||||
|
answer = llm.ask(SAME_PERSON, text, same_person_schema())
|
||||||
|
pairs.append({"person": row["person"], "candidate": row["candidate"],
|
||||||
|
"same": answer["same"], "reason": answer["reason"]}) # fmt: skip
|
||||||
|
nodes.write(pipeline_id, f"{link}{PAIRS}", pairs)
|
||||||
|
torn: dict[str, list[dict]] = {}
|
||||||
|
for row in nodes.rows(pipeline_id, link):
|
||||||
|
if "disagree" in (row.get(HELD) or ""):
|
||||||
|
record = {k: v for k, v in row.items() if not k.startswith("_") and v is not None}
|
||||||
|
torn.setdefault(row["person_id"], []).append({**record, "id": row[RECORD]})
|
||||||
|
found = []
|
||||||
|
for person, records in torn.items():
|
||||||
|
text = json.dumps(records, default=str, ensure_ascii=False)
|
||||||
|
answer = llm.ask(TORN, text, torn_schema([r["id"] for r in records]))
|
||||||
|
found.append({"person": person, "record": answer["record"], "reason": answer["reason"]})
|
||||||
|
nodes.write(pipeline_id, f"{link}{TORN_PERSONS}", found)
|
||||||
@@ -9,6 +9,8 @@ deaths: lambda = shrink / (shrink + deaths). Covariates are categorical; a missi
|
|||||||
category of its own (UNKNOWN).
|
category of its own (UNKNOWN).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import warnings
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from itertools import pairwise
|
from itertools import pairwise
|
||||||
|
|
||||||
@@ -267,6 +269,8 @@ class Spec:
|
|||||||
# "in", value) on the members' covariates and `scenario_columns` (kept for them only).
|
# "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)
|
scenarios: dict[str, tuple[tuple[str, str, object], ...]] = field(default_factory=dict)
|
||||||
scenario_columns: tuple[str, ...] = ()
|
scenario_columns: tuple[str, ...] = ()
|
||||||
|
# Features that are treatments: their odds ratios are reported as associations, unclassified.
|
||||||
|
treatments: tuple[str, ...] = ()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def horizons(self) -> tuple[float, ...]:
|
def horizons(self) -> tuple[float, ...]:
|
||||||
@@ -503,4 +507,102 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
|
|||||||
"escenarios": scenarios,
|
"escenarios": scenarios,
|
||||||
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
|
"escenarios_sin_curvas": skipped, # fewer than MIN_SCENARIO_EVENTS deaths
|
||||||
"min_fallecidos_escenario": MIN_SCENARIO_EVENTS,
|
"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),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,6 +59,9 @@ class Jobs:
|
|||||||
def routine(self) -> list[str]:
|
def routine(self) -> list[str]:
|
||||||
return list(MODELS)
|
return list(MODELS)
|
||||||
|
|
||||||
|
def scored(self) -> list[str]:
|
||||||
|
return list(MODELS) # the curves, then the association on their scores
|
||||||
|
|
||||||
|
|
||||||
JOBS = Jobs()
|
JOBS = Jobs()
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ dependencies = [
|
|||||||
"dagster",
|
"dagster",
|
||||||
"dagster-webserver",
|
"dagster-webserver",
|
||||||
"mlflow-skinny",
|
"mlflow-skinny",
|
||||||
"openai>=3.59.0",
|
|
||||||
"splink>=5.0.0",
|
"splink>=5.0.0",
|
||||||
"duckdb>=2.0.1",
|
"duckdb>=2.0.1",
|
||||||
"markitdown[docx,xlsx]>=0.1.9",
|
"markitdown[docx,xlsx]>=0.1.9",
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
"""The two public cohorts the recurrence model is proved on, METABRIC and SCAN-B, each as a
|
||||||
|
`Cohort` from its dataset as the `cama_reference` pipeline loads it (every value as written,
|
||||||
|
column names as dlt names them, `line` the order the file is published in)."""
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from models.cama import recurrence
|
||||||
|
from models.cama.recurrence import site
|
||||||
|
from models.cama.recurrence.cohorts import (
|
||||||
|
AGE,
|
||||||
|
DAYS_PER_MONTH,
|
||||||
|
GRADES,
|
||||||
|
NODES,
|
||||||
|
SIZE,
|
||||||
|
Cohort,
|
||||||
|
_band,
|
||||||
|
_number,
|
||||||
|
_text,
|
||||||
|
collinear,
|
||||||
|
)
|
||||||
|
|
||||||
|
SOURCES = ("metabric", "scanb")
|
||||||
|
SAVED = "metabric"
|
||||||
|
N_BOOTSTRAP = {"metabric": 100, "scanb": 40, "site": 40}
|
||||||
|
LABELS = {"metabric": "METABRIC", "scanb": "SCAN-B"}
|
||||||
|
SAMPLING = {
|
||||||
|
"criterio": "pacientes con tiempo y estado de recaída; SCAN-B solo mujeres",
|
||||||
|
"origen": "METABRIC y SCAN-B (externas)",
|
||||||
|
}
|
||||||
|
SCENARIOS = {
|
||||||
|
"metabric": {
|
||||||
|
"RE+ · sin ganglios · tumor ≤20 mm (bajo riesgo)": {
|
||||||
|
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["0"],
|
||||||
|
"Tamano_tumor": ["<=20 mm"]},
|
||||||
|
"Ganglios 4+": {"Ganglios_positivos": ["4+"]},
|
||||||
|
"Tumor >50 mm": {"Tamano_tumor": [">50 mm"]},
|
||||||
|
"< 45 años": {"Edad": ["<45"]},
|
||||||
|
"≥ 75 años": {"Edad": ["75+"]},
|
||||||
|
"Basal (PAM50)": {"Subtipo_PAM50": ["Basal"]},
|
||||||
|
"HER2 (PAM50)": {"Subtipo_PAM50": ["Her2"]},
|
||||||
|
"Luminal B (PAM50)": {"Subtipo_PAM50": ["LumB"]},
|
||||||
|
"RE+ · 1-3 ganglios · cirugía conservadora": {
|
||||||
|
"Receptor_estrogeno": ["Positive"], "Ganglios_positivos": ["1-3"],
|
||||||
|
"Cirugia": ["BREAST CONSERVING"]},
|
||||||
|
"RE− · grado 3": {"Receptor_estrogeno": ["Negative"], "Grado_histologico": ["3"]},
|
||||||
|
},
|
||||||
|
"scanb": site.SCENARIOS,
|
||||||
|
} # fmt: skip
|
||||||
|
FIXED = {
|
||||||
|
"metabric": ["paciente", "tiempo_meses", "evento"],
|
||||||
|
"scanb": ["paciente", "tiempo_meses", "evento", "muerte_sin_recaida"],
|
||||||
|
}
|
||||||
|
TREATMENT = {
|
||||||
|
"metabric": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia"],
|
||||||
|
"scanb": ["Cirugia", "Quimioterapia", "Radioterapia", "Hormonoterapia", "AntiHER2"],
|
||||||
|
}
|
||||||
|
# Covariates taken as they come (our name: the dataset's column).
|
||||||
|
PASSTHROUGH = {
|
||||||
|
"metabric": {
|
||||||
|
"Receptor_estrogeno": "er_status", "Receptor_progesterona": "pr_status",
|
||||||
|
"HER2": "her2_status", "Subtipo_PAM50": "pam50_x_claudin_low_subtype",
|
||||||
|
"Tipo_histologico": "cancer_type_detailed", "Celularidad": "cellularity",
|
||||||
|
"Estado_menopausico": "inferred_menopausal_state",
|
||||||
|
"Cluster_integrativo": "integrative_cluster", "Lateralidad": "primary_tumor_laterality",
|
||||||
|
"Cirugia": "type_of_breast_surgery", "Quimioterapia": "chemotherapy",
|
||||||
|
"Radioterapia": "radio_therapy", "Hormonoterapia": "hormone_therapy",
|
||||||
|
},
|
||||||
|
"scanb": {
|
||||||
|
"Receptor_estrogeno": "er", "Receptor_progesterona": "pr", "HER2": "her2",
|
||||||
|
"Ki67": "ki67", "Subtipo_clinico": "clinical_subtype", "Tipo_histologico": "histology",
|
||||||
|
"Estado_menopausico": "menopause_status_bin", "Lateralidad": "laterality",
|
||||||
|
"Estadio_clinico": "tnm_clinical_stage", "Cirugia": "surgery_type",
|
||||||
|
"Quimioterapia": "chemotherapy", "Radioterapia": "radiation",
|
||||||
|
"Hormonoterapia": "endocrine", "AntiHER2": "anti_her2",
|
||||||
|
},
|
||||||
|
} # fmt: skip
|
||||||
|
SCANB_NODES = {"NodeNegative": "0", "SubMicroMet": "0", "1to3": "1-3", "4toX": "4+"}
|
||||||
|
SCANB_GRADES = {"Grade1": "1", "Grade2": "2", "Grade3": "3"}
|
||||||
|
|
||||||
|
|
||||||
|
def _in_order(rows: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
return rows.sort_values("line", kind="stable").reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _metabric(rows: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
d = _in_order(rows).dropna(subset=["relapse_free_status", "relapse_free_status_monthsx"])
|
||||||
|
d = d.reset_index(drop=True)
|
||||||
|
out = pd.DataFrame({"paciente": d["patient_id"]})
|
||||||
|
out["tiempo_meses"] = _number(d["relapse_free_status_monthsx"])
|
||||||
|
out["evento"] = d["relapse_free_status"].str.startswith("1").astype(int)
|
||||||
|
out["Edad"] = _band(_number(d["age_at_diagnosis"]), *AGE)
|
||||||
|
out["Tamano_tumor"] = _band(_number(d["tumor_size"]), *SIZE)
|
||||||
|
out["Ganglios_positivos"] = _band(_number(d["lymph_nodes_examined_positive"]), *NODES)
|
||||||
|
out["Grado_histologico"] = _text(d["neoplasm_histologic_grade"].map(GRADES))
|
||||||
|
# Mutational load in tertiles of this cohort; a value on a cut falls in the lower band.
|
||||||
|
load = _number(d["mutation_count"])
|
||||||
|
q1, q2 = load.quantile([1 / 3, 2 / 3]).to_numpy()
|
||||||
|
edges = [-1, q1 + 1e-9, q2 + 1e-9, 1e6]
|
||||||
|
out["Carga_mutacional"] = _band(load, edges, ["baja", "media", "alta"])
|
||||||
|
for name, column in PASSTHROUGH["metabric"].items():
|
||||||
|
out[name] = _text(d[column])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _scanb(rows: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
d = _in_order(rows)
|
||||||
|
d = d[d["gender"] == "F"].dropna(subset=["rfi_event", "rfi_days"]).reset_index(drop=True)
|
||||||
|
rfi, died = _number(d["rfi_event"]), _number(d["os_event"])
|
||||||
|
out = pd.DataFrame({"paciente": d["patient_name"]})
|
||||||
|
out["tiempo_meses"] = _number(d["rfi_days"]) / DAYS_PER_MONTH
|
||||||
|
out["evento"] = rfi.astype(int)
|
||||||
|
out["muerte_sin_recaida"] = ((died == 1) & (rfi == 0)).astype(int)
|
||||||
|
out["Edad"] = _band(_number(d["age_5year_bin"]) - 2, *AGE) # the 5-year bin's middle
|
||||||
|
out["Tamano_tumor"] = _band(_number(d["tumor_size_mm"]), *SIZE)
|
||||||
|
out["Ganglios_positivos"] = _text(d["node_met_spec"].map(SCANB_NODES))
|
||||||
|
out["Grado_histologico"] = _text(d["nhg"].map(SCANB_GRADES))
|
||||||
|
for name, column in PASSTHROUGH["scanb"].items():
|
||||||
|
out[name] = _text(d[column])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def prepare(source: str, raw: pd.DataFrame) -> Cohort:
|
||||||
|
full = {"metabric": _metabric, "scanb": _scanb}[source](raw)
|
||||||
|
fixed, treatment = FIXED[source], TREATMENT[source]
|
||||||
|
covariates = [c for c in full.columns if c not in fixed]
|
||||||
|
dropped = collinear(full, [c for c in covariates if c not in treatment])
|
||||||
|
kept = [c for c in covariates if c not in dropped]
|
||||||
|
return Cohort(source, full[fixed + kept], kept, [c for c in treatment if c in kept], dropped,
|
||||||
|
LABELS[source], SCENARIOS[source], SAMPLING) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def train(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple:
|
||||||
|
"""Both cohorts' models, validation, calculator and risk factors; METABRIC's is kept."""
|
||||||
|
found = {s: prepare(s, raws[s]) for s in SOURCES}
|
||||||
|
return recurrence.fit(found, SAVED, "metabric+scanb", N_BOOTSTRAP if bootstrap else {})
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""What Automático checks without asking the model: documents grouped by the words their
|
||||||
|
layout prints, a proposed pattern kept only when it captures what the model read, a
|
||||||
|
column's date format, and the site's codes as a ConceptMap the platform accepts."""
|
||||||
|
|
||||||
|
from core import concept_map
|
||||||
|
from core.drafting import codes_schema, layout_schema, table_schema
|
||||||
|
from models.draft import fields
|
||||||
|
from models.draft.documents import layouts
|
||||||
|
|
||||||
|
FORM = (
|
||||||
|
"SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: {date}\n"
|
||||||
|
"Calidad de la muestra: SATISFACTORIO\nResultado: {result}\nObservaciones: ninguna"
|
||||||
|
)
|
||||||
|
MAMMOGRAM = (
|
||||||
|
"REPORTE DE MASTOGRAFÍA BILATERAL\nPaciente: {name}\nFecha del estudio: {date}\n"
|
||||||
|
"Hallazgos: densidad mamaria tipo B, sin masas\nBI-RADS: 2"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_documents_of_one_layout_group_together_whoever_they_are_about():
|
||||||
|
texts = [
|
||||||
|
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
||||||
|
MAMMOGRAM.format(name="LUISA ORTIZ MENA", date="11/04/2025"),
|
||||||
|
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
||||||
|
MAMMOGRAM.format(name="MARTA SOLÍS GIL", date="01/07/2025"),
|
||||||
|
FORM.format(name="EVA RUIZ CANO", date="20/08/2025", result="ASC-US"),
|
||||||
|
]
|
||||||
|
found = layouts(texts)
|
||||||
|
assert found[0] == found[2] == found[4] != found[1] == found[3]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_pattern_is_kept_only_if_it_captures_the_values_read():
|
||||||
|
texts = [
|
||||||
|
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
||||||
|
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
||||||
|
]
|
||||||
|
read = [
|
||||||
|
(texts[0], {"sample_date": "2025-03-02", "result": "NILM"}),
|
||||||
|
(texts[1], {"sample_date": "2025-06-15", "result": "LSIL"}),
|
||||||
|
]
|
||||||
|
codes = fields.Codes("sitio")
|
||||||
|
entity = "cervical_cytology"
|
||||||
|
date = r"recepci[oó]n:\s*(\d{2}/\d{2}/\d{4})"
|
||||||
|
assert fields.checks(entity, "sample_date", date, "%d/%m/%Y", read, codes)
|
||||||
|
assert not fields.checks(entity, "sample_date", date, "%m/%d/%Y", read, codes) # 15th month
|
||||||
|
assert not fields.checks(entity, "sample_date", r"(\d{2}/\d{2})", None, read, codes)
|
||||||
|
assert not fields.checks(entity, "sample_date", r"recepci[oó]n:", None, read, codes) # no group
|
||||||
|
assert not fields.checks(entity, "result", r"resultado:(\s*)", None, read, codes) # nothing
|
||||||
|
# A coded field: what the site writes becomes its ConceptMap, unless it is the code.
|
||||||
|
assert fields.checks(entity, "result", r"resultado:\s*(\S+)", None, read, codes)
|
||||||
|
assert codes.table() == {(entity, "result"): {"negativo": "NILM"}}
|
||||||
|
# A pattern taking text that means two things is the wrong text.
|
||||||
|
assert not fields.checks(entity, "result", r"(calidad)", None, read, fields.Codes("x"))
|
||||||
|
found = codes.concept_map()
|
||||||
|
assert concept_map.problems(found) == []
|
||||||
|
assert concept_map.table([found], "result") == {"negativo": "NILM"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_columns_dates_get_the_format_every_value_parses_with():
|
||||||
|
assert fields.date_format(["02/03/2025", "15/06/2025"]) == "%d/%m/%Y"
|
||||||
|
assert fields.date_format(["2025-03-02", None]) == "%Y-%m-%d"
|
||||||
|
assert fields.date_format(["mañana"]) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_answers_are_held_to_the_platforms_terms():
|
||||||
|
layout = layout_schema()["properties"]["entity"]["enum"]
|
||||||
|
assert "cervical_cytology" in layout and "none" in layout and "identity" not in layout
|
||||||
|
codes = codes_schema(["NEGATIVO", "BAJO GRADO"], ["NILM", "LSIL"])
|
||||||
|
one = codes["$defs"]["Code"]["properties"]
|
||||||
|
assert one["raw"]["enum"] == ["NEGATIVO", "BAJO GRADO"]
|
||||||
|
assert {"enum": ["NILM", "LSIL"], "type": "string"} in one["code"]["anyOf"]
|
||||||
|
table = table_schema(["num", "nombre"])
|
||||||
|
assert table["$defs"]["Who"]["properties"]["column"]["enum"] == ["num", "nombre"]
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""Automático's judgements that need no model: a layout whose title the text layer
|
||||||
|
garbles is still marked by a line it prints, and a report that leaves its sample's date to
|
||||||
|
the order it answers is paired with that order by the column both carry."""
|
||||||
|
|
||||||
|
from core.pipeline import Join, Route
|
||||||
|
from models.draft.documents import printed_line
|
||||||
|
from models.draft.joins import Kind, joined, partner
|
||||||
|
|
||||||
|
HPV = (
|
||||||
|
"No.Proceso {n}\nPaciente {name}\nDDDDEEEETTTTEEEECCCCCCCCIIIIOOOONNNN\n"
|
||||||
|
"ESPECIMEN: CEPILLADO CERVICOVAGINAL\nVVVVPPPPHHHH . . . . . NNNNEEEEGGGG"
|
||||||
|
)
|
||||||
|
FORM = "SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: 0{n}/03/2025"
|
||||||
|
|
||||||
|
|
||||||
|
def row(record: str, text: str, order) -> dict:
|
||||||
|
return {"_record": record, "_file": f"{record:0>64}", "text": text, "format": "pdf",
|
||||||
|
"orden_servicio_id": order, "tipo": "resultado"} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_layout_is_marked_by_a_line_only_it_prints():
|
||||||
|
hpv = [row(f"h{n}", HPV.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
||||||
|
forms = [row(f"c{n}", FORM.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
||||||
|
assert printed_line(hpv, forms) == "ESPECIMEN: CEPILLADO CERVICOVAGINAL"
|
||||||
|
assert printed_line(forms, forms[:1] + hpv) is None # what it prints, another prints too
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_report_is_read_with_the_order_the_same_column_pairs_it_with():
|
||||||
|
reports = Kind("cervical_cytology", "VPH", "cervicovaginal", [],
|
||||||
|
[row(f"h{n}", HPV.format(n=n, name="X"), n) for n in range(4)]) # fmt: skip
|
||||||
|
orders = Kind("cervical_cytology", "Citología", "citología", [],
|
||||||
|
[row(f"c{n}", FORM.format(n=n, name="X"), n) for n in range(1, 6)]) # fmt: skip
|
||||||
|
# `tipo` and `format` pair every document with every other: they pair nothing.
|
||||||
|
assert partner(reports, [reports, orders]) == (orders, "orden_servicio_id")
|
||||||
|
orders.route = Route(id="citologia", label="Citología", inputs=["texto"])
|
||||||
|
node = Join(id="vph_con_citologia", inputs=["vph", "citologia"],
|
||||||
|
on=[("orden_servicio_id", "orden_servicio_id")], how="left") # fmt: skip
|
||||||
|
found = dict((r["_record"], t) for t, r in joined(node, reports.everyone, orders))
|
||||||
|
assert found["h1"].startswith("SOLICITUD DE CITOLOGÍA") and "Proceso 1" in found["h1"]
|
||||||
|
assert found["h0"].startswith("No.Proceso 0") # no order: its own text alone
|
||||||
|
lone = Kind("cervical_cytology", "VPH", "x", [], reports.everyone[:1])
|
||||||
|
assert partner(lone, [lone, orders]) is None
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""A reviewer's "they are different people" is about the persons: it holds when more records
|
||||||
|
join one of them, whichever record the person is known by afterwards."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
PEOPLE = [("1001", "ANA LOPEZ RUIZ", "1980-01-01"), ("2002", "BEATRIZ MORA DIAZ", "1980-01-01")]
|
||||||
|
PEOPLE += [(f"9{k:03d}", f"PERSONA {k} DE RELLENO", f"19{50 + k}-0{1 + k % 9}-11")
|
||||||
|
for k in range(30)] # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def graph(db) -> dict:
|
||||||
|
fields = {"record_number": "num", "full_name": "nombre", "birth_date": "nac", "nss": "nss"}
|
||||||
|
return {"nodes": [
|
||||||
|
{"id": "people", "kind": "source", "source": "dlt.sources.sql_database:sql_table",
|
||||||
|
"args": {"credentials": f"sqlite:///{db}", "table": "people"}},
|
||||||
|
{"id": "identity", "kind": "map", "inputs": ["people"], "fields": fields},
|
||||||
|
{"id": "persons", "kind": "link", "inputs": ["identity"], "fields": list(fields)},
|
||||||
|
]} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def insert(db, rows) -> None:
|
||||||
|
with sqlite3.connect(db) as con:
|
||||||
|
con.execute(
|
||||||
|
"create table if not exists people "
|
||||||
|
"(id integer primary key, num text, nombre text, nac text, nss text)"
|
||||||
|
)
|
||||||
|
con.executemany("insert into people (num, nombre, nac, nss) values (?, ?, ?, ?)", rows)
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_answer_outlives_the_record_a_person_was_known_by(platform, tmp_path):
|
||||||
|
db, drawn = tmp_path / "people.db", tmp_path / "pipeline.json"
|
||||||
|
insert(db, [(*p, None) for p in PEOPLE])
|
||||||
|
drawn.write_text(json.dumps(graph(db)))
|
||||||
|
platform.save("pipelines", "site", drawn)
|
||||||
|
platform.ingest()
|
||||||
|
queue = "select person, candidate from bronze.n__site__persons__review"
|
||||||
|
((a, b),) = platform.query(queue)
|
||||||
|
platform.run("python", "-c", "from persistance import nodes; "
|
||||||
|
f"nodes.decide_persons({a!r}, {b!r}, False, 'reviewer')") # fmt: skip
|
||||||
|
platform.ingest()
|
||||||
|
assert platform.query(queue) == []
|
||||||
|
|
||||||
|
# Forty more documents of each woman: whichever of her records her person was known by,
|
||||||
|
# one of these is (almost surely) it now.
|
||||||
|
insert(db, [(num, None, None, f"{num}{k:07d}") for num in ("1001", "2002") for k in range(40)])
|
||||||
|
platform.ingest()
|
||||||
|
lowest = "select min(_record) from bronze.n__site__persons where record_number = '{}'"
|
||||||
|
known = {platform.query(lowest.format(n))[0][0] for n in ("1001", "2002")}
|
||||||
|
assert known != {a, b}
|
||||||
|
assert platform.query(queue) == []
|
||||||
+11
-11
@@ -25,6 +25,7 @@ from pathlib import Path
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytest
|
import pytest
|
||||||
|
import recurrence_reference as reference
|
||||||
from joblib.externals.loky import get_reusable_executor
|
from joblib.externals.loky import get_reusable_executor
|
||||||
from scipy.special import gammaln
|
from scipy.special import gammaln
|
||||||
|
|
||||||
@@ -71,14 +72,14 @@ def raws(tmp_path_factory) -> dict[str, pd.DataFrame]:
|
|||||||
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
# Each cohort's rows as the pipeline loaded them (one source node per cohort).
|
||||||
out = folder / "datasets.pkl"
|
out = folder / "datasets.pkl"
|
||||||
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
platform.run("python", "-c", "import pandas as pd; from persistance import nodes; "
|
||||||
"from models.cama import recurrence; pd.to_pickle({s: pd.DataFrame(nodes.rows("
|
f"pd.to_pickle({{s: pd.DataFrame(nodes.rows('cama_reference', s)) "
|
||||||
f"'cama_reference', s)) for s in recurrence.SOURCES}}, {str(out)!r})") # fmt: skip
|
f"for s in {reference.SOURCES!r}}}, {str(out)!r})") # fmt: skip
|
||||||
return pd.read_pickle(out)
|
return pd.read_pickle(out)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def prepared(raws):
|
def prepared(raws):
|
||||||
return {s: cohorts.prepare(s, raw) for s, raw in raws.items()}
|
return {s: reference.prepare(s, raw) for s, raw in raws.items()}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
@@ -155,7 +156,7 @@ def _check_figures(records: list[dict], fractional_tolerance: float):
|
|||||||
# ---------------------------------------------------------------- fast
|
# ---------------------------------------------------------------- fast
|
||||||
|
|
||||||
|
|
||||||
def test_cohorts(prepared, raws):
|
def test_cohorts(prepared):
|
||||||
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():
|
||||||
@@ -164,18 +165,17 @@ def test_cohorts(prepared, raws):
|
|||||||
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
assert c.eliminated == sampling[source]["eliminadas_por_colinealidad"]
|
||||||
assert c.covariates == list(missing[source])
|
assert c.covariates == list(missing[source])
|
||||||
assert cohorts.unknown_shares(c) == missing[source]
|
assert cohorts.unknown_shares(c) == missing[source]
|
||||||
pd.testing.assert_frame_equal(recurrence.cohort(source, raws[source]), c.frame)
|
|
||||||
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
|
assert prepared["metabric"].covariates == VERSION["model"]["covariates"]
|
||||||
|
|
||||||
|
|
||||||
def test_routines(prepared):
|
def test_routines(prepared):
|
||||||
found = reports.routines(prepared, modeling.N_BOOTSTRAP)
|
found = reports.routines(prepared, reference.N_BOOTSTRAP)
|
||||||
for name, record in found.items():
|
for name, record in found.items():
|
||||||
assert record == _json(f"rutinas/{name}.json"), name
|
assert record == _json(f"rutinas/{name}.json"), name
|
||||||
|
|
||||||
|
|
||||||
def test_c_index_and_internal_auc(fits):
|
def test_c_index_and_internal_auc(fits):
|
||||||
rows = [r for s in recurrence.SOURCES for r in reports.auc_rows(fits[s])]
|
rows = [r for s in reference.SOURCES for r in reports.auc_rows(fits[s])]
|
||||||
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
|
assert _auc_rows(rows, False) == _auc_rows(DEVELOPMENT["auc"]["filas"], False)
|
||||||
metrics = reports.metrics(rows)
|
metrics = reports.metrics(rows)
|
||||||
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
assert metrics == {k: v for k, v in VERSION["metrics"].items() if "bootstrap" not in k}
|
||||||
@@ -206,7 +206,7 @@ def test_saved_model(fits):
|
|||||||
def test_calculator(fits):
|
def test_calculator(fits):
|
||||||
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
"""All 60 table rows, and the 20 figures but their fractional Weibull's tolerance."""
|
||||||
records, rows = [], []
|
records, rows = [], []
|
||||||
for source in recurrence.SOURCES:
|
for source in reference.SOURCES:
|
||||||
found = calculator.calculator(fits[source])
|
found = calculator.calculator(fits[source])
|
||||||
records += found[0]
|
records += found[0]
|
||||||
rows += found[1]
|
rows += found[1]
|
||||||
@@ -220,12 +220,12 @@ def test_calculator(fits):
|
|||||||
def test_risk_factors(fits):
|
def test_risk_factors(fits):
|
||||||
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
"""All 273 rows, with v1's bootstrap selection shares (the slow test computes them)."""
|
||||||
table = pd.concat(
|
table = pd.concat(
|
||||||
[factors.risk_factors(fits[s], _reference_selection(s)) for s in recurrence.SOURCES],
|
[factors.risk_factors(fits[s], _reference_selection(s)) for s in reference.SOURCES],
|
||||||
ignore_index=True,
|
ignore_index=True,
|
||||||
)
|
)
|
||||||
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
_same_rows(reports.table(table)["filas"], DEVELOPMENT["factores_riesgo"]["filas"],
|
||||||
FACTOR_TOLERANCE) # fmt: skip
|
FACTOR_TOLERANCE) # fmt: skip
|
||||||
summary = [r for s in recurrence.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
summary = [r for s in reference.SOURCES for r in factors.scenario_summary(fits[s], table)]
|
||||||
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
assert reports.table(summary) == _stages(DEVELOPMENT["escenarios_resumen"])
|
||||||
|
|
||||||
|
|
||||||
@@ -262,7 +262,7 @@ def test_fractional_weibull_solver_matches_the_series():
|
|||||||
@pytest.mark.slow
|
@pytest.mark.slow
|
||||||
@slow
|
@slow
|
||||||
def test_train_reproduces_v1(raws):
|
def test_train_reproduces_v1(raws):
|
||||||
model, metrics, found = recurrence.train(raws, bootstrap=True)
|
model, metrics, found = reference.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]
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ FIELDS = {
|
|||||||
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
"ados2": ("evaluation_date", "module", *ADOS2_SCORES),
|
||||||
"eeg": ("study_date", "lab_record_id", "edf"),
|
"eeg": ("study_date", "lab_record_id", "edf"),
|
||||||
} # fmt: skip
|
} # fmt: skip
|
||||||
BOOLS = {"hpv", "hpv_16", "hpv_18"}
|
BOOLS = {f for s in catalog.studies().values() for f, d in s.fields.items() if d.type == "boolean"}
|
||||||
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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")]
|
original = theirs[(theirs["subgrupo"] == e["escenario"]) & (theirs["modelo"] == "COMB")]
|
||||||
gap = np.abs(ours - original.sort_values("meses")["S"].to_numpy()).max()
|
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}")
|
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
|
||||||
|
|||||||
Reference in New Issue
Block a user