ADescribe · distribution.fit
Fit a distribution (goodness of fit)
Which distribution describes this variable — and could the data have come from it?
Fits one of 13 distributions by maximum likelihood (normal, lognormal, exponential, gamma, Weibull, logistic, Gumbel, Laplace, uniform, beta, Cauchy, Pareto, half-normal) or ranks every one that fits the data's range by AIC with Akaike weights, then tests the fit with the one-sample Kolmogorov–Smirnov, Cramér–von Mises and Anderson–Darling tests. With estimated parameters the p-values come from a parametric bootstrap that refits each simulated sample (shared seeded stream, same in Python and R); with parameters you specify they come from the exact or asymptotic null distributions.
A real result
Example “Compare lifetime”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Gamma(shape = 1.687, scale = 58.6); KS D = 0.09, p = .165; A² = 0.39, p = .410
- AIC
- 887.73
- KS D
- 0.0869
- Anderson–Darling p
- 0.4100
Assumptions
- Independent, identically distributed values — The tests assume one distribution generated every value independently; trends, clusters or mixtures break this.
Candidate distributions
| Distribution | Parameters (ML) | Log-likelihood | AIC | ΔAIC | Akaike weight | KS D |
|---|---|---|---|---|---|---|
| Gamma | shape = 1.687; scale = 58.6 | −441.86 | 887.73 | 0 | 0.4731 | 0.0869 |
| Weibull | shape = 1.344; scale = 108.2 | −442.43 | 888.85 | 1.125 | 0.2695 | 0.0979 |
| Lognormal | meanlog = 4.269; sdlog = 0.8618 | −443.15 | 890.30 | 2.577 | 0.1305 | 0.0884 |
| Half-normal | sigma = 124.8 | −444.22 | 890.44 | 2.717 | 0.1216 | 0.1026 |
| Exponential | mean (1/rate) = 98.88 | −447.51 | 897.02 | 9.293 | 0.0045 | 0.1274 |
| Gumbel (largest extreme value) | location = 65.41; scale = 53.2 | −448.25 | 900.50 | 12.773 | 0.0008 | 0.1221 |
| Logistic | location = 89.22; scale = 42.07 | −459.11 | 922.21 | 34.487 | 1.535e-8 | 0.1388 |
| Normal | mean = 98.88; SD = 76.2 | −460.19 | 924.37 | 36.647 | 5.213e-9 | 0.1773 |
| Laplace | location = 72.16; scale = 58.7 | −461.25 | 926.50 | 38.773 | 1.801e-9 | 0.1648 |
| Uniform | lower = 7.011; width = 335.5 | −465.24 | 934.49 | 46.761 | 3.318e-11 | 0.3694 |
| Cauchy | location = 64.62; scale = 38.33 | −468.09 | 940.17 | 52.444 | 1.936e-12 | 0.1869 |
| Pareto | shape (alpha) = 0.4307; minimum (x_m) = 7.011 | −488.92 | 981.83 | 94.105 | 1.739e-21 | 0.3291 |
Goodness of fit — Gamma
| Test | Statistic | Value | p |
|---|---|---|---|
| Kolmogorov–Smirnov | D | 0.0869 | .165 |
| Cramér–von Mises | W² | 0.0749 | .285 |
| Anderson–Darling | A² | 0.3855 | .410 |
- The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot.
- With estimated parameters the p-values come from a parametric bootstrap that refits every simulated sample (Stute et al. 1993).
- AIC compares the candidates on the same data; Akaike weights are the relative support for each, given this set.
Gamma(shape = 1.687, scale = 58.6); KS D = 0.09, p = .165; A² = 0.39, p = .410
- AIC
- 887.73
- KS D
- 0.0869
- Anderson–Darling p
- 0.4100
Assumptions
- Independent, identically distributed values — The tests assume one distribution generated every value independently; trends, clusters or mixtures break this.
Candidate distributions
| Distribution | Parameters (ML) | Log-likelihood | AIC | ΔAIC | Akaike weight | KS D |
|---|---|---|---|---|---|---|
| Gamma | shape = 1.687; scale = 58.6 | −441.86 | 887.73 | 0 | 0.4731 | 0.0869 |
| Weibull | shape = 1.344; scale = 108.2 | −442.43 | 888.85 | 1.125 | 0.2695 | 0.0979 |
| Lognormal | meanlog = 4.269; sdlog = 0.8618 | −443.15 | 890.30 | 2.577 | 0.1305 | 0.0884 |
| Half-normal | sigma = 124.8 | −444.22 | 890.44 | 2.717 | 0.1216 | 0.1026 |
| Exponential | mean (1/rate) = 98.88 | −447.51 | 897.02 | 9.293 | 0.0045 | 0.1274 |
| Gumbel (largest extreme value) | location = 65.41; scale = 53.2 | −448.25 | 900.50 | 12.773 | 0.0008 | 0.1221 |
| Logistic | location = 89.22; scale = 42.07 | −459.11 | 922.21 | 34.487 | 1.535e-8 | 0.1388 |
| Normal | mean = 98.88; SD = 76.2 | −460.19 | 924.37 | 36.647 | 5.213e-9 | 0.1773 |
| Laplace | location = 72.16; scale = 58.7 | −461.25 | 926.50 | 38.773 | 1.801e-9 | 0.1648 |
| Uniform | lower = 7.011; width = 335.5 | −465.24 | 934.49 | 46.761 | 3.318e-11 | 0.3694 |
| Cauchy | location = 64.62; scale = 38.33 | −468.09 | 940.17 | 52.444 | 1.936e-12 | 0.1869 |
| Pareto | shape (alpha) = 0.4307; minimum (x_m) = 7.011 | −488.92 | 981.83 | 94.105 | 1.739e-21 | 0.3291 |
Goodness of fit — Gamma
| Test | Statistic | Value | p |
|---|---|---|---|
| Kolmogorov–Smirnov | D | 0.0869 | .165 |
| Cramér–von Mises | W² | 0.0749 | .285 |
| Anderson–Darling | A² | 0.3855 | .410 |
- The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot.
- With estimated parameters the p-values come from a parametric bootstrap that refits every simulated sample (Stute et al. 1993).
- AIC compares the candidates on the same data; Akaike weights are the relative support for each, given this set.
Shortened for the Academy: 2 chart(s) dropped to stay under 100 KB; 2 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
- Compare lifetimeh_fit · outcome: lifetime
- Weibull lifetimeh_fit · outcome: lifetime
- Gamma lifetimeh_fit · outcome: lifetime
- Beta shareh_fit · outcome: share
- Compare heavyh_fit · outcome: heavy
- Cauchy heavyh_fit · outcome: heavy
- Normal specifiedh_fit · outcome: normalish
- Weibull specified bootstraph_fit · outcome: lifetime
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Assess distribution: histogram, Q–Q · Statistics Guide · A — Describe data
- EDA (correlation, distributions) · DS & ML Decision Guide · Describe — summarize and visualize
What you need
- Variablenumeric · 1 column
- The numeric variable to fit distributions to.
Choices you make
options
- Distributiondefault compare
One distribution to fit and test, or compare every distribution whose range covers the data.
- Compare all that fit (AIC)(default) — Fits every candidate whose range covers the data, ranks them by AIC and tests the best.
- Normal — Symmetric bell curve; the reference for many tests.
- Logistic — Like the normal with slightly heavier tails.
- Laplace (double exponential) — Sharp peak, exponential tails; robust errors.
- Cauchy — Extremely heavy tails — no mean or variance.
- Gumbel (largest extreme value) — Maxima of many values: floods, peak loads.
- Uniform — Every value between a minimum and a maximum equally likely.
- Beta — Proportions and rates strictly between 0 and 1.
- Lognormal — Log of the values is normal; incomes, sizes, concentrations.
- Gamma — Waiting times and amounts; flexible right skew.
- Weibull — Lifetimes and strengths; shape < 1, = 1 or > 1 means falling, constant or rising hazard.
- Exponential — Memoryless waiting times (constant hazard).
- Half-normal — Absolute values of a centered normal: deviations, errors.
- Pareto (power law) — Heavy right tail above a minimum: city sizes, wealth.
- p-values fromdefault auto
Automatic uses the bootstrap for estimated parameters and the exact or asymptotic formulas for specified ones.
- Automatic(default) — Uses the bootstrap for estimated parameters and formulas for the ones you specified; the usual choice.
- Parametric bootstrap — Refits on simulated data so estimated parameters are allowed for; slower, and right when parameters were estimated.
- Exact / asymptotic formulas — Correct only for specified parameters; too lenient when the parameters were estimated.
hypothesis
- Parametersdefault estimated
Estimated from the data (the usual case) or fully specified in advance (the textbook one-sample tests).
- Estimated from the data (maximum likelihood)(default) — p-values by parametric bootstrap with refitting — honest when the parameters come from the same data.
- Specified in advance — Test a fully specified distribution, e.g. normal with mean 0 and SD 1 (exact / asymptotic p-values).
- Location (mean, meanlog, lower bound)default —
Normal mean, lognormal meanlog, logistic/Gumbel/Laplace/Cauchy location, uniform lower bound.
- Scale (SD, sdlog, mean, width, minimum)default —
Normal SD, lognormal sdlog, exponential mean, gamma/Weibull scale, uniform width, Pareto minimum, half-normal sigma.
- Shape (gamma, Weibull, Pareto, beta alpha)default —
Gamma or Weibull shape, Pareto alpha, beta's first shape.
- Second shape (beta)default —
Beta's second shape parameter.
Advanced
- Bootstrap samplesdefault 999
Simulated samples for the parametric bootstrap (shared seeded stream, same in Python and R).
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.
Independent, identically distributed values
One distribution generated every value independently; trends, clusters and mixtures break the tests.
What it reports
- Tests: Data follow the fitted distribution (Anderson–Darling)
- n
- How many independent units the analysis used; it sets precision and power.
- family
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- loc
- The distribution this model assumes for lifetimes. The AIC table shows whether another one fits better.
- scale
- Stretches or shrinks a fitted distribution without changing its form, so larger means more spread.
- shape
- Sets the form of a fitted distribution. For a Weibull lifetime, above 1 means a rising failure rate and below 1 a falling one.
- shape2
- Sets the form of a fitted distribution. For a Weibull lifetime, above 1 means a rising failure rate and below 1 a falling one.
- ks_d
- Compares distributions by the largest vertical gap (D) between their cumulative curves.
- ks_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- cvm_w2
- Goodness-of-fit test summing the squared gaps between the data's ECDF and the fitted distribution over all values.
- cvm_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- ad_a2
- Goodness-of-fit test that weighs the tails more than Kolmogorov–Smirnov, so it notices heavy or light tails sooner.
- ad_p
- Tests MCAR via equal covariances across missingness patterns; its nonparametric (Anderson–Darling) version suits non-normal data.
- n_reject
- How many independent units the analysis used; it sets precision and power.
- calibration
- Each p-value comes from a reference distribution, a simulation of the null, or an exact count: this column says which.
- reps_used
- A p-value estimated from simulated or resampled statistics, with its own small sampling error.
- skewness
- How lopsided a distribution is; positive skew has a long right tail.
- kurtosis
- How heavy a distribution's tails are compared with a normal; positive excess means more extreme values.
- n_candidates
- How many independent units the analysis used; it sets precision and power.
Per group, level or term: aic[<family>], delta_aic[<family>], weight[<family>], ks_d[<family>] (family = compare)
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines fit by the same closed forms and Newton / fixed-point iterations (codesplash.stats.distribution ↔ codesplashr), so ML estimates agree to ~1e-13; the bootstrap simulates with the same Wichmann–Hill uniforms and refits identically (same p-value counts).
- Gamma and beta bootstrap samples use scipy's gammaincinv / betaincinv vs R's qgamma / qbeta (agree to ~1e-13).
- Specified-parameter p-values: KS exact for n < 100 (Marsaglia, Tsang & Wang 2003) as R's ks.test; Cramér–von Mises by Csörgő & Faraway (1996) as goftest / scipy; Anderson–Darling by Marsaglia & Marsaglia (2004) as goftest.
The exact script CodeSplash ran for example “Compare lifetime” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Fit a distribution (goodness of fit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.fit 1.0.1 · spec 35b9d6ce03a3086d
# Dataset: h_fit (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import distribution as csd
# %% Data
df = pd.read_parquet("tests/parity/fixtures/h_fit.parquet", columns=["lifetime"])
n_input = len(df)
df = df.dropna(subset=["lifetime"]) # 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, ["lifetime"]) # infinite values stop the run (registry/errors.yaml)
# %% Fit
y = "lifetime"
x = df[y].to_numpy(dtype=float)
x = x[np.isfinite(x)]
n = x.size
family = "compare"
specified = "estimated" == "specified"
calibration = "auto"
seed, reps = 42, int(199) # bootstrap samples come from the shared Wichmann–Hill stream
alpha = 0.05
nan = math.nan
if n < 5:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Fitting a distribution", min=5, n=n)
if len(np.unique(x)) < 2: # every family's scale estimate would be zero
cs.cs_error("CS_E_CONSTANT", column=y)
if family == "compare":
candidates = [f for f in csd.FAMILY_ORDER if csd.supports(f, x)]
else:
if not csd.supports(family, x):
need = {"positive": "positive values", "nonnegative": "values ≥ 0", "unit": "values strictly between 0 and 1"}[csd.FAMILIES[family]["support"]]
raise ValueError(f"The {csd.FAMILIES[family]['label']} distribution needs {need}; {y} has values outside that range.")
candidates = [family]
fits = [csd.fit_one(f, x) for f in candidates]
usable = [f for f in fits if f["ok"] and np.isfinite(f["aic"])]
if not usable:
raise ValueError(f"No candidate distribution could be fitted to {y}.")
best = min(usable, key=lambda f: f["aic"])
chosen = best["family"]
spec = None
if specified:
given = {"loc": None, "scale": None, "shape": None, "shape2": None}
missing = [k for k in csd.FAMILIES[chosen]["params"] if given[k] is None]
if missing:
raise ValueError(f"Specified parameters for the {csd.FAMILIES[chosen]['label']} distribution need: {', '.join(missing)}.")
spec = {k: (nan if v is None else float(v)) for k, v in given.items()} | {"converged": True}
gof = csd.gof_test(chosen, x, spec, calibration, reps=reps, seed=seed)
p_used = gof["params"]
k_used = 0 if specified else csd.FAMILIES[chosen]["k"]
ll = float(np.sum(csd.logpdf(chosen, x, p_used)))
tests = [("Kolmogorov–Smirnov", "D", gof["ks_d"], gof["ks_p"]), ("Cramér–von Mises", "W²", gof["cvm_w2"], gof["cvm_p"]),
("Anderson–Darling", "A²", gof["ad_a2"], gof["ad_p"])]
n_reject = sum(1 for t in tests if np.isfinite(t[3]) and t[3] < alpha)
m = float(np.mean(x))
m2 = float(np.mean((x - m) ** 2))
g1 = math.sqrt(n * (n - 1)) / (n - 2) * float(np.mean((x - m) ** 3)) / m2**1.5 if m2 > 0 else nan
g2 = ((n + 1) * (float(np.mean((x - m) ** 4)) / m2**2 - 3) + 6) * (n - 1) / ((n - 2) * (n - 3)) if m2 > 0 else nan
# %% Result
values = {"n": n, "family": chosen, "n_params": k_used, "loglik": ll, "aic": 2 * k_used - 2 * ll, "bic": k_used * math.log(n) - 2 * ll,
"loc": p_used["loc"], "scale": p_used["scale"], "shape": p_used["shape"], "shape2": p_used["shape2"],
"ks_d": gof["ks_d"], "ks_p": gof["ks_p"], "cvm_w2": gof["cvm_w2"], "cvm_p": gof["cvm_p"], "ad_a2": gof["ad_a2"], "ad_p": gof["ad_p"],
"n_reject": n_reject, "calibration": gof["calibration"], "reps_used": gof["reps"], "skewness": g1, "kurtosis": g2,
"n_candidates": len(usable)}
fam_rows = []
w_den = sum(math.exp(-(f["aic"] - best["aic"]) / 2) for f in usable)
for f in fits:
d_aic = f["aic"] - best["aic"] if f["ok"] else nan
w = math.exp(-d_aic / 2) / w_den if f["ok"] else nan
if family == "compare":
values.update({f"aic[{f['family']}]": f["aic"], f"delta_aic[{f['family']}]": d_aic, f"weight[{f['family']}]": w, f"ks_d[{f['family']}]": f["ks_d"]})
info = csd.FAMILIES[f["family"]]
fam_rows.append({"family": info["label"],
"parameters": "; ".join(f"{nm} = {f['params'][k]:.4g}" for nm, k in zip(info["names"], info["params"])) if f["ok"] else "did not converge",
"loglik": f["loglik"], "aic": f["aic"], "delta_aic": d_aic, "weight": w, "ks_d": f["ks_d"]})
info = csd.FAMILIES[chosen]
par_text = ", ".join(f"{nm} = {p_used[k]:.4g}" for nm, k in zip(info["names"], info["params"]))
how = gof["calibration"] + (f", {gof['reps']} replicates, seed {seed}" if gof["reps"] else "")
lead = (f"Of {len(usable)} candidate distributions, the {info['label']} distribution fits {y} best by AIC (weight {1 / w_den:.2f}). "
if family == "compare" else f"{info['label']} distribution {'with the specified parameters' if specified else 'fitted by maximum likelihood'}. ")
summary = (lead + f"Parameters: {par_text}. Goodness of fit ({how}): KS D = {gof['ks_d']:.3f}, {cs.fmt_p(gof['ks_p'])}; "
f"Cramér–von Mises W² = {gof['cvm_w2']:.3f}, {cs.fmt_p(gof['cvm_p'])}; Anderson–Darling A² = {gof['ad_a2']:.3f}, {cs.fmt_p(gof['ad_p'])} — "
+ ("no test rejects the fit." if n_reject == 0 else f"{n_reject} of 3 tests reject the fit at α = .05."))
notes = ["The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot."]
if not specified and gof["calibration"].endswith("formulas"):
warnings.append("The parameters were estimated from the same data, so the textbook p-values are too large (anti-conservative); use the parametric bootstrap.")
if not specified:
notes.append("With estimated parameters the p-values come from a parametric bootstrap that refits every simulated sample (Stute et al. 1993).")
if family == "compare":
notes.append("AIC compares the candidates on the same data; Akaike weights are the relative support for each, given this set.")
# charts: fitted density over a kernel density of the data; Q–Q against the fitted quantiles
lo, hi = float(np.min(x)), float(np.max(x))
pad = 0.05 * (hi - lo if hi > lo else 1.0)
gl, gh = lo - pad, hi + pad
if info["support"] in ("positive", "nonnegative"):
gl = max(gl, lo / 2 if lo > 0 else 0.0)
if info["support"] == "unit":
gl, gh = max(gl, 1e-4), min(gh, 1 - 1e-4)
grid = np.linspace(gl, gh, 200)
show = [chosen] + ([f["family"] for f in sorted(usable, key=lambda f: f["aic"]) if f["family"] != chosen][:2] if family == "compare" else [])
dens_x, dens_y, dens_src = list(grid), list(csd.kde(x, grid)), ["Data (kernel density)"] * grid.size
for fam in show:
pf = p_used if fam == chosen else next(f["params"] for f in usable if f["family"] == fam)
ok = (grid > 0) if csd.FAMILIES[fam]["support"] in ("positive",) else ((grid >= 0) if csd.FAMILIES[fam]["support"] == "nonnegative" else ((grid > 0) & (grid < 1) if csd.FAMILIES[fam]["support"] == "unit" else np.ones(grid.size, bool)))
dv = np.zeros(grid.size)
dv[ok] = np.exp(csd.logpdf(fam, grid[ok], pf))
dens_x += list(grid)
dens_y += list(np.where(np.isfinite(dv), dv, 0.0))
dens_src += [f"Fitted {csd.FAMILIES[fam]['label']}"] * grid.size
xs = np.sort(x)
theo = csd.quantile(chosen, (np.arange(1, n + 1) - 0.5) / n, p_used)
cs.publish({
"method": "distribution.fit",
"methodVersion": "1.0.1",
"title": f"Distribution fit — {info['label']}",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{info['label']}({par_text}); KS D = {gof['ks_d']:.2f}, {cs.fmt_p(gof['ks_p'])}; A² = {gof['ad_a2']:.2f}, {cs.fmt_p(gof['ad_p'])}",
"statistics": [{"key": "aic", "label": "AIC", "value": values["aic"]}, {"key": "ks_d", "label": "KS D", "value": gof["ks_d"]},
{"key": "ad_p", "label": "Anderson–Darling p", "value": gof["ad_p"]}],
"tables": [
{"key": "fit", "title": "Candidate distributions" if family == "compare" else "Fitted distribution", "columns": [
{"key": "family", "label": "Distribution", "type": "string"}, {"key": "parameters", "label": "Parameters (ML)", "type": "string"},
{"key": "loglik", "label": "Log-likelihood", "type": "number"}, {"key": "aic", "label": "AIC", "type": "number"},
{"key": "delta_aic", "label": "ΔAIC", "type": "number"}, {"key": "weight", "label": "Akaike weight", "type": "number"},
{"key": "ks_d", "label": "KS D", "type": "number"}], "rows": sorted(fam_rows, key=lambda r: (not np.isfinite(r["aic"]), r["aic"] if np.isfinite(r["aic"]) else 0))},
{"key": "gof", "title": f"Goodness of fit — {info['label']}", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "symbol", "label": "Statistic", "type": "string"},
{"key": "statistic", "label": "Value", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": [{"test": t[0], "symbol": t[1], "statistic": t[2], "p": t[3]} for t in tests]},
],
"effectSizes": [],
"assumptions": [{"key": "independence", "label": "Independent, identically distributed values", "status": "info",
"detail": "The tests assume one distribution generated every value independently; trends, clusters or mixtures break this."}],
"warnings": warnings,
"notes": notes,
"charts": [
cs.chart("density", "density-compare", f"{y}: data and fitted density",
{"x": cs.col(y, dens_x), "density": cs.col("density", dens_y), "source": cs.col("curve", dens_src)}),
cs.chart("qq", "pred-actual", f"Q–Q plot against the fitted {info['label']}",
{"actual": cs.col(f"{y} (sorted)", xs), "predicted": cs.col(f"Fitted {info['label']} quantile", theo)}),
],
"values": values,
})
The exact script CodeSplash ran for example “Compare lifetime” · R version 4.5.1 (2025-06-13)
# Fit a distribution (goodness of fit)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.fit 1.0.1 · spec 35b9d6ce03a3086d
# Dataset: h_fit (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/h_fit.parquet", col_select = c("lifetime")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("lifetime")]), , 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("lifetime")) # infinite values stop the run (registry/errors.yaml)
# %% Fit
y <- "lifetime"
x <- as.numeric(df[[y]])
x <- x[is.finite(x)]
n <- length(x)
family <- "compare"
specified <- "estimated" == "specified"
calibration <- "auto"
seed <- 42 # bootstrap samples come from the shared Wichmann-Hill stream
reps <- as.integer(199)
alpha <- 0.05
fams <- cs_dist_families()
if (n < 5) cs_error("CS_E_TOO_FEW_ROWS", what = "Fitting a distribution", min = 5, n = n)
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = y) # every family's scale estimate would be zero
if (family == "compare") {
candidates <- Filter(function(f) cs_dist_supports(f, x), names(fams))
} else {
if (!cs_dist_supports(family, x)) {
need <- switch(fams[[family]]$support, positive = "positive values", nonnegative = "values ≥ 0", unit = "values strictly between 0 and 1")
stop(sprintf("The %s distribution needs %s; %s has values outside that range.", fams[[family]]$label, need, y))
}
candidates <- family
}
fits <- lapply(candidates, function(f) cs_dist_fit_one(f, x))
usable <- Filter(function(f) isTRUE(f$ok) && is.finite(f$aic), fits)
if (!length(usable)) stop(sprintf("No candidate distribution could be fitted to %s.", y))
best <- usable[[which.min(vapply(usable, function(f) f$aic, numeric(1)))]]
chosen <- best$family
spec <- NULL
if (specified) {
given <- list(loc = NULL, scale = NULL, shape = NULL, shape2 = NULL)
missing <- Filter(function(k) is.null(given[[k]]), fams[[chosen]]$params)
if (length(missing)) stop(sprintf("Specified parameters for the %s distribution need: %s.", fams[[chosen]]$label, paste(missing, collapse = ", ")))
spec <- lapply(given, function(v) if (is.null(v)) NaN else as.numeric(v))
spec$converged <- TRUE
}
gof <- cs_dist_gof_test(chosen, x, spec, calibration, reps = reps, seed = seed)
p_used <- gof$params
k_used <- if (specified) 0 else fams[[chosen]]$k
ll <- sum(cs_dist_logpdf(chosen, x, p_used))
tests <- list(list("Kolmogorov–Smirnov", "D", gof$ks_d, gof$ks_p), list("Cramér–von Mises", "W²", gof$cvm_w2, gof$cvm_p),
list("Anderson–Darling", "A²", gof$ad_a2, gof$ad_p))
n_reject <- sum(vapply(tests, function(t) is.finite(t[[4]]) && t[[4]] < alpha, logical(1)))
m <- mean(x)
m2 <- mean((x - m)^2)
g1 <- if (m2 > 0) sqrt(n * (n - 1)) / (n - 2) * mean((x - m)^3) / m2^1.5 else NaN
g2 <- if (m2 > 0) ((n + 1) * (mean((x - m)^4) / m2^2 - 3) + 6) * (n - 1) / ((n - 2) * (n - 3)) else NaN
# %% Result
values <- list(n = n, family = chosen, n_params = k_used, loglik = ll, aic = 2 * k_used - 2 * ll, bic = k_used * log(n) - 2 * ll,
loc = p_used$loc, scale = p_used$scale, shape = p_used$shape, shape2 = p_used$shape2,
ks_d = gof$ks_d, ks_p = gof$ks_p, cvm_w2 = gof$cvm_w2, cvm_p = gof$cvm_p, ad_a2 = gof$ad_a2, ad_p = gof$ad_p,
n_reject = n_reject, calibration = gof$calibration, reps_used = gof$reps, skewness = g1, kurtosis = g2,
n_candidates = length(usable))
w_den <- sum(vapply(usable, function(f) exp(-(f$aic - best$aic) / 2), numeric(1)))
fam_rows <- list()
for (f in fits) {
d_aic <- if (isTRUE(f$ok)) f$aic - best$aic else NaN
w <- if (isTRUE(f$ok)) exp(-d_aic / 2) / w_den else NaN
if (family == "compare") {
values[[sprintf("aic[%s]", f$family)]] <- f$aic
values[[sprintf("delta_aic[%s]", f$family)]] <- d_aic
values[[sprintf("weight[%s]", f$family)]] <- w
values[[sprintf("ks_d[%s]", f$family)]] <- f$ks_d
}
info <- fams[[f$family]]
fam_rows[[length(fam_rows) + 1]] <- list(
family = info$label,
parameters = if (isTRUE(f$ok)) paste(sprintf("%s = %s", info$names, vapply(info$params, function(k) formatC(f$params[[k]], digits = 4, format = "g"), "")), collapse = "; ") else "did not converge",
loglik = f$loglik, aic = f$aic, delta_aic = d_aic, weight = w, ks_d = f$ks_d)
}
fam_rows <- fam_rows[order(!vapply(fam_rows, function(r) is.finite(r$aic), logical(1)), vapply(fam_rows, function(r) if (is.finite(r$aic)) r$aic else 0, numeric(1)))]
info <- fams[[chosen]]
par_text <- paste(sprintf("%s = %s", info$names, vapply(info$params, function(k) formatC(p_used[[k]], digits = 4, format = "g"), "")), collapse = ", ")
how <- paste0(gof$calibration, if (gof$reps > 0) sprintf(", %d replicates, seed %d", as.integer(gof$reps), as.integer(seed)) else "")
lead <- if (family == "compare") {
sprintf("Of %d candidate distributions, the %s distribution fits %s best by AIC (weight %.2f). ", length(usable), info$label, y, 1 / w_den)
} else {
sprintf("%s distribution %s. ", info$label, if (specified) "with the specified parameters" else "fitted by maximum likelihood")
}
summary <- paste0(lead, sprintf("Parameters: %s. Goodness of fit (%s): KS D = %.3f, %s; Cramér–von Mises W² = %.3f, %s; Anderson–Darling A² = %.3f, %s — ",
par_text, how, gof$ks_d, cs_fmt_p(gof$ks_p), gof$cvm_w2, cs_fmt_p(gof$cvm_p), gof$ad_a2, cs_fmt_p(gof$ad_p)),
if (n_reject == 0) "no test rejects the fit." else sprintf("%d of 3 tests reject the fit at α = .05.", n_reject))
notes <- list("The tests ask whether the data could come from the fitted distribution; not rejecting is not proof of fit. Read the Q–Q plot.")
if (!specified && endsWith(gof$calibration, "formulas")) {
warnings <- c(warnings, "The parameters were estimated from the same data, so the textbook p-values are too large (anti-conservative); use the parametric bootstrap.")
}
if (!specified) notes[[length(notes) + 1]] <- "With estimated parameters the p-values come from a parametric bootstrap that refits every simulated sample (Stute et al. 1993)."
if (family == "compare") notes[[length(notes) + 1]] <- "AIC compares the candidates on the same data; Akaike weights are the relative support for each, given this set."
lo <- min(x)
hi <- max(x)
pad <- 0.05 * (if (hi > lo) hi - lo else 1)
gl <- lo - pad
gh <- hi + pad
if (info$support %in% c("positive", "nonnegative")) gl <- max(gl, if (lo > 0) lo / 2 else 0)
if (info$support == "unit") {
gl <- max(gl, 1e-4)
gh <- min(gh, 1 - 1e-4)
}
grid <- seq(gl, gh, length.out = 200)
ranked <- usable[order(vapply(usable, function(f) f$aic, numeric(1)))]
show <- c(chosen, if (family == "compare") head(Filter(function(f) f != chosen, vapply(ranked, function(f) f$family, "")), 2) else character(0))
dens_x <- grid
dens_y <- cs_dist_kde(x, grid)
dens_src <- rep("Data (kernel density)", length(grid))
for (fam in show) {
pf <- if (fam == chosen) p_used else Filter(function(f) f$family == fam, usable)[[1]]$params
s <- fams[[fam]]$support
ok <- if (s == "positive") grid > 0 else if (s == "nonnegative") grid >= 0 else if (s == "unit") grid > 0 & grid < 1 else rep(TRUE, length(grid))
dv <- numeric(length(grid))
dv[ok] <- exp(cs_dist_logpdf(fam, grid[ok], pf))
dv[!is.finite(dv)] <- 0
dens_x <- c(dens_x, grid)
dens_y <- c(dens_y, dv)
dens_src <- c(dens_src, rep(paste("Fitted", fams[[fam]]$label), length(grid)))
}
xs <- sort(x)
theo <- cs_dist_quantile(chosen, (seq_len(n) - 0.5) / n, p_used)
cs_publish(list(
method = "distribution.fit",
methodVersion = "1.0.1",
title = paste("Distribution fit —", info$label),
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s(%s); KS D = %.2f, %s; A² = %.2f, %s", info$label, par_text, gof$ks_d, cs_fmt_p(gof$ks_p), gof$ad_a2, cs_fmt_p(gof$ad_p)),
statistics = list(list(key = "aic", label = "AIC", value = values$aic), list(key = "ks_d", label = "KS D", value = gof$ks_d),
list(key = "ad_p", label = "Anderson–Darling p", value = gof$ad_p)),
tables = list(
list(key = "fit", title = if (family == "compare") "Candidate distributions" else "Fitted distribution", columns = list(
list(key = "family", label = "Distribution", type = "string"), list(key = "parameters", label = "Parameters (ML)", type = "string"),
list(key = "loglik", label = "Log-likelihood", type = "number"), list(key = "aic", label = "AIC", type = "number"),
list(key = "delta_aic", label = "ΔAIC", type = "number"), list(key = "weight", label = "Akaike weight", type = "number"),
list(key = "ks_d", label = "KS D", type = "number")), rows = fam_rows),
list(key = "gof", title = paste("Goodness of fit —", info$label), columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "symbol", label = "Statistic", type = "string"),
list(key = "statistic", label = "Value", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = lapply(tests, function(t) list(test = t[[1]], symbol = t[[2]], statistic = t[[3]], p = t[[4]])))
),
effectSizes = list(),
assumptions = list(list(key = "independence", label = "Independent, identically distributed values", status = "info",
detail = "The tests assume one distribution generated every value independently; trends, clusters or mixtures break this.")),
warnings = warnings,
notes = notes,
charts = list(
cs_chart("density", "density-compare", sprintf("%s: data and fitted density", y),
list(x = cs_col(y, dens_x), density = cs_col("density", dens_y), source = cs_col("curve", dens_src))),
cs_chart("qq", "pred-actual", sprintf("Q–Q plot against the fitted %s", info$label),
list(actual = cs_col(paste0(y, " (sorted)"), xs), predicted = cs_col(paste("Fitted", info$label, "quantile"), theo)))
),
values = values
))
Sources
- Stephens, M. A. (1986). Tests based on EDF statistics. In D'Agostino & Stephens (Eds.), Goodness-of-fit techniques. Marcel Dekker.
- Stute, W., Gonzáles Manteiga, W., & Presedo Quindimil, M. (1993). Bootstrap based goodness-of-fit tests. Metrika, 40, 243–256.
- Marsaglia, G., Tsang, W. W., & Wang, J. (2003). Evaluating Kolmogorov's distribution. Journal of Statistical Software, 8(18).
- Csörgő, S., & Faraway, J. J. (1996). The exact and asymptotic distributions of Cramér–von Mises statistics. JRSS B, 58, 221–234.
- Marsaglia, G., & Marsaglia, J. (2004). Evaluating the Anderson–Darling distribution. Journal of Statistical Software, 9(2).
- Burnham, K. P., & Anderson, D. R. (2002). Model selection and multimodel inference (2nd ed.). Springer.
From the CodeSplash method registry · distribution.fit v1.0.1.