【问题标题】:Networkx: Get the distance between nodesNetworkx:获取节点之间的距离
【发布时间】:2016-10-17 13:42:42
【问题描述】:

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

path=nx.all_pairs_dijkstra_path(G)

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

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

【问题讨论】:

  • 你说的具体距离是多少?两个节点之间的最小边数?
  • 例如,我有一个直路径图,由 5 个节点 [A,B,C,D,E] 与边 (A,B) (B,C) (C,D) (D ,E) 我想知道 A 节点和 D 节点之间的距离。当然我会在一个更大的程序中使用它,但我想知道我应该使用的方法。谢谢

标签: python graph-theory networkx


【解决方案1】:

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

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

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

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

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

这些方法中的每一个,当在图上执行时,将计算节点的字典矩阵(“字典的字典”),其值可以是各自的最短路径或最短路径的长度。我会用一个例子来证明这一点:

>>> 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",我只是像矩阵或字典一样访问spsp["A"]["E"]。然后它将返回两个节点之间的整个最短路径。最短路径长度的方法以类似的方式工作,但它只会返回任意两个给定节点之间的边数。

下一个代码 sn-p 可能会让我对字典矩阵的意思更清楚。如果我为节点 "A" 请求 sp 中的所有条目,它会返回另一个字典,其中包含每个其他节点的条目:

>>> 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!)

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      【解决方案3】:

      我一直在用它来计算最长的路径 - 众所周知,有向图很难,但对于树状图来说就足够简单了。 虽然您没有特别要求这样做,但它可能会对其他人有所帮助。 仅供参考,使用 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)
      

      【讨论】:

        【解决方案4】:

        根据您可以使用的图表的大小

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

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

        【讨论】:

          猜你喜欢
          • 2020-05-29
          • 1970-01-01
          • 2020-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多