4

I have a numpy array full of values that I would like to create vertices from for every point in the array. I am using networkx as my graphing support method(documentation here: http://networkx.github.io/documentation/latest/tutorial/ )

I would like to treat each element within the array as a pixel location and create a vertex instance at each location. This is easy using a simple for loop:

new=np.arange(16)
gnew=nx.Graph()
for x in new:
    if new[x]>0:
        gnew.add_node(x)
h=gnew.number_of_nodes()
print h

And as expected, 15 nodes will be printed. However, this becomes more tricky when you have identical values. For example:

new=np.ones(16)
gnew=nx.Graph()
for x in new:
    if new[x]>0:
        gnew.add_node(x)
h=gnew.number_of_nodes()
print h

Now, because all values are identical-(1), only one node will be added to the graph. Is there a way to circumnavigate this?

2
  • 1
    Just a quick comment - G.order() is the same as G.number_of_nodes(), but shorter... Commented Jun 18, 2015 at 17:34
  • The link is broken, unfortunately. Commented May 27, 2017 at 22:10

1 Answer 1

3

NetworkX requires that each node have a unique name. You could generate unique names and then set the elements of your array to be attributes of the nodes, e.g.

new = np.ones(16);
othernew = np.arange(16)

G = nx.Graph()
for i in range(len(othernew)):
   if new[i]>0:
      G.add_node(othernew[i])
      G.node[othernew[i]]['pos'] = new[i] #This gives the node a position attribute with value new[i]

h = G.order()
print(h)

>>16
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @jgloves, I should've checked back here sooner as I just arrived at the same conclusion you did and have written my code in the same way.
You're quite welcome. I'm glad you were able to solve it!
What if your new array is instead a 2D numpy array? So basically, what if you want to turn a raster image into a graph where the attribute of the node is the value in the array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.