Algorithm Search⌘K

Algorithmcore

Nelson-Aalen estimator

Also called Nelson-Aalen cumulative hazard estimator.

Estimates the cumulative hazard as the sum over event times of the deaths over the number at risk. It is a counting process martingale estimator.

Time
Θ(n log n) worst
Space
Θ(n) extra
Where
n = the number of subjects
Properties
deterministicexactofflineiterative
Origin
Wayne Nelson, Odd O. Aalen, 1972

The Nelson-Aalen estimator estimates the cumulative hazard H(t)=∫0th(u) duH(t) = \int_0^t h(u)\,du of an event time from right-censored data. At each distinct event time tjt_j it adds the number of events djd_j divided by the number njn_j still at risk:

H^(t)=∑j: tj≤tdjnj.\hat H(t) = \sum_{j:\, t_j \le t} \frac{d_j}{n_j}.

Each term estimates the hazard at tjt_j, the chance that a subject at risk has the event at that time, so the sum estimates the accumulated hazard. It uses the same table of njn_j and djd_j as the Kaplan-Meier estimator, which multiplies 1−dj/nj1 - d_j/n_j instead of adding dj/njd_j/n_j. Nelson-Aalen is the natural estimate when the quantity of interest is the hazard itself, for checking a parametric model by a plot, and for the baseline of the Cox model, where the Breslow estimator reduces to it when all coefficients are zero.

In plain words

Follow a group of patients over time. Each time someone has the event, look at how many people were still being watched just before, and write down one divided by that number (or the number of events divided by it, if several happen at once). Keep a running total. The total grows fast when events happen among few people at risk, and slowly when they happen among many. It measures how much risk has built up so far. People who leave the study early count in the totals until the time they leave and then stop counting.

The problem

Input. Observations (yi,δi)(y_i, \delta_i) for i=1,…,ni = 1, \ldots, n, with yi=min⁡(Ti,Ci)y_i = \min(T_i, C_i) the observed time and δi=1{Ti≤Ci}\delta_i = 1\{T_i \le C_i\} the event indicator, as on the censoring page.

Model. The subjects are independent, and censoring is independent: given that a subject is at risk just before tt, its chance of an event at tt is the hazard of TT at tt and does not depend on the censoring. In the counting process form, the number of observed events N(t)N(t) has intensity Y(t) h(t)Y(t)\,h(t), where Y(t)=#{i:yi≥t}Y(t) = \#\{i : y_i \ge t\} is the number at risk. This is Aalen's multiplicative intensity model.

Output. The distinct event times tjt_j with nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\} and dj=#{i:yi=tj,δi=1}d_j = \#\{i : y_i = t_j, \delta_i = 1\}, the values H^(tj)\hat H(t_j), and two variance estimates:

σ^P2(t)=∑tj≤tdjnj2,σ^B2(t)=∑tj≤tdj(nj−dj)nj3.\hat\sigma^2_{P}(t) = \sum_{t_j \le t} \frac{d_j}{n_j^2}, \qquad \hat\sigma^2_{B}(t) = \sum_{t_j \le t} \frac{d_j(n_j - d_j)}{n_j^3}.

The first (Aalen's) treats the events at tjt_j as Poisson, the second as binomial. They are close when every djd_j is small compared with njn_j, and the first is always the larger.

The algorithm

  1. NELSON-AALEN(y[1..n], δ[1..n])
  2. 1sort the indices 1..n by y
  3. 2r ← n; H ← 0; V ← 0; out ← empty list
  4. 3i ← 1
  5. 4while i ≤ n
  6. 5t ← y of the i-th sorted index; d ← 0; c ← 0
  7. 6while i ≤ n and y of the i-th sorted index = t: add 1 to d if δ = 1, else to c; i ← i + 1
  8. 7if d > 0 then H ← H + d/r; V ← V + d/r²; append (t, r, d, H, V) to out
  9. 8r ← r - d - c ▷ events and censorings at t leave after t
  10. 9return out

The structure is that of the Kaplan-Meier pass: a censored subject at tt is still in the risk set at tt. The code also accumulates σ^B2\hat\sigma^2_B in line L7, and it has a second tie rule, ties="sequential", which replaces d/rd/r by 1/r+1/(r−1)+⋯+1/(r−d+1)1/r + 1/(r - 1) + \cdots + 1/(r - d + 1). That is the value obtained if the dd tied events are taken to happen one after another in a very short time. The survival estimate exp⁡(−H^(t))\exp(-\hat H(t)) is a separate function.

Example

For the 6-MP arm of the leukemia trial (Freireich et al. 1963, as listed by Gehan 1965; the data are on the Kaplan-Meier page), the event times and the results are:

tjt_j njn_j djd_j dj/njd_j/n_j H^(tj)\hat H(t_j) exp⁡(−H^)\exp(-\hat H) Kaplan-Meier σ^P\hat\sigma_P
6 21 3 0.14286 0.14286 0.8669 0.8571 0.0825
7 17 1 0.05882 0.20168 0.8174 0.8067 0.1013
10 15 1 0.06667 0.26835 0.7646 0.7529 0.1213
13 12 1 0.08333 0.35168 0.7035 0.6902 0.1471
16 11 1 0.09091 0.44259 0.6424 0.6275 0.1730
22 7 1 0.14286 0.58545 0.5569 0.5378 0.2243
23 6 1 0.16667 0.75211 0.4714 0.4482 0.2795

Exactly, H^(23)=59071/78540\hat H(23) = 59071/78540. At t=6t = 6, with three tied events, σ^P2=3/441=0.00680\hat\sigma^2_P = 3/441 = 0.00680 and σ^B2=54/9261=0.00583\hat\sigma^2_B = 54/9261 = 0.00583; the sequential tie rule gives 1/21+1/20+1/19=0.150251/21 + 1/20 + 1/19 = 0.15025 instead of 3/21=0.142863/21 = 0.14286. At every time exp⁡(−H^)\exp(-\hat H) is above the Kaplan-Meier value, and the gap grows as dj/njd_j/n_j grows. If the hazard were constant, H^\hat H would grow linearly; here H^(t)/t\hat H(t)/t is about 0.0240.024 per week at t=6t = 6 and 0.0330.033 at t=23t = 23, but the late steps rest on risk sets of 6 and 7.

Correctness

The proof in proofs/correctness.md shows that the pass computes ∑tj≤tdj/nj\sum_{t_j \le t} d_j/n_j and the two variance sums, by the same invariant as for Kaplan-Meier. It then shows, for event times on a finite grid and under independent censoring, that M(t)=∑tj≤t(dj−qjnj)M(t) = \sum_{t_j \le t}(d_j - q_j n_j) is a martingale, where qjq_j is the discrete hazard; that E[H^(t)]=∑tj≤tqjP(nj>0)E[\hat H(t)] = \sum_{t_j \le t} q_j P(n_j > 0), so the bias is −∑tj≤tqjP(nj=0)-\sum_{t_j \le t} q_j P(n_j = 0); and that H^\hat H is the maximum likelihood estimate of the cumulative hazard ∑tj≤tqj\sum_{t_j \le t} q_j.

Proof: The pass computes the Nelson-Aalen sums, and in discrete time the estimate is a martingale estimator with an explicit bias and the MLE of the cumulative hazardfull

Let the data be (yi,δi)(y_i, \delta_i), i=1,…,ni = 1, \ldots, n, with distinct event times t1<⋯<tkt_1 < \cdots < t_k, nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\} and dj=#{i:yi=tj,δi=1}d_j = \#\{i : y_i = t_j, \delta_i = 1\}.

Claim 1 (the pass computes the sums). Every row that line L7 appends is (tj,nj,dj,∑l≤jdl/nl,∑l≤jdl/nl2)(t_j, n_j, d_j, \sum_{l \le j} d_l/n_l, \sum_{l \le j} d_l/n_l^2), one row for each jj, in order.

Proof. After the sort of line L1, the inner loop of line L6 reads exactly the subjects at the current distinct time uu, and sets dd and cc to the numbers of events and censorings at uu. Invariant: at the start of the group at uu, r=#{i:yi≥u}r = \#\{i : y_i \ge u\}, and HH and VV hold the two sums over the event times below uu. It holds at the first group, with r=nr = n and empty sums. Line L7 adds the terms of uu if uu is an event time, with r=njr = n_j at that moment, and line L8 removes the d+cd + c subjects at uu, so r=#{i:yi>u}r = \#\{i : y_i > u\}, which is the count at risk at the next distinct time. The same argument covers the binomial sum and the sequential tie rule, which only change the term added in line L7. □\square

For the remaining claims, fix a time tt, let the support of TT in (0,t](0, t] be a finite set s1<⋯<sms_1 < \cdots < s_m, and let qj=P(T=sj∣T≥sj)q_j = P(T = s_j \mid T \ge s_j) be the discrete hazard. The cumulative hazard of the discrete distribution is H(t)=∑j≤mqjH(t) = \sum_{j \le m} q_j. Observed event times in (0,t](0, t] are among the sjs_j, so H^(t)=∑j≤mdj/nj\hat H(t) = \sum_{j \le m} d_j/n_j, with dj=0d_j = 0 (and the term 00) where no event is observed, and the term 00 when nj=0n_j = 0. Assume:

  1. the subjects are independent;
  2. independent censoring in the sequential form: given everything observed before sjs_j (which determines who is at risk at sjs_j), each subject at risk at sjs_j has an event at sjs_j with probability qjq_j, independently of the others.

Condition 2 holds when the pairs (Ti,Ci)(T_i, C_i) are independent and TiT_i is independent of CiC_i. Let Fj\mathcal F_j be the information observed before sjs_j; then njn_j is Fj\mathcal F_j-measurable, and djd_j given Fj\mathcal F_j is binomial with njn_j trials and success probability qjq_j.

Claim 2 (martingale). Mj=∑l≤j(dl−qlnl)M_j = \sum_{l \le j}(d_l - q_l n_l) is a martingale with respect to Fj+1\mathcal F_{j+1}, and so is H^\hat H minus its compensator: Wj=∑l≤j(dl/nl−ql)1{nl>0}W_j = \sum_{l \le j}(d_l/n_l - q_l)1\{n_l > 0\}.

Proof. dl−qlnld_l - q_l n_l and (dl/nl−ql)1{nl>0}(d_l/n_l - q_l)1\{n_l > 0\} are Fl+1\mathcal F_{l+1}-measurable, bounded, and have conditional mean 00 given Fl\mathcal F_l, because E[dl∣Fl]=qlnlE[d_l \mid \mathcal F_l] = q_l n_l. A sum of bounded increments with conditional mean 00 is a martingale. □\square

Claim 3 (bias). E[H^(t)]=∑j≤mqj P(nj>0)E[\hat H(t)] = \sum_{j \le m} q_j\,P(n_j > 0), so H^(t)\hat H(t) is unbiased for H∗(t)=∑j≤mqj1{nj>0}H^*(t) = \sum_{j \le m} q_j 1\{n_j > 0\} in mean, and

H(t)−E[H^(t)]=∑j≤mqj P(nj=0)∈[0, H(t) P(nm=0)].H(t) - E[\hat H(t)] = \sum_{j \le m} q_j\,P(n_j = 0) \in \bigl[0,\ H(t)\,P(n_m = 0)\bigr].

Proof. E[Wm]=0E[W_m] = 0 by Claim 2, and H^(t)=Wm+∑jqj1{nj>0}\hat H(t) = W_m + \sum_j q_j 1\{n_j > 0\}. Take expectations. For the bound, nj≥nmn_j \ge n_m for j≤mj \le m, so P(nj=0)≤P(nm=0)P(n_j = 0) \le P(n_m = 0). □\square

Claim 4 (variance). Var(Wm)=∑j≤mE ⁣[qj(1−qj)nj1{nj>0}]\mathrm{Var}(W_m) = \sum_{j \le m} E\!\left[\frac{q_j(1 - q_j)}{n_j} 1\{n_j > 0\}\right], and dj(nj−dj)nj2(nj−1)\frac{d_j(n_j - d_j)}{n_j^2(n_j - 1)} (for nj≥2n_j \ge 2) has conditional mean qj(1−qj)nj\frac{q_j(1 - q_j)}{n_j} given Fj\mathcal F_j.

Proof. Martingale increments are uncorrelated: for l<jl < j, the increment at ll is Fj\mathcal F_j-measurable and the increment at jj has conditional mean 00 given Fj\mathcal F_j. So the variance of the sum is the sum of the expected conditional variances, and the conditional variance of dj/njd_j/n_j given Fj\mathcal F_j is qj(1−qj)/njq_j(1 - q_j)/n_j on {nj>0}\{n_j > 0\}. For the second statement, E[dj(nj−dj)∣Fj]=nj⋅njqj−(njqj(1−qj)+nj2qj2)=nj(nj−1)qj(1−qj)E[d_j(n_j - d_j) \mid \mathcal F_j] = n_j\cdot n_j q_j - (n_j q_j(1 - q_j) + n_j^2 q_j^2) = n_j(n_j - 1)q_j(1 - q_j). Divide by nj2(nj−1)n_j^2(n_j - 1). □\square

The binomial estimate σ^B2\hat\sigma^2_B of the code uses nj3n_j^3 in place of nj2(nj−1)n_j^2(n_j - 1), and Aalen's σ^P2=∑dj/nj2\hat\sigma^2_P = \sum d_j/n_j^2 has conditional mean ∑qj/nj\sum q_j/n_j, which is the continuous-time limit where qj(1−qj)≈qjq_j(1 - q_j) \approx q_j.

Claim 5 (maximum likelihood). Under conditions 1 and 2, with noninformative censoring, the likelihood of the hazards is ∏jqjdj(1−qj)nj−dj\prod_j q_j^{d_j}(1 - q_j)^{n_j - d_j} times a factor free of qq (the Kaplan-Meier correctness proof derives this product). Each factor is maximized uniquely at qj=dj/njq_j = d_j/n_j when nj>0n_j > 0. By the invariance of maximum likelihood under the map q↦∑j≤mqjq \mapsto \sum_{j \le m} q_j, H^(t)\hat H(t) is the MLE of H(t)H(t) in this model. □\square

Cost. One sort, Θ(nlog⁡n)\Theta(n \log n), and a pass in which each subject advances the index once, Θ(n)\Theta(n). The sequential tie rule adds djd_j terms at tjt_j, O(n)O(n) in total.

Complexity

Line L1 sorts in Θ(nlog⁡n)\Theta(n \log n) comparisons. Lines L4 to L8 handle each subject once with O(1)O(1) arithmetic, in Θ(n)\Theta(n). The total is Θ(nlog⁡n)\Theta(n \log n) time and Θ(n)\Theta(n) extra space in the real RAM model, and Θ(n)\Theta(n) if the data are already sorted. Every term is positive, so the floating-point sum has relative error at most about kk units in the last place for kk event times, with no cancellation.

Properties

  • Martingale and bias. In continuous time, N(t)−∫0tY(u) dH(u)N(t) - \int_0^t Y(u)\,dH(u) is a martingale, and H^(t)−H∗(t)\hat H(t) - H^*(t) with H∗(t)=∫0t1{Y(u)>0} dH(u)H^*(t) = \int_0^t 1\{Y(u) > 0\}\,dH(u) is a martingale with mean zero (Aalen 1978). So H^\hat H is unbiased for H∗H^*, and 0≤H(t)−EH^(t)≤H(t) P(Y(t)=0)0 \le H(t) - E\hat H(t) \le H(t)\,P(Y(t) = 0), which is exponentially small in nn when P(yi≥t)>0P(y_i \ge t) > 0.
  • Variance. The predictable variation of H^−H∗\hat H - H^* is ∫0t1{Y>0} dH/Y\int_0^t 1\{Y > 0\}\,dH/Y, estimated by σ^P2(t)\hat\sigma^2_P(t). With ties, ∑dj(nj−dj)/(nj2(nj−1))\sum d_j(n_j - d_j)/(n_j^2(n_j - 1)) is conditionally unbiased for the binomial variance; σ^B2\hat\sigma^2_B has njn_j in place of nj−1n_j - 1.
  • Large samples. If P(Y>τ)>0P(Y > \tau) > 0, then sup⁡t≤τ∣H^(t)−H(t)∣→0\sup_{t \le \tau}|\hat H(t) - H(t)| \to 0 in probability, and n(H^−H)\sqrt n(\hat H - H) converges to a Gaussian martingale with variance ∫0tdH(u)/π(u)\int_0^t dH(u)/\pi(u) for continuous HH, where π(u)=P(yi≥u)\pi(u) = P(y_i \ge u) (Andersen et al. 1993, Chapter IV).
  • Relation to Kaplan-Meier. exp⁡(−H^(t))≥S^KM(t)\exp(-\hat H(t)) \ge \hat S_{KM}(t), because e−x≥1−xe^{-x} \ge 1 - x term by term. The Kaplan-Meier estimate is the product integral of H^\hat H: S^KM(t)=∏tj≤t(1−ΔH^(tj))\hat S_{KM}(t) = \prod_{t_j \le t}(1 - \Delta\hat H(t_j)). Both are consistent for SS in continuous time, where the hazard increments are small.
  • Maximum likelihood. For a discrete model with hazards qjq_j at the observed event times, dj/njd_j/n_j is the MLE of qjq_j, and H^\hat H is the MLE of ∑qj\sum q_j.

The measured finite-sample behaviour, with T∼T \sim exponential with rate 1, independent C∼C \sim exponential with rate 0.5, tt with S(t)=0.5S(t) = 0.5 (H(t)=0.693H(t) = 0.693), r=10000r = 10000 replications and seed 1972:

nn mean of H^\hat H variance of H^\hat H mean of σ^P2\hat\sigma^2_P mean of σ^B2\hat\sigma^2_B plain 95% with σ^P\hat\sigma_P log-scale 95%
20 0.690 0.0658 0.0642 0.0569 0.915 0.960
50 0.691 0.0253 0.0248 0.0238 0.933 0.949
200 0.691 0.00619 0.00610 0.00604 0.946 0.949

The log-scale interval is H^exp⁡(±z σ^P/H^)\hat H \exp(\pm z\,\hat\sigma_P/\hat H). In the same runs, the mean of exp⁡(−H^)\exp(-\hat H) was 0.517 at n=20n = 20 against 0.502 for Kaplan-Meier, both for S(t)=0.5S(t) = 0.5.

Variants and improvements

  • Tie rules. The Breslow form dj/njd_j/n_j and the sequential form ∑l=0dj−11/(nj−l)\sum_{l=0}^{d_j - 1} 1/(n_j - l). The second is larger and corresponds to events that are distinct but recorded at the same time.
  • Delayed entry. With entry times viv_i, use the risk set {i:vi<tj≤yi}\{i : v_i < t_j \le y_i\}. The estimate is then of H(t)−H(v)H(t) - H(v).
  • Smoothed hazard. A kernel smoother applied to the increments of H^\hat H estimates the hazard h(t)h(t) itself (Ramlau-Hansen 1983).
  • Covariates. The Breslow estimator of the baseline cumulative hazard in the Cox model replaces njn_j by ∑i∈RjeβTxi\sum_{i \in R_j} e^{\beta^{\mathsf T}x_i}. Aalen's additive model gives covariate effects on the cumulative hazard scale.
  • Several states. The Nelson-Aalen estimates of the transition hazards of a multi-state model, combined by a product integral, give the Aalen-Johansen estimator of the transition probabilities, used for competing risks.

When to use it

Use Nelson-Aalen when the hazard is of interest: to see whether it is constant (H^\hat H linear in tt), Weibull (log⁡H^\log\hat H linear in log⁡t\log t) or proportional between groups (parallel log⁡H^\log\hat H curves). It is the building block for the cumulative incidence in competing risks and for the baseline hazard in regression. To estimate a survival probability, the Kaplan-Meier estimator is the standard choice; exp⁡(−H^)\exp(-\hat H) is close to it when risk sets are large.

Pitfalls

  • H^\hat H is not a probability. It can exceed 1, and it does when the curve continues long enough. 1−exp⁡(−H^)1 - \exp(-\hat H), not H^\hat H, is a probability.
  • Slope, not level. The hazard is the slope of HH. A large H^(t)\hat H(t) means much risk accumulated, not a high current hazard.
  • Ties in grouped data. With coarse time units many events share a time, and the two tie rules and the two variance estimates differ. Report which one is used.
  • Plain intervals near zero. For small H^\hat H the interval H^±zσ^\hat H \pm z\hat\sigma can go below 0 and undercovers. Use the log-scale interval.
  • The right tail. Late steps rest on few subjects and have large variance; σ^P2\hat\sigma^2_P grows by dj/nj2d_j/n_j^2 at each step.
  • Independent censoring. As for Kaplan-Meier, dependent censoring biases H^\hat H, and the data cannot reveal it.

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.

nelson_aalen_estimator.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nelson-aalen-estimator/. The authors are listed in prov/2X5FTW.jsonl.

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


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

    time: float
    at_risk: int  # n_j, the number with y_i >= t_j
    events: int  # d_j, the number of events at t_j
    cum_hazard: float  # H-hat(t_j)
    var_poisson: float  # sum over t_l <= t_j of d_l / n_l^2 (Aalen's estimate)
    var_binomial: float  # sum over t_l <= t_j of d_l (n_l - d_l) / n_l^3


def _increment(r: int, d: int, ties: str, exact: bool):
    if ties == "breslow":
        return Fraction(d, r) if exact else d / r
    if ties == "sequential":
        # The events at t_j are taken one after another: 1/r + 1/(r - 1) + ... + 1/(r - d + 1).
        s = sum((Fraction(1, r - l) for l in range(d)), Fraction(0))
        return s if exact else float(s)
    raise ValueError("ties must be 'breslow' or 'sequential'")


def nelson_aalen(times: Sequence[float], events: Sequence[int], exact: bool = False, ties: str = "breslow") -> list[Step]:
    """Nelson-Aalen estimate of the cumulative hazard from right-censored data.

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


def evaluate(steps: list[Step], t: float, field: str = "cum_hazard"):
    """The value of a step-function field at time t (0 before the first event time)."""
    value = 0
    for step in steps:
        if step.time > t:
            break
        value = getattr(step, field)
    return value


def survival_from_hazard(steps: list[Step], t: float) -> float:
    """The estimate exp(-H-hat(t)) of the survival function."""
    return math.exp(-float(evaluate(steps, t)))
test_nelson_aalen_estimator.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nelson-aalen-estimator/. The authors are listed in prov/2X5FTW.jsonl.

import math
import random
from fractions import Fraction

import pytest

from nelson_aalen_estimator import evaluate, nelson_aalen, survival_from_hazard

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


def direct(times, events, t):
    """Direct summation over the distinct event times s <= t of d(s)/n(s), d(s)/n(s)^2 and d(s)(n(s)-d(s))/n(s)^3."""
    h = v = w = Fraction(0)
    for s in sorted({y for y, e in zip(times, events) if e}):
        if s > t:
            break
        n = sum(1 for y in times if y >= s)
        d = sum(1 for y, e in zip(times, events) if y == s and e)
        h += Fraction(d, n)
        v += Fraction(d, n * n)
        w += Fraction(d * (n - d), n**3)
    return h, v, w


def test_six_mp_table() -> None:
    steps = nelson_aalen(MP_T, MP_D, exact=True)
    assert [(s.time, s.at_risk, s.events) for s in steps] == [
        (6, 21, 3), (7, 17, 1), (10, 15, 1), (13, 12, 1), (16, 11, 1), (22, 7, 1), (23, 6, 1)
    ]
    h = Fraction(3, 21) + Fraction(1, 17) + Fraction(1, 15) + Fraction(1, 12) + Fraction(1, 11) + Fraction(1, 7) + Fraction(1, 6)
    assert steps[-1].cum_hazard == h
    assert math.isclose(float(h), 0.75211, abs_tol=5e-6)
    assert math.isclose(float(steps[-1].var_poisson), 0.07810, abs_tol=5e-6)
    assert steps[0].var_poisson == Fraction(3, 441) and steps[0].var_binomial == Fraction(54, 9261)
    assert math.isclose(survival_from_hazard(steps, 23), 0.47137, abs_tol=5e-6)
    assert evaluate(steps, 5) == 0 and evaluate(steps, 100) == h


def test_against_direct_summation() -> None:
    rng = random.Random(1969)
    for _ in range(300):
        n = rng.randint(1, 25)
        times = [rng.randint(1, rng.randint(1, 12)) for _ in range(n)]
        p = rng.random()
        events = [0 if rng.random() < p else 1 for _ in range(n)]
        steps = nelson_aalen(times, events, exact=True)
        for t in range(0, max(times) + 2):
            h, v, w = direct(times, events, t)
            assert evaluate(steps, t) == h
            assert evaluate(steps, t, "var_poisson") == v
            assert evaluate(steps, t, "var_binomial") == w


def test_exp_minus_h_is_at_least_kaplan_meier() -> None:
    rng = random.Random(1972)
    for _ in range(200):
        n = rng.randint(1, 25)
        times = [rng.randint(1, 10) for _ in range(n)]
        events = [rng.randint(0, 1) for _ in range(n)]
        steps = nelson_aalen(times, events)
        s = 1.0
        for st in steps:
            s *= 1 - st.events / st.at_risk
            assert math.exp(-st.cum_hazard) >= s - 1e-15


def test_sequential_ties_equal_broken_ties() -> None:
    # Breaking the ties among events at t_j into distinct nearby times gives the sequential sum.
    rng = random.Random(1978)
    for _ in range(200):
        n = rng.randint(1, 20)
        times = [rng.randint(1, 6) for _ in range(n)]
        events = [rng.randint(0, 1) for _ in range(n)]
        seq = nelson_aalen(times, events, exact=True, ties="sequential")
        # Spread the events of each tie over distinct times just below the next integer.
        # Censorings at t move after all events at t, to t + 0.9, keeping them at risk.
        spread, k = [], {}
        for y, e in zip(times, events):
            if e:
                k[y] = k.get(y, 0) + 1
                spread.append(y + Fraction(k[y], 1000))
            else:
                spread.append(y + Fraction(9, 10))
        broken = nelson_aalen(spread, events, exact=True)
        for t in range(0, 8):
            assert evaluate(seq, t) == evaluate(broken, t + Fraction(1, 2))


def test_monte_carlo_mean_and_variance() -> None:
    # T ~ Exp(1), C ~ Exp(0.5), n = 40, t = log 2, so H(t) = log 2. r = 2000, seed 2026.
    rng = random.Random(2026)
    n, r, t = 40, 2000, math.log(2)
    hs, vs = [], []
    for _ in range(r):
        y, d = [], []
        for _ in range(n):
            a, b = rng.expovariate(1.0), rng.expovariate(0.5)
            y.append(min(a, b))
            d.append(1 if a <= b else 0)
        steps = nelson_aalen(y, d)
        hs.append(evaluate(steps, t))
        vs.append(evaluate(steps, t, "var_poisson"))
    mean = sum(hs) / r
    var = sum((x - mean) ** 2 for x in hs) / (r - 1)
    assert abs(mean - t) < 4 * math.sqrt(var / r)
    assert abs(sum(vs) / r / var - 1) < 0.15


def test_rejects_bad_input() -> None:
    with pytest.raises(ValueError):
        nelson_aalen([], [])
    with pytest.raises(ValueError):
        nelson_aalen([1, 2], [1, 3])
    with pytest.raises(ValueError):
        nelson_aalen([1, 2], [1, 1], ties="efron")

History

Wayne Nelson, an engineer at General Electric, introduced the cumulative hazard plot for censored failure data in 1969 and gave its theory in Technometrics in 1972: one plots the running sum of 1/nj1/n_j against time on paper scaled for a parametric family and reads off whether the family fits. Odd Aalen, in his 1975 Berkeley thesis and his 1978 Annals paper, placed the estimate in the theory of counting processes: for any counting process with intensity Y(t)h(t)Y(t)h(t), the estimator of ∫h\int h is a martingale transform, and martingale central limit theorems give its large-sample laws. This view, developed further by Gill and by Andersen, Borgan and Keiding, became the basis of modern survival analysis.

References

  1. Wayne Nelson, Hazard plotting for incomplete failure data, Journal of Quality Technology 1(1), 1969, pp. 27 to 52 (the cumulative hazard plot, with the sum of the reciprocals of the numbers at risk)
  2. Wayne Nelson, Theory and applications of hazard plotting for censored failure data, Technometrics 14(4), 1972, from p. 945 (the theory of the cumulative hazard estimate and its plots)
  3. Odd Aalen, Nonparametric inference for a family of counting processes, Annals of Statistics 6(4), 1978, pp. 701 to 726 (the multiplicative intensity model, the estimator of the integrated intensity and its martingale properties)
  4. Per Kragh Andersen, Ørnulf Borgan, Richard D. Gill and Niels Keiding, Statistical Models Based on Counting Processes, Springer, 1993, Chapter IV (the Nelson-Aalen estimator, its variance estimators, the tie conventions and the large-sample theory)
  5. John P. Klein and Melvin L. Moeschberger, Survival Analysis, Techniques for Censored and Truncated Data, 2nd edition, Springer, 2003, Chapter 4 (the Nelson-Aalen estimator of the cumulative hazard with its variance and confidence intervals)

Where this leads

About this page

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

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