How should I create a graph using graph-tool in python, out of an adjacency matrix?
Assume we have adj
matrix as the adjacency matrix.
What I do now is like this:
g = graph_tool.Graph(directed = False)
g.add_vertex(len(adj))
edge_weights = g.new_edge_property('double')
for i in range(adj.shape[0]):
for j in range(adj.shape[1]):
if i > j and adj[i,j] != 0:
e = g.add_edge(i, j)
edge_weights[e] = adj[i,j]
But it doesn't feel right, do we have any better solution for this?
(and I guess a proper tag for this would be graph-tool
, but I can't add it, some kind person with enough privileges could make the tag?)
Using an adjacency matrix The following code implements a graph using an adjacency matrix: add_vertex(v) adds new vertex v to the graph, and add_edge(v1, v2, e) adds an edge with weight e between vertices v1 and v2 . print("Vertex ", v1, " does not exist. ") print("Vertex ", v2, " does not exist.
Adjacency matrix representationTo store weighted graph using adjacency matrix form, we call the matrix as cost matrix. Here each cell at position M[i, j] is holding the weight from edge i to j. If the edge is not present, then it will be infinity. For same node, it will be 0.
An adjacency matrix is easily implemented as an array. Both directed and undirected graphs may be weighted. A weight is attached to each edge.
Adjacency Matrix of a GraphTo fill the adjacency matrix, we look at the name of the vertex in row and column. If those vertices are connected by an edge or more, we count number of edges and put this number as matrix element. The matrix to represent a graph in this way is called Adjacency matrix .
Graph-tool now includes a function to add a list of edges to the graph. You can now do, for instance:
import graph_tool as gt
import numpy as np
g = gt.Graph(directed=False)
adj = np.random.randint(0, 2, (100, 100))
g.add_edge_list(np.transpose(adj.nonzero()))
this is the extension of Tiago's answer for the weighted graph:
adj = numpy.random.randint(0, 10, (100, 100)) # a random directed graph
idx = adj.nonzero()
weights = adj[idx]
g = Graph()
g.add_edge_list(transpose(idx)))
#add weights as an edge propetyMap
ew = g.new_edge_property("double")
ew.a = weights
g.ep['edge_weight'] = ew
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With