SciPy Spatial Data
Spatial data is data about points in space: GPS positions, pixels, atoms, or any rows of numbers you treat as coordinates. The scipy.spatial module answers geometric questions about such points: Which points are closest to each other? How far apart are they? What shape encloses them?
Distance metrics
How far apart two points are depends on how you measure. scipy.spatial.distance provides many metrics:
from scipy.spatial import distance
a = (1, 2)
b = (4, 6)
print("euclidean :", distance.euclidean(a, b)) # straight line
print("cityblock :", distance.cityblock(a, b)) # Manhattan: along a grid
print("chebyshev :", distance.chebyshev(a, b)) # largest single-axis gap
print("cosine :", round(distance.cosine(a, b), 4)) # angle-based, 0 = same direction
u = [1, 0, 1, 1, 0]
v = [1, 1, 0, 1, 0]
print("hamming :", distance.hamming(u, v)) # fraction of positions that differ
print("jaccard :", round(distance.jaccard(u, v), 4))euclidean : 5.0
cityblock : 7
chebyshev : 4
cosine : 0.0077
hamming : 0.4
jaccard : 0.5
| Metric | Formula idea | Typical use |
|---|---|---|
| Euclidean | √Σ(aᵢ−bᵢ)² | Physical distance |
| City block (Manhattan) | Σ|aᵢ−bᵢ| | Grid movement, robust to outliers |
| Chebyshev | max|aᵢ−bᵢ| | King moves on a chessboard |
| Cosine | 1 − cos(angle) | Text vectors, direction similarity |
| Hamming | share of differing positions | Binary codes, strings |
| Jaccard | 1 − |A∩B| / |A∪B| | Sets of features |
Many distances at once
cdist(A, B) gives the distance from every point in A to every point in B; pdist(X) gives every pairwise distance within one set, in a compact form that squareform() expands into a matrix:
import numpy as np
from scipy.spatial.distance import cdist, pdist, squareform
shops = np.array([[0, 0], [5, 0], [0, 5]])
homes = np.array([[1, 1], [4, 1]])
d = cdist(homes, shops)
print(np.round(d, 2))
print("nearest shop for each home:", d.argmin(axis=1))
print("shop-to-shop:", np.round(pdist(shops), 2))
print(np.round(squareform(pdist(shops, "cityblock"))))[[1.41 4.12 4.12]
[4.12 1.41 5.66]]
nearest shop for each home: [0 1]
shop-to-shop: [5. 5. 7.07]
[[ 0. 5. 5.]
[ 5. 0. 10.]
[ 5. 10. 0.]]
Nearest neighbours with a KD-tree
Comparing every point with every other point gets slow as data grows. A KD-tree organises points so that nearest-neighbour searches are fast. Build it once with KDTree, then query as often as you like:
import numpy as np
from scipy.spatial import KDTree
stations = np.array([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]])
tree = KDTree(stations)
dist, idx = tree.query([6, 3])
print(f"closest station: #{idx} at {stations[idx]}, distance {dist:.3f}")
dist, idx = tree.query([6, 3], k=3)
print("3 closest:", idx, np.round(dist, 3))
within = tree.query_ball_point([6, 3], r=2.5)
print("within 2.5:", sorted(within))closest station: #1 at [5 4], distance 1.414
3 closest: [1 5 4] [1.414 1.414 2.828]
within 2.5: [1, 5]
Convex hull
The convex hull is the smallest convex polygon that contains all the points — imagine a rubber band snapped around pins on a board:
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
rng = np.random.default_rng(3)
points = rng.uniform(0, 10, size=(25, 2))
hull = ConvexHull(points)
print("corner points:", len(hull.vertices))
print("area :", round(hull.volume, 2)) # in 2-D, 'volume' is the area
print("perimeter:", round(hull.area, 2)) # and 'area' is the perimeter
plt.plot(points[:, 0], points[:, 1], "o", color="tab:blue")
loop = np.append(hull.vertices, hull.vertices[0])
plt.plot(points[loop, 0], points[loop, 1], "r-")
plt.title("Convex hull of 25 points")
plt.show()
print("Plotted the points and their hull.")corner points: 7
area : 67.82
perimeter: 31.91
Plotted the points and their hull.
Note: In 2-D,
ConvexHull.volumeis the enclosed area andConvexHull.areais the perimeter. The names come from the 3-D case, where they mean volume and surface area.
Triangulation
A Delaunay triangulation splits the region covered by the points into triangles, avoiding long thin slivers. It's the basis of mesh generation and of scattered-data interpolation:
import numpy as np
from scipy.spatial import Delaunay
pts = np.array([[0, 0], [2, 0], [1, 2], [3, 2], [2, 3.5]])
tri = Delaunay(pts)
triangles = sorted(sorted(t.tolist()) for t in tri.simplices)
print("number of triangles:", len(triangles))
print("triangles (point indices):", triangles)
print("is (2, 2.5) inside?", tri.find_simplex([2, 2.5]) >= 0)
print("is (5, 5) inside?", tri.find_simplex([5, 5]) >= 0)number of triangles: 3
triangles (point indices): [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
is (2, 2.5) inside? True
is (5, 5) inside? False
find_simplex() returns -1 for points outside every triangle, which makes it a quick "is this point inside the region?" test.
Test yourself
What is the Manhattan (city block) distance between (1, 2) and (4, 6)?
- 5
- 7
- 4
- 25
Why use a KDTree instead of computing all distances?
- It gives more accurate distances
- It makes repeated nearest-neighbour queries much faster
- It works only with integers
- It sorts the points alphabetically
For a 2-D ConvexHull, what does hull.volume contain?
- The perimeter
- The enclosed area
- The number of vertices
- Always 0