Last active
December 16, 2015 18:29
-
-
Save abrookins/5478445 to your computer and use it in GitHub Desktop.
Example code for in-memory proximity search with Python (1).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy.spatial import cKDTree | |
from scipy import inf | |
# ... Some code removed for clarity ... | |
class PortlandCrimeTracker(object): | |
DEFAULT_DATABASE_NAME = 'db' | |
def __init__(self, db_filename=DEFAULT_DATABASE_NAME): | |
crime_db = self.load_crimes_db(db_filename) | |
self.crimes = crime_db['crimes'] | |
self.points = self.crimes.keys() | |
self.crime_kdtree = cKDTree(self.points) | |
def get_points_nearby(self, point, max_points=250): | |
""" | |
Find the nearest points within 1/2 a mile of the tuple ``point``, to a | |
maximum of ``max_points``. | |
""" | |
# Find crimes within approximately 1/2 a mile. 1/4 mile is .005, | |
# 1/2 mile is .01, full mile is .02. | |
distances, indices = self.crime_kdtree.query(point, k=max_points, | |
distance_upper_bound=0.01) | |
point_neighbors = [] | |
for index, max_points in zip(indices, distances): | |
if max_points == inf: | |
break | |
point_neighbors.append(self.points[index]) | |
return point_neighbors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment