| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375 |
- import heapq
- import hashlib
- import json
- import random
- import requests
- import config
- import db
- import geo_util
- class TransitMethod:
- DRIVING = 'driving'
- WALKING = 'walking'
- CYCLING = 'bicycling'
- TRANSIT = 'transit'
- def _get_key(*args, **kwargs):
- length = kwargs.get('length', 12)
- k = ','.join([str(x) for x in args]).encode('utf-8')
- return hashlib.md5(k).hexdigest()[-length:]
- def _record_api_response(response):
- stmt = 'replace into transit (id, mode, submode, description, src_lat, src_lon, dest_lat, dest_lon, distance, duration, time, raw_json) VALUES'
- params = []
- for route in response.get('routes', []):
- for leg in route.get('legs', []):
- for step in leg.get('steps', []):
- distance = step['distance']['value']
- duration = step['duration']['value']
- source = round(step['start_location']['lat'], 10), round(step['start_location']['lng'], 10)
- destination = round(step['end_location']['lat'], 10), round(step['end_location']['lng'], 10)
- mode = step['travel_mode']
- submode = step.get('transit_details', {}).get('line', {}).get('vehicle', {}).get('type')
- description = None
- if step.get('transit_details'):
- transit_details = step['transit_details']
- line = transit_details.get('line',{})
- description = '%s (%s): %s -> %s' % (
- submode,
- line.get('name', line.get('short_name', '--')) if line else '--',
- transit_details.get('departure_stop', {}).get('name', '--'),
- transit_details.get('arrival_stop', {}).get('name', '--'),
- )
- stmt += ' (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
- params.extend([
- _get_key(source, destination, mode, submode),
- mode,
- submode,
- description,
- source[0],
- source[1],
- destination[0],
- destination[1],
- distance,
- duration,
- db.now(),
- json.dumps(step),
- ])
- with db.connect() as conn:
- conn.execute(stmt[:-1], *params)
- def directions_call(source, destination, mode):
- # doc: https://developers.google.com/maps/documentation/directions/intro
- url = 'https://maps.googleapis.com/maps/api/directions/json?origin=%s,%s&destination=%s,%s&key=%s&mode=%s&arrival_time=%i&alternatives=true'
- params = (
- source[0],
- source[1],
- destination[0],
- destination[1],
- config.GCLOUD_API_KEY,
- mode,
- config.WORKPLACE_TARGET_TIME,
- )
- resp = requests.get(url % params)
- resp_data = resp.json()
- if not resp_data.get('routes'):
- return
- _record_api_response(resp_data)
- def load_graph():
- print('Loading stored transit data...')
- graph = {
- config.WORKPLACE: {}
- }
- with db.connect() as conn:
- rows = conn.select('select id, mode, submode, description, dest_lat, dest_lon, src_lat, src_lon, duration from transit')
- for key, mode, submode, description, src_lat, src_lon, dest_lat, dest_lon, duration in rows:
- src = src_lat, src_lon
- dest = dest_lat, dest_lon
- if dest not in graph:
- graph[dest] = {}
- if src not in graph:
- graph[src] = {}
- graph[src][key] = {
- 'source': src,
- 'mode': mode,
- 'dest': (dest_lat, dest_lon),
- 'duration': duration,
- 'desc': description or submode,
- }
- locs = list(graph.keys())
- print('Creating additional commute links...')
- for i, loc in enumerate(locs):
- for secondary_loc in locs[i+1:]:
- distance = int(geo_util.ggcd(loc, secondary_loc))
- if 0 < distance < 500:
- k = 'w-' + _get_key(loc, secondary_loc, length=8)
- est_walk_duration = distance
- if secondary_loc not in [x['dest'] for x in graph[loc].values()]:
- graph[loc][k + '-1'] = {
- 'source': loc,
- 'dest': secondary_loc,
- 'mode': TransitMethod.WALKING.upper(),
- 'duration': est_walk_duration,
- 'desc': None,
- }
- if loc not in [x['dest'] for x in graph[secondary_loc].values()]:
- graph[secondary_loc][k + '-1'] = {
- 'source': secondary_loc,
- 'dest': loc,
- 'mode': TransitMethod.WALKING.upper(),
- 'duration': est_walk_duration,
- 'desc': None,
- }
- return graph
- def determine_fastest_paths(graph, source):
- print('Determining the fastest paths from transit locations to %s...' % str(source))
- indices = {}
- for loc in graph:
- if loc not in indices:
- indices[loc] = len(indices)
-
- queue = [(0, source, [])]
- heapq.heapify(queue)
- commutes = {}
- i = 0
- while queue:
- current_duration, current_source, current_path = heapq.heappop(queue)
- if current_source in commutes and commutes[current_source]['duration'] < current_duration:
- continue
- commutes[current_source] = {
- 'duration': current_duration,
- 'path': current_path,
- }
- for key, dest_data in graph[current_source].items():
- heapq.heappush(queue, (
- current_duration + max(1, dest_data['duration']),
- dest_data['dest'],
- current_path + [key]
- ))
- i += 1
- return commutes
- def log_graph(graph, commutes):
- paths = {}
- for loc, paths_data in graph.items():
- for k, path_data in paths_data.items():
- # path_data.update({
- # 'source': loc
- # })
- paths[k] = path_data
- for loc, data in sorted(commutes.items(), key=lambda x: x[1]['duration']):
- print(loc, data)
- for k in data['path']:
- print('\t', k, sorted(paths[k].items()))
- print('')
- def write_kml(commutes, properties, fname):
- print('Writing .kml visualization file...')
- with open(fname, 'w') as f:
- f.write('''<?xml version="1.0" encoding="UTF-8"?>
- <kml xmlns="http://www.opengis.net/kml/2.2">
- <Document>
- ''')
- for i in range(256):
- hexvalue = hex(255-i)[2:].lower()
- if len(hexvalue) == 1:
- hexvalue = '0' + hexvalue
- f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
- max_duration = min(4000, max([x['duration'] for x in commutes.values()]))
- f.write('''
- <Folder>
- <visibility>0</visibility>
- <name>Monitored bboxes</name>\n''')
- for (lat1, lon1), (lat2, lon2) in config.MONITORED_BBOXES:
- f.write('<Placemark><LineString><coordinates>')
- f.write('%s,%s' % (lon1, lat1))
- f.write(' %s,%s' % (lon1, lat2))
- f.write(' %s,%s' % (lon2, lat2))
- f.write(' %s,%s' % (lon2, lat1))
- f.write(' %s,%s' % (lon1, lat1))
- f.write(' %s,%s' % (lon2, lat2))
- f.write(' %s,%s' % (lon1, lat2))
- f.write(' %s,%s' % (lon2, lat1))
- f.write('</coordinates></LineString></Placemark>\n')
- # f.write('''
- # <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
- # <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
- # ''' % (lon1, lat1, lon2, lat2))
- f.write('</Folder>')
- f.write('<Folder><name>Commutes</name><visibility>0</visibility>\n')
- for loc, commute in commutes.items():
- duration = commute['duration']
- color = 20 + int((duration/float(max_duration)) * 236)
- color = min(color, 255)
- f.write('''<Placemark>
- <Point><coordinates>%f,%f</coordinates></Point>
- <styleUrl>#color-%i</styleUrl>
- <name>%s</name>
- <description>%s</description>
- </Placemark>\n''' % (loc[1], loc[0], color, int(duration / 60), loc))
- f.write('</Folder>')
- f.write('<Folder><name>Properties</name><visibility>0</visibility>\n')
- max_score = max(x['score'] for x in properties.values())
- properties = list(properties.items())
- properties.sort(key=lambda x: x[1]['score'], reverse=True)
- for i, (pid, data) in enumerate(properties):
- color = 20 + int((data['score']/float(max_score)) * 236)
- color = min(color, 255)
- color = 20 + int(236*(float(i)/len(properties)))
- name = '%s/%s/%s' % (data['price'], data['size'], data['bedrooms'])
- loc = data['loc']
- description = pid
- print(color, data)
- f.write('''<Placemark>
- <Point><coordinates>%f,%f</coordinates></Point>
- <styleUrl>#color-%i</styleUrl>
- <name>%s</name>
- <description>%s</description>
- </Placemark>\n''' % (loc[1], loc[0], color, name, description))
- f.write('</Folder>\n')
- f.write('''
- </Document>
- </kml>
- ''')
- def analyze_locations(commutes, num_locations=5):
- print('Loading new directions data for %i locations...' % num_locations)
- with db.connect() as conn:
- rows = conn.select('''select p.id, p.lat, p.lon from properties p
- where lat is not null and lon is not null''')
- random.shuffle(rows)
- to_load = []
- for property_id, lat, lon in rows:
- closest = None
- closest_dist = None
-
- for loc in commutes:
- dist = abs(loc[0] - lat) ** 2 + abs(loc[1] - lon) ** 2
- if closest_dist is None or dist < closest_dist:
- closest = loc
- closest_dist = dist
-
- target_loc = (lat, lon)
- if (geo_util.ggcd(target_loc, closest) > 200
- and any(geo_util.inside(target_loc, bbox) for bbox in config.MONITORED_BBOXES)):
- to_load.append(target_loc)
-
- print('\tRemaining to load: %i' % len(to_load))
- # target = (53.699593,-6.259772)
- # scores = {loc: geo_util.ggcd(target, loc) for loc in to_load}
- # to_load.sort(key=lambda loc: scores[loc])
- return
- for loc in to_load[:num_locations]:
- print('\tLoading %s...' % str(loc))
- directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
- def load_properties():
- with db.connect() as conn:
- rows = conn.select('select id, lat, lon, size, price, bedrooms from properties where price<450000')
- res = {}
- for property_id, lat, lon, size, price, bedrooms in rows:
- if not price or not size or not lat or not lon:
- continue
- if not any(geo_util.inside((lat, lon), bbox) for bbox in config.MONITORED_BBOXES):
- continue
- price = price/1000
- res[property_id] = {
- 'loc': (lat, lon),
- 'size': size,
- 'price': price,
- 'bedrooms': bedrooms,
- 'score': float(size) / int(price),
- }
- # print(res[property_id])
-
- return res
- if __name__ == '__main__':
- # _record_api_response(data.x)
- # exit()
- for _ in range(1):
- graph = load_graph()
- commutes = determine_fastest_paths(graph, config.WORKPLACE)
- # analyze_locations(commutes)
- properties = load_properties()
- write_kml(commutes, properties, 'vis.kml')
- # log_graph(graph, commutes)
|