Sign in

Geospatial analysis

Geospatial exploratory analysis

A first look at latitude and longitude points: valid coordinates, great-circle distances, a centroid, density clusters and a count grid.

Overview

Points on the Earth are given by two angles: latitude (north or south of the equator) and longitude (east or west of a reference line). They look like ordinary x and y values, but they sit on a sphere. A degree of longitude is about 111 km wide at the equator and shrinks to nothing at the poles, so plain subtraction of degrees gives wrong distances. The haversine formula gives the distance along the surface, called the great-circle distance. With real distances you can ask where points bunch together. DBSCAN finds groups of densely packed points without being told how many groups to expect, and labels isolated points as noise. A grid of counts gives the numbers behind a heat map.

A short history

Spatial analysis of points is often traced to John Snow's 1854 map of cholera deaths in London, which showed cases clustering around one water pump. The haversine formula for great circle distance comes from nineteenth century navigation tables. Geographic information systems developed from the 1960s. For clustering, Martin Ester, Hans-Peter Kriegel, Jörg Sander and Xiaowei Xu published DBSCAN in 1996, a density based method that finds clusters of any shape and labels isolated points as noise.

How it works

  1. Check coordinates with valid_mask: latitude must lie between -90 and 90, longitude between -180 and 180, and both must be finite.
  2. Compute bounds: the smallest and largest latitude and longitude of the valid points, with the box's height and width in kilometres.
  3. Compute distances with haversine, or all pairs at once with distance_matrix.
  4. Find the centre with centroid, which turns each point into a unit vector from the Earth's centre, averages the vectors and converts the result back to angles.
  5. Run dbscan: a point with at least min_samples points within eps_km (itself included) is a core point. Core points within reach of each other form a cluster, together with the points near them.
  6. Points that are within reach of no core point get the label -1, for noise.
  7. Count points per cell with density_grid and read off the fullest cell as the hot spot.

Watch out for

  • Swapped latitude and longitude often still pass the validity check, because many longitudes also fit inside the range -90 to 90. Check the bounding box against where the points should be.
  • The bounding box and the degree grid break for areas that cross the 180 degree meridian or include a pole, since they treat degrees as flat numbers.
  • The clustering here is the exact algorithm on a full distance matrix, which needs memory proportional to n2n^{2}. It suits a few thousand points, and millions need a spatial index.
  • DBSCAN uses one radius for all clusters, so it cannot handle groups of very different density: a radius that suits a city centre splits a suburb into noise.
  • Grid cells of equal size in degrees cover less ground the further they are from the equator, so the same count means a higher true density at high latitudes than near the equator.

Use cases

When to use it

When a table has latitude and longitude columns: to catch swapped or impossible coordinates, see where points concentrate, find natural groups such as stops or stores, and derive features such as distance to a centre.

In industry

Public health
Health agencies map case locations and look for density clusters to find the source of an outbreak, in the tradition of Snow's cholera map.
Ride hailing and delivery
Operators aggregate pickup points into grid cells to see where demand concentrates by hour and to position drivers.
Retail site selection
Chains compute distances from customer addresses to stores and map customer density to choose locations for new outlets.

Choosing it: what must hold

  • Point records with latitude and longitude in a known coordinate system, normally WGS84 decimal degrees.
  • Coordinates checked for valid ranges, swapped columns and placeholder values such as 0, 0.
  • A distance scale that suits the question, since the cluster radius and the grid cell size decide what counts as dense.

When to choose something else

IfUse instead
The data are regions with values, not pointsA choropleth map and spatial autocorrelation measures such as Moran's I
Travel follows roads, so straight line distance misleadsNetwork distances from a routing engine
Clusters have very different densitiesHDBSCAN or OPTICS instead of DBSCAN

Math foundations

  1. The haversine term

    a=sin⁡2 ⁣(Δϕ2)+cos⁡ϕ1 cos⁡ϕ2 sin⁡2 ⁣(Δλ2)a = \sin^{2}\!\left(\frac{\Delta\phi}{2}\right) + \cos\phi_1 \, \cos\phi_2 \, \sin^{2}\!\left(\frac{\Delta\lambda}{2}\right)

    A number between 0 and 1 built from the two latitudes and the differences in latitude and longitude, all in radians. The cosines shrink the east-west part as the points move away from the equator.

  2. Great-circle distance

    d=2R arcsin⁡ ⁣(a)d = 2R \, \arcsin\!\big(\sqrt{a}\big)

    The arcsine turns aa into half the angle between the two points as seen from the Earth's centre. Multiplying the angle by the radius gives the distance along the surface. A sphere is accurate to about 0.5 percent against the true shape of the Earth.

  3. Centroid on the sphere

    vˉ=1n∑i=1n(cos⁡ϕicos⁡λicos⁡ϕisin⁡λisin⁡ϕi),ϕˉ=atan2⁡ ⁣(vˉz,vˉx2+vˉy2),λˉ=atan2⁡(vˉy,vˉx)\bar{v} = \frac{1}{n} \sum_{i=1}^{n} \begin{pmatrix} \cos\phi_i \cos\lambda_i \\ \cos\phi_i \sin\lambda_i \\ \sin\phi_i \end{pmatrix}, \qquad \bar{\phi} = \operatorname{atan2}\!\Big(\bar{v}_z, \sqrt{\bar{v}_x^{2} + \bar{v}_y^{2}}\Big), \quad \bar{\lambda} = \operatorname{atan2}(\bar{v}_y, \bar{v}_x)

    Averaging angles directly fails near the 180 degree meridian, where 179 and -179 would average to 0. Averaging the points as three-dimensional vectors and reading the direction of the result avoids that.

  4. Core point condition

    ∣{ q:d(p,q)≤ε }∣≥m\big|\{\, q : d(p, q) \le \varepsilon \,\}\big| \ge m

    A point pp is a core point when at least mm points, itself included, lie within distance ε\varepsilon of it. Clusters grow by chaining core points whose neighbourhoods overlap.

Symbols

ϕ1,ϕ2\phi_1, \phi_2
latitudes of the two points, in radians
Δϕ,Δλ\Delta\phi, \Delta\lambda
difference in latitude and in longitude, in radians
RR
sphere radius (earth_radius_km, default 6371.0088 km)
dd
great-circle distance in kilometres
vˉ\bar{v}
mean of the points' unit vectors, with components x, y, z
ϕˉ,λˉ\bar{\phi}, \bar{\lambda}
latitude and longitude of the centroid
ε\varepsilon
neighbourhood radius (eps_km)
mm
points needed within the radius to make a core point (min_samples)
p,qp, q
two points of the dataset

Worked by hand

How long is one degree? First go one degree north along a meridian, then one degree east along the 60 degree parallel. Use R=6371.0088R = 6371.0088 km and note sin⁡(0.5∘)=0.0087265\sin(0.5^{\circ}) = 0.0087265.

north: a=sin⁡2(0.5∘)=0.00872652,a=0.0087265\text{north: } a = \sin^{2}(0.5^{\circ}) = 0.0087265^{2}, \qquad \sqrt{a} = 0.0087265
d=2×6371.0088×arcsin⁡(0.0087265)=12742.02×0.0087266=111.19 kmd = 2 \times 6371.0088 \times \arcsin(0.0087265) = 12742.02 \times 0.0087266 = 111.19 \text{ km}
east at 60∘:  a=cos⁡2(60∘) sin⁡2(0.5∘),a=0.5×0.0087265=0.0043633\text{east at } 60^{\circ}: \; a = \cos^{2}(60^{\circ}) \, \sin^{2}(0.5^{\circ}), \qquad \sqrt{a} = 0.5 \times 0.0087265 = 0.0043633
d=12742.02×arcsin⁡(0.0043633)=12742.02×0.0043633=55.60 kmd = 12742.02 \times \arcsin(0.0043633) = 12742.02 \times 0.0043633 = 55.60 \text{ km}

One degree of latitude is about 111 km everywhere. One degree of longitude at 60 degrees north is half that, about 56 km. Treating degrees as flat distances would be wrong by a factor of two there.

Visual example

Loading the example.

Try this

  • Lower the radius to 0.4 km and watch both clusters dissolve into noise.
  • Set the radius to 2 km, then move the map centre to 60 degrees north: the two clusters join into one though no coordinate changed.
  • Click empty map between the two clusters to add points until they join.

Code sample

import numpy as np
from impl import GeospatialAnalysis
from config import GeospatialAnalysisConfig

rng = np.random.default_rng(0)
lat = np.r_[48.85 + rng.normal(0, 0.003, 30), 51.50 + rng.normal(0, 0.003, 30), 10.0]
lon = np.r_[2.35 + rng.normal(0, 0.003, 30), -0.12 + rng.normal(0, 0.003, 30), 100.0]

geo = GeospatialAnalysis(GeospatialAnalysisConfig(eps_km=1.0, min_samples=5))
print(geo.haversine(48.85, 2.35, 51.50, -0.12))     # about 343 km
labels = geo.dbscan(lat, lon)                        # 0 for the first group, 1 for the second, -1 for the stray point
print(geo.cluster_summary(lat, lon, labels))
print(geo.bounds(lat, lon))
print(geo.density_grid(lat[:60], lon[:60])["hotspot"])
Read the implementation (156 lines)
"""Geospatial analysis of points given as latitude and longitude in decimal degrees.

NumPy only. Coordinates are checked and bounded, distances are great-circle distances on a sphere (haversine
formula), clusters are found with DBSCAN on those distances, and a density map is a grid of point counts.
The clustering builds the full (n, n) distance matrix, which suits up to a few thousand points.
"""
from __future__ import annotations

from collections import deque

import numpy as np

try:
    from .config import GeospatialAnalysisConfig
except ImportError:  # run from the template's own folder
    from config import GeospatialAnalysisConfig


class GeospatialAnalysis:
    """Bounds, distances, clusters and density of latitude/longitude points."""

    def __init__(self, config: GeospatialAnalysisConfig | None = None) -> None:
        self.config = config or GeospatialAnalysisConfig()

    @staticmethod
    def _pair(lat, lon) -> tuple[np.ndarray, np.ndarray]:
        lat = np.asarray(lat, dtype=float).ravel()
        lon = np.asarray(lon, dtype=float).ravel()
        if lat.size != lon.size:
            raise ValueError(f"lat and lon must have the same length, got {lat.size} and {lon.size}")
        return lat, lon

    # ---- validity and bounds -------------------------------------------------------------------------------
    def valid_mask(self, lat, lon) -> np.ndarray:
        """Boolean (n,): True where lat is in [-90, 90], lon is in [-180, 180] and both are finite."""
        lat, lon = self._pair(lat, lon)
        with np.errstate(invalid="ignore"):
            return np.isfinite(lat) & np.isfinite(lon) & (np.abs(lat) <= 90.0) & (np.abs(lon) <= 180.0)

    def bounds(self, lat, lon) -> dict:
        """Bounding box of the valid points.

        lat, lon: shape (n,) decimal degrees. Returns {"min_lat", "max_lat", "min_lon", "max_lon", "n_valid",
        "n_invalid", "height_km", "width_km"}; height is the north-south extent and width the east-west extent
        measured along the box's middle latitude. The box is a plain minimum and maximum, so a point set that
        straddles the 180 degree meridian gets a box that wraps the long way round.
        """
        lat, lon = self._pair(lat, lon)
        ok = self.valid_mask(lat, lon)
        if not ok.any():
            raise ValueError("no valid coordinates")
        la, lo = lat[ok], lon[ok]
        box = {
            "min_lat": float(la.min()), "max_lat": float(la.max()),
            "min_lon": float(lo.min()), "max_lon": float(lo.max()),
            "n_valid": int(ok.sum()), "n_invalid": int((~ok).sum()),
        }
        middle = 0.5 * (box["min_lat"] + box["max_lat"])
        box["height_km"] = float(self.haversine(box["min_lat"], box["min_lon"], box["max_lat"], box["min_lon"]))
        box["width_km"] = float(self.haversine(middle, box["min_lon"], middle, box["max_lon"]))
        return box

    # ---- distances -----------------------------------------------------------------------------------------
    def haversine(self, lat1, lon1, lat2, lon2) -> np.ndarray | float:
        """Great-circle distance in km between points 1 and points 2 (degrees; arrays broadcast)."""
        p1, p2 = np.radians(lat1), np.radians(lat2)
        dlat = p2 - p1
        dlon = np.radians(lon2) - np.radians(lon1)
        a = np.sin(dlat / 2.0) ** 2 + np.cos(p1) * np.cos(p2) * np.sin(dlon / 2.0) ** 2
        d = 2.0 * self.config.earth_radius_km * np.arcsin(np.sqrt(np.clip(a, 0.0, 1.0)))
        return float(d) if np.ndim(d) == 0 else d

    def distance_matrix(self, lat, lon) -> np.ndarray:
        """All pairwise great-circle distances in km. lat, lon: shape (n,). Returns shape (n, n)."""
        lat, lon = self._pair(lat, lon)
        return self.haversine(lat[:, None], lon[:, None], lat[None, :], lon[None, :])

    def centroid(self, lat, lon) -> tuple[float, float]:
        """Geographic mean (lat, lon): the points are averaged as unit vectors on the sphere.

        Unlike a plain average of degrees this is right across the 180 degree meridian and near the poles.
        """
        lat, lon = self._pair(lat, lon)
        if lat.size == 0:
            raise ValueError("no points")
        p, l = np.radians(lat), np.radians(lon)
        x, y, z = (np.cos(p) * np.cos(l)).mean(), (np.cos(p) * np.sin(l)).mean(), np.sin(p).mean()
        if np.sqrt(x * x + y * y + z * z) < 1e-12:
            raise ValueError("the points cancel out on the sphere; the centroid is undefined")
        return float(np.degrees(np.arctan2(z, np.hypot(x, y)))), float(np.degrees(np.arctan2(y, x)))

    # ---- clustering ----------------------------------------------------------------------------------------
    def dbscan(self, lat, lon) -> np.ndarray:
        """DBSCAN on great-circle distance.

        lat, lon: shape (n,). Returns integer labels (n,): 0, 1, ... for clusters in order of discovery and -1
        for noise. A core point has at least config.min_samples points within config.eps_km (itself included);
        a cluster is a set of core points chained through such neighbourhoods plus the points within reach.
        """
        lat, lon = self._pair(lat, lon)
        n = lat.size
        near = self.distance_matrix(lat, lon) <= self.config.eps_km
        core = near.sum(axis=1) >= self.config.min_samples
        labels = np.full(n, -1, dtype=int)
        cluster = 0
        for start in range(n):
            if not core[start] or labels[start] != -1:
                continue
            labels[start] = cluster
            queue = deque([start])
            while queue:
                point = queue.popleft()
                for neighbour in np.flatnonzero(near[point]):
                    if labels[neighbour] == -1:
                        labels[neighbour] = cluster
                        if core[neighbour]:  # only core points spread the cluster further
                            queue.append(neighbour)
            cluster += 1
        return labels

    def cluster_summary(self, lat, lon, labels) -> list[dict]:
        """One dict per cluster: {"label", "size", "centroid" (lat, lon), "radius_km" (largest distance to it)}."""
        lat, lon = self._pair(lat, lon)
        labels = np.asarray(labels)
        out = []
        for label in sorted(set(labels.tolist()) - {-1}):
            member = labels == label
            centre = self.centroid(lat[member], lon[member])
            radius = float(np.max(self.haversine(lat[member], lon[member], centre[0], centre[1])))
            out.append({"label": int(label), "size": int(member.sum()), "centroid": centre, "radius_km": radius})
        return out

    # ---- density map ---------------------------------------------------------------------------------------
    def density_grid(self, lat, lon, box: dict | None = None) -> dict:
        """Count points per cell of a regular latitude/longitude grid.

        lat, lon: shape (n,); invalid coordinates are ignored. box: optional dict with min_lat, max_lat, min_lon,
        max_lon (default: the bounds of the data). Returns {"counts" (grid_rows, grid_cols), "lat_edges"
        (grid_rows + 1,), "lon_edges" (grid_cols + 1,), "hotspot" (lat, lon of the centre of the fullest cell)}.
        Row 0 is the southernmost band and column 0 the westernmost.
        """
        lat, lon = self._pair(lat, lon)
        ok = self.valid_mask(lat, lon)
        box = box or self.bounds(lat, lon)
        lat_range = [box["min_lat"], box["max_lat"]]
        lon_range = [box["min_lon"], box["max_lon"]]
        if lat_range[0] == lat_range[1]:
            lat_range = [lat_range[0] - 0.5, lat_range[1] + 0.5]
        if lon_range[0] == lon_range[1]:
            lon_range = [lon_range[0] - 0.5, lon_range[1] + 0.5]
        counts, lat_edges, lon_edges = np.histogram2d(
            lat[ok], lon[ok], bins=[self.config.grid_rows, self.config.grid_cols], range=[lat_range, lon_range]
        )
        row, col = np.unravel_index(int(np.argmax(counts)), counts.shape)
        hotspot = (float(0.5 * (lat_edges[row] + lat_edges[row + 1])), float(0.5 * (lon_edges[col] + lon_edges[col + 1])))
        return {"counts": counts.astype(int), "lat_edges": lat_edges, "lon_edges": lon_edges, "hotspot": hotspot}
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Generate 30 points around Paris, 30 around London and one stray point, as in the template's README. Call haversine between the two city centres, then dbscan with eps_km at 1.0 and min_samples at 5, and cluster_summary on the labels. Change eps_km to 0.1 and to 500 and explain what happens to the labels.

Check on learning

  1. Two points are 1 degree of longitude apart. Why does the distance between them depend on their latitude, and where is it largest?
    A way to think about it

    Lines of longitude meet at the poles. Look at the role of the cosine terms in the haversine formula.

  2. A set of points has longitudes of 179 and -179. What does a plain average of the longitudes give, and what does the vector centroid give?
    A way to think about it

    The two points are 2 degrees apart across the 180 degree meridian. An average of 0 puts the centre on the other side of the planet.

  3. With eps_km far too small every point becomes noise, and far too large gives one cluster. How would you choose a sensible radius from the data?
    A way to think about it

    For each point, look at the distance to its mm-th nearest neighbour. Sort those distances and look for the level where they start to rise sharply.

  4. A dataset has thousands of points exactly at latitude 0, longitude 0. They pass valid_mask. What are they likely to be, and how would the density grid reveal them?
    A way to think about it

    Think about what a system writes when a location is unknown, and what is actually at that spot on a map.

  5. Why does DBSCAN not need the number of clusters, and what does it need in its place?
    A way to think about it

    It defines a cluster by density. The two settings together say how dense is dense enough.