Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add node to network x only if a node with same attribute doesn`t exist

I am very new to networkx and graphing in general and wanted your help.

I am designing a graph where each node has a node_id (which is just the number of points i am iterating through to make my graph) and five attributes.

I.e.

G.add_node(node_id)
G[id]['Coord1'] = 3
G[id]['Coord2'] = 7
G[id]['Coord3'] = None
G[id]['Coord4'] = None
G[id]['Coord5'] = None

So now i want to consider adding a new node, with some coordinates.

Now before adding a new node to my graph i want to check that there isn't already a node which has an attribute (one of the coords) which is the same as the node i am intending to add.

If there already exists a node which has a coord which is shared, then i will not add a new node but simply make some changes to the existing node.

The only way i could think of doing this was to loop through all existing nodes in the graph and checking if one of the attributes is the same as the node i am contemplating adding. E.g.

find_node = [attrdict for n,attrdict in G.node.items() if attrdict['coord1'] == tempcoord ]    

Where tempcoord is the coordinate of interest on the node i am intending adding.

This is clearly very inefficient to do this everytime i want to add node to have check all existing nodes, my question is: Is there a better way?

I understand that networkx will not add a new node which has the same id, but that doesnt extend to nodes which share the same attribute correct?

Alternatively, is it better to build the graph with all these "duplicate" nodes and then condense all nodes which have some shared attributes down into one node after i have added all nodes?

Sorry for the somewhat convoluted explaination, i hope that it makes some sense.

like image 659
AHawks Avatar asked Oct 23 '25 08:10

AHawks


1 Answers

Create a set which contains all of the observed node attributes. When you want to add a node with a given attribute, check if that attribute is there. If so, do nothing but if not, add it and put the attribute in the set. May be worth defining a function to do these steps if it's done in different parts of the code.

seen_attributes = set()

# code here adding nodes

node = node_to_add
attribute = attribute_of_node

if attribute not in seen_attributes:
    G.add_node(node, coord=attribute)
    seen_attributes.add(attribute)
like image 88
Joel Avatar answered Oct 25 '25 22:10

Joel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!