给定图形中的传递闭包(未知尺寸)

时间:2015-11-12 18:39:53

标签: python networkx

我有一个有向图

a,b,.....,z,a',b'.... c'' 

但我不知道里面有多少元素。它可以用不同的词来表达。 它们可以例如以a-b,b-c,c-d,....的方式连接。

我想在此图中添加传递闭包,它将在a-c,a-d等之间创建连接。

我的算法应该改变什么才能达到任何给定图形的传递闭包。现在它只适用于包含3个节点的图形。 我的代码如下。

for x in G:
# Extract all neighbours of neighbours of x (from G)
all_nh = []
for y in G.neighbours(x):
    all_nh += G.neighbours(y)

    # Remove from the list of neighbors the current node and its immediate neighbors
    all_nh = set(all_nh) - set([x]) - set(G.neighbours(x))

    # Create new edges (x -> z)
    edges = map(lambda z: (x, z), all_nh)

# Add them to the new graph
TC.add_edges_from(edges)

好的,我试图实现下面提供的伪代码。但是我仍然需要帮助,因为编译器会返回很多错误。对于前者TypeError:“NoneType”类型的对象没有len()

class FlowGraph:
    def __init__(self):
      self.G=nx.DiGraph()
      self.I=[]
      self.O=[]

F2=FlowGraph()
#F2.G=nx.Graph()
F2.G.add_node(1)
F2.G.add_node(2)
F2.G.add_node(3)
F2.G.add_node(4)
F2.G.add_edge(1,2)
F2.G.add_edge(2,3)
F2.G.add_edge(3,4)

def transitive_closure(G):
  TC = G.copy()
  n_nodes = len(G)
  #print(n_nodes)
  for i in range(n_nodes):
    for j in range(n_nodes):
        for k in range(n_nodes):
            if TC.has_edge(i,k) and TC.has_edge(k,j):
                TC.add_edge(i,j)

Z = transitive_closure(F2.G)
nx.draw(Z, with_labels = True) 
plt.show()

1 个答案:

答案 0 :(得分:0)

计算传递闭包的最简单方法是使用Floyd-Warshall。设TC为传递闭包图,G为原始

TC = G # copy all edges from G to TC
for i in range(n_nodes):
    for j in range(n_nodes):
        for k in range(n_nodes):
            if TC.has_edge(i,k) and TC.has_edge(k,j):
                TC.add_edge(i,j)
相关问题