Clusters of highs, categories and distances
Getis–Ord G asks whether high values cluster, join counts handle categories, and the Mantel test compares two distance matrices.
What runs in CodeSplash
- STAT250Getis–Ord global G test Runs in CodeSplash
- STAT253Join count tests Runs in CodeSplash
- STAT254Mantel permutation test Runs in CodeSplash
- Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts) Verified in Python and R
- Mantel test (and partial Mantel, correlogram) Verified in Python and R
You will be able to
- Say what Getis–Ord G can tell you that Moran's I can't
- Read join counts for a category on a map
- Explain why the Mantel test permutes whole rows rather than single distances
Read first
What Moran's I can't see
ReadMoran's I is positive whenever like sits next to like. A map where high values cluster and a map where low values cluster can give the same I.
Three other tests ask more specific questions:
- Do the high values cluster?
- Do the categories cluster?
- Do two sets of distances between the same objects go together?
Lows that cluster
PredictPredict first
Getis–Ord GGetis–Ord GThe share of all value products that falls between neighbors; above its expected value means high values cluster. is the share of all value products that falls on neighboring pairs:
The values on a map are non-negative, and the low values cluster while the highs are scattered. Where does G land?
Reveal
Below. Small values multiply to small products, so the neighboring pairs hold less than their share of the total. High values clustering would push G above. Moran's I is positive in both cases.
Read G
ReadG = 0.05, z = 1.50, p = .095
- G
- 0.0529
- Expected G
- 0.0495
- z
- 1.497
- p
- .095
- Mean neighbors
- 4.900
Plots
View data
| Site | rate (standardized) | Average of neighbors (spatial lag) |
|---|---|---|
| 37009 | −1.691 | 1.543 |
| 37005 | 2.900 | −2.138 |
| 37171 | −0.3148 | 1.209 |
| 37053 | 0.3075 | 2.141 |
| 37131 | −0.1417 | 2.611 |
| 37091 | 0.5652 | 1.835 |
| 37029 | 3.048 | 1.176 |
| 37073 | 1.102 | 0.9213 |
| 37185 | −0.2971 | −0.8202 |
| 37169 | 0.3438 | −2.133 |
| 37033 | −0.3672 | −1.448 |
| 37157 | −0.9211 | −1.030 |
| 37077 | −0.0914 | −1.812 |
| 37145 | 0.1624 | −0.9803 |
| 37181 | 0.1166 | −2.080 |
| 37083 | 1.468 | −3.048 |
| 37139 | −0.2328 | 2.459 |
| 37193 | −0.1324 | −3.055 |
| 37189 | −1.224 | −3.449 |
| 37143 | −1.691 | 0.1003 |
| 37041 | −0.7685 | −0.5895 |
| 37011 | −1.691 | 0.3299 |
| 37197 | −1.162 | −2.071 |
| 37069 | −1.691 | 0.7304 |
| 37067 | −0.7404 | −2.934 |
| 37081 | −0.1568 | −2.137 |
| 37001 | −0.1091 | −2.627 |
| 37015 | 0.8752 | −1.042 |
| 37135 | −0.5797 | −0.9093 |
| 37063 | 0.0581 | −1.621 |
| 37127 | −0.5722 | 0.2079 |
| 37121 | 0.1140 | −2.246 |
| 37065 | 0.0214 | −0.0624 |
| 37027 | 0.0657 | −1.720 |
| 37199 | −0.7366 | 0.2039 |
| 37117 | −1.242 | −0.1929 |
| 37183 | −0.4583 | −2.345 |
| 37115 | 0.1003 | 0.0747 |
| 37097 | −0.9231 | −0.9222 |
| 37059 | 0.0393 | −4.246 |
| 37003 | −0.7054 | −0.1504 |
| 37057 | −0.7621 | 1.216 |
| 37023 | 1.193 | 1.408 |
| 37187 | −1.691 | −4.300 |
| 37177 | −1.691 | −3.382 |
| 37111 | 0.1812 | −1.131 |
| 37151 | 0.0517 | 0.2621 |
| 37037 | −0.6534 | −1.518 |
| 37195 | 0.6001 | 1.451 |
| 37159 | −0.6587 | 2.270 |
| 37147 | −0.3160 | 1.286 |
| 37035 | 0.8394 | 1.461 |
| 37021 | −0.1915 | 1.519 |
| 37101 | 0.5646 | −2.182 |
| 37087 | 1.003 | 1.952 |
| 37055 | −0.9079 | −1.384 |
| 37013 | −0.5506 | −5.043 |
| 37173 | 0.1875 | 2.537 |
| 37079 | 1.125 | 1.969 |
| 37105 | −0.0036 | −1.130 |
First 60 of 100 rows.
View data
| Density | Observed | G |
|---|---|---|
| 18.718 | 0.0529 | 0.0440 |
| 0 | 0.0529 | 0.0443 |
| 0 | 0.0529 | 0.0446 |
| 18.718 | 0.0529 | 0.0448 |
| 56.155 | 0.0529 | 0.0451 |
| 18.718 | 0.0529 | 0.0454 |
| 37.437 | 0.0529 | 0.0456 |
| 74.874 | 0.0529 | 0.0459 |
| 18.718 | 0.0529 | 0.0462 |
| 37.437 | 0.0529 | 0.0464 |
| 112.31 | 0.0529 | 0.0467 |
| 112.31 | 0.0529 | 0.0470 |
| 112.31 | 0.0529 | 0.0472 |
| 56.155 | 0.0529 | 0.0475 |
| 149.75 | 0.0529 | 0.0478 |
| 131.03 | 0.0529 | 0.0480 |
| 205.90 | 0.0529 | 0.0483 |
| 187.18 | 0.0529 | 0.0486 |
| 224.62 | 0.0529 | 0.0488 |
| 168.47 | 0.0529 | 0.0491 |
| 149.75 | 0.0529 | 0.0494 |
| 168.47 | 0.0529 | 0.0497 |
| 149.75 | 0.0529 | 0.0499 |
| 149.75 | 0.0529 | 0.0502 |
| 56.155 | 0.0529 | 0.0505 |
| 112.31 | 0.0529 | 0.0507 |
| 131.03 | 0.0529 | 0.0510 |
| 131.03 | 0.0529 | 0.0513 |
| 131.03 | 0.0529 | 0.0515 |
| 93.592 | 0.0529 | 0.0518 |
| 93.592 | 0.0529 | 0.0521 |
| 112.31 | 0.0529 | 0.0523 |
| 112.31 | 0.0529 | 0.0526 |
| 149.75 | 0.0529 | 0.0529 |
| 0 | 0.0529 | 0.0531 |
| 56.155 | 0.0529 | 0.0534 |
| 74.874 | 0.0529 | 0.0537 |
| 56.155 | 0.0529 | 0.0539 |
| 18.718 | 0.0529 | 0.0542 |
| 37.437 | 0.0529 | 0.0545 |
Assumptions
- Neighbors chosen for a reason — Neighbors: Queen contiguity, binary (B). The result answers the question for these neighbors; try a second definition as a sensitivity check.
- Values exchangeable under the null — A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals.
- Regions at a meaningful scale — Changing the size or borders of regions can change the result (the modifiable areal unit problem).
- Neighbors: Queen contiguity, binary (B). p from 199 permutations of the values (seed 42); normal approximation with the randomization variance.
The exact R script · R R version 4.5.1 (2025-06-13)
# Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.autocorrelation 1.1.1 · spec b5d983e973c4b02c
# Dataset: sp_nc_sids (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/sp_nc_sids.parquet", col_select = c("rate", "fips")))
n_input <- nrow(df)
df[["fips"]] <- factor(df[["fips"]], levels = sort(unique(df[["fips"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("rate", "fips")]), , 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("rate", "fips")) # infinite values stop the run (registry/errors.yaml)
# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so R and
# Python read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt <- cs_load_weights("target/academy-parity/run-8142/spatial.autocorrelation/getis-ord-permutation/out-r")
if (nrow(df) != wt$n) wt <- cs_weights_subset(wt, as.integer(rownames(df)))
n_islands <- length(wt$islands)
neighbours_label <- if (nzchar(wt$description)) wt$description else "the chosen neighbors"
if (n_islands > 0) {
warnings <- c(warnings, sprintf("%d site(s) have no neighbors; their spatial lag is 0 and local tests skip them.", n_islands))
}
site <- as.character(df[["fips"]])
# %% Test
# Global spatial autocorrelation over the neighbors above (Moran 1950; Geary 1954; Getis & Ord 1992;
# Cliff & Ord 1981). Permutation p-values shuffle the values across sites on the shared random stream.
Y <- "rate"
test <- "getis_ord" # moran | geary | getis_ord | join_count
calibration <- "permutation" # permutation | randomization | normality
alternative <- "greater" # two_sided | greater | less
n_perm <- as.integer(199)
alpha <- 0.05
seed <- 42
n <- nrow(df)
cs_check_rows(n, 4, "A spatial autocorrelation test") # the moments need four sites (registry/errors.yaml)
LABELS <- c(moran = "Moran's I", geary = "Geary's C", getis_ord = "Getis–Ord G", join_count = "Join counts")
SYMBOLS <- c(moran = "I", geary = "C", getis_ord = "G", join_count = "BW")
rows <- list()
if (test == "join_count") {
# Join counts use binary weights: one link is one join.
if (wt$style != "B") {
wt$w <- cs_weights_style(wt$i, wt$j, wt$g, wt$n, "B")
wt$style <- "B"
warnings <- c(warnings, "Join counts use binary weights, so the weights style was set to binary for this test.")
}
vals <- df[[Y]]
if (is.factor(vals)) {
levels <- levels(vals)
codes <- as.integer(vals)
} else {
uniq <- sort(unique(vals))
levels <- if (is.logical(uniq)) ifelse(uniq, "true", "false") else sprintf("%g", as.numeric(uniq))
codes <- match(vals, uniq)
}
if (length(levels) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = Y, min = 2, k = length(levels))
res <- cs_sp_join_counts(wt, codes, if (calibration == "permutation") calibration else "normal", alternative, n_perm, seed)
rows <- res$rows
} else {
if (!is.numeric(df[[Y]])) stop(sprintf("%s needs a numeric variable; %s is not numeric. Use join counts for categories.", LABELS[[test]], Y))
if (test == "getis_ord" && wt$style != "B") {
warnings <- c(warnings, "Getis–Ord G is usually run with binary weights; row-standardized weights change what it measures.")
}
cs_check_not_constant(df[[Y]], Y)
res <- cs_sp_global_test(wt, as.numeric(df[[Y]]), test, calibration, alternative, n_perm, seed)
}
statistic <- res$statistic
expected <- res$expected
variance <- res$variance
z <- res$z
p <- res$p
# %% Assumptions
assumptions <- list(
list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
detail = sprintf("Neighbors: %s. The result answers the question for these neighbors; try a second definition as a sensitivity check.", neighbours_label)),
list(key = "exchangeable", label = "Values exchangeable under the null", status = "info",
detail = "A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals."),
list(key = "scale", label = "Regions at a meaningful scale", status = "info",
detail = "Changing the size or borders of regions can change the result (the modifiable areal unit problem).")
)
# %% Result
test_label <- LABELS[[test]]
test_symbol <- SYMBOLS[[test]]
clustered <- if (alternative == "two_sided") z > 0 else alternative == "greater"
pattern <- if (clustered) "Like values cluster more than chance alone would explain." else "Like values are kept apart more than chance alone would explain."
verdict <- if (p < alpha) pattern else "The map is compatible with values placed at random across sites."
how <- if (calibration == "permutation") "permutations" else "normal approximation"
summary <- sprintf("%s for %s: %s = %.3f (expected %.3f), z = %.2f, %s (%s). %s", test_label, Y, test_symbol, statistic, expected, z, cs_fmt_p(p), how, verdict)
values <- list(statistic = statistic, expected = expected, variance = variance, z = z, p = p, p_analytic = res$p_analytic,
p_perm = if (calibration == "permutation") res$p_perm else NULL, n = n, links = res$links,
mean_neighbours = res$links / n, islands = n_islands, n_perm = if (calibration == "permutation") n_perm else 0L,
kurtosis = res$kurtosis, missing_share = if (n_input > 0) n_dropped / n_input else 0,
test_label = test_label, test_symbol = test_symbol, pattern = pattern, neighbours_label = neighbours_label)
tables <- list()
if (length(rows)) {
for (row in rows) {
lv <- levels[row$level]
values[[sprintf("bb[%s]", lv)]] <- row$joins
values[[sprintf("bb_expected[%s]", lv)]] <- row$expected
values[[sprintf("bb_z[%s]", lv)]] <- row$z
values[[sprintf("bb_p[%s]", lv)]] <- row$p
}
columns <- list(list(key = "join", label = "Join", type = "string"), list(key = "joins", label = "Joins", type = "number"),
list(key = "expected", label = "Expected", type = "number"), list(key = "variance", label = "Variance", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"))
table_rows <- lapply(rows, function(r) list(join = sprintf("%s–%s", levels[r$level], levels[r$level]), joins = r$joins, expected = r$expected,
variance = r$variance, z = r$z, p = r$p))
table_rows[[length(table_rows) + 1L]] <- list(join = "Different categories", joins = statistic, expected = expected, variance = variance, z = z, p = p)
tables[[1]] <- list(key = "joins", title = "Joins between neighboring sites", columns = columns, rows = table_rows)
}
charts <- list()
if (test != "join_count") {
zv <- as.numeric(df[[Y]])
zv <- (zv - mean(zv)) / sqrt(mean((zv - mean(zv))^2))
charts[[length(charts) + 1L]] <- cs_chart("scatter", "moran-scatter", sprintf("Each site against its neighbors: %s", Y), list(
x = cs_col(sprintf("%s (standardized)", Y), zv),
y = cs_col("Average of neighbors (spatial lag)", cs_weights_lag(wt, zv)),
site = cs_col("Site", site)), controls = list(slope = if (test == "moran") statistic else NULL))
}
if (!is.null(res$null)) {
nc <- cs_sp_null_curve(res$null)
charts[[length(charts) + 1L]] <- cs_chart("null", "null-distribution", sprintf("%s under %d shuffles of the values", test_label, n_perm), list(
x = cs_col(test_symbol, nc$x), density = cs_col("Density", nc$density),
observed = cs_col("Observed", rep(statistic, length(nc$x)))))
}
for (key in c("p_perm", "kurtosis")) if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some options produce these
cs_publish(list(
method = "spatial.autocorrelation",
methodVersion = "1.1.1",
title = test_label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("%s = %.2f, z = %.2f, %s", test_symbol, statistic, z, cs_fmt_p(p)),
statistics = list(list(key = "statistic", label = test_symbol, value = statistic), list(key = "expected", label = sprintf("Expected %s", test_symbol), value = expected),
list(key = "z", label = "z", value = z), list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean_neighbours", label = "Mean neighbors", value = res$links / n)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Neighbors: %s. ", neighbours_label),
if (calibration == "permutation") sprintf("p from %d permutations of the values (seed %d); ", n_perm, seed) else "",
if (calibration != "normality") "normal approximation with the randomization variance." else "normal approximation assuming normal values.")),
values = values,
charts = charts
))
G = 0.05, z = 1.50, p = .095
- G
- 0.0529
- Expected G
- 0.0495
- z
- 1.497
- p
- .095
- Mean neighbors
- 4.900
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Neighbors chosen for a reason — Neighbors: Queen contiguity, binary (B). The result answers the question for these neighbors; try a second definition as a sensitivity check.
- Values exchangeable under the null — A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals.
- Regions at a meaningful scale — Changing the size or borders of regions can change the result (the modifiable areal unit problem).
- Neighbors: Queen contiguity, binary (B). p from 199 permutations of the values (seed 42); normal approximation with the randomization variance.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Global spatial autocorrelation (Moran's I, Geary's C, Getis–Ord G, join counts)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.autocorrelation 1.1.1 · spec b5d983e973c4b02c
# Dataset: sp_nc_sids (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
from codesplash.stats import spatial as sp
from codesplash.stats import spatial_weights as sw
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sp_nc_sids.parquet", columns=["rate", "fips"])
n_input = len(df)
df["fips"] = pd.Categorical(df["fips"], categories=sorted(df["fips"].dropna().unique()))
df = df.dropna(subset=["rate", "fips"]) # listwise deletion over the analysis columns
df["fips"] = df["fips"].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, ["rate", "fips"]) # infinite values stop the run (registry/errors.yaml)
# %% Spatial weights
# The host builds the neighbors once from the options you chose and writes them next to this run, so Python
# and R read the same file. Rows with missing values leave the weights too; the style is re-applied.
wt = sw.load_weights("target/academy-parity/run-8142/spatial.autocorrelation/getis-ord-permutation/out-python")
if len(df) != wt["n"]:
wt = sw.weights_subset(wt, df.index.to_numpy())
n_islands = len(wt["islands"])
neighbours_label = wt["description"] or "the chosen neighbors"
if n_islands:
warnings.append(f"{n_islands} site(s) have no neighbors; their spatial lag is 0 and local tests skip them.")
site = df["fips"].astype(str).to_numpy()
# %% Test
# Global spatial autocorrelation over the neighbors above (Moran 1950; Geary 1954; Getis & Ord 1992;
# Cliff & Ord 1981). Permutation p-values shuffle the values across sites on the shared random stream.
Y = "rate"
test = "getis_ord" # moran | geary | getis_ord | join_count
calibration = "permutation" # permutation | randomization | normality
alternative = "greater" # two_sided | greater | less
n_perm = int(199)
alpha = 0.05
seed = 42
n = len(df)
cs.check_rows(n, 4, "A spatial autocorrelation test") # the moments need four sites (registry/errors.yaml)
LABELS = {"moran": "Moran's I", "geary": "Geary's C", "getis_ord": "Getis–Ord G", "join_count": "Join counts"}
SYMBOLS = {"moran": "I", "geary": "C", "getis_ord": "G", "join_count": "BW"}
rows = []
if test == "join_count":
# Join counts use binary weights: one link is one join.
if wt["style"] != "B":
wt = {**wt, "w": sw.apply_style(wt["i"], wt["j"], wt["g"], wt["n"], "B"), "style": "B"}
warnings.append("Join counts use binary weights, so the weights style was set to binary for this test.")
vals = df[Y]
if isinstance(vals.dtype, pd.CategoricalDtype):
levels = [str(c) for c in vals.cat.categories]
codes = vals.cat.codes.to_numpy()
else:
uniq = np.sort(vals.unique())
levels = [("true" if u else "false") if isinstance(u, (bool, np.bool_)) else f"{float(u):g}" for u in uniq]
codes = np.searchsorted(uniq, vals.to_numpy())
if len(levels) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=Y, min=2, k=len(levels))
res = sp.join_counts(wt, codes, calibration if calibration == "permutation" else "normal", alternative, n_perm, seed)
rows = res["rows"]
else:
if not pd.api.types.is_numeric_dtype(df[Y]) or pd.api.types.is_bool_dtype(df[Y]):
raise ValueError(f"{LABELS[test]} needs a numeric variable; {Y} is not numeric. Use join counts for categories.")
if test == "getis_ord" and wt["style"] != "B":
warnings.append("Getis–Ord G is usually run with binary weights; row-standardized weights change what it measures.")
check_not_constant(df[Y], Y)
res = sp.global_test(wt, df[Y].to_numpy(dtype=float), test, calibration, alternative, n_perm, seed)
statistic, expected, variance, z, p = res["statistic"], res["expected"], res["variance"], res["z"], res["p"]
# %% Assumptions
assumptions = [
{"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
"detail": f"Neighbors: {neighbours_label}. The result answers the question for these neighbors; try a second definition as a sensitivity check."},
{"key": "exchangeable", "label": "Values exchangeable under the null", "status": "info",
"detail": "A trend across the map also produces clustering. If the mean drifts across the map, remove the trend first and test the residuals."},
{"key": "scale", "label": "Regions at a meaningful scale", "status": "info",
"detail": "Changing the size or borders of regions can change the result (the modifiable areal unit problem)."},
]
# %% Result
test_label, test_symbol = LABELS[test], SYMBOLS[test]
clustered = (z > 0) if alternative == "two_sided" else (alternative == "greater")
pattern = ("Like values cluster more than chance alone would explain." if clustered
else "Like values are kept apart more than chance alone would explain.")
if p < alpha:
verdict = pattern
else:
verdict = "The map is compatible with values placed at random across sites."
how = "permutations" if calibration == "permutation" else "normal approximation"
summary = f"{test_label} for {Y}: {test_symbol} = {statistic:.3f} (expected {expected:.3f}), z = {z:.2f}, {cs.fmt_p(p)} ({how}). {verdict}"
values = {"statistic": statistic, "expected": expected, "variance": variance, "z": z, "p": p, "p_analytic": res["p_analytic"],
"p_perm": res["p_perm"] if calibration == "permutation" else None, "n": n, "links": res["links"],
"mean_neighbours": res["links"] / n, "islands": n_islands, "n_perm": n_perm if calibration == "permutation" else 0,
"kurtosis": res.get("kurtosis"), "missing_share": n_dropped / n_input if n_input else 0.0,
"test_label": test_label, "test_symbol": test_symbol, "pattern": pattern, "neighbours_label": neighbours_label}
tables = []
if rows:
for row in rows:
lv = levels[row["level"]]
values[f"bb[{lv}]"] = row["joins"]
values[f"bb_expected[{lv}]"] = row["expected"]
values[f"bb_z[{lv}]"] = row["z"]
values[f"bb_p[{lv}]"] = row["p"]
columns = [{"key": "join", "label": "Join", "type": "string"}, {"key": "joins", "label": "Joins", "type": "number"},
{"key": "expected", "label": "Expected", "type": "number"}, {"key": "variance", "label": "Variance", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}]
table_rows = [{"join": f"{levels[r['level']]}–{levels[r['level']]}", "joins": r["joins"], "expected": r["expected"],
"variance": r["variance"], "z": r["z"], "p": r["p"]} for r in rows]
table_rows.append({"join": "Different categories", "joins": statistic, "expected": expected, "variance": variance, "z": z, "p": p})
tables.append({"key": "joins", "title": "Joins between neighboring sites", "columns": columns, "rows": table_rows})
charts = []
if test != "join_count":
zv = df[Y].to_numpy(dtype=float)
zv = (zv - zv.mean()) / zv.std(ddof=0)
charts.append(cs.chart("scatter", "moran-scatter", f"Each site against its neighbors: {Y}", {
"x": cs.col(f"{Y} (standardized)", zv),
"y": cs.col("Average of neighbors (spatial lag)", sw.weights_lag(wt, zv)),
"site": cs.col("Site", site)}, controls={"slope": statistic if test == "moran" else None}))
if res["null"] is not None:
grid, density = sp.null_curve(res["null"])
charts.append(cs.chart("null", "null-distribution", f"{test_label} under {n_perm} shuffles of the values", {
"x": cs.col(test_symbol, grid), "density": cs.col("Density", density),
"observed": cs.col("Observed", np.full(grid.size, statistic))}))
for key in ["p_perm", "kurtosis"]: # only some options produce these
values.setdefault(key, None)
cs.publish({
"method": "spatial.autocorrelation",
"methodVersion": "1.1.1",
"title": test_label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{test_symbol} = {statistic:.2f}, z = {z:.2f}, {cs.fmt_p(p)}",
"statistics": [{"key": "statistic", "label": test_symbol, "value": statistic}, {"key": "expected", "label": f"Expected {test_symbol}", "value": expected},
{"key": "z", "label": "z", "value": z}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean_neighbours", "label": "Mean neighbors", "value": res["links"] / n}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Neighbors: {neighbours_label}. " + (f"p from {n_perm} permutations of the values (seed {seed}); " if calibration == "permutation" else "")
+ ("normal approximation with the randomization variance." if calibration != "normality" else "normal approximation assuming normal values.")],
"values": values,
"charts": charts,
})
For SIDS rates across 100 North Carolina counties, G is 0.0529 against 0.0495 expected.
The normal approximation gives p = .134 two-sided. A one-sided permutation test asking only whether highs cluster gives p = .095.
So this is compatible with no clustering of high rates. G needs non-negative values, and binary weights are the convention.
Counting joins
ReadFor a category, count the neighboring pairs, called joins, by type. With two colors, you have same-color joins and different-color joinsJoin countsCounts neighbor pairs with the same or different categories, against what shuffled labels would give., written BW.
If colors cluster, you see fewer BW joins than chance would give, because like sits next to like.
Fewer or more?
PredictPredict first
A 6 × 6 grid of yes/no values has 120 directed links.
Under no pattern you would expect 30.9 BW joins. You count 26. Which way does that lean?
Reveal
Toward clustering: fewer unlike joins than expected. But the evidence is weak, p = .099, and this grid was simulated with no pattern.
Distance against distance
ReadThe Mantel test asks whether two sets of dissimilarities between the same objects go together: community and environment, or genes and geography.
Each row of a distance matrix involves one object, so the pairwise values share objects and aren't independent. That is why an ordinary correlation p-value is wrong. Instead, the test permutes whole objects, keeping each row and column together.
For 24 pastures, plant-community distances and soil-chemistry distances give MantelMantel testThe correlation between two dissimilarity matrices on the same objects, tested by permuting whole rows of one. r = 0.30 across 276 pairs, p = .005.
Partial Mantel needs caution
ReflectControlling for a third matrix gives a partial Mantel r: 0.17, p = .050, with a different choice of variables and a Spearman correlation.
When the variables are themselves spatially patterned, shuffling objects breaks that pattern, so the null can be wrong and the test can over-reject.
Say you want to separate geography from environment in your own data. What would you do alongside a partial Mantel test to avoid relying on it alone?
Check your understanding
CheckpointCheck yourself
Why might you run Getis–Ord G as well as Moran's I?
Show the answer
Answer: a
Moran's I is positive for either kind of clustering. G goes above its expected value when highs cluster and below when lows cluster. It is still a single number for the whole map, and it needs non-negative values.
Check yourself
A map of a yes/no outcome has many more BW joins than expected under no pattern. What does that suggest?
Show the answer
Answer: b
BW joins link unlike neighbors. Fewer than expected suggests clustering; more than expected suggests that neighbors differ.
Check yourself
Why does the Mantel test permute whole rows and columns of one matrix?
Show the answer
Answer: b
Shuffling single distances would break the structure that every real distance matrix has. Permuting objects keeps it. This doesn't cure spatial autocorrelation: the guide warns that it can still make the permutation null invalid.
Check yourself
A Mantel test compares two distance matrices on 24 pastures. How many distinct pairs does it use? That is .
Show the answer
Answer: 276
. Every pair enters the correlation, but only 24 objects were measured, which is why those pairs aren't independent.
Check yourself
You run a partial Mantel test on variables that are all spatially patterned. What should concern you?
Show the answer
Answer: b
Exchangeability is what makes the permutation valid. When the matrices are spatially autocorrelated, it can fail, and the test can over-reject.
Do it in CodeSplash
In the appChoose Getis–Ord G or Join counts under Test. Both use binary weights by convention, so set Weights style to match. Set the Mantel test up separately, because it compares two sets of variables.
This script counts BW joins on the grid and gives 26.
import pandas as pd
high = (pd.read_csv("sp_grid6.csv")["high"] == "yes").to_numpy()
m = 6
bw = 0
for r in range(m):
for c in range(m):
i = r * m + c
if c + 1 < m and high[i] != high[i + 1]:
bw += 1
if r + 1 < m and high[i] != high[i + m]:
bw += 1
print(bw)high <- read.csv("sp_grid6.csv")$high == "yes"
m <- 6
bw <- 0
for (r in 0:(m - 1)) {
for (c in 0:(m - 1)) {
i <- r * m + c + 1
if (c + 1 < m && high[i] != high[i + 1]) bw <- bw + 1
if (r + 1 < m && high[i] != high[i + m]) bw <- bw + 1
}
}
bwRecap
Recap- Getis–Ord G tells high-value clusters from low-value clusters. Moran's I doesn't.
- Join counts do the job for categories: fewer unlike joins suggest clustering.
- The Mantel test compares two distance matrices and permutes whole objects, because pairs aren't independent.
- A partial Mantel test can over-reject when the data are spatially patterned.
Concepts in this lesson