图形节点在复制时反转

时间:2017-09-18 00:57:01

标签: python-3.x graph networkx

我正在尝试从图中提取匹配的节点及其方向。代码如下:

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

在这里,我们看到最后三个节点的方向已经反转。我理解为什么会这样。请帮助

1 个答案:

答案 0 :(得分: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)