Spatial Statistics with GeoLattice tutorial banner

Spatial statistics asks whether a pattern on a map is real. Are cases of a disease closer together than chance would put them? Are high values next to high values? Does a relationship hold everywhere, or change from place to place? Which counties are hot spots, and how stable is a rate based on a few hundred people? Each method in this chapter replaces a visual impression with a model, a test and a measure of uncertainty that respects the fact that nearby places are alike.

These 77 notebooks are chapter 04 of the GeoLattice tutorials. They cover point patterns, spatial autocorrelation, spatial regression, clustering, disease mapping, geographically weighted models, interpolation, sampling design and space-time analysis, and finish with five capstone projects, using geolattice.spatial_statistics with real data from the United States.

GeoLattice

GeoLattice is a Python library for geospatial analysis that brings vector and raster processing, spatial analysis, spatial statistics, geostatistics, spatial databases, web and cloud GIS and remote sensing together under one import. It is built on GDAL, NumPy, pandas, GeoPandas, Shapely and xarray, so its functions take and return objects these libraries already use: GeoDataFrames, NumPy arrays and GDAL-readable files.

Package geolattice
Repository github.com/zia207/GeoLattice
Python 3.10 or newer
License MIT
Author Zia Ahmed, Upatta Analytics

GDAL and PROJ must be installed first, with Python GDAL bindings that match the GDAL library (conda or your system package manager). Then install the spatial statistics option:

python3 -m pip install "geolattice[statistics]"

geolattice.spatial_statistics is organised in subpackages. Import the package, or import names from a subpackage:

import geolattice.spatial_statistics as sstat
from geolattice.spatial_statistics.weights import KNN, Queen
from geolattice.spatial_statistics.esda import Moran, Moran_Local

Spatial weights and autocorrelation

Every spatial test starts by saying who is a neighbour of whom. A spatial weights matrix records that: polygons that share an edge or a corner, the k nearest points, everything within a distance, or the edges of a graph. Autocorrelation statistics then ask whether neighbours are more alike than chance, for the whole map (global) or around each place (local).

Task Functions
Contiguity weights (weights) Queen, Rook, higher_order
Distance and graph weights (weights) KNN, DistanceBand, Kernel, Delaunay, Gabriel, RelativeNeighborhood
Global autocorrelation (esda) Moran, Geary, GeneralG, Join_Counts, MoranBV, Moran_Diff
Local autocorrelation (esda) Moran_Local, Geary_Local, G_Local, Moran_Local_BV
Inference (esda) conditional_permutation, fdr_bh
Maps (viz) choropleth, moran_scatter, lisa_cluster_map

Point patterns

A point pattern is a set of event locations, such as crimes, trees or disease cases, inside a study window. First-order analysis estimates how intensity varies over the window; second-order analysis asks whether points attract or repel each other at a given distance, compared with complete spatial randomness (CSR).

Task Functions (pointpattern)
Points and windows PointPattern, Window
Intensity quadrat_test, kde, bandwidth_scott, bandwidth_cv, relative_risk
Distance functions clark_evans, g_function, f_function, j_function
Second-order functions ripley_k, ripley_l, pair_correlation, cross_k, k_inhom
Simulation and envelopes simulate_csr, simulate_thomas, simulate_matern_inhibition, envelope

Spatial regression

Ordinary least squares assumes the errors are independent, which spatial data rarely allow. Diagnostics on the OLS residuals, especially the Lagrange multiplier tests, say whether the dependence belongs in the outcome (a spatial lag model) or in the errors (a spatial error model).

Task Functions (regression)
Baseline and diagnostics OLS, moran_residuals, jarque_bera, breusch_pagan, condition_number
Model selection lm_tests
Spatial models SpatialLag, SpatialError, SpatialDurbin, SLX
Comparison lr_test, compare_models

The Georgia data bundled with the package (159 county centroids) runs this whole workflow:

import geolattice.spatial_statistics as sstat
from geolattice.spatial_statistics.weights import KNN
from geolattice.spatial_statistics.esda import Moran, Moran_Local
from geolattice.spatial_statistics.regression import OLS, lm_tests, SpatialLag
from geolattice.spatial_statistics.gwmodel import GWR

georgia, predictors, response = sstat.datasets.load_georgia()   # 159 county centroids
w = KNN(georgia, k=6)                                             # 6 nearest counties

print(Moran(georgia["PctBach"], w, seed=0))                       # global autocorrelation
lisa = Moran_Local(georgia["PctBach"], w, seed=0)                 # local clusters (LISA)

X = georgia[["PctRural", "PctPov", "PctBlack"]]
ols = OLS(georgia["PctBach"], X, w=w)                             # baseline model
print(lm_tests(ols, w))                                           # lag or error?
print(SpatialLag(georgia["PctBach"], X, w))                       # spatial lag model
gwr = GWR().fit(X, georgia["PctBach"], georgia.geometry)          # local coefficients

Clusters and disease mapping

Cluster methods find where values or events concentrate: hot and cold spots of a measured value, dense groups of points, circles that hold more cases than their population predicts, or regions of similar, contiguous areas. Disease mapping deals with the rates behind those maps: in small populations a raw rate is noisy, so empirical Bayes and Bayesian (BYM) models borrow strength from the rest of the map and from neighbours.

Task Functions
Hot spots (cluster) getis_ord_gi, local_moran_clusters, adjust_pvalues
Point and case clusters (cluster) dbscan_clusters, hdbscan_clusters, k_distance, spatial_scan
Regionalisation (cluster) skater, agglomerative, evaluate_regions, partition_agreement, flag_stability
Raw rates (bayes) expected_counts, smr, smr_confidence_interval, excess_pvalue, funnel_limits
Smoothing (bayes) eb_gamma_poisson, eb_james_stein, eb_local, BYM, icar_structure
Checks (bayes) rhat, ess, shrinkage_summary, evaluate_smoothing

Geographically weighted models

A global regression gives one coefficient for the whole map. Geographically weighted models fit a separate, distance-weighted model around every location, so each coefficient becomes a surface. The bandwidth sets how local “local” is.

Task Functions (gwmodel)
Local statistics GWSS
Local regression GWR, MGWR, GWGLM
Space and time GTWR, GTNNWR
Machine learning and deep models GWRandomForest, GWXGBoost, GWLightGBM, GNNWR
Other variants GWPCA, NetworkGWR
Compute set_compute_options, get_compute_config

Interpolation and sampling design

Interpolation predicts a surface from samples, either with deterministic rules (nearest neighbour, inverse distance, splines) or with kriging, and moves counts between incompatible zones (areal interpolation). Sampling design works the other way: it decides where to take the samples so that estimates are unbiased and precise.

Task Functions
Deterministic surfaces (interpolate) NearestNeighbor, Thiessen, TIN, IDW, RBF, Spline, ThinPlateSpline, TrendSurface
Kriging (interpolate) empirical_variogram, fit_variogram_auto, OrdinaryKriging, UniversalKriging, RegressionKriging
Areal interpolation (interpolate) areal_weighting, dasymetric
Validation (interpolate) cross_validate, grid_search, compare_methods
Designs (sampling) simple_random, systematic, stratified, two_stage, grts, space_filling, clhs
Estimation and evaluation (sampling) estimate_mean, local_mean_variance, design_effect, spatial_balance, compare_designs

Space-time analysis

Space-time data add a second axis: the same counties every year, or crimes with a time stamp. The space-time notebooks combine the tools above: Moran’s I per year and on the change between years (Moran_Diff), Gi* per year with a trend test for emerging hot spots, kernel density by time slice, space-time variograms and IDW, and GTWR.

Tutorials

Start with the foundation notebooks and spatial autocorrelation, since the weights and tests introduced there are used everywhere else. The other topics can be read in any order, and the capstones combine them.

Foundation

Tutorial Topic
Spatial Statistics What spatial statistics is and the questions it answers
Core Theoretical Concepts Spatial dependence, data types, stationarity, MAUP, CSR, weights
Module Map and Learning Paths The spatial_statistics API and suggested learning paths

Point Pattern Analysis

Tutorial Topic
Point Pattern Analysis Point processes, windows and marks on Buffalo crime data
Spatial Intensity Quadrats, kernel density, bandwidths and relative risk
Second-order Functions Clark-Evans, G, F, J, Ripley’s K and L, pair correlation
Hypothesis Testing Monte Carlo envelopes, inhomogeneous K and cross-K
Areal Integration and Pitfalls Aggregating points to areas, counts vs rates, MAUP

Spatial Autocorrelation

Tutorial Topic
Spatial Autocorrelation Spatial dependence, heterogeneity and scale
Spatial Weights Contiguity, distance and graph weights, higher orders
Visualisation and Exploration Choropleth classes and the Moran scatterplot
Global Autocorrelation Moran’s I, Geary’s C, General G, join counts, bivariate
Local Spatial Autocorrelation (LISA) Local Moran, permutation inference, LISA maps, Gi*
Sensitivity and Pitfalls How weights, permutations and seeds change results

Spatial Regression

Tutorial Topic
Spatial Regression Why OLS fails on spatial data, model taxonomy
OLS Baseline and Diagnostics OLS fit, classical diagnostics, residual Moran’s I
Model Selection Lagrange multiplier tests and Anselin’s decision rule
Model Families Spatial lag, spatial error, SLX and Durbin models
Comparison and Reporting Side-by-side comparison, likelihood-ratio tests, reporting
Limits and Connections Global models and the bridge to local regression
Exercises A code skeleton to adapt

Spatial Clustering

Tutorial Topic
Spatial Cluster Analysis Four families of cluster methods on the same data
Hot-Spot Detection Getis-Ord Gi*, local Moran and local Geary
Density-Based Clustering k-distance plots, DBSCAN and HDBSCAN
Spatial Scan Statistic Kulldorff scan statistic for clusters of cases
Regionalisation SKATER and constrained agglomerative clustering
Comparing and Validating Agreement between methods and regionalisations
Bridges Toward emerging hot spots and population-adjusted risk
Exercises Practice with cluster methods

Disease Mapping

Tutorial Topic
Disease Mapping What disease mapping does and a first look
The Small-Area Problem Poisson variability, funnel plots, unstable rankings
Data Preparation Observed and expected counts, weights for ICAR
Raw Estimates Crude rates, SMR, exact intervals, excess p-values
Empirical Bayes Smoothing Gamma-Poisson, James-Stein and local empirical Bayes
BYM and BYM2 Models BYM and BYM2 with and without covariates
MCMC Implementation Built-in sampler, PyMC backend, convergence, DIC
Comparing Smoothing Methods Raw vs smoothed maps, evaluation against a known truth
Shrinkage Assessment How much each area moved and why
Reporting and Ethics Uncertainty, small-cell suppression, ecological fallacy
Hand-offs and Exercises Links to GW models and space-time analysis

Geographically Weighted Models

Tutorial Topic
Geographically Weighted Models Non-stationarity and bandwidth as a spatial scale
Data The diabetes_atlantic data and the space-time panel
Kernels and Bandwidths Kernel functions, fixed vs adaptive, bandwidth search
GWSS Local means, spread and correlation
GWR and Inference Local coefficients, significance, local R², prediction
Advanced Variants MGWR, mixed GWR and GWGLM
Diagnostics Residual autocorrelation, non-stationarity tests, collinearity
Comparing Models Global, spatial and local models on the same data
Machine-Learning GW Models GW random forest, XGBoost and LightGBM, spatial CV
Spatio-Temporal and Multivariate GTWR and GWPCA
Deep and Network Models GNNWR, GTNNWR and NetworkGWR
Performance and Scaling Compute options, fit times, GPUs
Model Selection and Troubleshooting Choosing a model and four failure modes
Exercises Practice with GW models

Spatial Interpolation

Tutorial Topic
Spatial Interpolation Fields, exact vs smoothing interpolators, uncertainty
Data and Preparation California PM2.5 site means and a prediction grid
Deterministic Interpolation Trend surface, Thiessen, nearest, TIN, IDW, splines
Model Validation Leave-one-out vs spatial-block CV, tuning IDW
Covariate-Assisted Interpolation GWR and regression kriging with covariates
Areal Interpolation Area weighting and dasymetric interpolation
Exercises Practice with interpolation

Spatial Sampling Design

Tutorial Topic
Spatial Sampling and Design Design- vs model-based inference, balance, design effect
Sampling Designs Classical, stratified, cluster, GRTS, space-filling, cLHS
Estimation and Variance Estimator variance by design, 800 simulated replicates
Monitoring-Network Design Evaluating and extending a monitoring network
Exercises Practice with sampling designs

Spatio-Temporal Analysis

Tutorial Topic
Spatio-Temporal Analysis The space-time cube, county panel and crime points
Space-Time Weights Moran’s I by year, Moran_Diff, the Knox test
Local and Emerging Hot Spots Yearly Gi*, Mann-Kendall trends, emerging hot spots
Space-Time Point Patterns Kernel density by time-of-day slice
Space-Time Interpolation Space-time variogram and space-time IDW
Regression with Space-Time Data Pooled OLS, two-way fixed effects and GTWR

Capstone Projects

Tutorial Topic
Health Disparities Health outcomes and deprivation across US counties
Voting Patterns, 2020 vs 2024 Presidential voting, 2020 vs 2024: persistence and shift
Drug Overdose Mortality Overdose mortality, rates vs modelled rates, GW models
Crime in NYC Precincts Hot spots and predictors of crime across NYC precincts
Economic Deprivation An economic deprivation index and its hot spots

Quick reference

Spatial statistics quick reference for geolattice.spatial_statistics

Sample data

The notebooks read the sample data in Data/00_shared/data_spatial_stat/ of the repository: Buffalo crime incidents and city boundaries, US, Atlantic and Northeast county layers with health indicators, California PM2.5 monitors, NYC precinct crime data, and the datasets bundled with the package (sstat.datasets).

License

GeoLattice is released under the MIT License. See LICENSE.


Developed by Zia Ahmed, Upatta Analytics

Back to top