Algorithm Search⌘K

Algorithmcore

Kaplan-Meier estimator

Also called product-limit estimator.

Estimates the survival function under right censoring as the product over event times of one minus the deaths over the number at risk. It is the nonparametric MLE.

Time
Θ(n log n) worst
Space
Θ(n) extra
Where
k = the number of distinct event times; n = the number of subjects
Properties
deterministicexactofflineiterative
Origin
Edward L. Kaplan, Paul Meier, 1958

The Kaplan-Meier estimator estimates the survival function S(t)=P(T>t)S(t) = P(T > t) from data in which some event times are right censored: for those subjects we know only that the event had not happened by the time follow-up stopped. At each distinct event time tjt_j it counts the njn_j subjects still at risk and the djd_j events, estimates the conditional probability of getting past tjt_j as 1−dj/nj1 - d_j/n_j, and multiplies these factors:

S^(t)=∏j: tj≤t(1−djnj).\hat S(t) = \prod_{j:\, t_j \le t} \left(1 - \frac{d_j}{n_j}\right).

A censored subject counts in every risk set up to its censoring time and then leaves without causing a step. With no censoring, S^\hat S is one minus the empirical distribution function. Under independent censoring S^\hat S is the nonparametric maximum likelihood estimate of SS, and the computation is one sort and one pass.

In plain words

Patients enter a study and are followed until they die or until the study stops watching them. For a patient who left the study alive after 10 weeks, we do not know the death time, only that it is later than 10 weeks. To estimate the chance of surviving past 20 weeks, go through time in order. Each time someone dies, look at the people who were still being followed just before, and note the fraction who survived that moment. Multiply these fractions together. A person who left early helps in every fraction up to the time they left, and then drops out of the count. Throwing that person away, or counting them as dead, would both make survival look worse than it is.

The problem

Input. Observations (yi,δi)(y_i, \delta_i) for i=1,…,ni = 1, \ldots, n, where yi=min⁡(Ti,Ci)y_i = \min(T_i, C_i) is the observed time, TiT_i the event time, CiC_i the censoring time, and δi=1\delta_i = 1 if Ti≤CiT_i \le C_i (an event) and 00 otherwise (censored).

Model. The pairs (Ti,Ci)(T_i, C_i) are independent across ii, the TiT_i have survival function SS, and censoring is independent: given that a subject is still at risk at time tt, the chance of an event at tt does not depend on the censoring. No form of SS is assumed. The censoring page states these conditions in full.

Output. The distinct event times t1<⋯<tkt_1 < \cdots < t_k, with nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\} at risk and dj=#{i:yi=tj,δi=1}d_j = \#\{i : y_i = t_j, \delta_i = 1\} events at each, and the values S^(tj)\hat S(t_j). The estimate is the right-continuous step function that equals 11 before t1t_1 and S^(tj)\hat S(t_j) on [tj,tj+1)[t_j, t_{j+1}).

Ties. A censoring time equal to an event time counts as later: the censored subject is in the risk set njn_j. This is the convention of Kaplan and Meier, and it matches the usual reading that a subject censored at tt was seen alive at tt.

The algorithm

  1. KAPLAN-MEIER(y[1..n], δ[1..n])
  2. 1sort the indices 1..n by y
  3. 2r ← n; S ← 1; out ← empty list
  4. 3i ← 1
  5. 4while i ≤ n
  6. 5t ← y of the i-th sorted index; d ← 0; c ← 0
  7. 6while i ≤ n and y of the i-th sorted index = t: add 1 to d if δ = 1, else to c; i ← i + 1
  8. 7if d > 0 then S ← S · (1 - d/r); append (t, r, d, S) to out
  9. 8r ← r - d - c ▷ the d + c subjects leave the risk set after t
  10. 9return out

Line L1 sorts the times. The variable rr is the size of the current risk set; it starts at nn and line L8 removes each group of tied subjects after their time is processed, so censored subjects at tt are still counted at tt. Line L7 makes a step only at event times. The code returns the list of steps together with the largest observed time y(n)y_{(n)}, and evaluates S^(t)\hat S(t) by a scan or a binary search over the steps.

If the largest observation is censored, S^\hat S does not reach 00, and the data say nothing about SS beyond y(n)y_{(n)}: the code raises an error for t>y(n)t > y_{(n)} in that case. If the largest observation is an event, S^\hat S drops to 00 there.

Example

The 6-MP arm of the leukemia trial of Freireich et al. (1963), as listed by Gehan (1965), has 21 remission times in weeks, with ++ marking a censored time:

6, 6, 6, 6+, 7, 9+, 10, 10+, 11+, 13, 16, 17+, 19+, 20+, 22, 23, 25+, 32+, 32+, 34+, 35+.

The pass of lines L4 to L8 visits 16 distinct times. The rows with d>0d > 0 form the output:

tt rr at tt dd cc factor 1−d/r1 - d/r S^(t)\hat S(t) decimal
6 21 3 1 18/21 6/7 0.8571
7 17 1 0 16/17 96/119 0.8067
9 16 0 1 none 96/119 0.8067
10 15 1 1 14/15 64/85 0.7529
11 13 0 1 none 64/85 0.7529
13 12 1 0 11/12 176/255 0.6902
16 11 1 0 10/11 32/51 0.6275
17, 19, 20 10, 9, 8 0 1 each none 32/51 0.6275
22 7 1 0 6/7 64/119 0.5378
23 6 1 0 5/6 160/357 0.4482
25, 32, 34, 35 5, 4, 2, 1 0 1, 2, 1, 1 none 160/357 0.4482

At t=6t = 6 the censored subject is in the risk set of 21, and only after the step does rr fall by d+c=4d + c = 4 to 17. The estimated median remission time, the first tt with S^(t)≤1/2\hat S(t) \le 1/2, is 23 weeks. The last observation, 35, is censored, so S^\hat S stays at 160/357160/357 up to 35 and is undefined after it. The Greenwood formula gives standard errors 0.0764 at t=6t = 6 and 0.1346 at t=23t = 23.

The two wrong ways to treat the censored times give quite different answers. If the 12 censored times are dropped, the 9 events alone have empirical median 10 weeks. If they are counted as events, the median is 16 weeks and the estimate at 23 weeks is 5/21=0.2385/21 = 0.238 instead of 0.4480.448. Both are biased downward, because both lose the information that the censored patients were still in remission.

The placebo arm of the same trial has no censoring (1, 1, 2, 2, 3, 4, 4, 5, 5, 8, 8, 8, 8, 11, 11, 12, 12, 15, 17, 22, 23). Its Kaplan-Meier estimate is the empirical survival function #{yi>t}/21\#\{y_i > t\}/21: 19/2119/21 after week 1, 16/2116/21 after week 3, 8/218/21 after week 8, and median 8 weeks. The log-rank test compares the two arms.

Correctness

The proof in proofs/correctness.md shows three things. First, the pass of lines L4 to L8 keeps the invariant that rr equals the number of subjects with yi≥ty_i \ge t when the group at time tt starts, so every output row is (tj,nj,dj,∏l≤j(1−dl/nl))(t_j, n_j, d_j, \prod_{l \le j}(1 - d_l/n_l)). Second, under a likelihood that does not involve the censoring distribution, the product-limit estimate maximizes the likelihood over all distributions on (0,∞](0, \infty], and it is the unique maximizer on [0,y(n)][0, y_{(n)}]. Third, it equals Efron's redistribute-to-the-right estimate, in which each censored subject passes its probability mass in equal shares to every subject later in time.

Proof: The pass computes the product-limit estimate, which is the nonparametric MLE and equals Efron's redistribute-to-the-right estimatefull

Let the data be (yi,δi)(y_i, \delta_i) for i=1,…,ni = 1, \ldots, n, with distinct event times t1<⋯<tkt_1 < \cdots < t_k (the distinct yiy_i with δi=1\delta_i = 1), nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\} and dj=#{i:yi=tj,δi=1}d_j = \#\{i : y_i = t_j, \delta_i = 1\}. The product-limit estimate is S^(t)=∏j: tj≤t(1−dj/nj)\hat S(t) = \prod_{j:\, t_j \le t}(1 - d_j/n_j).

Claim 1 (the pass computes the product-limit estimate). Every row (t,r,d,S)(t, r, d, S) that line L7 appends is (tj,nj,dj,S^(tj))(t_j, n_j, d_j, \hat S(t_j)) for some jj, and each jj gives one row, in increasing order of tjt_j.

Proof. After line L1 the indices are in increasing order of yy. The inner loop of line L6 reads exactly the indices whose time equals tt, so the outer loop visits each distinct observed time u1<u2<⋯u_1 < u_2 < \cdots once, in order, and at time uu it sets dd and cc to the numbers of events and censorings at uu.

Invariant: when the outer loop starts the group at time uu, r=#{i:yi≥u}r = \#\{i : y_i \ge u\} and S=S^(u−)=∏j: tj<u(1−dj/nj)S = \hat S(u-) = \prod_{j:\, t_j < u}(1 - d_j/n_j). At the first group, r=nr = n and S=1S = 1, and both sides are right because no yiy_i is below the smallest time and the product is empty. Suppose the invariant holds at uu. If u=tju = t_j is an event time, line L7 sets SS to S^(u−)(1−dj/nj)=S^(tj)\hat S(u-)(1 - d_j/n_j) = \hat S(t_j); otherwise SS is unchanged and S^(u)=S^(u−)\hat S(u) = \hat S(u-). Line L8 subtracts the d+cd + c subjects with yi=uy_i = u, so rr becomes #{i:yi>u}=#{i:yi≥u′}\#\{i : y_i > u\} = \#\{i : y_i \ge u'\} for the next distinct time u′u', and S=S^(u)=S^(u′−)S = \hat S(u) = \hat S(u'-) because no event time lies in (u,u′)(u, u'). So the invariant holds at u′u'. At an event time the row appended has r=njr = n_j, d=djd = d_j and S=S^(tj)S = \hat S(t_j). □\square

Claim 2 (maximum likelihood). Let F\mathcal F be the set of probability distributions on (0,∞](0, \infty], where mass at ∞\infty means that the event never happens. For F∈FF \in \mathcal F write pF(u)=PF(T=u)p_F(u) = P_F(T = u) and SF(u)=PF(T>u)S_F(u) = P_F(T > u), and define

L(F)=∏i: δi=1pF(yi)∏i: δi=0SF(yi).L(F) = \prod_{i:\, \delta_i = 1} p_F(y_i) \prod_{i:\, \delta_i = 0} S_F(y_i).

Assume at least one event. Then LL attains its maximum over F\mathcal F, and FF is a maximizer if and only if SF(t)=S^(t)S_F(t) = \hat S(t) for all t≤y(n)t \le y_{(n)}, the largest observed time.

This LL is the likelihood of the data as a function of FF when censoring is independent and noninformative: the full likelihood is L(F)L(F) times a factor that depends only on the censoring distribution (censoring derives this factorization). So the claim says that the product-limit estimate is the nonparametric maximum likelihood estimate.

Proof. Put t0=0t_0 = 0 and tk+1=∞t_{k+1} = \infty. Take FF with L(F)>0L(F) > 0; such an FF exists (put mass 1/(k+1)1/(k+1) at each tjt_j and at ∞\infty). Then pF(tj)>0p_F(t_j) > 0 for every jj.

Step 1: the mass sits at the event times and beyond y(n)y_{(n)}. Define F∗F^* by moving the mass of FF in each open interval (tj−1,tj)(t_{j-1}, t_j), for j=1,…,kj = 1, \ldots, k, to the point tjt_j, and the mass in (tk,y(n)](t_k, y_{(n)}] to ∞\infty. Masses at the tjt_j only grow, so pF∗(yi)≥pF(yi)p_{F^*}(y_i) \ge p_F(y_i) for every event. For a censored yiy_i, every moved point goes to the right, so mass that was above yiy_i stays above yiy_i, and SF∗(yi)≥SF(yi)S_{F^*}(y_i) \ge S_F(y_i). Hence L(F∗)≥L(F)L(F^*) \ge L(F). The inequality is strict if FF has mass in some (tj−1,tj)(t_{j-1}, t_j) with j≤kj \le k, because then pF∗(tj)>pF(tj)p_{F^*}(t_j) > p_F(t_j) and dj≥1d_j \ge 1; it is also strict if FF has mass in (tk,y(n)](t_k, y_{(n)}], because the subject with yi=y(n)y_i = y_{(n)} is then censored (an event at y(n)y_{(n)} would make y(n)=tky_{(n)} = t_k) and SF∗(y(n))>SF(y(n))S_{F^*}(y_{(n)}) > S_F(y_{(n)}).

Step 2: maximize over distributions on {t1,…,tk,∞}\{t_1, \ldots, t_k, \infty\}. Write such a distribution through its discrete hazards hj=P(T=tj∣T≥tj)∈[0,1]h_j = P(T = t_j \mid T \ge t_j) \in [0, 1], which give p(tj)=hj∏l<j(1−hl)p(t_j) = h_j \prod_{l < j}(1 - h_l) and P(T>t)=∏l: tl≤t(1−hl)P(T > t) = \prod_{l:\, t_l \le t}(1 - h_l). Every vector h∈[0,1]kh \in [0, 1]^k comes from exactly one such distribution, with the remaining mass ∏l≤k(1−hl)\prod_{l \le k}(1 - h_l) at ∞\infty, and every such distribution has a vector hh (if P(T≥tj)=0P(T \ge t_j) = 0, set hj=1h_j = 1; then L=0L = 0 anyway). Substitute: the event of subject ii at tjt_j contributes hj∏l<j(1−hl)h_j \prod_{l < j}(1 - h_l), and a censored subject with tj≤yi<tj+1t_j \le y_i < t_{j+1} contributes ∏l≤j(1−hl)\prod_{l \le j}(1 - h_l). Collect the factors. hjh_j appears once for each event at tjt_j, so djd_j times. (1−hl)(1 - h_l) appears once for each event at a time tj>tlt_j > t_l and once for each censored subject with yi≥tly_i \ge t_l, that is, once for each subject with yi≥tly_i \ge t_l except the dld_l events at tlt_l. That count is nl−dln_l - d_l. So

L=∏j=1khjdj(1−hj)nj−dj.L = \prod_{j=1}^{k} h_j^{d_j}(1 - h_j)^{n_j - d_j}.

The factors depend on separate variables. For d≥1d \ge 1 and n≥dn \ge d, the function h↦hd(1−h)n−dh \mapsto h^d (1 - h)^{n - d} on [0,1][0, 1] has the unique maximizer h=d/nh = d/n: its logarithm dlog⁡h+(n−d)log⁡(1−h)d \log h + (n - d)\log(1 - h) is strictly concave on (0,1)(0, 1) with derivative d/h−(n−d)/(1−h)d/h - (n - d)/(1 - h), which vanishes only at h=d/nh = d/n (if n=dn = d, the function hdh^d is increasing and the maximizer is h=1=d/nh = 1 = d/n). So the unique maximizer has hj=dj/njh_j = d_j / n_j, and its survival function is ∏tj≤t(1−dj/nj)=S^(t)\prod_{t_j \le t}(1 - d_j/n_j) = \hat S(t).

Combining the steps: every FF has L(F)≤L(F∗)≤L(F^)L(F) \le L(F^*) \le L(\hat F), where F^\hat F is the distribution of Step 2. Equality throughout forces FF to have no mass in any (tj−1,tj)(t_{j-1}, t_j) or in (tk,y(n)](t_k, y_{(n)}] (Step 1) and to have the hazards dj/njd_j/n_j at the tjt_j (Step 2), which together fix SFS_F on [0,y(n)][0, y_{(n)}] to be S^\hat S. Beyond y(n)y_{(n)}, when the largest observation is censored, LL does not depend on where the mass S^(y(n))\hat S(y_{(n)}) lies, so SS is not identified there. □\square

Claim 3 (redistribute to the right). Order the subjects by time, with events before censorings at equal times, as positions 1,…,n1, \ldots, n. Give each subject mass 1/n1/n. Go through the positions in order; at a censored subject at position p<np < n, split its current mass equally among the subjects at positions p+1,…,np + 1, \ldots, n and set its own mass to 00. Let S~(t)=1−(total final mass of events with yi≤t)\tilde S(t) = 1 - (\text{total final mass of events with } y_i \le t). Then S~(tj)=S^(tj)\tilde S(t_j) = \hat S(t_j) for every jj.

Proof. Event subjects never pass mass on, and redistribution keeps the total mass equal to 11. Call the subjects at positions p,…,np, \ldots, n the tail at pp.

Invariant: when the pass reaches position pp, all subjects in the tail at pp hold the same mass mm, and the tail holds total mass 1−(mass of events at positions<p)1 - (\text{mass of events at positions} < p). At p=1p = 1 this holds with m=1/nm = 1/n. If position pp is an event, nothing moves, and the tail at p+1p + 1 still has equal masses and total 1−(event mass at positions<p+1)1 - (\text{event mass at positions} < p + 1). If position pp is censored and p<np < n, it gives m/(n−p)m/(n - p) to each of the n−pn - p later subjects, which all held mm; they now hold m(n−p+1)/(n−p)m(n - p + 1)/(n - p) each, equal again, and their total is (n−p+1)m(n - p + 1)m, the old total of the tail at pp. Censored subjects keep no mass, so the second part also holds.

Now take an event time tjt_j and let pp be the first position with y=tjy = t_j. By the ordering, the tail at pp is exactly the njn_j subjects with yi≥tjy_i \ge t_j, and its first djd_j positions are the events at tjt_j. By the invariant the njn_j subjects hold equal mass mjm_j and total njmj=1−(event mass at times<tj)=S~(tj−)n_j m_j = 1 - (\text{event mass at times} < t_j) = \tilde S(t_j -). The djd_j events at tjt_j come next, so nothing changes their mass before they are passed, and they keep mjm_j each to the end. So

S~(tj)=S~(tj−)−djmj=S~(tj−)(1−djnj).\tilde S(t_j) = \tilde S(t_j -) - d_j m_j = \tilde S(t_j -)\left(1 - \frac{d_j}{n_j}\right).

Since S~\tilde S is constant between event times and S~(t1−)=1\tilde S(t_1 -) = 1, induction on jj gives S~(tj)=∏l≤j(1−dl/nl)=S^(tj)\tilde S(t_j) = \prod_{l \le j}(1 - d_l/n_l) = \hat S(t_j). □\square

Cost. Line L1 sorts nn keys in Θ(nlog⁡n)\Theta(n \log n) comparisons. Each iteration of the inner loop of line L6 advances ii, so lines L4 to L8 run nn inner steps and at most nn outer steps, each with O(1)O(1) arithmetic. The total is Θ(nlog⁡n)\Theta(n \log n) in the worst case.

Complexity

The sort in line L1 costs Θ(nlog⁡n)\Theta(n \log n) comparisons in the worst case. The pass of lines L4 to L8 visits each subject once and does O(1)O(1) arithmetic per subject and per distinct time, so it costs Θ(n)\Theta(n). The output has k≤nk \le n rows. The total is Θ(nlog⁡n)\Theta(n \log n) time and Θ(n)\Theta(n) extra space in the real RAM model. If the data arrive sorted, the cost is Θ(n)\Theta(n). After the pass, a value S^(t)\hat S(t) costs O(log⁡k)O(\log k) by a binary search over the step times.

With exact rational arithmetic the numbers grow: the denominator of S^(tj)\hat S(t_j) divides n1n2⋯njn_1 n_2 \cdots n_j, so the bit size of S^\hat S can grow linearly in kk. In floating point the product of kk factors in (0,1](0, 1] has a relative error of at most about 3k3k units in the last place (one rounding each for d/rd/r, the subtraction and the product), and no cancellation grows the error. For very long products the sum of log⁡(1−dj/nj)\log(1 - d_j/n_j), computed with log1p, avoids underflow.

Properties

  • No censoring. If every δi=1\delta_i = 1, then nj+1=nj−djn_{j+1} = n_j - d_j, the product telescopes, and S^(t)=#{i:yi>t}/n\hat S(t) = \#\{i : y_i > t\}/n, one minus the empirical distribution function.
  • Self-consistency. For t≤y(n)t \le y_{(n)}, S^(t)=1n[#{i:yi>t}+∑i: δi=0, yi≤tS^(t)S^(yi)]\hat S(t) = \frac{1}{n}\left[\#\{i : y_i > t\} + \sum_{i:\, \delta_i = 0,\, y_i \le t} \frac{\hat S(t)}{\hat S(y_i)}\right]. Each censored subject contributes its conditional probability of being still alive at tt, estimated by S^\hat S itself (Efron 1967). The Turnbull estimator solves the same kind of equation for interval-censored data.
  • Nonparametric MLE. It maximizes the likelihood ∏iP(T=yi)δiP(T>yi)1−δi\prod_i P(T = y_i)^{\delta_i} P(T > y_i)^{1 - \delta_i} over all distributions, as proved in the correctness file.
  • Consistency and limit law. If P(Y>τ)>0P(Y > \tau) > 0, then sup⁡t≤τ∣S^(t)−S(t)∣→0\sup_{t \le \tau} |\hat S(t) - S(t)| \to 0 almost surely, and n(S^−S)\sqrt{n}(\hat S - S) converges on [0,τ][0, \tau] to a Gaussian process with variance S(t)2∫0tdF(u)S(u) S(u−) G(u−)S(t)^2 \int_0^t \frac{dF(u)}{S(u)\, S(u-)\, G(u-)} for continuous SS, where GG is the censoring survival function (Breslow and Crowley 1974; Andersen et al. 1993, Chapter IV). The Greenwood formula estimates this variance.
  • Relation to Nelson-Aalen. exp⁡(−H^(t))≥S^(t)\exp(-\hat H(t)) \ge \hat S(t), where H^\hat H is the Nelson-Aalen estimator, because e−x≥1−xe^{-x} \ge 1 - x for every factor. The two agree closely when every dj/njd_j / n_j is small.

Variants and improvements

  • Delayed entry (left truncation). If subject ii enters observation at time viv_i, the risk set at tjt_j is {i:vi<tj≤yi}\{i : v_i < t_j \le y_i\}. The same product with these njn_j estimates S(t)/S(v)S(t)/S(v) for t>v=min⁡ivit > v = \min_i v_i. Small risk sets early in time can make this estimate unstable.
  • Life-table (actuarial) estimate. For grouped data in intervals, use nj−cj/2n_j - c_j/2 as the effective number at risk, on the reading that censored subjects were at risk for half the interval.
  • Survival from the cumulative hazard. exp⁡(−H^(t))\exp(-\hat H(t)), with H^\hat H the Nelson-Aalen estimate, is an alternative estimate of SS. It never reaches 00.
  • Interval censoring. When event times are known only to lie in intervals, the nonparametric MLE is the Turnbull estimator, which reduces to Kaplan-Meier for exact and right-censored data.
  • Competing risks. With several causes of failure, 1−S^1 - \hat S computed with the other causes treated as censoring overestimates the cumulative incidence of one cause. The Aalen-Johansen estimator gives the correct estimate; see competing risks.
  • Covariates. The Cox model with the Breslow estimator gives a survival curve for each covariate value. Without covariates it reduces to exp⁡(−H^)\exp(-\hat H).
  • Dependent censoring. If censoring depends on measured covariates, inverse probability of censoring weights, in the style of inverse probability weighting, restore consistency.

When to use it

Use Kaplan-Meier to describe the survival of one group with right-censored data, to read off the median survival time or the survival probability at a fixed time, and as the first plot of any survival analysis. Report the number at risk under the plot, because the right end of the curve rests on few subjects. To compare groups, use the log-rank test, not the visual gap between curves. For pointwise confidence intervals use the Greenwood formula, preferably on the log-log scale.

Pitfalls

  • Dropping censored subjects, or treating them as events. Both bias S^\hat S downward, as the 6-MP example shows: medians of 10 and 16 weeks against 23.
  • Ties between events and censorings. Count a censoring at tjt_j in the risk set at tjt_j. Removing it first changes the factor at tjt_j.
  • The tail. After the largest time, if it is censored, the estimate is undefined. The mean survival time ∫0∞S^(t) dt\int_0^\infty \hat S(t)\, dt is then undefined too; report the restricted mean ∫0τS^(t) dt\int_0^\tau \hat S(t)\, dt with a stated τ\tau.
  • Informative censoring. If sicker patients leave the study earlier, S^\hat S is biased upward, and the data cannot reveal this (Tsiatis 1975): the bias is not testable from (yi,δi)(y_i, \delta_i) alone.
  • Competing risks. Treating death from other causes as censoring and reporting 1−S^1 - \hat S as the risk of one cause overestimates that risk.
  • Large steps at the end. When few subjects remain at risk, each event causes a large drop. Do not read the shape of the curve where njn_j is small.
  • Median. If S^\hat S never falls to 1/21/2, the median is not estimable, and the code returns no value. Do not replace it with the last time.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

kaplan_meier_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kaplan-meier-estimator/. The authors are listed in prov/FNVF5H.jsonl.

from collections.abc import Sequence
from fractions import Fraction
from typing import NamedTuple


class Step(NamedTuple):
    """One distinct event time t_j of the Kaplan-Meier table."""

    time: float
    at_risk: int  # n_j, the number with y_i >= t_j
    events: int  # d_j, the number of events at t_j
    survival: float  # S-hat(t_j), a Fraction when exact=True


class KaplanMeier:
    """The Kaplan-Meier estimate S-hat as a right-continuous step function.

    steps holds one row per distinct event time. t_max is the largest observed
    time. S-hat(t) is defined for t <= t_max, and also for t > t_max when the
    largest time is an event or S-hat has reached 0; otherwise S-hat is
    undefined beyond t_max and __call__ raises ValueError there.
    """

    def __init__(self, steps: list[Step], t_max: float, last_is_event: bool, one) -> None:
        self.steps = steps
        self.t_max = t_max
        self.last_is_event = last_is_event
        self._one = one

    def __call__(self, t: float):
        s = self._one
        for step in self.steps:
            if step.time > t:
                break
            s = step.survival
        if t > self.t_max and not self.last_is_event and s != 0:
            raise ValueError("S-hat is undefined after the largest time when that time is censored")
        return s

    def median(self):
        """The smallest event time t with S-hat(t) <= 1/2, or None if S-hat stays above 1/2."""
        for step in self.steps:
            if step.survival <= self._one / 2:
                return step.time
        return None


def kaplan_meier(times: Sequence[float], events: Sequence[int], exact: bool = False) -> KaplanMeier:
    """Kaplan-Meier estimate from right-censored data.

    times[i] is the observed time y_i = min(T_i, C_i) and events[i] is 1 when
    y_i is an event time and 0 when it is a censoring time. A censoring tied
    with an event counts as at risk at that time. With exact=True the survival
    values are Fractions. Cost: one sort, O(n log n), and one O(n) scan.
    """
    n = len(times)
    if n == 0 or len(events) != n:
        raise ValueError("need the same positive number of times and event flags")
    if any(e not in (0, 1) for e in events):
        raise ValueError("event flags must be 0 or 1")
    one = Fraction(1) if exact else 1.0
    order = sorted(range(n), key=lambda k: times[k])  # @line L1
    r, s, out = n, one, []  # @line L2
    i = 0  # @line L3
    while i < n:  # @line L4
        t, d, c = times[order[i]], 0, 0  # @line L5
        while i < n and times[order[i]] == t:  # @line L6
            if events[order[i]]:
                d += 1
            else:
                c += 1
            i += 1
        if d > 0:  # @line L7
            s = s * (one - Fraction(d, r)) if exact else s * (1.0 - d / r)
            out.append(Step(t, r, d, s))
        r -= d + c  # @line L8
    last = times[order[-1]]
    last_is_event = any(times[k] == last and events[k] for k in range(n))
    return KaplanMeier(out, last, last_is_event, one)  # @line L9


def greenwood_variance(km: KaplanMeier, t: float):
    """Greenwood's estimate S-hat(t)^2 * sum over t_j <= t of d_j / (n_j (n_j - d_j)).

    A term with d_j = n_j makes S-hat(t) = 0, and the estimate is then 0.
    """
    s = km(t)
    if s == 0:
        return s
    total = 0 * s
    for step in km.steps:
        if step.time > t:
            break
        n, d = step.at_risk, step.events
        total += Fraction(d, n * (n - d)) if isinstance(s, Fraction) else d / (n * (n - d))
    return s * s * total
test_kaplan_meier_estimator.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kaplan-meier-estimator/. The authors are listed in prov/FNVF5H.jsonl.

import math
import random
from fractions import Fraction

import pytest

from kaplan_meier_estimator import greenwood_variance, kaplan_meier

# 6-MP arm of Freireich et al. (1963), as listed by Gehan (1965). 0 marks a censored time.
MP_T = [6, 6, 6, 6, 7, 9, 10, 10, 11, 13, 16, 17, 19, 20, 22, 23, 25, 32, 32, 34, 35]
MP_D = [1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0]
PL_T = [1, 1, 2, 2, 3, 4, 4, 5, 5, 8, 8, 8, 8, 11, 11, 12, 12, 15, 17, 22, 23]


def product_limit(times, events, t):
    """The product-limit formula written out: product over event times s <= t of (1 - d(s)/n(s))."""
    s = Fraction(1)
    for u in sorted({y for y, e in zip(times, events) if e}):
        if u > t:
            break
        n = sum(1 for y in times if y >= u)
        d = sum(1 for y, e in zip(times, events) if y == u and e)
        s *= Fraction(n - d, n)
    return s


def redistribute_to_the_right(times, events):
    """Efron's construction: start with mass 1/n on each subject, ordered by time with
    events before censorings at equal times; each censored subject, in turn, gives its
    mass in equal parts to every subject after it. Returns 1 - (event mass up to t) as a function."""
    n = len(times)
    order = sorted(range(n), key=lambda k: (times[k], -events[k]))
    mass = [Fraction(1, n)] * n
    for pos, k in enumerate(order):
        if not events[k] and pos < n - 1:
            share = mass[pos] / (n - 1 - pos)
            for later in range(pos + 1, n):
                mass[later] += share
            mass[pos] = Fraction(0)

    def surv(t):
        return 1 - sum((mass[p] for p, k in enumerate(order) if events[k] and times[k] <= t), Fraction(0))

    return surv


def random_data(rng, n, tmax, pcens):
    times = [rng.randint(1, tmax) for _ in range(n)]
    events = [0 if rng.random() < pcens else 1 for _ in range(n)]
    return times, events


def test_six_mp_table() -> None:
    km = kaplan_meier(MP_T, MP_D, exact=True)
    rows = [(s.time, s.at_risk, s.events, s.survival) for s in km.steps]
    assert rows == [
        (6, 21, 3, Fraction(6, 7)),
        (7, 17, 1, Fraction(96, 119)),
        (10, 15, 1, Fraction(64, 85)),
        (13, 12, 1, Fraction(176, 255)),
        (16, 11, 1, Fraction(32, 51)),
        (22, 7, 1, Fraction(64, 119)),
        (23, 6, 1, Fraction(160, 357)),
    ]
    assert km(5) == 1 and km(9) == Fraction(96, 119) and km(34) == Fraction(160, 357)
    assert km.median() == 23
    assert math.isclose(math.sqrt(greenwood_variance(km, 23)), 0.13459, abs_tol=5e-5)
    assert math.isclose(math.sqrt(greenwood_variance(km, 6)), 0.07636, abs_tol=5e-5)
    # The largest time, 35, is censored, so S-hat is undefined after 35.
    assert km(35) == Fraction(160, 357)
    with pytest.raises(ValueError):
        km(35.5)


def test_placebo_arm_is_the_empirical_survival_function() -> None:
    km = kaplan_meier(PL_T, [1] * len(PL_T), exact=True)
    assert [s.survival for s in km.steps] == [Fraction(k, 21) for k in (19, 17, 16, 14, 12, 8, 6, 4, 3, 2, 1, 0)]
    assert km.median() == 8
    assert km(100) == 0


def test_against_product_limit_formula() -> None:
    rng = random.Random(20261114)
    for _ in range(300):
        n = rng.randint(1, 25)
        times, events = random_data(rng, n, rng.randint(1, 12), rng.random())
        km = kaplan_meier(times, events, exact=True)
        t_max = max(times)
        for t in range(0, t_max + 2):
            try:
                got = km(t)
            except ValueError:
                assert t > t_max and not any(e for y, e in zip(times, events) if y == t_max)
                continue
            assert got == product_limit(times, events, t)


def test_no_censoring_gives_empirical_survival() -> None:
    rng = random.Random(7)
    for _ in range(200):
        n = rng.randint(1, 30)
        times = [rng.randint(1, 10) for _ in range(n)]
        km = kaplan_meier(times, [1] * n, exact=True)
        for t in range(0, 12):
            assert km(t) == Fraction(sum(1 for y in times if y > t), n)


def test_equals_redistribute_to_the_right() -> None:
    rng = random.Random(1967)
    for _ in range(300):
        n = rng.randint(1, 20)
        times, events = random_data(rng, n, rng.randint(1, 8), rng.random())
        km = kaplan_meier(times, events, exact=True)
        rtr = redistribute_to_the_right(times, events)
        for step in km.steps:
            assert step.survival == rtr(step.time)


def test_self_consistency_equation() -> None:
    # Efron (1967): S(t) = (1/n) [#{y_i > t} + sum over censored y_i <= t of S(t) / S(y_i)].
    rng = random.Random(831)
    for _ in range(200):
        n = rng.randint(1, 20)
        times, events = random_data(rng, n, 9, rng.random())
        km = kaplan_meier(times, events, exact=True)
        for t in range(0, max(times) + 1):
            s = km(t)
            rhs = sum(1 for y in times if y > t) + sum(
                (s / km(y) for y, e in zip(times, events) if not e and y <= t and km(y) > 0), Fraction(0)
            )
            assert s == rhs / n


def test_float_and_exact_agree() -> None:
    rng = random.Random(3)
    for _ in range(100):
        times, events = random_data(rng, 40, 15, 0.4)
        a = kaplan_meier(times, events)
        b = kaplan_meier(times, events, exact=True)
        for x, y in zip(a.steps, b.steps):
            assert x[:3] == y[:3] and math.isclose(x.survival, float(y.survival), rel_tol=1e-12, abs_tol=1e-15)


def log_lik(times, events, support, probs, tail):
    """Log-likelihood of a distribution with mass probs[j] at support[j] and mass tail after support[-1]."""
    total = 0.0
    for y, e in zip(times, events):
        if e:
            p = probs[support.index(y)]
        else:
            p = sum(q for s, q in zip(support, probs) if s > y) + tail
        if p <= 0:
            return -math.inf
        total += math.log(p)
    return total


def test_kaplan_meier_maximizes_the_likelihood() -> None:
    rng = random.Random(1958)
    for _ in range(60):
        times, events = random_data(rng, 15, 10, 0.4)
        if not any(events):
            continue
        km = kaplan_meier(times, events)
        support = [s.time for s in km.steps]
        prev, probs = 1.0, []
        for s in km.steps:
            probs.append(prev - s.survival)
            prev = s.survival
        best = log_lik(times, events, support, probs, prev)
        for _ in range(200):
            w = [rng.expovariate(1.0) for _ in range(len(support) + 1)]
            z = sum(w)
            alt = log_lik(times, events, support, [x / z for x in w[:-1]], w[-1] / z)
            assert alt <= best + 1e-9


def test_greenwood_without_censoring_is_binomial_variance() -> None:
    rng = random.Random(1926)
    for _ in range(200):
        n = rng.randint(2, 30)
        times = [rng.randint(1, 10) for _ in range(n)]
        km = kaplan_meier(times, [1] * n, exact=True)
        for t in range(0, 11):
            s = km(t)
            assert greenwood_variance(km, t) == s * (1 - s) / n


def test_last_time_rules_and_median() -> None:
    km = kaplan_meier([1, 2, 3], [1, 0, 1], exact=True)
    assert km(3) == 0 and km(10) == 0
    km = kaplan_meier([1, 2, 3], [1, 1, 0], exact=True)
    assert km(2) == Fraction(1, 3) and km(3) == Fraction(1, 3)
    with pytest.raises(ValueError):
        km(4)
    assert km.median() == 2
    assert kaplan_meier([5, 6], [0, 0]).median() is None
    # A censoring tied with an event stays in the risk set at that time.
    km = kaplan_meier([2, 2, 4], [1, 0, 1], exact=True)
    assert km.steps[0].at_risk == 3 and km(2) == Fraction(2, 3)


def test_rejects_bad_input() -> None:
    with pytest.raises(ValueError):
        kaplan_meier([], [])
    with pytest.raises(ValueError):
        kaplan_meier([1, 2], [1])
    with pytest.raises(ValueError):
        kaplan_meier([1, 2], [1, 2])

History

Edward Kaplan and Paul Meier each wrote a paper on the estimation of survival from incomplete observations, and they published them as one joint paper in the Journal of the American Statistical Association in 1958. The paper gives the product-limit estimate, shows that it is the maximum likelihood estimate among all distributions, and derives its variance by the same argument as Greenwood (1926). Actuaries had long used products of conditional survival probabilities in life tables. Efron (1967) gave the redistribute-to-the-right description and the self-consistency equation while studying two-sample tests with censored data. Breslow and Crowley (1974) proved the weak convergence of n(S^−S)\sqrt{n}(\hat S - S), and the counting process approach of Aalen and of Gill in the late 1970s and early 1980s gave the martingale proofs collected by Andersen, Borgan, Gill and Keiding (1993).

References

  1. E. L. Kaplan and Paul Meier, Nonparametric estimation from incomplete observations, Journal of the American Statistical Association 53(282), 1958, pp. 457 to 481 (the product-limit estimate, its derivation as a maximum likelihood estimate, and its variance)
  2. Bradley Efron, The two sample problem with censored data, Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, Vol. 4, University of California Press, 1967, pp. 831 to 853 (the redistribute-to-the-right construction and self-consistency on pp. 842 and 843)
  3. John P. Klein and Melvin L. Moeschberger, Survival Analysis, Techniques for Censored and Truncated Data, 2nd edition, Springer, 2003, Chapter 4 (nonparametric estimation of basic quantities for right-censored and left-truncated data)
  4. Per Kragh Andersen, Ørnulf Borgan, Richard D. Gill and Niels Keiding, Statistical Models Based on Counting Processes, Springer, 1993, Chapter IV (nonparametric estimation, including the product-limit estimator, its consistency and its weak convergence)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example