commute.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import heapq
  2. import hashlib
  3. import json
  4. import random
  5. import requests
  6. import config
  7. import data
  8. import db
  9. import geo_util
  10. class TransitMethod:
  11. DRIVING = 'driving'
  12. WALKING = 'walking'
  13. CYCLING = 'bicycling'
  14. TRANSIT = 'transit'
  15. def _get_key(*args):
  16. k = ','.join([str(x) for x in args]).encode('utf-8')
  17. return hashlib.md5(k).hexdigest()[-12:]
  18. def _record_api_response(response):
  19. stmt = 'replace into transit (id, mode, submode, src_lat, src_lon, dest_lat, dest_lon, distance, duration, raw_json) VALUES'
  20. params = []
  21. for route in response.get('routes', []):
  22. for leg in route.get('legs', []):
  23. for step in leg.get('steps', []):
  24. distance = step['distance']['value']
  25. duration = step['duration']['value']
  26. source = round(step['start_location']['lat'], 10), round(step['start_location']['lng'], 10)
  27. destination = round(step['end_location']['lat'], 10), round(step['end_location']['lng'], 10)
  28. mode = step['travel_mode']
  29. submode = step.get('transit_details', {}).get('line', {}).get('vehicle', {}).get('type')
  30. stmt += ' (?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
  31. params.extend([
  32. _get_key(source, destination, mode, submode),
  33. mode,
  34. submode,
  35. source[0],
  36. source[1],
  37. destination[0],
  38. destination[1],
  39. distance,
  40. duration,
  41. json.dumps(step),
  42. ])
  43. with db.connect() as conn:
  44. conn.execute(stmt[:-1], *params)
  45. def directions_call(source, destination, mode):
  46. # doc: https://developers.google.com/maps/documentation/directions/intro
  47. url = 'https://maps.googleapis.com/maps/api/directions/json?origin=%s,%s&destination=%s,%s&key=%s&mode=%s&arrival_time=%i&alternatives=true'
  48. params = (
  49. source[0],
  50. source[1],
  51. destination[0],
  52. destination[1],
  53. config.GCLOUD_API_KEY,
  54. mode,
  55. config.WORKPLACE_TARGET_TIME,
  56. )
  57. resp = requests.get(url % params)
  58. print(resp.status_code)
  59. print(json.dumps(resp.json()))
  60. resp_data = resp.json()
  61. print('"%s"' % config.GCLOUD_API_KEY)
  62. if not resp_data.get('routes'):
  63. return
  64. # resp_data = data.x
  65. _record_api_response(resp_data)
  66. def load_graph():
  67. graph = {
  68. config.WORKPLACE: {}
  69. }
  70. with db.connect() as conn:
  71. rows = conn.select('select id, mode, dest_lat, dest_lon, src_lat, src_lon, duration from transit')
  72. for key, mode, src_lat, src_lon, dest_lat, dest_lon, duration in rows:
  73. src = src_lat, src_lon
  74. dest = dest_lat, dest_lon
  75. if dest not in graph:
  76. graph[dest] = {}
  77. if src not in graph:
  78. graph[src] = {}
  79. for lat, lon in graph:
  80. distance = int(geo_util.ggcd(lon, lat, src_lon, src_lat))
  81. if 0 < distance < 500:
  82. k = 'w-' + _get_key(lon, lat, src_lon, src_lat)
  83. est_walk_duration = distance
  84. graph[src][k] = {
  85. 'mode': TransitMethod.WALKING.upper(),
  86. 'dest': (lat, lon),
  87. 'duration': est_walk_duration,
  88. }
  89. graph[lat,lon][k] = {
  90. 'mode': TransitMethod.WALKING.upper(),
  91. 'dest': src,
  92. 'duration': est_walk_duration,
  93. }
  94. graph[src][key] = {
  95. 'mode': mode,
  96. 'dest': (dest_lat, dest_lon),
  97. 'duration': duration,
  98. }
  99. # for k, v in graph.items():
  100. # print((k,v))
  101. # print(graph[config.WORKPLACE])
  102. return graph
  103. # directions_call((53.388631,-6.071959), config.WORKPLACE, TransitMethod.TRANSIT)
  104. def determine_fastest_paths(graph, source):
  105. indices = {}
  106. for loc in graph:
  107. if loc not in indices:
  108. indices[loc] = len(indices)
  109. # for loc in graph:
  110. # print('%i: %s' % (indices[loc], loc))
  111. # for k in graph[loc]:
  112. # print('\t%i\t%i\t%s\t%s' % (indices[graph[loc][k]['dest']], graph[loc][k]['duration'], graph[loc][k]['mode'], k))
  113. queue = [(0, source, [])]
  114. heapq.heapify(queue)
  115. current_min_durations = {}
  116. # print('\n\n\n')
  117. i = 0
  118. while queue:
  119. current_duration, current_source, current_path = heapq.heappop(queue)
  120. if current_source in current_min_durations and current_min_durations[current_source] < current_duration:
  121. continue
  122. # print('%i\t%s\t%i\t%s' % (indices[current_source], current_source, current_duration, current_path))
  123. current_min_durations[current_source] = current_duration
  124. for key, dest_data in graph[current_source].items():
  125. heapq.heappush(queue, (
  126. current_duration + max(1, dest_data['duration']),
  127. dest_data['dest'],
  128. current_path + [key]
  129. ))
  130. i += 1
  131. return current_min_durations
  132. def write_kml(commutes, fname):
  133. with open(fname, 'w') as f:
  134. f.write('''<?xml version="1.0" encoding="UTF-8"?>
  135. <kml xmlns="http://www.opengis.net/kml/2.2">
  136. <Document>
  137. ''')
  138. for i in range(256):
  139. hexvalue = hex(255-i)[2:].lower()
  140. if len(hexvalue) == 1:
  141. hexvalue = '0' + hexvalue
  142. f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
  143. max_duration = min(3600, max(commutes.values()))
  144. f.write('<Folder>\n')
  145. f.write('<name>Commutes</name>\n')
  146. for loc, duration in commutes.items():
  147. color = 20 + int((duration/float(max_duration)) * 236)
  148. f.write('\t<Placemark><Point><coordinates>%f,%f</coordinates></Point><styleUrl>#color-%i</styleUrl></Placemark>\n' % (loc[1], loc[0], color))
  149. f.write('</Folder>')
  150. f.write('''
  151. </Document>
  152. </kml>
  153. ''')
  154. def analyze_locations(commutes):
  155. with db.connect() as conn:
  156. rows = conn.select('select id, lat, lon from properties where lat is not null and lon is not null')
  157. random.shuffle(rows)
  158. to_load = []
  159. for property_id, lat, lon in rows:
  160. closest = None
  161. closest_dist = None
  162. for loc in commutes:
  163. dist = abs(loc[0] - lat) ** 2 + abs(loc[1] - lon) ** 2
  164. if closest_dist is None or dist < closest_dist:
  165. closest = loc
  166. closest_dist = dist
  167. if geo_util.ggcd(lon, lat, closest[1], closest[0]) > 200:
  168. to_load.append((lat,lon))
  169. print('Remaining to load: %i' % len(to_load))
  170. directions_call(to_load[0], config.WORKPLACE, TransitMethod.TRANSIT)
  171. if __name__ == '__main__':
  172. graph = load_graph()
  173. commutes = determine_fastest_paths(graph, config.WORKPLACE)
  174. write_kml(commutes, 'vis.kml')
  175. # analyze_locations(commutes)