commute.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import heapq
  2. import hashlib
  3. import json
  4. import random
  5. import requests
  6. import config
  7. import db
  8. import geo_util
  9. class TransitMethod:
  10. DRIVING = 'driving'
  11. WALKING = 'walking'
  12. CYCLING = 'bicycling'
  13. TRANSIT = 'transit'
  14. def _get_key(*args, **kwargs):
  15. length = kwargs.get('length', 12)
  16. k = ','.join([str(x) for x in args]).encode('utf-8')
  17. return hashlib.md5(k).hexdigest()[-length:]
  18. def _record_api_response(response):
  19. stmt = 'replace into transit (id, mode, submode, description, src_lat, src_lon, dest_lat, dest_lon, distance, duration, time, 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. description = None
  31. if step.get('transit_details'):
  32. transit_details = step['transit_details']
  33. line = transit_details.get('line',{})
  34. description = '%s (%s): %s -> %s' % (
  35. submode,
  36. line.get('name', line.get('short_name', '--')) if line else '--',
  37. transit_details.get('departure_stop', {}).get('name', '--'),
  38. transit_details.get('arrival_stop', {}).get('name', '--'),
  39. )
  40. stmt += ' (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
  41. params.extend([
  42. _get_key(source, destination, mode, submode),
  43. mode,
  44. submode,
  45. description,
  46. source[0],
  47. source[1],
  48. destination[0],
  49. destination[1],
  50. distance,
  51. duration,
  52. db.now(),
  53. json.dumps(step),
  54. ])
  55. with db.connect() as conn:
  56. conn.execute(stmt[:-1], *params)
  57. def directions_call(source, destination, mode):
  58. # doc: https://developers.google.com/maps/documentation/directions/intro
  59. url = 'https://maps.googleapis.com/maps/api/directions/json?origin=%s,%s&destination=%s,%s&key=%s&mode=%s&arrival_time=%i&alternatives=true'
  60. params = (
  61. source[0],
  62. source[1],
  63. destination[0],
  64. destination[1],
  65. config.GCLOUD_API_KEY,
  66. mode,
  67. config.WORKPLACE_TARGET_TIME,
  68. )
  69. resp = requests.get(url % params)
  70. resp_data = resp.json()
  71. if not resp_data.get('routes'):
  72. return
  73. _record_api_response(resp_data)
  74. def load_graph():
  75. graph = {
  76. config.WORKPLACE: {}
  77. }
  78. with db.connect() as conn:
  79. rows = conn.select('select id, mode, submode, description, dest_lat, dest_lon, src_lat, src_lon, duration from transit')
  80. for key, mode, submode, description, src_lat, src_lon, dest_lat, dest_lon, duration in rows:
  81. src = src_lat, src_lon
  82. dest = dest_lat, dest_lon
  83. if dest not in graph:
  84. graph[dest] = {}
  85. if src not in graph:
  86. graph[src] = {}
  87. graph[src][key] = {
  88. 'source': src,
  89. 'mode': mode,
  90. 'dest': (dest_lat, dest_lon),
  91. 'duration': duration,
  92. 'desc': description or submode,
  93. }
  94. locs = list(graph.keys())
  95. for i, loc in enumerate(locs):
  96. for secondary_loc in locs[i+1:]:
  97. distance = int(geo_util.ggcd(loc, secondary_loc))
  98. if 0 < distance < 500:
  99. k = 'w-' + _get_key(loc, secondary_loc, length=8)
  100. est_walk_duration = distance
  101. if secondary_loc not in [x['dest'] for x in graph[loc].values()]:
  102. graph[loc][k + '-1'] = {
  103. 'source': loc,
  104. 'dest': secondary_loc,
  105. 'mode': TransitMethod.WALKING.upper(),
  106. 'duration': est_walk_duration,
  107. 'desc': None,
  108. }
  109. if loc not in [x['dest'] for x in graph[secondary_loc].values()]:
  110. graph[secondary_loc][k + '-1'] = {
  111. 'source': secondary_loc,
  112. 'dest': loc,
  113. 'mode': TransitMethod.WALKING.upper(),
  114. 'duration': est_walk_duration,
  115. 'desc': None,
  116. }
  117. return graph
  118. def determine_fastest_paths(graph, source):
  119. indices = {}
  120. for loc in graph:
  121. if loc not in indices:
  122. indices[loc] = len(indices)
  123. queue = [(0, source, [])]
  124. heapq.heapify(queue)
  125. commutes = {}
  126. i = 0
  127. while queue:
  128. current_duration, current_source, current_path = heapq.heappop(queue)
  129. if current_source in commutes and commutes[current_source]['duration'] < current_duration:
  130. continue
  131. commutes[current_source] = {
  132. 'duration': current_duration,
  133. 'path': current_path,
  134. }
  135. for key, dest_data in graph[current_source].items():
  136. heapq.heappush(queue, (
  137. current_duration + max(1, dest_data['duration']),
  138. dest_data['dest'],
  139. current_path + [key]
  140. ))
  141. i += 1
  142. return commutes
  143. def log_graph(graph, commutes):
  144. paths = {}
  145. for loc, paths_data in graph.items():
  146. for k, path_data in paths_data.items():
  147. # path_data.update({
  148. # 'source': loc
  149. # })
  150. paths[k] = path_data
  151. for loc, data in sorted(commutes.items(), key=lambda x: x[1]['duration']):
  152. print(loc, data)
  153. for k in data['path']:
  154. print('\t', k, sorted(paths[k].items()))
  155. print('')
  156. def write_kml(commutes, fname):
  157. with open(fname, 'w') as f:
  158. f.write('''<?xml version="1.0" encoding="UTF-8"?>
  159. <kml xmlns="http://www.opengis.net/kml/2.2">
  160. <Document>
  161. ''')
  162. for i in range(256):
  163. hexvalue = hex(255-i)[2:].lower()
  164. if len(hexvalue) == 1:
  165. hexvalue = '0' + hexvalue
  166. f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
  167. max_duration = min(4000, max([x['duration'] for x in commutes.values()]))
  168. f.write('''
  169. <Folder>
  170. <visibility>0</visibility>
  171. <name>bbox</name>
  172. <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
  173. <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
  174. </Folder>
  175. ''' % (config.MONITORED_BBOX[0][1], config.MONITORED_BBOX[0][0], config.MONITORED_BBOX[1][1], config.MONITORED_BBOX[1][0]))
  176. f.write('<Folder>\n')
  177. f.write('<name>Commutes</name>\n')
  178. for loc, commute in commutes.items():
  179. duration = commute['duration']
  180. color = 20 + int((duration/float(max_duration)) * 236)
  181. color = min(color, 255)
  182. f.write('''<Placemark>
  183. <Point><coordinates>%f,%f</coordinates></Point>
  184. <styleUrl>#color-%i</styleUrl>
  185. <name>%s</name>
  186. <description>%s</description>
  187. </Placemark>\n''' % (loc[1], loc[0], color, int(duration / 60), loc))
  188. f.write('</Folder>')
  189. f.write('''
  190. </Document>
  191. </kml>
  192. ''')
  193. def analyze_locations(commutes):
  194. with db.connect() as conn:
  195. locs = config.MONITORED_LOCALITIES
  196. rows = conn.select('''select p.id, p.lat, p.lon from properties p
  197. where lat is not null and lon is not null''')
  198. random.shuffle(rows)
  199. to_load = []
  200. for property_id, lat, lon in rows:
  201. closest = None
  202. closest_dist = None
  203. for loc in commutes:
  204. dist = abs(loc[0] - lat) ** 2 + abs(loc[1] - lon) ** 2
  205. if closest_dist is None or dist < closest_dist:
  206. closest = loc
  207. closest_dist = dist
  208. target_loc = (lat, lon)
  209. if (geo_util.ggcd(target_loc, closest) > 200
  210. and geo_util.inside(target_loc, config.MONITORED_BBOX)):
  211. to_load.append(target_loc)
  212. print('Remaining to load: %i' % len(to_load))
  213. # target = (53.699593,-6.259772)
  214. # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
  215. # to_load.sort(key=lambda loc: scores[loc])
  216. for loc in to_load[:1]:
  217. print('Loading %s...' % list(loc))
  218. directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
  219. if __name__ == '__main__':
  220. # _record_api_response(data.x)
  221. # exit()
  222. graph = load_graph()
  223. commutes = determine_fastest_paths(graph, config.WORKPLACE)
  224. write_kml(commutes, 'vis.kml')
  225. # analyze_locations(commutes)
  226. log_graph(graph, commutes)