Prechádzať zdrojové kódy

better commute data methods

Martin 8 rokov pred
rodič
commit
83390efe3b
6 zmenil súbory, kde vykonal 146 pridanie a 73 odobranie
  1. 118 57
      commute.py
  2. 6 1
      config.py
  3. 6 0
      db.py
  4. 3 1
      db_schema.py
  5. 9 6
      geo_util.py
  6. 4 8
      monitor.py

+ 118 - 57
commute.py

@@ -16,13 +16,15 @@ class TransitMethod:
     CYCLING = 'bicycling'
     TRANSIT = 'transit'
 
-def _get_key(*args):
+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()[-12:]
+    return hashlib.md5(k).hexdigest()[-length:]
 
 def _record_api_response(response):
 
-    stmt = 'replace into transit (id, mode, submode, src_lat, src_lon, dest_lat, dest_lon, distance, duration, raw_json) VALUES'
+    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', []):
@@ -35,17 +37,30 @@ def _record_api_response(response):
                 mode = step['travel_mode']
                 submode = step.get('transit_details', {}).get('line', {}).get('vehicle', {}).get('type')
 
-                stmt += ' (?, ?, ?, ?, ?, ?, ?, ?, ?, ?),'
+                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),
                 ])
 
@@ -69,19 +84,12 @@ def directions_call(source, destination, mode):
     )
 
     resp = requests.get(url % params)
-    print(resp.status_code)
-    print(json.dumps(resp.json()))
 
     resp_data = resp.json()
-    print('"%s"' % config.GCLOUD_API_KEY)
-
 
     if not resp_data.get('routes'):
         return
 
-
-    # resp_data = data.x
-
     _record_api_response(resp_data)
 
 def load_graph():
@@ -91,9 +99,9 @@ def load_graph():
     }
 
     with db.connect() as conn:
-        rows = conn.select('select id, mode, dest_lat, dest_lon, src_lat, src_lon, duration from transit')
+        rows = conn.select('select id, mode, submode, description, dest_lat, dest_lon, src_lat, src_lon, duration from transit')
 
-        for key, mode, src_lat, src_lon, dest_lat, dest_lon, duration in rows:
+        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
 
@@ -103,38 +111,44 @@ def load_graph():
             if src not in graph:
                 graph[src] = {}
 
-                for lat, lon in graph:
-                    distance = int(geo_util.ggcd(lon, lat, src_lon, src_lat))
-                    if 0 < distance < 500:
-                        k = 'w-' + _get_key(lon, lat, src_lon, src_lat)
-                        est_walk_duration = distance
-                        graph[src][k] = {
-                            'mode': TransitMethod.WALKING.upper(),
-                            'dest': (lat, lon),
-                            'duration': est_walk_duration,
-                        }
-                        graph[lat,lon][k] = {
-                            'mode': TransitMethod.WALKING.upper(),
-                            'dest': src,
-                            'duration': est_walk_duration,
-                        }
-
-
             graph[src][key] = {
+                'source': src,
                 'mode': mode,
                 'dest': (dest_lat, dest_lon),
                 'duration': duration,
+                'desc': description or submode,
             }
-            
-    # for k, v in graph.items():
-    #     print((k,v))
 
-    # print(graph[config.WORKPLACE])
+    locs = list(graph.keys())
+
+    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
 
-# directions_call((53.388631,-6.071959), config.WORKPLACE, TransitMethod.TRANSIT)
-
 
 def determine_fastest_paths(graph, source):
     indices = {}
@@ -142,29 +156,23 @@ def determine_fastest_paths(graph, source):
         if loc not in indices:
             indices[loc] = len(indices)
     
-    # for loc in graph:
-    #     print('%i: %s' % (indices[loc], loc))
-    #     for k in graph[loc]:
-    #         print('\t%i\t%i\t%s\t%s' % (indices[graph[loc][k]['dest']], graph[loc][k]['duration'],  graph[loc][k]['mode'], k))
-
     queue = [(0, source, [])]
     heapq.heapify(queue)
 
-    current_min_durations = {}
-
-    # print('\n\n\n')
+    commutes = {}
 
     i = 0
 
     while queue:
         current_duration, current_source, current_path = heapq.heappop(queue)
 
-        if current_source in current_min_durations and current_min_durations[current_source] < current_duration:
+        if current_source in commutes and commutes[current_source]['duration'] < current_duration:
             continue
 
-        # print('%i\t%s\t%i\t%s' % (indices[current_source], current_source, current_duration, current_path))
-
-        current_min_durations[current_source] = current_duration
+        commutes[current_source] = {
+            'duration': current_duration,
+            'path': current_path,
+        }
 
         for key, dest_data in graph[current_source].items():
             heapq.heappush(queue, (
@@ -175,7 +183,25 @@ def determine_fastest_paths(graph, source):
 
         i += 1
 
-    return current_min_durations
+    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, fname):
     with open(fname, 'w') as f:
@@ -190,14 +216,33 @@ def write_kml(commutes, fname):
                 hexvalue = '0' + hexvalue
             f.write('<Style id="color-%i"><IconStyle><color>ff%s%sff</color></IconStyle></Style>\n' % (i, hexvalue, hexvalue))
 
-        max_duration = min(3600, max(commutes.values()))
+        max_duration = min(4000, max([x['duration'] for x in commutes.values()]))
+
+        f.write('''
+        <Folder>
+            <visibility>0</visibility>
+            <name>bbox</name>
+            <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
+            <Placemark><Point><coordinates>%f,%f</coordinates></Point></Placemark>
+        </Folder>
+        ''' % (config.MONITORED_BBOX[0][1], config.MONITORED_BBOX[0][0], config.MONITORED_BBOX[1][1], config.MONITORED_BBOX[1][0]))
 
 
         f.write('<Folder>\n')
         f.write('<name>Commutes</name>\n')
-        for loc, duration in commutes.items():
+        
+        for loc, commute in commutes.items():
+            duration = commute['duration']
             color = 20 + int((duration/float(max_duration)) * 236)
-            f.write('\t<Placemark><Point><coordinates>%f,%f</coordinates></Point><styleUrl>#color-%i</styleUrl></Placemark>\n' % (loc[1], loc[0], color))
+            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>')
 
 
@@ -208,8 +253,9 @@ def write_kml(commutes, fname):
 
 def analyze_locations(commutes):
     with db.connect() as conn:
-        rows = conn.select('select  id, lat, lon from properties where lat is not null and lon is not null')
-
+        locs = config.MONITORED_LOCALITIES
+        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)
 
@@ -225,18 +271,33 @@ def analyze_locations(commutes):
                     closest = loc
                     closest_dist = dist
             
-            if geo_util.ggcd(lon, lat, closest[1], closest[0]) > 200:
-                to_load.append((lat,lon))
+            target_loc = (lat, lon)
+
+            if (geo_util.ggcd(target_loc, closest) > 200
+                and geo_util.inside(target_loc, config.MONITORED_BBOX)):
+
+                to_load.append(target_loc)
         
         print('Remaining to load: %i' % len(to_load))
 
-        directions_call(to_load[0], config.WORKPLACE, TransitMethod.TRANSIT)
+        # 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])
 
+        for loc in to_load[:1]:
+            print('Loading %s...' % list(loc))
+            directions_call(loc, config.WORKPLACE, TransitMethod.TRANSIT)
     
 
 if __name__ == '__main__':
+
+    # _record_api_response(data.x)
+    # exit()
+
     graph = load_graph()
     commutes = determine_fastest_paths(graph, config.WORKPLACE)
     write_kml(commutes, 'vis.kml')
 
     # analyze_locations(commutes)
+
+    log_graph(graph, commutes)

+ 6 - 1
config.py

@@ -11,12 +11,17 @@ DB_PATH = 'data.db'
 MONITORED_LOCALITIES = [
     1265, # Co Dublin
     4011, # Co Wicklow
-    3587, # Co Tipp
+    # 3587, # Co Tipp
     2362, # Co Kildare
     2535, # Co Louth
     2712, # Co Meath
 ]
 
+MONITORED_BBOX = (
+    (53, -6.9),
+    (53.75, -5.9),
+)
+
 WORKPLACE = (53.353361,-6.247984)
 WORKPLACE_TARGET_TIME = 1540893600 # tue 10:00
 while WORKPLACE_TARGET_TIME < time.time():

+ 6 - 0
db.py

@@ -1,9 +1,15 @@
 import logging
 import sqlite3
+import datetime
 
 import config
 import db_schema
 
+_DATETIME_FORMAT = r'%Y-%m-%d %H:%M:%S'
+
+def now():
+    return datetime.datetime.now().strftime(_DATETIME_FORMAT)
+
 class connect:
     conn = None
 

+ 3 - 1
db_schema.py

@@ -76,13 +76,15 @@ SCHEMA_STATEMENTS = [
         id varchar(256) not null primary key,
         mode varchar(128) not null,
         submode varchar(128),
+        description varchar(255),
         src_lat float not null,
         src_lon float not null,
         dest_lat float not null,
         dest_lon float not null,
         distance integer not null,
         duration integer not null,
+        time DATETIME,
         raw_json text
     )
-    '''
+    ''',
 ]

+ 9 - 6
geo_util.py

@@ -1,15 +1,18 @@
 import math
 
-def ggcd(lon1, lat1, lon2, lat2):
+def inside(loc, bbox):
+    sw_corner, ne_corner = bbox
+    
+    return sw_corner[0] <= loc[0] <= ne_corner[0] and sw_corner[1] <= loc[1] <= ne_corner[1]
+
+def ggcd(loc1, loc2):
     """
     Returns the great-circle distance between two points, in metres
-    @param lon1: longitude #1
-    @param lat1: latitude #1
-    @param lon2: longitude #2
-    @param lat2: latitude #2
-    @return: the distance between the two points, in metres
     """
 
+    lat1, lon1 = loc1
+    lat2, lon2 = loc2
+
     if lat1 == lat2 and lon1 == lon2:
         return 0
 

+ 4 - 8
monitor.py

@@ -14,10 +14,6 @@ import util
 
 _SEARCH_PAGE_SIZE = 50
 
-_DATETIME_FORMAT = r'%Y-%m-%d %H:%M:%S'
-
-def _now():
-    return datetime.datetime.now().strftime(_DATETIME_FORMAT)
 
 def get_locality_tree(conn):
     parents = {}
@@ -134,7 +130,7 @@ def fetch_properties(conn):
                 stmt += ' (?, ?, ?),'
                 params.extend([
                     property_id,
-                    _now(),
+                    db.now(),
                     None,
                 ])
 
@@ -144,7 +140,7 @@ def fetch_properties(conn):
                     stmt += ' (?, ?, ?),'
                     params.extend([
                         property_id,
-                        _now(),
+                        db.now(),
                         json.dumps(data)
                     ])
                 except Exception as e:
@@ -228,7 +224,7 @@ def search(conn, locality_id):
 
             params.extend([
                 locality_id,
-                _now(), 
+                db.now(), 
                 property_id, 
                 price,
                 json.dumps(result)
@@ -258,7 +254,7 @@ def search(conn, locality_id):
             stmt += ' (?, ?, ?, ?),' 
             params.extend([
                 locality_id,
-                _now(),
+                db.now(),
                 property_id,
                 'GONE',
             ])