"""Integrate an existing KM step table; does not fit survival or infer a population.""" import argparse from fractions import Fraction import hashlib import json import math from pathlib import Path def number(value): if isinstance(value, bool) or not isinstance(value, (int, float, str)): raise ValueError("Expected a finite number or rational string") if isinstance(value, float) and not math.isfinite(value): raise ValueError("Nonfinite values are not supported") try: return Fraction(str(value)) except (ValueError, ZeroDivisionError) as error: raise ValueError("Invalid rational number") from error def integrate(rows, horizon): """Exact rectangles for a supplied right-continuous curve, without extrapolation.""" tau = number(horizon) if tau < 0 or not isinstance(rows, list) or not rows: raise ValueError("Nonnegative horizon and a nonempty step table required") parsed = [] previous_time, previous_survival = Fraction(0), Fraction(1) for row in rows: time = number(row["day"]) survival = number(row["survival_fraction"]) if time <= previous_time or not 0 <= survival <= previous_survival: raise ValueError("Times must increase and survival must not increase") if "survival" in row and not math.isclose( float(number(row["survival"])), float(survival), rel_tol=1e-12, abs_tol=1e-12 ): raise ValueError("Decimal and exact survival values disagree") parsed.append((time, survival)) previous_time, previous_survival = time, survival if tau > parsed[-1][0]: raise ValueError("Horizon exceeds the final supplied observation; no extrapolation") intervals = [] previous_time, previous_survival = Fraction(0), Fraction(1) for time, survival in parsed: end = min(time, tau) if end > previous_time: if intervals and intervals[-1][2] == previous_survival: intervals[-1] = (intervals[-1][0], end, previous_survival) else: intervals.append((previous_time, end, previous_survival)) if time >= tau: break previous_time, previous_survival = time, survival area = sum(((end - start) * survival for start, end, survival in intervals), Fraction(0)) return area, intervals SOURCE_SHA256 = "e7399be2df9e400355fb2dfb8c516e093f679d67cd0c8aa06907fb3cac961e2a" def build(input_bytes, script_bytes): # Fixed publication claims refer to this exact existing six-device fixture. if hashlib.sha256(input_bytes).hexdigest() != SOURCE_SHA256: raise ValueError("Input differs from the published six-device example") example = json.loads(input_bytes) if example["kind"] != "synthetic-worked-example" or example["timeUnit"] != "day": raise ValueError("This publication uses only the existing fictional day-based example") rows = example["rows"] if not rows or number(rows[-1]["day"]) != max(number(o["exit_day"]) for o in example["observations"]): raise ValueError("Step table must end at the final observation") area, intervals = integrate(rows, 10) observations = example["observations"] failures = [o for o in observations if o["event"]] exit_mean = sum((number(o["exit_day"]) for o in observations), Fraction(0)) / len(observations) failure_mean = sum((number(o["exit_day"]) for o in failures), Fraction(0)) / len(failures) return { "schemaVersion": 1, "kind": "synthetic-worked-example", "title": "Restricted mean survival time from the existing six-device KM example", "timeUnit": "day", "horizon_day": 10, "population": example["population"], "eventDefinition": example["eventDefinition"], "source_url": "https://hesela.dev/data/methods/km-censoring-example.json", "source_sha256": hashlib.sha256(input_bytes).hexdigest(), "generator_sha256": hashlib.sha256(script_bytes).hexdigest(), "method": "Exact Fraction rectangles under the supplied right-continuous Kaplan-Meier steps; no refit or tail extrapolation.", "rmst_fraction": str(area), "rmst_days": float(area), "horizon_survival_fraction": str(number(rows[-1]["survival_fraction"])), "shortcut_comparisons": { "recorded_exit_mean_fraction": str(exit_mean), "recorded_exit_denominator": len(observations), "observed_failure_mean_fraction": str(failure_mean), "observed_failure_denominator": len(failures), "interpretation": "Mean observation exit and mean among observed failures are not the Kaplan-Meier restricted mean." }, "intervals": [ {"start_day": float(start), "end_day": float(end), "survival_fraction": str(survival), "area_fraction": str((end - start) * survival)} for start, end, survival in intervals ], "horizon_checks": [ {"horizon_day": tau, "rmst_fraction": str(integrate(rows, tau)[0]), "rmst_days": float(integrate(rows, tau)[0])} for tau in [5, 8, 10] ], "limits": [ "Invented inputs, not measured fleet reliability or a population estimate.", "No confidence interval, censoring correction or delayed-entry handling is added.", "This integrates existing KM rows; it is not a general survival estimator.", "Only one fictional device remains at risk just before day 10.", "The restricted mean is not unrestricted lifetime, MTBF or individual remaining life.", "Horizons beyond the final supplied observation are rejected." ], "sources": [ {"url": "https://link.springer.com/article/10.1186/1471-2288-13-152", "locator": "Methods, Definition of RMST, equation 1"}, {"url": "https://med.stanford.edu/content/dam/sm/dbds/documents/biostats-workshop/2014-Uno-JCO.pdf", "locator": "pp. 2383-2384: common-horizon contrasts and prespecification"}, {"url": "https://web.stanford.edu/~lutian/coursepdf/KMpaper.pdf", "locator": "Sections 1.4, 2.1 and 2.3: ties, unsupported tail, and survival at the restriction horizon"} ] } if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() result = build(args.input.read_bytes(), Path(__file__).read_bytes()) args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")