Spatial analysis is the cornerstone of Geographic Information Science (GIS). It encompasses a wide family of computational and statistical methods that extract meaning from the location, shape, pattern, and relationship of geographic features. Unlike conventional data analysis, which treats observations as independent, spatial analysis explicitly accounts for the fact that nearby things tend to be more similar (Tobler’s First Law of Geography) and that where something occurs is often as important as what it is.
This notebook is the entry point for Module 03 of GeoLattice. It explains what spatial analysis is, why it matters, and provides a structured overview of every sub-module in this section.
Eight parts take a layer from a measurement to a mapped decision, using geolattice.spatial_analysis.
Spatial Analysis. This notebook, then Vector Data Analysis (overlay, proximity, measurement) and Raster Data Analysis (map algebra, focal statistics, zonal summaries).
Digital Terrain Modeling (DTM). Condition a DEM, derive slope, aspect, curvature, and landforms, and route flow into streams and watersheds.
Spatial Analysis of Multidimensional Raster Data. Manage a time cube, aggregate it, map anomalies, fit a trend, and reduce the cube with principal components.
Multi-Criteria Suitability Modeling (MCSM). Turn criteria into a suitability map with categorical overlay, weighted overlay, and fuzzy membership, then test how much the weights matter.
Spatial Network Analysis. Embed places in a graph, route on OpenStreetMap, build a network from GeoPandas, and map service areas and flows.
Segregation Analysis. Measure how unevenly groups share a city, from a single index to local, multiscale, and inferential tests.
Spatial Causal Inference. Estimate what a county’s outcome would have been if a treatment there, or next door, had been different: confounding, spillovers, effects that vary across the map, and a trial designed for interference.
Capstones
Flood Susceptibility Mapping in the Sylhet Haor Basin, Bangladesh,
Watershed Characterization of the Onondaga Lake Watershed,
Land Suitability for Wheat in Bangladesh,
Landslide Susceptibility of the Central and Southern Rocky Mountains and Western Great Plains, S Habitat Suitability and Landscape Connectivity for the Forest Musk Deer, and
Farmer Information Networks and Technology Diffusion. Six studies that apply the module.
Spatial analysis is the process of examining the locations, attributes, and relationships of features in spatial data to discover patterns, understand phenomena, and make decisions. It integrates principles from geography, mathematics, statistics, and computer science to answer questions such as:
Where are things located, and how do they cluster or disperse?
What is the relationship between spatial features (overlap, adjacency, proximity)?
How do terrain, hydrology, or land cover influence human and ecological processes?
Which areas are most suitable for a specific use?
How does a phenomenon change over space and time?
The term was popularised by geographers and quantitative researchers in the 1960s-70s (most notably by Cliff & Ord on spatial autocorrelation, and later by Anselin on exploratory spatial data analysis) and has since grown into a multidisciplinary field underpinning environmental science, urban planning, public health, logistics, remote sensing, and more.
Branches of Spatial Analysis
Branch
Description
Example
Spatial query & selection
Filter features by location or attributes
All hospitals within 10 km of a flood zone
Measurement
Distance, area, perimeter, shape metrics
Euclidean vs network distance between cities
Overlay analysis
Combine layers to identify intersections
Crop suitability = soil ∩ slope ∩ rainfall
Proximity analysis
Buffers, Voronoi polygons, nearest-neighbour
Service area of a clinic
Terrain / surface analysis
Slope, aspect, hillshade, viewshed
Landslide hazard from DEM
Hydrological analysis
Flow routing, watershed delineation
Catchment area above a dam site
Pattern analysis
Clustering, hotspots, spatial autocorrelation
Disease cluster detection
Network analysis
Routing, accessibility, flow
Shortest evacuation route
Suitability / MCSM
Multi-criteria decision support
Best site for a wind farm
Spatio-temporal analysis
Change detection, trend analysis
NDVI trends from time-series satellite data
Why Spatial Analysis Matters
Location matters in virtually every field of science and applied decision-making:
Python, through libraries such as GeoPandas, Rasterio, xarray, WhiteboxTools, OSMnx, NetworkX, and scikit-fuzzy, has become the dominant open-source platform for spatial analysis. GeoLattice unifies these tools behind a consistent, GIS-practitioner-friendly API organised around the workflows described in this module.
Core Concepts
Before diving into the notebooks, a few foundational concepts are worth reviewing:
Spatial Data Models
Model
Description
Typical Formats
Vector
Discrete objects: points, lines, polygons with attributes
Shapefile, GeoJSON, GeoPackage, FlatGeobuf
Raster
Continuous grid of cells (pixels) with a value per cell
GeoTIFF, NetCDF, HDF5, Cloud-Optimised GeoTIFF
Multidimensional raster
Raster with extra axes: time, depth, wavelength
NetCDF, HDF5, Zarr
Network / Graph
Nodes + edges with spatial embedding
GraphML, OSM, GeoPackage
Coordinate Reference Systems (CRS)
All spatial analysis must occur in a consistent CRS. Key distinctions: - Geographic CRS (lon/lat, e.g., WGS 84 / EPSG:4326): angles, not metres: avoid for distance/area calculations. - Projected CRS (e.g., UTM, BTM): metres/feet: required for accurate distance, area, and slope calculations. - GeoLattice uses pyproj and PROJ under the hood; always check .crs before running analysis.
Tobler’s First Law of Geography
“Everything is related to everything else, but near things are more related than distant things.”
Waldo Tobler, 1970
This principle motivates spatial autocorrelation analysis, kriging, and the spatial weight matrices used throughout this module.
Scale and Resolution
Results depend heavily on the spatial resolution of the input data and the analysis scale (the Modifiable Areal Unit Problem. MAUP). Always document data provenance and resolution.
GeoLattice Spatial Analysis Architecture
The geolattice.spatial_analysis sub-package is structured around six functional domains that map directly to the six sub-modules of this tutorial section:
Each sub-module is designed to be self-contained: you can import and use any part without needing others. Common utilities (CRS handling, plotting styles, data loaders) live in geolattice.utils and geolattice.viz.
Key design principles
Principle
What it means in practice
GeoDataFrame-first
Vector functions accept and return geopandas.GeoDataFrame
Rasterio / xarray bridge
Raster functions work with file paths, rasterio datasets, or xarray.DataArray
WhiteboxTools integration
Terrain and hydrology leverage Whitebox under the hood via a thin GeoLattice wrapper
NetworkX / OSMnx integration
Network functions work with networkx.Graph / MultiDiGraph objects
Reproducible outputs
All functions accept output path arguments and log their Whitebox/GDAL calls
Module Overview
The following sections summarise each sub-module’s scope, key functions, and links to the relevant notebooks.
API module:geolattice.spatial_analysis.vector_analysis (also exported from geolattice.vector)
Vector analysis deals with discrete geographic objects: points, lines, and polygons. GeoLattice provides a rich set of functions that mirror the vector analysis workflows found in desktop GIS tools (QGIS, ArcGIS) but within a fully Python-based, scriptable environment.
API surface:geolattice.raster analysis helpers (reclassify, focal_statistics, zonal_stats, calc, proximity, rasterize)
Raster analysis is the gridded counterpart to vector analysis in this foundation chapter. It covers local reclassification, neighborhood (focal) statistics, zonal summaries by polygon, map algebra for combining criteria, and proximity surfaces. DEM morphometry and hydrology stay in Module 03.02; the Module 02 raster notebook remains the operator reference for clip, mosaic, aggregate, and related I/O tools.
What you will learn
Category
Key functions
Description
Local
reclassify
Assign thematic classes per cell
Neighborhood
focal_statistics
Moving-window mean, range, and related stats
Zonal
zonal_stats
Summarise a raster inside polygons
Map algebra
calc / raster_algebra
Combine rasters cell-by-cell
Proximity
rasterize, proximity
Distance from target features
Study area
Bangladesh hilly-district DEM (hilly_dem_BTM.tiff) with intersecting districts (bd_district_BTM.shp)
API module:geolattice.spatial_analysis.terrain_analysis
Digital Terrain Analysis (DTA) derives information about land surface form from a Digital Elevation Model (DEM). The GeoLattice terrain module wraps WhiteboxTools to provide a comprehensive suite of morphometric and surface derivatives.
Surface hydrology analysis models how water moves and accumulates over a landscape using a DEM. The GeoLattice hydrology module follows the Whitebox Workflows Spatial Hydrology chapter and spans DEM conditioning through to advanced connectivity and impoundment modelling.
Uncertainty in depression filling; reservoir/storage modelling
Study area
Bangladesh hilly-district DEM (~521 × 1,329 cells, 250 m, BTM projection)
Outputs written to Data/00_shared/raster_data/output_folder/bangladesh/hydrology/
Multidimensional Raster Analysis
API module:geolattice.spatial_analysis (multidimensional functions), backed by xarray and netCDF4
While conventional GeoTIFF rasters have two spatial dimensions (rows × columns), many Earth-science datasets are multidimensional: they add axes for time, depth/pressure level, or wavelength. This sub-module teaches you to work with these data cubes, which are increasingly common from climate models, reanalysis products (ERA5), and satellite image time series.
Dimensionality reduction: Principal Component Analysis (PCA) of spatio-temporal fields
Key capabilities
Capability
Description
Data cube construction
Assemble multi-file NetCDF/HDF5 into a single xarray.Dataset
Temporal aggregation
Monthly/seasonal/annual means, maxima, sums via resample and groupby
Anomaly detection
Climatological baselines, z-score standardisation
Trend analysis
Pixel-wise Mann-Kendall significance test and Theil-Sen slope magnitude
PCA / EOF
Extract dominant modes of spatio-temporal variability
Data source
ERA5 reanalysis NetCDF grids (temperature, precipitation, etc.) from Data/00_shared/raster_data/ERA5/
Multi-Criteria Suitability Modeling (MCSM)
API modules:geolattice.spatial_analysis.suitability, geolattice.spatial_analysis.fuzzy
Multi-Criteria Suitability Modeling (MCSM) integrates multiple spatial criteria to identify optimal or suitable locations for a given objective. It is one of the most widely applied decision-support frameworks in GIS: used in site selection, land-use planning, conservation prioritisation, and infrastructure routing.
GeoLattice supports three complementary approaches, each covered by a dedicated notebook series:
Min-max and percentile normalisation, Weighted Linear Combination (WLC), hybrid model, robustness analysis
Case study: Identifying underserved US counties for healthcare facility siting.
Part II: Fuzzy Suitability Modeling
Classical suitability models use crisp Boolean thresholds: a location either meets a criterion or it does not. Fuzzy logic allows partial membership: a slope of 14° might be “somewhat suitable” (membership = 0.7) rather than simply suitable or not. This is more realistic and reduces the sensitivity to arbitrary threshold choices.
API module:geolattice.spatial_analysis.network_analysis
Spatial network analysis studies systems of connected nodes and edges that are embedded in geographic space: road networks, river systems, utility networks, social ties with geographic context. GeoLattice integrates NetworkX, OSMnx, and igraph to provide a comprehensive suite of graph-theoretic and geographic network analysis tools.
The cell below shows the canonical import pattern used across all Module 03 notebooks. Run it to verify your environment is ready.
Installation. This notebook needs installation option 2 (core plus spatial analysis): pip install "geolattice[analysis]". See “Installation options” in the GeoLattice README.
Code
# Display matplotlib figures inline in this Jupyter notebook.%matplotlib inlinefrom pathlib import Path # filesystem paths for locating sample data# The installed package lives in src/; the repository root is its parent.import geolatticeREPO = Path(geolattice.__file__).resolve().parents[1]ifnot (REPO /"Data").is_dir():raiseFileNotFoundError("Could not find the GeoLattice repository root.")print(f"Repo root : {REPO}")print(f"geolattice : {geolattice.__version__}")# Third-party numeric / geospatial stack used across Module 03 notebooks.import numpy as np # array ops for raster and tabular workflowsimport pandas as pd # tabular data frames for attribute summariesimport geopandas as gpd # vector GeoDataFrames (points, lines, polygons)import matplotlib.pyplot as plt # figure and axes creation for mapsimport rasterio # GeoTIFF I/O and raster metadataimport xarray as xr # labeled multidimensional arrays (NetCDF / Zarr)# GeoLattice spatial analysis sub-modules (one per Module 03 topic area).import geolattice.spatial_analysis.vector_analysis as va # 03.01 vector analysis helpersimport geolattice.spatial_analysis.terrain_analysis as ta # 03.02 terrain / DEM helpersimport geolattice.spatial_analysis.surface_hydrology as sh # 03.03 hydrology helpers# Multidimensional helpers are imported from geolattice.spatial_analysis in later notebooks.import geolattice.spatial_analysis.suitability_analysis as su # 03.05 suitability / MCSM helpersimport geolattice.spatial_analysis.network_analysis as sna # 03.06 network analysis helpers# Shared tutorial plotting helpers.from geolattice.viz import plot_layer, apply_map_style # layer maps and consistent styleapply_map_style() # apply the GeoLattice tutorial matplotlib defaultsprint("\nAll GeoLattice spatial analysis modules loaded successfully!") # status lineprint(f" vector_analysis -> {va.__file__}") # confirm which file was importedprint(f" terrain_analysis -> {ta.__file__}")print(f" surface_hydrology -> {sh.__file__}")print(f" suitability -> {su.__file__}")print(f" network_analysis -> {sna.__file__}")
All Module 03 notebooks read from the same data layout under the repository root:
<REPO>/
├── data/
│ ├── vector_data/
│ │ ├── USA/ # US states, counties, cities (Shapefile / GeoPackage)
│ │ └── Bangladesh/ # Districts, upazilas, hilly region boundaries
│ ├── raster_data/
│ │ ├── Bangladesh/ # DEM (hilly_dem_BTM.tiff, 250 m, BTM)
│ │ ├── ERA5/ # ERA5 NetCDF climate grids
│ │ └── output_folder/ # All computed outputs are written here
│ ├── tabular_data/ # CSV / Excel: census, poverty, health statistics
│ └── data_spatial_net/ # Synthetic road network (GraphML, GeoJSON)
└── geolattice/
└── spatial_analysis/ # GeoLattice source code
Code
# Verify that the shared Module 03 sample-data folders exist under REPO.data_dirs = {"Vector (USA)": REPO /"Data"/"00_shared"/"vector_data"/"USA", # US states / counties / cities"Vector (Bangladesh)": REPO /"Data"/"00_shared"/"vector_data"/"Bangladesh", # districts / upazilas"Raster (Bangladesh)": REPO /"Data"/"00_shared"/"raster_data"/"Bangladesh", # DEM tiles"ERA5 NetCDF": REPO /"Data"/"00_shared"/"raster_data"/"ERA5", # climate NetCDF grids"Tabular data": REPO /"Data"/"00_shared"/"tabular_data", # CSV / Excel attributes"Spatial networks": REPO /"Data"/"00_shared"/"data_spatial_net", # GraphML / GeoJSON networks}print("Data directory status:") # section header for the checklistprint("-"*55) # visual separator line# Print one status line per expected data folder.for label, path in data_dirs.items(): status ="OK found"if path.exists() else"MISSING"# existence flag for this folderprint(f" {label:<25}{status} ({path})") # aligned label, status, and full path
Data directory status:
-------------------------------------------------------
Vector (USA) OK found (/home/zia207/Github/GeoLattice/Data/00_shared/vector_data/USA)
Vector (Bangladesh) OK found (/home/zia207/Github/GeoLattice/Data/00_shared/vector_data/Bangladesh)
Raster (Bangladesh) OK found (/home/zia207/Github/GeoLattice/Data/00_shared/raster_data/Bangladesh)
ERA5 NetCDF MISSING (/home/zia207/Github/GeoLattice/Data/00_shared/raster_data/ERA5)
Tabular data OK found (/home/zia207/Github/GeoLattice/Data/00_shared/tabular_data)
Spatial networks OK found (/home/zia207/Github/GeoLattice/Data/00_shared/data_spatial_net)
Suggested Learning Path
The sub-modules are designed to be largely independent, but the following sequences are recommended based on your background and goals:
Path A: GIS Fundamentals Track
(Recommended for learners new to spatial analysis)
Module 03 of GeoLattice provides a complete, practitioner-oriented spatial analysis toolkit structured around six domains:
#
Sub-module
Core Library
Primary Data Model
03.01
Vector Data Analysis
GeoPandas, Shapely
GeoDataFrame (points, lines, polygons)
03.02
Terrain Analysis
WhiteboxTools, Rasterio
GeoTIFF (DEM)
03.03
Hydrology Modeling
WhiteboxTools, Rasterio
GeoTIFF (DEM + derived rasters)
03.04
Multidimensional Raster
xarray, netCDF4, SciPy
xarray.Dataset (NetCDF / Zarr)
03.05
Suitability Modeling
GeoPandas, scikit-fuzzy, SALib
GeoDataFrame + GeoTIFF
03.06
Network Analysis
NetworkX, OSMnx, igraph
Graph / MultiDiGraph + GeoDataFrame
All sub-modules share a consistent design philosophy: GeoDataFrame-first, reproducible, and bridged to best-in-class scientific Python libraries. Together they cover the full breadth of spatial analysis workflows needed in environmental science, planning, logistics, and geographic data science.