Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a weighted graph from an adjacency matrix in graph-tool, python interface

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?)

like image 664
adrin Avatar asked Apr 25 '14 09:04

adrin


People also ask

How do you create a graph from adjacency matrix in python?

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.

How do you represent a weighted graph in adjacency matrix?

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.

Can adjacency matrix be weighted?

An adjacency matrix is easily implemented as an array. Both directed and undirected graphs may be weighted. A weight is attached to each edge.

How do you draw a graph from adjacency matrix?

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 .


2 Answers

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()))
like image 183
Tiago Peixoto Avatar answered Sep 30 '22 10:09

Tiago Peixoto


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
like image 34
Moj Avatar answered Sep 30 '22 10:09

Moj