commute.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. indices = {}
  123. for loc in graph:
  124. if loc not in indices:
  125. indices[loc] = len(indices)
  126. queue = [(0, source, [])]
  127. heapq.heapify(queue)
  128. commutes = {}
  129. i = 0
  130. while queue:
  131. current_duration, current_source, current_path = heapq.heappop(queue)
  132. if current_source in commutes and commutes[current_source]['duration'] < current_duration:
  133. continue
  134. commutes[current_source] = {
  135. 'duration': current_duration,
  136. 'path': current_path,
  137. }
  138. for key, dest_data in graph[current_source].items():
  139. heapq.heappush(queue, (
  140. current_duration + max(1, dest_data['duration']),
  141. dest_data['dest'],
  142. current_path + [key]
  143. ))
  144. i += 1
  145. return commutes
  146. def log_graph(graph, commutes):
  147. paths = {}
  148. for loc, paths_data in graph.items():
  149. for k, path_data in paths_data.items():
  150. # path_data.update({
  151. # 'source': loc
  152. # })
  153. paths[k] = path_data
  154. for loc, data in sorted(commutes.items(), key=lambda x: x[1]['duration']):
  155. print(loc, data)
  156. for k in data['path']:
  157. print('\t', k, sorted(paths[k].items()))
  158. print('')
  159. def analyze_locations(commutes, num_locations=5):
  160. print('Loading new directions data for %i locations...' % num_locations)
  161. with db.connect() as conn:
  162. rows = conn.select('''select p.id, p.lat, p.lon from properties p
  163. where lat is not null and lon is not null''')
  164. random.shuffle(rows)
  165. to_load = []
  166. for property_id, lat, lon in rows:
  167. closest = None
  168. closest_dist = None
  169. for loc in commutes:
  170. dist = abs(loc[0] - lat) ** 2 + abs(loc[1] - lon) ** 2
  171. if closest_dist is None or dist < closest_dist:
  172. closest = loc
  173. closest_dist = dist
  174. target_loc = (lat, lon)
  175. if (geo_util.ggcd(target_loc, closest) > 200
  176. and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
  177. to_load.append(target_loc)
  178. print('\tRemaining to load: %i' % len(to_load))
  179. # target = (53.699593,-6.259772)
  180. # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
  181. # to_load.sort(key=lambda loc: scores[loc])
  182. return
  183. for loc in to_load[:num_locations]:
  184. print('\tLoading %s...' % str(loc))
  185. directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
  186. def add_commute_data(properties, commutes):
  187. for p in properties.values():
  188. p.update({
  189. 'commute_duration': 1800,
  190. })
  191. if __name__ == '__main__':
  192. # _record_api_response(data.x)
  193. # exit()
  194. for _ in range(1):
  195. graph = load_graph()
  196. commutes = determine_fastest_paths(graph, config.WORKPLACE)
  197. # analyze_locations(commutes)