Which distribution fits your failures?
Keep units still running in the analysis, rank lifetime distributions by AIC, and read B-lives and mission reliability with their uncertainty.
What runs in CodeSplash
- Distribution ID for life data Verified in Python and R
You will be able to
- Say why units still running must stay in a life analysis
- Rank distributions by AIC, and read a small gap as a near tie
- Report a B-life and reliability at a mission time, with intervals
Failures, and units still running
ReadYou test devices to see how long they last. When the test ends, some have failed and some are still running.
The units still running are censoredCensoringFollow-up ended before the event happened, so you only know the event time is later than observed.: you know they lasted at least that long. They're real information. Leaving them out, or treating their stopping time as a failure, makes the product look worse than it is.
Here, 60 of 120 devices were still running.
Drop them and see
ExploreFExplorable · Why you cannot just drop censored patients
What goes wrong if you ignore or discard censored observations?
If you drop the censored patients, how does the median compare with the truth?
Commit your prediction above to see the result
Make your prediction to see the result.
Increase the censoring, then compare the methods that ignore it with the one that accounts for it. Which direction does the mistake go? Then turn on High-risk patients leave early, and see what no method can fix.
Which shape?
PredictPredict first
The app fits each lifetime family by maximum likelihood, counting censored units, and ranks them by AICAICA model score balancing fit against complexity; lower is better, and only differences matter.. With 60 failures, what do you expect?
Reveal
Log-logistic comes first, only 0.175 ahead of Gamma. A difference in AICΔAICHow far a model's AIC is above the best model's; the scale for comparing candidates. that small is a near tie. Ranking families takes many failures, so choose among close contenders by what you know about how the part fails, and check that your conclusions hold under each.
Read the fits
In the appLog-logistic, AIC = 1039.22, B5 = 233.11, 95% CI [158.28, 343.32]
- Failures
- 60
- Censored
- 60
- Mean life
- 2975.78
- B5
- 233.11
Assumptions
- Non-informative censoring — 60 of 120 units are censored; check that they stopped for reasons unrelated to their risk.
- Number of failures — 60 failures.
- Fit against Kaplan–Meier — The best family's largest gap from the Kaplan–Meier curve is 0.036.
Families ranked by AIC
| Family | Parameters | log L | AIC | BIC | ΔAIC | Akaike weight | Gap from Kaplan–Meier | Mean life | Median life | B5 | 95% CI low | 95% CI high | R(500) | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Log-logistic | μ (log time) = 7.268, σ (log time) = 0.6168 | −517.61 | 1039.22 | 1044.80 | 0 | 0.2212 | 0.0361 | 2975.78 | 1433.32 | 233.11 | 158.28 | 343.32 | 0.8465 | 0.7821 | 0.8944 |
| Gamma | Shape k = 1.527, Rate = 0.0008343 | −517.70 | 1039.40 | 1044.97 | 0.1753 | 0.2026 | 0.0421 | 1830.73 | 1450.34 | 221.16 | 142.82 | 342.47 | 0.8483 | 0.7871 | 0.8942 |
| Weibull | Shape β = 1.342, Scale η = 1919 | −517.95 | 1039.90 | 1045.48 | 0.6778 | 0.1576 | 0.0468 | 1761.71 | 1460.41 | 209.79 | 133.64 | 329.33 | 0.8483 | 0.7856 | 0.8951 |
| Weibull (3-parameter) | Shape β = 1.195, Scale η = 1915, Threshold γ = 50.46 | −517.04 | 1040.08 | 1048.44 | 0.8519 | 0.1445 | 0.0426 | 1854.04 | 1459.81 | 209.95 | 142.69 | 308.90 | 0.8378 | 0.7739 | 0.8863 |
| Log-normal | μ (log time) = 7.28, σ (log time) = 1.112 | −518.14 | 1040.28 | 1045.86 | 1.060 | 0.1302 | 0.0539 | 2693.18 | 1450.87 | 232.85 | 166.80 | 325.07 | 0.8309 | 0.7678 | 0.8796 |
| Generalized gamma | μ (log time) = 7.443, σ (log time) = 0.9203, Q = 0.5307 | −517.54 | 1041.08 | 1049.44 | 1.857 | 0.0874 | 0.0382 | 2006.19 | 1444.07 | 227.93 | 152.50 | 340.65 | 0.8432 | 0.7769 | 0.8924 |
| Gompertz | Shape b = 0.0004422, Rate a = 0.0003274 | −519.39 | 1042.78 | 1048.36 | 3.558 | 0.0373 | 0.0562 | 1642.77 | 1494.17 | 151.48 | 99.576 | 230.45 | 0.8326 | 0.7688 | 0.8815 |
| Exponential | Rate λ = 0.00046 | −521.06 | 1044.12 | 1046.91 | 4.897 | 0.0191 | 0.0796 | 2174.03 | 1506.92 | 111.51 | 86.584 | 143.62 | 0.7945 | 0.7445 | 0.8370 |
Likelihood-ratio tests of nested families
| Test | χ² | df | p |
|---|---|---|---|
| Weibull vs exponential (shape = 1) | 6.219 | 1 | .013 |
| Generalized gamma vs Weibull (Q = 1) | 0.8211 | 1 | .365 |
| Generalized gamma vs log-normal (Q = 0) | 1.203 | 1 | .273 |
| Generalized gamma vs gamma (Q = σ) | 0.3185 | 1 | .573 |
- Failure: failed = 1. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Distribution ID for life data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method life.distribution 1.0.1 · spec fbb02e8d5167dd58
# 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(codesplashr) # censored maximum likelihood, written from the texts
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/life_devices_sim.parquet", col_select = c("hours", "failed")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("hours", "failed")]), , 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")) # 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)
# %% Fit the families
if (any(tt <= 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "positive for a life distribution", count = sum(tt <= 0))
n <- length(tt)
events <- sum(ev)
cs_check_rows(n, 3, "Distribution ID")
cs_check_not_constant(tt, tcol) # with one time for every unit no family can be fitted
if (events < 3) cs_error("CS_E_UNDEFINED", what = "Distribution ID", reason = sprintf("it needs at least 3 failures, and there are %d", events))
conf <- 0.95
b_percent <- 5
mission <- 500 # reliability is reported at this time
families <- NULL
res <- cs_life_compare(tt, ev, families = families, b_percent = b_percent, mission = mission, conf = conf)
fits <- res$fits
rows <- res$rows
best <- res$best
ranked <- Filter(function(r) isTRUE(r$estimable), rows)
if (length(ranked) == 0) cs_error("CS_E_NO_CONVERGENCE", what = "The distribution fits")
top <- ranked[[1]]
second <- if (length(ranked) > 1) ranked[[2]] else NULL
has_mission <- !is.null(mission)
# %% Values
values <- list(
n = n, events = events, censored = n - events, censor_share = (n - events) / n, event_label = event_label,
best = best, best_label = top$label, best_aic = top$aic, second_label = if (!is.null(second)) second$label else NA, second_delta = if (!is.null(second)) second$delta_aic else NA,
best_mttf = top$mttf, best_median = top$median, best_blife = top$blife, best_blife_low = top$blife_low, best_blife_high = top$blife_high,
best_mission_r = if (has_mission) top$mission_r else NA, best_mission_low = if (has_mission) top$mission_low else NA,
best_mission_high = if (has_mission) top$mission_high else NA, b_percent = b_percent, mission_time = if (has_mission) mission else NA,
lr_weibull_exp = NA, lr_weibull_exp_p = NA, weibull_shape = NA
)
for (r in rows) {
f <- r$family
if (!isTRUE(r$estimable)) next
for (key in c("loglik", "aic", "bic", "delta_aic", "weight", "km_distance", "mttf", "median", "blife", "blife_low", "blife_high")) {
values[[sprintf("%s[%s]", key, f)]] <- r[[key]]
}
if (has_mission) for (key in c("mission_r", "mission_low", "mission_high")) values[[sprintf("%s[%s]", key, f)]] <- r[[key]]
for (par in cs_life_params(fits[[f]])) {
values[[sprintf("par[%s:%s]", f, par$name)]] <- par$value
values[[sprintf("par_se[%s:%s]", f, par$name)]] <- par$se
}
}
if (!is.null(fits$weibull) && isTRUE(fits$weibull$estimable)) values$weibull_shape <- cs_life_params(fits$weibull)[[1]]$value
test_rows <- list()
test_label <- c(weibull_vs_exponential = "Weibull vs exponential (shape = 1)", gengamma_vs_weibull = "Generalized gamma vs Weibull (Q = 1)",
gengamma_vs_lognormal = "Generalized gamma vs log-normal (Q = 0)", gengamma_vs_gamma = "Generalized gamma vs gamma (Q = σ)")
for (key in names(test_label)) {
tst <- res$tests[[key]]
if (is.null(tst)) next
values[[sprintf("lr[%s]", key)]] <- tst$lr
values[[sprintf("lr_p[%s]", key)]] <- tst$p
test_rows[[length(test_rows) + 1]] <- list(test = unname(test_label[[key]]), lr = tst$lr, df = tst$df, p = tst$p)
if (key == "weibull_vs_exponential") {
values$lr_weibull_exp <- tst$lr
values$lr_weibull_exp_p <- tst$p
}
}
# %% Assumptions
gap <- top$km_distance
assumptions <- list(
list(key = "censoring", label = "Non-informative censoring", status = "info", detail = sprintf("%d of %d units are censored; check that they stopped for reasons unrelated to their risk.", n - events, n)),
list(key = "sample_size", label = "Number of failures", status = if (events < 20) "warn" else "pass",
detail = if (events < 20) sprintf("%d failures: too few to rank families reliably, so several may be equally plausible.", events) else sprintf("%d failures.", events)),
list(key = "fit_gap", label = "Fit against Kaplan–Meier", status = if (gap > 0.15) "warn" else "pass",
detail = paste0(sprintf("The best family's largest gap from the Kaplan–Meier curve is %.3f", gap), if (gap > 0.15) "; none of these families follows the data closely." else "."))
)
extra_notes <- list()
for (r in rows) if (!is.null(r$note)) extra_notes[[length(extra_notes) + 1]] <- sprintf("%s: %s", r$label, r$note)
# %% Charts
grid <- seq(min(tt) * 0.5, max(tt), length.out = 60)
papers <- Filter(function(p) !is.null(fits[[p]]) && isTRUE(fits[[p]]$estimable), c("weibull", "lognormal", "exponential", "loglogistic"))
times <- c(tt, rep(grid, length(papers)))
fitted <- c(rep(NaN, n), unlist(lapply(papers, function(p) 1 - cs_life_surv(fits[[p]], grid))))
fam <- c(rep("data", n), rep(papers, each = length(grid)))
evs <- c(as.numeric(ev), rep(NaN, length(grid) * length(papers)))
charts <- list(
cs_chart("id", "dist-id-grid", sprintf("Distribution ID: %s", tcol), list(
time = cs_col(tcol, times, "numeric"), event = cs_col("Failed", evs, "numeric"),
fit = cs_col("Fitted F(t)", fitted, "numeric"), family = cs_col("Series", fam, "categorical", levels = c("data", papers))
))
)
curve_fams <- vapply(ranked[seq_len(min(3, length(ranked)))], function(r) r$family, character(1))
curve_labels <- vapply(ranked[seq_len(min(3, length(ranked)))], function(r) r$label, character(1))
line <- seq(0, max(tt), length.out = 101)
km <- cs_life_km(tt, ev)
rel_t <- c(0, km$time, rep(line, length(curve_fams)))
rel_s <- c(1, km$surv, unlist(lapply(curve_fams, function(f) cs_life_surv(fits[[f]], line))))
rel_g <- c(rep("Kaplan–Meier", length(km$time) + 1), rep(curve_labels, each = length(line)))
charts[[2]] <- cs_chart("reliability", "reliability-curve", sprintf("Reliability: %s", tcol), list(
time = cs_col(tcol, rel_t, "numeric"), surv = cs_col("Reliability", rel_s, "numeric"),
strata = cs_col("Curve", rel_g, "categorical", levels = c("Kaplan–Meier", curve_labels))
), controls = list(mission = if (has_mission) mission else 0, bLife = top$blife))
hz_t <- line[-1]
charts[[3]] <- cs_chart("hazard", "hazard-plot", sprintf("Fitted hazard: %s", tcol), list(
time = cs_col(tcol, rep(hz_t, length(curve_fams)), "numeric"),
hazard = cs_col("Hazard", unlist(lapply(curve_fams, function(f) cs_life_hazard(fits[[f]], hz_t))), "numeric"),
strata = cs_col("Family", rep(curve_labels, each = length(hz_t)), "categorical", levels = curve_labels)
))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
fam_rows <- lapply(ranked, function(r) {
pars <- paste(vapply(cs_life_params(fits[[r$family]]), function(p) sprintf("%s = %.4g", p$label, p$value), character(1)), collapse = ", ") # 4 digits: rates can be 0.0005
row <- list(family = r$label, parameters = pars, loglik = r$loglik, aic = r$aic, bic = r$bic, delta_aic = r$delta_aic, weight = r$weight,
km_distance = r$km_distance, mttf = if (is.finite(r$mttf)) r$mttf else NA_real_, median = r$median, blife = r$blife, blife_low = r$blife_low, blife_high = r$blife_high)
if (has_mission) row <- c(row, list(mission_r = r$mission_r, mission_low = r$mission_low, mission_high = r$mission_high))
row
})
bl <- sprintf("B%g", b_percent)
columns <- list(
list(key = "family", label = "Family", type = "string"), list(key = "parameters", label = "Parameters", type = "string"),
list(key = "loglik", label = "log L", type = "number"), list(key = "aic", label = "AIC", type = "number"), list(key = "bic", label = "BIC", type = "number"),
list(key = "delta_aic", label = "ΔAIC", type = "number"), list(key = "weight", label = "Akaike weight", type = "number"),
list(key = "km_distance", label = "Gap from Kaplan–Meier", type = "number"), list(key = "mttf", label = "Mean life", type = "number"),
list(key = "median", label = "Median life", type = "number"), list(key = "blife", label = bl, type = "number"),
list(key = "blife_low", label = paste(pct, "CI low"), type = "number"), list(key = "blife_high", label = paste(pct, "CI high"), type = "number")
)
if (has_mission) {
columns <- c(columns, 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 <- list(list(key = "families", title = "Families ranked by AIC", columns = columns, rows = fam_rows))
if (length(test_rows)) {
tables[[2]] <- list(key = "nested", title = "Likelihood-ratio tests of nested families", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "lr", label = "χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = test_rows)
}
cs_publish(list(
method = "life.distribution",
methodVersion = "1.0.1",
title = "Distribution ID",
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%s fits best by AIC (%d units, %d failures); %s = %s, mean life %s.", top$label, n, events, bl, cs_fmt_num(top$blife), cs_fmt_num(top$mttf)),
apa = sprintf("%s, AIC = %s, %s = %s, %s CI [%s, %s]", top$label, cs_fmt_num(top$aic), bl, cs_fmt_num(top$blife), pct, cs_fmt_num(top$blife_low), cs_fmt_num(top$blife_high)),
statistics = list(list(key = "events", label = "Failures", value = events, format = "integer"), list(key = "censored", label = "Censored", value = n - events, format = "integer"),
list(key = "best_mttf", label = "Mean life", value = top$mttf), list(key = "best_blife", label = bl, value = top$blife)),
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("Failure: %s. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits.", event_label)), extra_notes),
charts = charts,
values = values
))
Log-logistic, AIC = 1039.22, B5 = 233.11, 95% CI [158.28, 343.32]
- Failures
- 60
- Censored
- 60
- Mean life
- 2975.78
- B5
- 233.11
Assumptions
- Non-informative censoring — 60 of 120 units are censored; check that they stopped for reasons unrelated to their risk.
- Number of failures — 60 failures.
- Fit against Kaplan–Meier — The best family's largest gap from the Kaplan–Meier curve is 0.036.
Families ranked by AIC
| Family | Parameters | log L | AIC | BIC | ΔAIC | Akaike weight | Gap from Kaplan–Meier | Mean life | Median life | B5 | 95% CI low | 95% CI high | R(500) | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Log-logistic | μ (log time) = 7.268, σ (log time) = 0.6168 | −517.61 | 1039.22 | 1044.80 | 0 | 0.2212 | 0.0361 | 2975.78 | 1433.32 | 233.11 | 158.28 | 343.32 | 0.8465 | 0.7821 | 0.8944 |
| Gamma | Shape k = 1.527, Rate = 0.0008343 | −517.70 | 1039.40 | 1044.97 | 0.1753 | 0.2026 | 0.0421 | 1830.73 | 1450.34 | 221.16 | 142.82 | 342.47 | 0.8483 | 0.7871 | 0.8942 |
| Weibull | Shape β = 1.342, Scale η = 1919 | −517.95 | 1039.90 | 1045.48 | 0.6778 | 0.1576 | 0.0468 | 1761.71 | 1460.41 | 209.79 | 133.64 | 329.33 | 0.8483 | 0.7856 | 0.8951 |
| Weibull (3-parameter) | Shape β = 1.195, Scale η = 1915, Threshold γ = 50.46 | −517.04 | 1040.08 | 1048.44 | 0.8519 | 0.1445 | 0.0426 | 1854.04 | 1459.81 | 209.95 | 142.69 | 308.90 | 0.8378 | 0.7739 | 0.8863 |
| Log-normal | μ (log time) = 7.28, σ (log time) = 1.112 | −518.14 | 1040.28 | 1045.86 | 1.060 | 0.1302 | 0.0539 | 2693.18 | 1450.87 | 232.85 | 166.80 | 325.07 | 0.8309 | 0.7678 | 0.8796 |
| Generalized gamma | μ (log time) = 7.443, σ (log time) = 0.9203, Q = 0.5307 | −517.54 | 1041.08 | 1049.44 | 1.857 | 0.0874 | 0.0382 | 2006.19 | 1444.07 | 227.93 | 152.50 | 340.65 | 0.8432 | 0.7769 | 0.8924 |
| Gompertz | Shape b = 0.0004422, Rate a = 0.0003274 | −519.39 | 1042.78 | 1048.36 | 3.558 | 0.0373 | 0.0562 | 1642.77 | 1494.17 | 151.48 | 99.576 | 230.45 | 0.8326 | 0.7688 | 0.8815 |
| Exponential | Rate λ = 0.00046 | −521.06 | 1044.12 | 1046.91 | 4.897 | 0.0191 | 0.0796 | 2174.03 | 1506.92 | 111.51 | 86.584 | 143.62 | 0.7945 | 0.7445 | 0.8370 |
Likelihood-ratio tests of nested families
| Test | χ² | df | p |
|---|---|---|---|
| Weibull vs exponential (shape = 1) | 6.219 | 1 | .013 |
| Generalized gamma vs Weibull (Q = 1) | 0.8211 | 1 | .365 |
| Generalized gamma vs log-normal (Q = 0) | 1.203 | 1 | .273 |
| Generalized gamma vs gamma (Q = σ) | 0.3185 | 1 | .573 |
- Failure: failed = 1. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Distribution ID for life data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method life.distribution 1.0.1 · spec fbb02e8d5167dd58
# 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 numpy as np
import pandas as pd
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 # censored maximum likelihood, written from the texts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/life_devices_sim.parquet", columns=["hours", "failed"])
n_input = len(df)
df = df.dropna(subset=["hours", "failed"]) # 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, ["hours", "failed"]) # 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)
# %% Fit the families
if (t <= 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="positive for a life distribution", count=int((t <= 0).sum()))
n, events = int(t.size), int(ev.sum())
cs.check_rows(n, 3, "Distribution ID")
check_not_constant(t, tcol) # with one time for every unit no family can be fitted
if events < 3:
cs.cs_error("CS_E_UNDEFINED", what="Distribution ID", reason=f"it needs at least 3 failures, and there are {events}")
conf = 0.95
b_percent = 5
mission = 500 # reliability is reported at this time
families = None
res = lf.life_compare(t, ev, families=families, b_percent=b_percent, mission=mission, conf=conf)
fits, rows, best = res["fits"], res["rows"], res["best"]
ranked = [r for r in rows if r["estimable"]]
if not ranked:
cs.cs_error("CS_E_NO_CONVERGENCE", what="The distribution fits")
top = ranked[0]
second = ranked[1] if len(ranked) > 1 else None
# %% Values
values = {
"n": n, "events": events, "censored": n - events, "censor_share": (n - events) / n, "event_label": event_label,
"best": best, "best_label": top["label"], "best_aic": top["aic"], "second_label": second["label"] if second else None, "second_delta": second["delta_aic"] if second else None,
"best_mttf": top["mttf"], "best_median": top["median"], "best_blife": top["blife"], "best_blife_low": top["blife_low"], "best_blife_high": top["blife_high"],
"best_mission_r": top["mission_r"] if mission is not None else None, "best_mission_low": top["mission_low"] if mission is not None else None,
"best_mission_high": top["mission_high"] if mission is not None else None, "b_percent": b_percent, "mission_time": mission,
"lr_weibull_exp": None, "lr_weibull_exp_p": None, "weibull_shape": None,
}
for r in rows:
f = r["family"]
if not r["estimable"]:
continue
for key in ("loglik", "aic", "bic", "delta_aic", "weight", "km_distance", "mttf", "median", "blife", "blife_low", "blife_high"):
values[f"{key}[{f}]"] = r[key]
if mission is not None:
for key in ("mission_r", "mission_low", "mission_high"):
values[f"{key}[{f}]"] = r[key]
for par in lf.life_params(fits[f]):
values[f"par[{f}:{par['name']}]"], values[f"par_se[{f}:{par['name']}]"] = par["value"], par["se"]
if "weibull" in fits and fits["weibull"]["estimable"]:
values["weibull_shape"] = lf.life_params(fits["weibull"])[0]["value"]
test_rows = []
TEST_LABEL = {"weibull_vs_exponential": "Weibull vs exponential (shape = 1)", "gengamma_vs_weibull": "Generalized gamma vs Weibull (Q = 1)",
"gengamma_vs_lognormal": "Generalized gamma vs log-normal (Q = 0)", "gengamma_vs_gamma": "Generalized gamma vs gamma (Q = σ)"}
for key, tst in res["tests"].items():
if tst is None:
continue
values[f"lr[{key}]"], values[f"lr_p[{key}]"] = tst["lr"], tst["p"]
test_rows.append({"test": TEST_LABEL[key], "lr": tst["lr"], "df": tst["df"], "p": tst["p"]})
if key == "weibull_vs_exponential":
values["lr_weibull_exp"], values["lr_weibull_exp_p"] = tst["lr"], tst["p"]
# %% Assumptions
gap = top["km_distance"]
assumptions = [
{"key": "censoring", "label": "Non-informative censoring", "status": "info", "detail": f"{n - events} of {n} units are censored; check that they stopped for reasons unrelated to their risk."},
{"key": "sample_size", "label": "Number of failures", "status": "warn" if events < 20 else "pass",
"detail": f"{events} failures: too few to rank families reliably, so several may be equally plausible." if events < 20 else f"{events} failures."},
{"key": "fit_gap", "label": "Fit against Kaplan–Meier", "status": "warn" if gap > 0.15 else "pass",
"detail": f"The best family's largest gap from the Kaplan–Meier curve is {gap:.3f}" + ("; none of these families follows the data closely." if gap > 0.15 else ".")},
]
skipped = [r for r in rows if not r["estimable"] or r.get("note")]
extra_notes = [f"{r['label']}: {r['note']}" for r in skipped if r.get("note")]
# %% Charts
grid = np.linspace(float(t.min()) * 0.5, float(t.max()), 60)
papers = [p for p in ("weibull", "lognormal", "exponential", "loglogistic") if p in fits and fits[p]["estimable"]]
times = np.concatenate([t] + [grid for _ in papers])
fitted = np.concatenate([np.full(n, np.nan)] + [1 - lf.life_surv(fits[p], grid) for p in papers])
fam = ["data"] * n + [p for p in papers for _ in grid]
evs = np.concatenate([ev.astype(float), np.full(grid.size * len(papers), np.nan)])
levels = ["data"] + papers
charts = [
cs.chart("id", "dist-id-grid", f"Distribution ID: {tcol}", {
"time": cs.col(tcol, times, "numeric"), "event": cs.col("Failed", evs, "numeric"),
"fit": cs.col("Fitted F(t)", fitted, "numeric"), "family": cs.col("Series", fam, "categorical", levels=levels),
}),
]
curve_fams = [r["family"] for r in ranked[:3]]
line = np.linspace(0.0, float(t.max()), 101)
km = lf.km_steps(t, ev)
rel_t = np.concatenate([[0.0], km["time"]] + [line for _ in curve_fams])
rel_s = np.concatenate([[1.0], km["surv"]] + [lf.life_surv(fits[f], line) for f in curve_fams])
rel_g = ["Kaplan–Meier"] * (km["time"].size + 1) + [lf.LABELS[f] for f in curve_fams for _ in line]
charts.append(cs.chart("reliability", "reliability-curve", f"Reliability: {tcol}", {
"time": cs.col(tcol, rel_t, "numeric"), "surv": cs.col("Reliability", rel_s, "numeric"),
"strata": cs.col("Curve", rel_g, "categorical", levels=["Kaplan–Meier"] + [lf.LABELS[f] for f in curve_fams]),
}, controls={"mission": mission if mission is not None else 0, "bLife": top["blife"]}))
hz_t = line[1:]
charts.append(cs.chart("hazard", "hazard-plot", f"Fitted hazard: {tcol}", {
"time": cs.col(tcol, np.concatenate([hz_t for _ in curve_fams]), "numeric"),
"hazard": cs.col("Hazard", np.concatenate([lf.life_hazard(fits[f], hz_t) for f in curve_fams]), "numeric"),
"strata": cs.col("Family", [lf.LABELS[f] for f in curve_fams for _ in hz_t], "categorical", levels=[lf.LABELS[f] for f in curve_fams]),
}))
# %% Result
pct = f"{conf:.0%}"
fam_rows = []
for r in ranked:
pars = ", ".join(f"{p['label']} = {p['value']:.4g}" for p in lf.life_params(fits[r["family"]])) # 4 digits: rates can be 0.0005
row = {"family": r["label"], "parameters": pars, "loglik": r["loglik"], "aic": r["aic"], "bic": r["bic"], "delta_aic": r["delta_aic"], "weight": r["weight"],
"km_distance": r["km_distance"], "mttf": r["mttf"] if np.isfinite(r["mttf"]) else None, "median": r["median"], "blife": r["blife"], "blife_low": r["blife_low"], "blife_high": r["blife_high"]}
if mission is not None:
row.update({"mission_r": r["mission_r"], "mission_low": r["mission_low"], "mission_high": r["mission_high"]})
fam_rows.append(row)
bl = f"B{b_percent:g}"
columns = [
{"key": "family", "label": "Family", "type": "string"}, {"key": "parameters", "label": "Parameters", "type": "string"},
{"key": "loglik", "label": "log L", "type": "number"}, {"key": "aic", "label": "AIC", "type": "number"}, {"key": "bic", "label": "BIC", "type": "number"},
{"key": "delta_aic", "label": "ΔAIC", "type": "number"}, {"key": "weight", "label": "Akaike weight", "type": "number"},
{"key": "km_distance", "label": "Gap from Kaplan–Meier", "type": "number"}, {"key": "mttf", "label": "Mean life", "type": "number"},
{"key": "median", "label": "Median life", "type": "number"}, {"key": "blife", "label": bl, "type": "number"},
{"key": "blife_low", "label": f"{pct} CI low", "type": "number"}, {"key": "blife_high", "label": f"{pct} CI high", "type": "number"},
]
if mission is not None:
columns += [{"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 = [{"key": "families", "title": "Families ranked by AIC", "columns": columns, "rows": fam_rows}]
if test_rows:
tables.append({"key": "nested", "title": "Likelihood-ratio tests of nested families", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "lr", "label": "χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": test_rows})
cs.publish({
"method": "life.distribution",
"methodVersion": "1.0.1",
"title": "Distribution ID",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": n,
"summary": f"{top['label']} fits best by AIC ({n} units, {events} failures); {bl} = {cs.fmt_num(top['blife'])}, mean life {cs.fmt_num(top['mttf'])}.",
"apa": f"{top['label']}, AIC = {cs.fmt_num(top['aic'])}, {bl} = {cs.fmt_num(top['blife'])}, {pct} CI [{cs.fmt_num(top['blife_low'])}, {cs.fmt_num(top['blife_high'])}]",
"statistics": [{"key": "events", "label": "Failures", "value": events, "format": "integer"}, {"key": "censored", "label": "Censored", "value": n - events, "format": "integer"},
{"key": "best_mttf", "label": "Mean life", "value": top["mttf"]}, {"key": "best_blife", "label": bl, "value": top["blife"]}],
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Failure: {event_label}. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits."] + extra_notes,
"charts": charts,
"values": values,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
A probability plot rescales its axes so that data from a family fall on a straight line, with censored units handled through median ranks. Look at the grid for the panel where the points hug the line, especially among the earliest failures.
The card also compares each fit with the Kaplan–Meier curve. A large gap means none of the families fits.
Numbers that matter
ReadA B-lifeB-lifeThe time by which a stated percent of units has failed; B10 is the age at which 10% are gone. is the time by which a given share of units have failed. Here, B5 is 233 hours, with an interval from 158 to 343.
At a mission time of 500 hours, 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. is 0.846, from 0.782 to 0.894.
The mean lifeMean time to failureThe average lifetime under a fitted distribution; it depends heavily on the tail, far beyond most observed failures. is 2,976. Half the test was still running, so the mean leans heavily on the fitted tail.
Does the choice of family matter?
ReflectOpen the table of families on the card and compare the B5 column. Most of the two-parameter families agree closely with each other, and the exponential gives a much shorter life.
Families that agree in the middle of the data can disagree far out in the tails, and the tails are where warranty and safety questions live. Which of your own decisions depend on the earliest failures?
A complete sample
In the appBall bearings were tested until all 23 failed.
Gamma, AIC = 230.06, B10 = 31.61, 95% CI [22.10, 45.20]
- Failures
- 23
- Censored
- 0
- Mean life
- 72.221
- B10
- 31.605
Assumptions
- Non-informative censoring — 0 of 23 units are censored; check that they stopped for reasons unrelated to their risk.
- Number of failures — 23 failures.
- Fit against Kaplan–Meier — The best family's largest gap from the Kaplan–Meier curve is 0.123.
Families ranked by AIC
| Family | Parameters | log L | AIC | BIC | ΔAIC | Akaike weight | Gap from Kaplan–Meier | Mean life | Median life | B10 | 95% CI low | 95% CI high | R(50) | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Gamma | Shape k = 4.025, Rate = 0.05573 | −113.03 | 230.06 | 232.33 | 0 | 0.2491 | 0.1229 | 72.221 | 66.336 | 31.605 | 22.097 | 45.204 | 0.6997 | 0.5319 | 0.8269 |
| Log-normal | μ (log time) = 4.15, σ (log time) = 0.5217 | −113.13 | 230.26 | 232.53 | 0.1975 | 0.2256 | 0.0897 | 72.709 | 63.458 | 32.519 | 24.388 | 43.360 | 0.6761 | 0.5078 | 0.8086 |
| Log-logistic | μ (log time) = 4.159, σ (log time) = 0.2988 | −113.37 | 230.75 | 233.02 | 0.6864 | 0.1767 | 0.0944 | 74.459 | 63.995 | 33.190 | 24.403 | 45.141 | 0.6955 | 0.5147 | 0.8310 |
| Weibull | Shape β = 2.102, Scale η = 81.87 | −113.69 | 231.38 | 233.65 | 1.324 | 0.1284 | 0.1510 | 72.515 | 68.773 | 28.065 | 18.056 | 43.621 | 0.7014 | 0.5307 | 0.8299 |
| Weibull (3-parameter) | Shape β = 1.594, Scale η = 63.87, Threshold γ = 14.88 | −112.85 | 231.70 | 235.11 | 1.641 | 0.1096 | 0.1174 | 72.165 | 65.630 | 30.445 | 22.497 | 41.200 | 0.6801 | 0.5083 | 0.8139 |
| Generalized gamma | μ (log time) = 4.23, σ (log time) = 0.51, Q = 0.3076 | −112.97 | 231.94 | 235.34 | 1.879 | 0.0973 | 0.1095 | 72.230 | 65.186 | 32.076 | 22.966 | 44.800 | 0.6915 | 0.5143 | 0.8259 |
| Gompertz | Shape b = 0.01632, Rate a = 0.005399 | −115.98 | 235.96 | 238.23 | 5.904 | 0.0130 | 0.1551 | 71.162 | 69.226 | 16.940 | 9.157 | 31.340 | 0.6588 | 0.4903 | 0.7949 |
| Exponential | Rate λ = 0.01385 | −121.43 | 244.87 | 246.00 | 14.808 | 0.0002 | 0.3068 | 72.221 | 50.060 | 7.609 | 5.057 | 11.451 | 0.5004 | 0.3625 | 0.6383 |
Likelihood-ratio tests of nested families
| Test | χ² | df | p |
|---|---|---|---|
| Weibull vs exponential (shape = 1) | 15.484 | 1 | < .001 |
| Generalized gamma vs Weibull (Q = 1) | 1.445 | 1 | .229 |
| Generalized gamma vs log-normal (Q = 0) | 0.3186 | 1 | .572 |
| Generalized gamma vs gamma (Q = σ) | 0.1211 | 1 | .728 |
- Failure: every unit failed. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits.
The exact R script · R R version 4.5.1 (2025-06-13)
# Distribution ID for life data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method life.distribution 1.0.1 · spec 43d4f59a594cd72b
# Dataset: life_bearings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # censored maximum likelihood, written from the texts
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/life_bearings.parquet", col_select = c("revs")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("revs")]), , 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("revs")) # infinite values stop the run (registry/errors.yaml)
# %% Every unit failed
tcol <- "revs"
tt <- as.numeric(df[[tcol]])
ev <- rep(TRUE, length(tt))
event_label <- "every unit failed"
# %% Fit the families
if (any(tt <= 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "positive for a life distribution", count = sum(tt <= 0))
n <- length(tt)
events <- sum(ev)
cs_check_rows(n, 3, "Distribution ID")
cs_check_not_constant(tt, tcol) # with one time for every unit no family can be fitted
if (events < 3) cs_error("CS_E_UNDEFINED", what = "Distribution ID", reason = sprintf("it needs at least 3 failures, and there are %d", events))
conf <- 0.95
b_percent <- 10
mission <- 50 # reliability is reported at this time
families <- NULL
res <- cs_life_compare(tt, ev, families = families, b_percent = b_percent, mission = mission, conf = conf)
fits <- res$fits
rows <- res$rows
best <- res$best
ranked <- Filter(function(r) isTRUE(r$estimable), rows)
if (length(ranked) == 0) cs_error("CS_E_NO_CONVERGENCE", what = "The distribution fits")
top <- ranked[[1]]
second <- if (length(ranked) > 1) ranked[[2]] else NULL
has_mission <- !is.null(mission)
# %% Values
values <- list(
n = n, events = events, censored = n - events, censor_share = (n - events) / n, event_label = event_label,
best = best, best_label = top$label, best_aic = top$aic, second_label = if (!is.null(second)) second$label else NA, second_delta = if (!is.null(second)) second$delta_aic else NA,
best_mttf = top$mttf, best_median = top$median, best_blife = top$blife, best_blife_low = top$blife_low, best_blife_high = top$blife_high,
best_mission_r = if (has_mission) top$mission_r else NA, best_mission_low = if (has_mission) top$mission_low else NA,
best_mission_high = if (has_mission) top$mission_high else NA, b_percent = b_percent, mission_time = if (has_mission) mission else NA,
lr_weibull_exp = NA, lr_weibull_exp_p = NA, weibull_shape = NA
)
for (r in rows) {
f <- r$family
if (!isTRUE(r$estimable)) next
for (key in c("loglik", "aic", "bic", "delta_aic", "weight", "km_distance", "mttf", "median", "blife", "blife_low", "blife_high")) {
values[[sprintf("%s[%s]", key, f)]] <- r[[key]]
}
if (has_mission) for (key in c("mission_r", "mission_low", "mission_high")) values[[sprintf("%s[%s]", key, f)]] <- r[[key]]
for (par in cs_life_params(fits[[f]])) {
values[[sprintf("par[%s:%s]", f, par$name)]] <- par$value
values[[sprintf("par_se[%s:%s]", f, par$name)]] <- par$se
}
}
if (!is.null(fits$weibull) && isTRUE(fits$weibull$estimable)) values$weibull_shape <- cs_life_params(fits$weibull)[[1]]$value
test_rows <- list()
test_label <- c(weibull_vs_exponential = "Weibull vs exponential (shape = 1)", gengamma_vs_weibull = "Generalized gamma vs Weibull (Q = 1)",
gengamma_vs_lognormal = "Generalized gamma vs log-normal (Q = 0)", gengamma_vs_gamma = "Generalized gamma vs gamma (Q = σ)")
for (key in names(test_label)) {
tst <- res$tests[[key]]
if (is.null(tst)) next
values[[sprintf("lr[%s]", key)]] <- tst$lr
values[[sprintf("lr_p[%s]", key)]] <- tst$p
test_rows[[length(test_rows) + 1]] <- list(test = unname(test_label[[key]]), lr = tst$lr, df = tst$df, p = tst$p)
if (key == "weibull_vs_exponential") {
values$lr_weibull_exp <- tst$lr
values$lr_weibull_exp_p <- tst$p
}
}
# %% Assumptions
gap <- top$km_distance
assumptions <- list(
list(key = "censoring", label = "Non-informative censoring", status = "info", detail = sprintf("%d of %d units are censored; check that they stopped for reasons unrelated to their risk.", n - events, n)),
list(key = "sample_size", label = "Number of failures", status = if (events < 20) "warn" else "pass",
detail = if (events < 20) sprintf("%d failures: too few to rank families reliably, so several may be equally plausible.", events) else sprintf("%d failures.", events)),
list(key = "fit_gap", label = "Fit against Kaplan–Meier", status = if (gap > 0.15) "warn" else "pass",
detail = paste0(sprintf("The best family's largest gap from the Kaplan–Meier curve is %.3f", gap), if (gap > 0.15) "; none of these families follows the data closely." else "."))
)
extra_notes <- list()
for (r in rows) if (!is.null(r$note)) extra_notes[[length(extra_notes) + 1]] <- sprintf("%s: %s", r$label, r$note)
# %% Charts
grid <- seq(min(tt) * 0.5, max(tt), length.out = 60)
papers <- Filter(function(p) !is.null(fits[[p]]) && isTRUE(fits[[p]]$estimable), c("weibull", "lognormal", "exponential", "loglogistic"))
times <- c(tt, rep(grid, length(papers)))
fitted <- c(rep(NaN, n), unlist(lapply(papers, function(p) 1 - cs_life_surv(fits[[p]], grid))))
fam <- c(rep("data", n), rep(papers, each = length(grid)))
evs <- c(as.numeric(ev), rep(NaN, length(grid) * length(papers)))
charts <- list(
cs_chart("id", "dist-id-grid", sprintf("Distribution ID: %s", tcol), list(
time = cs_col(tcol, times, "numeric"), event = cs_col("Failed", evs, "numeric"),
fit = cs_col("Fitted F(t)", fitted, "numeric"), family = cs_col("Series", fam, "categorical", levels = c("data", papers))
))
)
curve_fams <- vapply(ranked[seq_len(min(3, length(ranked)))], function(r) r$family, character(1))
curve_labels <- vapply(ranked[seq_len(min(3, length(ranked)))], function(r) r$label, character(1))
line <- seq(0, max(tt), length.out = 101)
km <- cs_life_km(tt, ev)
rel_t <- c(0, km$time, rep(line, length(curve_fams)))
rel_s <- c(1, km$surv, unlist(lapply(curve_fams, function(f) cs_life_surv(fits[[f]], line))))
rel_g <- c(rep("Kaplan–Meier", length(km$time) + 1), rep(curve_labels, each = length(line)))
charts[[2]] <- cs_chart("reliability", "reliability-curve", sprintf("Reliability: %s", tcol), list(
time = cs_col(tcol, rel_t, "numeric"), surv = cs_col("Reliability", rel_s, "numeric"),
strata = cs_col("Curve", rel_g, "categorical", levels = c("Kaplan–Meier", curve_labels))
), controls = list(mission = if (has_mission) mission else 0, bLife = top$blife))
hz_t <- line[-1]
charts[[3]] <- cs_chart("hazard", "hazard-plot", sprintf("Fitted hazard: %s", tcol), list(
time = cs_col(tcol, rep(hz_t, length(curve_fams)), "numeric"),
hazard = cs_col("Hazard", unlist(lapply(curve_fams, function(f) cs_life_hazard(fits[[f]], hz_t))), "numeric"),
strata = cs_col("Family", rep(curve_labels, each = length(hz_t)), "categorical", levels = curve_labels)
))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
fam_rows <- lapply(ranked, function(r) {
pars <- paste(vapply(cs_life_params(fits[[r$family]]), function(p) sprintf("%s = %.4g", p$label, p$value), character(1)), collapse = ", ") # 4 digits: rates can be 0.0005
row <- list(family = r$label, parameters = pars, loglik = r$loglik, aic = r$aic, bic = r$bic, delta_aic = r$delta_aic, weight = r$weight,
km_distance = r$km_distance, mttf = if (is.finite(r$mttf)) r$mttf else NA_real_, median = r$median, blife = r$blife, blife_low = r$blife_low, blife_high = r$blife_high)
if (has_mission) row <- c(row, list(mission_r = r$mission_r, mission_low = r$mission_low, mission_high = r$mission_high))
row
})
bl <- sprintf("B%g", b_percent)
columns <- list(
list(key = "family", label = "Family", type = "string"), list(key = "parameters", label = "Parameters", type = "string"),
list(key = "loglik", label = "log L", type = "number"), list(key = "aic", label = "AIC", type = "number"), list(key = "bic", label = "BIC", type = "number"),
list(key = "delta_aic", label = "ΔAIC", type = "number"), list(key = "weight", label = "Akaike weight", type = "number"),
list(key = "km_distance", label = "Gap from Kaplan–Meier", type = "number"), list(key = "mttf", label = "Mean life", type = "number"),
list(key = "median", label = "Median life", type = "number"), list(key = "blife", label = bl, type = "number"),
list(key = "blife_low", label = paste(pct, "CI low"), type = "number"), list(key = "blife_high", label = paste(pct, "CI high"), type = "number")
)
if (has_mission) {
columns <- c(columns, 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 <- list(list(key = "families", title = "Families ranked by AIC", columns = columns, rows = fam_rows))
if (length(test_rows)) {
tables[[2]] <- list(key = "nested", title = "Likelihood-ratio tests of nested families", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "lr", label = "χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = test_rows)
}
cs_publish(list(
method = "life.distribution",
methodVersion = "1.0.1",
title = "Distribution ID",
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%s fits best by AIC (%d units, %d failures); %s = %s, mean life %s.", top$label, n, events, bl, cs_fmt_num(top$blife), cs_fmt_num(top$mttf)),
apa = sprintf("%s, AIC = %s, %s = %s, %s CI [%s, %s]", top$label, cs_fmt_num(top$aic), bl, cs_fmt_num(top$blife), pct, cs_fmt_num(top$blife_low), cs_fmt_num(top$blife_high)),
statistics = list(list(key = "events", label = "Failures", value = events, format = "integer"), list(key = "censored", label = "Censored", value = n - events, format = "integer"),
list(key = "best_mttf", label = "Mean life", value = top$mttf), list(key = "best_blife", label = bl, value = top$blife)),
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("Failure: %s. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits.", event_label)), extra_notes),
charts = charts,
values = values
))
Gamma, AIC = 230.06, B10 = 31.61, 95% CI [22.10, 45.20]
- Failures
- 23
- Censored
- 0
- Mean life
- 72.221
- B10
- 31.605
Assumptions
- Non-informative censoring — 0 of 23 units are censored; check that they stopped for reasons unrelated to their risk.
- Number of failures — 23 failures.
- Fit against Kaplan–Meier — The best family's largest gap from the Kaplan–Meier curve is 0.123.
Families ranked by AIC
| Family | Parameters | log L | AIC | BIC | ΔAIC | Akaike weight | Gap from Kaplan–Meier | Mean life | Median life | B10 | 95% CI low | 95% CI high | R(50) | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Gamma | Shape k = 4.025, Rate = 0.05573 | −113.03 | 230.06 | 232.33 | 0 | 0.2491 | 0.1229 | 72.221 | 66.336 | 31.605 | 22.097 | 45.204 | 0.6997 | 0.5319 | 0.8269 |
| Log-normal | μ (log time) = 4.15, σ (log time) = 0.5217 | −113.13 | 230.26 | 232.53 | 0.1975 | 0.2256 | 0.0897 | 72.709 | 63.458 | 32.519 | 24.388 | 43.360 | 0.6761 | 0.5078 | 0.8086 |
| Log-logistic | μ (log time) = 4.159, σ (log time) = 0.2988 | −113.37 | 230.75 | 233.02 | 0.6864 | 0.1767 | 0.0944 | 74.459 | 63.995 | 33.190 | 24.403 | 45.141 | 0.6955 | 0.5147 | 0.8310 |
| Weibull | Shape β = 2.102, Scale η = 81.87 | −113.69 | 231.38 | 233.65 | 1.324 | 0.1284 | 0.1510 | 72.515 | 68.773 | 28.065 | 18.056 | 43.621 | 0.7014 | 0.5307 | 0.8299 |
| Weibull (3-parameter) | Shape β = 1.594, Scale η = 63.87, Threshold γ = 14.88 | −112.85 | 231.70 | 235.11 | 1.641 | 0.1096 | 0.1174 | 72.165 | 65.630 | 30.445 | 22.497 | 41.200 | 0.6801 | 0.5083 | 0.8139 |
| Generalized gamma | μ (log time) = 4.23, σ (log time) = 0.51, Q = 0.3076 | −112.97 | 231.94 | 235.34 | 1.879 | 0.0973 | 0.1095 | 72.230 | 65.186 | 32.076 | 22.966 | 44.800 | 0.6915 | 0.5143 | 0.8259 |
| Gompertz | Shape b = 0.01632, Rate a = 0.005399 | −115.98 | 235.96 | 238.23 | 5.904 | 0.0130 | 0.1551 | 71.162 | 69.226 | 16.940 | 9.157 | 31.340 | 0.6588 | 0.4903 | 0.7949 |
| Exponential | Rate λ = 0.01385 | −121.43 | 244.87 | 246.00 | 14.808 | 0.0002 | 0.3068 | 72.221 | 50.060 | 7.609 | 5.057 | 11.451 | 0.5004 | 0.3625 | 0.6383 |
Likelihood-ratio tests of nested families
| Test | χ² | df | p |
|---|---|---|---|
| Weibull vs exponential (shape = 1) | 15.484 | 1 | < .001 |
| Generalized gamma vs Weibull (Q = 1) | 1.445 | 1 | .229 |
| Generalized gamma vs log-normal (Q = 0) | 0.3186 | 1 | .572 |
| Generalized gamma vs gamma (Q = σ) | 0.1211 | 1 | .728 |
- Failure: every unit failed. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Distribution ID for life data
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method life.distribution 1.0.1 · spec 43d4f59a594cd72b
# Dataset: life_bearings (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
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 # censored maximum likelihood, written from the texts
# %% Data
df = pd.read_parquet("tests/parity/fixtures/life_bearings.parquet", columns=["revs"])
n_input = len(df)
df = df.dropna(subset=["revs"]) # 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, ["revs"]) # infinite values stop the run (registry/errors.yaml)
# %% Every unit failed
tcol = "revs"
t = df[tcol].to_numpy(dtype=float)
ev = np.ones(len(t), dtype=bool)
event_label = "every unit failed"
# %% Fit the families
if (t <= 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="positive for a life distribution", count=int((t <= 0).sum()))
n, events = int(t.size), int(ev.sum())
cs.check_rows(n, 3, "Distribution ID")
check_not_constant(t, tcol) # with one time for every unit no family can be fitted
if events < 3:
cs.cs_error("CS_E_UNDEFINED", what="Distribution ID", reason=f"it needs at least 3 failures, and there are {events}")
conf = 0.95
b_percent = 10
mission = 50 # reliability is reported at this time
families = None
res = lf.life_compare(t, ev, families=families, b_percent=b_percent, mission=mission, conf=conf)
fits, rows, best = res["fits"], res["rows"], res["best"]
ranked = [r for r in rows if r["estimable"]]
if not ranked:
cs.cs_error("CS_E_NO_CONVERGENCE", what="The distribution fits")
top = ranked[0]
second = ranked[1] if len(ranked) > 1 else None
# %% Values
values = {
"n": n, "events": events, "censored": n - events, "censor_share": (n - events) / n, "event_label": event_label,
"best": best, "best_label": top["label"], "best_aic": top["aic"], "second_label": second["label"] if second else None, "second_delta": second["delta_aic"] if second else None,
"best_mttf": top["mttf"], "best_median": top["median"], "best_blife": top["blife"], "best_blife_low": top["blife_low"], "best_blife_high": top["blife_high"],
"best_mission_r": top["mission_r"] if mission is not None else None, "best_mission_low": top["mission_low"] if mission is not None else None,
"best_mission_high": top["mission_high"] if mission is not None else None, "b_percent": b_percent, "mission_time": mission,
"lr_weibull_exp": None, "lr_weibull_exp_p": None, "weibull_shape": None,
}
for r in rows:
f = r["family"]
if not r["estimable"]:
continue
for key in ("loglik", "aic", "bic", "delta_aic", "weight", "km_distance", "mttf", "median", "blife", "blife_low", "blife_high"):
values[f"{key}[{f}]"] = r[key]
if mission is not None:
for key in ("mission_r", "mission_low", "mission_high"):
values[f"{key}[{f}]"] = r[key]
for par in lf.life_params(fits[f]):
values[f"par[{f}:{par['name']}]"], values[f"par_se[{f}:{par['name']}]"] = par["value"], par["se"]
if "weibull" in fits and fits["weibull"]["estimable"]:
values["weibull_shape"] = lf.life_params(fits["weibull"])[0]["value"]
test_rows = []
TEST_LABEL = {"weibull_vs_exponential": "Weibull vs exponential (shape = 1)", "gengamma_vs_weibull": "Generalized gamma vs Weibull (Q = 1)",
"gengamma_vs_lognormal": "Generalized gamma vs log-normal (Q = 0)", "gengamma_vs_gamma": "Generalized gamma vs gamma (Q = σ)"}
for key, tst in res["tests"].items():
if tst is None:
continue
values[f"lr[{key}]"], values[f"lr_p[{key}]"] = tst["lr"], tst["p"]
test_rows.append({"test": TEST_LABEL[key], "lr": tst["lr"], "df": tst["df"], "p": tst["p"]})
if key == "weibull_vs_exponential":
values["lr_weibull_exp"], values["lr_weibull_exp_p"] = tst["lr"], tst["p"]
# %% Assumptions
gap = top["km_distance"]
assumptions = [
{"key": "censoring", "label": "Non-informative censoring", "status": "info", "detail": f"{n - events} of {n} units are censored; check that they stopped for reasons unrelated to their risk."},
{"key": "sample_size", "label": "Number of failures", "status": "warn" if events < 20 else "pass",
"detail": f"{events} failures: too few to rank families reliably, so several may be equally plausible." if events < 20 else f"{events} failures."},
{"key": "fit_gap", "label": "Fit against Kaplan–Meier", "status": "warn" if gap > 0.15 else "pass",
"detail": f"The best family's largest gap from the Kaplan–Meier curve is {gap:.3f}" + ("; none of these families follows the data closely." if gap > 0.15 else ".")},
]
skipped = [r for r in rows if not r["estimable"] or r.get("note")]
extra_notes = [f"{r['label']}: {r['note']}" for r in skipped if r.get("note")]
# %% Charts
grid = np.linspace(float(t.min()) * 0.5, float(t.max()), 60)
papers = [p for p in ("weibull", "lognormal", "exponential", "loglogistic") if p in fits and fits[p]["estimable"]]
times = np.concatenate([t] + [grid for _ in papers])
fitted = np.concatenate([np.full(n, np.nan)] + [1 - lf.life_surv(fits[p], grid) for p in papers])
fam = ["data"] * n + [p for p in papers for _ in grid]
evs = np.concatenate([ev.astype(float), np.full(grid.size * len(papers), np.nan)])
levels = ["data"] + papers
charts = [
cs.chart("id", "dist-id-grid", f"Distribution ID: {tcol}", {
"time": cs.col(tcol, times, "numeric"), "event": cs.col("Failed", evs, "numeric"),
"fit": cs.col("Fitted F(t)", fitted, "numeric"), "family": cs.col("Series", fam, "categorical", levels=levels),
}),
]
curve_fams = [r["family"] for r in ranked[:3]]
line = np.linspace(0.0, float(t.max()), 101)
km = lf.km_steps(t, ev)
rel_t = np.concatenate([[0.0], km["time"]] + [line for _ in curve_fams])
rel_s = np.concatenate([[1.0], km["surv"]] + [lf.life_surv(fits[f], line) for f in curve_fams])
rel_g = ["Kaplan–Meier"] * (km["time"].size + 1) + [lf.LABELS[f] for f in curve_fams for _ in line]
charts.append(cs.chart("reliability", "reliability-curve", f"Reliability: {tcol}", {
"time": cs.col(tcol, rel_t, "numeric"), "surv": cs.col("Reliability", rel_s, "numeric"),
"strata": cs.col("Curve", rel_g, "categorical", levels=["Kaplan–Meier"] + [lf.LABELS[f] for f in curve_fams]),
}, controls={"mission": mission if mission is not None else 0, "bLife": top["blife"]}))
hz_t = line[1:]
charts.append(cs.chart("hazard", "hazard-plot", f"Fitted hazard: {tcol}", {
"time": cs.col(tcol, np.concatenate([hz_t for _ in curve_fams]), "numeric"),
"hazard": cs.col("Hazard", np.concatenate([lf.life_hazard(fits[f], hz_t) for f in curve_fams]), "numeric"),
"strata": cs.col("Family", [lf.LABELS[f] for f in curve_fams for _ in hz_t], "categorical", levels=[lf.LABELS[f] for f in curve_fams]),
}))
# %% Result
pct = f"{conf:.0%}"
fam_rows = []
for r in ranked:
pars = ", ".join(f"{p['label']} = {p['value']:.4g}" for p in lf.life_params(fits[r["family"]])) # 4 digits: rates can be 0.0005
row = {"family": r["label"], "parameters": pars, "loglik": r["loglik"], "aic": r["aic"], "bic": r["bic"], "delta_aic": r["delta_aic"], "weight": r["weight"],
"km_distance": r["km_distance"], "mttf": r["mttf"] if np.isfinite(r["mttf"]) else None, "median": r["median"], "blife": r["blife"], "blife_low": r["blife_low"], "blife_high": r["blife_high"]}
if mission is not None:
row.update({"mission_r": r["mission_r"], "mission_low": r["mission_low"], "mission_high": r["mission_high"]})
fam_rows.append(row)
bl = f"B{b_percent:g}"
columns = [
{"key": "family", "label": "Family", "type": "string"}, {"key": "parameters", "label": "Parameters", "type": "string"},
{"key": "loglik", "label": "log L", "type": "number"}, {"key": "aic", "label": "AIC", "type": "number"}, {"key": "bic", "label": "BIC", "type": "number"},
{"key": "delta_aic", "label": "ΔAIC", "type": "number"}, {"key": "weight", "label": "Akaike weight", "type": "number"},
{"key": "km_distance", "label": "Gap from Kaplan–Meier", "type": "number"}, {"key": "mttf", "label": "Mean life", "type": "number"},
{"key": "median", "label": "Median life", "type": "number"}, {"key": "blife", "label": bl, "type": "number"},
{"key": "blife_low", "label": f"{pct} CI low", "type": "number"}, {"key": "blife_high", "label": f"{pct} CI high", "type": "number"},
]
if mission is not None:
columns += [{"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 = [{"key": "families", "title": "Families ranked by AIC", "columns": columns, "rows": fam_rows}]
if test_rows:
tables.append({"key": "nested", "title": "Likelihood-ratio tests of nested families", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "lr", "label": "χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": test_rows})
cs.publish({
"method": "life.distribution",
"methodVersion": "1.0.1",
"title": "Distribution ID",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": n,
"summary": f"{top['label']} fits best by AIC ({n} units, {events} failures); {bl} = {cs.fmt_num(top['blife'])}, mean life {cs.fmt_num(top['mttf'])}.",
"apa": f"{top['label']}, AIC = {cs.fmt_num(top['aic'])}, {bl} = {cs.fmt_num(top['blife'])}, {pct} CI [{cs.fmt_num(top['blife_low'])}, {cs.fmt_num(top['blife_high'])}]",
"statistics": [{"key": "events", "label": "Failures", "value": events, "format": "integer"}, {"key": "censored", "label": "Censored", "value": n - events, "format": "integer"},
{"key": "best_mttf", "label": "Mean life", "value": top["mttf"]}, {"key": "best_blife", "label": bl, "value": top["blife"]}],
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Failure: {event_label}. Probability plots use median ranks (Benard's approximation) with Johnson's adjusted order numbers for censored units; lines are the maximum-likelihood fits."] + extra_notes,
"charts": charts,
"values": values,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
The event column says every unit failed. Gamma ranks first, 0.197 ahead of Log-normal. The Weibull's shape is 2.10.
With this few failures, treat the AIC order as provisional. The next lesson uses that shape.
Check your understanding
CheckpointCheck yourself
You remove all units that hadn't failed by the end of the test. What happens to your estimate of typical life?
Show the answer
Answer: b
Censored units tell you the part lasted at least that long. Removing them keeps mostly the early failures.
Check yourself
Technicians pull units from the test when they start to sound worn. What does this threaten?
Show the answer
Answer: a
Life models assume censored units have the same future risk as those still running at that age. Pulling the worst ones makes the product look better than it is.
Check yourself
A supplier reports B10 = 1,000 hours. What does this mean?
Show the answer
Answer: c
B-lives count failures from the start. So B10 means 90% of units are expected to survive to that time.
Try it
In the appIn the Quality studio, choose Life data & reliability, or start directly with Which distribution fits?. The Distribution ID step takes your time and failure columns.
import pandas as pd
from lifelines import WeibullFitter, LogNormalFitter, LogLogisticFitter
df = pd.read_csv("devices.csv")
for fitter in (WeibullFitter(), LogNormalFitter(), LogLogisticFitter()):
fitter.fit(df["hours"], event_observed=df["failed"])
print(type(fitter).__name__, round(fitter.AIC_, 2))library(survival)
df <- read.csv("devices.csv")
for (dist in c("weibull", "lognormal", "loglogistic")) {
fit <- survreg(Surv(hours, failed) ~ 1, df, dist = dist)
cat(dist, round(AIC(fit), 2), "\n")
}Recap
Recap- Units still running are data. Keep them in, as censored.
- A small AIC gap is a near tie, so use engineering knowledge and check the tails.
- Report B-lives and mission reliability with their intervals.
Concepts in this lesson