本文整理汇总了Python中networkx.barabasi_albert_graph函数的典型用法代码示例。如果您正苦于以下问题:Python barabasi_albert_graph函数的具体用法?Python barabasi_albert_graph怎么用?Python barabasi_albert_graph使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了barabasi_albert_graph函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_all_parameter
def update_all_parameter(diff):
#print 'each difference - %s' % diff
luc_node = int(30*diff)
hcc_node = int(5)
time = 10
#parameter
luc_gro = int(6*diff)
hcc_gro = int(2)
lucG = nx.barabasi_albert_graph(luc_node, luc_gro)
hccG = nx.barabasi_albert_graph(hcc_node, hcc_gro)
frequency = np.array([0.9, 0.1])
G_combine =nx.Graph()
G_combine = graph.merge_graph(G_combine, hccG, lucG, frequency)
frequency_1 = np.array([0.5, 0.5])
G_combine_1 =nx.Graph()
G_combine_1 = graph.merge_graph(G_combine_1, hccG, lucG, frequency_1)
#Time series cell volume
LucN = []
hccN = []
#Number of initial cell
LucN0 = 100
hccN0 = 100
LucN_init = 100
hccN_init = 100
for t in range(time):
LucN.append(calc.convert_volume(LucN0))
lucG = graph.update_graph(lucG, luc_gro)
LucN0 = LucN_init*calc.calc_entropy(lucG, t+1)
for t in range(time):
hccN.append(calc.convert_volume(hccN0))
hccG = graph.update_graph(hccG, hcc_gro)
hccN0 = hccN_init*calc.calc_entropy(hccG, t+1)
#Mix Number of cell
MixN0 = 100
MixN_init = 100
initial_populations = MixN0*frequency
G_comb_gro = ((frequency*np.array([luc_gro, hcc_gro])).sum())/2
MixN = []
x = []
for t in range(time):
x.append(t)
MixN.append(calc.convert_volume(MixN0))
G_combine = graph.update_graph(G_combine, G_comb_gro)
MixN0 = MixN_init*calc.calc_entropy(G_combine, t+1)
sim_ratio = np.array(LucN)/np.array(MixN)
return sim_ratio
"""
示例2: setUp
def setUp(self):
self.G=nx.barabasi_albert_graph(1000, 10, 8)
pth_graph=nx.path_graph(1000)
edge=random.choice(pth_graph.edges())
pth_graph.remove_edge(edge[0], edge[1])
self.dG=pth_graph
self.dG2=nx.barabasi_albert_graph(900, 10, 0)
for i in xrange(900,1000):
self.dG2.add_node(i)
示例3: test_powerlaw_mle
def test_powerlaw_mle():
print 'Testing Power law MLE estimator'
G = nx.barabasi_albert_graph(100, 5)
print 'nn: %d, alpha: %f'%(G.number_of_nodes(),powerlaw_mle(G))
G = nx.barabasi_albert_graph(1000, 5)
print 'nn: %d, alpha: %f'%(G.number_of_nodes(),powerlaw_mle(G))
G = nx.barabasi_albert_graph(10000, 5)
print 'nn: %d, alpha: %f'%(G.number_of_nodes(),powerlaw_mle(G))
G = nx.barabasi_albert_graph(100000, 5)
print 'nn: %d, alpha: %f'%(G.number_of_nodes(),powerlaw_mle(G))
print 'Expected: 2.9 (or thereabout)'
示例4: main
def main():
msg = "usage: ./p2p2012.py type r|g|g2 ttl par tries churn_rate"
if len(sys.argv) < 7:
print msg
sys.exit(1)
global out_file, churn_rate
out_file = sys.stdout
gtype = sys.argv[1]
walk = sys.argv[2]
ttl = int(sys.argv[3])
par = int(sys.argv[4])
tries = int(sys.argv[5])
churn_rate = float(sys.argv[6])
if gtype == "a":
g = nx.barabasi_albert_graph(97134, 3)
elif gtype == "b":
g = nx.barabasi_albert_graph(905668, 12)
elif gtype == "c":
g = sm.randomWalk_mod(97134, 0.90, 0.23)
elif gtype == "d":
g = sm.randomWalk_mod(905668, 0.93, 0.98)
elif gtype == "e":
g = sm.nearestNeighbor_mod(97134, 0.53, 1)
elif gtype == "f":
g = sm.nearestNeighbor_mod(905668, 0.90, 5)
elif gtype == "g":
g = nx.random_regular_graph(6, 97134)
elif gtype == "h":
g = nx.random_regular_graph(20, 905668)
elif gtype == "i":
g = nx.read_edgelist(sys.argv[7])
if walk == "r":
lookup(g, ttl, tries, par, get_random_node)
elif walk == "g":
lookup(g, ttl, tries, par, get_greedy_node)
elif walk == "g2":
lookup(g, ttl, tries, par, get_greedy2_node)
elif walk == "sum":
sum_edges(g, int(sys.argv[3]))
nodes = g.number_of_nodes()
edges = g.size()
avg_cc = nx.average_clustering(g)
print >> sys.stderr, nodes, edges, avg_cc
示例5: test_networkx_matrix
def test_networkx_matrix(self):
print('\n---------- Matrix Test Start -----------\n')
g = nx.barabasi_albert_graph(30, 2)
nodes = g.nodes()
edges = g.edges()
print(edges)
mx1 = nx.adjacency_matrix(g)
fp = tempfile.NamedTemporaryFile()
file_name = fp.name
sp.savetxt(file_name, mx1.toarray(), fmt='%d')
# Load it back to matrix
mx2 = sp.loadtxt(file_name)
fp.close()
g2 = nx.from_numpy_matrix(mx2)
cyjs_g = util.from_networkx(g2)
#print(json.dumps(cyjs_g, indent=4))
self.assertIsNotNone(cyjs_g)
self.assertIsNotNone(cyjs_g['data'])
self.assertEqual(len(nodes), len(cyjs_g['elements']['nodes']))
self.assertEqual(len(edges), len(cyjs_g['elements']['edges']))
# Make sure all edges are reproduced
print(set(edges))
diff = compare_edge_sets(set(edges), cyjs_g['elements']['edges'])
self.assertEqual(0, len(diff))
示例6: compare_graphs
def compare_graphs(graph):
n = nx.number_of_nodes(graph)
m = nx.number_of_edges(graph)
k = np.mean(list(nx.degree(graph).values()))
erdos = nx.erdos_renyi_graph(n, p=m/float(n*(n-1)/2))
barabasi = nx.barabasi_albert_graph(n, m=int(k)-7)
small_world = nx.watts_strogatz_graph(n, int(k), p=0.04)
print(' ')
print('Compare the number of edges')
print(' ')
print('My network: ' + str(nx.number_of_edges(graph)))
print('Erdos: ' + str(nx.number_of_edges(erdos)))
print('Barabasi: ' + str(nx.number_of_edges(barabasi)))
print('SW: ' + str(nx.number_of_edges(small_world)))
print(' ')
print('Compare average clustering coefficients')
print(' ')
print('My network: ' + str(nx.average_clustering(graph)))
print('Erdos: ' + str(nx.average_clustering(erdos)))
print('Barabasi: ' + str(nx.average_clustering(barabasi)))
print('SW: ' + str(nx.average_clustering(small_world)))
print(' ')
print('Compare average path length')
print(' ')
print('My network: ' + str(nx.average_shortest_path_length(graph)))
print('Erdos: ' + str(nx.average_shortest_path_length(erdos)))
print('Barabasi: ' + str(nx.average_shortest_path_length(barabasi)))
print('SW: ' + str(nx.average_shortest_path_length(small_world)))
print(' ')
print('Compare graph diameter')
print(' ')
print('My network: ' + str(nx.diameter(graph)))
print('Erdos: ' + str(nx.diameter(erdos)))
print('Barabasi: ' + str(nx.diameter(barabasi)))
print('SW: ' + str(nx.diameter(small_world)))
示例7: ba_network
def ba_network(p=25, n=150):
""" Barabasi-Albert algorithm is used to generate a scale free network. The
precision matrix is constructed as the above nearest neighbor based
algorithm. We also set the degree as 5."""
m = 5
G = networkx.barabasi_albert_graph(p, m) # obtain networkx library graph G
A = np.array(networkx.adjacency_matrix(G)) # numpy matrix is returned
# We weight the edges using a random number in [-1.0, -0.5] \cup [0.5, 1.0]
for i in range(p):
for j in range(p):
if A[i, j] > 0:
A[i, j] = A[i, j] * np.random.uniform(0.5, 1.0)
A[j, i] = A[i, j]
# ensure symmetry
A = (A + A.T) / 2.0
# Randomize sign
A = A * pow(-1.0, np.random.random_integers(0, 1, [p, p]))
# The diagonal entires are set to the sum of the absolute values of the row
# then, we obtain precision matrix
# I placed the factor 2 to ensure invertibility
P = A + 0.25 * np.diag(np.sum(np.absolute(A), 1))
# normalize entries to make the diagonal elements equal to one
P = P / np.diag(P)
cov = np.linalg.inv(P) # covariance matrix
# Sample from the covariance matrix
samples = np.random.multivariate_normal(np.zeros(p), cov, n)
return samples, cov
示例8: test_random_model
def test_random_model():
n_node = graph.number_of_nodes()
n_edge = graph.number_of_edges()
p = float(2 * n_edge) / (n_node*n_node - 2*n_node)
#new_graph = networkx.erdos_renyi_graph(n_node, p)
new_graph = networkx.barabasi_albert_graph(n_node, n_edge/n_node)
mapping = dict(zip(new_graph.nodes(), graph.nodes()))
new_graph = networkx.relabel_nodes(new_graph, mapping)
return new_graph
available_edges = graph.edges()
for edge in new_graph.edges():
if len(available_edges) > 0:
edge_org = available_edges.pop()
new_graph.add_edge(edge[0], edge[1], graph.get_edge(edge_org[0], edge_org[1]))
else:
print "Removing:", edge
new_graph.remove_edge(edge[0], edge[1])
for edge_org in available_edges:
print "Adding:", edge_org
new_graph.add_edge(edge_org[0], edge_org[1], graph.get_edge(edge_org[0], edge_org[1]))
return new_graph
示例9: get_graph
def get_graph(objects, properties):
graph_type = properties['graph_type']
n = len(objects)-1
if 'num_nodes_to_attach' in properties.keys():
k = properties['num_nodes_to_attach']
else:
k = 3
r = properties['connection_probability']
tries = 0
while(True):
if graph_type == 'random':
x = nx.fast_gnp_random_graph(n,r)
elif graph_type == 'erdos_renyi_graph':
x = nx.erdos_renyi_graph(n,r)
elif graph_type == 'watts_strogatz_graph':
x = nx.watts_strogatz_graph(n, k, r)
elif graph_type == 'newman_watts_strogatz_graph':
x = nx.newman_watts_strogatz_graph(n, k, r)
elif graph_type == 'barabasi_albert_graph':
x = nx.barabasi_albert_graph(n, k, r)
elif graph_type == 'powerlaw_cluster_graph':
x = nx.powerlaw_cluster_graph(n, k, r)
elif graph_type == 'cycle_graph':
x = nx.cycle_graph(n)
else: ##Star by default
x = nx.star_graph(len(objects)-1)
tries += 1
cc_conn = nx.connected_components(x)
if len(cc_conn) == 1 or tries > 5:
##best effort to create a connected graph!
break
return x, cc_conn
示例10: main
def main():
### Undirected graph ###
# Initialize model using the Petersen graph
model=gmm.gmm(nx.petersen_graph())
old_graph=model.get_base()
model.set_termination(node_ceiling)
model.set_rule(rand_add)
# Run simualation with tau=4 and Poisson density for motifs
gmm.algorithms.simulate(model,4)
# View results
new_graph=model.get_base()
print(nx.info(new_graph))
# Draw graphs
old_pos=nx.spring_layout(old_graph)
new_pos=nx.spring_layout(new_graph,iterations=2000)
fig1=plt.figure(figsize=(15,7))
fig1.add_subplot(121)
#fig1.text(0.1,0.9,"Base Graph")
nx.draw(old_graph,pos=old_pos,node_size=25,with_labels=False)
fig1.add_subplot(122)
#fig1.text(0.1,0.45,"Simulation Results")
nx.draw(new_graph,pos=new_pos,node_size=20,with_labels=False)
fig1.savefig("undirected_model.png")
### Directed graph ###
# Initialize model using random directed Barabasi-Albert model
directed_base=nx.barabasi_albert_graph(25,2).to_directed()
directed_model=gmm.gmm(directed_base)
directed_model.set_termination(node_ceiling)
directed_model.set_rule(rand_add)
# Run simualation with tau=4 and Poisson density for motifs
gmm.algorithms.simulate(directed_model,4)
# View results
new_directed=directed_model.get_base()
print(nx.info(new_directed))
# Draw directed graphs
old_dir_pos=new_pos=nx.spring_layout(directed_base)
new_dir_pos=new_pos=nx.spring_layout(new_directed,iterations=2000)
fig2=plt.figure(figsize=(7,10))
fig2.add_subplot(211)
fig2.text(0.1,0.9,"Base Directed Graph")
nx.draw(directed_base,pos=old_dir_pos,node_size=25,with_labels=False)
fig2.add_subplot(212)
fig2.text(0.1,0.45, "Simualtion Results")
nx.draw(new_directed,pos=new_dir_pos,node_size=20,with_labels=False)
fig2.savefig("directed_model.png")
# Export files
nx.write_graphml(model.get_base(), "base_model.graphml")
nx.write_graphml(directed_model.get_base(), "directed_model.graphml")
nx.write_graphml(nx.petersen_graph(), "petersen_graph.graphml")
示例11: generate
def generate(self):
barabasi_albert = nx.barabasi_albert_graph(self.nodes, self.m, self.seed)
self.nx_topology = nx.MultiDiGraph()
self.nx_topology.clear()
index = 0
nodes = []
for node in barabasi_albert.nodes():
#SSnodes.append(node+1)
nodes.append(str(node+1))
self.nx_topology.add_nodes_from(nodes)
for (n1, n2) in barabasi_albert.edges():
n1 = n1 + 1
n2 = n2 + 1
self.sip.update(str(index))
id_ = str(self.sip.hash())
#SSself.nx_topology.add_edge(n1, n2, capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_)
self.nx_topology.add_edge(str(n1), str(n2), capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_)
index = index + 1
self.sip.update(str(index))
id_ = str(self.sip.hash())
#SSself.nx_topology.add_edge(n2, n1, capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_)
self.nx_topology.add_edge(str(n2), str(n1), capacity=self.DEFAULT_SPEED, allocated=0.0, src_port="", dst_port="", src_port_no="", dst_port_no="", src_mac="", dst_mac="", flows=[], id=id_)
index = index + 1
示例12: generate_graph
def generate_graph(type = 'PL', n = 100, seed = 1.0, parameter = 2.1):
if type == 'ER':
G = nx.erdos_renyi_graph(n, p=parameter, seed=seed, directed=True)
G = nx.DiGraph(G)
G.remove_edges_from(G.selfloop_edges())
elif type == 'PL':
z = nx.utils.create_degree_sequence(n, nx.utils.powerlaw_sequence, exponent = parameter)
while not nx.is_valid_degree_sequence(z):
z = nx.utils.create_degree_sequence(n, nx.utils.powerlaw_sequence, exponent = parameter)
G = nx.configuration_model(z)
G = nx.DiGraph(G)
G.remove_edges_from(G.selfloop_edges())
elif type == 'BA':
G = nx.barabasi_albert_graph(n, 3, seed=None)
G = nx.DiGraph(G)
elif type == 'grid':
G = nx.grid_2d_graph(int(np.ceil(np.sqrt(n))), int(np.ceil(np.sqrt(n))))
G = nx.DiGraph(G)
elif type in ['facebook', 'enron', 'twitter', 'students', 'tumblr', 'facebookBig']:
#print 'start reading'
#_, G, _, _ = readRealGraph(os.path.join("..","..","Data", type+".txt"))
_, G, _, _ = readRealGraph(os.path.join("..","Data", type+".txt"))
print 'size of graph', G.number_of_nodes()
#Gcc = sorted(nx.connected_component_subgraphs(G.to_undirected()), key = len, reverse=True)
#print Gcc[0].number_of_nodes()
#print 'num of connected components', len(sorted(nx.connected_component_subgraphs(G.to_undirected()), key = len, reverse=True))
#exit()
if G.number_of_nodes() > n:
G = getSubgraph(G, n)
#G = getSubgraphSimulation(G, n, infP = 0.3)
#nx.draw(G)
#plt.show()
return G
示例13: __init__
def __init__(self, N = 10000, m_0 = 3):
"""
:Purpose:
This is the base class used to generate the social network
for the other agents, i.e. . The class inherits from the PopulationClass.
:Input:
N : int
Number of agents. Default: 10000
m_0: int
Number of nodes each node is connected to in preferential
attachment step
"""
if type(N) is not int:
raise ValueError(('Population size must be integer,\
n = %s, not %s')%(string(N), type(N)))
else: pass
if m_0 not in range(10):
raise ValueError('m_0 must be integer smaller than 10')
else: self.m_0 = m_0
PopulationClass.__init__(self, n = N) # Create population
SpecialAgents = set(self.IDU_agents).union(set(self.MSM_agents))
SpecialAgents = SpecialAgents.union(set(self.NIDU_agents))
NormalAgents = set(range(self.PopulationSize)).difference(SpecialAgents)
NormalAgents = list(NormalAgents)
self.NetworkSize = len(NormalAgents)
# scale free Albert Barabsai Graph
self.G = nx.barabasi_albert_graph(self.NetworkSize,m_0)
示例14: correlation_betweenness_degree_on_BA
def correlation_betweenness_degree_on_BA():
n = 1000
m = 2
G = nx.barabasi_albert_graph(n, m)
print nx.info(G)
ND, ND_lambda = ECT.get_number_of_driver_nodes(G)
print "ND = ", ND
print "ND lambda:", ND_lambda
ND, driverNodes = ECT.get_driver_nodes(G)
print "ND =", ND
degrees = []
betweenness = []
tot_degree = nx.degree_centrality(G)
tot_betweenness = nx.betweenness_centrality(G,weight=None)
for node in driverNodes:
degrees.append(tot_degree[node])
betweenness.append(tot_betweenness[node])
with open("results/driver_degree_BA.txt", "w") as f:
for x in degrees:
print >> f, x
with open("results/driver_betweenness_BA.txt", "w") as f:
for x in betweenness:
print >> f, x
with open("results/tot_degree_BA.txt", "w") as f:
for key, value in tot_degree.iteritems():
print >> f, value
with open("results/tot_betweenness_BA.txt", "w") as f:
for key, value in tot_betweenness.iteritems():
print >> f, value
示例15: createGraphsAndCommunities
def createGraphsAndCommunities():
g = nx.scale_free_graph(500, alpha=0.40, beta=0.40, gamma=0.20)
g1 = nx.powerlaw_cluster_graph(500, 10, 0.2)
g2 = nx.barabasi_albert_graph(500, 10)
g3 = nx.newman_watts_strogatz_graph(500, 10, 0.2)
nx.write_graphml (g, direc+"sfg.graphml")
nx.write_graphml(g1, direc+"pcg.graphml")
nx.write_graphml(g2, direc+"bag.graphml")
nx.write_graphml(g3, direc+"nwsg.graphml")
graphs = {}
graphs["sfg"] = graph_tool.load_graph(direc+"sfg.graphml")
graphs["pcg"] = graph_tool.load_graph(direc+"pcg.graphml")
graphs["bag"] = graph_tool.load_graph(direc+"bag.graphml")
graphs["nwsg"] = graph_tool.load_graph(direc+"nwsg.graphml")
graphs["price"] = graph_tool.generation.price_network(1000)
for i,h in graphs.iteritems():
s = graph_tool.community.minimize_blockmodel_dl(h)
b = s.b
graph_tool.draw.graph_draw(h, vertex_fill_color=b, vertex_shape=b, output=direc+"block"+str(i)+".pdf")
com = graph_tool.community.community_structure(h, 10000, 20)
graph_tool.draw.graph_draw(h, vertex_fill_color=com, vertex_shape=com, output=direc+"community"+str(i)+".pdf")
state = graph_tool.community.minimize_nested_blockmodel_dl(h)
graph_tool.draw.draw_hierarchy(state, output=direc+"nestedblock"+str(i)+".pdf")
pagerank = graph_tool.centrality.pagerank(h)
graph_tool.draw.graph_draw(h, vertex_fill_color=pagerank, vertex_size = graph_tool.draw.prop_to_size(pagerank, mi=5, ma=15), vorder=pagerank, output=direc+"pagerank"+str(i)+".pdf")
h.set_reversed(is_reversed=True)
pagerank = graph_tool.centrality.pagerank(h)
graph_tool.draw.graph_draw(h, vertex_fill_color=pagerank, vertex_size = graph_tool.draw.prop_to_size(pagerank, mi=5, ma=15), vorder=pagerank, output=direc+"reversed_pagerank"+str(i)+".pdf")