Python 基于优先连接算法的无标度网络
我很难理解这段代码的作用。请有人一步一步地检查代码,并解释它是如何工作的以及它在做什么Python 基于优先连接算法的无标度网络,python,networkx,Python,Networkx,我很难理解这段代码的作用。请有人一步一步地检查代码,并解释它是如何工作的以及它在做什么 def scale_free(n,m): if m < 1 or m >=n: raise nx.NetworkXError("Preferential attactment algorithm must have m >= 1" " and m < n, m = %d, n = %d" % (m
def scale_free(n,m):
if m < 1 or m >=n:
raise nx.NetworkXError("Preferential attactment algorithm must have m >= 1"
" and m < n, m = %d, n = %d" % (m, n))
# Add m initial nodes (m0 in barabasi-speak)
G=nx.empty_graph(m)
# Target nodes for new edges
targets=list(range(m))
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes=[]
# Start adding the other n-m nodes. The first node is m.
source=m
while source<n:
# Add edges to m nodes from the source.
G.add_edges_from(zip([source]*m,targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source]*m)
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachement)
targets = _random_subset(repeated_nodes,m)
source += 1
return G
def无刻度(n,m):
如果m<1或m>=n:
提高nx.NetworkXError(“优先附加算法必须具有m>=1”
“和m 而source的第一部分确保m
至少为1和n>m
def scale_free(n,m):
if m < 1 or m >=n:
raise nx.NetworkXError("Preferential attactment algorithm must have m >= 1"
" and m < n, m = %d, n = %d" % (m, n))
现在,它将开始一次添加1个新节点,并根据各种规则将它们连接到现有节点。它首先创建一组“目标”,其中包含无边图中的所有节点
# Target nodes for new edges
targets=list(range(m))
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes=[]
# Start adding the other n-m nodes. The first node is m.
source=m
现在,它将一次添加每个节点1。当它这样做时,它会将带有边的新节点添加到先前现有节点的m
。那些m
以前的节点已存储在名为targets
的列表中
while source<n:
现在,它将决定在添加下一个节点时谁将获得这些边。它应该以与其程度成比例的概率来选择它们,其方法是通过一个列表重复的\u节点
,每个节点在每条边上出现一次。然后,它从中随机选择一组m
节点作为新目标。根据\u random\u subset
的定义方式,它可能会或可能不会多次选择同一节点作为同一步骤中的目标
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source]*m)
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachement)
targets = _random_subset(repeated_nodes,m)
source += 1
return G
您好@killerownage2006,注释中对代码进行了很好的记录。你有什么特别的问题吗?非常感谢!这有助于我的理解:)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source]*m,targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source]*m)
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachement)
targets = _random_subset(repeated_nodes,m)
source += 1
return G