Skip to content

Beyond correlation: ξ, Hoeffding's D, distance correlation and HSIC

Correlation can be zero for a perfect U shape. These tests look for any relationship at all, linear or not, including between groups of variables.

Advanced ~14 min12 steps

What runs in CodeSplash

You will be able to

  • Explain why zero correlation does not mean independence
  • Choose among ξ, Hoeffding's D, distance correlation and HSIC
  • Use the asymmetry of ξ to see which variable predicts which
  • Test dependence between sets of variables with distance covariance or cross HSIC

Read first

01

A perfect curve, zero correlation

Read

Let yy be a noisy quadratic in xx, with xx centered on zero. The relationship is obvious on a plot, yet Pearson's r = −0.028 and Spearman's ρ = −0.025.

Both are near zero because the rise on the right cancels the fall on the left. Zero correlation does not mean independence. You need a measure that is zero only when the variables are truly independent.

02

See it

Explore

CExplorable · Dependence the correlation misses

Can two variables be strongly related and still have a correlation near zero?

Pearson's r for this relationship will be about what?

0.00
How sure?

Relationship

0.10
120
0.13|Pearson|0.17|Spearman|0.69ξ0.49dCor

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Switch shapes: line, curve, circle, wave, noise. Note which coefficients react to which shapes, and which ones stay near zero while the picture shows a clear pattern.

03

Chatterjee's ξ asks whether y is a function of x

Read

Sort the rows by xx. If yy is a smooth function of xx, neighboring rows have similar ranks of yy, so the ranks jump little:

ξn=1−3∑i=1n−1∣ri+1−ri∣n2−1\xi_n = 1 - \frac{3\sum_{i=1}^{n-1} |r_{i+1} - r_i|}{n^2 - 1}

For the quadratic, ξChatterjee's ξHow much y is a function of x — 0 under independence, 1 when y is exactly determined by x, any shape.(x → y) = 0.402 with p < .001. It's the default here: fast, no tuning, and with a known null distribution.

04

ξ has a direction

Predict

Predict first

yy is a function of xx here. But given yy, there are two possible values of xx, one positive and one negative. How does ξ(y → x) compare with ξ(x → y)?

About the sameξ(y → x) is much smallerξ(y → x) is much larger
Reveal

ξ(x → y) = 0.402 and ξ(y → x) = 0.003. Knowing xx fixes yy, while knowing yy leaves xx ambiguous. ξ picks that up where symmetric measures can't.

05

Hoeffding's D

Read

Hoeffding's DHoeffding's DA rank statistic for how far the joint distribution is from what independence would give. compares the joint distribution of ranks with what independence would produce, at every point of the plane. It detects many non-monotonic shapes without any tuning.

On a noisy wave, Pearson's r is 0.327, and Hoeffding's test gives p = .005. The card also reports 30D30D, which runs from about −0.5-0.5 to 11.

06

Distance correlation and HSIC

Read

Distance correlationDistance correlationA correlation built from distances between rows; it is zero only when the variables are independent. correlates the pairwise distances within xx and within yy. It's zero if and only if the variables are independent, given finite means, and xx and yy can each be several columns. CodeSplash reports a bias-corrected form with a tt test.

HSICHSICA kernel measure of dependence between two sets of variables; zero under independence for Gaussian kernels. does the same with similarity kernels. It needs a bandwidth; the default median heuristic uses the typical distance between points. On the quadratic, p = .005 by permutation.

On pure noise, the bias-corrected distance correlation sits at −0.001 with p = .545: no false alarm.

07

Sets of variables, and the cross tests

Read

Because distances work in any number of dimensions, you can ask whether one set of variables depends on another. The distance correlation of two columns against one gives p = .005 by permutation.

Cross distance covariance and cross HSIC split the data in two and compare the halves. That gives a statistic with a normal null, so no permutations are needed: fast at large nn, at some cost in power. Cross HSIC on the quadratic gives zz = 6.25, p < .001, and cross dCov on two sets of columns gives p = .006.

08

Which one?

Reflect
You wantUse
A fast default, and the direction of predictionChatterjee's ξ
A single pair, many shapes, no tuningHoeffding's D
Sets of variablesDistance correlation or HSIC
Very large nnCross dCov or cross HSIC

Beware of ξ on simple, noisy linear relationships: it has low power there. If you expect a monotonic trend, Spearman will detect it with far fewer rows. Which row matches a question you have right now?

09

Read the card

In the app
Test of independence: Chatterjee's ξ(x → y)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

Chatterjee's ξ(x → y) = 0.402, p < .001, N = 118

Chatterjee's ξ(x → y)
0.4019
z
6.901
p
< .001
n
118

Effect size

  • Chatterjee's ξ(x → y) 0.4019

Plots

y quadratic against xHow do two numeric variables move together?
View data
xy quadratic
0.52060.8319
−1.0800.1154
0.1392−1.026
−0.0847−0.6384
−0.66660.9804
−2.5166.778
−1.0201.064
0.11360.3246
−0.47380.4670
−0.40820.4326
−0.73040.6322
−0.22140.2123
−0.2258−0.6691
−2.5477.544
1.3471.722
0.61640.6260
0.2176−0.6333
−0.80470.4650
0.68970.8538
−0.32870.1813
−0.16470.1581
−1.3921.285
1.4662.395
0.0482−0.2532
1.9082.810
1.7313.307
0.05810.0112
0.64530.0495
1.7263.115
−0.5290−0.6496
0.16641.067
0.33280.2743
0.1824−0.0805
1.1650.7660
0.59350.5174
−0.89180.5918
0.57731.096
−0.82490.1289
−1.1572.008
0.77800.8816
−1.2040.9219
0.3067−0.0010
−0.83370.2404
1.4181.011
0.71181.461
−0.40250.9465
0.79940.7091
0.4265−0.5284
−1.1701.625
−0.2062−0.4512
−0.93061.165
0.44940.6359
−0.64480.5104
−0.23140.0189
−1.2362.067
−0.96101.459
0.13400.2288
−0.99910.9358
−0.14150.4886
0.16730.1283

First 60 of 118 rows.

Assumptions

  • Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
  • Ties — Ties in x are broken at random (seeded) for ξ.

The same variables under other dependence measures

MeasureValueSensitive to
Pearson r−0.0277Linear association
Spearman ρ−0.0254Monotonic association
ξ(x → y)0.4019y is a function of x (any shape)
ξ(y → x)0.0034x is a function of y (any shape)
Hoeffding 30·D0.0676Any departure from independence (ranks)
Distance correlation0.4592Any dependence (finite means)
Bias-corrected dCor0.1767Any dependence; ≈ 0 under independence
HSIC (median bandwidth)0.0194Any dependence (kernel)
  • 2 of 120 rows were left out because a value was missing.
  • Chatterjee's ξ(x → y); one-sided test of independence (asymptotic normal p-value).
The exact R script · R R version 4.5.1 (2025-06-13)
# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 3c303f0c5fe8f8c7
# Dataset: f_dependence (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/f_dependence.parquet", col_select = c("x", "y quadratic")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y quadratic")]), , 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("x", "y quadratic"))  # infinite values stop the run (registry/errors.yaml)

# %% Dependence
x_cols <- c("x")
y_cols <- c("y quadratic")
measure <- "xi"
calibration <- "auto"
n_perm <- as.integer(999)
bandwidth <- "median"
standardize <- TRUE
max_n <- as.integer(1000)
seed <- 42  # shared Wichmann-Hill streams: ties in x, permutations, subsample, split
univariate <- length(x_cols) == 1 && length(y_cols) == 1
if (measure %in% c("xi", "hoeffding") && !univariate) stop("ξ and Hoeffding's D compare one x variable with one y variable.")
if (length(intersect(x_cols, y_cols))) stop("A column cannot be both an x and a y variable.")
X <- as.matrix(df[x_cols]); storage.mode(X) <- "double"
Y <- as.matrix(df[y_cols]); storage.mode(Y) <- "double"
n <- nrow(df)
if (n < 10) cs_error("CS_E_TOO_FEW_ROWS", what = "A dependence test", min = 10, n = n)
for (col in c(x_cols, y_cols)) {
  # a constant variable cannot depend on anything (most measures are 0 / 0)
  if (length(unique(as.double(df[[col]]))) < 2) cs_error("CS_E_CONSTANT", column = col)
}
if (n > max_n) {  # n x n matrices: analyze a seeded random subsample
  idx <- sort(cs_rperm(cs_rng(seed + 2), n)[seq_len(max_n)])
  warnings <- c(warnings, sprintf("Distance and kernel measures used a random subsample of %d of %d rows (seed %d).", max_n, n, as.integer(seed)))
} else {
  idx <- seq_len(n)
}
Xs <- X[idx, , drop = FALSE]
Ys <- Y[idx, , drop = FALSE]
n_used <- if (measure != "xi") length(idx) else n
scaled <- function(M) {
  if (!standardize) return(M)
  sweep(sweep(M, 2, colMeans(M), "-"), 2, apply(M, 2, stats::sd), "/")
}

if (calibration == "auto") {
  calibration <- c(xi = "asymptotic", hoeffding = "permutation", dcor = "permutation", hsic = "permutation")[measure]
  if (is.na(calibration)) calibration <- "normal"
  calibration <- unname(calibration)
}
if (measure %in% c("cross_hsic", "cross_dcov")) {
  calibration <- "normal"
} else if (calibration == "asymptotic" && !(measure %in% c("xi", "dcor"))) {
  stop("Only ξ and distance correlation have an asymptotic test; choose permutations.")
}
z <- NULL; test_statistic <- NULL; dof <- NULL; count <- NULL
bw_x <- NULL; bw_y <- NULL
used_perm <- calibration == "permutation"
if (measure == "xi") {
  xv <- X[, 1]; yv <- Y[, 1]
  res <- cs_xi(xv, yv, seed)
  statistic <- res$statistic
  label <- "Chatterjee's ξ(x → y)"
  if (used_perm) {
    pr <- cs_perm_pvalue(function(pm) cs_xi(xv, yv[pm], seed)$statistic, statistic, n, n_perm, seed + 1)
    p <- pr$p; count <- pr$count
  } else {
    z <- res$z; p <- res$p
  }
} else if (measure == "hoeffding") {
  xv <- Xs[, 1]; yv <- Ys[, 1]
  statistic <- cs_hoeffding_d(xv, yv)
  label <- "Hoeffding's D"
  pr <- cs_perm_pvalue(function(pm) cs_hoeffding_d(xv, yv[pm]), statistic, length(xv), n_perm, seed + 1)
  p <- pr$p; count <- pr$count
} else if (measure == "dcor") {
  dc <- cs_dcov(scaled(Xs), scaled(Ys))
  if (used_perm) {
    A <- dc$A; B <- dc$B
    statistic <- dc$dcor; test_statistic <- dc$nv2
    label <- "Distance correlation"
    m <- nrow(A)
    pr <- cs_perm_pvalue(function(pm) m * mean(A * B[pm, pm]), test_statistic, m, n_perm, seed + 1)
    p <- pr$p; count <- pr$count
  } else {
    statistic <- dc$dcor_bc; test_statistic <- dc$t; dof <- dc$df; p <- dc$p_t
    label <- "Bias-corrected distance correlation"
  }
} else if (measure == "hsic") {
  Xh <- scaled(Xs); Yh <- scaled(Ys)
  if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
  hs <- cs_hsic(Xh, Yh, bw_x, bw_y)
  statistic <- hs$statistic
  label <- "HSIC"
  Kc <- hs$Kc; Lc <- hs$Lc
  m <- nrow(Kc)
  pr <- cs_perm_pvalue(function(pm) sum(Kc * Lc[pm, pm]) / (m - 1)^2, statistic, m, n_perm, seed + 1)
  p <- pr$p; count <- pr$count
} else {
  Xh <- scaled(Xs); Yh <- scaled(Ys)
  kernel <- if (measure == "cross_hsic") "gaussian" else "distance"
  if (kernel == "gaussian") {
    if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
  }
  res <- cs_cross_stat(Xh, Yh, kernel, if (is.null(bw_x)) 1 else bw_x, if (is.null(bw_y)) 1 else bw_y, seed + 3)
  statistic <- res$statistic; z <- res$z; p <- res$p
  label <- if (kernel == "gaussian") "Cross HSIC" else "Cross distance covariance"
  n_used <- 2 * res$half
}

# %% Profile: the same pair under other measures (estimates only)
xi_xy <- NULL; xi_yx <- NULL; hoeffding_30d <- NULL; pearson <- NULL; spearman <- NULL
Xp <- scaled(Xs); Yp <- scaled(Ys)
dcor_all <- cs_dcov(Xp, Yp)
dcor_v <- dcor_all$dcor; dcor_bc <- dcor_all$dcor_bc
rows <- list()
if (univariate) {
  xa <- Xs[, 1]; ya <- Ys[, 1]
  pearson <- stats::cor(xa, ya)
  spearman <- stats::cor(rank(xa), rank(ya))
  xi_xy <- cs_xi(xa, ya, seed)$statistic
  xi_yx <- cs_xi(ya, xa, seed)$statistic
  hoeffding_30d <- 30 * cs_hoeffding_d(xa, ya)
  rows <- list(list(measure = "Pearson r", value = pearson, detects = "Linear association"),
               list(measure = "Spearman ρ", value = spearman, detects = "Monotonic association"),
               list(measure = "ξ(x → y)", value = xi_xy, detects = "y is a function of x (any shape)"),
               list(measure = "ξ(y → x)", value = xi_yx, detects = "x is a function of y (any shape)"),
               list(measure = "Hoeffding 30·D", value = hoeffding_30d, detects = "Any departure from independence (ranks)"))
}
hsic_med <- cs_hsic(Xp, Yp, cs_median_bandwidth(Xp), cs_median_bandwidth(Yp))$statistic
rows <- c(rows, list(list(measure = "Distance correlation", value = dcor_v, detects = "Any dependence (finite means)"),
                     list(measure = "Bias-corrected dCor", value = dcor_bc, detects = "Any dependence; ≈ 0 under independence"),
                     list(measure = "HSIC (median bandwidth)", value = hsic_med, detects = "Any dependence (kernel)")))

# %% Result
alpha <- 0.050000000000000044
verdict <- if (p < alpha) sprintf("The variables are not independent (%s).", cs_fmt_p(p)) else sprintf("The data are compatible with independence (%s).", cs_fmt_p(p))
summary <- sprintf("%s between %s and %s was %.3f (n = %d). %s", label, paste(x_cols, collapse = ", "), paste(y_cols, collapse = ", "), statistic, as.integer(n_used), verdict)
how <- switch(calibration,
              asymptotic = if (measure == "xi") "asymptotic normal p-value" else "bias-corrected t-test",
              permutation = sprintf("%d Monte Carlo permutations (seed %d)", n_perm, as.integer(seed)),
              normal = "studentized cross statistic, standard normal p-value")
apa <- sprintf("%s = %.3f, %s, N = %d", label, statistic, cs_fmt_p(p), as.integer(n_used))
statistics_rows <- list(list(key = "statistic", label = label, value = statistic))
if (!is.null(test_statistic)) statistics_rows <- c(statistics_rows, list(list(key = "test_statistic", label = if (!is.null(dof)) "t" else "nV²", value = test_statistic)))
if (!is.null(z)) statistics_rows <- c(statistics_rows, list(list(key = "z", label = "z", value = z)))
statistics_rows <- c(statistics_rows, list(list(key = "p", label = "p", value = p, format = "p"), list(key = "n", label = "n", value = n_used)))
charts <- list()
if (univariate) {
  sel <- unique(round(seq(1, n, length.out = min(n, 5000))))
  charts <- list(cs_chart("scatter", "scatter", sprintf("%s against %s", y_cols[1], x_cols[1]), list(x = cs_col(x_cols[1], X[sel, 1]), y = cs_col(y_cols[1], Y[sel, 1]))))
}
cs_publish(list(
  method = "correlation.dependence",
  methodVersion = "1.0.1",
  title = sprintf("Test of independence: %s", label),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_used,
  summary = summary,
  apa = apa,
  statistics = statistics_rows,
  tables = list(list(key = "profile", title = "The same variables under other dependence measures", columns = list(
    list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
    list(key = "detects", label = "Sensitive to", type = "string")), rows = rows)),
  effectSizes = list(list(key = "statistic", label = label, value = statistic, method = how)),
  assumptions = list(
    list(key = "independence", label = "Independent rows", status = "info",
         detail = "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."),
    list(key = "ties", label = "Ties", status = "info",
         detail = if (measure == "xi") "Ties in x are broken at random (seeded) for ξ." else "Ties are handled by midranks or exact distances.")
  ),
  charts = charts,
  warnings = warnings,
  notes = list(sprintf("%s; one-sided test of independence (%s).", label, how)),
  values = list(measure = measure, measure_label = label, statistic = statistic, z = z, test_statistic = test_statistic, df = dof,
                p = p, calibration = calibration, n = n, n_used = n_used, n_perm = if (used_perm) n_perm else NULL, count = count,
                xi_xy = xi_xy, xi_yx = xi_yx, dcor = dcor_v, dcor_bc = dcor_bc, hoeffding_30d = hoeffding_30d, hsic = hsic_med,
                pearson = pearson, spearman = spearman, bandwidth_x = bw_x, bandwidth_y = bw_y)
))
Python

Chatterjee's ξ(x → y) = 0.402, p < .001, N = 118

Chatterjee's ξ(x → y)
0.4019
z
6.901
p
< .001
n
118

Effect size

  • Chatterjee's ξ(x → y) 0.4019

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

Assumptions

  • Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
  • Ties — Ties in x are broken at random (seeded) for ξ.

The same variables under other dependence measures

MeasureValueSensitive to
Pearson r−0.0277Linear association
Spearman ρ−0.0254Monotonic association
ξ(x → y)0.4019y is a function of x (any shape)
ξ(y → x)0.0034x is a function of y (any shape)
Hoeffding 30·D0.0676Any departure from independence (ranks)
Distance correlation0.4592Any dependence (finite means)
Bias-corrected dCor0.1767Any dependence; ≈ 0 under independence
HSIC (median bandwidth)0.0194Any dependence (kernel)
  • 2 of 120 rows were left out because a value was missing.
  • Chatterjee's ξ(x → y); one-sided test of independence (asymptotic normal p-value).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 3c303f0c5fe8f8c7
# Dataset: f_dependence (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import dependence
from codesplash.stats.rng import Rng

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

# %% Dependence
x_cols = ["x"]
y_cols = ["y quadratic"]
measure = "xi"
calibration = "auto"
n_perm = int(999)
bandwidth = "median"
standardize = True
max_n = int(1000)
seed = 42  # shared Wichmann–Hill streams: ties in x, permutations, subsample, split
univariate = len(x_cols) == 1 and len(y_cols) == 1
if measure in ("xi", "hoeffding") and not univariate:
    raise ValueError("ξ and Hoeffding's D compare one x variable with one y variable.")
if set(x_cols) & set(y_cols):
    raise ValueError("A column cannot be both an x and a y variable.")
X = df[x_cols].to_numpy(dtype=float)
Y = df[y_cols].to_numpy(dtype=float)
n = len(df)
if n < 10:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A dependence test", min=10, n=n)
for col, v in zip(x_cols + y_cols, np.column_stack([X, Y]).T):
    if len(np.unique(v)) < 2:  # a constant variable cannot depend on anything (most measures are 0 / 0)
        cs.cs_error("CS_E_CONSTANT", column=col)
if n > max_n:  # n × n matrices: analyze a seeded random subsample
    idx = np.sort(Rng(seed + 2).permutation(n)[:max_n])
    warnings.append(f"Distance and kernel measures used a random subsample of {max_n} of {n} rows (seed {seed}).")
else:
    idx = np.arange(n)
Xs, Ys = X[idx], Y[idx]
n_used = len(idx) if measure != "xi" else n


def scaled(M):
    return (M - M.mean(axis=0)) / M.std(axis=0, ddof=1) if standardize else M


if calibration == "auto":
    calibration = {"xi": "asymptotic", "hoeffding": "permutation", "dcor": "permutation", "hsic": "permutation"}.get(measure, "normal")
if measure in ("cross_hsic", "cross_dcov"):
    calibration = "normal"
elif calibration == "asymptotic" and measure not in ("xi", "dcor"):
    raise ValueError("Only ξ and distance correlation have an asymptotic test; choose permutations.")
z = test_statistic = dof = count = None
bw_x = bw_y = None
used_perm = calibration == "permutation"
if measure == "xi":
    xv, yv = X[:, 0], Y[:, 0]
    res = dependence.xi(xv, yv, seed)
    statistic = res["statistic"]
    label = "Chatterjee's ξ(x → y)"
    if used_perm:
        pr = dependence.perm_pvalue(lambda pm: dependence.xi(xv, yv[pm], seed)["statistic"], statistic, n, n_perm, seed + 1)
        p, count = pr["p"], pr["count"]
    else:
        z, p = res["z"], res["p"]
elif measure == "hoeffding":
    xv, yv = Xs[:, 0], Ys[:, 0]
    statistic = dependence.hoeffding_d(xv, yv)
    label = "Hoeffding's D"
    pr = dependence.perm_pvalue(lambda pm: dependence.hoeffding_d(xv, yv[pm]), statistic, len(xv), n_perm, seed + 1)
    p, count = pr["p"], pr["count"]
elif measure == "dcor":
    dc = dependence.dcov(scaled(Xs), scaled(Ys))
    if used_perm:
        A, B = dc["A"], dc["B"]
        statistic, test_statistic = dc["dcor"], dc["nv2"]
        label = "Distance correlation"
        m = A.shape[0]
        pr = dependence.perm_pvalue(lambda pm: m * float(np.mean(A * B[np.ix_(pm, pm)])), test_statistic, m, n_perm, seed + 1)
        p, count = pr["p"], pr["count"]
    else:
        statistic, test_statistic, dof, p = dc["dcor_bc"], dc["t"], dc["df"], dc["p_t"]
        label = "Bias-corrected distance correlation"
elif measure == "hsic":
    Xh, Yh = scaled(Xs), scaled(Ys)
    bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
    hs = dependence.hsic(Xh, Yh, bw_x, bw_y)
    statistic = hs["statistic"]
    label = "HSIC"
    Kc, Lc = hs["Kc"], hs["Lc"]
    m = Kc.shape[0]
    pr = dependence.perm_pvalue(lambda pm: float(np.sum(Kc * Lc[np.ix_(pm, pm)]) / (m - 1) ** 2), statistic, m, n_perm, seed + 1)
    p, count = pr["p"], pr["count"]
else:
    Xh, Yh = scaled(Xs), scaled(Ys)
    kernel = "gaussian" if measure == "cross_hsic" else "distance"
    if kernel == "gaussian":
        bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
    res = dependence.cross_stat(Xh, Yh, kernel, bw_x or 1.0, bw_y or 1.0, seed + 3)
    statistic, z, p = res["statistic"], res["z"], res["p"]
    label = "Cross HSIC" if kernel == "gaussian" else "Cross distance covariance"
    n_used = 2 * res["half"]

# %% Profile: the same pair under other measures (estimates only)
xi_xy = xi_yx = hoeffding_30d = pearson = spearman = hsic_med = None
Xp, Yp = scaled(Xs), scaled(Ys)
dcor_all = dependence.dcov(Xp, Yp)
dcor_v, dcor_bc = dcor_all["dcor"], dcor_all["dcor_bc"]
rows = []
if univariate:
    xa, ya = Xs[:, 0], Ys[:, 0]
    pearson = float(np.corrcoef(xa, ya)[0, 1])
    spearman = float(np.corrcoef(stats.rankdata(xa), stats.rankdata(ya))[0, 1])
    xi_xy = dependence.xi(xa, ya, seed)["statistic"]
    xi_yx = dependence.xi(ya, xa, seed)["statistic"]
    hoeffding_30d = 30 * dependence.hoeffding_d(xa, ya)
    rows += [{"measure": "Pearson r", "value": pearson, "detects": "Linear association"},
             {"measure": "Spearman ρ", "value": spearman, "detects": "Monotonic association"},
             {"measure": "ξ(x → y)", "value": xi_xy, "detects": "y is a function of x (any shape)"},
             {"measure": "ξ(y → x)", "value": xi_yx, "detects": "x is a function of y (any shape)"},
             {"measure": "Hoeffding 30·D", "value": hoeffding_30d, "detects": "Any departure from independence (ranks)"}]
hsic_med = dependence.hsic(Xp, Yp, dependence.median_bandwidth(Xp), dependence.median_bandwidth(Yp))["statistic"]
rows += [{"measure": "Distance correlation", "value": dcor_v, "detects": "Any dependence (finite means)"},
         {"measure": "Bias-corrected dCor", "value": dcor_bc, "detects": "Any dependence; ≈ 0 under independence"},
         {"measure": "HSIC (median bandwidth)", "value": hsic_med, "detects": "Any dependence (kernel)"}]

# %% Result
alpha = 0.050000000000000044
names = lambda cols: ", ".join(cols)
verdict = (f"The variables are not independent ({cs.fmt_p(p)})." if p < alpha
           else f"The data are compatible with independence ({cs.fmt_p(p)}).")
summary = f"{label} between {names(x_cols)} and {names(y_cols)} was {statistic:.3f} (n = {n_used}). {verdict}"
how = {"asymptotic": "asymptotic normal p-value" if measure == "xi" else "bias-corrected t-test",
       "permutation": f"{n_perm} Monte Carlo permutations (seed {seed})", "normal": "studentized cross statistic, standard normal p-value"}[calibration]
apa = f"{label} = {statistic:.3f}, {cs.fmt_p(p)}, N = {n_used}"
statistics_rows = [{"key": "statistic", "label": label, "value": statistic}]
if test_statistic is not None:
    statistics_rows.append({"key": "test_statistic", "label": "t" if dof is not None else "nV²", "value": test_statistic})
if z is not None:
    statistics_rows.append({"key": "z", "label": "z", "value": z})
statistics_rows += [{"key": "p", "label": "p", "value": p, "format": "p"}, {"key": "n", "label": "n", "value": n_used}]
charts = []
if univariate:
    sel = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
    charts.append(cs.chart("scatter", "scatter", f"{y_cols[0]} against {x_cols[0]}", {"x": cs.col(x_cols[0], X[sel, 0]), "y": cs.col(y_cols[0], Y[sel, 0])}))
cs.publish({
    "method": "correlation.dependence",
    "methodVersion": "1.0.1",
    "title": f"Test of independence: {label}",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n_used,
    "summary": summary,
    "apa": apa,
    "statistics": statistics_rows,
    "tables": [{"key": "profile", "title": "The same variables under other dependence measures", "columns": [
        {"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
        {"key": "detects", "label": "Sensitive to", "type": "string"}], "rows": rows}],
    "effectSizes": [{"key": "statistic", "label": label, "value": statistic, "method": how}],
    "assumptions": [
        {"key": "independence", "label": "Independent rows", "status": "info",
         "detail": "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."},
        {"key": "ties", "label": "Ties", "status": "info",
         "detail": "Ties in x are broken at random (seeded) for ξ." if measure == "xi" else "Ties are handled by midranks or exact distances."},
    ],
    "charts": charts,
    "warnings": warnings,
    "notes": [f"{label}; one-sided test of independence ({how})."],
    "values": {"measure": measure, "measure_label": label, "statistic": statistic, "z": z, "test_statistic": test_statistic, "df": dof,
               "p": p, "calibration": calibration, "n": n, "n_used": n_used, "n_perm": n_perm if used_perm else None, "count": count,
               "xi_xy": xi_xy, "xi_yx": xi_yx, "dcor": dcor_v, "dcor_bc": dcor_bc, "hoeffding_30d": hoeffding_30d, "hsic": hsic_med,
               "pearson": pearson, "spearman": spearman, "bandwidth_x": bw_x, "bandwidth_y": bw_y},
})

The card reports the measure you chose plus the others for comparison, including Pearson and Spearman. A large gap between ξ or dCor and Pearson is your cue to look at the plot, because the relationship isn't a straight line.

10

Check your understanding

Checkpoint

Check yourself

Pearson's r = 0.01 and bias-corrected distance correlation = 0.45 with p < .001. What's the most likely situation?

Show the answer

Answer: b

Distance correlation detects dependence of any form. A big gap from Pearson usually means curved or non-monotonic structure.

Check yourself

What does ξ(x → y) much larger than ξ(y → x) suggest?

Show the answer

Answer: b

ξ measures how well one variable determines the other. It says nothing about causation.

Check yourself

You want to test whether a set of 5 sensor readings is related to a set of 3 outcomes. What fits?

Show the answer

Answer: c

Pearson and ξ compare two single columns. Distance correlation and HSIC work with sets of variables.

Check yourself

You expect a simple increasing trend with a lot of noise. Why might Spearman be better than ξ?

Show the answer

Answer: a

General tests pay for their generality. If you know the shape you expect, a test aimed at that shape usually needs fewer rows.

11

Do it on your own data

In the app

Pick the columns and a Measure. Permutation calibration is available for all but the cross tests, and it runs on the shared random stream, so Python and R give the same p-value.

Python
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
x = rng.normal(size=300)
y = x**2 + rng.normal(scale=0.3, size=300)
print(stats.pearsonr(x, y).statistic)
print(stats.chatterjeexi(x, y).statistic)  # SciPy 1.15+
R
xi <- function(x, y) {  # no ties assumed
  r <- rank(y[order(x)])
  1 - 3 * sum(abs(diff(r))) / (length(y)^2 - 1)
}
set.seed(1)
x <- rnorm(300)
y <- x^2 + rnorm(300, sd = 0.3)
c(pearson = cor(x, y), xi = xi(x, y))

These two scripts draw different random data, so their numbers differ a little.

12

Recap

Recap
  • Zero correlation doesn't rule out a strong relationship.
  • ξ is fast and directional; Hoeffding's D is a tuning-free omnibus for a pair.
  • Distance correlation and HSIC handle sets of variables; the cross versions scale to large nn.
  • General tests have less power against simple trends, so use the most specific test you can justify.

Concepts in this lesson