Skip to content

Reliability numbers: B-lives, MTTF and missions

Turn a fitted lifetime model into figures people act on, compare two suppliers, and see what forcing a constant failure rate costs.

Applied ~13 min10 steps

What runs in CodeSplash

You will be able to

  • Define a B-life, MTTF and reliability at a mission time
  • Explain why the MTTF is not a typical life
  • Compare groups with a time ratio under a common shape

Read first

01

How long does it last?

Predict

Predict first

A fitted model for the same devices gives a mean time to failure, the MTTFMean time to failureThe average lifetime under a fitted distribution; it depends heavily on the tail, far beyond most observed failures., of 2,976 hours.

By that time, roughly what share of the devices have failed?

About half have failedFar fewer than half have failedFar more than half have failed
Reveal

Far more than half. The median is 1,433 hours, so half are gone at less than half of the MTTF. A few long survivors pull the mean far out, and with censoring the fit has to guess how far.

02

Three figures

Read
FigureAnswersWeibull formula
B-lifeB-lifeThe time by which a stated percent of units has failed; B10 is the age at which 10% are gone. BpB_pBy when has pp% failed?η [−ln⁡(1−p/100)]1/β\eta\,[-\ln(1-p/100)]^{1/\beta}
ReliabilityReliability functionR(t) is the share of units still working at age t; the reliability at a mission time answers how many will finish the job. R(t)R(t)What share lasts to tt?exp⁡[−(t/η)β]\exp[-(t/\eta)^\beta]
MTTFWhat is the mean life?η Γ(1+1/β)\eta\,\Gamma(1 + 1/\beta)

Here β\beta is the shape and η\eta the scale. Choose the figure that fits the decision: a warranty cares about a B-life, a mission about R(t)R(t).

03

Work one out

Predict

Predict first

A Weibull has β=2\beta = 2 and η=1000\eta = 1000 hours. Estimate its B10 life, the time by which 10% have failed.

Make your guess between 0 and 1000 hours, then reveal.

Reveal

B10=1000×[−ln⁡0.9]1/2=1000×0.3246≈325B_{10} = 1000 \times [-\ln 0.9]^{1/2} = 1000 \times 0.3246 \approx 325 hours. The 10% point arrives at about a third of the scale.

04

Read a mission

Read

With a mission of 500 hours, the best-fitting model for the devices gives a reliability of 0.85, 95% CI 0.78 to 0.89.

So a unit is about that likely to complete the mission.

That interval only reflects sampling error in this family. It doesn't cover the choice of family, so compare the figure across families, and be careful with mission times beyond your longest observed failures.

05

Two suppliers

Read
Weibull accelerated failure time modelRecorded · Python and R agreeRecorded 2026-11-17 · 75 values compared
R

time ratio = 1.95, 95% CI [1.30, 2.91], p = .001

log L
−511.84
AIC
1029.68
Scale σ
0.7246
Likelihood-ratio p
< .001
Concordance (C, apparent)
0.6110

Plots

Time ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Time ratioupperTermlower
1.9492.912supplier: B1.304
Cox–Snell residuals on exponential paperDo these failures fall on a straight line on this family's probability paper?
View data
EventSeriesUnit exponential F(r)Cox–Snell residual
1data—0.2836
1data—0.3343
1data—0.5389
0data—0.1056
0data—0.2946
0data—0.5370
0data—0.2758
1data—0.0740
0data—0.1968
0data—0.6525
1data—1.529
0data—0.6525
1data—1.238
1data—0.1844
1data—0.0775
1data—0.4771
0data—0.3195
0data—0.4381
0data—1.639
1data—0.1025
1data—0.8678
0data—0.3584
0data—1.639
0data—0.2131
1data—0.9300
0data—0.2411
0data—0.2088
1data—0.4897
1data—0.3269
0data—0.6525
1data—1.069
1data—0.3257
0data—1.639
0data—0.0853
1data—0.6435
0data—0.1947
0data—1.639
0data—0.1559
0data—1.639
0data—0.4768
1data—0.0790
1data—0.0281
1data—0.5781
0data—0.6525
1data—0.1075
1data—0.0564
1data—0.4896
1data—0.0765
1data—0.3461
0data—0.6525
1data—0.6556
1data—0.2577
0data—1.639
1data—0.1057
1data—0.7294
0data—0.3483
1data—0.6760
1data—0.1656
1data—0.5404
0data—0.5737

First 60 of 180 rows.

Fitted reliability: hoursWhat share of units is still working at each age?
View data
ProfileReliabilityhours
A10
A0.997220
A0.992640
A0.987160
A0.980980
A0.9741100
A0.9668120
A0.9591140
A0.9510160
A0.9426180
A0.9340200
A0.9250220
A0.9159240
A0.9065260
A0.8970280
A0.8873300
A0.8775320
A0.8675340
A0.8575360
A0.8473380
A0.8371400
A0.8268420
A0.8164440
A0.8060460
A0.7956480
A0.7851500
A0.7746520
A0.7641540
A0.7536560
A0.7431580
A0.7326600
A0.7221620
A0.7117640
A0.7012660
A0.6909680
A0.6805700
A0.6702720
A0.6599740
A0.6497760
A0.6396780
A0.6295800
A0.6195820
A0.6095840
A0.5997860
A0.5899880
A0.5801900
A0.5705920
A0.5609940
A0.5514960
A0.5421980
A0.53271,000
A0.52351,020
A0.51441,040
A0.50541,060
A0.49651,080
A0.48761,100
A0.47891,120
A0.47021,140
A0.46171,160
A0.45331,180

First 60 of 202 rows.

Assumptions

  • Distribution fits — The log-normal model has the lowest AIC (1029.7); the Weibull model is 0.0 higher.
  • Events per variable — 60.0 events per coefficient.
  • Common shape — Likelihood-ratio test of separate shapes by supplier: χ²(1) = 0.26, p = .613.
  • Non-informative censoring — 60 of 120 observations are censored.
  • Functional form — No numeric predictor with more than two values to check.

Coefficients and time ratios

Termβ (log time)SETime ratio95% CI low95% CI highzp
(Intercept)7.2430.11631398.141113.091756.1862.262< .001
supplier: B0.66740.20491.9491.3042.9123.257.001

Scale σ = 0.7246 (Weibull shape 1/σ = 1.38).

Distribution comparison

Distributionlog LAIC
Weibull−511.841029.68
exponential−515.631035.25
log-normal−511.841029.68
log-logistic−511.901029.81

Life metrics

ProfileMean life95% CI low95% CI highR(500)95% CI low95% CI high
A1277.251011.571612.700.78510.69150.8533
B2489.501749.983541.520.90820.84860.9451

B-lives

ProfilePercent failedTime95% CI low95% CI high
A10273.75182.88409.78
A501072.03850.891350.65
B10533.57365.51778.90
B502089.511518.802874.66

Model fit

MeasureValue95% CI low95% CI highNote
Concordance (C, apparent)0.61100.54640.6755Harrell's C on the data the model was fitted to; SE 0.0330 (infinitesimal jackknife).
AIC1029.68——−2 log L + 2k.
BIC1038.05——−2 log L + k·log(n), n = 120 subjects.
Cox–Snell residual sum60——Near the 60 events when the model fits (exactly equal for the Weibull and exponential models).
  • Event: failed = 1. 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 45b4a81a2def8ac2
# Dataset: life_devices_sim (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/life_devices_sim.parquet", col_select = c("hours", "failed", "supplier")))
n_input <- nrow(df)
df[["supplier"]] <- factor(df[["supplier"]], levels = c("A", "B"))  # stored level order
df <- df[stats::complete.cases(df[c("hours", "failed", "supplier")]), , 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("hours", "failed", "supplier"))  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol <- "hours"
ecol <- "failed"
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))
codes <- sort(unique(df[[ecol]]))
if (all(codes %in% c(0, 1))) {
  event_code <- 1  # 0 = censored, 1 = event
} else if (all(codes %in% c(1, 2))) {
  event_code <- 2  # 1 = censored, 2 = event (survival::Surv convention)
} else {
  stop(sprintf("%s must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column", ecol))
}
ev <- df[[ecol]] == event_code
event_label <- sprintf("%s = %s", ecol, format(event_code))
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)

# %% Predictors (treatment contrasts against the first stored level)
preds <- c("supplier")
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 <- 500  # 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
))
Python

time ratio = 1.95, 95% CI [1.30, 2.91], p = .001

log L
−511.84
AIC
1029.68
Scale σ
0.7246
Likelihood-ratio p
< .001
Concordance (C, apparent)
0.6110

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Distribution fits — The log-normal model has the lowest AIC (1029.7); the Weibull model is 0.0 higher.
  • Events per variable — 60.0 events per coefficient.
  • Common shape — Likelihood-ratio test of separate shapes by supplier: χ²(1) = 0.26, p = .613.
  • Non-informative censoring — 60 of 120 observations are censored.
  • Functional form — No numeric predictor with more than two values to check.

Coefficients and time ratios

Termβ (log time)SETime ratio95% CI low95% CI highzp
(Intercept)7.2430.11631398.141113.091756.1862.262< .001
supplier: B0.66740.20491.9491.3042.9123.257.001

Scale σ = 0.7246 (Weibull shape 1/σ = 1.38).

Distribution comparison

Distributionlog LAIC
Weibull−511.841029.68
exponential−515.631035.25
log-normal−511.841029.68
log-logistic−511.901029.81

Life metrics

ProfileMean life95% CI low95% CI highR(500)95% CI low95% CI high
A1277.251011.571612.700.78510.69150.8533
B2489.501749.983541.520.90820.84860.9451

B-lives

ProfilePercent failedTime95% CI low95% CI high
A10273.75182.88409.78
A501072.03850.891350.65
B10533.57365.51778.90
B502089.511518.802874.66

Model fit

MeasureValue95% CI low95% CI highNote
Concordance (C, apparent)0.61100.54640.6755Harrell's C on the data the model was fitted to; SE 0.0330 (infinitesimal jackknife).
AIC1029.68——−2 log L + 2k.
BIC1038.05——−2 log L + k·log(n), n = 120 subjects.
Cox–Snell residual sum60.000——Near the 60 events when the model fits (exactly equal for the Weibull and exponential models).
  • Event: failed = 1. 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 45b4a81a2def8ac2
# Dataset: life_devices_sim (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/life_devices_sim.parquet", columns=["hours", "failed", "supplier"])
n_input = len(df)
df["supplier"] = pd.Categorical(df["supplier"], categories=["A", "B"])  # stored level order
df = df.dropna(subset=["hours", "failed", "supplier"])  # listwise deletion over the analysis columns
df["supplier"] = df["supplier"].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, ["hours", "failed", "supplier"])  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol = "hours"
ecol = "failed"
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()))
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)

# %% Design matrix (treatment contrasts against the first stored level)
preds = ["supplier"]
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 = 500  # 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,
})

An accelerated failure time model gives a time ratio. Supplier B's lives are 1.95 times supplier A's, 95% CI 1.30 to 2.91, p = .001.

That comparison assumes both suppliers share one shape. The card tests that: p = .613, compatible with a common shape.

06

What a constant rate costs

Predict

Predict first

The Weibull shape on these data is 1.38, above 1, so the failure rate rises.

You refit with an exponential, forcing the shape to 1. What happens to supplier B's time ratio?

The same time ratioA larger time ratioA smaller time ratio
Reveal

It grows: 2.38 against 1.95. With a smaller shape, the same difference in survival takes a larger stretch in time. AIC prefers the Weibull: 1029.7 against 1035.3.

07

From figure to decision

Reflect

Your team asks for one number for a warranty. You could give the MTTF, the B10 or RR at the warranty length.

Which would you choose, and which interval goes with it? What would you say about how far past your data that figure reaches?

08

Check your understanding

Checkpoint

Check yourself

A Weibull has β=2\beta = 2, η=1000\eta = 1000. At what time is R(t)=e−0.1R(t) = e^{-0.1}? Use R(t)=exp⁡[−(t/η)β]R(t) = \exp[-(t/\eta)^\beta], and give one decimal.

Show the answer

Answer: 316.2

(t/1000)2=0.1(t/1000)^2 = 0.1, so t=10000.1≈316.2t = 1000\sqrt{0.1} \approx 316.2 hours.

Check yourself

A customer needs a part to survive 2,000 hours in the field. Which figure answers that?

Show the answer

Answer: c

The mission reliability answers the question directly. The MTTF can be far past most units' lives and says little about one mission.

Check yourself

A time ratio of 2 for supplier B, with a 95% CI that excludes 1, says what?

Show the answer

Answer: b

In an accelerated failure time model, a time ratio stretches the whole lifetime distribution. It isn't a hazard ratio, unless the model is exponential.

09

Do it in CodeSplash

In the app

In Analyze, set Mission time and B-lives (percent) on the parametric survival method, and add a group to compare. The Quality & DoE studio chains these steps in its life-data flow.

This script takes the Weibull shape and scale fitted to these devices and gives each figure. The B10, MTTF and reliability at 500 hours match the bearings-weibull-life example.

Python
import numpy as np
from scipy.special import gamma

shape, scale = 1.34185, 1919.10

b10 = scale * (-np.log(1 - 0.10)) ** (1 / shape)
mttf = scale * gamma(1 + 1 / shape)
r500 = np.exp(-((500 / scale) ** shape))
print(b10, mttf, r500)
R
shape <- 1.34185; scale <- 1919.10

b10 <- scale * (-log(1 - 0.10))^(1 / shape)
mttf <- scale * gamma(1 + 1 / shape)
r500 <- exp(-(500 / scale)^shape)
c(b10, mttf, r500)
10

Recap

Recap
  • A B-life and a mission reliability answer most reliability questions better than the MTTF.
  • Lifetimes are skewed, so the MTTF can sit far past the median.
  • A time ratio compares groups under a common shape: test that assumption.
  • Forcing a constant rate changes the comparison, and intervals don't cover the choice of family.

Concepts in this lesson