Exemple #1
0
def test_routing():

    G = ox.graph_from_address(address=address,
                              dist=500,
                              dist_type="bbox",
                              network_type="bike")

    # give each edge speed and travel time attributes
    G = ox.add_edge_speeds(G)
    G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100})
    G = ox.add_edge_travel_times(G)

    orig_x = np.array([-122.404771])
    dest_x = np.array([-122.401429])
    orig_y = np.array([37.794302])
    dest_y = np.array([37.794987])
    orig_node = ox.distance.nearest_nodes(G, orig_x, orig_y)[0]
    dest_node = ox.distance.nearest_nodes(G, dest_x, dest_y)[0]

    route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time")
    attributes = ox.utils_graph.get_route_edge_attributes(G, route)
    attributes = ox.utils_graph.get_route_edge_attributes(
        G, route, "travel_time")

    fig, ax = ox.plot_graph_route(G, route, save=True)

    # test multiple origins-destinations
    n = 5
    nodes = np.array(G.nodes)
    origs = np.random.choice(nodes, size=n, replace=True)
    dests = np.random.choice(nodes, size=n, replace=True)
    paths1 = ox.shortest_path(G, origs, dests, weight="length", cpus=1)
    paths2 = ox.shortest_path(G, origs, dests, weight="length", cpus=2)
    paths3 = ox.shortest_path(G, origs, dests, weight="length", cpus=None)
    assert paths1 == paths2 == paths3

    # test k shortest paths
    routes = ox.k_shortest_paths(G,
                                 orig_node,
                                 dest_node,
                                 k=2,
                                 weight="travel_time")
    fig, ax = ox.plot_graph_routes(G, list(routes))

    # test folium with keyword arguments to pass to folium.PolyLine
    gm = ox.plot_graph_folium(G,
                              popup_attribute="name",
                              color="#333333",
                              weight=5,
                              opacity=0.7)
    rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7)

    # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs
    fg = folium.FeatureGroup(name="legend name", show=True)
    gm = ox.plot_graph_folium(G, graph_map=fg)
    assert isinstance(gm, folium.FeatureGroup)

    rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x")
    assert isinstance(rm, folium.FeatureGroup)
Exemple #2
0
def shortest_safest(origin, destination):
    route1 = ox.shortest_path(G, origin, destination,
                              weight='danger_weight')  #safest road
    route2 = ox.shortest_path(G, origin, destination,
                              weight='length')  #shortest road
    fig, ax = ox.plot_graph_routes(G,
                                   routes=[route1, route2],
                                   route_colors=['r', 'y'],
                                   route_linewidth=6,
                                   node_size=0)
    return fig
Exemple #3
0
    def safest_way(self,
                   origin,
                   destination,
                   short=False):  # select safest route

        a, b = origin
        print(origin)
        print(type(a))
        print(destination)
        #We create a graphml file and save every node/edges in it then with with this line we just load it

        G = ox.io.load_graphml(filepath='data/ml.graphml')
        # place = 'New york city, New York, USA'
        # G = ox.graph_from_place(place, network_type='drive')

        origin_node = ox.get_nearest_node(G, origin)
        destination_node = ox.get_nearest_node(G, destination)

        nx.set_edge_attributes(G, 0, 'danger_weight')

        route1 = ox.shortest_path(G,
                                  origin_node,
                                  destination_node,
                                  weight='danger_weight')
        route_risk = int(
            sum(
                ox.utils_graph.get_route_edge_attributes(
                    G, route1,
                    'danger_weight')))  # print the risk on this road
        txt = 'The risk on this Route is {} accidents per year'.format(
            route_risk)

        if short:

            route2 = ox.shortest_path(G,
                                      origin_node,
                                      destination_node,
                                      weight='length')  #shortest road
            route = [route1, route2]
            colors = ['r', 'y']
            #fig, ax = ox.plot_graph_routes(G, route, route_colors=colors, route_linewidth=6, node_size=0)
            return route1, route2  # plot the safest road

        else:

            #fig, ax = ox.plot_graph_route(G, route=route1, route_color='r',route_linewidth=6, node_size=0)
            long = []
            lat = []
            for i in route1:
                point = G.nodes[i]
                long.append(point['x'])
                lat.append(point['y'])
            return long, lat
Exemple #4
0
    def get_path(self, G, start, end, limit_ratio, weight='length', inverse=False):
        '''
        Return the path with certain constraint
        
        Parameters:
            G : map graph object
            start (float tuple): coordinate for the start point
            end (float tuple): coordinate for the end point
            limit_ratio (float): the length restriction
            weight (str): path type
            inverse (bool): switch between maximum and minimum
        '''
        # transfer node coordinates to node ids
        if type(start) is not np.int64:
            start = ox.get_nearest_node(G, start)
            end = ox.get_nearest_node(G, end)

        # calculate shortest path
        sp = ox.shortest_path(G, start, end, weight='length')
        sp_len = self.get_weight_sum(G, sp, 'length')
        sp_grad = self.get_weight_sum(G, sp, 'grade_abs')

        # print('shortest path: ')
        # print("  length: ", sp_len)
        # print("  height: ", sp_grad)

        path = None
        if weight == 'length' and inverse is False:
            path = sp
        else:
            if weight == 'height':
                weight = 'grade_abs' if not inverse else 'inv_grade_abs'
            
            path_gen = ox.k_shortest_paths(G, start, end, self._timeout, weight=weight)

            cnt = 0
            for pth in path_gen:
                cnt += 1
                if self.get_weight_sum(G, pth, 'length') > limit_ratio * sp_len:
                    continue
                path = pth
                # print(cnt)

                # print("limit_ratio:", limit_ratio)
                # print("sp_len", sp_len)
                # print("sp_len * limit_ratio", limit_ratio * sp_len)
                # print("now length", self.get_weight_sum(G, pth, 'length'))

                # print('find path under constraint:')
                # print("  length: ", self.get_weight_sum(G, path, 'length'))
                # print("  height: ", self.get_weight_sum(G, path, 'grade_abs'))
                break

        path_length = self.get_weight_sum(G, path, 'length')
        path_elevation_gain = self.get_weight_sum(G, path, 'grade_abs')
        coords = []
        for node in path:
            coords.append((G.nodes[node]['x'], G.nodes[node]['y']))

        return path, coords, int(path_length), int(path_elevation_gain), int(sp_len), int(sp_grad)
Exemple #5
0
def find_trans_paths(G, transportables, targets):

    print('Finding paths from pickup to delivery..')

    dic = defaultdict(lambda: [])

    dic['node_info'] = G.nodes

    for i in range(len(transportables)):
        temp_dic = defaultdict(lambda: [])

        way = ox.shortest_path(G,
                               transportables[i],
                               targets[i],
                               weight='travel_time')
        dic['route_list'].append(way)
        way_weight = 0
        way_length = 0

        for k in range(len(way) - 1):
            way_weight += G[way[k]][way[k + 1]][0]['travel_time']
            way_length += G[way[k]][way[k + 1]][0]['length']

        dic['weight_list'].append(int(way_weight))
        dic['length_list'].append(int(way_length))

    print('Paths for transportables found..')

    return dic
Exemple #6
0
    def test_shortest_path(self):
        s = StatsSummary()

        G = s.create_graph("University of Massachusetts Amherst", dist = 700)
        G = s.populate_graph(G) #add all the necessary gradients to the graph we have
        G = s.modify_graph_elevate(G)

        origin = ox.get_nearest_node(G, (42.3878210, -72.5239110)) #Frank DC coordinates from the graph G
        end = ox.get_nearest_node(G, (2.3894329, -72.5190326)) #Chadbourne Hall coordinate from G

        shortest_path_normal = ox.shortest_path(G, origin, end, weight = 'length') #shortest path from origin to end
        shortest_path_grad = ox.shortest_path(G, origin, end, weight='impedance')
        shortest_path_dijkstra = networkx.dijkstra_path(G, origin, end, weight = 'length')
        shortest_path_grad_dijkstra = networkx.dijkstra_path(G, origin, end, weight =' impedance')

        self.assertEquals(shortest_path_normal, shortest_path_dijkstra)
        self.assertEquals(shortest_path_grad, shortest_path_grad_dijkstra)
Exemple #7
0
 def shortest_path_elevate(self, G, start, end, dijkstra=False):
     if not dijkstra:
         short_path = ox.shortest_path(G, start, end, weight='impedance')
         coord_path = self.convert_nodes_to_coord(G, short_path)
         return {"nodes": short_path, "coordinates": coord_path}
     else:
         short_path = nx.dijkstra_path(G, start, end, weight='impedance')
         coord_path = self.convert_nodes_to_coord(G, short_path)
         return {"nodes": short_path, "coordinates": coord_path}
Exemple #8
0
def test_routing():

    G = ox.graph_from_address(address=address,
                              dist=500,
                              dist_type="bbox",
                              network_type="bike")

    # give each node a random elevation then calculate edge grades
    randm = np.random.random(size=len(G))
    elevs = {n: e for n, e in zip(G.nodes(), randm)}
    nx.set_node_attributes(G, name="elevation", values=elevs)
    G = ox.add_edge_grades(G, add_absolute=True)

    # give each edge speed and travel time attributes
    G = ox.add_edge_speeds(G)
    G = ox.add_edge_speeds(G, hwy_speeds={"motorway": 100})
    G = ox.add_edge_travel_times(G)

    orig_node = list(G.nodes())[5]
    dest_node = list(G.nodes())[-5]
    orig_pt = (G.nodes[orig_node]["y"], G.nodes[orig_node]["x"])
    dest_pt = (G.nodes[dest_node]["y"], G.nodes[dest_node]["x"])
    route = ox.shortest_path(G, orig_node, dest_node, weight="travel_time")

    attributes = ox.utils_graph.get_route_edge_attributes(G, route)
    attributes = ox.utils_graph.get_route_edge_attributes(
        G, route, "travel_time")

    fig, ax = ox.plot_graph_route(G, route, save=True)

    fig, ax = ox.plot_graph_route(G, route, save=True)

    # test multiple routes
    routes = ox.k_shortest_paths(G,
                                 orig_node,
                                 dest_node,
                                 k=2,
                                 weight="travel_time")
    fig, ax = ox.plot_graph_routes(G, list(routes))

    # test folium with keyword arguments to pass to folium.PolyLine
    gm = ox.plot_graph_folium(G,
                              popup_attribute="name",
                              color="#333333",
                              weight=5,
                              opacity=0.7)
    rm = ox.plot_route_folium(G, route, color="#cc0000", weight=5, opacity=0.7)

    # test calling folium plotters with FeatureGroup instead of Map, and extra kwargs
    fg = folium.FeatureGroup(name="legend name", show=True)
    gm = ox.plot_graph_folium(G, graph_map=fg)
    assert isinstance(gm, folium.FeatureGroup)

    rm = ox.plot_route_folium(G, route, route_map=fg, tooltip="x")
    assert isinstance(rm, folium.FeatureGroup)
Exemple #9
0
def colour_routes(G, routes):
    colours = ['r', 'g', 'b', 'y', 'c']
    cindex = 0
    froutes = []
    fcolours = []
    for grp in routes:
        for i in range(0, len(grp) - 1):
            temp = ox.shortest_path(G, grp[i], grp[i + 1])
            froutes.append(temp)
            fcolours.append(colours[cindex % len(colours)])
        cindex += 1
    return froutes, fcolours
Exemple #10
0
def make_route(origin, destination, selected_poi_impedance):
    """
    Returns the shortest and health routes.

    This function returns two routes for the inputted road network, the selected start and end points and impedance.
    Shortest route : Impedance simply based on length.
    HealthPath : Impedance based on a modified impedance integrating the POIs.
    """
    origin_xy = list(zip(origin.lat, origin.lon))[0]
    dest_xy = list(zip(destination.lat, destination.lon))[0]
    orig = ox.get_nearest_node(G, origin_xy)
    dest = ox.get_nearest_node(G, dest_xy)
    route_health = ox.shortest_path(G,
                                    orig,
                                    dest,
                                    weight=selected_poi_impedance)
    route_short = ox.shortest_path(G, orig, dest, weight='length')
    ####
    gdf_route_edges_short = getRouteEdges(route_short)
    gdf_route_edges_health = getRouteEdges(route_health)

    return origin_xy, dest_xy, route_health, route_short, gdf_route_edges_short, gdf_route_edges_health
Exemple #11
0
def safest_way(origin, destination):  # select safest route
    route = ox.shortest_path(G, origin, destination, weight='danger_weight')
    fig, ax = ox.plot_graph_route(G,
                                  route,
                                  route_color='y',
                                  route_linewidth=6,
                                  node_size=0)  # plot the safest road
    route_risk = int(
        sum(ox.utils_graph.get_route_edge_attributes(
            G, route, 'danger_weight')))  # print the risk on this road
    txt1 = 'The risk on this Route is '
    txt2 = ' accidents per year'
    return fig, txt1, txt2, route_risk
Exemple #12
0
def find_first_paths(G, carriers, transportables):

    print('Finding initial paths to transportables..')

    dic = defaultdict(lambda: [])

    dic['node_info'] = G.nodes

    for i, carrier in enumerate(carriers):
        temp_dic = defaultdict(lambda: [])
        counter = 0
        for j, transportable in enumerate(transportables):

            #if (ox.distance.euclidean_dist_vec(dic['node_info'][carrier]['y'],
            #                                   dic['node_info'][carrier]['x'],
            #                                   dic['node_info'][transportable]['y'],
            #                                   dic['node_info'][transportable]['x'])) <= 0.15:

            dic['connection_list'].append(j * 4 + 1 + len(carriers))
            dic['connection_list_single'].append(j + 1 + len(carriers))
            temp_dic['end_numbers'].append(j)
            temp_dic['start_to_end'].append([i, j])
            dic['plot_start_end'].append([i + 1, len(carriers) + 1 + j * 4])
            way = ox.shortest_path(G,
                                   carrier,
                                   transportable,
                                   weight='travel_time')
            temp_dic['ways_to_transportable'].append(way)
            dic['plot_route'].append(way)
            way_weight = 0
            way_length = 0

            for k in range(len(way) - 1):
                way_weight += G[way[k]][way[k + 1]][0]['travel_time']
                way_length += G[way[k]][way[k + 1]][0]['length']

            dic['weight_list'].append(int(way_weight))
            temp_dic['length_of_routes'].append(int(way_length))
            temp_dic['weights_to_transportables'].append(int(way_weight))
            counter += 1

        dic['end_list'].append(temp_dic['end_numbers'])
        dic['connection_number'].append(counter)
        dic['route_list'].append(temp_dic['ways_to_transportable'])
        dic['weight_list_2'].append(temp_dic['weights_to_transportables'])
        dic['start_end_list'].append(temp_dic['start_to_end'])
        dic['length_list'].append(temp_dic['length_of_routes'])

    print('Initial paths found..')

    return dic
Exemple #13
0
def find_inter_paths(G, transportables, targets, n_carrier):

    print('Finding paths between delivery points and transportables..')

    dic = defaultdict(lambda: [])

    dic['node_info'] = G.nodes

    for i, start_trans in enumerate(targets):
        temp_dic = defaultdict(lambda: [])
        counter = 0
        for j, end_trans in enumerate(transportables):

            #if (ox.distance.euclidean_dist_vec(dic['node_info'][carrier]['y'],
            #                                   dic['node_info'][carrier]['x'],
            #                                   dic['node_info'][transportable]['y'],
            #                                   dic['node_info'][transportable]['x'])) <= 0.15:

            dic['connection_list'].append(j * 4 + 1 + n_carrier)
            temp_dic['end_numbers'].append(j)
            temp_dic['start_to_end'].append([i, j])
            dic['plot_start_end'].append(
                [n_carrier + 1 + i * 4 + 2, n_carrier + 1 + j * 4])
            way = ox.shortest_path(G,
                                   start_trans,
                                   end_trans,
                                   weight='travel_time')
            temp_dic['ways_to_transportable'].append(way)
            dic['plot_route'].append(way)
            way_weight = 0
            way_length = 0

            for k in range(len(way) - 1):
                way_weight += G[way[k]][way[k + 1]][0]['travel_time']
                way_length += G[way[k]][way[k + 1]][0]['length']

            dic['weight_list'].append(int(way_weight))
            temp_dic['length_of_routes'].append(int(way_length))
            temp_dic['weights_to_transportables'].append(int(way_weight))
            counter += 1

        dic['end_list'].append(temp_dic['end_numbers'])
        dic['connection_number'].append(counter)
        dic['route_list'].append(temp_dic['ways_to_transportable'])
        dic['weight_list_2'].append(temp_dic['weights_to_transportables'])
        dic['start_end_list'].append(temp_dic['start_to_end'])
        dic['length_list'].append(temp_dic['length_of_routes'])

    print('Interconnecting paths found..')

    return dic
def shortest_path(G, origen, destino):
    try:
        orig = tuple(reversed(origen))
        dest = tuple(reversed(destino))

        origin_node = ox.distance.get_nearest_node(G, orig)
        destination_node = ox.distance.get_nearest_node(G, dest)
        ruta = ox.shortest_path(G,
                                origin_node,
                                destination_node,
                                weight="travel_time")
        ruta_cambio = nodes_to_linestring(G, ruta)
        print("Se obtuvo ruta correctamente")
        return ruta_cambio
    except Exception:
        # for unsolvable routes (due to directed graph perimeter effects)
        return None
Exemple #15
0
 def distance(self, loc):
     try:
         orig = ox.get_nearest_node(G, (self.lat, self.long))
         dest = ox.get_nearest_node(G, (loc.lat, loc.long))
         route = ox.shortest_path(G, orig, dest, weight='travel_time')
         edge_lengths = ox.utils_graph.get_route_edge_attributes(
             G, route, 'length')
         edge_time = ox.utils_graph.get_route_edge_attributes(
             G, route, 'travel_time')
         dis = sum(edge_lengths) / 1000
         dur = sum(edge_time) / 60
         return [dis, dur]
     except:
         origin = [self.lat, self.long]
         destination = [loc.lat, loc.long]
         dis = geodesic(origin, destination).kilometers
         dur = dis / 0.5
         return [dis, dur]
Exemple #16
0
def hello_world():
    arry = []
    record = {}
    if request.method == 'POST':
        lat1 = float(request.form['lat1'])
        lng1 = float(request.form['lng1'])
        lat2 = float(request.form['lat2'])
        lng2 = float(request.form['lng2'])
        city = ox.graph_from_point((lat1, lng1), dist=1000, network_type='drive')
        start = ox.get_nearest_node(city, (lat1, lng1))
        end = ox.get_nearest_node(city, (lat2, lng2))
        path = ox.shortest_path(city, start, end)
    for x in path:
        lat = city.nodes[x]['y']
        lng = city.nodes[x]['x']
        arry.append({
            'lat':lat,
            'lng':lng
        })
    record['path'] = arry
    return record
Exemple #17
0
def getRoute(data):

    distRec = np.zeros(len(data), order='C')
    for i in range(0, len(data.iloc[0:1])):
        try:
            a = [
                data['latitude_start'].iloc[i], data['longitude_start'].iloc[i]
            ]
            b = [data['latitude_end'].iloc[i], data['longitude_end'].iloc[i]]
            d = float(str(geopy.distance.great_circle(a, b)).split()[0])
            '''bike,drive, mode'''
            # get a graph for some city
            if d != 0:
                G = ox.graph_from_point([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2],
                                        dist=d * 1200,
                                        network_type='bike')
            else:
                G = ox.graph_from_point([(a[0] + b[0]) / 2, (a[1] + b[1]) / 2],
                                        dist=d + 1200,
                                        network_type='bike')
            # get the nearest network nodes to two lat/lng points
            orig = ox.get_nearest_node(G, (a))
            dest = ox.get_nearest_node(G, (b))
            # find the shortest path between these nodes, minimizing travel time, then plot it
            route = ox.shortest_path(G, orig, dest, weight='length')

            #fig1, ax = ox.plot_graph_route(G, route, node_size=0, show=False, close=True, save=True, filepath='plot.png', bgcolor="#ffffff",edge_color="#85d3de")
            #ax.set_title(' Bike Route')

            # how long is our route in meters?
            edge_lengths = ox.utils_graph.get_route_edge_attributes(
                G, route, 'length')
            distRec[i] = sum(edge_lengths) / 1000
        except:
            distRec[i] = np.nan
    #print('distRec: =', distRec[i])
    return distRec, G, route
def shortest_path(datos):
    try:
        G = datos[0]
        agebs_cvegeo = datos[1]
        destino = datos[2]
        orig = tuple(reversed(datos[3]))
        dest = datos[4]

        origin_node = ox.distance.get_nearest_node(G, orig)
        destination_node = ox.distance.get_nearest_node(G, dest)
        ruta = ox.shortest_path(G,
                                origin_node,
                                destination_node,
                                weight="travel_time")
        ruta_cambio = nodes_to_linestring(ruta)
        resultados = {
            'ageb': [agebs_cvegeo],
            'destino': [destino],
            "ruta": [ruta_cambio]
        }
        return pd.DataFrame(resultados)
    except Exception:
        # for unsolvable routes (due to directed graph perimeter effects)
        return None
Exemple #19
0
                       south,
                       east,
                       west,
                       network_type='drive',
                       simplify=True)

# orig = ox.get_nearest_node(G, (f1['lat'],f1['lng']))
# route = nx.shortest_path(G, orig, 136012883)
# fig, ax = ox.plot_graph_route(G, route, show=False, close=False)

# route_map = ox.plot_route_folium(G, route)
# route_map

dest = ox.get_nearest_node(G, (40.135788, -75.5076694))

route1 = ox.shortest_path(G, 254777437, dest, weight='length')
route2 = ox.shortest_path(G, 136012883, dest, weight='length')
route3 = ox.shortest_path(G, 136148333, dest, weight='length')

fig, ax = ox.plot_graph(G, node_size=0, show=False, close=False)
ax.scatter(-75.3965480, 40.0137071, c='green', alpha=1, zorder=9)

plt.show()

# Loop through every Call
# for i in df.index:
#     newLat = df.at[i,'lat']
#     newLng = df.at[i,'lng']
#     emer = df.at[i,'Alert Type']

#     dest = ox.get_nearest_node(G, (newLat,newLng))
Exemple #20
0
 def shortest_path_normal(G, start, end):
     return ox.shortest_path(G, start, end, weight='length')
Exemple #21
0
 def shortest_path_elevate(G, start, end):
     return ox.shortest_path(G, start, end, weight='impedance')
import re
from num2words import num2words

import csv

#G = ox.graph_from_place('New york city, New York, USA', network_type='drive')

#ox.io.save_graphml(G, filepath='data/ml.graphml', gephi=False, encoding='utf-8')

G = ox.io.load_graphml(filepath='nyc-navigation/data/ml.graphml')

origin_node = ox.get_nearest_node(G, (40.789592, -73.800298))
destination_node = ox.get_nearest_node(G, (40.735079, -73.708458))

route2 = ox.shortest_path(G, origin_node, destination_node, weight='length')

fig, ax = ox.plot_graph_route(G,
                              route2,
                              route_color='y',
                              route_linewidth=6,
                              node_size=0)
"""unpacked = [pd.DataFrame({**{'node': node, **data}}, index=[i]) for i, (node, data) in enumerate(G.nodes(data=True))]
df = pd.concat(unpacked)
df.to_csv('data/g.csv')"""

#G = ox.add_edge_speeds(G)

# df = pd.read_csv('nyc-navigation/data/datweight_2.csv')
# edges = pd.read_csv('nyc-navigation/data/edges_new.csv')