Reputation: 2163
Based on the examples I can find for scipy graph_search, it seems to take the form NxN for the input graph, where the index pair of the graph is equal to that value.
so a matrix
G = [ [0,5,2],
[3,0,8],
[12,7,0] ]
means that the edge weight of 2->1
is the value of index G[1,0] = 3
If this is wrong, please explain.
The issue I have is with efficiently entering node connections in this way, starting with a dictionary, where the key is a node and the value is an array of connected nodes.
{'node1' : [node2,weight1],[node3,weight2]}
where the edge node1->node2 = weight1
I can iterate through a loop of the keys and make a new array of [ [node1,node2,,weight1],[node1,node3,weight2] ]
, but this also does not get me much closer to the scipy format. Is there an easy way to do this conversion from either the dictionary or the iterated array that I can make?
Upvotes: 0
Views: 72
Reputation: 7157
Assuming you already know the number N of nodes in your graph and your graph is directed, you could do it like this:
def create_csgraph_matrix(d, N):
M = np.zeros((N,N))
for i, node_weights in d.items():
for j, weight in node_weights:
M[i, j] = weight
return M
where d
is a dictionary of your form. Example:
In [38]: d = {0: [[1, 10], [2, 20]], 2: [[1, 15]]}
In [39]: create_csgraph_matrix(d,3)
Out[39]:
array([[ 0., 10., 20.],
[ 0., 0., 0.],
[ 0., 15., 0.]])
Note that the nodes in this graph are 0,1,2.
Upvotes: 1