Algorithm Search⌘K

Algorithmcore

Log-rank test

Also called Mantel-Cox test, Mantel-Haenszel log-rank test.

Compares survival curves of groups by the observed minus expected events at each event time, summed over time. It is the locally most powerful rank test under proportional hazards.

Time
Θ(n log n) worstΘ(b n log n) permutation
Space
Θ(n) extra
Where
b = the number of random relabellings in the permutation version; n = the number of subjects
Properties
deterministicnot exactofflineiterative
Origin
Nathan Mantel, Richard Peto, Julian Peto, David R. Cox, 1966

The log-rank test compares the survival of two (or more) groups when some event times are right censored. At each distinct event time tjt_j it forms the 2×22 \times 2 table of group against event among the subjects still at risk, and compares the observed number of events in group 1 with the number expected if both groups had the same hazard. The differences are summed over all event times and divided by the square root of the summed hypergeometric variances. Under the null hypothesis of equal hazards the result is asymptotically standard normal, so its square is asymptotically chi-square with one degree of freedom. It is the score test of the Cox model with a group indicator, and it has the highest asymptotic local power among rank tests when the hazards are proportional.

In plain words

Two groups of patients are followed over time, and some leave the study before their outcome is known. Each time someone has the event, look at everyone still being followed just before. If the two treatments were equally good, the event would be equally likely to fall on any of them, so the share falling in group 1 should match group 1's share of the people at risk. Add up, over all event times, how many events group 1 actually had and how many it should have had by this fair share. A large difference, measured against how much such a total varies by chance, says that the groups differ.

The problem

Model. Observations (yi,δi,gi)(y_i, \delta_i, g_i), i=1,…,ni = 1, \ldots, n, with yi=min⁡(Ti,Ci)y_i = \min(T_i, C_i), δi=1{Ti≤Ci}\delta_i = 1\{T_i \le C_i\} and a group label gi∈{0,1}g_i \in \{0, 1\}. The subjects are independent, and censoring is independent within each group (see censoring). Group gg has hazard hg(t)h_g(t) and survival function Sg(t)S_g(t).

Hypotheses. H0:h1(t)=h0(t)H_0: h_1(t) = h_0(t) for all tt (equivalently S1=S0S_1 = S_0) on the range where both groups are observed. The alternative is two-sided, S1≠S0S_1 \ne S_0. The one-sided form uses the sign of UU below. The test is built to detect h1(t)=θ h0(t)h_1(t) = \theta\, h_0(t) with θ≠1\theta \ne 1 (proportional hazards).

Statistic. At the distinct event times t1<⋯<tkt_1 < \cdots < t_k of the pooled sample let njn_j and n1jn_{1j} be the numbers at risk (yi≥tjy_i \ge t_j) overall and in group 1, n0j=nj−n1jn_{0j} = n_j - n_{1j}, and djd_j and d1jd_{1j} the events overall and in group 1. Then

E1j=dj n1jnj,Vj=n1j n0j dj (nj−dj)nj2 (nj−1) (Vj=0 if nj=1),E_{1j} = \frac{d_j\, n_{1j}}{n_j}, \qquad V_j = \frac{n_{1j}\, n_{0j}\, d_j\,(n_j - d_j)}{n_j^2\,(n_j - 1)} \ (V_j = 0 \text{ if } n_j = 1),
U=∑j=1k(d1j−E1j)=O1−E1,V=∑j=1kVj,X2=U2V.U = \sum_{j=1}^k (d_{1j} - E_{1j}) = O_1 - E_1, \qquad V = \sum_{j=1}^k V_j, \qquad X^2 = \frac{U^2}{V}.

The weighted log-rank family uses Uw=∑jwj(d1j−E1j)U_w = \sum_j w_j (d_{1j} - E_{1j}) and Vw=∑jwj2VjV_w = \sum_j w_j^2 V_j with a weight wjw_j that depends only on the data before tjt_j and on njn_j, djd_j.

Null distribution. Asymptotic. Given the risk sets and the total djd_j at tjt_j, d1jd_{1j} is hypergeometric under H0H_0 with mean E1jE_{1j} and variance VjV_j, as in Fisher's exact test for that one table. The centred terms are uncorrelated across event times, and U/V→N(0,1)U/\sqrt V \to N(0, 1) as n→∞n \to \infty, so X2→χ12X^2 \to \chi^2_1. The proof is in the correctness file. A permutation version, which permutes the group labels among the nn observed pairs (yi,δi)(y_i, \delta_i), is exact only when the two groups have the same censoring distribution.

Rejection rule and p-value. Reject at level α\alpha when X2>χ1,1−α2X^2 > \chi^2_{1, 1 - \alpha}. The p-value is P(χ12>X2)P(\chi^2_1 > X^2), computed as an upper tail without cancellation. Since χ12\chi^2_1 is the square of a standard normal, this equals the two-sided normal p-value 2P(Z>∣U∣/V)2P(Z > |U|/\sqrt V). The size is only near α\alpha in finite samples.

The algorithm

  1. LOG-RANK(y[1..n], δ[1..n], g[1..n], weight rule w)
  2. 1sort the indices 1..n by y
  3. 2r ← n; r1 ← number of i with g[i] = 1; U ← 0; V ← 0
  4. 3i ← 1
  5. 4while i ≤ n
  6. 5t ← y of the i-th sorted index; d ← 0; d1 ← 0; m ← 0; m1 ← 0
  7. 6while i ≤ n and y of the i-th sorted index = t: m ← m + 1; m1 ← m1 + g; if δ = 1 then d ← d + 1; d1 ← d1 + g; i ← i + 1
  8. 7if d > 0 then
  9. 8E ← d · r1 / r; v ← r1 (r - r1) d (r - d) / (r² (r - 1)), or 0 if r = 1; compute the weight w
  10. 9U ← U + w (d1 - E); V ← V + w² v
  11. 10r ← r - m; r1 ← r1 - m1 ▷ everyone at t, censored or not, leaves after t
  12. 11X² ← U² / V; return U, V, X² and the chi-square upper tail of X² with 1 degree of freedom

The code supports five weight rules: the log-rank wj=1w_j = 1; Gehan's wj=njw_j = n_j; Tarone and Ware's wj=njw_j = \sqrt{n_j}; Peto and Peto's wj=∏tl≤tj(1−dl/(nl+1))w_j = \prod_{t_l \le t_j}(1 - d_l/(n_l + 1)); and the Fleming-Harrington Gρ,γG^{\rho, \gamma} weight wj=S^(tj−)ρ(1−S^(tj−))γw_j = \hat S(t_j-)^\rho (1 - \hat S(t_j-))^\gamma, where S^\hat S is the pooled Kaplan-Meier estimate. With exact=True the table and UU and VV are exact fractions for the rational weights. A second function gives the two-sided permutation p-value, exact by enumeration for small nn or by bb random relabellings with the (1+#)/(1+b)(1 + \#)/(1 + b) rule. The p-value uses the chi-square tail of the shared stdist helper.

Example

The leukemia trial of Freireich et al. (1963), as listed by Gehan (1965), has 21 patients on 6-MP (group 1, 9 relapses and 12 censored remissions) and 21 on placebo (group 0, 21 relapses, none censored). The data are on the Kaplan-Meier page. The pooled sample has 17 distinct event times. The first rows and the rows where 6-MP patients relapse are:

tjt_j njn_j n1jn_{1j} djd_j d1jd_{1j} E1jE_{1j} VjV_j
1 42 21 2 0 1 0.4878
2 40 21 2 0 21/20 0.4860
6 33 21 3 3 21/11 0.6508
7 29 17 1 1 17/29 0.2426
8 28 16 4 0 16/7 0.8707
10 23 15 1 1 15/23 0.2268
13 16 12 1 1 3/4 0.1875
16 14 11 1 1 11/14 0.1684
22 9 7 2 1 14/9 0.3025
23 7 6 2 1 12/7 0.2041

At t=1t = 1, V1=21⋅21⋅2⋅40/(422⋅41)=20/41V_1 = 21 \cdot 21 \cdot 2 \cdot 40/(42^2 \cdot 41) = 20/41. Over all 17 rows, O1=9O_1 = 9 against E1=19.2505E_1 = 19.2505, so U=−10.2505U = -10.2505; V=6.25696V = 6.25696; X2=16.793X^2 = 16.793, and the p-value is P(χ12>16.793)=4.17×10−5P(\chi^2_1 > 16.793) = 4.17 \times 10^{-5}. The placebo group had O0=21O_0 = 21 against E0=10.7495E_0 = 10.7495. The 6-MP group relapsed less than equal hazards would predict. The weighted versions give X2=13.46X^2 = 13.46 (Gehan, p=2.4×10−4p = 2.4 \times 10^{-4}), 15.1215.12 (Tarone-Ware), 14.0814.08 (Peto-Peto) and 13.0513.05 (Fleming-Harrington with ρ=0\rho = 0, γ=1\gamma = 1).

Correctness

The proof in proofs/correctness.md shows that the pass of lines L4 to L10 builds the table of (tj,nj,n1j,dj,d1j)(t_j, n_j, n_{1j}, d_j, d_{1j}), by the same invariant as for Kaplan-Meier. It then proves, for event times on a finite grid, that under H0H_0 and independent censoring d1jd_{1j} given the past and djd_j is hypergeometric with mean E1jE_{1j} and variance VjV_j, that the terms wj(d1j−E1j)w_j(d_{1j} - E_{1j}) are uncorrelated martingale differences, and that U/V→N(0,1)U/\sqrt V \to N(0, 1) by a central limit theorem for a sum of independent terms plus Slutsky's theorem. Finally it shows that UU is the score of the Cox partial likelihood at β=0\beta = 0, and that VV is its information when there are no ties.

Proof: The pass computes the log-rank table, the centred terms are uncorrelated hypergeometric deviations, and the statistic is asymptotically chi-square with one degree of freedomfull

Let the data be (yi,δi,gi)(y_i, \delta_i, g_i), i=1,…,ni = 1, \ldots, n, with distinct event times t1<⋯<tkt_1 < \cdots < t_k of the pooled sample, nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\}, n1j=#{i:yi≥tj,gi=1}n_{1j} = \#\{i : y_i \ge t_j, g_i = 1\}, n0j=nj−n1jn_{0j} = n_j - n_{1j}, dj=#{i:yi=tj,δi=1}d_j = \#\{i : y_i = t_j, \delta_i = 1\} and d1j=#{i:yi=tj,δi=1,gi=1}d_{1j} = \#\{i : y_i = t_j, \delta_i = 1, g_i = 1\}.

Claim 1 (the pass computes the table). Line L9 is executed once for each jj, in increasing order of tjt_j, and at that moment r=njr = n_j, r1=n1jr_1 = n_{1j}, d=djd = d_j and d1=d1jd_1 = d_{1j}. So the returned UU and VV are ∑jwj(d1j−E1j)\sum_j w_j (d_{1j} - E_{1j}) and ∑jwj2Vj\sum_j w_j^2 V_j.

Proof. After the sort of line L1, the inner loop of line L6 reads exactly the subjects whose time equals the current distinct time uu, and sets mm, m1m_1, dd, d1d_1 to the numbers of subjects, group-1 subjects, events and group-1 events at uu. Invariant: at the start of the group at uu, r=#{i:yi≥u}r = \#\{i : y_i \ge u\} and r1=#{i:yi≥u,gi=1}r_1 = \#\{i : y_i \ge u, g_i = 1\}. It holds at the first group, where r=nr = n and r1=∑igir_1 = \sum_i g_i by line L2. Line L10 subtracts all subjects at uu, censored or not, so afterwards r=#{i:yi>u}r = \#\{i : y_i > u\}, which is the count at risk at the next distinct time; the same holds for r1r_1. Line L7 skips the times with no event, and at an event time u=tju = t_j the invariant gives r=njr = n_j and r1=n1jr_1 = n_{1j}. Line L8 then computes E1jE_{1j} and VjV_j by their formulas, and line L9 adds the terms. □\square

The null distribution

The asymptotic claims are proved for event and censoring times on a finite grid τ1<⋯<τK\tau_1 < \cdots < \tau_K, which covers all data recorded in days, weeks or months. The conditions are:

  1. All times TiT_i and CiC_i take values in {τ1,…,τK}\{\tau_1, \ldots, \tau_K\}, and a subject censored at τl\tau_l is at risk at τl\tau_l, so yi=min⁡(Ti,Ci)y_i = \min(T_i, C_i) and δi=1{Ti≤Ci}\delta_i = 1\{T_i \le C_i\}.
  2. The pairs (Ti,Ci)(T_i, C_i) are independent across subjects, identically distributed within each group, and TiT_i is independent of CiC_i. The censoring distribution may differ between the groups.
  3. Under H0H_0 both groups have the same discrete hazard hl=P(T=τl∣T≥τl)h_l = P(T = \tau_l \mid T \ge \tau_l) at each τl\tau_l.
  4. The group sizes satisfy n1/n→p∈(0,1)n_1/n \to p \in (0, 1) as n→∞n \to \infty.
  5. σ2>0\sigma^2 > 0, with σ2\sigma^2 defined in Claim 4. It holds when some τl\tau_l has 0<hl<10 < h_l < 1 and positive probability of being at risk in both groups.

Write Ril=1{yi≥τl}R_{il} = 1\{y_i \ge \tau_l\} and Xil=1{yi=τl,δi=1}X_{il} = 1\{y_i = \tau_l, \delta_i = 1\}. A grid time with no event contributes nothing to UU or VV, so sums over the event times tjt_j equal sums over all τl\tau_l with dl=0d_l = 0 terms included.

Claim 2 (hypergeometric conditional law). Under conditions 1 to 3, let Fl\mathcal F_l be the history of the whole sample strictly before τl\tau_l together with the labels, and Gl=Fl∨σ(dl)\mathcal G_l = \mathcal F_l \vee \sigma(d_l). Given Gl\mathcal G_l, the set of subjects that fail at τl\tau_l is uniform among the (nldl)\binom{n_l}{d_l} subsets of size dld_l of the risk set. Hence d1ld_{1l} given Gl\mathcal G_l is hypergeometric with

E[d1l∣Gl]=dl n1lnl=E1l,Var(d1l∣Gl)=n1l n0l dl(nl−dl)nl2(nl−1)=Vl.E[d_{1l} \mid \mathcal G_l] = \frac{d_l\, n_{1l}}{n_l} = E_{1l}, \qquad \mathrm{Var}(d_{1l} \mid \mathcal G_l) = \frac{n_{1l}\, n_{0l}\, d_l (n_l - d_l)}{n_l^2 (n_l - 1)} = V_l.

Proof. For a subject at risk at τl\tau_l, the history says only that Ti≥τlT_i \ge \tau_l and Ci≥τlC_i \ge \tau_l, and by condition 2 the other subjects carry no information about it. So P(Xil=1∣Fl)=P(Ti=τl∣Ti≥τl,Ci≥τl)=P(Ti=τl∣Ti≥τl)=hlP(X_{il} = 1 \mid \mathcal F_l) = P(T_i = \tau_l \mid T_i \ge \tau_l, C_i \ge \tau_l) = P(T_i = \tau_l \mid T_i \ge \tau_l) = h_l by the independence of TiT_i and CiC_i and condition 3, whatever the group. Given Fl\mathcal F_l the failure indicators of the nln_l subjects at risk are therefore independent Bernoulli(hlh_l). For any fixed subset AA of the risk set with ∣A∣=d|A| = d, the probability that exactly AA fails is hld(1−hl)nl−dh_l^d (1 - h_l)^{n_l - d}, which does not depend on AA, so given the total dl=dd_l = d all subsets of size dd are equally likely.

Let ZaZ_a indicate that the group-1 subject aa fails. Then P(Za=1)=d/nP(Z_a = 1) = d/n and, for a≠ba \ne b, P(Za=Zb=1)=d(d−1)/(n(n−1))P(Z_a = Z_b = 1) = d(d-1)/(n(n-1)), writing n=nln = n_l, n1=n1ln_1 = n_{1l}, d=dld = d_l. The mean of d1l=∑aZad_{1l} = \sum_a Z_a is n1d/nn_1 d/n. Since

d(d−1)n(n−1)−d2n2=d [n(d−1)−d(n−1)]n2(n−1)=−d(n−d)n2(n−1),\frac{d(d-1)}{n(n-1)} - \frac{d^2}{n^2} = \frac{d\,[n(d-1) - d(n-1)]}{n^2(n-1)} = -\frac{d(n-d)}{n^2(n-1)},

the variance is

n1dn(1−dn)−n1(n1−1)d(n−d)n2(n−1)=n1d(n−d)n2(1−n1−1n−1)=n1(n−n1) d(n−d)n2(n−1).n_1 \frac{d}{n}\Big(1 - \frac{d}{n}\Big) - n_1(n_1 - 1)\frac{d(n-d)}{n^2(n-1)} = \frac{n_1 d(n-d)}{n^2}\Big(1 - \frac{n_1 - 1}{n - 1}\Big) = \frac{n_1 (n - n_1)\, d(n-d)}{n^2(n-1)}.

For n=1n = 1 the variance is 0, which is the convention of line L8. □\square

Claim 3 (uncorrelated increments, exact mean and variance). Let the weight wlw_l be Gl\mathcal G_l-measurable and bounded, which holds for all five weight rules, and let Dl=wl(d1l−E1l)D_l = w_l(d_{1l} - E_{1l}). Then E[Dl∣Gl]=0E[D_l \mid \mathcal G_l] = 0, E[Dl2∣Gl]=wl2VlE[D_l^2 \mid \mathcal G_l] = w_l^2 V_l and E[DlDm]=0E[D_l D_m] = 0 for l<ml < m. Consequently E[Uw]=0E[U_w] = 0 and Var(Uw)=E[Vw]\mathrm{Var}(U_w) = E[V_w] exactly, for every nn.

Proof. The first two identities are Claim 2 multiplied by the Gl\mathcal G_l-measurable wlw_l. For l<ml < m, DlD_l is determined by the history before τm\tau_m, so it is Gm\mathcal G_m-measurable and E[DlDm]=E[Dl E[Dm∣Gm]]=0E[D_l D_m] = E[D_l\, E[D_m \mid \mathcal G_m]] = 0. Summing gives E[Uw]=0E[U_w] = 0 and E[Uw2]=∑lE[Dl2]=∑lE[wl2Vl]=E[Vw]E[U_w^2] = \sum_l E[D_l^2] = \sum_l E[w_l^2 V_l] = E[V_w]. □\square

So VV is an unbiased estimate of the null variance of UU in finite samples. The normal approximation is asymptotic.

Claim 4 (asymptotic normality). Under conditions 1 to 5 and H0H_0, for the log-rank weight wl=1w_l = 1, U/V→N(0,1)U/\sqrt V \to N(0, 1) in distribution, so X2=U2/V→χ12X^2 = U^2/V \to \chi^2_1.

Proof. Let πgl=P(y≥τl∣group g)\pi_{gl} = P(y \ge \tau_l \mid \text{group } g), al=p π1la_l = p\,\pi_{1l}, bl=(1−p) π0lb_l = (1 - p)\,\pi_{0l}, ml=al+blm_l = a_l + b_l, and for ml>0m_l > 0 set ql=al/mlq_l = a_l/m_l and q^l=n1l/nl\hat q_l = n_{1l}/n_l. Drop the grid points with ml=0m_l = 0, at which nobody is ever at risk.

Step 1 (an exact identity). For each ll with nl>0n_l > 0, ∑i(gi−q^l)Ril=n1l−q^lnl=0\sum_i (g_i - \hat q_l) R_{il} = n_{1l} - \hat q_l n_l = 0 and ∑i(gi−q^l)Xil=d1l−q^ldl=d1l−E1l\sum_i (g_i - \hat q_l) X_{il} = d_{1l} - \hat q_l d_l = d_{1l} - E_{1l}. Hence, for any numbers hlh_l,

U=∑l∑i(gi−q^l)(Xil−hlRil)=∑iψi+∑l(ql−q^l) Ml,U = \sum_l \sum_i (g_i - \hat q_l)(X_{il} - h_l R_{il}) = \sum_i \psi_i + \sum_l (q_l - \hat q_l)\, M_l,

with ψi=∑l(gi−ql)(Xil−hlRil)\psi_i = \sum_l (g_i - q_l)(X_{il} - h_l R_{il}) and Ml=∑i(Xil−hlRil)M_l = \sum_i (X_{il} - h_l R_{il}).

Step 2 (moments of one subject). Fix ii and let εl=Xil−hlRil\varepsilon_l = X_{il} - h_l R_{il}. By the argument of Claim 2, E[Xil∣Ril=1]=hlE[X_{il} \mid R_{il} = 1] = h_l, and εl=0\varepsilon_l = 0 when Ril=0R_{il} = 0, so E[εl]=0E[\varepsilon_l] = 0. Since Xil2=XilX_{il}^2 = X_{il} and XilRil=XilX_{il} R_{il} = X_{il}, E[εl2]=hlERil−2hl2ERil+hl2ERil=hl(1−hl)ERilE[\varepsilon_l^2] = h_l E R_{il} - 2h_l^2 E R_{il} + h_l^2 E R_{il} = h_l(1 - h_l) E R_{il}. For l<ml < m, εm≠0\varepsilon_m \ne 0 only if yi≥τmy_i \ge \tau_m, and then Xil=0X_{il} = 0 and Ril=1R_{il} = 1, so εlεm=−hlεm\varepsilon_l \varepsilon_m = -h_l \varepsilon_m and E[εlεm]=−hlE[εm]=0E[\varepsilon_l \varepsilon_m] = -h_l E[\varepsilon_m] = 0. Therefore E[ψi]=0E[\psi_i] = 0 and

Var(ψi)=∑l(gi−ql)2 hl(1−hl) πgil.\mathrm{Var}(\psi_i) = \sum_l (g_i - q_l)^2\, h_l (1 - h_l)\, \pi_{g_i l}.

Step 3 (CLT for the main term). The ψi\psi_i are independent, bounded by ∑l(1+hl)≤2K\sum_l (1 + h_l) \le 2K, and

1n∑iVar(ψi)=n1n∑l(1−ql)2hl(1−hl)π1l+n0n∑lql2hl(1−hl)π0l→∑lhl(1−hl)[al(1−ql)2+blql2].\frac1n \sum_i \mathrm{Var}(\psi_i) = \frac{n_1}{n}\sum_l (1 - q_l)^2 h_l(1 - h_l)\pi_{1l} + \frac{n_0}{n}\sum_l q_l^2 h_l(1 - h_l)\pi_{0l} \to \sum_l h_l(1 - h_l)\big[a_l (1 - q_l)^2 + b_l q_l^2\big].

Since al(bl/ml)2+bl(al/ml)2=albl/mla_l(b_l/m_l)^2 + b_l(a_l/m_l)^2 = a_l b_l/m_l, the limit is σ2=∑lhl(1−hl) albl/ml\sigma^2 = \sum_l h_l (1 - h_l)\, a_l b_l/m_l, positive by condition 5. The total variance grows like nσ2→∞n\sigma^2 \to \infty while the summands stay bounded, so the Lindeberg condition holds, and the Lindeberg-Feller central limit theorem gives n−1/2∑iψi→N(0,σ2)n^{-1/2}\sum_i \psi_i \to N(0, \sigma^2).

Step 4 (the remainder vanishes). By Step 2, MlM_l is a sum of nn independent mean-zero terms with variance at most 1/41/4 each, so E[(n−1/2Ml)2]≤1/4E[(n^{-1/2} M_l)^2] \le 1/4 and n−1/2Mln^{-1/2}M_l is bounded in probability. By the law of large numbers, n1l/n→aln_{1l}/n \to a_l and nl/n→ml>0n_l/n \to m_l > 0 in probability, so q^l→ql\hat q_l \to q_l. Each product (ql−q^l) n−1/2Ml(q_l - \hat q_l)\, n^{-1/2} M_l tends to 0 in probability, and so does their finite sum. By Slutsky's theorem, n−1/2U→N(0,σ2)n^{-1/2} U \to N(0, \sigma^2).

Step 5 (the variance estimate). By the law of large numbers, n1l/n→aln_{1l}/n \to a_l, n0l/n→bln_{0l}/n \to b_l, nl/n→mln_l/n \to m_l, and dl/n→E[Xil]d_l/n \to E[X_{il}] averaged over the groups, which is hlmlh_l m_l. So Vl/n=(n1l/n)(n0l/n)(dl/n)((nl−dl)/n)/((nl/n)2((nl−1)/n))→alblhlml⋅ml(1−hl)/ml3=hl(1−hl)albl/mlV_l/n = (n_{1l}/n)(n_{0l}/n)(d_l/n)((n_l - d_l)/n)/((n_l/n)^2 ((n_l - 1)/n)) \to a_l b_l h_l m_l \cdot m_l (1 - h_l)/m_l^3 = h_l(1 - h_l) a_l b_l/m_l, by continuity of this rational function where ml>0m_l > 0. Summing over the KK grid points, V/n→σ2V/n \to \sigma^2 in probability. By Slutsky's theorem, U/V=(n−1/2U)/V/n→N(0,1)U/\sqrt V = (n^{-1/2}U)/\sqrt{V/n} \to N(0, 1), and by continuity of x↦x2x \mapsto x^2, X2→χ12X^2 \to \chi^2_1. □\square

The same proof covers a weight with wl/cn→ωlw_l/c_n \to \omega_l in probability for deterministic constants cnc_n and ωl\omega_l: Gehan's wl=nlw_l = n_l with cn=nc_n = n, Tarone and Ware's nl\sqrt{n_l} with cn=nc_n = \sqrt n, and the Peto-Peto and Fleming-Harrington weights with cn=1c_n = 1, since S^\hat S and the Peto product converge to deterministic limits at each grid point. The exact identity of Step 1 holds term by term, so Uw/cn=∑i∑lωl(gi−ql)εil+oP(n1/2)U_w/c_n = \sum_i \sum_l \omega_l (g_i - q_l)\varepsilon_{il} + o_P(n^{1/2}), and the limit variance ∑lωl2hl(1−hl)albl/ml\sum_l \omega_l^2 h_l(1 - h_l) a_l b_l/m_l is the limit of Vw/(cn2n)V_w/(c_n^2 n). For continuous time, the same result follows from Rebolledo's martingale central limit theorem applied to the counting process martingales Ngi(t)−∫0tRgi(s) dH(s)N_{gi}(t) - \int_0^t R_{gi}(s)\, dH(s); see Andersen, Borgan, Gill and Keiding (1993), Chapter V.

The size of the test in finite samples is not proved. The tables on the algorithm page give measured sizes.

The score test and the permutation test

Claim 5 (score test of the Cox model). With the covariate xi=gix_i = g_i, the Cox log partial likelihood with Breslow's handling of ties is ℓ(β)=∑j[βd1j−djlog⁡(n0j+n1jeβ)]\ell(\beta) = \sum_j [\beta d_{1j} - d_j \log(n_{0j} + n_{1j} e^\beta)]. Its derivative at β=0\beta = 0 is UU, and its negative second derivative at β=0\beta = 0 is ∑jdjn1jn0j/nj2\sum_j d_j n_{1j} n_{0j}/n_j^2, which equals VV when every dj=1d_j = 1.

Proof. ddβdjlog⁡(n0j+n1jeβ)=djn1jeβ/(n0j+n1jeβ)\frac{d}{d\beta} d_j \log(n_{0j} + n_{1j}e^\beta) = d_j n_{1j} e^\beta/(n_{0j} + n_{1j} e^\beta), which is E1jE_{1j} at β=0\beta = 0, so ℓ′(0)=∑j(d1j−E1j)=U\ell'(0) = \sum_j (d_{1j} - E_{1j}) = U. Differentiating again gives djn1jn0jeβ/(n0j+n1jeβ)2d_j n_{1j} n_{0j} e^\beta/(n_{0j} + n_{1j}e^\beta)^2, which is djn1jn0j/nj2d_j n_{1j} n_{0j}/n_j^2 at β=0\beta = 0. When dj=1d_j = 1, Vj=n1jn0j(nj−1)/(nj2(nj−1))=n1jn0j/nj2V_j = n_{1j} n_{0j} (n_j - 1)/(n_j^2 (n_j - 1)) = n_{1j} n_{0j}/n_j^2. □\square

Claim 6 (exact permutation test). If, in addition to conditions 2 and 3, both groups have the same censoring distribution, then under H0H_0 the pairs (yi,δi)(y_i, \delta_i) are independent and identically distributed over all nn subjects. Given the multiset of pairs, every assignment of the labels with n1n_1 ones is equally likely, so the permutation p-value P∗(∣U∗∣≥∣U∣)P^*(|U^*| \ge |U|) over the (nn1)\binom{n}{n_1} relabellings satisfies P(p≤α)≤αP(p \le \alpha) \le \alpha for every α\alpha, and the Monte Carlo version with (1+#)/(1+b)(1 + \#)/(1 + b) has the same property. If the censoring distributions differ, the pairs are not exchangeable between groups, the permutation test is not exact, and its size can be far from the nominal level.

Proof. The joint law of i.i.d. pairs is invariant under permutations of the subjects, and the labels are fixed in advance, so conditioning on the multiset makes all relabellings equiprobable. The validity of a p-value defined as the tail proportion of a statistic over a group of transformations under which the data are invariant, including the (1+#)/(1+b)(1 + \#)/(1 + b) rule, is proved on the permutation test page. □\square

Cost

The sort costs O(nlog⁡n)O(n \log n) comparisons. Lines L4 to L10 advance ii once for each subject, and lines L7 to L9 run at most once per distinct time, each with O(1)O(1) arithmetic operations, so the pass costs O(n)O(n). The space is the sorted index array, O(n)O(n), plus O(k)O(k) for the optional table of rows.

Complexity

The sort in line L1 costs Θ(nlog⁡n)\Theta(n \log n). Lines L4 to L10 process each subject once, with O(1)O(1) work per subject and per event time, so the pass costs Θ(n)\Theta(n) and the test Θ(nlog⁡n)\Theta(n \log n) time and Θ(n)\Theta(n) extra space in the real RAM model. The permutation version with bb relabellings costs Θ(b nlog⁡n)\Theta(b\, n \log n) as coded; sorting once and keeping the order makes it Θ(b n)\Theta(b\, n). Full enumeration costs (nn1)\binom{n}{n_1} passes and is feasible only for small nn. All terms of VV are non-negative, so VV has no cancellation; UU is a sum of signed terms, and the exact mode removes its rounding error.

Properties

  • Score test of the Cox model. With covariate xi=gix_i = g_i, the log partial likelihood with Breslow's tie handling has score UU at β=0\beta = 0 and information ∑jdjn1jn0j/nj2\sum_j d_j n_{1j} n_{0j}/n_j^2. With no tied event times this is VV. With ties, VV has the extra factor (nj−dj)/(nj−1)≤1(n_j - d_j)/(n_j - 1) \le 1 of the hypergeometric variance.
  • Asymptotic efficiency. Against proportional hazards alternatives h1=θh0h_1 = \theta h_0 with θ\theta near 1, the log-rank test is asymptotically efficient among rank tests (Peto and Peto 1972). Gehan's and Peto's weights put more weight on early times and are efficient against alternatives such as a shift of a logistic distribution; the Fleming-Harrington G0,1G^{0, 1} weight emphasizes late differences.
  • Number of events. Under proportional hazards with equal allocation, U/VU/\sqrt V is approximately N(D/4 log⁡θ,1)N(\sqrt{D/4}\,\log\theta, 1), where DD is the number of events (Schoenfeld 1981). So a two-sided test at level α\alpha with power 1−β1 - \beta needs about D=4(z1−α/2+z1−β)2/(log⁡θ)2D = 4(z_{1 - \alpha/2} + z_{1 - \beta})^2/(\log\theta)^2 events: 66 events for θ=2\theta = 2, α=0.05\alpha = 0.05 and power 0.8. See sample-size determination.
  • No censoring. With no censoring and no ties, Gehan's UU equals 2W−n1n02W - n_1 n_0, where WW is the number of pairs in which the group-1 time is the smaller: Gehan's test is then the Mann-Whitney test with a different variance.
  • Gehan's pair form. Gehan's U=∑i: gi=1∑l: gl=0[ϕ(i,l)−ϕ(l,i)]U = \sum_{i:\, g_i = 1}\sum_{l:\, g_l = 0}[\phi(i, l) - \phi(l, i)], where ϕ(a,b)=1\phi(a, b) = 1 if aa has an observed event and bb is known to outlast it (yb>yay_b > y_a, or yb=yay_b = y_a with bb censored).

Measured size and power, two-sided at α=0.05\alpha = 0.05. Event times are exponential; censoring is exponential with rate 0.2 in both groups, plus administrative censoring at time 3; r=4000r = 4000 replications, except r=2000r = 2000 for the last row. "Crossing" means group 1 has hazard 2 before time 0.4 and 0.4 after, against hazard 1 in group 0, so the survival curves cross at t=1.07t = 1.07.

setting n1+n0n_1 + n_0 seed log-rank Gehan FH G0,1G^{0,1}
H0H_0 10 + 10 12 0.061 0.052 0.082
H0H_0 30 + 30 11 0.059 0.057 0.063
H0H_0, censoring rate 2 in group 1 and none in group 0 15 + 45 13 0.053 0.050 0.074
hazard ratio 2 30 + 30 14 0.680 0.561 0.574
crossing 30 + 30 15 0.056 0.170 0.234
crossing 100 + 100 16 0.050 0.423 0.617

In the hazard ratio 2 row the expected number of events is 51.6, for which Schoenfeld's formula predicts power 0.70. In the crossing rows the early excess and the late deficit of events in group 1 nearly cancel in UU. The cancellation is not exact: the mean of UU is about −0.0026-0.0026 per subject, against a variance of about 0.19 per subject, so the power stays near the size at practical sample sizes (about 0.054 at n=1000n = 1000 and 0.14 at n=20 000n = 20\,000) and tends to 1 only very slowly.

Variants and improvements

  • Weighted log-rank tests. The weights above, chosen before seeing the data. A max-combination of several weighted statistics with a joint null distribution keeps the size while guarding against several shapes of alternative.
  • k groups. With groups 1,…,K1, \ldots, K, form the vector Ug=∑j(dgj−djngj/nj)U_g = \sum_j (d_{gj} - d_j n_{gj}/n_j) for g=1,…,K−1g = 1, \ldots, K - 1 and its covariance from the multivariate hypergeometric law, Cov(Ug,Uh)=∑jdj(nj−dj) ngj(1{g=h}nj−nhj)/(nj2(nj−1))\mathrm{Cov}(U_g, U_h) = \sum_j d_j(n_j - d_j)\, n_{gj}(1\{g = h\} n_j - n_{hj})/(n_j^2(n_j - 1)). The quadratic form UTV−1UU^{\mathsf T}V^{-1}U is asymptotically χK−12\chi^2_{K-1}. For ordered groups, a trend test uses scores sgs_g and has one degree of freedom.
  • Stratified test. Compute U(s)U^{(s)} and V(s)V^{(s)} within each stratum and add them before forming X2X^2. This is the Mantel-Haenszel combination of the tables over strata as well as over time.
  • Permutation version. Permuting labels gives an exact test when the censoring distributions are equal. With heavy censoring in the smaller group and none in the larger, it was far too conservative in a simulation: size 0.006 at nominal 0.05 (n1=15n_1 = 15, n0=45n_0 = 45, r=500r = 500 data sets, b=199b = 199 relabellings, seed 17), while the asymptotic test had 0.052.
  • Restricted mean survival time. When hazards are not proportional, comparing the areas under the two survival curves up to a time τ\tau gives an interpretable effect measure and a test.

When to use it

Use the log-rank test as the primary comparison of survival between randomized groups, especially when proportional hazards is plausible. Report it with the Kaplan-Meier curves and a hazard ratio from the Cox model. If early differences matter more, or the curves are expected to converge, prespecify a weighted test. If the curves may cross, prespecify a test that can detect that (a combination test or a restricted mean comparison); do not choose the weight after looking at the curves.

Pitfalls

  • Crossing hazards. As measured above, opposite differences at early and late times nearly cancel. A non-significant log-rank test does not show that the curves are equal.
  • Choosing the weight after the fact. Trying several weights and reporting the smallest p-value inflates the size.
  • Ties and censoring at the same time. Count censorings at tjt_j as at risk at tjt_j, and use the hypergeometric variance with the (nj−dj)/(nj−1)(n_j - d_j)/(n_j - 1) factor when events are tied.
  • Permutation with unequal censoring. Group labels are exchangeable only if the censoring is the same in both groups.
  • Informative or group-dependent dropout. Independent censoring within each group is required. If patients leave one arm because of side effects that predict their outcome, the test compares the wrong hazards.
  • Not an effect size. X2X^2 and the p-value do not measure how different the groups are. Give the hazard ratio or the difference in survival at a fixed time with an interval.
  • Small samples. The size can exceed α\alpha slightly, as in the 10 + 10 row above; the Fleming-Harrington G0,1G^{0,1} statistic, which rests on the few late events, deviates more.

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.

log_rank_core.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/log-rank-test/. The authors are listed in prov/W9TSMC.jsonl.

import itertools
import math
import random
from collections.abc import Sequence
from fractions import Fraction
from typing import NamedTuple

from stdist import chi2_sf


class Row(NamedTuple):
    """One distinct event time of the log-rank table."""

    time: float
    at_risk: int  # n_j
    at_risk1: int  # n_1j, at risk in group 1
    events: int  # d_j
    events1: int  # d_1j, events in group 1
    expected1: float  # E_1j = d_j n_1j / n_j
    variance: float  # V_j = n_1j n_0j d_j (n_j - d_j) / (n_j^2 (n_j - 1))
    weight: float  # w_j


class LogRankResult(NamedTuple):
    observed1: int  # O_1, events in group 1
    expected1: float  # E_1 = sum of E_1j
    score: float  # U = sum of w_j (d_1j - E_1j)
    variance: float  # V = sum of w_j^2 V_j
    statistic: float  # U^2 / V
    p_value: float  # upper tail of chi-square with 1 degree of freedom
    rows: list[Row]


WEIGHTS = ("logrank", "gehan", "tarone-ware", "peto-peto", "fleming-harrington")


def _check(times, events, groups):
    n = len(times)
    if n == 0 or len(events) != n or len(groups) != n:
        raise ValueError("times, events and groups must have the same positive length")
    if any(e not in (0, 1) for e in events) or any(g not in (0, 1) for g in groups):
        raise ValueError("event flags and group labels must be 0 or 1")
    if sum(groups) in (0, n):
        raise ValueError("both groups must be non-empty")


def log_rank(
    times: Sequence[float],
    events: Sequence[int],
    groups: Sequence[int],
    weights: str = "logrank",
    rho: float = 0.0,
    gamma: float = 0.0,
    exact: bool = False,
) -> LogRankResult:
    """Two-sample weighted log-rank test.

    times[i] = min(T_i, C_i), events[i] = 1 for an event and 0 for a censoring,
    groups[i] in {0, 1}. U > 0 means more events in group 1 than expected under
    equal hazards. weights: 'logrank' (w = 1), 'gehan' (w = n_j), 'tarone-ware'
    (w = sqrt(n_j)), 'peto-peto' (w = prod over t_l <= t_j of (1 - d_l/(n_l + 1)))
    or 'fleming-harrington' (w = S(t_j-)^rho (1 - S(t_j-))^gamma, S the pooled
    Kaplan-Meier). exact=True keeps the table and U and V as Fractions (only for
    the rational weights 'logrank' and 'gehan'). Cost: O(n log n).
    """
    _check(times, events, groups)
    if weights not in WEIGHTS:
        raise ValueError(f"weights must be one of {WEIGHTS}")
    if exact and weights not in ("logrank", "gehan"):
        raise ValueError("exact arithmetic needs rational weights")
    num = (lambda a, b: Fraction(a, b)) if exact else (lambda a, b: a / b)
    n = len(times)
    order = sorted(range(n), key=lambda k: times[k])  # @line L1
    r, r1, u, v = n, sum(groups), 0, 0  # @line L2
    km, peto = 1.0, 1.0  # pooled Kaplan-Meier S(t-) and the Peto-Peto product
    rows, o1, e1 = [], 0, 0
    i = 0  # @line L3
    while i < n:  # @line L4
        t, d, d1, m, m1 = times[order[i]], 0, 0, 0, 0  # @line L5
        while i < n and times[order[i]] == t:  # @line L6
            k = order[i]
            m += 1
            m1 += groups[k]
            if events[k]:
                d += 1
                d1 += groups[k]
            i += 1
        if d > 0:  # @line L7
            e = num(d * r1, r)  # @line L8
            var = num(r1 * (r - r1) * d * (r - d), r * r * (r - 1)) if r > 1 else 0 * e
            if weights == "logrank":
                w = 1
            elif weights == "gehan":
                w = r
            elif weights == "tarone-ware":
                w = math.sqrt(r)
            elif weights == "peto-peto":
                peto *= 1 - d / (r + 1)
                w = peto
            else:
                w = km**rho * (1 - km) ** gamma
            u += w * (d1 - e)  # @line L9
            v += w * w * var
            o1 += d1
            e1 += e
            rows.append(Row(t, r, r1, d, d1, e, var, w))
            km *= 1 - d / r
        r -= m  # @line L10
        r1 -= m1
    if v == 0:
        raise ValueError("the variance is zero: no event time with both groups at risk")
    stat = u * u / v  # @line L11
    return LogRankResult(o1, e1, u, v, stat, chi2_sf(float(stat), 1), rows)


def log_rank_permutation(
    times: Sequence[float],
    events: Sequence[int],
    groups: Sequence[int],
    weights: str = "logrank",
    b: int | None = None,
    rng: random.Random | None = None,
) -> float:
    """Two-sided permutation p-value of the weighted log-rank score U.

    Under H0 the labels are exchangeable given the observed (time, event)
    pairs; this holds when the two groups have the same censoring distribution.
    With b=None every relabelling with the same group sizes is enumerated and
    the p-value is the exact fraction with |U*| >= |U|. Otherwise b random
    relabellings give (1 + #{|U*| >= |U|}) / (1 + b).
    """
    _check(times, events, groups)
    n, n1 = len(times), sum(groups)

    def score(labels):
        try:
            return abs(log_rank(times, events, labels, weights=weights).score)
        except ValueError:  # V = 0 for this labelling; U is then 0 as well
            return 0.0

    obs = score(groups)
    tol = 1e-9 * (1 + obs)

    def extreme(labels):
        return score(labels) >= obs - tol

    if b is None:
        count = total = 0
        for chosen in itertools.combinations(range(n), n1):
            labels = [0] * n
            for k in chosen:
                labels[k] = 1
            total += 1
            count += extreme(labels)
        return count / total
    if rng is None:
        raise ValueError("pass a random.Random for the Monte Carlo version")
    labels = list(groups)
    count = 0
    for _ in range(b):
        rng.shuffle(labels)
        count += extreme(labels)
    return (1 + count) / (1 + b)
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
log_rank_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/log-rank-test/. The authors are listed in prov/W9TSMC.jsonl.
"""Entry point named after the slug. The code lives in log_rank_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from log_rank_core import WEIGHTS, LogRankResult, Row, log_rank, log_rank_permutation

__all__ = ["WEIGHTS", "LogRankResult", "Row", "log_rank", "log_rank_permutation"]
test_log_rank_test.py 194 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/log-rank-test/. The authors are listed in prov/W9TSMC.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from log_rank_test import log_rank, log_rank_permutation
from stdist import chi2_sf

# Freireich et al. (1963) leukemia trial, as listed by Gehan (1965). Group 1 is 6-MP, group 0 placebo.
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]
TIMES = MP_T + PL_T
EVENTS = MP_D + [1] * 21
GROUPS = [1] * 21 + [0] * 21


def random_two_sample(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)]
    groups = [rng.randint(0, 1) for _ in range(n)]
    groups[0], groups[-1] = 0, 1
    return times, events, groups


def test_leukemia_data() -> None:
    res = log_rank(TIMES, EVENTS, GROUPS, exact=True)
    assert res.observed1 == 9
    assert len(res.rows) == 17
    assert math.isclose(float(res.expected1), 19.2505, abs_tol=5e-5)
    assert math.isclose(float(res.score), -10.2505, abs_tol=5e-5)
    assert math.isclose(float(res.variance), 6.25696, abs_tol=5e-6)
    assert math.isclose(float(res.statistic), 16.7929, abs_tol=5e-5)
    assert math.isclose(res.p_value, 4.169e-5, rel_tol=1e-3)
    flt = log_rank(TIMES, EVENTS, GROUPS)
    assert math.isclose(flt.statistic, float(res.statistic), rel_tol=1e-12)
    # The first row: t = 1, 42 at risk, 21 in each group, 2 placebo events.
    first = res.rows[0]
    assert (first.time, first.at_risk, first.at_risk1, first.events, first.events1) == (1, 42, 21, 2, 0)
    assert first.expected1 == 1 and first.variance == Fraction(21 * 21 * 2 * 40, 42 * 42 * 41)


def test_rows_are_hypergeometric_moments() -> None:
    # At each event time, choose which d_j of the n_j at risk have the event, uniformly over
    # all C(n_j, d_j) subsets. The count from group 1 then has the mean E_1j and variance V_j.
    rng = random.Random(1966)
    for _ in range(150):
        times, events, groups = random_two_sample(rng, rng.randint(2, 14), rng.randint(1, 6), 0.3)
        try:
            res = log_rank(times, events, groups, exact=True)
        except ValueError:
            continue
        for row in res.rows:
            at_risk = [g for y, g in zip(times, groups) if y >= row.time]
            assert len(at_risk) == row.at_risk and sum(at_risk) == row.at_risk1
            counts = [sum(at_risk[k] for k in sub) for sub in itertools.combinations(range(row.at_risk), row.events)]
            mean = Fraction(sum(counts), len(counts))
            var = Fraction(sum(c * c for c in counts), len(counts)) - mean * mean
            assert row.expected1 == mean and row.variance == var


def test_gehan_weight_is_a_pair_count() -> None:
    def beats(a, b, y, d):
        # a has an observed event, and b is known to outlast a.
        return d[a] == 1 and (y[b] > y[a] or (y[b] == y[a] and d[b] == 0))

    rng = random.Random(1965)
    for _ in range(200):
        y, d, g = random_two_sample(rng, rng.randint(2, 20), rng.randint(1, 8), 0.4)
        try:
            res = log_rank(y, d, g, weights="gehan", exact=True)
        except ValueError:
            continue
        ones = [i for i in range(len(y)) if g[i] == 1]
        zeros = [k for k in range(len(y)) if g[k] == 0]
        pairs = sum(beats(i, k, y, d) - beats(k, i, y, d) for i in ones for k in zeros)
        assert res.score == pairs


def test_gehan_without_censoring_is_mann_whitney() -> None:
    rng = random.Random(1947)
    for _ in range(100):
        n = rng.randint(4, 16)
        y = rng.sample(range(100), n)
        g = [0, 1] + [rng.randint(0, 1) for _ in range(n - 2)]
        res = log_rank(y, [1] * n, g, weights="gehan", exact=True)
        n1 = sum(g)
        smaller = sum(1 for i in range(n) for k in range(n) if g[i] == 1 and g[k] == 0 and y[i] < y[k])
        assert res.score == 2 * smaller - n1 * (n - n1)


def test_score_test_of_the_cox_model() -> None:
    # Without ties U and V are the score and the information of the Cox partial likelihood at beta = 0.
    def partial_loglik(beta, y, d, g):
        total = 0.0
        for i in range(len(y)):
            if d[i]:
                risk = sum(math.exp(beta * g[k]) for k in range(len(y)) if y[k] >= y[i])
                total += beta * g[i] - math.log(risk)
        return total

    rng = random.Random(1972)
    for _ in range(50):
        n = rng.randint(4, 25)
        y = rng.sample(range(1, 200), n)
        d = [rng.randint(0, 1) for _ in range(n)]
        g = [0, 1] + [rng.randint(0, 1) for _ in range(n - 2)]
        try:
            res = log_rank(y, d, g)
        except ValueError:
            continue
        h = 1e-4
        score = (partial_loglik(h, y, d, g) - partial_loglik(-h, y, d, g)) / (2 * h)
        info = -(partial_loglik(h, y, d, g) - 2 * partial_loglik(0, y, d, g) + partial_loglik(-h, y, d, g)) / h**2
        assert math.isclose(score, res.score, abs_tol=1e-6)
        assert math.isclose(info, res.variance, rel_tol=1e-5, abs_tol=1e-6)


def test_permutation_matches_brute_force() -> None:
    def direct_score(y, d, g):
        u = Fraction(0)
        for t in sorted({y[i] for i in range(len(y)) if d[i]}):
            n = sum(1 for x in y if x >= t)
            n1 = sum(1 for x, h in zip(y, g) if x >= t and h)
            dt = sum(1 for x, e in zip(y, d) if x == t and e)
            d1 = sum(1 for x, e, h in zip(y, d, g) if x == t and e and h)
            u += d1 - Fraction(dt * n1, n)
        return u

    rng = random.Random(1972)
    for _ in range(12):
        n = rng.randint(4, 9)
        y, d, g = random_two_sample(rng, n, 6, 0.3)
        n1 = sum(g)
        obs = abs(direct_score(y, d, g))
        hits = total = 0
        for chosen in itertools.combinations(range(n), n1):
            lab = [1 if k in chosen else 0 for k in range(n)]
            total += 1
            hits += abs(direct_score(y, d, lab)) >= obs
        assert math.isclose(log_rank_permutation(y, d, g), hits / total, abs_tol=1e-12)


def test_monte_carlo_size() -> None:
    # H0: both groups Exp(1), censoring Exp(0.5) in both, 30 per group. r = 2000, seed 1966.
    rng = random.Random(1966)
    r, rejections = 2000, 0
    for _ in range(r):
        y, d = [], []
        for _ in range(60):
            a, b = rng.expovariate(1.0), rng.expovariate(0.5)
            y.append(min(a, b))
            d.append(1 if a <= b else 0)
        rejections += log_rank(y, d, [1] * 30 + [0] * 30).p_value < 0.05
    size = rejections / r
    assert abs(size - 0.05) < 4 * math.sqrt(0.05 * 0.95 / r) + 0.01


def test_symmetry_and_p_value() -> None:
    rng = random.Random(5)
    for _ in range(50):
        y, d, g = random_two_sample(rng, 30, 10, 0.3)
        try:
            a = log_rank(y, d, g, exact=True)
        except ValueError:
            continue
        b = log_rank(y, d, [1 - x for x in g], exact=True)
        assert a.score == -b.score and a.variance == b.variance and a.statistic == b.statistic
        assert math.isclose(a.p_value, chi2_sf(float(a.statistic), 1), rel_tol=1e-15)
        for w in ("tarone-ware", "peto-peto", "fleming-harrington"):
            assert 0 <= log_rank(y, d, g, weights=w, rho=1.0, gamma=1.0).p_value <= 1


def test_single_subject_at_risk_has_zero_variance() -> None:
    res = log_rank([1, 2, 3], [1, 1, 1], [0, 1, 0], exact=True)
    assert res.rows[-1].at_risk == 1 and res.rows[-1].variance == 0


def test_rejects_bad_input() -> None:
    with pytest.raises(ValueError):
        log_rank([1, 2], [1, 1], [1, 1])
    with pytest.raises(ValueError):
        log_rank([1, 2], [1, 1], [0, 2])
    with pytest.raises(ValueError):
        log_rank([1, 2], [1, 1], [0, 1], weights="wilcoxon")
    with pytest.raises(ValueError):
        log_rank([1, 2], [1, 1], [0, 1], weights="tarone-ware", exact=True)
    with pytest.raises(ValueError):
        log_rank([1, 2], [0, 0], [0, 1])

History

Nathan Mantel (1966) proposed to treat each event time as a 2×22 \times 2 table and to combine the tables by the method of Mantel and Haenszel (1959) for stratified tables. Richard and Julian Peto (1972) derived the same statistic as a locally most powerful rank invariant test, named it the logrank test because it uses the scores of the logarithm of the estimated survival, and also gave the Peto-Peto weights. Cox (1972) showed that it is the score test of his proportional hazards model, and in the Cox literature it is sometimes called the Mantel-Cox test. The weighted family grew from Gehan's (1965) generalization of the Wilcoxon test, Breslow's (1970) generalization of the Kruskal-Wallis test, Tarone and Ware (1977), and Harrington and Fleming (1982). Schoenfeld (1981) gave the power formula still used to plan trials.

References

  1. Nathan Mantel, Evaluation of survival data and two new rank order statistics arising in its consideration, Cancer Chemotherapy Reports 50(3), 1966, pp. 163 to 170 (the sum over event times of observed minus expected deaths, with the hypergeometric variances)
  2. Richard Peto and Julian Peto, Asymptotically efficient rank invariant test procedures, Journal of the Royal Statistical Society Series A 135(2), 1972, from p. 185 (the logrank test, its name, and its asymptotic efficiency against proportional hazards alternatives)
  3. David Schoenfeld, The asymptotic properties of nonparametric tests for comparing survival distributions, Biometrika 68(1), 1981, pp. 316 to 319 (the limit law under proportional hazards alternatives near the null, which gives the required number of events)
  4. John P. Klein and Melvin L. Moeschberger, Survival Analysis, Techniques for Censored and Truncated Data, 2nd edition, Springer, 2003, Chapter 7 (hypothesis testing, with the log-rank test, its weighted forms and the k-sample and stratified versions)
  5. Per Kragh Andersen, Ørnulf Borgan, Richard D. Gill and Niels Keiding, Statistical Models Based on Counting Processes, Springer, 1993, Chapter V (the k-sample tests with weight processes and their large-sample theory by martingale methods)

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.permutation
  • 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