Skip to content

A classifier, a kernel and sign flips: tests with fewer assumptions

Three tests that trade formulas for simulation. Ask a classifier whether two groups can be told apart on new rows, measure a model's fit with the kernel Stein discrepancy, and get a paired p-value from sign flips.

Advanced ~15 min6 steps

What runs in CodeSplash

You will be able to

  • Run and read the classifier two-sample test, and say why the held-out half matters
  • Test the fit of a normal, lognormal or gamma model with the kernel Stein discrepancy
  • Explain what a sign-flip p-value assumes and when it is exact

Read first

01

Can a model tell the groups apart?

Read

The energy and MMD tests compare two groups through distances. The classifier two-sample testClassifier two-sample testIf a classifier can tell new rows from training rows, the data has shifted; its AUC measures by how much. asks a more practical question: if I trained a model to tell the groups apart, would it work on rows it hasn't seen? If the groups come from the same distribution, no model can, and its held-out AUC sits near 0.5.

The test splits each group's rows, fits a classifier on one part, scores the other part and permutes the held-out labels with the classifier fixed. Because the labels of new rows are exchangeable under the null, the p-value is exact for any classifier.

02

A classifier test on simulated groups

Read
Classifier two-sample test (held-out AUC)Recorded · Python and R agreeRecorded 2026-11-21 · 19 values compared
R

Classifier two-sample test (held-out AUC), AUC = 0.72, p = .015

AUC
0.7240
p
.015

Plots

Principal coordinates of the rows by groupDo the groups separate in the dissimilarity space, and do they differ in where they sit or in how spread out they are?
View data
groupPCoA 1 (42.4%)PCoA 2 (32.5%)
g11.880−0.0590
g1−1.6120.8910
g11.8520.2849
g11.1820.9049
g10.65580.7322
g1−1.7232.557
g1−0.35371.066
g10.87331.373
g1−1.190−0.0974
g1−1.994−0.0357
g12.3631.065
g1−0.91710.3980
g11.1050.4423
g1−0.87310.2165
g11.6093.095
g10.7412−0.9501
g11.794−0.2277
g11.2020.0360
g10.81361.379
g10.6387−0.6940
g1−0.69970.1242
g10.44240.5991
g10.28181.578
g11.449−0.7876
g10.5212−0.4453
g10.2217−1.750
g12.778−1.161
g1−1.653−0.0826
g11.813−0.1413
g11.168−0.9665
g10.91671.327
g11.1300.4960
g1−0.41980.8517
g10.3646−0.3902
g10.48880.4014
g11.132−0.9397
g1−0.82840.1889
g1−1.2680.8131
g1−1.258−1.108
g10.39731.515
g20.3005−1.929
g22.515−1.324
g2−0.27580.0576
g20.8521−0.7303
g2−0.25711.649
g2−1.075−0.8621
g21.3360.2787
g20.19760.4148
g2−1.410−0.4676
g2−0.5506−1.262
g20.4851−0.0900
g2−0.9148−2.405
g2−0.6339−0.7328
g2−1.1240.1816
g20.1908−0.2489
g2−1.143−0.1104
g20.49091.963
g2−0.9839−0.6186
g2−0.5787−1.013
g2−1.271−1.232

First 60 of 90 rows.

Held-out AUC when the test half's labels are shuffledHow unusual is the observed statistic if the null hypothesis were true?
View data
DensityObservedAUC
0.36410.72400.2069
00.72400.2207
00.72400.2345
00.72400.2483
00.72400.2621
0.36410.72400.2759
0.36410.72400.2897
0.36410.72400.3035
0.72830.72400.3173
0.72830.72400.3311
0.36410.72400.3449
1.0920.72400.3587
2.1850.72400.3725
4.3700.72400.3863
2.1850.72400.4001
3.2770.72400.4139
2.5490.72400.4277
4.3700.72400.4415
1.8210.72400.4553
1.4570.72400.4691
3.2770.72400.4829
2.9130.72400.4967
6.9190.72400.5105
4.7340.72400.5243
5.4620.72400.5381
2.5490.72400.5519
4.3700.72400.5657
3.6410.72400.5795
2.1850.72400.5933
1.4570.72400.6071
2.1850.72400.6209
1.8210.72400.6347
0.72830.72400.6485
1.4570.72400.6623
00.72400.6761
0.36410.72400.6899
0.72830.72400.7037
0.36410.72400.7175
00.72400.7313
0.72830.72400.7451

Assumptions

  • Exchangeable rows — Under the null the group labels are exchangeable; rows must be independent.
  • Comparable scales — Distances use the raw values, so variables with large units dominate; standardize when units differ.

Groups

groupn
g140
g250
  • Rows split by group on the shared seeded stream (seed 42): 45 to fit, 45 to test; variables standardized with the fitting half. p: the test half's labels permuted 199 times with the classifier fixed (one-sided: AUC above chance).
The exact R script · R R version 4.5.1 (2025-06-13)
# Multivariate tests of equal distributions (energy, MMD, DISCO, classifier)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.distribution_test 1.1.0 · spec c753b66079ec0ef6
# Dataset: mv_guide (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/mv_guide.parquet", col_select = c("y1", "y2", "y3", "group")))
n_input <- nrow(df)
df[["group"]] <- factor(df[["group"]], levels = c("g1", "g2"))  # stored level order
df <- df[stats::complete.cases(df[c("y1", "y2", "y3", "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("y1", "y2", "y3", "group"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Do the groups come from the same multivariate distribution? Energy distance (Szekely & Rizzo 2004),
# maximum mean discrepancy with a Gaussian kernel (Gretton et al. 2012) or DISCO (Rizzo & Szekely 2010)
# on Euclidean distances, each with a label-permutation p from the shared Wichmann-Hill stream.
variables <- c("y1", "y2", "y3")
g <- "group"
test <- "c2st"  # energy | mmd | disco | c2st
transform_kind <- "none"
seed <- 42
n_perm <- as.integer(199)
alpha <- 0.05
levels_g <- levels(df[[g]])
codes <- as.integer(df[[g]]) - 1L
k <- length(levels_g)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
if (test == "mmd" && k != 2) stop(sprintf("The MMD test compares exactly two groups; %s has %d. Use the energy test or DISCO for more.", g, k))
if (test == "c2st" && k != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = k)
Y <- cs_mvd_transform(as.matrix(df[variables]), transform_kind)
n <- nrow(Y)
if (n > 5000) stop(sprintf("These tests use an n × n distance matrix; %d rows is too many (at most 5000).", n))
D <- cs_mvd_distance(Y, "euclidean")
group_n <- tabulate(codes + 1L, nbins = k)
extra <- list()
if (test == "energy") {
  res <- cs_mvd_energy_test(D, codes, k, n_perm, seed)
  stat <- res$statistic
  symbol <- "E"
  label <- "Energy test of equal distributions"
} else if (test == "c2st") {
  # Classifier two-sample test (Stage 12.7): fit on one half, score the other, AUC against a label permutation null.
  if (min(group_n) < 4) cs_error("CS_E_TOO_FEW_ROWS", what = "Each group in the classifier two-sample test", min = 4, n = min(group_n))
  classifier <- "logistic"  # logistic | knn
  res <- cs_c2st(Y, codes, classifier, 0.5, as.integer(10), n_perm, seed)
  stat <- res$auc
  symbol <- "AUC"
  label <- "Classifier two-sample test (held-out AUC)"
  extra <- list(classifier = classifier, c2st_accuracy = res$accuracy, baseline_accuracy = res$baseline, n_train = res$n_train, n_test = res$n_test)
} else if (test == "mmd") {
  sigma <- cs_mvd_mmd_bandwidth(D, "median", 1)
  res <- cs_mvd_mmd_test(D, codes, sigma, n_perm, seed)
  stat <- res$statistic
  symbol <- "MMD²ᵤ"
  label <- "Maximum mean discrepancy test"
  extra <- list(sigma = sigma)
} else {
  exponent <- 1
  res <- cs_mvd_disco(D, codes, k, exponent, n_perm, seed)
  stat <- res$f
  symbol <- "F"
  label <- "DISCO (distance components)"
  extra <- list(between = res$between, within = res$within, total = res$total, df1 = res$df1, df2 = res$df2, exponent = exponent)
}
p <- res$p

# %% Assumptions
scaled <- transform_kind %in% c("standardize", "range")
assumptions <- list(
  list(key = "exchangeable", label = "Exchangeable rows", status = "info",
       detail = "Under the null the group labels are exchangeable; rows must be independent."),
  list(key = "scaling", label = "Comparable scales", status = if (scaled || length(variables) == 1) "pass" else "info",
       detail = if (scaled) paste0("Variables were ", if (transform_kind == "standardize") "standardized" else "range-scaled", " before the distances.") else
         "Distances use the raw values, so variables with large units dominate; standardize when units differ.")
)

# %% Result
what <- if (p < alpha) "differ in distribution (location, spread or shape)" else "show no evidence of differing in distribution"
summary <- sprintf("%s on %s: the %d groups of %s %s (%s = %s, %s, %d permutations).", label, paste(variables, collapse = ", "), k, g, what,
                   symbol, format(signif(stat, 4)), cs_fmt_p(p), n_perm)
if (test == "mmd") summary <- paste(summary, sprintf("Gaussian kernel bandwidth σ = %s.", format(signif(extra$sigma, 4))))
if (test == "c2st") summary <- paste(summary, sprintf("A %s fitted on %d rows told the groups apart on %d new rows with AUC %.3f (0.5 = no better than chance) and accuracy %.1f%% (always guessing the larger group: %.1f%%).",
  if (extra$classifier == "logistic") "logistic regression" else "nearest-neighbor classifier", as.integer(extra$n_train), as.integer(extra$n_test), stat,
  100 * extra$c2st_accuracy, 100 * extra$baseline_accuracy))
values <- list(test = test, statistic = stat, p = p, k = k, n = n, n_perm = n_perm, sigma = NULL, between = NULL, within = NULL,
               total = NULL, df1 = NULL, df2 = NULL, exponent = NULL)
for (key in names(extra)) values[[key]] <- extra[[key]]
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0
tables <- list(list(key = "groups", title = "Groups",
                    columns = list(list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer")),
                    rows = data.frame(group = levels_g, n = as.integer(group_n))))
if (test == "disco") {
  tables <- c(list(list(key = "components", title = sprintf("Distance components (exponent %s)", format(extra$exponent)),
    columns = list(list(key = "source", label = "Source", type = "string"), list(key = "df", label = "df", type = "integer"),
                   list(key = "dist", label = "Sum of distances", type = "number"), list(key = "mean", label = "Mean", type = "number"),
                   list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue")),
    rows = list(list(source = g, df = extra$df1, dist = extra$between, mean = extra$between / extra$df1, f = stat, p = p),
                list(source = "Within", df = extra$df2, dist = extra$within, mean = extra$within / extra$df2, f = NULL, p = NULL),
                list(source = "Total", df = n - 1, dist = extra$total, mean = NULL, f = NULL, p = NULL)))), tables)
}
pc <- cs_mvd_pcoa(D)
V <- pc$vectors
ex <- pc$explained
ax1 <- if (ncol(V) > 0) V[, 1] else rep(0, n)
ax2 <- if (ncol(V) > 1) V[, 2] else rep(0, n)
cs_publish(list(
  method = "multivariate.distribution_test",
  methodVersion = "1.1.0",
  title = label,
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("%s, %s = %s, %s", label, symbol, cs_fmt_num(stat), cs_fmt_p(p)),
  statistics = list(list(key = "statistic", label = symbol, value = stat), list(key = "p", label = "p", value = p, format = "p")),
  tables = tables,
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(if (test != "c2st") sprintf("Euclidean distances of the %svariables; p from %d label permutations on the shared seeded stream (seed %d).",
                       if (transform_kind == "standardize") "standardized " else "", n_perm, as.integer(seed)) else
               sprintf("Rows split by group on the shared seeded stream (seed %d): %d to fit, %d to test; variables standardized with the fitting half. p: the test half's labels permuted %d times with the classifier fixed (one-sided: AUC above chance).",
                       as.integer(seed), as.integer(extra$n_train), as.integer(extra$n_test), n_perm)),
  values = values,
  charts = c(list(cs_chart("ordination", "pcoa-centroids", sprintf("Principal coordinates of the rows by %s", g), list(
    x = cs_col(if (ncol(V) > 0) sprintf("PCoA 1 (%.1f%%)", 100 * ex[1]) else "PCoA 1", ax1),
    y = cs_col(if (ncol(V) > 1) sprintf("PCoA 2 (%.1f%%)", 100 * ex[2]) else "PCoA 2", ax2),
    group = cs_col(g, as.character(df[[g]]), levels = levels_g)), controls = list(center = "centroid", spokes = FALSE, hulls = TRUE))),
    if (test == "c2st") {
      nc <- cs_signflip_null_curve(res$null)
      list(cs_chart("null", "null-distribution", "Held-out AUC when the test half's labels are shuffled", list(
        x = cs_col("AUC", nc$x), density = cs_col("Density", nc$density), observed = cs_col("Observed", rep(stat, length(nc$x)))),
        controls = list(alternative = "greater")))
    } else list())
))
Python

Classifier two-sample test (held-out AUC), AUC = 0.72, p = .015

AUC
0.7240
p
.015

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Exchangeable rows — Under the null the group labels are exchangeable; rows must be independent.
  • Comparable scales — Distances use the raw values, so variables with large units dominate; standardize when units differ.

Groups

groupn
g140
g250
  • Rows split by group on the shared seeded stream (seed 42): 45 to fit, 45 to test; variables standardized with the fitting half. p: the test half's labels permuted 199 times with the classifier fixed (one-sided: AUC above chance).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multivariate tests of equal distributions (energy, MMD, DISCO, classifier)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method multivariate.distribution_test 1.1.0 · spec c753b66079ec0ef6
# Dataset: mv_guide (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.stats import mvdist

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mv_guide.parquet", columns=["y1", "y2", "y3", "group"])
n_input = len(df)
df["group"] = pd.Categorical(df["group"], categories=["g1", "g2"])  # stored level order
df = df.dropna(subset=["y1", "y2", "y3", "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, ["y1", "y2", "y3", "group"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Do the groups come from the same multivariate distribution? Energy distance (Székely & Rizzo 2004),
# maximum mean discrepancy with a Gaussian kernel (Gretton et al. 2012) or DISCO (Rizzo & Székely 2010)
# on Euclidean distances, each with a label-permutation p from the shared Wichmann–Hill stream.
variables = ["y1", "y2", "y3"]
g = "group"
test = "c2st"  # energy | mmd | disco | c2st
transform_kind = "none"
seed = 42
n_perm = int(199)
alpha = 0.05
levels = [str(lv) for lv in df[g].cat.categories]
codes = df[g].cat.codes.to_numpy().astype(int)
k = len(levels)
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
if test == "mmd" and k != 2:
    raise ValueError(f"The MMD test compares exactly two groups; {g} has {k}. Use the energy test or DISCO for more.")
if test == "c2st" and k != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=k)
Y = mvdist.transform(df[variables].to_numpy(dtype=float), transform_kind)
n = int(Y.shape[0])
if n > 5000:
    raise ValueError(f"These tests use an n × n distance matrix; {n} rows is too many (at most 5000).")
D = mvdist.distance(Y, "euclidean")
group_n = np.bincount(codes, minlength=k)
if test == "energy":
    res = mvdist.energy_test(D, codes, k, n_perm, seed)
    stat, symbol, label = res["statistic"], "E", "Energy test of equal distributions"
    extra = {}
elif test == "c2st":
    # Classifier two-sample test (Stage 12.7): fit on one half, score the other, AUC against a label permutation null.
    from codesplash.stats import c2st as c2
    if int(group_n.min()) < 4:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what="Each group in the classifier two-sample test", min=4, n=int(group_n.min()))
    classifier = "logistic"  # logistic | knn
    res = c2.c2st(Y, codes, classifier, 0.5, int(10), n_perm, seed)
    stat, symbol, label = res["auc"], "AUC", "Classifier two-sample test (held-out AUC)"
    extra = {"classifier": classifier, "c2st_accuracy": res["accuracy"], "baseline_accuracy": res["baseline"],
             "n_train": res["n_train"], "n_test": res["n_test"]}
elif test == "mmd":
    sigma = mvdist.mmd_bandwidth(D, "median", 1)
    res = mvdist.mmd_test(D, codes, sigma, n_perm, seed)
    stat, symbol, label = res["statistic"], "MMD²ᵤ", "Maximum mean discrepancy test"
    extra = {"sigma": sigma}
else:
    exponent = 1
    res = mvdist.disco(D, codes, k, exponent, n_perm, seed)
    stat, symbol, label = res["f"], "F", "DISCO (distance components)"
    extra = {"between": res["between"], "within": res["within"], "total": res["total"], "df1": res["df1"], "df2": res["df2"], "exponent": exponent}
p = res["p"]

# %% Assumptions
assumptions = [
    {"key": "exchangeable", "label": "Exchangeable rows", "status": "info",
     "detail": "Under the null the group labels are exchangeable; rows must be independent."},
    {"key": "scaling", "label": "Comparable scales", "status": "pass" if transform_kind in ("standardize", "range") or len(variables) == 1 else "info",
     "detail": ("Variables were " + ("standardized" if transform_kind == "standardize" else "range-scaled") + " before the distances."
                if transform_kind in ("standardize", "range") else
                "Distances use the raw values, so variables with large units dominate; standardize when units differ.")},
]

# %% Result
what = "differ in distribution (location, spread or shape)" if p < alpha else "show no evidence of differing in distribution"
summary = (f"{label} on {', '.join(variables)}: the {k} groups of {g} {what} ({symbol} = {stat:.4g}, {cs.fmt_p(p)}, {n_perm} permutations).")
if test == "mmd":
    summary += f" Gaussian kernel bandwidth σ = {extra['sigma']:.4g}."
if test == "c2st":
    summary += (f" A {'logistic regression' if extra['classifier'] == 'logistic' else 'nearest-neighbor classifier'} fitted on {extra['n_train']} rows"
                f" told the groups apart on {extra['n_test']} new rows with AUC {stat:.3f} (0.5 = no better than chance) and accuracy {extra['c2st_accuracy']:.1%}"
                f" (always guessing the larger group: {extra['baseline_accuracy']:.1%}).")
values = {"test": test, "statistic": stat, "p": p, "k": k, "n": n, "n_perm": n_perm,
          **{key: None for key in ("sigma", "between", "within", "total", "df1", "df2", "exponent")}, **extra}
values["missing_share"] = n_dropped / n_input if n_input else 0.0
tables = [{"key": "groups", "title": "Groups",
           "columns": [{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"}],
           "rows": [{"group": lv, "n": int(m)} for lv, m in zip(levels, group_n)]}]
if test == "disco":
    tables.insert(0, {"key": "components", "title": f"Distance components (exponent {extra['exponent']:g})",
                      "columns": [{"key": "source", "label": "Source", "type": "string"}, {"key": "df", "label": "df", "type": "integer"},
                                  {"key": "dist", "label": "Sum of distances", "type": "number"}, {"key": "mean", "label": "Mean", "type": "number"},
                                  {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
                      "rows": [{"source": g, "df": extra["df1"], "dist": extra["between"], "mean": extra["between"] / extra["df1"], "f": stat, "p": p},
                               {"source": "Within", "df": extra["df2"], "dist": extra["within"], "mean": extra["within"] / extra["df2"], "f": None, "p": None},
                               {"source": "Total", "df": n - 1, "dist": extra["total"], "mean": None, "f": None, "p": None}]})
pc = mvdist.pcoa(D)
V, ex = pc["vectors"], pc["explained"]
ax1 = V[:, 0] if V.shape[1] else np.zeros(n)
ax2 = V[:, 1] if V.shape[1] > 1 else np.zeros(n)
cs.publish({
    "method": "multivariate.distribution_test",
    "methodVersion": "1.1.0",
    "title": label,
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"{label}, {symbol} = {cs.fmt_num(stat)}, {cs.fmt_p(p)}",
    "statistics": [{"key": "statistic", "label": symbol, "value": stat}, {"key": "p", "label": "p", "value": p, "format": "p"}],
    "tables": tables,
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Euclidean distances of the {('standardized ' if transform_kind == 'standardize' else '')}variables; p from {n_perm} label permutations on the shared seeded stream (seed {seed})."
              if test != "c2st" else
              f"Rows split by group on the shared seeded stream (seed {seed}): {extra['n_train']} to fit, {extra['n_test']} to test; variables standardized with the fitting half. "
              f"p: the test half's labels permuted {n_perm} times with the classifier fixed (one-sided: AUC above chance)."],
    "values": values,
    "charts": [cs.chart("ordination", "pcoa-centroids", f"Principal coordinates of the rows by {g}", {
        "x": cs.col(f"PCoA 1 ({100 * ex[0]:.1f}%)" if V.shape[1] else "PCoA 1", ax1),
        "y": cs.col(f"PCoA 2 ({100 * ex[1]:.1f}%)" if V.shape[1] > 1 else "PCoA 2", ax2),
        "group": cs.col(g, df[g].astype(str).to_numpy(), levels=levels)}, controls={"center": "centroid", "spokes": False, "hulls": True})]
        + ([cs.chart("null", "null-distribution", "Held-out AUC when the test half's labels are shuffled", {
            "x": cs.col("AUC", c2.null_curve(res["null"])[0]), "density": cs.col("Density", c2.null_curve(res["null"])[1]),
            "observed": cs.col("Observed", np.full(40, stat))}, controls={"alternative": "greater"})] if test == "c2st" else []),
})

On the simulated two-group study, a ridge logistic regression fitted on 45 rows reached AUC 0.724 on the other 45 (p = 0.015).

03

How far is the data from a model?

Read

Goodness-of-fit tests usually compare distribution functions in one variable. The kernel Stein discrepancyKernel Stein discrepancy (KSD)A distance between the data and a model that needs only the model's score function, so it works for several variables at once. uses the model's score function, the slope of its log density, so it needs no normalizing constant and it tests several variables at once.

Kernel Stein discrepancy testRecorded · Python and R agreeRecorded 2026-11-21 · 9 values compared
R

n·KSD² = 0.67, p = .780

n·KSD²
0.6720
p
.780
KSD² (unbiased)
−0.0331

Plots

n·KSD² under the fitted modelHow unusual is the observed statistic if the null hypothesis were true?
View data
DensityObservedn·KSD²
0.36700.67200.3859
00.67200.4135
00.67200.4410
00.67200.4685
00.67200.4960
1.1010.67200.5236
1.1010.67200.5511
0.73400.67200.5786
1.1010.67200.6061
2.2020.67200.6337
1.4680.67200.6612
2.2020.67200.6887
1.4680.67200.7162
1.8350.67200.7437
2.5690.67200.7713
2.2020.67200.7988
2.5690.67200.8263
2.5690.67200.8538
1.8350.67200.8814
2.2020.67200.9089
1.1010.67200.9364
1.4680.67200.9639
0.73400.67200.9915
0.73400.67201.019
00.67201.047
0.36700.67201.074
0.73400.67201.102
00.67201.129
0.73400.67201.157
0.36700.67201.184
0.73400.67201.212
0.36700.67201.239
00.67201.267
00.67201.294
00.67201.322
00.67201.349
0.36700.67201.377
0.36700.67201.404
0.36700.67201.432
0.36700.67201.459

Assumptions

  • Independent rows — The test treats the rows as independent draws from one distribution.
  • Calibration accounts for fitting — Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters.

Fitted multivariate normal model (maximum likelihood)

ParameterEstimate
mean of y10.2635
mean of y20.2052
mean of y30.1372
SD of y10.9719
SD of y20.9765
SD of y31.035
  • Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = 2.201, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed 42), p = (1 + count) / (B + 1).
The exact R script · R R version 4.5.1 (2025-06-13)
# Kernel Stein discrepancy goodness-of-fit test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.ksd 1.0.0 · spec 93b70776f8a087bb
# Dataset: mv_guide (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/mv_guide.parquet", col_select = c("y1", "y2", "y3")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("y1", "y2", "y3")]), , 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("y1", "y2", "y3"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Kernel Stein discrepancy (Liu, Lee & Jordan 2016; Chwialkowski et al. 2016): how far the data are from the
# fitted model, using only its score function grad log p; IMQ kernel with the median-distance bandwidth.
variables <- c("y1", "y2", "y3")
family <- "normal"  # normal | lognormal | gamma
calibration <- "parametric"  # parametric | wild
n_boot <- as.integer(99)
alpha <- 0.05
seed <- 42  # portable Wichmann-Hill stream: Python simulates the same bootstrap data
X <- as.matrix(df[variables])
storage.mode(X) <- "double"
n <- nrow(X)
d <- ncol(X)
cs_check_rows(n, 5, "The kernel Stein discrepancy test")
for (v in variables) cs_check_not_constant(as.numeric(df[[v]]), v)
if (family != "normal" && d != 1) cs_error("CS_E_INVALID_OPTION", option = "Model", allowed = "the normal model when you test more than one variable", value = family)
if (family != "normal" && any(X <= 0)) cs_error("CS_E_INVALID_VALUES", column = variables[1], requirement = "positive (the lognormal and gamma models need values above 0)", count = sum(X <= 0))
if (n > 2000) stop(sprintf("The test builds an n × n kernel matrix for every bootstrap sample; %d rows is too many (at most 2000).", n))
res <- cs_ksd_test(X, family, calibration, n_boot, seed)
stat <- res$statistic
p <- res$p
par <- res$params

# %% Assumptions
assumptions <- list(
  list(key = "independence", label = "Independent rows", status = "info",
       detail = "The test treats the rows as independent draws from one distribution."),
  list(key = "calibration", label = "Calibration accounts for fitting", status = if (calibration == "parametric") "pass" else "warn",
       detail = if (calibration == "parametric") "Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters." else
         "The wild bootstrap holds the fitted parameters fixed; with estimated parameters its p-value is only approximate (usually too large).")
)

# %% Result
fam_label <- switch(family, normal = if (d > 1) "multivariate normal" else "normal", lognormal = "lognormal", gamma = "gamma")
extra <- list()
if (family == "normal") {
  rows <- c(lapply(seq_len(d), function(i) list(parameter = paste("mean of", variables[i]), value = par$mu[[i]])),
            lapply(seq_len(d), function(i) list(parameter = paste("SD of", variables[i]), value = sqrt(par$Sigma[i, i]))))
  if (d == 1) extra <- list(mean = par$mu[[1]], sd = sqrt(par$Sigma[1, 1]))
} else if (family == "lognormal") {
  rows <- list(list(parameter = "mean of log", value = par$meanlog), list(parameter = "SD of log", value = par$sdlog))
  extra <- list(meanlog = par$meanlog, sdlog = par$sdlog)
} else {
  rows <- list(list(parameter = "shape", value = par$shape), list(parameter = "scale", value = par$scale))
  extra <- list(shape = par$shape, scale = par$scale)
}
fits <- if (p >= alpha) "is compatible with" else "departs from"
how <- if (calibration == "parametric") sprintf("%d parametric bootstrap samples, each refitted", n_boot) else sprintf("%d wild-bootstrap sign patterns (parameters held fixed)", n_boot)
summary <- sprintf("The %s model %s the data in %s (n·KSD² = %s, %s; %s). The unbiased KSD² estimate is %s (0 = the model fits exactly).",
                   fam_label, fits, paste(variables, collapse = ", "), format(signif(stat, 4)), cs_fmt_p(p), how, format(signif(res$ksd2, 4)))
nc <- cs_signflip_null_curve(res$null)
values <- c(list(family = family, calibration = calibration, n = n, d = d, statistic = stat, ksd2 = res$ksd2, p = p,
                 n_boot = n_boot, bandwidth = res$bandwidth), extra)
cs_publish(list(
  method = "distribution.ksd",
  methodVersion = "1.0.0",
  title = "Kernel Stein discrepancy test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("n·KSD² = %s, %s", cs_fmt_num(stat), cs_fmt_p(p)),
  statistics = list(list(key = "statistic", label = "n·KSD²", value = stat), list(key = "p", label = "p", value = p, format = "p"),
                    list(key = "ksd2", label = "KSD² (unbiased)", value = res$ksd2)),
  tables = list(list(key = "fit", title = sprintf("Fitted %s model (maximum likelihood)", fam_label),
                     columns = list(list(key = "parameter", label = "Parameter", type = "string"), list(key = "value", label = "Estimate", type = "number")),
                     rows = rows)),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = %s, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed %d), p = (1 + count) / (B + 1).",
                       format(signif(res$bandwidth, 4)), as.integer(seed))),
  values = values,
  charts = list(cs_chart("null", "null-distribution", "n·KSD² under the fitted model", list(
    x = cs_col("n·KSD²", nc$x), density = cs_col("Density", nc$density), observed = cs_col("Observed", rep(stat, length(nc$x)))),
    controls = list(alternative = "greater")))
))
Python

n·KSD² = 0.67, p = .780

n·KSD²
0.6720
p
.780
KSD² (unbiased)
−0.0331

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Independent rows — The test treats the rows as independent draws from one distribution.
  • Calibration accounts for fitting — Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters.

Fitted multivariate normal model (maximum likelihood)

ParameterEstimate
mean of y10.2635
mean of y20.2052
mean of y30.1372
SD of y10.9719
SD of y20.9765
SD of y31.035
  • Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = 2.201, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed 42), p = (1 + count) / (B + 1).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kernel Stein discrepancy goodness-of-fit test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.ksd 1.0.0 · spec 93b70776f8a087bb
# Dataset: mv_guide (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, check_rows
from codesplash.stats import ksd  # twin: codesplashr cs_ksd_*
from codesplash.stats import signflip  # null_curve for the chart

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mv_guide.parquet", columns=["y1", "y2", "y3"])
n_input = len(df)
df = df.dropna(subset=["y1", "y2", "y3"])  # 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, ["y1", "y2", "y3"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Kernel Stein discrepancy (Liu, Lee & Jordan 2016; Chwialkowski et al. 2016): how far the data are from the
# fitted model, using only its score function ∇ log p; IMQ kernel with the median-distance bandwidth.
variables = ["y1", "y2", "y3"]
family = "normal"  # normal | lognormal | gamma
calibration = "parametric"  # parametric | wild
n_boot = int(99)
alpha = 0.05
seed = 42  # portable Wichmann–Hill stream: R simulates the same bootstrap data
X = df[variables].to_numpy(dtype=float)
n, d = X.shape
check_rows(n, 5, "The kernel Stein discrepancy test")
for v in variables:
    check_not_constant(df[v].to_numpy(dtype=float), v)
if family != "normal" and d != 1:
    cs.cs_error("CS_E_INVALID_OPTION", option="Model", allowed="the normal model when you test more than one variable", value=family)
if family != "normal" and np.any(X <= 0):
    cs.cs_error("CS_E_INVALID_VALUES", column=variables[0], requirement="positive (the lognormal and gamma models need values above 0)", count=int(np.sum(X <= 0)))
if n > 2000:
    raise ValueError(f"The test builds an n × n kernel matrix for every bootstrap sample; {n} rows is too many (at most 2000).")
res = ksd.ksd_test(X, family, calibration, n_boot, seed)
stat, p, par = res["statistic"], res["p"], res["params"]

# %% Assumptions
assumptions = [
    {"key": "independence", "label": "Independent rows", "status": "info",
     "detail": "The test treats the rows as independent draws from one distribution."},
    {"key": "calibration", "label": "Calibration accounts for fitting", "status": "pass" if calibration == "parametric" else "warn",
     "detail": ("Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters." if calibration == "parametric"
                else "The wild bootstrap holds the fitted parameters fixed; with estimated parameters its p-value is only approximate (usually too large).")},
]

# %% Result
fam_label = {"normal": "multivariate normal" if d > 1 else "normal", "lognormal": "lognormal", "gamma": "gamma"}[family]
if family == "normal":
    rows = ([{"parameter": f"mean of {v}", "value": float(par["mu"][i])} for i, v in enumerate(variables)]
            + [{"parameter": f"SD of {v}", "value": float(np.sqrt(par["Sigma"][i, i]))} for i, v in enumerate(variables)])
    extra = {"mean": float(par["mu"][0]), "sd": float(np.sqrt(par["Sigma"][0, 0]))} if d == 1 else {}
elif family == "lognormal":
    rows = [{"parameter": "mean of log", "value": par["meanlog"]}, {"parameter": "SD of log", "value": par["sdlog"]}]
    extra = {"meanlog": par["meanlog"], "sdlog": par["sdlog"]}
else:
    rows = [{"parameter": "shape", "value": par["shape"]}, {"parameter": "scale", "value": par["scale"]}]
    extra = {"shape": par["shape"], "scale": par["scale"]}
fits = "is compatible with" if p >= alpha else "departs from"
how = f"{n_boot} parametric bootstrap samples, each refitted" if calibration == "parametric" else f"{n_boot} wild-bootstrap sign patterns (parameters held fixed)"
summary = (f"The {fam_label} model {fits} the data in {', '.join(variables)} (n·KSD² = {stat:.4g}, {cs.fmt_p(p)}; {how}). "
           f"The unbiased KSD² estimate is {res['ksd2']:.4g} (0 = the model fits exactly).")
nx, nd = signflip.null_curve(res["null"])
cs.publish({
    "method": "distribution.ksd",
    "methodVersion": "1.0.0",
    "title": "Kernel Stein discrepancy test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"n·KSD² = {cs.fmt_num(stat)}, {cs.fmt_p(p)}",
    "statistics": [{"key": "statistic", "label": "n·KSD²", "value": stat}, {"key": "p", "label": "p", "value": p, "format": "p"},
                   {"key": "ksd2", "label": "KSD² (unbiased)", "value": res["ksd2"]}],
    "tables": [{"key": "fit", "title": f"Fitted {fam_label} model (maximum likelihood)",
                "columns": [{"key": "parameter", "label": "Parameter", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"}],
                "rows": rows}],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = {res['bandwidth']:.4g}, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); "
              f"bootstrap on the shared seeded stream (seed {seed}), p = (1 + count) / (B + 1)."],
    "values": {"family": family, "calibration": calibration, "n": n, "d": d, "statistic": stat, "ksd2": res["ksd2"], "p": p,
               "n_boot": n_boot, "bandwidth": res["bandwidth"], **extra},
    "charts": [cs.chart("null", "null-distribution", "n·KSD² under the fitted model", {
        "x": cs.col("n·KSD²", nx), "density": cs.col("Density", nd), "observed": cs.col("Observed", np.full(nx.size, stat))},
        controls={"alternative": "greater"})],
})

For three variables tested jointly against a multivariate normal, n·KSD² = 0.672 with p = 0.78. The parameters were estimated from the same data, so the p-value comes from a parametric bootstrap: samples drawn from the fitted model, each refitted. A wild bootstrap is quicker but treats the estimated parameters as known.

04

A skewed variable against a gamma model

Read
Kernel Stein discrepancy testRecorded · Python and R agreeRecorded 2026-11-21 · 11 values compared
R

n·KSD² = 3.01, p = .280

n·KSD²
3.012
p
.280
KSD² (unbiased)
−0.0061

Plots

n·KSD² under the fitted modelHow unusual is the observed statistic if the null hypothesis were true?
View data
DensityObservedn·KSD²
0.34263.0120.7934
0.22563.0122.002
0.08363.0123.211
0.06693.0124.420
0.03343.0125.628
0.03343.0126.837
03.0128.046
03.0129.255
03.01210.463
0.00843.01211.672
03.01212.881
03.01214.089
03.01215.298
0.00843.01216.507
0.00843.01217.716
03.01218.924
03.01220.133
03.01221.342
03.01222.550
03.01223.759
03.01224.968
03.01226.177
03.01227.385
03.01228.594
0.00843.01229.803
03.01231.012
03.01232.220
03.01233.429
03.01234.638
03.01235.846
03.01237.055
03.01238.264
03.01239.473
03.01240.681
03.01241.890
03.01243.099
03.01244.308
03.01245.516
03.01246.725
0.00843.01247.934

Assumptions

  • Independent rows — The test treats the rows as independent draws from one distribution.
  • Calibration accounts for fitting — Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters.

Fitted gamma model (maximum likelihood)

ParameterEstimate
shape1.699
scale24.792
  • 37 of 153 rows were left out because a value was missing.
  • Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = 1.049, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed 42), p = (1 + count) / (B + 1).
The exact R script · R R version 4.5.1 (2025-06-13)
# Kernel Stein discrepancy goodness-of-fit test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.ksd 1.0.0 · spec 046ef7244b9ef3ed
# Dataset: airquality (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/airquality.parquet", col_select = c("Ozone")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Ozone")]), , 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("Ozone"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Kernel Stein discrepancy (Liu, Lee & Jordan 2016; Chwialkowski et al. 2016): how far the data are from the
# fitted model, using only its score function grad log p; IMQ kernel with the median-distance bandwidth.
variables <- c("Ozone")
family <- "gamma"  # normal | lognormal | gamma
calibration <- "parametric"  # parametric | wild
n_boot <- as.integer(99)
alpha <- 0.05
seed <- 42  # portable Wichmann-Hill stream: Python simulates the same bootstrap data
X <- as.matrix(df[variables])
storage.mode(X) <- "double"
n <- nrow(X)
d <- ncol(X)
cs_check_rows(n, 5, "The kernel Stein discrepancy test")
for (v in variables) cs_check_not_constant(as.numeric(df[[v]]), v)
if (family != "normal" && d != 1) cs_error("CS_E_INVALID_OPTION", option = "Model", allowed = "the normal model when you test more than one variable", value = family)
if (family != "normal" && any(X <= 0)) cs_error("CS_E_INVALID_VALUES", column = variables[1], requirement = "positive (the lognormal and gamma models need values above 0)", count = sum(X <= 0))
if (n > 2000) stop(sprintf("The test builds an n × n kernel matrix for every bootstrap sample; %d rows is too many (at most 2000).", n))
res <- cs_ksd_test(X, family, calibration, n_boot, seed)
stat <- res$statistic
p <- res$p
par <- res$params

# %% Assumptions
assumptions <- list(
  list(key = "independence", label = "Independent rows", status = "info",
       detail = "The test treats the rows as independent draws from one distribution."),
  list(key = "calibration", label = "Calibration accounts for fitting", status = if (calibration == "parametric") "pass" else "warn",
       detail = if (calibration == "parametric") "Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters." else
         "The wild bootstrap holds the fitted parameters fixed; with estimated parameters its p-value is only approximate (usually too large).")
)

# %% Result
fam_label <- switch(family, normal = if (d > 1) "multivariate normal" else "normal", lognormal = "lognormal", gamma = "gamma")
extra <- list()
if (family == "normal") {
  rows <- c(lapply(seq_len(d), function(i) list(parameter = paste("mean of", variables[i]), value = par$mu[[i]])),
            lapply(seq_len(d), function(i) list(parameter = paste("SD of", variables[i]), value = sqrt(par$Sigma[i, i]))))
  if (d == 1) extra <- list(mean = par$mu[[1]], sd = sqrt(par$Sigma[1, 1]))
} else if (family == "lognormal") {
  rows <- list(list(parameter = "mean of log", value = par$meanlog), list(parameter = "SD of log", value = par$sdlog))
  extra <- list(meanlog = par$meanlog, sdlog = par$sdlog)
} else {
  rows <- list(list(parameter = "shape", value = par$shape), list(parameter = "scale", value = par$scale))
  extra <- list(shape = par$shape, scale = par$scale)
}
fits <- if (p >= alpha) "is compatible with" else "departs from"
how <- if (calibration == "parametric") sprintf("%d parametric bootstrap samples, each refitted", n_boot) else sprintf("%d wild-bootstrap sign patterns (parameters held fixed)", n_boot)
summary <- sprintf("The %s model %s the data in %s (n·KSD² = %s, %s; %s). The unbiased KSD² estimate is %s (0 = the model fits exactly).",
                   fam_label, fits, paste(variables, collapse = ", "), format(signif(stat, 4)), cs_fmt_p(p), how, format(signif(res$ksd2, 4)))
nc <- cs_signflip_null_curve(res$null)
values <- c(list(family = family, calibration = calibration, n = n, d = d, statistic = stat, ksd2 = res$ksd2, p = p,
                 n_boot = n_boot, bandwidth = res$bandwidth), extra)
cs_publish(list(
  method = "distribution.ksd",
  methodVersion = "1.0.0",
  title = "Kernel Stein discrepancy test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("n·KSD² = %s, %s", cs_fmt_num(stat), cs_fmt_p(p)),
  statistics = list(list(key = "statistic", label = "n·KSD²", value = stat), list(key = "p", label = "p", value = p, format = "p"),
                    list(key = "ksd2", label = "KSD² (unbiased)", value = res$ksd2)),
  tables = list(list(key = "fit", title = sprintf("Fitted %s model (maximum likelihood)", fam_label),
                     columns = list(list(key = "parameter", label = "Parameter", type = "string"), list(key = "value", label = "Estimate", type = "number")),
                     rows = rows)),
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = %s, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed %d), p = (1 + count) / (B + 1).",
                       format(signif(res$bandwidth, 4)), as.integer(seed))),
  values = values,
  charts = list(cs_chart("null", "null-distribution", "n·KSD² under the fitted model", list(
    x = cs_col("n·KSD²", nc$x), density = cs_col("Density", nc$density), observed = cs_col("Observed", rep(stat, length(nc$x)))),
    controls = list(alternative = "greater")))
))
Python

n·KSD² = 3.01, p = .280

n·KSD²
3.012
p
.280
KSD² (unbiased)
−0.0061

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Independent rows — The test treats the rows as independent draws from one distribution.
  • Calibration accounts for fitting — Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters.

Fitted gamma model (maximum likelihood)

ParameterEstimate
shape1.699
scale24.792
  • 37 of 153 rows were left out because a value was missing.
  • Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = 1.049, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); bootstrap on the shared seeded stream (seed 42), p = (1 + count) / (B + 1).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kernel Stein discrepancy goodness-of-fit test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method distribution.ksd 1.0.0 · spec 046ef7244b9ef3ed
# Dataset: airquality (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, check_rows
from codesplash.stats import ksd  # twin: codesplashr cs_ksd_*
from codesplash.stats import signflip  # null_curve for the chart

# %% Data
df = pd.read_parquet("tests/parity/fixtures/airquality.parquet", columns=["Ozone"])
n_input = len(df)
df = df.dropna(subset=["Ozone"])  # 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, ["Ozone"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
# Kernel Stein discrepancy (Liu, Lee & Jordan 2016; Chwialkowski et al. 2016): how far the data are from the
# fitted model, using only its score function ∇ log p; IMQ kernel with the median-distance bandwidth.
variables = ["Ozone"]
family = "gamma"  # normal | lognormal | gamma
calibration = "parametric"  # parametric | wild
n_boot = int(99)
alpha = 0.05
seed = 42  # portable Wichmann–Hill stream: R simulates the same bootstrap data
X = df[variables].to_numpy(dtype=float)
n, d = X.shape
check_rows(n, 5, "The kernel Stein discrepancy test")
for v in variables:
    check_not_constant(df[v].to_numpy(dtype=float), v)
if family != "normal" and d != 1:
    cs.cs_error("CS_E_INVALID_OPTION", option="Model", allowed="the normal model when you test more than one variable", value=family)
if family != "normal" and np.any(X <= 0):
    cs.cs_error("CS_E_INVALID_VALUES", column=variables[0], requirement="positive (the lognormal and gamma models need values above 0)", count=int(np.sum(X <= 0)))
if n > 2000:
    raise ValueError(f"The test builds an n × n kernel matrix for every bootstrap sample; {n} rows is too many (at most 2000).")
res = ksd.ksd_test(X, family, calibration, n_boot, seed)
stat, p, par = res["statistic"], res["p"], res["params"]

# %% Assumptions
assumptions = [
    {"key": "independence", "label": "Independent rows", "status": "info",
     "detail": "The test treats the rows as independent draws from one distribution."},
    {"key": "calibration", "label": "Calibration accounts for fitting", "status": "pass" if calibration == "parametric" else "warn",
     "detail": ("Each bootstrap sample is refitted, so the p-value accounts for estimating the parameters." if calibration == "parametric"
                else "The wild bootstrap holds the fitted parameters fixed; with estimated parameters its p-value is only approximate (usually too large).")},
]

# %% Result
fam_label = {"normal": "multivariate normal" if d > 1 else "normal", "lognormal": "lognormal", "gamma": "gamma"}[family]
if family == "normal":
    rows = ([{"parameter": f"mean of {v}", "value": float(par["mu"][i])} for i, v in enumerate(variables)]
            + [{"parameter": f"SD of {v}", "value": float(np.sqrt(par["Sigma"][i, i]))} for i, v in enumerate(variables)])
    extra = {"mean": float(par["mu"][0]), "sd": float(np.sqrt(par["Sigma"][0, 0]))} if d == 1 else {}
elif family == "lognormal":
    rows = [{"parameter": "mean of log", "value": par["meanlog"]}, {"parameter": "SD of log", "value": par["sdlog"]}]
    extra = {"meanlog": par["meanlog"], "sdlog": par["sdlog"]}
else:
    rows = [{"parameter": "shape", "value": par["shape"]}, {"parameter": "scale", "value": par["scale"]}]
    extra = {"shape": par["shape"], "scale": par["scale"]}
fits = "is compatible with" if p >= alpha else "departs from"
how = f"{n_boot} parametric bootstrap samples, each refitted" if calibration == "parametric" else f"{n_boot} wild-bootstrap sign patterns (parameters held fixed)"
summary = (f"The {fam_label} model {fits} the data in {', '.join(variables)} (n·KSD² = {stat:.4g}, {cs.fmt_p(p)}; {how}). "
           f"The unbiased KSD² estimate is {res['ksd2']:.4g} (0 = the model fits exactly).")
nx, nd = signflip.null_curve(res["null"])
cs.publish({
    "method": "distribution.ksd",
    "methodVersion": "1.0.0",
    "title": "Kernel Stein discrepancy test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"n·KSD² = {cs.fmt_num(stat)}, {cs.fmt_p(p)}",
    "statistics": [{"key": "statistic", "label": "n·KSD²", "value": stat}, {"key": "p", "label": "p", "value": p, "format": "p"},
                   {"key": "ksd2", "label": "KSD² (unbiased)", "value": res["ksd2"]}],
    "tables": [{"key": "fit", "title": f"Fitted {fam_label} model (maximum likelihood)",
                "columns": [{"key": "parameter", "label": "Parameter", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"}],
                "rows": rows}],
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Inverse multiquadric kernel (1 + ‖x − y‖²/h²)^(−1/2) with h = {res['bandwidth']:.4g}, the median distance between rows on the fitted model's own scale (whitened for the normal; divided by the fitted scale otherwise); "
              f"bootstrap on the shared seeded stream (seed {seed}), p = (1 + count) / (B + 1)."],
    "values": {"family": family, "calibration": calibration, "n": n, "d": d, "statistic": stat, "ksd2": res["ksd2"], "p": p,
               "n_boot": n_boot, "bandwidth": res["bandwidth"], **extra},
    "charts": [cs.chart("null", "null-distribution", "n·KSD² under the fitted model", {
        "x": cs.col("n·KSD²", nx), "density": cs.col("Density", nd), "observed": cs.col("Observed", np.full(nx.size, stat))},
        controls={"alternative": "greater"})],
})

Ozone is positive and skewed; against a gamma model with shape 1.70 the test gives p = 0.28. The method is Experimental: its numbers agree between Python and R and its Type I error is checked by simulation, but it has fewer worked examples than the classic tests.

05

A paired p-value from sign flips

Read

If before and after don't differ, each difference is as likely to be positive as negative. Flip the signs of any subset and you get another data set that was equally likely. The sign-flip testSign-flip testFlips the signs of paired differences in every possible way; exact when the differences are symmetric about zero. compares the observed sum of differences with the sums under every sign pattern.

Paired t-testRecorded · Python and R agreeRecorded 2026-11-21 · 20 values compared · largest relative difference 2.1e-12
R

t(9) = −4.06, p = .003, g_z = −1.17, 95% CI [−1.94, −0.38]

t
−4.062
df
9
p
.003
Mean difference (drug1 − drug2)
−1.580
95% CI
[−2.460, −0.7001]
Sign-flip p
.004

Effect size

  • Hedges' g_z −1.174 95% CI [−1.936, −0.3789] · large

Plots

drug1 and drug2 per rowHow did each subject change across conditions or time points?
View data
MeasurementRowValue
drug110.7000
drug12−1.600
drug13−0.2000
drug14−1.200
drug15−0.1000
drug163.400
drug173.700
drug180.8000
drug190
drug1102
drug211.900
drug220.8000
drug231.100
drug240.1000
drug25−0.1000
drug264.400
drug275.500
drug281.600
drug294.600
drug2103.400
Sum of the differences under sign flipsHow unusual is the observed statistic if the null hypothesis were true?
View data
DensityObservedΣ (difference − μ₀)
0.0025−15.800−15.405
0−15.800−14.615
0.0049−15.800−13.825
0.0099−15.800−13.035
0.0049−15.800−12.245
0.0173−15.800−11.455
0.0223−15.800−10.665
0.0173−15.800−9.875
0.0297−15.800−9.085
0.0371−15.800−8.295
0.0297−15.800−7.505
0.0470−15.800−6.715
0.0470−15.800−5.925
0.0470−15.800−5.135
0.0544−15.800−4.345
0.0494−15.800−3.555
0.0544−15.800−2.765
0.0544−15.800−1.975
0.0494−15.800−1.185
0.0544−15.800−0.3950
0.0544−15.8000.3950
0.0494−15.8001.185
0.0544−15.8001.975
0.0544−15.8002.765
0.0494−15.8003.555
0.0544−15.8004.345
0.0470−15.8005.135
0.0470−15.8005.925
0.0470−15.8006.715
0.0297−15.8007.505
0.0371−15.8008.295
0.0297−15.8009.085
0.0173−15.8009.875
0.0223−15.80010.665
0.0173−15.80011.455
0.0049−15.80012.245
0.0099−15.80013.035
0.0049−15.80013.825
0−15.80014.615
0.0025−15.80015.405

Assumptions

  • Normality of the differences — Differences: Shapiro–Wilk p = .033 with fewer than 30 pairs; consider the Wilcoxon signed-rank test.

Descriptives

MeasurementnMeanSDMedian
drug1100.75001.7890.3500
drug2102.3302.0021.750
drug1 − drug210−1.5801.230−1.300
  • Difference = drug1 − drug2; alternative: two-sided; H0 difference = 0. Correlation between the measurements r = 0.80.
  • Sign-flip p: the statistic Σ(difference − 0) against its values under every sign pattern (exact, p = share at least as extreme) or 1,024 random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about 0 under H0.
The exact R script · R R version 4.5.1 (2025-06-13)
# Paired t-test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.paired 1.3.0 · spec 0aa6fcaaab31220a
# Dataset: sleep_wide (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/sleep_wide.parquet", col_select = c("drug1", "drug2")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("drug1", "drug2")]), , 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("drug1", "drug2"))  # 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
ncp_ci <- function(t, df, conf) {
  # CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)
  solve <- function(prob) {
    # P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
    f <- function(ncp) suppressWarnings(pt(t, df, ncp)) - prob
    lo <- t - 1
    hi <- t + 1
    step <- 1
    while (f(lo) < 0) {
      lo <- lo - step
      step <- step * 2
    }
    step <- 1
    while (f(hi) > 0) {
      hi <- hi + step
      step <- step * 2
    }
    uniroot(f, c(lo, hi), tol = 1e-12)$root
  }
  alpha <- 1 - conf
  c(solve(1 - alpha / 2), solve(alpha / 2))
}

hedges_j <- function(df) {
  # Exact small-sample correction J = gamma(df/2) / (sqrt(df/2) * gamma((df - 1)/2))
  exp(lgamma(df / 2) - log(sqrt(df / 2)) - lgamma((df - 1) / 2))
}

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
a <- "drug1"
b <- "drug2"
x1 <- df[[a]]
x2 <- df[[b]]
n <- length(x1)
alternative <- "two-sided"
conf <- 0.95
mu <- 0  # hypothesized mean difference (first - second)
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A paired t-test", min = 2, n = n)
if (all(x1 == x2)) cs_error("CS_E_ALL_ZERO_DIFFERENCES")
if (length(unique(x1 - x2)) < 2) cs_error("CS_E_CONSTANT", column = sprintf("%s − %s", a, b))  # t is undefined

res <- t.test(x1, x2, paired = TRUE, mu = mu, alternative = sub("-", ".", alternative, fixed = TRUE), conf.level = conf)
t <- unname(res$statistic)
dof <- unname(res$parameter)
p <- res$p.value
diffs <- x1 - x2
mean_d <- mean(diffs)
sd_d <- sd(diffs)
ci_low <- res$conf.int[1]
ci_high <- res$conf.int[2]
# The correlation is undefined when a measurement doesn't vary: NA (published as null).
r <- if (length(unique(x1)) > 1 && length(unique(x2)) > 1) cor(x1, x2) else NA_real_

# Effect size: d_z = mean difference / SD of differences; g_z with the exact J; noncentral-t CI.
dz <- mean_d / sd_d
nc <- ncp_ci(dz * sqrt(n), n - 1, conf)
j <- hedges_j(n - 1)
gz <- dz * j
gz_low <- nc[1] / sqrt(n) * j
gz_high <- nc[2] / sqrt(n) * j

# %% Assumptions
sw <- if (n >= 3 && n <= 5000 && diff(range(diffs)) > 0) shapiro.test(diffs) else NULL
if (is.null(sw)) {
  status <- "info"
  detail <- "Shapiro–Wilk needs 3–5,000 differences that are not all equal; inspect a Q–Q plot."
} else if (sw$p.value < 0.05 && n < 30) {
  status <- "warn"
  detail <- sprintf("Differences: Shapiro–Wilk %s with fewer than 30 pairs; consider the Wilcoxon signed-rank test.", cs_fmt_p(sw$p.value))
} else if (sw$p.value < 0.05) {
  status <- "info"
  detail <- sprintf("Differences: Shapiro–Wilk %s, but with %d pairs the t-test is robust.", cs_fmt_p(sw$p.value), n)
} else {
  status <- "pass"
  detail <- sprintf("Differences: Shapiro–Wilk W = %.3f, %s.", sw$statistic, cs_fmt_p(sw$p.value))
}
assumptions <- list(list(key = "normality", label = "Normality of the differences", status = status, detail = detail))
if (n < 5) warnings <- c(warnings, "Fewer than 5 pairs; estimates are unstable.")

normality_p <- NULL
if (normality_test != "shapiro_wilk") {
  ns_ <- normality_selected(list(diffs), "Normality of the differences", n < 30)
  normality_p <- ns_$p
  assumptions <- lapply(assumptions, function(a) if (a$key == "normality") ns_$row else a)
}

# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
size <- magnitude(gz, c(0.2, 0.5, 0.8))
significance <- if (p < alpha) {
  sprintf("The change is statistically significant (%s).", cs_fmt_p(p))
} else {
  sprintf("The data are compatible with no change (%s).", cs_fmt_p(p))
}
summary <- sprintf("Across %d pairs, %s − %s averaged %.2f (SD %.2f), %s CI [%.2f, %.2f]. %s The standardized change is %s (g_z = %.2f).",
                   n, a, b, mean_d, sd_d, pct, ci_low, ci_high, significance, size, gz)

# Lens (equivalence / minimal effect / non-inferiority) on the mean difference, at alpha = 1 - confidence.
lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, mean_d, sd_d / sqrt(n), dof, NULL, NULL, 1 - conf)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))

# Optional sign-flip randomization p (Stage 12.7): exact over all 2^n sign patterns for <= 16 pairs, else
# random sign patterns from the shared Wichmann-Hill stream; needs symmetric differences, not normal ones.
perm <- NULL
if ("sign_flip" == "sign_flip") perm <- cs_signflip_test(diffs, mu, alternative, as.integer(9999), 42)
if (!is.null(perm)) {
  perm_how <- if (perm$kind == "exact") sprintf("exact over all %s sign patterns", format(perm$b, big.mark = ",")) else sprintf("%s random sign patterns", format(perm$b, big.mark = ","))
  summary <- paste(summary, sprintf("Sign-flip randomization test: %s (%s).", cs_fmt_p(perm$p), perm_how))
}
values <- list(
  t = t, df = dof, p = p, n = n, mean_diff = mean_d, sd_diff = sd_d, ci_low = ci_low, ci_high = ci_high,
  mean_1 = mean(x1), mean_2 = mean(x2), r = r,
  d_z = dz, g_z = gz, gz_ci_low = gz_low, gz_ci_high = gz_high,
  sw_p = if (is.null(sw)) NULL else sw$p.value, mu = mu
)
if (!is.null(lens)) values <- c(values, lens)
if (!is.null(normality_p)) values$normality_p <- normality_p
if (!is.null(perm)) values <- c(values, list(perm_p = perm$p, perm_kind = perm$kind, perm_b = perm$b))
nn <- length(x1)
cs_publish(list(
  method = "ttest.paired",
  methodVersion = "1.3.0",
  title = "Paired t-test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("t(%.0f) = %s, %s, g_z = %s, %s CI [%s, %s]", dof, cs_fmt_num(t), cs_fmt_p(p), cs_fmt_num(gz), pct, cs_fmt_num(gz_low), cs_fmt_num(gz_high)),
  statistics = c(list(
    list(key = "t", label = "t", value = t),
    list(key = "df", label = "df", value = dof),
    list(key = "p", label = "p", value = p, format = "p"),
    list(key = "mean_diff", label = sprintf("Mean difference (%s − %s)", a, b), value = mean_d),
    list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high))),
    if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list(),
    if (!is.null(perm)) list(list(key = "perm_p", label = "Sign-flip p", value = perm$p, format = "p")) else list()
  ),
  tables = list(list(
    key = "descriptives", title = "Descriptives",
    columns = list(list(key = "variable", label = "Measurement", 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 = "median", label = "Median", type = "number")),
    rows = data.frame(variable = c(a, b, sprintf("%s − %s", a, b)), n = n,
                      mean = c(mean(x1), mean(x2), mean_d), sd = c(sd(x1), sd(x2), sd_d),
                      median = c(median(x1), median(x2), median(diffs)))
  )),
  effectSizes = list(list(key = "g_z", label = "Hedges' g_z", value = gz, ciLow = gz_low, ciHigh = gz_high, ciLevel = conf,
                          method = "mean difference / SD of differences, exact J, noncentral-t interval", magnitude = size, ruleSet = "Cohen (1988)")),
  assumptions = assumptions,
  warnings = warnings,
  notes = c(list(sprintf("Difference = %s − %s; alternative: %s; H0 difference = %s. Correlation between the measurements r = %s.",
                         a, b, alternative, format(mu), if (is.na(r)) "undefined" else sprintf("%.2f", r))),
            if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the %.0f%% interval for the mean difference.", lens$lens_ci_low, lens$lens_ci_high, (1 - 2 * (1 - conf)) * 100)) else list(),
            if (!is.null(perm)) list(sprintf("Sign-flip p: the statistic Σ(difference − %s) against its values under every sign pattern (exact, p = share at least as extreme) or %s random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about %s under H0.", format(mu), format(perm$b, big.mark = ","), format(mu))) else list()),
  values = values,
  charts = c(list(cs_chart("pairs", "paired-lines", sprintf("%s and %s per row", a, b), list(
    subject = cs_col("Row", rep(as.character(seq_len(min(nn, 2500))), 2), "categorical"),
    condition = cs_col("Measurement", rep(c(a, b), each = min(nn, 2500)), "categorical", levels = c(a, b)),
    value = cs_col("Value", c(head(x1, 2500), head(x2, 2500)), "numeric")))),
    if (!is.null(perm)) {
      nc <- cs_signflip_null_curve(perm$null)
      list(cs_chart("null", "null-distribution", "Sum of the differences under sign flips", list(
        x = cs_col("Σ (difference − μ₀)", nc$x), density = cs_col("Density", nc$density),
        observed = cs_col("Observed", rep(perm$statistic, length(nc$x)))), controls = list(alternative = alternative)))
    } else list())
))
Python

t(9) = −4.06, p = .003, g_z = −1.17, 95% CI [−1.94, −0.38]

t
−4.062
df
9
p
.003
Mean difference (drug1 − drug2)
−1.580
95% CI
[−2.460, −0.7001]
Sign-flip p
.004

Effect size

  • Hedges' g_z −1.174 95% CI [−1.936, −0.3789] · large

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Normality of the differences — Differences: Shapiro–Wilk p = .033 with fewer than 30 pairs; consider the Wilcoxon signed-rank test.

Descriptives

MeasurementnMeanSDMedian
drug1100.75001.7890.3500
drug2102.3302.0021.750
drug1 − drug210−1.5801.230−1.300
  • Difference = drug1 − drug2; alternative: two-sided; H0 difference = 0. Correlation between the measurements r = 0.80.
  • Sign-flip p: the statistic Σ(difference − 0) against its values under every sign pattern (exact, p = share at least as extreme) or 1,024 random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about 0 under H0.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Paired t-test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.paired 1.3.0 · spec 0aa6fcaaab31220a
# Dataset: sleep_wide (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 optimize, special, stats

import codesplash as cs
from codesplash.stats import means as csm

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sleep_wide.parquet", columns=["drug1", "drug2"])
n_input = len(df)
df = df.dropna(subset=["drug1", "drug2"])  # 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, ["drug1", "drug2"])  # 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 ncp_ci(t, df, conf):
    """CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)."""

    def solve(prob):
        # P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
        f = lambda ncp: stats.nct.cdf(t, df, ncp) - prob  # noqa: E731
        lo, hi, step = t - 1.0, t + 1.0, 1.0
        while f(lo) < 0:
            lo, step = lo - step, step * 2
        step = 1.0
        while f(hi) > 0:
            hi, step = hi + step, step * 2
        return optimize.brentq(f, lo, hi, xtol=1e-12)

    alpha = 1 - conf
    return solve(1 - alpha / 2), solve(alpha / 2)


def hedges_j(df):
    """Exact small-sample correction J = Γ(df/2) / (√(df/2) · Γ((df − 1)/2))."""
    return float(np.exp(special.gammaln(df / 2) - np.log(np.sqrt(df / 2)) - special.gammaln((df - 1) / 2)))


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
a, b = "drug1", "drug2"
x1 = df[a].to_numpy(dtype=float)
x2 = df[b].to_numpy(dtype=float)
n = len(x1)
alternative = "two-sided"
conf = 0.95
mu = 0  # hypothesized mean difference (first − second)
if n < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A paired t-test", min=2, n=n)
if np.all(x1 == x2):
    cs.cs_error("CS_E_ALL_ZERO_DIFFERENCES")
if len(np.unique(x1 - x2)) < 2:  # the differences don't vary: t is undefined
    cs.cs_error("CS_E_CONSTANT", column=f"{a} − {b}")

# scipy tests mean(x1 − x2) = 0, so shift x1 by mu and shift the interval back.
res = stats.ttest_rel(x1 - mu, x2, alternative=alternative)
ci = res.confidence_interval(confidence_level=conf)
t, dof, p = float(res.statistic), float(res.df), float(res.pvalue)
diffs = x1 - x2
mean_d, sd_d = diffs.mean(), diffs.std(ddof=1)
ci_low, ci_high = float(ci.low) + mu, float(ci.high) + mu
# The correlation is undefined when a measurement doesn't vary: null, as R's cor() gives NA.
r = float(np.corrcoef(x1, x2)[0, 1]) if len(np.unique(x1)) > 1 and len(np.unique(x2)) > 1 else None

# Effect size: d_z = mean difference / SD of differences; g_z with the exact J; noncentral-t CI.
dz = mean_d / sd_d
nc_low, nc_high = ncp_ci(dz * np.sqrt(n), n - 1, conf)
j = hedges_j(n - 1)
gz, gz_low, gz_high = dz * j, nc_low / np.sqrt(n) * j, nc_high / np.sqrt(n) * j

# Lens (equivalence / minimal effect / non-inferiority) on the mean difference, at α = 1 − confidence.
lens_kind = "none"
lens = None
if lens_kind != "none":
    lens = csm.lens(lens_kind, mean_d, sd_d / np.sqrt(n), dof, None, None, 1 - conf)

# Optional sign-flip randomization p (Stage 12.7): exact over all 2ⁿ sign patterns for ≤ 16 pairs, else
# random sign patterns from the shared Wichmann–Hill stream; needs symmetric differences, not normal ones.
perm = None
if "sign_flip" == "sign_flip":
    from codesplash.stats import signflip
    perm = signflip.signflip_test(diffs, mu, alternative, int(9999), 42)

# %% Assumptions
assumptions = []
sw = stats.shapiro(diffs) if 3 <= n <= 5000 and np.ptp(diffs) > 0 else None
if sw is None:
    status, detail = "info", "Shapiro–Wilk needs 3–5,000 differences that are not all equal; inspect a Q–Q plot."
elif sw.pvalue < 0.05 and n < 30:
    status, detail = "warn", f"Differences: Shapiro–Wilk {cs.fmt_p(sw.pvalue)} with fewer than 30 pairs; consider the Wilcoxon signed-rank test."
elif sw.pvalue < 0.05:
    status, detail = "info", f"Differences: Shapiro–Wilk {cs.fmt_p(sw.pvalue)}, but with {n} pairs the t-test is robust."
else:
    status, detail = "pass", f"Differences: Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}."
assumptions.append({"key": "normality", "label": "Normality of the differences", "status": status, "detail": detail})
if n < 5:
    warnings.append("Fewer than 5 pairs; estimates are unstable.")

normality_p = None
if normality_test != "shapiro_wilk":
    _row, normality_p = normality_selected([diffs], "Normality of the differences", n < 30)
    assumptions = [_row if a["key"] == "normality" else a for a in assumptions]

# %% Result
alpha = 1 - conf
size = magnitude(gz, (0.2, 0.5, 0.8))
significance = (
    f"The change is statistically significant ({cs.fmt_p(p)})." if p < alpha
    else f"The data are compatible with no change ({cs.fmt_p(p)})."
)
summary = (
    f"Across {n} pairs, {a} − {b} averaged {mean_d:.2f} (SD {sd_d:.2f}), {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}]. "
    f"{significance} The standardized change is {size} (g_z = {gz:.2f})."
)
if lens:
    summary += f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
if perm:
    perm_how = f"exact over all {perm['b']:,} sign patterns" if perm["kind"] == "exact" else f"{perm['b']:,} random sign patterns"
    summary += f" Sign-flip randomization test: {cs.fmt_p(perm['p'])} ({perm_how})."
cs.publish({
    "method": "ttest.paired",
    "methodVersion": "1.3.0",
    "title": "Paired t-test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"t({dof:.0f}) = {cs.fmt_num(t)}, {cs.fmt_p(p)}, g_z = {cs.fmt_num(gz)}, {conf:.0%} CI [{cs.fmt_num(gz_low)}, {cs.fmt_num(gz_high)}]",
    "statistics": [
        {"key": "t", "label": "t", "value": t},
        {"key": "df", "label": "df", "value": dof},
        {"key": "p", "label": "p", "value": p, "format": "p"},
        {"key": "mean_diff", "label": f"Mean difference ({a} − {b})", "value": mean_d},
        {"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
    ] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else [])
      + ([{"key": "perm_p", "label": "Sign-flip p", "value": perm["p"], "format": "p"}] if perm else []),
    "tables": [{
        "key": "descriptives", "title": "Descriptives",
        "columns": [{"key": "variable", "label": "Measurement", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                    {"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
                    {"key": "median", "label": "Median", "type": "number"}],
        "rows": [
            {"variable": a, "n": n, "mean": float(x1.mean()), "sd": float(x1.std(ddof=1)), "median": float(np.quantile(x1, 0.5))},
            {"variable": b, "n": n, "mean": float(x2.mean()), "sd": float(x2.std(ddof=1)), "median": float(np.quantile(x2, 0.5))},
            {"variable": f"{a} − {b}", "n": n, "mean": float(mean_d), "sd": float(sd_d), "median": float(np.quantile(diffs, 0.5))},
        ],
    }],
    "effectSizes": [{"key": "g_z", "label": "Hedges' g_z", "value": gz, "ciLow": gz_low, "ciHigh": gz_high, "ciLevel": conf,
                     "method": "mean difference / SD of differences, exact J, noncentral-t interval", "magnitude": size, "ruleSet": "Cohen (1988)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Difference = {a} − {b}; alternative: {alternative}; H0 difference = {mu:g}. Correlation between the measurements r = {'undefined' if r is None else format(r, '.2f')}."]
             + ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} interval for the mean difference."] if lens else [])
             + ([f"Sign-flip p: the statistic Σ(difference − {mu:g}) against its values under every sign pattern (exact, p = share at least as extreme) or {perm['b']:,} random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about {mu:g} under H0."] if perm else []),
    "values": {
        "t": t, "df": dof, "p": p, "n": n, "mean_diff": mean_d, "sd_diff": sd_d, "ci_low": ci_low, "ci_high": ci_high,
        "mean_1": float(x1.mean()), "mean_2": float(x2.mean()), "r": r,
        "d_z": dz, "g_z": gz, "gz_ci_low": gz_low, "gz_ci_high": gz_high,
        "sw_p": None if sw is None else float(sw.pvalue), "mu": mu,
        **(lens or {}),
        **({"normality_p": normality_p} if normality_p is not None else {}),
        **({"perm_p": perm["p"], "perm_kind": perm["kind"], "perm_b": perm["b"]} if perm else {}),
    },
    "charts": [cs.chart("pairs", "paired-lines", f"{a} and {b} per row", {
        "subject": cs.col("Row", [str(i + 1) for i in range(min(n, 2500))] * 2, "categorical"),
        "condition": cs.col("Measurement", [a] * min(n, 2500) + [b] * min(n, 2500), "categorical", levels=[a, b]),
        "value": cs.col("Value", np.concatenate([x1[:2500], x2[:2500]]), "numeric")})]
        + ([cs.chart("null", "null-distribution", "Sum of the differences under sign flips", {
            "x": cs.col("Σ (difference − μ₀)", signflip.null_curve(perm["null"])[0]),
            "density": cs.col("Density", signflip.null_curve(perm["null"])[1]),
            "observed": cs.col("Observed", np.full(40, perm["statistic"]))}, controls={"alternative": alternative})] if perm else []),
})

With 10 pairs there are 1,024 sign patterns, so the test enumerates them all: p = 0.0039, beside the t-test's 0.0028. Above 16 pairs it draws random patterns instead. It needs symmetric differences, not normal ones.

06

Check yourself

Read

Check yourself

Why does the classifier two-sample test score rows the classifier wasn't fitted on?

Show the answer

Answer: b

Training accuracy measures memorization. Only new rows show whether the groups truly differ.

Check yourself

What does the kernel Stein discrepancy need from the model?

Show the answer

Answer: b

That's why it works for multivariate models whose density is known only up to a constant.

Check yourself

The model's parameters were estimated from the data. Which calibration keeps the p-value honest?

Show the answer

Answer: a

Fitting pulls the model toward the data, so a fixed-parameter null makes the fit look better than it is and the p-value too large.

Check yourself

How many sign patterns does an exact sign-flip test enumerate for 12 pairs?

Show the answer

Answer: 4096

Each pair's sign can flip or not: 212=40962^{12} = 4096.

Concepts in this lesson