Networkx:获取节点之间的距离

Networkx: Get the distance between nodes

我是使用 NetworkX 的初学者,我正在尝试找到一种方法来检测哪些节点彼此之间的距离为 x。 我已经开始使用这个算法来获取所有对

path=nx.all_pairs_dijkstra_path(G)

但我仍然不确定如何使用 for 循环检测节点之间的距离。

如有任何帮助,我将不胜感激。谢谢

NetworkX 具有自动计算加权和未加权图的最短路径(或仅路径长度)的方法。确保针对您的用例使用正确的方法。

networkx.all_pairs_shortest_path - 计算未加权图中所有节点之间的最短路径

networkx.all_pairs_shortest_path_length - 计算未加权图中所有节点之间的最短路径长度

networkx.all_pairs_dijkstra_path - 计算加权图中所有节点之间的最短路径

networkx.all_pairs_dijkstra_path_length - 计算 weighted graph

中所有节点之间的最短路径的长度

当在图上执行时,这些方法中的每一个都将计算节点的字典矩阵(“字典的字典”),这些节点具有相应的最短路径或最短路径的长度作为值。我将用一个例子来证明这一点:

>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_nodes_from(["A", "B", "C", "D", "E"])
>>> G.add_edges_from([("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")])
>>> sp = dict(nx.all_pairs_shortest_path(G))
>>> sp["A"]["E"]
['A', 'B', 'C', 'D', 'E']
>>> spl = dict(nx.all_pairs_shortest_path_length(G))
>>> spl["A"]["E"]
4

如您所见,我生成了一个包含五个节点的图,并使用边将每个节点链接到下一个节点。我在 sp 中存储了一个最短路径矩阵,在 spl 中存储了一个最短路径长度矩阵。当我需要知道两个节点之间的最短路径时,例如节点 "A" 和节点 "E",我只是访问 sp 就像一个矩阵,或者字典的字典:sp["A"]["E"]。然后它将 return 两个节点之间的整个最短路径。最短路径长度的方法以类似的方式工作,但它只会 return 任何两个给定节点之间的边数。

下一个代码片段可能会让我更清楚地了解字典矩阵的含义。如果我为节点 "A" 请求 sp 中的所有条目,它 return 是另一个字典,其中包含每个其他节点的条目:

>>> sp["A"]
{'B': ['A', 'B'], 'A': ['A'], 'E': ['A', 'B', 'C', 'D', 'E'], 'C': ['A', 'B', 'C
'], 'D': ['A', 'B', 'C', 'D']}

如果您想使用 for 循环检查所有节点之间的距离,您可以只遍历矩阵的第一个字典的键,然后遍历该字典内的字典。这比听起来容易:

>>> for node1 in spl:
...   for node2 in spl[node1]:
...     print("Length between", node1, "and", node2, "is", spl[node1][node2])
...
Length between B and B is 0
Length between B and A is 1
Length between B and E is 3
Length between B and C is 1
Length between B and D is 2
Length between A and B is 1
... (and so on!)

这是找到节点之间距离的一种解决方案:

G = nx.Graph()
G.add_edges_from([(1,2), (1,3), (2,3), (2,4), (3,4)])
path = nx.all_pairs_shortest_path_length(G) # This is a generator
dpath = {x[0]:x[1] for x in path}           # Create a dictionary from it 
# To find e.g. the distance between node 1 and node 4: 
print(dpath[1][4]) # = 2

我一直在使用它来计算最长的路径 - 对于有向图来说非常困难,但对于树状图来说却很容易。 虽然您不是特别要求这样做,但它可能会对其他人有所帮助。 仅供参考,使用 all_pairs_shortest_path_length 对于大型网络来说非常昂贵。

        # Find the longest path for a tree
        # Choose a random start. (or first).
        rnd_node = choice(nodes)
        # Find distances from random node by calculating all distances
        r_dists = dict(nx.single_source_shortest_path_length(g, rnd_node))
        begins = [node for node, dist in r_dists.items() if dist == max(r_dists.values())]
        # being the longest from a random start, makes it suitable as a start to the longest path.
        begin = choice(begins)
        # Find distances from begin by calculating all distances.
        # If we want to know the actual journey, use 'single_source_shortest_path()' instead.
        s_dists = dict(nx.single_source_shortest_path_length(g, begin))
        stops = [node for node, dist in s_dists.items() if dist == max(s_dists.values())]
        dist, stop = choice(stops)

取决于您可以使用的图表的大小

distances = nx.floyd_warshall_numpy(graph)
nodes = np.where(distances==4)

获取距离矩阵。从中你可以过滤你的距离。行和列是 list(g)

中的节点