Kulldorff’s Poisson scan statistic, its population adjustment, a real key-mismatch data hazard, and calibration/power studies. This notebook is Part 4. Spatial Cluster Analysis (Chapter 4.4 of 8). The worked example uses diabetes_northeast.shp (Dia_count, POP_Total); cancer_areas.shp + cancer_points.csv (217 counties, cases derived from rate). The methods come from geolattice.spatial_statistics.cluster.
Overview
Chapter 4.2’s Gi* asks whether a value (like a prevalence percentage) clusters spatially. The spatial scan statistic asks a related but genuinely different question: do the raw case counts in some region exceed what the population living there would lead you to expect? A county with a modest diabetes prevalence but a huge population can contribute more excess cases than a small county with a much higher rate: the scan statistic is built around that distinction directly.
Step
What we do
Theory
Kulldorff’s circular-window, Poisson-likelihood-ratio scan, and why its Monte Carlo p-value already accounts for having searched everywhere
Primary example
Diabetes cases vs. county population on the Northeast
Contrast
Scan statistic vs. Gi* on the same region: population-adjusted cases vs. a value field
Secondary example
Cancer incidence, where cases must be derived from a rate: including a real, concrete data-key hazard
Calibration
A Monte Carlo check that the false-positive rate matches its nominal level
Power
Planting a known cluster and checking how reliably the method recovers it
API overview
- Queen
- spatial_scan, getis_ord_gi
Setup
Locate the repository root, import the spatial-statistics helpers, and point DATA at the example files.
Installation. This notebook needs installation option 3 (core, spatial analysis and spatial statistics): pip install "geolattice[statistics]". See “Installation options” in the GeoLattice README.
Code
import sysimport timefrom pathlib import Pathimport numpy as npimport pandas as pdimport geopandas as gpdimport matplotlib.pyplot as pltROOT = Path.cwd().resolve()for candidate in [ROOT, *ROOT.parents]:if (candidate /"pyproject.toml").is_file() and (candidate /"Data").is_dir(): ROOT = candidatebreakelse:raiseFileNotFoundError("Could not find the GeoLattice repository root.")sys.path.insert(0, str(ROOT))DATA = ROOT /"Data"/"00_shared"/"data_spatial_stat"import geolattice.spatial_statisticsfrom geolattice.viz import apply_map_stylefrom geolattice.spatial_statistics.weights import Queenfrom geolattice.spatial_statistics.cluster import spatial_scan, getis_ord_giapply_map_style()C = {"blue": "#2b6cb0", "red": "#c0392b", "green": "#2f855a", "orange": "#dd6b20","grey": "#718096", "purple": "#6b46c1", "teal": "#2c7a7b"}counties = gpd.read_file(DATA /"diabetes_northeast.shp")print(f"geolattice.spatial_statistics : version {geolattice.spatial_statistics.__version__}")
geolattice.spatial_statistics : version 0.3.49
The Kulldorff Scan Statistic
Circular windows are grown, one location at a time, centred on every area’s centroid. For a window with observed cases \(c\) and expected cases \(e\) (out of totals \(C\), \(E\)), the Poisson log-likelihood ratio of “risk differs inside vs. outside” is
\[
\text{LLR} = c\ln\!\frac{c}{e} + (C-c)\ln\!\frac{C-c}{C-e}, \qquad \text{evaluated only when } c > e
\text{ (for high-risk clusters)}.
\]
The window with the largest LLR over every centre and every radius is the most likely cluster. Significance comes from Monte Carlo: cases are redrawn under the null (proportional to expected counts, total fixed) and the maximum LLR over the entire search is recorded each time: so the reported p-value already accounts for having tried every window everywhere, not just the one that happened to look best. Further non-overlapping windows are reported as secondary clusters, tested against the same null distribution.
Primary Example: Diabetes Cases on the Northeast
spatial_scan needs case counts and either raw population or pre-computed expected counts.
Three clusters reported, all significant at \(p \le 0.039\). The most likely cluster (row 0) spans 95 counties with a relative risk of about 1.15: a broad, population-heavy region with modestly elevated prevalence; a smaller, more concentrated secondary cluster (row 2, 9 counties) may have a different, more extreme relative risk. Compare rr across the three rows directly:
Contrast with Gi*: Population-Adjusted vs. Value-Based
Gi* (Chapter 4.2) and the scan statistic can disagree, because they adjust for fundamentally different things.
Code
w = Queen(counties)gi_star = getis_ord_gi(counties["Dia_pct"], w, star=True, inference="analytic", correction="fdr")print(f"Gi* on Dia_pct (rate) : {gi_star.hot.sum()} hot, {gi_star.cold.sum()} cold")print(f"Scan on Dia_count (cases) : {int(scan.clusters['significant'].sum())} significant clusters, "f"covering {sum(len(m) for m, sig inzip(scan.members, scan.clusters['significant']) if sig)} counties")
Gi* on Dia_pct (rate) : 7 hot, 3 cold
Scan on Dia_count (cases) : 3 significant clusters, covering 107 counties
Gi* works from the rateDia_pct directly: it does not know or care how many people that rate applies to. The scan statistic works from raw counts relative to population: a large county with an unremarkable rate can still anchor a scan cluster if its sheer population means it contributes many excess cases in absolute terms. Neither is more “correct”: Gi* is the right tool for “is this rate unusually high here”, the scan statistic for “is the disease burden, the actual number of affected people, concentrated here more than population size explains”.
Secondary Example: Deriving Cases from a Rate
cancer_areas.shp provides only a rate (98-192, presumably per 100,000, age-adjusted: the source data does not state this explicitly, and that ambiguity should be flagged in any real report using it). To use the scan statistic, case counts must be derived: \(\text{cases} = \text{rate} \times \text{population} / 100{,}000\), with population summed from cancer_points.csv (individual population-weighted points) by county.
Code
cancer_areas = gpd.read_file(DATA /"cancer_areas.shp")cancer_points = pd.read_csv(DATA /"cancer_points.csv")print(f"cancer_areas : {len(cancer_areas)} counties, rate range [{cancer_areas['rate'].min()}, "f"{cancer_areas['rate'].max()}]")print(f"cancer_points : {len(cancer_points)} population points, "f"{cancer_points['FIPS'].isna().sum()} ({cancer_points['FIPS'].isna().mean():.1%}) with no FIPS match")
cancer_areas : 217 counties, rate range [98.1, 192.2]
cancer_points : 5419 population points, 459 (8.5%) with no FIPS match
The FIPS key-mismatch hazard
cancer_areas.FIPS is stored as an integer; cancer_points.FIPS is stored as a float (with some missing values). A numeric merge works fine, pandas casts across the two automatically, but building string keys from each column independently, a common next step when joining to yet other data sources, silently fails:
Code
areas_str = cancer_areas["FIPS"].astype(str)points_str = cancer_points["FIPS"].astype(str)print("cancer_areas FIPS as string (sample):", areas_str.head(3).tolist())print("cancer_points FIPS as string (sample):", points_str.head(3).tolist())print(f"string-key overlap: {len(set(areas_str) &set(points_str))} of {areas_str.nunique()} areas")
cancer_areas FIPS as string (sample): ['25019', '36121', '33001']
cancer_points FIPS as string (sample): ['42049.0', '42049.0', '42039.0']
string-key overlap: 0 of 217 areas
Zero matches: '25019' against '25019.0', differing only in a trailing .0 that the float dtype introduces. The fix is a canonical, zero-padded 5-digit string key built the same way on both sides, with the missing-FIPS points dropped before summing population (they cannot be attributed to any county):
Every result from this point on is downstream of the assumption that rate means “cases per 100,000 population”: an assumption this dataset does not confirm and that should be stated explicitly whenever this derivation is reused, exactly as flagged above.
Null Calibration: the False-Positive Rate
Does the scan statistic’s reported significance actually mean what it claims? Simulate case counts under the null (proportional to population, no real cluster) many times, and check how often a “significant” cluster is (falsely) reported at \(\alpha=0.05\).
Code
pop = counties["POP_Total"].to_numpy()rng = np.random.default_rng(0)n_reps =150false_positives =0t0 = time.time()for i inrange(n_reps): expected_null = pop / pop.sum() *50_000 cases_null = rng.poisson(expected_null) res = spatial_scan(coords, cases_null, population=pop, permutations=199, seed=i, n_clusters=1)iflen(res.clusters) and res.clusters.iloc[0]["significant"]: false_positives +=1print(f"{n_reps} null replicates, {time.time() - t0:.0f}s")print(f"false-positive rate: {false_positives / n_reps:.1%} (nominal alpha = 5%)")
About 5%: right at the nominal level, exactly as a correctly calibrated test should behave. This confirms the Monte Carlo p-value’s claim: even though the scan statistic searches over an enormous number of overlapping windows, comparing the observed maximum LLR to the null distribution of the maximum LLR (not to a per-window threshold) keeps the overall false-positive rate at its nominal level rather than inflating it with repeated testing.
Statistical Power: Recovering a Planted Cluster
Calibration confirms the test does not over-reject; power asks whether it reliably detects a real signal. Plant a 15-county cluster with 60% elevated risk (relative risk 1.6) and check recovery across repeated simulations.
planted cluster: 15 counties around index 100, true relative risk = 1.6
30 replicates, 6s
detection rate: 100%
mean planted counties recovered: 15.0 of 15
mean spurious (non-planted) members: 0.23
100% detection, with the recovered cluster containing nearly all 15 planted counties and almost no spurious members: a relative risk of 1.6 spread over 15 contiguous counties is well within this method’s detection range at this sample size. Together, Sections 7 and 8 are the standard pair of checks any detection method should pass before being trusted on real data: does it stay quiet when nothing is there, and does it reliably speak up when something is?
Summary and Conclusions
This chapter built and validated the population-adjusted alternative to Chapter 4.2’s value-based hot-spot tools.
What we did
Explained the Kulldorff Poisson scan statistic and why its Monte Carlo p-value already accounts for searching over every window.
Ran the primary example (Dia_count vs. POP_Total): three significant clusters at different scales and relative risks.
Contrasted the scan statistic against Gi*: population-adjusted case excess vs. a raw rate field: genuinely different questions that can and do disagree.
Worked the secondary cancer-rate example end to end, including deriving case counts from a rate and population, and demonstrated a real, reproducible data hazard: string keys built independently from an int and a float FIPS column have zero overlap, fixed with a canonical zero-padded key.
Ran a 150-replicate null calibration: false-positive rate ≈5%, matching the nominal level.
Ran a 30-replicate power study with a planted RR=1.6, 15-county cluster: 100% detection, near-complete recovery, minimal spurious membership.
Practical takeaways
Never build a merge key by casting each side to string independently when the source dtypes differ (int vs. float, in particular): always normalise to a common canonical form first.
State explicitly what a derived rate is assumed to mean (per what population base, age-adjusted or not), every downstream number inherits that assumption.
A calibration and a power check, even at a reduced replicate count, are worth running on any new detection method before trusting its p-values on the real question.
Next steps
Chapter 4.5 (Regionalisation) turns from detecting existing clusters to constructing new, internally homogeneous, spatially contiguous regions: a genuinely different task from anything in this chapter or Chapter 4.2.
Further reading
Textbooks
Reference
Notes
Kulldorff, M. (1997). A spatial scan statistic. Communications in Statistics: Theory and Methods, 26, 1481-1496.
The original scan statistic
Waller, L. A. & Gotway, C. A. (2004). Applied Spatial Statistics for Public Health Data. Wiley.
Broad treatment of disease-cluster detection, including the scan statistic
Key papers
Paper
Contribution
Kulldorff, M. & Nagarwalla, N. (1995). Spatial disease clusters: detection and inference. Statistics in Medicine, 14, 799-810.
Statistical foundations and inference for spatial scan statistics
Kulldorff, M. et al. (2003). A space-time permutation scan statistic for disease outbreak detection. PLOS Medicine, 2(3), e59.