[英]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.