[英]Distance between two vertices in igraph
我有一個大(半百萬條邊)加權圖(非定向),我想找到兩個節點 u 和 v 之間的距離。我可以使用my_graph.shortest_paths(u, v, weights='length')
來獲得距離。 但是,這真的很慢。
我也可以先找到路徑,然后計算它的長度。 這很快,但我不明白為什么這比直接計算長度要快。
在 networkx 我使用nx.shortest_path_length(my_graph u, v, weight='length')
我用這段代碼來計算速度。 對於任何想要運行代碼的人,我將edgelist放在 Google 驅動器上
import pandas as pd
import networkx as nx
import igraph
import time
# load edgelist
edgelist = pd.read_pickle('edgelist.pkl')
# create igraph
tuples = [tuple(x) for x in edgelist[['u', 'v', 'length']].values]
graph_igraph = igraph.Graph.TupleList(tuples, directed=False, edge_attrs=['length'])
# create nx graph
graph_nx = nx.from_pandas_edgelist(edgelist, source='u', target='v', edge_attr=True)
def distance_shortest_path(u, v):
return graph_igraph.shortest_paths(u, v, weights='length')[0]
get_length = lambda edge: graph_igraph.es[edge]['length']
def distance_path_then_sum(u, v):
path = graph_igraph.get_shortest_paths(u, v, weights='length', output='epath')[0]
return sum(map(get_length, path))
def distance_nx(u, v):
return nx.shortest_path_length(graph_nx, u, v, weight='length')
some_nodes = [
'Delitzsch unt Bf',
'Neustadt(Holst)Gbf',
'Delitzsch ob Bf',
'Karlshagen',
'Berlin-Karlshorst (S)',
'Köln/Bonn Flughafen',
'Mannheim Hbf',
'Neu-Edingen/Friedrichsfeld',
'Ladenburg',
'Heddesheim/Hirschberg',
'Weinheim-Lützelsachsen',
'Wünsdorf-Waldstadt',
'Zossen',
'Dabendorf',
'Rangsdorf',
'Dahlewitz',
'Blankenfelde(Teltow-Fläming)',
'Berlin-Schönefeld Flughafen',
'Berlin Ostkreuz',
]
print('distance_shortest_path ', end='')
start = time.time()
for node in some_nodes:
distance_shortest_path('Köln Hbf', node)
print('took', time.time() - start)
print('distance_nx ', end='')
start = time.time()
for node in some_nodes:
distance_nx('Köln Hbf', node)
print('took', time.time() - start)
print('distance_path_then_sum ', end='')
start = time.time()
for node in some_nodes:
distance_path_then_sum('Köln Hbf', node)
print('took', time.time() - start)
這導致
distance_shortest_path took 46.34037733078003
distance_nx took 12.006148099899292
distance_path_then_sum took 0.9555535316467285
您可以在igraph
中使用shortest_paths
function 。 使用非常簡單,假設G
是您的圖,具有G.es['weight']
邊權重,然后
D = G.shortest_paths(weights='weight'))
會給你一個igraph
矩陣D
。 您可以將其轉換為numpy
數組
D = np.array(list(D))
要僅獲取特定一對(組)節點之間的距離,您可以指定 shortest_paths 的source
和target
shortest_paths
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.