-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathlocation.py
More file actions
262 lines (180 loc) · 7.65 KB
/
Copy pathlocation.py
File metadata and controls
262 lines (180 loc) · 7.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#Copyright 2011 Do@. All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification, are
#permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
# of conditions and the following disclaimer in the documentation and/or other materials
# provided with the distribution.
#
#THIS SOFTWARE IS PROVIDED BY Do@ ``AS IS'' AND ANY EXPRESS OR IMPLIED
#WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
#FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
#CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#The views and conclusions contained in the software and documentation are those of the
#authors and should not be interpreted as representing official policies, either expressed
#or implied, of Do@.
from .countries import countries
from geohasher import hasher
import math
import struct
import base64
import logging
class Location(object):
"""
This is the base class for all location subclasses
"""
__spec__ = ['lat', 'lon', 'name']
__keyspec__ = None
#keys should be named so we can query by the key names
_keys = {}
def __init__(self, **kwargs):
self.lat = float(kwargs.get('lat', None))
self.lon = float(kwargs.get('lon', None))
self.name = kwargs.get('name', '').strip()
@classmethod
def _key(cls, _valdict):
h = hash(':'.join((str(_valdict.get(x)) for x in cls.__keyspec__ or cls.__spec__)))
return '%s:%s' % (cls.__name__, base64.b64encode(struct.pack('q', h).strip('=')))
def getId(self):
#h = hash(':'.join((str(getattr(self, x)) for x in self.__keyspec__ or self.__spec__)))
#'%s:%s' % (self.__class__.__name__, base64.b64encode(struct.pack('q', h).strip('=')))
return self._key(self.__dict__)
def get(self, prop):
return getattr(self, prop)
@classmethod
def getGeohashIndexKey(cls):
return '%s:geohash' % cls.__name__
def save(self, redisConn):
#save all properties
redisConn.hmset(self.getId(), dict(((k, getattr(self, k)) for k in \
self.__spec__)))
self._indexGeohash(redisConn)
for k in self._keys.values():
k.save(self, redisConn)
def _indexGeohash(self, redisConn):
"""
Save the key of the object into the goehash index for this object type
"""
redisConn.zadd(self.getGeohashIndexKey(), self.getId(), hasher.encode(self.lat, self.lon))
def __str__(self):
return "%s: %s" % (self.__class__.__name__, self.__dict__)
def __repr__(self):
return "%s: %s" % (self.__class__.__name__, self.__dict__)
@classmethod
def load(cls, key, redisConn):
"""
a Factory function to load a location from a given location key
"""
d = redisConn.hgetall(str(key))
if not d:
return None
#build a new object based on the loaded dict
return cls(**d)
def score(self, refLat, refLon):
"""
To be implemented by child classes
"""
return 1
@classmethod
def multiLoad(cls, keys, redisConn):
"""
a Factory function to load a location from a given location key
"""
p = redisConn.pipeline()
[p.hgetall(str(key)) for key in keys]
rx = p.execute()
#build a new object based on the loaded dict
return [cls(**d) for d in rx if d is not None]
@classmethod
def getIdsByNamedKey(cls, keyName, redisConn, *args, **kwargs):
k = cls._keys[keyName]
return k.getIds(redisConn, *args, **kwargs)
@classmethod
def loadByNamedKey(cls, keyName, redisConn, *args, **kwargs):
"""
Load a class by a named key indexing some if its fields
"""
k = cls._keys[keyName]
ids = k.getIds(redisConn, *args, **kwargs)
logging.info("Found %d ids for %s",len(ids or []), keyName)
p = redisConn.pipeline(False)
[p.hgetall(id) for id in ids]
rx = p.execute()
ret = [cls(**d) for d in filter(None, rx)]
# for id in ids:
# ret.append(cls.load(id, redisConn))
return ret
@classmethod
def getByKey(cls, redisConn, **kwargs):
"""
Load an object by combining data from kwargs to create the unique key for this object
useful for loading ZIP codes with only the known zip
"""
key = cls._key(kwargs)
return cls.load(key, redisConn)
@classmethod
def getByLatLon(cls, lat, lon, redisConn):
geoKey = hasher.encode(lat, lon)
return cls.getByGeohash(geoKey, redisConn)
@staticmethod
def getDistance(geoHash1, geoHash2):
"""
Estimate the distance between 2 geohashes in uint64 format
"""
# return abs(geoHash1 - geoHash2)
try:
coords1 = hasher.decode(geoHash1)
coords2 = hasher.decode(geoHash2)
return Location.getLatLonDistance(coords1, coords2)
#return math.sqrt(math.pow(coords1[0] - coords2[0], 2) +
#math.pow(coords1[1] - coords2[1], 2))
except Exception as e:
print(e)
return None
@staticmethod
def getLatLonDistance(x, y):
R = 6371
dLat = math.radians(y[0]-x[0])
dLon = math.radians(y[1]-x[1])
a = math.sin(dLat/2) * math.sin(dLat/2) + \
math.cos( math.radians(x[0])) * math.cos( math.radians(y[0])) * \
math.sin(dLon/2) * math.sin(dLon/2);
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return R * c
@classmethod
def getByGeohash(cls, geoKey, redisConn):
"""
Get a location (used directly on a subclass only!) according to a geohash key
"""
key = cls.getGeohashIndexKey()
tx = redisConn.pipeline()
tx.zrangebyscore(key, geoKey, 'inf', 0, 10, True)
tx.zrevrangebyscore(key, geoKey, '-inf', 0, 10, True)
ret = tx.execute()
#find the two closest locations to the left and to the right of us
candidates = filter(None, ret[0]) + filter(None, ret[1])
closestDist = None
selected = None
if not candidates :
return None
for i in range(len(candidates)):
gk = long(candidates[i][1])
dist = Location.getDistance(geoKey, gk)
if dist is None:
continue
if not closestDist or dist < closestDist:
closestDist = dist
selected = i
if selected is None:
return None
return cls.load(str(candidates[selected][0]), redisConn)