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.
217 lines
11 KiB
Python
217 lines
11 KiB
Python
"""Stage 02b, categorization: groups the balanced cohort's age and tumor size into ordinal groups where the patients'
|
|
composition changes, and proposes alternatives (other covariate blocks, fixed clinical cuts, quantiles).
|
|
|
|
Each public function is a Hamilton node and each parameter is the node of that name; it continues `balancing.py`
|
|
(`balanced_frame`, `valid_frame`, `keep_mask`, `labels`, `age_column`, `age_levels`, `age_midpoints`) and takes
|
|
`categorization` (its settings) as an input. The segmentation itself is in `categorization_stats.py`.
|
|
"""
|
|
|
|
from dataclasses import dataclass
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from matplotlib.figure import Figure
|
|
|
|
from models.cama.seer_survival import categorization_stats as stats
|
|
from models.cama.seer_survival.columns import find_col
|
|
from models.cama.seer_survival.settings import CategorizationSettings
|
|
|
|
AGE_GROUP, TUMOR_GROUP, TUMOR_BIN = "Age_group", "Tumor_group", "Tumor_bin"
|
|
|
|
|
|
@dataclass(frozen=True, eq=False)
|
|
class CutDiagnostics:
|
|
"""What the final cuts of an axis do: sensitivity/specificity per cut, the overlap of deaths and survivors, and
|
|
their distribution along the axis."""
|
|
|
|
table: pd.DataFrame
|
|
overlap: float
|
|
figure: Figure
|
|
|
|
|
|
@dataclass(frozen=True, eq=False)
|
|
class Proposals:
|
|
table: pd.DataFrame # row_id and one `<Age|Tumor>_group__<proposal>` column per proposal and axis
|
|
summary: pd.DataFrame
|
|
|
|
|
|
def min_segment_size(balanced_frame: pd.DataFrame, categorization: CategorizationSettings) -> int:
|
|
"""The smallest segment, as a share of the balanced cohort."""
|
|
return max(categorization.min_n_floor, round(categorization.min_n_pct * len(balanced_frame)))
|
|
|
|
|
|
# ---------------------------------------------------------------- age
|
|
|
|
def age_axis(balanced_frame: pd.DataFrame, age_column: str, age_levels: list[str],
|
|
age_midpoints: list[float]) -> stats.Axis:
|
|
return stats.Axis.of(balanced_frame, age_column, age_levels, age_midpoints, "corte_edad")
|
|
|
|
|
|
def age_configurations(balanced_frame: pd.DataFrame, age_axis: stats.Axis, labels: dict,
|
|
categorization: CategorizationSettings,
|
|
min_segment_size: int) -> dict[str, stats.Segmentation]:
|
|
"""The segmentation of age under every combination of covariate blocks."""
|
|
s = categorization
|
|
blocks = {"outcome": ["Outcome"], "biología": list(s.biology), "tratamiento": list(s.treatment),
|
|
"demográfico": list(s.demographic)}
|
|
return stats.segment_configurations(balanced_frame, age_axis, blocks, labels, s, min_segment_size)
|
|
|
|
|
|
def age_comparison(age_configurations: dict[str, stats.Segmentation], age_axis: stats.Axis) -> pd.DataFrame:
|
|
return stats.comparison_table(age_configurations, age_axis)
|
|
|
|
|
|
def age_group_map(age_configurations: dict[str, stats.Segmentation], age_axis: stats.Axis,
|
|
categorization: CategorizationSettings) -> dict[str, str]:
|
|
"""Each age level -> its group, by the final configuration's segments."""
|
|
return stats.level_to_group(age_configurations[categorization.age_final].segments, list(age_axis.levels))
|
|
|
|
|
|
def age_grouped(balanced_frame: pd.DataFrame, age_column: str, age_group_map: dict[str, str]) -> pd.DataFrame:
|
|
df = balanced_frame.copy()
|
|
df[AGE_GROUP] = df[age_column].map(age_group_map)
|
|
return df
|
|
|
|
|
|
# ---------------------------------------------------------------- tumor size
|
|
|
|
def tumor_raw_column(labels: dict, balanced_frame: pd.DataFrame) -> str:
|
|
col = find_col(labels, ["tumor size"])
|
|
if col is None or col not in balanced_frame.columns:
|
|
raise ValueError("No se encontró la columna cruda del tamaño tumoral.")
|
|
return col
|
|
|
|
|
|
def tumor_binned(age_grouped: pd.DataFrame, tumor_raw_column: str,
|
|
categorization: CategorizationSettings) -> pd.DataFrame:
|
|
"""The frame with the tumor size in mm (`tumor_mm`) and its ordinal level (`Tumor_bin`)."""
|
|
s = categorization
|
|
df = age_grouped.copy()
|
|
df["tumor_mm"] = df[tumor_raw_column].map(stats.tumor_size_mm)
|
|
df[TUMOR_BIN] = df["tumor_mm"].map(lambda mm: stats.tumor_bin_label(mm, s.bin_width_mm, s.tumor_cap_mm))
|
|
return df
|
|
|
|
|
|
def tumor_axis(tumor_binned: pd.DataFrame, categorization: CategorizationSettings) -> stats.Axis:
|
|
levels, mids = stats.tumor_levels(categorization.bin_width_mm, categorization.tumor_cap_mm)
|
|
return stats.Axis.of(tumor_binned, TUMOR_BIN, levels, mids, "corte_mm")
|
|
|
|
|
|
def tumor_configurations(tumor_binned: pd.DataFrame, tumor_axis: stats.Axis, labels: dict,
|
|
categorization: CategorizationSettings,
|
|
min_segment_size: int) -> dict[str, stats.Segmentation]:
|
|
"""The segmentation of tumor size under every combination of blocks; age (`Age_group`) is one more block."""
|
|
s = categorization
|
|
blocks = {"outcome": ["Outcome"], "biología": [b for b in s.biology if b != "Tamano_tumor"],
|
|
"tratamiento": list(s.treatment), "demográfico": list(s.demographic), "edad": [AGE_GROUP]}
|
|
return stats.segment_configurations(tumor_binned, tumor_axis, blocks, labels, s, min_segment_size,
|
|
direct=(AGE_GROUP,))
|
|
|
|
|
|
def tumor_comparison(tumor_configurations: dict[str, stats.Segmentation], tumor_axis: stats.Axis) -> pd.DataFrame:
|
|
return stats.comparison_table(tumor_configurations, tumor_axis)
|
|
|
|
|
|
def tumor_group_map(tumor_configurations: dict[str, stats.Segmentation], tumor_axis: stats.Axis,
|
|
categorization: CategorizationSettings) -> dict[str, str]:
|
|
return stats.level_to_group(tumor_configurations[categorization.tumor_final].segments, list(tumor_axis.levels))
|
|
|
|
|
|
def categorized(tumor_binned: pd.DataFrame, tumor_group_map: dict[str, str]) -> pd.DataFrame:
|
|
"""The balanced cohort with `Age_group` and `Tumor_group`."""
|
|
df = tumor_binned.copy()
|
|
df[TUMOR_GROUP] = df[TUMOR_BIN].map(tumor_group_map)
|
|
return df
|
|
|
|
|
|
def balanced_final(categorized: pd.DataFrame, categorization: CategorizationSettings) -> pd.DataFrame:
|
|
"""The preprocessing's final file, read by bootstrapping and modelling: the recoded tumor size is dropped, since
|
|
`Tumor_group` carries it."""
|
|
assert TUMOR_GROUP in categorized.columns, "Falta Tumor_group"
|
|
return categorized.drop(columns=[c for c in categorization.drop_after if c in categorized.columns])
|
|
|
|
|
|
# ---------------------------------------------------------------- diagnostics of the final cuts
|
|
|
|
def _distribution_figure(df: pd.DataFrame, axis: stats.Axis, known: pd.Series, bounds: list[int], overlap: float,
|
|
xlabel: str, title: str) -> Figure:
|
|
fig = Figure(figsize=(11, 3.5))
|
|
ax = fig.subplots()
|
|
for label, color in [("Sobrevive", "steelblue"), ("Muerte", "indianred")]:
|
|
sub = df.loc[known & (df["Outcome_cat"] == label), axis.column]
|
|
counts = np.array([(sub == l).sum() for l in axis.levels], dtype=float)
|
|
ax.plot(axis.mids, counts / max(counts.sum(), 1), marker="o", ms=3, label=label, color=color)
|
|
for b in bounds:
|
|
ax.axvline((axis.mids[b - 1] + axis.mids[b]) / 2, color="black", lw=1.5, ls="--")
|
|
ax.set_xlabel(xlabel)
|
|
ax.set_ylabel("proporción dentro del grupo")
|
|
ax.set_title(f"{title} (OVL={overlap:.3f}, líneas = cortes finales)", fontsize=10)
|
|
ax.legend()
|
|
fig.tight_layout()
|
|
return fig
|
|
|
|
|
|
def age_diagnostics(categorized: pd.DataFrame, age_axis: stats.Axis, age_configurations: dict,
|
|
categorization: CategorizationSettings) -> CutDiagnostics:
|
|
bounds = age_configurations[categorization.age_final].bounds
|
|
table, overlap, known = stats.sens_spec_table(categorized, age_axis, bounds)
|
|
return CutDiagnostics(table, overlap, _distribution_figure(
|
|
categorized, age_axis, known, bounds, overlap, "Edad (punto medio del nivel)", "Distribución de edad por desenlace"))
|
|
|
|
|
|
def tumor_diagnostics(categorized: pd.DataFrame, tumor_axis: stats.Axis, tumor_configurations: dict,
|
|
categorization: CategorizationSettings) -> CutDiagnostics:
|
|
bounds = tumor_configurations[categorization.tumor_final].bounds
|
|
table, overlap, known = stats.sens_spec_table(categorized, tumor_axis, bounds)
|
|
return CutDiagnostics(table, overlap, _distribution_figure(
|
|
categorized, tumor_axis, known, bounds, overlap, "Tamaño tumoral en mm (punto medio del nivel)",
|
|
"Distribución de tamaño tumoral por desenlace"))
|
|
|
|
|
|
# ---------------------------------------------------------------- proposals and the natural population
|
|
|
|
def proposals(categorized: pd.DataFrame, age_column: str, age_axis: stats.Axis, tumor_axis: stats.Axis,
|
|
age_configurations: dict, tumor_configurations: dict, categorization: CategorizationSettings) -> Proposals:
|
|
"""Each proposal fixes how age and tumor size are grouped; the modelling stage runs every one and compares them."""
|
|
s = categorization
|
|
table = pd.DataFrame({"row_id": np.arange(len(categorized))})
|
|
rows = []
|
|
axes = [("edad", "age", "Age_group", age_column, age_axis, age_configurations, list(s.clinical_age), 0.0),
|
|
("tumor", "tumor", "Tumor_group", TUMOR_BIN, tumor_axis, tumor_configurations, list(s.clinical_tumor), 0.5)]
|
|
for pid, spec in s.proposals.items():
|
|
for eje, key, col_base, col_level, axis, configs, clinical, shift in axes:
|
|
try:
|
|
segs = stats.resolve_segments(spec[key], axis, configs, clinical, shift, s.k_quantiles)
|
|
except KeyError:
|
|
continue
|
|
levels = list(axis.levels)
|
|
mapping = stats.level_to_group(segs, levels)
|
|
col = f"{col_base}__{pid}"
|
|
table[col] = categorized[col_level].map(mapping).values
|
|
# mutually exclusive (each level in one group) and exhaustive (every level covered)
|
|
assert sorted(t for a, b in segs for t in range(a, b)) == list(range(len(levels))), \
|
|
f"{pid}/{eje}: segmentos no particionan el eje"
|
|
order = list(dict.fromkeys(mapping.values()))
|
|
rows.append({"propuesta": pid, "eje": eje, "especificación": spec[key], "K": table[col].nunique(),
|
|
"grupos": " | ".join(order),
|
|
"n_por_grupo": table[col].value_counts().reindex(order).dropna().astype(int).tolist(),
|
|
"filas_sin_grupo": int(table[col].isna().sum())})
|
|
return Proposals(table, pd.DataFrame(rows))
|
|
|
|
|
|
def natural_population(valid_frame: pd.DataFrame, keep_mask: np.ndarray, age_column: str, age_group_map: dict,
|
|
tumor_raw_column: str, tumor_group_map: dict, balanced_final: pd.DataFrame,
|
|
categorization: CategorizationSettings) -> pd.DataFrame:
|
|
"""Every patient with a known outcome (before the undersampling), grouped like the final file, with `en_balanceado`
|
|
= 1 where the undersampling kept them. For the AUC diagnosis; no stage consumes it."""
|
|
s = categorization
|
|
df = valid_frame.copy()
|
|
df["en_balanceado"] = np.asarray(keep_mask).astype(int)
|
|
df[AGE_GROUP] = df[age_column].map(age_group_map)
|
|
df[TUMOR_GROUP] = (df[tumor_raw_column].map(stats.tumor_size_mm)
|
|
.map(lambda mm: stats.tumor_bin_label(mm, s.bin_width_mm, s.tumor_cap_mm))
|
|
.map(tumor_group_map))
|
|
df = df.drop(columns=[c for c in s.drop_after if c in df.columns])
|
|
assert int(df["en_balanceado"].sum()) == len(balanced_final), "El balanceado y la población natural no coinciden"
|
|
return df
|