Algorithm Search⌘K

Algorithmadvanced

Aalen-Johansen estimator

Also called cumulative incidence function estimator.

Estimates the transition probabilities of a finite-state Markov process under censoring, and so the cumulative incidence of each cause with competing risks.

Time
Θ(n log n + m K) worst
Space
Θ(n + m K) extra
Where
K = the number of causes; m = the number of distinct event times; n = the number of subjects
Properties
deterministicexactofflineiterative
Origin
Odd O. Aalen, Søren Johansen, 1978

The Aalen-Johansen estimator estimates the probabilities of a process that moves between a finite set of states, from data in which subjects are censored. Its most common use is competing risks: from the time to the first event and its cause, it estimates the cumulative incidence Fk(t)=P(T≤t,cause=k)F_k(t) = P(T \le t, \text{cause} = k) of each cause kk as

F^k(t)=∑j: tj≤tS^(tj−1) dkjnj,\hat F_k(t) = \sum_{j:\, t_j \le t} \hat S(t_{j-1})\,\frac{d_{kj}}{n_j},

where tjt_j are the distinct event times, njn_j the number at risk at tjt_j, dkjd_{kj} the number of events of cause kk at tjt_j and S^\hat S the all-cause Kaplan-Meier estimate. With one cause it is one minus Kaplan-Meier. The estimates of the KK causes and S^\hat S add up to 11 exactly. In general, it is the product over event times of I+dA^I + d\hat A, where dA^d\hat A is the matrix of Nelson-Aalen increments of the transitions.

In plain words

Follow a group of patients in time. At each time when someone has an event, look at the patients still free of any event. A fraction of them has an event of cause 1, a fraction has cause 2, and so on. The chance of having a cause 1 event at that moment, for a patient at the start, is the chance of still being event-free just before, times the fraction with cause 1. Add these chances over time to get the cumulative incidence of cause 1. A patient who had an event of cause 2 does not stay in the pool, so it cannot later count as a cause 1 event. This is the difference from one minus Kaplan-Meier with cause 2 treated as censored, which pretends that such a patient could still have cause 1.

The problem

Input. Observations (yi,ci)(y_i, c_i) for i=1,…,ni = 1, \ldots, n, where yiy_i is the observed time and ci=k∈{1,…,K}c_i = k \in \{1, \ldots, K\} if subject ii had an event of cause kk at yiy_i, or ci=0c_i = 0 if it was censored at yiy_i.

Model. The pairs (time to the first event, cause) are independent across subjects, and censoring is independent: among the subjects still at risk at tt, the cause-specific hazards are those of the whole population. No form is assumed for the hazards.

Output. For each distinct event time tjt_j (of any cause), the number at risk nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\}, the counts d1j,…,dKjd_{1j}, \ldots, d_{Kj}, the all-cause survival S^(tj)\hat S(t_j) and the cumulative incidences F^1(tj),…,F^K(tj)\hat F_1(t_j), \ldots, \hat F_K(t_j). The estimates are right-continuous step functions, S^=1\hat S = 1 and F^k=0\hat F_k = 0 before t1t_1.

Ties. A censored time equal to an event time counts as at risk at that time, as for Kaplan-Meier. Events of different causes at the same time all use S^(tj−1)\hat S(t_{j-1}), the survival just before tjt_j.

The algorithm

  1. AALEN-JOHANSEN(y[1..n], c[1..n], K)
  2. 1sort the indices 1..n by increasing y
  3. 2S ← 1; F[1..K] ← 0; r ← n; out ← empty list
  4. 3for each distinct time t in that order
  5. 4count d[k] ← #{i : y_i = t, c_i = k} for each k, and leave ← #{i : y_i = t}
  6. 5if d[1] + ... + d[K] > 0
  7. 6F[k] ← F[k] + S · d[k] / r for each k ▷ uses S before the update
  8. 7S ← S · (1 - (d[1] + ... + d[K]) / r); append (t, r, d, S, F) to out
  9. 8r ← r - leave

Line L1 is the only sort. The variable rr is the size of the risk set: it starts at nn, and line L8 removes the subjects with time tt only after the time is processed, so a subject censored at tt counts at tt. Line L6 must come before line L7, because the increment of F^k\hat F_k uses the survival just before tt. The reference code works in Fractions, so its output is exact for exact input. It also has the general form for a multi-state model, described under the variants.

Example

Six subjects. Times 1,2,2,3,4,51, 2, 2, 3, 4, 5 with causes 1,2,0,1,0,21, 2, 0, 1, 0, 2.

tt rr d1d_1 d2d_2 leave F^1\hat F_1 F^2\hat F_2 S^\hat S
1 6 1 0 1 1⋅16=161 \cdot \frac16 = \frac16 0 56\frac56
2 5 0 1 2 16\frac16 56⋅15=16\frac56 \cdot \frac15 = \frac16 56⋅45=23\frac56 \cdot \frac45 = \frac23
3 3 1 0 1 16+23⋅13=718\frac16 + \frac23 \cdot \frac13 = \frac{7}{18} 16\frac16 23⋅23=49\frac23 \cdot \frac23 = \frac49
4 2 0 0 1 no row
5 1 0 1 1 718\frac{7}{18} 16+49=1118\frac16 + \frac49 = \frac{11}{18} 00

At every row F^1+F^2+S^=1\hat F_1 + \hat F_2 + \hat S = 1. At t=2t = 2 the censored subject is in the risk set of 5, and only then does rr fall by 2. Treating cause 2 as censoring gives 1−S^1∗(3)=1−56⋅23=491 - \hat S_1^\ast(3) = 1 - \frac56\cdot\frac23 = \frac49, larger than F^1(3)=718\hat F_1(3) = \frac{7}{18}. The competing risks page shows the naive values next to these.

An illness-death model. States 0 (healthy), 1 (ill) and 2 (dead). Four subjects start healthy. Subject A becomes ill at time 1 and dies at 3. Subject B dies at 2 without illness. Subject C becomes ill at 2 and is censored at 4. Subject D is censored healthy at 2.5. The first row of the product ∏(I+dA^)\prod(I + d\hat A) is the estimate of (P(healthy),P(ill),P(dead))(P(\text{healthy}), P(\text{ill}), P(\text{dead})) at time tt for a subject healthy at 0:

tt transitions (at risk) row 0 of I+dA^I + d\hat A row 1 P^0⋅(t)\hat P_{0\cdot}(t)
1 0 to 1: one of 4 (34,14,0)(\frac34, \frac14, 0) (0,1,0)(0, 1, 0) (34,14,0)(\frac34, \frac14, 0)
2 0 to 1 and 0 to 2: one each of 3 (13,13,13)(\frac13, \frac13, \frac13) (0,1,0)(0, 1, 0) (14,12,14)(\frac14, \frac12, \frac14)
3 1 to 2: one of 2 (1,0,0)(1, 0, 0) (0,12,12)(0, \frac12, \frac12) (14,14,12)(\frac14, \frac14, \frac12)

The probability of being ill at time 3 is 14\frac14. It cannot be read from any single Kaplan-Meier curve.

A simulation. The tests draw 2000 subjects with cause-specific hazards 11 and 0.50.5 and an independent censoring rate 0.30.3, so F1(t)=23(1−e−1.5t)F_1(t) = \frac23(1 - e^{-1.5t}). At t=0.2,0.5,1t = 0.2, 0.5, 1 and 22 both estimates lie within 4 standard errors of the truth. This is a measurement for one seed, not a proof of consistency.

Correctness

The proof in proofs/correctness.md shows six things. First, the pass of lines L3 to L8 keeps r=njr = n_j at the start of each time, so every row is (tj,nj,d⋅j,S^(tj),F^⋅(tj))(t_j, n_j, d_{\cdot j}, \hat S(t_j), \hat F_\cdot(t_j)). Second, with one cause F^1=1−S^\hat F_1 = 1 - \hat S. Third, S^(t)+∑kF^k(t)=1\hat S(t) + \sum_k \hat F_k(t) = 1 for every tt. Fourth, 1−S^k∗(t)≥F^k(t)1 - \hat S_k^\ast(t) \ge \hat F_k(t), where S^k∗\hat S_k^\ast is Kaplan-Meier with the other causes censored. Fifth, without censoring F^k(t)\hat F_k(t) is the fraction of subjects with an event of cause kk by tt. Sixth, for the general product integral every row of P^\hat P sums to 11 with entries in [0,1][0, 1], the competing risks case gives lines L6 and L7, and without censoring P^0h(t)\hat P_{0h}(t) is the fraction of subjects in state hh at tt. The consistency and the limit law are cited, not proved.

Proof: The pass computes the cumulative incidences, which reduce to one minus Kaplan-Meier for one cause, add up with the survival to one, lie below one minus the cause-specific Kaplan-Meier, and equal the empirical proportions without censoringfull

Let the data be (yi,ci)(y_i, c_i), i=1,…,ni = 1, \ldots, n, with ci=0c_i = 0 for a censored subject and ci=k∈{1,…,K}c_i = k \in \{1, \ldots, K\} for an event of cause kk at yiy_i. Let t1<⋯<tmt_1 < \cdots < t_m be the distinct event times of any cause, nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\}, dkjd_{kj} the number of events of cause kk at tjt_j and dj=∑kdkjd_j = \sum_k d_{kj}. The estimates are

S^(t)=∏tj≤t(1−djnj),F^k(t)=∑tj≤tS^(tj−1) dkjnj,\hat S(t) = \prod_{t_j \le t}\Bigl(1 - \frac{d_j}{n_j}\Bigr), \qquad \hat F_k(t) = \sum_{t_j \le t} \hat S(t_{j-1})\,\frac{d_{kj}}{n_j},

with S^(t0)=1\hat S(t_0) = 1. Here S^(tj−1)=S^(tj−)\hat S(t_{j-1}) = \hat S(t_j-), the value just before tjt_j, because S^\hat S only jumps at event times.

Claim 1 (the pass computes the sums). Every row that the pass appends is (tj,nj,(d1j,…,dKj),S^(tj),(F^1(tj),…,F^K(tj)))(t_j, n_j, (d_{1j}, \ldots, d_{Kj}), \hat S(t_j), (\hat F_1(t_j), \ldots, \hat F_K(t_j))), one row for each jj, in order.

Proof. After the sort of line L1, the inner loop of line L4 reads exactly the subjects at the current distinct time uu and counts the events of each cause. Invariant: at the start of the group at uu, the variable at_risk is #{i:yi≥u}\#\{i : y_i \ge u\}, and SS and FF hold S^\hat S and F^k\hat F_k just before uu. It holds at the first group, with nn subjects at risk, S=1S = 1 and F=0F = 0. If u=tju = t_j, line L6 adds S dkj/njS\,d_{kj}/n_j to each FkF_k while SS still holds S^(tj−)\hat S(t_j-), and line L7 then multiplies SS by 1−dj/nj1 - d_j/n_j. Line L8 removes all the subjects at uu, events and censored alike, so at_risk becomes the count at the next distinct time. □\square

The order of lines L6 and L7 matters: if SS were updated first, the increment would use S^(tj)\hat S(t_j) and the sum of Claim 3 would fail.

Claim 2 (one cause). If K=1K = 1, then F^1(t)=1−S^(t)\hat F_1(t) = 1 - \hat S(t), where S^\hat S is the Kaplan-Meier estimator of the event time.

Proof. With one cause, d1j=djd_{1j} = d_j, and the increment of F^1\hat F_1 at tjt_j is S^(tj−1) dj/nj=S^(tj−1)−S^(tj−1)(1−dj/nj)=S^(tj−1)−S^(tj)\hat S(t_{j-1})\,d_j/n_j = \hat S(t_{j-1}) - \hat S(t_{j-1})(1 - d_j/n_j) = \hat S(t_{j-1}) - \hat S(t_j). The sum telescopes to S^(t0)−S^(t)=1−S^(t)\hat S(t_0) - \hat S(t) = 1 - \hat S(t). □\square

Claim 3 (the sum is one). For every tt, S^(t)+∑k=1KF^k(t)=1\hat S(t) + \sum_{k=1}^K \hat F_k(t) = 1.

Proof. Add the increments over kk. The increment of ∑kF^k\sum_k \hat F_k at tjt_j is S^(tj−1) dj/nj=S^(tj−1)−S^(tj)\hat S(t_{j-1})\,d_j/n_j = \hat S(t_{j-1}) - \hat S(t_j), as in Claim 2, so ∑kF^k(t)=1−S^(t)\sum_k \hat F_k(t) = 1 - \hat S(t). □\square

Claim 4 (one minus the cause-specific Kaplan-Meier overstates). Let S^k\hat S_k be the Kaplan-Meier estimator computed with the events of the other causes treated as censored. Then 1−S^k(t)≥F^k(t)1 - \hat S_k(t) \ge \hat F_k(t) for every tt.

Proof. A subject with an event of another cause at tlt_l is censored at tlt_l in S^k\hat S_k, and a censored subject is at risk at its own time and leaves after it. So the risk set of S^k\hat S_k at tjt_j is the same set {i:yi≥tj}\{i : y_i \ge t_j\}, with njn_j members, and S^k(t)=∏tj≤t(1−dkj/nj)\hat S_k(t) = \prod_{t_j \le t}(1 - d_{kj}/n_j). Each factor 1−dkj/nj1 - d_{kj}/n_j is at least 1−dj/nj≥01 - d_j/n_j \ge 0, so S^k(t)≥S^(t)\hat S_k(t) \ge \hat S(t) for every tt. As in Claim 2, 1−S^k1 - \hat S_k has the increment S^k(tj−1) dkj/nj\hat S_k(t_{j-1})\,d_{kj}/n_j at tjt_j, and F^k\hat F_k has the increment S^(tj−1) dkj/nj\hat S(t_{j-1})\,d_{kj}/n_j, which is not larger. Add the increments. □\square

The inequality is strict at tt as soon as an event of another cause comes before an event of cause kk in (0,t](0, t] while S^\hat S is still positive. With the hand example of the page, 1−S^1(3)=4/91 - \hat S_1(3) = 4/9 and F^1(3)=7/18\hat F_1(3) = 7/18.

The same inequality holds in the population. With cause-specific hazards hkh_k, Hk(t)=∫0thkH_k(t) = \int_0^t h_k and H=∑kHkH = \sum_k H_k, we have Fk(t)=∫0te−H(u)hk(u) duF_k(t) = \int_0^t e^{-H(u)} h_k(u)\,du and 1−e−Hk(t)=∫0te−Hk(u)hk(u) du1 - e^{-H_k(t)} = \int_0^t e^{-H_k(u)} h_k(u)\,du, and e−H(u)≤e−Hk(u)e^{-H(u)} \le e^{-H_k(u)}.

Claim 5 (no censoring). If no subject is censored, then F^k(t)=#{i:yi≤t, ci=k}/n\hat F_k(t) = \#\{i : y_i \le t,\ c_i = k\}/n and S^(t)=#{i:yi>t}/n\hat S(t) = \#\{i : y_i > t\}/n.

Proof. Without censoring, every subject that leaves the risk set before tjt_j has an event, so nj=n−∑l<jdln_j = n - \sum_{l < j} d_l, and S^(tj−1)=∏l<j(nl−dl)/nl=nj/n\hat S(t_{j-1}) = \prod_{l < j}(n_l - d_l)/n_l = n_j/n because the product telescopes (nl+1=nl−dln_{l+1} = n_l - d_l). The increment of F^k\hat F_k at tjt_j is (nj/n)(dkj/nj)=dkj/n(n_j/n)(d_{kj}/n_j) = d_{kj}/n. Add the increments. □\square

Claim 6 (the product integral). Let P(t)=∏tj≤t(I+dA^(tj))P(t) = \prod_{t_j \le t}(I + d\hat A(t_j)), with dA^gh(tj)=Ngh(tj)/Yg(tj)d\hat A_{gh}(t_j) = N_{gh}(t_j)/Y_g(t_j) for g≠hg \ne h and dA^gg(tj)=−∑h≠gdA^gh(tj)d\hat A_{gg}(t_j) = -\sum_{h \ne g} d\hat A_{gh}(t_j), where Ngh(tj)N_{gh}(t_j) counts the transitions from gg to hh at tjt_j and Yg(tj)Y_g(t_j) counts the subjects in state gg just before tjt_j that are under observation at tjt_j. Then:

  1. every row of P(t)P(t) sums to 11 and every entry is in [0,1][0, 1];
  2. for the competing risks data (state 00 alive, state kk dead of cause kk), P00(t)=S^(t)P_{00}(t) = \hat S(t) and P0k(t)=F^k(t)P_{0k}(t) = \hat F_k(t);
  3. if every subject starts in state 00 and is followed until it reaches an absorbing state, P0h(t)P_{0h}(t) is the proportion of subjects in state hh at time tt.

Proof. (1) Each row of dA^d\hat A sums to 00, so each row of I+dA^I + d\hat A sums to 11. The off-diagonal entries are at least 00, and the diagonal entry 1−∑h≠gNgh/Yg1 - \sum_{h \ne g} N_{gh}/Y_g is at least 00 because the subjects that leave gg at tjt_j are among the YgY_g subjects in gg just before tjt_j. A product of matrices with entries at least 00 and row sums 11 has the same two properties, and then each entry is at most its row sum 11.

(2) For competing risks, Y0(tj)=njY_0(t_j) = n_j and N0k(tj)=dkjN_{0k}(t_j) = d_{kj}, and the states k≥1k \ge 1 are absorbing, so their rows of I+dA^I + d\hat A are rows of II. Row 00 of I+dA^(tj)I + d\hat A(t_j) is (1−dj/nj,d1j/nj,…,dKj/nj)(1 - d_j/n_j, d_{1j}/n_j, \ldots, d_{Kj}/n_j). Row 00 of the product obeys P00(tj)=P00(tj−1)(1−dj/nj)P_{00}(t_j) = P_{00}(t_{j-1})(1 - d_j/n_j) and P0k(tj)=P0k(tj−1)+P00(tj−1) dkj/njP_{0k}(t_j) = P_{0k}(t_{j-1}) + P_{00}(t_{j-1})\,d_{kj}/n_j, which are lines L7 and L6.

(3) Let ph(t)p_h(t) be the proportion of subjects in state hh at tt, and Yh′(tj)Y'_h(t_j) the number of subjects in hh just before tjt_j, so that ph(tj−)=Yh′(tj)/np_h(t_j-) = Y'_h(t_j)/n. Assume P0h(tj−)=ph(tj−)P_{0h}(t_j-) = p_h(t_j-) for every hh, which holds before the first transition. Row 00 of P(tj)=P(tj−)(I+dA^(tj))P(t_j) = P(t_j-)(I + d\hat A(t_j)) is

P0h(tj)=ph(tj−)−ph(tj−)∑h′≠hNhh′Yh+∑g≠hpg(tj−)NghYg.P_{0h}(t_j) = p_h(t_j-) - p_h(t_j-) \sum_{h' \ne h} \frac{N_{hh'}}{Y_h} + \sum_{g \ne h} p_g(t_j-) \frac{N_{gh}}{Y_g}.

A state gg with transitions out of it is not absorbing, and without censoring every subject in a state that is not absorbing is still under observation, so Yg=Yg′Y_g = Y'_g and pg(tj−)/Yg=1/np_g(t_j-)/Y_g = 1/n. So P0h(tj)=(Yh′−∑h′Nhh′+∑gNgh)/nP_{0h}(t_j) = (Y'_h - \sum_{h'} N_{hh'} + \sum_g N_{gh})/n, which is the number of subjects in hh just after tjt_j divided by nn. Induction over the transition times completes the proof. □\square

What is not proved here. Under independent censoring, F^k\hat F_k and PP are uniformly consistent, and n\sqrt n times the error converges to a Gaussian process (Aalen and Johansen 1978; Andersen, Borgan, Gill and Keiding 1993). We cite these results. The tests of the page check them only by simulation at a few time points.

Cost. One sort, Θ(nlog⁡n)\Theta(n \log n), and one pass with O(K)O(K) work at each of the mm event times, O(n+mK)O(n + mK) in total. The general product integral costs O(nlog⁡n)O(n \log n) to sort the transitions and O(s)O(s) for each pair (g,h)(g, h) that has a transition at tjt_j, because only the columns gg and hh of PP change.

Complexity

The sort in line L1 costs Θ(nlog⁡n)\Theta(n \log n). The pass visits each subject once and does O(K)O(K) work at each of the mm event times, so it costs Θ(n+mK)\Theta(n + mK). The output holds mm rows of K+1K + 1 numbers, Θ(mK)\Theta(mK) space. In exact arithmetic the denominators of S^(tj)\hat S(t_j) divide n1⋯njn_1 \cdots n_j, so the numbers grow, as for Kaplan-Meier. In floating point there is no cancellation: every increment is a product of nonnegative numbers.

The general product integral for a process with ss states costs Θ(Nlog⁡N)\Theta(N \log N) to sort the NN transitions and censorings. Multiplying by I+dA^(tj)I + d\hat A(t_j) changes only the columns gg and hh of P^(0,t)\hat P(0, t) for each pair (g,h)(g, h) with a move at tjt_j, so each such pair costs O(s)O(s) for the whole matrix, as in the reference code.

Properties

  • Reduces to Kaplan-Meier. With K=1K = 1, F^1=1−S^\hat F_1 = 1 - \hat S.
  • Additivity. S^+∑kF^k=1\hat S + \sum_k \hat F_k = 1, and ∑k∈AF^k\sum_{k \in A}\hat F_k is the Aalen-Johansen estimate for the merged cause AA.
  • Bounded by the naive estimate. F^k≤1−S^k∗\hat F_k \le 1 - \hat S_k^\ast, with equality at tt only if no other cause has an event before tt while cause kk still has events.
  • Plug-in form. F^k(t)=∫0tS^(u−) dH^k(u)\hat F_k(t) = \int_0^t \hat S(u-)\,d\hat H_k(u), where H^k\hat H_k is the Nelson-Aalen estimate of the cause-specific cumulative hazard. It is the population formula of the competing risks page with each part estimated.
  • Inverse probability of censoring weights. F^k(t)=1n∑i1{yi≤t,ci=k}/G^(yi−)\hat F_k(t) = \frac1n\sum_i 1\{y_i \le t, c_i = k\}/\hat G(y_i-), where G^\hat G is the Kaplan-Meier estimate of the censoring distribution with the events counted first at tied times. It follows from the identity nj/n=S^(tj−)G^(tj−)n_j/n = \hat S(t_j-)\hat G(t_j-), which the Fine-Gray page proves: the increment S^(tj−)dkj/nj\hat S(t_j-)d_{kj}/n_j equals dkj/(nG^(tj−))d_{kj}/(n\hat G(t_j-)).
  • Large samples. Under independent censoring, n(F^k−Fk)\sqrt n(\hat F_k - F_k) converges on [0,τ][0, \tau] to a Gaussian process (Aalen and Johansen 1978; Andersen et al. 1993, Chapter IV). We cite this and do not prove it. A Greenwood-type formula or the delta method gives the variance.

Variants and improvements

  • Multi-state models. For a Markov process with states 0,…,s−10, \ldots, s - 1, let Ngh(tj)N_{gh}(t_j) count the moves from gg to hh at tjt_j and Yg(tj)Y_g(t_j) the subjects in gg just before tjt_j and under observation. With dA^gh=Ngh/Ygd\hat A_{gh} = N_{gh}/Y_g for g≠hg \ne h and the diagonal chosen so each row sums to 00, the estimate of the transition matrix is P^(s,t)=∏s<tj≤t(I+dA^(tj))\hat P(s, t) = \prod_{s < t_j \le t}(I + d\hat A(t_j)), a product integral, the discrete analogue of the matrix exponential of the cumulative intensity. Competing risks is the case with one transient state and KK absorbing ones.
  • Delayed entry. Subjects that enter at viv_i are at risk only for vi<t≤yiv_i < t \le y_i. The pass then needs entries and exits in time order.
  • Non-Markov processes. If the process is not Markov, P^0h(0,t)\hat P_{0h}(0, t) from a start at time 0 is still consistent for the state occupation probabilities under independent censoring (Datta and Satten 2001). Transition probabilities from later times need other estimators.
  • Covariates. The Fine-Gray model regresses FkF_k on covariates directly. Cause-specific Cox models, combined through the plug-in formula, give a second route.
  • Comparing groups. Gray's test compares the cumulative incidence of one cause between groups.

When to use it

Use it whenever an event of interest can be prevented by other events: to report the risk of relapse when patients can die in remission, the risk of cancer death in elderly cohorts, or the probability of being in each state of a disease process. Do not report one minus Kaplan-Meier with the competing events censored as a risk. Report the curves of all causes, or at least of the main competing cause, so the reader can see why one cause looks rare.

Pitfalls

  • Censoring the competing events. It gives 1−S^k∗1 - \hat S_k^\ast, which overstates the risk, and the curves of several causes can add up to more than 11.
  • Order of the updates. Updating S^\hat S before the increment of F^k\hat F_k uses the wrong survival, and the sum of the estimates is then less than 1−S^1 - \hat S.
  • Ties with censoring. Count a censored subject at tt in the risk set at tt.
  • Dependent censoring. If the censoring depends on the risk of an event, the estimate is biased, as Kaplan-Meier is. Censoring weights that depend on covariates, as in inverse probability weighting, can correct this when the dependence is through measured covariates.
  • Cause-specific hazards are not risks. The cumulative incidence depends on all the causes. A treatment that lowers the hazard of death from other causes raises the cumulative incidence of cancer death, even with no effect on the cancer hazard.
  • The tail. With few subjects at risk at the end, each event moves the estimates by a large step.

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.

aalen_johansen_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aalen-johansen-estimator/. The authors are listed in prov/ZVA82Z.jsonl.
"""Aalen-Johansen estimator: cumulative incidence functions and multistate transition matrices.

Competing risks input: times[i] = y_i and causes[i] = 0 if subject i is
censored at y_i, or k in 1..K if the subject has an event of cause k at y_i.
A censored time tied with an event time counts as at risk at that time.
All the arithmetic is done in Fractions, so every output is exact for exact
input times; convert with float() for display.
"""

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


class Row(NamedTuple):
    time: float  # t_j, a distinct event time (of any cause)
    at_risk: int  # n_j
    events: tuple  # (d_1j, ..., d_Kj)
    surv: Fraction  # S-hat(t_j), the all-cause Kaplan-Meier estimate
    cif: tuple  # (F_1-hat(t_j), ..., F_K-hat(t_j))


def cumulative_incidence(times: Sequence, causes: Sequence[int], n_causes: int | None = None) -> list[Row]:
    """F_k-hat(t) = sum over t_j <= t of S-hat(t_j-) d_kj / n_j, for every cause k.

    One sort, O(n log n), then one pass that costs O(K) per distinct event time.
    """
    n = len(times)
    if n == 0 or len(causes) != n:
        raise ValueError("times and causes must have the same positive length")
    if any(not isinstance(c, int) or c < 0 for c in causes):
        raise ValueError("causes must be integers >= 0 (0 = censored)")
    K = max(causes) if n_causes is None else n_causes
    if max(causes) > K:
        raise ValueError("a cause is larger than n_causes")
    order = sorted(range(n), key=lambda i: times[i])  # @line L1
    S, F, at_risk, out, i = Fraction(1), [Fraction(0)] * K, n, [], 0  # @line L2
    while i < n:  # @line L3
        t, d, leave = times[order[i]], [0] * K, 0
        while i < n and times[order[i]] == t:  # @line L4
            c = causes[order[i]]
            if c:
                d[c - 1] += 1
            leave += 1
            i += 1
        total = sum(d)
        if total:  # @line L5
            F = [F[k] + S * Fraction(d[k], at_risk) for k in range(K)]  # @line L6
            S = S * Fraction(at_risk - total, at_risk)  # @line L7
            out.append(Row(t, at_risk, tuple(d), S, tuple(F)))
        at_risk -= leave  # @line L8
    return out


def evaluate(rows: list[Row], t: float, k: int | None = None):
    """F_k-hat(t) for cause k (1-based), or S-hat(t) when k is None; step function, right-continuous."""
    value = Fraction(1) if k is None else Fraction(0)
    for r in rows:
        if r.time > t:
            break
        value = r.surv if k is None else r.cif[k - 1]
    return value


def kaplan_meier(times: Sequence, events: Sequence[int]) -> list[tuple]:
    """Plain Kaplan-Meier (time, S-hat) at each event time, for comparisons."""
    out, S = [], Fraction(1)
    for t in sorted(set(y for y, e in zip(times, events) if e)):
        n_j = sum(1 for y in times if y >= t)
        d_j = sum(1 for y, e in zip(times, events) if e and y == t)
        S *= Fraction(n_j - d_j, n_j)
        out.append((t, S))
    return out


class Subject(NamedTuple):
    start: int  # state at time 0
    moves: tuple  # ((time, new_state), ...) in increasing time
    end: float  # end of follow-up, at least the last move time


def transition_matrices(subjects: Sequence[Subject], n_states: int) -> list[tuple]:
    """Aalen-Johansen product integral P-hat(0, t) = prod over t_j <= t of (I + dA-hat(t_j)).

    dA-hat_gh(t_j) = N_gh(t_j) / Y_g(t_j) for g != h, and each row of dA-hat sums
    to 0. Y_g(t_j) counts the subjects in state g just before t_j that are under
    observation at t_j. Returns a list of (t_j, P-hat(0, t_j)), the matrix as a
    list of rows of Fractions. Cost: O(n log n + m s^2) for m distinct
    transition times and s states.
    """
    s = n_states
    events = []
    for idx, sub in enumerate(subjects):
        last = 0
        for t, h in sub.moves:
            if t < last or t > sub.end or not 0 <= h < s:
                raise ValueError("moves must be in time order, inside follow-up and to a valid state")
            last = t
            events.append((t, 0, idx, h))
        events.append((sub.end, 1, idx, None))
    events.sort(key=lambda e: (e[0], e[1]))
    state = [sub.start for sub in subjects]
    Y = [0] * s
    for g in state:
        Y[g] += 1
    P = [[Fraction(int(a == b)) for b in range(s)] for a in range(s)]
    out, i = [], 0
    while i < len(events):
        t = events[i][0]
        N = {}
        j = i
        while j < len(events) and events[j][0] == t and events[j][1] == 0:
            _, _, idx, h = events[j]
            g = state[idx]
            if h != g:
                N[(g, h)] = N.get((g, h), 0) + 1
            j += 1
        if N:
            # P <- P (I + dA): copy the old columns of the source states first.
            old = {g: [P[a][g] for a in range(s)] for g, _ in N}
            for (g, h), c in N.items():
                rate = Fraction(c, Y[g])
                for a in range(s):
                    P[a][h] += old[g][a] * rate
                    P[a][g] -= old[g][a] * rate
            out.append((t, [row[:] for row in P]))
        for e in events[i:j]:
            _, _, idx, h = e
            Y[state[idx]] -= 1
            Y[h] += 1
            state[idx] = h
        while j < len(events) and events[j][0] == t:
            Y[state[events[j][2]]] -= 1
            j += 1
        i = j
    return out


def competing_risks_subjects(times: Sequence, causes: Sequence[int]) -> list[Subject]:
    """The competing risks data as a multistate model: state 0 alive, state k for death of cause k."""
    return [Subject(0, ((y, c),) if c else (), y) for y, c in zip(times, causes)]
test_aalen_johansen_estimator.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aalen-johansen-estimator/. The authors are listed in prov/ZVA82Z.jsonl.

import math
import random
from fractions import Fraction

from aalen_johansen_estimator import (
    Subject, competing_risks_subjects, cumulative_incidence, evaluate, kaplan_meier, transition_matrices,
)


def random_data(rng, n, K, censor=0.3, ties=True):
    times = [rng.randint(1, 9) if ties else rng.random() for _ in range(n)]
    causes = [0 if rng.random() < censor else rng.randint(1, K) for _ in range(n)]
    return times, causes


def grid(times):
    return sorted(set(times)) + [min(times) - 1, max(times) + 1]


def test_one_cause_is_one_minus_kaplan_meier() -> None:
    rng = random.Random(1)
    for _ in range(50):
        times, causes = random_data(rng, rng.randint(1, 15), 1)
        rows = cumulative_incidence(times, causes, 1)
        km = kaplan_meier(times, causes)
        assert [r.time for r in rows] == [t for t, _ in km]
        for r, (_, S) in zip(rows, km):
            assert r.cif[0] == 1 - S
            assert r.surv == S


def test_incidences_and_survival_sum_to_one() -> None:
    rng = random.Random(2)
    for _ in range(50):
        K = rng.randint(1, 4)
        times, causes = random_data(rng, rng.randint(1, 20), K)
        rows = cumulative_incidence(times, causes, K)
        for t in grid(times):
            assert evaluate(rows, t) + sum(evaluate(rows, t, k) for k in range(1, K + 1)) == 1


def test_one_minus_cause_specific_km_overstates() -> None:
    rng = random.Random(3)
    strict = 0
    for _ in range(50):
        K = rng.randint(2, 3)
        times, causes = random_data(rng, rng.randint(2, 20), K)
        rows = cumulative_incidence(times, causes, K)
        for k in range(1, K + 1):
            km = kaplan_meier(times, [int(c == k) for c in causes])
            for t in grid(times):
                S_k = Fraction(1)
                for u, s in km:
                    if u <= t:
                        S_k = s
                F = evaluate(rows, t, k)
                assert 1 - S_k >= F
                strict += 1 - S_k > F
    assert strict > 0


def test_no_censoring_gives_empirical_proportions() -> None:
    rng = random.Random(4)
    for _ in range(30):
        K = rng.randint(1, 3)
        n = rng.randint(1, 20)
        times, causes = random_data(rng, n, K, censor=0.0)
        rows = cumulative_incidence(times, causes, K)
        for t in grid(times):
            for k in range(1, K + 1):
                assert evaluate(rows, t, k) == Fraction(sum(1 for y, c in zip(times, causes) if y <= t and c == k), n)
            assert evaluate(rows, t) == Fraction(sum(1 for y in times if y > t), n)


def test_multistate_form_equals_cumulative_incidence() -> None:
    rng = random.Random(5)
    for _ in range(40):
        K = rng.randint(1, 3)
        times, causes = random_data(rng, rng.randint(1, 18), K)
        rows = cumulative_incidence(times, causes, K)
        mats = transition_matrices(competing_risks_subjects(times, causes), K + 1)
        assert [t for t, _ in mats] == [r.time for r in rows]
        for (t, P), r in zip(mats, rows):
            assert P[0][0] == r.surv
            assert tuple(P[0][1:]) == r.cif


def illness_death(rng, n, censor):
    """States 0 healthy, 1 ill, 2 dead; integer times so that ties occur."""
    subs = []
    for _ in range(n):
        t, state, moves = 0, 0, []
        while state != 2:
            t += rng.randint(1, 4)
            state = rng.choice([1, 2]) if state == 0 else 2
            moves.append((t, state))
        end = moves[-1][0]
        if censor and rng.random() < censor:
            end = rng.randint(0, end)
            moves = [m for m in moves if m[0] <= end]
        subs.append(Subject(0, tuple(moves), end))
    return subs


def state_at(sub, t):
    s = sub.start
    for u, h in sub.moves:
        if u <= t:
            s = h
    return s


def test_illness_death_without_censoring_is_empirical() -> None:
    rng = random.Random(6)
    for _ in range(20):
        n = rng.randint(1, 15)
        subs = illness_death(rng, n, 0.0)
        for t, P in transition_matrices(subs, 3):
            for h in range(3):
                assert P[0][h] == Fraction(sum(1 for sub in subs if state_at(sub, t) == h), n)


def test_rows_sum_to_one_with_censoring() -> None:
    rng = random.Random(7)
    for _ in range(30):
        subs = illness_death(rng, rng.randint(1, 20), 0.4)
        for _, P in transition_matrices(subs, 3):
            for row in P:
                assert sum(row) == 1
            assert P[2] == [0, 0, 1]
            assert all(v >= 0 for row in P for v in row)


def test_exponential_competing_risks_by_simulation() -> None:
    # Cause-specific hazards 1 and 0.5, censoring rate 0.3; F_1(t) = (2/3)(1 - e^(-1.5 t)).
    rng = random.Random(8)
    n = 2000
    times, causes = [], []
    for _ in range(n):
        a, b, c = rng.expovariate(1.0), rng.expovariate(0.5), rng.expovariate(0.3)
        y = min(a, b, c)
        times.append(y)
        causes.append(0 if y == c else (1 if y == a else 2))
    rows = cumulative_incidence(times, causes, 2)
    for t in [0.2, 0.5, 1.0, 2.0]:
        F1 = (2 / 3) * (1 - math.exp(-1.5 * t))
        F2 = (1 / 3) * (1 - math.exp(-1.5 * t))
        se = math.sqrt(F1 * (1 - F1) / n) * 1.5
        assert abs(float(evaluate(rows, t, 1)) - F1) < 4 * se
        assert abs(float(evaluate(rows, t, 2)) - F2) < 4 * se


def test_hand_example_and_input_checks() -> None:
    times = [1, 2, 2, 3, 4, 5]
    causes = [1, 2, 0, 1, 0, 2]
    rows = cumulative_incidence(times, causes)
    assert [r.time for r in rows] == [1, 2, 3, 5]
    assert [r.cif for r in rows] == [
        (Fraction(1, 6), Fraction(0)),
        (Fraction(1, 6), Fraction(1, 6)),
        (Fraction(7, 18), Fraction(1, 6)),
        (Fraction(7, 18), Fraction(11, 18)),
    ]
    assert [r.surv for r in rows] == [Fraction(5, 6), Fraction(2, 3), Fraction(4, 9), Fraction(0)]
    for bad in [([], []), ([1], [-1]), ([1, 2], [1])]:
        try:
            cumulative_incidence(*bad)
        except ValueError:
            pass
        else:
            raise AssertionError("bad input accepted")

History

Odd O. Aalen and Søren Johansen published the empirical transition matrix for non-homogeneous Markov chains with censored data in the Scandinavian Journal of Statistics in 1978, as a product integral of the Nelson-Aalen increments, with its martingale representation and its asymptotic behavior. For one transition it reduces to Kaplan-Meier. The cumulative incidence formula for competing risks was in use before, in the actuarial "crude probability" of death from a cause and in the work of Kalbfleisch and Prentice (1980). Gill and Johansen (1990) developed the theory of product integration that underlies the estimator, and Andersen, Borgan, Gill and Keiding (1993) collected the counting process proofs.

References

  1. Odd O. Aalen and Søren Johansen, An empirical transition matrix for non-homogeneous Markov chains based on censored observations, Scandinavian Journal of Statistics 5(3), 1978, pp. 141 to 150 (the product-integral estimator of the transition matrix, its martingale representation and its large-sample behavior)
  2. 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 of a transition matrix and its weak convergence)
  3. H. Putter, M. Fiocco and R. B. Geskus, Tutorial in biostatistics, competing risks and multi-state models, Statistics in Medicine 26(11), 2007, pp. 2389 to 2430 (the cumulative incidence estimate, the bias of one minus Kaplan-Meier, and the Aalen-Johansen estimate in multi-state models)
  4. John D. Kalbfleisch and Ross L. Prentice, The Statistical Analysis of Failure Time Data, 2nd edition, Wiley, 2002, Chapter 8 (competing risks, the estimate of the cumulative incidence functions and multistate models)

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