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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 it forms the 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 , , with , and a group label . The subjects are independent, and censoring is independent within each group (see censoring). Group has hazard and survival function .
Hypotheses. for all (equivalently ) on the range where both groups are observed. The alternative is two-sided, . The one-sided form uses the sign of below. The test is built to detect with (proportional hazards).
Statistic. At the distinct event times of the pooled sample let and be the numbers at risk () overall and in group 1, , and and the events overall and in group 1. Then
The weighted log-rank family uses and with a weight that depends only on the data before and on , .
Null distribution. Asymptotic. Given the risk sets and the total at , is hypergeometric under with mean and variance , as in Fisher's exact test for that one table. The centred terms are uncorrelated across event times, and as , so . The proof is in the correctness file. A permutation version, which permutes the group labels among the observed pairs , is exact only when the two groups have the same censoring distribution.
Rejection rule and p-value. Reject at level when . The p-value is , computed as an upper tail without cancellation. Since is the square of a standard normal, this equals the two-sided normal p-value . The size is only near in finite samples.
The algorithm
LOG-RANK(y[1..n], δ[1..n], g[1..n], weight rule w)- 1
sort the indices 1..n by y - 2
r ← n; r1 ← number of i with g[i] = 1; U ← 0; V ← 0 - 3
i ← 1 - 4
while i ≤ n - 5
t ← y of the i-th sorted index; d ← 0; d1 ← 0; m ← 0; m1 ← 0 - 6
while 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 - 7
if d > 0 then - 8
E ← d · r1 / r; v ← r1 (r - r1) d (r - d) / (r² (r - 1)), or 0 if r = 1; compute the weight w - 9
U ← U + w (d1 - E); V ← V + w² v - 10
r ← r - m; r1 ← r1 - m1 ▷ everyone at t, censored or not, leaves after t - 11
X² ← 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 ; Gehan's ; Tarone and Ware's ; Peto and Peto's ; and the Fleming-Harrington weight , where is the pooled Kaplan-Meier estimate. With exact=True the table and and are exact fractions for the rational weights. A second function gives the two-sided permutation p-value, exact by enumeration for small or by random relabellings with the 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:
| 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 , . Over all 17 rows, against , so ; ; , and the p-value is . The placebo group had against . The 6-MP group relapsed less than equal hazards would predict. The weighted versions give (Gehan, ), (Tarone-Ware), (Peto-Peto) and (Fleming-Harrington with , ).
Correctness
The proof in proofs/correctness.md shows that the pass of lines L4 to L10 builds the table of , by the same invariant as for Kaplan-Meier. It then proves, for event times on a finite grid, that under and independent censoring given the past and is hypergeometric with mean and variance , that the terms are uncorrelated martingale differences, and that by a central limit theorem for a sum of independent terms plus Slutsky's theorem. Finally it shows that is the score of the Cox partial likelihood at , and that 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 , , with distinct event times of the pooled sample, , , , and .
Claim 1 (the pass computes the table). Line L9 is executed once for each , in increasing order of , and at that moment , , and . So the returned and are and .
Proof. After the sort of line L1, the inner loop of line L6 reads exactly the subjects whose time equals the current distinct time , and sets , , , to the numbers of subjects, group-1 subjects, events and group-1 events at . Invariant: at the start of the group at , and . It holds at the first group, where and by line L2. Line L10 subtracts all subjects at , censored or not, so afterwards , which is the count at risk at the next distinct time; the same holds for . Line L7 skips the times with no event, and at an event time the invariant gives and . Line L8 then computes and by their formulas, and line L9 adds the terms.
The null distribution
The asymptotic claims are proved for event and censoring times on a finite grid , which covers all data recorded in days, weeks or months. The conditions are:
- All times and take values in , and a subject censored at is at risk at , so and .
- The pairs are independent across subjects, identically distributed within each group, and is independent of . The censoring distribution may differ between the groups.
- Under both groups have the same discrete hazard at each .
- The group sizes satisfy as .
- , with defined in Claim 4. It holds when some has and positive probability of being at risk in both groups.
Write and . A grid time with no event contributes nothing to or , so sums over the event times equal sums over all with terms included.
Claim 2 (hypergeometric conditional law). Under conditions 1 to 3, let be the history of the whole sample strictly before together with the labels, and . Given , the set of subjects that fail at is uniform among the subsets of size of the risk set. Hence given is hypergeometric with
Proof. For a subject at risk at , the history says only that and , and by condition 2 the other subjects carry no information about it. So by the independence of and and condition 3, whatever the group. Given the failure indicators of the subjects at risk are therefore independent Bernoulli(). For any fixed subset of the risk set with , the probability that exactly fails is , which does not depend on , so given the total all subsets of size are equally likely.
Let indicate that the group-1 subject fails. Then and, for , , writing , , . The mean of is . Since
the variance is
For the variance is 0, which is the convention of line L8.
Claim 3 (uncorrelated increments, exact mean and variance). Let the weight be -measurable and bounded, which holds for all five weight rules, and let . Then , and for . Consequently and exactly, for every .
Proof. The first two identities are Claim 2 multiplied by the -measurable . For , is determined by the history before , so it is -measurable and . Summing gives and .
So is an unbiased estimate of the null variance of in finite samples. The normal approximation is asymptotic.
Claim 4 (asymptotic normality). Under conditions 1 to 5 and , for the log-rank weight , in distribution, so .
Proof. Let , , , , and for set and . Drop the grid points with , at which nobody is ever at risk.
Step 1 (an exact identity). For each with , and . Hence, for any numbers ,
with and .
Step 2 (moments of one subject). Fix and let . By the argument of Claim 2, , and when , so . Since and , . For , only if , and then and , so and . Therefore and
Step 3 (CLT for the main term). The are independent, bounded by , and
Since , the limit is , positive by condition 5. The total variance grows like while the summands stay bounded, so the Lindeberg condition holds, and the Lindeberg-Feller central limit theorem gives .
Step 4 (the remainder vanishes). By Step 2, is a sum of independent mean-zero terms with variance at most each, so and is bounded in probability. By the law of large numbers, and in probability, so . Each product tends to 0 in probability, and so does their finite sum. By Slutsky's theorem, .
Step 5 (the variance estimate). By the law of large numbers, , , , and averaged over the groups, which is . So , by continuity of this rational function where . Summing over the grid points, in probability. By Slutsky's theorem, , and by continuity of , .
The same proof covers a weight with in probability for deterministic constants and : Gehan's with , Tarone and Ware's with , and the Peto-Peto and Fleming-Harrington weights with , since and the Peto product converge to deterministic limits at each grid point. The exact identity of Step 1 holds term by term, so , and the limit variance is the limit of . For continuous time, the same result follows from Rebolledo's martingale central limit theorem applied to the counting process martingales ; 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 , the Cox log partial likelihood with Breslow's handling of ties is . Its derivative at is , and its negative second derivative at is , which equals when every .
Proof. , which is at , so . Differentiating again gives , which is at . When , .
Claim 6 (exact permutation test). If, in addition to conditions 2 and 3, both groups have the same censoring distribution, then under the pairs are independent and identically distributed over all subjects. Given the multiset of pairs, every assignment of the labels with ones is equally likely, so the permutation p-value over the relabellings satisfies for every , and the Monte Carlo version with 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 rule, is proved on the permutation test page.
Cost
The sort costs comparisons. Lines L4 to L10 advance once for each subject, and lines L7 to L9 run at most once per distinct time, each with arithmetic operations, so the pass costs . The space is the sorted index array, , plus for the optional table of rows.
Complexity
The sort in line L1 costs . Lines L4 to L10 process each subject once, with work per subject and per event time, so the pass costs and the test time and extra space in the real RAM model. The permutation version with relabellings costs as coded; sorting once and keeping the order makes it . Full enumeration costs passes and is feasible only for small . All terms of are non-negative, so has no cancellation; is a sum of signed terms, and the exact mode removes its rounding error.
Properties
- Score test of the Cox model. With covariate , the log partial likelihood with Breslow's tie handling has score at and information . With no tied event times this is . With ties, has the extra factor of the hypergeometric variance.
- Asymptotic efficiency. Against proportional hazards alternatives with 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 weight emphasizes late differences.
- Number of events. Under proportional hazards with equal allocation, is approximately , where is the number of events (Schoenfeld 1981). So a two-sided test at level with power needs about events: 66 events for , and power 0.8. See sample-size determination.
- No censoring. With no censoring and no ties, Gehan's equals , where 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 , where if has an observed event and is known to outlast it (, or with censored).
Measured size and power, two-sided at . Event times are exponential; censoring is exponential with rate 0.2 in both groups, plus administrative censoring at time 3; replications, except 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 .
| setting | seed | log-rank | Gehan | FH | |
|---|---|---|---|---|---|
| 10 + 10 | 12 | 0.061 | 0.052 | 0.082 | |
| 30 + 30 | 11 | 0.059 | 0.057 | 0.063 | |
| , 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 . The cancellation is not exact: the mean of is about 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 and 0.14 at ) 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 , form the vector for and its covariance from the multivariate hypergeometric law, . The quadratic form is asymptotically . For ordered groups, a trend test uses scores and has one degree of freedom.
- Stratified test. Compute and within each stratum and add them before forming . 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 (, , data sets, 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 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 as at risk at , and use the hypergeometric variance with the 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. 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 slightly, as in the 10 + 10 row above; the Fleming-Harrington 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.
# 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 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
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W9TSMC Edit this page History Report an error Markdown