yannis
yannis

Reputation: 916

turning igraph adjacency matrix into numpy array

By writing

import igraph
g = igraph.Graph()
g.add_vertices(6)
g.add_edges([(0,1),(0,3),(0,4),(0,5),(1,2),(2,4),(2,5),(3,0),(3,2),(3,5),(4,5),(3,3)])
A=g.get_adjacency()

I get the adjacency matrix of graph g, as a Matrix object. I want to calculate its eigenvalues by using, for example, numpy.linalg.eigvals(). This method takes a numpy array object as argument. How do I convert a Matrix object into a numpy array object? I tried by using

X=numpy.matrix(A)

but it produced some mixture of the two and eigenvalues could not be calculated.

Upvotes: 4

Views: 3940

Answers (2)

Joel
Joel

Reputation: 23827

Not exactly the answer you're after, but here's how to do it with networkx (option with igraph is below - I think):

import networkx as nx
G= nx.Graph()
G.add_edges_from([(0,1),(0,3),(0,4),(0,5),(1,2),(2,4),(2,5),(3,0),(3,2),(3,5),(4,5),(3,3)])
A=nx.adjacency_matrix(G)  #by default A is sparse

import numpy as np
np.linalg.eig(A.todense())

I don't have igraph, so not sure if a similar .todense() might work for the Matrix type it returns.

edit I see some suggestion that

numpy.array(list(g.get_adjacency()))

might do what you're after with igraph. I don't have igraph, so can't test. Please let me know if it works. (but consider networkx anyways ;) )

re-edit I think the solution by Oliver is cleaner. But I still want to leave the networkx version and this other igraph approach for others to see.

Upvotes: 1

Oliver W.
Oliver W.

Reputation: 13459

According to the documentation of iGraph's matrix class, you could retrieve the data as a list of lists and then convert easily to a numpy ndarray:

A = g.get_adjacency()
A = np.array(A.data)

Upvotes: 10

Related Questions