2017-09-18 36 views
0

我試圖從圖中提取匹配節點以及它們的方向。下面的代碼給出:圖形節點在複製時反轉

for n1,n2,attr in G_new.edges(data=True): 
      if G_source.has_edge(n1,n2) : 
       #Get the specific weight between the two nodes 
       w = G_source[n1][n2]['weight'] 
       matching_graph.add_edge(n1,n2,weight=w) 
       matching_graph.node[n1]['order'] = G_new.node[n1]['order'] 
       matching_graph.node[n2]['order'] = G_new.node[n2]['order'] 
       print('Matching:', n1,'->',n2,'order:',matching_graph.node[n1]['order'],'->',matching_graph.node[n2]['order'],'weight:',w) 

     graphs = list(nx.connected_component_subgraphs(matching_graph)) 

     mcs_length = 0 
     mcs_graph = nx.Graph() 
     for i, graph in enumerate(graphs): 
      print('i:',i) 
      if len(graph.nodes()) > mcs_length: 
       mcs_length = len(graph.nodes()) 
       mcs_graph = graph.copy() 

     total_weight=0 
     for n1,n2,attr in mcs_graph.edges(data=True): 
      w = mcs_graph[n1][n2]['weight'] 
      total_weight=total_weight+w 
      print(n1,'->',n2,'order:',mcs_graph.node[n1]['order'],'->',mcs_graph.node[n2]['order'],'weight:',w,'total weight:', total_weight) 
     print("***printing MCS***") 
     self.printGraphTable(mcs_graph) 

這句話我傳遞的是:

fan would have a hard time sit through this one . 

當我在第一張圖做一個打印我收到這是正確如下:

Matching: hard -> time order: 4 -> 5 weight: 1 
Matching: have -> a order: 2 -> 3 weight: 1 
Matching: would -> have order: 1 -> 2 weight: 1 
Matching: a -> hard order: 3 -> 4 weight: 1 

但是,當我查看從複製的節點和邊緣創建的圖形時,我得到:

hard -> time order: 4 -> 5 weight: 1 total weight: 1 
hard -> a order: 4 -> 3 weight: 1 total weight: 2 
a -> have order: 3 -> 2 weight: 1 total weight: 3 
have -> would order: 2 -> 1 weight: 1 total weight: 4 

這裏我們看到最後三個節點的方向已經顛倒過來了。我明白爲什麼會發生這種情況。請幫助

回答

0

我正在創建一個Graph對象而不是DiGraph對象,所以這個問題。

return_mcs_graph = nx.DiGraph() 
for i, graph in enumerate(graphs): 
    if len(graph.nodes()) > mcs_length: 
     mcs_length = len(graph.nodes()) 
     mcs_graph = graph.copy() 

total_weight=0 
for n1,n2,attr in mcs_graph.edges(data=True): 
    w = mcs_graph[n1][n2]['weight'] 

    if G_new.has_edge(n1,n2): 
     return_mcs_graph.add_edge(n1,n2,weight=w) 
    elif G_new.has_edge(n2,n1): 
     return_mcs_graph.add_edge(n2,n1,weight=w) 
    return_mcs_graph.node[n1]['order'] = G_new.node[n1]['order'] 
    return_mcs_graph.node[n2]['order'] = G_new.node[n2]['order'] 
    total_weight=total_weight+w 
print("***printing return_mcs_graph***") 
self.printGraphTable(return_mcs_graph) 
print(total_weight)