Skip to content

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.

Advanced ~12 min7 steps

What runs in CodeSplash

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

Read first

01

Events that happen again

Read

In 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 tt. It can pass 1, because it counts events rather than people.

02

Three models, three questions

Read
ModelTreats each event asAnswers
Andersen–GillOne ongoing rateDoes treatment lower the overall rate?
PWP (total or gap time)Conditional on the event beforeDoes it delay the next event, given the last?
WLWA separate marginal outcomeWhat 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.

03

Predict the difference

Predict

Predict 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?

The same answerA stronger effect from Andersen–GillA stronger effect from PWP
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.

04

Run it

In the app
Recurrent events — Andersen–Gill modelRecorded · Python and R agreeRecorded 2026-11-17 · 46 values compared
R

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]

Plots

Mean cumulative function by treatFor repeated events (readmissions, failures, purchases), how many events per subject accumulate over time?
View data
treatupperlowerMean events per subjecttstop
placebo0000
placebo0.0453−0.01450.01544
placebo0.0728−0.01120.03086
placebo0.0972−0.00490.04628
placebo0.12000.00310.061511
placebo0.14170.01210.076914
placebo0.16270.02190.092318
placebo0.18310.03230.107719
placebo0.21360.03250.123122
placebo0.23260.04430.138523
placebo0.26030.04740.153826
placebo0.27850.05990.169252
placebo0.29660.07270.184657
placebo0.32210.07790.200065
placebo0.33970.09110.215467
placebo0.35700.10450.230891
placebo0.37490.11840.246699
placebo0.37490.11840.2466102
placebo0.39310.13250.2628104
placebo0.41100.14680.2789120
placebo0.46000.16230.3112121
placebo0.47740.17710.3273146
placebo0.50690.18000.3434152
placebo0.52970.18940.3595159
placebo0.54670.20460.3757168
placebo0.57440.20930.3918169
placebo0.59110.22470.4079175
placebo0.59110.22470.4079192
placebo0.59110.22470.4079195
placebo0.59110.22470.4079198
placebo0.59110.22470.4079200
placebo0.62040.23000.4252203
placebo0.63920.24680.4430206
placebo0.63920.24680.4430207
placebo0.65830.26410.4612211
placebo0.68810.27070.4794213
placebo0.70730.28850.4979226
placebo0.70730.28850.4979227
placebo0.72730.30700.5171236
placebo0.76290.30990.5364241
placebo0.76290.30990.5364245
placebo0.78290.32900.5560246
placebo0.80790.34330.5756248
placebo0.84820.34220.5952249
placebo0.87800.35160.6148250
placebo0.87800.35160.6148252
placebo0.90360.36600.6348253
placebo0.93210.37760.6548255
placebo0.95730.39320.6752260
placebo0.95730.39320.6752261
placebo0.97760.41440.6960264
placebo1.0090.42530.7173265
placebo1.0460.43090.7386269
placebo1.0460.43090.7386270
placebo1.0460.43090.7386271
placebo1.0460.43090.7386273
placebo1.0460.43090.7386274
placebo1.0460.43090.7386276
placebo1.0460.43090.7386278
placebo1.1080.48350.7957280

First 60 of 166 rows.

Rate ratios (Andersen–Gill)How large are several estimates, how precise, and which exclude the null?
View data
Rate ratioupperTermlower
0.32630.5989treat: rIFN-g0.1777
0.96990.9978age0.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 SERate ratio95% CI low95% CI highzp
treat: rIFN-g−1.1200.30990.32630.17770.5989−3.614< .001
age−0.03050.01440.96990.94280.9978−2.114.034

Hazard (rate) ratios with robust standard errors clustered by subject.

Mean cumulative function

treatTimeMean events per subjectSE95% CI low95% CI high
placebo1000.24660.06540.11840.3749
placebo2000.40790.09350.22470.5911
placebo3000.89300.16820.56331.223
rIFN-g1000.03170.0221−0.01150.0750
rIFN-g2000.16030.05640.04980.2708
rIFN-g3000.27950.07300.13640.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
))
Python

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 SERate ratio95% CI low95% CI highzp
treat: rIFN-g−1.1200.30990.32630.17770.5989−3.614< .001
age−0.03050.01440.96990.94280.9978−2.114.034

Hazard (rate) ratios with robust standard errors clustered by subject.

Mean cumulative function

treatTimeMean events per subjectSE95% CI low95% CI high
placebo1000.24660.06540.11840.3749
placebo2000.40790.09350.22470.5911
placebo3000.89300.16820.56331.223
rIFN-g1000.03170.0221−0.01150.0750
rIFN-g2000.16030.05640.04980.2708
rIFN-g3000.27950.07300.13640.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.

05

Only known to lie between two visits

In the app

Now 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.

Interval-censored survivalRecorded · Python and R agreeRecorded 2026-11-17 · 39 values compared · largest relative difference 8.4e-10
R

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

Turnbull survival estimateWhat fraction survives (is event-free) over time, and do groups differ?
View data
CurveSurvival probabilityTime
All10
All0.95211.540
All0.95213
All0.95213.620
All0.95034.600
All0.92765.320
All0.92766.040
All0.90046.080
All0.90046.630
All0.90047.620
All0.90048.330
All0.89568.590
All0.89569.140
All0.84709.290
All0.84709.710
All0.824910.020
All0.824910.190
All0.811610.650
All0.811610.950
All0.811611.220
All0.799111.540
All0.787911.650
All0.787911.930
All0.787912.130
All0.773212.810
All0.773213.490
All0.773213.870
All0.757714.700
All0.757715.220
All0.733115.470
All0.733116.430
All0.687316.870
All0.687317.940
All0.687318.040
All0.687318.660
All0.687318.700
All0.668019.610
All0.668019.840
All0.668020.140
All0.668020.260
All0.666220.790
All0.666220.820
All0.613621.260
All0.613621.580
All0.613621.990
All0.613622.490
All0.586722.730
All0.586723.150
All0.586723.410
All0.586723.760
All0.586723.870
All0.586724.160
All0.586724.330
All0.586724.750
All0.586725.050
All0.586725.500
All0.560725.630
All0.505026.020
All0.505026.570
All0.505026.870

First 60 of 99 rows.

Time ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Time ratioupperTermlower
1.6142.014group: treated1.294
1.0381.075dose mg1.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

CurveTimeSurvival
All50.9503
All100.8470
All200.6680
All300.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)SETime ratio95% CI low95% CI highzp
(Intercept)3.1410.1109———28.330< .001
group: treated0.47900.11281.6141.2942.0144.246< .001
dose mg0.03720.01801.0381.0021.0752.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
))
Python

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

CurveTimeSurvival
All50.9503
All100.8470
All200.6680
All300.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)SETime ratio95% CI low95% CI highzp
(Intercept)3.1410.1109———28.330< .001
group: treated0.47900.11281.6141.2942.0144.246< .001
dose mg0.03720.01801.0381.0021.0752.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.

06

Check your understanding

Checkpoint

Check 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.

07

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