在Python中结合Barabasi-Albert模型和Watts-Strogatz模型

时间:2018-11-07 07:11:03

标签: python

是否可以将Watts-Strogatz model与所需边缘的一半合并,并且将Barabasi-Albert model与其余边缘的另一半合并?我正在尝试在python中执行此操作,但是由于我在编码方面的能力很弱,因此我不确定应该如何开始,因此我在这里寻求一些建议。 我实际上正在尝试将MATLAB代码(如下所示)转换为python代码。 MATLAB代码:

function B = custom207 ()
% This file provides a simulation for Facebook network .
N =4039;
mean_d =2;
% A WS - model is used as initial network of BA - model .
initial_network = WattsStrogatz (3850 ,1 ,0.05) ;
% The following part is the model growth of BA - model . Nodes are added to
this network until the number of nodes reaches 4039.
% A is the adjacency matrix , it is pre - allocated for efficiency .
A = zeros (N , N ) ;
A (1:3850 ,1:3850) = initial_network ;
% This step use the exactly same method as BA model except the number of
nodes attached to a new node ( which is mean_d ) is increasing by 4( this
is obtained by trying different values ).
for i =3851: N
prob_vec = sum ( A ) / sum ( sum ( A ) ) ;
attachment = unique ( randsample (N , mean_d , true , prob_vec ) ) ;
A (( i -1) * N + attachment ) =1;
A =( A +A ') >0;
mean_d = mean_d +4;
end

到目前为止,我的python代码是:

#initialise values
#WS model used as initial network of BA model  
N = 4039
mean_k = 2
initial_network = nx.watts_strogatz_graph(3850,mean_k,0.05)
nx.draw(initial_network,node_size=0.5,node_color='blue', alpha=0.2,edge_colour='red')

#model growth of BA model. Nodes added to this network till total 4039 nodes
#Allocate adjacency matrix
adjacency = np.zeros((N,N))
initial_network = adjacency(1:3850, 1:3850)

所以我被困在如何附加BA模型的节点上

1 个答案:

答案 0 :(得分:0)

我必须承认,我对networkx模块不是很熟悉(绘制图形除外)。但是我认为,最简单的方法是像您一样简单地提取邻接矩阵,然后继续使用numpy。

    import numpy as np
    import networkx as nx
    N = 4039
    A = np.zeros((N,N))
    mean_k = 2
    initial_network = nx.watts_strogatz_graph(3850,mean_k,0.05)
    # nx.draw(initial_network,node_size=0.5, node_color='blue',  alpha=0.2, edge_colour='red')
    A[:3850, :3850] = nx.to_numpy_array(initial_network)
    for i in range(3850, N):
        prob_vec = np.sum(A, 1) / np.sum(A) # Be aware of the differen conventions in Matlab and python functions!
        attachment = np.unique(np.random.choice(np.arange(N), mean_k, replace=True, p=prob_vec))
        temp = A.copy().flatten(order='F') # Probably there is nicer array indexing than this detour.
        temp[i * N + attachment] = 1
        A = np.reshape(temp, A.shape, order='F') # Here I am especially not sure about the order..
        A = (A + A.T) > 0
        mean_k += 4
    out_graph = nx.DiGraph(A)

请注意,到目前为止,我刚刚测试了这段代码,我知道它可以工作。我不确定结果是否符合您的期望... 但我希望这足以让您入门!始终要注意Matlab和Python中不同的索引编制和重塑等操作,即在处理数组时从0开始以及Fortran vs. C约定。