Lonewolf
Lonewolf

Reputation: 527

Networkx: Interconnect nodes between two graphs

I have graph A. For every node in Graph A, I use some rules to convert the name of the node and decide to add it to Graph B.

So now I have B derived from A. I was wondering if it is possible to create some sort of link between the original node in A and the transformed node in B.

I couldn't figure out a method to do it using networkx library. Any pointers would be helpful...

Upvotes: 0

Views: 197

Answers (1)

Julian Neuer
Julian Neuer

Reputation: 316

Nodes can have attributes. In each node in graph A, you can create an attribute to hold the corresponding node in graph B.

In the code below, graph A has 3 nodes: 1, 2, and 3. Graph B is created with nodes 1, 4, and 9 (the squares of the values of the nodes in A). As each node in B is created, its value is stored in the b_node attribute of the A-node that originated it.

import networkx as nx

def main():
    # Create graph A
    a = nx.Graph()
    a.add_node(1)
    a.add_node(2)
    a.add_node(3)

    # Create graph B with nodes that are squares of the nodes in A
    # Add to each node in A an attribute (b_node) 
    # to hold the corresponding node in B
    b = nx.Graph()
    for node in a:
        a.add_node(node, b_node=node * node)
        b.add_node(node * node)

    print("A:")
    print(a.nodes.data())
    print("\nB:")
    print(b.nodes.data())

if __name__ == '__main__':
    main()

Output:

A:
[(1, {'b_node': 1}), (2, {'b_node': 4}), (3, {'b_node': 9})]

B:
[(1, {}), (4, {}), (9, {})]

Upvotes: 1

Related Questions