def closest_vertex(id, lat, lon): cv = None min_dist = sys.maxint for s_id, s_lat, s_lon in stations: dist = distance(lat, lon, s_lat, s_lon) if dist < min_dist: min_dist = dist cv = 'sta-' + s_id range = 0.05 # might not be the best number conn = psycopg2.connect(db_conn_string) c = conn.cursor() c.execute('''SELECT id, lat, lon FROM osm_nodes WHERE endnode_refs > 1 AND lat > %s AND lat < %s AND lon > %s AND lon < %s''', ( lat-range, lat+range, lon-range, lon+range )) nodes = [n for n in c] for n_id, n_lat, n_lon in nodes: dist = distance(lat, lon, n_lat, n_lon) if dist < min_dist: min_dist = dist cv = 'osm-' + n_id corres_vertices.append(( id, cv )) if not c.closed: c.close(); if not conn.closed: conn.close();
def link_osm_gtfs(db_conn_string, max_link_dist=150): conn = psycopg2.connect(db_conn_string) cursor = conn.cursor() gdb = GraphDatabase(db_conn_string) cursor.execute('SELECT stop_id, stop_lat, stop_lon FROM gtfs_stops') for i, (s_label, s_lat, s_lon) in enumerate(cursor.fetchall()): j = False range = 0.05 # might not be the best number cursor.execute('''SELECT id, lat, lon FROM osm_nodes WHERE endnode_refs > 1 AND lat > %s AND lat < %s AND lon > %s AND lon < %s''', ( s_lat-range, s_lat+range, s_lon-range, s_lon+range )) nodes = cursor.fetchall() dists = [] for n_label, n_lat, n_lon in nodes: dists.append( distance(s_lat, s_lon, n_lat, n_lon) ) for d in dists: if d < max_link_dist: j = True n_label, n_lat, n_lon = nodes[dists.index(d)] gdb.add_edge('sta-'+s_label, 'osm-'+n_label, Street('gtfs-osm link', d)) gdb.add_edge('osm-'+n_label, 'sta-'+s_label, Street('gtfs-osm link', d)) if not j and dists: # fallback mode d = min(dists) n_label, n_lat, n_lon = nodes[dists.index(d)] gdb.add_edge('sta-'+s_label, 'osm-'+n_label, Street('gtfs-osm link', d)) gdb.add_edge('osm-'+n_label, 'sta-'+s_label, Street('gtfs-osm link', d)) if not dists: print(colored('WARNING: failed linking %s! (%s, %s)' % (s_label, s_lat, s_lon), 'yellow')) gdb.commit() conn.commit() cursor.close()