diff --git a/models/survival.py b/models/survival.py index e21478a..2ff5b96 100644 --- a/models/survival.py +++ b/models/survival.py @@ -435,13 +435,14 @@ 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 - +def _combination_curves(spec: Spec, model: IntervalSurvival, members: pd.DataFrame) -> list[dict]: + """The curves of the members who share every covariate value, the ones a patient with those + values is shown: Kaplan-Meier, Weibull, fractional Weibull and the model's points for those + values (its bootstrap band where training saw them). Fewer than MIN_SCENARIO_EVENTS deaths: + counts and why, no curve.""" months, event = members["months"].to_numpy(), members["event"].to_numpy(bool) keys = spec._combinations(members) + intervals = getattr(model, "intervals_", {}) found = [] for values, rows in keys.groupby(list(spec.features), sort=True).indices.items(): values = values if isinstance(values, tuple) else (values,) @@ -450,13 +451,20 @@ def _combination_curves(spec: Spec, members: pd.DataFrame) -> list[dict]: 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"}, - } + entry |= _scenario_curves(months[rows], event[rows], spec.cap_months) + point = {"S": model.survival(members.iloc[rows[:1]])[0].tolist()} + band = intervals.get(values) + if band: # kept as mortality: survival's limits are its complements, swapped + point |= {"low": [1 - v for v in band[1]], "high": [1 - v for v in band[0]]} + point["interval"] = {"available": bool(band), + "level": spec.interval_level if band else None, + "method": "bootstrap_percentile" if band else None} # fmt: skip + entry["points"] = {"COMB": point} + entry["horizons_months"] = list(spec.borders[1:]) + entry["km"]["interval"] = { + "available": True, "level": 0.95, "method": "greenwood_log_log"} + for name in ("weibull", "weibull_fractional"): + entry[name]["interval"] = {"available": False, "level": None, "method": None} found.append(entry) return found @@ -558,7 +566,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) + report["km_combinaciones"] = _combination_curves(spec, model, members) return report diff --git a/tests/test_cacu_models.py b/tests/test_cacu_models.py index af73ed4..6800a0f 100644 --- a/tests/test_cacu_models.py +++ b/tests/test_cacu_models.py @@ -130,6 +130,10 @@ def test_survival_matches_the_current_model_and_publishes_patient_scenarios(monk for c in combined: assert set(c["valores"]) == set(spec.features) assert ("km" in c) == (c["fallecidos"] >= survival.MIN_SCENARIO_EVENTS) + if "km" in c: + assert {"weibull", "weibull_fractional", "points"} <= set(c) + point = c["points"]["COMB"] + assert len(point["S"]) == len(c["horizons_months"]) == len(spec.borders) - 1 (scenario,) = report["escenarios"] name = scenario["escenario"] assert name == "Citología · HSIL+"