News

New paper! in the American Naturalist

Thursday, February 9, 2023

Generate a graph from adjacency matrix

import igraph as ig
import numpy as np

matrix = np.array([[0, 0.1, 0.2],[0, 0, 0.1],[0,0,0]])
g = ig.Graph.Adjacency((matrix > 0).tolist())
g.es['weight'] = matrix[matrix.nonzero()]
g.vs['label'] = node_label # a list of node labels

* To generate an UNDIRECTED graph, use 'mode=ig.ADJ_UPPER' :
g = ig.Graph.Adjacency((matrix > 0).tolist(), mode=ig.ADJ_UPPER)

Otherwise, if a matrix is symmetric and supposed to be for an undirected graph, the function will assign redundant edges. e.g. 

>>> mat = array([[0. , 0.1, 0.2], [0.1, 0. , 0.1], [0.2, 0.1, 0. ]]) # a symmetric matrix

>>> g = ig.Graph().Adjacency((mat>0).tolist())

>>> g.es['weight'] = mat[mat.nonzero()]

>>> list(g.get_edgelist())

[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] # contains edges into both directions


In contrast, if you use 'mode=ig.ADJ_UPPER' for the same symmetric matrix :

>>> g = ig.Graph().Adjacency((mat>0).tolist(),mode=ig.ADJ_UPPER)

>>> g.es['weight'] = mat[mat.nonzero()]

>>> list(g.get_edgelist())

[(0, 1), (0, 2), (1, 2)]