Algorithm Search⌘K

Techniqueadvanced

Partial likelihood

Also called Cox partial likelihood.

Cox's likelihood for beta that multiplies, over event times, the chance that the unit that failed is the one to fail among those at risk. The baseline hazard drops out.

The partial likelihood is the function of β\beta that Cox used to fit the proportional hazards model h(t∣x)=h0(t)exp⁡(βTx)h(t \mid x) = h_0(t)\exp(\beta^{\mathsf T}x) without any model for h0h_0. At each event time tjt_j it takes the probability that the event happened to the subject that had it, given that exactly one event happened among the subjects at risk:

L(β)=∏jexp⁡(βTx(j))∑i∈R(tj)exp⁡(βTxi),R(tj)={i:yi≥tj}.L(\beta) = \prod_{j} \frac{\exp(\beta^{\mathsf T}x_{(j)})}{\sum_{i \in R(t_j)} \exp(\beta^{\mathsf T}x_i)}, \qquad R(t_j) = \{i : y_i \ge t_j\}.

The factor h0(tj) dth_0(t_j)\,dt is the same in the numerator and in every term of the denominator, so it cancels. The result is not the likelihood of the data, but Cox (1975) and Andersen and Gill (1982) showed that its maximizer behaves like a maximum likelihood estimate. The log of LL is concave, and one sort followed by running sums gives each Newton step in O(np2)O(np^2) time.

In plain words

At each moment when someone has the event, look at everyone who could have had it then. Under the model, each of them had a chance proportional to eβTxe^{\beta^{\mathsf T}x}, their relative risk. The partial likelihood asks how probable it was that the person who actually had the event was the one picked. Multiply these chances over all event times. Good values of β\beta make the people who had events look like the high-risk members of their risk sets. The baseline hazard tells us when events happen, but not who has them, so it does not enter. Censored people count in every risk set up to the time they leave.

When it applies

  • The model is a relative risk model: hi(t)=h0(t) r(β,xi(t))h_i(t) = h_0(t)\,r(\beta, x_i(t)) with the same unknown h0h_0 for every subject, usually r=eβTxr = e^{\beta^{\mathsf T}x}. Covariates may change in time.
  • Censoring and delayed entry are independent: given the past, leaving or entering the risk set does not depend on the future event times. The risk set at tt is then exactly the set of subjects under observation just before tt.
  • The idea works for any process where the probability of "which unit" at each step does not depend on the nuisance parameter that rules "when". Cox (1975) gives the general definition. A matched case-control study with one case per set has the same form, which gives conditional logistic regression.
  • It does not apply directly when the hazards of different subjects have different baseline functions (use strata), or when h0h_0 itself is the target (use the Breslow estimator after the fit).

The template

  1. COX-NEWTON(y[1..n], δ[1..n], x[1..n], ties)
  2. 1sort the subjects by decreasing y
  3. 2β ← 0
  4. 3repeat
  5. 4S0 ← 0; S1 ← 0; S2 ← 0; ℓ ← 0; U ← 0; I ← 0
  6. 5for each distinct time t, from the largest down
  7. 6add w_i, w_i x_i and w_i x_i x_iᵀ to S0, S1, S2 for each i with y_i = t ▷ w_i = exp(βᵀx_i)
  8. 7if t has d > 0 events, add their terms to ℓ, U and I ▷ hole: the rule for ties
  9. 8Δ ← I⁻¹ U; halve Δ until ℓ(β + Δ) ≥ ℓ(β)
  10. 9β ← β + Δ
  11. 10until every entry of Δ is small
  12. 11return β, ℓ, I⁻¹

Line L1 is the only sort. Because the times are visited from the largest down, the sums S0=∑i∈R(t)wiS_0 = \sum_{i \in R(t)} w_i, S1=∑i∈R(t)wixiS_1 = \sum_{i \in R(t)} w_i x_i and S2=∑i∈R(t)wixixiTS_2 = \sum_{i \in R(t)} w_i x_i x_i^{\mathsf T} only grow, so line L6 keeps them as running prefix sums of positive terms, without subtraction. A censored subject tied with an event time joins the sums before line L7, so it is in the risk set at that time.

The terms of line L7. Let DD be the set of the dd subjects with an event at tt, s=∑i∈Dxis = \sum_{i \in D} x_i, and xˉ=S1/S0\bar x = S_1/S_0. Then:

  • Breslow (1974): ℓ\ell gains βTs−dlog⁡S0\beta^{\mathsf T}s - d\log S_0, UU gains s−dxˉs - d\bar x, and II gains d (S2/S0−xˉxˉT)d\,(S_2/S_0 - \bar x\bar x^{\mathsf T}). It treats the dd events as if each had the whole risk set.
  • Efron (1977): the rr-th event, r=0,…,d−1r = 0, \ldots, d - 1, sees the risk set with a fraction r/dr/d of each dead subject removed: replace (S0,S1,S2)(S_0, S_1, S_2) by (S0−rdD0,S1−rdD1,S2−rdD2)(S_0 - \tfrac rd D_0, S_1 - \tfrac rd D_1, S_2 - \tfrac rd D_2), where DkD_k are the same sums over DD, and add the dd single-event terms.
  • Exact (Cox's discrete model): ℓ\ell gains βTs−log⁡ed\beta^{\mathsf T}s - \log e_d, where ed=∑A⊆R(t), ∣A∣=dexp⁡(βT∑i∈Axi)e_d = \sum_{A \subseteq R(t),\, |A| = d} \exp(\beta^{\mathsf T}\sum_{i \in A} x_i). The recursion of Gail, Lubin and Rubinstein (1981) computes ede_d, its gradient and its Hessian over the risk set in O(∣R(t)∣ d p2)O(|R(t)|\,d\,p^2) time.

With d=1d = 1 the three rules agree.

The log partial likelihood is concave. For each rule, ℓ(β)\ell(\beta) is a linear function minus a sum of functions of the form log⁡∑kckexp⁡(βTzk)\log \sum_k c_k \exp(\beta^{\mathsf T}z_k) with ck>0c_k > 0. Proof. For Breslow, the sum is S0=∑i∈R(t)exp⁡(βTxi)S_0 = \sum_{i \in R(t)} \exp(\beta^{\mathsf T}x_i). For Efron, it is S0−rdD0S_0 - \tfrac rd D_0, in which each dead subject has the coefficient 1−r/d>01 - r/d > 0 and each other subject the coefficient 11. For the exact rule, it is ede_d, a sum over subsets with zA=∑i∈Axiz_A = \sum_{i \in A} x_i. Now let g(β)=log⁡∑kckeβTzkg(\beta) = \log \sum_k c_k e^{\beta^{\mathsf T}z_k} and πk=ckeβTzk/∑mcmeβTzm\pi_k = c_k e^{\beta^{\mathsf T}z_k}/\sum_m c_m e^{\beta^{\mathsf T}z_m}. Then ∇g=∑kπkzk\nabla g = \sum_k \pi_k z_k and

∇2g=∑kπkzkzkT−(∑kπkzk)(∑kπkzk)T=Cov⁡π(z),\nabla^2 g = \sum_k \pi_k z_k z_k^{\mathsf T} - \Bigl(\sum_k \pi_k z_k\Bigr)\Bigl(\sum_k \pi_k z_k\Bigr)^{\mathsf T} = \operatorname{Cov}_\pi(z),

the covariance matrix of zz under the weights π\pi, which is positive semidefinite. So each gg is a convex function, and ℓ\ell, a linear function minus a sum of convex functions, is concave. □\square

The information matrix I=−∇2ℓI = -\nabla^2\ell is the sum of these weighted covariance matrices. It is positive definite, and ℓ\ell is strictly concave, when the vectors xi−xkx_i - x_k for i,ki, k in a common risk set at an event time span Rp\mathbb{R}^p. Then the maximizer is unique if it exists, and Newton's method with the step halving of line L8 converges to it. Each Newton step costs O(np2)O(np^2) for the sums plus O(p3)O(p^3) for the solve, and the sort of line L1 costs O(nlog⁡n)O(n \log n) once. The reference code sorts again in each evaluation, which adds O(nlog⁡n)O(n \log n) per step and keeps the code short.

The score test at β=0\beta = 0 is the log-rank test. Take one binary covariate (xi=1x_i = 1 in group 1, 00 in group 0). Let njn_j and n1jn_{1j} be the numbers at risk in all and in group 1 at tjt_j, n0j=nj−n1jn_{0j} = n_j - n_{1j}, djd_j the number of events and o1jo_{1j} the number of events in group 1.

No ties. At β=0\beta = 0 all wi=1w_i = 1, so xˉ=n1j/nj\bar x = n_{1j}/n_j and S2/S0=n1j/njS_2/S_0 = n_{1j}/n_j (since x2=xx^2 = x). The score is U(0)=∑j(o1j−n1j/nj)=O−EU(0) = \sum_j (o_{1j} - n_{1j}/n_j) = O - E, and the information is I(0)=∑jn1jnj(1−n1jnj)=∑jn1jn0jnj2I(0) = \sum_j \frac{n_{1j}}{n_j}\bigl(1 - \frac{n_{1j}}{n_j}\bigr) = \sum_j \frac{n_{1j}n_{0j}}{n_j^2}. With dj=1d_j = 1, the hypergeometric variance of the log-rank test, n1jn0jdj(nj−dj)nj2(nj−1)\frac{n_{1j}n_{0j}d_j(n_j - d_j)}{n_j^2(n_j - 1)}, is also n1jn0jnj2\frac{n_{1j}n_{0j}}{n_j^2}. So U(0)2/I(0)=(O−E)2/VU(0)^2/I(0) = (O - E)^2/V, the log-rank statistic. □\square

Exact rule with ties. At β=0\beta = 0, ed(β)/(njdj)=E[exp⁡(βS)]e_d(\beta)/\binom{n_j}{d_j} = E[\exp(\beta S)], where SS is the number of group 1 subjects in a uniformly random subset of size djd_j of R(tj)R(t_j). So log⁡ed\log e_d is a cumulant generating function plus a constant, its gradient at 00 is E[S]=djn1j/njE[S] = d_j n_{1j}/n_j and its Hessian at 00 is Var⁡(S)\operatorname{Var}(S). SS is hypergeometric, with variance n1jn0jdj(nj−dj)nj2(nj−1)\frac{n_{1j}n_{0j}d_j(n_j - d_j)}{n_j^2(n_j - 1)}. So the exact-rule score test at 00 is the log-rank test with its usual hypergeometric variance, for any ties. □\square

Breslow rule with ties. The score is still O−EO - E, but the information is ∑jdjn1jn0j/nj2\sum_j d_j n_{1j}n_{0j}/n_j^2, the binomial variance, which is larger than the hypergeometric one by the factor (nj−1)/(nj−dj)(n_j - 1)/(n_j - d_j) at each time with dj≥2d_j \ge 2. So the Breslow score statistic is a little smaller than the log-rank statistic. The Efron score at 00 is not O−EO - E when there are ties.

Classic examples

A hand example. Five subjects with times 1,2,3+,4,51, 2, 3^+, 4, 5 (3+3^+ censored) and x=1,0,1,0,1x = 1, 0, 1, 0, 1. The risk sets at the event times 1, 2, 4 and 5 have the covariates {1,0,1,0,1}\{1,0,1,0,1\}, {0,1,0,1}\{0,1,0,1\}, {0,1}\{0,1\} and {1}\{1\}. At β=0\beta = 0 the weighted means are 3/53/5, 1/21/2, 1/21/2 and 11, so

U(0)=(1−35)+(0−12)+(0−12)+(1−1)=−35,I(0)=625+14+14+0=3750,U(0) = (1 - \tfrac35) + (0 - \tfrac12) + (0 - \tfrac12) + (1 - 1) = -\tfrac35, \qquad I(0) = \tfrac{6}{25} + \tfrac14 + \tfrac14 + 0 = \tfrac{37}{50},

and ℓ(0)=−log⁡(5⋅4⋅2⋅1)=−3.6889\ell(0) = -\log(5 \cdot 4 \cdot 2 \cdot 1) = -3.6889. The score statistic is U2/I=18/37=0.486U^2/I = 18/37 = 0.486. Newton's method from 00 stops after 5 steps at β^=−0.8341\hat\beta = -0.8341 with ℓ(β^)=−3.4433\ell(\hat\beta) = -3.4433 and I(β^)=0.6611I(\hat\beta) = 0.6611, so the likelihood ratio statistic is 0.4910.491 and the standard error is 1.2301.230. The last risk set has one member, so its factor is 11 for every β\beta: a subject alone in its risk set gives no information.

The leukemia data and the three rules for ties. For the Gehan data of the Cox model page (x=1x = 1 for placebo, 30 events at 17 distinct times, with up to 4 events at one time):

ties ℓ(0)\ell(0) ℓ(β^)\ell(\hat\beta) β^\hat\beta standard error I(0)I(0) score statistic
Breslow -93.985 -86.380 1.5092 0.4096 6.596 15.93
Efron -93.184 -85.008 1.5721 0.4124 6.482 17.25
exact -82.669 -74.543 1.6282 0.4331 6.257 16.79

The score U(0)=O−E=10.2505U(0) = O - E = 10.2505 for Breslow and the exact rule. The exact information 6.2576.257 is the log-rank variance and 10.25052/6.257=16.7910.2505^2/6.257 = 16.79 is the log-rank statistic. The Breslow information is larger, so its statistic is smaller, as proved above. With many ties, Breslow pulls β^\hat\beta toward 00 compared with the exact rule; Efron lies between them here and is the default of most software.

Matched case-control studies. If each matched set has one case and the controls, and the "risk set" is the matched set, the partial likelihood is the conditional likelihood of the conditional logistic regression for matched data. Survival software fits such studies with the exact rule.

Strata. With strata ss, each with its own h0sh_{0s}, the log partial likelihood is the sum over strata of the stratum log partial likelihoods. The sort and the running sums are done within each stratum.

Variations

  • Time-dependent covariates. If xi(t)x_i(t) changes in time, the risk-set sums must use the values at each tjt_j. Split each subject into intervals with constant covariates and use risk sets {i:ai<tj≤yi}\{i : a_i < t_j \le y_i\}. The running sums then need both entries and exits, so they are computed by a pass in time order that adds and removes intervals.
  • Delayed entry. A subject that enters at time aia_i is in R(t)R(t) only for ai<t≤yia_i < t \le y_i. The same pass with entries and exits handles it.
  • Weighted partial likelihood. Weights vi(t)v_i(t) in the risk-set sums give the case-cohort designs, inverse probability weighting and the Fine-Gray model, where subjects with a competing event stay in the risk set with a censoring weight.
  • Penalized partial likelihood. A penalty on β\beta (ridge or lasso) keeps the problem concave. The Firth penalty, 12log⁡det⁡I(β)\frac12 \log\det I(\beta), gives finite estimates under a monotone likelihood (Heinze and Schemper 2001).
  • Robust variance. If the subjects are clustered or the model is not exactly right, replace I−1I^{-1} by a sandwich estimate built from the score residuals, as with cluster-robust standard errors.

Pitfalls

  • It is not a full likelihood. Do not compare ℓ(β^)\ell(\hat\beta) across data sets or with a parametric likelihood. Differences of ℓ\ell for nested models with the same data and risk sets give valid likelihood ratio tests.
  • Ties. With many ties, the Breslow rule is biased toward 00. Use Efron, or the exact rule when the ties come from a truly discrete time scale.
  • The monotone likelihood. If, for some direction, the subjects with events always have the largest score in their risk sets, ℓ\ell increases without bound. Newton's steps then grow in that direction, the reported β^\hat\beta depends on when the iteration stopped, and the Wald test is useless. Check for a slowly increasing ℓ\ell and a huge standard error. The reference code reports converged = False.
  • Overflow. exp⁡(βTxi)\exp(\beta^{\mathsf T}x_i) overflows for large scores. Subtract the largest βTxi\beta^{\mathsf T}x_i before taking exponentials. The shift cancels in every ratio.
  • Cancellation. A pass forward in time that subtracts the subjects who leave from S0S_0 can lose all digits when the late weights are small. The backward pass of line L5 only adds.
  • Tied censoring. A censored time equal to an event time must count as at risk at that time. Changing this convention changes β^\hat\beta.
  • Only the measured part is measured. The large-sample results are cited (Andersen and Gill 1982), not proved here. The tests of the reference code measure the size of the score test at level 0.05 in one setting (2000 data sets of 40 subjects), which says nothing about small samples with heavy censoring.

Code

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.

cox_partial_likelihood.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cox-partial-likelihood/. The authors are listed in prov/9HJDFT.jsonl.
"""Cox partial likelihood: value, score, information, Newton fit, score test, Schoenfeld residuals.

Data: times[i] = y_i, events[i] = delta_i (1 event, 0 censored), X[i] = the
covariate vector x_i of length p, beta = the coefficient vector of length p.
Ties between event times are handled by the Breslow (1974) or Efron (1977)
approximation, or exactly by the discrete (conditional logistic) partial
likelihood of Cox (1972), computed with the subset-sum recursion of Gail,
Lubin and Rubinstein (1981). A censored time tied with an event time counts
as at risk at that time.

If every entry of beta is 0 and the covariates are ints or Fractions, the
weights exp(x_i' beta) are the integer 1 and the score and the information
come out exact (Fractions). The log partial likelihood is always a float.
"""

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

from stdist import chi2_sf

TIES = ("breslow", "efron", "exact")


def _check(times, events, X, beta):
    n = len(times)
    if n == 0 or len(events) != n or len(X) != n:
        raise ValueError("times, events and X must have the same positive length")
    if any(e not in (0, 1) for e in events):
        raise ValueError("event flags must be 0 or 1")
    p = len(beta)
    if any(len(x) != p for x in X):
        raise ValueError("every covariate vector must have the length of beta")
    return n, p


def _weights(X, beta):
    """exp(x_i' beta - c), with c the largest linear predictor; the integer 1 when beta = 0.

    The shift c cancels in every ratio of the partial likelihood, so it changes
    nothing but prevents overflow.
    """
    if all(b == 0 for b in beta):
        return [1] * len(X)
    eta = [sum(float(a) * float(b) for a, b in zip(x, beta)) for x in X]
    c = max(eta)
    return [math.exp(e - c) for e in eta]


def _groups(times, events):
    """Distinct times from the largest to the smallest, with all subjects and the events at each."""
    order = sorted(range(len(times)), key=lambda k: times[k], reverse=True)  # @line L1
    out, i = [], 0
    while i < len(order):
        t, members, dead = times[order[i]], [], []
        while i < len(order) and times[order[i]] == t:
            members.append(order[i])
            if events[order[i]]:
                dead.append(order[i])
            i += 1
        out.append((t, members, dead))
    return out


def _zero_vec(p):
    return [0] * p


def _zero_mat(p):
    return [[0] * p for _ in range(p)]


def _esp_derivatives(ws, xs, d, p):
    """e_d of the weights ws, with its gradient and Hessian in beta (Gail, Lubin and Rubinstein 1981).

    e_k is the sum over subsets of size k of the product of the weights. With
    w_i = exp(x_i' beta), the gradient of a product over a subset is that product
    times the sum of the x_i, which gives the recursions below.
    """
    E = [1] + [0] * d
    G = [_zero_vec(p) for _ in range(d + 1)]
    H = [_zero_mat(p) for _ in range(d + 1)]
    for w, x in zip(ws, xs):
        for k in range(d, 0, -1):
            e1, g1, h1 = E[k - 1], G[k - 1], H[k - 1]
            for a in range(p):
                for b in range(p):
                    H[k][a][b] += w * (x[a] * x[b] * e1 + x[a] * g1[b] + g1[a] * x[b] + h1[a][b])
            for a in range(p):
                G[k][a] += w * (x[a] * e1 + g1[a])
            E[k] += w * e1
    return E[d], G[d], H[d]


class Fit(NamedTuple):
    loglik: float  # log partial likelihood, up to the shift that cancels
    score: list  # U(beta), length p
    information: list  # I(beta) = minus the Hessian, p x p


def score_information(times: Sequence, events: Sequence[int], X: Sequence[Sequence], beta: Sequence, ties: str = "breslow") -> Fit:
    """Log partial likelihood, score vector and observed information at beta.

    Breslow and Efron: one sort and one backward pass with cumulative sums
    S0 = sum w, S1 = sum w x, S2 = sum w x x' over the risk set, O(n p^2) after
    the sort. Exact: the subset-sum recursion over each risk set with ties.
    """
    if ties not in TIES:
        raise ValueError(f"ties must be one of {TIES}")
    n, p = _check(times, events, X, beta)
    w = _weights(X, beta)
    eta_shift = None if all(b == 0 for b in beta) else [math.log(v) for v in w]
    # S0, S1, S2 are the sums over the subjects with y >= t.
    S0, S1, S2 = 0, _zero_vec(p), _zero_mat(p)  # @line L4
    seen = []  # subjects added so far, used only for exact ties
    ll, U, Imat = 0.0, _zero_vec(p), _zero_mat(p)
    for t, members, dead in _groups(times, events):  # @line L5
        # Every subject with y_i = t enters the risk set at t.
        for i in members:  # @line L6
            wi, xi = w[i], X[i]
            S0 += wi
            for a in range(p):
                S1[a] += wi * xi[a]
                for b in range(p):
                    S2[a][b] += wi * xi[a] * xi[b]
            seen.append(i)
        d = len(dead)  # @line L7
        if d == 0:
            continue
        s = [sum(X[i][a] for i in dead) for a in range(p)]  # sum of x over the events at t
        eta_dead = 0.0 if eta_shift is None else sum(eta_shift[i] for i in dead)
        for a in range(p):
            U[a] += s[a]
        if ties == "exact" and d > 1:
            E, G, H = _esp_derivatives([w[i] for i in seen], [X[i] for i in seen], d, p)
            ll += eta_dead - math.log(float(E))
            for a in range(p):
                U[a] -= Fraction(G[a]) / E if isinstance(E, int) else G[a] / E
                for b in range(p):
                    if isinstance(E, int):
                        Imat[a][b] += Fraction(H[a][b]) / E - Fraction(G[a] * G[b]) / (E * E)
                    else:
                        Imat[a][b] += H[a][b] / E - G[a] * G[b] / (E * E)
            continue
        if ties == "breslow" or d == 1:
            parts = [(S0, S1, S2, d)]  # with one event the three rules agree
        else:  # Efron: the r-th of the d events sees the risk set minus r/d of the dead
            D0 = sum(w[i] for i in dead)
            D1 = [sum(w[i] * X[i][a] for i in dead) for a in range(p)]
            D2 = [[sum(w[i] * X[i][a] * X[i][b] for i in dead) for b in range(p)] for a in range(p)]
            parts = []
            for r in range(d):
                f = Fraction(r, d)
                parts.append((S0 - f * D0, [S1[a] - f * D1[a] for a in range(p)],
                              [[S2[a][b] - f * D2[a][b] for b in range(p)] for a in range(p)], 1))
        ll += eta_dead
        for A0, A1, A2, m in parts:
            ll -= m * math.log(float(A0))
            A0q = Fraction(A0) if isinstance(A0, (int, Fraction)) else A0
            for a in range(p):
                U[a] -= m * A1[a] / A0q
                for b in range(p):
                    Imat[a][b] += m * (A2[a][b] / A0q - A1[a] * A1[b] / (A0q * A0q))
    return Fit(ll, U, Imat)


def solve(A, b):
    """Solve A z = b by Gaussian elimination with partial pivoting (works with floats or Fractions)."""
    m = len(b)
    M = [list(A[i]) + [b[i]] for i in range(m)]
    for c in range(m):
        piv = max(range(c, m), key=lambda r: abs(M[r][c]))
        if M[piv][c] == 0:
            raise ZeroDivisionError("the information matrix is singular")
        M[c], M[piv] = M[piv], M[c]
        for r in range(c + 1, m):
            f = M[r][c] / M[c][c]
            for k in range(c, m + 1):
                M[r][k] -= f * M[c][k]
    z = [0] * m
    for r in range(m - 1, -1, -1):
        z[r] = (M[r][m] - sum(M[r][k] * z[k] for k in range(r + 1, m))) / M[r][r]
    return z


def inverse(A):
    m = len(A)
    cols = [solve(A, [1 if i == j else 0 for i in range(m)]) for j in range(m)]
    return [[cols[j][i] for j in range(m)] for i in range(m)]


class CoxResult(NamedTuple):
    beta: list
    loglik: float
    information: list  # observed information at beta-hat
    covariance: list  # its inverse, the usual variance estimate of beta-hat
    iterations: int
    converged: bool  # False when Newton did not settle, as under a monotone likelihood


def fit(times, events, X, ties="breslow", beta0=None, tol=1e-10, max_iter=60) -> CoxResult:
    """Maximize the log partial likelihood by Newton's method with step halving.

    Stops when the largest step is below tol. The log partial likelihood is
    concave, so a step that does not decrease it is accepted, and halving
    always finds one while the score is not zero. Under a monotone likelihood
    (no finite maximum) the iterates drift to infinity and converged is False.
    """
    n, p = _check(times, events, X, [0] * (len(X[0]) if X else 0))
    beta = [float(b) for b in (beta0 if beta0 is not None else [0.0] * p)]  # @line L2
    cur = score_information(times, events, X, beta, ties)
    for it in range(1, max_iter + 1):  # @line L3
        try:
            step = [float(v) for v in solve([[float(v) for v in row] for row in cur.information], [float(u) for u in cur.score])]  # @line L8
        except ZeroDivisionError:
            return CoxResult(beta, cur.loglik, cur.information, None, it, False)
        for _ in range(60):  # step halving
            cand = [b + s for b, s in zip(beta, step)]
            new = score_information(times, events, X, cand, ties)
            if new.loglik >= cur.loglik - 1e-12 * (1 + abs(cur.loglik)):
                break
            step = [s / 2 for s in step]
        beta, cur = cand, new  # @line L9
        if max(abs(s) for s in step) < tol:  # @line L10
            info = [[float(v) for v in row] for row in cur.information]
            return CoxResult(beta, cur.loglik, info, inverse(info), it, True)  # @line L11
    info = [[float(v) for v in row] for row in cur.information]
    try:
        cov = inverse(info)
    except ZeroDivisionError:
        cov = None
    return CoxResult(beta, cur.loglik, info, cov, max_iter, False)


def score_test(times, events, X, beta0=None, ties="breslow"):
    """Score test of beta = beta0: returns (U' I^-1 U, p, upper chi-square p-value)."""
    p = len(X[0])
    beta0 = beta0 if beta0 is not None else [0] * p
    f = score_information(times, events, X, beta0, ties)
    z = solve(f.information, f.score)
    stat = sum(u * v for u, v in zip(f.score, z))
    return stat, p, chi2_sf(float(stat), p)


def schoenfeld_residuals(times, events, X, beta, ties="breslow"):
    """One residual per event: x_i minus the risk-set weighted mean of x at its time.

    With ties='efron' the mean is the average over r = 0..d-1 of the Efron
    means, so that the residuals add up to the Efron score. Returns a list of
    (time, subject index, residual vector) in increasing time.
    """
    if ties not in ("breslow", "efron"):
        raise ValueError("ties must be 'breslow' or 'efron'")
    n, p = _check(times, events, X, beta)
    w = _weights(X, beta)
    S0, S1, out = 0, _zero_vec(p), []
    for t, members, dead in _groups(times, events):
        for i in members:
            S0 += w[i]
            for a in range(p):
                S1[a] += w[i] * X[i][a]
        d = len(dead)
        if d == 0:
            continue
        if ties == "breslow" or d == 1:
            S0q = Fraction(S0) if isinstance(S0, int) else S0
            mean = [S1[a] / S0q for a in range(p)]
        else:
            D0 = sum(w[i] for i in dead)
            D1 = [sum(w[i] * X[i][a] for i in dead) for a in range(p)]
            mean = [0] * p
            for r in range(d):
                f = Fraction(r, d)
                A0 = S0 - f * D0
                for a in range(p):
                    mean[a] += (S1[a] - f * D1[a]) / A0 / d
        for i in sorted(dead):
            out.append((t, i, [X[i][a] - mean[a] for a in range(p)]))
    out.sort(key=lambda r: (r[0], r[1]))
    return out


def scaled_schoenfeld(times, events, X, beta, covariance, ties="breslow"):
    """Grambsch and Therneau (1994) scaled residuals beta + D * covariance * r, with D the number of events."""
    res = schoenfeld_residuals(times, events, X, beta, ties)
    D = len(res)
    out = []
    for t, i, r in res:
        out.append((t, i, [beta[a] + D * sum(covariance[a][b] * r[b] for b in range(len(r))) for a in range(len(r))]))
    return out
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)
test_cox_partial_likelihood.py 250 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cox-partial-likelihood/. The authors are listed in prov/9HJDFT.jsonl.

import itertools
import math
import random
from fractions import Fraction

from cox_partial_likelihood import (
    TIES, fit, schoenfeld_residuals, score_information, score_test,
)

# Remission times in weeks of the leukemia trial of Freireich et al. (1963), as listed by Gehan (1965).
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]
GEHAN_T = MP_T + PL_T
GEHAN_D = MP_D + [1] * 21
GEHAN_X = [[0]] * 21 + [[1]] * 21  # x = 1 for placebo


def random_data(rng, n, p, tmax=6, censor=0.3):
    """Integer times (so ties occur), random censoring and covariates."""
    T = [rng.randint(1, tmax) for _ in range(n)]
    D = [0 if rng.random() < censor else 1 for _ in range(n)]
    X = [[round(rng.gauss(0, 1), 2) for _ in range(p)] for _ in range(n)]
    return T, D, X


def direct_loglik(T, D, X, beta, ties):
    """The log partial likelihood by direct summation over each risk set."""
    eta = [sum(a * b for a, b in zip(x, beta)) for x in X]
    ll = 0.0
    for t in sorted({y for y, e in zip(T, D) if e}):
        R = [i for i in range(len(T)) if T[i] >= t]
        Dset = [i for i in R if T[i] == t and D[i]]
        d = len(Dset)
        ll += sum(eta[i] for i in Dset)
        if ties == "breslow":
            ll -= d * math.log(sum(math.exp(eta[i]) for i in R))
        elif ties == "efron":
            sR = sum(math.exp(eta[i]) for i in R)
            sD = sum(math.exp(eta[i]) for i in Dset)
            ll -= sum(math.log(sR - r / d * sD) for r in range(d))
        else:  # exact: every subset of size d of the risk set could have been the d failures
            ll -= math.log(sum(math.exp(sum(eta[i] for i in s)) for s in itertools.combinations(R, d)))
    return ll


def test_loglik_matches_direct_summation():
    rng = random.Random(1)
    for _ in range(20):
        T, D, X = random_data(rng, 12, 2)
        beta = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        for ties in TIES:
            got = score_information(T, D, X, beta, ties).loglik
            assert abs(got - direct_loglik(T, D, X, beta, ties)) < 1e-9


def test_score_and_information_match_numerical_derivatives():
    rng = random.Random(2)
    h = 1e-5
    for _ in range(10):
        T, D, X = random_data(rng, 14, 2)
        beta = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        for ties in TIES:
            f = score_information(T, D, X, beta, ties)
            for a in range(2):
                up = list(beta); up[a] += h
                dn = list(beta); dn[a] -= h
                num = (direct_loglik(T, D, X, up, ties) - direct_loglik(T, D, X, dn, ties)) / (2 * h)
                assert abs(f.score[a] - num) < 1e-6
                su = score_information(T, D, X, up, ties).score
                sd = score_information(T, D, X, dn, ties).score
                for b in range(2):
                    # The information is minus the Hessian: minus the derivative of the score.
                    assert abs(f.information[b][a] + (su[b] - sd[b]) / (2 * h)) < 1e-6


def test_log_partial_likelihood_is_concave():
    rng = random.Random(3)
    for _ in range(10):
        T, D, X = random_data(rng, 15, 3)
        for ties in TIES:
            for _ in range(5):
                b = [rng.uniform(-2, 2) for _ in range(3)]
                v = [rng.gauss(0, 1) for _ in range(3)]
                f = score_information(T, D, X, b, ties)
                quad = sum(v[i] * f.information[i][j] * v[j] for i in range(3) for j in range(3))
                assert quad >= -1e-12  # the information is positive semidefinite
                g = lambda s: score_information(T, D, X, [bi + s * vi for bi, vi in zip(b, v)], ties).loglik
                assert g(0.3) + g(-0.3) - 2 * g(0.0) <= 1e-9


def test_newton_matches_a_fine_grid():
    rng = random.Random(4)
    for ties in TIES:
        T, D, X = random_data(rng, 20, 1)
        res = fit(T, D, X, ties)
        assert res.converged
        ll = lambda b: score_information(T, D, X, [b], ties).loglik
        grid = [k / 100 for k in range(-400, 401)]
        best = max(grid, key=ll)
        for step in (1e-4, 1e-6):  # refine around the best point twice
            best = max([best + k * step for k in range(-100, 101)], key=ll)
        assert abs(best - res.beta[0]) <= 2e-5
        assert ll(res.beta[0]) >= ll(best) - 1e-12


def log_rank(T, D, G):
    """Log-rank O - E for group 1 and the hypergeometric variance, in Fractions."""
    U = V = Fraction(0)
    for t in sorted({y for y, e in zip(T, D) if e}):
        n = sum(1 for y in T if y >= t)
        n1 = sum(1 for y, g in zip(T, G) if y >= t and g)
        d = sum(1 for y, e in zip(T, D) if y == t and e)
        d1 = sum(1 for y, e, g in zip(T, D, G) if y == t and e and g)
        U += d1 - Fraction(d * n1, n)
        if n > 1:
            V += Fraction(d * n1 * (n - n1) * (n - d), n * n * (n - 1))
    return U, V


def test_score_test_at_zero_is_the_log_rank_statistic_without_ties():
    rng = random.Random(5)
    for _ in range(30):
        n = rng.randint(4, 12)
        T = rng.sample(range(1, 40), n)  # distinct times, so no ties
        D = [rng.randint(0, 1) for _ in range(n)]
        if not any(D):
            D[0] = 1
        G = [rng.randint(0, 1) for _ in range(n)]
        if len(set(G)) < 2:
            G[0], G[1] = 0, 1
        U, V = log_rank(T, D, G)
        for ties in TIES:  # with no ties the three rules are the same function
            f = score_information(T, D, [[g] for g in G], [0], ties)
            assert f.score[0] == U and f.information[0][0] == V
            if V > 0:
                stat, df, _ = score_test(T, D, [[g] for g in G], [0], ties)
                assert stat == U * U / V and df == 1


def test_exact_ties_score_test_is_the_log_rank_with_hypergeometric_variance():
    rng = random.Random(6)
    for _ in range(30):
        T, D, _ = random_data(rng, 10, 1, tmax=4)
        if not any(D):
            D[0] = 1
        G = [rng.randint(0, 1) for _ in range(10)]
        U, V = log_rank(T, D, G)
        f = score_information(T, D, [[g] for g in G], [0], "exact")
        assert f.score[0] == U and f.information[0][0] == V
        # Breslow keeps the score but uses the binomial variance d n1 n0 / n^2.
        fb = score_information(T, D, [[g] for g in G], [0], "breslow")
        VB = Fraction(0)
        for t in sorted({y for y, e in zip(T, D) if e}):
            n = sum(1 for y in T if y >= t)
            n1 = sum(1 for y, g in zip(T, G) if y >= t and g)
            d = sum(1 for y, e in zip(T, D) if y == t and e)
            VB += Fraction(d * n1 * (n - n1), n * n)
        assert fb.score[0] == U and fb.information[0][0] == VB and VB >= V


def test_efron_score_and_information_at_zero_match_the_formula():
    rng = random.Random(7)
    for _ in range(20):
        T, D, _ = random_data(rng, 10, 1, tmax=4)
        X = [[rng.randint(-2, 2)] for _ in range(10)]
        f = score_information(T, D, X, [0], "efron")
        U = I = Fraction(0)
        for t in sorted({y for y, e in zip(T, D) if e}):
            R = [i for i in range(10) if T[i] >= t]
            Ds = [i for i in R if T[i] == t and D[i]]
            d = len(Ds)
            U += sum(X[i][0] for i in Ds)
            for r in range(d):
                c = Fraction(r, d)
                A0 = len(R) - c * len(Ds)
                A1 = sum(X[i][0] for i in R) - c * sum(X[i][0] for i in Ds)
                A2 = sum(X[i][0] ** 2 for i in R) - c * sum(X[i][0] ** 2 for i in Ds)
                U -= A1 / A0
                I += A2 / A0 - (A1 / A0) ** 2
        assert f.score[0] == U and f.information[0][0] == I


def test_schoenfeld_residuals_sum_to_the_score():
    rng = random.Random(8)
    for _ in range(10):
        T, D, _ = random_data(rng, 12, 1)
        X = [[rng.randint(0, 3), rng.randint(-1, 1)] for _ in range(12)]
        for ties in ("breslow", "efron"):
            res = schoenfeld_residuals(T, D, X, [0, 0], ties)
            f = score_information(T, D, X, [0, 0], ties)
            assert [sum(r[2][a] for r in res) for a in range(2)] == f.score  # exact at beta = 0
            bhat = fit(T, D, [[float(v) for v in x] for x in X], ties)
            if bhat.converged:
                res = schoenfeld_residuals(T, D, X, bhat.beta, ties)
                assert all(abs(sum(r[2][a] for r in res)) < 1e-8 for a in range(2))


def test_gehan_leukemia_data():
    want = {"breslow": (1.5092, 0.4096), "efron": (1.5721, 0.4124), "exact": (1.6282, 0.4331)}
    for ties, (b, se) in want.items():
        r = fit(GEHAN_T, GEHAN_D, GEHAN_X, ties)
        assert r.converged
        assert abs(r.beta[0] - b) < 1e-4 and abs(math.sqrt(r.covariance[0][0]) - se) < 1e-4
    stat, _, p = score_test(GEHAN_T, GEHAN_D, GEHAN_X, [0], "exact")
    U, V = log_rank(GEHAN_T, GEHAN_D, [x[0] for x in GEHAN_X])
    assert stat == U * U / V and abs(float(stat) - 16.793) < 1e-3 and p < 1e-4


def test_invariance_to_shift_and_scale_of_a_covariate():
    rng = random.Random(9)
    T, D, X = random_data(rng, 25, 2)
    r = fit(T, D, X, "efron")
    shifted = [[x[0] + 7.0, x[1] - 3.0] for x in X]
    scaled = [[2.0 * x[0], x[1]] for x in X]
    r1 = fit(T, D, shifted, "efron")
    r2 = fit(T, D, scaled, "efron")
    assert max(abs(a - b) for a, b in zip(r.beta, r1.beta)) < 1e-8
    assert abs(r2.beta[0] - r.beta[0] / 2) < 1e-8 and abs(r2.beta[1] - r.beta[1]) < 1e-8


def test_monotone_likelihood_does_not_converge():
    # Every event is in group 1 and group 1 is always in the risk set: the
    # partial likelihood increases in beta without bound.
    T = [1, 2, 3, 4, 5, 6, 7, 8]
    D = [1, 1, 1, 1, 0, 0, 0, 0]
    X = [[1], [1], [1], [1], [0], [0], [0], [0]]
    r = fit(T, D, X, "breslow", max_iter=30)
    assert not r.converged and r.beta[0] > 10


def test_score_test_size_by_simulation():
    # Under beta = 0 the score statistic is asymptotically chi-square(1).
    rng = random.Random(10)
    reps, rejections = 2000, 0
    for _ in range(reps):
        n = 40
        X = [[rng.randint(0, 1)] for _ in range(n)]
        T = [rng.expovariate(1.0) for _ in range(n)]
        C = [rng.expovariate(0.5) for _ in range(n)]
        Y = [min(a, b) for a, b in zip(T, C)]
        D = [1 if a <= b else 0 for a, b in zip(T, C)]
        if not any(D) or len({x[0] for x in X}) < 2:
            continue
        rejections += score_test(Y, D, X, [0], "breslow")[2] < 0.05
    rate = rejections / reps
    assert abs(rate - 0.05) < 4 * math.sqrt(0.05 * 0.95 / reps) + 0.01
test_stdist.py 60 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

import math

from stdist import (
    beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
    norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)

XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]


def test_chi2_two_degrees_of_freedom() -> None:
    for x in XS:
        assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
        assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)


def test_t_one_and_two_degrees_of_freedom() -> None:
    for x in XS + [-v for v in XS] + [0.0]:
        assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
        assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
        assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14


def test_f_is_square_of_t() -> None:
    for k in [1, 2, 3, 5, 10, 30]:
        for x in XS:
            two_sided = 2.0 * t_sf(math.sqrt(x), k)
            assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
            assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14


def test_gamma_and_beta_identities() -> None:
    for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
        for x in XS:
            assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
    # P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
    for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
        assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
        for a in [0.5, 2.0, 7.0]:
            assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
            assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13


def test_upper_tails_do_not_cancel() -> None:
    assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
    assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
    assert norm_cdf(-30.0) > 0.0

def test_quantiles() -> None:
    assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
    assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
    assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
    for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
        for k in [1, 4, 25]:
            assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
            assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
            assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12

Exercises

  1. Show that L(β)L(\beta) does not change if the same vector cc is added to every xix_i. Answer. Each factor gains eβTce^{\beta^{\mathsf T}c} in the numerator and in every term of the denominator, so it cancels. This is why the model has no intercept.
  2. Two subjects are at risk at the only event time, and the subject with the event has the larger scalar covariate. Find β^\hat\beta. Answer. L(β)=1/(1+e−β(x1−x2))L(\beta) = 1/(1 + e^{-\beta(x_1 - x_2)}) increases in β\beta to 11, so there is no finite maximizer. This is the smallest monotone likelihood.
  3. Show that the three rules for ties give the same ℓ\ell, UU and II at a time with one event. Answer. With d=1d = 1, Efron has only r=0r = 0, which is the Breslow term, and e1=S0e_1 = S_0.
  4. Show that the Breslow information at β=0\beta = 0 for one binary covariate is djn1jn0j/nj2d_j n_{1j}n_{0j}/n_j^2 at tjt_j, and that it is at least the hypergeometric variance, with equality exactly when dj=1d_j = 1 (or n1jn0j=0n_{1j}n_{0j} = 0). Answer. dj(S2/S0−xˉ2)=dj(n1j/nj)(1−n1j/nj)d_j(S_2/S_0 - \bar x^2) = d_j(n_{1j}/n_j)(1 - n_{1j}/n_j). The ratio of the two variances is (nj−dj)/(nj−1)≤1(n_j - d_j)/(n_j - 1) \le 1, with equality iff dj=1d_j = 1.
  5. Show that the score U(β)U(\beta) is the sum of the Schoenfeld residuals, so that they sum to 00 at β^\hat\beta. Answer. With the Breslow rule, the term of line L7 is s−dxˉ=∑i∈D(xi−xˉ)s - d\bar x = \sum_{i \in D}(x_i - \bar x), a sum of the residuals at tt. At β^\hat\beta the score is 00.

References

  1. D. R. Cox, Regression models and life-tables, Journal of the Royal Statistical Society, Series B 34(2), 1972, pp. 187 to 220 (the conditional likelihood of the event at each time given the risk set, and the discrete logistic model for ties)
  2. D. R. Cox, Partial likelihood, Biometrika 62(2), 1975, pp. 269 to 276 (the general definition of partial likelihood and the argument that the usual large-sample results apply)
  3. N. E. Breslow, Covariance analysis of censored survival data, Biometrics 30(1), 1974, pp. 89 to 99 (the approximation for tied times and the estimate of the baseline hazard)
  4. Bradley Efron, The efficiency of Cox's likelihood function for censored data, Journal of the American Statistical Association 72(359), 1977, pp. 557 to 565 (the efficiency of the partial likelihood and the approximation for tied times)
  5. Mitchell H. Gail, Jay H. Lubin and Lawrence V. Rubinstein, Likelihood calculations for matched case-control studies and survival studies with tied death times, Biometrika 68(3), 1981, pp. 703 to 707 (the recursion for the exact conditional likelihood with tied times)
  6. Per Kragh Andersen and Richard D. Gill, Cox's regression model for counting processes, a large sample study, Annals of Statistics 10(4), 1982, pp. 1100 to 1120 (consistency and asymptotic normality of the maximum partial likelihood estimate)
  7. Georg Heinze and Michael Schemper, A solution to the problem of monotone likelihood in Cox regression, Biometrics 57(1), 2001, pp. 114 to 119 (monotone likelihood and the Firth penalized partial likelihood)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples