I'm trying to convert paths in graphs in into adjacency matrix using the networkx library. I can convert a whole graph into an adjacency matrix:
>>>import networkx as nx
>>>DG=nx.DiGraph()
>>>DG.add_edges_from([(1,2), (2,3),(1,3)])
>>>nx.to_numpy_matrix(DG)
....matrix([[ 0., 1., 1.],
[ 0., 0., 1.],
[ 0., 0., 0.]])
However, after I find all simple paths from node 1 to node 3:
>>>list(nx.all_simple_paths(DG,1,3))
....[[1, 2, 3], [1, 3]]
I'm unable to turn them into an adjacency matrix. I want to be able to choose a path and turn it into an adjacency matrix, for example, the second path should return:
....matrix([[ 0., 0., 1.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
That is not an adjacency matrix. But you can easily build it yourself as follows:
import networkx as nx
import numpy as np
DG=nx.DiGraph()
DG.add_edges_from([(1,2), (2,3),(1,3)])
paths = list(nx.all_simple_paths(DG,1,3))
for path in paths:
matrix = np.matrix(np.zeros((len(DG), len(DG))))
for i in range(len(path)-1):
matrix[path[i]-1], path[i+1]-1] = 1 # edit: credits to @Joel
print(matrix)
output:
[[ 0. 1. 0.]
[ 0. 0. 1.]
[ 0. 0. 0.]]
[[ 0. 0. 1.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.