2017-09-18 8 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 

ここで、最後の3つのノードの方向が逆転していることがわかります。なぜこれが起こっているのか理解しています。助けてください

答えて

0

私はDiGraphオブジェクトではなくGraphオブジェクトを作成していました。

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) 
関連する問題