"""Small statistics library in pure Python (no third-party packages), for schumann-storm-recovery. Kaplan-Meier with Greenwood variance, KM median and its Brookmeyer-Crowley CI, bootstrap helpers, exact and normal-approximation Wilcoxon signed-rank, Mann-Whitney U, log-rank, Holm, type-7 quantiles, binomial tail. """ import math, random def quantile7(xs, p): """Type-7 (numpy 'linear', R default) quantile of a list.""" s = sorted(xs); n = len(s) if n == 0: return float('nan') h = (n - 1) * p; lo = math.floor(h); hi = math.ceil(h) return s[lo] + (h - lo) * (s[hi] - s[lo]) def median(xs): return quantile7(xs, 0.5) def km(times, events): """Product-limit estimate. Returns list of (t, S(t) just after t, n_at_risk, d_events, greenwood_sum).""" data = sorted(zip(times, events)) n = len(data); S = 1.0; gw = 0.0; out = []; i = 0 while i < n: t = data[i][0]; d = 0; c = 0 while i < n and data[i][0] == t: if data[i][1]: d += 1 else: c += 1 i += 1 at_risk = n - (i - d - c) if d > 0: S *= (1 - d / at_risk) if at_risk - d > 0: gw += d / (at_risk * (at_risk - d)) else: gw = float('inf') out.append((t, S, at_risk, d, gw)) return out def km_S_at(curve, t): S = 1.0 for (ti, Si, _, _, _) in curve: if ti <= t: S = Si else: break return S def km_median(times, events): curve = km(times, events) for (t, S, _, d, _) in curve: if d > 0 and S <= 0.5 + 1e-12: return t return None def km_median_bc_ci(times, events, z=1.959964): """Brookmeyer-Crowley 95% CI: times t where |S(t) - 0.5| <= z * se(S(t)) (Greenwood).""" curve = km(times, events) ok = [] for (t, S, _, d, gw) in curve: se = S * math.sqrt(gw) if gw != float('inf') else 0.0 if abs(S - 0.5) <= z * se: ok.append(t) if not ok: return (None, None) lo = min(ok); hi = max(ok) # upper limit is "not reached" (None) if the condition still holds at the last time on the curve if hi == curve[-1][0]: hi = None return (lo, hi) def bootstrap(fn, rows, n=2000, seed=20261106): rng = random.Random(seed); out = [] for _ in range(n): sample = [rows[rng.randrange(len(rows))] for _ in rows] out.append(fn(sample)) return out def wilcoxon_signed_rank(diffs, alternative='greater'): """One-sample Wilcoxon signed-rank test of median(diffs) = 0. Returns (W_plus, p, method). Exact null distribution when no zeros and no ties; otherwise normal approximation with tie correction (zeros dropped, as in scipy's default zero_method='wilcox').""" d = [x for x in diffs if x != 0] n = len(d) absd = sorted((abs(x), i) for i, x in enumerate(d)) ranks = [0.0] * n; i = 0; ties = [] while i < n: j = i while j + 1 < n and absd[j + 1][0] == absd[i][0]: j += 1 r = (i + j + 2) / 2.0 for k in range(i, j + 1): ranks[absd[k][1]] = r if j > i: ties.append(j - i + 1) i = j + 1 Wp = sum(r for r, x in zip(ranks, d) if x > 0) if not ties and len(d) == len(diffs) and n <= 60: # exact distribution of W+ over 2^n sign assignments of ranks 1..n maxs = n * (n + 1) // 2 cnt = [0] * (maxs + 1); cnt[0] = 1 for r in range(1, n + 1): for s in range(maxs, r - 1, -1): cnt[s] += cnt[s - r] tot = 2 ** n; w = int(round(Wp)) if alternative == 'greater': p = sum(cnt[w:]) / tot elif alternative == 'less': p = sum(cnt[:w + 1]) / tot else: p = min(1.0, 2 * min(sum(cnt[w:]), sum(cnt[:w + 1])) / tot) return Wp, p, 'exact' mu = n * (n + 1) / 4.0 var = n * (n + 1) * (2 * n + 1) / 24.0 - sum(t ** 3 - t for t in ties) / 48.0 zz = (Wp - mu) / math.sqrt(var) if alternative == 'greater': p = 0.5 * math.erfc(zz / math.sqrt(2)) elif alternative == 'less': p = 0.5 * math.erfc(-zz / math.sqrt(2)) else: p = math.erfc(abs(zz) / math.sqrt(2)) return Wp, p, 'normal' def mann_whitney(x, y, alternative='greater'): """Mann-Whitney U for x > y (normal approximation with tie correction). Returns (U_x, p, AUC).""" allv = sorted([(v, 0) for v in x] + [(v, 1) for v in y]) N = len(allv); ranks = [0.0] * N; i = 0; tie_term = 0 while i < N: j = i while j + 1 < N and allv[j + 1][0] == allv[i][0]: j += 1 r = (i + j + 2) / 2.0 for k in range(i, j + 1): ranks[k] = r t = j - i + 1 tie_term += t ** 3 - t i = j + 1 n1, n2 = len(x), len(y) R1 = sum(r for r, (v, g) in zip(ranks, allv) if g == 0) U1 = R1 - n1 * (n1 + 1) / 2.0 mu = n1 * n2 / 2.0 var = n1 * n2 / 12.0 * ((N + 1) - tie_term / (N * (N - 1))) zz = (U1 - mu) / math.sqrt(var) if var > 0 else 0.0 if alternative == 'greater': p = 0.5 * math.erfc(zz / math.sqrt(2)) elif alternative == 'less': p = 0.5 * math.erfc(-zz / math.sqrt(2)) else: p = math.erfc(abs(zz) / math.sqrt(2)) return U1, p, U1 / (n1 * n2) def logrank(t1, e1, t2, e2): """Two-sample log-rank test. Returns (chi2, p, observed1, expected1).""" times = sorted(set([t for t, e in zip(t1, e1) if e] + [t for t, e in zip(t2, e2) if e])) O1 = E1 = V = 0.0 for t in times: n1 = sum(1 for x in t1 if x >= t); n2 = sum(1 for x in t2 if x >= t) d1 = sum(1 for x, e in zip(t1, e1) if x == t and e); d2 = sum(1 for x, e in zip(t2, e2) if x == t and e) n = n1 + n2; d = d1 + d2 if n == 0: continue O1 += d1; E1 += d * n1 / n if n > 1: V += d * (n1 / n) * (1 - n1 / n) * (n - d) / (n - 1) chi2 = (O1 - E1) ** 2 / V if V > 0 else 0.0 p = math.erfc(math.sqrt(chi2 / 2)) # chi-square with 1 df return chi2, p, O1, E1 def holm(ps): m = len(ps); order = sorted(range(m), key=lambda i: ps[i]); adj = [0.0] * m; run = 0.0 for k, i in enumerate(order): run = max(run, min(1.0, (m - k) * ps[i])); adj[i] = run return adj def binom_tail_ge(k, n, p=0.5): return sum(math.comb(n, j) * p ** j * (1 - p) ** (n - j) for j in range(k, n + 1))