"""The heavy routines of the categorization stage, apart from its Hamilton nodes (`categorization.py`): the Bayesian change-point segmentation of an ordinal axis (age, tumor size), the choice of segments, the effect sizes across boundaries, the overlap and sensitivity/specificity of a cut, and the fixed and quantile cuts. Plain functions with no I/O. Ported from `02_balanceo_categorizacion.py`. An ordinal axis is cut into contiguous segments where the composition of the covariates changes. The marginal likelihood of each segment is a Dirichlet-multinomial per covariate; the best segmentation for K segments is a dynamic programme over those segment scores; K is the largest whose smallest boundary effect (mean total variation between neighbouring segments) reaches `threshold`; segments under `min_n` patients are merged into a neighbour. """ import itertools from dataclasses import dataclass import numpy as np import pandas as pd from scipy.special import gammaln from models.cama.seer_survival.columns import resolve_column from models.cama.seer_survival.settings import CategorizationSettings @dataclass(frozen=True, eq=False) class Axis: """An ordinal axis: the column holding the level, the levels (low to high), their middles and the patients per level.""" column: str levels: tuple[str, ...] mids: tuple[float, ...] n_per_level: np.ndarray cut_name: str # name of the cut's column in the tables: "corte_edad", "corte_mm" @property def m(self) -> int: return len(self.levels) @classmethod def of(cls, df: pd.DataFrame, column: str, levels, mids, cut_name: str) -> "Axis": return cls(column, tuple(levels), tuple(mids), np.array([int((df[column] == l).sum()) for l in levels]), cut_name) @dataclass(frozen=True, eq=False) class Segmentation: covariate_cols: dict counts: dict segments: list[tuple[int, int]] bounds: list[int] merge_log: list[str] effect_sizes: pd.DataFrame # ---------------------------------------------------------------- segmentation def build_counts(df, axis_col, levels, covariate_cols, min_count=0) -> dict: """Per covariate, the level x category table of counts; categories under `min_count` are dropped when two remain.""" counts = {} for name, col in covariate_cols.items(): tab = pd.crosstab(df[axis_col], df[col]).reindex(index=levels).fillna(0) if min_count > 0: keep = tab.sum(axis=0) >= min_count if keep.sum() >= 2: tab = tab.loc[:, keep] if tab.shape[1] >= 2: counts[name] = tab return counts def cumulative_counts(counts: dict) -> dict: return {c: np.vstack([np.zeros((1, t.shape[1])), np.cumsum(t.values.astype(float), axis=0)]) for c, t in counts.items()} def segment_logml(cum, u, v, alpha=1.0) -> float: """Log marginal likelihood of levels [u, v) forming one segment, summed over the covariates.""" total = 0.0 for c, cm in cum.items(): cj = cm[v] - cm[u] J = len(cj) N = cj.sum() total += (gammaln(J * alpha) - gammaln(N + J * alpha) + (gammaln(cj + alpha) - gammaln(alpha)).sum()) return total def precompute_segments(cum, m, alpha=1.0) -> np.ndarray: S = np.full((m + 1, m + 1), -np.inf) for u in range(m): for v in range(u + 1, m + 1): S[u, v] = segment_logml(cum, u, v, alpha) return S def best_segmentation(S, m, K): """(boundaries, log score) of the best segmentation into K segments.""" V = np.full((K + 1, m + 1), -np.inf) back = np.zeros((K + 1, m + 1), dtype=int) V[1, 1:] = S[0, 1:] for k in range(2, K + 1): for v in range(k, m + 1): cand = V[k - 1, k - 1:v] + S[k - 1:v, v] j = int(np.argmax(cand)) V[k, v] = cand[j] back[k, v] = k - 1 + j bounds, v = [], m for k in range(K, 1, -1): u = back[k, v] bounds.append(int(u)) v = u return sorted(bounds), V[K, m] def compute_effect(counts, seg_a, seg_b) -> float: """Mean over covariates of the total variation between the category mix of two segments.""" tvs = [] for c, tab in counts.items(): mat = tab.values.astype(float) p = mat[seg_a[0]:seg_a[1]].sum(axis=0) p = p / max(p.sum(), 1) q = mat[seg_b[0]:seg_b[1]].sum(axis=0) q = q / max(q.sum(), 1) tvs.append(0.5 * np.abs(p - q).sum()) return float(np.mean(tvs)) def choose_K_by_magnitude(S, counts, m, threshold, kmax): """(K, boundaries) of the largest K up to `kmax` whose smallest boundary effect is >= `threshold`; (1, []) if none.""" best_K, best_bounds = 1, [] for K in range(2, kmax + 1): bounds, _ = best_segmentation(S, m, K) segs = list(zip([0] + bounds, bounds + [m])) effects = [compute_effect(counts, segs[i], segs[i + 1]) for i in range(len(segs) - 1)] if min(effects) >= threshold: best_K, best_bounds = K, bounds return best_K, best_bounds def fix_small_segments(counts, n_per_level, bounds, m, min_n): """Merges each segment under `min_n` patients into the neighbour whose mix differs least; (segments, log).""" segments = list(zip([0] + bounds, bounds + [m])) log = [] while len(segments) > 1: sizes = [n_per_level[a:b].sum() for a, b in segments] below = [i for i, s in enumerate(sizes) if s < min_n] if not below: break i = below[0] effects = [compute_effect(counts, segments[k], segments[k + 1]) for k in range(len(segments) - 1)] if i == 0: j = 0 elif i == len(segments) - 1: j = i - 1 else: j = i - 1 if effects[i - 1] <= effects[i] else i log.append(f" Fusionando por tamaño insuficiente: segmentos {j} y {j + 1} (n={sizes[i]:.0f} < {min_n})") segments = segments[:j] + [(segments[j][0], segments[j + 1][1])] + segments[j + 2:] return segments, log def boundary_effect_sizes(counts, bounds, m, levels) -> pd.DataFrame: """One row per boundary: between which levels, the mean and max change, and the covariate that changes most.""" segs = list(zip([0] + list(bounds), list(bounds) + [m])) rows = [] for i in range(len(segs) - 1): (u1, v1), (u2, v2) = segs[i], segs[i + 1] tvs = {} for c, tab in counts.items(): mat = tab.values.astype(float) p = mat[u1:v1].sum(axis=0) p = p / max(p.sum(), 1) q = mat[u2:v2].sum(axis=0) q = q / max(q.sum(), 1) tvs[c] = 0.5 * np.abs(p - q).sum() rows.append({"entre": f"{levels[v1 - 1]} | {levels[v1]}", "cambio_medio": float(np.mean(list(tvs.values()))), "cambio_max": float(np.max(list(tvs.values()))), "covariable_que_mas_cambia": max(tvs, key=tvs.get)}) return pd.DataFrame(rows) def segment(df: pd.DataFrame, axis: Axis, use_list, labels: dict, s: CategorizationSettings, min_n: int, direct=()) -> Segmentation: """Segments `axis` by the composition of the covariates in `use_list` over the frame's patients.""" cols = {} for name in use_list: col = resolve_column(df, name, labels, s.candidate_keywords, direct) if col is not None and col in df.columns: cols[name] = col counts = build_counts(df, axis.column, list(axis.levels), cols, min_count=s.min_count) S = precompute_segments(cumulative_counts(counts), axis.m, alpha=s.alpha) _, b1 = choose_K_by_magnitude(S, counts, axis.m, threshold=s.threshold, kmax=s.kmax) segments, log = fix_small_segments(counts, axis.n_per_level, b1, axis.m, min_n=min_n) bounds = [seg[1] for seg in segments[:-1]] return Segmentation(cols, counts, segments, bounds, log, boundary_effect_sizes(counts, bounds, axis.m, list(axis.levels))) def configurations(blocks: dict) -> dict[str, list[str]]: """Every non-empty combination of the blocks: "Solo outcome", "Outcome + biología", ... -> its covariates.""" out = {} for r in range(1, len(blocks) + 1): for combo in itertools.combinations(blocks, r): label = f"Solo {combo[0]}" if r == 1 else " + ".join(combo) out[label[0].upper() + label[1:]] = sum((blocks[b] for b in combo), []) return out def segment_configurations(df, axis, blocks, labels, s, min_n, direct=()) -> dict[str, Segmentation]: return {label: segment(df, axis, use, labels, s, min_n, direct) for label, use in configurations(blocks).items()} # ---------------------------------------------------------------- tables and cuts def _cut(axis: Axis, b: int) -> float: return round((axis.mids[b - 1] + axis.mids[b]) / 2, 1) def boundary_table(result: Segmentation, label: str, axis: Axis) -> pd.DataFrame: cols = ["configuración", axis.cut_name, "entre_niveles", "n_izquierda", "n_derecha", "cambio_medio"] if not result.bounds: return pd.DataFrame(columns=cols) effect = result.effect_sizes.reset_index(drop=True) rows = [] for i, b in enumerate(result.bounds): segs = result.segments rows.append({"configuración": label, axis.cut_name: _cut(axis, b), "entre_niveles": f"{axis.levels[b - 1]} | {axis.levels[b]}", "n_izquierda": int(axis.n_per_level[segs[i][0]:segs[i][1]].sum()), "n_derecha": int(axis.n_per_level[segs[i + 1][0]:segs[i + 1][1]].sum()), "cambio_medio": round(float(effect.loc[i, "cambio_medio"]), 3)}) return pd.DataFrame(rows, columns=cols) def segmentation_summary(result: Segmentation, label: str, axis: Axis) -> dict: groups = [f"{axis.levels[a]} a {axis.levels[b - 1]}" if b - a > 1 else axis.levels[a] for a, b in result.segments] sizes = [int(axis.n_per_level[a:b].sum()) for a, b in result.segments] effects = result.effect_sizes["cambio_medio"].tolist() if len(result.bounds) else [] return {"configuración": label, "n_covariables": len(result.covariate_cols), "K (nº de grupos)": len(result.segments), axis.cut_name.replace("corte_", "cortes_"): boundary_table(result, label, axis)[axis.cut_name].tolist(), "grupos": " | ".join(groups), "n por grupo": sizes, "efecto mín.": round(min(effects), 3) if effects else None, "efecto máx.": round(max(effects), 3) if effects else None} def comparison_table(results: dict[str, Segmentation], axis: Axis) -> pd.DataFrame: return pd.DataFrame([segmentation_summary(r, label, axis) for label, r in results.items()]) def level_to_group(segments, levels) -> dict[str, str]: """Each level -> the label of its segment: the level itself, or "first a last".""" out = {} for a, b in segments: label = levels[a] if b - a == 1 else f"{levels[a]} a {levels[b - 1]}" for t in range(a, b): out[levels[t]] = label return out def overlap_coefficient(values_a: pd.Series, values_b: pd.Series, levels) -> float: """Overlap of the level distributions of two groups (1 = identical, 0 = disjoint).""" pa = np.array([(values_a == l).sum() for l in levels], dtype=float) pb = np.array([(values_b == l).sum() for l in levels], dtype=float) pa = pa / max(pa.sum(), 1) pb = pb / max(pb.sum(), 1) return float(np.minimum(pa, pb).sum()) def sens_spec_at_cut(level_index: np.ndarray, is_death: np.ndarray, b: int) -> dict: """Sensitivity and specificity of calling "high risk" the side of boundary `b` with the higher death rate.""" high = level_index >= b rate_high = is_death[high].mean() if high.any() else np.nan rate_low = is_death[~high].mean() if (~high).any() else np.nan high_is_positive = rate_high >= rate_low positive = high if high_is_positive else ~high tp = int((positive & is_death).sum()) fn = int((~positive & is_death).sum()) tn = int((~positive & ~is_death).sum()) fp = int((positive & ~is_death).sum()) sens = tp / (tp + fn) if (tp + fn) else np.nan spec = tn / (tn + fp) if (tn + fp) else np.nan return {"lado_alto_riesgo": "arriba del corte" if high_is_positive else "abajo del corte", "tasa_muerte_abajo": round(float(rate_low), 3) if pd.notna(rate_low) else np.nan, "tasa_muerte_arriba": round(float(rate_high), 3) if pd.notna(rate_high) else np.nan, "sensibilidad": round(sens, 3) if pd.notna(sens) else np.nan, "especificidad": round(spec, 3) if pd.notna(spec) else np.nan} def sens_spec_table(df: pd.DataFrame, axis: Axis, bounds: list[int]) -> tuple[pd.DataFrame, float, pd.Series]: """(table by final cut, overlap coefficient of deaths vs survivors, mask of the patients used): the patients with a known outcome and a level on the axis.""" known = (df["Outcome_cat"] != "Desconocido") & df[axis.column].notna() is_death = (df.loc[known, "Outcome_cat"] == "Muerte").to_numpy() pos = {l: i for i, l in enumerate(axis.levels)} idx = df.loc[known, axis.column].map(pos).to_numpy() ovl = overlap_coefficient(df.loc[known & (df["Outcome_cat"] == "Muerte"), axis.column], df.loc[known & (df["Outcome_cat"] == "Sobrevive"), axis.column], axis.levels) cols = [axis.cut_name, "entre_niveles", "tasa_muerte_abajo", "tasa_muerte_arriba", "lado_alto_riesgo", "sensibilidad", "especificidad"] rows = [] for b in bounds: r = sens_spec_at_cut(idx, is_death, b) r[axis.cut_name] = _cut(axis, b) r["entre_niveles"] = f"{axis.levels[b - 1]} | {axis.levels[b]}" rows.append(r) return (pd.DataFrame(rows)[cols] if rows else pd.DataFrame(columns=cols)), ovl, known def tumor_size_mm(v) -> float: """A tumor size in mm from SEER's code: 1..899 is the size; 0, 9xx and anything else is unknown.""" import re if not isinstance(v, str): return np.nan s = v.strip() if not re.match(r"^\d{1,3}$", s): return np.nan mm = int(s) if mm == 0 or mm >= 900: return np.nan return float(mm) def tumor_bin_label(mm: float, width: int, cap: int): if pd.isna(mm): return np.nan if mm > cap: return f">{cap} mm" lo = int((mm - 1) // width) * width + 1 return f"{lo:03d}-{lo + width - 1:03d} mm" def tumor_levels(width: int, cap: int) -> tuple[list[str], list[float]]: """The ordinal levels of tumor size ("001-005 mm", ..., ">100 mm") and their middles.""" n_bins = cap // width levels = [f"{1 + i * width:03d}-{(i + 1) * width:03d} mm" for i in range(n_bins)] + [f">{cap} mm"] mids = [1 + i * width + (width - 1) / 2 for i in range(n_bins)] + [cap + width / 2] return levels, mids # ---------------------------------------------------------------- proposals def segments_from_bounds(bounds, n_levels) -> list[tuple[int, int]]: cuts = [0] + sorted(set(int(b) for b in bounds if 0 < b < n_levels)) + [n_levels] return list(zip(cuts[:-1], cuts[1:])) def quantile_bounds(n_per_level, K) -> list[int]: cum = np.cumsum(n_per_level) tot = cum[-1] return sorted({int(np.searchsorted(cum, tot * q)) + 1 for q in np.linspace(0, 1, K + 1)[1:-1]}) def resolve_segments(spec: str, axis: Axis, configs: dict[str, Segmentation], clinical: list, shift: float, k_quantiles: int) -> list[tuple[int, int]]: """The segments a proposal's spec means on an axis: fixed clinical cuts, quantiles, or a configuration's own.""" if spec == "clinico": return segments_from_bounds([int(np.searchsorted(axis.mids, thr + shift)) for thr in clinical], axis.m) if spec == "cuantiles": return segments_from_bounds(quantile_bounds(axis.n_per_level, k_quantiles), axis.m) if spec not in configs: raise KeyError(f"configuración '{spec}' no existe") return configs[spec].segments