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.
What runs in CodeSplash
- STAT247Grambsch–Therneau proportional hazards test Runs in CodeSplash
- Cox proportional hazards regression Verified in Python and R
- Cox model with time-varying covariates (start–stop data) Verified in Python and R
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
What the assumption says
ReadProportional 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.
The residual that reveals it
ReadAt 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.
View data
| KM-transformed time | scaled Schoenfeld residual | term |
|---|---|---|
| 0.6900 | 0.0221 | age |
| 0.6900 | −0.9653 | treatment |
| 0.2060 | 0.1183 | age |
| 0.2060 | −1.421 | treatment |
| 0.9170 | −0.0725 | age |
| 0.9170 | 0.3364 | treatment |
| 0.5400 | −0.0791 | age |
| 0.5400 | 0.1558 | treatment |
| 0.9090 | 0.0402 | age |
| 0.9090 | 0.5365 | treatment |
| 0.6280 | −0.0106 | age |
| 0.6280 | 2.208 | treatment |
| 0.8750 | 0.0593 | age |
| 0.8750 | 0.2587 | treatment |
| 0.8030 | 0.0664 | age |
| 0.8030 | 1.709 | treatment |
| 0.7630 | 0.1597 | age |
| 0.7630 | 1.004 | treatment |
| 0.8770 | −0.0210 | age |
| 0.8770 | 0.5896 | treatment |
| 0.1830 | −0.0281 | age |
| 0.1830 | −0.5443 | treatment |
| 0.2820 | −0.0009 | age |
| 0.2820 | −1.022 | treatment |
| 0.2730 | −0.0129 | age |
| 0.2730 | 0.2795 | treatment |
| 0.9150 | 0.0624 | age |
| 0.9150 | 0.1156 | treatment |
| 0.0550 | 0.0160 | age |
| 0.0550 | −1.210 | treatment |
| 0.4850 | 0.1816 | age |
| 0.4850 | −1.663 | treatment |
| 0.9510 | 0.0084 | age |
| 0.9510 | −0.8741 | treatment |
| 0.7640 | 0.0383 | age |
| 0.7640 | 0.5828 | treatment |
| 0.7310 | −0.0139 | age |
| 0.7310 | 2.404 | treatment |
| 0.3140 | 0.0167 | age |
| 0.3140 | 0.0711 | treatment |
| 0.8550 | 0.0317 | age |
| 0.8550 | 3.604 | treatment |
| 0.6570 | 0.0093 | age |
| 0.6570 | 1.503 | treatment |
| 0.3850 | −0.0396 | age |
| 0.3850 | 1.520 | treatment |
| 0.0790 | 0.0724 | age |
| 0.0790 | 0.2498 | treatment |
| 0.0860 | 0.0772 | age |
| 0.0860 | −1.989 | treatment |
| 0.0630 | −0.0333 | age |
| 0.0630 | −0.5789 | treatment |
| 0.9740 | −0.0507 | age |
| 0.9740 | −0.0108 | treatment |
| 0.5160 | 0.0610 | age |
| 0.5160 | −0.5535 | treatment |
| 0.1740 | 0.0739 | age |
| 0.1740 | 2.675 | treatment |
| 0.3700 | −0.0606 | age |
| 0.3700 | 1.612 | treatment |
First 60 of 180 rows.
Predict the verdict
PredictPredict 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?
Reveal
Evidence against it: = 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.
Find it on the card
In the appThe 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.
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
View data
| Hazard ratio | upper | Term | lower |
|---|---|---|---|
| 2.696 | 4.435 | celltype: smallcell | 1.639 |
| 3.175 | 5.638 | celltype: adeno | 1.788 |
| 1.265 | 2.180 | celltype: large | 0.7343 |
| 1.006 | 1.025 | age | 0.9876 |
View data
| β(t) | Term | time |
|---|---|---|
| −3.499 | celltype: smallcell | 1 |
| −3.249 | celltype: smallcell | 1 |
| 1.969 | celltype: smallcell | 2 |
| 2.861 | celltype: smallcell | 3 |
| 2.072 | celltype: smallcell | 4 |
| 1.786 | celltype: smallcell | 7 |
| 1.836 | celltype: smallcell | 7 |
| 2.777 | celltype: smallcell | 7 |
| −3.416 | celltype: smallcell | 8 |
| 2.792 | celltype: smallcell | 8 |
| 1.858 | celltype: smallcell | 8 |
| 2.750 | celltype: smallcell | 8 |
| −3.278 | celltype: smallcell | 10 |
| 1.888 | celltype: smallcell | 10 |
| −3.274 | celltype: smallcell | 11 |
| 2.778 | celltype: smallcell | 12 |
| −2.193 | celltype: smallcell | 12 |
| 1.970 | celltype: smallcell | 13 |
| 1.921 | celltype: smallcell | 13 |
| −3.204 | celltype: smallcell | 15 |
| −2.134 | celltype: smallcell | 15 |
| 1.979 | celltype: smallcell | 16 |
| 2.097 | celltype: smallcell | 18 |
| 1.947 | celltype: smallcell | 18 |
| 2.747 | celltype: smallcell | 18 |
| 3.007 | celltype: smallcell | 19 |
| −1.897 | celltype: smallcell | 19 |
| 1.955 | celltype: smallcell | 20 |
| 2.047 | celltype: smallcell | 20 |
| 2.063 | celltype: smallcell | 21 |
| 1.930 | celltype: smallcell | 21 |
| 1.975 | celltype: smallcell | 22 |
| 2.157 | celltype: smallcell | 24 |
| 2.940 | celltype: smallcell | 24 |
| −3.239 | celltype: smallcell | 25 |
| 2.027 | celltype: smallcell | 25 |
| 2.018 | celltype: smallcell | 25 |
| 2.070 | celltype: smallcell | 27 |
| 2.043 | celltype: smallcell | 29 |
| 2.107 | celltype: smallcell | 30 |
| −3.225 | celltype: smallcell | 30 |
| 2.081 | celltype: smallcell | 31 |
| 3.172 | celltype: smallcell | 31 |
| −3.189 | celltype: smallcell | 33 |
| 2.995 | celltype: smallcell | 35 |
| 3.039 | celltype: smallcell | 36 |
| −3.280 | celltype: smallcell | 42 |
| −1.781 | celltype: smallcell | 43 |
| −3.236 | celltype: smallcell | 44 |
| 2.936 | celltype: smallcell | 45 |
| 2.876 | celltype: smallcell | 48 |
| −1.646 | celltype: smallcell | 49 |
| 2.168 | celltype: smallcell | 51 |
| 2.235 | celltype: smallcell | 51 |
| 3.085 | celltype: smallcell | 51 |
| 2.342 | celltype: smallcell | 52 |
| 3.317 | celltype: smallcell | 52 |
| −1.629 | celltype: smallcell | 52 |
| −1.772 | celltype: smallcell | 53 |
| 2.295 | celltype: smallcell | 54 |
First 60 of 512 rows.
View data
| Martingale residual | Predictor | Predictor value |
|---|---|---|
| 0.6453 | age | 69 |
| −1.111 | age | 64 |
| 0.0891 | age | 38 |
| 0.3827 | age | 63 |
| 0.4064 | age | 65 |
| 0.9528 | age | 49 |
| 0.6108 | age | 69 |
| 0.4796 | age | 68 |
| −0.2680 | age | 43 |
| −0.4876 | age | 70 |
| 0.7631 | age | 81 |
| 0.9607 | age | 63 |
| 0.2747 | age | 63 |
| −0.1477 | age | 52 |
| 0.9475 | age | 48 |
| 0.5304 | age | 61 |
| −3.089 | age | 42 |
| 0.9584 | age | 35 |
| 0.1893 | age | 63 |
| 0.8143 | age | 56 |
| −1.547 | age | 55 |
| −1.197 | age | 67 |
| −1.068 | age | 63 |
| 0.1296 | age | 65 |
| −0.3784 | age | 46 |
| 0.7795 | age | 53 |
| −1.083 | age | 69 |
| 0.6321 | age | 68 |
| 0.2534 | age | 43 |
| 0.6777 | age | 55 |
| 0.7725 | age | 42 |
| −0.8114 | age | 64 |
| 0.6838 | age | 65 |
| 0.4893 | age | 65 |
| 0.2896 | age | 55 |
| −2.750 | age | 66 |
| 0.7470 | age | 60 |
| 0.2928 | age | 67 |
| −0.5286 | age | 53 |
| 0.5636 | age | 62 |
| 0.1700 | age | 67 |
| 0.9268 | age | 72 |
| 0.1746 | age | 48 |
| −4.367 | age | 68 |
| 0.8586 | age | 67 |
| 0.8768 | age | 61 |
| −0.2888 | age | 60 |
| 0.3646 | age | 62 |
| −0.5481 | age | 38 |
| −0.8627 | age | 50 |
| 0.7985 | age | 63 |
| −1.636 | age | 64 |
| 0.9591 | age | 43 |
| −0.1466 | age | 34 |
| −0.1479 | age | 66 |
| −0.0385 | age | 62 |
| −0.2095 | age | 52 |
| −1.935 | age | 47 |
| −0.6009 | age | 63 |
| 0.9173 | age | 68 |
First 60 of 137 rows.
View data
| Event | Series | Unit exponential F(r) | Cox–Snell residual |
|---|---|---|---|
| 1 | data | — | 0.3547 |
| 1 | data | — | 2.111 |
| 1 | data | — | 0.9109 |
| 1 | data | — | 0.6173 |
| 1 | data | — | 0.5936 |
| 1 | data | — | 0.0472 |
| 1 | data | — | 0.3892 |
| 1 | data | — | 0.5204 |
| 1 | data | — | 1.268 |
| 0 | data | — | 0.4876 |
| 1 | data | — | 0.2369 |
| 1 | data | — | 0.0393 |
| 1 | data | — | 0.7253 |
| 0 | data | — | 0.1477 |
| 1 | data | — | 0.0525 |
| 1 | data | — | 0.4696 |
| 1 | data | — | 4.089 |
| 1 | data | — | 0.0416 |
| 1 | data | — | 0.8107 |
| 1 | data | — | 0.1857 |
| 0 | data | — | 1.547 |
| 0 | data | — | 1.197 |
| 1 | data | — | 2.068 |
| 1 | data | — | 0.8704 |
| 1 | data | — | 1.378 |
| 1 | data | — | 0.2205 |
| 1 | data | — | 2.083 |
| 1 | data | — | 0.3679 |
| 1 | data | — | 0.7466 |
| 1 | data | — | 0.3223 |
| 1 | data | — | 0.2275 |
| 1 | data | — | 1.811 |
| 1 | data | — | 0.3162 |
| 1 | data | — | 0.5107 |
| 1 | data | — | 0.7104 |
| 1 | data | — | 3.750 |
| 1 | data | — | 0.2530 |
| 1 | data | — | 0.7072 |
| 1 | data | — | 1.529 |
| 1 | data | — | 0.4364 |
| 1 | data | — | 0.8300 |
| 1 | data | — | 0.0732 |
| 1 | data | — | 0.8254 |
| 1 | data | — | 5.367 |
| 1 | data | — | 0.1414 |
| 1 | data | — | 0.1232 |
| 1 | data | — | 1.289 |
| 1 | data | — | 0.6354 |
| 1 | data | — | 1.548 |
| 1 | data | — | 1.863 |
| 1 | data | — | 0.2015 |
| 1 | data | — | 2.636 |
| 1 | data | — | 0.0409 |
| 1 | data | — | 1.147 |
| 1 | data | — | 1.148 |
| 1 | data | — | 1.038 |
| 1 | data | — | 1.209 |
| 1 | data | — | 2.935 |
| 1 | data | — | 1.601 |
| 1 | data | — | 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 | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| celltype: smallcell | 0.9919 | 0.2540 | 2.696 | 1.639 | 4.435 | 3.906 | < .001 |
| celltype: adeno | 1.155 | 0.2930 | 3.175 | 1.788 | 5.638 | 3.942 | < .001 |
| celltype: large | 0.2353 | 0.2776 | 1.265 | 0.7343 | 2.180 | 0.8477 | .397 |
| age | 0.0059 | 0.0094 | 1.006 | 0.9876 | 1.025 | 0.6305 | .528 |
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 25.252 | 4 | < .001 |
| Wald | 24.529 | 4 | < .001 |
| Score (log-rank) | 25.940 | 4 | < .001 |
Proportional-hazards test (Grambsch–Therneau)
| Term | χ² | df | p |
|---|---|---|---|
| celltype | 8.794 | 3 | .032 |
| age | 1.274 | 1 | .259 |
| Global | 10.887 | 4 | .028 |
Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6117 | 0.5515 | 0.6718 | Harrell's C on the data the model was fitted to; SE 0.0307 (infinitesimal jackknife). |
| AIC | 993.65 | — | — | −2 log partial likelihood + 2k. |
| BIC | 1005.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
| Row | Term most affected | DFBETA | DFBETAS | Martingale residual |
|---|---|---|---|---|
| 17 | age | 0.0049 | 0.5268 | −3.089 |
| 44 | celltype: smallcell | −0.1148 | −0.4520 | −4.367 |
| 58 | celltype: large | −0.0794 | −0.2862 | −1.935 |
| 78 | celltype: smallcell | 0.0705 | 0.2777 | −1.816 |
| 70 | celltype: large | 0.0747 | 0.2691 | −3.256 |
| 36 | celltype: smallcell | −0.0679 | −0.2673 | −2.750 |
| 75 | celltype: large | 0.0737 | 0.2656 | −2.181 |
| 91 | age | 0.0023 | 0.2499 | −1.104 |
| 83 | celltype: smallcell | 0.0622 | 0.2448 | −1.312 |
| 2 | celltype: smallcell | 0.0618 | 0.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
))
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 | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| celltype: smallcell | 0.9919 | 0.2540 | 2.696 | 1.639 | 4.435 | 3.906 | < .001 |
| celltype: adeno | 1.155 | 0.2930 | 3.175 | 1.788 | 5.638 | 3.942 | < .001 |
| celltype: large | 0.2353 | 0.2776 | 1.265 | 0.7343 | 2.180 | 0.8477 | .397 |
| age | 0.0059 | 0.0094 | 1.006 | 0.9876 | 1.025 | 0.6305 | .528 |
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 25.252 | 4 | < .001 |
| Wald | 24.529 | 4 | < .001 |
| Score (log-rank) | 25.940 | 4 | < .001 |
Proportional-hazards test (Grambsch–Therneau)
| Term | χ² | df | p |
|---|---|---|---|
| celltype | 8.794 | 3 | .032 |
| age | 1.274 | 1 | .259 |
| Global | 10.887 | 4 | .028 |
Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6117 | 0.5515 | 0.6718 | Harrell's C on the data the model was fitted to; SE 0.0307 (infinitesimal jackknife). |
| AIC | 993.65 | — | — | −2 log partial likelihood + 2k. |
| BIC | 1005.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
| Row | Term most affected | DFBETA | DFBETAS | Martingale residual |
|---|---|---|---|---|
| 17 | age | 0.0049 | 0.5268 | −3.089 |
| 44 | celltype: smallcell | −0.1148 | −0.4520 | −4.367 |
| 58 | celltype: large | −0.0794 | −0.2862 | −1.935 |
| 78 | celltype: smallcell | 0.0705 | 0.2777 | −1.816 |
| 70 | celltype: large | 0.0747 | 0.2691 | −3.256 |
| 36 | celltype: smallcell | −0.0679 | −0.2673 | −2.750 |
| 75 | celltype: large | 0.0737 | 0.2656 | −2.181 |
| 91 | age | 0.0023 | 0.2499 | −1.104 |
| 83 | celltype: smallcell | 0.0622 | 0.2448 | −1.312 |
| 2 | celltype: smallcell | 0.0618 | 0.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,
})
Read a large p-value
CheckpointCheck 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.
What to do about it
ReadChoose 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.
Which remedy fits?
ReflectTake 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?
Same check, two dialects
Readimport 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)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)Check your understanding
CheckpointCheck 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.
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