CSpatial · spatial.hotspots
Hot spots and local spatial patterns (LISA, Getis–Ord Gi and Gi*, LOSH)
Where on the map are the clusters, hot spots, spatial outliers or unusually variable neighborhoods?
One test per site: local Moran's I finds clusters of like values and spatial outliers, Getis–Ord Gi and Gi* find concentrations of high or low values, and LOSH finds neighborhoods that vary unusually much. With one test per site, false discoveries are the main risk, so the map uses adjusted p-values by default.
A real result
Example “Lisa guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
0 of 36 sites flagged, the Benjamini–Hochberg correction
- Sites flagged
- 0
- Sites tested
- 36
- Smallest adjusted p
- .624
Plots
View data
| Pattern | Adjusted p | Site | Local Moran's I | x |
|---|---|---|---|---|
| Not significant | 0.6366 | 1 | −0.4728 | 0.5206 |
| Not significant | 0.9674 | 2 | 0.0916 | −1.080 |
| Not significant | 0.8664 | 3 | −0.0531 | 0.1392 |
| Not significant | 0.8664 | 4 | 0.0160 | −0.0847 |
| Not significant | 0.6240 | 5 | 0.6046 | −0.6666 |
| Not significant | 0.6573 | 6 | 1.623 | −2.516 |
| Not significant | 0.8664 | 7 | 0.1443 | −0.7351 |
| Not significant | 0.7349 | 8 | 0.4363 | −1.020 |
| Not significant | 0.6240 | 9 | −0.1334 | 0.1136 |
| Not significant | 0.8664 | 10 | −0.1182 | −0.4738 |
| Not significant | 0.8664 | 11 | 0.1044 | −0.4082 |
| Not significant | 0.6240 | 12 | 0.5963 | −0.7304 |
| Not significant | 0.7349 | 13 | 0.1040 | −0.2214 |
| Not significant | 0.6240 | 14 | 0.1419 | −0.2258 |
| Not significant | 0.8664 | 15 | −0.6334 | −2.547 |
| Not significant | 0.6366 | 16 | −0.8240 | 1.347 |
| Not significant | 0.9843 | 17 | −0.0178 | 0.6164 |
| Not significant | 0.7892 | 18 | 0.1170 | 0.2176 |
| Not significant | 0.9009 | 19 | −0.1537 | −0.8047 |
| Not significant | 0.8664 | 20 | 0.1185 | 0.6897 |
| Not significant | 0.9719 | 21 | 0.0122 | −0.3287 |
| Not significant | 0.9719 | 22 | 0.0063 | −0.1647 |
| Not significant | 0.6240 | 23 | −0.8941 | −1.392 |
| Not significant | 0.8664 | 24 | 0.3141 | 1.466 |
| Not significant | 0.8664 | 25 | 0.0172 | 0.0482 |
| Not significant | 0.6240 | 26 | 1.308 | 1.908 |
| Not significant | 0.7657 | 27 | 0.6489 | 1.731 |
| Not significant | 0.6240 | 28 | 0.0581 | 0.0581 |
| Not significant | 0.8664 | 29 | 0.1153 | 0.6453 |
| Not significant | 0.6240 | 30 | 1.929 | 1.726 |
| Not significant | 0.9695 | 31 | −0.0673 | −0.5290 |
| Not significant | 0.8664 | 32 | 0.0783 | 0.1664 |
| Not significant | 0.6240 | 33 | −0.1695 | −0.2547 |
| Not significant | 0.9763 | 34 | 0.0093 | 0.3328 |
| Not significant | 0.6240 | 35 | 0.1554 | 0.1824 |
| Not significant | 0.6240 | 36 | 1.152 | 1.165 |
View data
| Pattern | Site | x (standardized) | Average of neighbors (spatial lag) |
|---|---|---|---|
| Not significant | 1 | 0.5454 | −0.8669 |
| Not significant | 2 | −1.037 | −0.0883 |
| Not significant | 3 | 0.1682 | −0.3159 |
| Not significant | 4 | −0.0533 | −0.2996 |
| Not significant | 5 | −0.6288 | −0.9615 |
| Not significant | 6 | −2.458 | −0.6603 |
| Not significant | 7 | −0.6966 | −0.2072 |
| Not significant | 8 | −0.9784 | −0.4460 |
| Not significant | 9 | 0.1428 | −0.9342 |
| Not significant | 10 | −0.4381 | 0.2697 |
| Not significant | 11 | −0.3732 | −0.2797 |
| Not significant | 12 | −0.6919 | −0.8618 |
| Not significant | 13 | −0.1885 | −0.5516 |
| Not significant | 14 | −0.1928 | −0.7356 |
| Not significant | 15 | −2.488 | 0.2545 |
| Not significant | 16 | 1.363 | −0.6047 |
| Not significant | 17 | 0.6401 | −0.0278 |
| Not significant | 18 | 0.2457 | 0.4761 |
| Not significant | 19 | −0.7654 | 0.2008 |
| Not significant | 20 | 0.7127 | 0.1662 |
| Not significant | 21 | −0.2946 | −0.0414 |
| Not significant | 22 | −0.1324 | −0.0475 |
| Not significant | 23 | −1.346 | 0.6642 |
| Not significant | 24 | 1.480 | 0.2122 |
| Not significant | 25 | 0.0782 | 0.2199 |
| Not significant | 26 | 1.918 | 0.6821 |
| Not significant | 27 | 1.742 | 0.3724 |
| Not significant | 28 | 0.0880 | 0.6596 |
| Not significant | 29 | 0.6687 | 0.1725 |
| Not significant | 30 | 1.737 | 1.110 |
| Not significant | 31 | −0.4926 | 0.1366 |
| Not significant | 32 | 0.1951 | 0.4012 |
| Not significant | 33 | −0.2214 | 0.7657 |
| Not significant | 34 | 0.3596 | 0.0258 |
| Not significant | 35 | 0.2109 | 0.7369 |
| Not significant | 36 | 1.182 | 0.9740 |
Assumptions
- Neighbors chosen for a reason — Neighbors: Rook contiguity, row-standardized (W). Try a second definition as a sensitivity check.
- Many tests corrected — 36 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 | x | Local Moran's I | z | p | Adjusted p | Pattern |
|---|---|---|---|---|---|---|
| 1 | 0.5206 | −0.4728 | −1.210 | .226 | .637 | Not significant |
| 2 | −1.080 | 0.0916 | 0.2108 | .833 | .967 | Not significant |
| 3 | 0.1392 | −0.0531 | −0.5479 | .584 | .866 | Not significant |
| 4 | −0.0847 | 0.0160 | 0.5300 | .596 | .866 | Not significant |
| 5 | −0.6666 | 0.6046 | 1.734 | .083 | .624 | Not significant |
| 6 | −2.516 | 1.623 | 1.137 | .256 | .657 | Not significant |
| 7 | −0.7351 | 0.1443 | 0.4025 | .687 | .866 | Not significant |
| 8 | −1.020 | 0.4363 | 0.9924 | .321 | .735 | Not significant |
| 9 | 0.1136 | −0.1334 | −1.921 | .055 | .624 | Not significant |
| 10 | −0.4738 | −0.1182 | −0.5327 | .594 | .866 | Not significant |
| 11 | −0.4082 | 0.1044 | 0.6008 | .548 | .866 | Not significant |
| 12 | −0.7304 | 0.5963 | 1.563 | .118 | .624 | Not significant |
| 13 | −0.2214 | 0.1040 | 0.9810 | .327 | .735 | Not significant |
| 14 | −0.2258 | 0.1419 | 1.531 | .126 | .624 | Not significant |
| 15 | −2.547 | −0.6334 | −0.4176 | .676 | .866 | Not significant |
| 16 | 1.347 | −0.8240 | −1.201 | .230 | .637 | Not significant |
| 17 | 0.6164 | −0.0178 | −0.0197 | .984 | .984 | Not significant |
| 18 | 0.2176 | 0.1170 | 0.8513 | .395 | .789 | Not significant |
| 19 | −0.8047 | −0.1537 | −0.3176 | .751 | .901 | Not significant |
| 20 | 0.6897 | 0.1185 | 0.3881 | .698 | .866 | Not significant |
| 21 | −0.3287 | 0.0122 | 0.1030 | .918 | .972 | Not significant |
| 22 | −0.1647 | 0.0063 | 0.1060 | .916 | .972 | Not significant |
| 23 | −1.392 | −0.8941 | −1.327 | .184 | .624 | Not significant |
| 24 | 1.466 | 0.3141 | 0.4627 | .644 | .866 | Not significant |
| 25 | 0.0482 | 0.0172 | 0.3910 | .696 | .866 | Not significant |
| 26 | 1.908 | 1.308 | 1.609 | .108 | .624 | Not significant |
| 27 | 1.731 | 0.6489 | 0.9124 | .362 | .766 | Not significant |
| 28 | 0.0581 | 0.0581 | 1.368 | .171 | .624 | Not significant |
| 29 | 0.6453 | 0.1153 | 0.3982 | .690 | .866 | Not significant |
| 30 | 1.726 | 1.929 | 2.136 | .033 | .624 | Not significant |
| 31 | −0.5290 | −0.0673 | −0.1741 | .862 | .970 | Not significant |
| 32 | 0.1664 | 0.0783 | 0.7164 | .474 | .866 | Not significant |
| 33 | −0.2547 | −0.1695 | −1.338 | .181 | .624 | Not significant |
| 34 | 0.3328 | 0.0093 | 0.0637 | .949 | .976 | Not significant |
| 35 | 0.1824 | 0.1554 | 1.309 | .191 | .624 | Not significant |
| 36 | 1.165 | 1.152 | 1.456 | .145 | .624 | Not significant |
- Neighbors: Rook contiguity, row-standardized (W). adjusted with the Benjamini–Hochberg correction.
0 of 36 sites flagged, the Benjamini–Hochberg correction
- Sites flagged
- 0
- Sites tested
- 36
- Smallest adjusted p
- .624
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Neighbors chosen for a reason — Neighbors: Rook contiguity, row-standardized (W). Try a second definition as a sensitivity check.
- Many tests corrected — 36 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 | x | Local Moran's I | z | p | Adjusted p | Pattern |
|---|---|---|---|---|---|---|
| 1 | 0.5206 | −0.4728 | −1.210 | .226 | .637 | Not significant |
| 2 | −1.080 | 0.0916 | 0.2108 | .833 | .967 | Not significant |
| 3 | 0.1392 | −0.0531 | −0.5479 | .584 | .866 | Not significant |
| 4 | −0.0847 | 0.0160 | 0.5300 | .596 | .866 | Not significant |
| 5 | −0.6666 | 0.6046 | 1.734 | .083 | .624 | Not significant |
| 6 | −2.516 | 1.623 | 1.137 | .256 | .657 | Not significant |
| 7 | −0.7351 | 0.1443 | 0.4025 | .687 | .866 | Not significant |
| 8 | −1.020 | 0.4363 | 0.9924 | .321 | .735 | Not significant |
| 9 | 0.1136 | −0.1334 | −1.921 | .055 | .624 | Not significant |
| 10 | −0.4738 | −0.1182 | −0.5327 | .594 | .866 | Not significant |
| 11 | −0.4082 | 0.1044 | 0.6008 | .548 | .866 | Not significant |
| 12 | −0.7304 | 0.5963 | 1.563 | .118 | .624 | Not significant |
| 13 | −0.2214 | 0.1040 | 0.9810 | .327 | .735 | Not significant |
| 14 | −0.2258 | 0.1419 | 1.531 | .126 | .624 | Not significant |
| 15 | −2.547 | −0.6334 | −0.4176 | .676 | .866 | Not significant |
| 16 | 1.347 | −0.8240 | −1.201 | .230 | .637 | Not significant |
| 17 | 0.6164 | −0.0178 | −0.0197 | .984 | .984 | Not significant |
| 18 | 0.2176 | 0.1170 | 0.8513 | .395 | .789 | Not significant |
| 19 | −0.8047 | −0.1537 | −0.3176 | .751 | .901 | Not significant |
| 20 | 0.6897 | 0.1185 | 0.3881 | .698 | .866 | Not significant |
| 21 | −0.3287 | 0.0122 | 0.1030 | .918 | .972 | Not significant |
| 22 | −0.1647 | 0.0063 | 0.1060 | .916 | .972 | Not significant |
| 23 | −1.392 | −0.8941 | −1.327 | .184 | .624 | Not significant |
| 24 | 1.466 | 0.3141 | 0.4627 | .644 | .866 | Not significant |
| 25 | 0.0482 | 0.0172 | 0.3910 | .696 | .866 | Not significant |
| 26 | 1.908 | 1.308 | 1.609 | .108 | .624 | Not significant |
| 27 | 1.731 | 0.6489 | 0.9124 | .362 | .766 | Not significant |
| 28 | 0.0581 | 0.0581 | 1.368 | .171 | .624 | Not significant |
| 29 | 0.6453 | 0.1153 | 0.3982 | .690 | .866 | Not significant |
| 30 | 1.726 | 1.929 | 2.136 | .033 | .624 | Not significant |
| 31 | −0.5290 | −0.0673 | −0.1741 | .862 | .970 | Not significant |
| 32 | 0.1664 | 0.0783 | 0.7164 | .474 | .866 | Not significant |
| 33 | −0.2547 | −0.1695 | −1.338 | .181 | .624 | Not significant |
| 34 | 0.3328 | 0.0093 | 0.0637 | .949 | .976 | Not significant |
| 35 | 0.1824 | 0.1554 | 1.309 | .191 | .624 | Not significant |
| 36 | 1.165 | 1.152 | 1.456 | .145 | .624 | Not significant |
- Neighbors: Rook contiguity, row-standardized (W). adjusted with the Benjamini–Hochberg correction.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Lisa guidesp_grid6 · region: site · y: x
- Lisa totalsp_grid6 · region: site · y: x
- Lisa conditional permutationsp_columbus · region: site · y: crime
- Lisa total permutationsp_columbus · region: site · y: crime
- Gi guidesp_grid6 · region: site · y: x
- Gi star guidesp_grid6 · region: site · y: x
- Gi star permutationsp_nc_sids · region: fips · y: rate
- Gi lonlat knnsp_nc_sids · lat: lat · lon: lon · y: rate
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
What you need
- Variablenumeric · 1 column
- What you measured at each site: a rate, amount or score.
- Regioncategorical / numeric · 0–1 column
- One row per region, with the map layer's feature id (FIPS code, ISO code …). Needs a map layer.
- Longitudenumeric · 0–1 column
- Degrees east, when sites are points instead of regions of a map layer.
- Latitudenumeric · 0–1 column
- Degrees north, when sites are points instead of regions of a map layer.
Choices you make
hypothesis
- Local statisticdefault local_moran
Which local pattern to map.
- Local Moran's I (LISA)(default) — Clusters of like values (high–high, low–low) and spatial outliers (high–low, low–high).
- Getis–Ord Gi* — Hot and cold spots, counting the site's own value with its neighbors.
- Getis–Ord Gi — Hot and cold spots around a site, leaving its own value out.
- LOSH — Where values vary unusually much between neighbors; about variability, not high values.
- Reference distributiondefault permutation
How each site's p-value is calibrated.
- Permutation(default) — Shuffle values across sites; assumes nothing about their distribution.
- Approximation (normal; chi-square for LOSH) — Quick reference distribution; rough for skewed values and few neighbors.
- Shuffledefault conditional
Whether each site's own value stays fixed while the others are shuffled.
- Conditional (hold this site's value fixed)(default) — The usual local reference: shuffle the other values around each site.
- Total (shuffle every value) — Also varies the site's own value; p-values usually differ from the conditional ones.
- Alternativedefault two_sided
The local pattern you expect, stated before testing.
- Either direction(default) — Clusters or outliers; hot or cold spots.
- Higher than chance — Clusters of like values, or hot spots.
- Lower than chance — Spatial outliers, or cold spots.
- Multiple-testing correctiondefault BH
One test per site means many chances of a false alarm.
- False discovery rate (Benjamini–Hochberg)(default) — Controls the share of false discoveries among the flagged sites; the usual choice for maps.
- False discovery rate (Benjamini–Yekutieli) — Valid under any dependence between sites; more cautious.
- Holm — Controls the chance of any false site; strict on large maps.
- Bonferroni — The strictest: each site tested at alpha divided by the number of sites.
- No correction — Raw p-values. Expect about 5% of sites flagged by chance alone.
- Permutationsdefault 999
Shuffles per site; adjusted p-values need many, so raise it on large maps.
- Significance leveldefault 0.05
Sites with an adjusted p below this are flagged on the map.
options
- Deviation powerdefault 2
Power a of the deviations in LOSH: 2 squares them; the chi-square approximation is built for 2.
- Map layerdefault —
Regions to build neighbors from; rows match features through the Region role. Leave empty to use longitude and latitude columns.
- Neighborsdefault queen
Which sites count as neighbors. The host builds the weights once; Python and R read the same file.
- Queen contiguity(default) — Regions sharing any boundary point.
- Rook contiguity — Regions sharing a boundary edge (two or more points).
- k nearest — Each site's k closest sites (not symmetric).
- Distance band — All sites within a distance.
- Inverse distance — Closer sites weigh more: 1 / distance^power.
- Kernel — Weights fall smoothly to zero at a bandwidth.
- Neighbors (k)default 4
How many nearest sites count as neighbors (k nearest), or set the adaptive kernel bandwidth.
- Distance (km)default —
Distance band, inverse-distance cut-off or fixed kernel bandwidth, in km between longitude/latitude sites.
- Kerneldefault triangular
Shape of the decay inside the bandwidth.
- Triangular(default) — 1 − d/h.
- Uniform — Equal weight inside the bandwidth.
- Quadratic (Epanechnikov) — ¾ (1 − (d/h)²).
- Quartic (biweight) — 15/16 (1 − (d/h)²)².
- Gaussian — Normal density of d/h, cut at the bandwidth.
- Adaptive bandwidthdefault off
Each site's bandwidth reaches its k-th nearest site, so dense areas get narrower kernels.
- Weights styledefault W
How weights are scaled (spdep styles). Row-standardized is the usual choice for Moran's I and spatial lags.
- Row-standardized (W)(default) — Each site's weights sum to 1: spatial lags are neighbor averages.
- Binary (B) — 1 for neighbors (raw weights for inverse distance and kernels).
- Global (C) — All weights sum to the number of sites.
- Sum to one (U) — All weights together sum to 1.
- Variance-stabilizing (S) — Tiefelsdorf's style: between W and C for uneven neighbor counts.
- Min–max — Divided by the smaller of the largest row and column sums.
- Sites with no neighborsdefault keep
Islands (e.g. Hawaii with contiguity) have no neighbors; keep them, stop, or join each to its nearest site.
- Keep (no neighbors)(default) — Tests exclude or zero their lag (spdep zero.policy).
- Stop and list them — Fail so you can choose a different neighborhood.
- Join to the nearest site — Add a link to the closest site in both directions.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Neighbors chosen for a reason
The neighbor rule defines each site's neighborhood; try a second definition as a sensitivity check.
Many tests corrected
One test per site; uncorrected maps contain many false discoveries.
Local tests are dependent
Neighboring sites share neighbors, so their tests are correlated; treat flagged sites as leads, not proof.
Regions at a meaningful scale
Clusters can appear or vanish when regions change (the modifiable areal unit problem).
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_tested
- How many independent units the analysis used; it sets precision and power.
- n_flagged
- How many independent units the analysis used; it sets precision and power.
- share_flagged
- Sites whose adjusted p-value is below the significance level. They are leads to investigate, not proof of a local cause.
- n_high_high
- A Moran's I for each site. It flags clusters (high–high, low–low) and spatial outliers (high–low, low–high).
- n_low_low
- A Moran's I for each site. It flags clusters (high–high, low–low) and spatial outliers (high–low, low–high).
- n_high_low
- A Moran's I for each site. It flags clusters (high–high, low–low) and spatial outliers (high–low, low–high).
- n_low_high
- A Moran's I for each site. It flags clusters (high–high, low–low) and spatial outliers (high–low, low–high).
- n_hot
- 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.
- n_cold
- 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.
- sum_statistic
- Sites whose adjusted p-value is below the significance level. They are leads to investigate, not proof of a local cause.
- sum_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- sum_p_adj
- Sites whose adjusted p-value is below the significance level. They are leads to investigate, not proof of a local cause.
- max_statistic
- Sites whose adjusted p-value is below the significance level. They are leads to investigate, not proof of a local cause.
- min_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- min_p_adj
- Sites whose adjusted p-value is below the significance level. They are leads to investigate, not proof of a local cause.
- links
- Who counts as whose neighbor, and how much. They define the spatial question a test answers.
- islands
- Sites with no neighbors under the chosen rule, such as Hawaii with contiguity.
- n_perm
- How many independent units the analysis used; it sets precision and power.
- h1
- Flags neighborhoods whose values vary unusually much. It is about variability, not about high values.
- h2
- Flags neighborhoods whose values vary unusually much. It is about variability, not about high values.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
- adjust_label
- The correction applied across sites before flagging hot and cold spots, e.g. Benjamini–Hochberg.
- statistic_label
- The local statistic computed at each site, e.g. Getis–Ord Gi* or local Moran's I.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, jsonlite, codesplashr.
Default traps between the two languages
- Both engines read the host's weights and share one Wichmann–Hill matrix of draws per run, the conditional randomization of Anselin (1995), so statistics and permutation p-values match. spdep's localmoran_perm draws separately per site with R's generator, so its permutation p differs by Monte Carlo error; analytic moments, Gi, Gi* and LOSH match spdep to 1e-9.
- spdep names the LOSH chi-square statistic Z.Hi; the card's z is (Hi − 1) / sd(Hi) and its chi-square column is spdep's Z.Hi.
The exact script CodeSplash ran for example “Lisa guide” · 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 4a98d78f815c3169
# Dataset: sp_grid6 (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_grid6.parquet", columns=["x", "site"])
n_input = len(df)
df["site"] = pd.Categorical(df["site"], categories=sorted(df["site"].dropna().unique()))
df = df.dropna(subset=["x", "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, ["x", "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-guide/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 = "x"
statistic = "local_moran" # local_moran | gi_star | gi | losh
calibration = "normal" # 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(999)
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_grid6"})]
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,
})
The exact script CodeSplash ran for example “Lisa guide” · 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 4a98d78f815c3169
# Dataset: sp_grid6 (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_grid6.parquet", col_select = c("x", "site")))
n_input <- nrow(df)
df[["site"]] <- factor(df[["site"]], levels = sort(unique(df[["site"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("x", "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("x", "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-guide/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 <- "x"
statistic <- "local_moran" # local_moran | gi_star | gi | losh
calibration <- "normal" # 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(999)
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_grid6")))
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
))
Sources
- Anselin, L. (1995). Local indicators of spatial association — LISA. Geographical Analysis, 27, 93–115.
- Sokal, R. R., Oden, N. L., & Thomson, B. A. (1998). Local spatial autocorrelation in a biological model. Geographical Analysis, 30, 331–354.
- Getis, A., & Ord, J. K. (1992). The analysis of spatial association by use of distance statistics. Geographical Analysis, 24, 189–206.
- Ord, J. K., & Getis, A. (1995). Local spatial autocorrelation statistics. Geographical Analysis, 27, 286–306.
- Ord, J. K., & Getis, A. (2012). Local spatial heteroscedasticity (LOSH). The Annals of Regional Science, 48, 529–539.
- Caldas de Castro, M., & Singer, B. H. (2006). Controlling the false discovery rate. Geographical Analysis, 38, 180–208.
From the CodeSplash method registry · spatial.hotspots v1.0.3.