Wear-out, chance failures and comparing suppliers
Read the failure rate's shape, test for a constant rate with a battery, and compare groups with a life model that shares one shape.
What runs in CodeSplash
- Exponentiality tests (battery) Verified in Python and R
- Parametric survival regression (AFT) Verified in Python and R
You will be able to
- Connect a Weibull shape to rising, constant or falling failure rates
- Read an exponentiality battery as a pattern, and not as thirty separate verdicts
- Compare two groups with a time ratio, and test the common-shape assumption
Read first
Why the failure rate's shape matters
ReadThe hazardHazard rateThe failure rate among units still working at a given age. Rising means wear-out, falling means early failures, flat means random failures. is the current risk of failing, for a unit still working. Its shape decides what you do:
| Hazard | What it suggests | Action |
|---|---|---|
| Falling | Early failures, from defects | Burn-in, screening |
| Constant | Chance failures | Spares; replacing early doesn't help |
| Rising | Wear-out | Preventive replacement |
A WeibullWeibull distributionA lifetime distribution whose shape says whether risk falls (below 1), holds (1) or rises (above 1) with time. shape below 1 means a falling hazard, 1 means constant, and above 1 means rising.
Shape it yourself
ExploreFExplorable · From hazard to survival
How does the moment-to-moment risk build up into a survival curve?
What share of group A is still event-free at this time?
Below 1 risk falls with time; above 1 it rises.
Hazard: risk at each moment
Survival: still event-free
Commit your prediction above to see the result
Make your prediction to see the result.
Change the hazard's shape, and watch the survival curve respond. Could two very different hazards produce survival curves that look alike?
Two products
PredictPredict first
Ball bearings and air-conditioning units have Weibull shapes of 2.10 and 0.895. What do these suggest?
Reveal
Bearings wear out. For air conditioners, the shape is slightly below 1, and the likelihood-ratio test of Weibull against exponential gives p = .371: compatible with a constant rate. For bearings, the same test gives p < .001.
Test for a constant rate
In the appExponential lifetimes have a constant failure rate. The method runs a battery of exponentialityExponentialityLifetimes are exponential when the failure rate is constant, so a working unit is as good as new at any age. tests, with Monte Carlo p-values.
Cox–Oakes = 32.50, p = .005
- Mean life
- 91.359
- Failure rate
- 0.0109
- Tests rejecting
- 30
- p, adjusted for the battery
- .015
- Tests run
- 30
Plots
View data
| x |
|---|
| 81.618 |
| 118.31 |
| 162.25 |
| 55.913 |
| 80.387 |
| 146.57 |
| 132.70 |
| 108.41 |
| 86.288 |
| 142.56 |
| 43.498 |
| 148.57 |
| 106.92 |
| 105.26 |
| 90.330 |
| 59.016 |
| 74.441 |
| 39.637 |
| 78.563 |
| 103.15 |
| 88.313 |
| 53.098 |
| 121.04 |
| 96.064 |
| 173.49 |
| 79.150 |
| 100.95 |
| 45.178 |
| 112.42 |
| 87.843 |
| 101.18 |
| 63.476 |
| 15.392 |
| 162.06 |
| 46.503 |
| 64.622 |
| 75.189 |
| 42.630 |
| 49.751 |
| 111.60 |
View data
| Series | Fitted F(t) | x |
|---|---|---|
| data | — | 81.618 |
| data | — | 118.31 |
| data | — | 162.25 |
| data | — | 55.913 |
| data | — | 80.387 |
| data | — | 146.57 |
| data | — | 132.70 |
| data | — | 108.41 |
| data | — | 86.288 |
| data | — | 142.56 |
| data | — | 43.498 |
| data | — | 148.57 |
| data | — | 106.92 |
| data | — | 105.26 |
| data | — | 90.330 |
| data | — | 59.016 |
| data | — | 74.441 |
| data | — | 39.637 |
| data | — | 78.563 |
| data | — | 103.15 |
| data | — | 88.313 |
| data | — | 53.098 |
| data | — | 121.04 |
| data | — | 96.064 |
| data | — | 173.49 |
| data | — | 79.150 |
| data | — | 100.95 |
| data | — | 45.178 |
| data | — | 112.42 |
| data | — | 87.843 |
| data | — | 101.18 |
| data | — | 63.476 |
| data | — | 15.392 |
| data | — | 162.06 |
| data | — | 46.503 |
| data | — | 64.622 |
| data | — | 75.189 |
| data | — | 42.630 |
| data | — | 49.751 |
| data | — | 111.60 |
| exponential | 0.1551 | 15.392 |
| exponential | 0.1795 | 18.072 |
| exponential | 0.2032 | 20.751 |
| exponential | 0.2262 | 23.431 |
| exponential | 0.2486 | 26.110 |
| exponential | 0.2703 | 28.790 |
| exponential | 0.2914 | 31.469 |
| exponential | 0.3119 | 34.149 |
| exponential | 0.3318 | 36.829 |
| exponential | 0.3511 | 39.508 |
| exponential | 0.3698 | 42.188 |
| exponential | 0.3881 | 44.867 |
| exponential | 0.4057 | 47.547 |
| exponential | 0.4229 | 50.226 |
| exponential | 0.4396 | 52.906 |
| exponential | 0.4558 | 55.586 |
| exponential | 0.4715 | 58.265 |
| exponential | 0.4868 | 60.945 |
| exponential | 0.5016 | 63.624 |
| exponential | 0.5160 | 66.304 |
First 60 of 100 rows.
View data
| x |
|---|
| 81.618 |
| 118.31 |
| 162.25 |
| 55.913 |
| 80.387 |
| 146.57 |
| 132.70 |
| 108.41 |
| 86.288 |
| 142.56 |
| 43.498 |
| 148.57 |
| 106.92 |
| 105.26 |
| 90.330 |
| 59.016 |
| 74.441 |
| 39.637 |
| 78.563 |
| 103.15 |
| 88.313 |
| 53.098 |
| 121.04 |
| 96.064 |
| 173.49 |
| 79.150 |
| 100.95 |
| 45.178 |
| 112.42 |
| 87.843 |
| 101.18 |
| 63.476 |
| 15.392 |
| 162.06 |
| 46.503 |
| 64.622 |
| 75.189 |
| 42.630 |
| 49.751 |
| 111.60 |
Assumptions
- Independent lifetimes — Not testable from these numbers alone; check how the units were sampled.
- Complete lifetimes — All 40 values are treated as failures. For censored units use Distribution ID.
- No tied lifetimes — All lifetimes are distinct.
Exponentiality tests
| Test | Statistic | z | p (reference) | p (simulated) | p used | p adjusted | Rejects at .05 |
|---|---|---|---|---|---|---|---|
| Cox–Oakes | 32.502 | 4.007 | < .001 | .005 | .005 | — | yes |
| Epps–Pulley | 0.3987 | −4.441 | < .001 | .005 | .005 | — | yes |
| Henze–Meintanis (exponential weight) | 5.787 | — | — | .005 | .005 | — | yes |
| Henze–Meintanis (Gaussian weight) | 2.055 | — | — | .005 | .005 | — | yes |
| Meintanis–Iliopoulos (exponential weight) | 13.357 | — | — | .005 | .005 | — | yes |
| Meintanis–Iliopoulos (Gaussian weight) | 2.268 | — | — | .005 | .005 | — | yes |
| Gnedenko F | 4.412 | — | < .001 | .010 | .010 | — | yes |
| Harris | 2.236 | — | .013 | .010 | .010 | — | yes |
| Hegazy–Green T₁ | 0.3757 | — | — | .005 | .005 | — | yes |
| Hegazy–Green T₂ | 0.2388 | — | — | .045 | .045 | — | yes |
| Hollander–Proschan | 0.0826 | −9.840 | < .001 | .005 | .005 | — | yes |
| Deshpande | 0.8968 | 8.566 | < .001 | .005 | .005 | — | yes |
| Atkinson | 0.0212 | 3.952 | < .001 | .005 | .005 | — | yes |
| Ahsanullah | 0.5984 | 10.228 | < .001 | .005 | .005 | — | yes |
| Epstein (Bartlett) | 56.850 | — | .032 | .045 | .045 | — | yes |
| Frosini | 0.9453 | — | — | .005 | .005 | — | yes |
| Kimber–Michael | 0.2803 | — | — | .005 | .005 | — | yes |
| Kochar | 5.046 | 5.046 | < .001 | .005 | .005 | — | yes |
| Moran | 0.4770 | 3.757 | < .001 | .005 | .005 | — | yes |
| Rossberg | 0.2637 | 7.758 | < .001 | .005 | .005 | — | yes |
| Gini | 0.2386 | −5.655 | < .001 | .005 | .005 | — | yes |
| Patwardhan | 182.93 | — | — | .005 | .005 | — | yes |
| Baringhaus–Henze | 1.731 | — | — | .005 | .005 | — | yes |
| Shapiro–Wilk W for exponentiality | 0.1051 | — | — | .010 | .010 | — | yes |
| Lilliefors (Kolmogorov–Smirnov, rate estimated) | 0.3270 | — | — | .005 | .005 | — | yes |
| Anderson–Darling (rate estimated) | 6.204 | — | — | .005 | .005 | — | yes |
| Cramér–von Mises (rate estimated) | 1.217 | — | — | .005 | .005 | — | yes |
| Watson U² (rate estimated) | 0.8058 | — | — | .005 | .005 | — | yes |
| Total time on test (area under the TTT plot) | 0.7614 | 5.655 | < .001 | .005 | .005 | — | yes |
| Proschan–Pyke | 560 | 3.961 | < .001 | .005 | .005 | — | yes |
Mean life under the exponential model
| Mean life | 95% CI low | 95% CI high | Failure rate |
|---|---|---|---|
| 91.359 | 68.543 | 127.88 | 0.0109 |
- Simulated p-values compare each statistic with 199 exponential samples of the same size (seed 42), renormalized as in the data; every test sees the same samples.
- The count of rejections is not a combined test: the tests overlap, so about 3 in 10 exponential samples get at least one. The adjusted p asks how often exponential samples of this size give a smallest p-value this small across all the tests (single-step min-p, Westfall & Young 1993).
- The total-time-on-test area equals one minus the Gini statistic.
- A Gini statistic below one half and a TTT plot above the diagonal point to a rising failure rate; the reverse points to a falling one.
The exact R script · R R version 4.5.1 (2025-06-13)
# Exponentiality tests (battery)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method life.exponentiality 1.0.2 · spec 00595429764b03cd
# Dataset: life_wear_sim (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # the tests, written from the papers; shared random stream
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/life_wear_sim.parquet", col_select = c("x")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x")]), , 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("x")) # infinite values stop the run (registry/errors.yaml)
# %% Tests
y <- "x"
x <- as.numeric(df[[y]])
x <- x[!is.na(x)]
if (any(x <= 0)) cs_error("CS_E_INVALID_VALUES", column = y, requirement = "positive (lifetimes above zero)", count = sum(x <= 0))
n <- length(x)
cs_check_rows(n, 5, "The exponentiality tests") # the battery needs at least 5 lifetimes
test <- "battery"
alpha <- 0.05
seed <- 42 # exponential samples from the shared Wichmann-Hill stream
reps <- as.integer(199)
a <- 1
b <- 0.44
power <- 0.99
if (b == 1) stop("Deshpande's b must differ from 1")
if (power %in% c(0, 1)) stop("Atkinson's power cannot be 0 or 1")
rows <- cs_exp_battery(x, tests = if (test == "battery") NULL else test, calibration = "monte_carlo", reps = reps, seed = seed, a = a, b = b, power = power,
r_gnedenko = NULL,
r_harris = NULL)
tested <- Filter(function(r) is.finite(r$p), rows)
rejecting <- Filter(function(r) r$p < alpha, tested)
# About 1.5 of 30 tests reject by chance, and because they overlap, some rejection turns up in about 3 of every 10
# truly exponential samples. So the verdict rests on the p adjusted for running them all, not on the count.
adjust_method <- rows[[1]]$adjust
battery_p <- if (length(tested)) min(vapply(tested, function(r) r$p_adj, numeric(1))) else NaN
if (n < 300 && any(vapply(rows, function(r) r$calibration == "reference" && r$key %in% c("kochar", "ahsanullah", "rossberg", "deshpande"), logical(1)))) {
warnings <- c(warnings, "Reference distributions reject too often below about 300 lifetimes: Kochar 12%, Ahsanullah 11% and Rossberg 10% at the 5% level with 30 lifetimes. Simulate instead.")
}
# %% Mean life under the exponential model (exact chi-square interval)
conf <- 0.95
mean_x <- mean(x)
mean_low <- 2 * n * mean_x / stats::qchisq(1 - (1 - conf) / 2, 2 * n)
mean_high <- 2 * n * mean_x / stats::qchisq((1 - conf) / 2, 2 * n)
gini <- 2 * sum((2 * seq_len(n) - n - 1) * sort(x)) / (2 * n * (n - 1) * mean_x)
# %% Verdict and values
keys <- vapply(rows, function(r) r$key, character(1))
lead <- if ("cox_oakes" %in% keys) rows[[which(keys == "cox_oakes")]] else rows[[1]]
verdict <- if (length(rows) == 1) {
if (is.finite(lead$p) && lead$p < alpha) "exponentiality rejected at α = .05" else "compatible with an exponential distribution"
} else if (!length(rejecting)) {
"the lifetimes are compatible with a constant failure rate"
} else if (!isTRUE(battery_p < alpha)) {
"that is what chance gives across this many overlapping tests, so the lifetimes are compatible with a constant failure rate"
} else if (!isTRUE(rows[[which(keys == "gini")]]$p < alpha)) {
"the lifetimes depart from an exponential, with no clear rising or falling failure rate"
} else if (gini < 0.5) {
"the departure looks like a rising failure rate (wear-out)"
} else {
"the departure looks like a falling failure rate (early failures)"
}
values <- list(n = n, mean = mean_x, mean_low = mean_low, mean_high = mean_high, rate = 1 / mean_x, min = min(x), max = max(x),
n_tests = length(tested), n_reject = length(rejecting), n_not_computed = length(rows) - length(tested),
battery_p = battery_p, n_reject_adj = sum(vapply(tested, function(r) r$p_adj < alpha, logical(1))), adjust_method = adjust_method,
test_label = if (length(rows) == 1) lead$test else "Battery", verdict = verdict, lead_label = lead$test, lead_stat = lead$statistic, lead_p = lead$p,
gini = gini, reps = reps)
cell <- function(v) if (is.finite(v)) v else NA_real_ # a number the test does not have shows a dash, not NaN
table <- list()
for (r in rows) {
k <- r$key
values[[sprintf("stat[%s]", k)]] <- r$statistic
values[[sprintf("z[%s]", k)]] <- r$z
values[[sprintf("p[%s]", k)]] <- r$p
values[[sprintf("p_ref[%s]", k)]] <- r$p_ref
values[[sprintf("p_adj[%s]", k)]] <- r$p_adj
values[[sprintf("p_mc[%s]", k)]] <- r$p_mc
values[[sprintf("calibration[%s]", k)]] <- r$calibration
table[[length(table) + 1]] <- list(test = r$test, statistic = cell(r$statistic), z = cell(r$z), p_ref = cell(r$p_ref), p_mc = cell(r$p_mc), p = cell(r$p),
reject = if (is.finite(r$p)) (if (r$p < alpha) "yes" else "no") else "not computed")
}
# %% Assumptions
tied <- n - length(unique(x))
assumptions <- list(
list(key = "independence", label = "Independent lifetimes", status = "info", detail = "Not testable from these numbers alone; check how the units were sampled."),
list(key = "complete_data", label = "Complete lifetimes", status = "info", detail = sprintf("All %d values are treated as failures. For censored units use Distribution ID.", n)),
list(key = "ties", label = "No tied lifetimes", status = if (tied) "warn" else "pass",
detail = if (tied) sprintf("%d tied value(s): zero spacings stop the Epstein test and weaken the other spacing tests.", tied) else "All lifetimes are distinct.")
)
# %% Charts
pct <- sprintf("%.0f%%", conf * 100)
fit_t <- seq(min(x), max(x), length.out = 60)
charts <- list(
cs_chart("ttt", "ttt-plot", sprintf("Scaled total-time-on-test plot: %s", y), list(value = cs_col(y, x, "numeric"))),
cs_chart("paper", "probability-plot", sprintf("Exponential probability plot: %s", y), list(
time = cs_col(y, c(x, fit_t), "numeric"),
fit = cs_col("Fitted F(t)", c(rep(NaN, n), -expm1(-fit_t / mean_x)), "numeric"),
family = cs_col("Series", c(rep("data", n), rep("exponential", length(fit_t))), "categorical", levels = c("data", "exponential"))
), controls = list(paper = "exponential")),
cs_chart("lorenz", "lorenz-gini", sprintf("Lorenz curve: %s", y), list(value = cs_col(y, x, "numeric")))
)
# %% Result
cs_publish(list(
method = "life.exponentiality",
methodVersion = "1.0.2",
title = if (length(rows) > 1) "Exponentiality tests" else paste0("Exponentiality: ", lead$test),
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = if (length(rows) > 1) sprintf("%d of %d tests reject exponentiality at α = .05; adjusted for running all %d, %s: %s.", length(rejecting), length(tested), length(tested), cs_fmt_p(battery_p), verdict)
else sprintf("%s: %s; %s.", lead$test, cs_fmt_p(lead$p), verdict),
apa = sprintf("%s = %s, %s", lead$test, cs_fmt_num(lead$statistic), cs_fmt_p(lead$p)),
statistics = list(list(key = "mean", label = "Mean life", value = mean_x), list(key = "rate", label = "Failure rate", value = 1 / mean_x),
list(key = "n_reject", label = "Tests rejecting", value = length(rejecting), format = "integer"),
list(key = "battery_p", label = "p, adjusted for the battery", value = battery_p, format = "p"),
list(key = "n_tests", label = "Tests run", value = length(tested), format = "integer")),
tables = list(
list(key = "tests", title = "Exponentiality tests", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p_ref", label = "p (reference)", type = "pvalue"),
list(key = "p_mc", label = "p (simulated)", type = "pvalue"), list(key = "p", label = "p used", type = "pvalue"),
list(key = "p_adj", label = "p adjusted", type = "pvalue"),
list(key = "reject", label = "Rejects at .05", type = "string")), rows = table),
list(key = "mean_life", title = "Mean life under the exponential model", columns = list(
list(key = "mean", label = "Mean life", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
list(key = "high", label = paste(pct, "CI high"), type = "number"), list(key = "rate", label = "Failure rate", type = "number")),
rows = list(list(mean = mean_x, low = mean_low, high = mean_high, rate = 1 / mean_x)))
),
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(
sprintf("Simulated p-values compare each statistic with %d exponential samples of the same size (seed %d), renormalized as in the data; every test sees the same samples.", reps, as.integer(seed)),
if (adjust_method == "min_p") "The count of rejections is not a combined test: the tests overlap, so about 3 in 10 exponential samples get at least one. The adjusted p asks how often exponential samples of this size give a smallest p-value this small across all the tests (single-step min-p, Westfall & Young 1993)."
else "The count of rejections is not a combined test: the tests overlap, so about 3 in 10 exponential samples get at least one. Some tests here use a reference distribution, so the adjusted p is Bonferroni, which is cautious for overlapping tests.",
"The total-time-on-test area equals one minus the Gini statistic.",
"A Gini statistic below one half and a TTT plot above the diagonal point to a rising failure rate; the reverse points to a falling one."
),
charts = charts,
values = values
))
Cox–Oakes = 32.50, p = .005
- Mean life
- 91.359
- Failure rate
- 0.0109
- Tests rejecting
- 30
- p, adjusted for the battery
- .015
- Tests run
- 30
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent lifetimes — Not testable from these numbers alone; check how the units were sampled.
- Complete lifetimes — All 40 values are treated as failures. For censored units use Distribution ID.
- No tied lifetimes — All lifetimes are distinct.
Exponentiality tests
| Test | Statistic | z | p (reference) | p (simulated) | p used | p adjusted | Rejects at .05 |
|---|---|---|---|---|---|---|---|
| Cox–Oakes | 32.502 | 4.007 | < .001 | .005 | .005 | .015 | yes |
| Epps–Pulley | 0.3987 | −4.441 | < .001 | .005 | .005 | .015 | yes |
| Henze–Meintanis (exponential weight) | 5.787 | — | — | .005 | .005 | .015 | yes |
| Henze–Meintanis (Gaussian weight) | 2.055 | — | — | .005 | .005 | .015 | yes |
| Meintanis–Iliopoulos (exponential weight) | 13.357 | — | — | .005 | .005 | .015 | yes |
| Meintanis–Iliopoulos (Gaussian weight) | 2.268 | — | — | .005 | .005 | .015 | yes |
| Gnedenko F | 4.412 | — | < .001 | .010 | .010 | .070 | yes |
| Harris | 2.236 | — | .013 | .010 | .010 | .070 | yes |
| Hegazy–Green T₁ | 0.3757 | — | — | .005 | .005 | .015 | yes |
| Hegazy–Green T₂ | 0.2388 | — | — | .045 | .045 | .260 | yes |
| Hollander–Proschan | 0.0826 | −9.840 | < .001 | .005 | .005 | .015 | yes |
| Deshpande | 0.8968 | 8.566 | < .001 | .005 | .005 | .015 | yes |
| Atkinson | 0.0212 | 3.952 | < .001 | .005 | .005 | .015 | yes |
| Ahsanullah | 0.5984 | 10.228 | < .001 | .005 | .005 | .015 | yes |
| Epstein (Bartlett) | 56.850 | — | .032 | .045 | .045 | .260 | yes |
| Frosini | 0.9453 | — | — | .005 | .005 | .015 | yes |
| Kimber–Michael | 0.2803 | — | — | .005 | .005 | .015 | yes |
| Kochar | 5.046 | 5.046 | < .001 | .005 | .005 | .015 | yes |
| Moran | 0.4770 | 3.757 | < .001 | .005 | .005 | .015 | yes |
| Rossberg | 0.2637 | 7.758 | < .001 | .005 | .005 | .015 | yes |
| Gini | 0.2386 | −5.655 | < .001 | .005 | .005 | .015 | yes |
| Patwardhan | 182.93 | — | — | .005 | .005 | .015 | yes |
| Baringhaus–Henze | 1.731 | — | — | .005 | .005 | .015 | yes |
| Shapiro–Wilk W for exponentiality | 0.1051 | — | — | .010 | .010 | .070 | yes |
| Lilliefors (Kolmogorov–Smirnov, rate estimated) | 0.3270 | — | — | .005 | .005 | .015 | yes |
| Anderson–Darling (rate estimated) | 6.204 | — | — | .005 | .005 | .015 | yes |
| Cramér–von Mises (rate estimated) | 1.217 | — | — | .005 | .005 | .015 | yes |
| Watson U² (rate estimated) | 0.8058 | — | — | .005 | .005 | .015 | yes |
| Total time on test (area under the TTT plot) | 0.7614 | 5.655 | < .001 | .005 | .005 | .015 | yes |
| Proschan–Pyke | 560 | 3.961 | < .001 | .005 | .005 | .015 | yes |
Mean life under the exponential model
| Mean life | 95% CI low | 95% CI high | Failure rate |
|---|---|---|---|
| 91.359 | 68.543 | 127.88 | 0.0109 |
- Simulated p-values compare each statistic with 199 exponential samples of the same size (seed 42), renormalized as in the data; every test sees the same samples.
- The count of rejections is not a combined test: the tests overlap, so about 3 in 10 exponential samples get at least one. The adjusted p asks how often exponential samples of this size give a smallest p-value this small across all the tests (single-step min-p, Westfall & Young 1993).
- The total-time-on-test area equals one minus the Gini statistic.
- A Gini statistic below one half and a TTT plot above the diagonal point to a rising failure rate; the reverse points to a falling one.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Exponentiality tests (battery)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method life.exponentiality 1.0.2 · spec 00595429764b03cd
# Dataset: life_wear_sim (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import exponentiality as ex # the tests, written from the papers; shared random stream
# %% Data
df = pd.read_parquet("tests/parity/fixtures/life_wear_sim.parquet", columns=["x"])
n_input = len(df)
df = df.dropna(subset=["x"]) # listwise deletion over the analysis columns
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, ["x"]) # infinite values stop the run (registry/errors.yaml)
# %% Tests
y = "x"
x = df[y].to_numpy(dtype=float)
x = x[~np.isnan(x)]
if (x <= 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=y, requirement="positive (lifetimes above zero)", count=int((x <= 0).sum()))
n = x.size
cs.check_rows(n, 5, "The exponentiality tests") # the battery needs at least 5 lifetimes
test = "battery"
alpha = 0.05
seed, reps = 42, int(199) # exponential samples from the shared Wichmann–Hill stream
a, b, power = 1, 0.44, 0.99
if b == 1:
raise ValueError("Deshpande's b must differ from 1")
if power in (0, 1):
raise ValueError("Atkinson's power cannot be 0 or 1")
rows = ex.exp_battery(
x, tests=None if test == "battery" else [test], calibration="monte_carlo", reps=reps, seed=seed, a=a, b=b, power=power,
r_gnedenko=None,
r_harris=None,
)
tested = [r for r in rows if np.isfinite(r["p"])]
rejecting = [r for r in tested if r["p"] < alpha]
# About 1.5 of 30 tests reject by chance, and because they overlap, some rejection turns up in about 3 of every 10
# truly exponential samples. So the verdict rests on the p adjusted for running them all, not on the count.
adjust_method = rows[0]["adjust"]
battery_p = min((r["p_adj"] for r in tested), default=float("nan"))
if n < 300 and any(r["calibration"] == "reference" and r["key"] in ("kochar", "ahsanullah", "rossberg", "deshpande") for r in rows):
warnings.append("Reference distributions reject too often below about 300 lifetimes: Kochar 12%, Ahsanullah 11% and Rossberg 10% at the 5% level with 30 lifetimes. Simulate instead.")
# %% Mean life under the exponential model (exact chi-square interval)
conf = 0.95
mean = float(x.mean())
mean_low = 2 * n * mean / float(stats.chi2.ppf(1 - (1 - conf) / 2, 2 * n))
mean_high = 2 * n * mean / float(stats.chi2.ppf((1 - conf) / 2, 2 * n))
order = np.sort(x)
gini = float(2 * np.sum((2 * np.arange(1, n + 1) - n - 1) * order) / (2 * n * (n - 1) * mean))
# %% Verdict and values
lead = next((r for r in rows if r["key"] == "cox_oakes"), rows[0])
if len(rows) == 1:
verdict = "exponentiality rejected at α = .05" if lead["p"] < alpha else "compatible with an exponential distribution"
elif not rejecting:
verdict = "the lifetimes are compatible with a constant failure rate"
elif not battery_p < alpha:
verdict = "that is what chance gives across this many overlapping tests, so the lifetimes are compatible with a constant failure rate"
elif not next(r for r in rows if r["key"] == "gini")["p"] < alpha:
verdict = "the lifetimes depart from an exponential, with no clear rising or falling failure rate"
elif gini < 0.5:
verdict = "the departure looks like a rising failure rate (wear-out)"
else:
verdict = "the departure looks like a falling failure rate (early failures)"
values = {"n": n, "mean": mean, "mean_low": mean_low, "mean_high": mean_high, "rate": 1 / mean, "min": float(x.min()), "max": float(x.max()),
"n_tests": len(tested), "n_reject": len(rejecting), "n_not_computed": len(rows) - len(tested),
"battery_p": battery_p, "n_reject_adj": sum(1 for r in tested if r["p_adj"] < alpha), "adjust_method": adjust_method,
"test_label": lead["test"] if len(rows) == 1 else "Battery", "verdict": verdict, "lead_label": lead["test"], "lead_stat": lead["statistic"], "lead_p": lead["p"],
"gini": gini, "reps": reps}
def cell(v):
"""A table cell: a number the test does not have shows a dash, not NaN."""
return float(v) if np.isfinite(v) else None
table = []
for r in rows:
k = r["key"]
values[f"stat[{k}]"], values[f"z[{k}]"], values[f"p[{k}]"] = r["statistic"], r["z"], r["p"]
values[f"p_ref[{k}]"], values[f"p_mc[{k}]"], values[f"calibration[{k}]"] = r["p_ref"], r["p_mc"], r["calibration"]
values[f"p_adj[{k}]"] = r["p_adj"]
computed = bool(np.isfinite(r["p"]))
table.append({"test": r["test"], "statistic": cell(r["statistic"]), "z": cell(r["z"]), "p_ref": cell(r["p_ref"]), "p_mc": cell(r["p_mc"]), "p": cell(r["p"]), "p_adj": cell(r["p_adj"]),
"reject": ("yes" if r["p"] < alpha else "no") if computed else "not computed"})
# %% Assumptions
tied = n - np.unique(x).size
assumptions = [
{"key": "independence", "label": "Independent lifetimes", "status": "info", "detail": "Not testable from these numbers alone; check how the units were sampled."},
{"key": "complete_data", "label": "Complete lifetimes", "status": "info", "detail": f"All {n} values are treated as failures. For censored units use Distribution ID."},
{"key": "ties", "label": "No tied lifetimes", "status": "warn" if tied else "pass",
"detail": f"{tied} tied value(s): zero spacings stop the Epstein test and weaken the other spacing tests." if tied else "All lifetimes are distinct."},
]
# %% Charts
pct = f"{conf:.0%}"
fit_t = np.linspace(float(x.min()), float(x.max()), 60)
charts = [
cs.chart("ttt", "ttt-plot", f"Scaled total-time-on-test plot: {y}", {"value": cs.col(y, x, "numeric")}),
cs.chart("paper", "probability-plot", f"Exponential probability plot: {y}", {
"time": cs.col(y, np.concatenate((x, fit_t)), "numeric"),
"fit": cs.col("Fitted F(t)", np.concatenate((np.full(n, np.nan), -np.expm1(-fit_t / mean))), "numeric"),
"family": cs.col("Series", ["data"] * n + ["exponential"] * fit_t.size, "categorical", levels=["data", "exponential"]),
}, controls={"paper": "exponential"}),
cs.chart("lorenz", "lorenz-gini", f"Lorenz curve: {y}", {"value": cs.col(y, x, "numeric")}),
]
# %% Result
cs.publish({
"method": "life.exponentiality",
"methodVersion": "1.0.2",
"title": "Exponentiality tests" if len(rows) > 1 else f"Exponentiality: {lead['test']}",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": (f"{len(rejecting)} of {len(tested)} tests reject exponentiality at α = .05; adjusted for running all {len(tested)}, {cs.fmt_p(battery_p)}: {verdict}." if len(rows) > 1
else f"{lead['test']}: {cs.fmt_p(lead['p'])}; {verdict}."),
"apa": f"{lead['test']} = {cs.fmt_num(lead['statistic'])}, {cs.fmt_p(lead['p'])}",
"statistics": [{"key": "mean", "label": "Mean life", "value": mean}, {"key": "rate", "label": "Failure rate", "value": 1 / mean},
{"key": "n_reject", "label": "Tests rejecting", "value": len(rejecting), "format": "integer"},
{"key": "battery_p", "label": "p, adjusted for the battery", "value": battery_p, "format": "p"},
{"key": "n_tests", "label": "Tests run", "value": len(tested), "format": "integer"}],
"tables": [
{"key": "tests", "title": "Exponentiality tests", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p_ref", "label": "p (reference)", "type": "pvalue"},
{"key": "p_mc", "label": "p (simulated)", "type": "pvalue"}, {"key": "p", "label": "p used", "type": "pvalue"},
{"key": "p_adj", "label": "p adjusted", "type": "pvalue"},
{"key": "reject", "label": "Rejects at .05", "type": "string"}], "rows": table},
{"key": "mean_life", "title": "Mean life under the exponential model", "columns": [
{"key": "mean", "label": "Mean life", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
{"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "rate", "label": "Failure rate", "type": "number"}],
"rows": [{"mean": mean, "low": mean_low, "high": mean_high, "rate": 1 / mean}]},
],
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [
f"Simulated p-values compare each statistic with {reps} exponential samples of the same size (seed {seed}), renormalized as in the data; every test sees the same samples.",
("The count of rejections is not a combined test: the tests overlap, so about 3 in 10 exponential samples get at least one. The adjusted p asks how often exponential samples of this size give a smallest p-value this small across all the tests (single-step min-p, Westfall & Young 1993)." if adjust_method == "min_p"
else "The count of rejections is not a combined test: the tests overlap, so about 3 in 10 exponential samples get at least one. Some tests here use a reference distribution, so the adjusted p is Bonferroni, which is cautious for overlapping tests."),
"The total-time-on-test area equals one minus the Gini statistic.",
"A Gini statistic below one half and a TTT plot above the diagonal point to a rising failure rate; the reverse points to a falling one.",
],
"charts": charts,
"values": values,
})
On simulated wear-out data, 30 of 30 tests reject. The verdict reads: the departure looks like a rising failure rate (wear-out). On the air conditioners, 0 of 29 reject.
The TTT plotTotal-time-on-test plotScaled accumulated running time against the share failed. On the diagonal the hazard is constant; bowed up it rises, bowed down it falls. shows the direction: bowing above the diagonal suggests wear-out, and below it, early failures.
A battery isn't thirty verdicts
PredictPredict first
These 24 lifetimes were simulated as truly exponential. You run 30 tests, each at the 5% level. How many will reject?
Reveal
2. At the 5% level, 30 separate tests would average false rejections, if each were independent. A couple of rejections are compatible with an exponential distribution. Look for the pattern across the battery, and choose your main test before you run it.
Compare two suppliers
In the appThe Life model step adds covariates to the chosen family, as an accelerated failure timeAccelerated failure timeA survival model of log time, where features stretch or shrink how long until the event, with no proportional-hazards assumption. model. Covariates stretch or shrink time.
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
View data
| Time ratio | upper | Term | lower |
|---|---|---|---|
| 1.949 | 2.912 | supplier: B | 1.304 |
View data
| Event | Series | Unit exponential F(r) | Cox–Snell residual |
|---|---|---|---|
| 1 | data | — | 0.2836 |
| 1 | data | — | 0.3343 |
| 1 | data | — | 0.5389 |
| 0 | data | — | 0.1056 |
| 0 | data | — | 0.2946 |
| 0 | data | — | 0.5370 |
| 0 | data | — | 0.2758 |
| 1 | data | — | 0.0740 |
| 0 | data | — | 0.1968 |
| 0 | data | — | 0.6525 |
| 1 | data | — | 1.529 |
| 0 | data | — | 0.6525 |
| 1 | data | — | 1.238 |
| 1 | data | — | 0.1844 |
| 1 | data | — | 0.0775 |
| 1 | data | — | 0.4771 |
| 0 | data | — | 0.3195 |
| 0 | data | — | 0.4381 |
| 0 | data | — | 1.639 |
| 1 | data | — | 0.1025 |
| 1 | data | — | 0.8678 |
| 0 | data | — | 0.3584 |
| 0 | data | — | 1.639 |
| 0 | data | — | 0.2131 |
| 1 | data | — | 0.9300 |
| 0 | data | — | 0.2411 |
| 0 | data | — | 0.2088 |
| 1 | data | — | 0.4897 |
| 1 | data | — | 0.3269 |
| 0 | data | — | 0.6525 |
| 1 | data | — | 1.069 |
| 1 | data | — | 0.3257 |
| 0 | data | — | 1.639 |
| 0 | data | — | 0.0853 |
| 1 | data | — | 0.6435 |
| 0 | data | — | 0.1947 |
| 0 | data | — | 1.639 |
| 0 | data | — | 0.1559 |
| 0 | data | — | 1.639 |
| 0 | data | — | 0.4768 |
| 1 | data | — | 0.0790 |
| 1 | data | — | 0.0281 |
| 1 | data | — | 0.5781 |
| 0 | data | — | 0.6525 |
| 1 | data | — | 0.1075 |
| 1 | data | — | 0.0564 |
| 1 | data | — | 0.4896 |
| 1 | data | — | 0.0765 |
| 1 | data | — | 0.3461 |
| 0 | data | — | 0.6525 |
| 1 | data | — | 0.6556 |
| 1 | data | — | 0.2577 |
| 0 | data | — | 1.639 |
| 1 | data | — | 0.1057 |
| 1 | data | — | 0.7294 |
| 0 | data | — | 0.3483 |
| 1 | data | — | 0.6760 |
| 1 | data | — | 0.1656 |
| 1 | data | — | 0.5404 |
| 0 | data | — | 0.5737 |
First 60 of 180 rows.
View data
| Profile | Reliability | hours |
|---|---|---|
| A | 1 | 0 |
| A | 0.9972 | 20 |
| A | 0.9926 | 40 |
| A | 0.9871 | 60 |
| A | 0.9809 | 80 |
| A | 0.9741 | 100 |
| A | 0.9668 | 120 |
| A | 0.9591 | 140 |
| A | 0.9510 | 160 |
| A | 0.9426 | 180 |
| A | 0.9340 | 200 |
| A | 0.9250 | 220 |
| A | 0.9159 | 240 |
| A | 0.9065 | 260 |
| A | 0.8970 | 280 |
| A | 0.8873 | 300 |
| A | 0.8775 | 320 |
| A | 0.8675 | 340 |
| A | 0.8575 | 360 |
| A | 0.8473 | 380 |
| A | 0.8371 | 400 |
| A | 0.8268 | 420 |
| A | 0.8164 | 440 |
| A | 0.8060 | 460 |
| A | 0.7956 | 480 |
| A | 0.7851 | 500 |
| A | 0.7746 | 520 |
| A | 0.7641 | 540 |
| A | 0.7536 | 560 |
| A | 0.7431 | 580 |
| A | 0.7326 | 600 |
| A | 0.7221 | 620 |
| A | 0.7117 | 640 |
| A | 0.7012 | 660 |
| A | 0.6909 | 680 |
| A | 0.6805 | 700 |
| A | 0.6702 | 720 |
| A | 0.6599 | 740 |
| A | 0.6497 | 760 |
| A | 0.6396 | 780 |
| A | 0.6295 | 800 |
| A | 0.6195 | 820 |
| A | 0.6095 | 840 |
| A | 0.5997 | 860 |
| A | 0.5899 | 880 |
| A | 0.5801 | 900 |
| A | 0.5705 | 920 |
| A | 0.5609 | 940 |
| A | 0.5514 | 960 |
| A | 0.5421 | 980 |
| A | 0.5327 | 1,000 |
| A | 0.5235 | 1,020 |
| A | 0.5144 | 1,040 |
| A | 0.5054 | 1,060 |
| A | 0.4965 | 1,080 |
| A | 0.4876 | 1,100 |
| A | 0.4789 | 1,120 |
| A | 0.4702 | 1,140 |
| A | 0.4617 | 1,160 |
| A | 0.4533 | 1,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) | SE | Time ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| (Intercept) | 7.243 | 0.1163 | 1398.14 | 1113.09 | 1756.18 | 62.262 | < .001 |
| supplier: B | 0.6674 | 0.2049 | 1.949 | 1.304 | 2.912 | 3.257 | .001 |
Scale σ = 0.7246 (Weibull shape 1/σ = 1.38).
Distribution comparison
| Distribution | log L | AIC |
|---|---|---|
| Weibull | −511.84 | 1029.68 |
| exponential | −515.63 | 1035.25 |
| log-normal | −511.84 | 1029.68 |
| log-logistic | −511.90 | 1029.81 |
Life metrics
| Profile | Mean life | 95% CI low | 95% CI high | R(500) | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| A | 1277.25 | 1011.57 | 1612.70 | 0.7851 | 0.6915 | 0.8533 |
| B | 2489.50 | 1749.98 | 3541.52 | 0.9082 | 0.8486 | 0.9451 |
B-lives
| Profile | Percent failed | Time | 95% CI low | 95% CI high |
|---|---|---|---|---|
| A | 10 | 273.75 | 182.88 | 409.78 |
| A | 50 | 1072.03 | 850.89 | 1350.65 |
| B | 10 | 533.57 | 365.51 | 778.90 |
| B | 50 | 2089.51 | 1518.80 | 2874.66 |
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6110 | 0.5464 | 0.6755 | Harrell's C on the data the model was fitted to; SE 0.0330 (infinitesimal jackknife). |
| AIC | 1029.68 | — | — | −2 log L + 2k. |
| BIC | 1038.05 | — | — | −2 log L + k·log(n), n = 120 subjects. |
| Cox–Snell residual sum | 60 | — | — | 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
))
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) | SE | Time ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| (Intercept) | 7.243 | 0.1163 | 1398.14 | 1113.09 | 1756.18 | 62.262 | < .001 |
| supplier: B | 0.6674 | 0.2049 | 1.949 | 1.304 | 2.912 | 3.257 | .001 |
Scale σ = 0.7246 (Weibull shape 1/σ = 1.38).
Distribution comparison
| Distribution | log L | AIC |
|---|---|---|
| Weibull | −511.84 | 1029.68 |
| exponential | −515.63 | 1035.25 |
| log-normal | −511.84 | 1029.68 |
| log-logistic | −511.90 | 1029.81 |
Life metrics
| Profile | Mean life | 95% CI low | 95% CI high | R(500) | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| A | 1277.25 | 1011.57 | 1612.70 | 0.7851 | 0.6915 | 0.8533 |
| B | 2489.50 | 1749.98 | 3541.52 | 0.9082 | 0.8486 | 0.9451 |
B-lives
| Profile | Percent failed | Time | 95% CI low | 95% CI high |
|---|---|---|---|---|
| A | 10 | 273.75 | 182.88 | 409.78 |
| A | 50 | 1072.03 | 850.89 | 1350.65 |
| B | 10 | 533.57 | 365.51 | 778.90 |
| B | 50 | 2089.51 | 1518.80 | 2874.66 |
Model fit
| Measure | Value | 95% CI low | 95% CI high | Note |
|---|---|---|---|---|
| Concordance (C, apparent) | 0.6110 | 0.5464 | 0.6755 | Harrell's C on the data the model was fitted to; SE 0.0330 (infinitesimal jackknife). |
| AIC | 1029.68 | — | — | −2 log L + 2k. |
| BIC | 1038.05 | — | — | −2 log L + k·log(n), n = 120 subjects. |
| Cox–Snell residual sum | 60.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,
})
Units from supplier: B last 1.95 times as long as those from supplier A, with an interval from 1.30 to 2.91.
The model assumes both suppliers share a shape. The test of that gives p = .613, which is compatible with a common shape.
Compute a B-life
CheckpointFor an exponential model, reliability is , where is the mean life.
Check yourself
An exponential model has a mean life of 1,000 hours. What is its B10? Give one decimal.
Show the answer
Answer: 105.4
Solve R(t) = 0.9: t = −1,000 × ln(0.9) = 105.4 hours. So B10 is much smaller than the mean, since exponential lifetimes spread widely.
Check yourself
Under the same model, what is the reliability at a mission of 500 hours? Give three decimals.
Show the answer
Answer: 0.607
R(500) = e^(−500/1,000) = e^(−0.5) = 0.607. So nearly 4 in 10 units fail before the mean life is even half used.
Check your understanding
CheckpointCheck yourself
A pump's failure rate is constant. Would replacing pumps early, before they fail, reduce failures?
Show the answer
Answer: b
The exponential model has no memory. Preventive replacement only helps when the hazard rises with age.
Check yourself
A time ratio of 2 for supplier B means what?
Show the answer
Answer: a
Accelerated failure time models work on the time scale. So median life and B-lives scale by the same ratio.
Check yourself
The common-shape test rejects. What does that tell you about comparing suppliers?
Show the answer
Answer: b
When shapes differ, one supplier may be better early and worse late. Fit them separately, and compare B-lives at the times you care about.
Try it
In the appIn the Quality studio, choose Life data & reliability. The steps run from Life data through Distribution ID, Exponentiality and Life model to Compare. Each later step starts from the first step's columns, and the Life model starts from the family and mission time you chose. To begin at the battery, choose Is the failure rate constant?.
import pandas as pd
from lifelines import WeibullAFTFitter
df = pd.read_csv("devices.csv")
df["supplier_B"] = (df["supplier"] == "B").astype(int)
aft = WeibullAFTFitter().fit(df[["hours", "failed", "supplier_B"]], "hours", "failed")
print(aft.summary.loc[("lambda_", "supplier_B"), ["exp(coef)", "exp(coef) lower 95%", "exp(coef) upper 95%"]])library(survival)
df <- read.csv("devices.csv")
fit <- survreg(Surv(hours, failed) ~ supplier, df, dist = "weibull")
exp(coef(fit)["supplierB"]) # time ratio
exp(confint(fit)["supplierB", ]) # its intervalRecap
Recap- A hazard's shape decides whether to screen, stock spares or replace early.
- Read an exponentiality battery as a pattern, since a few false rejections are expected.
- Time ratios compare groups, and they assume a common shape, which you can test.
Concepts in this lesson