2

I am having a numpy 2D array, with the values representing the weights of edges between nodes. The matrix is symmetric, and I take the diagonal to be zero. I don't find an example of how to convert this matrix into igraph Graph object. I've tried the following approach, but it doesn't work:

import numpy as np
import igraph

def symmetrize(a):
    return a + a.T - 2*np.diag(a.diagonal())

A = symmetrize(np.random.random((100,100)))

G = igraph.Graph.Adjacency(A.tolist())
Tamás
  • 47,239
  • 12
  • 105
  • 124
Ohm
  • 2,312
  • 4
  • 36
  • 75

2 Answers2

6

Use Graph.Weighted_Adjacency() if you want to preserve the original values in the matrix as weights. The weights will be attached as the weight edge attribute to the graph that igraph creates.

Tamás
  • 47,239
  • 12
  • 105
  • 124
0

As of version 0.9.6, the Weighted_Adjacency can receive

@param matrix: the adjacency matrix. Possible types are:
  - a list of lists
  - a numpy 2D array or matrix (will be converted to list of lists)
  - a scipy.sparse matrix (will be converted to a COO matrix, but not
    to a dense matrix)

There is no need to convert to a list.

Let extend possible use case scenario for multiple temporal slice, say, 5

from simeeg import rand_tril_arr as rt # pip install simeeg
import leidenalg as la
import igraph as ig
from string import ascii_uppercase
    
nsize=5
all_arr=[rt ( nsize=nsize, overwite_val=True, kmax=4, val_rand=0 ) for _ in range (5)]
nlabel=list(ascii_uppercase)[:nsize]
all_G=[]
for arr in all_arr:
    G = ig.Graph.Weighted_Adjacency ( arr)
    G.vs ['name'] = nlabel
    all_G.append(G)

G_layers, G_interslice, G = la.time_slices_to_layers(all_G, interslice_weight=1e-1,slice_attr='slice',
                                                     vertex_id_attr='name',edge_type_attr='type',
                                                     weight_attr='weight')

ig.plot(G,
        vertex_label = [f'{v["name"]}-{v["slice"]}' for v in G.vs])

Which produced:

enter image description here

mpx
  • 3,081
  • 2
  • 26
  • 56