从 numpy 求和二维数组创建加权 igraph 图作为邻接矩阵

Create weighted igraph Graph from numpy summetric 2D array as adjacency matrix

我有一个 numpy 二维数组,其值表示节点之间边的权重。矩阵是对称的,我取对角线为零。我找不到如何将此矩阵转换为 igraph Graph 对象的示例。我尝试了以下方法,但它不起作用:

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

如果您想保留矩阵中的原始值作为权重,请使用Graph.Weighted_Adjacency()。权重将作为 weight 边属性附加到 igraph 创建的图形。

从版本 0.9.6 开始,Weighted_Adjacency 可以接收

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

无需转换为 list

让我们扩展多个时间片的可能用例场景,比如 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])

产生了: