Exemple #1
0
def create_intersections_db_by_zip(data):
    """This function creates a database of the coordinates and streets of all intersections in a mile radius of a given zipcode. Currently set to drive network and a radius of 1610m (1 mile). Edit the parameters in line 81 to fit your preferences"""
    d = data[1]
    zipcode = d[1]
    city = d[2]
    state = d[3]
    county = d[4]

    tablename = "intersections_" + str(zipcode)

    try:
        cur.execute(
            "CREATE TABLE " + tablename +
            " (zip_code TEXT, city TEXT, state TEXT, county TEXT, latlon_str TEXT);"
        )

        latlon_array = []
        streetname_array = []
        latlon_array_str = ""
        streetname_array_str = ""

        try:
            G = ox.graph_from_address(zipcode,
                                      network_type='drive',
                                      distance=1610)
            G_proj = ox.project_graph(G)
            # clean up the intersections and extract their xy coords
            intersections = ox.clean_intersections(G_proj,
                                                   tolerance=15,
                                                   dead_ends=False)
            points = np.array([point.xy for point in intersections])

            gdf = gpd.GeoDataFrame(geometry=intersections)
            gdf.crs = G_proj.graph['crs']
            lonlat = ox.project_gdf(gdf, to_latlong=True)
            a = lonlat['geometry'].tolist()
            for coord in a:
                lon = coord.x
                lat = coord.y
                latlon_tuple = (lat, lon)

                # nearest_streets = get_nearest_streetnames(latlon_tuple)

                # streetname_array.append(nearest_streets)
                latlon_array.append(latlon_tuple)
        except:
            #THROW A WARNING THAT THERE IS NO LAT/LON DATA FOR THIS ZIPCODE
            pass

        latlon_array_str = str(latlon_array).strip('[]')
        # streetname_array_str = str(streetname_array).strip('[]')

        to_db = [zipcode, city, state, county, latlon_array_str]
        cmd = "INSERT INTO " + tablename + " (zip_code, city, state, county,latlon_str) VALUES (?, ?, ?, ?, ?);"
        cur.execute(cmd, to_db)

        for row in cur.execute("SELECT * from " + tablename):
            print(row)
    except:
        print(tablename + " already exists")
Exemple #2
0
def get_nearest_streetnames(location_tuple, distFromPoint=50):
    """This function retrieves the nearest streets of a coordinate tuple (lat, lon). Currently set to drive network. Edit the parameters in line 40 to fit your preferences."""
    try:
        G = ox.graph_from_point(location_tuple,
                                network_type='drive',
                                distance=distFromPoint)
        G = ox.project_graph(G)
        ints = ox.clean_intersections(G)

        gdf = gpd.GeoDataFrame(ints, columns=['geometry'], crs=G.graph['crs'])
        X = gdf['geometry'].map(lambda pt: pt.coords[0][0])
        Y = gdf['geometry'].map(lambda pt: pt.coords[0][1])

        nodes = ox.get_nearest_nodes(G, X, Y, method='kdtree')
        streetnames = []

        for n in nodes:
            for nbr in nx.neighbors(G, n):
                for d in G.get_edge_data(n, nbr).values():
                    if 'name' in d:
                        if type(d['name']) == str:
                            streetnames.append(d['name'])
                        elif type(d['name']) == list:
                            for name in d['name']:
                                streetnames.append(name)
        streetnames = list(set(streetnames))
    except:
        streetnames = []
    return streetnames
Exemple #3
0
def connections(place):
    '''
    inputs - textual query specifying spatial boundaries of some geocodeable place(s)
    returns - tuples of street intersections using OSM data
    '''

    # Create a networkx graph from OSM data within the spatial boundaries of geocodable place(s).
    G = ox.graph_from_place(place, network_type='drive', timeout=3600)

    # Project a graph from lat-long to the UTM zone appropriate for its geographic location.
    # https://en.wikipedia.org/wiki/Universal_Transverse_Mercator_coordinate_system
    Gp = ox.project_graph(G)

    # Clean-up intersections comprising clusters of nodes by merging them and returning their centroids
    ints = ox.clean_intersections(Gp)

    # create a dataframe of intersections
    gdf = gpd.GeoDataFrame(ints, columns=['geometry'], crs=Gp.graph['crs'])

    # generate lists of X, Y locations (UTM zone)
    X = gdf['geometry'].map(lambda pt: pt.coords[0][0])
    Y = gdf['geometry'].map(lambda pt: pt.coords[0][1])

    nodes = ox.get_nearest_nodes(Gp, X, Y, method='kdtree')
    connections = {}

    intersections = []
    for n in nodes:
        dict = {
            'osmid': G.nodes()[n]['osmid'],
            'latitude': G.nodes()[n]['y'],
            'longitude': G.nodes()[n]['x']
        }
        # print(dict)
        connections[n] = set([])
        for nbr in nx.neighbors(G, n):
            for d in G.get_edge_data(n, nbr).values():
                if 'name' in d:
                    if type(d['name']) == str:
                        connections[n].add(d['name'])
                    elif type(d['name']) == list:
                        for name in d['name']:
                            connections[n].add(name)
                    else:
                        connections[n].add(None)
                else:
                    connections[n].add(None)

        if len(connections) > 0:
            dict['streets'] = list(connections[n])
            print(dict)
            intersections.append(dict)

    return intersections
Exemple #4
0
def test_plots():

    G = ox.graph_from_place('Piedmont, California, USA',
                            network_type='drive',
                            simplify=False)
    G2 = ox.simplify_graph(G, strict=False)
    nc = ox.get_node_colors_by_attr(G2, 'osmid')
    ec = ox.get_edge_colors_by_attr(G2, 'length')

    fig, ax = ox.plot_graph(G, save=True, file_format='png')

    G_simplified = ox.simplify_graph(G)
    fig, ax = ox.plot_graph(G_simplified,
                            show=False,
                            save=True,
                            close=True,
                            file_format='svg')

    G_projected = ox.project_graph(G_simplified)
    intersections = ox.clean_intersections(G_projected)
    fig, ax = ox.plot_graph(G_projected)

    fig, ax = ox.plot_graph(G_projected,
                            fig_height=5,
                            fig_width=5,
                            margin=0.05,
                            axis_off=False,
                            bgcolor='y',
                            file_format='png',
                            filename='x',
                            dpi=180,
                            annotate=True,
                            node_color='k',
                            node_size=5,
                            node_alpha=0.1,
                            node_edgecolor='b',
                            node_zorder=5,
                            edge_color='r',
                            edge_linewidth=2,
                            edge_alpha=0.1,
                            use_geom=False,
                            show=False,
                            save=True,
                            close=True)

    fig, ax = ox.plot_figure_ground(G=G_simplified, file_format='png')
    fig, ax = ox.plot_figure_ground(point=(33.694981, -117.841375),
                                    file_format='png')
    fig, ax = ox.plot_figure_ground(address='Denver, Colorado, USA',
                                    file_format='png')
Exemple #5
0
def test_stats():
    # create graph, add bearings, project it
    G = ox.graph_from_point(location_point, dist=500, network_type="drive")
    G = ox.add_edge_bearings(G)
    G_proj = ox.project_graph(G)

    # calculate stats
    stats = ox.basic_stats(G)
    stats = ox.basic_stats(G, area=1000)
    stats = ox.basic_stats(
        G_proj, area=1000, clean_intersects=True, tolerance=15, circuity_dist="euclidean"
    )

    # calculate extended stats
    stats = ox.extended_stats(G, connectivity=True, anc=False, ecc=True, bc=True, cc=True)

    # test cleaning and rebuilding graph
    G_clean = ox.clean_intersections(G_proj, tolerance=10, rebuild_graph=True, dead_ends=True)
Exemple #6
0
def getIntersections(boundary, projection, tolerance=100):
    '''
    INPUT:  boundary shap
            projection in UTM
            int (in meters) representing tolerance of clean_intersections() function for osmnx package

    OUTPUT: GeoSeries of Intersections
    '''

    # Create Graph
    G = ox.graph_from_polygon(boundary, network_type='drive')
    ox.plot_graph(G)
    plt.show()

    # Clean Intersections
    G_proj = ox.project_graph(G, to_crs=projection)
    intersections = ox.clean_intersections(G_proj,
                                           tolerance=tolerance,
                                           dead_ends=False)

    return intersections
Exemple #7
0
def get_voronoi_grid(G, tolerance=15, remove_random=None, buffer=20, cutt_buffer= 400, remove_empty = True, 
                    exclude_highways=None, is_dual=False, primal_graph=None, max_area_m=None, 
                    cutt_geom = 'convex_hull'):
    
    """ Função que recebe um grafo e retorna os poligonos das regiões voronoi associadas a cada ponto.
        G: grafo (geralmente obtido com o osmnx);
        cut_extremes: bool - se True, constroe um retangulo que abrange os pontos extremos do grafo e recorta regiões que
                            possivelmente saem desses limites.
        Retorna:
                voronoi_gdf: GeoDataFrame com os pontos (coordenadas) e os poligonos das regiões criadas;
                p_pol: dicionário com os tuplas das coordenadas dos pontos como key e os poligonos como values
                vor: instancia voronoi, que pode ser usada para plotar os pontos e as regiões
    """
    # Criando um vetor com os pontos do grafo a partir do gdf do mesmo
    if not is_dual:
        primal_graph = G
    if exclude_highways != None:
        exclude_highways = list(exclude_highways)
    ids = []
    G_ = G.copy()
    G_proj = ox.project_graph(G)
    for node, d in G.nodes(data=True):
        if d['osmid'] in ids:
            G_.remove_node(node)
        else:
            ids.append(d['osmid'])
    
    intersections = ox.clean_intersections(G_proj, tolerance=tolerance)
    points = gpd.GeoDataFrame({'geometry':intersections},crs=G_proj.graph['crs'])
    points = points.to_crs(G_.graph['crs']).geometry
    if remove_random != None:
        points = [(p.x,p.y) for p in points if random.random()>=remove_random]
    else:
        points = [(p.x,p.y) for p in points]
    point_list = np.array(points)
    # Criação da classe Voronoi, com os respectivos vertices e regiões
    vor = Voronoi(point_list)
    verts = vor.vertices.tolist()
    regs = vor.regions
    pr = vor.point_region
    p_reg = {}
    p_pol = []
    p_coo = []

    # cada pr[i] é um índice da lista de regiões relacionada ao ponto de índice i da lista verts  
    for i in range(len(pr)):
        point = tuple(point_list[i])
        r = regs[pr[i]] # cada r é uma região, expressa por uma lista com os índices dos vertices que a compõem

        if (-1 in r) or (len(r)==0): continue # ignora regiões inexistentes ou infinitas
        else:
            p_reg[point] = [verts[v] for v in r] # dicionário com ponto as key e região as value
            p_pol.append(Polygon(p_reg[point]))
            p_coo.append(point)
    voronoi_gdf = gpd.GeoDataFrame({'id': [n for n in range(len(p_pol))],'geometry': list(p_pol), 'coord': p_coo}, 
                                   crs=G_.graph['crs'])
    if cutt_geom!=None:
        voronoi_gdf = cutt_from_predef_geometry(primal_graph, voronoi_gdf, G_proj=G_proj, geom_type = cutt_geom, 
                                                cutt_buffer=cutt_buffer)
        
    if remove_empty:
        polys = remove_excess_polys(primal_graph, voronoi_gdf, buffer=buffer, exclude_highways=exclude_highways)
        if max_area_m != None:
            polys_proj = polys.to_crs(G_proj.graph['crs'])
            polys = polys[polys_proj.geometry.area<=max_area_m]
        return polys
    return voronoi_gdf