Time-varying covariates and immortal time
A patient who waits months for a transplant had to survive those months first. Set up start–stop data so that survival isn't credited to the treatment.
What runs in CodeSplash
- Cox model with time-varying covariates (start–stop data) Verified in Python and R
You will be able to
- Explain immortal time bias with a concrete example
- Lay out counting-process data with one row per interval
- Distinguish a covariate that changes over time from an effect that changes over time
The transplant that looks like a miracle
ReadThe Stanford heart program followed patients from acceptance. Some received a transplant, often months later. Others died waiting.
Sort everyone into "ever transplanted" and "never", then compare survival. The transplanted patients seem to do far better. But they could only be transplanted by staying alive long enough to get a heart. Those waiting months were guaranteed survivors in the "transplant" column.
This is immortal time biasImmortal time biasCounting time before a treatment started as treated time, when patients had to survive that time to receive it..
Predict what the fix does
PredictPredict first
Now count each patient's time correctly: everyone starts as "not transplanted" and switches only on the day of surgery.
What happens to the hazard ratio for transplant?
Reveal
The benefit shrinks a lot. Compared naively the hazard ratio is about a quarter; counted correctly it sits near 1, with a wide interval. Run both versions in the code below. These data are compatible with a real benefit or none: they don't show that transplant does nothing, only that the naive comparison can't be trusted.
One row per interval
In the appThe fix uses time-varying covariatesTime-varying covariateA predictor whose value changes during follow-up, entered as one row per interval with start and stop times. and counting-process data: one row for each stretch when a patient's covariates were constant.
| id | start | stop | event | transplant |
|---|---|---|---|---|
| 7 | 0 | 50 | no | no |
| 7 | 50 | 200 | yes | yes |
In CodeSplash these are the Interval start and Interval stop roles of the extended Cox method. Fill Subject id too, so standard errors account for one patient's several rows.
HR = 1.03, 95% CI [1.00, 1.06], p = .033
- Likelihood-ratio χ²
- 10.719
- df
- 3
- p
- .013
- Events
- 75
Effect size
- Hazard ratio (age) 1.031 95% CI [1.002, 1.060]
Plots
View data
| Hazard ratio | upper | Term | lower |
|---|---|---|---|
| 1.031 | 1.060 | age | 1.002 |
| 0.4615 | 0.8868 | surgery: true | 0.2402 |
| 1.016 | 1.863 | transplant: true | 0.5542 |
Assumptions
- Events per variable — 25.0 events per coefficient.
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative censoring and entry — 97 of 172 intervals end without the event; 0 subjects enter after time 0 (delayed entry is handled by the risk sets).
Hazard ratios
| Term | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | 0.0305 | 0.0143 | 1.031 | 1.002 | 1.060 | 2.131 | .033 |
| surgery: true | −0.7733 | 0.3332 | 0.4615 | 0.2402 | 0.8868 | −2.321 | .020 |
| transplant: true | 0.0161 | 0.3093 | 1.016 | 0.5542 | 1.863 | 0.0520 | .958 |
Standard errors: robust (clustered by subject).
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 10.719 | 3 | .013 |
| Wald (robust) | 10.804 | 3 | .013 |
| Score | 10.002 | 3 | .019 |
- Event: event = 1. Ties: efron.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cox model with time-varying covariates (start–stop data)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox_tv 1.0.1 · spec 876c06fff1bf27f1
# Dataset: s2_heart (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/s2_heart.parquet", col_select = c("start", "stop", "event", "age", "surgery", "transplant", "id")))
n_input <- nrow(df)
df[["surgery"]] <- factor(df[["surgery"]], levels = c("false", "true")) # stored level order
df[["transplant"]] <- factor(df[["transplant"]], levels = c("false", "true")) # stored level order
df[["id"]] <- factor(df[["id"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103")) # stored level order
df <- df[stats::complete.cases(df[c("start", "stop", "event", "age", "surgery", "transplant", "id")]), , 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("start", "stop", "event", "age", "surgery", "transplant", "id")) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol <- "start"
tcol <- "stop"
ecol <- "event"
t0 <- as.numeric(df[[scol]])
t1 <- as.numeric(df[[tcol]])
bad_rows <- sum(t1 <= t0)
if (bad_rows > 0) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = sprintf("later than %s on every row", scol), count = bad_rows)
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 (time-varying-effect columns are also main effects)
preds <- c("age", "surgery", "transplant")
tv <- c()
preds <- c(preds, setdiff(tv, preds))
dd <- data.frame(.start = t0, .stop = t1, .e = ev)
# %% Predictors `preds` (treatment contrasts against the first stored level) into `dd`
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 <- if (length(preds)) paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ") else "1"
as_number <- function(x) if (is.factor(x)) as.numeric(as.character(x) == "true") else as.numeric(x) # yes/no columns
conf <- 0.95
ties <- "efron" # pinned: coxph's default is Efron, SAS/Stata use Breslow
tt_function <- "log"
idcol <- "id"
ids <- as.character(df[[idcol]])
dd$.id <- ids
n_subjects <- length(unique(ids))
robust <- TRUE
o <- order(ids, t0, method = "radix")
same <- ids[o][-1] == ids[o][-length(o)]
n_overlap <- sum(same & (t0[o][-1] < t1[o][-length(o)]))
first <- c(TRUE, !same)
n_delayed <- sum(t0[o][first] > 0)
sname <- NULL
# %% Time-varying effects: coxph's tt() evaluates x × g(t) at every event time
tt_names <- character(0)
for (i in seq_along(tv)) {
nm <- sprintf(".tt%d", i)
dd[[nm]] <- as_number(df[[tv[i]]])
tt_names <- c(tt_names, nm)
}
if (length(tv)) {
rhs <- paste(rhs, "+", paste(sprintf("tt(%s)", tt_names), collapse = " + "))
labels <- c(labels, sprintf("%s × %s", tv, if (tt_function == "log") "log(t)" else "t"))
if (tt_function == "log" && min(t1[ev]) <= 0) stop("log(t) needs event times above zero; choose g(t) = t")
}
tt_fun <- if (tt_function == "log") function(x, t, ...) x * log(t) else function(x, t, ...) x * t
# %% Cox model
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
form <- stats::as.formula(paste("Surv(.start, .stop, .e) ~", rhs))
fit <- if (robust) coxph(form, data = dd, ties = ties, tt = tt_fun, cluster = .id, control = ctl) else
coxph(form, data = dd, ties = ties, tt = tt_fun, control = ctl)
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(fit$var)
naive_se <- sqrt(diag(if (robust) unname(fit$naive.var) else V))
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)
se_type <- if (robust) "robust (clustered by subject)" else "model-based"
values <- list(
n_rows = length(t1), n_subjects = n_subjects, n_delayed = n_delayed, events = sum(ev), n_coef = k, n_tt = length(tv),
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),
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, se_type = se_type, event_label = event_label
)
coef_rows <- list()
for (i in seq_along(labels)) {
lab <- labels[i]
vals <- list(coef = beta[i], se = se[i], naive_se = naive_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]]
coef_rows[[i]] <- c(list(term = lab), vals[c("coef", "se", "hr", "hr_low", "hr_high", "z", "p")])
}
# %% Assumptions
epv <- values$epv
assumptions <- list(
list(key = "events_per_variable", label = "Events per variable", status = if (epv < 10) "warn" else "pass",
detail = paste0(sprintf("%.1f events per coefficient", epv), if (epv < 10) " — fewer than 10; estimates may be biased and unstable." else ".")),
list(key = "intervals", label = "Non-overlapping intervals",
status = if (n_overlap > 0) "fail" else if (TRUE) "pass" else "info",
detail = if (n_overlap > 0) sprintf("%d intervals overlap the subject's previous interval — fix the data before interpreting the model.", n_overlap)
else if (TRUE) "Intervals of each subject do not overlap."
else "Without a subject id the intervals cannot be checked per subject."),
list(key = "censoring", label = "Non-informative censoring and entry", status = "info",
detail = sprintf("%d of %d intervals end without the event; %d subjects enter after time 0 (delayed entry is handled by the risk sets).",
sum(!ev), length(ev), n_delayed))
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
method = "survival.cox_tv",
methodVersion = "1.0.1",
title = "Cox model with time-varying covariates",
engine = cs_engine_info("survival", "codesplashr"),
n = n_subjects,
summary = sprintf("Cox model for start–stop data (%d events, %d intervals): likelihood-ratio χ²(%d) = %.2f, %s.", sum(ev), length(t1), k, lr, cs_fmt_p(lr_p)),
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 = "events", label = "Events", value = sum(ev), format = "integer")
),
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, note = sprintf("Standard errors: %s.", se_type)),
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 = if (robust) "Wald (robust)" else "Wald", chisq = wald, df = k, p = values$wald_p),
list(test = "Score", chisq = score, df = k, p = values$score_p)
))
),
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 = sprintf("Wald interval on log(HR), %s SE", se_type))),
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 "",
if (length(tv)) sprintf(" Time-varying effects: %s × %s.", paste(tv, collapse = ", "), if (tt_function == "log") "log(t)" else "t") 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))
),
values = values
))
HR = 1.03, 95% CI [1.00, 1.06], p = .033
- Likelihood-ratio χ²
- 10.719
- df
- 3
- p
- .013
- Events
- 75
Effect size
- Hazard ratio (age) 1.031 95% CI [1.002, 1.060]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Events per variable — 25.0 events per coefficient.
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative censoring and entry — 97 of 172 intervals end without the event; 0 subjects enter after time 0 (delayed entry is handled by the risk sets).
Hazard ratios
| Term | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | 0.0305 | 0.0143 | 1.031 | 1.002 | 1.060 | 2.131 | .033 |
| surgery: true | −0.7733 | 0.3332 | 0.4615 | 0.2402 | 0.8868 | −2.321 | .020 |
| transplant: true | 0.0161 | 0.3093 | 1.016 | 0.5542 | 1.863 | 0.0520 | .958 |
Standard errors: robust (clustered by subject).
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 10.719 | 3 | .013 |
| Wald (robust) | 10.804 | 3 | .013 |
| Score | 10.002 | 3 | .019 |
- Event: event = 1. Ties: efron.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cox model with time-varying covariates (start–stop data)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox_tv 1.0.1 · spec 876c06fff1bf27f1
# Dataset: s2_heart (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_adv as sa # coxph for (start, stop] data: Efron/Breslow, strata, robust SEs
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s2_heart.parquet", columns=["start", "stop", "event", "age", "surgery", "transplant", "id"])
n_input = len(df)
df["surgery"] = pd.Categorical(df["surgery"], categories=["false", "true"]) # stored level order
df["transplant"] = pd.Categorical(df["transplant"], categories=["false", "true"]) # stored level order
df["id"] = pd.Categorical(df["id"], categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103"]) # stored level order
df = df.dropna(subset=["start", "stop", "event", "age", "surgery", "transplant", "id"]) # listwise deletion over the analysis columns
df["surgery"] = df["surgery"].cat.remove_unused_categories()
df["transplant"] = df["transplant"].cat.remove_unused_categories()
df["id"] = df["id"].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, ["start", "stop", "event", "age", "surgery", "transplant", "id"]) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol = "start"
tcol = "stop"
ecol = "event"
t0 = df[scol].to_numpy(dtype=float)
t1 = df[tcol].to_numpy(dtype=float)
bad_rows = int(np.sum(t1 <= t0))
if bad_rows:
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement=f"later than {scol} on every row", count=bad_rows)
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)
# %% Predictors (time-varying-effect columns are also main effects)
preds = ["age", "surgery", "transplant"]
tv = []
for c in tv:
if c not in preds:
preds.append(c)
# %% Design matrix for `preds` (treatment contrasts against the first stored level)
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) if cols else np.zeros((len(df), 0))
def as_number(name):
s = df[name]
if isinstance(s.dtype, pd.CategoricalDtype): # yes/no columns
return (s.astype(str) == "true").to_numpy(dtype=float)
return s.to_numpy(dtype=float)
conf = 0.95
ties = "efron" # pinned: coxph's default is Efron, SAS/Stata use Breslow
tt_function = "log"
idcol = "id"
ids = df[idcol].astype(str).to_numpy()
n_subjects = len(np.unique(ids))
robust = True
# overlapping intervals within a subject and late entry (first start > 0)
order = np.lexsort((t0, ids))
same = ids[order][1:] == ids[order][:-1]
n_overlap = int(np.sum(same & (t0[order][1:] < t1[order][:-1])))
first = np.r_[True, ~same]
n_delayed = int(np.sum(t0[order][first] > 0))
sname = None
scodes = None
# %% Time-varying effects: split the intervals at every event time and add x × g(t) (coxph's tt())
start, stop, event, Xf, rows = t0, t1, ev, X, np.arange(len(t1))
if tv:
cuts = np.unique(t1[ev])
if tt_function == "log" and cuts.min() <= 0:
raise ValueError("log(t) needs event times above zero; choose g(t) = t")
sp = sa.split_at(t0, t1, ev, cuts)
rows = sp["row"]
g_t = np.log(sp["stop"]) if tt_function == "log" else sp["stop"]
Xf = np.column_stack([X[rows]] + [as_number(c)[rows] * g_t for c in tv])
start, stop, event = sp["start"], sp["stop"], sp["event"]
labels = labels + [f"{c} × {'log(t)' if tt_function == 'log' else 't'}" for c in tv]
# %% Cox model
fit = sa.cox_cp(start, stop, event, Xf, strata=None if scodes is None else scodes[rows], ties=ties,
cluster=ids[rows] if robust else None)
beta = fit["coef"]
naive_se = np.sqrt(np.diag(fit["cov"]))
V = fit["rcov"] if robust else fit["cov"]
se = np.sqrt(np.diag(V))
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))
wald = float(beta @ np.linalg.solve(V, beta))
se_type = "robust (clustered by subject)" if robust else "model-based"
values = {
"n_rows": float(len(t1)), "n_subjects": float(n_subjects), "n_delayed": float(n_delayed), "events": float(ev.sum()),
"n_coef": float(k), "n_tt": float(len(tv)), "loglik": fit["loglik"], "loglik0": fit["loglik0"],
"lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": lr_p, "wald_chisq": wald, "wald_p": float(stats.chi2.sf(wald, k)),
"score_chisq": fit["score"], "score_p": float(stats.chi2.sf(fit["score"], k)),
"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, "se_type": se_type, "event_label": event_label,
}
coef_rows = []
for i, lab in enumerate(labels):
for key, val in (("coef", beta[i]), ("se", se[i]), ("naive_se", naive_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)
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])})
# %% Assumptions
epv = values["epv"]
assumptions = [
{"key": "events_per_variable", "label": "Events per variable", "status": "warn" if epv < 10 else "pass",
"detail": f"{epv:.1f} events per coefficient" + (" — fewer than 10; estimates may be biased and unstable." if epv < 10 else ".")},
{"key": "intervals", "label": "Non-overlapping intervals", "status": "fail" if n_overlap else ("pass" if ids is not None else "info"),
"detail": (f"{n_overlap} intervals overlap the subject's previous interval — fix the data before interpreting the model." if n_overlap
else "Intervals of each subject do not overlap." if ids is not None else "Without a subject id the intervals cannot be checked per subject.")},
{"key": "censoring", "label": "Non-informative censoring and entry", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} intervals end without the event; {n_delayed} subjects enter after time 0 (delayed entry is handled by the risk sets)."},
]
# %% Result
pct = f"{conf:.0%}"
cs.publish({
"method": "survival.cox_tv",
"methodVersion": "1.0.1",
"title": "Cox model with time-varying covariates",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n_subjects),
"summary": f"Cox model for start–stop data ({int(ev.sum())} events, {len(t1)} intervals): likelihood-ratio χ²({k}) = {fit['lr']:.2f}, {cs.fmt_p(lr_p)}.",
"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": "events", "label": "Events", "value": float(ev.sum()), "format": "integer"},
],
"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, "note": f"Standard errors: {se_type}."},
{"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" + (" (robust)" if robust else ""), "chisq": wald, "df": float(k), "p": values["wald_p"]},
{"test": "Score", "chisq": fit["score"], "df": float(k), "p": values["score_p"]},
]},
],
"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": f"Wald interval on log(HR), {se_type} SE"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Ties: {ties}." + (f" Stratified by {sname}." if sname else "")
+ (f" Time-varying effects: {', '.join(tv)} × {'log(t)' if tt_function == 'log' else 't'}." if tv 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}),
],
"values": values,
})
The card reports 172 rows for 103 patients, with robust (clustered by subject) standard errors.
See both versions
Readimport pandas as pd
from lifelines import CoxPHFitter, CoxTimeVaryingFitter
h = pd.read_csv("s2_heart.csv")
h["tx"] = (h["transplant"] == True).astype(int)
# Wrong: "ever transplanted", timed from acceptance
last = h.groupby("id").agg(stop=("stop", "max"), event=("event", "max"), tx=("tx", "max"))
naive = CoxPHFitter().fit(last, "stop", "event")
print("naive", naive.hazard_ratios_["tx"])
# Right: switches on the day of surgery
tv = CoxTimeVaryingFitter().fit(
h[["id", "start", "stop", "event", "tx"]],
id_col="id", start_col="start", stop_col="stop", event_col="event",
)
print("time-varying", tv.hazard_ratios_["tx"])library(survival)
h <- read.csv("s2_heart.csv")
h$tx <- h$transplant == "true" | h$transplant == TRUE
# Wrong: "ever transplanted", timed from acceptance
last <- merge(
aggregate(cbind(stop, event) ~ id, h, max),
aggregate(tx ~ id, h, any)
)
exp(coef(coxph(Surv(stop, event) ~ tx, data = last)))
# Right: switches on the day of surgery
exp(coef(coxph(Surv(start, stop, event) ~ tx, data = h)))Covariate or effect?
In the appTwo things can vary over time, and they need different tools:
- A covariate changes: a blood pressure measured at each visit, a treatment that starts midway. Use start–stop rows.
- An effect changes: the hazard ratio for a fixed covariate drifts over follow-up. Use the Time-varying effects role, which adds an interaction with a function of time.
Here transplant's own effect is allowed to change with time (linearly, using the identity function):
HR = 1.03, 95% CI [1.00, 1.06], p = .044
- Likelihood-ratio χ²
- 5.189
- df
- 3
- p
- .158
- Events
- 75
Effect size
- Hazard ratio (age) 1.031 95% CI [1.001, 1.062]
Plots
View data
| Hazard ratio | upper | Term | lower |
|---|---|---|---|
| 1.031 | 1.062 | age | 1.001 |
| 0.9736 | 1.900 | transplant: true | 0.4989 |
| 1.000 | 1.003 | transplant × t | 0.9977 |
Assumptions
- Events per variable — 25.0 events per coefficient.
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative censoring and entry — 97 of 172 intervals end without the event; 0 subjects enter after time 0 (delayed entry is handled by the risk sets).
Hazard ratios
| Term | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | 0.0305 | 0.0151 | 1.031 | 1.001 | 1.062 | 2.018 | .044 |
| transplant: true | −0.0267 | 0.3411 | 0.9736 | 0.4989 | 1.900 | −0.0783 | .938 |
| transplant × t | 0.0002 | 0.0013 | 1.000 | 0.9977 | 1.003 | 0.1737 | .862 |
Standard errors: robust (clustered by subject).
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 5.189 | 3 | .158 |
| Wald (robust) | 4.178 | 3 | .243 |
| Score | 4.657 | 3 | .199 |
- Event: event = 1. Ties: efron. Time-varying effects: transplant × t.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cox model with time-varying covariates (start–stop data)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox_tv 1.0.1 · spec e1ee4acd356737cd
# Dataset: s2_heart (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/s2_heart.parquet", col_select = c("start", "stop", "event", "age", "transplant", "id")))
n_input <- nrow(df)
df[["transplant"]] <- factor(df[["transplant"]], levels = c("false", "true")) # stored level order
df[["id"]] <- factor(df[["id"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103")) # stored level order
df <- df[stats::complete.cases(df[c("start", "stop", "event", "age", "transplant", "id")]), , 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("start", "stop", "event", "age", "transplant", "id")) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol <- "start"
tcol <- "stop"
ecol <- "event"
t0 <- as.numeric(df[[scol]])
t1 <- as.numeric(df[[tcol]])
bad_rows <- sum(t1 <= t0)
if (bad_rows > 0) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = sprintf("later than %s on every row", scol), count = bad_rows)
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 (time-varying-effect columns are also main effects)
preds <- c("age", "transplant")
tv <- c("transplant")
preds <- c(preds, setdiff(tv, preds))
dd <- data.frame(.start = t0, .stop = t1, .e = ev)
# %% Predictors `preds` (treatment contrasts against the first stored level) into `dd`
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 <- if (length(preds)) paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ") else "1"
as_number <- function(x) if (is.factor(x)) as.numeric(as.character(x) == "true") else as.numeric(x) # yes/no columns
conf <- 0.95
ties <- "efron" # pinned: coxph's default is Efron, SAS/Stata use Breslow
tt_function <- "identity"
idcol <- "id"
ids <- as.character(df[[idcol]])
dd$.id <- ids
n_subjects <- length(unique(ids))
robust <- TRUE
o <- order(ids, t0, method = "radix")
same <- ids[o][-1] == ids[o][-length(o)]
n_overlap <- sum(same & (t0[o][-1] < t1[o][-length(o)]))
first <- c(TRUE, !same)
n_delayed <- sum(t0[o][first] > 0)
sname <- NULL
# %% Time-varying effects: coxph's tt() evaluates x × g(t) at every event time
tt_names <- character(0)
for (i in seq_along(tv)) {
nm <- sprintf(".tt%d", i)
dd[[nm]] <- as_number(df[[tv[i]]])
tt_names <- c(tt_names, nm)
}
if (length(tv)) {
rhs <- paste(rhs, "+", paste(sprintf("tt(%s)", tt_names), collapse = " + "))
labels <- c(labels, sprintf("%s × %s", tv, if (tt_function == "log") "log(t)" else "t"))
if (tt_function == "log" && min(t1[ev]) <= 0) stop("log(t) needs event times above zero; choose g(t) = t")
}
tt_fun <- if (tt_function == "log") function(x, t, ...) x * log(t) else function(x, t, ...) x * t
# %% Cox model
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
form <- stats::as.formula(paste("Surv(.start, .stop, .e) ~", rhs))
fit <- if (robust) coxph(form, data = dd, ties = ties, tt = tt_fun, cluster = .id, control = ctl) else
coxph(form, data = dd, ties = ties, tt = tt_fun, control = ctl)
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(fit$var)
naive_se <- sqrt(diag(if (robust) unname(fit$naive.var) else V))
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)
se_type <- if (robust) "robust (clustered by subject)" else "model-based"
values <- list(
n_rows = length(t1), n_subjects = n_subjects, n_delayed = n_delayed, events = sum(ev), n_coef = k, n_tt = length(tv),
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),
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, se_type = se_type, event_label = event_label
)
coef_rows <- list()
for (i in seq_along(labels)) {
lab <- labels[i]
vals <- list(coef = beta[i], se = se[i], naive_se = naive_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]]
coef_rows[[i]] <- c(list(term = lab), vals[c("coef", "se", "hr", "hr_low", "hr_high", "z", "p")])
}
# %% Assumptions
epv <- values$epv
assumptions <- list(
list(key = "events_per_variable", label = "Events per variable", status = if (epv < 10) "warn" else "pass",
detail = paste0(sprintf("%.1f events per coefficient", epv), if (epv < 10) " — fewer than 10; estimates may be biased and unstable." else ".")),
list(key = "intervals", label = "Non-overlapping intervals",
status = if (n_overlap > 0) "fail" else if (TRUE) "pass" else "info",
detail = if (n_overlap > 0) sprintf("%d intervals overlap the subject's previous interval — fix the data before interpreting the model.", n_overlap)
else if (TRUE) "Intervals of each subject do not overlap."
else "Without a subject id the intervals cannot be checked per subject."),
list(key = "censoring", label = "Non-informative censoring and entry", status = "info",
detail = sprintf("%d of %d intervals end without the event; %d subjects enter after time 0 (delayed entry is handled by the risk sets).",
sum(!ev), length(ev), n_delayed))
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
method = "survival.cox_tv",
methodVersion = "1.0.1",
title = "Cox model with time-varying covariates",
engine = cs_engine_info("survival", "codesplashr"),
n = n_subjects,
summary = sprintf("Cox model for start–stop data (%d events, %d intervals): likelihood-ratio χ²(%d) = %.2f, %s.", sum(ev), length(t1), k, lr, cs_fmt_p(lr_p)),
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 = "events", label = "Events", value = sum(ev), format = "integer")
),
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, note = sprintf("Standard errors: %s.", se_type)),
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 = if (robust) "Wald (robust)" else "Wald", chisq = wald, df = k, p = values$wald_p),
list(test = "Score", chisq = score, df = k, p = values$score_p)
))
),
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 = sprintf("Wald interval on log(HR), %s SE", se_type))),
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 "",
if (length(tv)) sprintf(" Time-varying effects: %s × %s.", paste(tv, collapse = ", "), if (tt_function == "log") "log(t)" else "t") 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))
),
values = values
))
HR = 1.03, 95% CI [1.00, 1.06], p = .044
- Likelihood-ratio χ²
- 5.189
- df
- 3
- p
- .158
- Events
- 75
Effect size
- Hazard ratio (age) 1.031 95% CI [1.001, 1.062]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Events per variable — 25.0 events per coefficient.
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative censoring and entry — 97 of 172 intervals end without the event; 0 subjects enter after time 0 (delayed entry is handled by the risk sets).
Hazard ratios
| Term | β | SE | HR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | 0.0305 | 0.0151 | 1.031 | 1.001 | 1.062 | 2.018 | .044 |
| transplant: true | −0.0267 | 0.3411 | 0.9736 | 0.4989 | 1.900 | −0.0783 | .938 |
| transplant × t | 0.0002 | 0.0013 | 1.000 | 0.9977 | 1.003 | 0.1737 | .862 |
Standard errors: robust (clustered by subject).
Overall tests
| Test | χ² | df | p |
|---|---|---|---|
| Likelihood ratio | 5.189 | 3 | .158 |
| Wald (robust) | 4.178 | 3 | .243 |
| Score | 4.657 | 3 | .199 |
- Event: event = 1. Ties: efron. Time-varying effects: transplant × t.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cox model with time-varying covariates (start–stop data)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox_tv 1.0.1 · spec e1ee4acd356737cd
# Dataset: s2_heart (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_adv as sa # coxph for (start, stop] data: Efron/Breslow, strata, robust SEs
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s2_heart.parquet", columns=["start", "stop", "event", "age", "transplant", "id"])
n_input = len(df)
df["transplant"] = pd.Categorical(df["transplant"], categories=["false", "true"]) # stored level order
df["id"] = pd.Categorical(df["id"], categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103"]) # stored level order
df = df.dropna(subset=["start", "stop", "event", "age", "transplant", "id"]) # listwise deletion over the analysis columns
df["transplant"] = df["transplant"].cat.remove_unused_categories()
df["id"] = df["id"].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, ["start", "stop", "event", "age", "transplant", "id"]) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol = "start"
tcol = "stop"
ecol = "event"
t0 = df[scol].to_numpy(dtype=float)
t1 = df[tcol].to_numpy(dtype=float)
bad_rows = int(np.sum(t1 <= t0))
if bad_rows:
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement=f"later than {scol} on every row", count=bad_rows)
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)
# %% Predictors (time-varying-effect columns are also main effects)
preds = ["age", "transplant"]
tv = ["transplant"]
for c in tv:
if c not in preds:
preds.append(c)
# %% Design matrix for `preds` (treatment contrasts against the first stored level)
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) if cols else np.zeros((len(df), 0))
def as_number(name):
s = df[name]
if isinstance(s.dtype, pd.CategoricalDtype): # yes/no columns
return (s.astype(str) == "true").to_numpy(dtype=float)
return s.to_numpy(dtype=float)
conf = 0.95
ties = "efron" # pinned: coxph's default is Efron, SAS/Stata use Breslow
tt_function = "identity"
idcol = "id"
ids = df[idcol].astype(str).to_numpy()
n_subjects = len(np.unique(ids))
robust = True
# overlapping intervals within a subject and late entry (first start > 0)
order = np.lexsort((t0, ids))
same = ids[order][1:] == ids[order][:-1]
n_overlap = int(np.sum(same & (t0[order][1:] < t1[order][:-1])))
first = np.r_[True, ~same]
n_delayed = int(np.sum(t0[order][first] > 0))
sname = None
scodes = None
# %% Time-varying effects: split the intervals at every event time and add x × g(t) (coxph's tt())
start, stop, event, Xf, rows = t0, t1, ev, X, np.arange(len(t1))
if tv:
cuts = np.unique(t1[ev])
if tt_function == "log" and cuts.min() <= 0:
raise ValueError("log(t) needs event times above zero; choose g(t) = t")
sp = sa.split_at(t0, t1, ev, cuts)
rows = sp["row"]
g_t = np.log(sp["stop"]) if tt_function == "log" else sp["stop"]
Xf = np.column_stack([X[rows]] + [as_number(c)[rows] * g_t for c in tv])
start, stop, event = sp["start"], sp["stop"], sp["event"]
labels = labels + [f"{c} × {'log(t)' if tt_function == 'log' else 't'}" for c in tv]
# %% Cox model
fit = sa.cox_cp(start, stop, event, Xf, strata=None if scodes is None else scodes[rows], ties=ties,
cluster=ids[rows] if robust else None)
beta = fit["coef"]
naive_se = np.sqrt(np.diag(fit["cov"]))
V = fit["rcov"] if robust else fit["cov"]
se = np.sqrt(np.diag(V))
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))
wald = float(beta @ np.linalg.solve(V, beta))
se_type = "robust (clustered by subject)" if robust else "model-based"
values = {
"n_rows": float(len(t1)), "n_subjects": float(n_subjects), "n_delayed": float(n_delayed), "events": float(ev.sum()),
"n_coef": float(k), "n_tt": float(len(tv)), "loglik": fit["loglik"], "loglik0": fit["loglik0"],
"lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": lr_p, "wald_chisq": wald, "wald_p": float(stats.chi2.sf(wald, k)),
"score_chisq": fit["score"], "score_p": float(stats.chi2.sf(fit["score"], k)),
"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, "se_type": se_type, "event_label": event_label,
}
coef_rows = []
for i, lab in enumerate(labels):
for key, val in (("coef", beta[i]), ("se", se[i]), ("naive_se", naive_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)
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])})
# %% Assumptions
epv = values["epv"]
assumptions = [
{"key": "events_per_variable", "label": "Events per variable", "status": "warn" if epv < 10 else "pass",
"detail": f"{epv:.1f} events per coefficient" + (" — fewer than 10; estimates may be biased and unstable." if epv < 10 else ".")},
{"key": "intervals", "label": "Non-overlapping intervals", "status": "fail" if n_overlap else ("pass" if ids is not None else "info"),
"detail": (f"{n_overlap} intervals overlap the subject's previous interval — fix the data before interpreting the model." if n_overlap
else "Intervals of each subject do not overlap." if ids is not None else "Without a subject id the intervals cannot be checked per subject.")},
{"key": "censoring", "label": "Non-informative censoring and entry", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} intervals end without the event; {n_delayed} subjects enter after time 0 (delayed entry is handled by the risk sets)."},
]
# %% Result
pct = f"{conf:.0%}"
cs.publish({
"method": "survival.cox_tv",
"methodVersion": "1.0.1",
"title": "Cox model with time-varying covariates",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n_subjects),
"summary": f"Cox model for start–stop data ({int(ev.sum())} events, {len(t1)} intervals): likelihood-ratio χ²({k}) = {fit['lr']:.2f}, {cs.fmt_p(lr_p)}.",
"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": "events", "label": "Events", "value": float(ev.sum()), "format": "integer"},
],
"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, "note": f"Standard errors: {se_type}."},
{"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" + (" (robust)" if robust else ""), "chisq": wald, "df": float(k), "p": values["wald_p"]},
{"test": "Score", "chisq": fit["score"], "df": float(k), "p": values["score_p"]},
]},
],
"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": f"Wald interval on log(HR), {se_type} SE"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Ties: {ties}." + (f" Stratified by {sname}." if sname else "")
+ (f" Time-varying effects: {', '.join(tv)} × {'log(t)' if tt_function == 'log' else 't'}." if tv 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}),
],
"values": values,
})
Check your understanding
CheckpointCheck yourself
A study compares people who started a drug at some point in the first year with people who never did, timing everyone from diagnosis. Why might the drug look better than it is?
Show the answer
Answer: b
The time before starting is "immortal" for the drug group. Count it as unexposed time using a time-varying covariate, or use a landmark analysis.
Check yourself
A patient joins at day 0, starts treatment on day 30 and dies on day 90. Put the correct rows in order.
Show the answer
The order:
- start 0, stop 30, event no, treated no
- start 30, stop 90, event yes, treated yes
Each row covers one stretch with constant covariates. Only the last row carries the event.
Check yourself
A treatment's benefit is thought to fade over two years. Every patient's treatment arm is fixed at randomization. Which tool fits?
Show the answer
Answer: b
The covariate never changes here; its effect does.
Recap
Recap- Classifying people by something that happens after time zero gives them immortal time.
- Use start–stop rows so people switch group at the moment they switch.
- Time-varying covariates and time-varying effects are different things.
- Beware covariates that respond to the outcome.
Concepts in this lesson