Algorithm Search⌘K

Modelresearch

Fine-Gray model

Also called subdistribution hazard model, proportional subdistribution hazards.

A proportional hazards model for the subdistribution hazard of one cause, so covariate effects act directly on its cumulative incidence.

The Fine-Gray model is a regression model for the cumulative incidence of one cause in a competing risks problem. A Cox model on the cause-specific hazard tells how a covariate changes the rate of cause 1 among event-free subjects, but the risk of cause 1, F1(t)=P(T≤t,cause=1)F_1(t) = P(T \le t, \text{cause} = 1), also depends on the other causes. Fine and Gray (1999) put the proportional hazards form on the subdistribution hazard of Gray (1988),

h~1(t∣x)=−ddtlog⁡(1−F1(t∣x))=h~10(t)exp⁡(βTx),\tilde h_1(t \mid x) = -\frac{d}{dt}\log\bigl(1 - F_1(t \mid x)\bigr) = \tilde h_{10}(t)\exp(\beta^{\mathsf T}x),

so that 1−F1(t∣x)=(1−F10(t))exp⁡(βTx)1 - F_1(t \mid x) = (1 - F_{10}(t))^{\exp(\beta^{\mathsf T}x)}: a positive βk\beta_k raises the cumulative incidence of cause 1 at every time. The model is fitted by a weighted partial likelihood in which subjects who had another cause stay in the risk set, with weights from the censoring distribution.

The machine

The data. For subject ii we observe yiy_i, the cause ci∈{0,1,…,K}c_i \in \{0, 1, \ldots, K\}, with 00 for censored, and covariates xix_i. Censoring is independent of the event process, and in the basic form also of the covariates.

The subdistribution time. Let T∗=TT^\ast = T if the cause is 11 and T∗=∞T^\ast = \infty otherwise. Then P(T∗≤t)=F1(t)P(T^\ast \le t) = F_1(t), an improper distribution with mass 1−F1(∞)1 - F_1(\infty) at infinity, and its hazard is h~1\tilde h_1. The risk set of T∗T^\ast at tt is

{i:Ti≥t}∪{i:Ti<t, ci∉{0,1}},\{i : T_i \ge t\} \cup \{i : T_i < t,\ c_i \notin \{0, 1\}\},

the subjects still event-free and the subjects that already had another cause. The second group is not at risk of anything in reality, but it is at risk in the arithmetic of 1−F11 - F_1.

The conditions.

  1. Proportional subdistribution hazards. h~1(t∣x)=h~10(t)eβTx\tilde h_1(t \mid x) = \tilde h_{10}(t)e^{\beta^{\mathsf T}x} with an unspecified h~10\tilde h_{10}, for the cause of interest only. The other causes are left unmodeled.
  2. Independent censoring, independent of xx in the basic form. Covariate-dependent censoring needs censoring weights that depend on xx.
  3. Independent subjects.

Equivalent form. F1(t∣x)=1−(1−F10(t))exp⁡(βTx)=1−exp⁡(−H~10(t)eβTx)F_1(t \mid x) = 1 - (1 - F_{10}(t))^{\exp(\beta^{\mathsf T}x)} = 1 - \exp\bigl(-\tilde H_{10}(t)e^{\beta^{\mathsf T}x}\bigr), with H~10=∫0th~10\tilde H_{10} = \int_0^t \tilde h_{10}. Proof. Integrate the definition: −log⁡(1−F1(t∣x))=H~10(t)eβTx-\log(1 - F_1(t \mid x)) = \tilde H_{10}(t)e^{\beta^{\mathsf T}x}. □\square

The estimating equation with censoring. Subjects with another cause are not followed after their event, so whether they would have been censored later is unknown. Fine and Gray give them the weight

wi(t)=G^(t−)G^(yi−)for yi<t, ci∉{0,1},w_i(t) = \frac{\hat G(t-)}{\hat G(y_i-)} \quad \text{for } y_i < t,\ c_i \notin \{0, 1\},

and weight 11 while yi≥ty_i \ge t, where G^\hat G is the Kaplan-Meier estimate of the censoring distribution, with events leaving before censorings at tied times. The weight is the estimated probability that the subject would still be uncensored at tt given that it was at yiy_i, a form of inverse probability weighting. The weighted log partial likelihood is

ℓ(β)=∑j[βTsj−djlog⁡∑iwi(tj)eβTxi],\ell(\beta) = \sum_{j}\Bigl[\beta^{\mathsf T}s_j - d_j\log\sum_i w_i(t_j)e^{\beta^{\mathsf T}x_i}\Bigr],

over the distinct times tjt_j of cause 1, with djd_j events of cause 1 and covariate sum sjs_j, using the Breslow rule for ties. It is concave by the argument of the partial likelihood page, since the weights do not depend on β\beta.

Computation. The reference code splits the weighted risk sums into a backward running sum over {yi≥tj}\{y_i \ge t_j\} and G^(tj−)\hat G(t_j-) times a forward running sum of eβTxixi⊗r/G^(yi−)e^{\beta^{\mathsf T}x_i}x_i^{\otimes r}/\hat G(y_i-) over the subjects with another cause before tjt_j. After one sort, a Newton step costs O(np2+p3)O(np^2 + p^3), as for the Cox model. The baseline H~10\tilde H_{10} is a Breslow-type sum of dj/∑iwi(tj)eβ^Txid_j/\sum_i w_i(t_j)e^{\hat\beta^{\mathsf T}x_i}.

What it counts

  • The subdistribution hazard ratio eβke^{\beta_k}. It is the factor on h~1\tilde h_1, and so it orders the cumulative incidence curves: eβTx>1e^{\beta^{\mathsf T}x} > 1 means F1(t∣x)>F10(t)F_1(t \mid x) > F_{10}(t) at every tt. It is not the ratio of the rates of cause 1 among event-free subjects. That is the cause-specific hazard ratio.
  • Predicted risks. F^1(t∣x)=1−exp⁡(−H~^10(t)eβ^Tx)\hat F_1(t \mid x) = 1 - \exp(-\hat{\tilde H}_{10}(t)e^{\hat\beta^{\mathsf T}x}) for any xx. This is what the model is for.
  • Only one cause. Each cause needs its own model. The models of different causes are not linked, and they cannot all hold, as proved below.

Relation to other models

  • Cox model on T∗T^\ast. Without censoring, every weight is 11, and the fit is exactly a Cox model in which the subjects with another cause get the time +∞+\infty. The tests check this against a direct Cox fit.
  • Cause-specific hazards. h~1(t)=h1(t)S(t)1−F1(t)≤h1(t)\tilde h_1(t) = h_1(t)\dfrac{S(t)}{1 - F_1(t)} \le h_1(t), where SS is the all-cause survival. Proof. ddtF1=Sh1\frac{d}{dt}F_1 = S h_1, and S≤1−F1S \le 1 - F_1 because S+∑kFk=1S + \sum_k F_k = 1. □\square The two hazards agree as long as no other cause has happened. Proportional cause-specific hazards for all causes do not give proportional subdistribution hazards in general, and the converse fails too, so the two models are different assumptions, not two fits of one model.
  • The Aalen-Johansen estimator. With no covariates, or at β=0\beta = 0, the weighted product-limit estimate of F1F_1 is exactly the Aalen-Johansen estimate. This is proved below.
  • Direct binomial and pseudo-observation models. Other models for F1F_1 use other links, such as the logit, with censoring weights or jackknife pseudo-values. The Fine-Gray model is the case of the complementary log-log link, log⁡(−log⁡(1−F1))=log⁡H~10(t)+βTx\log(-\log(1 - F_1)) = \log\tilde H_{10}(t) + \beta^{\mathsf T}x.

Known results in the model

A censoring identity. Let S^\hat S be the all-cause Kaplan-Meier estimate and G^\hat G the Kaplan-Meier estimate of the censoring distribution, with events leaving before censorings at tied times, and let nj=#{i:yi≥tj}n_j = \#\{i : y_i \ge t_j\}. Then nj/n=S^(tj−)G^(tj−)n_j/n = \hat S(t_j-)\hat G(t_j-) for every time tjt_j.

Proof. At a distinct observed time uu with rr at risk, dd events and cc censorings, S^\hat S has the factor (r−d)/r(r - d)/r and G^\hat G the factor (r−d−c)/(r−d)(r - d - c)/(r - d), or 11 if c=0c = 0. Their product is (r−d−c)/r(r - d - c)/r, the ratio of the numbers at risk just after and at uu. The product over all u<tju < t_j telescopes to nj/nn_j/n. (If r=dr = d, then c=0c = 0 and both sides are 00.) □\square

So the Aalen-Johansen increment S^(tj−)dkj/nj\hat S(t_j-)d_{kj}/n_j equals dkj/(nG^(tj−))d_{kj}/(n\hat G(t_j-)), and F^k(t−)=1n∑yi<t, ci=k1/G^(yi−)\hat F_k(t-) = \frac1n\sum_{y_i < t,\, c_i = k} 1/\hat G(y_i-): the Aalen-Johansen estimate is an inverse probability of censoring weighted proportion.

At β=0\beta = 0 the model reproduces Aalen-Johansen. With all eβTxi=1e^{\beta^{\mathsf T}x_i} = 1, let Δj=d1j/∑iwi(tj)\Delta_j = d_{1j}/\sum_i w_i(t_j) be the baseline jump at a time tjt_j of cause 1. Then 1−∏tj≤t(1−Δj)=F^1(t)1 - \prod_{t_j \le t}(1 - \Delta_j) = \hat F_1(t), the Aalen-Johansen estimate.

Proof. By the identity, the subjects still at risk contribute nj=nS^(tj−)G^(tj−)n_j = n\hat S(t_j-)\hat G(t_j-), and the subjects with cause k≠1k \ne 1 before tjt_j contribute G^(tj−)∑yi<tj, ci=k1/G^(yi−)=nG^(tj−)F^k(tj−)\hat G(t_j-)\sum_{y_i < t_j,\, c_i = k} 1/\hat G(y_i-) = n\hat G(t_j-)\hat F_k(t_j-). So

∑iwi(tj)=nG^(tj−)(S^(tj−)+∑k≠1F^k(tj−))=nG^(tj−)(1−F^1(tj−)),\sum_i w_i(t_j) = n\hat G(t_j-)\Bigl(\hat S(t_j-) + \sum_{k \ne 1}\hat F_k(t_j-)\Bigr) = n\hat G(t_j-)\bigl(1 - \hat F_1(t_j-)\bigr),

using S^+∑kF^k=1\hat S + \sum_k \hat F_k = 1. The Aalen-Johansen increment at tjt_j is d1j/(nG^(tj−))d_{1j}/(n\hat G(t_j-)), so Δj=(F^1(tj)−F^1(tj−))/(1−F^1(tj−))\Delta_j = (\hat F_1(t_j) - \hat F_1(t_j-))/(1 - \hat F_1(t_j-)), which is 1−F^1(tj)=(1−F^1(tj−))(1−Δj)1 - \hat F_1(t_j) = (1 - \hat F_1(t_j-))(1 - \Delta_j). Multiply over jj. □\square

The tests check both results in exact fractions on random data with ties.

The models of two causes cannot both hold for all covariates. Suppose cause 1 and cause 2 both follow Fine-Gray models with one covariate x∈Rx \in \mathbb{R} and coefficients β1,β2>0\beta_1, \beta_2 > 0, with 0<Fk0(t)<10 < F_{k0}(t) < 1 at some tt. Then Fk(t∣x)=1−(1−Fk0(t))eβkx→1F_k(t \mid x) = 1 - (1 - F_{k0}(t))^{e^{\beta_k x}} \to 1 as x→∞x \to \infty for both kk, so F1+F2>1F_1 + F_2 > 1 for large xx, which is impossible. □\square With a bounded covariate the contradiction may not appear, but the two models remain separate approximations.

Large samples. Under the model and independent censoring, β^\hat\beta is consistent and asymptotically normal. Its variance is not the inverse of the weighted information, because G^\hat G is estimated and the weighted terms are not martingale increments. Fine and Gray (1999) give a sandwich variance with an extra term for G^\hat G. We cite these results and do not prove them. The reference code reports only the inverse information, which is labeled naive. Use the Fine-Gray variance, or the bootstrap, for inference.

A simulation. The tests use the design of Fine and Gray: a binary xx, F1(t∣x)=1−(1−p(1−e−t))exp⁡(β1x)F_1(t \mid x) = 1 - (1 - p(1 - e^{-t}))^{\exp(\beta_1 x)} with p=0.6p = 0.6 and β1=0.5\beta_1 = 0.5, cause 2 given that cause 1 does not happen exponential with rate eβ2xe^{\beta_2 x}, β2=−0.5\beta_2 = -0.5, and censoring uniform on (0,3)(0, 3). The numbers are measured.

fit (one data set, n=2000n = 2000: 950 cause 1, 386 cause 2, 664 censored) coefficient of xx
Fine-Gray, cause 1 (truth 0.5) 0.452 (naive standard error 0.066)
Cox on the cause-specific hazard of cause 1 0.298 (standard error 0.066)
Cox on the cause-specific hazard of cause 2 -0.746
Fine-Gray, cause 2 (not a true model in this design) -0.871

Over 40 data sets of 200 subjects (seed 6, as in the tests) the Fine-Gray estimates had mean 0.480 and standard deviation 0.209, so the mean is within one standard error (0.209/40=0.0330.209/\sqrt{40} = 0.033) of 0.5. The cause-specific coefficient of cause 1 is a different quantity: in this design the cause-specific hazards are not proportional, and its value is not an estimate of β1\beta_1. The predicted F1(1∣x=1)F_1(1 \mid x = 1) from a fit to 2000 subjects is within 0.04 of the truth.

Checks in code. The tests compare the weighted risk sums with a direct O(n2)O(n^2) sum, the fit without censoring with a direct Cox fit with the competing times set to infinity, the score and information with numerical derivatives, the censoring identity and the Aalen-Johansen identity in exact fractions, and the simulation above.

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.

fine_gray_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fine-gray-model/. The authors are listed in prov/YSYJCC.jsonl.
"""Fine-Gray proportional subdistribution hazards model, fitted by weighted Cox Newton steps.

Input: times[i] = y_i, causes[i] = 0 (censored) or k >= 1 (event of cause k)
and covariate rows X[i]. For the cause of interest, a subject with another
cause stays in the risk set after its event time y_i with the weight
G(t-) / G(y_i-), where G is the Kaplan-Meier estimate of the censoring
distribution (censorings at a tied time come after the events). Ties of the
cause of interest use the Breslow rule. The weighted sums of a Newton step
are a backward cumulative sum (subjects still at risk) plus G(t-) times a
forward cumulative sum (subjects with another cause before t), so a step
costs O(n p^2) after one sort, plus O(p^3) for the solve.
"""

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


def censoring_survival(times: Sequence, causes: Sequence[int]) -> list[tuple]:
    """Kaplan-Meier (u, G(u)) of the censoring time; events at u leave before the censorings at u."""
    out, G = [], Fraction(1)
    order = sorted(range(len(times)), key=lambda i: times[i])
    at_risk, i, n = len(times), 0, len(times)
    while i < n:
        u, c, d = times[order[i]], 0, 0
        while i < n and times[order[i]] == u:
            if causes[order[i]] == 0:
                c += 1
            else:
                d += 1
            i += 1
        if c:
            G *= Fraction(at_risk - d - c, at_risk - d)
            out.append((u, G))
        at_risk -= c + d
    return out


def _left_limit(steps: list[tuple], t):
    """G(t-): the value at the last censoring time strictly before t, and 1 before the first."""
    value = Fraction(1)
    for u, g in steps:
        if u >= t:
            break
        value = g
    return value


class Design(NamedTuple):
    order: list  # subjects by increasing time
    event_times: list  # distinct times of the cause of interest, increasing
    g_event: list  # G(t_j-) at each of them
    g_subject: list  # G(y_i-) for every subject (used for the other causes)


def _design(times, causes, cause):
    n = len(times)
    if n == 0 or len(causes) != n:
        raise ValueError("times and causes must have the same positive length")
    if any(not isinstance(c, int) or c < 0 for c in causes):
        raise ValueError("causes must be integers >= 0 (0 = censored)")
    G = censoring_survival(times, causes)
    order = sorted(range(n), key=lambda i: times[i])
    ev = sorted(set(times[i] for i in range(n) if causes[i] == cause))
    return Design(order, ev, [_left_limit(G, t) for t in ev], [_left_limit(G, times[i]) for i in range(n)])


class Sums(NamedTuple):
    loglik: float
    score: list
    information: list
    risk_sums: list  # S0_j, the weighted risk set sums at the event times of interest


def weighted_sums(times, causes, X, beta, cause=1, design=None, exact=False) -> Sums:
    """The weighted log partial likelihood, its score and information at beta.

    With exact=True and beta = 0 everything is computed in Fractions (the
    log-likelihood is then None).
    """
    n, p = len(times), len(beta)
    des = design or _design(times, causes, cause)
    if exact:
        if any(b != 0 for b in beta):
            raise ValueError("exact arithmetic needs beta = 0")
        w = [1] * n
        conv = Fraction
    else:
        eta = [sum(a * b for a, b in zip(X[i], beta)) for i in range(n)]
        m = max(eta)
        w = [math.exp(e - m) for e in eta]
        conv = float
    zero = conv(0)

    def blank():
        return [zero, [zero] * p, [[zero] * p for _ in range(p)]]

    def add(acc, i, scale):
        ws = w[i] * scale
        acc[0] += ws
        for a in range(p):
            acc[1][a] += ws * X[i][a]
            for b in range(p):
                acc[2][a][b] += ws * X[i][a] * X[i][b]

    # Forward: subjects with another cause before t_j, each scaled by 1 / G(y_i-).
    # Backward: subjects with y_i >= t_j.
    k = len(des.event_times)
    fwd, back = [None] * k, [None] * k
    acc, pos = blank(), 0
    for j, t in enumerate(des.event_times):
        while pos < n and times[des.order[pos]] < t:
            i = des.order[pos]
            if causes[i] not in (0, cause):
                add(acc, i, conv(1) / conv(des.g_subject[i]))
            pos += 1
        fwd[j] = [acc[0], acc[1][:], [row[:] for row in acc[2]]]
    acc, pos = blank(), n - 1
    for j in range(k - 1, -1, -1):
        t = des.event_times[j]
        while pos >= 0 and times[des.order[pos]] >= t:
            add(acc, des.order[pos], conv(1))
            pos -= 1
        back[j] = [acc[0], acc[1][:], [row[:] for row in acc[2]]]
    ll = zero if not exact else None
    U = [zero] * p
    I = [[zero] * p for _ in range(p)]
    S0s = []
    dead = {}
    for i in range(n):
        if causes[i] == cause:
            dead.setdefault(times[i], []).append(i)
    for j, t in enumerate(des.event_times):
        g = conv(des.g_event[j])
        S0 = back[j][0] + g * fwd[j][0]
        S1 = [back[j][1][a] + g * fwd[j][1][a] for a in range(p)]
        S2 = [[back[j][2][a][b] + g * fwd[j][2][a][b] for b in range(p)] for a in range(p)]
        S0s.append(S0)
        d = len(dead[t])
        mean = [s / S0 for s in S1]
        for i in dead[t]:
            for a in range(p):
                U[a] += X[i][a] - mean[a]
            if not exact:
                ll += eta[i] - m - math.log(S0)
        for a in range(p):
            for b in range(p):
                I[a][b] += d * (S2[a][b] / S0 - mean[a] * mean[b])
    return Sums(ll, U, I, S0s)


def solve(A, b):
    """Gaussian elimination with partial pivoting; ZeroDivisionError if A is singular."""
    p = len(b)
    M = [list(map(float, A[r])) + [float(b[r])] for r in range(p)]
    for c in range(p):
        r = max(range(c, p), key=lambda q: abs(M[q][c]))
        if M[r][c] == 0.0:
            raise ZeroDivisionError("singular information matrix")
        M[c], M[r] = M[r], M[c]
        for q in range(c + 1, p):
            f = M[q][c] / M[c][c]
            for s in range(c, p + 1):
                M[q][s] -= f * M[c][s]
    x = [0.0] * p
    for c in range(p - 1, -1, -1):
        x[c] = (M[c][p] - sum(M[c][s] * x[s] for s in range(c + 1, p))) / M[c][c]
    return x


class FineGrayResult(NamedTuple):
    beta: list
    loglik: float
    information: list
    iterations: int
    converged: bool


def fit(times, causes, X, cause=1, beta0=None, tol=1e-10, max_iter=60) -> FineGrayResult:
    """Newton's method with step halving on the weighted log partial likelihood."""
    p = len(X[0])
    des = _design(times, causes, cause)
    if not des.event_times:
        raise ValueError("no event of the cause of interest")
    beta = list(beta0) if beta0 is not None else [0.0] * p
    cur = weighted_sums(times, causes, X, beta, cause, des)
    for it in range(1, max_iter + 1):
        try:
            step = solve(cur.information, cur.score)
        except ZeroDivisionError:
            return FineGrayResult(beta, cur.loglik, cur.information, it, False)
        scale = 1.0
        while True:
            trial = [b + scale * s for b, s in zip(beta, step)]
            new = weighted_sums(times, causes, X, trial, cause, des)
            if new.loglik >= cur.loglik - 1e-12 or scale < 1e-8:
                break
            scale /= 2.0  # step halving
        beta, cur = trial, new
        if max(abs(scale * s) for s in step) < tol:
            return FineGrayResult(beta, cur.loglik, cur.information, it, True)
    return FineGrayResult(beta, cur.loglik, cur.information, max_iter, False)


def baseline(times, causes, X, beta, cause=1) -> list[tuple]:
    """Breslow-type jumps of the baseline cumulative subdistribution hazard: (t_j, d_j / S0_j, cumulative).

    The weights use exp(x' beta) itself, not the shifted values of weighted_sums.
    """
    des = _design(times, causes, cause)
    exact = all(b == 0 for b in beta)
    sums = weighted_sums(times, causes, X, beta, cause, des, exact=exact)
    if not exact:
        m = max(sum(a * b for a, b in zip(x, beta)) for x in X)
        sums = sums._replace(risk_sums=[s * math.exp(m) for s in sums.risk_sums])
    out, H = [], 0
    for t, S0 in zip(des.event_times, sums.risk_sums):
        d = sum(1 for y, c in zip(times, causes) if c == cause and y == t)
        jump = Fraction(d) / S0 if exact else d / S0
        H += jump
        out.append((t, jump, H))
    return out


def predict_cif(steps: list[tuple], x: Sequence[float], beta: Sequence[float], t) -> float:
    """F_k(t | x) = 1 - exp(-Lambda0(t) exp(x' beta))."""
    H = 0.0
    for u, _, cum in steps:
        if u > t:
            break
        H = float(cum)
    return 1.0 - math.exp(-H * math.exp(sum(a * b for a, b in zip(x, beta))))
test_fine_gray_model.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fine-gray-model/. The authors are listed in prov/YSYJCC.jsonl.

import math
import random
from fractions import Fraction

from fine_gray_model import (
    _left_limit, baseline, censoring_survival, fit, predict_cif, weighted_sums,
)


def random_data(rng, n, p, censor=0.3, ties=True):
    times = [rng.randint(1, 8) if ties else rng.random() for _ in range(n)]
    causes = [0 if rng.random() < censor else rng.randint(1, 2) for _ in range(n)]
    X = [[rng.choice([0, 1, 2]) if ties else rng.gauss(0, 1) for _ in range(p)] for _ in range(n)]
    return times, causes, X


def direct_terms(times, causes, X, beta, cause=1):
    """Weighted risk set sums by a fresh O(n) loop at every event time."""
    G = censoring_survival(times, causes)
    exact = all(b == 0 for b in beta)
    out = []
    for t in sorted(set(y for y, c in zip(times, causes) if c == cause)):
        S0 = 0
        for y, c, x in zip(times, causes, X):
            w = 1 if exact else math.exp(sum(a * b for a, b in zip(x, beta)))
            if y >= t:
                S0 += w
            elif c not in (0, cause):
                S0 += w * _left_limit(G, t) / _left_limit(G, y)
        out.append(S0)
    return out


def cox_direct(times, events, X):
    """Breslow-ties Cox fit by Newton with O(n^2) direct sums; infinite times never die."""
    p = len(X[0])
    beta = [0.0] * p
    for _ in range(100):
        U = [0.0] * p
        I = [[0.0] * p for _ in range(p)]
        for t, e, x in zip(times, events, X):
            if not e:
                continue
            S0, S1, S2 = 0.0, [0.0] * p, [[0.0] * p for _ in range(p)]
            for y, z in zip(times, X):
                if y >= t:
                    w = math.exp(sum(a * b for a, b in zip(z, beta)))
                    S0 += w
                    for a in range(p):
                        S1[a] += w * z[a]
                        for b in range(p):
                            S2[a][b] += w * z[a] * z[b]
            for a in range(p):
                U[a] += x[a] - S1[a] / S0
                for b in range(p):
                    I[a][b] += S2[a][b] / S0 - S1[a] * S1[b] / S0 ** 2
        if p == 1:
            step = [U[0] / I[0][0]]
        else:
            det = I[0][0] * I[1][1] - I[0][1] * I[1][0]
            step = [(I[1][1] * U[0] - I[0][1] * U[1]) / det, (I[0][0] * U[1] - I[1][0] * U[0]) / det]
        beta = [b + s for b, s in zip(beta, step)]
        if max(abs(s) for s in step) < 1e-13:
            break
    return beta


def aalen_johansen(times, causes, cause=1):
    out, S, F = [], Fraction(1), Fraction(0)
    for t in sorted(set(y for y, c in zip(times, causes) if c)):
        n_j = sum(1 for y in times if y >= t)
        d = sum(1 for y, c in zip(times, causes) if y == t and c)
        dk = sum(1 for y, c in zip(times, causes) if y == t and c == cause)
        F += S * Fraction(dk, n_j)
        S *= Fraction(n_j - d, n_j)
        out.append((t, F))
    return out


def test_risk_sums_match_direct_summation() -> None:
    rng = random.Random(1)
    for trial in range(30):
        times, causes, X = random_data(rng, rng.randint(2, 15), 2)
        if 1 not in causes:
            continue
        exact = weighted_sums(times, causes, X, [0, 0], exact=True)
        assert exact.risk_sums == direct_terms(times, causes, X, [0, 0])
        beta = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        got = weighted_sums(times, causes, X, beta)
        m = max(sum(a * b for a, b in zip(x, beta)) for x in X)
        for a, b in zip(got.risk_sums, direct_terms(times, causes, X, beta)):
            assert abs(a * math.exp(m) - float(b)) < 1e-10 * float(b)


def test_without_censoring_equals_cox_with_competing_times_at_infinity() -> None:
    rng = random.Random(2)
    for _ in range(10):
        n = rng.randint(15, 40)
        times, causes, X = random_data(rng, n, 2, censor=0.0, ties=False)
        if causes.count(1) < 3 or causes.count(2) < 1:
            continue
        r = fit(times, causes, X)
        assert r.converged
        t2 = [y if c == 1 else math.inf for y, c in zip(times, causes)]
        b = cox_direct(t2, [int(c == 1) for c in causes], X)
        assert max(abs(u - v) for u, v in zip(r.beta, b)) < 1e-8


def test_score_and_information_are_derivatives() -> None:
    rng = random.Random(3)
    times, causes, X = random_data(rng, 30, 2, ties=False)
    beta = [0.3, -0.4]
    s = weighted_sums(times, causes, X, beta)
    h = 1e-6
    for a in range(2):
        up = beta[:]
        up[a] += h
        dn = beta[:]
        dn[a] -= h
        su, sd = weighted_sums(times, causes, X, up), weighted_sums(times, causes, X, dn)
        assert abs((su.loglik - sd.loglik) / (2 * h) - s.score[a]) < 1e-6
        for b in range(2):
            assert abs(-(su.score[b] - sd.score[b]) / (2 * h) - s.information[a][b]) < 1e-5
    r = fit(times, causes, X)
    assert r.converged and max(abs(u) for u in weighted_sums(times, causes, X, r.beta).score) < 1e-9


def test_censoring_km_factorizes_the_risk_set() -> None:
    # n_j / n = S(t_j-) G(t_j-) exactly, where S is the all-cause Kaplan-Meier estimate.
    rng = random.Random(4)
    for _ in range(40):
        times, causes, _ = random_data(rng, rng.randint(1, 20), 1, censor=0.4)
        n = len(times)
        G = censoring_survival(times, causes)
        S = Fraction(1)
        for t in sorted(set(times)):
            n_t = sum(1 for y in times if y >= t)
            assert Fraction(n_t, n) == S * _left_limit(G, t)
            d = sum(1 for y, c in zip(times, causes) if y == t and c)
            S *= Fraction(n_t - d, n_t)


def test_weighted_product_limit_at_beta_zero_is_aalen_johansen() -> None:
    rng = random.Random(5)
    for _ in range(40):
        times, causes, X = random_data(rng, rng.randint(1, 20), 1, censor=0.35)
        if 1 not in causes:
            continue
        steps = baseline(times, causes, X, [0])
        aj = dict(aalen_johansen(times, causes))
        prod = Fraction(1)
        for t, jump, _ in steps:
            prod *= 1 - jump
            assert 1 - prod == aj[t]


def simulate(rng, n, b1, b2, p):
    """The design of Fine and Gray (1999): F_1(t | x) = 1 - (1 - p (1 - e^(-t)))^exp(x b1)."""
    times, causes, X = [], [], []
    for _ in range(n):
        x = rng.choice([0.0, 1.0])
        r1 = math.exp(b1 * x)
        u = rng.random()
        if u < 1 - (1 - p) ** r1:
            t = -math.log(1 - (1 - (1 - u) ** (1 / r1)) / p)
            c = 1
        else:
            t = rng.expovariate(math.exp(b2 * x))
            c = 2
        cens = rng.uniform(0, 3)
        if cens < t:
            t, c = cens, 0
        times.append(t)
        causes.append(c)
        X.append([x])
    return times, causes, X


def test_simulation_recovers_beta() -> None:
    rng = random.Random(6)
    b1, b2, p = 0.5, -0.5, 0.6
    est = []
    for _ in range(40):
        times, causes, X = simulate(rng, 200, b1, b2, p)
        est.append(fit(times, causes, X).beta[0])
    mean = sum(est) / len(est)
    sd = math.sqrt(sum((e - mean) ** 2 for e in est) / (len(est) - 1))
    assert abs(mean - b1) < 4 * sd / math.sqrt(len(est)) + 0.02
    # The predicted cumulative incidence at t = 1 for x = 1 against the truth.
    times, causes, X = simulate(rng, 2000, b1, b2, p)
    r = fit(times, causes, X)
    steps = baseline(times, causes, X, r.beta)
    true = 1 - (1 - p * (1 - math.exp(-1.0))) ** math.exp(b1)
    assert abs(predict_cif(steps, [1.0], r.beta, 1.0) - true) < 0.04

References

  1. Jason P. Fine and Robert J. Gray, A proportional hazards model for the subdistribution of a competing risk, Journal of the American Statistical Association 94(446), 1999, pp. 496 to 509 (the model, the risk set with inverse probability of censoring weights, the estimating equation, its asymptotic normality and the robust variance, and the simulation design used here)
  2. Robert J. Gray, A class of K-sample tests for comparing the cumulative incidence of a competing risk, Annals of Statistics 16(3), 1988, pp. 1141 to 1154 (the subdistribution hazard and its risk set, and the K-sample test)
  3. H. Putter, M. Fiocco and R. B. Geskus, Tutorial in biostatistics, competing risks and multi-state models, Statistics in Medicine 26(11), 2007, pp. 2389 to 2430 (the interpretation of subdistribution hazard ratios next to cause-specific hazard ratios)
  4. John D. Kalbfleisch and Ross L. Prentice, The Statistical Analysis of Failure Time Data, 2nd edition, Wiley, 2002, Chapter 8 (competing risks, cause-specific hazards and cumulative incidence)

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)
WritingW4 complete
  • a review of the text: no review record reviews/YSYJCC/text.yaml