"""One cohort's patients as the frame the analysis reads: one row per patient with the follow-up in months, the recurrence event and each covariate's category, built from the timeline by the dictionary (`[variables]` of `cohorts.toml`). The index is the date of the patient's first biopsy reported as invasive carcinoma, the diagnosis (the cohort's `fecha_indice`); the follow-up runs from it to the recurrence or, without one, to the last contact. The events are a cohort's (`fecha_indice` is the index). A covariate is read from the events up to `window_days_after_index` after the index; a category no rule gives is the variable's `missing` one. """ import tomllib from pathlib import Path import pandas as pd from models.cama.seer_survival.variables import Reader, category_of TOML = Path(__file__).with_name("cohorts.toml") SOURCE_CODE = {"metabric": "METABRIC", "scanb": "SCANB"} def load(path: Path = TOML) -> dict: return tomllib.loads(Path(path).read_text(encoding="utf-8")) def _spec(dictionary: dict, name: str, cohort: str) -> dict: spec = dictionary[name] own = spec.get(cohort, {}) return {**spec, "rules": own["rules"]} if "rules" in own else spec def _cut(values: pd.Series, cuts: list, labels: list, missing: str) -> pd.Series: cut = pd.cut(values, cuts, labels=labels, right=False) return cut.astype("object").where(cut.notna(), missing).astype(str) def recode(events: pd.DataFrame, model: dict, cohort: str, *, of_source: bool = True, follow_up: bool = True) -> pd.DataFrame: """One row per patient. `of_source` keeps only the patients whose record comes from this cohort's source (a patient of another source is read with the same variables when it is false); `follow_up` drops those with no recurrence or last contact, whose time is unknown.""" dictionary = model["variables"] index = dictionary["index"] events = events.copy() events["fecha"] = pd.to_datetime(events["fecha"]) events["fecha_indice"] = pd.to_datetime(events["fecha_indice"]) if of_source: source = events[events["tipo"] == "fuente"].groupby("pac_id")["valor_codigo"].last() patients = pd.Index(sorted(source[source == SOURCE_CODE[cohort]].index), name="pac_id") else: patients = pd.Index(sorted(events["pac_id"].unique()), name="pac_id") events = events[events["pac_id"].isin(patients)] start = events.groupby("pac_id")["fecha_indice"].first().reindex(patients) recurrence = events[events["tipo"] == index["recurrence_source"]].groupby("pac_id")["fecha"].min().reindex(patients) contact = events[events["tipo"] == index["last_contact_source"]].groupby("pac_id")["fecha"].max().reindex(patients) end = recurrence.fillna(contact) birth = events[events["tipo"] == index["birth_source"]].groupby("pac_id")["fecha"].min().reindex(patients) window = pd.Timedelta(days=int(dictionary["window_days_after_index"])) visible = events[events["fecha"] <= events["pac_id"].map(start) + window] reader = Reader(visible, patients, {}) result = pd.DataFrame(index=patients) result["paciente"] = patients.to_numpy() result["tiempo_meses"] = ((end - start).dt.days / index["days_per_month"]).to_numpy() result["evento"] = recurrence.notna().astype(int).to_numpy() unknown = dictionary["Edad"]["missing"] for name in model["cohorts"][cohort]["covariates"]: spec = _spec(dictionary, name, cohort) if name == "Edad": age = (start - birth).dt.days / 365.25 result[name] = _cut(age, spec["cuts"], spec["labels"], unknown).to_numpy() elif "rules" in spec: category = category_of(spec, reader) labels = spec.get(cohort, {}).get("labels", {}) result[name] = category.replace(labels).to_numpy() if labels else category.to_numpy() elif spec.get("terciles"): count = reader.value(spec["source"], True) q = count.quantile([1 / 3, 2 / 3]).to_numpy() result[name] = _cut(count, [-1, q[0] + 1e-9, q[1] + 1e-9, 1e6], spec["labels"], spec["missing"]).to_numpy() else: result[name] = _cut(reader.value(spec["source"], True), spec["cuts"], spec["labels"], spec["missing"]).to_numpy() keep = start.notna().to_numpy() & (end.notna().to_numpy() if follow_up else True) result = result[keep] return result.reset_index(drop=True)