Algorithmadvanced
Turnbull estimator
Also called Turnbull's self-consistency algorithm, NPMLE for interval-censored data.
The nonparametric MLE of the distribution of interval-censored times, found by self-consistency iterations, an EM algorithm, over Turnbull's innermost intervals.
- Time
- Θ(n log n + k n m) totalΘ(n m) per_iterationΘ(n + m) per_iteration_prefix_sumsΘ(n log n + n m) setup
- Space
- Θ(n m) extraΘ(n + m) extra_prefix_sums
- Where
- k = the number of iterations; m = the number of innermost intervals (m ≤ n); n = the number of observations
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bruce W. Turnbull, Richard Peto, 1976
The Turnbull estimator is the nonparametric maximum likelihood estimate (NPMLE) of a distribution when each event time is known only to lie in an interval . Such data arise when a condition is checked at clinic visits, so that an onset is known only to fall between the last negative and the first positive visit. Exact times () and right-censored times () are special cases, and on them the estimator is the Kaplan-Meier estimator. The likelihood depends on the distribution only through the probabilities of a few disjoint sets, Turnbull's innermost intervals, and the masses on them are found by the self-consistency iteration , which is the EM algorithm for this problem. The estimate of the survival function is determined between the innermost intervals and undetermined inside them.
In plain words
Each person's event happened somewhere inside a known window. We want the distribution of event times that makes these windows as likely as possible. Only a few places matter: the stretches where windows overlap as much as they can. The method starts with equal weight on each such stretch. Then, for each person, it splits that person between the stretches inside their window, in proportion to the current weights. Adding up these shares gives new weights. Repeating this never makes the fit worse, and it settles on the best weights. A simple test tells how far the current weights can still be from the best.
The problem
Input. Observations , , with , meaning that the event time satisfies . An exact time is , read as the point ; a right censoring at is ; a left censoring at is . The times are independent with distribution function , and the inspection process that produces the intervals is independent of (non-informative interval censoring).
Output. A distribution that maximizes the likelihood
represented by disjoint sets and masses with , and the survival function at every outside the .
Innermost intervals. Sort the endpoints; at equal values put the closed left ends of exact times first, then right ends, then open left ends. Each left end that is followed directly by a right end gives an innermost interval : , or the point when it comes from an exact time. With and , every maximizer of can be moved into the without loss, so the problem is the concave program
The algorithm
TURNBULL(L[1..n], R[1..n], ε)- 1
sort the 2n endpoints, at ties exact left ends, then right ends, then open left ends - 2
Q[1..m] ← the left ends followed directly by a right end, each paired with that right end - 3
α[i][j] ← 1 if Q[j] ⊆ I[i] else 0, for all i and j - 4
s[j] ← 1/m for all j - 5
repeat - 6
D[i] ← Σ_j α[i][j] s[j] for all i ▷ P(T ∈ I[i]) under s - 7
g[j] ← (1/n) Σ_i α[i][j] / D[i] for all j ▷ ∂ℓ/∂s[j] divided by n - 8
if max_j g[j] ≤ 1 + ε then exit the loop - 9
s[j] ← s[j] g[j] for all j ▷ expected share of Q[j], divided by n - 10
return Q, s and ℓ = Σ_i log D[i]
Line L9 is the E step and the M step at once: is the conditional probability that given , the sum over is the expected number of times in , and dividing by is the complete-data MLE. The new masses sum to 1 because ; the code renormalizes with math.fsum against rounding drift. The stopping rule of line L8 certifies the result: for the maximizer , so the returned log-likelihood is within of the maximum. A second function returns the lower and upper value of , which differ only for inside an innermost interval of positive width.
Example
Six patients are checked for a condition at irregular visits. Two were negative at week 1 and positive at week 5, one negative at 2 and positive at 7, one had a known onset at week 3, one was negative at 3 and positive at 6, and one negative at 5 and positive at 6: .
Sorted endpoints, with and marking left and right ends: . The adjacent pairs give , and . Their inclusion pattern is:
| observation | |||
|---|---|---|---|
| , twice | 1 | 1 | 0 |
| 1 | 1 | 1 | |
| 1 | 0 | 0 | |
| 0 | 1 | 1 | |
| 0 | 0 | 1 |
From , the are , so and , and the first step gives . The iteration converges to : at this point and , so the Kuhn-Tucker conditions hold and . From the uniform start it took 77, 133 and 189 iterations to reach , and : linear convergence, about 56 iterations per factor 1000.
The estimate is for , , and for . For it is anywhere in , and for in : the data do not say how the mass is spread inside and . No mass lies in , although three windows meet it, because each of them also contains , where the exact time needs mass.
Correctness
The proof in proofs/correctness.md shows that lines L1 and L2 find exactly the innermost intervals, and that for every point some innermost interval lies in every observation that contains , so a maximizer of exists with all its mass on the . It proves the Kuhn-Tucker characterization, is optimal if and only if for all with equality where , and the certificate used by line L8. It shows that each step of line L9 increases by at least times the Kullback-Leibler divergence between the new and the old masses, and that from the uniform start after steps, so the loop ends. Finally, the values are the same for every maximizer.
Proof: The innermost intervals carry a maximizer, the Kuhn-Tucker gap certifies the fit, and the self-consistency iteration increases the likelihood with a gap below n log m over kfull
Let the observations be for and for , , with allowed.
The innermost intervals
Keys. Give each endpoint a key: for the left end of an exact time, for a right end, for any other left end; and give each real point the key . Keys are compared lexicographically, which is the order of line L1. Then
For : holds exactly when , and exactly when . For : holds exactly when . So every observation is the set of points whose keys lie strictly between its two endpoint keys, and the problem becomes one about intervals on a line of keys. No left key equals a right key, since their second components differ.
A pair of positions in the sorted list with a left end at and a right end at defines . If the left end is open with value and the right end has value , this is , nonempty because a right end with value sorts before , so . If the left end is the exact time , its own right end is the first right key after , so and . These are the regions of line L2.
Lemma 1 (each region is inside or outside each observation). For every region and every , either or , and if and only if and . The regions are pairwise disjoint, and .
Proof. No endpoint key lies strictly between and , since they are adjacent. So each of is at most or at least . If both are at most or both at least , then and are disjoint; otherwise and , and . This is the test of the function contains. Two pairs cannot share a position, since position of one pair holds a right end and cannot be the left end of another, so the key ranges and hence the regions are disjoint. Each pair uses a different left end, so .
Lemma 2 (every point is dominated by a region). For a point let , and for a region let . For every there is a with . In particular every observation contains a region.
Proof. If is empty, any works. Otherwise let be the largest left key and the smallest right key among the observations in . Then , so comes before in the sorted list. The stretch of the list from to starts with a left end and ends with a right end, so somewhere in it a left end is directly followed by a right end. That pair gives a region with , and by Lemma 1, for every . For the last statement take any ; then , so the region found lies in .
Claim 1 (reduction to the regions). For every distribution of there are masses with for all , where . Every distribution that gives mass to has , however it spreads the mass inside each . Hence , and a maximizing gives the NPMLE.
Proof. The sets change only at endpoints, so the line splits into finitely many intervals on which is constant. Choose for each the smallest given by Lemma 2; it is constant on those intervals, so is measurable. Let . If and then , so , and
The second statement follows from Lemma 1: each lies entirely inside or outside .
The maximum exists: is continuous from the compact simplex to , and it is finite at the uniform point because every observation contains a region, so .
Optimality and the certificate
For with every , , and
Claim 2 (certificate). For every such and every , .
Proof. is concave, a sum of logarithms of linear functions, so it lies below its tangent plane: by (1), and because is a probability vector.
So when line L8 exits, the returned is within of the maximum.
Claim 3 (Kuhn-Tucker conditions). maximizes over if and only if for every . Then wherever .
Proof. If all , Claim 2 gives for all . Conversely, if for some , the direction stays in the simplex for small steps, and the derivative of along it is , so is not a maximizer. When all , (1) is a weighted average of the with weights that equals 1, so every with equals 1.
Claim 4 (uniqueness of the fitted probabilities). All maximizers have the same vector .
Proof. If two maximizers and had different vectors, their midpoint would satisfy , by strict concavity of on the coordinates where they differ.
The iteration
Line L9 maps to with . By (1), . Every region lies in the observation whose left end defines it, so whenever all ; from the uniform start every iterate has all and all .
Claim 5 (EM step). is one step of the EM algorithm for the complete data "the region that contains ".
Proof. Given and masses , the probability that is . The E step gives the expected count in , and the M step, the multinomial MLE from these counts, is .
Claim 6 (ascent). , where , with equality only if .
Proof. For each the weights are non-negative and sum to 1 over , and . By Jensen's inequality for the concave ,
using . Gibbs' inequality gives , with equality only for equal vectors.
Claim 7 (rate). Let be a maximizer and the uniform start. Then for every .
Proof. Fix with all and , and let be its update. For with , Claim 3 gives , so are weights summing to 1 over , and . By Jensen's inequality, . Multiplying by and summing over ,
The left side is . Summing over the steps telescopes:
since . By Claim 6 the terms decrease in , so the last one is at most the average, .
Claim 8 (the loop ends). For every , line L8 exits after finitely many iterations.
Proof. By Claim 7, . Suppose for infinitely many . Those iterates have a convergent subsequence in the compact simplex, with limit . Since is upper semicontinuous, , so is a maximizer and for all . The are continuous where all , so , which contradicts Claim 3.
The proved rate is sublinear, and the example on the algorithm page with a zero mass where shows that the iteration can be that slow. The faster linear convergence seen in other examples is only measured.
Special cases. For exact and right-censored data the regions are the distinct event times and, when the largest time is censored, the interval beyond it; the maximizer of Claim 1 is then the Kaplan-Meier estimate, by the NPMLE theorem in the Kaplan-Meier correctness proof. For current status data the maximizer is the isotonic regression of the indicators (Ayer et al. 1955).
Cost
The sort in line L1 costs , line L2 one pass over keys, and line L3 calls of contains, each . Lines L6 and L7 cost , and lines L8 and L9 cost , per iteration. By Lemma 1 the regions inside are those between two positions of the sorted list, a contiguous run ; with prefix sums , , and is obtained by adding to a difference array at and subtracting it at , so an iteration costs .
Complexity
The sort costs . A left end followed directly by a right end can occur at most times, so . Line L3 tests all pairs, , and lines L6 and L7 cost per iteration. Since the are disjoint and ordered and each is an interval, the inside form a contiguous run found by binary search. Then is a difference of prefix sums of , and is a prefix sum of a difference array, so an iteration costs . The number of iterations dominates the cost. The bound on the likelihood gap is proved, but the linear rate of the example is only observed, and it fails when a Kuhn-Tucker condition holds with equality at a zero mass. For the sets the maximizer is on with . There the middle mass decays like : 998, 31620 and 999980 iterations to reach , and .
Measured on simulated data with visits at weeks 1 to 4, each attended with probability 0.6, exponential with rate 0.5, and : the median number of iterations was 36 (maximum 3747) for , , seed 1978, and 31 (maximum 58) for , , seed 1979. Current status data (one inspection per subject) can be much slower: of 10 simulated current status data sets with between 5 and 30 (seed 1955), one with needed 75444 iterations to reach , and the others at most 599.
Properties
- Reduces to Kaplan-Meier. With only exact and right-censored times, the innermost intervals are the distinct event times plus the interval when the largest time is censored, and the NPMLE is the Kaplan-Meier estimator; its self-consistency equation is Efron's (1967).
- Current status data. When each subject is inspected once at and only is seen, the NPMLE of at the inspection times is the isotonic regression of the indicators, computed in after sorting by pool adjacent violators (Ayer et al. 1955).
- Partly unique. The probabilities of the observed sets are unique. The masses are unique under a rank condition on the matrix (Gentleman and Geyer 1994), and the spread of each mass inside is never identified.
- Slow statistical rate. Unlike Kaplan-Meier, the estimate is not -consistent in general. For current status data converges at rate with a non-normal limit (Groeneboom and Wellner 1992), so Greenwood-type standard errors do not apply. The bootstrap of the NPMLE is also unreliable in that case; inference on smooth functionals such as the mean is regular.
- Not online, deterministic. All intervals are needed before the innermost intervals are known.
Measured accuracy against the simple fix of replacing each interval by its midpoint and running Kaplan-Meier, for the visit design above, true : the Turnbull estimate had bias and root mean square error at (, seed 1978), and bias , RMSE at (, seed 1979). Midpoint imputation had bias and , RMSE and . Its bias does not shrink with .
Variants and improvements
- Truncation. Turnbull's paper also covers left-truncated data, where subject is observed only if lies in a set . The self-consistency equations then include the expected number of unobserved subjects, the "ghosts", whose times fall outside .
- Iterative convex minorant and hybrid algorithms. Groeneboom and Wellner (1992) maximize over the distribution function with the iterative convex minorant algorithm, which treats the monotonicity constraint directly. Wellner and Zhan (1997) alternate EM steps and ICM steps, which is much faster when EM is slow.
- Support reduction and Kuhn-Tucker pruning. Masses whose stays below 1 can be set to zero and the problem solved on the remaining support, then checked with the Kuhn-Tucker conditions.
- Smooth and parametric alternatives. A parametric model (Weibull or log-normal) fitted by maximum likelihood, or a spline or kernel-smoothed NPMLE, gives a unique curve inside the innermost intervals and rates under its assumptions.
- Bivariate and regression versions. The same EM step works for two-dimensional intervals (rectangles), and the semiparametric proportional hazards model for interval-censored data has an NPMLE of the baseline with the same structure.
When to use it
Use the Turnbull estimator for the survival curve whenever the event is detected at inspections rather than observed when it happens: onset of a disease found at screening visits, failure of equipment found at maintenance, seroconversion between blood tests. Report the estimate as steps over the innermost intervals, not as a continuous curve. For exact and right-censored data, Kaplan-Meier gives the same answer directly. Use the prefix-sum iteration or a hybrid EM-ICM solver for large , and always check the Kuhn-Tucker gap.
Pitfalls
- Midpoint or right-endpoint imputation. Treating each interval as an exact time at its midpoint or right end and running Kaplan-Meier gives a biased curve, as measured above; using the right end systematically delays the events.
- Stopping on small changes. EM can move very slowly, so a small change between iterations does not mean a near-optimal fit. Stop on the Kuhn-Tucker gap , which bounds the likelihood gap.
- Reading the curve inside an innermost interval. Any value between the two bounds is equally good. Plots that draw a straight line or a step at a chosen point inside add information that the data do not contain.
- Open and closed ends. Whether a visit time belongs to the left or the right set changes the innermost intervals. With visits on a common schedule, use throughout, and represent an exact time as a point, not as with an arbitrary .
- Informative inspection. If visits become more frequent after symptoms start, the inspection process depends on , and the likelihood is no longer correct.
- Starting values with zeros. A mass started at 0 stays at 0 under line L9. Start every positive.
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/turnbull-estimator/. The authors are listed in prov/0DBRMH.jsonl.
import math
from collections.abc import Sequence
from typing import NamedTuple
class Region(NamedTuple):
"""An innermost interval: (left, right] if left_open, else the single point [left, left]."""
left: float
right: float
left_open: bool
class TurnbullFit(NamedTuple):
regions: list[Region] # Q_1 < ... < Q_m, the innermost intervals
mass: list[float] # s_j, the probability of Q_j; sums to 1
loglik: float # sum over i of log P(T_i in I_i)
kkt_gap: float # max_j g_j - 1 >= 0; the log-likelihood is within n * kkt_gap of the maximum
iterations: int
def _check(left, right):
if len(left) == 0 or len(left) != len(right):
raise ValueError("left and right must have the same positive length")
for a, b in zip(left, right):
if math.isnan(a) or math.isnan(b) or a > b or a == math.inf:
raise ValueError("each observation needs left <= right and a finite left end")
def contains(region: Region, a: float, b: float) -> bool:
"""Whether the region lies inside the observation set: (a, b] if a < b, the point {a} if a == b."""
if a == b:
return not region.left_open and region.left == a
if region.left_open:
return a <= region.left and region.right <= b
return a < region.left <= b
def innermost_intervals(left: Sequence[float], right: Sequence[float]) -> list[Region]:
"""Turnbull's innermost intervals of the sets (left_i, right_i], with exact times left_i == right_i."""
_check(left, right)
ends = []
for a, b in zip(left, right):
# At equal values: a closed left end (an exact time) first, then right ends, then open left ends.
ends.append((a, 0 if a == b else 2, "L"))
ends.append((b, 1, "R"))
ends.sort() # @line L1
regions = []
for (x, kx, sx), (y, _, sy) in zip(ends, ends[1:]): # @line L2
if sx == "L" and sy == "R":
regions.append(Region(x, y, kx == 2))
return regions
def turnbull(
left: Sequence[float],
right: Sequence[float],
tol: float = 1e-9,
max_iter: int = 1_000_000,
) -> TurnbullFit:
"""The NPMLE of the distribution of T from the sets T_i in (left_i, right_i].
left_i == right_i is an exact time, right_i = inf a right censoring at left_i,
left_i = 0 with T > 0 a left censoring at right_i. Self-consistency (EM)
iterations run until max_j g_j <= 1 + tol, where g_j is (1/n) times the
derivative of the log-likelihood in s_j; then the log-likelihood is within
n * tol of its maximum. Cost per iteration: O(sum_i #{j : Q_j in I_i}).
"""
regions = innermost_intervals(left, right)
n, m = len(left), len(regions)
cover = [[j for j in range(m) if contains(regions[j], a, b)] for a, b in zip(left, right)] # @line L3
s = [1.0 / m] * m # @line L4
it = 0
while True: # @line L5
dens = [sum(s[j] for j in cover[i]) for i in range(n)] # @line L6
g = [0.0] * m # @line L7
for i in range(n):
for j in cover[i]:
g[j] += 1.0 / dens[i]
g = [x / n for x in g]
gap = max(g) - 1.0
if gap <= tol or it >= max_iter: # @line L8
break
s = [s[j] * g[j] for j in range(m)] # @line L9
total = math.fsum(s) # equal to 1 up to rounding, since sum_j s_j g_j = 1
s = [x / total for x in s]
it += 1
loglik = math.fsum(math.log(d) for d in dens)
return TurnbullFit(regions, s, loglik, max(gap, 0.0), it) # @line L10
def survival(fit: TurnbullFit, t: float) -> tuple[float, float]:
"""Bounds (lower, upper) of S(t) = P(T > t) over all NPMLEs with the fitted region masses.
The two agree unless t falls inside a region of positive width, where the
NPMLE does not say how the mass of the region is spread.
"""
lo = hi = 0.0
for q, w in zip(fit.regions, fit.mass):
if q.left_open:
if q.left >= t:
lo += w
if q.right > t:
hi += w
elif q.left > t:
lo += w
hi += w
return lo, hi
test_turnbull_estimator.py 218 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/turnbull-estimator/. The authors are listed in prov/0DBRMH.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
from turnbull_estimator import Region, contains, innermost_intervals, survival, turnbull
INF = math.inf
def loglik(cells_of_obs, p):
total = 0.0
for cells in cells_of_obs:
x = sum(p[c] for c in cells)
if x <= 0:
return -INF
total += math.log(x)
return total
def compositions(total, parts):
"""All tuples of `parts` non-negative integers that sum to `total`."""
for bars in itertools.combinations(range(total + parts - 1), parts - 1):
prev, out = -1, []
for b in bars:
out.append(b - prev - 1)
prev = b
out.append(total + parts - 2 - prev)
yield out
def random_interval_data(rng, n):
left, right = [], []
for _ in range(n):
a = rng.randint(0, 4)
b = rng.choice([x for x in range(a + 1, 5)] + [INF])
left.append(a)
right.append(b)
return left, right
def test_hand_example() -> None:
# Sets (0,2], (1,3], (2,4], (3,inf): innermost intervals (1,2], (2,3], (3,4]. The
# log-likelihood is log s1 + log(s1 + s2) + log(s2 + s3) + log s3, maximal at (1/2, 0, 1/2)
# with value 4 log(1/2). The KKT condition holds with equality at the zero mass, g_2 = 1,
# and there EM converges only sublinearly: s_2 is about 1/k after k iterations.
fit = turnbull([0, 1, 2, 3], [2, 3, 4, INF], tol=1e-8)
assert fit.regions == [Region(1, 2, True), Region(2, 3, True), Region(3, 4, True)]
assert abs(fit.mass[0] - 0.5) < 1e-3 and abs(fit.mass[2] - 0.5) < 1e-3 and fit.mass[1] < 1e-3
assert 4 * math.log(0.5) - 4 * fit.kkt_gap <= fit.loglik <= 4 * math.log(0.5)
assert 1000 < fit.iterations
lo, hi = survival(fit, 1)
assert math.isclose(lo, 1.0) and math.isclose(hi, 1.0)
lo, hi = survival(fit, 1.5)
assert math.isclose(lo, 1 - fit.mass[0]) and math.isclose(hi, 1.0)
def test_against_brute_force_npmle_on_a_grid() -> None:
# Endpoints in {0,...,4} or inf. The cells (0,1], ..., (3,4], (4,inf) carry the mass of any
# distribution as far as the likelihood is concerned. The brute force tries every mass vector
# on the simplex with step 1/16, 3876 vectors, without using the innermost intervals.
rng = random.Random(1976)
cells = [(k, k + 1) for k in range(4)] + [(4, INF)]
for _ in range(6):
left, right = random_interval_data(rng, rng.randint(4, 9))
n = len(left)
cells_of_obs = [[c for c, (u, v) in enumerate(cells) if a <= u and v <= b] for a, b in zip(left, right)]
best = max(loglik(cells_of_obs, [k / 16 for k in comp]) for comp in compositions(16, 5))
fit = turnbull(left, right, tol=1e-11)
assert fit.loglik >= best - 1e-9 # the EM limit is at least as good as every grid point
assert fit.loglik - best < 0.1 # and the grid comes close to it
# The certified bound: no distribution beats the fit by more than n * kkt_gap.
assert fit.kkt_gap <= 1e-11
for _ in range(200):
w = [rng.random() for _ in cells]
tot = sum(w)
assert loglik(cells_of_obs, [x / tot for x in w]) <= fit.loglik + n * fit.kkt_gap + 1e-12
def test_innermost_intervals_carry_every_signature() -> None:
# Each point of the line has a signature, the set of observations that contain it.
# Every signature is contained in the signature of some innermost interval, so moving
# mass into the innermost intervals never lowers the likelihood.
rng = random.Random(1955)
for _ in range(100):
n = rng.randint(1, 8)
left, right = [], []
for _ in range(n):
a = rng.randint(0, 6)
if rng.random() < 0.25:
left.append(a)
right.append(a) # an exact time
else:
left.append(a)
right.append(rng.choice([x for x in range(a + 1, 8)] + [INF]))
regions = innermost_intervals(left, right)
sig = [frozenset(i for i in range(n) if contains(q, left[i], right[i])) for q in regions]
for i in range(n):
assert any(i in s for s in sig) # every observation contains an innermost interval
points = [x / 2 for x in range(0, 20)]
for x in points:
s = frozenset(i for i in range(n) if (left[i] < x <= right[i]) or (left[i] == right[i] == x))
assert any(s <= t for t in sig)
for a, b in itertools.combinations(range(len(regions)), 2):
assert not (sig[a] < sig[b] or sig[b] < sig[a]) # no region is dominated by another
def pav(values, weights):
"""Weighted isotonic (nondecreasing) regression by pool adjacent violators, in Fractions."""
blocks = [] # [value, weight, count]
for v, w in zip(values, weights):
blocks.append([Fraction(v), Fraction(w), 1])
while len(blocks) > 1 and blocks[-2][0] > blocks[-1][0]:
v2, w2, c2 = blocks.pop()
v1, w1, c1 = blocks.pop()
blocks.append([(v1 * w1 + v2 * w2) / (w1 + w2), w1 + w2, c1 + c2])
out = []
for v, _, c in blocks:
out.extend([v] * c)
return out
def test_current_status_is_isotonic_regression() -> None:
# Current status data: at time c_i only delta_i = 1{T_i <= c_i} is seen, so the set is
# (0, c_i] or (c_i, inf). The NPMLE of F at the distinct c is the isotonic regression of
# the delta, the mean of the delta at each c weighted by the count (Ayer et al. 1955).
rng = random.Random(1955)
for _ in range(10):
n = rng.randint(5, 30)
c = [rng.randint(1, 10) for _ in range(n)]
t = [rng.expovariate(0.2) for _ in range(n)]
delta = [1 if ti <= ci else 0 for ti, ci in zip(t, c)]
left = [0 if d else ci for ci, d in zip(c, delta)]
right = [ci if d else INF for ci, d in zip(c, delta)]
xs = sorted(set(c))
means = [Fraction(sum(d for ci, d in zip(c, delta) if ci == x), c.count(x)) for x in xs]
f_hat = pav(means, [c.count(x) for x in xs])
ll_pav = sum(math.log(f_hat[xs.index(ci)] if d else 1 - f_hat[xs.index(ci)]) for ci, d in zip(c, delta))
fit = turnbull(left, right, tol=1e-9)
assert ll_pav - n * fit.kkt_gap - 1e-12 <= fit.loglik <= ll_pav + 1e-12
for x, f in zip(xs, f_hat):
lo, hi = survival(fit, x)
assert lo == hi # S is determined at the observation times
assert abs((1 - lo) - float(f)) < 1e-3
def kaplan_meier_exact(times, events):
"""S at each distinct time, by the product limit in Fractions."""
s, out = Fraction(1), {}
for t in sorted(set(times)):
n = sum(1 for y in times if y >= t)
d = sum(1 for y, e in zip(times, events) if y == t and e)
s *= 1 - Fraction(d, n)
out[t] = s
return out
def test_exact_and_right_censored_data_give_kaplan_meier() -> None:
rng = random.Random(1958)
for _ in range(25):
n = rng.randint(2, 25)
times = [rng.randint(1, 12) for _ in range(n)]
events = [1 if rng.random() < 0.6 else 0 for _ in range(n)]
events[0] = 1
left = list(times)
right = [y if e else INF for y, e in zip(times, events)]
fit = turnbull(left, right, tol=1e-12)
km = kaplan_meier_exact(times, events)
for t, s in km.items():
lo, hi = survival(fit, t)
assert math.isclose(lo, hi, abs_tol=1e-12)
assert abs(lo - float(s)) < 1e-6
def test_exact_times_give_the_empirical_distribution() -> None:
# Only exact times: the innermost intervals are the distinct times, the iteration stops
# at once, and the masses are the empirical frequencies.
rng = random.Random(1933)
for _ in range(25):
n = rng.randint(1, 30)
times = [rng.randint(0, 9) for _ in range(n)]
fit = turnbull(times, times, tol=1e-14)
assert [q.left for q in fit.regions] == sorted(set(times))
assert all(not q.left_open and q.left == q.right for q in fit.regions)
for q, w in zip(fit.regions, fit.mass):
assert math.isclose(w, float(Fraction(times.count(q.left), n)), rel_tol=1e-12)
for t in range(-1, 11):
lo, hi = survival(fit, t)
assert lo == hi and math.isclose(lo, sum(1 for y in times if y > t) / n, abs_tol=1e-12)
def test_self_consistency_at_the_limit() -> None:
# Turnbull's equation: s_j = (1/n) sum_i alpha_ij s_j / sum_l alpha_il s_l.
rng = random.Random(7)
left, right = random_interval_data(rng, 40)
fit = turnbull(left, right, tol=1e-13)
cover = [[j for j, q in enumerate(fit.regions) if contains(q, a, b)] for a, b in zip(left, right)]
dens = [sum(fit.mass[j] for j in cov) for cov in cover]
for j, s in enumerate(fit.mass):
rhs = sum(s / dens[i] for i in range(len(left)) if j in cover[i]) / len(left)
assert math.isclose(s, rhs, abs_tol=1e-12)
assert math.isclose(math.fsum(fit.mass), 1.0, rel_tol=1e-14)
def test_rejects_bad_input() -> None:
with pytest.raises(ValueError):
turnbull([], [])
with pytest.raises(ValueError):
turnbull([2], [1])
with pytest.raises(ValueError):
turnbull([INF], [INF])
with pytest.raises(ValueError):
turnbull([1, 2], [3])
History
Ayer, Brunk, Ewing, Reid and Silverman (1955) found the NPMLE for current status data as an isotonic regression. Efron (1967) introduced self-consistency for right-censored data, and Peto (1973) defined the NPMLE for general interval-censored data, observed that its support lies in the intervals between a left end and the next right end, and maximized the likelihood numerically. Turnbull (1976) gave the innermost intervals for grouped, censored and truncated data together with the self-consistency algorithm, one year before Dempster, Laird and Rubin (1977) described the EM algorithm in general, of which it is an instance. Groeneboom and Wellner (1992) developed the asymptotic theory and the iterative convex minorant algorithm, and Gentleman and Geyer (1994) used the Kuhn-Tucker conditions to verify that a computed solution is the NPMLE and to study its uniqueness.
References
- Bruce W. Turnbull, The empirical distribution function with arbitrarily grouped, censored and truncated data, Journal of the Royal Statistical Society Series B 38(3), 1976, pp. 290 to 295 (the innermost intervals, the self-consistency equations and the iteration, with truncation)
- Richard Peto, Experimental survival curves for interval-censored data, Applied Statistics 22(1), 1973, pp. 86 to 91 (the NPMLE for interval-censored data and its support on the intervals between a left end and the next right end)
- Robert Gentleman and Charles J. Geyer, Maximum likelihood for interval censored data, consistency and computation, Biometrika 81(3), 1994, pp. 618 to 623 (the Kuhn-Tucker conditions as a check of the computed NPMLE, and its uniqueness)
- Miriam Ayer, H. D. Brunk, G. M. Ewing, W. T. Reid and Edward Silverman, An empirical distribution function for sampling with incomplete information, Annals of Mathematical Statistics 26(4), 1955, pp. 641 to 647 (the NPMLE for current status data as a monotone regression)
- John P. Klein and Melvin L. Moeschberger, Survival Analysis, Techniques for Censored and Truncated Data, 2nd edition, Springer, 2003, Chapter 5 (estimation of the survival function for other sampling schemes, including Turnbull's algorithm for interval-censored data)
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 0DBRMH Edit this page History Report an error Markdown