Compare commits

..

2 Commits

Author SHA1 Message Date
Roberto Treviño 77350b8fec A reviewer's answer holds when more records join a person 2026-11-30 02:14:13 -06:00
Roberto Treviño a9945bc021 A training run takes every model; the public cohorts' code lives with the tests 2026-11-29 21:12:17 -06:00
15 changed files with 283 additions and 253 deletions
+12 -29
View File
@@ -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}
+3 -42
View File
@@ -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,
+9 -88
View File
@@ -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."""
+2 -2
View File
@@ -8,7 +8,7 @@ import numpy as np
import pandas as pd import pandas as pd
from models import factors as rated from models import factors as rated
from models.cama.recurrence.calculator import SCENARIOS, masks 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 from models.cama.recurrence.modeling import CohortFit
from models.factors import FREQ_MIN, ORDER from models.factors import FREQ_MIN, ORDER
@@ -102,7 +102,7 @@ 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 = rated.classified(factors[factors["cohorte"] == source]) found = rated.classified(factors[factors["cohorte"] == source])
rows = [] rows = []
for name, mask in masks(frame, scenarios).items(): for name, mask in masks(frame, scenarios).items():
+2 -3
View File
@@ -20,10 +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 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
@@ -32,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
+1 -12
View File
@@ -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}»); "
+38 -1
View File
@@ -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
+7 -5
View File
@@ -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 = []
+1 -1
View File
@@ -43,7 +43,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)
+4 -1
View File
@@ -425,6 +425,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 +442,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
+4 -9
View File
@@ -41,12 +41,11 @@ 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 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]: def scored(self) -> list[str]:
"""The models a score run takes when none is named: all of them (only training is """The models a score run takes when none is named: all of them."""
slow)."""
return list(self.models) return list(self.models)
def registered(self, name: str) -> str: def registered(self, name: str) -> str:
@@ -56,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}")
@@ -82,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
+135
View File
@@ -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 {})
+51
View File
@@ -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
View File
@@ -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]
+3 -49
View File
@@ -17,55 +17,9 @@ from datetime import date
from core import catalog from core import catalog
ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number") ADOS2_SCORES = tuple(f for f, d in catalog.studies()["ados2"].fields.items() if d.type == "number")
GYN = (
"gyn_puerperium",
"gyn_pregnancy",
"gyn_iud",
"gyn_hormonal_treatment",
"gyn_other_treatment",
"gyn_postmenopause",
"gyn_hysterectomy",
"gyn_not_applicable",
)
PRESENTS = (
"presents_discharge",
"presents_vulvar_pruritus",
"presents_abnormal_bleeding",
"presents_none",
)
CYTO = (
"cyto_inflammation",
"cyto_reactive_changes",
"cyto_bacterial_vaginosis_flora",
"cyto_candida",
"cyto_bacillary_flora_cytolysis",
"cyto_intermediate_cytolysis",
"cyto_trichomonas",
"cyto_leptothrix",
"cyto_actinomyces_organisms",
"cyto_actinomyces_changes",
"cyto_herpes_simplex_changes",
"cyto_squamous_tubular_metaplasia",
"cyto_keratotic_changes",
"cyto_pregnancy_changes",
"cyto_atrophy",
"cyto_hypoestrogenism",
"cyto_radiotherapy_effect",
"cyto_iud_changes",
"cyto_post_hysterectomy_glandular_cells",
"cyto_bacteria",
"cyto_herpes_image",
"cyto_fungi",
"cyto_radiation",
"cyto_repair",
"cyto_iud_effect",
"cyto_endometrial_cells_40_plus",
"cyto_findings_none",
)
FIELDS = { FIELDS = {
"cervical_cytology": ("sample_date", "screening_history", *GYN, *PRESENTS, "cervical_cytology": ("sample_date", "report_date", "adequacy", "result", "hpv", "hpv_16",
"cervix_exam", "report_date", "adequacy", "result", "hpv", "hpv_16", "hpv_18"),
"hpv_18", "cyto_findings_text", *CYTO),
"cervical_biopsy": ("request_date", "report_date", "histology"), "cervical_biopsy": ("request_date", "report_date", "histology"),
"mammography": ("exam_date", "report_date", "adequacy", "birads"), "mammography": ("exam_date", "report_date", "adequacy", "birads"),
"breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade", "breast_biopsy": ("request_date", "report_date", "histology", "histologic_type", "grade",
@@ -78,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", *GYN, *PRESENTS, *CYTO} BOOLS = {"hpv", "hpv_16", "hpv_18"}
NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES} NUMBERS = {"ki67_pct", "size_mm", "positive_nodes", "score", *ADOS2_SCORES}