def smallWorldness(graph):
	return_values = []
	#Small-worldness criteria
	n = len(nx.nodes(graph))
	e = len(nx.edges(graph))
	#probability of edges: (number of edges in real graph)/possible edges
	p = e/float((n*(n-1)/2.0))	
	##
	#generate random graph using probability
	rand_graph = nx.fast_gnp_random_graph(n, p, seed=1)
	#calculate values for real graph and random graph
	Creal = nx.transitivity(graph) #float
	Crand = nx.transitivity(rand_graph) #float
	Lreal = 0
	Lrand = 0
	real_sum = 0
	rand_sum = 0
	splReal = shortest_path_lengths(graph)
	splRand = shortest_path_lengths(rand_graph)
	for i in range(len(splReal)):
		real_sum += splReal[i]
		rand_sum += splRand[i]
	Lreal = real_sum / len(splReal)
	Lrand = rand_sum / len(splRand)		
	#compare with actual graph
	if(Lreal != 0 and Lrand !=0 and Crand !=0):
		S = (Creal)/(Crand) / (float(Lreal)/(Lrand))
	else:
		S = 0
	return_values.append(S)
	return return_values
Ejemplo n.º 2
0
def go():
    """
    Run the IterF algorithm on some random graphs.
    """
    l = 9
    n = 2**l
    p = 3*math.log(n)/n

    for i in range(100):
        # Generate a random graph:
        g = nx.fast_gnp_random_graph(n,p)
        # Build AlgState from the graph:
        algs = AlgState(g)
        # Run the IterF algorithm until we reach a stationary state:
        algs.run_until_stat()

        # Print the properties of the resulting state:
        print('next_node Injective: {} | '
              'One round cycles: {} | '
              'Is only one cycle: {}'.\
                      format(\
                algs.is_next_node_injection(),\
                algs.is_all_cycles_one_round(),\
                algs.is_only_one_cycle())\
                )
Ejemplo n.º 3
0
def test_edge_cutset_random_graphs():
    for i in range(5):
        G = nx.fast_gnp_random_graph(50,0.2)
        cutset = nx.minimum_edge_cut(G)
        assert_equal(nx.edge_connectivity(G), len(cutset))
        G.remove_edges_from(cutset)
        assert_false(nx.is_connected(G))
Ejemplo n.º 4
0
def generate_cluster_graph(n,m,in_p,out_p):
	'''Generates graph with 'n' nodes with form m clustures,
	with average in_p within cluster and 'out_degree' between clustures'''
	print "Generating G..."
	if m == 0 or n == 0:
		raise "n or m can not be 0"

	nodes_per_clusture = n/m
	num_of_outer_nodes = math.ceil(nodes_per_clusture * out_p)
	larger_graph = nx.Graph()
	print "\tExpected communities:",m
	print "\tnodes_per_clusture:",nodes_per_clusture,"\n\tnum_of_outer_nodes:",num_of_outer_nodes
	for i in xrange(m):
		# print 'clusture_id',i
		G = nx.fast_gnp_random_graph(nodes_per_clusture,in_p)
		for node in G.nodes():
			larger_graph.add_node((node)+nodes_per_clusture*i)
		for edge in G.edges():
			larger_graph.add_edge((edge[0])+nodes_per_clusture*i,(edge[1])+nodes_per_clusture*i)
		
		chosen_nodes = np.random.choice(G.nodes(),num_of_outer_nodes)
		for node in chosen_nodes:
			node_for_large_graph = node+nodes_per_clusture*i
			larger_graph.add_edge(node_for_large_graph,np.random.choice(larger_graph.nodes()))
	# print larger_graph.nodes()
	# print larger_graph.edges()
	return larger_graph
def main():
    args = parse_arguments()
    # Generate graph for given parameters

    if args.cycle:
        graph = networkx.cycle_graph(args.vertices)
        graph = networkx.path_graph(args.vertices)
    elif args.star:
        graph = networkx.star_graph(args.vertices)
    elif args.wheel:
        graph = networkx.wheel_graph(args.vertices)
    elif args.ladder:
        graph = networkx.ladder_graph(args.vertices)
    elif args.fill_rate:
        if args.fill_rate > 50.0:
            graph = networkx.gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed)
        else:
            graph = networkx.fast_gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed)
    else:
        graph = networkx.gnm_random_graph(args.vertices, args.edges, None, args.directed)

    # Print generated graph
    print("{} {}".format(graph.number_of_nodes(), graph.number_of_edges()))
    for edge in graph.edges():
        print("{} {}".format(edge[0] + 1, edge[1] + 1))

    # Export generated graph to .png
    if args.image_path:
        export_to_png(graph, args.image_path)
def get_random_weighted_graph(n, p=0.5, max_weight=10):
	print "n=%d, p=%f, max_weight=%d" % (n, p, max_weight)
	G = nx.fast_gnp_random_graph(n, p)
	for e in G.edges():
		G[e[0]][e[1]]['weight'] = random.randint(1, max_weight)
	# print list(G.edges(data='weight', default=1))
	return G
Ejemplo n.º 7
0
def test(test_functions,V,p):
    print V
    G = nx.fast_gnp_random_graph(V,p)
    for f in test_functions:
        time,runtime = f(G)
        fp = open(f.__name__+".res","a")
        fp.write("%i,%f,%f\n" % (V,time,runtime))
Ejemplo n.º 8
0
def main():
	import networkx as nx
	from complex_systems.pgg import PublicGoodGames
	import pylab as plt
	import numpy as np
	
	nb_node = 1000
	edge_prob = 10.0/nb_node
	coop_ratio = 0.5
	synergy = 8
	nb_round = 100
	nb_game_per_round = 10
	nb_def = []
	nb_coop = []
	
	# Generate a Random Graph 
	G = nx.fast_gnp_random_graph(nb_node, edge_prob)
	# initialize the game 
	PGG = PublicGoodGames(G=G, synergy=synergy,nb_simulation_step=nb_game_per_round, cooperator_ratio=coop_ratio)
	for i in range(nb_round):
		PGG.run_game()
		nb_def.append(PGG.defector_counter())
		nb_coop.append(PGG.cooperator_counter())
		#print nb_coop, nb_def
	plt.figure()
	plt.plot(nb_def,'b-*')
	plt.plot(nb_coop,'r-*')
	plt.figure()
	print np.mean([val for key, val in G.degree().iteritems()])
	nx.draw_networkx(G, node_size=20, with_labels = False)
	plt.show()
def gen_gnp_graph(i):
    """
    Generate a gnp random graph with 2**i nodes.
    """
    n = 2**i
    p = 2*i / (2**i)
    return nx.fast_gnp_random_graph(n,p)
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
 def test__init__(self):
     from social_meaning.agent import Agent
     society = nx.watts_strogatz_graph(10, 2, 0)
     a = Agent(mental_graph=nx.fast_gnp_random_graph(10, .1),
               social_network=society,
               node_name=society.nodes()[0])
     repr(a)
def testSerialRandom():
    """ 50 Random serial test cases
    """

    N = 10
    p = .7
    runs = 0
    while runs < 50:

        # a random graph
        G = nx.fast_gnp_random_graph(N, p)
        try:
            nx.shortest_path(G, source=0, target=N-1)
        except:
            continue
        # convert to plain ndarray
        nw1 = nx2nw(G)

        # copy and join network
        nw2 = serialCopy(nw1)

        # compute effective resistance
        ER1 = ResNetwork(
            nw1, silence_level=3).effective_resistance(0, len(nw1)-1)
        ER2 = ResNetwork(
            nw2, silence_level=3).effective_resistance(0, len(nw2)-1)

        # increment runs
        runs += 1
        # assertion
        print (ER1*2-ER2)
        assert (ER1*2-ER2) < 1E-6
def getRandomPageRanks(filename):
	Ga=nx.read_graphml(sys.argv[1])

	# create a copy of the graph and extract giant component
	# get component size distribution
	cc=nx.connected_components(Ga)
	cc_dict={}
	for x in range(0,len(cc)):
		try:
			cc_dict[len(cc[x])].append(x)
		except KeyError:
			cc_dict[len(cc[x])]=[]
			cc_dict[len(cc[x])].append(x)

	isolates=nx.isolates(Ga)

	rg=nx.fast_gnp_random_graph(Ga.number_of_nodes(),2.0*Ga.number_of_edges()/(Ga.number_of_nodes()*(Ga.number_of_nodes()-1)))
	c_rg=nx.average_clustering(rg)
	rg_cc=nx.connected_component_subgraphs(rg)[0]
	rg_asp=nx.algorithms.shortest_paths.generic.average_shortest_path_length(rg_cc)

	p_rg=community.best_partition(rg_cc)
	m_rg=community.modularity(p_rg,rg_cc)

	pageranks = nx.pagerank_numpy(rg)
	return pageranks
Ejemplo n.º 14
0
def run_er_algo():
    """
    run homework
    """
    nodes = 10000
    prob = 0.1

    # er_graph= er_algorithm(nodes, prob)

    time0 = time.time()
    G = nx.fast_gnp_random_graph(nodes, prob, directed=True)
    digraph = nx.to_dict_of_lists(G)
    time1 = time.time()
    print('NetworkX took {} second'.format(time1 - time0))

    time0 = time.time()
    digraph2 = er_algorithm(nodes, prob)
    time1 = time.time()
    print('Mine took {} second'.format(time1 - time0))

    norm_dist1 = normal_degree_distribution(digraph, 'in')
    norm_dist2 = normal_degree_distribution(digraph2, 'in')
    plt.plot(list(norm_dist1.keys()), list(norm_dist1.values()), 'o',
             list(norm_dist2.keys()), list(norm_dist2.values()), 'g^')



    plt.show()
Ejemplo n.º 15
0
def get_er_graph(n, p):
    """
    Function to get an ER graph
    :param n: number of nodes
    :param p: probability of connection between the nodes
    :return: ER graph
    """
    return nx.fast_gnp_random_graph(n, p)
Ejemplo n.º 16
0
def generate_ER_graph_with_trust(N, p, trust_list, filename):
    N_VALS = len(trust_list)
    G = nx.fast_gnp_random_graph(N, p)
    for (u,v) in G.edges_iter():
        val = random.randint(0,N_VALS-1)
        G.edge[u][v]['t'] = trust_list[val]
        
    nx.write_edgelist(G, filename, '#', '\t', True, 'utf-8')
Ejemplo n.º 17
0
def main():
    numTraders = int(raw_input("Enter the number of traders : "))
    numItems = int(raw_input("Enter the number of items : "))
    G = nx.fast_gnp_random_graph(numTraders, 0.5)
    nx.draw(G, with_labels = True)
    plt.show()
    gen_data(G, numItems)
    market(G)
Ejemplo n.º 18
0
def construct(G1,G2): #返回一个随机ER网络,G1为现实网络,G2为在线网络
	G1 = nx.fast_gnp_random_graph(nodeNumber, probDegree)
	G2 = nx.fast_gnp_random_graph(nodeNumber, probDegree)
	r = Random()	#随机数生成器
	#现实网络
	Y = []
	for edge in G1.edges():	#边赋予权值
		id1 = edge[0]
		id2 = edge[1]
		weight = r.gauss(0.15,0.05)
		G1.edge[id1][id2]['weight'] = weight
		weight = 1 if weight>1 else weight #边界检查
		weight = 0 if weight<0 else weight
		Y.append(weight)
	displayFigure(Y,'Real LT network\'s edges\'weight distribution')

	Y = []
	for node in G1.nodes(): #点赋予阈值
		threshold = r.gauss(0.31,0.1)
		threshold = 1 if threshold>1 else threshold #边界检查
		threshold = 0 if threshold<0 else threshold
		G1.node[node]['threshold'] = threshold
		Y.append(threshold)	
		G1.node[node]['active'] = False	#点初始为不激活
	displayFigure(Y,'Real LT network\'s node\'s threshold distribution')

	#在线网络
	Y = []	
	for edge in G2.edges():#每条边赋予激活概率
		id1 = edge[0]
		id2 = edge[1]
		prob = r.gauss(0.15,0.05)
		prob = 1 if prob>1 else prob #边界检查
		prob = 0 if prob<0 else prob
		G2.edge[id1][id2]['actProb'] = prob	#边的激活高斯分布
		Y.append(prob)

		G2[id1][id2]['unuse'] = True 	#初始化为未使用过 

	for node in G2.nodes():	
		G2.node[node]['active'] = False #点初始化为不激活
		G2.node[node]['selfProb'] = 1
	displayFigure(Y,'Online IC network\'s edge\'s activate probability distribution')

	return (G1,G2)
Ejemplo n.º 19
0
def test_ER_random_graph(N = 200, p = 0.2):
    
    G = nx.fast_gnp_random_graph(N, p)
    
    k = 1
    eig_vals, eig_vecs = compute_spectral_coordinate(G, k)
    
    rel_NR = graph_NR_relative(G, eig_vals, k)
    
    print "ER random graph, rel_NR =", rel_NR
Ejemplo n.º 20
0
	def gen_graph(self):
		if self.network_structure == 'small_world':
			nx_graph = nx.watts_strogatz_graph(self.num_nodes, self.graph_args['k'], self.graph_args['p'])
			return nx_graph, self.convert_nx_graph(nx_graph)
		elif self.network_structure == 'erdos_renyi':
			nx_graph = nx.fast_gnp_random_graph(self.num_nodes, self.graph_args['p'])
			return nx_graph, self.convert_nx_graph(nx_graph)
		elif self.network_structure == 'preferential_attachment':
			nx_graph = nx.barabasi_albert_graph(self.num_nodes, self.graph_args['m'])
			return nx_graph, self.convert_nx_graph(nx_graph)
Ejemplo n.º 21
0
def random_sdf_graph(n = 5, m = 15, sumrange = (2, 5), phaserange = (1, 3), wcetrange = (1, 1), seed = None):
    p = m / (n * (n - 1))
    g = nx.fast_gnp_random_graph(n, p, seed, directed = True)
    cycle = [scc.pop() for scc in nx.strongly_connected_components(g)]
    if len(cycle) > 1:
        g.add_edge( cycle[-1], cycle[0] )
        for i in range(1, len(cycle)):
            g.add_edge( cycle[i - 1], cycle[i] )

    return make_sdf_graph(g, sumrange, phaserange, wcetrange)
def main():
    G = nx.fast_gnp_random_graph(50, 0.05, 142443)
    pos = nx.spring_layout(G)
    path = nx.shortest_path(G, source=24, target=43)
    path_edges = list(zip(path, path[1:]))
    nx.draw_networkx(G, pos)
    nx.draw_networkx_nodes(G, pos, nodelist=path, node_color='g')
    nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color='g', width=10)
    plt.axis('off')
    plt.show()
Ejemplo n.º 23
0
def gc(N,p):                                # generate cluster for N nodes
    h = nx.fast_gnp_random_graph(N, p)      # with probability p
    cluster = nx.connected_components(h)
    lc = len(cluster[0])                    # size of largest cluster
    k = N * p                               # average connectivity as on p.14
    mc = 0.                                 # initialize mean cluster
    if len(cluster) > 1:
      for i in range(len(cluster)-1):
        mc += len(cluster[i+1])             # accumulate cluster sizes
      mc = mc*1./(len(cluster)-1)           # and normalize
    return lc, mc
Ejemplo n.º 24
0
def test_edge_cutset_random_graphs():
    for i in range(5):
        G = nx.fast_gnp_random_graph(50,0.2)
        if not nx.is_connected(G):
            ccs = iter(nx.connected_components(G))
            start = next(ccs)[0]
            G.add_edges_from( (start,c[0]) for c in ccs )
        cutset = nx.minimum_edge_cut(G)
        assert_equal(nx.edge_connectivity(G), len(cutset))
        G.remove_edges_from(cutset)
        assert_false(nx.is_connected(G))
Ejemplo n.º 25
0
def test_edge_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = arbitrary_element(next(ccs))
                G.add_edges_from((start, arbitrary_element(c)) for c in ccs)
            cutset = nx.minimum_edge_cut(G, flow_func=flow_func)
            assert_equal(nx.edge_connectivity(G), len(cutset), msg=msg.format(flow_func.__name__))
            G.remove_edges_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__))
Ejemplo n.º 26
0
    def test_random_graph(self):
        g = nx.fast_gnp_random_graph(10, 0.5)
        nx.set_node_attributes(g, 'infected', {n: False for n in g.nodes()})
        g.node[1]['infected'] = True
        g.node[2]['infected'] = True
        g.node[3]['infected'] = True
        g.node[4]['infected'] = True

        # FIXME Cannot assert anything because graph is random !
        sz = AlgorithmSZ()
        source_estimation = sz.run(g, v=4)
        print("Source of rumor is %s" % source_estimation)
Ejemplo n.º 27
0
    def __init__(self, N, k, i, steps):
        self.k = k
        self.N = N
        self.i = i
        self.graph = nx.fast_gnp_random_graph(N, k / N)
        # set infected array, infected =1, not infected = 2
        self.infected = self.intializeInfected()

        # Create the prevalence array and set the first step
        self.prevalence = [0] * steps
        self.prevalence[0] = sum(self.infected) / (N * 1.0)
        self.currentStep = 1
Ejemplo n.º 28
0
	def __init__(self, N, k, i, steps):
		self.N = N
		self.i = i
		self.k = k
		self.currentStep = 1
		self.graph = nx.fast_gnp_random_graph(N, k / N)

		# set infected array, infected =1, not infected = 2
		self.infected = self.intializeInfected()

		# set the first step of the new infected list
		self.newInfected = [0] * steps
		self.newInfected[0] = 0
Ejemplo n.º 29
0
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100,0.0575)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph."
                raise Exception(msg % max_attempts)
            else:
                attempts += 1
Ejemplo n.º 30
0
def profile_d():
    d_vs_t = [[], []]
    print 'Timing graphpca(G, d) on Erdos-Renyi Graph nx.fast_gnp_random_graph(1000, 0.02)'
    print '\t'.join(('d', 't (ms)'))
    g = nx.fast_gnp_random_graph(1000, 0.02)
    for d in range(1, 950, 30):
        tic = timeit.default_timer()
        graphpca.reduce_graph(g, d)
        toc = timeit.default_timer()
        print '\t'.join((str(d), str((toc - tic) * 1000)))
        d_vs_t[0].append(d)
        d_vs_t[1].append(toc - tic)
    return d_vs_t
Ejemplo n.º 31
0
topology = iu.module_from_spec(spec)
spec.loader.exec_module(topology)

import networkx as nx
import numpy as np
import os
from subprocess import call
from tempfile import mktemp
from scipy.io import savemat, loadmat
from scipy.sparse import csc_matrix

### MEAT ----- #

### Graph to test implementations

G = nx.fast_gnp_random_graph(30, 0.4)

### Compute the local candidate

bc = topology.betti(nx.find_cliques(G))

print("Candidate:", bc)

### Invoke MATLAB for reference

M = csc_matrix(nx.adjacency_matrix(G), dtype='d')

filename = mktemp(".mat")
#filename = "./tmp.mat"
savemat(filename, {'G': M})
Ejemplo n.º 32
0
print "Pearson correlation coefficient ", pearsonr(deg_data, eig_data)

# Plot correlation between degree and eigenvector centrality
plt.figure(6)
plt.plot(deg_data, eig_data, 'ro')
plt.xlabel('Degree centrality')
plt.ylabel('Eigenvector centrality')
plt.draw()
if doPrint:
    plt.savefig("deg_eig_correlation.pdf")

#-----------------------------------------------------------------------------
# 6:
# Generate a random graph with 200 nodes
R = nx.fast_gnp_random_graph(200, 0.1)

print 'Number of nodes:', R.number_of_nodes()
print 'Number of edges:', R.number_of_edges()
print 'Number of connected components:', nx.number_connected_components(R)

# Connected components
GCC = list(nx.connected_component_subgraphs(R))[0]

# Fraction of nodes and edges in GCC
print "Fraction of nodes in GCC: ", GCC.number_of_nodes() / R.number_of_nodes()
print "Fraction of edges in GCC: ", GCC.number_of_edges() / R.number_of_edges()

degree_sequence_random = R.degree().values()
print "Min degree ", np.min(degree_sequence_random)
print "Max degree ", np.max(degree_sequence_random)
Ejemplo n.º 33
0
import networkx as nx
from node2vec import Node2Vec

# Create a graph 这里可以给出自己的graph
graph = nx.fast_gnp_random_graph(n=100, p=0.5)

# Precompute probabilities and generate walks - **ON WINDOWS ONLY WORKS WITH workers=1**
node2vec = Node2Vec(graph,
                    dimensions=64,
                    walk_length=30,
                    num_walks=200,
                    workers=4)  # Use temp_folder for big graphs

# Embed nodes
model = node2vec.fit(
    window=10, min_count=1, batch_words=4
)  # Any keywords acceptable by gensim.Word2Vec can be passed, `diemnsions` and `workers` are automatically passed (from the Node2Vec constructor)

# Look for most similar nodes
model.wv.most_similar('2')  # Output node names are always strings

model.wv.save_word2vec_format(EMBEDDING_FILENAME)

# Save model for later use
model.save(EMBEDDING_MODEL_FILENAME)

# Embed edges using Hadamard method
from node2vec.edges import HadamardEmbedder

edges_embs = HadamardEmbedder(keyed_vectors=model.wv)
Ejemplo n.º 34
0
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import random

M = 6 # number of arms

# SET GRAPH TYPE BELOW #

#G = nx.DiGraph() # directed_rooted.png from this
#G.add_nodes_from([0, 1, 2, 3, 4, 5])
#G.add_edges_from([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5),
#                 (0, 1), (1, 2), (1, 3), (2, 4), (3, 5), (5, 2)])

G = nx.fast_gnp_random_graph(6, 0.6, seed=1,directed=True) # directed_strongly_connected.png from this
print(nx.is_strongly_connected(G)) # check directed_strongly_connected.png with this

#G = nx.fast_gnp_random_graph(6, 0.4, seed=1,directed=True) # directed_weakly_connected.png from this
#print(nx.is_weakly_connected(G)) # check directed_weakly_connected.png with this
#print(nx.is_strongly_connected(G)) # and this

#G = nx.fast_gnp_random_graph(6, 0.5, seed=40,directed=False) # test.png from this
#G = nx.fast_gnp_random_graph(5, 0.25, seed=42,directed=False) #undirected_unconnected.png from this

#G = nx.Graph() # graph for single agent
#G.add_nodes_from([0]) # for single agent

#G = nx.complete_graph(6)

# SET GRAPH TYPE ABOVE #
Ejemplo n.º 35
0
 def create_er_graph(self):
     self.er_prob = 0.2
     self.er_graph = nx.fast_gnp_random_graph(self.num_vertices,
                                              self.er_prob)
     self.er_normL = nx.normalized_laplacian_matrix(self.er_graph)
     return
Ejemplo n.º 36
0
def make_specific_dataset():
    ''' Creates a dataset of 5200 graphs, with 25 different class labels and no node attributes or node labels.
    The class labels are the number of triangles the graph has, and the graphs are randomly generated. The number of 
    triangles is calculated via a NetworkX function that determines the number of 3-cliques the graph has.
    Each graph has between 5 and 70 nodes, and a fixed edge probability of 20%. This is to prevent extremly long
    calculation times, as we do need a NP-calculation. So we try to keep the amount of edges lower than completly random.
    One can however pick the edge probability p at random aswell.
    '''
    arbitrary_graphs = []
    for _ in trange(1, file=sys.stdout,
                    desc='Outer Loop'):  # Calculate 200 graphs per class
        for desired_triangle_number in trange(26,
                                              file=sys.stdout,
                                              desc='TriangleNumber'):
            #we have 26 classes: Each graph has between 0 and 25 triangles in it. The loop will
            #desired_triangle_number is the number of triangles we want to produce in our current graph

            #Roll a random graph
            n = np.random.choice(np.arange(71)[5:],
                                 1)[0]  #number of nodes between 5 and 70
            G = nx.fast_gnp_random_graph(
                n, 0.2)  #Random graph with n nodes and edge probability 0.2

            #Calculate the number of triangles
            list_of_triangles = [
                x for x in (list(nx.find_cliques(G))) if len(x) == 3
            ]
            number_of_triangles = len(list_of_triangles)
            #Set the graph label accordingly to the number of triangles it has
            G.graph['label'] = number_of_triangles

            while (number_of_triangles != desired_triangle_number):
                #Reroll until we have the desired amount of triangles in our graph

                #Attempt to free memory
                del G
                del list_of_triangles

                n = np.random.choice(np.arange(101)[5:],
                                     1)[0]  #number of nodes between 5 and 100
                #p = np.random.random_sample() #probability of edges in the random graph can be rolled randomly instead

                G = nx.fast_gnp_random_graph(n, 0.2)
                list_of_triangles = [
                    x for x in (list(nx.find_cliques(G))) if len(x) == 3
                ]
                number_of_triangles = len(list_of_triangles)
                G.graph['label'] = number_of_triangles

            arbitrary_graphs.append(
                G)  #memorize the graph if it has the right amount of triangles

    out_dir = r"C:\Users\Dips\Documents\Praktikum\group1\exercise4\datasets"

    #Save dataset
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    outfile = os.path.join(out_dir, 'test')
    export_dataset(outfile,
                   arbitrary_graphs,
                   has_g_labels=True,
                   has_n_labels=False,
                   has_n_attributes=False)
Ejemplo n.º 37
0
graph.addVertex({'name': 'v2'})
graph.addVertex({'name': 'v3'})

graph.addEdge(0, 1)
graph.addEdge(0, 2)
graph.addEdge(1, 2)

print(graph)


# NetworkX conversion
from networkx import fast_gnp_random_graph, draw
prob_edge = 0.5
n_nodes = 8
# Create a random networkx graph
networkx_graph = fast_gnp_random_graph(n_nodes, prob_edge)

# Convert to XACC graph:
xacc_graph = xacc.getGraph("boost-digraph")
# Add nodes
for node in networkx_graph.nodes:
    xacc_graph.addVertex({'name': str(node)})
# Add edges
for (from_node, to_node) in networkx_graph.edges:
    xacc_graph.addEdge(from_node, to_node)

print(xacc_graph)
# Plot the networkx to check.
draw(networkx_graph, with_labels=True)
import matplotlib.pyplot as plt
plt.savefig("graph.png")
Ejemplo n.º 38
0
 def create_random_graph(self):
     # Create a graph
     self.G = nx.fast_gnp_random_graph(n=100, p=0.5)
Ejemplo n.º 39
0
 def test_equitable_color(self):
     G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42)
     coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
     assert is_equitable(G, coloring)
Ejemplo n.º 40
0
filepath = 'data/realexptimetrackinfectednorewire.csv'
r = 4
mu = 5
p = mu / n
lambd = 2
rho = 0
niv = []
nivcount = 1
newmu = 0
while (r / n < .2):
    counter = 0
    infected = []
    susceptible = []
    unexplored = []
    si = []
    G = nx.fast_gnp_random_graph(n,
                                 p)  #set up the er graph and infect patient 0
    writefile = open(filepath, 'w')
    writefile.write('n,p,lambda,rho,s,i,r,t,mu,newmu\n')
    writefile.close()
    t = 0
    r = 0
    i = 1
    s = n - 1
    for j in range(len(G.nodes)):
        G.nodes[j]['state'] = 's'
    G.nodes[0]['state'] = 'i'
    infected = [0]
    susceptible = list(range(1, n))
    """
        for i in susceptible:
                unex = 1
Ejemplo n.º 41
0
    def test(self):
        self.config.save_dir = self.test_conf.test_model_dir

        ### Compute Erdos-Renyi baseline
        if self.config.test.is_test_ER:
            p_ER = sum([
                aa.number_of_edges() for aa in self.graphs_train
            ]) / sum([aa.number_of_nodes()**2 for aa in self.graphs_train])
            graphs_gen = [
                nx.fast_gnp_random_graph(self.max_num_nodes, p_ER, seed=ii)
                for ii in range(self.num_test_gen)
            ]
        else:
            ### load model
            model = eval(self.model_conf.name)(self.config)
            model_file = os.path.join(self.config.save_dir,
                                      self.test_conf.test_model_name)
            load_model(model, model_file, self.device)

            if self.use_gpu:
                model = nn.DataParallel(model,
                                        device_ids=self.gpus).to(self.device)

            model.eval()

            ### Generate Graphs
            A_pred = []
            num_nodes_pred = []
            num_test_batch = int(
                np.ceil(self.num_test_gen / self.test_conf.batch_size))

            gen_run_time = []
            for ii in tqdm(range(num_test_batch)):
                with torch.no_grad():
                    start_time = time.time()
                    input_dict = {}
                    input_dict['is_sampling'] = True
                    input_dict['batch_size'] = self.test_conf.batch_size
                    input_dict['num_nodes_pmf'] = self.num_nodes_pmf_train
                    A_tmp = model(input_dict)
                    gen_run_time += [time.time() - start_time]
                    A_pred += [aa.data.cpu().numpy() for aa in A_tmp]
                    num_nodes_pred += [aa.shape[0] for aa in A_tmp]

            logger.info('Average test time per mini-batch = {}'.format(
                np.mean(gen_run_time)))

            graphs_gen = [get_graph(aa) for aa in A_pred]

        ### Visualize Generated Graphs
        if self.is_vis:
            num_col = self.vis_num_row
            num_row = int(np.ceil(self.num_vis / num_col))
            test_epoch = self.test_conf.test_model_name
            test_epoch = test_epoch[test_epoch.rfind('_') +
                                    1:test_epoch.find('.pth')]
            save_name = os.path.join(
                self.config.save_dir,
                '{}_gen_graphs_epoch_{}_block_{}_stride_{}.png'.format(
                    self.config.test.test_model_name[:-4], test_epoch,
                    self.block_size, self.stride))

            # remove isolated nodes for better visulization
            graphs_pred_vis = [
                copy.deepcopy(gg) for gg in graphs_gen[:self.num_vis]
            ]

            if self.better_vis:
                for gg in graphs_pred_vis:
                    gg.remove_nodes_from(list(nx.isolates(gg)))

            # display the largest connected component for better visualization
            vis_graphs = []
            for gg in graphs_pred_vis:
                CGs = [gg.subgraph(c) for c in nx.connected_components(gg)]
                CGs = sorted(CGs,
                             key=lambda x: x.number_of_nodes(),
                             reverse=True)
                vis_graphs += [CGs[0]]

            if self.is_single_plot:
                draw_graph_list(vis_graphs,
                                num_row,
                                num_col,
                                fname=save_name,
                                layout='spring')
            else:
                draw_graph_list_separate(vis_graphs,
                                         fname=save_name[:-4],
                                         is_single=True,
                                         layout='spring')

            save_name = os.path.join(self.config.save_dir, 'train_graphs.png')

            if self.is_single_plot:
                to_visualize = []
                to_visualize.extend(self.graphs_train[:self.num_vis])
                to_visualize.extend(self.graphs_train[-self.num_vis:])
                draw_graph_list(to_visualize,
                                num_row,
                                num_col,
                                fname=save_name,
                                layout='spring')
            else:
                to_visualize = []
                to_visualize.extend(self.graphs_train[:self.num_vis])
                to_visualize.extend(self.graphs_train[-self.num_vis:])
                draw_graph_list_separate(to_visualize,
                                         fname=save_name[:-4],
                                         is_single=True,
                                         layout='spring')

        ### Evaluation
        if self.config.dataset.name in ['lobster']:
            acc = eval_acc_lobster_graph(graphs_gen)
            logger.info(
                'Validity accuracy of generated graphs = {}'.format(acc))

        num_nodes_gen = [len(aa) for aa in graphs_gen]

        # Compared with Validation Set
        num_nodes_dev = [len(gg.nodes)
                         for gg in self.graphs_dev]  # shape B X 1
        mmd_degree_dev, mmd_clustering_dev, mmd_4orbits_dev, mmd_spectral_dev = evaluate(
            self.graphs_dev, graphs_gen, degree_only=False)
        mmd_num_nodes_dev = compute_mmd([np.bincount(num_nodes_dev)],
                                        [np.bincount(num_nodes_gen)],
                                        kernel=gaussian_emd)

        # Compared with Test Set
        num_nodes_test = [len(gg.nodes)
                          for gg in self.graphs_test]  # shape B X 1
        mmd_degree_test, mmd_clustering_test, mmd_4orbits_test, mmd_spectral_test = evaluate(
            self.graphs_test, graphs_gen, degree_only=False)
        mmd_num_nodes_test = compute_mmd([np.bincount(num_nodes_test)],
                                         [np.bincount(num_nodes_gen)],
                                         kernel=gaussian_emd)

        logger.info(
            "Validation MMD scores of #nodes/degree/clustering/4orbits/spectral are = {}/{}/{}/{}/{}"
            .format(mmd_num_nodes_dev, mmd_degree_dev, mmd_clustering_dev,
                    mmd_4orbits_dev, mmd_spectral_dev))
        logger.info(
            "Test MMD scores of #nodes/degree/clustering/4orbits/spectral are = {}/{}/{}/{}/{}"
            .format(mmd_num_nodes_test, mmd_degree_test, mmd_clustering_test,
                    mmd_4orbits_test, mmd_spectral_test))

        if self.config.dataset.name in ['lobster']:
            return mmd_degree_dev, mmd_clustering_dev, mmd_4orbits_dev, mmd_spectral_dev, mmd_degree_test, mmd_clustering_test, mmd_4orbits_test, mmd_spectral_test, acc
        else:
            return mmd_degree_dev, mmd_clustering_dev, mmd_4orbits_dev, mmd_spectral_dev, mmd_degree_test, mmd_clustering_test, mmd_4orbits_test, mmd_spectral_test
Ejemplo n.º 42
0
def end_to_end(release_number,
               number_infected_before_release,
               stop_inflow_at_intervention,
               background_inmate_turnover=20,
               death_rate=0.012,
               tau=0.03,
               gamma=0.07,
               rho=0.0003,
               max_time=60,
               N=3000,
               p=0.02,
               percent_infected=0.0035,
               percent_recovered=0.0015,
               save_plot=False,
               title='',
               social_distance=False,
               social_distance_tau=0.01,
               custom_graph=None,
               initial_infected_list=None):
    """Runs end-to-end simulation and plots results.

    Args:
        background_inmate_turnover: background # of inmates added/released at each time step
        release_number: # of inmates to release
        number_infected_before_release: number of infected at which to perform release on next integer time
        death_rate: probability of dying after being infected
        tau: transmission rate
        gamma: recovery rate
        rho: percent of inmates that are initially infected
        max_time: # of time steps to run simulation
        N: # of inmates initially
        p: probability of contact between inmate and other inmates
        percent_infected: percent of general population that is infected
        percent_recovered: percent of general population that is recovered
        save_plot: should plot of results be saved to computer?
        stop_inflow_at_intervention: should we stop the background inflow of inmates at intervention time?
        title: title of plot
        social_distance: boolean flag, if we lower transmission rate after major release
        social_distance_tau: new transmission rate after major release
        custom_graph: If custom_graph passed, uses custom_graph. Otherwise, creates graph from N and p
        initial_infected_list: sets node numbers of initial infected. If not passed, rho is used

    Returns:
        t: array of times at which events occur
        S: # of susceptible inmates at each time
        I: # of infected inmates at each time
        R: # of recovered inmates at each time
        D: # of dead inmates at each time step
    """
    # Save parameters
    parameters_dict = locals()

    # Use custom_graph if passed
    if custom_graph is not None:
        G = custom_graph.copy()
    else:  # Build new graph
        G = nx.fast_gnp_random_graph(N, p)

    # Run simulation
    t, S, I, R, D = simulation(G, tau, gamma, rho, max_time,
                               number_infected_before_release, release_number,
                               background_inmate_turnover,
                               stop_inflow_at_intervention, p, death_rate,
                               percent_infected, percent_recovered,
                               social_distance, social_distance_tau,
                               initial_infected_list)

    # Print summary of results
    summary(t, S, I, R, D, save_plot, title, parameters_dict)

    return t, S, I, R, D
Ejemplo n.º 43
0
"""

import sys

import networkx as nx

from vispy import app, scene
from vispy.visuals.graphs import layouts

canvas = scene.SceneCanvas(title='Simple NetworkX Graph',
                           size=(600, 600),
                           bgcolor='white',
                           show=True)
view = canvas.central_widget.add_view('panzoom')

graph = nx.adjacency_matrix(nx.fast_gnp_random_graph(500, 0.005,
                                                     directed=True))
layout = layouts.get_layout('force_directed', iterations=100)

visual = scene.visuals.Graph(graph,
                             layout=layout,
                             line_color='black',
                             arrow_type="stealth",
                             arrow_size=30,
                             node_symbol="disc",
                             node_size=20,
                             face_color=(1, 0, 0, 0.2),
                             border_width=0.0,
                             animate=True,
                             directed=False,
                             parent=view.scene)
    write_log("Formatting {}".format(filename))

    f = open(filename, 'w+')
    for e in values:
        f.write('{}\n'.format(e))


DIM = 10**5
write_log("DIM = {}".format(DIM))

PERC_SPARSE = 0.000003
write_log("PERC_SPARSE = {}% => expecting {} elements per column".format(
    str((1 - PERC_SPARSE) * 100), DIM * PERC_SPARSE))

write_log("Generating graph...")
g = nx.fast_gnp_random_graph(DIM, PERC_SPARSE, directed=True)

# The following line is used for testing with parra's matrix
#g = nx.from_numpy_matrix(np.matrix(m), create_using=nx.DiGraph)

write_log("Computing pagerank... alpha=0.85, max_iter=200, tol=1e-12", endl='')
start = time()

pr = nx.pagerank_scipy(g, alpha=0.85, max_iter=200, tol=1e-12)

write_log("DONE [{}s]".format(time() - start))

write_log("Sorting and dumping pr values...", endl='')
start = time()

pr_sorted = sorted(pr.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
Ejemplo n.º 45
0
def test_disconnected_graph():
    G = nx.fast_gnp_random_graph(100, 0.01, seed=42)
    cuts = nx.all_node_cuts(G)
    pytest.raises(nx.NetworkXError, next, cuts)
Ejemplo n.º 46
0
import random
from collections import defaultdict
import time

import matplotlib.pyplot as plt
import networkx as nx
from tqdm import tqdm

from clique import clique_finder_rand

n_nodes = 10000
max_deg = 9000

# print("building graph")
# graph = {i: random.sample(set(list(range(n_nodes))) - {i}, random.randint(1, max_deg)) for i in range(n_nodes)}
graph = nx.fast_gnp_random_graph(1000, 0.8)
# graph = pickle.load(open("graph.pickle", "rb"))
# print("graph built")


def animate(i):
    graph_data = open('data.txt', 'r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(float(x))
            ys.append(float(y))
    ax1.clear()
Ejemplo n.º 47
0
 def test_add_node_to_sub_graph(self):
     G = HeGraph()
     sub_graph = nx.fast_gnp_random_graph(3, 3)
     G.add_graph(sub_graph)
     G.add_node_to_sub_graph(0, 4)
     self.assertEqual(4, len(sub_graph.nodes()))
Ejemplo n.º 48
0
#!/usr/bin/env python2
import networkx as nx

nodes = [70, 100, 500, 1000, 4000, 6000, 10000, 100000]

z_deg = 13
for n in nodes:
    p = 1.0 * z_deg / (n - 1)
    G = nx.fast_gnp_random_graph(n, p, seed=123)
    print p, n
    print nx.is_connected(G)

# Z average degree
#G = fast_gnp_random_graph(n, p, seed=123)
#average_shortest_path_length(G, weight=None)
# Check if the graph is complete

# watts_strogatz_graph(n, k, p, seed=None)
# k = 4
# n = constant
# change p paramater [0.0001 to 1]
# Averagre shortest path
# Average Clustering coefficient

# Many the avg_cluster, shortest path

#G = nx.erdos_renyi_graph(n, p, seed=123)
#  O(n^2)
# z_deg = (n - 1) * p
Ejemplo n.º 49
0
 def test_equitable_color_large(self):
     G = nx.fast_gnp_random_graph(100, 0.1, seed=42)
     coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
     assert is_equitable(G, coloring, num_colors=max_degree(G) + 1)
Ejemplo n.º 50
0
import networkx as nx
import random

#generate random graph
#p = 5%
G = nx.fast_gnp_random_graph(10000, 0.05)

#assign random weight to each edge
for (u, v) in G.edges():
    G.edges[u, v]['weight'] = random.randint(1, 100)

#write graph to file
nx.write_weighted_edgelist(G, "random_graph.edgelist")
Ejemplo n.º 51
0
# "angeliya c.u" <*****@*****.**>, "priodyuti pradhan" <*****@*****.**>
# Complex Systems Lab, Indian Institute of Technology Indore 

#---------modelling network------------ 
n = 100 # Number of nodes
c = 3    # average degree of the random subgraph
deg = []
hub = {}
lst = []

p = c/float(n-1)   
print 'connection probability: ', p

flag = True
while flag:
  gnp = nx.fast_gnp_random_graph(n,p)
  if nx.is_connected(gnp):
     flag = False 
  
print 'Number of nodes: ',n
print 'Number of edges: ', len(gnp.edges())
print 'Check for connectedness: ',nx.is_connected(gnp)
A = nx.to_scipy_sparse_matrix(gnp,nodelist=None,dtype=np.float32,format='lil')
d = A.sum(axis=1)
avg_deg = sum(d)/n
print 'avg deg: ' ,avg_deg[0,0] 

#-------for loop for iterating d---------

fd = open('hub-deg_vs_ipr.txt','w')
Ejemplo n.º 52
0
def main(args):

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(asctime)s %(levelname)-8s [%(name)s]  %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S")

    LOG = logging.getLogger('MAIN')
    LOG_STATS = logging.getLogger('STAT')

    LOG.info('Loading graph \'%s\'...' % args.graph)
    start = timer()
    if args.graph == 'example1':
        G = nx.Graph()
        G.add_nodes_from(range(0, 6))
        G.add_edges_from([(0, 3), (0, 4), (0, 5), (1, 2), (1, 4), (1, 5),
                          (2, 5), (3, 4)])
    elif args.graph == 'example2':
        G = nx.Graph()
        G.add_nodes_from(range(0, 5))
        G.add_edges_from([(0, 3), (2, 1), (2, 4), (3, 2)])
    elif '.xsc' in args.graph:
        G = nx.Graph()
        input_iter = io.read_xsc_graph(args.graph)
        for edge in input_iter:
            [u, v] = edge
            if not G.has_node(u):
                G.add_node(u)
            if not G.has_node(v):
                G.add_node(v)
            G.add_edge(u, v)

    elif '.txt' in args.graph:
        G = nx.Graph()
        input_iter = io.read_txt_graph(args.graph)
        for edge in input_iter:
            [u, v] = edge
            if not G.has_node(u):
                G.add_node(u)
            if not G.has_node(v):
                G.add_node(v)
            G.add_edge(u, v)
    else:
        G = nx.fast_gnp_random_graph(args.vertices, args.edge_prob, args.seed)
    end = timer()
    LOG_STATS.info('Read/generated graph in %0.4f seconds' % (end - start))
    LOG_STATS.info('Graph has %d vertices and %d edges' %
                   (len(G.nodes), len(G.edges)))

    if args.plot:
        plt.subplot(121)
        nx.draw(G, with_labels=True, font_weight='bold')
        plt.show()

    file = open(args.file, 'w') if args.file is not None else None
    output = io.PatternOutput(file,
                              args.canonical,
                              args.sort,
                              log_patterns=args.log_patterns)

    if args.algorithm == 'clique':
        alg = algorithms.CliqueFinding(output, args.max if args.max else None)
    elif args.algorithm == 'cycle':
        alg = algorithms.CycleFinding(output, args.max if args.max else None)
    elif args.algorithm.startswith('example'):
        alg = algorithms.ExampleTree(output, args.max if args.max else None)
    else:
        alg = algorithms.Algorithm(output, args.max if args.max else None)

    if args.mode == 'static' or args.mode == 'both':
        alg.reset_stats()
        LOG.info('Running forwards exploration with algorithm \'%s\'' %
                 args.algorithm)
        start = timer()
        mining.forwards_explore_all(G, alg)
        end = timer()
        LOG_STATS.info('Ran forwards exploration in %0.4f seconds' %
                       (end - start))
        LOG_STATS.info(' - Found %d matches' % alg.num_found)
        LOG_STATS.info(' - Executed %d filters' % alg.num_filters)

    if args.mode == 'dynamic' or args.mode == 'both':
        alg.reset_stats()
        if args.mode == 'dynamic':
            updates = list(
                map(
                    lambda t: list(t),
                    list(G.edges)[:args.updates] if args.updates else list(
                        G.edges)))  # get list of list, not list of tuples
            if args.reset:
                G = nx.Graph()  # reset graph
        elif args.graph == 'example':
            updates = [[1, 3], [0, 1]]
        else:
            updates = []
            for _ in range(0, args.updates):
                valid = False
                while not valid:
                    edge = [
                        random.randint(0, len(G.nodes)),
                        random.randint(0, args.vertices)
                    ]
                    if edge[0] != edge[1] and not G.has_edge(
                            edge[0], edge[1]) and edge not in updates:
                        valid = True
                        updates.append(edge)

        LOG.info(
            'Running middle-out exploration with algorithm \'%s\' and %d updates'
            % (args.algorithm, len(updates)))

        random.shuffle(updates)

        start = timer()
        for i, update in enumerate(updates):
            if i < 1000 and i % 100 == 0 or i % 1000 == 0:
                LOG.info('Processed updates: %d / %d' % (i, len(updates)))
            LOG.debug('Processing update %s' % str(update))
            mining.middleout_explore_update(G, alg, update, add_to_graph=True)
            LOG_STATS.debug('Found %d matches' % alg.num_found)
            LOG_STATS.debug('Executed %d filters' % alg.num_filters)
        end = timer()
        LOG_STATS.info('Ran middle-out exploration in %0.4f seconds' %
                       (end - start))
        LOG_STATS.info(' - Found %d matches' % alg.num_found)
        LOG_STATS.info(' - Executed %d filters' % alg.num_filters)

    if file is not None:
        file.close()
Ejemplo n.º 53
0
import networkx
import sys

if len(sys.argv) < 2:

    print("python genRandomGraph.py [output folder]")
    input()
    sys.exit(0)

outputPath = sys.argv[1]

genList = [(100000, 2), (100000, 3), (1000000, 2), (1000000, 3)]

for i, (node, mean_degree) in enumerate(genList):

    print(i, (node, mean_degree))

    G = networkx.fast_gnp_random_graph(node, mean_degree / node)
    networkx.write_edgelist(G,
                            outputPath + "/genRandomGraph_" + str(i) + ".csv",
                            data=False,
                            delimiter=',')
Ejemplo n.º 54
0
import networkx as nx
from node2vec import Node2Vec

graph = nx.fast_gnp_random_graph(n=100, p=0.5)  #快速随机生成一个无向图
node2vec = Node2Vec(graph,
                    dimensions=64,
                    walk_length=30,
                    num_walks=100,
                    p=0.3,
                    q=0.7,
                    workers=4)  #初始化模型
model = node2vec.fit()  #训练模型
print(model.wv.most_similar('2', topn=3))  # 观察与节点2最相近的三个节点
Ejemplo n.º 55
0
 def setup(self, graph_size, graph_density, num_reads):
     self.sampler = greedy.SteepestDescentSampler()
     self.graph = nx.fast_gnp_random_graph(n=graph_size, p=graph_density, seed=0)
     self.bqm = dimod.generators.random.ran_r(r=1, graph=self.graph, seed=0)
Ejemplo n.º 56
0
def __er_graph(n,p,seed=None):
    '''
    erdos renyi graph
    '''
    return nx.fast_gnp_random_graph(n,p,seed=seed)
Ejemplo n.º 57
0
k0 = 100

alpha = 1/5
rho = 1/8
eta = R0 * rho / k0
kappa = Q0/(1-Q0) * rho
chi = 1/2
xi = (1-Q0)/Q0 * chi
omega = 1/14

S, E, I, R, X, T_I, T_E, Q = "S E I R X T_I T_E Q".split(" ")

N = 20000

print("generating network")
edges = [(e[0],e[1],1.0) for e in (nx.fast_gnp_random_graph(N,k0/(N-1))).edges() ] 
agentmodel = StochasticEpiModel([S, E, I, R, X, T_I, T_E, Q], N, edges)
#model = StochasticEpiModel([S, E, I, R, X, T_I, T_E, Q], N, well_mixed_mean_contact_number=k0)

agentmodel.set_node_transition_processes([
        (E, alpha, I),
        (I, rho, R),
        (I, kappa, T_I),
        (T_I, chi, X),
        (T_E, xi, R),
        (T_E, chi, X),
        #(Q, omega, S),
    ])

agentmodel.set_link_transmission_processes([
        (I, S, R0*rho/k0, I, E),
Ejemplo n.º 58
0
def getEnsambleBowTieNetworkValues(gx,
                                   samples=5,
                                   model="configuration",
                                   debug=False):
    """
    Returns an object BowTieEnsembleNetworkValues for the ensamble of graphs created based on the
    network topology of the given graph under a certain model.
    Parameters
    ----------
    gx : Networkx DiGraph
        Networkx DiGraph
    samples : number of graph in the ensamble
        Name of the 
    model : "configuration", "ER", default: "configuration",
        Model with wich the graphs will be created, valid modesl are:
        "configuration" : directed_configuration_model
        "ER" : Erdős-Rényi Gnp graph fast_gnp_random_graph
        "configuration"  will be used if no other valid name is given.
    Returns
    -------
    R : BowTieEnsembleNetworkValues
        TODO
    """
    def __printDebug(*val):
        if debug:
            print(list(val))

    din = list(d for n, d in gx.in_degree())
    dout = list(d for n, d in gx.out_degree())
    n = gx.order()
    m = nx.number_of_edges(gx)
    p = m / (n * (n - 1))

    resultsNodesAllGraph = []
    reusltNodesWeaklyLCC = []
    resultNodesTubes = []
    resultNodesTendrilsIn = []
    resultsNodesIn = []
    resultNodesSCC = []
    resultNodesOut = []
    resultNodesTendrilsOut = []
    resultNodesOCC = []

    if (model == "ER"):
        print("Gnp values. n:", n, ", p:", p)

    # add the values for each realization
    for i in range(samples):
        if (model == "ER"):
            g = nx.fast_gnp_random_graph(n=n, p=p, directed=True)
        else:
            g = nx.directed_configuration_model(din, dout)

        btV = getBowTieNetworkValues(g)

        resultsNodesAllGraph.append(btV.nrNodesAllGraph)
        reusltNodesWeaklyLCC.append(btV.nrNodesWeaklyLCC)
        resultNodesTubes.append(btV.nrNodesTubes)
        resultNodesTendrilsIn.append(btV.nrNodesTendrilsIn)
        resultsNodesIn.append(btV.nrNodesIn)
        resultNodesSCC.append(btV.nrNodesSCC)
        resultNodesOut.append(btV.nrNodesOut)
        resultNodesTendrilsOut.append(btV.nrNodesTendrilsOut)
        resultNodesOCC.append(btV.nrNodesOCC)

    __printDebug("Result Nodes All Graph: ", resultsNodesAllGraph)

    # create dictionary
    bowTieEnsembleNetworkValues = BowTieEnsembleNetworkValues(
        meanNrNodesAllGraph=np.mean(resultsNodesAllGraph, dtype=np.float64),
        meanNrNodesWeaklyLCC=np.mean(reusltNodesWeaklyLCC, dtype=np.float64),
        meanNrNodesTubes=np.mean(resultNodesTubes, dtype=np.float64),
        meanNrNodesTendrilsIn=np.mean(resultNodesTendrilsIn, dtype=np.float64),
        meanNrNodesIn=np.mean(resultsNodesIn, dtype=np.float64),
        meanNrNodesSCC=np.mean(resultNodesSCC, dtype=np.float64),
        meanNrNodesOut=np.mean(resultNodesOut, dtype=np.float64),
        meanNrNodesTendrilsOut=np.mean(resultNodesTendrilsOut,
                                       dtype=np.float64),
        meanNrNodesOCC=np.mean(resultNodesOCC, dtype=np.float64),
        stdNrNodesAllGraph=np.std(resultsNodesAllGraph, dtype=np.float64),
        stdNrNodesWeaklyLCC=np.std(reusltNodesWeaklyLCC, dtype=np.float64),
        stdNrNodesTubes=np.std(resultNodesTubes, dtype=np.float64),
        stdNrNodesTendrilsIn=np.std(resultNodesTendrilsIn, dtype=np.float64),
        stdNrNodesIn=np.std(resultsNodesIn, dtype=np.float64),
        stdNrNodesSCC=np.std(resultNodesSCC, dtype=np.float64),
        stdNrNodesOut=np.std(resultNodesOut, dtype=np.float64),
        stdNrNodesTendrilsOut=np.std(resultNodesTendrilsOut, dtype=np.float64),
        stdNrNodesOCC=np.std(resultNodesOCC, dtype=np.float64))

    return bowTieEnsembleNetworkValues
Ejemplo n.º 59
0
import matplotlib.pyplot as plt
import random
from random import shuffle
import math
import numpy as np
from networkx.algorithms.community import greedy_modularity_communities
from networkx.algorithms.community import asyn_lpa_communities
from networkx.algorithms.community import label_propagation_communities
from networkx.algorithms.community import asyn_fluidc
from networkx.algorithms.community.quality import coverage
from networkx.algorithms.community.quality import performance
from networkx.algorithms.community.centrality import girvan_newman

# Graph=nx.karate_club_graph()
# Graph=nx.read_gml('datasets/dolphins.gml',label='id')
Graph = nx.fast_gnp_random_graph(25, 0.7)
# Graph=nx.windmill_graph(8,4)

# sizes = [5, 5, 10]
# probs = [[0.05, 0.05, 0.02],
#          [0.05, 0.15, 0.07],
#          [0.02, 0.07, 0.04]]
# Graph = nx.stochastic_block_model(sizes, probs, seed=0)

gmc = list(greedy_modularity_communities(Graph))
alc = list(asyn_lpa_communities(Graph))
lpac = list(label_propagation_communities(Graph))
asfl = list(asyn_fluidc(Graph, 3))
girvanNewmanCommunities = list(girvan_newman(Graph))
W2 = np.zeros((len(Graph), len(Graph)))
for i in Graph:
Ejemplo n.º 60
0
        print("Number of node should be an integer.")
        exit()

    if not sys.argv[2] == '0' and not sys.argv[2] == '1':
        print("Illegal para: 1 for directed graph and 0 for undirected. ")
    elif sys.argv[2] == '0':
        directed = False
    else:
        directed = True

    if directed:
        try:
            os.remove("graph" + str(num_node) + ".txt")
        except OSError:
            pass
        DG = nx.fast_gnp_random_graph(num_node, 0.2, 100, True)
        with open("graph" + str(num_node) + ".txt", "a") as myfile:
            for i in range(num_node):
                keyList = list(DG[i].keys())
                currentList = []
                for k in range(num_node):
                    if k not in keyList:
                        currentList.append(str(0))
                    else:
                        currentList.append(str(random.randint(1, 100)))
                line = " ".join(currentList)
                line += "\n"
                myfile.write(line)
    else:
        try:
            os.remove("udgraph" + str(num_node) + ".txt")