acc8c371bc
models/cama/seer_survival is the SEER survival pipeline as Hamilton dataflows, with the interval LR and network keeping their per-interval fits and surviving an interval without deaths. models/cama/survival is the scenario: it indexes the total cohort at the first invasive biopsy report (steps/indexing.py), derives the covariates and the outcome from the cohort's events, fits the interval survival, writes the five routines and publishes the population curves (analisis/curvas.json) with the version. An estimate may carry the model's own index date.
105 lines
4.6 KiB
Python
105 lines
4.6 KiB
Python
"""Stage 02a, balancing: the 18-month outcome and an informed undersampling of the majority class.
|
|
|
|
The patients with a complete record and a known outcome are placed in MCA space (the multiple correspondence analysis
|
|
of their categorical columns); every patient of the minority class (death) is kept, with the same number of survivors
|
|
closest to them. Each public function is a Hamilton node and each parameter is the node of that name; the inputs are
|
|
`depurated_csv`, `labels_json` and `balancing` (its settings). The heavy routines live in `balancing_stats.py`; the
|
|
age and tumor categorization of the balanced cohort is `categorization.py`.
|
|
"""
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
from models.cama.seer_survival import balancing_stats as stats
|
|
from models.cama.seer_survival.columns import find_col
|
|
from models.cama.seer_survival.settings import BalancingSettings
|
|
|
|
MINORITY, MAJORITY = 0, 1
|
|
|
|
|
|
def depurated(depurated_csv: str) -> pd.DataFrame:
|
|
return pd.read_csv(depurated_csv, dtype=str)
|
|
|
|
|
|
def labels(labels_json: str, depurated: pd.DataFrame) -> dict:
|
|
"""Column -> its description; when there is no labels file, the column's own name."""
|
|
path = Path(labels_json)
|
|
if path.exists():
|
|
return json.loads(path.read_text(encoding="utf-8"))
|
|
return {c: c.replace("_", " ") for c in depurated.columns}
|
|
|
|
|
|
def age_column(labels: dict, depurated: pd.DataFrame, balancing: BalancingSettings) -> str:
|
|
col = find_col(labels, balancing.age_keywords)
|
|
if col is None or col not in depurated.columns:
|
|
raise ValueError(f"No se encontró la columna de edad (palabras clave {list(balancing.age_keywords)}).")
|
|
return col
|
|
|
|
|
|
def age_order(depurated: pd.DataFrame, age_column: str) -> pd.DataFrame:
|
|
"""The age levels with a number in them, youngest first: `nivel` and `mid` (its middle)."""
|
|
return (pd.Series(depurated[age_column].dropna().unique())
|
|
.to_frame("nivel")
|
|
.assign(mid=lambda d: d["nivel"].map(stats.age_midpoint))
|
|
.dropna(subset=["mid"])
|
|
.sort_values("mid"))
|
|
|
|
|
|
def age_levels(age_order: pd.DataFrame) -> list[str]:
|
|
return age_order["nivel"].tolist()
|
|
|
|
|
|
def age_midpoints(age_order: pd.DataFrame) -> list[float]:
|
|
return age_order["mid"].tolist()
|
|
|
|
|
|
def full_frame(depurated: pd.DataFrame, age_column: str, age_levels: list[str], labels: dict,
|
|
balancing: BalancingSettings) -> pd.DataFrame:
|
|
"""The patients with an ordered age level, and their `Outcome_cat`: Sobrevive, Muerte or Desconocido."""
|
|
df = depurated[depurated[age_column].isin(age_levels)].copy()
|
|
values = stats.outcome_values(df, labels, balancing)
|
|
df["Outcome_cat"] = np.where(pd.isna(values), "Desconocido", np.where(values == 1, "Sobrevive", "Muerte"))
|
|
return df
|
|
|
|
|
|
def categorical_columns(full_frame: pd.DataFrame) -> list[str]:
|
|
return [c for c in full_frame.columns if c.endswith("_cat") and c != "Outcome_cat"]
|
|
|
|
|
|
def valid_members(full_frame: pd.DataFrame, categorical_columns: list[str], age_column: str) -> pd.Series:
|
|
"""Patients with every categorical column and the age filled in, and a known outcome: the same subset for both
|
|
MCA variants."""
|
|
complete = full_frame[categorical_columns + [age_column]].notna().all(axis=1)
|
|
return complete & (full_frame["Outcome_cat"] != "Desconocido")
|
|
|
|
|
|
def valid_frame(full_frame: pd.DataFrame, valid_members: pd.Series) -> pd.DataFrame:
|
|
return full_frame[valid_members].reset_index(drop=True)
|
|
|
|
|
|
def survives(valid_frame: pd.DataFrame) -> np.ndarray:
|
|
"""1 survives, 0 dies, per valid patient."""
|
|
return (valid_frame["Outcome_cat"] == "Sobrevive").astype(int).values
|
|
|
|
|
|
def mca(valid_frame: pd.DataFrame, categorical_columns: list[str], age_column: str,
|
|
balancing: BalancingSettings) -> stats.Mca:
|
|
"""The MCA of the chosen variant: `con_edad` also takes the age level as a column, `sin_edad` does not."""
|
|
columns = categorical_columns + ([age_column] if balancing.mca_variant == "con_edad" else [])
|
|
return stats.fit_mca(valid_frame[columns], n_components=balancing.n_components)
|
|
|
|
|
|
def keep_mask(mca: stats.Mca, survives: np.ndarray, balancing: BalancingSettings) -> np.ndarray:
|
|
"""Per valid patient: kept by the undersampling (every death, and the survivors nearest to them)."""
|
|
mask, _ = stats.select_informed_undersample(
|
|
mca.F, survives, minority_label=MINORITY, majority_label=MAJORITY, target_ratio=balancing.target_ratio,
|
|
dims=balancing.distance_dims or None)
|
|
return mask
|
|
|
|
|
|
def balanced_frame(valid_frame: pd.DataFrame, keep_mask: np.ndarray) -> pd.DataFrame:
|
|
return valid_frame[keep_mask].reset_index(drop=True)
|