FTime to event · survival.interval
Interval-censored survival (Turnbull estimate and parametric models)
What is the survival distribution when events are only known to have happened between two visits?
For events detected at periodic checks — the exact time is only known to lie in an interval (last negative, first positive] — estimates the survival curve with the Turnbull nonparametric maximum-likelihood estimator (icenReg) and, with predictors, fits a parametric accelerated failure time model (Weibull, exponential, log-normal or log-logistic) to the interval-, left- and right-censored times (survreg's interval2). Reports survival at chosen times and time ratios with confidence intervals.
A real result
Example “Ic overall weibull”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Ic overall weibulls2_ic · lower: left · predictors: group, dose mg · upper: right
- Ic groups lognormals2_ic · group: group · lower: left · predictors: dose mg · upper: right
- Ic loglogistics2_ic · lower: left · predictors: group · upper: right
- Ic turnbull only exponentials2_ic · group: group · lower: left · upper: right
- Degenerate all nas2_ic · lower: left · predictors: group, dose mg · upper: right
- Degenerate constants2_ic · lower: left · predictors: group, dose mg · upper: right
- Degenerate empty after filters2_ic · lower: left · predictors: group, dose mg · upper: right
- Degenerate infs2_ic · lower: left · predictors: group, dose mg · upper: right
In the guides
Where it sits in the decision guides
- Time-to-event: Cox, survival models · Statistics Guide · D — Predict an outcome
- Parametric models: Weibull, exponential … · Statistics Guide · F — Time-to-event analysis
- Interval censoring, recurrent events, delayed entry · Statistics Guide · F — Time-to-event analysis
What you need
- Last time without the eventnumeric · 1 column
- The latest time the subject was known to be event-free (0 or empty = the event happened before the first check — left-censored).
- First time with the eventnumeric · 1 column
- The first time the event was seen (empty = never seen — right-censored). Equal to the lower time for an exactly known time.
- Predictorsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
- Optional — covariates for the parametric model (time ratios).
- Groupscategorical / boolean · 0–1 column · 2–10 levels
- Optional — a Turnbull curve per group.
Choices you make
hypothesis
- Distributiondefault weibull
Distribution of the event times for the parametric model.
- Weibull(default) — Risk rises or falls steadily over time; the usual first choice for interval-censored times.
- Exponential — Risk stays constant over time; pick it only if time shouldn't change the risk.
- Log-normal — Risk rises and then falls; pick it when early risk peaks and fades.
- Log-logistic — Risk can rise and then fall, with heavier tails than log-normal; pick it when many subjects last a long time.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Report survival at timesdefault
Times for the survival table (default 25%, 50% and 75% of the largest finite time).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Non-informative inspection times
When subjects are checked must not depend on whether the event has happened.
Censoring pattern
How many times are exact, interval-, left- and right-censored; the Turnbull estimate is only determined between its innermost intervals.
Distribution fit
The parametric model assumes the chosen distribution; compare it with the Turnbull curve.
What it reports
- Tests: First predictor's time ratio
- n
- How many independent units the analysis used; it sets precision and power.
- n_exact
- How many independent units the analysis used; it sets precision and power.
- n_interval
- How many independent units the analysis used; it sets precision and power.
- n_left
- How many independent units the analysis used; it sets precision and power.
- n_right
- How many independent units the analysis used; it sets precision and power.
- np_loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- n_intervals
- How many independent units the analysis used; it sets precision and power.
- dist
- Distribution assumed by the parametric model of event times: weibull, exponential, lognormal or loglogistic.
- n_coef
- How many coefficients the model estimated, counting the intercept.
- aft_loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- log_scale
- The spread of log time around the model's prediction. For a Weibull model the shape is one over this scale.
- scale
- Stretches or shrinks a fitted distribution without changing its form, so larger means more spread.
- coef_1_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- tr_1
- How many times longer lifetimes last for this predictor, holding the others fixed; 1 means no difference.
- tr_1_low
- A range of effect values compatible with your data at the chosen confidence level.
- tr_1_high
- A range of effect values compatible with your data at the chosen confidence level.
- p_1
- How surprising your data would be if the null hypothesis were true, as a probability.
Per group, level or term: surv[<curve>@<time>], coef[<term>], se[<term>], tr[<term>], tr_low[<term>], tr_high[<term>], z[<term>], p[<term>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses survival, icenReg, nanoparquet, codesplashr.
Default traps between the two languages
- The Turnbull estimate: R uses icenReg::ic_np (EMICM, converged to its tolerance); Python finds the same maximum with an EM warm start and an active-set Newton method (codesplash.stats.survival_adv.turnbull). Survival is reported at the chosen times as 1 − the mass of innermost intervals ending by then; masses agree to ≈ 1e-8 absolute (icenReg stops when the log-likelihood changes by < 1e-10), so survival far in the tail can differ by ≈ 1e-6 relative — hence the 1e-5 tolerance on surv[*]; the log-likelihood agrees to ≈ 1e-14.
- The parametric model: R fits survreg(Surv(l, r, type = "interval2") ~ …); Python maximizes the same likelihood by Newton's method with analytic scores and a finite-difference Hessian of the scores (aft_interval). Coefficients agree to ≈ 1e-14, standard errors to ≈ 1e-10.
The exact script CodeSplash ran for example “Ic overall weibull” · 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 exact script CodeSplash ran for example “Ic overall weibull” · 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
))
Sources
- Turnbull, B. W. (1976). The empirical distribution function with arbitrarily grouped, censored and truncated data. JRSS B, 38, 290–295.
- Anderson-Bergman, C. (2017). icenReg: Regression models for interval censored data in R. Journal of Statistical Software, 81(12).
- Gentleman, R., & Geyer, C. J. (1994). Maximum likelihood for interval censored data: Consistency and computation. Biometrika, 81, 618–623.
From the CodeSplash method registry · survival.interval v1.0.1.