Skip to content

Checking proportional hazards

The Grambsch–Therneau test and Schoenfeld residuals show whether a hazard ratio changes over time, and what to do when it does.

Applied ~12 min10 steps

What runs in CodeSplash

You will be able to

  • Explain what a time-varying effect looks like in Schoenfeld residuals
  • Read the Grambsch–Therneau test on a Cox card, including what a large p-value doesn't show
  • Choose a remedy when proportional hazards fails

Read first

01

What the assumption says

Read

Proportional hazardsProportional hazardsCox models assume each hazard ratio is constant over time. means one number describes a covariate's effect across all of follow-up. If one group has 3 times the hazard of another at month 1, it has 3 times the hazard at month 12.

Treatments often break this: surgery can raise risk early and lower it later. Then the single hazard ratio is a weighted average of very different effects, and it may describe no one's experience.

02

The residual that reveals it

Read

At each death, a Schoenfeld residual compares the covariate value of the person who died with the expected value among those at risk. If the effect is constant, these residuals have no trend over time.

The Grambsch–Therneau testGrambsch–Therneau testTests proportional hazards by asking whether scaled Schoenfeld residuals trend over time. asks whether the residuals trend with (a function of) time, covariate by covariate and for the model as a whole. Its null hypothesis: the coefficient doesn't change.

βj(t)=βj+θj g(t),H0:θj=0\beta_j(t) = \beta_j + \theta_j\, g(t), \qquad H_0: \theta_j = 0
Schoenfeld residualsDoes a Cox model coefficient change over time (proportional-hazards check)?
View data
KM-transformed timescaled Schoenfeld residualterm
0.69000.0221age
0.6900−0.9653treatment
0.20600.1183age
0.2060−1.421treatment
0.9170−0.0725age
0.91700.3364treatment
0.5400−0.0791age
0.54000.1558treatment
0.90900.0402age
0.90900.5365treatment
0.6280−0.0106age
0.62802.208treatment
0.87500.0593age
0.87500.2587treatment
0.80300.0664age
0.80301.709treatment
0.76300.1597age
0.76301.004treatment
0.8770−0.0210age
0.87700.5896treatment
0.1830−0.0281age
0.1830−0.5443treatment
0.2820−0.0009age
0.2820−1.022treatment
0.2730−0.0129age
0.27300.2795treatment
0.91500.0624age
0.91500.1156treatment
0.05500.0160age
0.0550−1.210treatment
0.48500.1816age
0.4850−1.663treatment
0.95100.0084age
0.9510−0.8741treatment
0.76400.0383age
0.76400.5828treatment
0.7310−0.0139age
0.73102.404treatment
0.31400.0167age
0.31400.0711treatment
0.85500.0317age
0.85503.604treatment
0.65700.0093age
0.65701.503treatment
0.3850−0.0396age
0.38501.520treatment
0.07900.0724age
0.07900.2498treatment
0.08600.0772age
0.0860−1.989treatment
0.0630−0.0333age
0.0630−0.5789treatment
0.9740−0.0507age
0.9740−0.0108treatment
0.51600.0610age
0.5160−0.5535treatment
0.17400.0739age
0.17402.675treatment
0.3700−0.0606age
0.37001.612treatment

First 60 of 180 rows.

03

Predict the verdict

Predict

Predict first

The Veterans' trial is known for cell-type effects that shift during follow-up. The Cox model includes cell type and age. What will the global proportional-hazards test say?

Compatible with proportional hazardsEvidence against proportional hazards
Reveal

Evidence against it: χ2\chi^2 = 10.89, p = .028. So the hazard ratios on that card are averages over follow-up, and an honest report says so. For the lung model the same test gives p = .250.

04

Find it on the card

In the app

The assumption row Proportional hazards reports this test. When it warns, the card offers a remedy: a log-normal accelerated failure time model, which doesn't assume proportional hazards. Open the example and find it.

Cox proportional hazards modelRecorded · Python and R agreeRecorded 2026-11-17 · 70 values compared
R

HR = 2.70, 95% CI [1.64, 4.44], p < .001

Likelihood-ratio χ²
25.252
df
4
p
< .001
Concordance (C, apparent)
0.6117
AIC
993.65

Effect size

  • Hazard ratio (celltype: smallcell) 2.696 95% CI [1.639, 4.435]

Plots

Hazard ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Hazard ratioupperTermlower
2.6964.435celltype: smallcell1.639
3.1755.638celltype: adeno1.788
1.2652.180celltype: large0.7343
1.0061.025age0.9876
Scaled Schoenfeld residualsDoes a Cox model coefficient change over time (proportional-hazards check)?
View data
β(t)Termtime
−3.499celltype: smallcell1
−3.249celltype: smallcell1
1.969celltype: smallcell2
2.861celltype: smallcell3
2.072celltype: smallcell4
1.786celltype: smallcell7
1.836celltype: smallcell7
2.777celltype: smallcell7
−3.416celltype: smallcell8
2.792celltype: smallcell8
1.858celltype: smallcell8
2.750celltype: smallcell8
−3.278celltype: smallcell10
1.888celltype: smallcell10
−3.274celltype: smallcell11
2.778celltype: smallcell12
−2.193celltype: smallcell12
1.970celltype: smallcell13
1.921celltype: smallcell13
−3.204celltype: smallcell15
−2.134celltype: smallcell15
1.979celltype: smallcell16
2.097celltype: smallcell18
1.947celltype: smallcell18
2.747celltype: smallcell18
3.007celltype: smallcell19
−1.897celltype: smallcell19
1.955celltype: smallcell20
2.047celltype: smallcell20
2.063celltype: smallcell21
1.930celltype: smallcell21
1.975celltype: smallcell22
2.157celltype: smallcell24
2.940celltype: smallcell24
−3.239celltype: smallcell25
2.027celltype: smallcell25
2.018celltype: smallcell25
2.070celltype: smallcell27
2.043celltype: smallcell29
2.107celltype: smallcell30
−3.225celltype: smallcell30
2.081celltype: smallcell31
3.172celltype: smallcell31
−3.189celltype: smallcell33
2.995celltype: smallcell35
3.039celltype: smallcell36
−3.280celltype: smallcell42
−1.781celltype: smallcell43
−3.236celltype: smallcell44
2.936celltype: smallcell45
2.876celltype: smallcell48
−1.646celltype: smallcell49
2.168celltype: smallcell51
2.235celltype: smallcell51
3.085celltype: smallcell51
2.342celltype: smallcell52
3.317celltype: smallcell52
−1.629celltype: smallcell52
−1.772celltype: smallcell53
2.295celltype: smallcell54

First 60 of 512 rows.

Martingale residuals by predictor (functional form)Is a predictor's effect really a straight line?
View data
Martingale residualPredictorPredictor value
0.6453age69
−1.111age64
0.0891age38
0.3827age63
0.4064age65
0.9528age49
0.6108age69
0.4796age68
−0.2680age43
−0.4876age70
0.7631age81
0.9607age63
0.2747age63
−0.1477age52
0.9475age48
0.5304age61
−3.089age42
0.9584age35
0.1893age63
0.8143age56
−1.547age55
−1.197age67
−1.068age63
0.1296age65
−0.3784age46
0.7795age53
−1.083age69
0.6321age68
0.2534age43
0.6777age55
0.7725age42
−0.8114age64
0.6838age65
0.4893age65
0.2896age55
−2.750age66
0.7470age60
0.2928age67
−0.5286age53
0.5636age62
0.1700age67
0.9268age72
0.1746age48
−4.367age68
0.8586age67
0.8768age61
−0.2888age60
0.3646age62
−0.5481age38
−0.8627age50
0.7985age63
−1.636age64
0.9591age43
−0.1466age34
−0.1479age66
−0.0385age62
−0.2095age52
−1.935age47
−0.6009age63
0.9173age68

First 60 of 137 rows.

Cox–Snell residuals on exponential paperDo these failures fall on a straight line on this family's probability paper?
View data
EventSeriesUnit exponential F(r)Cox–Snell residual
1data—0.3547
1data—2.111
1data—0.9109
1data—0.6173
1data—0.5936
1data—0.0472
1data—0.3892
1data—0.5204
1data—1.268
0data—0.4876
1data—0.2369
1data—0.0393
1data—0.7253
0data—0.1477
1data—0.0525
1data—0.4696
1data—4.089
1data—0.0416
1data—0.8107
1data—0.1857
0data—1.547
0data—1.197
1data—2.068
1data—0.8704
1data—1.378
1data—0.2205
1data—2.083
1data—0.3679
1data—0.7466
1data—0.3223
1data—0.2275
1data—1.811
1data—0.3162
1data—0.5107
1data—0.7104
1data—3.750
1data—0.2530
1data—0.7072
1data—1.529
1data—0.4364
1data—0.8300
1data—0.0732
1data—0.8254
1data—5.367
1data—0.1414
1data—0.1232
1data—1.289
1data—0.6354
1data—1.548
1data—1.863
1data—0.2015
1data—2.636
1data—0.0409
1data—1.147
1data—1.148
1data—1.038
1data—1.209
1data—2.935
1data—1.601
1data—0.0827

First 60 of 197 rows.

Assumptions

  • Proportional hazards — Global Grambsch–Therneau χ²(4) = 10.89, p = .028; time-varying effect for celltype. Consider stratifying by it, a time-varying effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival.
  • Events per variable — 32.0 events per coefficient.
  • Non-informative censoring — 9 of 137 observations are censored.
  • Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
  • Influential observations — Largest |DFBETAS| = 0.53; 17 of 137 subjects above 2/√n = 0.17.

Hazard ratios

TermβSEHR95% CI low95% CI highzp
celltype: smallcell0.99190.25402.6961.6394.4353.906< .001
celltype: adeno1.1550.29303.1751.7885.6383.942< .001
celltype: large0.23530.27761.2650.73432.1800.8477.397
age0.00590.00941.0060.98761.0250.6305.528

Overall tests

Testχ²dfp
Likelihood ratio25.2524< .001
Wald24.5294< .001
Score (log-rank)25.9404< .001

Proportional-hazards test (Grambsch–Therneau)

Termχ²dfp
celltype8.7943.032
age1.2741.259
Global10.8874.028

Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").

Model fit

MeasureValue95% CI low95% CI highNote
Concordance (C, apparent)0.61170.55150.6718Harrell's C on the data the model was fitted to; SE 0.0307 (infinitesimal jackknife).
AIC993.65——−2 log partial likelihood + 2k.
BIC1005.05——−2 log partial likelihood + k·log(events), events = 128.

The apparent C is optimistic for new data; the bootstrap option estimates by how much.

Most influential subjects

RowTerm most affectedDFBETADFBETASMartingale residual
17age0.00490.5268−3.089
44celltype: smallcell−0.1148−0.4520−4.367
58celltype: large−0.0794−0.2862−1.935
78celltype: smallcell0.07050.2777−1.816
70celltype: large0.07470.2691−3.256
36celltype: smallcell−0.0679−0.2673−2.750
75celltype: large0.07370.2656−2.181
91age0.00230.2499−1.104
83celltype: smallcell0.06220.2448−1.312
2celltype: smallcell0.06180.2435−1.111

Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.

  • Event: status = 1. Ties: efron.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cox proportional hazards regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox 1.1.0 · spec 69935454976a6434
# Dataset: veteran (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(survival)
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/veteran.parquet", col_select = c("time", "status", "celltype", "age")))
n_input <- nrow(df)
df[["celltype"]] <- factor(df[["celltype"]], levels = c("squamous", "smallcell", "adeno", "large"))  # stored level order
df <- df[stats::complete.cases(df[c("time", "status", "celltype", "age")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "status", "celltype", "age"))  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol <- "time"
ecol <- "status"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
codes <- sort(unique(df[[ecol]]))
if (all(codes %in% c(0, 1))) {
  event_code <- 1  # 0 = censored, 1 = event
} else if (all(codes %in% c(1, 2))) {
  event_code <- 2  # 1 = censored, 2 = event (survival::Surv convention)
} else {
  stop(sprintf("%s must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column", ecol))
}
ev <- df[[ecol]] == event_code
event_label <- sprintf("%s = %s", ecol, format(event_code))
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)

# %% Predictors (treatment contrasts against the first stored level)
preds <- c("celltype", "age")
dd <- data.frame(.t = tt, .e = ev)
labels <- character(0)
for (pname in preds) {
  x <- df[[pname]]
  if (is.factor(x)) {
    if (nlevels(x) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = pname, min = 2, k = nlevels(x))  # a factor needs two levels with data
    labels <- c(labels, paste0(pname, ": ", levels(x)[-1]))
  } else {
    labels <- c(labels, pname)
  }
  dd[[pname]] <- x
}
rhs <- paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ")

# %% Cox model
conf <- 0.95
ties <- "efron"  # pinned: coxph's default is Efron, SAS/Stata use Breslow
sname <- NULL
fit <- coxph(stats::as.formula(paste("Surv(.t, .e) ~", rhs)), data = dd, ties = ties,
             control = coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60))
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(vcov(fit))
se <- sqrt(diag(V))
z <- beta / se
pv <- 2 * stats::pnorm(-abs(z))
q <- stats::qnorm(1 - (1 - conf) / 2)
hr <- exp(beta)
hr_lo <- exp(beta - q * se)
hr_hi <- exp(beta + q * se)
k <- length(beta)
lr <- 2 * diff(fit$loglik)
lr_p <- stats::pchisq(lr, k, lower.tail = FALSE)
wald <- drop(beta %*% solve(V, beta))
score <- unname(fit$score)
cc <- concordance(fit)  # var: infinitesimal-jackknife variance of C
conc <- unname(cc$concordance)
one_time <- length(unique(tt[ev])) < 2  # with every event at one time the proportional-hazards test is undefined
if (one_time) {
  warnings <- c(warnings, cs_warning("CS_W_TIES", column = tcol, consequence = "every event happened at the same time, so the proportional-hazards test is not computed."))
  zph <- NULL
  zt <- matrix(NA_real_, length(preds) + 1, 3)
} else {
  zph <- cox.zph(fit, transform = "km")
  zt <- unname(zph$table)
}
ph_chisq <- zt[nrow(zt), 1]
ph_p <- zt[nrow(zt), 3]

# %% Fit measures and the apparent concordance
aic <- -2 * fit$loglik[2] + 2 * k
bic <- -2 * fit$loglik[2] + k * log(sum(ev))  # n = the number of events, as BIC() for coxph
c_se <- sqrt(unname(cc$var))
ci_ok <- is.finite(conc) && is.finite(c_se)
c_lo <- if (ci_ok) max(0, conc - q * c_se) else NA_real_
c_hi <- if (ci_ok) min(1, conc + q * c_se) else NA_real_

# %% Residuals: martingale (functional form), Cox–Snell (overall fit) and dfbeta (influence)
mart <- unname(residuals(fit, type = "martingale"))
cox_snell <- ev - mart
dfb <- unname(as.matrix(residuals(fit, type = "dfbeta")))  # one-step change in each coefficient when the row is left out
dfbs <- sweep(dfb, 2, se, "/")
abs_dfbs <- abs(dfbs)
infl_cut <- 2 / sqrt(length(tt))
n_infl <- sum(apply(abs_dfbs, 1, max) > infl_cut)
max_dfbs <- max(abs_dfbs)
num_preds <- preds[vapply(preds, function(p) is.numeric(df[[p]]) && length(unique(df[[p]])) > 2, logical(1))]
optimism <- NA_real_
c_corrected <- NA_real_
boot_used <- 0

values <- list(
  n = length(tt), events = sum(ev), n_coef = k, loglik = fit$loglik[2], loglik0 = fit$loglik[1],
  lr_chisq = lr, lr_df = k, lr_p = lr_p,
  wald_chisq = wald, wald_p = stats::pchisq(wald, k, lower.tail = FALSE),
  score_chisq = score, score_p = stats::pchisq(score, k, lower.tail = FALSE),
  concordance = conc, ph_chisq = ph_chisq, ph_p = ph_p,
  coef_1_label = labels[1], hr_1 = hr[1], hr_1_low = hr_lo[1], hr_1_high = hr_hi[1], p_1 = pv[1],
  epv = sum(ev) / k, event_label = event_label,
  aic = aic, bic = bic, concordance_se = c_se, concordance_low = c_lo, concordance_high = c_hi,
  max_abs_dfbetas = max_dfbs, n_influential = n_infl, martingale_min = min(mart), martingale_max = max(mart),
  optimism = optimism, concordance_corrected = c_corrected, boot_used = boot_used
)
coef_rows <- list()
for (i in seq_along(labels)) {
  lab <- labels[i]
  vals <- list(coef = beta[i], se = se[i], hr = hr[i], hr_low = hr_lo[i], hr_high = hr_hi[i], z = z[i], p = pv[i])
  for (key in names(vals)) values[[sprintf("%s[%s]", key, lab)]] <- vals[[key]]
  values[[sprintf("dfbetas_max[%s]", lab)]] <- max(abs_dfbs[, i])
  coef_rows[[i]] <- c(list(term = lab), vals)
}
ph_rows <- list()
for (i in seq_along(preds)) {
  values[[sprintf("ph_chisq[%s]", preds[i])]] <- zt[i, 1]
  values[[sprintf("ph_p[%s]", preds[i])]] <- zt[i, 3]
  ph_rows[[i]] <- list(term = preds[i], chisq = zt[i, 1], df = zt[i, 2], p = zt[i, 3])
}
ph_rows[[length(ph_rows) + 1]] <- list(term = "Global", chisq = ph_chisq, df = k, p = ph_p)

# %% Assumptions
bad <- preds[which(zt[seq_along(preds), 3] < 0.05)]
ph_check <- if (one_time) {
  list(key = "proportional_hazards", label = "Proportional hazards", status = "info", detail = "Not tested: every event happened at the same time.")
} else {
  list(key = "proportional_hazards", label = "Proportional hazards", status = if (ph_p < 0.05 || length(bad)) "warn" else "pass",
       statistic = ph_chisq, p = ph_p,
       detail = paste0(sprintf("Global Grambsch–Therneau χ²(%d) = %.2f, %s", k, ph_chisq, cs_fmt_p(ph_p)),
                       if (length(bad)) sprintf(paste0("; time-varying effect for %s. Consider stratifying by %s, a time-varying",
                                                       " effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival."),
                                                paste(bad, collapse = ", "), if (length(bad) == 1) "it" else "them")
                       else "; no evidence that hazard ratios change over time."))
}
assumptions <- list(
  ph_check,
  list(key = "events_per_variable", label = "Events per variable", status = if (values$epv < 10) "warn" else "pass",
       detail = paste0(sprintf("%.1f events per coefficient", values$epv),
                       if (values$epv < 10) " — fewer than 10; estimates may be biased and unstable." else ".")),
  list(key = "censoring", label = "Non-informative censoring", status = "info",
       detail = sprintf("%d of %d observations are censored.", sum(!ev), length(ev))),
  list(key = "functional_form", label = "Functional form", status = "info",
       detail = if (length(num_preds)) sprintf(paste0("Not tested: look at the martingale residuals against %s. A smooth that bends away from zero",
                                                      " suggests a transformation or a spline."), paste(num_preds, collapse = ", "))
                else "No numeric predictor with more than two values to check."),
  list(key = "influence", label = "Influential observations", status = if (max_dfbs > 1) "warn" else "pass", statistic = max_dfbs,
       detail = paste0(sprintf("Largest |DFBETAS| = %.2f; %d of %d subjects above 2/√n = %.2f", max_dfbs, n_infl, length(tt), infl_cut),
                       if (max_dfbs > 1) ". At least one subject moves a coefficient by more than one standard error." else "."))
)

# %% Charts: hazard ratios and scaled Schoenfeld residuals
sch <- if (one_time) matrix(numeric(0), 0, k) else as.matrix(zph$y)
sch_times <- if (one_time) numeric(0) else zph$time
rows_sch <- seq_len(nrow(sch))
if (length(rows_sch) * k > 5000) rows_sch <- unique(round(seq(1, nrow(sch), length.out = max(5000 %/% k, 2))))
sch_time <- rep(sch_times[rows_sch], k)
sch_res <- as.vector(sch[rows_sch, , drop = FALSE])
sch_term <- rep(labels, each = length(rows_sch))

# %% Charts: martingale residuals by numeric predictor, Cox–Snell residuals on exponential paper
mart_x <- numeric(0)
mart_r <- numeric(0)
mart_term <- character(0)
if (length(num_preds)) {
  rows_m <- seq_along(tt)
  if (length(rows_m) * length(num_preds) > 5000) rows_m <- unique(round(seq(1, length(tt), length.out = max(5000 %/% length(num_preds), 2))))
  for (pname in num_preds) {
    mart_x <- c(mart_x, as.numeric(df[[pname]])[rows_m])
    mart_r <- c(mart_r, mart[rows_m])
    mart_term <- c(mart_term, rep(pname, length(rows_m)))
  }
}
rows_cs <- seq_along(tt)
if (length(rows_cs) > 5000) rows_cs <- unique(round(seq(1, length(tt), length.out = 5000)))
cs_fit <- if (max(cox_snell) > 0) seq(0, max(cox_snell), length.out = 61)[-1] else numeric(0)

# %% Influence: the subjects with the largest scaled dfbeta
row_max <- apply(abs_dfbs, 1, max)
top <- head(order(-row_max, seq_along(row_max)), 10)
infl_rows <- lapply(top, function(r) {
  j <- which.max(abs_dfbs[r, ])
  list(row = r, term = labels[j], dfbeta = dfb[r, j], dfbetas = dfbs[r, j], martingale = mart[r])
})

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
fit_rows <- list(
  list(measure = "Concordance (C, apparent)", value = conc, low = c_lo, high = c_hi,
       note = sprintf("Harrell's C on the data the model was fitted to; SE %.4f (infinitesimal jackknife).", c_se)),
  list(measure = "AIC", value = aic, low = NA_real_, high = NA_real_, note = "−2 log partial likelihood + 2k."),
  list(measure = "BIC", value = bic, low = NA_real_, high = NA_real_, note = sprintf("−2 log partial likelihood + k·log(events), events = %d.", sum(ev)))
)
if (!is.na(c_corrected)) {
  fit_rows <- append(fit_rows, list(list(measure = "Concordance (optimism-corrected)", value = c_corrected, low = NA_real_, high = NA_real_,
                                         note = sprintf("Apparent C minus the mean optimism %.4f over %d bootstrap refits (Harrell).", optimism, boot_used))), after = 1)
}
cs_publish(list(
  method = "survival.cox",
  methodVersion = "1.1.0",
  title = "Cox proportional hazards model",
  engine = cs_engine_info("survival", "codesplashr"),
  n = length(tt),
  summary = sprintf("Cox model (%d events): likelihood-ratio χ²(%d) = %.2f, %s; apparent concordance %.3f.", sum(ev), k, lr, cs_fmt_p(lr_p), conc),
  apa = sprintf("HR = %s, %s CI [%s, %s], %s", cs_fmt_num(hr[1]), pct, cs_fmt_num(hr_lo[1]), cs_fmt_num(hr_hi[1]), cs_fmt_p(pv[1])),
  statistics = list(
    list(key = "lr_chisq", label = "Likelihood-ratio χ²", value = lr), list(key = "lr_df", label = "df", value = k, format = "integer"),
    list(key = "lr_p", label = "p", value = lr_p, format = "p"), list(key = "concordance", label = "Concordance (C, apparent)", value = conc),
    list(key = "aic", label = "AIC", value = aic)
  ),
  tables = list(
    list(key = "coefficients", title = "Hazard ratios", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β", type = "number"),
      list(key = "se", label = "SE", type = "number"), list(key = "hr", label = "HR", type = "number"),
      list(key = "hr_low", label = paste(pct, "CI low"), type = "number"), list(key = "hr_high", label = paste(pct, "CI high"), type = "number"),
      list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue")
    ), rows = coef_rows),
    list(key = "tests", title = "Overall tests", columns = list(
      list(key = "test", label = "Test", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
      list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")
    ), rows = list(
      list(test = "Likelihood ratio", chisq = lr, df = k, p = lr_p),
      list(test = "Wald", chisq = wald, df = k, p = values$wald_p),
      list(test = "Score (log-rank)", chisq = score, df = k, p = values$score_p)
    )),
    list(key = "proportional_hazards", title = "Proportional-hazards test (Grambsch–Therneau)", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
      list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")
    ), rows = ph_rows, note = "Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = \"km\")."),
    list(key = "fit", title = "Model fit", columns = list(
      list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
      list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number"),
      list(key = "note", label = "Note", type = "string")
    ), rows = fit_rows, note = "The apparent C is optimistic for new data; the bootstrap option estimates by how much."),
    list(key = "influence", title = "Most influential subjects", columns = list(
      list(key = "row", label = "Row", type = "integer"), list(key = "term", label = "Term most affected", type = "string"),
      list(key = "dfbeta", label = "DFBETA", type = "number"), list(key = "dfbetas", label = "DFBETAS", type = "number"),
      list(key = "martingale", label = "Martingale residual", type = "number")
    ), rows = infl_rows, note = "Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.")
  ),
  effectSizes = list(list(key = "hr_1", label = sprintf("Hazard ratio (%s)", labels[1]), value = hr[1], ciLow = hr_lo[1],
                          ciHigh = hr_hi[1], ciLevel = conf, method = "Wald interval on log(HR)")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Event: %s. Ties: %s.", event_label, ties), if (!is.null(sname)) sprintf(" Stratified by %s.", sname) else "")),
  charts = list(
    cs_chart("hr", "forest", "Hazard ratios", list(
      label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("Hazard ratio", hr, "numeric"),
      low = cs_col("lower", hr_lo, "numeric"), high = cs_col("upper", hr_hi, "numeric")
    ), controls = list(reference = 1, log = TRUE)),
    cs_chart("schoenfeld", "schoenfeld", "Scaled Schoenfeld residuals", list(
      time = cs_col(tcol, sch_time, "numeric"), residual = cs_col("β(t)", sch_res, "numeric"),
      term = cs_col("Term", sch_term, "categorical", levels = labels)
    )),
    if (length(num_preds)) cs_chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", list(
      x = cs_col("Predictor value", mart_x, "numeric"), partial = cs_col("Martingale residual", mart_r, "numeric"),
      term = cs_col("Predictor", mart_term, "categorical", levels = num_preds)
    ), controls = list(smooth = TRUE)),
    cs_chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", list(
      time = cs_col("Cox–Snell residual", c(cox_snell[rows_cs], cs_fit), "numeric"),
      event = cs_col("Event", c(as.numeric(ev[rows_cs]), rep(NA_real_, length(cs_fit))), "numeric"),
      fit = cs_col("Unit exponential F(r)", c(rep(NA_real_, length(rows_cs)), -expm1(-cs_fit)), "numeric"),
      family = cs_col("Series", c(rep("data", length(rows_cs)), rep("unit exponential", length(cs_fit))), "categorical",
                      levels = c("data", "unit exponential"))
    ), controls = list(paper = "exponential"))
  ),
  values = values
))
Python

HR = 2.70, 95% CI [1.64, 4.44], p < .001

Likelihood-ratio χ²
25.252
df
4
p
< .001
Concordance (C, apparent)
0.6117
AIC
993.65

Effect size

  • Hazard ratio (celltype: smallcell) 2.696 95% CI [1.639, 4.435]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Proportional hazards — Global Grambsch–Therneau χ²(4) = 10.89, p = .028; time-varying effect for celltype. Consider stratifying by it, a time-varying effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival.
  • Events per variable — 32.0 events per coefficient.
  • Non-informative censoring — 9 of 137 observations are censored.
  • Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
  • Influential observations — Largest |DFBETAS| = 0.53; 17 of 137 subjects above 2/√n = 0.17.

Hazard ratios

TermβSEHR95% CI low95% CI highzp
celltype: smallcell0.99190.25402.6961.6394.4353.906< .001
celltype: adeno1.1550.29303.1751.7885.6383.942< .001
celltype: large0.23530.27761.2650.73432.1800.8477.397
age0.00590.00941.0060.98761.0250.6305.528

Overall tests

Testχ²dfp
Likelihood ratio25.2524< .001
Wald24.5294< .001
Score (log-rank)25.9404< .001

Proportional-hazards test (Grambsch–Therneau)

Termχ²dfp
celltype8.7943.032
age1.2741.259
Global10.8874.028

Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").

Model fit

MeasureValue95% CI low95% CI highNote
Concordance (C, apparent)0.61170.55150.6718Harrell's C on the data the model was fitted to; SE 0.0307 (infinitesimal jackknife).
AIC993.65——−2 log partial likelihood + 2k.
BIC1005.05——−2 log partial likelihood + k·log(events), events = 128.

The apparent C is optimistic for new data; the bootstrap option estimates by how much.

Most influential subjects

RowTerm most affectedDFBETADFBETASMartingale residual
17age0.00490.5268−3.089
44celltype: smallcell−0.1148−0.4520−4.367
58celltype: large−0.0794−0.2862−1.935
78celltype: smallcell0.07050.2777−1.816
70celltype: large0.07470.2691−3.256
36celltype: smallcell−0.0679−0.2673−2.750
75celltype: large0.07370.2656−2.181
91age0.00230.2499−1.104
83celltype: smallcell0.06220.2448−1.312
2celltype: smallcell0.06180.2435−1.111

Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.

  • Event: status = 1. Ties: efron.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cox proportional hazards regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox 1.1.0 · spec 69935454976a6434
# Dataset: veteran (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import survival as sv  # Cox fit, proportional-hazards test, concordance

# %% Data
df = pd.read_parquet("tests/parity/fixtures/veteran.parquet", columns=["time", "status", "celltype", "age"])
n_input = len(df)
df["celltype"] = pd.Categorical(df["celltype"], categories=["squamous", "smallcell", "adeno", "large"])  # stored level order
df = df.dropna(subset=["time", "status", "celltype", "age"])  # listwise deletion over the analysis columns
df["celltype"] = df["celltype"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "status", "celltype", "age"])  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol = "time"
ecol = "status"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
    cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
codes = set(np.unique(df[ecol].to_numpy(dtype=float)).tolist())
if codes <= {0.0, 1.0}:
    event_code = 1.0  # 0 = censored, 1 = event
elif codes <= {1.0, 2.0}:
    event_code = 2.0  # 1 = censored, 2 = event (survival::Surv convention)
else:
    raise ValueError(f"{ecol} must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column")
ev = df[ecol].to_numpy(dtype=float) == event_code
event_label = f"{ecol} = {event_code:g}"
if not ev.any():
    cs.cs_error("CS_E_NO_EVENTS", event=event_label)

# %% Design matrix (treatment contrasts against the first stored level)
preds = ["celltype", "age"]
cols, labels, terms = [], [], []
for pname in preds:
    s = df[pname]
    if isinstance(s.dtype, pd.CategoricalDtype):
        lv = [str(x) for x in s.cat.categories]
        if len(lv) < 2:
            cs.cs_error("CS_E_TOO_FEW_GROUPS", column=pname, min=2, k=len(lv))  # a factor needs two levels with data
        idx = []
        for level in lv[1:]:
            idx.append(len(cols))
            cols.append((s.astype(str) == level).to_numpy(dtype=float))
            labels.append(f"{pname}: {level}")
        terms.append(idx)
    else:
        terms.append([len(cols)])
        cols.append(s.to_numpy(dtype=float))
        labels.append(pname)
X = np.column_stack(cols)

# %% Cox model
conf = 0.95
ties = "efron"  # pinned: coxph's default is Efron, SAS/Stata use Breslow
sname = None
scodes = None
fit = sv.cox_fit(t, ev, X, strata=scodes, ties=ties)
beta = fit["coef"]
se = np.sqrt(np.diag(fit["cov"]))
z = beta / se
pv = 2 * stats.norm.sf(np.abs(z))
q = stats.norm.ppf(1 - (1 - conf) / 2)
hr, hr_lo, hr_hi = np.exp(beta), np.exp(beta - q * se), np.exp(beta + q * se)
k = len(beta)
lr_p = float(stats.chi2.sf(fit["lr"], k))
conc = sv.concordance(t, ev, X @ beta, strata=scodes)["concordance"]
one_time = np.unique(t[ev]).size < 2  # with every event at one time the proportional-hazards test is undefined
if one_time:
    warnings.append(cs.cs_warning("CS_W_TIES", column=tcol, consequence="every event happened at the same time, so the proportional-hazards test is not computed."))
    zph = {"global": (None, None, None), "terms": [(None, None, None) for _ in preds], "times": np.zeros(0), "scaled": np.zeros((0, k))}
else:
    zph = sv.cox_zph(t, ev, X, beta, terms, strata=scodes, ties=ties)
ph_chisq, _, ph_p = zph["global"]

# %% Fit measures and the apparent concordance
aic = -2 * fit["loglik"] + 2 * k
bic = -2 * fit["loglik"] + k * np.log(ev.sum())  # n = the number of events, as R's BIC() for coxph
cvar = sv.concordance_var(t, ev, X @ beta, strata=scodes)  # infinitesimal-jackknife SE, as survival::concordance()
c_se = cvar["se"]
c_lo, c_hi = (max(0.0, conc - q * c_se), min(1.0, conc + q * c_se)) if np.isfinite(conc) and np.isfinite(c_se) else (None, None)

# %% Residuals: martingale (functional form), Cox–Snell (overall fit) and dfbeta (influence)
res = sv.cox_residuals(t, ev, X, beta, strata=scodes, ties=ties)
mart = res["martingale"]
cox_snell = ev - mart
dfb = res["score"] @ fit["cov"]  # one-step change in each coefficient when the row is left out
dfbs = dfb / se
abs_dfbs = np.abs(dfbs)
infl_cut = 2 / np.sqrt(len(t))
n_infl = int((abs_dfbs.max(axis=1) > infl_cut).sum())
max_dfbs = float(abs_dfbs.max())
num_preds = [pname for pname, idx in zip(preds, terms) if len(idx) == 1 and not isinstance(df[pname].dtype, pd.CategoricalDtype)
             and not pd.api.types.is_bool_dtype(df[pname]) and df[pname].nunique() > 2]
optimism = c_corrected = None
boot_used = 0

values = {
    "n": float(len(t)), "events": float(ev.sum()), "n_coef": float(k), "loglik": fit["loglik"], "loglik0": fit["loglik0"],
    "lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": lr_p,
    "wald_chisq": fit["wald"], "wald_p": float(stats.chi2.sf(fit["wald"], k)),
    "score_chisq": fit["score"], "score_p": float(stats.chi2.sf(fit["score"], k)),
    "concordance": conc, "ph_chisq": ph_chisq, "ph_p": ph_p,
    "coef_1_label": labels[0], "hr_1": float(hr[0]), "hr_1_low": float(hr_lo[0]), "hr_1_high": float(hr_hi[0]), "p_1": float(pv[0]),
    "epv": float(ev.sum()) / k, "event_label": event_label,
    "aic": float(aic), "bic": float(bic), "concordance_se": float(c_se), "concordance_low": c_lo, "concordance_high": c_hi,
    "max_abs_dfbetas": max_dfbs, "n_influential": float(n_infl), "martingale_min": float(mart.min()), "martingale_max": float(mart.max()),
    "optimism": optimism, "concordance_corrected": c_corrected, "boot_used": float(boot_used),
}
coef_rows = []
for i, lab in enumerate(labels):
    for key, val in (("coef", beta[i]), ("se", se[i]), ("hr", hr[i]), ("hr_low", hr_lo[i]), ("hr_high", hr_hi[i]), ("z", z[i]), ("p", pv[i])):
        values[f"{key}[{lab}]"] = float(val)
    values[f"dfbetas_max[{lab}]"] = float(abs_dfbs[:, i].max())
    coef_rows.append({"term": lab, "coef": float(beta[i]), "se": float(se[i]), "hr": float(hr[i]), "hr_low": float(hr_lo[i]),
                      "hr_high": float(hr_hi[i]), "z": float(z[i]), "p": float(pv[i])})
ph_rows = []
for pname, (c2, dfree, pp) in zip(preds, zph["terms"]):
    values[f"ph_chisq[{pname}]"], values[f"ph_p[{pname}]"] = c2, pp
    ph_rows.append({"term": pname, "chisq": c2, "df": None if dfree is None else float(dfree), "p": pp})
ph_rows.append({"term": "Global", "chisq": ph_chisq, "df": float(k), "p": ph_p})

# %% Assumptions
bad = [r["term"] for r in ph_rows[:-1] if r["p"] is not None and r["p"] < 0.05]
if one_time:
    ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "info", "detail": "Not tested: every event happened at the same time."}
else:
    ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "warn" if ph_p < 0.05 or bad else "pass",
                "statistic": ph_chisq, "p": ph_p,
                "detail": f"Global Grambsch–Therneau χ²({k}) = {ph_chisq:.2f}, {cs.fmt_p(ph_p)}"
                + (f"; time-varying effect for {', '.join(bad)}. Consider stratifying by {'it' if len(bad) == 1 else 'them'}, a time-varying"
                   " effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival."
                   if bad else "; no evidence that hazard ratios change over time.")}
assumptions = [
    ph_check,
    {"key": "events_per_variable", "label": "Events per variable", "status": "warn" if values["epv"] < 10 else "pass",
     "detail": f"{values['epv']:.1f} events per coefficient" + (" — fewer than 10; estimates may be biased and unstable." if values["epv"] < 10 else ".")},
    {"key": "censoring", "label": "Non-informative censoring", "status": "info", "detail": f"{int((~ev).sum())} of {len(ev)} observations are censored."},
    {"key": "functional_form", "label": "Functional form", "status": "info",
     "detail": (f"Not tested: look at the martingale residuals against {', '.join(num_preds)}. A smooth that bends away from zero"
                " suggests a transformation or a spline." if num_preds else "No numeric predictor with more than two values to check.")},
    {"key": "influence", "label": "Influential observations", "status": "warn" if max_dfbs > 1 else "pass", "statistic": max_dfbs,
     "detail": f"Largest |DFBETAS| = {max_dfbs:.2f}; {n_infl} of {len(t)} subjects above 2/√n = {infl_cut:.2f}"
     + (". At least one subject moves a coefficient by more than one standard error." if max_dfbs > 1 else ".")},
]

# %% Charts: hazard ratios and scaled Schoenfeld residuals
rows_sch = np.arange(len(zph["times"]))
if len(rows_sch) * k > 5000:
    rows_sch = np.unique(np.round(np.linspace(0, len(rows_sch) - 1, max(5000 // k, 2))).astype(int))
sch_time, sch_res, sch_term = [], [], []
for i, lab in enumerate(labels):
    sch_time += zph["times"][rows_sch].tolist()
    sch_res += zph["scaled"][rows_sch, i].tolist()
    sch_term += [lab] * len(rows_sch)

# %% Charts: martingale residuals by numeric predictor, Cox–Snell residuals on exponential paper
mart_x, mart_r, mart_term = [], [], []
if num_preds:
    rows_m = np.arange(len(t))
    if len(rows_m) * len(num_preds) > 5000:
        rows_m = np.unique(np.round(np.linspace(0, len(t) - 1, max(5000 // len(num_preds), 2))).astype(int))
    for pname in num_preds:
        mart_x += df[pname].to_numpy(dtype=float)[rows_m].tolist()
        mart_r += mart[rows_m].tolist()
        mart_term += [pname] * len(rows_m)
rows_cs = np.arange(len(t))
if len(rows_cs) > 5000:
    rows_cs = np.unique(np.round(np.linspace(0, len(t) - 1, 5000)).astype(int))
cs_fit = np.linspace(0.0, float(cox_snell.max()), 61)[1:] if cox_snell.max() > 0 else np.zeros(0)

# %% Influence: the subjects with the largest scaled dfbeta
top = np.lexsort((np.arange(len(t)), -abs_dfbs.max(axis=1)))[:10]
infl_rows = []
for r in top:
    j = int(np.argmax(abs_dfbs[r]))
    infl_rows.append({"row": float(r + 1), "term": labels[j], "dfbeta": float(dfb[r, j]), "dfbetas": float(dfbs[r, j]), "martingale": float(mart[r])})

# %% Result
pct = f"{conf:.0%}"
fit_rows = [
    {"measure": "Concordance (C, apparent)", "value": conc, "low": c_lo, "high": c_hi,
     "note": f"Harrell's C on the data the model was fitted to; SE {c_se:.4f} (infinitesimal jackknife)."},
    {"measure": "AIC", "value": float(aic), "low": None, "high": None, "note": "−2 log partial likelihood + 2k."},
    {"measure": "BIC", "value": float(bic), "low": None, "high": None, "note": f"−2 log partial likelihood + k·log(events), events = {int(ev.sum())}."},
]
if c_corrected is not None:
    fit_rows.insert(1, {"measure": "Concordance (optimism-corrected)", "value": c_corrected, "low": None, "high": None,
                        "note": f"Apparent C minus the mean optimism {optimism:.4f} over {boot_used} bootstrap refits (Harrell)."})
cs.publish({
    "method": "survival.cox",
    "methodVersion": "1.1.0",
    "title": "Cox proportional hazards model",
    "engine": cs.engine_info("numpy", "scipy", "statsmodels", "codesplash"),
    "n": int(len(t)),
    "summary": f"Cox model ({int(ev.sum())} events): likelihood-ratio χ²({k}) = {fit['lr']:.2f}, {cs.fmt_p(lr_p)}; apparent concordance {conc:.3f}.",
    "apa": f"HR = {cs.fmt_num(hr[0])}, {pct} CI [{cs.fmt_num(hr_lo[0])}, {cs.fmt_num(hr_hi[0])}], {cs.fmt_p(pv[0])}",
    "statistics": [
        {"key": "lr_chisq", "label": "Likelihood-ratio χ²", "value": fit["lr"]}, {"key": "lr_df", "label": "df", "value": float(k), "format": "integer"},
        {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"}, {"key": "concordance", "label": "Concordance (C, apparent)", "value": conc},
        {"key": "aic", "label": "AIC", "value": float(aic)},
    ],
    "tables": [
        {"key": "coefficients", "title": "Hazard ratios", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"}, {"key": "hr", "label": "HR", "type": "number"},
            {"key": "hr_low", "label": f"{pct} CI low", "type": "number"}, {"key": "hr_high", "label": f"{pct} CI high", "type": "number"},
            {"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        ], "rows": coef_rows},
        {"key": "tests", "title": "Overall tests", "columns": [
            {"key": "test", "label": "Test", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
            {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
        ], "rows": [
            {"test": "Likelihood ratio", "chisq": fit["lr"], "df": float(k), "p": lr_p},
            {"test": "Wald", "chisq": fit["wald"], "df": float(k), "p": values["wald_p"]},
            {"test": "Score (log-rank)", "chisq": fit["score"], "df": float(k), "p": values["score_p"]},
        ]},
        {"key": "proportional_hazards", "title": "Proportional-hazards test (Grambsch–Therneau)", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
            {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
        ], "rows": ph_rows, "note": "Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = \"km\")."},
        {"key": "fit", "title": "Model fit", "columns": [
            {"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
            {"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
            {"key": "note", "label": "Note", "type": "string"},
        ], "rows": fit_rows, "note": "The apparent C is optimistic for new data; the bootstrap option estimates by how much."},
        {"key": "influence", "title": "Most influential subjects", "columns": [
            {"key": "row", "label": "Row", "type": "integer"}, {"key": "term", "label": "Term most affected", "type": "string"},
            {"key": "dfbeta", "label": "DFBETA", "type": "number"}, {"key": "dfbetas", "label": "DFBETAS", "type": "number"},
            {"key": "martingale", "label": "Martingale residual", "type": "number"},
        ], "rows": infl_rows, "note": "Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE."},
    ],
    "effectSizes": [{"key": "hr_1", "label": f"Hazard ratio ({labels[0]})", "value": float(hr[0]), "ciLow": float(hr_lo[0]),
                     "ciHigh": float(hr_hi[0]), "ciLevel": conf, "method": "Wald interval on log(HR)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Event: {event_label}. Ties: {ties}." + (f" Stratified by {sname}." if sname else "")],
    "charts": [
        cs.chart("hr", "forest", "Hazard ratios", {
            "label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Hazard ratio", hr, "numeric"),
            "low": cs.col("lower", hr_lo, "numeric"), "high": cs.col("upper", hr_hi, "numeric"),
        }, controls={"reference": 1, "log": True}),
        cs.chart("schoenfeld", "schoenfeld", "Scaled Schoenfeld residuals", {
            "time": cs.col(tcol, sch_time, "numeric"), "residual": cs.col("β(t)", sch_res, "numeric"),
            "term": cs.col("Term", sch_term, "categorical", levels=labels),
        }),
        *([cs.chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", {
            "x": cs.col("Predictor value", mart_x, "numeric"), "partial": cs.col("Martingale residual", mart_r, "numeric"),
            "term": cs.col("Predictor", mart_term, "categorical", levels=num_preds),
        }, controls={"smooth": True})] if num_preds else []),
        cs.chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", {
            "time": cs.col("Cox–Snell residual", np.concatenate((cox_snell[rows_cs], cs_fit)), "numeric"),
            "event": cs.col("Event", np.concatenate((ev[rows_cs].astype(float), np.full(cs_fit.size, np.nan))), "numeric"),
            "fit": cs.col("Unit exponential F(r)", np.concatenate((np.full(rows_cs.size, np.nan), -np.expm1(-cs_fit))), "numeric"),
            "family": cs.col("Series", ["data"] * rows_cs.size + ["unit exponential"] * cs_fit.size, "categorical", levels=["data", "unit exponential"]),
        }, controls={"paper": "exponential"}),
    ],
    "values": values,
})
05

Read a large p-value

Checkpoint

Check yourself

The proportional-hazards test gives p = 0.40 in a study with 40 events. What can you say?

Show the answer

Answer: b

A large p-value isn't evidence of constancy. Look at the residual plot, and think about whether the effect should be constant from the science.

06

What to do about it

Read

Choose by what you need to know:

  • Stratify on the offending categorical variable. You lose its hazard ratio, keep the others, and let it have its own baseline.
  • Model the change, with a time interaction in an extended Cox model. This is the next lesson.
  • Summarize differently, with a restricted mean difference or survival at fixed times. Both stay meaningful when hazards aren't proportional.
  • Report the average, labeled as one. It's still a valid summary of "on average over this follow-up", though it depends on the censoring pattern.

Even stratifying on cell type isn't a cure-all: with treatment, Karnofsky score and prior therapy as predictors, the test still gives p = .022.

07

Which remedy fits?

Reflect

Take a Cox model you've seen or built. If the test flagged its main variable of interest, which of these responses would you choose, and what would you report differently?

08

Same check, two dialects

Read
Python
import pandas as pd
from lifelines import CoxPHFitter
from lifelines.statistics import proportional_hazard_test

df = pd.read_csv("veteran.csv")
data = pd.get_dummies(
    df[["time", "status", "age", "celltype"]], columns=["celltype"], dtype=int
).drop(columns="celltype_squamous")
cox = CoxPHFitter().fit(data, "time", "status")
print(proportional_hazard_test(cox, data, time_transform="km").summary)
R
library(survival)
df <- read.csv("veteran.csv")
df$celltype <- relevel(factor(df$celltype), ref = "squamous")
fit <- coxph(Surv(time, status) ~ celltype + age, data = df)
zp <- cox.zph(fit)
print(zp)
plot(zp)
09

Check your understanding

Checkpoint

Check yourself

The test flags treatment, your main interest, and the curves cross. Which is the worst response?

Show the answer

Answer: c

Stratifying on treatment removes its hazard ratio from the model, and that's the quantity you care about. Stratify on nuisance variables instead.

Check yourself

With 20,000 events, the test gives p < 0.001 for age, but the residual plot looks almost flat. What's the sensible reading?

Show the answer

Answer: b

Large samples detect trivial departures. Use the plot to judge whether the change in effect is big enough to matter.

10

Recap

Recap
  • Proportional hazards means one hazard ratio fits all of follow-up.
  • Schoenfeld residuals and the Grambsch–Therneau test look for a trend over time.
  • A large p-value doesn't prove the assumption; a small one doesn't always matter.
  • Stratify on nuisance variables, model the change, or use summaries that don't need the assumption.

Concepts in this lesson