commute.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. if 'error_message' in resp_data:
  73. print('Error: %s' % resp_data['error_message'])
  74. return
  75. _record_api_response(resp_data)
  76. def load_graph():
  77. print('Loading stored transit data...')
  78. graph = {
  79. config.WORKPLACE: {}
  80. }
  81. with db.connect() as conn:
  82. rows = conn.select('select id, mode, submode, description, dest_lat, dest_lon, src_lat, src_lon, duration from transit')
  83. for key, mode, submode, description, src_lat, src_lon, dest_lat, dest_lon, duration in rows:
  84. src = src_lat, src_lon
  85. dest = dest_lat, dest_lon
  86. if dest not in graph:
  87. graph[dest] = {}
  88. if src not in graph:
  89. graph[src] = {}
  90. graph[src][key] = {
  91. 'source': src,
  92. 'mode': mode,
  93. 'dest': (dest_lat, dest_lon),
  94. 'duration': duration,
  95. 'desc': description or submode,
  96. }
  97. locs = list(graph.keys())
  98. print('Creating additional commute links...')
  99. for i, loc in enumerate(locs):
  100. for secondary_loc in locs[i+1:]:
  101. distance = int(geo_util.ggcd(loc, secondary_loc))
  102. if 0 < distance < 500:
  103. k = 'w-' + _get_key(loc, secondary_loc, length=8)
  104. est_walk_duration = distance
  105. if secondary_loc not in [x['dest'] for x in graph[loc].values()]:
  106. graph[loc][k + '-1'] = {
  107. 'source': loc,
  108. 'dest': secondary_loc,
  109. 'mode': TransitMethod.WALKING.upper(),
  110. 'duration': est_walk_duration,
  111. 'desc': None,
  112. }
  113. if loc not in [x['dest'] for x in graph[secondary_loc].values()]:
  114. graph[secondary_loc][k + '-1'] = {
  115. 'source': secondary_loc,
  116. 'dest': loc,
  117. 'mode': TransitMethod.WALKING.upper(),
  118. 'duration': est_walk_duration,
  119. 'desc': None,
  120. }
  121. return graph
  122. def determine_fastest_paths(graph, source):
  123. print('Determining the fastest paths from transit locations to %s...' % str(source))
  124. links = {}
  125. for link_dict in graph.values():
  126. links.update(link_dict)
  127. indices = {}
  128. for loc in graph:
  129. if loc not in indices:
  130. indices[loc] = len(indices)
  131. queue = [(0, source, [])]
  132. heapq.heapify(queue)
  133. commutes = {}
  134. i = 0
  135. while queue:
  136. current_duration, current_source, current_path = heapq.heappop(queue)
  137. if current_source in commutes and commutes[current_source]['duration'] < current_duration:
  138. continue
  139. commutes[current_source] = {
  140. 'duration': current_duration,
  141. 'path': [links[link] for link in current_path],
  142. }
  143. for key, dest_data in graph[current_source].items():
  144. heapq.heappush(queue, (
  145. current_duration + max(1, dest_data['duration']),
  146. dest_data['dest'],
  147. current_path + [key]
  148. ))
  149. i += 1
  150. return commutes
  151. def log_graph(graph, commutes):
  152. paths = {}
  153. for loc, paths_data in graph.items():
  154. for k, path_data in paths_data.items():
  155. # path_data.update({
  156. # 'source': loc
  157. # })
  158. paths[k] = path_data
  159. for loc, data in sorted(commutes.items(), key=lambda x: x[1]['duration']):
  160. print(loc, data)
  161. for k in data['path']:
  162. print('\t', k, sorted(paths[k].items()))
  163. print('')
  164. def analyze_locations(commutes, num_locations):
  165. with db.connect() as conn:
  166. rows = conn.select('''select p.lat, p.lon, price from properties p
  167. where lat is not null and lon is not null and property_type != "Site" and price is not null''')
  168. random.shuffle(rows)
  169. to_load = []
  170. durations = []
  171. paths = []
  172. for lat, lon, price in rows:
  173. if not (config.MIN_PRICE < price < config.MAX_PRICE):
  174. continue
  175. closest = None
  176. closest_dist = None
  177. for loc in commutes:
  178. dist = abs(loc[0] - lat) ** 2 + abs(loc[1] - lon) ** 2
  179. if closest_dist is None or dist < closest_dist:
  180. closest = loc
  181. closest_dist = dist
  182. target_loc = (lat, lon)
  183. closest_dist = geo_util.ggcd(target_loc, closest)
  184. if (closest_dist > 300 and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
  185. to_load.append(target_loc)
  186. elif closest_dist <= 300:
  187. durations.append(commutes[closest]['duration'] + closest_dist)
  188. paths.append(commutes[closest]['path'])
  189. print('\tRemaining to load: %i' % len(to_load))
  190. durations.sort()
  191. print('Durations (min): ' + ', '.join(['%.2f' % (durations[int(len(durations) * x)] / 60.)
  192. for x in [0.05, 0.25, 0.5, 0.75, 0.95]]))
  193. random.shuffle(paths)
  194. for p in paths[:10]:
  195. print(p)
  196. return
  197. random.shuffle(to_load)
  198. # target = (53.699593,-6.259772)
  199. # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
  200. # to_load.sort(key=lambda loc: scores[loc])
  201. print('Loading new directions data for %i locations...' % num_locations)
  202. for loc in to_load[:num_locations]:
  203. # print('\tLoading %s...' % str(loc))
  204. directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
  205. def add_commute_data(properties, commutes):
  206. cyclable = {k: v for k, v in commutes.items()
  207. if not v['path'] or (v['path'][-1].get('desc') or '').startswith('HEAVY_RAIL')
  208. or (v['path'][-1].get('desc') or '').startswith('HEAVY_RAIL')}
  209. transport_options = [
  210. (cyclable, 5.5, TransitMethod.CYCLING),
  211. (commutes, 1, TransitMethod.WALKING),
  212. ]
  213. for p in properties.values():
  214. best_path = None
  215. best_duration = None
  216. for data, speed, mode in transport_options:
  217. for loc, commute_data in data.items():
  218. if best_duration is not None and best_duration <= commute_data['duration']:
  219. continue
  220. duration = int(round(geo_util.ggcd(p['loc'], loc) / speed))
  221. total_duration = commute_data['duration'] + duration
  222. if best_duration is None or total_duration < best_duration:
  223. best_duration = total_duration
  224. best_path = commute_data['path'] + [{
  225. 'source': p['loc'],
  226. 'dest': loc,
  227. 'duration': duration,
  228. 'mode': mode,
  229. }]
  230. p.update({
  231. 'commute_duration': best_duration,
  232. 'commute_path': best_path,
  233. })
  234. def run():
  235. while True:
  236. graph = load_graph()
  237. commutes = determine_fastest_paths(graph, config.WORKPLACE)
  238. analyze_locations(commutes, 20)
  239. if __name__ == '__main__':
  240. run()