typestar

Spatial queries in Python

Distances, nearest neighbours and hulls over point sets.

import numpy as np
from scipy import spatial

points = np.array([[0.0, 0.0], [1.0, 0.5], [3.0, 3.0], [4.0, 0.5]])
query = np.array([[1.2, 0.6]])

print(spatial.distance.cdist(query, points).round(3))
print(round(spatial.distance.euclidean(points[0], points[2]), 4))

tree = spatial.KDTree(points)
distance, index = tree.query(query, k=2)
print(distance.round(3), index)

hull = spatial.ConvexHull(points)
print(sorted(hull.vertices.tolist()), round(hull.volume, 2))

How it works

  1. cdist gives every pairwise distance between two sets.
  2. KDTree answers nearest-neighbour queries in log time.
  3. ConvexHull returns the vertices of the enclosing polygon.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
465
Tokens
159
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 3 of 4 in Sparse & spatial, step 21 of 23 in Scientific computing with SciPy.

← Previous Next →