When the two engines disagree
A checklist for reconciling two results, in the order that finds the cause fastest, and how to read a known difference.
What runs in CodeSplash
- STAT108Lilliefors normality test Runs in CodeSplash
- STAT109Anderson–Darling normality test Runs in CodeSplash
- Normality tests (battery) Verified in Python and R
- One-way ANOVA (Welch / classic) Verified in Python and R
You will be able to
- Reconcile two different results with a fixed checklist
- Read a method's tolerance and known differences
- Decide whether a disagreement is a definition, a data problem or a real bug
Someone's number doesn't match yours
ReadA colleague sends you a p-value and it doesn't match yours. The worst thing to do is to assume either of you is wrong.
Work through the causes in the order they're cheapest to check. In practice, the first three find nearly everything.
- Data: same rows? Same version?
- Missing values: did both use the same rows?
- Options and definitions: which variant, what default?
- Algorithm and tolerance: iterative? Simulated?
- Then, and only then, a bug.
Start with the row count
PredictPredict first
Your mean differs from a colleague's in the third decimal place. What do you check first?
Reveal
The row counts. It takes ten seconds, and a difference tells you instantly that you're computing on different rows, because of a filter, a duplicate or a missing value. Reading code comes later, when you know the inputs match.
Work a case
ExploreTwo scripts test two groups' tooth growth and report different p-values. Find the cause.
import pandas as pd
from scipy import stats
df = pd.read_csv("toothgrowth.csv")
a = df.loc[df["supp"] == "OJ", "len"]
b = df.loc[df["supp"] == "VC", "len"]
print(len(a), len(b)) # 30 30
print(stats.ttest_ind(a, b)) # t = 1.9153, df = 58, p = 0.0604df <- read.csv("toothgrowth.csv")
print(table(df$supp)) # OJ 30, VC 30
print(t.test(len ~ supp, df)) # t = 1.9153, df = 55.309, p = 0.0606Work the list. Rows match. No values are missing. The statistics match, but the degrees of freedom don't: that's the signature of a different variant. Set equal_var=False, and the p-values match.
Reading a difference
In the appRun an analysis and press Verify in R. Press values on the badge. Each row shows the value in each engine, the relative difference and the tolerance it's tested against.
F(2, 17.13) = 5.18, p = .017, ω² = .20
- F
- 5.181
- df1
- 2
- df2
- 17.128
- p
- .017
Effect size
- ω² 0.2041 · large
- η² 0.2641 · large
- ε² 0.2096
Plots
View data
| group | weight |
|---|---|
| ctrl | 4.170 |
| ctrl | 5.580 |
| ctrl | 5.180 |
| ctrl | 6.110 |
| ctrl | 4.500 |
| ctrl | 4.610 |
| ctrl | 5.170 |
| ctrl | 4.530 |
| ctrl | 5.330 |
| ctrl | 5.140 |
| trt1 | 4.810 |
| trt1 | 4.170 |
| trt1 | 4.410 |
| trt1 | 3.590 |
| trt1 | 5.870 |
| trt1 | 3.830 |
| trt1 | 6.030 |
| trt1 | 4.890 |
| trt1 | 4.320 |
| trt1 | 4.690 |
| trt2 | 6.310 |
| trt2 | 5.120 |
| trt2 | 5.540 |
| trt2 | 5.500 |
| trt2 | 5.370 |
| trt2 | 5.290 |
| trt2 | 4.920 |
| trt2 | 6.150 |
| trt2 | 5.800 |
| trt2 | 5.260 |
View data
| Difference in weight | CI high | Comparison | CI low |
|---|---|---|---|
| −0.3710 | 0.4301 | trt1-ctrl | −1.172 |
| 0.4940 | 1.089 | trt2-ctrl | −0.1006 |
| 0.8650 | 1.616 | trt2-trt1 | 0.1135 |
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.966, p = .438.
- Equal variances — Welch's ANOVA does not assume equal variances (Brown–Forsythe F = 1.12, p = .341).
Descriptives
| group | n | Mean | SD | SE |
|---|---|---|---|---|
| ctrl | 10 | 5.032 | 0.5831 | 0.1844 |
| trt1 | 10 | 4.661 | 0.7937 | 0.2510 |
| trt2 | 10 | 5.526 | 0.4426 | 0.1400 |
Games–Howell
| Comparison | Difference | 95% CI low | 95% CI high | p (adjusted) |
|---|---|---|---|---|
| trt1-ctrl | −0.3710 | −1.172 | 0.4301 | .475 |
| trt2-ctrl | 0.4940 | −0.1006 | 1.089 | .113 |
| trt2-trt1 | 0.8650 | 0.1135 | 1.616 | .024 |
- Welch's one-way ANOVA; effect sizes from the classic sums of squares; post hoc differences are later − earlier level.
The exact R script · R R version 4.5.1 (2025-06-13)
# One-way ANOVA (Welch / classic)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.oneway 1.2.2 · spec 9396dc3962ec49cc
# Dataset: plantgrowth (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/plantgrowth.parquet", col_select = c("weight", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("ctrl", "trt1", "trt2")) # stored level order
df <- df[stats::complete.cases(df[c("weight", "group")]), , 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("weight", "group")) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro-Wilk keeps the
# method's own row; any other choice replaces it (cs_normality_test; a simulated p such as
# Filliben's uses the fixed seed 42, so Python draws the same stream).
normality_test <- "shapiro_wilk"
normality_selected <- function(samples, row_label, small) {
res <- lapply(samples, function(s) cs_normality_test(as.numeric(s), normality_test, 42, 1999))
ok <- Filter(function(r) is.finite(r$p), res)
label <- res[[1]]$label
symbol <- res[[1]]$symbol
if (!length(ok)) {
return(list(row = list(key = "normality", label = row_label, status = "info",
detail = sprintf("%s is not available for these sample sizes.", label)), p = NULL))
}
ps <- vapply(ok, function(r) r$p, 0)
p_min <- min(ps)
bad <- sum(ps < 0.05)
status <- if (bad) (if (small) "warn" else "info") else "pass"
tail <- if (status == "warn") "; consider a rank-based or robust method." else "."
row <- if (length(samples) == 1) {
list(key = "normality", label = row_label, status = status, statistic = ok[[1]]$statistic, p = ok[[1]]$p,
detail = paste0(sprintf("%s %s = %.3f, %s", label, symbol, ok[[1]]$statistic, cs_fmt_p(ok[[1]]$p)), tail))
} else {
list(key = "normality", label = row_label, status = status,
detail = paste0(if (bad) sprintf("%s: p < .05 in %d of %d groups (smallest %s)", label, bad, length(ok), cs_fmt_p(p_min))
else sprintf("%s: p ≥ .05 in every group", label), tail))
}
list(row = row, p = p_min)
}
# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
y <- "weight"
g <- "group"
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
d <- data.frame(y = df[[y]], g = df[[g]])
levels_g <- levels(d$g)
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
if (any(is.infinite(d$y))) cs_error("CS_E_NOT_FINITE", column = y, count = sum(is.infinite(d$y)))
if (length(unique(d$y)) < 2) cs_error("CS_E_CONSTANT", column = y)
ns <- as.vector(table(d$g))
for (i in seq_len(k)) { # every variant needs a variance in each group (oneway.test: two values per group)
if (ns[i] < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = levels_g[i], n = ns[i])
}
means <- as.vector(tapply(d$y, d$g, mean))
variances <- as.vector(tapply(d$y, d$g, var))
N <- sum(ns)
variant <- "welch" # welch (default) | brown_forsythe | alexander_govern: no equal-variance assumption; classic
posthoc_method <- "auto"
if (!TRUE) posthoc_method <- "none" # legacy switch: analyses saved before version 1.2
if (posthoc_method == "auto") posthoc_method <- if (variant == "classic") "tukey" else "games_howell" # match the omnibus test
posthoc_labels <- c(tukey = "Tukey–Kramer", scheffe = "Scheffé", lsd = "Fisher's protected LSD", games_howell = "Games–Howell",
tamhane_t2 = "Tamhane T2", dunnett_t3 = "Dunnett T3", uwh = "Ury–Wiggins–Hochberg")
conf <- 0.95
# Sums of squares (classic decomposition) for the effect sizes.
grand <- mean(d$y)
ss_between <- sum(ns * (means - grand)^2)
ss_within <- sum((ns - 1) * variances)
if (ss_within <= 1e-12 * sum((d$y - grand)^2)) { # no variation inside the groups: every F ratio is undefined
cs_error("CS_E_UNDEFINED", what = "One-way ANOVA", reason = sprintf("%s does not vary within any group", y))
}
if (variant %in% c("welch", "alexander_govern")) { # weights are 1 / variance: a group without variation makes them infinite
for (i in seq_len(k)) {
if (length(unique(d$y[d$g == levels_g[i]])) == 1) {
cs_error("CS_E_UNDEFINED", what = if (variant == "welch") "Welch's ANOVA" else "The Alexander–Govern test",
reason = sprintf("%s does not vary within %s", y, levels_g[i]))
}
}
}
ss_total <- ss_between + ss_within
df1 <- k - 1
df_within <- N - k
ms_within <- ss_within / df_within
eta_sq <- ss_between / ss_total
omega_sq <- (ss_between - df1 * ms_within) / (ss_total + ms_within)
epsilon_sq <- (ss_between - df1 * ms_within) / ss_total
chisq <- NULL
df1_mehrotra <- NULL
p_mehrotra <- NULL
if (variant == "brown_forsythe") {
bf <- cs_brown_forsythe(split(d$y, d$g)) # Brown & Forsythe (1974) F* (onewaytests::bf.test)
f <- bf$f
df2 <- bf$df2
p <- bf$p
df1_mehrotra <- bf$df1_mehrotra # Mehrotra (1997) corrected df
p_mehrotra <- bf$p_mehrotra
} else if (variant == "alexander_govern") {
ag <- cs_alexander_govern(split(d$y, d$g)) # Alexander & Govern (1994), A ~ chi^2(k - 1)
f <- NULL
df2 <- NULL
p <- ag$p
chisq <- ag$statistic
} else {
res <- oneway.test(y ~ g, data = d, var.equal = variant == "classic") # Welch (1951) unless classic
f <- unname(res$statistic)
df2 <- unname(res$parameter[2])
p <- res$p.value
}
# %% Post hoc
pairs <- list()
if (posthoc_method != "none" && k > 2) {
# The shared post hoc twins (cs_* <-> codesplash.stats.posthoc, posthoc.pairwise) report earlier - later;
# this card reports later - earlier, so flip the sign and the interval.
groups <- split(d$y, d$g)
rows <- switch(posthoc_method,
tukey = cs_tukey_kramer(groups, levels_g, conf),
scheffe = cs_scheffe(groups, levels_g, conf)$rows,
lsd = cs_lsd(groups, levels_g, conf)$rows, # gated by the classic F
games_howell = cs_games_howell(groups, levels_g, conf),
tamhane_t2 = cs_tamhane_t2(groups, levels_g, conf),
dunnett_t3 = cs_dunnett_t3(groups, levels_g, conf),
cs_ury_wiggins_hochberg(groups, levels_g, conf = conf))
pairs <- lapply(seq_len(nrow(rows)), function(r) list(pair = paste(rows$b[r], rows$a[r], sep = "-"), diff = -rows$estimate[r],
p_adj = rows$p_adj[r], ci_low = -rows$ci_high[r], ci_high = -rows$ci_low[r]))
}
# %% Assumptions
assumptions <- list()
resid <- d$y - ave(d$y, d$g)
sw <- if (N >= 3 && N <= 5000 && diff(range(resid)) > 0) shapiro.test(resid) else NULL
if (is.null(sw)) {
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = "info", detail = "Shapiro–Wilk not computed (needs 3–5,000 residuals).")
} else {
status <- if (sw$p.value >= 0.05) "pass" else if (min(ns) >= 30) "info" else "warn"
assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = status, statistic = unname(sw$statistic), p = sw$p.value,
detail = paste0(sprintf("Shapiro–Wilk W = %.3f, %s", sw$statistic, cs_fmt_p(sw$p.value)),
if (status == "warn") "; consider Kruskal–Wallis." else "."))
}
lev <- oneway.test(abs(d$y - ave(d$y, d$g, FUN = median)) ~ d$g, var.equal = TRUE) # Brown-Forsythe
lev_f <- unname(lev$statistic)
lev_p <- lev$p.value
if (variant == "classic") {
status <- if (lev_p < 0.05) "warn" else "pass"
detail <- paste0(sprintf("Brown–Forsythe F = %.2f, %s", lev_f, cs_fmt_p(lev_p)), if (lev_p < 0.05) "; Welch's ANOVA is safer." else ".")
} else {
status <- "info"
detail <- sprintf("Welch's ANOVA does not assume equal variances (Brown–Forsythe F = %.2f, %s).", lev_f, cs_fmt_p(lev_p))
}
assumptions[[2]] <- list(key = "equal_variance", label = "Equal variances", status = status, detail = detail, statistic = lev_f, p = lev_p)
# Equal-variance row: the dialog's `variance_test` (Brown-Forsythe above is the default).
variance_test <- "brown_forsythe"
if (variance_test != "brown_forsythe") {
vt <- cs_spread_test(d$y, as.integer(d$g) - 1L, variance_test) # cs_spread_test <-> codesplash.stats.spread
lev_f <- vt$statistic
lev_p <- vt$p
shown <- sprintf("%s %s = %.2f, %s", vt$label, vt$symbol, lev_f, cs_fmt_p(lev_p))
if (variant != "classic") {
status <- "info"
detail <- sprintf("Welch's ANOVA does not assume equal variances (%s).", shown)
} else {
status <- if (lev_p < 0.05) "warn" else "pass"
detail <- paste0(shown, if (lev_p < 0.05) "; Welch's ANOVA is safer." else ".")
}
assumptions <- lapply(assumptions, function(a) if (a$key == "equal_variance") list(key = "equal_variance", label = "Equal variances",
status = status, detail = detail, statistic = lev_f, p = lev_p) else a)
}
if (min(ns) < 5) warnings <- c(warnings, "A group has fewer than 5 values.")
normality_p <- NULL
if (normality_test != "shapiro_wilk") {
ns_ <- normality_selected(list(resid), "Normality of residuals", min(ns) < 30)
normality_p <- ns_$p
assumptions <- lapply(assumptions, function(a) if (a$key == "normality") ns_$row else a)
}
# %% Result
alpha <- 1 - conf
size <- magnitude(omega_sq, c(0.01, 0.06, 0.14))
name <- c(welch = "Welch's one-way ANOVA", brown_forsythe = "Brown–Forsythe test of means",
alexander_govern = "Alexander–Govern test", classic = "One-way ANOVA")[[variant]]
significance <- if (p < alpha) {
sprintf("The group means differ significantly (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with equal means (%s).", cs_fmt_p(p))
}
summary <- sprintf("Mean %s across %d groups of %s ranged from %.2f to %.2f. %s %s accounts for an estimated %.0f%% of the variance in %s (ω² = %.2f, %s).",
y, k, g, min(means), max(means), significance, g, omega_sq * 100, y, omega_sq, size)
if (length(pairs)) {
n_sig <- sum(vapply(pairs, function(r) r$p_adj < alpha, logical(1)))
summary <- paste(summary, sprintf("%d of %d pairwise differences are significant (%s).", n_sig, length(pairs),
posthoc_labels[[posthoc_method]]))
}
values <- list(f = f, df1 = df1, df2 = df2, p = p, k = k, n = N, chisq = chisq, df1_mehrotra = df1_mehrotra, p_mehrotra = p_mehrotra,
eta_sq = eta_sq, omega_sq = omega_sq, epsilon_sq = epsilon_sq,
ss_between = ss_between, ss_within = ss_within, levene_f = lev_f, levene_p = lev_p,
sw_p_resid = if (is.null(sw)) NULL else sw$p.value)
for (r in pairs) {
for (key in c("diff", "p_adj", "ci_low", "ci_high")) values[[sprintf("%s[%s]", key, r$pair)]] <- r[[key]]
}
pct <- sprintf("%.0f%%", conf * 100)
tables <- list(list(
key = "descriptives", title = "Descriptives",
columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
list(key = "se", label = "SE", type = "number")),
rows = data.frame(group = levels_g, n = ns, mean = means, sd = sqrt(variances), se = sqrt(variances / ns))
))
if (length(pairs)) {
tables[[2]] <- list(
key = "posthoc", title = posthoc_labels[[posthoc_method]],
columns = list(list(key = "pair", label = "Comparison", type = "string"), list(key = "diff", label = "Difference", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "p_adj", label = "p (adjusted)", type = "pvalue")),
rows = pairs
)
}
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0 # consult-a-statistician input
values$max_interaction_order <- 1
if (!is.null(normality_p)) values$normality_p <- normality_p
chart_rows <- unique(round(seq(1, nrow(df), length.out = min(nrow(df), 5000))))
cs_publish(list(
method = "anova.oneway",
methodVersion = "1.2.2",
title = name,
engine = cs_engine_info("stats", "nanoparquet"),
n = N,
summary = summary,
apa = if (variant == "alexander_govern") sprintf("χ²(%d) = %s, %s, ω² = %s", df1, cs_fmt_num(chisq), cs_fmt_p(p), cs_fmt_num(omega_sq, leading_zero = FALSE))
else sprintf("F(%d, %s) = %s, %s, ω² = %s", df1, if (variant == "classic") sprintf("%.0f", df2) else sprintf("%.2f", df2),
cs_fmt_num(f), cs_fmt_p(p), cs_fmt_num(omega_sq, leading_zero = FALSE)),
statistics = c(if (variant == "alexander_govern") list(list(key = "chisq", label = "A (χ²)", value = chisq), list(key = "df1", label = "df", value = df1))
else list(list(key = "f", label = if (variant == "brown_forsythe") "F*" else "F", value = f), list(key = "df1", label = "df1", value = df1),
list(key = "df2", label = "df2", value = df2)),
list(list(key = "p", label = "p", value = p, format = "p"))),
tables = tables,
effectSizes = list(
list(key = "omega_sq", label = "ω²", value = omega_sq, method = "(SSb − df1·MSw) / (SSt + MSw)", magnitude = size, ruleSet = "Cohen (1988)"),
list(key = "eta_sq", label = "η²", value = eta_sq, method = "SSb / SSt", magnitude = magnitude(eta_sq, c(0.01, 0.06, 0.14)), ruleSet = "Cohen (1988)"),
list(key = "epsilon_sq", label = "ε²", value = epsilon_sq, method = "(SSb − df1·MSw) / SSt")
),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("%s; effect sizes from the classic sums of squares; post hoc differences are later − earlier level.", name)),
if (variant == "brown_forsythe") list(sprintf("Mehrotra's (1997) corrected numerator df = %.3f gives %s.", df1_mehrotra, cs_fmt_p(p_mehrotra))) else list()),
values = values,
charts = c(list(cs_chart("distribution", "raincloud", sprintf("%s by %s", y, g),
list(y = cs_col(y, df[[y]][chart_rows]), group = cs_col(g, as.character(df[[g]][chart_rows]), levels = levels_g)))),
if (length(pairs)) list(cs_chart("differences", "forest", sprintf("Differences in mean %s (%.0f%% simultaneous CI)", y, conf * 100), list(
label = cs_col("Comparison", vapply(pairs, function(x) x$pair, ""), "categorical"),
estimate = cs_col(sprintf("Difference in %s", y), vapply(pairs, function(x) x$diff, 0), "numeric"),
low = cs_col("CI low", vapply(pairs, function(x) x$ci_low, 0), "numeric"),
high = cs_col("CI high", vapply(pairs, function(x) x$ci_high, 0), "numeric")), controls = list(reference = 0))) else list())
))
F(2, 17.13) = 5.18, p = .017, ω² = .20
- F
- 5.181
- df1
- 2
- df2
- 17.128
- p
- .017
Effect size
- ω² 0.2041 · large
- η² 0.2641 · large
- ε² 0.2096
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of residuals — Shapiro–Wilk W = 0.966, p = .438.
- Equal variances — Welch's ANOVA does not assume equal variances (Brown–Forsythe F = 1.12, p = .341).
Descriptives
| group | n | Mean | SD | SE |
|---|---|---|---|---|
| ctrl | 10 | 5.032 | 0.5831 | 0.1844 |
| trt1 | 10 | 4.661 | 0.7937 | 0.2510 |
| trt2 | 10 | 5.526 | 0.4426 | 0.1400 |
Games–Howell
| Comparison | Difference | 95% CI low | 95% CI high | p (adjusted) |
|---|---|---|---|---|
| trt1-ctrl | −0.3710 | −1.172 | 0.4301 | .475 |
| trt2-ctrl | 0.4940 | −0.1006 | 1.089 | .113 |
| trt2-trt1 | 0.8650 | 0.1135 | 1.616 | .024 |
- Welch's one-way ANOVA; effect sizes from the classic sums of squares; post hoc differences are later − earlier level.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One-way ANOVA (Welch / classic)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.oneway 1.2.2 · spec 9396dc3962ec49cc
# Dataset: plantgrowth (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
from scipy import stats
import codesplash as cs
from codesplash.stats import means as csm
from codesplash.stats import posthoc as ph
# %% Data
df = pd.read_parquet("tests/parity/fixtures/plantgrowth.parquet", columns=["weight", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["ctrl", "trt1", "trt2"]) # stored level order
df = df.dropna(subset=["weight", "group"]) # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
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, ["weight", "group"]) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro–Wilk keeps the
# method's own row; any other choice replaces it (codesplash.stats.normality.normality_test; a
# simulated p such as Filliben's uses the fixed seed 42, so R draws the same stream).
normality_test = "shapiro_wilk"
def normality_selected(samples, row_label, small):
from codesplash.stats import normality as csn
res = [csn.normality_test(np.asarray(s, dtype=float), normality_test, 42, 1999) for s in samples]
ok = [r for r in res if np.isfinite(r["p"])]
label, symbol = res[0]["label"], res[0]["symbol"]
if not ok:
return {"key": "normality", "label": row_label, "status": "info", "detail": f"{label} is not available for these sample sizes."}, None
p_min = min(r["p"] for r in ok)
bad = sum(r["p"] < 0.05 for r in ok)
status = ("warn" if small else "info") if bad else "pass"
row = {"key": "normality", "label": row_label, "status": status}
if len(samples) == 1:
row.update({"statistic": ok[0]["statistic"], "p": ok[0]["p"],
"detail": f"{label} {symbol} = {ok[0]['statistic']:.3f}, {cs.fmt_p(ok[0]['p'])}" + ("; consider a rank-based or robust method." if status == "warn" else ".")})
else:
row["detail"] = (f"{label}: p < .05 in {bad} of {len(ok)} groups (smallest {cs.fmt_p(p_min)})" if bad
else f"{label}: p ≥ .05 in every group") + ("; consider a rank-based or robust method." if status == "warn" else ".")
return row, p_min
# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
y, g = "weight", "group"
if len(df) == 0:
cs.cs_error("CS_E_NO_ROWS")
levels = [str(lv) for lv in df[g].cat.categories]
k = len(levels)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
if np.isinf(df[y].to_numpy(dtype=float)).any():
cs.cs_error("CS_E_NOT_FINITE", column=y, count=int(np.isinf(df[y].to_numpy(dtype=float)).sum()))
if df[y].nunique() < 2:
cs.cs_error("CS_E_CONSTANT", column=y)
groups = [df.loc[df[g] == lv, y].to_numpy(dtype=float) for lv in df[g].cat.categories]
ns = np.array([len(x) for x in groups])
for lv, n_lv in zip(levels, ns): # every variant needs a variance in each group (R's oneway.test: two values per group)
if n_lv < 2:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=lv, n=int(n_lv))
means = np.array([x.mean() for x in groups])
variances = np.array([x.var(ddof=1) if len(x) > 1 else np.nan for x in groups])
N = int(ns.sum())
variant = "welch" # welch (default) | brown_forsythe | alexander_govern: no equal-variance assumption; classic
posthoc_method = "auto"
if not True: # legacy switch: analyses saved before version 1.2 ("posthoc: false")
posthoc_method = "none"
if posthoc_method == "auto": # match the omnibus test
posthoc_method = "tukey" if variant == "classic" else "games_howell"
POSTHOC_LABELS = {"tukey": "Tukey–Kramer", "scheffe": "Scheffé", "lsd": "Fisher's protected LSD", "games_howell": "Games–Howell",
"tamhane_t2": "Tamhane T2", "dunnett_t3": "Dunnett T3", "uwh": "Ury–Wiggins–Hochberg"}
conf = 0.95
# Sums of squares (classic decomposition) for the effect sizes.
grand = df[y].mean()
ss_between = float((ns * (means - grand) ** 2).sum())
ss_within = float(((ns - 1) * variances).sum())
if ss_within <= 1e-12 * float(((df[y] - grand) ** 2).sum()): # no variation inside the groups: every F ratio is undefined
cs.cs_error("CS_E_UNDEFINED", what="One-way ANOVA", reason=f"{y} does not vary within any group")
if variant in ("welch", "alexander_govern"): # weights are 1 / variance: a group without variation makes them infinite
for lv, x in zip(levels, groups):
if len(np.unique(x)) == 1:
cs.cs_error("CS_E_UNDEFINED", what="Welch's ANOVA" if variant == "welch" else "The Alexander–Govern test",
reason=f"{y} does not vary within {lv}")
ss_total = ss_between + ss_within
df1, df_within = k - 1, N - k
ms_within = ss_within / df_within
eta_sq = ss_between / ss_total
omega_sq = (ss_between - df1 * ms_within) / (ss_total + ms_within)
epsilon_sq = (ss_between - df1 * ms_within) / ss_total
chisq = df1_mehrotra = p_mehrotra = None
if variant == "welch":
res = stats.f_oneway(*groups, equal_var=False) # Welch (1951)
w = ns / variances
tmp = float((((1 - w / w.sum()) ** 2) / (ns - 1)).sum())
df2 = (k**2 - 1) / (3 * tmp)
f, p = float(res.statistic), float(res.pvalue)
elif variant == "brown_forsythe":
bf = csm.brown_forsythe(groups) # Brown & Forsythe (1974) F* (onewaytests::bf.test)
f, df2, p = bf["f"], bf["df2"], bf["p"]
df1_mehrotra, p_mehrotra = bf["df1_mehrotra"], bf["p_mehrotra"] # Mehrotra (1997) corrected df
elif variant == "alexander_govern":
ag = csm.alexander_govern(groups) # Alexander & Govern (1994), A ~ χ²(k − 1)
f, df2, p, chisq = None, None, ag["p"], ag["statistic"]
else:
res = stats.f_oneway(*groups) # classic F (equal variances)
df2 = float(df_within)
f, p = float(res.statistic), float(res.pvalue)
# %% Post hoc
pairs = []
if posthoc_method != "none" and k > 2:
# The shared post hoc twins (codesplash.stats.posthoc ↔ cs_*, posthoc.pairwise) report earlier − later;
# this card reports later − earlier, so flip the sign and the interval.
if posthoc_method == "tukey":
rows = ph.tukey_kramer(groups, levels, conf)
elif posthoc_method == "scheffe":
rows, _crit = ph.scheffe(groups, levels, conf)
elif posthoc_method == "lsd":
rows, _f, _p, _crit = ph.lsd(groups, levels, conf) # gated by the classic F
elif posthoc_method == "games_howell":
rows = ph.games_howell(groups, levels, conf)
elif posthoc_method == "tamhane_t2":
rows = ph.tamhane_t2(groups, levels, conf)
elif posthoc_method == "dunnett_t3":
rows = ph.dunnett_t3(groups, levels, conf)
else:
rows = ph.ury_wiggins_hochberg(groups, levels, conf=conf)
pairs = [{"pair": f"{r['b']}-{r['a']}", "diff": -float(r["estimate"]), "p_adj": float(r["p_adj"]),
"ci_low": -float(r["ci_high"]), "ci_high": -float(r["ci_low"])} for r in rows]
# %% Assumptions
assumptions = []
resid = np.concatenate([x - x.mean() for x in groups])
sw = stats.shapiro(resid) if 3 <= N <= 5000 and np.ptp(resid) > 0 else None
if sw is None:
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "info", "detail": "Shapiro–Wilk not computed (needs 3–5,000 residuals)."})
else:
status = "pass" if sw.pvalue >= 0.05 else ("info" if ns.min() >= 30 else "warn")
assumptions.append({"key": "normality", "label": "Normality of residuals", "status": status, "statistic": float(sw.statistic), "p": float(sw.pvalue),
"detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}" + ("; consider Kruskal–Wallis." if status == "warn" else ".")})
lev = stats.levene(*groups, center="median") # Brown–Forsythe
if variant == "classic":
status = "warn" if lev.pvalue < 0.05 else "pass"
detail = f"Brown–Forsythe F = {lev.statistic:.2f}, {cs.fmt_p(lev.pvalue)}" + ("; Welch's ANOVA is safer." if lev.pvalue < 0.05 else ".")
else:
status, detail = "info", f"Welch's ANOVA does not assume equal variances (Brown–Forsythe F = {lev.statistic:.2f}, {cs.fmt_p(lev.pvalue)})."
assumptions.append({"key": "equal_variance", "label": "Equal variances", "status": status, "detail": detail, "statistic": float(lev.statistic), "p": float(lev.pvalue)})
# Equal-variance row: the dialog's `variance_test` (Brown–Forsythe above is the default).
variance_test = "brown_forsythe"
lev_f, lev_p = float(lev.statistic), float(lev.pvalue)
if variance_test != "brown_forsythe":
from codesplash.stats import spread
vt = spread.spread_test(np.concatenate(groups), np.repeat(np.arange(k), ns.astype(int)), variance_test) # codesplash.stats.spread ↔ cs_spread_test
lev_f, lev_p = float(vt["statistic"]), float(vt["p"])
shown = f"{vt['label']} {vt['symbol']} = {lev_f:.2f}, {cs.fmt_p(lev_p)}"
if variant != "classic":
status, detail = "info", f"Welch's ANOVA does not assume equal variances ({shown})."
else:
status = "warn" if lev_p < 0.05 else "pass"
detail = shown + ("; " + "Welch's ANOVA" + " is safer." if lev_p < 0.05 else ".")
assumptions = [{"key": "equal_variance", "label": "Equal variances", "status": status, "detail": detail, "statistic": lev_f, "p": lev_p}
if a["key"] == "equal_variance" else a for a in assumptions]
if ns.min() < 5:
warnings.append("A group has fewer than 5 values.")
normality_p = None
if normality_test != "shapiro_wilk":
_row, normality_p = normality_selected([resid], "Normality of residuals", ns.min() < 30)
assumptions = [_row if a["key"] == "normality" else a for a in assumptions]
# %% Result
alpha = 1 - conf
size = magnitude(omega_sq, (0.01, 0.06, 0.14))
name = {"welch": "Welch's one-way ANOVA", "brown_forsythe": "Brown–Forsythe test of means",
"alexander_govern": "Alexander–Govern test", "classic": "One-way ANOVA"}[variant]
significance = (
f"The group means differ significantly ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with equal means ({cs.fmt_p(p)})."
)
summary = (
f"Mean {y} across {k} groups of {g} ranged from {means.min():.2f} to {means.max():.2f}. {significance} "
f"{g} accounts for an estimated {omega_sq:.0%} of the variance in {y} (ω² = {omega_sq:.2f}, {size})."
)
significant_pairs = [r["pair"] for r in pairs if r["p_adj"] < alpha]
if pairs:
summary += f" {len(significant_pairs)} of {len(pairs)} pairwise differences are significant ({POSTHOC_LABELS[posthoc_method]})."
values = {
"f": f, "df1": float(df1), "df2": None if df2 is None else float(df2), "p": p, "k": k, "n": N,
"chisq": chisq, "df1_mehrotra": df1_mehrotra, "p_mehrotra": p_mehrotra,
"eta_sq": eta_sq, "omega_sq": omega_sq, "epsilon_sq": epsilon_sq,
"ss_between": ss_between, "ss_within": ss_within,
"levene_f": lev_f, "levene_p": lev_p, "sw_p_resid": None if sw is None else float(sw.pvalue),
}
for r in pairs:
values.update({f"{key}[{r['pair']}]": r[key] for key in ("diff", "p_adj", "ci_low", "ci_high")})
tables = [{
"key": "descriptives", "title": "Descriptives",
"columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
{"key": "se", "label": "SE", "type": "number"}],
"rows": [{"group": lv, "n": int(n), "mean": float(m), "sd": float(np.sqrt(v)), "se": float(np.sqrt(v / n))}
for lv, n, m, v in zip(levels, ns, means, variances)],
}]
if pairs:
tables.append({
"key": "posthoc", "title": POSTHOC_LABELS[posthoc_method],
"columns": [{"key": "pair", "label": "Comparison", "type": "string"}, {"key": "diff", "label": "Difference", "type": "number"},
{"key": "ci_low", "label": f"{conf:.0%} CI low", "type": "number"}, {"key": "ci_high", "label": f"{conf:.0%} CI high", "type": "number"},
{"key": "p_adj", "label": "p (adjusted)", "type": "pvalue"}],
"rows": pairs,
})
values["missing_share"] = n_dropped / n_input if n_input else 0.0 # consult-a-statistician input
values["max_interaction_order"] = 1
if normality_p is not None:
values["normality_p"] = normality_p
chart_rows = np.unique(np.round(np.linspace(0, len(df) - 1, min(len(df), 5000))).astype(int))
cs.publish({
"method": "anova.oneway",
"methodVersion": "1.2.2",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": N,
"summary": summary,
"apa": (f"χ²({df1}) = {cs.fmt_num(chisq)}, {cs.fmt_p(p)}, ω² = {cs.fmt_num(omega_sq, leading_zero=False)}" if variant == "alexander_govern"
else f"F({df1}, {df2:.0f}) = {cs.fmt_num(f)}, {cs.fmt_p(p)}, ω² = {cs.fmt_num(omega_sq, leading_zero=False)}" if variant == "classic"
else f"F({df1}, {df2:.2f}) = {cs.fmt_num(f)}, {cs.fmt_p(p)}, ω² = {cs.fmt_num(omega_sq, leading_zero=False)}"),
"statistics": ([{"key": "chisq", "label": "A (χ²)", "value": chisq}, {"key": "df1", "label": "df", "value": df1}]
if variant == "alexander_govern" else
[{"key": "f", "label": "F*" if variant == "brown_forsythe" else "F", "value": f}, {"key": "df1", "label": "df1", "value": df1},
{"key": "df2", "label": "df2", "value": df2}])
+ [{"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": tables,
"effectSizes": [
{"key": "omega_sq", "label": "ω²", "value": omega_sq, "method": "(SSb − df1·MSw) / (SSt + MSw)", "magnitude": size, "ruleSet": "Cohen (1988)"},
{"key": "eta_sq", "label": "η²", "value": eta_sq, "method": "SSb / SSt", "magnitude": magnitude(eta_sq, (0.01, 0.06, 0.14)), "ruleSet": "Cohen (1988)"},
{"key": "epsilon_sq", "label": "ε²", "value": epsilon_sq, "method": "(SSb − df1·MSw) / SSt"},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{name}; effect sizes from the classic sums of squares; post hoc differences are later − earlier level."]
+ ([f"Mehrotra's (1997) corrected numerator df = {df1_mehrotra:.3f} gives {cs.fmt_p(p_mehrotra)}."] if variant == "brown_forsythe" else []),
"values": values,
"charts": [cs.chart("distribution", "raincloud", f"{y} by {g}", {
"y": cs.col(y, df[y].to_numpy(dtype=float)[chart_rows]),
"group": cs.col(g, df[g].astype(str).to_numpy()[chart_rows], levels=levels)})]
+ ([cs.chart("differences", "forest", f"Differences in mean {y} ({conf:.0%} simultaneous CI)", {
"label": cs.col("Comparison", [x["pair"] for x in pairs], "categorical"),
"estimate": cs.col(f"Difference in {y}", [x["diff"] for x in pairs], "numeric"),
"low": cs.col("CI low", [x["ci_low"] for x in pairs], "numeric"),
"high": cs.col("CI high", [x["ci_high"] for x in pairs], "numeric")}, controls={"reference": 0})] if pairs else []),
})
Tier badges list known differences: reasons already understood, such as one engine integrating a distribution numerically where the other uses a published algorithm. A tiny difference with a known cause is expected. A value outside its tolerance shows Python ≠ R, which is worth reporting.
Definitions in the wild
ExploreLibrary versions of "the same test" can use different formulas. The app's method notes that its Anderson–Darling and Lilliefors p-values follow one published implementation, and that other libraries' differ.
0 of 3 groups of weight depart from normality by the n-dependent rule.
- Tests rejecting
- 0
- Tests run
- 11
- Departing
- 0
- Groups
- 3
Plots
View data
| weight |
|---|
| 4.170 |
| 5.580 |
| 5.180 |
| 6.110 |
| 4.500 |
| 4.610 |
| 5.170 |
| 4.530 |
| 5.330 |
| 5.140 |
View data
| weight |
|---|
| 4.810 |
| 4.170 |
| 4.410 |
| 3.590 |
| 5.870 |
| 3.830 |
| 6.030 |
| 4.890 |
| 4.320 |
| 4.690 |
View data
| weight |
|---|
| 6.310 |
| 5.120 |
| 5.540 |
| 5.500 |
| 5.370 |
| 5.290 |
| 4.920 |
| 6.150 |
| 5.800 |
| 5.260 |
Normality tests
| group | Test | Statistic | p | Rejects at .05 |
|---|---|---|---|---|
| ctrl | Shapiro–Wilk | 0.9567 | .747 | no |
| ctrl | Shapiro–Francia | 0.9553 | .694 | no |
| ctrl | Filliben probability-plot correlation | 0.9771 | .657 | no |
| ctrl | Anderson–Darling | 0.2829 | .555 | no |
| ctrl | Lilliefors (Kolmogorov–Smirnov) | 0.1735 | .528 | no |
| ctrl | Cramér–von Mises | 0.0495 | .482 | no |
| ctrl | D'Agostino–Pearson omnibus | 0.2335 | .890 | no |
| ctrl | Jarque–Bera | 0.3120 | .856 | no |
| ctrl | D'Agostino skewness | 0.4831 | .629 | no |
| ctrl | Anscombe–Glynn kurtosis | 0.0104 | .992 | no |
| ctrl | Pearson χ² | 4.400 | .221 | no |
| trt1 | Shapiro–Wilk | 0.9304 | .452 | no |
| trt1 | Shapiro–Francia | 0.9380 | .474 | no |
| trt1 | Filliben probability-plot correlation | 0.9687 | .473 | no |
| trt1 | Anderson–Darling | 0.3298 | .444 | no |
| trt1 | Lilliefors (Kolmogorov–Smirnov) | 0.1865 | .410 | no |
| trt1 | Cramér–von Mises | 0.0490 | .491 | no |
| trt1 | D'Agostino–Pearson omnibus | 0.9677 | .616 | no |
| trt1 | Jarque–Bera | 0.6962 | .706 | no |
| trt1 | D'Agostino skewness | 0.9832 | .326 | no |
| trt1 | Anscombe–Glynn kurtosis | 0.0329 | .974 | no |
| trt1 | Pearson χ² | 3.200 | .362 | no |
| trt2 | Shapiro–Wilk | 0.9410 | .564 | no |
| trt2 | Shapiro–Francia | 0.9467 | .578 | no |
| trt2 | Filliben probability-plot correlation | 0.9730 | .563 | no |
| trt2 | Anderson–Darling | 0.3089 | .503 | no |
| trt2 | Lilliefors (Kolmogorov–Smirnov) | 0.1874 | .403 | no |
| trt2 | Cramér–von Mises | 0.0513 | .456 | no |
| trt2 | D'Agostino–Pearson omnibus | 1.013 | .603 | no |
| trt2 | Jarque–Bera | 0.7585 | .684 | no |
| trt2 | D'Agostino skewness | 1.004 | .315 | no |
| trt2 | Anscombe–Glynn kurtosis | −0.0725 | .942 | no |
| trt2 | Pearson χ² | 2 | .572 | no |
Shape and verdict
| group | n | Tests rejecting | Skewness (G1) | z | Excess kurtosis (G2) | z | Verdict |
|---|---|---|---|---|---|---|---|
| ctrl | 10 | 0 | 0.3210 | 0.4672 | −0.2291 | −0.1717 | no evidence against normality |
| trt1 | 10 | 0 | 0.6590 | 0.9591 | −0.2028 | −0.1520 | no evidence against normality |
| trt2 | 10 | 0 | 0.6732 | 0.9799 | −0.3242 | −0.2430 | no evidence against normality |
- Verdict: n < 50 → Shapiro–Wilk at α = .05; 50–299 → |z| of skewness or kurtosis > 3.29; n ≥ 300 → |G1| > 2 or excess kurtosis > 4 (Kim 2013). With large samples every test rejects trivial departures, so the magnitudes decide.
- All eleven tests estimate the mean and SD (composite null). Shapiro–Wilk needs 3–5,000 values, Shapiro–Francia 5–5,000, Anderson–Darling, Cramér–von Mises, Pearson χ² and the D'Agostino tests at least 8, Lilliefors at least 5.
- Filliben's p compares r with 1999 normal samples of the same size (seed 42); the tests overlap, so 'k of 11 reject' is a summary of agreement, not a combined test.
The exact R script · R R version 4.5.1 (2025-06-13)
# Normality tests (battery)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method normality.battery 1.1.1 · spec 443cb27941ed89ce
# Dataset: plantgrowth (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/plantgrowth.parquet", col_select = c("weight", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("ctrl", "trt1", "trt2")) # stored level order
df <- df[stats::complete.cases(df[c("weight", "group")]), , 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("weight", "group")) # infinite values stop the run (registry/errors.yaml)
# %% Tests
y <- "weight"
g <- "group"
parts <- lapply(levels(df[[g]]), function(lv) list(level = lv, x = df[[y]][df[[g]] == lv]))
if (nrow(df) >= 2 && length(unique(df[[y]])) < 2) cs_error("CS_E_CONSTANT", column = y) # no variation: every test and shape measure is undefined
alpha <- 0.05
verdict <- function(n, sw_p, m, flat = FALSE) {
# n-dependent rule (Kim 2013): tests for small n, standardized shape for moderate n, magnitudes for large n.
if (n < 8) return(list(FALSE, "too few values to judge"))
if (flat) return(list(FALSE, "no variation to judge")) # every value the same: tests and shape are undefined
if (n < 50) {
bad <- is.finite(sw_p) && sw_p < alpha
return(list(bad, if (bad) "departs from normality (Shapiro–Wilk)" else "no evidence against normality"))
}
if (n < 300) {
bad <- abs(m$skewness_z) > 3.29 || abs(m$kurtosis_z) > 3.29
return(list(bad, if (bad) "departs from normality (|z| of skewness or kurtosis > 3.29)" else "approximately normal in shape"))
}
bad <- abs(m$skewness) > 2 || m$kurtosis > 4
list(bad, if (bad) "substantially non-normal (|G1| > 2 or G2 > 4)" else "approximately normal in shape (large n: judged by magnitude)")
}
# Each test: c(statistic key, p key) in the published values.
keys <- list(shapiro_wilk = c("sw_w", "sw_p"), shapiro_francia = c("sf_w", "sf_p"), filliben = c("ppcc_r", "ppcc_p"),
anderson_darling = c("ad_a", "ad_p"), lilliefors = c("lillie_d", "lillie_p"), cramer_von_mises = c("cvm_w2", "cvm_p"),
dagostino_pearson = c("k2", "k2_p"), jarque_bera = c("jb", "jb_p"), skewness = c("skew_z", "skew_p"),
kurtosis = c("kurt_z", "kurt_p"), pearson_chisq = c("chisq", "chisq_p"))
seed <- 42 # Filliben's p: normal samples from the shared Wichmann-Hill stream
reps <- as.integer(1999)
rows <- list()
tests <- list()
values <- list(n_total = nrow(df))
for (pt in parts) {
x <- pt$x[!is.na(pt$x)]
n <- length(x)
part <- list(n = n)
n_tests <- 0
n_reject <- 0
for (name in cs_normality_test_names()) {
r <- cs_normality_test(x, name, seed = seed, reps = reps)
part[[keys[[name]][1]]] <- r$statistic
part[[keys[[name]][2]]] <- r$p
if (name == "pearson_chisq") part$chisq_df <- if (is.null(r$df) || r$df == 0) NaN else r$df
tested <- is.finite(r$p)
n_tests <- n_tests + tested
n_reject <- n_reject + (tested && r$p < alpha)
tests[[length(tests) + 1]] <- c(if (!is.null(g)) list(group = pt$level),
list(test = r$label, statistic = r$statistic, p = r$p,
reject = if (tested) (if (r$p < alpha) "yes" else "no") else "not computed"))
}
m <- cs_moments(x)
vd <- verdict(n, part$sw_p, m, flat = n > 0 && diff(range(x)) == 0)
part <- c(part, list(n_tests = n_tests, n_reject = n_reject, skewness = m$skewness, skewness_z = m$skewness_z,
kurtosis = m$kurtosis, kurtosis_z = m$kurtosis_z, depart = vd[[1]], verdict = vd[[2]]))
for (k in names(part)) values[[sprintf("%s[%s]", k, pt$level)]] <- part[[k]]
rows[[length(rows) + 1]] <- c(if (!is.null(g)) list(group = pt$level), part)
}
# %% Result
departing <- Filter(function(r) isTRUE(r$depart), rows)
values$n_parts <- length(rows)
values$n_departing <- length(departing)
values$lead <- parts[[1]]$level
group_col <- if (!is.null(g)) list(list(key = "group", label = g, type = "string")) else list()
charts <- list()
for (i in seq_len(min(6, length(parts)))) {
x <- parts[[i]]$x
if (length(x) < 3) next
rc <- unique(round(seq(1, length(x), length.out = min(length(x), 5000))))
charts[[length(charts) + 1]] <- cs_chart(sprintf("qq-%d", i - 1), "qq",
paste0("Normal Q–Q: ", y, if (!is.null(g)) sprintf(" (%s)", parts[[i]]$level) else ""),
list(x = cs_col(y, x[rc])))
}
cs_publish(list(
method = "normality.battery",
methodVersion = "1.1.1",
title = "Normality tests",
engine = cs_engine_info("stats", "nanoparquet"),
n = nrow(df),
summary = paste0(
if (is.null(g)) sprintf("%d of %d tests reject normality at α = .05 for %s; by the n-dependent rule it %s from normality.",
rows[[1]]$n_reject, rows[[1]]$n_tests, y, if (isTRUE(rows[[1]]$depart)) "departs" else "does not depart")
else sprintf("%d of %d groups of %s depart from normality by the n-dependent rule.", length(departing), length(rows), y),
if (any(vapply(rows, function(r) r$n >= 300, logical(1)))) " With n ≥ 300 every test rejects trivial departures — read the shape, not the p-values." else ""),
statistics = list(list(key = "n_reject", label = "Tests rejecting", value = rows[[1]]$n_reject), list(key = "n_tests", label = "Tests run", value = rows[[1]]$n_tests),
list(key = "n_departing", label = "Departing", value = length(departing)), list(key = "n_parts", label = "Groups", value = length(rows))),
tables = list(
list(key = "tests", title = "Normality tests", columns = c(group_col, list(
list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "reject", label = "Rejects at .05", type = "string"))), rows = tests),
list(key = "shape", title = "Shape and verdict", columns = c(group_col, list(
list(key = "n", label = "n", type = "integer"), list(key = "n_reject", label = "Tests rejecting", type = "integer"),
list(key = "skewness", label = "Skewness (G1)", type = "number"),
list(key = "skewness_z", label = "z", type = "number"), list(key = "kurtosis", label = "Excess kurtosis (G2)", type = "number"),
list(key = "kurtosis_z", label = "z", type = "number"), list(key = "verdict", label = "Verdict", type = "string"))),
rows = lapply(rows, function(r) r[intersect(c("group", "n", "n_reject", "skewness", "skewness_z", "kurtosis", "kurtosis_z", "verdict"), names(r))]))
),
effectSizes = list(),
assumptions = list(),
warnings = warnings,
notes = list(
paste("Verdict: n < 50 → Shapiro–Wilk at α = .05; 50–299 → |z| of skewness or kurtosis > 3.29; n ≥ 300 → |G1| > 2 or excess kurtosis > 4 (Kim 2013).",
"With large samples every test rejects trivial departures, so the magnitudes decide."),
paste("All eleven tests estimate the mean and SD (composite null). Shapiro–Wilk needs 3–5,000 values, Shapiro–Francia 5–5,000,",
"Anderson–Darling, Cramér–von Mises, Pearson χ² and the D'Agostino tests at least 8, Lilliefors at least 5."),
sprintf("Filliben's p compares r with %d normal samples of the same size (seed %d); the tests overlap, so 'k of 11 reject' is a summary of agreement, not a combined test.", reps, as.integer(seed))
),
charts = charts,
values = values
))
0 of 3 groups of weight depart from normality by the n-dependent rule.
- Tests rejecting
- 0
- Tests run
- 11
- Departing
- 0
- Groups
- 3
To keep this page light, the plots are shown once, under the R tab.
Normality tests
| group | Test | Statistic | p | Rejects at .05 |
|---|---|---|---|---|
| ctrl | Shapiro–Wilk | 0.9567 | .747 | no |
| ctrl | Shapiro–Francia | 0.9553 | .694 | no |
| ctrl | Filliben probability-plot correlation | 0.9771 | .657 | no |
| ctrl | Anderson–Darling | 0.2829 | .555 | no |
| ctrl | Lilliefors (Kolmogorov–Smirnov) | 0.1735 | .528 | no |
| ctrl | Cramér–von Mises | 0.0495 | .482 | no |
| ctrl | D'Agostino–Pearson omnibus | 0.2335 | .890 | no |
| ctrl | Jarque–Bera | 0.3120 | .856 | no |
| ctrl | D'Agostino skewness | 0.4831 | .629 | no |
| ctrl | Anscombe–Glynn kurtosis | 0.0104 | .992 | no |
| ctrl | Pearson χ² | 4.400 | .221 | no |
| trt1 | Shapiro–Wilk | 0.9304 | .452 | no |
| trt1 | Shapiro–Francia | 0.9380 | .474 | no |
| trt1 | Filliben probability-plot correlation | 0.9687 | .473 | no |
| trt1 | Anderson–Darling | 0.3298 | .444 | no |
| trt1 | Lilliefors (Kolmogorov–Smirnov) | 0.1865 | .410 | no |
| trt1 | Cramér–von Mises | 0.0490 | .491 | no |
| trt1 | D'Agostino–Pearson omnibus | 0.9677 | .616 | no |
| trt1 | Jarque–Bera | 0.6962 | .706 | no |
| trt1 | D'Agostino skewness | 0.9832 | .326 | no |
| trt1 | Anscombe–Glynn kurtosis | 0.0329 | .974 | no |
| trt1 | Pearson χ² | 3.200 | .362 | no |
| trt2 | Shapiro–Wilk | 0.9410 | .564 | no |
| trt2 | Shapiro–Francia | 0.9467 | .578 | no |
| trt2 | Filliben probability-plot correlation | 0.9730 | .563 | no |
| trt2 | Anderson–Darling | 0.3089 | .503 | no |
| trt2 | Lilliefors (Kolmogorov–Smirnov) | 0.1874 | .403 | no |
| trt2 | Cramér–von Mises | 0.0513 | .456 | no |
| trt2 | D'Agostino–Pearson omnibus | 1.013 | .603 | no |
| trt2 | Jarque–Bera | 0.7585 | .684 | no |
| trt2 | D'Agostino skewness | 1.004 | .315 | no |
| trt2 | Anscombe–Glynn kurtosis | −0.0725 | .942 | no |
| trt2 | Pearson χ² | 2.000 | .572 | no |
Shape and verdict
| group | n | Tests rejecting | Skewness (G1) | z | Excess kurtosis (G2) | z | Verdict |
|---|---|---|---|---|---|---|---|
| ctrl | 10 | 0 | 0.3210 | 0.4672 | −0.2291 | −0.1717 | no evidence against normality |
| trt1 | 10 | 0 | 0.6590 | 0.9591 | −0.2028 | −0.1520 | no evidence against normality |
| trt2 | 10 | 0 | 0.6732 | 0.9799 | −0.3242 | −0.2430 | no evidence against normality |
- Verdict: n < 50 → Shapiro–Wilk at α = .05; 50–299 → |z| of skewness or kurtosis > 3.29; n ≥ 300 → |G1| > 2 or excess kurtosis > 4 (Kim 2013). With large samples every test rejects trivial departures, so the magnitudes decide.
- All eleven tests estimate the mean and SD (composite null). Shapiro–Wilk needs 3–5,000 values, Shapiro–Francia 5–5,000, Anderson–Darling, Cramér–von Mises, Pearson χ² and the D'Agostino tests at least 8, Lilliefors at least 5.
- Filliben's p compares r with 1999 normal samples of the same size (seed 42); the tests overlap, so 'k of 11 reject' is a summary of agreement, not a combined test.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Normality tests (battery)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method normality.battery 1.1.1 · spec 443cb27941ed89ce
# Dataset: plantgrowth (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
from scipy import stats
import codesplash as cs
from codesplash.stats import describe as csd
from codesplash.stats import normality as csn
# %% Data
df = pd.read_parquet("tests/parity/fixtures/plantgrowth.parquet", columns=["weight", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["ctrl", "trt1", "trt2"]) # stored level order
df = df.dropna(subset=["weight", "group"]) # listwise deletion over the analysis columns
df["group"] = df["group"].cat.remove_unused_categories()
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, ["weight", "group"]) # infinite values stop the run (registry/errors.yaml)
# %% Tests
y = "weight"
g = "group"
parts = [(str(lv), df.loc[df[g] == lv, y].to_numpy(dtype=float)) for lv in df[g].cat.categories]
if len(df) >= 2 and len(np.unique(df[y].to_numpy(dtype=float))) < 2: # no variation: every test and shape measure is undefined
cs.cs_error("CS_E_CONSTANT", column=y)
alpha = 0.05
nan = float("nan")
def verdict(n, sw_p, m, flat=False):
"""n-dependent rule (Kim 2013): tests for small n, standardized shape for moderate n, shape
magnitudes for large n (where any test rejects trivial departures)."""
if n < 8:
return False, "too few values to judge"
if flat: # every value the same: the tests and shape measures are undefined
return False, "no variation to judge"
if n < 50:
bad = np.isfinite(sw_p) and sw_p < alpha
return bool(bad), "departs from normality (Shapiro–Wilk)" if bad else "no evidence against normality"
if n < 300:
bad = abs(m["skewness_z"]) > 3.29 or abs(m["kurtosis_z"]) > 3.29
return bool(bad), "departs from normality (|z| of skewness or kurtosis > 3.29)" if bad else "approximately normal in shape"
bad = abs(m["skewness"]) > 2 or m["kurtosis"] > 4
return bool(bad), "substantially non-normal (|G1| > 2 or G2 > 4)" if bad else "approximately normal in shape (large n: judged by magnitude)"
# Each test: (statistic key, p key) in the published values.
KEYS = {"shapiro_wilk": ("sw_w", "sw_p"), "shapiro_francia": ("sf_w", "sf_p"), "filliben": ("ppcc_r", "ppcc_p"),
"anderson_darling": ("ad_a", "ad_p"), "lilliefors": ("lillie_d", "lillie_p"), "cramer_von_mises": ("cvm_w2", "cvm_p"),
"dagostino_pearson": ("k2", "k2_p"), "jarque_bera": ("jb", "jb_p"), "skewness": ("skew_z", "skew_p"),
"kurtosis": ("kurt_z", "kurt_p"), "pearson_chisq": ("chisq", "chisq_p")}
seed, reps = 42, int(1999) # Filliben's p: normal samples from the shared Wichmann–Hill stream
rows, tests, values = [], [], {"n_total": len(df)}
for level, x in parts:
x = x[~np.isnan(x)]
n = x.size
part = {"n": n}
n_tests = n_reject = 0
for name in csn.TESTS:
r = csn.normality_test(x, name, seed=seed, reps=reps)
sk, pk = KEYS[name]
part[sk], part[pk] = r["statistic"], r["p"]
if name == "pearson_chisq":
part["chisq_df"] = r["df"] if r["df"] else nan
tested = np.isfinite(r["p"])
n_tests += int(tested)
n_reject += int(tested and r["p"] < alpha)
tests.append({"group": level, "test": r["label"], "statistic": r["statistic"], "p": r["p"],
"reject": ("yes" if r["p"] < alpha else "no") if tested else "not computed"})
m = csd.moments(x)
bad, text = verdict(n, part["sw_p"], m, flat=bool(n) and np.ptp(x) == 0)
part.update({"n_tests": n_tests, "n_reject": n_reject, "skewness": m["skewness"], "skewness_z": m["skewness_z"],
"kurtosis": m["kurtosis"], "kurtosis_z": m["kurtosis_z"], "depart": bad, "verdict": text})
values.update({f"{k}[{level}]": v for k, v in part.items()})
rows.append({"group": level, **part})
# %% Result
departing = [r for r in rows if r["depart"]]
values.update({"n_parts": len(rows), "n_departing": len(departing), "lead": rows[0]["group"]})
group_col = [{"key": "group", "label": g, "type": "string"}] if g else []
charts = [
cs.chart(f"qq-{i}", "qq", f"Normal Q–Q: {y}" + (f" ({level})" if g else ""),
{"x": cs.col(y, x[np.unique(np.round(np.linspace(0, x.size - 1, min(x.size, 5000))).astype(int))])})
for i, (level, x) in enumerate(parts[:6]) if x.size >= 3
]
cs.publish({
"method": "normality.battery",
"methodVersion": "1.1.1",
"title": "Normality tests",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": len(df),
"summary": (f"{rows[0]['n_reject']} of {rows[0]['n_tests']} tests reject normality at α = .05 for {y}; by the n-dependent rule it {'departs' if rows[0]['depart'] else 'does not depart'} from normality."
if not g else f"{len(departing)} of {len(rows)} groups of {y} depart from normality by the n-dependent rule.")
+ (" With n ≥ 300 every test rejects trivial departures — read the shape, not the p-values." if any(r["n"] >= 300 for r in rows) else ""),
"statistics": [{"key": "n_reject", "label": "Tests rejecting", "value": rows[0]["n_reject"]}, {"key": "n_tests", "label": "Tests run", "value": rows[0]["n_tests"]},
{"key": "n_departing", "label": "Departing", "value": len(departing)}, {"key": "n_parts", "label": "Groups", "value": len(rows)}],
"tables": [
{"key": "tests", "title": "Normality tests", "columns": group_col + [
{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "reject", "label": "Rejects at .05", "type": "string"}],
"rows": [{k: v for k, v in t.items() if g or k != "group"} for t in tests]},
{"key": "shape", "title": "Shape and verdict", "columns": group_col + [
{"key": "n", "label": "n", "type": "integer"}, {"key": "n_reject", "label": "Tests rejecting", "type": "integer"},
{"key": "skewness", "label": "Skewness (G1)", "type": "number"},
{"key": "skewness_z", "label": "z", "type": "number"}, {"key": "kurtosis", "label": "Excess kurtosis (G2)", "type": "number"},
{"key": "kurtosis_z", "label": "z", "type": "number"}, {"key": "verdict", "label": "Verdict", "type": "string"}],
"rows": [{k: r[k] for k in ("group", "n", "n_reject", "skewness", "skewness_z", "kurtosis", "kurtosis_z", "verdict") if g or k != "group"} for r in rows]},
],
"effectSizes": [],
"assumptions": [],
"warnings": warnings,
"notes": [
"Verdict: n < 50 → Shapiro–Wilk at α = .05; 50–299 → |z| of skewness or kurtosis > 3.29; n ≥ 300 → |G1| > 2 or excess kurtosis > 4 (Kim 2013). "
"With large samples every test rejects trivial departures, so the magnitudes decide.",
"All eleven tests estimate the mean and SD (composite null). Shapiro–Wilk needs 3–5,000 values, Shapiro–Francia 5–5,000, "
"Anderson–Darling, Cramér–von Mises, Pearson χ² and the D'Agostino tests at least 8, Lilliefors at least 5.",
f"Filliben's p compares r with {reps} normal samples of the same size (seed {seed}); the tests overlap, so "
"'k of 11 reject' is a summary of agreement, not a combined test.",
],
"charts": charts,
"values": values,
})
So when you compare the app with a library you call yourself, a difference may be real and still innocent. The plate for a method lists its references and known differences. Read those before deciding anyone is wrong.
Check your understanding
CheckpointCheck yourself
Put these checks in the order to try them.
Show the answer
The order:
- Same rows and dataset version
- Same handling of missing values
- Same test variant and options
- Same algorithm, tolerance or seed
- Suspect a bug
Each step is cheaper and likelier to find the cause than the next. Most disagreements end at the first three.
Check yourself
Two t tests give the same t statistic with different degrees of freedom. What's the likely cause?
Show the answer
Answer: b
With equal group sizes, the statistics match and only the degrees of freedom differ. Different data would change the statistic too.
Check yourself
A mixed model's coefficients agree between engines to five decimals but not ten. How should you read that?
Show the answer
Answer: a
Iterative optimizers stop when they're close enough, so they agree up to their stopping rule. That's what a P1 tier states.
Reconcile something real
ReflectFind a number in a past report that you could reproduce today in another tool. Try it. If it matches, you've gained real confidence. If it doesn't, which step of the checklist explains it?
Recap
Recap- Check in the order: data, missing values, options, algorithm, and only then a bug.
- A signature often tells you the cause: same statistic with different df means a different variant.
- Tolerances and known differences say what's expected; Python ≠ R says what isn't.
Concepts in this lesson