def small_worldness(self, G, N, matrix):
        G_rand = nx.gnm_random_graph(G.number_of_nodes(), G.number_of_edges())
        path_length = nx.average_shortest_path_length(G, weight='weight')

        # G_rand path length
        weight_matrix = copy(matrix)
        if 'edge_threshold' in self.params:
            edge_threshold = self.params['edge_threshold']
        else:
            edge_threshold = 0.
        non_edges = np.where(weight_matrix <= edge_threshold)
        weight_matrix[non_edges[0], non_edges[1]] = 0.
        np.fill_diagonal(weight_matrix, 0)
        triu_idx = np.triu_indices(N, 1)
        rand_weights = weight_matrix[triu_idx[0], triu_idx[1]]
        rand_weights = np.array([w for w in rand_weights if w])
        np.random.shuffle(rand_weights)
        # print len(rand_weights), len(G_rand.edges())
        for count, e in enumerate(G_rand.edges()):
            G_rand[e[0]][e[1]]['weight'] = rand_weights[count]

        path_length_rand = nx.average_shortest_path_length(G_rand,
                                                           weight='weight')

        # transitivity
        transitivity = self.transitivity(G, N, matrix)

        # G_rand transitivity
        G_rand2 = nx.gnm_random_graph(G.number_of_nodes(), G.number_of_edges())
        transitivity_rand = nx.transitivity(G_rand2)
        self.prediction_dim = 0
        return (transitivity / transitivity_rand) / (path_length /
                                                     path_length_rand)
Esempio n. 2
0
def gen_single_graph(pos, attr, dist_key):
	global group_counter
	global config
	global attribute

	s_levels = range(1, 6)
	u_levels = range(1, 6)

	G = nx.gnm_random_graph(18, 25)
	while not nx.is_connected(G):
		G = nx.gnm_random_graph(18, 25)
	for e in G.edges():
		G[e[0]][e[1]]['strength'] = random.choice(s_levels)
		G[e[0]][e[1]]['certainty'] = random.choice(u_levels)
	
	counter = 0
	attr_values = list(dist_template[dist_key])
	random.shuffle(attr_values)
	for e in G.edges():
		G[e[0]][e[1]][attr] = attr_values[counter]
		counter += 1

	# write json formatted data
	d = json_graph.node_link_data(G) # node-link format to serialize
	# write json
	output_name = 'task_cp_' + attribute + '_' + config + '_' + str(group_counter) + '_' + pos + '.json'
	output = open(output_name, 'w')
	json.dump(d, output, indent=2, separators=(', ', ':' ))
	print('Wrote node-link JSON data to ' + output_name)
Esempio n. 3
0
def gen_single_graph(pos, attr, dist_key):
    global group_counter
    global config
    global attribute

    s_levels = range(1, 6)
    u_levels = range(1, 6)

    G = nx.gnm_random_graph(18, 25)
    while not nx.is_connected(G):
        G = nx.gnm_random_graph(18, 25)
    for e in G.edges():
        G[e[0]][e[1]]['strength'] = random.choice(s_levels)
        G[e[0]][e[1]]['certainty'] = random.choice(u_levels)

    counter = 0
    attr_values = list(dist_template[dist_key])
    random.shuffle(attr_values)
    for e in G.edges():
        G[e[0]][e[1]][attr] = attr_values[counter]
        counter += 1

    # write json formatted data
    d = json_graph.node_link_data(G)  # node-link format to serialize
    # write json
    output_name = 'task_cp_' + attribute + '_' + config + '_' + str(
        group_counter) + '_' + pos + '.json'
    output = open(output_name, 'w')
    json.dump(d, output, indent=2, separators=(', ', ':'))
    print('Wrote node-link JSON data to ' + output_name)
Esempio n. 4
0
def setup(
        network='random',  # ['complete', 'random', 'Watts-Strogatz', 'connected caveman', 'Barabasi-Albert'] 
        n_agents=40,  # number of agents 
        deg=4,  # number of connections for each agent
        n_beliefs=25,  # number of knowledge graph elements each agent has
        n_concepts=30):
    """
    Generates the initial conditions of the simulation

    Returns
    -------
    g: networkx graph
        primary graph represents the semantic network,
        each individual (node) has an attribute 'M' representing their semantic network

    all_beliefs: an array of tuples, which represents all edges anywhere in the semantic
        network network of any individual. Does not include edges that could be part of the
        semantic network (because they are present in a complete graph with `n_concepts`, 
        but were not selected).
    """
    np.random.seed()

    connected = False
    while not connected:
        if network == 'complete':
            g = nx.complete_graph(n=n_agents)
        elif network == 'random':
            g = nx.gnm_random_graph(n=n_agents, m=int(n_agents * deg / 2))
        elif network == 'random regular':
            g = nx.random_regular_graph(d=deg, n=n_agents)
        elif network == 'Watts-Strogatz':
            g = nx.connected_watts_strogatz_graph(n=n_agents, k=deg,
                                                  p=.02)  # valid for even deg
        elif network == 'connected caveman':
            g = nx.connected_caveman_graph(l=int(n_agents / deg), k=deg + 1)
        elif network == 'Barabasi-Albert':
            g = nx.barabasi_albert_graph(n=n_agents, m=int(
                deg /
                2))  # approximates deg for large n_agents, when deg is even.
        else:
            raise ValueError('%s is not a valid network name' % network)

        connected = nx.is_connected(g)

    # give starting information
    nx.set_node_attributes(
        g,
        name='M',  # M for mind
        values={i: nx.gnm_random_graph(n_concepts, n_beliefs)
                for i in g})

    beliefs = np.unique([
        tuple(sorted(belief)) for agent in g
        for belief in g.nodes[agent]['M'].edges()
    ],
                        axis=0)
    return g, beliefs
Esempio n. 5
0
def generate_random_graph(n_nodes,
                          density,
                          directed=False,
                          is_tree=False,
                          seed=None,
                          draw=False):
    r"""Generate a random graph with the desired number of nodes and density.
    Draw the graph if asked. Returns the graph as a networkx object.

    Parameters:
    ----------
    n_nodes: int,
             number of nodes
    density: float (\in [0,1]),
             density of edges
    directed: bool,
              whether or not the graph is directed
    is_tree: bool,
             whether to generate a tree or not
    seed: int,
          the random seed to use
    draw: bool,
          whether to draw the graph or not

    Returns:
    -------
    graph: networkx Digraph"""

    # if we want to generate a directed graph, we generate two undirected graphs
    # of the same size and assemble them in one single directed graph by saying the
    # vertices of the first are in the direction left -> right and the inverse for the second

    # Compute the number of edges corresponding to the given density
    n_edges = int(density * n_nodes * (n_nodes - 1) / 2)
    # Create the graph
    seed_1 = None if seed is None else seed + 1
    if is_tree:
        graph_0 = nx.random_tree(n_nodes, seed=seed)
        if directed:
            graph_1 = nx.random_tree(n_nodes, seed=seed_1)
        else:
            graph_1 = graph_0
    else:
        graph_0 = nx.gnm_random_graph(n_nodes, n_edges, seed)
        if directed:
            graph_1 = nx.gnm_random_graph(n_nodes, n_edges, seed_1)
        else:
            graph_1 = graph_0
    graph_2 = nx.DiGraph()
    graph_2.add_nodes_from(graph_0.nodes())
    graph_2.add_edges_from([(u, v) for (u, v) in graph_0.edges()])
    graph_2.add_edges_from([(v, u) for (u, v) in graph_1.edges()])

    if draw:
        plot_graph(graph_2, color_type="fabulous")

    return graph_2
Esempio n. 6
0
def getGraph():

    edges1 = random.randint(nodeNo, nodeNo + 10)
    graph1 = nx.gnm_random_graph(nodeNo, edges1, False)

    edges2 = random.randint(nodeNo, nodeNo + 10)
    graph2 = nx.gnm_random_graph(nodeNo, edges2, False)

    return graph1, graph2
def gen_input(n,m):
	from random import randint
	import networkx as nx

	G = nx.gnm_random_graph(n, m) # gen graph
	while not nx.is_connected(G):
		G = nx.gnm_random_graph(n, m) # gen graph

	R = [randint(0, n) for i in xrange(n)] # gen requirements
	S = [randint(0, 100) for i in xrange(n)] # gen requirements
	return G, R, S
Esempio n. 8
0
    def test_different_number_of_edges(self):
        for i in range(10):
            N = np.random.randint(2, 50)
            E1 = np.random.randint(N * (N - 1) / 2 - 1)
            E2 = np.random.randint(N * (N - 1) / 2 - 1)
            if E1 == E2:
                E1 -= 1
            G = nx.gnm_random_graph(N, E1)
            H = nx.gnm_random_graph(N, E2)

            assert not nx.is_isomorphic(G, H)
            assert not is_possibly_isomorphic(G, H, N)
def BinarySearchMethod( N, L ):
    
    locN,locL=N, L
    G=nx.gnm_random_graph(locN,locL)
    delta=1
    
    
    #   Check if we are lucky...
    if __getGCCNodeCount(G)==locN:
        return G
    
    
    finished=False
    
    while not finished:
    
        while __getGCCNodeCount(G)<locN:
            G=nx.gnm_random_graph(locN+delta,locL)
            delta=delta*2
        
        if __getGCCNodeCount(G)>=locN:        
            delta=int(delta/2)
            left,right=int(locN+delta/2),int(locN+delta)        
            while left!=right:
                middle=left+(right-left)/2
                G=nx.gnm_random_graph(int(middle),locL)
                NC=__getGCCNodeCount(G)
                if NC>locN:
                    right=middle
                elif NC<locN:
                    left=middle
                else:
                    left=right
        
        Gccs=sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)
        G0=Gccs[0]
        
        nodes=list(G0.nodes())            
        while G.number_of_edges()<locL:
            a=random.choice(nodes)    
            b=random.choice(nodes)    
                
            G0.add_edge(a,b)
            
        curN,curL,curCon=G0.number_of_nodes(),G0.number_of_edges(),nx.is_connected(G0)
        
        if curN==locN and curL==locL and curCon==True:
            finished=True
            
    return G0
Esempio n. 10
0
 def randomize_graph(self, n, e):
     """
     Creates 1000 random graphs with
     networkx.gnm_random_graph(nodecount, edgecount),
     and computes average_clustering_coefficient and
     average_shortest_path_length, to compare with drama-graph.
     Returns a tuple:
     randavgpathl, randcluster = (float or "NaN", float or "NaN")
     """
     randcluster = 0
     randavgpathl = 0
     # what is c, what is a, what is n, what is e?
     # e=edges?, c=clustering_coefficient?, a=average_shortest_path_length?
     c = 0
     a = 0
     if not self.randomization:  # hack so that quartett poster works
         self.randomization = 50
     for i in tqdm(range(self.randomization), desc="Randomization",
                   mininterval=1):
         R = nx.gnm_random_graph(n, e)
         try:
             randcluster += nx.average_clustering(R)
             c += 1
         except ZeroDivisionError:
             pass
         j = 0
         while True:
             j += 1
             try:
                 R = nx.gnm_random_graph(n, e)
                 randavgpathl += nx.average_shortest_path_length(R)
                 a += 1
             except:
                 pass
             else:
                 break
             if j > 50:
                 randavgpathl = "NaN"
                 break
     try:
         randcluster = randcluster / c
     except:
         randcluster = "NaN"
     try:
         randavgpathl = randavgpathl / a
     except:
         randavgpathl = "NaN"
     return randavgpathl, randcluster
Esempio n. 11
0
def MinDistanceGraphFinder(number_of_vertices,number_of_edges):
		
	if number_of_edges<number_of_vertices-1:
		print 'Too few edges. The graph will be disconnected. Exiting...'
		return -1
	if number_of_edges>(number_of_vertices-1)*number_of_vertices/2.0:
		print 'Too many edges. Such a graph cannot exist. Exiting...'
		return -1
		
	if number_of_edges>(number_of_vertices-2)*(number_of_vertices-1)/2.0:
		OutputGraph=nx.gnm_random_graph(number_of_vertices,number_of_edges)
		return OutputGraph
	
	
	G=nx.star_graph(number_of_vertices-1)
	VertexList=G.nodes()
	remaining_edges=number_of_edges-number_of_vertices+1
	
	while remaining_edges>0:
		first_vertex=random.choice(VertexList)
		second_vertex=random.choice(VertexList)
		if first_vertex==second_vertex:continue
		if (first_vertex,second_vertex) in G.edges():continue
		if (second_vertex,first_vertex) in G.edges():continue
		
		G.add_edge(first_vertex,second_vertex)
		remaining_edges-=1
		
	OutputGraph=G.copy()
		
	return OutputGraph
Esempio n. 12
0
def measure_single(graph_size):
	global args
	time_results = []
	memory_results = []

	print('graph size={}:'.format(graph_size), end=' ')
	for density in args.densities:
		vertices = compute_vertices_count(graph_size, density)
		edges = graph_size - vertices

		nx_graph = nx.gnm_random_graph(vertices, edges, directed=True)
		if nx_graph.number_of_nodes() + nx_graph.number_of_edges() != graph_size:
			time_results.append(float('nan'))
			memory_results.append(float('nan'))
			continue
		print('[D={} |V|={} |E|={}]'.format(density, nx_graph.number_of_nodes(), nx_graph.number_of_edges()), end=' ')

		stats = get_stats(args.repetitions, args.multiplication, [args.algorithm], nx_graph, args.garbage_collection)
		time_results.append(round(min(stats[args.algorithm]['time']), 5))
		memory_results.append(stats[args.algorithm]['memory'] / float(2**20))

	print()
	for res in [(time_results, '_time.csv'), (memory_results, '_memory.csv')]:
		with open(args.output + res[1], 'a') as csvfile:
			writer = csv.writer(csvfile)
			row = [graph_size] + res[0]
			writer.writerow(row)
Esempio n. 13
0
def measure_multi(graph_size):
	global args

	vertices = compute_vertices_count(graph_size, args.density)
	edges = graph_size - vertices

	nx_graph = nx.gnm_random_graph(vertices, edges, directed=True)
	if nx_graph.number_of_nodes() + nx_graph.number_of_edges() != graph_size:
		return

	print('graph size={}: [D={} |V|={} |E|={}]'.format(graph_size, args.density,
		nx_graph.number_of_nodes(), nx_graph.number_of_edges()))

	stats = get_stats(args.repetitions, args.multiplication, args.algorithms, nx_graph, args.garbage_collection)

	#extract minimal time from all measured times
	for key in stats:
		stats[key]['time'] = round(min(stats[key]['time']), 5)

	#write time and memory values into files as CSV
	for res_type in ['time', 'memory']:
		with open(args.output + '_' + res_type + '.csv', 'a') as csvfile:
			writer = csv.writer(csvfile)
			row = [graph_size] + [stats[key][res_type] for key in sorted(stats)]
			writer.writerow(row)
Esempio n. 14
0
 def generate_random_graph(self):
     print 'performer.generate_random_graph:', self.NODE_COUNT, self.EDGE_COUNT
     while True:
         graph = gnm_random_graph(self.NODE_COUNT, self.EDGE_COUNT)
         if self.constraints_satisfied(graph):
             self.process_graph(graph)
             return graph
Esempio n. 15
0
def test_layouts():
    G =nx.gnm_random_graph(10,15)

    rand = [nx.random_layout(G)]
    circ = [nx.circular_layout(G)]
    #shell = [nx.shell_layout(G)] #same as circular layout...
    spectral = [nx.spectral_layout(G)]
    tripod = [tripod_layout(G)]

    layouts = [rand,circ,spectral, tripod]
    regimes = ["random","circular","spectral", "tripod"]

    for layout in layouts:
        layout.append(nx.spring_layout(G,2,layout[0]))
        layout.append(iterate_swaps(G,layout[0]))
        layout.append(nx.spring_layout(G,2,layout[2]))
        layout.append(greedy_swapper(G,layout[0]))

    # Now have list of lists... Find lengths of edgecrossings...

    num_crossings = []
    for layout in layouts:
        for sublayout in layout:
            num_crossings.append(count_crosses(G,sublayout))

    names = []
    for regime in regimes:
        names.append(regime)
        names.append(regime + "-spring")
        names.append(regime + "-swap")
        names.append(regime + "-swap-spr")
        names.append(regime + "-greedy")

    return G, layouts, names, num_crossings
Esempio n. 16
0
 def generate_graph(self):
     n = self._num_of_nodes
     m = self._num_of_edges
     G = networkx.gnm_random_graph(n, m)
     for u, v in G.edges():
         G[u][v]["weight"] = 1
     return G
Esempio n. 17
0
    def create_graph(self, params):

        # case statements on type of graph

        if self.type == 'small_world':
            self.graph = nx.watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.SWC += 1
            self.idx = cg.SWC
            self.path = 'smallWorldGraphs'
        elif self.type == 'small_world_connected':
            self.graph = nx.connected_watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                100 if len(params) < 4 else int(params[3]),
                None if len(params) < 5 else int(params[4]))
            cg.SWCC += 1
            self.idx = cg.SWCC
            self.path = 'smallWorldConnectedGraphs'
        elif self.type == 'small_world_newman':
            self.graph = nx.newman_watts_strogatz_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.SWNC += 1
            self.idx = cg.SWNC
            self.path = 'smallWorldNewmanGraphs'
        elif self.type == 'power_law':
            self.graph = nx.powerlaw_cluster_graph(
                int(params[0]), int(params[1]), float(params[2]),
                None if len(params) < 4 else int(params[3]))
            cg.PLC += 1
            self.idx = cg.PLC
            self.path = 'powerLawGraphs'
        elif self.type == 'power_law_tree':
            self.graph = nx.random_powerlaw_tree(
                int(params[0]), 3 if len(params) < 2 else float(params[1]),
                None if len(params) < 3 else int(params[2]),
                100 if len(params) < 4 else int(params[3]))
            cg.PLTC += 1
            self.idx = cg.PLTC
            self.path = 'powerLawTreeGraphs'
        elif self.type == 'random_graph':
            self.graph = nx.gnm_random_graph(
                int(params[0]), int(params[1]),
                None if len(params) < 3 else int(params[2]),
                False if len(params) < 4 else bool(params[3]))
            cg.RGC += 1
            self.idx = cg.RGC
            self.path = 'randomGraphs'
        elif self.type == 'erdos_renyi_random':
            self.graph = nx.erdos_renyi_graph(
                int(params[0]), float(params[1]),
                None if len(params) < 3 else int(params[2]),
                False if len(params) < 4 else bool(params[3]))
            cg.ERRC += 1
            self.idx = cg.ERRC
            self.path = 'erdosRenyiRandomGraphs'
        else:
            print 'GRAPH TYPE:', self.type
            raise Exception('Invalid Type of Graph input into argv[2]')
Esempio n. 18
0
    def GenerateRandom(cls,
                       nodes_nmb,
                       edges_nmb,
                       capacity_min=0,
                       capacity_max=0):
        """
        Create graph with specified number of nodes and arcs, where random nodes are connected to random nodes.
        Does not contain self loop.
        Set to every arc in the graph random value of the capacity from min to max.
        """

        network_graph = nx.gnm_random_graph(nodes_nmb,
                                            edges_nmb,
                                            directed=True)

        nx.set_edge_attributes(network_graph, {
            edge: np.around(
                (capacity_max - capacity_min) * nrnd.ranf() + capacity_min, 3)
            for edge in nx.edges(network_graph)
        },
                               name='capacity')
        self = cls(network_graph)
        self.capacity_min = capacity_min
        self.capacity_max = capacity_max
        return self
Esempio n. 19
0
def construct_example(n, q, bits = 6):
    done = False

    m = int(np.ceil(n*np.log(n)/4))
    G = nx.gnm_random_graph(n,m)
    edges = np.array(G.edges())
    # print("edges",edges)
    edges = edges.flatten()
    queries = np.array([np.random.choice(n, 2, replace=False) for _ in range(q)])
    connected = np.zeros(q, dtype=np.float32)
    # print("queries",queries)
    for qi in range(q):
        try:
            shortest_paths = np.array([expand_shortest_path(p) for p in 
                                       nx.all_shortest_paths(G, queries[qi,0], queries[qi,1])])
            connected[qi] = 1.0
        except:
            connected[qi] = 0.0

    # print("shortest_paths",shortest_paths)
    # print("length_of_shortest_path",length_of_shortest_path)
    # print("connected", connected)

    edges = get_bit_sequence(edges, bits)
    queries = get_bit_sequence(queries.flatten())
    return edges, queries, connected
Esempio n. 20
0
def CreateRandom(n, m, n_opinion=None, simple_graph=False, seed=None):
    """
    Creates an OpinionGraph with an interal graph which is a $G_{n,m}$ random graph, with $n_opinions$ randomly assigned.

    In the $G_{n,m}$ model, a graph is chosen uniformly at random from the set
    of all graphs with $n$ nodes and $m$ edges.

    Parameters
    ----------
    n : int
        The number of nodes.
    m : int
        The number of edges.
    n_opinion : int, optional
        The number of opinions (default=None, which gives n_opinion=n).
    simple_graph : bool, optional
        True if the graph is simple (default=None).
    seed : int, optional
        Seed for random number generator (default=None).
    
    Returns
    -------
    G : OpinionGraph
    """

    internal_graph = nx.gnm_random_graph(n, m)

    if not simple_graph:
        internal_graph = nx.MultiGraph(internal_graph)

    graph = OpinionGraph(internal_graph, n_opinion, simple_graph)
    return graph
Esempio n. 21
0
 def losowy_graf(self, n, m, maks_cap, orient):
     g = nx.gnm_random_graph(n, m)
     graf = [ [] for x in range(0, n)]
 #    print str(graf)
     c = zeros((n, n))
     for i in range(0, n):
         for j in range(0,n):
             if i < j: # gererujemy graf nieskierowany
                 c[i,j] = random.randint(0, maks_cap)
                 if orient:
                     c[j,i] = c[i,j]
                 else:
                     c[j,i] = random.randint(0, maks_cap)
     if orient:
         self.zorientowany = True
     #print str(g.edges())
     for (u,v) in g.edges():
 #        print 'Dodajemy wierzcholek'
         (graf[u]).append(v)
         graf[v].append(u)
     #print str(graf)
 #    for u in range(0,n):
 #        for v in graf[u]:
 #            print str(u) + ' -> '+ str(v)
     return (graf, c)
Esempio n. 22
0
def evaluation2(args, original_network):
    n = original_network.shape[0]
    m = int(np.sum(original_network))
    random_ER_G = nx.gnm_random_graph(n, m)
    random_bara_G = nx.generators.random_graphs.barabasi_albert_graph(n, 250)
    ER_G = nx.to_numpy_matrix(random_ER_G)
    bara_G = nx.to_numpy_matrix(random_bara_G)
    np.save('{}/ER.npy'.format(args.output_dir), ER_G)
    np.save('{}/BA.npy'.format(args.output_dir), bara_G)
    # ER_G = ER_G  + ER_G .T
    # ER_G[ER_G  > 1] = 1
    # bara_G = bara_G  + bara_G .T
    # bara_G[bara_G  > 1] = 1
    ER_G = np.array(ER_G)
    bara_G = np.array(bara_G)
    print('Computing metrics for ER graph')
    c = compute_graph_statistics(ER_G)
    with open('./{}/ER_statistics.pickle'.format(args.checkpoint),
              'wb') as handle:
        pickle.dump(c, handle, protocol=pickle.HIGHEST_PROTOCOL)
    print(c)
    print('Computing metrics for bara graph')
    d = compute_graph_statistics(bara_G)
    with open('./{}/bara_statistics.pickle'.format(args.checkpoint),
              'wb') as handle:
        pickle.dump(d, handle, protocol=pickle.HIGHEST_PROTOCOL)
    print(d)
Esempio n. 23
0
def generate_test ( filenum, isCyclic, nodes, edges, prefix=None ):

    while True:
        if isCyclic:
            G = nx.gnm_random_graph(nodes, edges)
        else:
            G = nx.random_tree(nodes)
        if nx.is_connected(G): # ensure connected graph
            break

    # nx.draw(G, with_labels=True, font_weight='bold')
    # plt.savefig("{}tests/test{}.png".format(prefix if prefix else "",filenum))
    # plt.close()

    with open("{}tests/test{}.txt".format(prefix if prefix else "",filenum), "w") as infile:
        infile.write("{}\n".format(nodes))
        A = nx.adjacency_matrix(G).toarray()
        for row in A:
            for col in row:
                infile.write("{} ".format(col))
            infile.write("\n")

    with open("{}queries/query{}.txt".format(prefix if prefix else "",filenum), "w") as qfile:

        source = random.randrange(nodes)
        qfile.write("{}\n".format(source))

        target = source
        while target == source:
            target = random.randrange(nodes) # make sure source and target are different nodes
        qfile.write("{}\n".format(target))

    with open("{}edgelists/edgelist{}.txt".format(prefix if prefix else "",filenum), "wb") as efile:
        nx.write_edgelist(G, efile, data=False)
Esempio n. 24
0
def CriaGrafoAleatorio(n, direct, pond):

    #	if direct == False:
    # Cria um grafo completo nao direcionado
    #		G = nx.Graph()

    #	else: # Cria um grafo completo direcionado
    #		G = nx.DiGraph()

    G = nx.gnm_random_graph(n,
                            random.randint(n - 1,
                                           n * (n - 1) / 2),
                            seed=time.time(),
                            directed=direct)

    x = random.sample(range(100), n)
    y = random.sample(range(100), n)

    # Adiciona vertices ao grafo
    for i in range(n):
        G.add_node(i, pos=(x[i], y[i]))

    if pond == True:
        # Adiciona arestas com pesos formando um grafo nao direcionado ponderado completo
        for e in G.edges():
            G.add_edge(e[0],
                       e[1],
                       weight=euclid_dist((x[e[0]], x[e[1]]),
                                          (y[e[0]], y[e[1]])))

    return G
 def generate_random_graph(self):
     print 'performer.generate_random_graph:', self.NODE_COUNT, self.EDGE_COUNT
     while True:
         graph = gnm_random_graph(self.NODE_COUNT, self.EDGE_COUNT)
         if self.constraints_satisfied(graph):
             self.process_graph(graph)
             return graph
Esempio n. 26
0
 def debug_mode(self, param):
     G = nx.gnm_random_graph(param['nNodes'], param['nEdges'])
     self.modelData = {'nodes': [], 'edges': []}
     # Store nodes in self.modelData['nodes']
     node_data = [n for n in G.nodes_iter()]
     for n in node_data:
         tmp = {
             'node_id': str(n),
             'label': str(n),
             'size': random.uniform(param['minNodeSize'],
                                    param['maxNodeSize'])
         }
         self.modelData['nodes'].append(tmp)
     # Store category information
     edgeTypes = param['edgeTypes']
     num_edgeTypes = len(edgeTypes)
     edge_data = list(G.edges_iter(data=False))
     for e in edge_data:
         tmp = {
             'source':
             str(e[0]),
             'target':
             str(e[1]),
             'strength':
             random.uniform(param['minEdgeStrength'],
                            param['maxEdgeStrength'])
         }
         self.modelData['edges'].append(tmp)
     return True
Esempio n. 27
0
def simulate_dag(d, s0):
    """Simulate random DAG with some expected number of edges.
    Args:
        d (int): num of nodes
        s0 (int): expected num of edges
    Returns:
        B (np.ndarray): [d, d] binary adj matrix of DAG
    
    Function based xunzheng/notears
    """
    def _random_permutation(M):
        # np.random.permutation permutes first axis only
        P = np.random.permutation(np.eye(M.shape[0]))
        return P.T @ M @ P

    def _random_acyclic_orientation(B_und):
        return np.tril(_random_permutation(B_und), k=-1)

    G_und = nx.gnm_random_graph(d, s0)
    B_und = nx.to_numpy_matrix(G_und)
    B = _random_acyclic_orientation(B_und)
    B_perm = _random_permutation(B)

    assert nx.is_directed_acyclic_graph(
        nx.from_numpy_matrix(B_perm, create_using=nx.DiGraph))
    return B_perm
Esempio n. 28
0
def random_graph(N, E):
    '''
    Creates adjacency list representation of a random graph with N nodes and E edges
    '''
    G = nx.gnm_random_graph(N, E)
    draw_graph(G)
    return nx.convert.to_dict_of_dicts(G)
Esempio n. 29
0
def generate_test(filenum, isTree, nodes, edges, prefix=None):

    if isTree:
        G = nx.random_tree(nodes)
    else:
        G = nx.gnm_random_graph(nodes, edges)

    # nx.draw(G, with_labels=True, font_weight='bold')
    # plt.savefig("{}tests/test{}.png".format(prefix if prefix else "",filenum))
    # plt.close()

    with open("{}tests/test{}.txt".format(prefix if prefix else "", filenum),
              "w") as infile:
        infile.write("{}\n".format(nodes))
        A = nx.adjacency_matrix(G).toarray()
        for row in A:
            for col in row:
                infile.write("{} ".format(col))
            infile.write("\n")

    with open(
            "{}answers/answer{}.txt".format(prefix if prefix else "", filenum),
            "w") as outfile:
        try:
            cycle = nx.find_cycle(G)
        except nx.NetworkXNoCycle:
            cycle = None
        outfile.write("no" if cycle else "yes")
Esempio n. 30
0
def create_or_read_simple_graph(name: str) -> nx.Graph:
    """Read a simple unweighted graph from the specified file or create random G_n,m graph if name is gnm-n-m.

    The nodes are labeled beginning with 0.

    File format:
        - ``c <comments>    #`` ignored
        - ``p <name> <number of nodes> <number of edges>``
        - ``e <node_1> <node_2>    #`` for each edge, nodes are labeled in 1...number of nodes
    """
    if name.startswith('gnm-'):
        # create random G_n,m graph
        par = name.split(sep='-')
        return nx.gnm_random_graph(int(par[1]), int(par[2]), int(par[3]) if len(par) == 4 else None)
    else:  # read from file
        graph: nx.Graph = nx.Graph()
        with open(name) as f:
            for line in f:
                flag = line[0]
                if flag == 'p':
                    split_line = line.split(' ')
                    n = int(split_line[2])
                    # m = int(split_line[3])
                    graph.add_nodes_from(range(n))
                elif flag == 'e':
                    split_line = line.split(' ')
                    u = int(split_line[1]) - 1
                    v = int(split_line[2]) - 1
                    graph.add_edge(u, v)
        return graph
Esempio n. 31
0
def generate_random_graphs(numberOfNodes, outputFile, graphType, degree=None):
    sparseResult = open(outputFile, "w")
    #first writing the number of nodes
    if (graphType == "degreeBased"):
        G = nx.random_regular_graph(
            degree, numberOfNodes,
            numberOfNodes * int(math.sqrt(numberOfNodes)))
    if (graphType == "completeChaos"):
        G = nx.gnm_random_graph(numberOfNodes,
                                numberOfNodes * int(math.sqrt(numberOfNodes)))
    if (graphType == "dense"):
        G = nx.dense_gnm_random_graph(
            numberOfNodes, numberOfNodes * int(math.sqrt(numberOfNodes)))

    sparseResult.write(
        str(numberOfNodes) + " " + str(nx.number_of_edges(G)) + "\n")
    semiSparseRep = nx.to_dict_of_lists(G)
    #print semiSparseRep
    for element in semiSparseRep:
        if len(semiSparseRep[element]) == 0:
            return 0
        for j in semiSparseRep[element]:
            sparseResult.write(str(j + 1) + " ")
        sparseResult.write("\n")
    return 1
Esempio n. 32
0
def gen_random_networks(n, m, U, num=20):
    '''
        Input
        -----
        n : number of nodes in the network
        m : number of edges in the network
        U : maximum capacity of any arc in the network
        num : total number of networks to be generated (defaults to 20)
        
        Output
        ------
        'num' feasible non-trivial networks in forward-star representation
        feasible signify networks with s-t paths,
        non-trivial signifies networks where there is no direct s-t arc
    '''
    feasible_networks = []
    for i in range(num):
        fs_repr = []
        isNotFeasible = True
        while isNotFeasible:
            net = nx.gnm_random_graph(
                n, m, directed=True)  # Use of networkx library method
            if (exists_st_path(net.edges, 0, n - 1)):
                isNotFeasible = False
        for edge in net.edges:
            rc = np.random.randint(
                1, U)  # generate random capacity of the edge between [1, U]
            fs_repr.append([edge[0] + 1, edge[1] + 1,
                            rc])  # converting 1-based index for the algorithms
        #print(fs_repr)
        feasible_networks.append(fs_repr)
    return feasible_networks
Esempio n. 33
0
    def losowy_graf(self, n, m, maks_cap, orient):
        g = nx.gnm_random_graph(n, m)
        graf = [[] for x in range(0, n)]
        #    print str(graf)
        c = zeros((n, n))
        for i in range(0, n):
            for j in range(0, n):
                if i < j:  # gererujemy graf nieskierowany
                    c[i, j] = random.randint(0, maks_cap)
                    if orient:
                        c[j, i] = c[i, j]
                    else:
                        c[j, i] = random.randint(0, maks_cap)
        if orient:
            self.zorientowany = True
        #print str(g.edges())
        for (u, v) in g.edges():
            #        print 'Dodajemy wierzcholek'
            (graf[u]).append(v)
            graf[v].append(u)
        #print str(graf)

    #    for u in range(0,n):
    #        for v in graf[u]:
    #            print str(u) + ' -> '+ str(v)
        return (graf, c)
Esempio n. 34
0
    def test_kcores(self):
        # Check that results correspond to those of networkx.
        G = nx.gnm_random_graph(100, 300)
        core_graph = nx.algorithms.k_core(G, 4)
        result, _ = k_cores(G, 4)

        self.assertEqual(result.edges, core_graph.edges)
Esempio n. 35
0
def MinDiameterGraphFinder(number_of_vertices, number_of_edges):

    if number_of_edges < number_of_vertices - 1:
        #print 'Too few edges. The graph will be disconnected. Exiting...'
        return -1
    if number_of_edges > (number_of_vertices - 1) * number_of_vertices / 2.0:
        #print 'Too many edges. Such a graph cannot exist. Exiting...'
        return -1

    if number_of_edges > (number_of_vertices - 2) * (number_of_vertices -
                                                     1) / 2.0:
        OutputGraph = nx.gnm_random_graph(number_of_vertices, number_of_edges)
        return OutputGraph

    G = nx.star_graph(number_of_vertices - 1)
    VertexList = G.nodes()
    remaining_edges = number_of_edges - number_of_vertices + 1

    while remaining_edges > 0:
        first_vertex = random.choice(VertexList)
        second_vertex = random.choice(VertexList)
        if first_vertex == second_vertex: continue
        if (first_vertex, second_vertex) in G.edges(): continue
        if (second_vertex, first_vertex) in G.edges(): continue

        G.add_edge(first_vertex, second_vertex)
        remaining_edges -= 1

    OutputGraph = G.copy()

    return OutputGraph
Esempio n. 36
0
def generate_graph(n, m, seed):
    G = nx.gnm_random_graph(n, m, seed)
    data = json_graph.node_link_data(G)
    with open('./Working/graph.json', 'w') as f:
        json.dump(data, f)
    with open('./Working/graph_flag', mode = 'w', encoding = 'utf-8') as fh:
        fh.write("i look at you")
def Densityrandom_date(density):

    density=density/100
    nodes=random.randint(3,200)
    edges= (density*nodes*(nodes-1))//2

    print(density,"nodes",nodes,"edges", edges)

    domain = {}
    constraint = {}

    G = nx.gnm_random_graph(nodes, edges, False)
    # print(G.nodes)
    # print(G.edges)

    for nd in G.nodes:
        # domain[nd]=random.sample(range(1, 100), 10)
        domain[nd] = random.sample(range(1, 1000), 50)

    numberOfConst = 6
    for e in G.edges:
        constraint[e] = random.randint(0, numberOfConst)

    # print(domain)
    # print(constraint)
    return (G, domain, constraint)
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)
Esempio n. 39
0
def test():
	import networkx as nx
	
	network = nx.gnm_random_graph(50,
								  50,
								  directed=True)
	sim = Simulation(10, 50, network)

	# generate users
	print('Generation')
	print('=' * 20)
	for n in network.nodes():
		u1 = User(n, sim.topics)
		sim.add_user(u1)
		print(sim.get_user(n))

	# add follow
	print('Follow')
	print('=' * 20)
	for e in network.edges():
		sim.new_follow(e[0],e[1])
		print(sim.get_user(e[0]).get_attachment(e[1]))
		

	print('Simulation')
	print('=' * 20)
	flag = 0
	while(flag>-1):
		print('Time: %d Edges: %d' % (sim.now, len(network.edges())))
		print('Tweets: %d' % len(sim.tweet))
		print('Retweets: %d' % len(sim.retweet))
		sim.step_tweet()
		sim.step_retweet()
		sim.now += 1
		flag += 1
Esempio n. 40
0
def ErdosRenyi(n, m, d, display=None, seed=None):
    """
	n: the number of nodes
	m: the number of edges
	"""
    # counter = 0
    # naive way to generate connected graph
    while True:
        if m <= 30:
            G = nx.gnm_random_graph(n, m, seed=None, directed=False)
        else:
            G = nx.dense_gnm_random_graph(n, m, seed=None)
        maxDegree = max([item for item in G.degree().values()])
        if nx.is_connected(G) and maxDegree <= d:
            break
        # if maxDegree > d:
        # counter += 1

    # avgDegree = 2 * nx.number_of_edges(G) / nx.number_of_nodes(G)
    # print avgDegree

    if display:
        nx.draw(G)
        img_name = 'erdos_renyi_%i_%i.png' % (n, m)
        plt.savefig(img_name)
        sh.open(img_name)

    adjacencyMatrix = generateAdjacencyMatrix(G)
    return adjacencyMatrix
	def random_graph(self):
		
		#Compute graph and caculate average path length, clustering coeff 
		logging.info('Inside random graph')
		RG = nx.gnm_random_graph(self.node_count, self.edge_count)
		RG = nx.connected_component_subgraphs(RG.to_undirected())[0]
		self.average_shortest_path_length('Random graph', RG)
		self.global_clustering_coefficient('Random graph', RG)
Esempio n. 42
0
 def connect_fixed_edges(self,N,p):
     """
     A fixed fraction of the total possible N*(N-1)/2 connections are made. (Not a binomial
     graph!  The number of edges is always p*N(N-1)/2, not just in the N->infinity limit.)
     """
     self.connect_empty(N)
     dN = int(p*N*(N-1)/2)
     self.add_edges_from(nx.gnm_random_graph(N,dN).edges())
Esempio n. 43
0
def random_graph_heterogeneous_synapses(cell_positions):
    h = spatial_graph_2010(cell_positions)
    weights = [e[2]['weight'] for e in h.edges(data=True)]
    random.shuffle(weights)
    g = nx.gnm_random_graph(h.order(), h.size())
    for k, e in enumerate(g.edges()):
        g[e[0]][e[1]]['weight'] = weights[k]
    return g
Esempio n. 44
0
    def obtain_graph(args):
        """Build a Graph according to command line arguments

        Arguments:
        - `args`: command line options
        """
        if hasattr(args,'gnd') and args.gnd:

            n,d = args.gnd
            if (n*d)%2 == 1:
                raise ValueError("n * d must be even")
            G=networkx.random_regular_graph(d,n)
            return G

        elif hasattr(args,'gnp') and args.gnp:

            n,p = args.gnp
            G=networkx.gnp_random_graph(n,p)

        elif hasattr(args,'gnm') and args.gnm:

            n,m = args.gnm
            G=networkx.gnm_random_graph(n,m)

        elif hasattr(args,'grid') and args.grid:

            G=networkx.grid_graph(args.grid)

        elif hasattr(args,'torus') and args.torus:
            
            G=networkx.grid_graph(args.torus,periodic=True)

        elif hasattr(args,'complete') and args.complete>0:

            G=networkx.complete_graph(args.complete)

        elif args.graphformat:

            G=readGraph(args.input,args.graphformat)
        else:
            raise RuntimeError("Invalid graph specification on command line")

        # Graph modifications
        if hasattr(args,'plantclique') and args.plantclique>1:

            clique=random.sample(G.nodes(),args.plantclique)

            for v,w in combinations(clique,2):
                G.add_edge(v,w)

        # Output the graph is requested
        if hasattr(args,'savegraph') and args.savegraph:
            writeGraph(G,
                       args.savegraph,
                       args.graphformat,
                       graph_type='simple')

        return G
Esempio n. 45
0
def demo():
    '''
    Run a demo showing how a random, ugly network graph evolves into
    a much nicer-looking graph.
    '''
    size = 8
    G = nx.gnm_random_graph(size,11)
    seed = nx.spring_layout(G)
    evol = run_simulation(G,seed)
Esempio n. 46
0
def graphFactoryPlanarNormalDistribution(nb_graph,size_graph,graphtype,location,spread,section='all'):
    cpt=0
    while cpt <= nb_graph:
        rdm_density = np.random.normal(location,spread)
        G = nx.gnm_random_graph(size_graph,edgeForDensity(size_graph,rdm_density))
        if graphToCSV(G,graphtype,section,pl.is_planar(G)):
            cpt+=1
            if cpt%10 == 0:
                print(str(cpt)+'/'+str(nb_graph)+' '+str(100*cpt/nb_graph)+'%')
Esempio n. 47
0
def graphFactoryPlanar(nb_graph, size_graph, graphtype, section='all'):
    cpt = 0
    while cpt <= nb_graph:
        m = np.random.random_sample(1)
        G = nx.gnm_random_graph(size_graph,edgeForDensity(size_graph,m))
        if graphToCSV(G,graphtype,section,pl.is_planar(G)):
            cpt+=1
            if cpt%10 == 0:
                print(str(cpt)+'/'+str(nb_graph)+' '+str(100*cpt/nb_graph)+'%')
def build_random_network(n=100, m=300, directed=False):
    """
    Builds a random network with n nodes (default n=100) and m edges
    (default m=300).
    """

    network = nx.gnm_random_graph(n, m, directed=directed)

    return network
Esempio n. 49
0
def RandomGNM(n, m, dense=False, seed=None):
    """
    Returns a graph randomly picked out of all graphs on n vertices
    with m edges.

    INPUT:


    -  ``n`` - number of vertices.

    -  ``m`` - number of edges.

    -  ``dense`` - whether to use NetworkX's
       dense_gnm_random_graph or gnm_random_graph


    EXAMPLES: We show the edge list of a random graph on 5 nodes with
    10 edges.

    ::

        sage: graphs.RandomGNM(5, 10).edges(labels=False)
        [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

    We plot a random graph on 12 nodes with m = 12.

    ::

        sage: gnm = graphs.RandomGNM(12, 12)
        sage: gnm.show()  # long time

    We view many random graphs using a graphics array::

        sage: g = []
        sage: j = []
        sage: for i in range(9):
        ...    k = graphs.RandomGNM(i+3, i^2-i)
        ...    g.append(k)
        ...
        sage: for i in range(3):
        ...    n = []
        ...    for m in range(3):
        ...        n.append(g[3*i + m].plot(vertex_size=50, vertex_labels=False))
        ...    j.append(n)
        ...
        sage: G = sage.plot.graphics.GraphicsArray(j)
        sage: G.show()  # long time
    """
    if seed is None:
        seed = current_randstate().long_seed()
    import networkx

    if dense:
        return graph.Graph(networkx.dense_gnm_random_graph(n, m, seed=seed))
    else:
        return graph.Graph(networkx.gnm_random_graph(n, m, seed=seed))
 def setUp(self):
     self.graph = nx.gnm_random_graph(N,E)
     for e in self.graph.edges():
         self.graph[e[0]][e[1]]['weight'] = random.random()
     
     self.atheta = { n : np.random.random((Z))/Z for n in self.graph.nodes() }
     
     pcgpath = cg_path + 'model.social.tapmodel.TAPModel.__init__.png'
     with Profile(pcgpath):
         self.T = TAPModel(self.graph, self.atheta)
Esempio n. 51
0
def demo_evolution():
    '''
    Run a demo showing how a random, ugly network graph evolves into
    a much nicer-looking graph, using an asexually-reproducing
    evolutionary algorithm.
    '''
    size = 8
    G = nx.gnm_random_graph(size,11)
    seed = nx.spring_layout(G)
    evol = evolve_asexually(G,seed)
Esempio n. 52
0
def make_graph(num_nodes, num_edges, seed=None, directed=True):
    # create the graph 
    # (if we use the same seed every time, we'll get the same graph)
    graph = nx.gnm_random_graph(num_nodes, num_edges, seed=seed,
                                directed=directed)
    # assign edge weights
    # (again we use a seed so we get the same weights every time)
    random.seed(seed)
    for _, _, edge_attrs in graph.edges_iter(data=True):
        edge_attrs['weight'] = random.randint(0, 99)
    return graph
def create_3(nodes, edges):
    conn = 1
    loop_count = 0

    while conn < 3 and loop_count < 1000:
        G = nx.gnm_random_graph(nodes, edges)
        conn = nx.node_connectivity(G)

        loop_count = loop_count + 1

    return G
Esempio n. 54
0
def random_connected_graph(numNodes, numEdges):
    '''Generates a weakly connected random graph with numNodes nodes
       and numEdges edges
    '''
    tries = 0
    while tries < 100:
        tries += 1
        random_graph = nx.gnm_random_graph(numNodes,numEdges,directed = True)
        if nx.is_weakly_connected(random_graph): 
            return random_graph
    return None
Esempio n. 55
0
def randomize_graph(n,e):
    """
    Creates 1000 random graphs with networkx.gnm_random_graph(nodecount, edgecount),
    and computes average_clustering_coefficient and average_shortest_path_length,
    to compare with drama-graph.
    Returns a tuple:
    randavgpathl, randcluster = (float or "NaN", float or "NaN")
    """
    randcluster = 0
    randavgpathl = 0
    c = 0
    
    for i in range(0, 1000):
        R = nx.gnm_random_graph(n, e)
        try:
            randcluster += nx.average_clustering(R)
            c += 1
        except ZeroDivisionError:
            pass
        j = 0
        while True:
            j += 1
            try:
                R = nx.gnm_random_graph(n, e)
                randavgpathl += nx.average_shortest_path_length(R)
            except:
                pass
            else:
                break
            if j > 50:
                randavgpathl = "NaN"
                break
    try:
        randcluster = randcluster / c
    except:
        randcluster = "NaN"
    try:
        randavgpathl = randavgpathl / 1000
    except:
        randavgpathl = "NaN"
    return randavgpathl, randcluster
Esempio n. 56
0
def make_gnms():
    for n in [10, 1000, 2000, 3000, 4000, 5000]:
        for d in [3,4]:
            m = (d*n)/2
            G = nx.gnm_random_graph(n,m)
            R = random.sample(G.nodes(), n/10)
            name = 'gnm-{0}-{1}-0'.format(n,m)
            write_graph(G, name, 0, 1, R)

            R = random.sample(G.nodes(), n/2)
            name = 'gnm-{0}-{1}-1'.format(n,m)
            write_graph(G, name, 0, 1, R)
Esempio n. 57
0
    def _generate_graph(self):
        samples = [
            nx.gnm_random_graph(self._cstarrt['Nodes'], self._cst['Edges'], directed=True),
        ]

        while self._maxtry:
            self._maxtry -= 1
            graph = random.sample(samples, 1)[0]
            if self._is_valid_graph(graph):
                return graph
        print "can't generate DAG worker graph"
        raise
Esempio n. 58
0
def random_regulatory(num_nodes, num_activating, num_inhibiting,
        function="function", seed=None):
    net = nx.gnm_random_graph(num_nodes, num_activating + num_inhibiting,
            seed=seed, directed=True)
    edges = net.edges()
    activating = random.sample(edges, num_activating)
    for (u, v) in activating:
        net[u][v][function] = 1
    for (u, v) in list(set(edges) - set(activating)):
        net[u][v][function] = -1
    add_self_inhibition(net, function)
    return net
Esempio n. 59
0
    def obtain_graph(args,suffix=""):
        """Build a Graph according to command line arguments

        Arguments:
        - `args`: command line options
        """
        if getattr(args,'gnd'+suffix) is not None:

            n,d = getattr(args,'gnd'+suffix)
            if (n*d)%2 == 1:
                raise ValueError("n * d must be even")
            G=networkx.random_regular_graph(d,n)

        elif getattr(args,'gnp'+suffix) is not None:

            n,p = getattr(args,'gnp'+suffix)
            G=networkx.gnp_random_graph(n,p)

        elif getattr(args,'gnm'+suffix) is not None:

            n,m = getattr(args,'gnm'+suffix)
            G=networkx.gnm_random_graph(n,m)

        elif getattr(args,'grid'+suffix) is not None:

            G=networkx.grid_graph(getattr(args,'grid'+suffix))

        elif getattr(args,'torus'+suffix) is not None:
            
            G=networkx.grid_graph(getattr(args,'torus'+suffix),periodic=True)

        elif getattr(args,'complete'+suffix) is not None:

            G=networkx.complete_graph(getattr(args,'complete'+suffix))

        elif getattr(args,'empty'+suffix) is not None:

            G=networkx.empty_graph(getattr(args,'empty'+suffix))

        elif getattr(args,'graphformat'+suffix) is not None:

            try:
                print("INFO: reading simple graph {} from '{}'".format(suffix,getattr(args,"input"+suffix).name),
                      file=sys.stderr)
                G=readGraph(getattr(args,'input'+suffix),
                            "simple",
                            getattr(args,'graphformat'+suffix))
            except ValueError,e:
                print("ERROR ON '{}'. {}".format(
                    getattr(args,'input'+suffix).name,e),
                      file=sys.stderr)
                exit(-1)
Esempio n. 60
0
 def __init__(self, n, m, seed=None):
     """ Produces a graph picked randomly 
     out of the set of all graphs 
     with n nodes and m edges.
     @param n: Number of nodes
     @param m: Number of edges
     @param seed: Seed for random number generator (default=None).
     @return: The Topology
     """
     Topo.__init__(self, name='Random')
     self.n = n
     self.m = m
     self.G = nx.gnm_random_graph(n, m)