Recurrent events and interval-censored data
Infections repeat and scans only happen at visits. Choose among Andersen–Gill, PWP and WLW for repeated events, and use Turnbull's estimate when you only know an interval.
What runs in CodeSplash
- Recurrent events (mean cumulative function, Andersen–Gill, PWP, WLW) Verified in Python and R
- Interval-censored survival (Turnbull estimate and parametric models) Verified in Python and R
You will be able to
- Choose among Andersen–Gill, PWP and WLW for a recurrent-event question
- Read a mean cumulative function
- Set up and read an interval-censored survival analysis
Events that happen again
ReadIn a trial of interferon for chronic granulomatous disease, children could have several serious infections. The first event isn't the whole story: 128 children had 76 infections, up to 7 per child.
The mean cumulative functionMean cumulative functionThe expected number of events per subject by time t, for events that can happen repeatedly. is the first thing to look at: the expected number of events per subject by time . It can pass 1, because it counts events rather than people.
Three models, three questions
Read| Model | Treats each event as | Answers |
|---|---|---|
| Andersen–Gill | One ongoing rate | Does treatment lower the overall rate? |
| PWP (total or gap time) | Conditional on the event before | Does it delay the next event, given the last? |
| WLW | A separate marginal outcome | What is its effect on the 1st, 2nd… event? |
All need start–stop rows. Robust (clustered) standard errors account for repeat events in the same person.
Predict the difference
PredictPredict first
Interferon's effect on infections is modeled twice. Andersen–Gill uses all events as one rate. PWP total-time asks about each next event, within its own stratum.
Do you expect the two to agree?
Reveal
They differ. Andersen–Gill gives a hazard ratio of 0.33, and PWP gives 0.42 (with other covariates differing too). Both show fewer infections on interferon. They're estimating different things, so choose before you see the results.
Run it
In the appRR = 0.33, 95% CI [0.18, 0.60], p < .001
- Events
- 76
- Events per subject
- 0.5938
- Robust Wald χ²
- 16.620
- p
- < .001
Effect size
- Rate ratio (treat: rIFN-g) 0.3263 95% CI [0.1777, 0.5989]
Plots
View data
| treat | upper | lower | Mean events per subject | tstop |
|---|---|---|---|---|
| placebo | 0 | 0 | 0 | 0 |
| placebo | 0.0453 | −0.0145 | 0.0154 | 4 |
| placebo | 0.0728 | −0.0112 | 0.0308 | 6 |
| placebo | 0.0972 | −0.0049 | 0.0462 | 8 |
| placebo | 0.1200 | 0.0031 | 0.0615 | 11 |
| placebo | 0.1417 | 0.0121 | 0.0769 | 14 |
| placebo | 0.1627 | 0.0219 | 0.0923 | 18 |
| placebo | 0.1831 | 0.0323 | 0.1077 | 19 |
| placebo | 0.2136 | 0.0325 | 0.1231 | 22 |
| placebo | 0.2326 | 0.0443 | 0.1385 | 23 |
| placebo | 0.2603 | 0.0474 | 0.1538 | 26 |
| placebo | 0.2785 | 0.0599 | 0.1692 | 52 |
| placebo | 0.2966 | 0.0727 | 0.1846 | 57 |
| placebo | 0.3221 | 0.0779 | 0.2000 | 65 |
| placebo | 0.3397 | 0.0911 | 0.2154 | 67 |
| placebo | 0.3570 | 0.1045 | 0.2308 | 91 |
| placebo | 0.3749 | 0.1184 | 0.2466 | 99 |
| placebo | 0.3749 | 0.1184 | 0.2466 | 102 |
| placebo | 0.3931 | 0.1325 | 0.2628 | 104 |
| placebo | 0.4110 | 0.1468 | 0.2789 | 120 |
| placebo | 0.4600 | 0.1623 | 0.3112 | 121 |
| placebo | 0.4774 | 0.1771 | 0.3273 | 146 |
| placebo | 0.5069 | 0.1800 | 0.3434 | 152 |
| placebo | 0.5297 | 0.1894 | 0.3595 | 159 |
| placebo | 0.5467 | 0.2046 | 0.3757 | 168 |
| placebo | 0.5744 | 0.2093 | 0.3918 | 169 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 175 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 192 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 195 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 198 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 200 |
| placebo | 0.6204 | 0.2300 | 0.4252 | 203 |
| placebo | 0.6392 | 0.2468 | 0.4430 | 206 |
| placebo | 0.6392 | 0.2468 | 0.4430 | 207 |
| placebo | 0.6583 | 0.2641 | 0.4612 | 211 |
| placebo | 0.6881 | 0.2707 | 0.4794 | 213 |
| placebo | 0.7073 | 0.2885 | 0.4979 | 226 |
| placebo | 0.7073 | 0.2885 | 0.4979 | 227 |
| placebo | 0.7273 | 0.3070 | 0.5171 | 236 |
| placebo | 0.7629 | 0.3099 | 0.5364 | 241 |
| placebo | 0.7629 | 0.3099 | 0.5364 | 245 |
| placebo | 0.7829 | 0.3290 | 0.5560 | 246 |
| placebo | 0.8079 | 0.3433 | 0.5756 | 248 |
| placebo | 0.8482 | 0.3422 | 0.5952 | 249 |
| placebo | 0.8780 | 0.3516 | 0.6148 | 250 |
| placebo | 0.8780 | 0.3516 | 0.6148 | 252 |
| placebo | 0.9036 | 0.3660 | 0.6348 | 253 |
| placebo | 0.9321 | 0.3776 | 0.6548 | 255 |
| placebo | 0.9573 | 0.3932 | 0.6752 | 260 |
| placebo | 0.9573 | 0.3932 | 0.6752 | 261 |
| placebo | 0.9776 | 0.4144 | 0.6960 | 264 |
| placebo | 1.009 | 0.4253 | 0.7173 | 265 |
| placebo | 1.046 | 0.4309 | 0.7386 | 269 |
| placebo | 1.046 | 0.4309 | 0.7386 | 270 |
| placebo | 1.046 | 0.4309 | 0.7386 | 271 |
| placebo | 1.046 | 0.4309 | 0.7386 | 273 |
| placebo | 1.046 | 0.4309 | 0.7386 | 274 |
| placebo | 1.046 | 0.4309 | 0.7386 | 276 |
| placebo | 1.046 | 0.4309 | 0.7386 | 278 |
| placebo | 1.108 | 0.4835 | 0.7957 | 280 |
First 60 of 166 rows.
View data
| Rate ratio | upper | Term | lower |
|---|---|---|---|
| 0.3263 | 0.5989 | treat: rIFN-g | 0.1777 |
| 0.9699 | 0.9978 | age | 0.9428 |
Assumptions
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative end of follow-up — 128 subjects followed for 37477 time units in total.
- Events per variable — 38.0 events per coefficient.
Rate ratios (Andersen–Gill)
| Term | β | Robust SE | Rate ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| treat: rIFN-g | −1.120 | 0.3099 | 0.3263 | 0.1777 | 0.5989 | −3.614 | < .001 |
| age | −0.0305 | 0.0144 | 0.9699 | 0.9428 | 0.9978 | −2.114 | .034 |
Hazard (rate) ratios with robust standard errors clustered by subject.
Mean cumulative function
| treat | Time | Mean events per subject | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| placebo | 100 | 0.2466 | 0.0654 | 0.1184 | 0.3749 |
| placebo | 200 | 0.4079 | 0.0935 | 0.2247 | 0.5911 |
| placebo | 300 | 0.8930 | 0.1682 | 0.5633 | 1.223 |
| rIFN-g | 100 | 0.0317 | 0.0221 | −0.0115 | 0.0750 |
| rIFN-g | 200 | 0.1603 | 0.0564 | 0.0498 | 0.2708 |
| rIFN-g | 300 | 0.2795 | 0.0730 | 0.1364 | 0.4226 |
Lawless–Nadeau robust standard errors.
- Event: status = 1. Model: Andersen–Gill. Ties: efron.
The exact R script · R R version 4.5.1 (2025-06-13)
# Recurrent events (mean cumulative function, Andersen–Gill, PWP, WLW)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.recurrent 1.0.1 · spec 47c780e24b140a3e
# Dataset: s2_cgd (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_cgd.parquet", col_select = c("id", "tstart", "tstop", "status", "treat", "age")))
n_input <- nrow(df)
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", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "121", "122", "123", "125", "131", "132", "133", "134", "135")) # stored level order
df[["treat"]] <- factor(df[["treat"]], levels = c("placebo", "rIFN-g")) # stored level order
df <- df[stats::complete.cases(df[c("id", "tstart", "tstop", "status", "treat", "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("id", "tstart", "tstop", "status", "treat", "age")) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol <- "tstart"
tcol <- "tstop"
ecol <- "status"
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)
# %% Subjects and events
idcol <- "id"
ids <- as.character(df[[idcol]])
n_subjects <- length(unique(ids))
per_subject <- tapply(as.integer(ev), ids, sum)
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)]))
conf <- 0.95
ties <- "efron"
model <- "ag"
K <- as.integer(4)
model_label <- switch(model, ag = "Andersen–Gill", pwp_tt = "PWP total-time", pwp_gt = "PWP gap-time", wlw = "Wei–Lin–Weissfeld")
q <- stats::qnorm(1 - (1 - conf) / 2)
# %% Mean cumulative function: survfit's cumulative hazard with id (robust = Lawless–Nadeau SE)
times <- c(100, 200, 300)
if (length(times) == 0) times <- cs_default_times(t1)
g <- "treat"
curves <- levels(df[[g]])
gv <- as.character(df[[g]])
values <- list()
mcf_rows <- list()
chart <- list(time = numeric(0), mcf = numeric(0), low = numeric(0), high = numeric(0), strata = character(0))
for (cname in curves) {
m <- gv == cname
sf <- survfit(Surv(t0[m], t1[m], ev[m]) ~ 1, id = ids[m], robust = TRUE) # robust even when every id has one row
est <- cs_step_at(sf$time, sf$cumhaz, times, start = 0)
se_x <- cs_step_at(sf$time, sf$std.chaz, times, start = 0)
for (i in seq_along(times)) {
values[[sprintf("mcf[%s@%s]", cname, cs_key_num(times[i]))]] <- est[i]
values[[sprintf("mcf_se[%s@%s]", cname, cs_key_num(times[i]))]] <- se_x[i]
mcf_rows[[length(mcf_rows) + 1]] <- list(curve = cname, time = times[i], mcf = est[i], se = se_x[i],
low = est[i] - q * se_x[i], high = est[i] + q * se_x[i])
}
chart$time <- c(chart$time, 0, sf$time)
chart$mcf <- c(chart$mcf, 0, sf$cumhaz)
chart$low <- c(chart$low, 0, sf$cumhaz - q * sf$std.chaz)
chart$high <- c(chart$high, 0, sf$cumhaz + q * sf$std.chaz)
chart$strata <- c(chart$strata, rep(cname, length(sf$time) + 1))
}
values <- c(values, list(n_subjects = n_subjects, n_rows = length(t1), events = sum(ev), mean_events = sum(ev) / n_subjects,
max_events_subject = max(per_subject), model_label = model_label, event_label = event_label))
# %% Regression model (robust SEs clustered by subject)
preds <- c("treat", "age")
coef_rows <- list()
k <- 0L
dd <- data.frame(.start = t0, .stop = t1, .e = ev, .id = ids)
# %% 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"
if (length(preds)) {
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
if (model == "ag") {
fit <- coxph(stats::as.formula(paste("Surv(.start, .stop, .e) ~", rhs)), data = dd, cluster = .id, ties = ties, control = ctl)
} else if (model == "pwp_tt") {
dd$.enum <- pmin(cs_surv_episode(ids, t0, ev), K)
fit <- coxph(stats::as.formula(paste("Surv(.start, .stop, .e) ~", rhs, "+ strata(.enum)")), data = dd, cluster = .id, ties = ties, control = ctl)
} else if (model == "pwp_gt") {
dd$.enum <- pmin(cs_surv_episode(ids, t0, ev), K)
dd$.gap <- t1 - t0
fit <- coxph(stats::as.formula(paste("Surv(.gap, .e) ~", rhs, "+ strata(.enum)")), data = dd, cluster = .id, ties = ties, control = ctl)
} else {
w <- cs_surv_wlw(ids, t0, t1, ev, min(K, max(per_subject)))
dw <- dd[w$row, , drop = FALSE]
dw$.time <- w$time
dw$.status <- w$status
dw$.k <- w$k
fit <- coxph(stats::as.formula(paste("Surv(.time, .status) ~", rhs, "+ strata(.k)")), data = dw, cluster = .id, ties = ties, 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(unname(fit$naive.var)))
se <- sqrt(diag(V))
z <- beta / se
pv <- 2 * stats::pnorm(-abs(z))
hr <- exp(beta)
hr_lo <- exp(beta - q * se)
hr_hi <- exp(beta + q * se)
k <- length(beta)
lr <- 2 * diff(fit$loglik)
wald <- drop(beta %*% solve(V, beta))
values <- c(values, list(n_coef = k, lr_chisq = lr, lr_df = k, lr_p = stats::pchisq(lr, k, lower.tail = FALSE),
wald_chisq = wald, wald_p = stats::pchisq(wald, 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]))
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")])
}
} else {
for (key in c("n_coef", "lr_chisq", "lr_df", "lr_p", "wald_chisq", "wald_p", "coef_1_label", "hr_1", "hr_1_low", "hr_1_high", "p_1")) {
values[key] <- list(NULL)
}
}
# %% Assumptions
assumptions <- list(
list(key = "intervals", label = "Non-overlapping intervals", status = if (n_overlap > 0) "fail" else "pass",
detail = if (n_overlap > 0) sprintf("%d intervals overlap the subject's previous interval.", n_overlap) else "Intervals of each subject do not overlap."),
list(key = "censoring", label = "Non-informative end of follow-up", status = "info",
detail = sprintf("%d subjects followed for %s time units in total.", n_subjects, format(sum(t1 - t0), digits = 6)))
)
if (k > 0) {
epv <- sum(ev) / k
assumptions[[3]] <- list(key = "events_per_variable", label = "Events per variable", status = if (epv < 10) "warn" else "pass",
detail = sprintf("%.1f events per coefficient.", epv))
}
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
tables <- list(list(key = "mcf", title = "Mean cumulative function", columns = list(
list(key = "curve", label = if (is.null(g)) "Curve" else g, type = "string"), list(key = "time", label = "Time", type = "number"),
list(key = "mcf", label = "Mean events per subject", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number")
), rows = mcf_rows, note = "Lawless–Nadeau robust standard errors."))
charts <- list(cs_chart("mcf", "mcf-plot", paste0("Mean cumulative function", if (!is.null(g)) paste(" by", g) else ""), list(
time = cs_col(tcol, chart$time, "numeric"), mcf = cs_col("Mean events per subject", chart$mcf, "numeric"),
low = cs_col("lower", chart$low, "numeric"), high = cs_col("upper", chart$high, "numeric"),
group = cs_col(if (is.null(g)) "Curve" else g, chart$strata, "categorical", levels = curves)
)))
if (length(coef_rows)) {
tables <- c(list(list(key = "coefficients", title = sprintf("Rate ratios (%s)", model_label), columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β", type = "number"),
list(key = "se", label = "Robust SE", type = "number"), list(key = "hr", label = "Rate ratio", 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 = "Hazard (rate) ratios with robust standard errors clustered by subject.")), tables)
charts[[2]] <- cs_chart("hr", "forest", sprintf("Rate ratios (%s)", model_label), list(
label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("Rate ratio", hr, "numeric"),
low = cs_col("lower", hr_lo, "numeric"), high = cs_col("upper", hr_hi, "numeric")
), controls = list(reference = 1, log = TRUE))
}
cs_publish(list(
method = "survival.recurrent",
methodVersion = "1.0.1",
title = paste0("Recurrent events", if (length(coef_rows)) paste(" —", model_label, "model") else ""),
engine = cs_engine_info("survival", "codesplashr"),
n = n_subjects,
summary = paste0(sprintf("%d events in %d subjects (%.2f per subject)", sum(ev), n_subjects, sum(ev) / n_subjects),
if (length(coef_rows)) sprintf("; %s robust Wald χ²(%d) = %.2f, %s.", model_label, k, values$wald_chisq, cs_fmt_p(values$wald_p)) else "."),
apa = if (length(coef_rows)) sprintf("RR = %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]))
else sprintf("%d events in %d subjects", sum(ev), n_subjects),
statistics = c(list(list(key = "events", label = "Events", value = sum(ev), format = "integer"),
list(key = "mean_events", label = "Events per subject", value = values$mean_events)),
if (length(coef_rows)) list(list(key = "wald_chisq", label = "Robust Wald χ²", value = values$wald_chisq),
list(key = "wald_p", label = "p", value = values$wald_p, format = "p")) else list()),
tables = tables,
effectSizes = if (length(coef_rows)) list(list(key = "hr_1", label = sprintf("Rate ratio (%s)", labels[1]), value = hr[1], ciLow = hr_lo[1],
ciHigh = hr_hi[1], ciLevel = conf, method = "Wald interval on log(RR), robust SE")) else list(),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Event: %s. Model: %s", event_label, model_label),
if (model %in% c("pwp_tt", "pwp_gt")) sprintf(" (event numbers above %d pooled)", K) else "",
if (model == "wlw") sprintf(" (first %d events)", min(K, max(per_subject))) else "", sprintf(". Ties: %s.", ties))),
charts = charts,
values = values
))
RR = 0.33, 95% CI [0.18, 0.60], p < .001
- Events
- 76
- Events per subject
- 0.5938
- Robust Wald χ²
- 16.620
- p
- < .001
Effect size
- Rate ratio (treat: rIFN-g) 0.3263 95% CI [0.1777, 0.5989]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative end of follow-up — 128 subjects followed for 37477 time units in total.
- Events per variable — 38.0 events per coefficient.
Rate ratios (Andersen–Gill)
| Term | β | Robust SE | Rate ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| treat: rIFN-g | −1.120 | 0.3099 | 0.3263 | 0.1777 | 0.5989 | −3.614 | < .001 |
| age | −0.0305 | 0.0144 | 0.9699 | 0.9428 | 0.9978 | −2.114 | .034 |
Hazard (rate) ratios with robust standard errors clustered by subject.
Mean cumulative function
| treat | Time | Mean events per subject | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| placebo | 100 | 0.2466 | 0.0654 | 0.1184 | 0.3749 |
| placebo | 200 | 0.4079 | 0.0935 | 0.2247 | 0.5911 |
| placebo | 300 | 0.8930 | 0.1682 | 0.5633 | 1.223 |
| rIFN-g | 100 | 0.0317 | 0.0221 | −0.0115 | 0.0750 |
| rIFN-g | 200 | 0.1603 | 0.0564 | 0.0498 | 0.2708 |
| rIFN-g | 300 | 0.2795 | 0.0730 | 0.1364 | 0.4226 |
Lawless–Nadeau robust standard errors.
- Event: status = 1. Model: Andersen–Gill. Ties: efron.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Recurrent events (mean cumulative function, Andersen–Gill, PWP, WLW)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.recurrent 1.0.1 · spec 47c780e24b140a3e
# Dataset: s2_cgd (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 # report times
from codesplash.stats import survival_adv as sa # coxph for (start, stop] data with robust SEs, MCF, PWP/WLW data
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s2_cgd.parquet", columns=["id", "tstart", "tstop", "status", "treat", "age"])
n_input = len(df)
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", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "121", "122", "123", "125", "131", "132", "133", "134", "135"]) # stored level order
df["treat"] = pd.Categorical(df["treat"], categories=["placebo", "rIFN-g"]) # stored level order
df = df.dropna(subset=["id", "tstart", "tstop", "status", "treat", "age"]) # listwise deletion over the analysis columns
df["id"] = df["id"].cat.remove_unused_categories()
df["treat"] = df["treat"].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, ["id", "tstart", "tstop", "status", "treat", "age"]) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol = "tstart"
tcol = "tstop"
ecol = "status"
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)
# %% Subjects and events
idcol = "id"
ids = df[idcol].astype(str).to_numpy()
subjects = np.unique(ids)
n_subjects = len(subjects)
per_subject = pd.Series(ev.astype(int)).groupby(ids).sum()
order = np.lexsort((t0, ids))
same = ids[order][1:] == ids[order][:-1]
n_overlap = int(np.sum(same & (t0[order][1:] < t1[order][:-1])))
conf = 0.95
ties = "efron"
model = "ag"
K = int(4)
model_label = {"ag": "Andersen–Gill", "pwp_tt": "PWP total-time", "pwp_gt": "PWP gap-time", "wlw": "Wei–Lin–Weissfeld"}[model]
# %% Mean cumulative function (Lawless–Nadeau robust SE, normal interval)
times = [100, 200, 300, ] or sv.default_times(t1)
q = stats.norm.ppf(1 - (1 - conf) / 2)
g = "treat"
curves = [str(x) for x in df[g].cat.categories]
gv = df[g].astype(str).to_numpy()
values = {}
mcf_rows = []
chart = {"time": [], "surv": [], "low": [], "high": [], "strata": []}
for cname in curves:
m = gv == cname
res = sa.mcf(t0[m], t1[m], ev[m], ids[m], conf=conf)
for x in times:
est = sa.step_at(res["time"], res["mcf"], x, 0.0)
se_x = sa.step_at(res["time"], res["se"], x, 0.0)
values[f"mcf[{cname}@{sv.key_num(x)}]"] = est
values[f"mcf_se[{cname}@{sv.key_num(x)}]"] = se_x
mcf_rows.append({"curve": cname, "time": float(x), "mcf": est, "se": se_x, "low": est - q * se_x, "high": est + q * se_x})
chart["time"] += [0.0] + res["time"].tolist()
chart["surv"] += [0.0] + res["mcf"].tolist()
chart["low"] += [0.0] + res["lower"].tolist()
chart["high"] += [0.0] + res["upper"].tolist()
chart["strata"] += [cname] * (len(res["time"]) + 1)
values.update({
"n_subjects": float(n_subjects), "n_rows": float(len(t1)), "events": float(ev.sum()), "mean_events": float(ev.sum()) / n_subjects,
"max_events_subject": float(per_subject.max()), "model_label": model_label, "event_label": event_label,
})
# %% Regression model (robust SEs clustered by subject)
preds = ["treat", "age"]
coef_rows = []
# %% 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))
if preds:
if model == "ag":
fit = sa.cox_cp(t0, t1, ev, X, ties=ties, cluster=ids)
elif model == "pwp_tt":
enum = np.minimum(sa.episode_numbers(ids, t0, ev), K)
fit = sa.cox_cp(t0, t1, ev, X, strata=enum, ties=ties, cluster=ids)
elif model == "pwp_gt":
enum = np.minimum(sa.episode_numbers(ids, t0, ev), K)
fit = sa.cox_cp(np.zeros(len(t1)), t1 - t0, ev, X, strata=enum, ties=ties, cluster=ids)
else: # WLW: the k-th event time from time 0 for k = 1..K
K_eff = int(min(K, per_subject.max()))
w = sa.wlw_data(ids, t0, t1, ev, K_eff)
fit = sa.cox_cp(np.zeros(len(w["time"])), w["time"], w["status"] == 1, X[w["row"]], strata=w["k"], ties=ties,
cluster=ids[w["row"]])
beta = fit["coef"]
naive_se = np.sqrt(np.diag(fit["cov"]))
V = fit["rcov"]
se = np.sqrt(np.diag(V))
z = beta / se
pv = 2 * stats.norm.sf(np.abs(z))
hr, hr_lo, hr_hi = np.exp(beta), np.exp(beta - q * se), np.exp(beta + q * se)
k = len(beta)
wald = float(beta @ np.linalg.solve(V, beta))
values.update({
"n_coef": float(k), "lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": float(stats.chi2.sf(fit["lr"], k)),
"wald_chisq": wald, "wald_p": float(stats.chi2.sf(wald, 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]),
})
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])})
else:
k = 0
for key in ("n_coef", "lr_chisq", "lr_df", "lr_p", "wald_chisq", "wald_p", "coef_1_label", "hr_1", "hr_1_low", "hr_1_high", "p_1"):
values[key] = None
# %% Assumptions
assumptions = [
{"key": "intervals", "label": "Non-overlapping intervals", "status": "fail" if n_overlap else "pass",
"detail": f"{n_overlap} intervals overlap the subject's previous interval." if n_overlap else "Intervals of each subject do not overlap."},
{"key": "censoring", "label": "Non-informative end of follow-up", "status": "info",
"detail": f"{n_subjects} subjects followed for {float(np.sum(t1 - t0)):.6g} time units in total."},
]
if k:
epv = float(ev.sum()) / k
assumptions.append({"key": "events_per_variable", "label": "Events per variable", "status": "warn" if epv < 10 else "pass",
"detail": f"{epv:.1f} events per coefficient."})
# %% Result
pct = f"{conf:.0%}"
tables = [{"key": "mcf", "title": "Mean cumulative function", "columns": [
{"key": "curve", "label": g or "Curve", "type": "string"}, {"key": "time", "label": "Time", "type": "number"},
{"key": "mcf", "label": "Mean events per subject", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
], "rows": mcf_rows, "note": "Lawless–Nadeau robust standard errors."}]
charts = [cs.chart("mcf", "mcf-plot", "Mean cumulative function" + (f" by {g}" if g else ""), {
"time": cs.col(tcol, chart["time"], "numeric"), "mcf": cs.col("Mean events per subject", chart["surv"], "numeric"),
"low": cs.col("lower", chart["low"], "numeric"), "high": cs.col("upper", chart["high"], "numeric"),
"group": cs.col(g or "Curve", chart["strata"], "categorical", levels=curves),
})]
if coef_rows:
tables.insert(0, {"key": "coefficients", "title": f"Rate ratios ({model_label})", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β", "type": "number"},
{"key": "se", "label": "Robust SE", "type": "number"}, {"key": "hr", "label": "Rate ratio", "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": "Hazard (rate) ratios with robust standard errors clustered by subject."})
charts.append(cs.chart("hr", "forest", f"Rate ratios ({model_label})", {
"label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Rate ratio", hr, "numeric"),
"low": cs.col("lower", hr_lo, "numeric"), "high": cs.col("upper", hr_hi, "numeric"),
}, controls={"reference": 1, "log": True}))
cs.publish({
"method": "survival.recurrent",
"methodVersion": "1.0.1",
"title": "Recurrent events" + (f" — {model_label} model" if coef_rows else ""),
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n_subjects),
"summary": f"{int(ev.sum())} events in {n_subjects} subjects ({float(ev.sum()) / n_subjects:.2f} per subject)"
+ (f"; {model_label} robust Wald χ²({k}) = {values['wald_chisq']:.2f}, {cs.fmt_p(values['wald_p'])}." if coef_rows else "."),
"apa": (f"RR = {cs.fmt_num(hr[0])}, {pct} CI [{cs.fmt_num(hr_lo[0])}, {cs.fmt_num(hr_hi[0])}], {cs.fmt_p(pv[0])}" if coef_rows
else f"{int(ev.sum())} events in {n_subjects} subjects"),
"statistics": [{"key": "events", "label": "Events", "value": float(ev.sum()), "format": "integer"},
{"key": "mean_events", "label": "Events per subject", "value": values["mean_events"]}]
+ ([{"key": "wald_chisq", "label": "Robust Wald χ²", "value": values["wald_chisq"]},
{"key": "wald_p", "label": "p", "value": values["wald_p"], "format": "p"}] if coef_rows else []),
"tables": tables,
"effectSizes": ([{"key": "hr_1", "label": f"Rate ratio ({labels[0]})", "value": float(hr[0]), "ciLow": float(hr_lo[0]),
"ciHigh": float(hr_hi[0]), "ciLevel": conf, "method": "Wald interval on log(RR), robust SE"}] if coef_rows else []),
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Model: {model_label}" + (f" (event numbers above {K} pooled)" if model in ("pwp_tt", "pwp_gt") else "")
+ (f" (first {min(K, int(per_subject.max()))} events)" if model == "wlw" else "") + f". Ties: {ties}."],
"charts": charts,
"values": values,
})
The option Regression model switches among the forms, and Event numbers modeled separately limits how many events get their own stratum in PWP and WLW. Later strata hold few people, so effects there are unstable.
Only known to lie between two visits
In the appNow a different problem. A test at each clinic visit tells you an event has happened since the previous one, but not when. The data have two columns, set in the roles Last time without the event and First time with the event. The second is empty when no event was ever seen.
In this example, 123 rows are interval-censored, 83 right-censored, 14 left-censored and 20 exact.
TR = 1.61, 95% CI [1.29, 2.01], p < .001
- Innermost intervals
- 98
- NPMLE log-likelihood
- −478.07
Effect size
- Time ratio (group: treated) 1.614 95% CI [1.294, 2.014]
Plots
View data
| Curve | Survival probability | Time |
|---|---|---|
| All | 1 | 0 |
| All | 0.9521 | 1.540 |
| All | 0.9521 | 3 |
| All | 0.9521 | 3.620 |
| All | 0.9503 | 4.600 |
| All | 0.9276 | 5.320 |
| All | 0.9276 | 6.040 |
| All | 0.9004 | 6.080 |
| All | 0.9004 | 6.630 |
| All | 0.9004 | 7.620 |
| All | 0.9004 | 8.330 |
| All | 0.8956 | 8.590 |
| All | 0.8956 | 9.140 |
| All | 0.8470 | 9.290 |
| All | 0.8470 | 9.710 |
| All | 0.8249 | 10.020 |
| All | 0.8249 | 10.190 |
| All | 0.8116 | 10.650 |
| All | 0.8116 | 10.950 |
| All | 0.8116 | 11.220 |
| All | 0.7991 | 11.540 |
| All | 0.7879 | 11.650 |
| All | 0.7879 | 11.930 |
| All | 0.7879 | 12.130 |
| All | 0.7732 | 12.810 |
| All | 0.7732 | 13.490 |
| All | 0.7732 | 13.870 |
| All | 0.7577 | 14.700 |
| All | 0.7577 | 15.220 |
| All | 0.7331 | 15.470 |
| All | 0.7331 | 16.430 |
| All | 0.6873 | 16.870 |
| All | 0.6873 | 17.940 |
| All | 0.6873 | 18.040 |
| All | 0.6873 | 18.660 |
| All | 0.6873 | 18.700 |
| All | 0.6680 | 19.610 |
| All | 0.6680 | 19.840 |
| All | 0.6680 | 20.140 |
| All | 0.6680 | 20.260 |
| All | 0.6662 | 20.790 |
| All | 0.6662 | 20.820 |
| All | 0.6136 | 21.260 |
| All | 0.6136 | 21.580 |
| All | 0.6136 | 21.990 |
| All | 0.6136 | 22.490 |
| All | 0.5867 | 22.730 |
| All | 0.5867 | 23.150 |
| All | 0.5867 | 23.410 |
| All | 0.5867 | 23.760 |
| All | 0.5867 | 23.870 |
| All | 0.5867 | 24.160 |
| All | 0.5867 | 24.330 |
| All | 0.5867 | 24.750 |
| All | 0.5867 | 25.050 |
| All | 0.5867 | 25.500 |
| All | 0.5607 | 25.630 |
| All | 0.5050 | 26.020 |
| All | 0.5050 | 26.570 |
| All | 0.5050 | 26.870 |
First 60 of 99 rows.
View data
| Time ratio | upper | Term | lower |
|---|---|---|---|
| 1.614 | 2.014 | group: treated | 1.294 |
| 1.038 | 1.075 | dose mg | 1.002 |
Assumptions
- Censoring pattern — 123 interval-censored, 14 left-censored, 20 exact and 83 right-censored times.
- Non-informative inspection times — Assumed: check-up times must not depend on the (unseen) event.
- Distribution fit — Weibull log-likelihood -493.45; compare the model with the Turnbull curve.
Turnbull survival estimate
| Curve | Time | Survival |
|---|---|---|
| All | 5 | 0.9503 |
| All | 10 | 0.8470 |
| All | 20 | 0.6680 |
| All | 30 | 0.4308 |
1 − the probability of innermost intervals that end by the time (the estimate is not determined inside an innermost interval).
Weibull accelerated failure time model
| Term | β (log time) | SE | Time ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| (Intercept) | 3.141 | 0.1109 | — | — | — | 28.330 | < .001 |
| group: treated | 0.4790 | 0.1128 | 1.614 | 1.294 | 2.014 | 4.246 | < .001 |
| dose mg | 0.0372 | 0.0180 | 1.038 | 1.002 | 1.075 | 2.060 | .039 |
Scale 0.674; log-likelihood -493.4490.
- Intervals (lower, upper]: left = 0 or empty means before the first check; empty right means never seen with the event.
The exact R script · R R version 4.5.1 (2025-06-13)
# Interval-censored survival (Turnbull estimate and parametric models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.interval 1.0.1 · spec 22fb2badb99da276
# Dataset: s2_ic (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(icenReg)
library(codesplashr)
# %% Data (an empty bound is meaningful here: open interval, so only the other columns drop rows)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s2_ic.parquet", col_select = c("left", "right", "group", "dose mg")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("control", "treated")) # stored level order
lcol <- "left"
ucol <- "right"
others <- setdiff(c("left", "right", "group", "dose mg"), c(lcol, ucol))
keep <- (if (length(others)) stats::complete.cases(df[others]) else rep(TRUE, nrow(df))) & !(is.na(df[[lcol]]) & is.na(df[[ucol]]))
df <- df[keep, , drop = FALSE]
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, sprintf("%d of %d rows were left out because a value was missing (or both times were empty).", n_dropped, n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
for (cc in c(lcol, ucol)) if (all(is.na(df[[cc]]))) cs_error("CS_E_ALL_MISSING", column = cc)
cs_check_finite_columns(df, c(lcol, others)) # an infinite upper time is allowed: it means no upper bound (right-censored)
# %% Censoring pattern: (L, R] with L = 0 → left-censored, R = ∞ → right-censored, L = R → exact
L <- as.numeric(df[[lcol]])
L[is.na(L)] <- 0
R <- as.numeric(df[[ucol]])
R[is.na(R)] <- Inf
bad <- L < 0 | L > R
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = lcol, requirement = sprintf("between 0 and %s", ucol), count = sum(bad))
# The model needs times bounded on both sides somewhere: without any lower (or upper) bound its likelihood has no maximum.
if (!any(L > 0)) cs_error("CS_E_UNDEFINED", what = "The accelerated failure time model", reason = sprintf("no row has a %s time above 0, so the times have no lower bound", lcol))
if (!any(is.finite(R))) cs_error("CS_E_UNDEFINED", what = "The accelerated failure time model", reason = sprintf("no row has a finite %s time, so the times have no upper bound", ucol))
exact <- L == R
right <- is.infinite(R)
left <- L == 0 & !right & !exact
interval <- !exact & !right & !left
conf <- 0.95
dist <- "weibull"
times <- c(5, 10, 20, 30)
if (length(times) == 0) times <- cs_default_times(c(L[L > 0], R[is.finite(R)]))
# %% Turnbull estimate (icenReg::ic_np; overall and per group)
g <- NULL
curves <- "All"
gv <- rep("All", length(L))
overall <- ic_np(cbind(L, R))
surv_at <- function(fit, t) 1 - sum(fit$p_hat[fit$T_bull_Intervals[2, ] <= t])
values <- list()
surv_rows <- list()
chart <- list(time = numeric(0), surv = numeric(0), strata = character(0))
for (cname in curves) {
m <- gv == cname
fit <- if (cname == "All") overall else ic_np(cbind(L[m], R[m]))
for (x in times) {
s_x <- surv_at(fit, x)
values[[sprintf("surv[%s@%s]", cname, cs_key_num(x))]] <- s_x
surv_rows[[length(surv_rows) + 1]] <- list(curve = cname, time = x, surv = s_x)
}
up <- fit$T_bull_Intervals[2, ]
cum <- 1 - cumsum(fit$p_hat)
fin <- is.finite(up)
chart$time <- c(chart$time, 0, up[fin])
chart$surv <- c(chart$surv, 1, cum[fin])
chart$strata <- c(chart$strata, rep(cname, 1 + sum(fin)))
}
# %% Parametric AFT model for interval-censored times (survreg, interval2)
preds <- c("group", "dose mg")
dd <- data.frame(.l = ifelse(left, NA_real_, L), .r = ifelse(right, NA_real_, R))
# %% 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"
use <- !(L == 0 & right) # a row open at both ends, (0, Inf), says nothing about the time; survreg can't take a zero time
aft <- survreg(stats::as.formula(paste("Surv(.l, .r, type = \"interval2\") ~", rhs)), data = dd[use, , drop = FALSE], dist = dist,
control = survreg.control(rel.tolerance = 1e-12, maxiter = 100))
if (aft$iter >= 100) cs_error("CS_E_NO_CONVERGENCE", what = "The accelerated failure time model") # e.g. censoring that leaves no finite maximum
coef_all <- unname(coef(aft))
p <- length(coef_all)
se_all <- sqrt(diag(unname(vcov(aft))))[seq_len(p)]
q <- stats::qnorm(1 - (1 - conf) / 2)
values <- c(values, list(n = length(L), n_exact = sum(exact), n_interval = sum(interval), n_left = sum(left), n_right = sum(right),
np_loglik = overall$llk, n_intervals = length(overall$p_hat), dist = dist, n_coef = length(labels),
aft_loglik = aft$loglik[2], log_scale = log(aft$scale), scale = aft$scale))
coef_rows <- list()
terms <- c("(Intercept)", labels)
for (i in seq_len(p)) {
b <- coef_all[i]
s_ <- se_all[i]
z_ <- b / s_
p_ <- 2 * stats::pnorm(-abs(z_))
lab <- terms[i]
values[[sprintf("coef[%s]", lab)]] <- b
values[[sprintf("se[%s]", lab)]] <- s_
values[[sprintf("z[%s]", lab)]] <- z_
values[[sprintf("p[%s]", lab)]] <- p_
row <- list(term = lab, coef = b, se = s_, tr = NULL, tr_low = NULL, tr_high = NULL, z = z_, p = p_)
if (i > 1) {
row$tr <- exp(b)
row$tr_low <- exp(b - q * s_)
row$tr_high <- exp(b + q * s_)
values[[sprintf("tr[%s]", lab)]] <- row$tr
values[[sprintf("tr_low[%s]", lab)]] <- row$tr_low
values[[sprintf("tr_high[%s]", lab)]] <- row$tr_high
}
coef_rows[[i]] <- row
}
if (length(labels)) {
r1 <- coef_rows[[2]]
values <- c(values, list(coef_1_label = labels[1], tr_1 = r1$tr, tr_1_low = r1$tr_low, tr_1_high = r1$tr_high, p_1 = r1$p))
} else {
for (key in c("coef_1_label", "tr_1", "tr_1_low", "tr_1_high", "p_1")) values[key] <- list(NULL)
}
# %% Assumptions
assumptions <- list(
list(key = "censoring_mix", label = "Censoring pattern", status = "info",
detail = sprintf("%d interval-censored, %d left-censored, %d exact and %d right-censored times.", sum(interval), sum(left), sum(exact), sum(right))),
list(key = "independent_inspection", label = "Non-informative inspection times", status = "info",
detail = "Assumed: check-up times must not depend on the (unseen) event."),
list(key = "distribution", label = "Distribution fit", status = "info",
detail = sprintf("%s log-likelihood %.2f; compare the model with the Turnbull curve.", paste0(toupper(substring(dist, 1, 1)), substring(dist, 2)), aft$loglik[2]))
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
dist_title <- paste0(toupper(substring(dist, 1, 1)), substring(dist, 2))
tables <- list(
list(key = "survival", title = "Turnbull survival estimate", columns = list(
list(key = "curve", label = if (is.null(g)) "Curve" else g, type = "string"), list(key = "time", label = "Time", type = "number"),
list(key = "surv", label = "Survival", type = "number")
), rows = surv_rows, note = "1 − the probability of innermost intervals that end by the time (the estimate is not determined inside an innermost interval)."),
list(key = "coefficients", title = sprintf("%s accelerated failure time model", dist_title), columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β (log time)", type = "number"),
list(key = "se", label = "SE", type = "number"), list(key = "tr", label = "Time ratio", type = "number"),
list(key = "tr_low", label = paste(pct, "CI low"), type = "number"), list(key = "tr_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("Scale %.4g; log-likelihood %.4f.", aft$scale, aft$loglik[2]))
)
charts <- list(cs_chart("turnbull", "km-curve", paste0("Turnbull survival estimate", if (!is.null(g)) paste(" by", g) else ""), list(
time = cs_col("Time", chart$time, "numeric"), surv = cs_col("Survival probability", chart$surv, "numeric"),
strata = cs_col(if (is.null(g)) "Curve" else g, chart$strata, "categorical", levels = curves)
)))
if (length(labels)) {
rows_p <- coef_rows[-1]
charts[[2]] <- cs_chart("tr", "forest", "Time ratios", list(
label = cs_col("Term", labels, "categorical", levels = labels),
estimate = cs_col("Time ratio", vapply(rows_p, function(r) r$tr, numeric(1)), "numeric"),
low = cs_col("lower", vapply(rows_p, function(r) r$tr_low, numeric(1)), "numeric"),
high = cs_col("upper", vapply(rows_p, function(r) r$tr_high, numeric(1)), "numeric")
), controls = list(reference = 1, log = TRUE))
}
cs_publish(list(
method = "survival.interval",
methodVersion = "1.0.1",
title = "Interval-censored survival",
engine = cs_engine_info("survival", "icenReg", "codesplashr"),
n = length(L),
summary = paste0(sprintf("Turnbull estimate on %d innermost intervals (%d interval-censored times)", length(overall$p_hat), sum(interval)),
if (length(labels)) sprintf("; %s AFT time ratio for %s %.3g (%s).", dist, labels[1], values$tr_1, cs_fmt_p(values$p_1)) else "."),
apa = if (length(labels)) sprintf("TR = %s, %s CI [%s, %s], %s", cs_fmt_num(values$tr_1), pct, cs_fmt_num(values$tr_1_low), cs_fmt_num(values$tr_1_high), cs_fmt_p(values$p_1))
else sprintf("N = %d, %d innermost intervals", length(L), length(overall$p_hat)),
statistics = list(list(key = "n_intervals", label = "Innermost intervals", value = length(overall$p_hat), format = "integer"),
list(key = "np_loglik", label = "NPMLE log-likelihood", value = overall$llk)),
tables = tables,
effectSizes = if (length(labels)) list(list(key = "tr_1", label = sprintf("Time ratio (%s)", labels[1]), value = values$tr_1, ciLow = values$tr_1_low,
ciHigh = values$tr_1_high, ciLevel = conf, method = "Wald interval on log(TR)")) else list(),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Intervals (lower, upper]: %s = 0 or empty means before the first check; empty %s means never seen with the event.", lcol, ucol)),
charts = charts,
values = values
))
TR = 1.61, 95% CI [1.29, 2.01], p < .001
- Innermost intervals
- 98
- NPMLE log-likelihood
- −478.07
Effect size
- Time ratio (group: treated) 1.614 95% CI [1.294, 2.014]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Censoring pattern — 123 interval-censored, 14 left-censored, 20 exact and 83 right-censored times.
- Non-informative inspection times — Assumed: check-up times must not depend on the (unseen) event.
- Distribution fit — Weibull log-likelihood -493.45; compare the model with the Turnbull curve.
Turnbull survival estimate
| Curve | Time | Survival |
|---|---|---|
| All | 5 | 0.9503 |
| All | 10 | 0.8470 |
| All | 20 | 0.6680 |
| All | 30 | 0.4308 |
1 − the probability of innermost intervals that end by the time (the estimate is not determined inside an innermost interval).
Weibull accelerated failure time model
| Term | β (log time) | SE | Time ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| (Intercept) | 3.141 | 0.1109 | — | — | — | 28.330 | < .001 |
| group: treated | 0.4790 | 0.1128 | 1.614 | 1.294 | 2.014 | 4.246 | < .001 |
| dose mg | 0.0372 | 0.0180 | 1.038 | 1.002 | 1.075 | 2.060 | .039 |
Scale 0.674; log-likelihood -493.4490.
- Intervals (lower, upper]: left = 0 or empty means before the first check; empty right means never seen with the event.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Interval-censored survival (Turnbull estimate and parametric models)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.interval 1.0.1 · spec 22fb2badb99da276
# Dataset: s2_ic (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 # report times
from codesplash.stats import survival_adv as sa # Turnbull NPMLE (icenReg::ic_np) and survreg's interval2 AFT
# %% Data (an empty bound is meaningful here: open interval, so only the other columns drop rows)
df = pd.read_parquet("tests/parity/fixtures/s2_ic.parquet", columns=["left", "right", "group", "dose mg"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["control", "treated"]) # stored level order
lcol = "left"
ucol = "right"
others = [c for c in ["left", "right", "group", "dose mg"] if c not in (lcol, ucol)]
keep = df[others].notna().all(axis=1) & ~(df[lcol].isna() & df[ucol].isna())
df = df[keep]
df["group"] = df["group"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(f"{n_dropped} of {n_input} rows were left out because a value was missing (or both times were empty).")
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
for c in (lcol, ucol):
if df[c].isna().all():
cs.cs_error("CS_E_ALL_MISSING", column=c)
cs.check_finite_columns(df, [lcol] + others) # an infinite upper time is allowed: it means no upper bound (right-censored)
# %% Censoring pattern: (L, R] with L = 0 → left-censored, R = ∞ → right-censored, L = R → exact
L = df[lcol].to_numpy(dtype=float)
L = np.where(np.isnan(L), 0.0, L)
R = df[ucol].to_numpy(dtype=float)
R = np.where(np.isnan(R), np.inf, R)
bad = (L < 0) | (L > R)
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=lcol, requirement=f"between 0 and {ucol}", count=int(bad.sum()))
# The model needs times bounded on both sides somewhere: without any lower (or upper) bound its likelihood has no maximum.
if not (L > 0).any():
cs.cs_error("CS_E_UNDEFINED", what="The accelerated failure time model", reason=f"no row has a {lcol} time above 0, so the times have no lower bound")
if not np.isfinite(R).any():
cs.cs_error("CS_E_UNDEFINED", what="The accelerated failure time model", reason=f"no row has a finite {ucol} time, so the times have no upper bound")
exact = L == R
right = np.isinf(R)
left = (L == 0) & ~right & ~exact
interval = ~exact & ~right & ~left
conf = 0.95
dist = "weibull"
finite = np.concatenate([L[L > 0], R[np.isfinite(R)]])
times = [5, 10, 20, 30, ] or sv.default_times(finite)
# %% Turnbull estimate (overall and per group)
g = None
curves = ["All"]
gv = np.full(len(L), "All")
overall = sa.turnbull(L, R)
values = {}
surv_rows = []
chart = {"time": [], "surv": [], "strata": []}
for cname in curves:
m = gv == cname
fit = overall if cname == "All" else sa.turnbull(L[m], R[m])
for x in times:
s_x = sa.turnbull_surv(fit, x)
values[f"surv[{cname}@{sv.key_num(x)}]"] = s_x
surv_rows.append({"curve": cname, "time": float(x), "surv": s_x})
cum = 1.0 - np.cumsum(fit["p"])
chart["time"] += [0.0] + fit["upper"][np.isfinite(fit["upper"])].tolist()
chart["surv"] += [1.0] + cum[np.isfinite(fit["upper"])].tolist()
chart["strata"] += [cname] * (1 + int(np.sum(np.isfinite(fit["upper"]))))
# %% Parametric AFT model for interval-censored times (survreg, interval2)
preds = ["group", "dose mg"]
# %% 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))
Xa = np.column_stack([np.ones(len(L)), X])
use = ~((L == 0) & right) # a row open at both ends, (0, ∞), says nothing about the time; survreg can't take a zero time
aft = sa.aft_interval(np.where(left, np.nan, L)[use], np.where(right, np.nan, R)[use], Xa[use], dist)
if not aft["converged"]:
cs.cs_error("CS_E_NO_CONVERGENCE", what="The accelerated failure time model") # e.g. censoring that leaves no finite maximum
p = Xa.shape[1]
coef = aft["coef"]
se_all = np.sqrt(np.diag(aft["cov"]))[:p]
q = stats.norm.ppf(1 - (1 - conf) / 2)
values.update({
"n": float(len(L)), "n_exact": float(exact.sum()), "n_interval": float(interval.sum()), "n_left": float(left.sum()),
"n_right": float(right.sum()), "np_loglik": overall["llk"], "n_intervals": float(len(overall["p"])), "dist": dist,
"n_coef": float(len(labels)), "aft_loglik": aft["loglik"], "log_scale": aft["log_scale"], "scale": float(np.exp(aft["log_scale"])),
})
coef_rows = []
for i, lab in enumerate(["(Intercept)"] + labels):
b, s_ = float(coef[i]), float(se_all[i])
z_ = b / s_
p_ = float(2 * stats.norm.sf(abs(z_)))
values[f"coef[{lab}]"], values[f"se[{lab}]"], values[f"z[{lab}]"], values[f"p[{lab}]"] = b, s_, z_, p_
row = {"term": lab, "coef": b, "se": s_, "z": z_, "p": p_, "tr": None, "tr_low": None, "tr_high": None}
if i > 0:
row.update({"tr": float(np.exp(b)), "tr_low": float(np.exp(b - q * s_)), "tr_high": float(np.exp(b + q * s_))})
values[f"tr[{lab}]"], values[f"tr_low[{lab}]"], values[f"tr_high[{lab}]"] = row["tr"], row["tr_low"], row["tr_high"]
coef_rows.append(row)
if labels:
r1 = coef_rows[1]
values.update({"coef_1_label": labels[0], "tr_1": r1["tr"], "tr_1_low": r1["tr_low"], "tr_1_high": r1["tr_high"], "p_1": r1["p"]})
else:
values.update({"coef_1_label": None, "tr_1": None, "tr_1_low": None, "tr_1_high": None, "p_1": None})
# %% Assumptions
assumptions = [
{"key": "censoring_mix", "label": "Censoring pattern", "status": "info",
"detail": f"{int(interval.sum())} interval-censored, {int(left.sum())} left-censored, {int(exact.sum())} exact and {int(right.sum())} right-censored times."},
{"key": "independent_inspection", "label": "Non-informative inspection times", "status": "info",
"detail": "Assumed: check-up times must not depend on the (unseen) event."},
{"key": "distribution", "label": "Distribution fit", "status": "info",
"detail": f"{dist.capitalize()} log-likelihood {aft['loglik']:.2f}; compare the model with the Turnbull curve."},
]
# %% Result
pct = f"{conf:.0%}"
tables = [{"key": "survival", "title": "Turnbull survival estimate", "columns": [
{"key": "curve", "label": g or "Curve", "type": "string"}, {"key": "time", "label": "Time", "type": "number"},
{"key": "surv", "label": "Survival", "type": "number"},
], "rows": surv_rows, "note": "1 − the probability of innermost intervals that end by the time (the estimate is not determined inside an innermost interval)."}]
tables.append({"key": "coefficients", "title": f"{dist.capitalize()} accelerated failure time model", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β (log time)", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}, {"key": "tr", "label": "Time ratio", "type": "number"},
{"key": "tr_low", "label": f"{pct} CI low", "type": "number"}, {"key": "tr_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"Scale {np.exp(aft['log_scale']):.4g}; log-likelihood {aft['loglik']:.4f}."})
charts = [cs.chart("turnbull", "km-curve", "Turnbull survival estimate" + (f" by {g}" if g else ""), {
"time": cs.col("Time", chart["time"], "numeric"), "surv": cs.col("Survival probability", chart["surv"], "numeric"),
"strata": cs.col(g or "Curve", chart["strata"], "categorical", levels=curves),
})]
if labels:
trs = [r["tr"] for r in coef_rows[1:]]
charts.append(cs.chart("tr", "forest", "Time ratios", {
"label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Time ratio", trs, "numeric"),
"low": cs.col("lower", [r["tr_low"] for r in coef_rows[1:]], "numeric"), "high": cs.col("upper", [r["tr_high"] for r in coef_rows[1:]], "numeric"),
}, controls={"reference": 1, "log": True}))
cs.publish({
"method": "survival.interval",
"methodVersion": "1.0.1",
"title": "Interval-censored survival",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(L)),
"summary": f"Turnbull estimate on {len(overall['p'])} innermost intervals ({int(interval.sum())} interval-censored times)"
+ (f"; {dist} AFT time ratio for {labels[0]} {values['tr_1']:.3g} ({cs.fmt_p(values['p_1'])})." if labels else "."),
"apa": (f"TR = {cs.fmt_num(values['tr_1'])}, {pct} CI [{cs.fmt_num(values['tr_1_low'])}, {cs.fmt_num(values['tr_1_high'])}], {cs.fmt_p(values['p_1'])}"
if labels else f"N = {len(L)}, {len(overall['p'])} innermost intervals"),
"statistics": [{"key": "n_intervals", "label": "Innermost intervals", "value": float(len(overall["p"])), "format": "integer"},
{"key": "np_loglik", "label": "NPMLE log-likelihood", "value": overall["llk"]}],
"tables": tables,
"effectSizes": ([{"key": "tr_1", "label": f"Time ratio ({labels[0]})", "value": values["tr_1"], "ciLow": values["tr_1_low"],
"ciHigh": values["tr_1_high"], "ciLevel": conf, "method": "Wald interval on log(TR)"}] if labels else []),
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Intervals (lower, upper]: {lcol} = 0 or empty means before the first check; empty {ucol} means never seen with the event."],
"charts": charts,
"values": values,
})
The Turnbull estimate makes no distributional assumption; the parametric model adds covariates. Treated patients' times are 1.61 times as long.
Check your understanding
CheckpointCheck yourself
A hospital wants to know whether a program reduces its overall readmission rate per patient-year. Which model fits?
Show the answer
Answer: a
Andersen–Gill treats events as one rate, the question asked. A first-event analysis would throw away most of the readmissions.
Check yourself
A mean cumulative function reaches 1.4 at two years. What does that mean?
Show the answer
Answer: b
It counts events per subject, so it isn't a probability and can exceed 1.
Check yourself
Why not use the midpoint of each interval and run Kaplan–Meier?
Show the answer
Answer: b
Midpoint imputation treats a guess as a fact. Turnbull's estimator and interval-censored models use the interval itself.
Recap
Recap- Recurrent events: look at the mean cumulative function, then pick a model by the question.
- Andersen–Gill models an overall rate; PWP the next event; WLW each event as its own outcome.
- With interval-censored data, keep the interval: use Turnbull or a parametric interval model, not midpoints.
Concepts in this lesson