2017-09-18 1 views
0

J'essaie d'extraire les nœuds correspondants avec leur direction à partir du graphique. Le code est donné ci-dessous:Les nœuds du graphique sont inversés lors de la copie

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) 

La phrase que je passe est:

fan would have a hard time sit through this one . 

Quand je fais une impression dans le premier graphique que je reçois ce qui suit qui est correct:

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 

Cependant, lorsque je regarde le graphique créé à partir des nœuds copiés et des bords que je reçois:

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 

Ici, nous voyons que la direction des trois derniers nœuds a été inversée. Je comprends pourquoi cela arrive. Veuillez aider

Répondre

0

Je créais un objet graphique plutôt qu'un objet DiGraph et donc le problème.

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)