は、ここでノードの数及び度の値のアレイでキーイング辞書を返すBarabasiアルバートグラフの修正されたソースコードである:
import random
import networkx as nx
def _random_subset(seq,m):
""" Return m unique elements from seq.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
"""
targets=set()
while len(targets)<m:
x=random.choice(seq)
targets.add(x)
return targets
def barabasi_albert_graph_modified(n, m, seed=None):
if m < 1 or m >=n:
raise nx.NetworkXError(\
"Barabási-Albert network must have m>=1 and m<n, m=%d,n=%d"%(m,n))
if seed is not None:
random.seed(seed)
# Add m initial nodes (m0 in barabasi-speak)
G=nx.empty_graph(m)
G.name="barabasi_albert_graph(%s,%s)"%(n,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
d = {}
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)
deg = np.array(list(G.degree().values()))
deg.sort()
d[G.number_of_nodes()] = deg
source += 1
return G,d
だがそれを試してみましょう:
g,d = barabasi_albert_graph_modified(10,2)
#out:
#{3: array([1, 1, 2]),
# 4: array([1, 2, 2, 3]),
# 5: array([1, 2, 2, 3, 4]),
# 6: array([1, 2, 2, 2, 4, 5]),
# 7: array([1, 2, 2, 2, 3, 4, 6]),
# 8: array([2, 2, 2, 2, 2, 3, 4, 7]),
# 9: array([2, 2, 2, 2, 2, 2, 4, 5, 7]),
# 10: array([2, 2, 2, 2, 2, 2, 3, 4, 5, 8])}
これが割り当ての一部である場合、インストラクターが中間の詳細の要件を割り当てた理由の一部は、組み込みコマンドを使用するのではなく、アルゴリズムを自分でコーディングすることになります。 – Joel