commute.py 9.3 KB

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