182 lines
8.0 KiB
Python
182 lines
8.0 KiB
Python
"""Survival curves of a group (free of death, or of recurrence), from whole months of
|
|
follow-up: Kaplan-Meier with its Greenwood band (log-log scale), and a classic and a
|
|
fractional (Kilbas-Saigo) Weibull, both fitted by maximum likelihood on the monthly counts of
|
|
events and censorings (an event in month m falls between S(m) and S(m+1); a censoring there
|
|
survives to m + 1/2). Fits start from several points and run each to the optimizer's
|
|
convergence; one that doesn't converge is an error, not a curve."""
|
|
|
|
import numpy as np
|
|
from scipy.optimize import minimize, minimize_scalar
|
|
from scipy.special import beta as beta_function
|
|
from scipy.special import betainc, gammaln
|
|
|
|
Z = 1.96
|
|
INVALID = 1e12 # the likelihood outside a model's parameter region
|
|
|
|
|
|
def life_table(months: np.ndarray, event: np.ndarray, length: int = 0):
|
|
"""Per month: recurrences, censorings, and patients at risk at its start."""
|
|
months, event = np.asarray(months, int), np.asarray(event, bool)
|
|
length = max(length, int(months.max()) + 2)
|
|
d = np.bincount(months[event], minlength=length)
|
|
c = np.bincount(months[~event], minlength=length)
|
|
at_risk = len(months) - np.concatenate([[0], np.cumsum(d + c)[:-1]])
|
|
return d, c, at_risk
|
|
|
|
|
|
def kaplan_meier(months, event, until: int):
|
|
"""S, low, high at the start of months 0..until."""
|
|
d, _, n = life_table(months, event, until + 1)
|
|
with np.errstate(divide="ignore", invalid="ignore"):
|
|
q = np.where(n > 0, 1 - d / np.maximum(n, 1), 1.0)
|
|
v = np.where((n > 0) & (n > d), d / (np.maximum(n, 1) * np.maximum(n - d, 1)), 0.0)
|
|
S = np.concatenate([[1.0], np.cumprod(q)])[: until + 1]
|
|
se = np.sqrt(np.concatenate([[0.0], np.cumsum(v)])[: until + 1]) / np.abs(np.log(S))
|
|
inside = (S > 0) & (S < 1)
|
|
return (
|
|
S,
|
|
np.where(inside, S ** np.exp(Z * se), S),
|
|
np.where(inside, S ** np.exp(-Z * se), S),
|
|
)
|
|
|
|
|
|
def _nll(survival, d, c) -> float:
|
|
T = len(d)
|
|
both = survival(np.concatenate([np.arange(0, T + 1, dtype=float), np.arange(T) + 0.5]))
|
|
S, mid = both[: T + 1], both[T + 1 :]
|
|
if not (np.all(np.isfinite(S)) and np.all(np.isfinite(mid))):
|
|
return INVALID
|
|
p = np.clip(S[:-1] - S[1:], 1e-300, None)
|
|
return -(np.sum(d * np.log(p)) + np.sum(c * np.log(np.clip(mid, 1e-300, None))))
|
|
|
|
|
|
def weibull(t, k, lam):
|
|
return np.exp(-((np.asarray(t, float) / lam) ** k))
|
|
|
|
|
|
def fit_weibull(d, c) -> tuple[float, float]:
|
|
"""(k, lambda) of the classic Weibull, best of a 3 x 3 grid of Nelder-Mead starts."""
|
|
best = None
|
|
for k0 in (0.7, 1.0, 1.5):
|
|
for l0 in (50.0, 200.0, 1000.0):
|
|
r = minimize(
|
|
lambda p: _nll(lambda t: weibull(t, *np.exp(p)), d, c),
|
|
[np.log(k0), np.log(l0)],
|
|
method="Nelder-Mead",
|
|
options={"xatol": 1e-5, "fatol": 1e-8, "maxiter": 2000},
|
|
)
|
|
r = _converged(r, "Weibull")
|
|
best = r if best is None or r.fun < best.fun else best
|
|
k, lam = np.exp(best.x)
|
|
return float(k), float(lam)
|
|
|
|
|
|
# ---------------------------------------------------------------- fractional Weibull
|
|
|
|
STEPS = 800 # the solver's grid: its error falls as 1/STEPS^2 (~1e-7 here)
|
|
|
|
|
|
class NotConverged(RuntimeError):
|
|
pass
|
|
|
|
|
|
def _converged(r, what: str):
|
|
if not r.success:
|
|
raise NotConverged(f"{what}: {r.message}")
|
|
return r
|
|
|
|
|
|
def kilbas_saigo_survival(t, c: float, rho: float, s: float) -> np.ndarray:
|
|
"""S(t) with S(0) = 1 and Caputo derivative D^rho S(t) = -c t^s S(t) (0 < rho <= 1,
|
|
s + rho > 0): the Kilbas-Saigo function E_{rho, 1+s/rho, s/rho}(-c t^(rho+s)).
|
|
|
|
Solved as its Volterra equation, S(t) = 1 - c/G(rho) int_0^t (t-u)^(rho-1) u^s S(u) du,
|
|
by product integration in w = t^(rho+s), where S is a power series in z = c w and so
|
|
smooth: S is linear in w on each step, and the kernel's integrals against u^s and
|
|
u^(s+rho+s) are exact (incomplete beta functions). The steps are even in log(1 + z):
|
|
fine where S starts to fall, wide over its slow tail. No series, no extended precision."""
|
|
t = np.atleast_1d(np.asarray(t, float))
|
|
e = rho + s
|
|
top = float(t.max()) if t.size else 0.0
|
|
if top <= 0:
|
|
return np.ones_like(t)
|
|
w = np.expm1(np.linspace(0.0, np.log1p(c * top**e), STEPS + 1)) / c
|
|
w[-1] = top**e
|
|
grid = w ** (1 / e)
|
|
y = np.ones(STEPS + 1)
|
|
kappa = c / np.exp(gammaln(rho))
|
|
b0, be = beta_function(s + 1, rho), beta_function(s + e + 1, rho)
|
|
dw = np.diff(w)
|
|
for n in range(1, STEPS + 1):
|
|
x = grid[: n + 1] / grid[n]
|
|
i0 = grid[n] ** (rho + s) * b0 * np.diff(betainc(s + 1, rho, x))
|
|
ie = grid[n] ** (rho + s + e) * be * np.diff(betainc(s + e + 1, rho, x))
|
|
slope = (ie - w[:n] * i0) / dw[:n]
|
|
own, next_ = i0 - slope, slope # y_j's and y_(j+1)'s weights on step j
|
|
known = own[0] + np.dot(own[1:n] + next_[: n - 1], y[1:n])
|
|
y[n] = (1 - kappa * known) / (1 + kappa * next_[n - 1])
|
|
return np.interp(t**e, w, y)
|
|
|
|
|
|
def fractional(t, k, alpha, beta, lam) -> np.ndarray:
|
|
"""The fractional Weibull's survival (Kilbas-Saigo, with the classic Weibull as its
|
|
alpha = beta = 1 case); NaN outside its parameter region."""
|
|
t = np.atleast_1d(np.asarray(t, float))
|
|
s = k + alpha - 2
|
|
if k + alpha <= 1 or s + beta <= 0:
|
|
return np.full(t.shape, np.nan)
|
|
c = np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)) / lam ** (k + alpha + beta - 2)
|
|
return np.clip(kilbas_saigo_survival(t, c, beta, s), 0.0, 1.0)
|
|
|
|
|
|
def _shape(k: float, alpha: float, beta: float) -> tuple[float, float, float]:
|
|
"""(rho, s, scale): the fractional Weibull is S(t) = g(z), z = scale (t/lambda)^(rho+s),
|
|
with g the Kilbas-Saigo survival of order rho and power s at c = 1."""
|
|
return beta, k + alpha - 2, float(np.exp(gammaln(k + 1) - gammaln(k + alpha - 1)))
|
|
|
|
|
|
def fit_fractional(d, c, k: float, lam: float) -> tuple[float, ...]:
|
|
"""(alpha, beta, lambda) of the fractional Weibull with `k` fixed at the classic fit's, by
|
|
maximum likelihood profiled over lambda: for each (alpha, beta), g is solved once over
|
|
every z the allowed lambdas (1 to 1e7) reach, and lambda is then fitted exactly on it.
|
|
(alpha, beta) is the best of a start at the classic fit (alpha = beta = 1, so it is
|
|
never worse) and a grid of others, each to Nelder-Mead's convergence."""
|
|
floor = max(0.0, 1.0 - k) + 1e-6
|
|
top = len(d) + 0.5 # the latest month the likelihood reads (a censoring's half month)
|
|
months = np.concatenate([np.arange(0, len(d) + 1, dtype=float), np.arange(len(d)) + 0.5])
|
|
lambdas = (0.0, np.log(1e7))
|
|
|
|
def unpack(p):
|
|
return floor + np.exp(p[0]), 1 / (1 + np.exp(-p[1]))
|
|
|
|
def profile(p) -> tuple[float, float]:
|
|
a, b = unpack(p)
|
|
if k + a <= 1 or k + a + b <= 2:
|
|
return INVALID, np.nan
|
|
rho, s, scale = _shape(k, a, b)
|
|
e = rho + s
|
|
z_top = scale * top**e # lambda = 1 reaches the farthest
|
|
z = np.expm1(np.linspace(0.0, np.log1p(z_top), STEPS + 1))
|
|
g = np.clip(kilbas_saigo_survival(z ** (1 / e), 1.0, rho, s), 0.0, 1.0)
|
|
|
|
def nll(log_lam: float) -> float:
|
|
found = np.interp(np.log1p(scale * (months / np.exp(log_lam)) ** e), np.log1p(z), g)
|
|
return _nll(lambda t: found, d, c)
|
|
|
|
coarse = np.linspace(*lambdas, 141)
|
|
i = int(np.argmin([nll(x) for x in coarse]))
|
|
r = minimize_scalar(nll, bounds=(coarse[max(i - 1, 0)], coarse[min(i + 1, 140)]),
|
|
method="bounded", options={"xatol": 1e-9}) # fmt: skip
|
|
return float(r.fun), float(r.x)
|
|
|
|
starts = [[np.log(max(1.0 - floor, 1e-9)), 8.0]]
|
|
starts += [[np.log(a0), np.log(b0 / (1 - b0))] for a0 in (0.3, 1.0) for b0 in (0.5, 0.9)]
|
|
best = None
|
|
for p0 in starts:
|
|
options = {"xatol": 1e-5, "fatol": 1e-8, "maxiter": 20_000, "maxfev": 20_000}
|
|
r = minimize(lambda p: profile(p)[0], p0, method="Nelder-Mead", options=options)
|
|
r = _converged(r, "fractional Weibull")
|
|
best = r if best is None or r.fun < best.fun else best
|
|
a, b = unpack(best.x)
|
|
return float(a), float(b), float(np.exp(profile(best.x)[1]))
|