Skip to content

Which lifetime distribution?

Rank Weibull, log-normal, gamma and other families on censored failures, read probability plots, and see how little the fit can say about the far tail.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Explain why running units must be counted in a fit
  • Read a probability plot built from median ranks
  • Use AIC differences without declaring a winner too quickly

Read first

01

Why the family matters

Read

Most lifetime families look alike in the middle of the data, where your failures are. They part ways in the tails.

The decisions often live there: how many units fail in the first year? So you want to know which families the data support, and how far that support goes.

02

Still running

Predict

Predict first

A test ran 120 devices, and 60 of them hadn't failed when it stopped.

You drop those and fit a distribution to the 60 failures alone. What do your lifetime estimates look like?

Too shortAbout rightToo long
Reveal

Too short. Those running units are the long-lived ones, and each has a lower bound on its life. CensoredCensoringFollow-up ended before the event happened, so you only know the event time is later than observed. maximum likelihood uses that bound: a failure contributes its density, and a running unit its survival probability.

03

See the bias

Explore

Raise the censoring rate below, and compare the estimate that drops running units with the one that accounts for them.

FExplorable · 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?

How sure?
0.10
0.100
300
median6.9Truth7.5Kaplan–Meier3.4Drop censored3.3As events

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

04

Probability plots

Read

Each family has an axis scale on which its CDF is a straight line. Sort the failures, give each a plotting position, and look at whether the points follow the line.

Median ranksMedian ranksThe plotting position of the i-th failure, (i − 0.3)/(n + 0.4). Censored units raise the order numbers of later failures. are the usual plotting position:

Fi≈i−0.3n+0.4F_i \approx \frac{i - 0.3}{n + 0.4}

With censoring, a running unit shifts the ranks of the failures after it, rather than getting a point of its own.

Curvature means the family is wrong. Look at the low tail first, because that is where a decision usually sits.

05

Ranking by AIC

Read
Distribution IDRecorded · Python and R agreeRecorded 2026-11-17 · 177 values compared · largest relative difference 3.0e-8
R

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

FamilyParameterslog LAICBICΔAICAkaike weightGap from Kaplan–MeierMean lifeMedian lifeB595% CI low95% CI highR(500)95% CI low95% CI high
Log-logisticμ (log time) = 7.268, σ (log time) = 0.6168−517.611039.221044.8000.22120.03612975.781433.32233.11158.28343.320.84650.78210.8944
GammaShape k = 1.527, Rate = 0.0008343−517.701039.401044.970.17530.20260.04211830.731450.34221.16142.82342.470.84830.78710.8942
WeibullShape β = 1.342, Scale η = 1919−517.951039.901045.480.67780.15760.04681761.711460.41209.79133.64329.330.84830.78560.8951
Weibull (3-parameter)Shape β = 1.195, Scale η = 1915, Threshold γ = 50.46−517.041040.081048.440.85190.14450.04261854.041459.81209.95142.69308.900.83780.77390.8863
Log-normalμ (log time) = 7.28, σ (log time) = 1.112−518.141040.281045.861.0600.13020.05392693.181450.87232.85166.80325.070.83090.76780.8796
Generalized gammaμ (log time) = 7.443, σ (log time) = 0.9203, Q = 0.5307−517.541041.081049.441.8570.08740.03822006.191444.07227.93152.50340.650.84320.77690.8924
GompertzShape b = 0.0004422, Rate a = 0.0003274−519.391042.781048.363.5580.03730.05621642.771494.17151.4899.576230.450.83260.76880.8815
ExponentialRate λ = 0.00046−521.061044.121046.914.8970.01910.07962174.031506.92111.5186.584143.620.79450.74450.8370

Likelihood-ratio tests of nested families

Testχ²dfp
Weibull vs exponential (shape = 1)6.2191.013
Generalized gamma vs Weibull (Q = 1)0.82111.365
Generalized gamma vs log-normal (Q = 0)1.2031.273
Generalized gamma vs gamma (Q = σ)0.31851.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
))
Python

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

FamilyParameterslog LAICBICΔAICAkaike weightGap from Kaplan–MeierMean lifeMedian lifeB595% CI low95% CI highR(500)95% CI low95% CI high
Log-logisticμ (log time) = 7.268, σ (log time) = 0.6168−517.611039.221044.8000.22120.03612975.781433.32233.11158.28343.320.84650.78210.8944
GammaShape k = 1.527, Rate = 0.0008343−517.701039.401044.970.17530.20260.04211830.731450.34221.16142.82342.470.84830.78710.8942
WeibullShape β = 1.342, Scale η = 1919−517.951039.901045.480.67780.15760.04681761.711460.41209.79133.64329.330.84830.78560.8951
Weibull (3-parameter)Shape β = 1.195, Scale η = 1915, Threshold γ = 50.46−517.041040.081048.440.85190.14450.04261854.041459.81209.95142.69308.900.83780.77390.8863
Log-normalμ (log time) = 7.28, σ (log time) = 1.112−518.141040.281045.861.0600.13020.05392693.181450.87232.85166.80325.070.83090.76780.8796
Generalized gammaμ (log time) = 7.443, σ (log time) = 0.9203, Q = 0.5307−517.541041.081049.441.8570.08740.03822006.191444.07227.93152.50340.650.84320.77690.8924
GompertzShape b = 0.0004422, Rate a = 0.0003274−519.391042.781048.363.5580.03730.05621642.771494.17151.4899.576230.450.83260.76880.8815
ExponentialRate λ = 0.00046−521.061044.121046.914.8970.01910.07962174.031506.92111.5186.584143.620.79450.74450.8370

Likelihood-ratio tests of nested families

Testχ²dfp
Weibull vs exponential (shape = 1)6.2191.013
Generalized gamma vs Weibull (Q = 1)0.82111.365
Generalized gamma vs log-normal (Q = 0)1.2031.273
Generalized gamma vs gamma (Q = σ)0.31851.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.

The lowest AIC is Log-logistic. But second place, Gamma, is only 0.18 behind.

Differences under about 2 don't separate families. Treat them as tied, and let what you know about the failure mechanism break the tie.

The exponential is tested directly: Weibull against exponential gives LR = 6.22, p = .013, with Weibull shape 1.34.

06

How far does the tail reach?

Predict

Predict first

Two runs on the same devices give early-life figures from the same log-logistic model:

  • B5 = 233 hours, 95% CI 158 to 343.
  • B10 = 370 hours, 90% CI 285 to 479.

Which would change less if you picked another family?

B5 depends less on the familyB10 depends less on the family
Reveal

B10. The further into the tail you go, the less data you have and the more the family's shape decides the answer. The card lists a B-life for every family: compare them across families before you trust one.

07

When the data don't decide

Reflect

Ball bearings give Gamma the lowest AIC, even though engineers usually reach for a Weibull with this kind of part, and the two sit close.

Air-conditioner intervals give Exponential, with only 36 failures.

Would you switch to whichever family came first in each? What would you need to know about the failure mechanism to decide?

08

Check your understanding

Checkpoint

Check yourself

Half the units in your test are still running. How should a distribution fit treat them?

Show the answer

Answer: c

Each running unit adds its survival probability to the likelihood. Dropping them biases lives short, and treating their age as a failure does too.

Check yourself

Two families differ by 0.5 in AIC and give quite different B1 lives. What should you do?

Show the answer

Answer: b

A small AIC difference doesn't separate them, and the far tail is where families disagree most. Reporting the range is honest, and more early failures would help the most.

Check yourself

Using median ranks, what is the plotting position of the third failure out of five with no censoring? That is (i−0.3)/(n+0.4)(i - 0.3)/(n + 0.4).

Show the answer

Answer: 0.5

(3−0.3)/(5+0.4)=2.7/5.4=0.5(3 - 0.3)/(5 + 0.4) = 2.7/5.4 = 0.5. The middle failure sits exactly at the median.

09

Do it in CodeSplash

In the app

In Studios, open Quality & DoE and start from Which distribution fits?. The result flows on to a life model in the next steps. Or run the single method in Analyze, with a Failure level telling it which value of your event column means failed.

This script fits a censored Weibull by maximum likelihood, and matches 1.342 for the shape.

Python
import numpy as np
import pandas as pd
from scipy.optimize import minimize

d = pd.read_csv("life_devices_sim.csv")
t, failed = d["hours"].to_numpy(), d["failed"].to_numpy()

def neg_loglik(par):
    shape, scale = np.exp(par)
    log_density = np.log(shape / scale) + (shape - 1) * np.log(t / scale)
    return -(np.sum(failed * log_density) - np.sum((t / scale) ** shape))

fit = minimize(neg_loglik, [0, np.log(t.mean())], method="Nelder-Mead",
               options={"xatol": 1e-8, "fatol": 1e-10, "maxiter": 5000})
print(np.exp(fit.x), -fit.fun)
R
library(survival)
d <- read.csv("life_devices_sim.csv")

fit <- survreg(Surv(hours, failed) ~ 1, data = d, dist = "weibull")
c(shape = 1 / fit$scale, scale = exp(coef(fit)), loglik = fit$loglik[1])
10

Recap

Recap
  • Count running units: each one survives at least to its current age.
  • A probability plot straightens one family's CDF; curvature shows a mismatch, and median ranks place the points.
  • AIC differences under about 2 don't separate families.
  • The further into the tail you go, the more the family decides the answer, so report the spread.

Concepts in this lesson