Publicar Kaplan-Meier por combinación de valores en supervivencia CaCu

This commit is contained in:
2026-12-02 23:20:50 -06:00
parent fe1f284e00
commit da14e4ea8e
2 changed files with 32 additions and 0 deletions
+27
View File
@@ -435,6 +435,32 @@ def _scenario_curves(months: np.ndarray, event: np.ndarray, cap_months: int) ->
} # fmt: skip
def _combination_curves(spec: Spec, members: pd.DataFrame) -> list[dict]:
"""Kaplan-Meier of the members who share every covariate value: the one curve a patient with
those values is shown. Fewer than MIN_SCENARIO_EVENTS deaths: counts and why, no curve."""
from models import curves
months, event = members["months"].to_numpy(), members["event"].to_numpy(bool)
keys = spec._combinations(members)
found = []
for values, rows in keys.groupby(list(spec.features), sort=True).indices.items():
values = values if isinstance(values, tuple) else (values,)
entry = {"valores": dict(zip(spec.features, values, strict=True)), "n": len(rows),
"fallecidos": int(event[rows].sum())} # fmt: skip
if entry["fallecidos"] < MIN_SCENARIO_EVENTS:
entry["reason"] = "insufficient_deaths"
else:
until = int(months[rows].max())
km = curves.kaplan_meier(months[rows], event[rows], until)
entry["km"] = {
"months": list(range(until + 1)),
**{n: v.tolist() for n, v in zip(("S", "low", "high"), km, strict=True)},
"interval": {"available": True, "level": 0.95, "method": "greenwood_log_log"},
}
found.append(entry)
return found
def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"""The training members' observed survival (Kaplan-Meier with its Greenwood band, and a
Weibull fit when anyone died), the model's mean survival at each horizon with a bootstrap
@@ -532,6 +558,7 @@ def interpretability(spec: Spec, model: IntervalSurvival, data: dict) -> dict:
"available": True, "level": 0.95, "method": "bootstrap_percentile"}
for scenario in report["escenarios_sin_curvas"]:
scenario["reason"] = "insufficient_deaths"
report["km_combinaciones"] = _combination_curves(spec, members)
return report
+5
View File
@@ -125,6 +125,11 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk
monkeypatch.setattr(curves, "fit_fractional", lambda d, c, k, lam: (1.0, 1.0, lam))
with parallel_config(backend="sequential"):
report = reports.interpretability(spec, model, data)
combined = report["km_combinaciones"]
assert sum(c["n"] for c in combined) == len(pd.concat([data["train"], data["test"]]))
for c in combined:
assert set(c["valores"]) == set(spec.features)
assert ("km" in c) == (c["fallecidos"] >= survival.MIN_SCENARIO_EVENTS)
(scenario,) = report["escenarios"]
name = scenario["escenario"]
assert name == "Citología · HSIL+"