예제 #1
0
파일: Render.py 프로젝트: 4ilo/masterproef
 def __init__(self, map_path, start_node=-137971):
     self.G = ox.graph_from_file(map_path,
                                 name="Map",
                                 retain_all=True,
                                 simplify=False)
     ox.config(imgs_folder="data/plot")
     self.start = start_node
def convert_to_graph(osm_file=config.osm_file):
    graph = ox.graph_from_file(osm_file,
                               simplify=False,
                               retain_all=True,
                               name='Chel')
    largest_component = list(
        max(nx.strongly_connected_components(graph), key=len))
    return graph, largest_component
예제 #3
0
def main():
    
    grafo = object
    
    try:
        # grafo - MultiDiGraph
        print('>>\tCarregando grafo de arquivo .OSM')
        grafo = ox.graph_from_file(simplify=True, retain_all=False, filename=NOME_ARQUIVO_OSM + ".osm", name=NOME_ARQUIVO_OSM)
    except IOError as e:
        print('!!\tO grafo não pôde ser carregado.\n\nErro:\n', e)
    
    print('OK\tGrafo OSM carregado.\n')
    
    
    r = input(">>\tGerar arquivo graphml e grafos em formato de texto? (s/n)")
    if r == 's':
        #grafo = ox.graph_from_file(network_type='all', simplify=True, retain_all=False, filename=NOME_ARQUIVO_OSM + ".osm", name=NOME_ARQUIVO_OSM)
        #Salvando grafo gerado como arquivo .graphml em disco local
        ox.save_load.save_graphml(grafo, filename="grafo("+NOME_ARQUIVO_OSM+").graphml", folder=CAMINHO_ARQUIVOS )
    
        print('OK\tGrafo graphml gerado.\n')

        print('>>\tGerando grafo com nós padrão e grafo indexado no formato de arquivo texto.')
        # como é preciso que os grafos txt sejam gerados e que o número de nós seja
        # conhecido, a opção de gerar grafo agora é obrigatória ao usuário. O grafo
        # é carregado a partir de arquivo .graphml
        grafo = ox.save_load.load_graphml("grafo(" + NOME_ARQUIVO_OSM + ").graphml", folder=CAMINHO_ARQUIVOS)
        salva_grafo_txt(grafo, NOME_ARQUIVO_OSM)
        
        print('OK\tGrafos de texto gerados.\n')


    r = input('>>\tGerar instância (s/n)?')
    if r == 's': 
        gera_instancia_uhga()
        
        print('OK\tInstância gerada.\n')


    r = input(">>\tGerar arquivo '.graphml' modificado? (s/n)")
    if r == 's':
        # recebe o grafo com valores de nós padronizados
        # e retorna um grafo modificado com valores de nós menores (indexados) para ser desenhado
        try:
            arquivo_grafo = open(CAMINHO_ARQUIVOS + 'grafo('+NOME_ARQUIVO_OSM+').graphml', 'r', encoding='utf-8')
            recursos.modificador_grafo.modifica_valores_no_grafo(CAMINHO_ARQUIVOS, arquivo_grafo, NOME_ARQUIVO_OSM)        
        except IOError as e:
            print (e)

        print('OK\tGrafo modificado gerado.\n')

    grafoml = ox.save_load.load_graphml("grafomod(" + NOME_ARQUIVO_OSM + ").graphml", CAMINHO_ARQUIVOS)

    r = input('>>\tMostrar rotas no Grafo? (s/n)')
    if r == 's': 
        mostra_rotas(grafoml)    
예제 #4
0
    def _osm_net_from_osmnx(self, boundary, osm_file=None):
        """
        Submits an Overpass API query and returns a geodataframe of results

        Parameters
        ----------
        boundary : shapely geometry object
            shapely geometry representing the boundary for pulling the network
        osm_file : str, optional
            an OSM XML file to use instead of downloading data from the network
        """
        # https://osmnx.readthedocs.io/en/stable/osmnx.html#osmnx.save_load.graph_to_gdfs
        node_tags = [
            "access", "amenity", "bicycle", "bridge", "button_operated",
            "crossing", "flashing_lights", "foot", "highway", "junction",
            "leisure", "motorcar", "name", "oneway", "oneway:bicycle",
            "operator", "public_transport", "railway", "segregated", "shop",
            "stop", "surface", "traffic_sign", "traffic_signals", "tunnel",
            "width"
        ]
        way_tags = [
            "access", "bridge", "bicycle", "button_operated", "crossing",
            "cycleway", "cycleway:left", "cycleway:right", "cycleway:both",
            "cycleway:buffer", "cycleway:left:buffer", "cycleway:right:buffer",
            "cycleway:both:buffer", "cycleway:width", "cycleway:left:width",
            "cycleway:right:width", "cycleway:both:width", "flashing_lights",
            "foot", "footway", "highway", "junction", "landuse", "lanes",
            "lanes:forward", "lanes:backward", "lanes:both_ways", "leisure",
            "maxspeed", "motorcar", "name", "oneway", "oneway:bicycle",
            "operator", "parking", "parking:lane", "parking:lane:right",
            "parking:lane:left", "parking:lane:both", "parking:lane:width",
            "parking:lane:right:width", "parking:lane:left:width",
            "parking:lane:both:width", "public_transport", "railway",
            "segregated", "service", "shop", "stop", "surface", "tracktype",
            "traffic_sign", "traffic_signals:direction", "tunnel",
            "turn:lanes", "turn:lanes:both_ways", "turn:lanes:backward",
            "turn:lanes:forward", "width", "width:lanes",
            "width:lanes:forward", "width:lanes:backward"
        ]

        ox.config(useful_tags_node=node_tags, useful_tags_path=way_tags)
        if osm_file:
            G = ox.graph_from_file(osm_file, simplify=True, retain_all=False)
        else:
            G = ox.graph_from_polygon(boundary,
                                      network_type='all',
                                      simplify=True,
                                      retain_all=False,
                                      truncate_by_edge=False,
                                      timeout=180,
                                      clean_periphery=True,
                                      custom_filter=None)
        G = ox.get_undirected(G)
        gdfs = ox.graph_to_gdfs(G)
        return gdfs[1], gdfs[0]
예제 #5
0
    def __init__(self, height=50, width=50, num_bikes=10, num_riders=100, place='Boston, Massachusetts, USA'):
        # Set parameters
        self.height = height
        self.width = width
        self.num_bikes = num_bikes
        self.num_riders = num_riders
        self.place = place
        self.cur_time = "10/01/19 0:00:00"

        # hard coded for now
        self.schedule = TimedActivation(self, "10/01/19 0:00:00", "10/02/19 14:00:00")

        if 'Quincy' in place:
            self.G = ox.graph_from_file('data/quincy.osm')
        elif 'Boston' in place:
            self.G = ox.graph_from_file('data/boston.osm')
        else:
            self.G = ox.graph_from_place(place, network_type='bike')

        # self.G = self.G.to_directed()

        self.grid = NetworkGrid(self.G)
        self.datacollector = DataCollector({
            "Rider": lambda m: m.schedule.get_breed_count(Rider),
            "Missed Rides": lambda m: m.missed_rides
        })

        self.stations = {}
        self.missed_rides = 0

        # Create stations
        self.createStations()

        # Create riders:
        self.createRiders()

        # Create bikes:
        self.createBikes()

        self.running = True
        self.datacollector.collect(self)
예제 #6
0
def extract_full_graph_from_osm(osm_path, osm_data_name="external"):
    """
    Extracts graph from a pre-downloaded OSM file (either xml or pbf format).
    Typically useful if using older data and thus latest OSM map might be too up to date.
    You can download old OSM files from http://download.geofabrik.de/
    e.g. http://download.geofabrik.de/europe/portugal.html -> raw directory index - > *.osm.pbf
    If OSM file, this function requires osmconvert, which can be installed with:
        Linux: apt install osmctools
        Mac OS: brew install interline-io/planetutils/osmctools
    :param osm_path: path of OSM pbf or xml file
    :param osm_data_name: name of data (i.e. location and data)
    :return: networkx graph, pruned but not simplified or projected
    """

    # Source data paths
    _, process_data_path = data.utils.source_data()

    # Check extension of data
    if osm_path[-3:] == 'pbf':
        # Convert pbf to xml
        _, process_data_path = data.utils.source_data()

        convert_path = process_data_path + '/graphs/' + os.path.basename(
            osm_path)[:-3] + 'xml'

        # Use osmconvert to convert
        osmconvert_cmd = "osmconvert " + osm_path \
                         + " -b={},{},{},{}".format(bbox_ll[3], bbox_ll[1], bbox_ll[2], bbox_ll[0]) \
                         + "--drop-broken-refs --complete-ways" \
                         + " -o=" + convert_path

        os.system(osmconvert_cmd)

    elif osm_path[-3:] == 'xml':
        convert_path = osm_path
    else:
        raise ValueError('OSM file must be either .xml or .pbf')

    graph_full = ox.graph_from_file(convert_path,
                                    name=osm_data_name,
                                    simplify=False)

    graph_full = ox.truncate_graph_bbox(graph_full, bbox_ll[0], bbox_ll[1],
                                        bbox_ll[2], bbox_ll[3])

    graph_full = prune_non_highways(graph_full)

    return graph_full
예제 #7
0
def buildHTMLWithQuery(query):
    writeXMLResponse(query)
    try:
        if os.stat(responsePath).st_size >= 2097152:
            logging.warning(
                "Response is too big. Maybe the map will not work properly but you can use the option "
                "'Open netedit'.")
        G = ox.graph_from_file(responsePath, retain_all=True)
    except (ValueError, KeyError):
        raise OsmnxException(
            "Probably there are elements without all its nodes or the response is empty. "
            "It is not possible to show the results but you can use the option 'Open netedit'."
        )
    logging.info("Network built.")

    return buildHTMLWithNetworkx(G)
예제 #8
0
def query_OSM(directory, boundary, graph_pickle_file, query='drive_main'):
    """
    Query OpenStreetMap and save it as a pickle file.

    Parameters
    ----------
    directory : directory path where inputs and outputs should be
    boundary : Boundary for road network which can be either polygon boundary file
               or bounding box coordinates [north, south, west, east]
    network_type : string
        {'walk', 'bike', 'drive_all', 'drive_main', 'drive_main_links_included', 'drive_service', 'all', 'all_private', 'none'}
        what type of street or other network to get
    """
    mainG = ox.graph_from_file(input_osm_file,
                               network_type=query,
                               simplify=False,
                               retain_all=True)
    # mainG = ox.graph_from_xml(input_osm_file, simplify=False, retain_all=True)
    nx.write_gpickle(mainG, graph_pickle_file)
예제 #9
0
def test_graph_from_file():
    # test loading a graph from a local .osm file
    node_id = 53098262
    neighbor_ids = 53092170, 53060438, 53027353, 667744075

    with bz2.BZ2File("tests/input_data/West-Oakland.osm.bz2") as input:
        handle, temp_filename = tempfile.mkstemp(suffix=".osm")
        os.write(handle, input.read())
        os.close(handle)

    for filename in ("tests/input_data/West-Oakland.osm.bz2", temp_filename):
        G = ox.graph_from_file(filename)
        assert node_id in G.nodes

        for neighbor_id in neighbor_ids:
            edge_key = (node_id, neighbor_id, 0)
            assert neighbor_id in G.nodes
            assert edge_key in G.edges
            assert G.edges[edge_key]["name"] in ("8th Street", "Willow Street")

    os.remove(temp_filename)
예제 #10
0
def test_graph_from_file():
    
    node_id = 53098262
    neighbor_ids = 53092170, 53060438, 53027353, 667744075

    with bz2.BZ2File('tests/input_data/West-Oakland.osm.bz2') as input:
        handle, temp_filename = tempfile.mkstemp(suffix='.osm')
        os.write(handle, input.read())
        os.close(handle)

    for filename in ('tests/input_data/West-Oakland.osm.bz2', temp_filename):
        G = ox.graph_from_file(filename)
        assert node_id in G.nodes

        for neighbor_id in neighbor_ids:
            edge_key = (node_id, neighbor_id, 0)
            assert neighbor_id in G.nodes
            assert edge_key in G.edges
            assert G.edges[edge_key]['name'] in ('8th Street', 'Willow Street')

    os.remove(temp_filename)
예제 #11
0
파일: test_osmnx.py 프로젝트: gboeing/osmnx
def test_graph_from_file():

    # test loading a graph from a local .osm file
    import bz2, tempfile

    node_id = 53098262
    neighbor_ids = 53092170, 53060438, 53027353, 667744075

    with bz2.BZ2File('tests/input_data/West-Oakland.osm.bz2') as input:
        handle, temp_filename = tempfile.mkstemp(suffix='.osm')
        os.write(handle, input.read())
        os.close(handle)

    for filename in ('tests/input_data/West-Oakland.osm.bz2', temp_filename):
        G = ox.graph_from_file(filename)
        assert node_id in G.nodes

        for neighbor_id in neighbor_ids:
            edge_key = (node_id, neighbor_id, 0)
            assert neighbor_id in G.nodes
            assert edge_key in G.edges
            assert G.edges[edge_key]['name'] in ('8th Street', 'Willow Street')

    os.remove(temp_filename)
예제 #12
0
def load_graph():
    while True:
        text = input('Import a graph? (y|n)')
        if text == 'y' or text == 'Y' or text == "Yes" or text == "yes":
            path = input('Enter graph path')
            graph = ox.graph_from_file(path,
                                       network_type='drive',
                                       simplify=True,
                                       retain_all=True,
                                       name='unnamed')
            G_projected = ox.project_graph(graph)
            ox.plot_graph(G_projected)
            return graph
        text = input("Create new graph? (y|n)")
        if text == 'y' or text == 'Y' or text == "Yes" or text == "yes":
            while True:
                # west = float(input("Top left coordinate latitude (west bounding)"))
                # north = float(input("Top left coordinate longitude (north bounding)"))
                # east = float(input("Bottom right coordinate latitude (east bounding)"))
                # south = float(input("Bottom right coordinate longitude (south bounding)"))

                north, south, east, west = 37.79, 37.78, -122.41, -122.43
                graph = ox.graph_from_bbox(north,
                                           south,
                                           east,
                                           west,
                                           network_type='drive',
                                           truncate_by_edge=True,
                                           simplify=True)
                # G_projected = ox.project_graph(graph)
                # ox.plot_graph(G_projected)
                text = input("Does this look correct?")
                if text == 'y' or text == 'Y' or text == "Yes" or text == "yes":
                    text = str(input("Name the graph file"))
                    ox.save_graphml(graph, filename=text + '.graphml')
                    return graph
예제 #13
0
        returndict = 0
        print('返回结果')
        print(returndict)
        returnjson = json.dumps(returndict)
        returnjson = make_response(returnjson)
        returnjson.headers['Access-Control-Allow-Origin'] = '*'
        return returnjson
    else:
        return '只接受post请求!'


if __name__ == '__main__':

    # 获取路网信息
    print("开始路网匹配")
    huangpu = ox.graph_from_file("D:\Anaconda\data\huangpu\huangpu.osm", network_type="drive")
    nodes, edges = ox.graph_to_gdfs(huangpu)
    edges["name"].fillna("nan", inplace=True)


    def list_perform(x):
        if type(x) == type([]):
            return x[0]
        else:
            return x


    edges['name'] = edges['name'].apply(lambda x: list_perform(x))
    huangpu_edges = edges
    huangpu_edges = huangpu_edges[huangpu_edges['name'] != "nan"]
예제 #14
0
파일: test.py 프로젝트: 4ilo/masterproef
import osmnx as ox

G = ox.graph_from_file("amk_copy.osm", name="test")
ox.plot_graph(G)
#test = ox.graph_to_gdfs(G)
#ox.plot_shape(ox.project_gdf(test))
예제 #15
0
import osmnx as ox
import networkx as nx

# Read map
G = ox.graph_from_file("data/map.osm", name="Kaart", retain_all=True)

nodes = [-126565, -126574, -126583, -126592, -126601, -126610, -126619]

start = ox.get_nearest_node(G, (50.13554168794, 8.64772690044))

for node in nodes:
    route = nx.shortest_path(G, start, node, weight='length')
    fig, ax = ox.plot_graph_route(G, route, node_size=0, show=False)
    fig.show()
예제 #16
0
import numpy as np
import networkx as nx

#G =  osmnx.graph_from_file('/home/user/MiniTaxiFleets/AnuStart/mini_centraal_sac_town.osm', network_type='drive',simplify=True)

#G =  osmnx.graph_from_file('/home/user/MiniTaxiFleets/road_network_osm_files/cologne_centraal_ish_8km2.osm', network_type='drive',simplify=True)

#all on c207
path_to_osm_files = '/home/user/Downloads/osm_city_road_maps/'

SF_central_filename = 'SF_central_64km2_-122.479,37.733_-122.388,37.805.osm'
Roma_centrale_filename = 'roma_centrale_64km2_12.442,41.856_12.5387,41.928.osm'
Birmingham_central_filename = 'Birmingham_central_64km2_-1.971,52.447_-1.825,52.508.osm'

G1 = osmnx.graph_from_file(path_to_osm_files + SF_central_filename,
                           network_type='drive',
                           simplify=True)

G2 = osmnx.graph_from_file(path_to_osm_files + Roma_centrale_filename,
                           network_type='drive',
                           simplify=True)

G3 = osmnx.graph_from_file(path_to_osm_files + Birmingham_central_filename,
                           network_type='drive',
                           simplify=True)

G1b = osmnx.core.add_edge_lengths(G1)
G2b = osmnx.core.add_edge_lengths(G2)
G3b = osmnx.core.add_edge_lengths(G3)

#nx.write_gpickle(G2, "Cologne_Centraal_Road_Network.gpickle", protocol=2)
예제 #17
0
 def load_map():
     return ox.graph_from_file(
         f'{OSM_OUTPUT_DIR}/{OSM_OUTPUT_FILENAME}.osm')
예제 #18
0
import json

import matplotlib.pyplot as plt
import networkx as nx
import osmnx as ox

G = ox.graph_from_file("map.osm")

# nodes, _ = ox.graph_to_gdfs(G)

library = (31.242, 121.433)
museum = (31.235, 121.45)

closest_node_to_lib = ox.get_nearest_node(G, library, method='haversine')
closest_node_to_museum = ox.get_nearest_node(G, museum, method='haversine')

route = nx.shortest_path(G, closest_node_to_lib, closest_node_to_museum)
print(route)

total_line = []
for i in range(len(route) - 1):
    # 当前node
    node_id = route[i]
    # 下一node
    next_node_id = route[i + 1]
    segment = G[node_id][next_node_id][0]
    # 两个node之间为直线时, edge中不包含geometry, 用node的坐标连线即可
    # 两个node之间为折线时, edge会有geometry(LineString)
    if 'geometry' in segment:
        line = segment['geometry']
        if i == 0:
예제 #19
0
    # Find nodes closest to the specified coordinates
    node_start = ox.utils.get_nearest_node(area_graph, startpoint)
    node_stop = ox.utils.get_nearest_node(area_graph, endpoint)
    #Calculate the shortest network distance between the nodes via the edges length
    try:
        distance = round(nx.shortest_path_length(area_graph, node_start, node_stop, weight="length"),0)
    # return NA if no path exists
    except nx.NetworkXNoPath:
        distance = "NA"
    return distance

print("Downloading Dublin maps from OpenStreetMap API...")
# Load map from OpenStreetMap API
G = ox.graph_from_place('Dublin, Ireland', network_type='drive')
ox.save_graph_osm(G, filename='mynetwork.osm')
E = ox.graph_from_file(filename='data\mynetwork.osm', bidirectional = False)

# Settings for Streetnetwork-Download
map_file = 'data\mynetwork.osm'
force_creat = False

#Checks if the Streetnetwork File exists (or creation is overwritten)
if (not os.path.isfile(map_file))or force_creat:
    area_graph = ox.graph_from_place('Dublin, Ireland', network_type='drive')
    ox.save_graph_osm(area_graph, filename=map_file)
else:
    area_graph = ox.graph_from_file(filename = map_file, bidirectional = False)

print("Map download complete")

# input lat long from position file
예제 #20
0
def index(request):
    try:
        if request.method == 'POST':
            retrieveForm = AddressForm(request.POST)
            if retrieveForm.is_valid():
                # punggol, singapore
                org_var = retrieveForm.cleaned_data['var_org']
                # blk 128B, punggol, singapore
                dst_var = retrieveForm.cleaned_data['var_dst']
                type_var = retrieveForm.cleaned_data['var_type']

                geolocator = Nominatim(user_agent="test")
                org_addr = geolocator.geocode(org_var)
                dst_addr = geolocator.geocode(dst_var)
                org = (org_addr.latitude, org_addr.longitude)
                dest = (dst_addr.latitude, dst_addr.longitude)

                if type_var == 'Bus':
                    graph = ox.graph_from_file(JSON_FOLDER + "punggol.osm",
                                               bidirectional=True,
                                               simplify=True,
                                               retain_all=False)

                    start = ox.geocode(org_var)
                    end = ox.geocode(dst_var)

                    print("Found a starting node", start)
                    print("Found a ending node", end)

                    start_node = ox.get_nearest_node(graph, start)
                    end_node = ox.get_nearest_node(graph, end)

                    nodes, edges = ox.graph_to_gdfs(graph)

                    # TO CREATE BUS ROUTING
                    pathcheck = bus(busGraph, graph, start, end, start_node,
                                    end_node)

                    # IF BUS ROUTE IS AVAILABLE
                    if pathcheck[1] == 0:
                        startStopCoords = pathcheck[2]
                        endStopCoords = pathcheck[3]

                        print(startStopCoords)
                        print(endStopCoords)

                        start_Bus = ox.get_nearest_node(graph, startStopCoords)
                        end_Bus = ox.get_nearest_node(graph, endStopCoords)

                        pathToBusstop = astar_path(graph, start_node,
                                                   start_Bus)
                        pathFromBusstop = astar_path(graph, end_Bus, end_node)

                        latlontobus = []
                        latlonfrombus = []

                        # walk from start to bus start
                        startbuscoord = (graph.nodes[start_Bus]['y'],
                                         graph.nodes[start_Bus]['x'])
                        prev = None
                        splice = None
                        ptr = 0
                        temp = float("Infinity")
                        for item in pathToBusstop:
                            if prev is None:
                                prev = item
                            else:
                                try:
                                    line = graph[prev][item][0]["geometry"]
                                    for point in list(line.coords):
                                        if splice is None:
                                            splice = ptr
                                            temp = geopy.distance.distance(
                                                startbuscoord,
                                                (point[1], point[0])).km
                                        elif geopy.distance.distance(
                                                startbuscoord,
                                            (point[1], point[0])).km < temp:
                                            splice = ptr
                                            temp = geopy.distance.distance(
                                                startbuscoord,
                                                (point[1], point[0])).km
                                        latlontobus.append(
                                            (point[1], point[0]))
                                        ptr += 1
                                except:
                                    pass
                                finally:
                                    prev = item
                        latlontobus = latlontobus[:splice + 1]

                        # walk for bus end to dst
                        endbuscoord = (graph.nodes[end_Bus]['y'],
                                       graph.nodes[end_Bus]['x'])
                        prev = None
                        splice = None
                        ptr = 0
                        temp = float("Infinity")
                        for item in pathFromBusstop:
                            if prev is None:
                                prev = item
                            else:
                                try:
                                    line = graph[prev][item][0]["geometry"]
                                    for point in list(line.coords):
                                        if splice is None:
                                            splice = ptr
                                            temp = geopy.distance.distance(
                                                endbuscoord,
                                                (point[1], point[0])).km
                                        elif geopy.distance.distance(
                                                endbuscoord,
                                            (point[1], point[0])).km < temp:
                                            splice = ptr
                                            temp = geopy.distance.distance(
                                                endbuscoord,
                                                (point[1], point[0])).km
                                        latlonfrombus.append(
                                            (point[1], point[0]))
                                        ptr += 1
                                except:
                                    pass
                                finally:
                                    prev = item
                        latlonfrombus = latlonfrombus[:splice + 1]

                        path = pathcheck[0]
                        indexing = 0
                        line = []
                        prevService = None
                        prevIndex = None
                        i = 0
                        markers = []
                        routing = None
                        while i < len(path):
                            stopCode, service = path[i]
                            # in the case of first stop, no bus service stated, take next
                            if service is None:
                                service = path[i + 1][1]

                            if service != prevService:
                                indexing = 0
                                prevIndex = 0

                            qlat = bus_stop_code_map[stopCode]["Latitude"]
                            qlon = bus_stop_code_map[stopCode]["Longitude"]

                            # get routes for respective direction
                            if service[1] == 1:
                                routing = busRoute0[service[0]]["coordinates"]
                            else:
                                routing = busRoute1[service[0]]["coordinates"]
                            while indexing < len(routing):
                                clon, clat = routing[indexing]
                                u = (qlat, qlon)
                                v = (clat, clon)
                                # stop found in range of 30 meters, latlong accuracy difference from
                                # two sources
                                if geopy.distance.distance(u, v).km < 0.03:
                                    # first bus stop
                                    if prevService is None:
                                        line.append(v)
                                    else:
                                        if prevService == service:
                                            print("ALWAYS COME HERE?",
                                                  prevIndex, indexing)
                                            for x, y in routing[
                                                    prevIndex:indexing + 1]:
                                                line.append((y, x))
                                        else:
                                            print(
                                                "ENTER ELSE ---------------------------------"
                                            )
                                            prevLatLong = line[-1]
                                            tempIndex = 0
                                            while tempIndex < len(routing):
                                                plon, plat = routing[tempIndex]
                                                p = (plat, plon)
                                                if geopy.distance.distance(
                                                        prevLatLong,
                                                        p).km < 0.03:
                                                    for x, y in routing[
                                                            tempIndex:
                                                            indexing + 1]:
                                                        line.append((y, x))
                                                    break
                                                tempIndex += 1
                                    prevIndex = indexing
                                    prevService = service
                                    markers.append((v, stopCode))
                                    break
                                indexing += 1
                            i += 1

                        # TO CREATE ROUTING WITH BUS
                        nodepath = astar_path(graph, start_node, end_node)
                        m = ox.plot_route_folium(graph,
                                                 nodepath,
                                                 tiles='openstreetmap',
                                                 route_color='green',
                                                 route_opacity=0)
                        folium.Marker(location=(start[0], start[1]),
                                      popup='START',
                                      icon=folium.Icon(color='red',
                                                       icon='flag')).add_to(m)
                        folium.Marker(location=(end[0], end[1]),
                                      popup='END',
                                      icon=folium.Icon(color='blue',
                                                       icon='flag')).add_to(m)
                        for loc, code in markers:
                            folium.Marker(location=loc,
                                          popup='Bus stop number:' + str(code),
                                          icon=folium.Icon(
                                              color='green',
                                              icon='bus',
                                              prefix='fa')).add_to(m)
                        folium.PolyLine(line,
                                        color="red",
                                        weight=2.5,
                                        opacity=1).add_to(m)

                        # start point to start busstop
                        folium.PolyLine([start, latlontobus[0]],
                                        color="blue",
                                        weight=2.5,
                                        opacity=1,
                                        dasharray="4").add_to(m)
                        folium.PolyLine(latlontobus,
                                        color="green",
                                        weight=2.5,
                                        opacity=1).add_to(m)
                        folium.PolyLine([latlontobus[-1], line[0]],
                                        color="blue",
                                        weight=2.5,
                                        opacity=1,
                                        dasharray="4").add_to(m)

                        # End  bus stop to end point
                        folium.PolyLine([line[-1], latlonfrombus[0]],
                                        color="blue",
                                        weight=2.5,
                                        opacity=1,
                                        dasharray="4").add_to(m)
                        folium.PolyLine(latlonfrombus,
                                        color="green",
                                        weight=2.5,
                                        opacity=1,
                                        dasharray="4").add_to(m)
                        folium.PolyLine([latlonfrombus[-1], end],
                                        color="blue",
                                        weight=2.5,
                                        opacity=1,
                                        dasharray="4").add_to(m)

                        m.save(ROUTE_FOLDER + 'bus_routing.html')

                    # IF BUS ROUTE NOT FOUND, RUN WALK ROUTE
                    if pathcheck[1] == 1:
                        nodepath = pathcheck[0]
                        m = ox.plot_route_folium(graph,
                                                 nodepath,
                                                 tiles='openstreetmap',
                                                 route_color='green')
                        folium.Marker(location=(start[0], start[1]),
                                      popup='START',
                                      icon=folium.Icon(color='red',
                                                       icon='flag')).add_to(m)
                        folium.Marker(location=(end[0], end[1]),
                                      popup='END',
                                      icon=folium.Icon(color='blue',
                                                       icon='flag')).add_to(m)
                        m.save(ROUTE_FOLDER + 'bus_routing.html')

                    print("bus_routing.html created!")

                    speedBus = 40
                    stopsBus = getStops()
                    distanceBus = round(getDistance(), 3)
                    timeBus = math.ceil((getDistance() / speedBus) * 60)
                    timeBus = timeBus + stopsBus
                    if distanceBus <= 3.2:
                        costBus = 0.92
                    elif distanceBus <= 4.2:
                        costBus = 1.02
                    elif distanceBus <= 5.2:
                        costBus = 1.12
                    elif distanceBus <= 6.2:
                        costBus = 1.22
                    elif distanceBus <= 7.2:
                        costBus = 1.31
                    elif distanceBus <= 8.2:
                        costBus = 1.38
                    elif distanceBus <= 9.2:
                        costBus = 1.44
                    else:
                        costBus = 2
                    busRoute = getBus().split(',')

                    contentDict = {
                        "org_addr": org_addr.address,
                        "dst_addr": dst_addr.address,
                        "mode_var": type_var,
                        "distance": distanceBus,
                        "stops": getStops(),
                        "bus": busRoute,
                        "time": timeBus,
                        "cost": costBus
                    }
                    return render(request, "bus.html", contentDict)

                elif type_var == 'LRT':
                    print("Loading OSM")
                    graph = ox.graph_from_file(JSON_FOLDER + "punggol.osm",
                                               bidirectional=True,
                                               simplify=True,
                                               retain_all=False)

                    start = ox.geocode(org_var)
                    end = ox.geocode(dst_var)
                    print("Found a starting node", start)
                    print("Found a ending node", end)

                    start_node = ox.get_nearest_node(graph, start)
                    end_node = ox.get_nearest_node(graph, end)

                    nodes, edges = ox.graph_to_gdfs(graph)

                    # TO CREATE ROUTE TO AND FROM LRT
                    path_to_Lrt = findNearestLrt(graph, start, end, start_node,
                                                 end_node)

                    # LRT ROUTING
                    lrtline = []
                    lrtMarkers = []

                    if path_to_Lrt is not None:
                        # if LRT path is found
                        if path_to_Lrt[1] == 0:
                            pathDict = path_to_Lrt[0]
                            for path in pathDict:
                                indexing = 0
                                prevService = None
                                prevIndex = None
                                i = 0
                                for item in path:
                                    direction = item[0][4]
                                    stationName = item[0][1]
                                    loop = item[0][-1]
                                if direction == 1:
                                    print("D 1 \n")
                                    routing = LrtRoute0[loop]["coordinates"]
                                else:
                                    print("D 2 \n")
                                    routing = LrtRoute1[loop]["coordinates"]

                                while i < len(path[item]):
                                    qlat = path[item][i][2]
                                    qlon = path[item][i][3]
                                    while indexing < len(routing):
                                        clon, clat = routing[indexing]
                                        u = (qlat, qlon)
                                        v = (clat, clon)
                                        if geopy.distance.distance(
                                                u, v).km < 0.03:
                                            if prevService is None:
                                                lrtline.append(v)
                                            else:
                                                prevLatLong = lrtline[-1]
                                                tempIndex = 0
                                                while tempIndex < len(routing):
                                                    plon, plat = routing[
                                                        tempIndex]
                                                    p = (plat, plon)
                                                    if geopy.distance.distance(
                                                            prevLatLong,
                                                            p).km < 0.01:
                                                        for x, y in routing[
                                                                tempIndex:
                                                                indexing + 1]:
                                                            lrtline.append(
                                                                (y, x))
                                                        break
                                                    tempIndex += 1
                                            prevIndex = indexing
                                            prevService = path[item]
                                            lrtMarkers.append(
                                                (v, path[item][i][1],
                                                 path[item][i][-1],
                                                 path[item][i][-2]))
                                            break
                                        indexing += 1
                                    i += 1

                            nearestStartStop = path_to_Lrt[2]
                            nearestEndStop = path_to_Lrt[3]

                            start_Lrt = ox.get_nearest_node(
                                graph, nearestStartStop)
                            end_Lrt = ox.get_nearest_node(
                                graph, nearestEndStop)

                            pathToLrtStop = astar_path(graph, start_node,
                                                       start_Lrt)
                            pathFromLrtStop = astar_path(
                                graph, end_Lrt, end_node)

                            latlontolrt = []
                            latlonfromlrt = []

                            # walk from start to lrt start
                            startlrtcoord = (graph.nodes[start_Lrt]['y'],
                                             graph.nodes[start_Lrt]['x'])
                            prev = None
                            splice = None
                            ptr = 0
                            temp = float("Infinity")
                            for item in pathToLrtStop:
                                if prev is None:
                                    prev = item
                                else:
                                    try:
                                        line = graph[prev][item][0]["geometry"]
                                        for point in list(line.coords):
                                            if splice is None:
                                                splice = ptr
                                                temp = geopy.distance.distance(
                                                    startlrtcoord,
                                                    (point[1], point[0])).km
                                            elif geopy.distance.distance(
                                                    startlrtcoord,
                                                (point[1],
                                                 point[0])).km < temp:
                                                splice = ptr
                                                temp = geopy.distance.distance(
                                                    startlrtcoord,
                                                    (point[1], point[0])).km
                                            latlontolrt.append(
                                                (point[1], point[0]))
                                            ptr += 1
                                    except:
                                        pass
                                    finally:
                                        prev = item
                            if splice is not None:
                                latlontolrt = latlontolrt[:splice + 1]

                            # walk from lrt end to end
                            endlrtcoord = (graph.nodes[end_Lrt]['y'],
                                           graph.nodes[end_Lrt]['x'])
                            prev = None
                            splice = None
                            ptr = 0
                            temp = float("Infinity")
                            for item in pathFromLrtStop:
                                if prev is None:
                                    prev = item
                                else:
                                    try:
                                        line = graph[prev][item][0]["geometry"]
                                        for point in list(line.coords):
                                            if splice is None:
                                                splice = ptr
                                                temp = geopy.distance.distance(
                                                    endlrtcoord,
                                                    (point[1], point[0])).km
                                            elif geopy.distance.distance(
                                                    endlrtcoord,
                                                (point[1],
                                                 point[0])).km < temp:
                                                splice = ptr
                                                temp = geopy.distance.distance(
                                                    endlrtcoord,
                                                    (point[1], point[0])).km
                                            latlonfromlrt.append(
                                                (point[1], point[0]))
                                            ptr += 1
                                    except:
                                        pass
                                    finally:
                                        prev = item
                            if splice is not None:
                                latlonfromlrt = latlonfromlrt[:splice + 1]
                        else:
                            print("LRT route unable to be established")

                    # default route
                    nodepath = astar_path(graph, start_node, end_node)

                    if path_to_Lrt[1] == 0:
                        # INIT
                        m = ox.plot_route_folium(graph,
                                                 nodepath,
                                                 tiles='openstreetmap',
                                                 route_color='green',
                                                 route_opacity=0)

                        # LRT LINE
                        folium.PolyLine(lrtline,
                                        color="black",
                                        weight=2.5,
                                        opacity=1).add_to(m)

                        # Variables for Display
                        strStation = ''
                        stationCount = 0

                        # LRT Markers
                        for loc, station, loop, direction in lrtMarkers:
                            folium.Marker(
                                location=loc,
                                popup='<b>Station Name:</b> ' + str(station) +
                                '<br><b>Lat:</b> ' + str(loc[0]) +
                                '<br><b>Lon:</b> ' + str(loc[1]) +
                                '<br><b>Loop:</b> ' + str(loop) +
                                '<br><b>Direction: </b>' + str(direction),
                                icon=folium.Icon(color='black',
                                                 icon='train',
                                                 prefix='fa')).add_to(m)
                            strStation = strStation + str(station) + ','
                            stationCount = stationCount + 1
                        strStation = strStation + 'End'

                        # START AND END MARKERS
                        folium.Marker(location=(start[0], start[1]),
                                      popup='START',
                                      icon=folium.Icon(color='red',
                                                       icon='flag')).add_to(m)
                        folium.Marker(location=(end[0], end[1]),
                                      popup='END',
                                      icon=folium.Icon(color='blue',
                                                       icon='flag')).add_to(m)

                        if len(latlontolrt) > 0:
                            # start point to start lRT
                            folium.PolyLine([start, latlontolrt[0]],
                                            color="blue",
                                            weight=2.5,
                                            opacity=1,
                                            dasharray="4").add_to(m)
                            folium.PolyLine(latlontolrt,
                                            color="green",
                                            weight=2.5,
                                            opacity=1).add_to(m)
                            folium.PolyLine([latlontolrt[-1], lrtline[0]],
                                            color="blue",
                                            weight=2.5,
                                            opacity=1,
                                            dasharray="4").add_to(m)
                        if len(latlonfromlrt) > 0:
                            # End LRT stop to end point
                            folium.PolyLine([lrtline[-1], latlonfromlrt[0]],
                                            color="blue",
                                            weight=2.5,
                                            opacity=1,
                                            dasharray="4").add_to(m)
                            folium.PolyLine(latlonfromlrt,
                                            color="green",
                                            weight=2.5,
                                            opacity=1,
                                            dasharray="4").add_to(m)
                            folium.PolyLine([latlonfromlrt[-1], end],
                                            color="blue",
                                            weight=2.5,
                                            opacity=1,
                                            dasharray="4").add_to(m)

                        m.save(ROUTE_FOLDER + 'lrt_routing.html')

                        print("LRT_Routing.html created!")

                    # IF LRT ROUTE NOT FOUND, RUN WALK ROUTE
                    if path_to_Lrt[1] == 1:
                        # INIT
                        m = ox.plot_route_folium(graph,
                                                 nodepath,
                                                 tiles='openstreetmap',
                                                 route_color='green')
                        folium.Marker(location=(start[0], start[1]),
                                      popup='START',
                                      icon=folium.Icon(color='red',
                                                       icon='flag')).add_to(m)
                        folium.Marker(location=(end[0], end[1]),
                                      popup='END',
                                      icon=folium.Icon(color='blue',
                                                       icon='flag')).add_to(m)
                        m.save(ROUTE_FOLDER + 'lrt_routing.html')
                        print("LRT_Routing.html created!")

                    strStation = strStation.split(',')
                    timeTrain = 2 * stationCount
                    if getDistanceLRT() <= 3.2:
                        costLRT = 0.92
                    elif getDistanceLRT() <= 4.2:
                        costLRT = 1.02
                    elif getDistanceLRT() <= 5.2:
                        costLRT = 1.12
                    elif getDistanceLRT() <= 6.2:
                        costLRT = 1.22
                    elif getDistanceLRT() <= 7.2:
                        costLRT = 1.31
                    elif getDistanceLRT() <= 8.2:
                        costLRT = 1.38
                    elif getDistanceLRT() <= 9.2:
                        costLRT = 1.44
                    else:
                        costLRT = 2

                    contentDict = {
                        "org_addr": org_addr.address,
                        "dst_addr": dst_addr.address,
                        "mode_var": type_var,
                        "count": stationCount,
                        "route": strStation,
                        "time": timeTrain,
                        "cost": costLRT
                    }
                    return render(request, "lrt.html", contentDict)

                else:
                    if type_var == 'Walk':
                        if org:
                            graph = ox.graph_from_point(org,
                                                        distance=2000,
                                                        network_type='walk')
                        else:
                            (graph,
                             org) = ox.graph_from_address(address,
                                                          distance=5000,
                                                          network_type='walk',
                                                          return_coords=True)
                    elif type_var == 'Drive':
                        if org:
                            graph = ox.graph_from_point(org,
                                                        distance=2000,
                                                        network_type='drive')
                        else:
                            graph = ox.graph_from_address(address,
                                                          distance=5000,
                                                          network_type='drive')

                    # get cloest node to the point of search
                    global target_node
                    orig_node = ox.get_nearest_node(graph, org)
                    target_node = ox.get_nearest_node(graph, dest)

                    nodes, edges = ox.graph_to_gdfs(graph)

                    node_data = get_nodes(edges)
                    ourRoute3 = list(
                        creator3(nodes, node_data, orig_node, target_node))

                    # usage of folium to create interactive web map
                    astar_map = ox.plot_route_folium(graph,
                                                     ourRoute3,
                                                     popup_attribute='name',
                                                     tiles='openstreetmap',
                                                     route_color='blue')
                    folium.Marker(
                        location=org,
                        popup=org_addr.address,
                        icon=folium.Icon(color='red')).add_to(astar_map)
                    folium.Marker(
                        location=dest,
                        popup=dst_addr.address,
                        icon=folium.Icon(color='blue')).add_to(astar_map)
                    filepath3 = ROUTE_FOLDER + 'astar_route.html'
                    astar_map.save(filepath3)

                    distanceAstar = round(
                        getDistanceTravelled(nodes, node_data, ourRoute3), 3)
                    if type_var == 'Walk':
                        estSpeed = 5
                    else:
                        estSpeed = 50
                    timeAstar = math.ceil((distanceAstar / estSpeed) * 60)

                    contentDict = {
                        "org_addr": org_addr.address,
                        "dst_addr": dst_addr.address,
                        "dist_astar": distanceAstar,
                        "mode_var": type_var,
                        "time": timeAstar,
                        "estSpeed": estSpeed
                    }
                    return render(request, "main.html", contentDict)

        else:
            inputForm = AddressForm()
            return render(request, "index.html", {'form': inputForm})
    except:
        inputForm = AddressForm()
        return render(request, "error.html", {'form': inputForm})
예제 #21
0
punggol = (1.403948, 103.909048)
#G = ox.graph_from_point(punggol, distance=1200, truncate_by_edge=True, network_type="walk")

# =========================================================
# PLACE IN INIT
# =========================================================

take_bus_distance = 150  # in meters. this value is for lrt+bus+walk
# if destination falls within this distance, user wont take a bus

punggol = (1.4053828, 103.9022239)  # punggol MRT station, change according to whatever coordinates you are using
G = ox.graph_from_point(punggol, distance=1200, truncate_by_edge=True, network_type="walk",infrastructure='way["highway"]')

G = ox.remove_isolated_nodes(G)

lrt_east = ox.graph_from_file(filename="data\lrt_pg_east.osm",
                              retain_all="true")  # retain all is essential
lrt_west = ox.graph_from_file(filename="data\lrt_pg_west.osm",
                              retain_all="true")

lrt_exits = ox.graph_from_file(filename="data\lrt_bridges.osm",
                              retain_all="true")

lrt_stations = nx.compose(lrt_east, lrt_west)

# =========================================================
# END OF "PLACE IN INIT" requirements
# =========================================================

@app.route("/")
@app.route("/home", methods=['GET', 'POST'])
def home():
예제 #22
0
def buildOSMnx(file):
    G = ox.graph_from_file(file, simplify=False)
    return G
예제 #23
0
import osmnx as ox
import networkx as nx
import folium

import os
path = os.path.dirname(os.path.abspath(__file__)) + "\\"
path = path[:-5]

G = ox.graph_from_file(path + "maps\\bremm.osm")
K = ox.graph_from_place('Amersfoort,NL', network_type='drive')
Z = ox.graph_from_place('NL', network_type='drive')
H = ox.graph_from_place('Bremm,GER', network_type='drive')

# origin = ox.geo_utils.geocode('KROAST,Amersfoort, NL')
# destination = ox.geo_utils.geocode('krakelingtunnel,Almere, NL')
# orig = ox.get_nearest_node(Z, origin)
# dest = ox.get_nearest_node(Z, destination)
# route = nx.shortest_path(Z,orig, dest)
# ox.plot_graph_route(Z, route)
#ox.plot_graph(G)\
#ox.plot_graph(ox.project_graph(H));

print("test")

place = {'city': 'Amersfoort', 'state': 'Utrecht', 'country': 'NL'}
kaas = ox.graph_from_place(place, network_type='drive')
fig, ax = ox.plot_graph(kaas, fig_height=12, node_size=0, edge_linewidth=0.5)
예제 #24
0
def generateGraphML(osmFile,filePathML):
    multiGraph = ox.graph_from_file(osmFile,True,True,True)
    ox.save_graphml(multiGraph, filePathML)
예제 #25
0
def get_graph_from_osm(filename):
    ox.config(use_cache=True, log_console=False)
    G_nx = ox.graph_from_file(filename)
    G_nx = nx.relabel.convert_node_labels_to_integers(G_nx)

    return G_nx
예제 #26
0
#!/usr/bin/env python
# coding: utf-8

# Import required libraries

# In[59]:

import osmnx as ox
import networkx as nx
import queue
import math
import priority_dict

# Import OSM map of VNIT and apply A* for mission planning
map_graph = ox.graph_from_file(
    '/home/aniket/autonomous-delivery-robot/Planning/Vnit_map/CollegeMap.osm',
    simplify=True)
origin = ox.get_nearest_node(map_graph, (21.122, 79.045))
destination = list(map_graph.nodes())[15]

#fig, ax = ox.plot_graph(map_graph)


# This function follows the predecessor
# backpointers and generates the equivalent path from the
# origin as a list of vertex keys.
def get_path(origin_key, goal_key, predecessors):
    key = goal_key
    path = [goal_key]

    while (key != origin_key):
예제 #27
0
def osm_to_graphml(osm_file, graphml_file):
    G = ox.graph_from_file(place,network_type="drive")
    ox.save_load.save_graphml(G, graphml_file)
예제 #28
0
파일: osm.py 프로젝트: nst-guide/data
 def load_geofabrik(self, polygon):
     path = self._filter_geofabrik(polygon)
     return ox.graph_from_file(path, retain_all=True, simplify=False)
        local_volume_data = False

    if options.gen_costs:
        gen_cost_arg_dict = {'on': True, 'off': False}
        gen_costs_on = gen_cost_arg_dict[options.gen_costs]

    assert ox.settings.all_oneway

    # 1. LOAD OSM DATA
    logger.info('Loading OSM data...')

    # load from disk
    if osm_mode == 'local':
        osm_path = os.path.join(data_dir, osm_fname)
        try:
            G = ox.graph_from_file(osm_path, simplify=False, retain_all=True)
        except OSError:
            raise OSError("Couldn't find file {0}. Make sure it is in "
                          "the data directory ({1}).".format(
                              osm_fname, data_dir))

    # or pull it from the web "on-the-fly"
    elif osm_mode == 'otf':
        G = ox.graph_from_place(place,
                                network_type='all',
                                simplify=False,
                                retain_all=True)

    else:
        raise ValueError('Must specify a valid OSM mode. See --help '
                         'for more details.')
예제 #30
0
import datetime

import networkx as nx
import osmnx as ox
import utm
from shapely.geometry import box

start_time = datetime.datetime.now()
graph = ox.graph_from_file("map.osm", network_type="drive")
# graph = ox.graph_from_place("Kamppi, Helsinki, Finland", network_type="drive")
end_time = datetime.datetime.now()
print("Load graph: " + str((end_time - start_time).seconds) + "s")

edges = ox.graph_to_gdfs(graph, nodes=False, edges=True)

start_time = datetime.datetime.now()
graph_proj = ox.project_graph(graph)
end_time = datetime.datetime.now()
print("Project graph:" + str((end_time - start_time).seconds) + "s")
# fig, ax = ox.plot_graph(graph_proj)
# plt.tight_layout()

nodes_proj, edges_proj = ox.graph_to_gdfs(graph_proj, nodes=True, edges=True)
print("Coordinate system:", edges_proj.crs)

bbox = box(*edges_proj.unary_union.bounds)
print(bbox)

orig_point = bbox.centroid
print(orig_point)
orig_point_utm = utm.from_latlon(longitude=121.43741, latitude=31.239888)