user6053895
user6053895

Reputation:

Mapping two graphs in Networkx

I am trying hard these days to map two different graphs depending on the node they have in common. Here is what the two graphs look like. The colors of the node indicate that the blue one is priority1 and the yellow one is priority2.

Nodes who share the same node, I want to combine them. Here is what I want to achieve. In this case, 10 and 190 are a common node for 31, 130, 204, and 240 respectively.

Here is the code that I tried.

for node1, node2 in Graph2.edges():
    if Graph1.has_edge(node1, node2):
        for attr in Graph2.adj[node1][node2]:
            if (Graph1.node[node1]['priority']==1):

                name = str(node1) + '/' + str(node2)            
                mapping = {n1: name, node2: name}
                Graph2 =nx.relabel_nodes(Graph2, mapping)

    pos1 = nx.shell_layout(Graph2) 

    nodes = nx.draw_networkx_nodes(Graph2, pos1, node_size=2000, node_color = 'b' , alpha=0.3, with_labels = True) 
    nx.draw_networkx_edges(Graph2, pos1, width=1.5, alpha=0.3, edge_color='k')
    nx.draw_networkx_labels(Graph2, pos1, font_size=15, font_family='sans-serif')  

Can anyone help me to achieve this, please?

Many thanks!!

Upvotes: 1

Views: 887

Answers (1)

user6053895
user6053895

Reputation:

For those who are looking for similar solution, I tried to solve the above problem for priority 1 which means for the nodes with the blue color. The same to do for the rest of the priorities. Here priority and name are my graph attributes.

    try:
        for n1, n2, attr in list(graph1.edges(data ='True')):
            for x1, x2, attr1 in list(graph2.edges(data ='True')):
                if ((graph1.node[n1]['priority'] ==1) & (graph1.node[n1]['name'] =='Start')):
                    if ((graph2.node[x1]['priority'] ==1) & (graph2.node[x1]['name'] =='Start')):

                        name1 = str(n1) + '/' + str(x1)
                        mapping1 = {n1: name1, x1:name1}
                        graph1 =nx.relabel_nodes(graph1, mapping1)
                        graph2 =nx.relabel_nodes(graph2, mapping1)


    except KeyError:
        print('')   

    try:
        for n1, n2, attr in list(graph1.edges(data ='True')):
            for x1, x2, attr1 in list(graph2.edges(data ='True')):
                if ((graph1.node[n2]['priority'] ==1) & (graph1.node[n2]['name'] =='End')):
                    if ((graph2.node[x2]['priority'] ==1) & (graph2.node[x2]['name'] =='End')):

                        name1 = str(n2) + '/' + str(x2)
                        mapping1 = {n2: name1, x2:name1}
                        graph1 =nx.relabel_nodes(graph1, mapping1)
                        graph2 =nx.relabel_nodes(graph2, mapping1)


    except KeyError: 
        print('')  

Upvotes: 1

Related Questions