Where are the clusters? LISA, Gi* and LOSH
Local statistics put a test on every site. Read local Moran clusters, Gi* hot spots and LOSH, and correct for the fact that a map is many tests.
What runs in CodeSplash
- STAT251Local Moran I tests Runs in CodeSplash
- STAT252Getis–Ord local G and G star tests Runs in CodeSplash
- STAT255LOSH tests Runs in CodeSplash
- Hot spots and local spatial patterns (LISA, Getis–Ord Gi and Gi*, LOSH) Verified in Python and R
You will be able to
- Read LISA labels such as High-High and Low-High
- Tell Gi from Gi* and say what LOSH looks for
- Explain why a hot-spot map needs a multiple-testing correction
Read first
A map is many tests
PredictPredict first
You run one local test per site on a map of 100 sites at the 0.05 level. The map has no pattern at all.
About how many sites get flagged anyway?
Make your guess between 0 and 100 sites, then reveal.
Reveal
About five, since . Because neighboring sites share neighbors, those false flags often sit side by side and look like a real cluster.
From one number to one per site
ReadA global test gives one number for the whole map. A local statistic gives one per site, so you can ask where.
Local Moran's ILISAA Moran's I for each site. It flags clusters (high–high, low–low) and spatial outliers (high–low, low–high). (LISA) compares each site with its neighbors' average and names the four cases:
| Label | The site | Its neighbors |
|---|---|---|
| High-High | High | High |
| Low-Low | Low | Low |
| High-Low | High | Low |
| Low-High | Low | High |
The first two are clusters. The last two are spatial outliers.
Control the false discoveries
ExploreThe Benjamini–HochbergBenjamini–Hochberg procedureControls the false discovery rate by comparing sorted p-values with rising thresholds. rule controls the share of false discoveries among the flagged sites. Change the number of real effects below and watch which p-values pass the step-up line.
BExplorable · The Benjamini–Hochberg step-up
How does controlling the false discovery rate find more than Bonferroni while keeping errors in check?
How many tests will Benjamini–Hochberg reject?
Commit your prediction above to see the result
Make your prediction to see the result.
Here a site's p-value only counts after this adjustment. It is the default on the hot-spot method.
One map, two settings
ReadThe Columbus crime map, tested at every neighborhood.
- Total shuffles, no correction: 11 of 49 sites flagged. That is 6 High-High, 4 Low-Low and 1 Low-High.
- Conditional shuffles, Benjamini–Hochberg: 0 flagged.
The smallest adjusted p is 0.065, so nothing passes 0.05.
0 of 49 sites flagged, the Benjamini–Hochberg correction
- Sites flagged
- 0
- Sites tested
- 49
- Smallest adjusted p
- .065
Plots
View data
| Pattern | Adjusted p | Site | Local Moran's I | crime |
|---|---|---|---|---|
| Not significant | 0.5553 | 1 | 0.7368 | 15.726 |
| Not significant | 0.5206 | 2 | 0.5288 | 18.802 |
| Not significant | 0.6396 | 3 | 0.0939 | 30.627 |
| Not significant | 0.9880 | 4 | 0.0048 | 32.388 |
| Not significant | 0.3659 | 5 | 0.3036 | 50.732 |
| Not significant | 0.7689 | 6 | −0.1816 | 26.067 |
| Not significant | 0.1470 | 7 | −1.861 | 0.1783 |
| Not significant | 0.4173 | 8 | 0.0766 | 38.426 |
| Not significant | 0.8557 | 9 | −0.0306 | 30.516 |
| Not significant | 0.3659 | 10 | 0.0403 | 34.001 |
| Not significant | 0.0871 | 11 | 1.458 | 62.275 |
| Not significant | 0.3214 | 12 | 0.6389 | 56.706 |
| Not significant | 0.8477 | 13 | 0.1253 | 46.716 |
| Not significant | 0.3267 | 14 | 0.6153 | 57.066 |
| Not significant | 0.0871 | 15 | 0.7348 | 48.585 |
| Not significant | 0.0653 | 16 | 1.239 | 54.839 |
| Not significant | 0.1470 | 17 | −0.1081 | 36.869 |
| Not significant | 0.1176 | 18 | 0.5171 | 43.962 |
| Not significant | 0.3659 | 19 | 0.8000 | 54.522 |
| Not significant | 0.5986 | 20 | 0.3414 | 0.2238 |
| Not significant | 0.5488 | 21 | 0.1549 | 40.074 |
| Not significant | 0.9147 | 22 | −0.0040 | 33.705 |
| Not significant | 0.1470 | 23 | 0.9008 | 20.049 |
| Not significant | 0.0653 | 24 | 0.2285 | 38.298 |
| Not significant | 0.0784 | 25 | 1.416 | 61.299 |
| Not significant | 0.1176 | 26 | 0.2875 | 40.970 |
| Not significant | 0.8820 | 27 | −0.1240 | 52.794 |
| Not significant | 0.0871 | 28 | 0.9770 | 56.920 |
| Not significant | 0.0653 | 29 | 1.557 | 60.750 |
| Not significant | 0.1069 | 30 | 1.655 | 68.892 |
| Not significant | 0.1470 | 31 | 1.018 | 17.677 |
| Not significant | 0.0784 | 32 | 1.240 | 19.146 |
| Not significant | 0.8615 | 33 | 0.0536 | 41.968 |
| Not significant | 0.2130 | 34 | 0.5284 | 23.974 |
| Not significant | 0.8798 | 35 | −0.0300 | 39.175 |
| Not significant | 0.0871 | 36 | 1.243 | 14.306 |
| Not significant | 0.1069 | 37 | 0.4232 | 42.445 |
| Not significant | 0.3267 | 38 | 0.5775 | 53.711 |
| Not significant | 0.1176 | 39 | 1.108 | 19.101 |
| Not significant | 0.1176 | 40 | 0.9693 | 16.241 |
| Not significant | 0.2130 | 41 | 0.8317 | 18.905 |
| Not significant | 0.2858 | 42 | 1.087 | 16.492 |
| Not significant | 0.8798 | 43 | 0.0058 | 36.664 |
| Not significant | 0.9147 | 44 | −0.0207 | 25.962 |
| Not significant | 0.8615 | 45 | 0.0680 | 29.028 |
| Not significant | 0.1470 | 46 | 1.250 | 16.531 |
| Not significant | 0.2130 | 47 | 0.4677 | 27.823 |
| Not significant | 0.5488 | 48 | 0.2035 | 26.645 |
| Not significant | 0.5405 | 49 | 0.3634 | 22.541 |
View data
| Pattern | Site | crime (standardized) | Average of neighbors (spatial lag) |
|---|---|---|---|
| Not significant | 1 | −1.172 | −0.6289 |
| Not significant | 2 | −0.9859 | −0.5363 |
| Not significant | 3 | −0.2719 | −0.3452 |
| Not significant | 4 | −0.1655 | −0.0291 |
| Not significant | 5 | 0.9422 | 0.3222 |
| Not significant | 6 | −0.5472 | 0.3318 |
| Not significant | 7 | −2.110 | 0.8816 |
| Not significant | 8 | 0.1991 | 0.3847 |
| Not significant | 9 | −0.2785 | 0.1098 |
| Not significant | 10 | −0.0681 | −0.5918 |
| Not significant | 11 | 1.639 | 0.8894 |
| Not significant | 12 | 1.303 | 0.4904 |
| Not significant | 13 | 0.6997 | 0.1791 |
| Not significant | 14 | 1.325 | 0.4645 |
| Not significant | 15 | 0.8126 | 0.9043 |
| Not significant | 16 | 1.190 | 1.041 |
| Not significant | 17 | 0.1051 | −1.029 |
| Not significant | 18 | 0.5334 | 0.9693 |
| Not significant | 19 | 1.171 | 0.6832 |
| Not significant | 20 | −2.108 | −0.1620 |
| Not significant | 21 | 0.2986 | 0.5189 |
| Not significant | 22 | −0.0860 | 0.0468 |
| Not significant | 23 | −0.9106 | −0.9893 |
| Not significant | 24 | 0.1914 | 1.194 |
| Not significant | 25 | 1.580 | 0.8963 |
| Not significant | 26 | 0.3527 | 0.8152 |
| Not significant | 27 | 1.067 | −0.1162 |
| Not significant | 28 | 1.316 | 0.7425 |
| Not significant | 29 | 1.547 | 1.006 |
| Not significant | 30 | 2.039 | 0.8118 |
| Not significant | 31 | −1.054 | −0.9663 |
| Not significant | 32 | −0.9651 | −1.285 |
| Not significant | 33 | 0.4130 | 0.1298 |
| Not significant | 34 | −0.6736 | −0.7845 |
| Not significant | 35 | 0.2443 | −0.1226 |
| Not significant | 36 | −1.257 | −0.9887 |
| Not significant | 37 | 0.4418 | 0.9580 |
| Not significant | 38 | 1.122 | 0.5147 |
| Not significant | 39 | −0.9678 | −1.145 |
| Not significant | 40 | −1.141 | −0.8499 |
| Not significant | 41 | −0.9797 | −0.8489 |
| Not significant | 42 | −1.125 | −0.9655 |
| Not significant | 43 | 0.0927 | 0.0623 |
| Not significant | 44 | −0.5535 | 0.0373 |
| Not significant | 45 | −0.3684 | −0.1845 |
| Not significant | 46 | −1.123 | −1.113 |
| Not significant | 47 | −0.4412 | −1.060 |
| Not significant | 48 | −0.5123 | −0.3973 |
| Not significant | 49 | −0.7601 | −0.4781 |
Assumptions
- Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). Try a second definition as a sensitivity check.
- Many tests corrected — 49 sites tested with the Benjamini–Hochberg correction.
- Local tests are dependent — Neighboring sites share neighbors, so their tests are correlated. Treat flagged sites as leads to investigate, not proof.
- Regions at a meaningful scale — Clusters can appear or vanish when regions change (the modifiable areal unit problem).
Tests by site
| Site | crime | Local Moran's I | z | p | Adjusted p | Pattern |
|---|---|---|---|---|---|---|
| 1 | 15.726 | 0.7368 | 0.9260 | .408 | .555 | Not significant |
| 2 | 18.802 | 0.5288 | 0.9892 | .340 | .521 | Not significant |
| 3 | 30.627 | 0.0939 | 0.6917 | .496 | .640 | Not significant |
| 4 | 32.388 | 0.0048 | 0.0239 | .988 | .988 | Not significant |
| 5 | 50.732 | 0.3036 | 1.139 | .224 | .366 | Not significant |
| 6 | 26.067 | −0.1816 | −0.4932 | .612 | .769 | Not significant |
| 7 | 0.1783 | −1.861 | −1.892 | .048 | .147 | Not significant |
| 8 | 38.426 | 0.0766 | 1.082 | .264 | .417 | Not significant |
| 9 | 30.516 | −0.0306 | −0.3602 | .716 | .856 | Not significant |
| 10 | 34.001 | 0.0403 | 1.239 | .212 | .366 | Not significant |
| 11 | 62.275 | 1.458 | 2.322 | .016 | .087 | Not significant |
| 12 | 56.706 | 0.6389 | 1.407 | .164 | .321 | Not significant |
| 13 | 46.716 | 0.1253 | 0.4270 | .692 | .848 | Not significant |
| 14 | 57.066 | 0.6153 | 1.327 | .180 | .327 | Not significant |
| 15 | 48.585 | 0.7348 | 2.442 | .016 | .087 | Not significant |
| 16 | 54.839 | 1.239 | 3.288 | .004 | .065 | Not significant |
| 17 | 36.869 | −0.1081 | −1.872 | .056 | .147 | Not significant |
| 18 | 43.962 | 0.5171 | 2.048 | .036 | .118 | Not significant |
| 19 | 54.522 | 0.8000 | 1.282 | .220 | .366 | Not significant |
| 20 | 0.2238 | 0.3414 | 0.7336 | .452 | .599 | Not significant |
| 21 | 40.074 | 0.1549 | 0.9214 | .384 | .549 | Not significant |
| 22 | 33.705 | −0.0040 | −0.1287 | .896 | .915 | Not significant |
| 23 | 20.049 | 0.9008 | 1.862 | .060 | .147 | Not significant |
| 24 | 38.298 | 0.2285 | 3.370 | .004 | .065 | Not significant |
| 25 | 61.299 | 1.416 | 2.971 | .008 | .078 | Not significant |
| 26 | 40.970 | 0.2875 | 2.193 | .036 | .118 | Not significant |
| 27 | 52.794 | −0.1240 | −0.1959 | .828 | .882 | Not significant |
| 28 | 56.920 | 0.9770 | 2.657 | .012 | .087 | Not significant |
| 29 | 60.750 | 1.557 | 3.011 | .004 | .065 | Not significant |
| 30 | 68.892 | 1.655 | 2.210 | .024 | .107 | Not significant |
| 31 | 17.677 | 1.018 | 1.845 | .056 | .147 | Not significant |
| 32 | 19.146 | 1.240 | 2.762 | .008 | .078 | Not significant |
| 33 | 41.968 | 0.0536 | 0.2815 | .756 | .861 | Not significant |
| 34 | 23.974 | 0.5284 | 1.702 | .096 | .213 | Not significant |
| 35 | 39.175 | −0.0300 | −0.2896 | .804 | .880 | Not significant |
| 36 | 14.306 | 1.243 | 2.366 | .016 | .087 | Not significant |
| 37 | 42.445 | 0.4232 | 2.483 | .024 | .107 | Not significant |
| 38 | 53.711 | 0.5775 | 1.400 | .180 | .327 | Not significant |
| 39 | 19.101 | 1.108 | 2.176 | .036 | .118 | Not significant |
| 40 | 16.241 | 0.9693 | 2.001 | .032 | .118 | Not significant |
First 40 of 49 rows.
- Neighbors: Queen contiguity, row-standardized (W). p from 499 permutations (seed 42), one shared set of draws for all sites; adjusted with the Benjamini–Hochberg correction.
The exact R script · R R version 4.5.1 (2025-06-13)
# Hot spots and local spatial patterns (LISA, Getis–Ord Gi and Gi*, LOSH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.hotspots 1.0.3 · spec 5aa938a73749f946
# Dataset: sp_columbus (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_columbus.parquet", col_select = c("crime", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("crime", "site")]), , 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("crime", "site")) # 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.hotspots/lisa-conditional-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[["site"]])
# %% Test
# One test per site: local Moran's I (Anselin 1995; Sokal et al. 1998), Getis–Ord Gi and Gi* (Getis & Ord 1992;
# Ord & Getis 1995) or LOSH (Ord & Getis 2012), with a multiple-testing correction across the sites.
Y <- "crime"
statistic <- "local_moran" # local_moran | gi_star | gi | losh
calibration <- "permutation" # permutation | normal
randomization <- "conditional" # conditional | total
alternative <- "two_sided" # two_sided | greater | less
adjust_method <- "BH" # BH | BY | holm | bonferroni | none
a <- 2
n_perm <- as.integer(499)
alpha <- 0.05
seed <- 42
x <- as.numeric(df[[Y]])
n <- length(x)
cs_check_rows(n, 5, "Local spatial tests") # five sites with values that vary (registry/errors.yaml)
cs_check_not_constant(x, Y)
LABELS <- c(local_moran = "Local Moran's I", gi_star = "Getis–Ord Gi*", gi = "Getis–Ord Gi", losh = "LOSH")
ADJUST <- c(BH = "the Benjamini–Hochberg correction", BY = "the Benjamini–Yekutieli correction", holm = "the Holm correction",
bonferroni = "the Bonferroni correction", none = "no correction")
res <- if (statistic == "local_moran") {
cs_sp_local_moran(wt, x, randomization, calibration, alternative, n_perm, seed)
} else if (statistic == "losh") {
cs_sp_losh(wt, x, a, if (calibration == "permutation") "permutation" else "chisq", n_perm, seed)
} else {
cs_sp_local_g(wt, x, statistic == "gi_star", calibration, alternative, n_perm, seed)
}
stat <- res$statistic
z <- res$z
p <- res$p
p_adj <- cs_sp_adjust(p, adjust_method)
flagged <- !is.nan(p_adj) & p_adj < alpha
label <- if (statistic == "local_moran") {
cs_sp_clusters(res$centered, res$lag, p_adj, alpha)
} else if (statistic == "losh") {
ifelse(flagged, "High variability", "Not significant")
} else {
ifelse(flagged & !is.nan(stat) & stat > 0, "Hot spot", ifelse(flagged & !is.nan(stat) & stat < 0, "Cold spot", "Not significant"))
}
# %% Assumptions
n_tested <- sum(res$tested)
n_flagged <- sum(flagged)
assumptions <- list(
list(key = "weights_chosen", label = "Neighbors chosen for a reason", status = "info",
detail = sprintf("Neighbors: %s. Try a second definition as a sensitivity check.", neighbours_label)),
list(key = "multiplicity", label = "Many tests corrected", status = if (adjust_method == "none") "warn" else "pass",
detail = if (adjust_method == "none") {
sprintf("%d sites tested without a correction: expect about %.1f flagged by chance alone.", n_tested, alpha * n_tested)
} else {
sprintf("%d sites tested with %s.", n_tested, ADJUST[[adjust_method]])
}),
list(key = "dependence", label = "Local tests are dependent", status = "info",
detail = "Neighboring sites share neighbors, so their tests are correlated. Treat flagged sites as leads to investigate, not proof."),
list(key = "scale", label = "Regions at a meaningful scale", status = "info",
detail = "Clusters can appear or vanish when regions change (the modifiable areal unit problem).")
)
# %% Result
statistic_label <- LABELS[[statistic]]
adjust_label <- ADJUST[[adjust_method]]
count <- function(name) sum(label == name)
finite <- !is.nan(stat)
values <- list(n = n, n_tested = n_tested, n_flagged = n_flagged, share_flagged = if (n_tested > 0) n_flagged / n_tested else 0,
n_high_high = count("High-High"), n_low_low = count("Low-Low"), n_high_low = count("High-Low"), n_low_high = count("Low-High"),
n_hot = count("Hot spot"), n_cold = count("Cold spot"),
sum_statistic = sum(stat[finite]), sum_p = sum(p[!is.nan(p)]), sum_p_adj = sum(p_adj[!is.nan(p_adj)]),
max_statistic = max(stat[finite]), min_p = min(p[!is.nan(p)]), min_p_adj = min(p_adj[!is.nan(p_adj)]),
links = length(wt$i), islands = n_islands, n_perm = if (calibration == "permutation") n_perm else 0L,
missing_share = if (n_input > 0) n_dropped / n_input else 0,
statistic_label = statistic_label, adjust_label = adjust_label)
if (statistic == "losh") {
values$h1 <- mean(res$residual)
values$h2 <- mean(res$residual^2)
}
describe <- function(keys, names) {
out <- character(0)
for (k in seq_along(keys)) if (values[[keys[k]]] > 0) out <- c(out, sprintf("%d %s", values[[keys[k]]], names[k]))
out
}
parts <- if (statistic == "local_moran") {
describe(c("n_high_high", "n_low_low", "n_high_low", "n_low_high"), c("high–high", "low–low", "high–low", "low–high"))
} else if (statistic == "losh") {
if (n_flagged > 0) sprintf("%d with unusually high variability", n_flagged) else character(0)
} else {
describe(c("n_hot", "n_cold"), c("hot", "cold"))
}
found <- if (n_flagged > 0) {
sprintf("%d of %d sites flagged at %g after %s: %s.", n_flagged, n_tested, alpha, adjust_label, paste(parts, collapse = ", "))
} else {
sprintf("No site stands out at %g after %s.", alpha, adjust_label)
}
summary <- paste0(sprintf("%s for %s. %s", statistic_label, Y, found), if (n_flagged > 0) " Treat flagged sites as leads to investigate; they are not causes." else "")
columns <- list(list(key = "site", label = "Site", type = "string"), list(key = "value", label = Y, type = "number"),
list(key = "statistic", label = statistic_label, type = "number"), list(key = "z", label = "z", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = "Adjusted p", type = "pvalue"),
list(key = "label", label = "Pattern", type = "string"))
num <- function(v) if (is.nan(v)) NULL else v
site_rows <- lapply(seq_len(n), function(k) list(site = site[k], value = x[k], statistic = num(stat[k]), z = num(z[k]), p = num(p[k]), p_adj = num(p_adj[k]), label = label[k]))
tables <- list(list(key = "sites", title = "Tests by site", columns = columns, rows = site_rows))
geo <- list(site = cs_col("Site", site), value = cs_col(Y, x), statistic = cs_col(statistic_label, stat), p_adj = cs_col("Adjusted p", p_adj),
label = cs_col("Pattern", label))
recipe <- if (statistic == "local_moran") "lisa-map" else "hotspot-map"
charts <- list(cs_chart("map", recipe, sprintf("%s for %s", statistic_label, Y), geo, controls = list(layer = "sp_columbus")))
if (statistic == "local_moran") {
zv <- (x - mean(x)) / sqrt(mean((x - mean(x))^2))
charts[[2]] <- 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), label = cs_col("Pattern", label)))
}
for (key in c("h1", "h2")) if (is.null(values[[key]])) values[[key]] <- NA_real_ # only some options produce these
cs_publish(list(
method = "spatial.hotspots",
methodVersion = "1.0.3",
title = statistic_label,
engine = cs_engine_info("stats"),
n = n,
summary = summary,
apa = sprintf("%d of %d sites flagged, %s", n_flagged, n_tested, adjust_label),
statistics = list(list(key = "n_flagged", label = "Sites flagged", value = n_flagged), list(key = "n_tested", label = "Sites tested", value = n_tested),
list(key = "min_p_adj", label = "Smallest adjusted p", value = values$min_p_adj, format = "p")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Neighbors: %s. ", neighbours_label),
if (calibration == "permutation") sprintf("p from %d permutations (seed %d), one shared set of draws for all sites; ", n_perm, seed) else "",
sprintf("adjusted with %s.", adjust_label))),
values = values,
charts = charts
))
0 of 49 sites flagged, the Benjamini–Hochberg correction
- Sites flagged
- 0
- Sites tested
- 49
- Smallest adjusted p
- .065
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Neighbors chosen for a reason — Neighbors: Queen contiguity, row-standardized (W). Try a second definition as a sensitivity check.
- Many tests corrected — 49 sites tested with the Benjamini–Hochberg correction.
- Local tests are dependent — Neighboring sites share neighbors, so their tests are correlated. Treat flagged sites as leads to investigate, not proof.
- Regions at a meaningful scale — Clusters can appear or vanish when regions change (the modifiable areal unit problem).
Tests by site
| Site | crime | Local Moran's I | z | p | Adjusted p | Pattern |
|---|---|---|---|---|---|---|
| 1 | 15.726 | 0.7368 | 0.9260 | .408 | .555 | Not significant |
| 2 | 18.802 | 0.5288 | 0.9892 | .340 | .521 | Not significant |
| 3 | 30.627 | 0.0939 | 0.6917 | .496 | .640 | Not significant |
| 4 | 32.388 | 0.0048 | 0.0239 | .988 | .988 | Not significant |
| 5 | 50.732 | 0.3036 | 1.139 | .224 | .366 | Not significant |
| 6 | 26.067 | −0.1816 | −0.4932 | .612 | .769 | Not significant |
| 7 | 0.1783 | −1.861 | −1.892 | .048 | .147 | Not significant |
| 8 | 38.426 | 0.0766 | 1.082 | .264 | .417 | Not significant |
| 9 | 30.516 | −0.0306 | −0.3602 | .716 | .856 | Not significant |
| 10 | 34.001 | 0.0403 | 1.239 | .212 | .366 | Not significant |
| 11 | 62.275 | 1.458 | 2.322 | .016 | .087 | Not significant |
| 12 | 56.706 | 0.6389 | 1.407 | .164 | .321 | Not significant |
| 13 | 46.716 | 0.1253 | 0.4270 | .692 | .848 | Not significant |
| 14 | 57.066 | 0.6153 | 1.327 | .180 | .327 | Not significant |
| 15 | 48.585 | 0.7348 | 2.442 | .016 | .087 | Not significant |
| 16 | 54.839 | 1.239 | 3.288 | .004 | .065 | Not significant |
| 17 | 36.869 | −0.1081 | −1.872 | .056 | .147 | Not significant |
| 18 | 43.962 | 0.5171 | 2.048 | .036 | .118 | Not significant |
| 19 | 54.522 | 0.8000 | 1.282 | .220 | .366 | Not significant |
| 20 | 0.2238 | 0.3414 | 0.7336 | .452 | .599 | Not significant |
| 21 | 40.074 | 0.1549 | 0.9214 | .384 | .549 | Not significant |
| 22 | 33.705 | −0.0040 | −0.1287 | .896 | .915 | Not significant |
| 23 | 20.049 | 0.9008 | 1.862 | .060 | .147 | Not significant |
| 24 | 38.298 | 0.2285 | 3.370 | .004 | .065 | Not significant |
| 25 | 61.299 | 1.416 | 2.971 | .008 | .078 | Not significant |
| 26 | 40.970 | 0.2875 | 2.193 | .036 | .118 | Not significant |
| 27 | 52.794 | −0.1240 | −0.1959 | .828 | .882 | Not significant |
| 28 | 56.920 | 0.9770 | 2.657 | .012 | .087 | Not significant |
| 29 | 60.750 | 1.557 | 3.011 | .004 | .065 | Not significant |
| 30 | 68.892 | 1.655 | 2.210 | .024 | .107 | Not significant |
| 31 | 17.677 | 1.018 | 1.845 | .056 | .147 | Not significant |
| 32 | 19.146 | 1.240 | 2.762 | .008 | .078 | Not significant |
| 33 | 41.968 | 0.0536 | 0.2815 | .756 | .861 | Not significant |
| 34 | 23.974 | 0.5284 | 1.702 | .096 | .213 | Not significant |
| 35 | 39.175 | −0.0300 | −0.2896 | .804 | .880 | Not significant |
| 36 | 14.306 | 1.243 | 2.366 | .016 | .087 | Not significant |
| 37 | 42.445 | 0.4232 | 2.483 | .024 | .107 | Not significant |
| 38 | 53.711 | 0.5775 | 1.400 | .180 | .327 | Not significant |
| 39 | 19.101 | 1.108 | 2.176 | .036 | .118 | Not significant |
| 40 | 16.241 | 0.9693 | 2.001 | .032 | .118 | Not significant |
First 40 of 49 rows.
- Neighbors: Queen contiguity, row-standardized (W). p from 499 permutations (seed 42), one shared set of draws for all sites; adjusted with the Benjamini–Hochberg correction.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hot spots and local spatial patterns (LISA, Getis–Ord Gi and Gi*, LOSH)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method spatial.hotspots 1.0.3 · spec 5aa938a73749f946
# Dataset: sp_columbus (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_columbus.parquet", columns=["crime", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["crime", "site"]) # listwise deletion over the analysis columns
df["site"] = df["site"].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, ["crime", "site"]) # 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.hotspots/lisa-conditional-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["site"].astype(str).to_numpy()
# %% Test
# One test per site: local Moran's I (Anselin 1995; Sokal et al. 1998), Getis–Ord Gi and Gi* (Getis & Ord 1992;
# Ord & Getis 1995) or LOSH (Ord & Getis 2012), with a multiple-testing correction across the sites.
Y = "crime"
statistic = "local_moran" # local_moran | gi_star | gi | losh
calibration = "permutation" # permutation | normal
randomization = "conditional" # conditional | total
alternative = "two_sided" # two_sided | greater | less
adjust_method = "BH" # BH | BY | holm | bonferroni | none
a = 2
n_perm = int(499)
alpha = 0.05
seed = 42
x = df[Y].to_numpy(dtype=float)
n = x.size
cs.check_rows(n, 5, "Local spatial tests") # five sites with values that vary (registry/errors.yaml)
check_not_constant(x, Y)
LABELS = {"local_moran": "Local Moran's I", "gi_star": "Getis–Ord Gi*", "gi": "Getis–Ord Gi", "losh": "LOSH"}
ADJUST = {"BH": "the Benjamini–Hochberg correction", "BY": "the Benjamini–Yekutieli correction", "holm": "the Holm correction",
"bonferroni": "the Bonferroni correction", "none": "no correction"}
if statistic == "local_moran":
res = sp.local_moran(wt, x, randomization, calibration, alternative, n_perm, seed)
elif statistic == "losh":
res = sp.losh(wt, x, a, "permutation" if calibration == "permutation" else "chisq", n_perm, seed)
else:
res = sp.local_g(wt, x, statistic == "gi_star", calibration, alternative, n_perm, seed)
stat, z, p = res["statistic"], res["z"], res["p"]
p_adj = sp.adjust(p, adjust_method)
flagged = ~np.isnan(p_adj) & (p_adj < alpha)
if statistic == "local_moran":
label = sp.clusters(res["centered"], res["lag"], p_adj, alpha)
elif statistic == "losh":
label = np.where(flagged, "High variability", "Not significant")
else:
label = np.where(flagged & (stat > 0), "Hot spot", np.where(flagged & (stat < 0), "Cold spot", "Not significant"))
# %% Assumptions
n_tested = int(np.sum(res["tested"]))
n_flagged = int(np.sum(flagged))
assumptions = [
{"key": "weights_chosen", "label": "Neighbors chosen for a reason", "status": "info",
"detail": f"Neighbors: {neighbours_label}. Try a second definition as a sensitivity check."},
{"key": "multiplicity", "label": "Many tests corrected", "status": "warn" if adjust_method == "none" else "pass",
"detail": (f"{n_tested} sites tested without a correction: expect about {alpha * n_tested:.1f} flagged by chance alone." if adjust_method == "none"
else f"{n_tested} sites tested with {ADJUST[adjust_method]}.")},
{"key": "dependence", "label": "Local tests are dependent", "status": "info",
"detail": "Neighboring sites share neighbors, so their tests are correlated. Treat flagged sites as leads to investigate, not proof."},
{"key": "scale", "label": "Regions at a meaningful scale", "status": "info",
"detail": "Clusters can appear or vanish when regions change (the modifiable areal unit problem)."},
]
# %% Result
statistic_label = LABELS[statistic]
adjust_label = ADJUST[adjust_method]
count = lambda name: int(np.sum(label == name))
finite = ~np.isnan(stat)
values = {"n": n, "n_tested": n_tested, "n_flagged": n_flagged, "share_flagged": n_flagged / n_tested if n_tested else 0.0,
"n_high_high": count("High-High"), "n_low_low": count("Low-Low"), "n_high_low": count("High-Low"), "n_low_high": count("Low-High"),
"n_hot": count("Hot spot"), "n_cold": count("Cold spot"),
"sum_statistic": float(np.sum(stat[finite])), "sum_p": float(np.nansum(p)), "sum_p_adj": float(np.nansum(p_adj)),
"max_statistic": float(np.max(stat[finite])), "min_p": float(np.nanmin(p)), "min_p_adj": float(np.nanmin(p_adj)),
"links": int(wt["i"].size), "islands": n_islands, "n_perm": n_perm if calibration == "permutation" else 0,
"missing_share": n_dropped / n_input if n_input else 0.0,
"statistic_label": statistic_label, "adjust_label": adjust_label}
if statistic == "losh":
values["h1"] = float(np.mean(res["residual"]))
values["h2"] = float(np.mean(res["residual"] ** 2))
if statistic == "local_moran":
parts = [f"{values[k]} {name}" for k, name in (("n_high_high", "high–high"), ("n_low_low", "low–low"), ("n_high_low", "high–low"), ("n_low_high", "low–high")) if values[k]]
elif statistic == "losh":
parts = [f"{n_flagged} with unusually high variability"] if n_flagged else []
else:
parts = [f"{values[k]} {name}" for k, name in (("n_hot", "hot"), ("n_cold", "cold")) if values[k]]
found = (f"{n_flagged} of {n_tested} sites flagged at {alpha:g} after {adjust_label}: {', '.join(parts)}."
if n_flagged else f"No site stands out at {alpha:g} after {adjust_label}.")
summary = f"{statistic_label} for {Y}. {found}" + (" Treat flagged sites as leads to investigate; they are not causes." if n_flagged else "")
columns = [{"key": "site", "label": "Site", "type": "string"}, {"key": "value", "label": Y, "type": "number"},
{"key": "statistic", "label": statistic_label, "type": "number"}, {"key": "z", "label": "z", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": "Adjusted p", "type": "pvalue"},
{"key": "label", "label": "Pattern", "type": "string"}]
def num(v):
return None if np.isnan(v) else float(v)
site_rows = [{"site": str(site[k]), "value": float(x[k]), "statistic": num(stat[k]), "z": num(z[k]), "p": num(p[k]), "p_adj": num(p_adj[k]), "label": str(label[k])} for k in range(n)]
tables = [{"key": "sites", "title": "Tests by site", "columns": columns, "rows": site_rows}]
geo = {"site": cs.col("Site", site), "value": cs.col(Y, x), "statistic": cs.col(statistic_label, stat), "p_adj": cs.col("Adjusted p", p_adj),
"label": cs.col("Pattern", label.astype(str))}
recipe = "lisa-map" if statistic == "local_moran" else "hotspot-map"
charts = [cs.chart("map", recipe, f"{statistic_label} for {Y}", geo, controls={"layer": "sp_columbus"})]
if statistic == "local_moran":
charts.append(cs.chart("scatter", "moran-scatter", f"Each site against its neighbors: {Y}", {
"x": cs.col(f"{Y} (standardized)", (x - x.mean()) / x.std(ddof=0)),
"y": cs.col("Average of neighbors (spatial lag)", sw.weights_lag(wt, (x - x.mean()) / x.std(ddof=0))),
"site": cs.col("Site", site), "label": cs.col("Pattern", label.astype(str))}))
for key in ["h1", "h2"]: # only some options produce these
values.setdefault(key, None)
cs.publish({
"method": "spatial.hotspots",
"methodVersion": "1.0.3",
"title": statistic_label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{n_flagged} of {n_tested} sites flagged, {adjust_label}",
"statistics": [{"key": "n_flagged", "label": "Sites flagged", "value": n_flagged}, {"key": "n_tested", "label": "Sites tested", "value": n_tested},
{"key": "min_p_adj", "label": "Smallest adjusted p", "value": values["min_p_adj"], "format": "p"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Neighbors: {neighbours_label}. " + (f"p from {n_perm} permutations (seed {seed}), one shared set of draws for all sites; " if calibration == "permutation" else "")
+ f"adjusted with {adjust_label}."],
"values": values,
"charts": charts,
})
Why more shuffles can matter
ReflectA two-sided permutation p-value can't go below . With 499 shuffles, that floor is .
Benjamini–Hochberg with 49 sites lets the th smallest p pass at . A floor of only passes once reaches 4, so at least four sites must sit at the floor, however strong each one is.
What would you change before concluding that this map has no local clusters at all? And what would you report if nothing is flagged?
Hot and cold spots
ReadGetis–Ord GiGetis–Ord Gi and Gi*A z-value for each site showing a local concentration of high (hot) or low (cold) values. Gi* counts the site itself; Gi leaves it out. is a z-score for the values around a site. Large positive values mark a hot spot, large negative values a cold spot.
- Gi leaves the site's own value out, so it asks about the surroundings.
- Gi* counts the site too, so it asks about the local neighborhood as a whole.
On a 6 × 6 grid of pure noise, the largest Gi* is 2.65, with a raw p of 0.008. It looks striking until you correct for the 36 tests: 0.29.
Places that vary
ReadLOSHLOSHFlags neighborhoods whose values vary unusually much. It is about variability, not about high values. isn't about high values. It looks for neighborhoods where values differ unusually much from each other.
A high LOSH value marks a place where high and low sit close together, such as a boundary between two kinds of area. It can flag places the other statistics pass over.
On Columbus, the largest LOSH is 4.86. After correction, the smallest p is 0.061, from 199 shuffles.
Check your understanding
CheckpointCheck yourself
A county has a low rate and its neighbors have high rates. Which LISA label fits?
Show the answer
Answer: d
The first word is the site and the second is its neighbors. Low-High is a spatial outlier: a low value among highs.
Check yourself
What is the difference between Gi and Gi*?
Show the answer
Answer: b
Both are local z-scores for concentration. The guide's warning applies to reports: name which one you used, because a local G without the site itself isn't G*.
Check yourself
With no correction, 11 of 49 Columbus neighborhoods were flagged. What share is that? Give it as a proportion with two decimals.
Show the answer
Answer: 0.224489795918367
, far more than the 5% that chance alone would give, which is why these sites are worth a corrected look rather than being declared hot spots.
Do it in CodeSplash
In the appPick the Local statistic, keep Multiple-testing correction at Benjamini–Hochberg, and raise Permutations on a large map. Treat flagged sites as leads to investigate.
This script computes Benjamini–Hochberg adjusted p-values by hand. Run it on any list of site p-values.
import numpy as np
p = np.array([0.002, 0.004, 0.012, 0.03, 0.2, 0.5])
order = np.argsort(p)
m = len(p)
adj = p[order] * m / np.arange(1, m + 1)
adj = np.minimum.accumulate(adj[::-1])[::-1].clip(max=1)
out = np.empty(m)
out[order] = adj
print(out)p <- c(0.002, 0.004, 0.012, 0.03, 0.2, 0.5)
p.adjust(p, method = "BH")Recap
Recap- A local statistic is one test per site, so a map needs a multiple-testing correction.
- LISA names clusters and spatial outliers. Gi and Gi* mark hot and cold spots. LOSH marks unusual variability.
- Permutation p-values have a floor, so use enough shuffles for the number of sites on your map.
- Flagged sites are leads to investigate, not explanations.
Concepts in this lesson