Parametric models and time ratios
Assume a distribution and you can talk about survival time directly. Compare Weibull, log-normal and log-logistic fits, and turn a time ratio into a hazard ratio.
What runs in CodeSplash
- Parametric survival regression (AFT) Verified in Python and R
You will be able to
- Interpret a time ratio from an accelerated failure time model
- Read a Weibull shape as rising or falling risk
- Say when a parametric model is worth its extra assumption
Read first
Stretching time
ReadA Cox model says covariates multiply the hazard. An accelerated failure time modelAccelerated failure timeA survival model of log time, where features stretch or shrink how long until the event, with no proportional-hazards assumption. says they multiply time itself:
A time ratioTime ratioIn an accelerated failure time model, how much a predictor stretches or shrinks survival times. Above 1 means longer survival. of 2 means a group's survival times are stretched to twice as long, at every point of the distribution. Unlike a hazard ratio, you can say that to anyone.
The price is that you must choose a distribution for : Weibull, log-normal, log-logistic or exponential.
Read the shape
PredictPredict first
Patients with advanced lung cancer are being followed. A Weibull model's shape says whether the hazard rises or falls with time.
What do you expect here?
Reveal
Rising: the shape is 1.33. Patients' risk of death grows the longer they have been followed. The exponential distribution is the special case with shape exactly 1, where risk never changes.
Read the card
In the appEach extra year of age multiplies survival time by 0.988 (95% interval 0.974 to 1.001).
time ratio = 0.99, 95% CI [0.97, 1.00], p = .078
- log L
- −1147.05
- AIC
- 2302.11
- Scale σ
- 0.7541
- Likelihood-ratio p
- .001
- Concordance (C, apparent)
- 0.6029
Plots
View data
| Time ratio | upper | Term | lower |
|---|---|---|---|
| 0.9878 | 1.001 | age | 0.9744 |
| 1.465 | 1.881 | sex: female | 1.141 |
View data
| Martingale residual | Predictor | Predictor value |
|---|---|---|
| 0.0343 | age | 74 |
| −0.4824 | age | 68 |
| −3.512 | age | 56 |
| 0.5554 | age | 57 |
| −2.136 | age | 60 |
| −4.780 | age | 74 |
| 0.4631 | age | 68 |
| 0.3101 | age | 71 |
| 0.5622 | age | 53 |
| 0.6526 | age | 61 |
| 0.6640 | age | 57 |
| −0.4450 | age | 68 |
| −0.6657 | age | 68 |
| 0.8892 | age | 60 |
| −0.6598 | age | 57 |
| 0.6828 | age | 67 |
| −1.274 | age | 70 |
| −1.452 | age | 63 |
| 0.9488 | age | 56 |
| 0.8597 | age | 57 |
| 0.1568 | age | 67 |
| 0.9335 | age | 49 |
| −0.6819 | age | 50 |
| 0.0388 | age | 58 |
| −0.3071 | age | 72 |
| −0.1014 | age | 70 |
| −0.7713 | age | 60 |
| 0.7443 | age | 70 |
| 0.0531 | age | 53 |
| 0.9868 | age | 74 |
| 0.0443 | age | 69 |
| 0.9639 | age | 73 |
| −0.3210 | age | 48 |
| 0.8850 | age | 60 |
| 0.9236 | age | 61 |
| 0.8586 | age | 62 |
| −2.053 | age | 65 |
| −2.343 | age | 66 |
| 0.8010 | age | 74 |
| −0.5694 | age | 64 |
| −0.5537 | age | 70 |
| 0.7717 | age | 73 |
| 0.2775 | age | 59 |
| 0.8279 | age | 60 |
| −1.059 | age | 68 |
| 0.8726 | age | 76 |
| 0.0469 | age | 74 |
| −0.6273 | age | 63 |
| −1.585 | age | 74 |
| −0.3276 | age | 50 |
| −0.8003 | age | 72 |
| 0.5737 | age | 63 |
| 0.9144 | age | 68 |
| 0.4426 | age | 58 |
| −1.220 | age | 59 |
| 0.8982 | age | 62 |
| 0.9979 | age | 65 |
| 0.7598 | age | 57 |
| −0.3111 | age | 58 |
| 0.4202 | age | 64 |
First 60 of 228 rows.
View data
| Event | Series | Unit exponential F(r) | Cox–Snell residual |
|---|---|---|---|
| 1 | data | — | 0.9657 |
| 1 | data | — | 1.482 |
| 0 | data | — | 3.512 |
| 1 | data | — | 0.4446 |
| 1 | data | — | 3.136 |
| 0 | data | — | 4.780 |
| 1 | data | — | 0.5369 |
| 1 | data | — | 0.6899 |
| 1 | data | — | 0.4378 |
| 1 | data | — | 0.3474 |
| 1 | data | — | 0.3360 |
| 1 | data | — | 1.445 |
| 1 | data | — | 1.666 |
| 1 | data | — | 0.1108 |
| 1 | data | — | 1.660 |
| 1 | data | — | 0.3172 |
| 1 | data | — | 2.274 |
| 1 | data | — | 2.452 |
| 1 | data | — | 0.0512 |
| 1 | data | — | 0.1403 |
| 1 | data | — | 0.8432 |
| 1 | data | — | 0.0665 |
| 1 | data | — | 1.682 |
| 1 | data | — | 0.9612 |
| 1 | data | — | 1.307 |
| 1 | data | — | 1.101 |
| 1 | data | — | 1.771 |
| 1 | data | — | 0.2557 |
| 1 | data | — | 0.9469 |
| 1 | data | — | 0.0132 |
| 1 | data | — | 0.9557 |
| 1 | data | — | 0.0361 |
| 1 | data | — | 1.321 |
| 1 | data | — | 0.1150 |
| 1 | data | — | 0.0764 |
| 1 | data | — | 0.1414 |
| 1 | data | — | 3.053 |
| 0 | data | — | 2.343 |
| 1 | data | — | 0.1990 |
| 1 | data | — | 1.569 |
| 1 | data | — | 1.554 |
| 1 | data | — | 0.2283 |
| 1 | data | — | 0.7225 |
| 1 | data | — | 0.1721 |
| 1 | data | — | 2.059 |
| 1 | data | — | 0.1274 |
| 1 | data | — | 0.9531 |
| 1 | data | — | 1.627 |
| 1 | data | — | 2.585 |
| 1 | data | — | 1.328 |
| 1 | data | — | 1.800 |
| 1 | data | — | 0.4263 |
| 1 | data | — | 0.0856 |
| 1 | data | — | 0.5574 |
| 1 | data | — | 2.220 |
| 1 | data | — | 0.1018 |
| 1 | data | — | 0.0021 |
| 1 | data | — | 0.2402 |
| 1 | data | — | 1.311 |
| 1 | data | — | 0.5798 |
First 60 of 288 rows.
View data
| Profile | Reliability | time |
|---|---|---|
| Reference profile | 1 | 0 |
| Reference profile | 0.9912 | 10.220 |
| Reference profile | 0.9781 | 20.440 |
| Reference profile | 0.9628 | 30.660 |
| Reference profile | 0.9461 | 40.880 |
| Reference profile | 0.9282 | 51.100 |
| Reference profile | 0.9094 | 61.320 |
| Reference profile | 0.8901 | 71.540 |
| Reference profile | 0.8702 | 81.760 |
| Reference profile | 0.8500 | 91.980 |
| Reference profile | 0.8295 | 102.20 |
| Reference profile | 0.8089 | 112.42 |
| Reference profile | 0.7882 | 122.64 |
| Reference profile | 0.7674 | 132.86 |
| Reference profile | 0.7467 | 143.08 |
| Reference profile | 0.7261 | 153.30 |
| Reference profile | 0.7057 | 163.52 |
| Reference profile | 0.6854 | 173.74 |
| Reference profile | 0.6653 | 183.96 |
| Reference profile | 0.6454 | 194.18 |
| Reference profile | 0.6258 | 204.40 |
| Reference profile | 0.6065 | 214.62 |
| Reference profile | 0.5875 | 224.84 |
| Reference profile | 0.5689 | 235.06 |
| Reference profile | 0.5505 | 245.28 |
| Reference profile | 0.5325 | 255.50 |
| Reference profile | 0.5149 | 265.72 |
| Reference profile | 0.4977 | 275.94 |
| Reference profile | 0.4808 | 286.16 |
| Reference profile | 0.4643 | 296.38 |
| Reference profile | 0.4482 | 306.60 |
| Reference profile | 0.4325 | 316.82 |
| Reference profile | 0.4172 | 327.04 |
| Reference profile | 0.4023 | 337.26 |
| Reference profile | 0.3878 | 347.48 |
| Reference profile | 0.3736 | 357.70 |
| Reference profile | 0.3599 | 367.92 |
| Reference profile | 0.3465 | 378.14 |
| Reference profile | 0.3336 | 388.36 |
| Reference profile | 0.3210 | 398.58 |
| Reference profile | 0.3088 | 408.80 |
| Reference profile | 0.2969 | 419.02 |
| Reference profile | 0.2854 | 429.24 |
| Reference profile | 0.2743 | 439.46 |
| Reference profile | 0.2636 | 449.68 |
| Reference profile | 0.2531 | 459.90 |
| Reference profile | 0.2431 | 470.12 |
| Reference profile | 0.2333 | 480.34 |
| Reference profile | 0.2239 | 490.56 |
| Reference profile | 0.2148 | 500.78 |
| Reference profile | 0.2060 | 511 |
| Reference profile | 0.1975 | 521.22 |
| Reference profile | 0.1893 | 531.44 |
| Reference profile | 0.1815 | 541.66 |
| Reference profile | 0.1738 | 551.88 |
| Reference profile | 0.1665 | 562.10 |
| Reference profile | 0.1594 | 572.32 |
| Reference profile | 0.1526 | 582.54 |
| Reference profile | 0.1461 | 592.76 |
| Reference profile | 0.1398 | 602.98 |
First 60 of 101 rows.
Assumptions
- Distribution fits — The Weibull model has the lowest AIC of the four distributions.
- Events per variable — 82.5 events per coefficient.
- Non-informative censoring — 63 of 228 observations are censored.
- Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
Coefficients and time ratios
| Term | β (log time) | SE | Time ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| (Intercept) | 6.657 | 0.4475 | 778.16 | 323.70 | 1870.70 | 14.875 | < .001 |
| age | −0.0123 | 0.0070 | 0.9878 | 0.9744 | 1.001 | −1.762 | .078 |
| sex: female | 0.3821 | 0.1275 | 1.465 | 1.141 | 1.881 | 2.997 | .003 |
Scale σ = 0.7541 (Weibull shape 1/σ = 1.326).
Distribution comparison
| Distribution | log L | AIC |
|---|---|---|
| Weibull | −1147.05 | 2302.11 |
| exponential | −1156.10 | 2318.20 |
| log-normal | −1158.75 | 2325.50 |
| log-logistic | −1152.90 | 2313.79 |
Life metrics
| Profile | Mean life | 95% CI low | 95% CI high |
|---|---|---|---|
| Reference profile | 332.99 | 289.30 | 383.29 |
B-lives
| Profile | Percent failed | Time | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Reference profile | 10 | 66.329 | 50.954 | 86.344 |
| Reference profile | 50 | 274.55 | 236.44 | 318.81 |
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6029 | 0.5529 | 0.6529 | Harrell's C on the data the model was fitted to; SE 0.0255 (infinitesimal jackknife). |
| AIC | 2302.11 | — | — | −2 log L + 2k. |
| BIC | 2315.83 | — | — | −2 log L + k·log(n), n = 228 subjects. |
| Cox–Snell residual sum | 165 | — | — | Near the 165 events when the model fits (exactly equal for the Weibull and exponential models). |
- Event: dead = true. log T = Xβ + σW; time ratio = exp(β).
The exact R script · R R version 4.5.1 (2025-06-13)
# Parametric survival regression (AFT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.parametric 1.2.0 · spec fda7c6254320f37b
# Dataset: lung (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/lung.parquet", col_select = c("time", "dead", "age", "sex")))
n_input <- nrow(df)
df[["dead"]] <- factor(df[["dead"]], levels = c("false", "true")) # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("male", "female")) # stored level order
df <- df[stats::complete.cases(df[c("time", "dead", "age", "sex")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "dead", "age", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol <- "time"
ecol <- "dead"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
event_level <- "true" # the event; other levels are censored
ev <- as.character(df[[ecol]]) == event_level
event_label <- sprintf("%s = %s", ecol, event_level)
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)
# %% Predictors (treatment contrasts against the first stored level)
preds <- c("age", "sex")
dd <- data.frame(.t = tt, .e = ev)
labels <- character(0)
for (pname in preds) {
x <- df[[pname]]
if (is.factor(x)) {
if (nlevels(x) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = pname, min = 2, k = nlevels(x)) # a factor needs two levels with data
labels <- c(labels, paste0(pname, ": ", levels(x)[-1]))
} else {
labels <- c(labels, pname)
}
dd[[pname]] <- x
}
rhs <- paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ")
# %% Accelerated failure time model
if (any(tt <= 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "positive for a parametric model (log time)", count = sum(tt <= 0))
cs_check_not_constant(tt, tcol) # with one time for every row the scale of the time distribution collapses to zero
conf <- 0.95
dist <- "weibull"
dist_label <- c(weibull = "Weibull", exponential = "exponential", lognormal = "log-normal", loglogistic = "log-logistic")
ctl <- survreg.control(rel.tolerance = 1e-12, maxiter = 100)
form <- stats::as.formula(paste("Surv(.t, .e) ~", rhs))
fit <- survreg(form, data = dd, dist = dist, control = ctl)
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(vcov(fit))
p <- length(beta)
se_b <- sqrt(diag(V)[1:p])
fixed <- dist == "exponential"
log_scale <- if (fixed) 0 else log(fit$scale)
log_scale_se <- if (fixed) NA else sqrt(V[p + 1, p + 1])
scale <- exp(log_scale)
k <- p + if (fixed) 0 else 1
aic <- -2 * fit$loglik[2] + 2 * k
q <- stats::qnorm(1 - (1 - conf) / 2)
z <- beta / se_b
pv <- 2 * stats::pnorm(-abs(z))
tr <- exp(beta)
tr_lo <- exp(beta - q * se_b)
tr_hi <- exp(beta + q * se_b)
n_pred <- p - 1
lr <- 2 * (fit$loglik[2] - fit$loglik[1])
w50 <- if (dist %in% c("weibull", "exponential")) log(log(2)) else 0 # median of the error term
bic <- -2 * fit$loglik[2] + k * log(length(tt)) # n = subjects, as BIC() for survreg
lp <- unname(fit$linear.predictors)
if (n_pred) {
cc <- concordance(fit) # a longer predicted time is a lower risk; var: infinitesimal-jackknife variance of C
conc <- unname(cc$concordance)
c_se <- sqrt(unname(cc$var))
ci_ok <- is.finite(conc) && is.finite(c_se)
c_lo <- if (ci_ok) max(0, conc - q * c_se) else NA_real_
c_hi <- if (ci_ok) min(1, conc + q * c_se) else NA_real_
} else {
conc <- c_se <- c_lo <- c_hi <- NA_real_
}
zr <- (log(tt) - lp) / scale
cox_snell <- switch(dist, weibull = exp(zr), exponential = exp(zr), lognormal = -stats::pnorm(zr, lower.tail = FALSE, log.p = TRUE),
loglogistic = pmax(zr, 0) + log1p(exp(-abs(zr)))) # −log S(t | x): unit exponential if the model fits
mart <- ev - cox_snell # martingale residuals of the parametric model
num_preds <- preds[vapply(preds, function(p) is.numeric(df[[p]]) && length(unique(df[[p]])) > 2, logical(1))]
values <- list(
n = length(tt), events = sum(ev), dist_label = unname(dist_label[dist]), loglik = fit$loglik[2], loglik0 = fit$loglik[1],
lr_chisq = if (n_pred) lr else NA, lr_df = if (n_pred) n_pred else NA,
lr_p = if (n_pred) stats::pchisq(lr, n_pred, lower.tail = FALSE) else NA, aic = aic,
scale = scale, log_scale = log_scale, log_scale_se = log_scale_se,
shape = if (dist %in% c("weibull", "exponential")) 1 / scale else NA,
intercept = beta[1], intercept_se = se_b[1],
median_time = if (n_pred) NA else exp(beta[1] + scale * w50),
coef_1_label = if (n_pred) labels[1] else NA, tr_1 = if (n_pred) tr[2] else NA,
tr_1_low = if (n_pred) tr_lo[2] else NA, tr_1_high = if (n_pred) tr_hi[2] else NA,
p_1 = if (n_pred) pv[2] else NA, event_label = event_label,
bic = bic, concordance = conc, concordance_se = c_se, concordance_low = c_lo, concordance_high = c_hi,
cox_snell_sum = sum(cox_snell)
)
terms_all <- c("(Intercept)", labels)
coef_rows <- list()
for (i in seq_along(terms_all)) {
lab <- terms_all[i]
vals <- list(coef = beta[i], se = se_b[i], tr = tr[i], tr_low = tr_lo[i], tr_high = tr_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)
}
# %% Distribution comparison (AIC)
aic_rows <- list()
if (TRUE) {
for (d in c("weibull", "exponential", "lognormal", "loglogistic")) {
f <- if (d == dist) fit else survreg(form, data = dd, dist = d, control = ctl)
a <- -2 * f$loglik[2] + 2 * (p + if (d == "exponential") 0 else 1)
values[[sprintf("aic[%s]", d)]] <- a
aic_rows[[length(aic_rows) + 1]] <- list(dist = unname(dist_label[d]), loglik = f$loglik[2], aic = a)
}
best <- aic_rows[[which.min(vapply(aic_rows, function(r) r$aic, numeric(1)))]]
gap <- aic - best$aic
dist_check <- list(key = "distribution", label = "Distribution fits", status = if (gap > 2) "warn" else "pass",
detail = if (gap > 0) sprintf("The %s model has the lowest AIC (%.1f); the %s model is %.1f higher.",
best$dist, best$aic, dist_label[[dist]], gap)
else sprintf("The %s model has the lowest AIC of the four distributions.", dist_label[[dist]]))
} else {
dist_check <- list(key = "distribution", label = "Distribution fits", status = "info", detail = "Distributions were not compared.")
}
# %% Life metrics: one row per group for a single categorical predictor; else the reference profile
mission <- NULL # reliability is reported at this time
b_lives <- c(10, 50)
profiles <- list(list(name = "All units", x = 1))
single_cat <- NULL
if (n_pred) {
means <- unlist(lapply(preds, function(pn) if (is.factor(dd[[pn]])) rep(0, nlevels(dd[[pn]]) - 1) else mean(as.numeric(dd[[pn]]))))
profiles <- list(list(name = "Reference profile", x = c(1, means)))
if (length(preds) == 1 && is.factor(dd[[preds]])) {
single_cat <- preds
lv <- levels(dd[[preds]])
profiles <- c(list(list(name = lv[1], x = c(1, rep(0, n_pred)))), lapply(seq_len(n_pred), function(i) list(name = lv[i + 1], x = c(1, as.numeric(seq_len(n_pred) == i)))))
}
}
life_rows <- list()
blife_rows <- list()
values$mission_time <- if (is.null(mission)) NA else mission
values$life_profile <- if (!is.null(single_cat)) "group" else if (n_pred) "reference" else "all"
for (pf in profiles) {
lr_ <- cs_life_aft_row(dist, pf$x, beta, log_scale, V, mission, b_lives, conf)
values[[sprintf("mttf[%s]", pf$name)]] <- lr_$mttf
values[[sprintf("mttf_low[%s]", pf$name)]] <- lr_$mttf_low
values[[sprintf("mttf_high[%s]", pf$name)]] <- lr_$mttf_high
no_mean <- !is.finite(lr_$mttf) # a log-logistic with scale ≥ 1 has no mean
row <- list(profile = pf$name, mttf = if (no_mean) NA_real_ else lr_$mttf, mttf_low = if (no_mean) NA_real_ else lr_$mttf_low, mttf_high = if (no_mean) NA_real_ else lr_$mttf_high)
if (!is.null(mission)) {
values[[sprintf("mission_r[%s]", pf$name)]] <- lr_$mission_r
values[[sprintf("mission_low[%s]", pf$name)]] <- lr_$mission_low
values[[sprintf("mission_high[%s]", pf$name)]] <- lr_$mission_high
row <- c(row, list(mission_r = lr_$mission_r, mission_low = lr_$mission_low, mission_high = lr_$mission_high))
}
life_rows[[length(life_rows) + 1]] <- row
for (b in lr_$blives) {
key <- sprintf("%g@%s", b$percent, pf$name)
values[[sprintf("blife[%s]", key)]] <- b$life
values[[sprintf("blife_low[%s]", key)]] <- b$low
values[[sprintf("blife_high[%s]", key)]] <- b$high
blife_rows[[length(blife_rows) + 1]] <- list(profile = pf$name, percent = b$percent, life = b$life, low = b$low, high = b$high)
}
}
# %% Common shape across groups (likelihood-ratio test against separate shapes)
values$shape_lr <- NA
values$shape_lr_df <- NA
values$shape_lr_p <- NA
shape_check <- NULL
if (TRUE && !is.null(single_cat) && dist != "exponential") {
gv_ <- as.character(dd[[single_cat]])
groups_ <- levels(dd[[single_cat]])
if (all(vapply(groups_, function(lv) sum(ev[gv_ == lv]) >= 2, logical(1)))) {
ll_sep <- sum(vapply(groups_, function(lv) {
d_ <- dd[gv_ == lv, c(".t", ".e")]
survreg(Surv(.t, .e) ~ 1, data = d_, dist = dist, control = ctl)$loglik[2]
}, numeric(1)))
lr_shape <- max(0, 2 * (ll_sep - fit$loglik[2]))
df_shape <- length(groups_) - 1
p_shape <- stats::pchisq(lr_shape, df_shape, lower.tail = FALSE)
values$shape_lr <- lr_shape
values$shape_lr_df <- df_shape
values$shape_lr_p <- p_shape
shape_check <- list(key = "common_shape", label = "Common shape", status = if (p_shape < 0.05) "warn" else "pass", statistic = lr_shape, p = p_shape,
detail = paste0(sprintf("Likelihood-ratio test of separate shapes by %s: χ²(%d) = %.2f, %s", single_cat, df_shape, lr_shape, cs_fmt_p(p_shape)),
if (p_shape < 0.05) "; the time ratio changes with time." else "."))
}
}
epv <- sum(ev) / max(n_pred, 1)
assumptions <- list(dist_check,
list(key = "events_per_variable", label = "Events per variable", status = if (n_pred && epv < 10) "warn" else "pass",
detail = if (n_pred) sprintf("%.1f events per coefficient.", epv) else "No covariates."),
list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored.", sum(!ev), length(ev))))
if (!is.null(shape_check)) assumptions <- c(assumptions[1:2], list(shape_check), assumptions[3])
assumptions <- c(assumptions, list(list(
key = "functional_form", label = "Functional form", status = "info",
detail = if (length(num_preds)) sprintf(paste0("Not tested: look at the martingale residuals against %s. A smooth that bends away from zero",
" suggests a transformation or a spline."), paste(num_preds, collapse = ", "))
else "No numeric predictor with more than two values to check.")))
# %% Charts
charts <- list()
if (n_pred) {
charts[[1]] <- cs_chart("tr", "forest", "Time ratios", list(
label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("Time ratio", tr[-1], "numeric"),
low = cs_col("lower", tr_lo[-1], "numeric"), high = cs_col("upper", tr_hi[-1], "numeric")
), controls = list(reference = 1, log = TRUE))
} else {
km <- survfit(Surv(tt, ev) ~ 1, conf.type = "log-log")
grid <- seq(0, max(tt), length.out = 101)
zz <- (log(pmax(grid, 1e-300)) - beta[1]) / scale
surv_fit <- switch(dist, weibull = exp(-exp(zz)), exponential = exp(-exp(zz)), lognormal = stats::pnorm(zz, lower.tail = FALSE),
loglogistic = 1 / (1 + exp(zz)))
surv_fit[1] <- 1
lab_fit <- paste("Fitted", dist_label[[dist]])
charts[[1]] <- cs_chart("fit", "km-curve", sprintf("Kaplan–Meier and fitted %s survival", dist_label[[dist]]), list(
time = cs_col(tcol, c(0, km$time, grid), "numeric"),
surv = cs_col("Survival probability", c(1, km$surv, surv_fit), "numeric"),
strata = cs_col("Curve", c(rep("Kaplan–Meier", length(km$time) + 1), rep(lab_fit, length(grid))), "categorical",
levels = c("Kaplan–Meier", lab_fit))
), controls = list(ci = FALSE, riskTable = FALSE, censorTicks = FALSE))
}
if (length(num_preds)) {
rows_m <- seq_along(tt)
if (length(rows_m) * length(num_preds) > 5000) rows_m <- unique(round(seq(1, length(tt), length.out = max(5000 %/% length(num_preds), 2))))
charts[[length(charts) + 1]] <- cs_chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", list(
x = cs_col("Predictor value", unlist(lapply(num_preds, function(p) as.numeric(df[[p]])[rows_m])), "numeric"),
partial = cs_col("Martingale residual", rep(mart[rows_m], length(num_preds)), "numeric"),
term = cs_col("Predictor", rep(num_preds, each = length(rows_m)), "categorical", levels = num_preds)
), controls = list(smooth = TRUE))
}
rows_cs <- seq_along(tt)
if (length(rows_cs) > 5000) rows_cs <- unique(round(seq(1, length(tt), length.out = 5000)))
cs_fit <- seq(0, max(cox_snell), length.out = 61)[-1]
charts[[length(charts) + 1]] <- cs_chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", list(
time = cs_col("Cox–Snell residual", c(cox_snell[rows_cs], cs_fit), "numeric"),
event = cs_col("Event", c(as.numeric(ev[rows_cs]), rep(NA_real_, length(cs_fit))), "numeric"),
fit = cs_col("Unit exponential F(r)", c(rep(NA_real_, length(rows_cs)), -expm1(-cs_fit)), "numeric"),
family = cs_col("Series", c(rep("data", length(rows_cs)), rep("unit exponential", length(cs_fit))), "categorical",
levels = c("data", "unit exponential"))
), controls = list(paper = "exponential"))
line <- seq(0, max(tt), length.out = 101)
rel_names <- vapply(profiles, function(pf) pf$name, character(1))
charts[[length(charts) + 1]] <- cs_chart("reliability", "reliability-curve", sprintf("Fitted reliability: %s", tcol), list(
time = cs_col(tcol, rep(line, length(profiles)), "numeric"),
surv = cs_col("Reliability", unlist(lapply(profiles, function(pf) cs_life_aft_surv(dist, sum(pf$x * beta), log_scale, line))), "numeric"),
strata = cs_col("Profile", rep(rel_names, each = length(line)), "categorical", levels = rel_names)
), controls = list(mission = if (is.null(mission)) 0 else mission))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
tables <- list(list(key = "coefficients", title = "Coefficients and time ratios", 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 = paste0(sprintf("Scale σ = %s", format(signif(scale, 4))),
if (dist == "weibull") sprintf(" (Weibull shape 1/σ = %s)", format(signif(1 / scale, 4))) else "", ".")))
if (length(aic_rows)) {
tables[[length(tables) + 1]] <- list(key = "aic", title = "Distribution comparison", columns = list(
list(key = "dist", label = "Distribution", type = "string"), list(key = "loglik", label = "log L", type = "number"),
list(key = "aic", label = "AIC", type = "number")
), rows = aic_rows)
}
life_cols <- list(list(key = "profile", label = "Profile", type = "string"), list(key = "mttf", label = "Mean life", type = "number"),
list(key = "mttf_low", label = paste(pct, "CI low"), type = "number"), list(key = "mttf_high", label = paste(pct, "CI high"), type = "number"))
if (!is.null(mission)) {
life_cols <- c(life_cols, list(list(key = "mission_r", label = sprintf("R(%g)", mission), type = "number"), list(key = "mission_low", label = paste(pct, "CI low"), type = "number"),
list(key = "mission_high", label = paste(pct, "CI high"), type = "number")))
}
tables[[length(tables) + 1]] <- list(key = "life", title = "Life metrics", columns = life_cols, rows = life_rows)
if (length(blife_rows)) {
tables[[length(tables) + 1]] <- list(key = "blives", title = "B-lives", columns = list(
list(key = "profile", label = "Profile", type = "string"), list(key = "percent", label = "Percent failed", type = "number"), list(key = "life", label = "Time", type = "number"),
list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number")), rows = blife_rows)
}
cap <- function(s) paste0(toupper(substring(s, 1, 1)), substring(s, 2))
fit_rows <- list(
list(measure = "AIC", value = aic, low = NA_real_, high = NA_real_, note = "−2 log L + 2k."),
list(measure = "BIC", value = bic, low = NA_real_, high = NA_real_, note = sprintf("−2 log L + k·log(n), n = %d subjects.", length(tt))),
list(measure = "Cox–Snell residual sum", value = sum(cox_snell), low = NA_real_, high = NA_real_,
note = sprintf("Near the %d events when the model fits (exactly equal for the Weibull and exponential models).", sum(ev)))
)
if (n_pred) {
fit_rows <- c(list(list(measure = "Concordance (C, apparent)", value = conc, low = c_lo, high = c_hi,
note = sprintf("Harrell's C on the data the model was fitted to; SE %.4f (infinitesimal jackknife).", c_se))), fit_rows)
}
tables[[length(tables) + 1]] <- list(key = "fit", title = "Model fit", columns = list(
list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number"),
list(key = "note", label = "Note", type = "string")
), rows = fit_rows)
cs_publish(list(
method = "survival.parametric",
methodVersion = "1.2.0",
title = paste(cap(dist_label[[dist]]), "accelerated failure time model"),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = paste0(sprintf("%s AFT model: log L = %.2f, AIC = %.1f", cap(dist_label[[dist]]), fit$loglik[2], aic),
if (n_pred) sprintf("; likelihood-ratio χ²(%d) = %.2f, %s.", n_pred, lr, cs_fmt_p(values$lr_p)) else "."),
apa = if (n_pred) sprintf("time ratio = %s, %s CI [%s, %s], %s", cs_fmt_num(tr[2]), pct, cs_fmt_num(tr_lo[2]), cs_fmt_num(tr_hi[2]), cs_fmt_p(pv[2]))
else sprintf("log L = %s, AIC = %s", cs_fmt_num(fit$loglik[2]), cs_fmt_num(aic)),
statistics = c(list(list(key = "loglik", label = "log L", value = fit$loglik[2]), list(key = "aic", label = "AIC", value = aic),
list(key = "scale", label = "Scale σ", value = scale)),
if (n_pred) list(list(key = "lr_p", label = "Likelihood-ratio p", value = values$lr_p, format = "p"),
list(key = "concordance", label = "Concordance (C, apparent)", value = conc))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s. log T = Xβ + σW; time ratio = exp(β).", event_label)),
charts = charts,
values = values
))
time ratio = 0.99, 95% CI [0.97, 1.00], p = .078
- log L
- −1147.05
- AIC
- 2302.11
- Scale σ
- 0.7541
- Likelihood-ratio p
- .001
- Concordance (C, apparent)
- 0.6029
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Distribution fits — The Weibull model has the lowest AIC of the four distributions.
- Events per variable — 82.5 events per coefficient.
- Non-informative censoring — 63 of 228 observations are censored.
- Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
Coefficients and time ratios
| Term | β (log time) | SE | Time ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| (Intercept) | 6.657 | 0.4475 | 778.16 | 323.70 | 1870.70 | 14.875 | < .001 |
| age | −0.0123 | 0.0070 | 0.9878 | 0.9744 | 1.001 | −1.762 | .078 |
| sex: female | 0.3821 | 0.1275 | 1.465 | 1.141 | 1.881 | 2.997 | .003 |
Scale σ = 0.7541 (Weibull shape 1/σ = 1.326).
Distribution comparison
| Distribution | log L | AIC |
|---|---|---|
| Weibull | −1147.05 | 2302.11 |
| exponential | −1156.10 | 2318.20 |
| log-normal | −1158.75 | 2325.50 |
| log-logistic | −1152.90 | 2313.79 |
Life metrics
| Profile | Mean life | 95% CI low | 95% CI high |
|---|---|---|---|
| Reference profile | 332.99 | 289.30 | 383.29 |
B-lives
| Profile | Percent failed | Time | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Reference profile | 10 | 66.329 | 50.954 | 86.344 |
| Reference profile | 50 | 274.55 | 236.44 | 318.81 |
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6029 | 0.5529 | 0.6529 | Harrell's C on the data the model was fitted to; SE 0.0255 (infinitesimal jackknife). |
| AIC | 2302.11 | — | — | −2 log L + 2k. |
| BIC | 2315.83 | — | — | −2 log L + k·log(n), n = 228 subjects. |
| Cox–Snell residual sum | 165.00 | — | — | Near the 165 events when the model fits (exactly equal for the Weibull and exponential models). |
- Event: dead = true. log T = Xβ + σW; time ratio = exp(β).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Parametric survival regression (AFT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.parametric 1.2.0 · spec fda7c6254320f37b
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.errors import check_not_constant # catalog error shared with R (registry/errors.yaml)
from codesplash.stats import life as lf # MTTF, B-lives and mission reliability from the fit
from codesplash.stats import survival as sv # survreg twin (aft_fit) and Kaplan–Meier
# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "dead", "age", "sex"])
n_input = len(df)
df["dead"] = pd.Categorical(df["dead"], categories=["false", "true"]) # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["male", "female"]) # stored level order
df = df.dropna(subset=["time", "dead", "age", "sex"]) # listwise deletion over the analysis columns
df["dead"] = df["dead"].cat.remove_unused_categories()
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "dead", "age", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol = "time"
ecol = "dead"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
event_level = "true" # the event; other levels are censored
ev = (df[ecol].astype(str) == event_level).to_numpy()
event_label = f"{ecol} = {event_level}"
if not ev.any():
cs.cs_error("CS_E_NO_EVENTS", event=event_label)
# %% Design matrix (treatment contrasts against the first stored level)
preds = ["age", "sex"]
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)
# %% Accelerated failure time model
if (t <= 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="positive for a parametric model (log time)", count=int((t <= 0).sum()))
check_not_constant(t, tcol) # with one time for every row the scale of the time distribution collapses to zero
conf = 0.95
dist = "weibull"
DIST_LABEL = {"weibull": "Weibull", "exponential": "exponential", "lognormal": "log-normal", "loglogistic": "log-logistic"}
X1 = np.column_stack([np.ones(len(t)), X])
fit = sv.aft_fit(t, ev, X1, dist) # survreg(Surv(time, event) ~ predictors, dist = dist)
null = sv.aft_fit(t, ev, X1[:, :1], dist)
theta, cov = fit["theta"], fit["cov"]
p = X1.shape[1]
beta, se_b = theta[:p], np.sqrt(np.diag(cov)[:p])
fixed = dist == "exponential"
log_scale = 0.0 if fixed else float(theta[p])
log_scale_se = None if fixed else float(math.sqrt(cov[p, p]))
scale = math.exp(log_scale)
k = p + (0 if fixed else 1)
aic = -2 * fit["loglik"] + 2 * k
q = stats.norm.ppf(1 - (1 - conf) / 2)
z = beta / se_b
pv = 2 * stats.norm.sf(np.abs(z))
tr, tr_lo, tr_hi = np.exp(beta), np.exp(beta - q * se_b), np.exp(beta + q * se_b)
n_pred = p - 1
lr = 2 * (fit["loglik"] - null["loglik"])
w50 = {"weibull": math.log(math.log(2)), "exponential": math.log(math.log(2))}.get(dist, 0.0) # median of the error term
bic = -2 * fit["loglik"] + k * math.log(len(t)) # n = subjects, as R's BIC() for survreg
lp = X1 @ beta
if n_pred:
cvar = sv.concordance_var(t, ev, -lp) # a longer predicted time is a lower risk, as survival::concordance() for survreg
conc, c_se = cvar["concordance"], cvar["se"]
c_lo, c_hi = (max(0.0, conc - q * c_se), min(1.0, conc + q * c_se)) if np.isfinite(conc) and np.isfinite(c_se) else (None, None)
else:
conc = c_se = c_lo = c_hi = None
zr = (np.log(t) - lp) / scale
cox_snell = {"weibull": np.exp(zr), "exponential": np.exp(zr), "lognormal": -stats.norm.logsf(zr),
"loglogistic": np.maximum(zr, 0) + np.log1p(np.exp(-np.abs(zr)))}[dist] # −log S(t | x): unit exponential if the model fits
mart = ev - cox_snell # martingale residuals of the parametric model
num_preds = [pname for pname, idx in zip(preds, terms) if len(idx) == 1 and not isinstance(df[pname].dtype, pd.CategoricalDtype)
and not pd.api.types.is_bool_dtype(df[pname]) and df[pname].nunique() > 2]
values = {
"n": float(len(t)), "events": float(ev.sum()), "dist_label": DIST_LABEL[dist], "loglik": fit["loglik"], "loglik0": null["loglik"],
"lr_chisq": lr if n_pred else None, "lr_df": float(n_pred) if n_pred else None,
"lr_p": float(stats.chi2.sf(lr, n_pred)) if n_pred else None, "aic": aic,
"scale": scale, "log_scale": log_scale, "log_scale_se": log_scale_se,
"shape": 1 / scale if dist in ("weibull", "exponential") else None,
"intercept": float(beta[0]), "intercept_se": float(se_b[0]),
"median_time": None if n_pred else math.exp(beta[0] + scale * w50),
"coef_1_label": labels[0] if n_pred else None, "tr_1": float(tr[1]) if n_pred else None,
"tr_1_low": float(tr_lo[1]) if n_pred else None, "tr_1_high": float(tr_hi[1]) if n_pred else None,
"p_1": float(pv[1]) if n_pred else None, "event_label": event_label,
"bic": float(bic), "concordance": conc, "concordance_se": c_se, "concordance_low": c_lo, "concordance_high": c_hi,
"cox_snell_sum": float(cox_snell.sum()),
}
coef_rows = []
for i, lab in enumerate(["(Intercept)"] + labels):
for key, val in (("coef", beta[i]), ("se", se_b[i]), ("tr", tr[i]), ("tr_low", tr_lo[i]), ("tr_high", tr_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_b[i]), "tr": float(tr[i]), "tr_low": float(tr_lo[i]),
"tr_high": float(tr_hi[i]), "z": float(z[i]), "p": float(pv[i])})
# %% Distribution comparison (AIC)
aic_rows = []
if True:
for d in ("weibull", "exponential", "lognormal", "loglogistic"):
f = fit if d == dist else sv.aft_fit(t, ev, X1, d)
a = -2 * f["loglik"] + 2 * (p + (0 if d == "exponential" else 1))
values[f"aic[{d}]"] = a
aic_rows.append({"dist": DIST_LABEL[d], "loglik": f["loglik"], "aic": a})
best = min(aic_rows, key=lambda r: r["aic"])
gap = aic - best["aic"]
dist_check = {"key": "distribution", "label": "Distribution fits", "status": "warn" if gap > 2 else "pass",
"detail": f"The {best['dist']} model has the lowest AIC ({best['aic']:.1f}); the {DIST_LABEL[dist]} model is {gap:.1f} higher."
if gap > 0 else f"The {DIST_LABEL[dist]} model has the lowest AIC of the four distributions."}
else:
dist_check = {"key": "distribution", "label": "Distribution fits", "status": "info", "detail": "Distributions were not compared."}
# %% Life metrics: one row per group for a single categorical predictor; else the reference profile
mission = None # reliability is reported at this time
b_lives = [10, 50, ]
profiles = [("All units", np.array([1.0]))]
single_cat = None
if n_pred:
is_cat = np.zeros(n_pred, dtype=bool)
for pname, idx in zip(preds, terms):
is_cat[idx] = isinstance(df[pname].dtype, pd.CategoricalDtype)
means = np.concatenate(([1.0], np.where(is_cat, 0.0, X.mean(axis=0))))
profiles = [("Reference profile", means)]
if len(preds) == 1 and isinstance(df[preds[0]].dtype, pd.CategoricalDtype):
single_cat = preds[0]
lv = [str(x) for x in df[single_cat].cat.categories]
profiles = [(lv[0], np.array([1.0] + [0.0] * n_pred))] + [(lv[i + 1], np.array([1.0] + [1.0 if j == i else 0.0 for j in range(n_pred)])) for i in range(n_pred)]
cov_life = cov[: p, : p] if fixed else cov
life_rows = []
blife_rows = []
values.update({"mission_time": mission, "life_profile": "group" if single_cat else ("reference" if n_pred else "all")})
for name, xrow in profiles:
lr_ = lf.aft_life_row(dist, xrow, beta, log_scale, cov_life, mission, b_lives, conf)
values[f"mttf[{name}]"], values[f"mttf_low[{name}]"], values[f"mttf_high[{name}]"] = lr_["mttf"], lr_["mttf_low"], lr_["mttf_high"]
life_rows.append({"profile": name, **{k: lr_[k] if np.isfinite(lr_[k]) else None for k in ("mttf", "mttf_low", "mttf_high")}}) # a log-logistic with scale ≥ 1 has no mean
if mission is not None:
values[f"mission_r[{name}]"], values[f"mission_low[{name}]"], values[f"mission_high[{name}]"] = lr_["mission_r"], lr_["mission_low"], lr_["mission_high"]
life_rows[-1].update({"mission_r": lr_["mission_r"], "mission_low": lr_["mission_low"], "mission_high": lr_["mission_high"]})
for b in lr_["blives"]:
key = f"{b['percent']:g}@{name}"
values[f"blife[{key}]"], values[f"blife_low[{key}]"], values[f"blife_high[{key}]"] = b["life"], b["low"], b["high"]
blife_rows.append({"profile": name, "percent": b["percent"], "life": b["life"], "low": b["low"], "high": b["high"]})
# %% Common shape across groups (likelihood-ratio test against separate shapes)
values.update({"shape_lr": None, "shape_lr_df": None, "shape_lr_p": None})
shape_check = None
if True and single_cat and dist != "exponential":
gv_ = df[single_cat].astype(str).to_numpy()
groups_ = [str(x) for x in df[single_cat].cat.categories]
if all(ev[gv_ == lv].sum() >= 2 for lv in groups_):
ll_sep = sum(sv.aft_fit(t[gv_ == lv], ev[gv_ == lv], np.ones((int((gv_ == lv).sum()), 1)), dist)["loglik"] for lv in groups_)
lr_shape = max(0.0, 2 * (ll_sep - fit["loglik"]))
df_shape = float(len(groups_) - 1)
p_shape = float(stats.chi2.sf(lr_shape, df_shape))
values.update({"shape_lr": lr_shape, "shape_lr_df": df_shape, "shape_lr_p": p_shape})
shape_check = {"key": "common_shape", "label": "Common shape", "status": "warn" if p_shape < 0.05 else "pass", "statistic": lr_shape, "p": p_shape,
"detail": f"Likelihood-ratio test of separate shapes by {single_cat}: χ²({df_shape:.0f}) = {lr_shape:.2f}, {cs.fmt_p(p_shape)}" + ("; the time ratio changes with time." if p_shape < 0.05 else ".")}
epv = float(ev.sum()) / max(n_pred, 1)
assumptions = [dist_check,
{"key": "events_per_variable", "label": "Events per variable", "status": "warn" if n_pred and epv < 10 else "pass",
"detail": f"{epv:.1f} events per coefficient." if n_pred else "No covariates."},
{"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} observations are censored."}]
if shape_check:
assumptions.insert(2, shape_check)
assumptions.append({"key": "functional_form", "label": "Functional form", "status": "info",
"detail": (f"Not tested: look at the martingale residuals against {', '.join(num_preds)}. A smooth that bends away from zero"
" suggests a transformation or a spline." if num_preds else "No numeric predictor with more than two values to check.")})
# %% Charts
charts = []
if n_pred:
charts.append(cs.chart("tr", "forest", "Time ratios", {
"label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Time ratio", tr[1:], "numeric"),
"low": cs.col("lower", tr_lo[1:], "numeric"), "high": cs.col("upper", tr_hi[1:], "numeric"),
}, controls={"reference": 1, "log": True}))
else:
km = sv.km(t, ev, conf_type="log-log")
grid = np.linspace(0, float(t.max()), 101)
zz = (np.log(np.maximum(grid, 1e-300)) - beta[0]) / scale
surv_fit = {"weibull": np.exp(-np.exp(zz)), "exponential": np.exp(-np.exp(zz)), "lognormal": stats.norm.sf(zz),
"loglogistic": 1 / (1 + np.exp(zz))}[dist]
surv_fit[0] = 1.0
charts.append(cs.chart("fit", "km-curve", f"Kaplan–Meier and fitted {DIST_LABEL[dist]} survival", {
"time": cs.col(tcol, [0.0] + km["time"].tolist() + grid.tolist(), "numeric"),
"surv": cs.col("Survival probability", [1.0] + km["surv"].tolist() + surv_fit.tolist(), "numeric"),
"strata": cs.col("Curve", ["Kaplan–Meier"] * (len(km["time"]) + 1) + [f"Fitted {DIST_LABEL[dist]}"] * len(grid), "categorical",
levels=["Kaplan–Meier", f"Fitted {DIST_LABEL[dist]}"]),
}, controls={"ci": False, "riskTable": False, "censorTicks": False}))
if num_preds:
rows_m = np.arange(len(t))
if len(rows_m) * len(num_preds) > 5000:
rows_m = np.unique(np.round(np.linspace(0, len(t) - 1, max(5000 // len(num_preds), 2))).astype(int))
charts.append(cs.chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", {
"x": cs.col("Predictor value", np.concatenate([df[pname].to_numpy(dtype=float)[rows_m] for pname in num_preds]), "numeric"),
"partial": cs.col("Martingale residual", np.tile(mart[rows_m], len(num_preds)), "numeric"),
"term": cs.col("Predictor", [pname for pname in num_preds for _ in rows_m], "categorical", levels=num_preds),
}, controls={"smooth": True}))
rows_cs = np.arange(len(t))
if len(rows_cs) > 5000:
rows_cs = np.unique(np.round(np.linspace(0, len(t) - 1, 5000)).astype(int))
cs_fit = np.linspace(0.0, float(cox_snell.max()), 61)[1:]
charts.append(cs.chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", {
"time": cs.col("Cox–Snell residual", np.concatenate((cox_snell[rows_cs], cs_fit)), "numeric"),
"event": cs.col("Event", np.concatenate((ev[rows_cs].astype(float), np.full(cs_fit.size, np.nan))), "numeric"),
"fit": cs.col("Unit exponential F(r)", np.concatenate((np.full(rows_cs.size, np.nan), -np.expm1(-cs_fit))), "numeric"),
"family": cs.col("Series", ["data"] * rows_cs.size + ["unit exponential"] * cs_fit.size, "categorical", levels=["data", "unit exponential"]),
}, controls={"paper": "exponential"}))
line = np.linspace(0.0, float(t.max()), 101)
rel_names = [name for name, _ in profiles]
charts.append(cs.chart("reliability", "reliability-curve", f"Fitted reliability: {tcol}", {
"time": cs.col(tcol, np.tile(line, len(profiles)), "numeric"),
"surv": cs.col("Reliability", np.concatenate([lf.aft_surv(dist, float(xrow @ beta), log_scale, line) for _, xrow in profiles]), "numeric"),
"strata": cs.col("Profile", [nm for nm in rel_names for _ in line], "categorical", levels=rel_names),
}, controls={"mission": mission if mission is not None else 0}))
# %% Result
pct = f"{conf:.0%}"
tables = [{"key": "coefficients", "title": "Coefficients and time ratios", "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 σ = {scale:.4g}" + (f" (Weibull shape 1/σ = {1 / scale:.4g})" if dist == "weibull" else "") + "."}]
if aic_rows:
tables.append({"key": "aic", "title": "Distribution comparison", "columns": [
{"key": "dist", "label": "Distribution", "type": "string"}, {"key": "loglik", "label": "log L", "type": "number"},
{"key": "aic", "label": "AIC", "type": "number"},
], "rows": aic_rows})
life_cols = [{"key": "profile", "label": "Profile", "type": "string"}, {"key": "mttf", "label": "Mean life", "type": "number"},
{"key": "mttf_low", "label": f"{pct} CI low", "type": "number"}, {"key": "mttf_high", "label": f"{pct} CI high", "type": "number"}]
if mission is not None:
life_cols += [{"key": "mission_r", "label": f"R({mission:g})", "type": "number"}, {"key": "mission_low", "label": f"{pct} CI low", "type": "number"},
{"key": "mission_high", "label": f"{pct} CI high", "type": "number"}]
tables.append({"key": "life", "title": "Life metrics", "columns": life_cols, "rows": life_rows})
if blife_rows:
tables.append({"key": "blives", "title": "B-lives", "columns": [
{"key": "profile", "label": "Profile", "type": "string"}, {"key": "percent", "label": "Percent failed", "type": "number"}, {"key": "life", "label": "Time", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"}], "rows": blife_rows})
fit_rows = [{"measure": "AIC", "value": float(aic), "low": None, "high": None, "note": "−2 log L + 2k."},
{"measure": "BIC", "value": float(bic), "low": None, "high": None, "note": f"−2 log L + k·log(n), n = {len(t)} subjects."},
{"measure": "Cox–Snell residual sum", "value": float(cox_snell.sum()), "low": None, "high": None,
"note": f"Near the {int(ev.sum())} events when the model fits (exactly equal for the Weibull and exponential models)."}]
if n_pred:
fit_rows.insert(0, {"measure": "Concordance (C, apparent)", "value": conc, "low": c_lo, "high": c_hi,
"note": f"Harrell's C on the data the model was fitted to; SE {c_se:.4f} (infinitesimal jackknife)."})
tables.append({"key": "fit", "title": "Model fit", "columns": [
{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
{"key": "note", "label": "Note", "type": "string"},
], "rows": fit_rows})
cs.publish({
"method": "survival.parametric",
"methodVersion": "1.2.0",
"title": f"{DIST_LABEL[dist].capitalize()} accelerated failure time model",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(t)),
"summary": f"{DIST_LABEL[dist].capitalize()} AFT model: log L = {fit['loglik']:.2f}, AIC = {aic:.1f}"
+ (f"; likelihood-ratio χ²({n_pred}) = {lr:.2f}, {cs.fmt_p(values['lr_p'])}." if n_pred else "."),
"apa": (f"time ratio = {cs.fmt_num(tr[1])}, {pct} CI [{cs.fmt_num(tr_lo[1])}, {cs.fmt_num(tr_hi[1])}], {cs.fmt_p(pv[1])}"
if n_pred else f"log L = {cs.fmt_num(fit['loglik'])}, AIC = {cs.fmt_num(aic)}"),
"statistics": [{"key": "loglik", "label": "log L", "value": fit["loglik"]}, {"key": "aic", "label": "AIC", "value": aic},
{"key": "scale", "label": "Scale σ", "value": scale}]
+ ([{"key": "lr_p", "label": "Likelihood-ratio p", "value": values["lr_p"], "format": "p"},
{"key": "concordance", "label": "Concordance (C, apparent)", "value": conc}] if n_pred else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. log T = Xβ + σW; time ratio = exp(β)."],
"charts": charts,
"values": values,
})
With Compare distributions (AIC) on, the card ranks the candidates by AIC, so you can see whether Weibull is doing well or only being used out of habit. A low AIC among poor candidates isn't proof of fit, so compare the fitted curve with Kaplan–Meier too.
Read a time ratio
CheckpointCheck yourself
A log-normal model gives a time ratio of 1.5 for a treatment. What does it mean?
Show the answer
Answer: b
Time ratios multiply time. A time ratio above 1 is good news when the event is bad, and a hazard ratio above 1 is the reverse.
Connect it to Cox
ReadFor a Weibull model only, hazard ratios and time ratios are two views of the same effect:
For age, , close to the Cox model's 1.017. A longer time means a lower hazard, hence the minus sign: a time ratio below 1 becomes a hazard ratio above 1.
When to pay for the assumption
ReadA parametric model earns its assumption when you need to:
- talk about time directly, or extrapolate past follow-up (with caution);
- estimate reliability quantities, such as the time by which 10% have failed (the B-lives and Mission time options);
- work with small samples that fit the distribution, or with interval-censored data.
Otherwise, Cox's freedom from a baseline assumption is hard to beat.
Would you extrapolate?
ReflectThink of a number that reaches past your follow-up, such as lifetime value or 10-year survival. How much of it comes from the data, and how much from the distribution you chose? What would you show your reader?
Same model, two dialects
Readimport pandas as pd
from lifelines import WeibullAFTFitter
df = pd.read_csv("lung.csv")
data = pd.DataFrame({
"time": df["time"], "dead": df["dead"], "age": df["age"],
"female": (df["sex"] == "female").astype(int),
})
aft = WeibullAFTFitter().fit(data, "time", "dead")
print(aft.summary[["exp(coef)", "p"]])
# lifelines reports log(rho) under rho_: exp() of it is the Weibull shapelibrary(survival)
df <- read.csv("lung.csv")
df$sex <- relevel(factor(df$sex), ref = "male")
fit <- survreg(Surv(time, dead == "true") ~ age + sex, data = df, dist = "weibull")
exp(coef(fit)) # time ratios
1 / fit$scale # survreg's scale is 1 / shapeCheck your understanding
CheckpointCheck yourself
A Weibull model has shape 2 and a time ratio of 2 for a treatment. What is the equivalent hazard ratio?
Show the answer
Answer: 0.25
.
Check yourself
What is the main risk in extrapolating a Weibull survival curve far past follow-up?
Show the answer
Answer: b
Distributions that fit equally well inside the follow-up can differ widely beyond it. Compare several, and say that the result rests on assumption.
Recap
Recap- Accelerated failure time models stretch time, and report time ratios.
- A Weibull shape above 1 means rising risk, below 1 falling risk.
- For Weibull only, .
- Pay for the assumption when you need statements about time or reliability.
Concepts in this lesson