spatial.kdtree

Module Contents

Classes

Rectangle(self,maxes,mins) Hyperrectangle class.
KDTree(self,data,leafsize=10) kd-tree for quick nearest-neighbor lookup

Functions

minkowski_distance_p(x,y,p=2) Compute the p-th power of the L**p distance between two arrays.
minkowski_distance(x,y,p=2) Compute the L**p distance between two arrays.
distance_matrix(x,y,p=2,threshold=1000000) Compute the distance matrix.
minkowski_distance_p(x, y, p=2)

Compute the p-th power of the L**p distance between two arrays.

For efficiency, this function computes the L**p distance but does not extract the pth root. If p is 1 or infinity, this is equal to the actual L**p distance.

x : (M, K) array_like
Input array.
y : (N, K) array_like
Input array.
p : float, 1 <= p <= infinity
Which Minkowski p-norm to use.
>>> from scipy.spatial import minkowski_distance_p
>>> minkowski_distance_p([[0,0],[0,0]], [[1,1],[0,1]])
array([2, 1])
minkowski_distance(x, y, p=2)

Compute the L**p distance between two arrays.

x : (M, K) array_like
Input array.
y : (N, K) array_like
Input array.
p : float, 1 <= p <= infinity
Which Minkowski p-norm to use.
>>> from scipy.spatial import minkowski_distance
>>> minkowski_distance([[0,0],[0,0]], [[1,1],[0,1]])
array([ 1.41421356,  1.        ])
class Rectangle(maxes, mins)

Hyperrectangle class.

Represents a Cartesian product of intervals.

__init__(maxes, mins)

Construct a hyperrectangle.

__repr__()
volume()

Total volume.

split(d, split)

Produce two hyperrectangles by splitting.

In general, if you need to compute maximum and minimum distances to the children, it can be done more efficiently by updating the maximum and minimum distances to the parent.

d : int
Axis to split hyperrectangle along.
split : float
Position along axis d to split at.
min_distance_point(x, p=2.0)

Return the minimum distance between input and points in the hyperrectangle.

x : array_like
Input.
p : float, optional
Input.
max_distance_point(x, p=2.0)

Return the maximum distance between input and points in the hyperrectangle.

x : array_like
Input array.
p : float, optional
Input.
min_distance_rectangle(other, p=2.0)

Compute the minimum distance between points in the two hyperrectangles.

other : hyperrectangle
Input.
p : float
Input.
max_distance_rectangle(other, p=2.0)

Compute the maximum distance between points in the two hyperrectangles.

other : hyperrectangle
Input.
p : float, optional
Input.
class KDTree(data, leafsize=10)

kd-tree for quick nearest-neighbor lookup

This class provides an index into a set of k-dimensional points which can be used to rapidly look up the nearest neighbors of any point.

data : (N,K) array_like
The data points to be indexed. This array is not copied, and so modifying this data will result in bogus results.
leafsize : int, optional
The number of points at which the algorithm switches over to brute-force. Has to be positive.
RuntimeError

The maximum recursion limit can be exceeded for large data sets. If this happens, either increase the value for the leafsize parameter or increase the recursion limit by:

>>> import sys
>>> sys.setrecursionlimit(10000)

cKDTree : Implementation of KDTree in Cython

The algorithm used is described in Maneewongvatana and Mount 1999. The general idea is that the kd-tree is a binary tree, each of whose nodes represents an axis-aligned hyperrectangle. Each node specifies an axis and splits the set of points based on whether their coordinate along that axis is greater than or less than a particular value.

During construction, the axis and splitting point are chosen by the “sliding midpoint” rule, which ensures that the cells do not all become long and thin.

The tree can be queried for the r closest neighbors of any given point (optionally returning only those within some maximum distance of the point). It can also be queried, with a substantial gain in efficiency, for the r approximate closest neighbors.

For large dimensions (20 is already large) do not expect this to run significantly faster than brute force. High-dimensional nearest-neighbor queries are a substantial open problem in computer science.

The tree also supports all-neighbors queries, both with arrays of points and with other kd-trees. These do use a reasonably efficient algorithm, but the kd-tree is not necessarily the best data structure for this sort of calculation.

__init__(data, leafsize=10)
class node
__lt__(other)
__gt__(other)
__le__(other)
__ge__(other)
__eq__(other)
class leafnode(idx)
__init__(idx)
class innernode(split_dim, split, less, greater)
__init__(split_dim, split, less, greater)
__build(idx, maxes, mins)
__query(x, k=1, eps=0, p=2, distance_upper_bound=None)
query(x, k=1, eps=0, p=2, distance_upper_bound=None)

Query the kd-tree for nearest neighbors

x : array_like, last dimension self.m
An array of points to query.
k : int, optional
The number of nearest neighbors to return.
eps : nonnegative float, optional
Return approximate nearest neighbors; the kth returned value is guaranteed to be no further than (1+eps) times the distance to the real kth nearest neighbor.
p : float, 1<=p<=infinity, optional
Which Minkowski p-norm to use. 1 is the sum-of-absolute-values “Manhattan” distance 2 is the usual Euclidean distance infinity is the maximum-coordinate-difference distance
distance_upper_bound : nonnegative float, optional
Return only neighbors within this distance. This is used to prune tree searches, so if you are doing a series of nearest-neighbor queries, it may help to supply the distance to the nearest neighbor of the most recent point.
d : float or array of floats
The distances to the nearest neighbors. If x has shape tuple+(self.m,), then d has shape tuple if k is one, or tuple+(k,) if k is larger than one. Missing neighbors (e.g. when k > n or distance_upper_bound is given) are indicated with infinite distances. If k is None, then d is an object array of shape tuple, containing lists of distances. In either case the hits are sorted by distance (nearest first).
i : integer or array of integers
The locations of the neighbors in self.data. i is the same shape as d.
>>> from scipy import spatial
>>> x, y = np.mgrid[0:5, 2:8]
>>> tree = spatial.KDTree(list(zip(x.ravel(), y.ravel())))
>>> tree.data
array([[0, 2],
       [0, 3],
       [0, 4],
       [0, 5],
       [0, 6],
       [0, 7],
       [1, 2],
       [1, 3],
       [1, 4],
       [1, 5],
       [1, 6],
       [1, 7],
       [2, 2],
       [2, 3],
       [2, 4],
       [2, 5],
       [2, 6],
       [2, 7],
       [3, 2],
       [3, 3],
       [3, 4],
       [3, 5],
       [3, 6],
       [3, 7],
       [4, 2],
       [4, 3],
       [4, 4],
       [4, 5],
       [4, 6],
       [4, 7]])
>>> pts = np.array([[0, 0], [2.1, 2.9]])
>>> tree.query(pts)
(array([ 2.        ,  0.14142136]), array([ 0, 13]))
>>> tree.query(pts[0])
(2.0, 0)
__query_ball_point(x, r, p=2.0, eps=0)
query_ball_point(x, r, p=2.0, eps=0)

Find all points within distance r of point(s) x.

x : array_like, shape tuple + (self.m,)
The point or points to search for neighbors of.
r : positive float
The radius of points to return.
p : float, optional
Which Minkowski p-norm to use. Should be in the range [1, inf].
eps : nonnegative float, optional
Approximate search. Branches of the tree are not explored if their nearest points are further than r / (1 + eps), and branches are added in bulk if their furthest points are nearer than r * (1 + eps).
results : list or array of lists
If x is a single point, returns a list of the indices of the neighbors of x. If x is an array of points, returns an object array of shape tuple containing lists of neighbors.

If you have many points whose neighbors you want to find, you may save substantial amounts of time by putting them in a KDTree and using query_ball_tree.

>>> from scipy import spatial
>>> x, y = np.mgrid[0:5, 0:5]
>>> points = np.c_[x.ravel(), y.ravel()]
>>> tree = spatial.KDTree(points)
>>> tree.query_ball_point([2, 0], 1)
[5, 10, 11, 15]

Query multiple points and plot the results:

>>> import matplotlib.pyplot as plt
>>> points = np.asarray(points)
>>> plt.plot(points[:,0], points[:,1], '.')
>>> for results in tree.query_ball_point(([2, 0], [3, 3]), 1):
...     nearby_points = points[results]
...     plt.plot(nearby_points[:,0], nearby_points[:,1], 'o')
>>> plt.margins(0.1, 0.1)
>>> plt.show()
query_ball_tree(other, r, p=2.0, eps=0)

Find all pairs of points whose distance is at most r

other : KDTree instance
The tree containing points to search against.
r : float
The maximum distance, has to be positive.
p : float, optional
Which Minkowski norm to use. p has to meet the condition 1 <= p <= infinity.
eps : float, optional
Approximate search. Branches of the tree are not explored if their nearest points are further than r/(1+eps), and branches are added in bulk if their furthest points are nearer than r * (1+eps). eps has to be non-negative.
results : list of lists
For each element self.data[i] of this tree, results[i] is a list of the indices of its neighbors in other.data.
query_pairs(r, p=2.0, eps=0)

Find all pairs of points within a distance.

r : positive float
The maximum distance.
p : float, optional
Which Minkowski norm to use. p has to meet the condition 1 <= p <= infinity.
eps : float, optional
Approximate search. Branches of the tree are not explored if their nearest points are further than r/(1+eps), and branches are added in bulk if their furthest points are nearer than r * (1+eps). eps has to be non-negative.
results : set
Set of pairs (i,j), with i < j, for which the corresponding positions are close.
count_neighbors(other, r, p=2.0)

Count how many nearby pairs can be formed.

Count the number of pairs (x1,x2) can be formed, with x1 drawn from self and x2 drawn from other, and where distance(x1, x2, p) <= r. This is the “two-point correlation” described in Gray and Moore 2000, “N-body problems in statistical learning”, and the code here is based on their algorithm.

other : KDTree instance
The other tree to draw points from.
r : float or one-dimensional array of floats
The radius to produce a count for. Multiple radii are searched with a single tree traversal.
p : float, 1<=p<=infinity, optional
Which Minkowski p-norm to use
result : int or 1-D array of ints
The number of pairs. Note that this is internally stored in a numpy int, and so may overflow if very large (2e9).
sparse_distance_matrix(other, max_distance, p=2.0)

Compute a sparse distance matrix

Computes a distance matrix between two KDTrees, leaving as zero any distance greater than max_distance.

other : KDTree

max_distance : positive float

p : float, optional

result : dok_matrix
Sparse matrix representing the results in “dictionary of keys” format.
distance_matrix(x, y, p=2, threshold=1000000)

Compute the distance matrix.

Returns the matrix of all pair-wise distances.

x : (M, K) array_like
Matrix of M vectors in K dimensions.
y : (N, K) array_like
Matrix of N vectors in K dimensions.
p : float, 1 <= p <= infinity
Which Minkowski p-norm to use.
threshold : positive int
If M * N * K > threshold, algorithm uses a Python loop instead of large temporary arrays.
result : (M, N) ndarray
Matrix containing the distance from every vector in x to every vector in y.
>>> from scipy.spatial import distance_matrix
>>> distance_matrix([[0,0],[0,1]], [[1,0],[1,1]])
array([[ 1.        ,  1.41421356],
       [ 1.41421356,  1.        ]])