如何计算多个有向图中几个节点未连接的平均最短路径长度?

时间:2017-03-07 02:30:47

标签: python networkx

我想在我的多方向图中计算average_shortest_path_length但是有一个节点没有与其他节点连接

例如我有一个节点和边缘的网络如下:

lst_nodes=[2782, 27118, 28931, 28936, 43162, 28770, 48325, 33783]

lst_edge = [(28931, 28936L), (28931, 27118L), (28931, 27118L), (28931, 33783L), (48325, 28936L), (28936, 43162L),
            (28936, 48325L), (27118, 28936L), (27118, 28936L), (27118, 48325L), (43162, 48325L), (2782, 28931L),
            (2782, 48325L), (2782, 48325L), (2782, 27118L), (2782, 33783L)]

MDG = nx.MultiDiGraph()
MDG.add_nodes_from(lst_nodes)
MDG.add_edges_from(lst_edge)

print 'avg shortest path length:', nx.average_shortest_path_length(MDG)

figure_1-1.png

最终会出现像

这样的例外情况

networkx.exception.NetworkXError: Graph is not connected.

但根据NetworkX

中的说明
  

对于断开连接的图表,您可以计算每个组件的平均最短路径长度:>>> G = nx.Graph([(1,2),(3,4)])>>>对于nx.connected_component_subgraphs(G)中的g:... print(nx.average_shortest_path_length(g))1.0 1.0

它应该与组件一起使用,所以我在

之前尝试代码
for g in nx.connected_component_subgraphs(MDG):
    print nx.average_shortest_path_length(g)

但最终会出现例外情况 networkx.exception.NetworkXNotImplemented: not implemented for directed type 但是,如果我从网络中删除单个节点,我可以计算网络的平均最短路径长度,所以我想知道如何计算多个有向图中几个节点未连接的平均最短路径长度?

1 个答案:

答案 0 :(得分:0)

事实上,我认为nx.shortest_path_length是最合理的解决方案:

import statistics
from itertools import chain
# This includes the isolated node!
path_lengths = (x.values() for x in nx.shortest_path_length(MDG).values())
statistics.mean(chain.from_iterable(path_lengths))
# 1