Spatial Data, Rotations & Special Functions (spatial & special)
Geometric computation and physics problems rely heavily on coordinate transformations, nearest-neighbor searches, convex boundaries, and mathematical special functions.
1. Fast Nearest-Neighbor Search: cKDTree
Searching for the closest point among coordinates with brute force takes time per query. A k-dimensional tree (scipy.spatial.cKDTree) partitions space hierarchically, reducing lookup time to :
Example
Output:
2. Convex Hull & Spatial Boundaries (ConvexHull)
A Convex Hull represents the tightest convex polygon or polyhedron enclosing a set of discrete points (like snapping a rubber band around pins):
# A plotting script for generating the Convex Hull figure
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
np.random.seed(1)
points = np.random.rand(30, 2)
hull = ConvexHull(points)
plt.figure(figsize=(6, 5))
plt.plot(points[:, 0], points[:, 1], 'o', color='tab:blue', label='Data Points')
for simplex in hull.simplices:
plt.plot(points[simplex, 0], points[simplex, 1], 'r-', lw=2)
plt.title("Convex Hull of 2D Points")
plt.legend()
plt.tight_layout()
plt.savefig('public/modules/scipy/ch08_convexhull.png', dpi=300)
Figure 8.1: Convex Hull perimeter enclosing points.
Inspect the geometric volume and surface area programmatically:
Example
Output:
3. 3D Rotations Without Gimbal Lock (Rotation)
scipy.spatial.transform.Rotation manages 3D orientations cleanly.
Euler angles suffer from gimbal lock at pitch , losing one degree of freedom. For interpolation, physics simulation, and robotics, always use quaternions or rotation vectors.
Example
Output:
4. Special Functions (scipy.special)
scipy.special computes solutions to transcendental equations that arise frequently in science and engineering:
Gamma & Factorials
Factorials overflow 64-bit integers past . Use gammaln (log-gamma) to perform arithmetic in log-space:
from scipy.special import gamma, gammaln
print(gamma(5)) # 4! = 24Testing Log-Gamma & Log-Sum-Exp
Example
Output:
5. Try It Yourself
Problem: Compute Distance Matrix
Compute the Euclidean distance between point p1 = (1, 2) and p2 = (4, 6) using scipy.spatial.distance.euclidean.
Show solution
from scipy.spatial import distance
d = distance.euclidean((1.0, 2.0), (4.0, 6.0))
print(f"Distance: {d:.4f}")