Last active
August 15, 2019 15:06
-
-
Save dice89/c7c4adabded1425e5cdcdb045ad1b5f8 to your computer and use it in GitHub Desktop.
Spatial indexing Approaches
This file contains hidden or 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
| RADIANT_TO_KM_CONSTANT = 6367 | |
| import proximitypyhash as ppyh | |
| import pygeohash as pgh | |
| from sklearn.neighbors import DistanceMetric | |
| import numpy as np | |
| from collections import defaultdict | |
| class GeoHashIndexer: | |
| def __init__(self, precision, lat_longs): | |
| self.index = defaultdict(list) | |
| # build the index | |
| for lat_long in lat_longs: | |
| lat = lat_long[0] | |
| long = lat_long[1] | |
| geo_hash = pgh.encode(lat, long, precision=precision) | |
| lat_long_radian = np.radians(np.array(lat_long)) | |
| self.index[geo_hash].append(lat_long_radian) | |
| self.precision = precision | |
| self.haversine = DistanceMetric.get_metric('haversine') | |
| self.lat_longs = lat_longs | |
| def query_radius(self, query, radius): | |
| candidate_geohashes = ppyh.get_geohash_radius_approximation(latitude=query[0], | |
| longitude=query[1], | |
| radius=radius, | |
| precision=self.precision, | |
| georaptor_flag=False) | |
| candidate_points = [] | |
| for geohash in candidate_geohashes: | |
| if geohash in self.index.keys(): | |
| candidate_points.extend(self.index[geohash]) | |
| if not candidate_points: | |
| return [] | |
| query = np.radians(np.array([query])) | |
| result = self.haversine.pairwise(candidate_points, query) | |
| # convert radiant radius to meters | |
| radius_km = radius / 1e3 | |
| radius_radiant = radius_km / RADIANT_TO_KM_CONSTANT | |
| result = result[result < radius_radiant] | |
| return result * RADIANT_TO_KM_CONSTANT * 1000 # get meters again |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On line 31 is there a reason you switched to using the keys method here? Doesn't this change the complexity from O(1) to O(n) in python 2 & something worse than O(1) in python 3?
https://stackoverflow.com/a/17539425