Skip to content

GQuality & process · life.distribution

Distribution ID for life data

Which lifetime distribution fits these failures best, counting units still running?

Fits exponential, Weibull (2- and 3-parameter), log-normal, log-logistic, gamma, generalized gamma and Gompertz models by maximum likelihood with right censoring, and ranks them by AIC. Shows probability plots with median ranks, mean life, a B-life and reliability at a mission time for every family, and likelihood-ratio tests of the nested families.

Verified in Python and R Python and R agree to 6 decimals Also called distribution identification, distribution ID plot, life data analysis…

A real result

Example “Bearings complete”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Bearings completelife_bearings · time: revs
  • Devices censoredlife_devices_sim · event: failed · time: hours
  • Devices commonlife_devices_sim · event: failed · time: hours
  • Lung censoredlung · event: dead · time: time
  • Aircon falling hazardlife_aircon · time: hours
  • Degenerate constantlife_bearings · time: revs
  • Degenerate n2life_bearings · time: revs
  • Degenerate n3life_bearings · time: revs

In the guides

Where it sits in the decision guides

  • Parametric models: Weibull, exponential … · Statistics Guide · F — Time-to-event analysis

What you need

Timenumeric · 1 column
Time to failure or to the end of observation; all positive.
Failedboolean / numeric / categorical · 0–1 column
Whether the unit failed: yes/no, 0/1 or 1/2 (the larger code is a failure), or a category below. Leave empty if every unit failed.

Choices you make

hypothesis

Failure leveldefault —

For a categorical failure column, the level that marks a failure (default the last level).

Familiesdefault all

All eight families, or only the common two-parameter ones (a faster first look).

  • All eight families(default) — Exponential, Weibull (2- and 3-parameter), log-normal, log-logistic, gamma, generalized gamma and Gompertz.
  • Exponential, Weibull, log-normal, log-logistic — The four families that have straight-line probability paper.

statistics

B-life percentdefault 10

B10 is the time by which 10% of units have failed. Choose the percent your field reports.

Mission timedefault —

A time at which to report reliability: the share of units still working.

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% intervals, from the delta method on the log or logit scale.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Non-informative censoring

    Units still running must have the same future risk as units that failed at the same age.

  • Number of failures

    Ranking families takes many failures: with fewer than about 20 the AIC order is unstable.

  • Fit against Kaplan–Meier

    The best family should stay close to the Kaplan–Meier curve; a large gap means none of the families fits.

What it reports

n
How many independent units the analysis used; it sets precision and power.
events
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
censored
A unit taken off test or still running, so its life is only known to exceed the observed time; dropping it biases life estimates down.
censor_share
A unit taken off test or still running, so its life is only known to exceed the observed time; dropping it biases life estimates down.
event_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
best
The lifetime family with the lowest AIC. One within about 2 AIC units fits about as well, so compare their B-lives too.
best_label
The lifetime family with the lowest AIC. One within about 2 AIC units fits about as well, so compare their B-lives too.
best_aic
A model score balancing fit against complexity; lower is better, and only differences matter.
second_label
The next family by AIC and how far behind it is. A gap under about 2 means these data cannot tell the two apart.
second_delta
The next family by AIC and how far behind it is. A gap under about 2 means these data cannot tell the two apart.
best_mttf
The average lifetime under a fitted distribution; it depends heavily on the tail, far beyond most observed failures.
best_median
The time by which half the units have failed under the fitted model. Unlike the mean life, the far tail barely moves it.
best_blife
The time by which a stated percent of units has failed; B10 is the age at which 10% are gone.
best_blife_low
A range of effect values compatible with your data at the chosen confidence level.
best_blife_high
A range of effect values compatible with your data at the chosen confidence level.
best_mission_r
R(t) is the share of units still working at age t; the reliability at a mission time answers how many will finish the job.
best_mission_low
A range of effect values compatible with your data at the chosen confidence level.
best_mission_high
A range of effect values compatible with your data at the chosen confidence level.
b_percent
The time by which a stated percent of units has failed; B10 is the age at which 10% are gone.
mission_time
R(t) is the share of units still working at age t; the reliability at a mission time answers how many will finish the job.
lr_weibull_exp
A likelihood-ratio statistic for a Weibull shape of 1, asking whether a changing failure rate fits better than a constant one.
lr_weibull_exp_p
How surprising your data would be if the null hypothesis were true, as a probability.
weibull_shape
The failure rate among units still working at a given age. Rising means wear-out, falling means early failures, flat means random failures.

Per group, level or term: loglik[<family>], aic[<family>], bic[<family>], delta_aic[<family>], weight[<family>], km_distance[<family>], mttf[<family>], median[<family>], blife[<family>], blife_low[<family>], blife_high[<family>], mission_r[<family>], mission_low[<family>], mission_high[<family>], par[<family>:<parameter>], par_se[<family>:<parameter>], lr[<test>], lr_p[<test>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Both engines run the same damped Newton iteration with numerical derivatives from the same starting values (codesplash.stats.life ↔ codesplashr::cs_life_*), so they agree to the optimizer's precision. Checked against flexsurv in the reference tier.
  • The 3-parameter Weibull profiles the threshold over [0, first time): its maximum is not regular, so no interval is given for it and the family is left out when the likelihood keeps rising towards the first failure.
Python

The exact script CodeSplash ran for example “Bearings complete” · 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,
})
R

The exact script CodeSplash ran for example “Bearings complete” · 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
))

Sources

  • Meeker, W. Q., Escobar, L. A., & Pascual, F. G. (2022). Statistical methods for reliability data (2nd ed.). Wiley.
  • Lawless, J. F. (2003). Statistical models and methods for lifetime data (2nd ed.). Wiley.
  • Prentice, R. L. (1974). A log gamma model and its maximum likelihood estimation. Biometrika, 61, 539–544.
  • Benard, A., & Bos-Levenbach, E. C. (1953). Het uitzetten van waarnemingen op waarschijnlijkheidspapier. Statistica Neerlandica, 7, 163–173.
  • Johnson, L. G. (1964). The statistical treatment of fatigue experiments. Elsevier.
  • Abernethy, R. B. (2006). The new Weibull handbook (5th ed.). Author.

From the CodeSplash method registry · life.distribution v1.0.1.