如何将幂律分布中的权重随机分配给具有大量节点的网络。
我写了
import networkx as nx
import numpy as np
from networkx.utils import powerlaw_sequence
z=nx.utils.create_degree_sequence(200,nx.utils.powerlaw_sequence,exponent=1.9)
nx.is_valid_degree_sequence(z)
G=nx.configuration_model(z)
Gcc=nx.connected_component_subgraphs(G)[0]
edgelist=[nx.utils.powerlaw_sequence(nx.number_of_edges(Gcc),exponent=2.0)]
我知道我使用以下方法通过元组字典(node1,node2,weight)为边缘分配权重:
nx.from_edgelist(edgelist,create_using=None)
但是当我只想获得权重是幂律分布的加权网络时,还有另一种更短的方法吗?
答案 0 :(得分:3)
您可以使用G [u] [v] ['weight']直接指定权重,例如
In [1]: import networkx as nx
In [2]: import random
In [3]: G = nx.path_graph(10)
In [4]: for u,v in G.edges():
...: G[u][v]['weight'] = random.paretovariate(2)
...:
...:
In [5]: print G.edges(data=True)
[(0, 1, {'weight': 1.6988521989583232}), (1, 2, {'weight': 1.0749963615177736}), (2, 3, {'weight': 1.1503859779558812}), (3, 4, {'weight': 1.675436575683888}), (4, 5, {'weight': 1.1948608572552846}), (5, 6, {'weight': 1.080152340891444}), (6, 7, {'weight': 1.0296667672332183}), (7, 8, {'weight': 2.0014384064255446}), (8, 9, {'weight': 2.2691612212058447})]
我使用Python的random.paretovariate()来选择重量,但你当然可以放任何你想要的东西。
答案 1 :(得分:1)
我试过并得到以下内容..我希望它有所帮助。此外,我正在寻找更好的方法,因为这不能保证我得到一个连接网络。另外,我还要检查它的属性。
'''written by Aya Al-Zarka'''
import networkx as nx
import matplotlib.pyplot as plt
from networkx.utils import powerlaw_sequence
import random as r
import numpy as np
G=nx.Graph()
v=[]
for i in range(100):
v.append(i)
G.add_nodes_from(v)
weight=[]
for j in range(300):
l=powerlaw_sequence(300,exponent=2.0)
weight.append(r.choice(l))
#print(weight)
e=[]
for k in range(300):
f=[r.choice(v),r.choice(v),r.choice(weight)]
e.append(f)
G.add_weighted_edges_from(e,weight='weight')
print(nx.is_connected(G)) #not always!
m=np.divide(weight,100.0)
pos=nx.random_layout(G,dim=2)
nx.draw_networkx_nodes(G,pos,nodelist=None,node_size=300,node_color='y',
node_shape='*', alpha=1.0, cmap=None, vmin=None,
vmax=None, ax=None, linewidths=None,)
nx.draw_networkx_edges(G,pos,edgelist=None,width=m,
edge_color='b',style='solid',alpha=None,edge_cmap=None, edge_vmin=None,
edge_vmax=None, ax=None, arrows=False)
plt.ylim(0,1)
plt.xlim(0,1)
plt.axis('off')
plt.show()