Skip to content

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.

Advanced ~15 min10 steps

What runs in CodeSplash

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

01

A map is many tests

Predict

Predict 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 100×0.05=5100 \times 0.05 = 5. Because neighboring sites share neighbors, those false flags often sit side by side and look like a real cluster.

02

From one number to one per site

Read

A 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:

LabelThe siteIts neighbors
High-HighHighHigh
Low-LowLowLow
High-LowHighLow
Low-HighLowHigh

The first two are clusters. The last two are spatial outliers.

03

Control the false discoveries

Explore

The 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?

100
How sure?
40
8
3.0
0.10
Benjamini–Hochberg rejects 5

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.

Here a site's p-value only counts after this adjustment. It is the default on the hot-spot method.

04

One map, two settings

Read

The 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.

Local Moran's IRecorded · Python and R agreeRecorded 2026-11-25 · 24 values compared
R

0 of 49 sites flagged, the Benjamini–Hochberg correction

Sites flagged
0
Sites tested
49
Smallest adjusted p
.065

Plots

Local Moran's I for crimeWhere are clusters of like values, and where are spatial outliers?
View data
PatternAdjusted pSiteLocal Moran's Icrime
Not significant0.555310.736815.726
Not significant0.520620.528818.802
Not significant0.639630.093930.627
Not significant0.988040.004832.388
Not significant0.365950.303650.732
Not significant0.76896−0.181626.067
Not significant0.14707−1.8610.1783
Not significant0.417380.076638.426
Not significant0.85579−0.030630.516
Not significant0.3659100.040334.001
Not significant0.0871111.45862.275
Not significant0.3214120.638956.706
Not significant0.8477130.125346.716
Not significant0.3267140.615357.066
Not significant0.0871150.734848.585
Not significant0.0653161.23954.839
Not significant0.147017−0.108136.869
Not significant0.1176180.517143.962
Not significant0.3659190.800054.522
Not significant0.5986200.34140.2238
Not significant0.5488210.154940.074
Not significant0.914722−0.004033.705
Not significant0.1470230.900820.049
Not significant0.0653240.228538.298
Not significant0.0784251.41661.299
Not significant0.1176260.287540.970
Not significant0.882027−0.124052.794
Not significant0.0871280.977056.920
Not significant0.0653291.55760.750
Not significant0.1069301.65568.892
Not significant0.1470311.01817.677
Not significant0.0784321.24019.146
Not significant0.8615330.053641.968
Not significant0.2130340.528423.974
Not significant0.879835−0.030039.175
Not significant0.0871361.24314.306
Not significant0.1069370.423242.445
Not significant0.3267380.577553.711
Not significant0.1176391.10819.101
Not significant0.1176400.969316.241
Not significant0.2130410.831718.905
Not significant0.2858421.08716.492
Not significant0.8798430.005836.664
Not significant0.914744−0.020725.962
Not significant0.8615450.068029.028
Not significant0.1470461.25016.531
Not significant0.2130470.467727.823
Not significant0.5488480.203526.645
Not significant0.5405490.363422.541
Each site against its neighbors: crimeDo sites resemble their neighbors, and which sites break the pattern?
View data
PatternSitecrime (standardized)Average of neighbors (spatial lag)
Not significant1−1.172−0.6289
Not significant2−0.9859−0.5363
Not significant3−0.2719−0.3452
Not significant4−0.1655−0.0291
Not significant50.94220.3222
Not significant6−0.54720.3318
Not significant7−2.1100.8816
Not significant80.19910.3847
Not significant9−0.27850.1098
Not significant10−0.0681−0.5918
Not significant111.6390.8894
Not significant121.3030.4904
Not significant130.69970.1791
Not significant141.3250.4645
Not significant150.81260.9043
Not significant161.1901.041
Not significant170.1051−1.029
Not significant180.53340.9693
Not significant191.1710.6832
Not significant20−2.108−0.1620
Not significant210.29860.5189
Not significant22−0.08600.0468
Not significant23−0.9106−0.9893
Not significant240.19141.194
Not significant251.5800.8963
Not significant260.35270.8152
Not significant271.067−0.1162
Not significant281.3160.7425
Not significant291.5471.006
Not significant302.0390.8118
Not significant31−1.054−0.9663
Not significant32−0.9651−1.285
Not significant330.41300.1298
Not significant34−0.6736−0.7845
Not significant350.2443−0.1226
Not significant36−1.257−0.9887
Not significant370.44180.9580
Not significant381.1220.5147
Not significant39−0.9678−1.145
Not significant40−1.141−0.8499
Not significant41−0.9797−0.8489
Not significant42−1.125−0.9655
Not significant430.09270.0623
Not significant44−0.55350.0373
Not significant45−0.3684−0.1845
Not significant46−1.123−1.113
Not significant47−0.4412−1.060
Not significant48−0.5123−0.3973
Not significant49−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

SitecrimeLocal Moran's IzpAdjusted pPattern
115.7260.73680.9260.408.555Not significant
218.8020.52880.9892.340.521Not significant
330.6270.09390.6917.496.640Not significant
432.3880.00480.0239.988.988Not significant
550.7320.30361.139.224.366Not significant
626.067−0.1816−0.4932.612.769Not significant
70.1783−1.861−1.892.048.147Not significant
838.4260.07661.082.264.417Not significant
930.516−0.0306−0.3602.716.856Not significant
1034.0010.04031.239.212.366Not significant
1162.2751.4582.322.016.087Not significant
1256.7060.63891.407.164.321Not significant
1346.7160.12530.4270.692.848Not significant
1457.0660.61531.327.180.327Not significant
1548.5850.73482.442.016.087Not significant
1654.8391.2393.288.004.065Not significant
1736.869−0.1081−1.872.056.147Not significant
1843.9620.51712.048.036.118Not significant
1954.5220.80001.282.220.366Not significant
200.22380.34140.7336.452.599Not significant
2140.0740.15490.9214.384.549Not significant
2233.705−0.0040−0.1287.896.915Not significant
2320.0490.90081.862.060.147Not significant
2438.2980.22853.370.004.065Not significant
2561.2991.4162.971.008.078Not significant
2640.9700.28752.193.036.118Not significant
2752.794−0.1240−0.1959.828.882Not significant
2856.9200.97702.657.012.087Not significant
2960.7501.5573.011.004.065Not significant
3068.8921.6552.210.024.107Not significant
3117.6771.0181.845.056.147Not significant
3219.1461.2402.762.008.078Not significant
3341.9680.05360.2815.756.861Not significant
3423.9740.52841.702.096.213Not significant
3539.175−0.0300−0.2896.804.880Not significant
3614.3061.2432.366.016.087Not significant
3742.4450.42322.483.024.107Not significant
3853.7110.57751.400.180.327Not significant
3919.1011.1082.176.036.118Not significant
4016.2410.96932.001.032.118Not 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
))
Python

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

SitecrimeLocal Moran's IzpAdjusted pPattern
115.7260.73680.9260.408.555Not significant
218.8020.52880.9892.340.521Not significant
330.6270.09390.6917.496.640Not significant
432.3880.00480.0239.988.988Not significant
550.7320.30361.139.224.366Not significant
626.067−0.1816−0.4932.612.769Not significant
70.1783−1.861−1.892.048.147Not significant
838.4260.07661.082.264.417Not significant
930.516−0.0306−0.3602.716.856Not significant
1034.0010.04031.239.212.366Not significant
1162.2751.4582.322.016.087Not significant
1256.7060.63891.407.164.321Not significant
1346.7160.12530.4270.692.848Not significant
1457.0660.61531.327.180.327Not significant
1548.5850.73482.442.016.087Not significant
1654.8391.2393.288.004.065Not significant
1736.869−0.1081−1.872.056.147Not significant
1843.9620.51712.048.036.118Not significant
1954.5220.80001.282.220.366Not significant
200.22380.34140.7336.452.599Not significant
2140.0740.15490.9214.384.549Not significant
2233.705−0.0040−0.1287.896.915Not significant
2320.0490.90081.862.060.147Not significant
2438.2980.22853.370.004.065Not significant
2561.2991.4162.971.008.078Not significant
2640.9700.28752.193.036.118Not significant
2752.794−0.1240−0.1959.828.882Not significant
2856.9200.97702.657.012.087Not significant
2960.7501.5573.011.004.065Not significant
3068.8921.6552.210.024.107Not significant
3117.6771.0181.845.056.147Not significant
3219.1461.2402.762.008.078Not significant
3341.9680.05360.2815.756.861Not significant
3423.9740.52841.702.096.213Not significant
3539.175−0.0300−0.2896.804.880Not significant
3614.3061.2432.366.016.087Not significant
3742.4450.42322.483.024.107Not significant
3853.7110.57751.400.180.327Not significant
3919.1011.1082.176.036.118Not significant
4016.2410.96932.001.032.118Not 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,
})
05

Why more shuffles can matter

Reflect

A two-sided permutation p-value can't go below 2/(B+1)2/(B+1). With 499 shuffles, that floor is 2/500=0.0042/500 = 0.004.

Benjamini–Hochberg with 49 sites lets the kkth smallest p pass at k×0.05/49k \times 0.05/49. A floor of 0.0040.004 only passes once kk 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?

06

Hot and cold spots

Read

Getis–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.

07

Places that vary

Read

LOSHLOSHFlags 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.

08

Check your understanding

Checkpoint

Check 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

11/49≈0.2211/49 \approx 0.22, 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.

09

Do it in CodeSplash

In the app

Pick 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.

Python
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)
R
p <- c(0.002, 0.004, 0.012, 0.03, 0.2, 0.5)
p.adjust(p, method = "BH")
10

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