-
Notifications
You must be signed in to change notification settings - Fork 7
/
osrm.py
359 lines (276 loc) · 10.2 KB
/
osrm.py
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import asyncio
import collections.abc
import enum
import logging
import numbers
import random
try:
import ujson as json
except ImportError:
import json
from urllib.parse import urlencode
logger = logging.getLogger(__name__)
try:
import aiohttp
except ImportError:
aiohttp = None
try:
import requests
except ImportError:
requests = None
if not (aiohttp or requests):
logger.error('Could not import none of modules \'aiohttp\' or \'requests\'')
class overview(enum.Enum):
simplified = 'simplified'
full = 'full'
false = 'false'
# alias for avoiding name collision
osrm_overview = overview
class geometries(enum.Enum):
polyline = 'polyline'
polyline6 = 'polyline6'
geojson = 'geojson'
# alias for avoiding name collision
osrm_geometries = geometries
class gaps(enum.Enum):
split = 'split'
ignore = 'ignore'
# alias for avoiding name collision
osrm_gaps = gaps
class continue_straight(enum.Enum):
default = 'default'
true = 'true'
false = 'false'
# alias for avoiding name collision
osrm_continue_straight = continue_straight
class OSRMException(Exception):
pass
class OSRMServerException(OSRMException):
pass
class OSRMClientException(OSRMException):
pass
def _check_pairs(items):
''' checking that 'items' has format [[Number, Number], ...]'''
return (
isinstance(items, collections.abc.Iterable) and
all([isinstance(p, collections.abc.Iterable) for p in items]) and
all([
isinstance(p[0], numbers.Number) and
isinstance(p[1], numbers.Number) and
len(p) == 2
for p in items]))
class BaseRequest:
def __init__(self, coordinates, radiuses=[], bearings=[], hints=[]):
assert _check_pairs(coordinates), \
'''coordinates must be in format [[longitude, latitude],...]'''
assert all([
-180 <= lon <= 180 and -90 <= lat <= 90
for lon, lat in coordinates]), \
''''longitude' should be -180..180 and 'latitude' should be -90..90 (actual: {})'''.format(coordinates)
assert _check_pairs(bearings), \
'''bearings must be in format [[value, range],...]'''
assert all([
0 <= bvalue <= 360 and 0 <= brange <= 180
for bvalue, brange in bearings]), \
'''bearing 'value' should be 0..360 and 'range' should be 0..180 (actual: {})'''.format(bearings)
assert isinstance(radiuses, list)
assert isinstance(bearings, list)
assert isinstance(hints, list)
self.coordinates = coordinates
self.radiuses = radiuses
self.bearings = bearings
self.hints = hints
def get_coordinates(self):
return self._encode_pairs(self.coordinates)
def get_options(self):
return {
'radiuses': self._encode_array(self.radiuses),
'bearings': self._encode_pairs(self.bearings),
'hints': self._encode_array(self.hints)
}
def _encode_array(self, value):
return ';'.join(map(lambda x: str(x) if x else "", value))
def _encode_bool(self, value):
return 'true' if value else 'false'
def _encode_pairs(self, coordinates):
return ';'.join([','.join(map(str, coord)) for coord in coordinates])
def decode_response(self, url, status, response):
if status == 200:
return json.loads(response)
elif status == 400:
raise OSRMClientException(json.loads(response))
raise OSRMServerException(url, response)
class NearestRequest(BaseRequest):
service = 'nearest'
def __init__(self, number=1, **kwargs):
super().__init__(**kwargs)
self.number = number
def get_options(self):
options = super().get_options()
options['number'] = self.number
return options
class RouteRequest(BaseRequest):
service = 'route'
def __init__(
self,
alternatives=False,
steps=False, annotations=False,
geometries=geometries.geojson,
overview=overview.simplified,
continue_straight=continue_straight.default,
**kwargs):
super().__init__(**kwargs)
assert isinstance(alternatives, bool)
assert isinstance(steps, bool)
assert isinstance(annotations, bool)
assert isinstance(geometries, osrm_geometries)
assert isinstance(overview, osrm_overview)
assert isinstance(continue_straight, osrm_continue_straight)
self.alternatives = alternatives
self.steps = steps
self.annotations = annotations
self.geometries = geometries
self.overview = overview
self.continue_straight = continue_straight
def get_options(self):
options = super().get_options()
options.update({
'alternatives': self._encode_bool(self.alternatives),
'steps': self._encode_bool(self.steps),
'annotations': self._encode_bool(self.annotations),
'geometries': self.geometries.value,
'overview': self.overview.value
})
if self.continue_straight != continue_straight.default:
options['continue_straight'] = self.continue_straight.value
return options
class MatchRequest(RouteRequest):
service = 'match'
def __init__(
self,
timestamps=[],
gaps=gaps.split,
tidy=False,
**kwargs):
super().__init__(**kwargs)
assert isinstance(timestamps, list)
assert isinstance(gaps, osrm_gaps)
assert isinstance(tidy, bool)
self.timestamps = timestamps
self.gaps = gaps
self.tidy = tidy
def get_options(self):
options = super().get_options()
options.pop('alternatives', None)
options['timestamps'] = self._encode_array(self.timestamps)
# Don't send default values (for compatibility with 5.6)
if self.gaps.value != osrm_gaps.split:
options['gaps'] = self.gaps.value
if self.tidy:
options['tidy'] = self._encode_bool(self.tidy)
return options
class BaseClient:
def __init__(
self,
host='http://localhost:5000',
version='v1', profile='driving',
timeout=5, max_retries=5):
assert isinstance(host, str)
assert isinstance(version, str)
assert isinstance(profile, str)
assert isinstance(timeout, numbers.Number)
assert isinstance(max_retries, int) and max_retries >= 1
self.host = host
self.version = version
self.profile = profile
self.timeout = timeout
self.max_retries = max_retries
def _build_request(self, request):
url = '{host}/{service}/{version}/{profile}/{coordinates}'.format(
host=self.host,
service=request.service,
version=self.version,
profile=self.profile,
coordinates=request.get_coordinates())
params = {
k: v
for k, v in request.get_options().items()
if v
}
logger.debug('request url=%s; params=%s', url, params)
return (url, params)
class Client(BaseClient):
def __init__(self, *args, session=None, **kwargs):
super().__init__(*args, **kwargs)
if not requests:
raise RuntimeError('Module \'requests\' is not available')
self.session = session or requests.Session()
self.a = requests.adapters.HTTPAdapter(max_retries=self.max_retries)
self.session.mount('http://', self.a)
def nearest(self, **kwargs):
return self._request(
NearestRequest(**kwargs)
)
def route(self, **kwargs):
return self._request(
RouteRequest(**kwargs)
)
def match(self, **kwargs):
return self._request(
MatchRequest(**kwargs)
)
def _request(self, request):
if not requests:
raise RuntimeError('Module \'requests\' is not available')
url, params = self._build_request(request)
response = self.session.get(url, params=params, timeout=self.timeout)
return request.decode_response(url, response.status_code, response.text)
class AioHTTPClient(BaseClient):
BACKOFF_MAX = 120
BACKOFF_FACTOR = 0.5
def __init__(self, *args, session=None, loop=None, **kwargs):
super().__init__(*args, **kwargs)
if not aiohttp:
raise RuntimeError('Module \'aiohttp\' is not available')
if not session:
self.loop = loop or asyncio.get_event_loop()
self.session = aiohttp.ClientSession(loop=self.loop)
else:
self.session = session
async def nearest(self, **kwargs):
return await self._request(
NearestRequest(**kwargs)
)
async def route(self, **kwargs):
return await self._request(
RouteRequest(**kwargs)
)
async def match(self, **kwargs):
return await self._request(
MatchRequest(**kwargs)
)
def exp_backoff(self, attempt):
timeout = min(self.timeout * (2 ** attempt), self.BACKOFF_MAX)
return timeout + random.uniform(0, self.BACKOFF_FACTOR * timeout)
async def _request(self, request):
url, params = self._build_request(request)
attempt = 0
while attempt < self.max_retries:
try:
# This is a workaround for the https://github.com/aio-libs/aiohttp/issues/1901
request_url = "{}?{}".format(url, urlencode(params))
async with self.session.get(
request_url, timeout=self.timeout) as response:
body = await response.text()
return request.decode_response(
response.url, response.status, body)
except asyncio.TimeoutError:
timeout = self.exp_backoff(attempt)
logger.info(
'Timeout error url=%s (remaining tries %s, sleeping %.2f secs)',
url, self.max_retries - attempt, timeout)
await asyncio.sleep(timeout)
attempt += 1
raise OSRMServerException(url, 'server timeout')
async def close(self):
await self.session.close()