0

I am trying to calculate the distance between a node and two targets, afterwards I compare the lengths of the routes calculated and save the smallest in a list. I know I can use networkx.shortest_path() however this solution takes a long time and the code takes too long to run. For this reason I opted to use Igraph. Here is the code:

import networkx as nx
import matplotlib.pyplot as plt
import osmnx as ox
import pandas as pd
from shapely.wkt import loads as load_wkt
import numpy as np
import matplotlib.cm as cm
import igraph as ig
import matplotlib as mpl
import random as rd
ox.config(log_console=True, use_cache=True)


city = 'Portugal, Lisbon'
G = ox.graph_from_place(city, network_type='drive')

G_nx = nx.relabel.convert_node_labels_to_integers(G)

ox.speed.add_edge_speeds(G_nx, hwy_speeds=20, fallback=20)

ox.speed.add_edge_travel_times(G_nx)

weight = 'travel_time'

coord_1 = (38.74817825481225, -9.160815118526642)  # Coordenada Hospital Santa Maria
coord_2 = (38.74110711410615, -9.152159572392323)  # Coordenada Hopstial Curry Cabral
coord_3 = (38.7287248180068, -9.139114834357233) # Hospital Dona Estefania
coord_4 = (38.71814053423293, -9.137885476529883) # Hospital Sao Jose 
target_1 = ox.get_nearest_node(G_nx, coord_1)
target_2 = ox.get_nearest_node(G_nx, coord_2)
target_3 = ox.get_nearest_node(G_nx, coord_3)
target_4 = ox.get_nearest_node(G_nx, coord_4)


G_ig = ig.Graph(directed=True)
G_ig.add_vertices(list(G_nx.nodes()))
G_ig.add_edges(list(G_nx.edges()))
G_ig.vs['osmid'] = list(nx.get_node_attributes(G_nx, 'osmid').values())
G_ig.es[weight] = list(nx.get_edge_attributes(G_nx, weight).values())

assert len(G_nx.nodes()) == G_ig.vcount()
assert len(G_nx.edges()) == G_ig.ecount()

route_length=[]
list_nodes=[]

for node in G_nx.nodes:
    length_1 = G_ig.shortest_paths(source=node, target=target_1, weights=weight)[0][0]
    length_2 = G_ig.shortest_paths(source=node, target=target_2, weights=weight)[0][0]

    if length_1<length_2:
        route_length.append(length_1)
    else:
        route_length.append(length_2)
    list_nodes.append(node)

If you print the list with the lengths of the routes some values will be 'inf' which obviously doesn't make sense. Can anyone help me understand why the length would be inf?

DPM
  • 845
  • 7
  • 33
  • 2
    The distance between two nodes that are disconnected is `Inf`. Perhaps you want to double check that your network is actually connected? Notice that you are creating a directed network by the way, perhaps an undirected network would make more sense in this context? – Vincent Traag Jun 02 '20 at 05:25

1 Answers1

0

As Vincent Traag said the distance between two disconnected nodes in inf. So it means that for such results, the node and the source are not connected

DPM
  • 845
  • 7
  • 33