所以,我在python上还是新手,但我写了这个函数来生成一个具有某些层次特征的图。但是,有时此函数会创建一个包含未连接节点的图形。但这不应该发生,因为每个节点都应该与其" level"下面的其他节点完全连接。层次结构的特征遵循Seigel 2009的特征:"基础是由参数扩展率确定的层次结构,其中一个人位于顶部,并且网络中的每个人都连接到下面的一些个体他等于扩张率,一直持续到不再有人留在人口中。因此,虽然最后一个层次之前的层级中的每个层级包含等于扩展速率的数量的个体,但是如果总体群体没有适当地划分,则最后一个层次可以具有少于此的层次。同一级别内个体之间的每个潜在联系也具有等于正在进行的等级连接的概率。"
def heirarchy_graph(n,e,l):
'''
n is number of nodes in graph,
e is the Expansion Rate. This is the number of people on each level
If n/e has a remainder then the last level has that many
people in it.
l is the Level connection. It is the probability that a person is connected to someone
within the level they belong to.
'''
G = nx.Graph()
G.name="heirarchy_graph(%s,%s,%s)"%(n,e,l)
r = (n-1)%e
s = (n-r-1)/e
h = s + 1
#G = empty_graph(n=0)
G.add_node(0, level=int(0))
for i in range(s):
list = range(1,(e+1))
A = nx.Graph()
#for item in list:
#create e nodes with attribute level='i'
A.add_nodes_from(list,level=int(i))
# add edges between nodes with probability l
names = A.nodes()
for name in names:
B = non_neighbors(A,name)
for u in B:
q = random.uniform(0,1)
if q <= l:
A.add_edge(u,name)
#return A
#print(A)
G = nx.disjoint_union(G,A)
if r != 0:
h = s+1
list = range(1,(r+1))
A = nx.Graph()
#create e nodes with attribute level='i'
A.add_nodes_from(list,level=int(h))
# add edges between nodes with probability l
names = A.nodes()
for name in names:
B = non_neighbors(A,name)
for u in B:
q = random.uniform(0,1)
if q <= l:
A.add_edge(u,name)
G = nx.disjoint_union(G,A)
## add edges between levels
level = nx.get_node_attributes(G,'level')
names = G.nodes()
for name in names:
levelname = level[name]
B = non_neighbors(G,name)
for u in B:
levelneighbor = level[u]
if levelname == (levelneighbor + 1):
G.add_edge(u,name)
return G
我多次运行此代码,n = 25,e = 5和l = .5但我经常最终得到节点21,22,23或24(或它们的某些组合)未连接(通过拉动每个节点的中心性。)
我非常感谢任何帮助。代码运行没有错误,我只是不知道为什么它给了我未连接的节点。这些节点应与它们上面的级别连接。先感谢您。