GeoStride
GeoStride is a lightweight, pure-Python / NumPy & Pandas library for geospatial feature engineering, spatial autocorrelation, spatial clustering, and discrete spatial indexing.
Built directly on numpy, pandas, and scipy, GeoStride provides a focused, deployment-friendly suite of vectorized geospatial utilities with zero external C/C++ build requirements.
Design Philosophy & Ecosystem Positioning
GeoStride is designed to complement—not replace—the mature Python geospatial ecosystem. Choosing the right tool depends on your project's architectural requirements:
Complementary Ecosystems
- The Standard GIS Stack (
GeoPandas,Shapely,PySAL): The gold standard for comprehensive GIS workflows. Ideal when your project requires complex Coordinate Reference System (CRS) transformations, Shapefile/GeoPackage disk formats, satellite raster processing, or deep spatial econometric regression. - GeoStride: A focused, dependency-light toolkit tailored for serverless environments (AWS Lambda, Google Cloud Functions), Docker microservices, edge/IoT devices, and Scikit-Learn ML pipelines. It unifies core spatial operations—spatial lags, spatial autocorrelation (Moran's $I$, Getis-Ord $G_i^*$), trajectory kinematics, and self-contained Leaflet exports—into a single, compact package with instant installation.
When to Use What
| Project Requirement | Recommended Tool | Rationale |
|---|---|---|
| Full GIS & Multi-CRS Workflows | GeoPandas + PyProj |
Native support for arbitrary map projections, PostGIS, and Shapefiles. |
| Serverless & Edge Deployments | GeoStride |
Minimal footprint (< 2 MB), zero C-extension conflicts, fast Lambda cold starts. |
| Spatial Machine Learning Features | GeoStride |
Native Scikit-Learn transformers (SpatialLagTransformer, SpatialKFold), Morton indexing. |
| GPS Trajectory & Mobility Analytics | GeoStride |
Built-in kinematics (speed, forward azimuth, turns, acceleration) and Douglas-Peucker reduction. |
| Advanced Spatial Econometric Models | PySAL (spreg) |
Comprehensive spatial two-stage least squares and spatial error/lag regression models. |
Key Features
- Geodetic & Planar Metrics:
- Vectorized Haversine distance matrix computation.
- High-precision Vincenty inverse ellipsoidal geodesic formula.
- Manhattan spatial grid distance, cross-track, and along-track calculations.
- Discrete Spatial Indexing & Hashing:
- Fast bitwise Geohash encoding/decoding and neighbor lookups.
- Morton (Z-order) space-filling curve indexer.
- Discrete hexagonal and rectangular spatial grid binning.
- Spatial Feature Engineering:
- Spatial lag calculation using K-Nearest Neighbors ($k$-NN) and Inverse Distance Weighting (IDW).
- Point-of-Interest (POI) distance surfaces and radius density count estimators.
- Scikit-Learn compatible transformer pipeline (
SpatialLagTransformer).
- Spatial Autocorrelation & Statistics:
- Spatial weight matrix generators ($k$-NN, distance-band, contiguous).
- Global Moran's $I$ and Local Moran's $I$ (LISA) with Monte Carlo permutation inference.
- Getis-Ord $G_i$ and $G_i^*$ hot-spot and cold-spot statistics.
- Spatial Clustering & Outliers:
- BallTree-accelerated spatial DBSCAN with geographic radian conversion.
- Spatial outlier diagnostics and cluster boundary summarizers.
- I/O & Standalone Visualization:
- Lightweight GeoJSON serialization/deserialization for Pandas DataFrames.
- Self-contained interactive Leaflet HTML map exports without requiring a server.
Installation
pip install geostride
For development and testing:
git clone https://github.com/Rohan-Dedhia/geostride.git
cd geostride
pip install -e ".[dev]"
Quick Tour
1. Vectorized Distance Computation
import numpy as np
from geostride.metrics import haversine_pairwise, haversine_matrix
# New York to London & Tokyo coordinates (lat, lon)
coords_a = np.array([[40.7128, -74.0060]])
coords_b = np.array([
[51.5074, -0.1278], # London
[35.6762, 139.6503] # Tokyo
])
# Compute distance matrix in kilometers
distances = haversine_matrix(coords_a, coords_b, unit="km")
print(distances)
2. Spatial Lag Feature Engineering
import pandas as pd
from geostride.features import SpatialLagTransformer
df = pd.DataFrame({
"latitude": [40.71, 40.72, 40.75, 40.78],
"longitude": [-74.00, -73.99, -73.98, -73.96],
"house_price": [1200000, 1350000, 980000, 1100000]
})
transformer = SpatialLagTransformer(
lat_col="latitude",
lon_col="longitude",
value_col="house_price",
method="idw",
k_neighbors=2
)
df["price_spatial_lag"] = transformer.fit_transform(df)
3. Discrete Spatial Indexing (Geohash)
from geostride.indexing import encode_geohash, geohash_neighbors, geohash_bbox
# Encode coordinate into a 7-character Geohash (~150m cell)
gh = encode_geohash(latitude=40.7128, longitude=-74.0060, precision=7)
print(f"Geohash: {gh}")
# Retrieve all 8 adjacent neighbor cells
neighbors = geohash_neighbors(gh)
print(f"North neighbor: {neighbors['n']}")
4. Spatial Autocorrelation (Moran's I)
from geostride.stats import global_moran
# Check whether values cluster spatially
res = global_moran(coords=df[["latitude", "longitude"]].values, values=df["house_price"].values, k_neighbors=3)
print(f"Moran's I: {res.moran_i:.3f}, p-value: {res.p_value:.4f}")
5. Spatial DBSCAN Clustering
from geostride.cluster import spatial_dbscan
# Cluster coordinates within 2.0 km with at least 5 points
clusters = spatial_dbscan(df[["latitude", "longitude"]].values, eps_km=2.0, min_samples=5)
print(f"Clusters discovered: {clusters.n_clusters}")
print(f"Noise ratio: {clusters.noise_ratio:.1%}")
6. Zero-Dependency GeoJSON Serialization
from geostride.io import dataframe_to_geojson, geojson_to_dataframe
# Convert Pandas DataFrame directly to RFC 7946 FeatureCollection
geojson_data = dataframe_to_geojson(df, lat_col="latitude", lon_col="longitude")
# Parse GeoJSON back into a flat DataFrame
recovered_df = geojson_to_dataframe(geojson_data)
7. Interactive Leaflet HTML Map Export
from geostride.viz import export_html_map
# Export interactive Leaflet HTML map viewable in any browser without a web server
export_html_map(
"nyc_clusters.html",
coords=df[["latitude", "longitude"]].values,
labels=df["cluster_id"].values,
tooltips=[f"Price: ${p:,.0f}" for p in df["house_price"]],
title="NYC Housing Spatial Clusters"
)
8. Discrete Hexagonal Binning (H3-Style)
from geostride.indexing import bin_coordinates_hex, coord_to_hex_cell
# Map individual point to axial hexagonal grid cell (q, r)
q, r = coord_to_hex_cell(40.7128, -74.0060, edge_km=2.0)
# Aggregate thousands of coordinates into discrete equal-area hexagonal bins
hex_bins = bin_coordinates_hex(df[["latitude", "longitude"]].values, edge_km=2.0)
print(hex_bins.head())
9. Spatial Cross-Validation (Scikit-Learn Integration)
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from geostride.features import SpatialKFold
# Prevent optimistic spatial autocorrelation leakage across folds
cv = SpatialKFold(n_splits=5, method="morton", lat_col="latitude", lon_col="longitude")
scores = cross_val_score(Ridge(), X=df[["latitude", "longitude", "feature1"]], y=df["price"], cv=cv, scoring="r2")
print(f"Spatial CV R^2: {scores.mean():.3f} +/- {scores.std():.3f}")
10. Cluster Boundary Envelopes (Convex & Concave Hulls)
from geostride.cluster import alpha_shape_concave_hull, convex_hull_2d, polygon_area_km2
# Compute minimum convex bounding polygon
convex_hull = convex_hull_2d(df[["latitude", "longitude"]].values)
print(f"Convex Area: {polygon_area_km2(convex_hull):.1f} km^2")
# Extract tight non-convex alpha-shape boundary around irregular urban clusters
concave_rings = alpha_shape_concave_hull(df[["latitude", "longitude"]].values, alpha=0.5)
print(f"Concave Area: {polygon_area_km2(concave_rings[0]):.1f} km^2")
11. Spherical Voronoi Tessellation
from geostride.indexing import spherical_voronoi, voronoi_to_geojson
# Partition the Earth into exact spherical Voronoi service territories
voronoi_res = spherical_voronoi(df[["latitude", "longitude"]].values)
print(f"Total partitioned area: {voronoi_res.total_area_km2:,.0f} km^2")
# Export Voronoi polygons directly to GeoJSON
geojson_voronoi = voronoi_to_geojson(voronoi_res)
12. Vectorized Point-in-Polygon (Ray Casting)
from geostride.geometry import point_in_polygon, points_in_polygons
# Define administrative district polygon [latitude, longitude]
district_boundary = [
[40.70, -74.02],
[40.70, -73.97],
[40.76, -73.97],
[40.76, -74.02],
]
# High-throughput containment test across thousands of points
coords = df[["latitude", "longitude"]].values
in_district_mask = point_in_polygon(coords, district_boundary)
print(f"Points inside district: {in_district_mask.sum()} / {len(coords)}")
# Multi-polygon spatial indexing with bounding-box pre-filtering
district_ids = points_in_polygons(coords, [district_boundary])
13. Pure-Python Spatial R-Tree Indexing
from geostride.indexing import SpatialRTree
# Initialize hierarchical R-Tree indexer (zero external C dependencies)
rtree = SpatialRTree(max_entries=16, min_entries=4)
# Bulk load spatial features via Sort-Tile-Recursive (STR) packing
feature_ids = list(df.index)
bboxes = [
(lat - 0.01, lat + 0.01, lon - 0.01, lon + 0.01)
for lat, lon in df[["latitude", "longitude"]].values
]
rtree.bulk_load(feature_ids, bboxes)
# Fast spatial range intersection query
nearby_ids = rtree.query_range((40.71, 40.75, -74.01, -73.97))
# Best-first branch-and-bound k-nearest neighbor retrieval
nearest_3 = rtree.query_nearest(latitude=40.7128, longitude=-74.0060, k=3)
14. Local Indicators of Spatial Association (LISA)
from geostride.stats import local_moran
# Decompose spatial autocorrelation into local hot spots and spatial outliers
lisa_res = local_moran(
coords=df[["latitude", "longitude"]].values,
values=df["house_price"].values,
k_neighbors=5,
n_permutations=999,
p_threshold=0.05
)
print(f"High-High Hot Spots: {len(lisa_res.high_high)}")
print(f"Low-Low Cold Spots: {len(lisa_res.low_low)}")
print(f"High-Low Outliers: {len(lisa_res.high_low)}")
print(f"Low-High Outliers: {len(lisa_res.low_high)}")
15. Geodesic Polygon Buffering & Boundary Offsets
from geostride.geometry import buffer_point, buffer_polygon
# Generate exact geodesic circular buffer (e.g., 5 km emergency radius)
circle_buffer = buffer_point(latitude=40.7128, longitude=-74.0060, distance_km=5.0, n_points=32)
# Dilate delivery zone polygon outward by 2.0 km with smooth rounded corner joins
zone = [[40.70, -74.00], [40.75, -74.00], [40.75, -73.95], [40.70, -73.95]]
dilated_zone = buffer_polygon(zone, distance_km=2.0, join_style="round")
# Inward erosion by 1.0 km (contracting hazard perimeter)
eroded_zone = buffer_polygon(zone, distance_km=-1.0)
16. Vectorized Spatial Join (sjoin)
from geostride.geometry import spatial_join
# Point-in-polygon spatial join matching customer coordinates to delivery zones
joined_df = spatial_join(
left_df=df,
polygons=[dilated_zone],
how="inner",
predicate="within",
poly_id_col="zone_id",
)
# Nearest neighbor spatial join computing distance to closest facility
nearest_df = spatial_join(
left_df=df,
polygons={"HQ": dilated_zone},
how="left",
predicate="nearest",
distance_col="dist_to_hq_km",
)
17. Spherical Kernel Density Estimation (KDE)
from geostride.features import SphericalKDE
# Fit continuous spatial intensity surface with automated Silverman bandwidth
kde = SphericalKDE(bandwidth_km="silverman", kernel="gaussian")
kde.fit(df[["latitude", "longitude"]].values)
print(f"Optimal bandwidth: {kde.bandwidth_km_:.2f} km")
# Evaluate continuous probability density at specific coordinates
densities = kde.evaluate([[40.7128, -74.0060], [40.7580, -73.9855]])
# Rasterize density surface into a 2D regular grid for heatmap visualization
lats, lons, density_grid = kde.rasterize(resolution=(100, 100))
18. Well-Known Text (WKT) Serialization & DataFrame Parsing
from geostride.io import dataframe_to_wkt, from_wkt, to_wkt, wkt_to_dataframe
# Convert coordinate array or polygon rings into standard OGC WKT strings
point_wkt = to_wkt([40.7128, -74.0060]) # "POINT (-74.006 40.7128)"
line_wkt = to_wkt([[40.71, -74.00], [34.05, -118.24]]) # "LINESTRING (-74 40.71, -118.24 34.05)"
# Parse WKT strings back into geometry type and GeoStride coordinate matrices
geom_type, rings = from_wkt("POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))")
# Seamless integration with Pandas DataFrames
wkt_df = dataframe_to_wkt(df, lat_col="latitude", lon_col="longitude", wkt_col="wkt")
restored_df = wkt_to_dataframe(wkt_df, wkt_col="wkt")
19. Spatio-Temporal Trajectory Analytics & Resampling
from geostride.trajectory import resample_trajectory, trajectory_kinematics
# Analyze GPS trajectory kinematics: speed, forward heading, turning angles, and acceleration
metrics = trajectory_kinematics(
coords=[[40.7128, -74.0060], [40.7580, -73.9855], [40.7829, -73.9654]],
timestamps=["2026-01-01 10:00:00", "2026-01-01 10:05:00", "2026-01-01 10:12:00"],
)
print(f"Total distance: {metrics.total_distance_km:.2f} km")
print(f"Mean speed: {metrics.mean_speed_kmh:.1f} km/h, Max: {metrics.max_speed_kmh:.1f} km/h")
print(f"Segment headings: {metrics.headings_deg}")
print(f"Turning angles: {metrics.turning_angles_deg}")
# Resample trajectory to uniform 30-second temporal steps via Spherical Slerp
resampled_coords, resampled_ts = resample_trajectory(
coords=[[40.7128, -74.0060], [40.7829, -73.9654]],
timestamps=[0.0, 300.0],
step_seconds=30.0,
)
20. Spherical Trajectory Simplification (Douglas-Peucker)
from geostride.trajectory import cross_track_distance_meters, simplify_trajectory
# Simplify noisy GPS trajectory using geodesic cross-track error threshold
# Reduces redundant collinear points while preserving turns and curves
simplified_coords = simplify_trajectory(
coords=coords, # shape (N, 2)
tolerance_meters=25.0, # 25-meter cross-track tolerance
)
print(f"Compressed from {len(coords)} to {len(simplified_coords)} points "
f"({(1 - len(simplified_coords) / len(coords)) * 100:.1f}% reduction)")
# Compute great-circle cross-track distance from a point to a geodesic arc segment
xt_dist = cross_track_distance_meters(
lat=40.7300, lon=-73.9950,
start_lat=40.7128, start_lon=-74.0060,
end_lat=40.7580, end_lon=-73.9855,
)
21. Spatial Weights Matrix Standardization
from geostride.stats import knn_weights, standardize_weights
# Generate KNN spatial weights
w = knn_weights(coords, k=4, row_standardize=False)
# Standardize connectivity according to modeling requirements:
w_row = w.standardize("row") # Rows sum to 1.0 (local neighborhood averages)
w_bin = w.standardize("binary") # Binary 0/1 adjacency
w_spec = w.standardize("spectral") # Scales by largest eigenvalue (spectral radius = 1.0)
w_mm = w.standardize("minmax") # Scales by min(max_row_sum, max_col_sum)
# Or functional interface on raw NumPy adjacency matrices
std_matrix = standardize_weights(raw_adj_matrix, style="spectral")
22. Standalone Interactive Choropleth Maps
from geostride.viz import export_choropleth_map
# Export colored polygon regions with automated quantile bins and interactive legend
html_file = export_choropleth_map(
polygons=polygons, # List of polygon coordinate arrays or dict of regions
values=z_scores, # Statistical metrics (e.g. Getis-Ord z-scores)
output_path="choropleth.html", # Self-contained HTML file
colormap="viridis", # "viridis", "plasma", "blues", "reds", "greens", "coolwarm"
n_bins=5,
title="Spatial Hotspot Choropleth",
)
Benchmarks
GeoStride achieves substantial throughput through vectorized NumPy computations compared to naive Python loops:
| Benchmark Operation | Dataset Size | Execution Time | Throughput | Vectorized Speedup |
|---|---|---|---|---|
| Haversine Pairwise | $N = 50,000$ pairs | ~5.2 ms | 9,500,000 ops/s | ~24x faster |
| Haversine Cross-Matrix | $500 \times 500$ (250,000 pairs) | ~21.3 ms | 11,700,000 ops/s | Optimized BLAS/broadcasting |
| Morton Z-Order Encoding | $N = 30,000$ points | ~107 ms | 280,000 ops/s | Bit-interleaved |
| Geohash Batch Encoding | $N = 15,000$ points | ~121 ms | 123,000 ops/s | Pure-Python base32 |
| SpatialKFold Partitioning | $N = 20,000$ points | ~54 ms | 370,000 ops/s | Morton-ordered blocks |
Run the automated benchmark suite:
python -m benchmarks.run_benchmarks
Architecture
geostride/
├── core/ # Coordinate abstractions, validation & bounding boxes
├── metrics/ # Geodesic, Haversine, Vincenty & Manhattan metrics
├── indexing/ # Geohash, Morton curve, spatial grids
├── features/ # Spatial lags, POI density & scikit-learn transformers
├── stats/ # Moran's I, Getis-Ord Gi*, spatial weights
├── cluster/ # Spatial DBSCAN & boundary hulls
├── geometry/ # Point-in-polygon & spatial boundary operations
├── trajectory/ # Trajectory kinematics & spherical resampling
├── io/ # GeoJSON/WKT parsers
└── viz/ # Interactive map exporters
Roadmap
- Core geodetic distance algorithms (Haversine, Vincenty, Manhattan)
- Bitwise Geohash indexing and 8-direction neighbor search
- Morton space-filling curve (Z-order) indexing
- Inverse Distance Weighting (IDW) & KNN Spatial Lag Transformers
- Automated performance comparison benchmarking suite
- Spatial weight matrix generators (KNN, distance band, inverse distance)
- Global & Local Moran's I with permutation tests
- Getis-Ord $G_i^*$ spatial hot-spot analysis
- BallTree-accelerated spatial DBSCAN clustering
- Zero-dependency GeoJSON and WKT parser & serializer
- Self-contained interactive Leaflet visualization generator
- Discrete hexagonal (H3-style) spatial tessellation generator
- Full Scikit-Learn pipeline compatibility benchmarks
- Convex and concave alpha-shape cluster boundary hull generator
- GitHub Actions multi-OS test matrix and automated code quality verification
- Spherical Voronoi diagram generator (
geostride.indexing.voronoi) - Vectorized Point-in-Polygon indexer (
geostride.geometry.pip) - Spatial R-Tree nearest neighbor & range indexer (
geostride.indexing.rtree) - Local Indicators of Spatial Association (LISA) quadrant mapping (
geostride.stats.lisa) - Geodesic polygon buffering and dilation (
geostride.geometry.buffer) - Vectorized spatial join (
sjoin) for polygons and point proximity (geostride.geometry.sjoin) - Spherical Kernel Density Estimation (KDE) and heatmap rasterizer (
geostride.features.kde) - Well-Known Text (WKT) parser and serializer (
geostride.io.wkt) - Spatio-temporal trajectory analytics and kinematics (
geostride.trajectory.metrics) - Spherical trajectory simplification using geodesic Douglas-Peucker (
geostride.trajectory.simplify) - Spatial weights standardization matrix transformations (
geostride.stats.weights) - Standalone interactive Choropleth HTML map exporter (
geostride.viz.choropleth)
License
This project is licensed under the MIT License - see the LICENSE file for details.
Metadata
Release files for geostride 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| geostride-0.2.0.tar.gz | 114.1 kB | Without provenance | Details for geostride-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| geostride-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for geostride-0.2.0-py3-none-any.whl |
Total release size: 208.0 kB
Release files / geostride-0.2.0.tar.gz
| Download URL | geostride-0.2.0.tar.gz |
|---|---|
| Size | 114.1 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4533a024fc25cb36e7a10532fa95adba9f266da3c81d4e5f43e420498d37c0b7
|
|
BLAKE2b-256 checksum How to use checksums |
d01ed1975ce2e2cbea16a0e9ac1f15ae4d4c9592bed653bfaac647a12a103486
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / geostride-0.2.0-py3-none-any.whl
| Download URL | geostride-0.2.0-py3-none-any.whl |
|---|---|
| Size | 93.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a5f342cdda402c1238a759b24b58acbd702e432c13574316bde5e85f9ce319a4
|
|
BLAKE2b-256 checksum How to use checksums |
a225c5b57b8b4bfe1edcdf64f0fabd162dc0f5ae9a6562ba6dbe920b663cd306
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for geostride 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.