commute.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 write_kml(commutes, properties, fname):
  160. print('Writing .kml visualization file...')
  161. with open(fname, 'w') as f:
  162. f.write('''<?xml version="1.0" encoding="UTF-8"?>
  163. <kml xmlns="http://www.opengis.net/kml/2.2">
  164. <Document>
  165. ''')
  166. for i in range(256):
  167. hexvalue = hex(255-i)[2:].lower()
  168. if len(hexvalue) == 1:
  169. hexvalue = '0' + hexvalue
  170. f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
  171. max_duration = min(4000, max([x['duration'] for x in commutes.values()]))
  172. f.write('''
  173. <Folder>
  174. <visibility>0</visibility>
  175. <name>Monitored bboxes</name>\n''')
  176. for (lat1, lon1), (lat2, lon2) in config.MONITORED_BBOXES:
  177. f.write('<Placemark><LineString><coordinates>')
  178. f.write('%s,%s' % (lon1, lat1))
  179. f.write(' %s,%s' % (lon1, lat2))
  180. f.write(' %s,%s' % (lon2, lat2))
  181. f.write(' %s,%s' % (lon2, lat1))
  182. f.write(' %s,%s' % (lon1, lat1))
  183. f.write(' %s,%s' % (lon2, lat2))
  184. f.write(' %s,%s' % (lon1, lat2))
  185. f.write(' %s,%s' % (lon2, lat1))
  186. f.write('</coordinates></LineString></Placemark>\n')
  187. # f.write('''
  188. # <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
  189. # <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
  190. # ''' % (lon1, lat1, lon2, lat2))
  191. f.write('</Folder>')
  192. f.write('<Folder><name>Commutes</name><visibility>0</visibility>\n')
  193. for loc, commute in commutes.items():
  194. duration = commute['duration']
  195. color = 20 + int((duration/float(max_duration)) * 236)
  196. color = min(color, 255)
  197. f.write('''<Placemark>
  198. <Point><coordinates>%f,%f</coordinates></Point>
  199. <styleUrl>#color-%i</styleUrl>
  200. <name>%s</name>
  201. <description>%s</description>
  202. </Placemark>\n''' % (loc[1], loc[0], color, int(duration / 60), loc))
  203. f.write('</Folder>')
  204. f.write('<Folder><name>Properties</name><visibility>0</visibility>\n')
  205. max_score = max(x['score'] for x in properties.values())
  206. properties = list(properties.items())
  207. properties.sort(key=lambda x: x[1]['score'], reverse=True)
  208. for i, (pid, data) in enumerate(properties):
  209. color = 20 + int((data['score']/float(max_score)) * 236)
  210. color = min(color, 255)
  211. color = 20 + int(236*(float(i)/len(properties)))
  212. name = '%s/%s/%s' % (data['price'], data['size'], data['bedrooms'])
  213. loc = data['loc']
  214. description = pid
  215. print(color, data)
  216. f.write('''<Placemark>
  217. <Point><coordinates>%f,%f</coordinates></Point>
  218. <styleUrl>#color-%i</styleUrl>
  219. <name>%s</name>
  220. <description>%s</description>
  221. </Placemark>\n''' % (loc[1], loc[0], color, name, description))
  222. f.write('</Folder>\n')
  223. f.write('''
  224. </Document>
  225. </kml>
  226. ''')
  227. def analyze_locations(commutes, num_locations=5):
  228. print('Loading new directions data for %i locations...' % num_locations)
  229. with db.connect() as conn:
  230. rows = conn.select('''select p.id, p.lat, p.lon from properties p
  231. where lat is not null and lon is not null''')
  232. random.shuffle(rows)
  233. to_load = []
  234. for property_id, lat, lon in rows:
  235. closest = None
  236. closest_dist = None
  237. for loc in commutes:
  238. dist = abs(loc[0] - lat) ** 2 + abs(loc[1] - lon) ** 2
  239. if closest_dist is None or dist < closest_dist:
  240. closest = loc
  241. closest_dist = dist
  242. target_loc = (lat, lon)
  243. if (geo_util.ggcd(target_loc, closest) > 200
  244. and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
  245. to_load.append(target_loc)
  246. print('\tRemaining to load: %i' % len(to_load))
  247. # target = (53.699593,-6.259772)
  248. # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
  249. # to_load.sort(key=lambda loc: scores[loc])
  250. return
  251. for loc in to_load[:num_locations]:
  252. print('\tLoading %s...' % str(loc))
  253. directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
  254. def load_properties():
  255. with db.connect() as conn:
  256. rows = conn.select('select id, lat, lon, size, price, bedrooms from properties where price<450000')
  257. res = {}
  258. for property_id, lat, lon, size, price, bedrooms in rows:
  259. if not price or not size or not lat or not lon:
  260. continue
  261. if not any(geo_util.inside((lat, lon), bbox) for bbox in config.MONITORED_BBOXES):
  262. continue
  263. price = price/1000
  264. res[property_id] = {
  265. 'loc': (lat, lon),
  266. 'size': size,
  267. 'price': price,
  268. 'bedrooms': bedrooms,
  269. 'score': float(size) / int(price),
  270. }
  271. # print(res[property_id])
  272. return res
  273. if __name__ == '__main__':
  274. # _record_api_response(data.x)
  275. # exit()
  276. for _ in range(1):
  277. graph = load_graph()
  278. commutes = determine_fastest_paths(graph, config.WORKPLACE)
  279. # analyze_locations(commutes)
  280. properties = load_properties()
  281. write_kml(commutes, properties, 'vis.kml')
  282. # log_graph(graph, commutes)