commute.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. print('Loading stored transit data...')
  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. print('Creating additional commute links...')
  97. for i, loc in enumerate(locs):
  98. for secondary_loc in locs[i+1:]:
  99. distance = int(geo_util.ggcd(loc, secondary_loc))
  100. if 0 < distance < 500:
  101. k = 'w-' + _get_key(loc, secondary_loc, length=8)
  102. est_walk_duration = distance
  103. if secondary_loc not in [x['dest'] for x in graph[loc].values()]:
  104. graph[loc][k + '-1'] = {
  105. 'source': loc,
  106. 'dest': secondary_loc,
  107. 'mode': TransitMethod.WALKING.upper(),
  108. 'duration': est_walk_duration,
  109. 'desc': None,
  110. }
  111. if loc not in [x['dest'] for x in graph[secondary_loc].values()]:
  112. graph[secondary_loc][k + '-1'] = {
  113. 'source': secondary_loc,
  114. 'dest': loc,
  115. 'mode': TransitMethod.WALKING.upper(),
  116. 'duration': est_walk_duration,
  117. 'desc': None,
  118. }
  119. return graph
  120. def determine_fastest_paths(graph, source):
  121. print('Determining the fastest paths from transit locations to %s...' % str(source))
  122. links = {}
  123. for link_dict in graph.values():
  124. links.update(link_dict)
  125. indices = {}
  126. for loc in graph:
  127. if loc not in indices:
  128. indices[loc] = len(indices)
  129. queue = [(0, source, [])]
  130. heapq.heapify(queue)
  131. commutes = {}
  132. i = 0
  133. while queue:
  134. current_duration, current_source, current_path = heapq.heappop(queue)
  135. if current_source in commutes and commutes[current_source]['duration'] < current_duration:
  136. continue
  137. commutes[current_source] = {
  138. 'duration': current_duration,
  139. 'path': [links[link] for link in current_path],
  140. }
  141. for key, dest_data in graph[current_source].items():
  142. heapq.heappush(queue, (
  143. current_duration + max(1, dest_data['duration']),
  144. dest_data['dest'],
  145. current_path + [key]
  146. ))
  147. i += 1
  148. return commutes
  149. def log_graph(graph, commutes):
  150. paths = {}
  151. for loc, paths_data in graph.items():
  152. for k, path_data in paths_data.items():
  153. # path_data.update({
  154. # 'source': loc
  155. # })
  156. paths[k] = path_data
  157. for loc, data in sorted(commutes.items(), key=lambda x: x[1]['duration']):
  158. print(loc, data)
  159. for k in data['path']:
  160. print('\t', k, sorted(paths[k].items()))
  161. print('')
  162. def analyze_locations(commutes, num_locations):
  163. print('Loading new directions data for %i locations...' % num_locations)
  164. with db.connect() as conn:
  165. rows = conn.select('''select p.lat, p.lon from properties p
  166. where lat is not null and lon is not null''')
  167. random.shuffle(rows)
  168. to_load = []
  169. for lat, lon in rows:
  170. closest = None
  171. closest_dist = None
  172. for loc in commutes:
  173. dist = abs(loc[0] - lat) ** 2 + abs(loc[1] - lon) ** 2
  174. if closest_dist is None or dist < closest_dist:
  175. closest = loc
  176. closest_dist = dist
  177. target_loc = (lat, lon)
  178. if (geo_util.ggcd(target_loc, closest) > 300
  179. and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
  180. to_load.append(target_loc)
  181. print('\tRemaining to load: %i' % len(to_load))
  182. # target = (53.699593,-6.259772)
  183. # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
  184. # to_load.sort(key=lambda loc: scores[loc])
  185. for loc in to_load[:num_locations]:
  186. print('\tLoading %s...' % str(loc))
  187. directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
  188. def add_commute_data(properties, commutes):
  189. cyclable = {k: v for k, v in commutes.items()
  190. if not v['path'] or (v['path'][-1].get('desc') or '').startswith('HEAVY_RAIL')
  191. or (v['path'][-1].get('desc') or '').startswith('HEAVY_RAIL')}
  192. transport_options = [
  193. (cyclable, 5.5, TransitMethod.CYCLING),
  194. (commutes, 1, TransitMethod.WALKING),
  195. ]
  196. for p in properties.values():
  197. best_path = None
  198. best_duration = None
  199. for data, speed, mode in transport_options:
  200. for loc, commute_data in data.items():
  201. if best_duration is not None and best_duration <= commute_data['duration']:
  202. continue
  203. duration = int(round(geo_util.ggcd(p['loc'], loc) / speed))
  204. total_duration = commute_data['duration'] + duration
  205. if best_duration is None or total_duration < best_duration:
  206. best_duration = total_duration
  207. best_path = commute_data['path'] + [{
  208. 'source': p['loc'],
  209. 'dest': loc,
  210. 'duration': duration,
  211. 'mode': mode,
  212. }]
  213. p.update({
  214. 'commute_duration': best_duration,
  215. 'commute_path': best_path,
  216. })
  217. if __name__ == '__main__':
  218. while True:
  219. graph = load_graph()
  220. commutes = determine_fastest_paths(graph, config.WORKPLACE)
  221. analyze_locations(commutes, 20)