Code Review: Geospatial Data Processing Pipeline
SQL & DataModel answerLast updated
Evaluate a Python module that computes distances and clusters geographic points from CSV/GeoJSON sources, identifying bugs, performance issues, and production risks.
You are given a Python module that ingests geospatial datasets (CSV and GeoJSON), calculates pairwise distances between points, groups nearby points into clusters, and writes summary outputs. Your task is to conduct a thorough code review covering the following dimensions:
- Correctness bugs and numerical stability problems specific to geospatial computation
- Edge-case handling: missing or malformed coordinates, CRS mismatches, empty inputs
- Performance bottlenecks and concrete optimization strategies
- Code quality: modularity, type annotations, documentation
- Security and operational concerns: input validation, dependency management, file handling
- A testing strategy with specific fixture scenarios
For each issue you identify, explain why it matters and propose a concrete fix. Where relevant, estimate time and space complexity of the current approach and your proposed alternative. Discuss library choices (pandas, shapely, pyproj, scikit-learn, geopandas) and their trade-offs.
Hints
Hint 1
GeoJSON uses [lon, lat] ordering while most CSVs use lat, lon — check for coordinate swaps
Hint 2
DBSCAN with haversine metric expects radians, not degrees, and eps must be scaled by Earth's radius
Hint 3
A full n×n distance matrix for 100k points consumes roughly 80 GB of memory — think about spatial indexing
Hint 4
Haversine can produce domain errors for near-antipodal points when the arc-sin argument exceeds 1 due to floating-point drift
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
I would structure this review by severity: correctness first, then numerical stability, edge cases, performance, design, security, and testing.
Correctness Bugs
The most common geospatial bug is coordinate ordering. GeoJSON spec stores coordinates as [lon, lat], but most CSV files use lat, lon columns. Shapely's Point(x, y) takes (lon, lat). A swap produces distances that look plausible but are wrong — a latitude above 90 after parsing is a telltale sign.
Another classic: passing degrees directly to trig functions. math.sin(lat) without converting to radians first. Similarly, computing Euclidean distance sqrt(dlat² + dlon²) on raw lat/lon ignores the longitude shrinkage factor cos(lat) — one degree of longitude is roughly 111 km at the equator and nearly zero at the poles.
For clustering, DBSCAN(eps=0.5) on raw degrees with a comment claiming "500 meters" is a units mismatch. With metric="haversine", inputs must be in radians and eps must be meters / EARTH_RADIUS.
CRS mismatches are subtle: combining EPSG:4326 (degrees) with EPSG:3857 (Web Mercator, meters) without reprojection. Computing .buffer(500) or .area in 4326 produces nonsense because the units are degrees. Measuring distances in 3857 inflates them by roughly 1/cos(lat) — about 1.3× at 40° latitude.
Silent NaN propagation is also common. pd.to_numeric(errors="coerce") converts bad values to NaN, and aggregations skip NaN by default, so summary counts won't match input row counts.
I/O issues to check for: files opened without encoding="utf-8", CSV writes missing newline="", missing context managers for file handles, and mutable default arguments like def summarize(rows, acc={}).
Numerical Stability
The haversine term a can drift slightly above 1.0 for near-antipodal points due to floating-point error, causing arcsin(sqrt(a)) to return NaN or raise. Clamp with np.clip(a, 0, 1).
Haversine uses a spherical model with up to ~0.5% error. Fine for proximity queries, not for surveying. When accuracy matters, use pyproj.Geod(ellps="WGS84").inv for geodesic distance.
Floating-point equality for deduplication (lat1 == lat2) misses points that differ only by rounding. Round to 6 decimal places (~0.1 m) or use a distance tolerance.
Antimeridian wrap: a naive centroid of points at lon 179 and -179 lands near 0. Compute centroids via 3D unit vectors or handle the wrap explicitly.
Edge Cases and Validation
Validate once at the boundary: missing or non-numeric coordinates, out-of-range values (|lat| > 90, |lon| > 180), the (0, 0) Null Island sentinel, duplicate points, empty files, single-point inputs, polar coordinates, and mixed-geometry GeoJSON where Polygons appear where Points are expected. Decide on a policy — drop, quarantine, or fail — and log rejected rows with counts rather than dropping silently.
Performance
A nested-loop or iterrows approach for pairwise distances is O(n²) time and space. For 100k points, a full distance matrix in float64 is ~80 GB. The fix: replace with BallTree(metric="haversine") which builds in O(n log n) and queries in O(log n + k). For DBSCAN, pass algorithm="ball_tree" to get average O(n log n) behavior instead of brute-force O(n²). For point-in-polygon, use geopandas.sjoin which leverages STRtree at O((n + m) log m).
For I/O, switch from json.load of entire large files to chunked reads with pd.read_csv(chunksize=...) or pyogrio for GeoJSON. Output to Parquet/GeoParquet for downstream efficiency. Memory drops from O(n) to O(chunk_size).
Reference Implementation
import numpy as np
import pandas as pd
from sklearn.neighbors import BallTree
from sklearn.cluster import DBSCAN
EARTH_RADIUS_M = 6_371_008.8
def validate_coords(df, lat="lat", lon="lon"):
"""Return (valid, rejected). Coerces to float, rejects NaN/out-of-range/Null Island."""
out = df.copy()
out[lat] = pd.to_numeric(out[lat], errors="coerce")
out[lon] = pd.to_numeric(out[lon], errors="coerce")
ok = (out[lat].between(-90, 90) & out[lon].between(-180, 180)
& ~((out[lat] == 0) & (out[lon] == 0)))
return out[ok].reset_index(drop=True), out[~ok]
def haversine_m(lat1, lon1, lat2, lon2):
"""Vectorized great-circle distance in meters. Inputs in degrees."""
lat1, lon1, lat2, lon2 = map(np.radians, (lat1, lon1, lat2, lon2))
a = (np.sin((lat2 - lat1) / 2) ** 2
+ np.cos(lat1) * np.cos(lat2) * np.sin((lon2 - lon1) / 2) ** 2)
return 2 * EARTH_RADIUS_M * np.arcsin(np.sqrt(np.clip(a, 0.0, 1.0)))
def cluster_points(df, eps_m, min_samples=3):
"""DBSCAN labels using true great-circle eps in meters."""
if df.empty:
return np.array([], dtype=int)
X = np.radians(df[["lat", "lon"]].to_numpy())
return DBSCAN(eps=eps_m / EARTH_RADIUS_M, min_samples=min_samples,
metric="haversine", algorithm="ball_tree").fit_predict(X)
Key points: validation runs once and returns rejects for logging, units are explicit in naming (_m suffix), and the radians conversion lives next to the metric that requires it.
Design and Security
Split into focused modules: io for readers/writers, validate for boundary checks, geo for distance and clustering logic, and summarize for output generation. Add type annotations and docstrings throughout. Pin dependencies with exact versions in requirements.txt or pyproject.toml to avoid supply-chain surprises. Validate file paths to prevent directory traversal if inputs come from user uploads. Use context managers for all file operations.
Testing Strategy
Unit tests with small fixture data: a known distance pair (verify haversine against a reference value), a CRS mismatch scenario, a Null Island row, a near-antipodal pair (numerical stability), an empty DataFrame, and a single-point input. Integration tests with a real CSV and GeoJSON file covering the end-to-end pipeline, asserting cluster labels and summary counts. A performance smoke test with 10k synthetic points to catch O(n²) regressions. Property-based tests for validation: random coordinate tuples should be accepted or rejected consistently based on range rules.