Skip to content

BMultivariate · multivariate.distribution_test

Multivariate tests of equal distributions (energy, MMD, DISCO, classifier)

Do the groups come from the same multivariate distribution — in location, spread or shape?

Distribution-free tests that compare whole multivariate distributions, not only means: the energy test (Székely & Rizzo), the maximum mean discrepancy with a Gaussian kernel (two groups) and DISCO, an ANOVA of distance components, and the classifier two-sample test (a classifier fitted on half the rows tries to tell two groups apart on the other half). Each p-value permutes the group labels. Standardize variables measured in different units.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called classifier two-sample test, C2ST, held-out classifier test…

A real result

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

Energy test of equal distributionsRecorded · Python and R agreeRecorded 2026-11-21 · 14 values compared
R

Energy test of equal distributions, E = 9.64, p = .005

E
9.642
p
.005

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.

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
  • Euclidean distances of the variables; p from 199 label permutations on the shared seeded stream (seed 42).
Python

Energy test of equal distributions, E = 9.64, p = .005

E
9.642
p
.005

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
  • Euclidean distances of the variables; p from 199 label permutations on the shared seeded stream (seed 42).

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

Worked examples in the app

  • Guide energymv_guide · group: group · variables: y1, y2, y3
  • Guide mmd fixedmv_guide · group: group · variables: y1, y2, y3
  • Guide mmd medianmv_guide · group: group · variables: y1, y2, y3
  • Guide discomv_guide · group: group · variables: y1, y2, y3
  • Iris energy standardizediris · group: Species · variables: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width
  • Iris disco alpha2iris · group: Species · variables: Sepal.Length, Sepal.Width
  • C2st logisticmv_guide · group: group · variables: y1, y2, y3
  • C2st knn sharemv_guide · group: group · variables: y1, y2, y3

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • More than two independent groups: one-way ANOVA, Kruskal–Wallis · Statistics Guide · B — Compare groups
  • Factorial designs, covariates, multivariate (ANCOVA, MANOVA) · Statistics Guide · B — Compare groups

What you need

Variablesnumeric · 1–100 columns
The numeric variables whose joint distribution is compared.
Groupscategorical / boolean · 1 column · 2–30 levels
The groups to compare (MMD needs exactly two).

Choices you make

hypothesis

Testdefault energy

Which test to run; decide before looking at the data.

  • Energy test(default) — Sum over pairs of groups of n₁n₂/(n₁+n₂) × energy distance (Székely & Rizzo 2004); any number of groups.
  • Maximum mean discrepancy (MMD) — Unbiased MMD² with a Gaussian kernel (Gretton et al. 2012); exactly two groups.
  • DISCO — F ratio of between to within distance components (Rizzo & Székely 2010); exponent 2 is ordinary ANOVA of the squared distances.
  • Classifier two-sample test — Fit a classifier on half the rows; AUC on the other half above 0.5 means the two groups differ (Lopez-Paz & Oquab 2017).
Permutationsdefault 999

Label permutations; the smallest possible p is 1/(B + 1).

Significance leveldefault 0.05

Level used in the narrative.

options

Transform firstdefault none

A transform of the variables before the Euclidean distances.

  • None(default) — Use the values as they are.
  • Standardize (z-scores) — Each variable to mean 0 and SD 1 — recommended when units differ.
  • Scale to 0–1 — Each variable to its range.
Kernel bandwidthdefault median

The Gaussian kernel's width; it decides which differences MMD is most sensitive to.

  • Median heuristic(default) — σ = median pairwise distance of the pooled sample (Gretton et al. 2012).
  • Fixed σ — Use the σ you enter (state it before testing).
σdefault 1

Kernel bandwidth: k(x, y) = exp(−‖x − y‖² / (2σ²)).

Distance exponent αdefault 1

DISCO uses ‖x − y‖^α; 0 < α < 2 tests equal distributions, α = 2 only equal means.

Classifierdefault logistic

The classifier that tries to tell the groups apart.

  • Logistic regression(default) — Ridge-penalized (C = 1) on standardized variables; finds differences in means and linear combinations.
  • Nearest neighbors — Share of the other group among the k nearest rows; finds differences of any shape, needs more rows.
Share of rows held outdefault 0.5

Rows of each group kept aside to test the classifier; the rest fit it.

Neighbors kdefault 10

How many of the nearest fitting rows vote on each held-out row.

Checks and remedies

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

  • Exchangeable rows

    Rows must be independent; under the null the labels are exchangeable.

  • Comparable scales

    Euclidean distances on raw values let variables with large units dominate.

What it reports

  • Tests: Equal multivariate distributions
test
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
statistic
One test of "every component null holds" from several independent tests' p-values.
p
How surprising your data would be if the null hypothesis were true, as a probability.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
n
How many independent units the analysis used; it sets precision and power.
n_perm
How many independent units the analysis used; it sets precision and power.
sigma
The distance between two distributions' average kernel embeddings; zero when they are equal.
between
Twice the mean distance between samples minus the mean distances within each; zero only when the distributions are equal.
within
Twice the mean distance between samples minus the mean distances within each; zero only when the distributions are equal.
total
Each site's outcome depends on its neighbors' outcomes through ρ, so a change at one site spills over to others.
df1
How much independent information is left to estimate variability after fitting the model.
df2
How much independent information is left to estimate variability after fitting the model.
exponent
Twice the mean distance between samples minus the mean distances within each; zero only when the distributions are equal.
missing_share
Values that were not recorded; how they went missing decides which fixes are safe.

Per group, level or term: classifier, c2st_accuracy, baseline_accuracy, n_train, n_test (classifier two-sample test only)

Python and R

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

Default traps between the two languages

  • Both engines use the codesplash twins with the shared Wichmann–Hill permutations, so statistics and p-values match; energy::eqdist.etest and energy::disco give the same statistics (their permutation p-values use R's RNG).
Python

The exact script CodeSplash ran for example “Guide energy” · 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 11849a38125e4522
# 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 = "energy"  # 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 []),
})
R

The exact script CodeSplash ran for example “Guide energy” · 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 11849a38125e4522
# 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 <- "energy"  # 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())
))

Sources

  • Székely, G. J., & Rizzo, M. L. (2004). Testing for equal distributions in high dimension. InterStat, 5.
  • Gretton, A., Borgwardt, K. M., Rasch, M. J., Schölkopf, B., & Smola, A. (2012). A kernel two-sample test. Journal of Machine Learning Research, 13, 723–773.
  • Rizzo, M. L., & Székely, G. J. (2010). DISCO analysis: a nonparametric extension of analysis of variance. Annals of Applied Statistics, 4, 1034–1055.
  • Lopez-Paz, D., & Oquab, M. (2017). Revisiting classifier two-sample tests. International Conference on Learning Representations.
  • Friedman, J. H. (2004). On multivariate goodness-of-fit and two-sample testing. SLAC-PUB-10325.

From the CodeSplash method registry · multivariate.distribution_test v1.1.0.