This repository has been archived by the owner on Feb 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaps.py
436 lines (368 loc) · 11.4 KB
/
maps.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import googlemaps
import requests
import collections
import json
from datetime import datetime
import time
import random
import sys
import math
def globals():
global returnHome
global fixedEnd
global fixedOrigin
returnHome = False
fixedEnd = False
fixedOrigin = False
def randomRestart(items):
shuffled = list(items)
if(fixedOrigin):
shuffled = list(shuffled[1:]) # if origin is fixed, the first element isn't shuffled
if(fixedEnd):
shuffled = list(shuffled[:-1]) # if destination is fixed, the last element isn't shuffled
random.shuffle(shuffled)
if(fixedOrigin):
shuffled.insert(0,items[0]) # fixed origin -> add starting point on top
if(fixedEnd):
shuffled.append(items[-1]) # fixed destination -> add destination point on bottom
if(returnHome):
shuffled.append(shuffled[0]) # if returning home, add the first element to the bottom of the list
return shuffled
def rad(x):
return x * math.pi/180
def getDistanceFromAtoB(placeA,placeB):
url = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins='+placeA.replace(' ','+')+'&destinations='+placeB.replace(' ','+')+'&departure_time='+str(int(time.mktime(datetime.now().timetuple())))+'&mode=driving&traffic_model=best_guess&key=AIzaSyBDRaVrNOA74dFlno67A_pEMKNQHA5bPvk'
r = requests.get(url)
x = json.loads(r.text)['rows'][0]['elements']
if x[0]['status']=='OK':
return x[0]['distance']['value']
if x[0]['status']=='ZERO_RESULTS':
gmaps = googlemaps.Client(key='AIzaSyBDRaVrNOA74dFlno67A_pEMKNQHA5bPvk')
A_coord = gmaps.geocode(placeA)[0]['geometry']['location']
B_coord = gmaps.geocode(placeB)[0]['geometry']['location']
R = 6378137
dLat = rad(B_coord['lat'] - A_coord['lat'])
dLong = rad(B_coord['lng'] - A_coord['lng'])
a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(rad(A_coord['lat'])) * math.cos(rad(B_coord['lat'])) * math.sin(dLong / 2) * math.sin(dLong / 2);
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = R * c
return int(d)
sys.stdout.write("\rERRO:")
sys.stdout.flush()
print("\n\n"+r.text+"\n\n")
raise SystemExit
def getScore(route, edges):
score = 0
for i in range(0,len(route)-1):
score = score + edges[route[i]][route[i+1]]
return score
def listToString(lista):
return ''.join(lista)
def getMaxNeighbour(rota, edges):
aux = list(rota)
aux_score = 0
best = list(rota)
best_score = sys.maxsize
if returnHome or (fixedOrigin and fixedEnd):
i = 0
for placeA in aux[1:-1]:
i=i+1
j=0
for placeB in aux[1:-1]:
j=j+1
if(placeA==placeB):
break
aux[i], aux[j] = aux[j], aux[i]
if listToString(aux) in tabu:
aux_score = getScore(aux,edges)
if aux_score < best_score:
best_score = aux_score
best = list(aux)
aux[i], aux[j] = aux[j], aux[i]
return best
if fixedOrigin:
i = 0
for placeA in aux[1:]:
i=i+1
j=0
for placeB in aux[1:]:
j=j+1
if(placeA==placeB):
break
aux[i], aux[j] = aux[j], aux[i]
if listToString(aux) in tabu:
aux_score = getScore(aux,edges)
if aux_score < best_score:
best_score = aux_score
best = list(aux)
aux[i], aux[j] = aux[j], aux[i]
return best
if fixedEnd:
i=-1
for placeA in aux[:-1]:
i=i+1
j=-1
for placeB in aux[:-1]:
j=j+1
if(placeA==placeB):
break
aux[i], aux[j] = aux[j], aux[i]
if listToString(aux) in tabu:
aux_score = getScore(aux,edges)
if aux_score < best_score:
best_score = aux_score
best = list(aux)
aux[i], aux[j] = aux[j], aux[i]
return best
i=-1
for placeA in aux:
i=i+1
j=-1
for placeB in aux:
j=j+1
if(placeA==placeB):
break
aux[i], aux[j] = aux[j], aux[i]
if listToString(aux) in tabu:
aux_score = getScore(aux,edges)
if aux_score < best_score:
best_score = aux_score
best = list(aux)
aux[i], aux[j] = aux[j], aux[i]
return best
# ------------------- END OF DEFINITIONS ----------------
# ---------------------- START OF MAIN ---------------------------
globals()
if len(sys.argv)==1:
returnHome=False
else:
if("--return-home" in sys.argv or "-r" in sys.argv):
returnHome=True
if("--fixed-origin" in sys.argv or "-fo" in sys.argv):
fixedOrigin=True
if("--fixed-end" in sys.argv or "-fe" in sys.argv):
fixedEnd=True
if("--help" in sys.argv or "-h" in sys.argv):
print("Syntax: python maps.py [OPTIONS]")
print("Options:")
print("-h (or --help) -> print this menu")
print("-r (or --return-home)")
print("-fo (or --fixed-origin)")
print("-fe (or --fixed-end)")
raise SystemExit
print("Type the places you want to visit, separated by comma+blankspace:")
if(fixedEnd and returnHome):
print("You picked fixedEnd and returnHome, which isn't feasible. In this case, returnHome will have priority.")
fixedEnd = False
if(fixedOrigin):
print("You picked fixedOrigin, which means that the computed path will start on the first place you type.")
else:
print("You didn't pick fixedOrigin, which means that the computed path might start in any of the places you type.")
if(fixedEnd):
print("You picked fixedEnd, which means that the computed path will end on the last place you type.")
else:
print("You didn't pick fixedEnd, which means that the computed path might end in any of the places you type.")
if(returnHome):
print("You picked returnHome, which means that the computed path will consider that you want to return to the starting point, whichever it may be.")
places = input().split(", ")
#load known edges
known_edges = dict()
with open('edges.map','r') as f:
lines = f.readlines()
for line in lines:
known_edges[line.split(' : ')[0]] = int(line.split(' : ')[1])
f.closed
#compute all the edges (distance of suggested route between placeA and placeB)
edges = collections.defaultdict(dict)
dist = 0
with open('edges.map','a') as f:
for placeA in places:
for placeB in places:
if(placeA==placeB):
break
if listToString([placeA, placeB]) in known_edges:
dist = known_edges[listToString([placeA, placeB])]
else:
if listToString([placeB, placeA]) in known_edges:
dist = known_edges[listToString([placeB, placeA])]
else:
dist = getDistanceFromAtoB(placeA,placeB)
f.write("{0} {1} : {2}\n".format(placeA, placeB, dist))
edges[placeA][placeB] = dist
edges[placeB][placeA] = dist
sys.stdout.flush()
f.closed
rr = 0
tabu = dict()
rota_res = randomRestart(places)
rota_i = list(rota_res)
rota_ii = list(rota_res)
while rr < 1000:
sys.stdout.write('\rRunning Greedy Hill-Climb: %f %%' % (rr//10))
sys.stdout.flush()
rota_ii = getMaxNeighbour(rota_i,edges)
if(getScore(rota_i,edges)<=getScore(rota_ii,edges)):
rota_ii = randomRestart(places)
rr=rr+1
if(getScore(rota_ii,edges)<getScore(rota_res,edges)):
rota_res=rota_ii
tabu[listToString(rota_i)] = 1
rota_i = rota_ii
print('\n\n')
print('Final path: {0}'.format(rota_res))
print('Total distance: {0}'.format(getScore(rota_res,edges)/1000))
gmaps = googlemaps.Client(key='AIzaSyBDRaVrNOA74dFlno67A_pEMKNQHA5bPvk')
html = """
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var flightPlanCoordinates = [];
var renderArray = [];
var requestArray = [];
var req;
var map;
var directionsService;
function generateRequests() {
"""
while len(rota_res) > 1:
aux=list(rota_res[:2])
rota_res = list(rota_res[1:])
html += """
requestArray.push({
origin: '%s',
destination: '%s',
travelMode: google.maps.TravelMode.DRIVING
});
""" % (aux[0], aux[-1])
html += """
processRequests();
}
function processRequests(){
var i = 0;
function submitRequest(){
directionsService.route(requestArray[i], directionResults);
}
function directionResults(result, status) {
var geocoder = new google.maps.Geocoder();
if (status == google.maps.DirectionsStatus.OK) {
renderArray[i] = new google.maps.DirectionsRenderer();
renderArray[i].setMap(map);
renderArray[i].setOptions({
preserveViewport: true,
suppressInfoWindows: true,
polylineOptions: {
strokeWeight: 4,
strokeOpacity: 0.8,
strokeColor: 'red'
},
markerOptions:{
icon:{
path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW,
scale: 2,
strokeColor: 'blue'
}
}
});
renderArray[i].setDirections(result);
nextRequest();
}
if(status == google.maps.DirectionsStatus.ZERO_RESULTS){
geocoder.geocode( {address:requestArray[i].origin}, geocoderResults1);
}
}
function geocoderResults1(results,status){
if (status == google.maps.GeocoderStatus.OK){
flightPlanCoordinates.push(results[0].geometry.location);
new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon:{
path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW,
scale: 2,
strokeColor: 'blue'
}
});
}
else{
alert('Geocode was not successful for the following reason: ' + status);
}
nextGeo();
}
function nextGeo(){
var geocoder2 = new google.maps.Geocoder();
geocoder2.geocode( {address:requestArray[i].destination}, geocoderResults2);
}
function geocoderResults2(results,status){
if (status == google.maps.GeocoderStatus.OK){
flightPlanCoordinates.push(results[0].geometry.location);
new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon:{
path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW,
scale: 2,
strokeColor: 'blue'
}
});
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: 'yellow',
strokeOpacity: 1.0,
strokeWeight: 4
});
flightPath.setMap(map);
flightPlanCoordinates = [];
nextRequest();
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
}
function nextRequest(){
i++;
if(i >= requestArray.length){
return;
}
submitRequest();
}
submitRequest();
}
function initMap() {
directionsService = new google.maps.DirectionsService();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center:
"""
html += str(gmaps.geocode(rota_res[0])[0]['geometry']['location'])
html += """
});
generateRequests();
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBdJo19l4Np9c_H-JtYN-PeB9o37ZKfrT8&signed_in=true&callback=initMap"></script>
</body>
</html>
"""
filename=input('Output file name: ')
filename=filename+'.html'
with open(filename, 'w') as f:
f.write(html)
f.closed