Skip to content

Instantly share code, notes, and snippets.

@perrygeo
Created April 14, 2012 17:48
Show Gist options
  • Save perrygeo/2386206 to your computer and use it in GitHub Desktop.
Save perrygeo/2386206 to your computer and use it in GitHub Desktop.
K-D tree nearest neighbor search in n-dimensions
import numpy as np
from scipy.spatial import KDTree
def run_kdtree(ndim=8,npnts=500000):
"""
given a set of random n-dimensional points,
find the closest one to a given point
"""
print "Creating %d %d-dimensional points" % (npnts, ndim)
allpoints = np.random.random_sample((npnts, ndim)) * 100
tree = KDTree(allpoints)
print "------------- DATA ----------------"
print tree.data
querypoints = np.random.random_sample((1, ndim)) * 100
print "------------- QUERY FOR ----------------"
print querypoints
result = tree.query(querypoints)
print "------------- RESULTS ----------------"
print "Closest is point #", result[1][0], "... distance", result[0][0]
print "Closest point =", allpoints[result[1][0]]
run_kdtree()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment