Skip to content

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.

Applied ~13 min10 steps

What runs in CodeSplash

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
01

Failures, and units still running

Read

You 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.

02

Drop them and see

Explore

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.

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.

03

Which shape?

Predict

Predict 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?

One family wins by a wide marginSeveral families are almost tied
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.

04

Read the fits

In the app
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.

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.

05

Numbers that matter

Read

A 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.

06

Does the choice of family matter?

Reflect

Open 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?

07

A complete sample

In the app

Ball bearings were tested until all 23 failed.

Distribution IDRecorded · Python and R agreeRecorded 2026-11-17 · 177 values compared · largest relative difference 7.2e-9
R

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

FamilyParameterslog LAICBICΔAICAkaike weightGap from Kaplan–MeierMean lifeMedian lifeB1095% CI low95% CI highR(50)95% CI low95% CI high
GammaShape k = 4.025, Rate = 0.05573−113.03230.06232.3300.24910.122972.22166.33631.60522.09745.2040.69970.53190.8269
Log-normalμ (log time) = 4.15, σ (log time) = 0.5217−113.13230.26232.530.19750.22560.089772.70963.45832.51924.38843.3600.67610.50780.8086
Log-logisticμ (log time) = 4.159, σ (log time) = 0.2988−113.37230.75233.020.68640.17670.094474.45963.99533.19024.40345.1410.69550.51470.8310
WeibullShape β = 2.102, Scale η = 81.87−113.69231.38233.651.3240.12840.151072.51568.77328.06518.05643.6210.70140.53070.8299
Weibull (3-parameter)Shape β = 1.594, Scale η = 63.87, Threshold γ = 14.88−112.85231.70235.111.6410.10960.117472.16565.63030.44522.49741.2000.68010.50830.8139
Generalized gammaμ (log time) = 4.23, σ (log time) = 0.51, Q = 0.3076−112.97231.94235.341.8790.09730.109572.23065.18632.07622.96644.8000.69150.51430.8259
GompertzShape b = 0.01632, Rate a = 0.005399−115.98235.96238.235.9040.01300.155171.16269.22616.9409.15731.3400.65880.49030.7949
ExponentialRate λ = 0.01385−121.43244.87246.0014.8080.00020.306872.22150.0607.6095.05711.4510.50040.36250.6383

Likelihood-ratio tests of nested families

Testχ²dfp
Weibull vs exponential (shape = 1)15.4841< .001
Generalized gamma vs Weibull (Q = 1)1.4451.229
Generalized gamma vs log-normal (Q = 0)0.31861.572
Generalized gamma vs gamma (Q = σ)0.12111.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
))
Python

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

FamilyParameterslog LAICBICΔAICAkaike weightGap from Kaplan–MeierMean lifeMedian lifeB1095% CI low95% CI highR(50)95% CI low95% CI high
GammaShape k = 4.025, Rate = 0.05573−113.03230.06232.3300.24910.122972.22166.33631.60522.09745.2040.69970.53190.8269
Log-normalμ (log time) = 4.15, σ (log time) = 0.5217−113.13230.26232.530.19750.22560.089772.70963.45832.51924.38843.3600.67610.50780.8086
Log-logisticμ (log time) = 4.159, σ (log time) = 0.2988−113.37230.75233.020.68640.17670.094474.45963.99533.19024.40345.1410.69550.51470.8310
WeibullShape β = 2.102, Scale η = 81.87−113.69231.38233.651.3240.12840.151072.51568.77328.06518.05643.6210.70140.53070.8299
Weibull (3-parameter)Shape β = 1.594, Scale η = 63.87, Threshold γ = 14.88−112.85231.70235.111.6410.10960.117472.16565.63030.44522.49741.2000.68010.50830.8139
Generalized gammaμ (log time) = 4.23, σ (log time) = 0.51, Q = 0.3076−112.97231.94235.341.8790.09730.109572.23065.18632.07622.96644.8000.69150.51430.8259
GompertzShape b = 0.01632, Rate a = 0.005399−115.98235.96238.235.9040.01300.155171.16269.22616.9409.15731.3400.65880.49030.7949
ExponentialRate λ = 0.01385−121.43244.87246.0014.8080.00020.306872.22150.0607.6095.05711.4510.50040.36250.6383

Likelihood-ratio tests of nested families

Testχ²dfp
Weibull vs exponential (shape = 1)15.4841< .001
Generalized gamma vs Weibull (Q = 1)1.4451.229
Generalized gamma vs log-normal (Q = 0)0.31861.572
Generalized gamma vs gamma (Q = σ)0.12111.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.

08

Check your understanding

Checkpoint

Check 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.

09

Try it

In the app

In the Quality studio, choose Life data & reliability, or start directly with Which distribution fits?. The Distribution ID step takes your time and failure columns.

Python
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))
R
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")
}
10

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