Beispiel #1
4
def pytest_generate_tests(metafunc):
    """
    Generate the arguments for test funcs
    """

    if "testgraph" in metafunc.funcargnames:
        testgraphs = []

    # 100 vertex random undirected graph
        a = nx.gnp_random_graph(100, 0.1)
        for u, v in a.edges_iter():    
            a.add_weighted_edges_from([(u, v, uniform(0, 100))])
        edge_list = []
        for u, v, w in a.edges_iter(data = True):
            edge_list.append((u, v, w['weight']))
        e = iter(edge_list)
        deg = sg.wgraph.make_deg(a.order(), e)
        e = iter(edge_list)
        b = sg.wgraph.make(a.order(), a.size(), e, deg)

    # 100 vertex random directed graph
        c = nx.gnp_random_graph(100, 0.1, directed = True)
        for u, v in c.edges_iter():    
            c.add_weighted_edges_from([(u, v, uniform(0, 100))])
        edge_list = []
        for u, v, w in c.edges_iter(data = True):
            edge_list.append((u, v, w['weight']))
        e = iter(edge_list)
        deg = sg.wdigraph.make_deg(c.order(), e)
        e = iter(edge_list)
        d = sg.wdigraph.make(c.order(), c.size(), e, deg)
        testgraphs.append((a, b, c, d))


        metafunc.parametrize("testgraph", testgraphs)
    def generateGraph(self, max_available_capacity):
        """
    	"""
        OSPF_weights = [2, 4]
        
        # Generate random nodes and edges
    	graph_tmp = nx.gnp_random_graph(self.n, self.p)
        while not nx.is_connected(graph_tmp):
            graph_tmp = nx.gnp_random_graph(self.n, self.p)

        # Turn it into directed graph
        graph = graph_tmp.to_directed()

        # Generate random OSPF weights and capacities
    	taken = []
        for (x,y) in graph.edges_iter():
            # Generate capacities first
            capacity = random.randint(5, max_available_capacity)
            graph[x][y]['capacity'] = capacity
            
            # Generate OSPF weights
            if (x,y) not in taken:
                # Generate random weight
                index1 = random.randint(0, 1)
                index2 = random.randint(0, 1)
                graph[x][y]['weight'] = OSPF_weights[index1]
                graph[y][x]['weight'] = OSPF_weights[index2] 
                taken.append((x,y))
                taken.append((y,x))

        return graph
Beispiel #3
0
def pytest_generate_tests(metafunc):
    """
    Generate the arguments for test functions.
    """

    if "graph" in metafunc.funcargnames:
        wgraphs = []

        # 100 vertex random graph
        a = nx.gnp_random_graph(100, 0.1)
        for e in a.edges_iter(data = True):
            e[2]['weight'] = triangular(-2, 2, 0)
        deg = sg.wgraph.make_deg(a.order(), create_iter(a.edges_iter(data = True)))
        b = sg.wgraph.make(a.order(), a.size(), create_iter(a.edges_iter(data = True)), deg)
        wgraphs.append((a, b))
        
        # 100 vertex random graph with parallel edges
        a = nx.gnp_random_graph(100, 0.1)
        for e in a.edges_iter(data = True):
            e[2]['weight'] = triangular(-2, 2, 0)
        deg = sg.wgraph.make_deg(a.order(), chain(create_iter(a.edges_iter(data = True)), create_iter(a.edges_iter(data = True))))
        b = sg.wgraph.make(a.order(), 2 * a.size(), chain(create_iter(a.edges_iter(data = True)), create_iter(a.edges_iter(data = True))), deg)
        wgraphs.append((a, b))
        
        # 100 vertex random graph with overestimated edge count
        a = nx.gnp_random_graph(100, 0.1)
        for e in a.edges_iter(data = True):
            e[2]['weight'] = triangular(-2, 2, 0)
        deg = sg.wgraph.make_deg(a.order(), create_iter(a.edges_iter(data = True)))
        b = sg.wgraph.make(a.order(), 2 * a.size(), create_iter(a.edges_iter(data = True)), deg)
        wgraphs.append((a, b))
        
        metafunc.parametrize("graph", wgraphs)
Beispiel #4
0
def vnet_gen(snet, num_standby, fixed_node):
    """
    Generate virtual topology
    Parameters: 
    snet: the substrate network topology
    num_standby: the number of standby routers requested by a customer
    """
    node_list = snet.nodes()

    
    # minimum number of vnodes in a virtual network has to be three, but do 
    # not need to use all of the virtual nodes excluding the reserved standby 
    # virtual routers.     
    # In order to make sure every VN has a VR from a common substrate node, first remove the fixed node from the list
    rest_list = copy.deepcopy(node_list)
    rest_list.remove(fixed_node)
    vnode_in_topo = random.randint(3, len(rest_list) - num_standby)

    #vnode_in_topo = random.randint(5, len(rest_list) - num_standby)
    #vnode_in_topo = 100
    vnet_nodes = random.sample(set(rest_list), vnode_in_topo)
    vnet_nodes.append(fixed_node)
    rand_vnet = nx.gnp_random_graph(len(vnet_nodes), 0.3)
    # Avoid to create VNs with isolatd VRs
    check = check_degree(rand_vnet)
    while(check != 1):
        rand_vnet = nx.gnp_random_graph(len(vnet_nodes), 0.3)
        check = check_degree(rand_vnet)
    # relabel the nodes in the VN
    vnet = conf_vnet(rand_vnet, vnet_nodes)
    # remove selfloop edges
    vnet.remove_edges_from(vnet.selfloop_edges())
    return vnet
Beispiel #5
0
def pytest_generate_tests(metafunc):
    """
    Generate the arguments for test functions.
    """

    if "digraph" in metafunc.funcargnames:
        digraphs = []

        # 100 vertex random graph
        a = nx.gnp_random_graph(100, 0.1, directed=True)
        deg = sg.digraph.make_deg(a.order(), a.edges_iter())
        b = sg.digraph.make(a.order(), a.size(), a.edges_iter(), deg)
        digraphs.append((a, b))
        
        # 100 vertex random graph with parallel edges
        a = nx.gnp_random_graph(100, 0.1, directed=True)
        deg = sg.digraph.make_deg(a.order(), a.edges() + a.edges())
        b = sg.digraph.make(a.order(),  2 * a.size(), a.edges() + a.edges(), deg)
        digraphs.append((a, b))
        
        # 100 vertex random graph with overestimated edge count
        a = nx.gnp_random_graph(100, 0.1, directed=True)
        deg = sg.digraph.make_deg(a.order(), a.edges_iter())
        b = sg.digraph.make(a.order(), 2 * a.size(), a.edges_iter(), deg)
        digraphs.append((a, b))

        metafunc.parametrize("digraph", digraphs)
def pytest_generate_tests(metafunc):
    """
    Generate the arguments for test funcs
    """

    if "testgraph" in metafunc.funcargnames:
        testgraphs = []

        # 100 vertex random graph
        a = nx.gnp_random_graph(100, 0.1, directed=True)
        b = nx.gnp_random_graph(100, 0.1, directed=True)
        deg = sg.digraph.make_deg(a.order(), a.edges_iter())
        c = sg.digraph.make(a.order(), a.size(), a.edges_iter(), deg)
        deg = sg.digraph.make_deg(b.order(), b.edges_iter())
        d = sg.digraph.make(b.order(), b.size(), b.edges_iter(), deg)
        testgraphs.append((a, b, c, d))

        metafunc.parametrize("testgraph", testgraphs)

    if "mismatch_graph" in metafunc.funcargnames:
        mismatch_graphs = []

        a = nx.gnp_random_graph(100, 0.1, directed=True)
        b = nx.gnp_random_graph(150, 0.1, directed=True)
        deg = sg.digraph.make_deg(a.order(), a.edges_iter())
        c = sg.digraph.make(a.order(), a.size(), a.edges_iter(), deg)
        deg = sg.digraph.make_deg(b.order(), b.edges_iter())
        d = sg.digraph.make(b.order(), b.size(), b.edges_iter(), deg)
        mismatch_graphs.append((c, d))

        metafunc.parametrize("mismatch_graph", mismatch_graphs)
Beispiel #7
0
def generate_random_graph():
    if probability_of_graph_construction==0:
        k = rand()
    else:
        k = probability_of_graph_construction
    G=NX.gnp_random_graph(number_of_vertices, k) 
    while not(NX.is_connected(G)):
        G=NX.gnp_random_graph(number_of_vertices, k)
        k += 0.1
    return G
Beispiel #8
0
 def setUp(self):
     self.path = nx.path_graph(7)
     self.directed_path = nx.path_graph(7, create_using=nx.DiGraph())
     self.cycle = nx.cycle_graph(7)
     self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
     self.gnp = nx.gnp_random_graph(30, 0.1)
     self.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True)
     self.K20 = nx.complete_graph(20)
     self.K10 = nx.complete_graph(10)
     self.K5 = nx.complete_graph(5)
     self.G_list = [self.path, self.directed_path, self.cycle,
         self.directed_cycle, self.gnp, self.directed_gnp, self.K10, 
         self.K5, self.K20]
def pagerank_vs_hitting_time(num_graphs):
    graphs = []
    prs = []
    hts = []
    corrs = []
    for i in xrange(num_graphs):
        g = nx.gnp_random_graph(NUM_NODES, float(NUM_EDGES) / NUM_NODES,
                                directed=True)
        graphs.append(g)
        for e in g.edges_iter():
            g[e[0]][e[1]]['weight'] = random.random()

        prs.append(tm.pagerank(g))
        hts.append(tm.hitting_pagerank(g, 'all'))
        corrs.append(stats.spearmanr(prs[i], hts[i])[0])

        sys.stdout.write('.')

    # Plot correlations
    plt.hist(corrs)

    plt.suptitle('Correlation of PageRank and Eigen Hitting Time\n'
                 'Trials on Erdos-Renyi graphs with %d nodes and prob %0.2f'
                 % (NUM_NODES, float(NUM_EDGES) / NUM_NODES))
    plt.xlabel('Spearman rank-correlation')
    plt.ylabel('Number of graphs (independent trials)')
    plt.margins(0.07)
    plt.show()
Beispiel #10
0
def erdoes_3d_plot(number_of_average):
	N = np.arange(5, 105, 5)
	X = N
	P = arange(0, 0.2, 0.005)
	Y = P
	X, Y = np.meshgrid(X, Y)
	Z = X/2

	for i in range(len(N)):
		n = N[i]
		print n
		p = 0
		for j in range(len(P)):
			if n > 50 and p > 0.1:
				Z[j][i] = 100
				continue
			average = 0
			for av in range(number_of_average):
				G = nx.gnp_random_graph(n, p, None, 1)
				graph = Graph(G)
				graph.stats()
				average = average + graph.bow_tie[1]
			average = average / number_of_average
			Z[j][i] = average
			p = p + 0.01

	plot_3d(X, Y, Z, '3d_erdoes.png', 'nodes', 'probability of edge creation', 'scc [%]')
def random_weighted_graph(num_nodes, edge_prob, weight_dist='uniform'):
    """ Returns a Erdos-Renyi graph with edge weights. """
    g = nx.gnp_random_graph(num_nodes, edge_prob, directed=True)
    weights = agent_type_rv(weight_dist).rvs(size=g.number_of_edges())
    for i, e in enumerate(g.edges_iter()):
        g[e[0]][e[1]]['weight'] = weights[i]
    return g
Beispiel #12
0
def create_graph(N_nodes,p_edge,n_infected,regular = False):
    if regular:
        k = int(round(p_edge*(N_nodes-1)))
        G = nx.random_regular_graph(k,N_nodes)
    else:
        G = nx.gnp_random_graph(N_nodes,p_edge,directed=False)
    return set_graph_strategies(G, n_infected)
def gnp_survey_benchmark(path, n_array, p_array):
    with open(path, 'w', newline='\n') as f:
        w = csv.writer(f)
        w.writerow(['n', 'p = 0.2', 'p = 0.4', 'p = 0.5', 'p = 0.6', 'p = 0.8'])
        for n in n_array:
            list = [str(n)]
            for p in p_array:
                print("Starting trial n = " + str(n) + ", p = " + str(p) + ".")
                G = nx.gnp_random_graph(n, p)
                for (i, j) in G.edges_iter():
                    G[i][j]['weight'] = 1
                print("Calling GH algorithm")
                ############ TIMING ############
                start = time.time()
                gh = gomory_hu_tree(G)
                end = time.time()
                t = end-start
                ########## END TIMING ##########
                list.append(t)
                print("Completed trial n = " + str(n) + ", p = " + str(p) + ".")
                print("Time = " + str(t))
                nx.write_adjlist(G, 'Graph(' + str(n) + "," + str(p) + ").csv")
                nx.write_adjlist(gh, 'Gomory_Hu(' + str(n) + "," + str(p) + ").csv")
                print()
            w.writerow(list)
 def test_eigenvector_v_katz_random(self):
     G = nx.gnp_random_graph(10,0.5, seed=1234)
     l = float(max(eigvals(nx.adjacency_matrix(G).todense())))
     e = nx.eigenvector_centrality_numpy(G)
     k = nx.katz_centrality_numpy(G, 1.0/l)
     for n in G:
         assert_almost_equal(e[n], k[n])
def test_random_gnp():
    # seeds = [1550709854, 1309423156, 4208992358, 2785630813, 1915069929]
    seeds = [12, 13]

    for seed in seeds:
        G = nx.gnp_random_graph(20, 0.2, seed=seed)
        _check_edge_connectivity(G)
Beispiel #16
0
def generate_systems(prop_step=5, o_size=20):
    """ Generate population of systems
    """
    para_range = np.linspace(0, 1, prop_step)
    o_range = np.random.uniform(0, 3, o_size)

    systs = []
    for p in para_range:
        systs.append([])

        # setup network
        graph = nx.gnp_random_graph(20, p)

        dim = len(graph.nodes())
        Bvec = np.random.uniform(0, 5, size=dim)

        for omega in o_range:
            # setup dynamical system
            system_config = get_base_config(
                nx.to_numpy_matrix(graph), Bvec, omega)

            systs[-1].append(DW({
                'graph': graph,
                'system_config': system_config
            }))

    return systs, para_range
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)
Beispiel #18
0
 def connect_gnp(self,N,p):
     """
     Erdos-Renyi (Poisson random) graph G(N,p).
     """
     # this is kind of a dumb way to do this
     self.connect_empty(N)
     self.add_edges_from(nx.gnp_random_graph(N,p).edges())
def barabasi_gen(start_size, total_size, m):
    """
    Generate a graph according to the process outlined in Barabasi
    and Albert, where vertices are added one at a time, and attach to
    existing vertices with probability:
        p(existing) = deg(existing) / sum(deg(all_vertices))
    """
    if m > start_size:
        print("m must be >= than the initial number of vertices")
        return None
    # Start with an Erdos-Renyi random graph?
    g = networkx.gnp_random_graph(start_size, p=(m / start_size))
    # Need to number each node, so start with:
    new_node = start_size + 1
    while len(g) < total_size:
        # Create the list of other nodes before adding the new node,
        # easiest way to do it
        others = g.nodes()
        # Calculate the probabilities every time, or find a cleverer
        # way of updating the values?
        total_degree = sum(deg for node, deg in g.degree_iter())
        g.add_node(new_node)
        while g.degree(new_node) < m:
            node_to_check = random.choice(others)
            prob = g.degree(node_to_check) / total_degree
            dice_roll = random.random()
            if dice_roll < prob:
                g.add_edge(new_node, node_to_check)
        new_node += 1
    return g
Beispiel #20
0
def test_models_yaml():
    '''Creates a random models, saves them in yaml format, loads them from file,
    and compares the generated and loaded system models.
    '''
    for M, init_factory in ((Model, set), (Ts, set),
                            (Markov, lambda l: dict([(x, 1) for x in l]))):
        # generate random model
        model = M('Random system model', directed=True, multi=False)
        model.g = nx.gnp_random_graph(n=100, p=0.5, seed=1, directed=True)
        model.init = init_factory(random.sample(model.g.nodes(), 5))
        model.final = set(random.sample(model.g.nodes(), 5))

        # save system model to temporary yaml file
        f = tempfile.NamedTemporaryFile(mode='w+t', suffix='.yaml',
                                        delete=False)
        f.close()
        print('Saving', M.__name__, 'system model to', f.name)
        model.save(f.name)

        # load system model from temporary yaml file
        print('Loading', M.__name__, 'system model from', f.name)
        model2 = M.load(f.name)
    
        # test that the two system models are equal
        assert(model == model2), '{} are not equal!'.format(M.__name__)

        # remove temporary file
        os.remove(f.name)
Beispiel #21
0
def graphFactoryPlanarErdosRenyiGenration(nb_graph,size_graph,graphtype,edgeProba,section='all'):
    cpt=0
    while cpt <= nb_graph:
        G = nx.gnp_random_graph(size_graph,edgeProba)
        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 test_gnp_augmentation():
    rng = random.Random(0)
    G = nx.gnp_random_graph(30, 0.005, seed=0)
    # Randomly make edges available
    avail = {(u, v): 1 + rng.random()
             for u, v in complement_edges(G)
             if rng.random() < .25}
    _check_augmentations(G, avail)
Beispiel #23
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
def draw_random_graph(i):
    """
    Draw a random graph with 2**i nodes,
    and p=i/(2**i)
    """
    g_random = nx.gnp_random_graph(2**i,2*i/(2**i))
    nx.draw(g_random,node_size=20)
    plt.savefig("./random_graph.svg")
    plt.close()
Beispiel #25
0
def test_spanner_unweighted_gnp_graph():
    """Test spanner construction on an unweighted gnp graph."""
    G = nx.gnp_random_graph(20, 0.4, seed=_seed)

    spanner = nx.spanner(G, 4, seed=_seed)
    _test_spanner(G, spanner, 4)

    spanner = nx.spanner(G, 10, seed=_seed)
    _test_spanner(G, spanner, 10)
 def setUp(self):
     self.Gnp = nx.gnp_random_graph(20, 0.8)
     self.Anp = _AntiGraph(nx.complement(self.Gnp))
     self.Gd = nx.davis_southern_women_graph()
     self.Ad = _AntiGraph(nx.complement(self.Gd))
     self.Gk = nx.karate_club_graph()
     self.Ak = _AntiGraph(nx.complement(self.Gk))
     self.GA = [(self.Gnp, self.Anp),
                (self.Gd, self.Ad),
                (self.Gk, self.Ak)]
Beispiel #27
0
def test_spanner_weighted_gnp_graph():
    """Test spanner construction on an weighted gnp graph."""
    G = nx.gnp_random_graph(20, 0.4, seed=_seed)
    _assign_random_weights(G, seed=_seed)

    spanner = nx.spanner(G, 4, weight='weight', seed=_seed)
    _test_spanner(G, spanner, 4, weight='weight')

    spanner = nx.spanner(G, 10, weight='weight', seed=_seed)
    _test_spanner(G, spanner, 10, weight='weight')
Beispiel #28
0
def random_gen(topo_config):
    """
    create a random topology
    the topo_config is a tuple: (num_nodes, prob)
    """
    num_nodes, prob = topo_config
    print("Create random topology of {0} with edge generating \
            probability of {1}".format(num_nodes, prob))
    G = nx.gnp_random_graph(num_nodes, prob)
    return G
Beispiel #29
0
def ajax_build_graph_view(request, graph_id):
    graph = get_object_or_404(Graph, id=graph_id)
    size = graph.size
    graph_type = graph.graph_type
    if graph_type == 'random':
        G = nx.gnp_random_graph(size,0.1)
    else:
        G = nx.scale_free_graph(size)
    vega_graph = build_vega_graph(G)
    return HttpResponse(vega_graph, mimetype="text/javascript")
Beispiel #30
0
def fast_gnp_random_graph(n, p, seed=None):
    """Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph).

    Parameters
    ----------
    n : int
        The number of nodes.
    p : float
        Probability for edge creation.
    seed : int, optional
        Seed for random number generator (default=None). 
      
    Notes
    -----
    The G_{n,p} graph algorithm chooses each of the [n(n-1)]/2
    (undirected) or n(n-1) (directed) possible edges with probability p.

    This algorithm is O(n+m) where m is the expected number of
    edges m=p*n*(n-1)/2.
    
    It should be faster than gnp_random_graph when p is small and
    the expected number of edges is small (sparse graph).

    See Also
    --------
    gnp_random_graph

    References
    ----------
    .. [1] Batagelj and Brandes, "Efficient generation of large random networks",
       Phys. Rev. E, 71, 036113, 2005.
    """
    G=empty_graph(n)
    G.name="fast_gnp_random_graph(%s,%s)"%(n,p)

    if not seed is None:
        random.seed(seed)

    if p<=0 or p>=1:
        return nx.gnp_random_graph(n,p)

    v=1  # Nodes in graph are from 0,n-1 (this is the second node index).
    w=-1
    lp=math.log(1.0-p)  

    while v<n:
        lr=math.log(1.0-random.random())
        w=w+1+int(lr/lp)
        while w>=v and v<n:
            w=w-v
            v=v+1
        if v<n:
            G.add_edge(v,w)
    return G
Beispiel #31
0
def fast_gnp_random_graph(n, p, seed=None, directed=False):
    """Returns a `G_{n,p}` random graph, also known as an Erdős-Rényi graph or
    a binomial graph.

    Parameters
    ----------
    n : int
        The number of nodes.
    p : float
        Probability for edge creation.
    seed : int, optional
        Seed for random number generator (default=None).
    directed : bool, optional (default=False)
        If ``True``, this function returns a directed graph.

    Notes
    -----
    The `G_{n,p}` graph algorithm chooses each of the `[n (n - 1)] / 2`
    (undirected) or `n (n - 1)` (directed) possible edges with probability `p`.

    This algorithm runs in `O(n + m)` time, where `m` is the expected number of
    edges, which equals `p n (n - 1) / 2`. This should be faster than
    :func:`gnp_random_graph` when `p` is small and the expected number of edges
    is small (that is, the graph is sparse).

    See Also
    --------
    gnp_random_graph

    References
    ----------
    .. [1] Vladimir Batagelj and Ulrik Brandes,
       "Efficient generation of large random networks",
       Phys. Rev. E, 71, 036113, 2005.
    """
    G = empty_graph(n)
    G.name = "fast_gnp_random_graph(%s,%s)" % (n, p)

    if not seed is None:
        random.seed(seed)

    if p <= 0 or p >= 1:
        return nx.gnp_random_graph(n, p, directed=directed)

    w = -1
    lp = math.log(1.0 - p)

    if directed:
        G = nx.DiGraph(G)
        # Nodes in graph are from 0,n-1 (start with v as the first node index).
        v = 0
        while v < n:
            lr = math.log(1.0 - random.random())
            w = w + 1 + int(lr / lp)
            if v == w:  # avoid self loops
                w = w + 1
            while w >= n and v < n:
                w = w - n
                v = v + 1
                if v == w:  # avoid self loops
                    w = w + 1
            if v < n:
                G.add_edge(v, w)
    else:
        # Nodes in graph are from 0,n-1 (start with v as the second node index).
        v = 1
        while v < n:
            lr = math.log(1.0 - random.random())
            w = w + 1 + int(lr / lp)
            while w >= v and v < n:
                w = w - v
                v = v + 1
            if v < n:
                G.add_edge(v, w)
    return G
Beispiel #32
0
    def generate(self,
                 meanfriends=5,
                 sdfriends=5,
                 frienddist="uni",
                 connectdist="watstro"):
        #generates object and the f network
        for a in range(self.size):
            self.gf.add_node(a, obj=Agent(a))
        if connectdist == "CStyle":
            for a in range(self.size):
                #

                #self.gf.add_node(a,obj=______object_____)

                #
                tar = ["r"]
                friends = []
                for b in list(self.gf[a]):
                    friends.append(b)
                    for c in list(self.gf[b]):
                        tar.append(c)

                if frienddist == "uni":
                    #numf=rng.uniform()
                    #numf=numf*meanfriends//1+5
                    numf = 5
                    #numf=15-len(friends)
                    #if numf <0:
                    #   numf=1
                    numf = int(numf)
                if connectdist == "CStyle":
                    for aa in range(numf):
                        nex = rng.choice(tar)
                        if nex == "r" or int(nex) in friends + ["r", a]:
                            while nex in friends + ["r", a] or int(
                                    nex) in friends + ["r", a]:
                                nex = int(rng.choice(range(self.size)))
                        nex = int(nex)
                        self.gf.add_edge(a, int(nex))
                        tar = tar + list(self.gf[nex])
                        friends.append(nex)
                if len(self.gf[a]) < 5:
                    print(a)
                    print(friends)
                    print(self.gf[a])
                    print(" \n")
        elif connectdist == "randomunif":
            #notperfect
            numf = 10
            connect = {k: [] for k in range(self.size)}
            li = []
            for a in range(self.size - 1):
                it = 0
                while len(connect[a]) < numf and it < 100:
                    it += 1
                    r = rng.choice(range(a + 1, self.size))
                    if len(connect[r]) < 10 or r in connect[a]:
                        #print(a,r)
                        li.append([int(a), int(r)])
                        connect[a].append(r)
                        connect[r].append(a)
                print(a, it, len(connect[a]))
            print(len(li))
            for b, c in li:
                self.gf.add_edge(b, c)
                #gnm_random_graph(n, m, seed=None, directed=False)
                #connected_watts_strogatz_graph(n, k, p[, ...])
            #if len(self.gf[a])<5:
            #   print(a)
            #  print(friends)
            # print(self.gf[a])
            #print(" \n")
        elif connectdist == "randomunif2":
            al = []
            numf = 10
            for a in range(numf):
                al = al + list(range(self.size))
            con = []
            al2 = al
            rng.shuffle(al2)
            it = 0
            while it < 10000:
                it += 1
                if len(al2) >= 1:
                    cand = al2[:2]
                    if cand[0] != cand[
                            1] and cand not in con and cand[::-1] not in con:
                        con.append(frozenset(al2[:2]))
                        al2 = al2[2:]
                    else:
                        rng.shuffle(al2)
                else:
                    break
            print(con, len(con), len(set(con)), it)
            for b, c in con:
                self.gf.add_edge(b, c)
        elif connectdist == "prederd":
            n = self.size
            k = 10 / (n - 1)
            te = nx.gnp_random_graph(n, k)
            self.gf.add_edges_from(te.edges)
        elif connectdist == "watstro":
            n = self.size
            p = 0.05
            k = 10
            te = nx.connected_watts_strogatz_graph(n, k, p, 100)
            self.gf.add_edges_from(te.edges)
        elif connectdist == "bara":
            n = self.size
            p = 0.05
            k = 5
            te = nx.barabasi_albert_graph(n, k)
            self.gf.add_edges_from(te.edges)
        elif connectdist == "pow":
            n = self.size
            #k=min(n/10,5)
            k = 4
            p = 0.05
            te = nx.powerlaw_cluster_graph(n, k, p)
            self.gf.add_edges_from(te.edges)
        elif connectdist == "full":
            n = self.size
            e = []
            for a in range(n - 1):
                for b in range(a + 1, n):
                    e.append(set([a, b]))
            self.gf.add_edges_from(e)

            #karate_club_graph()
        elif connectdist == "star":
            n = self.size
            e = []
            for a in range(n):
                e.append([a, (n + 1) % n])
            self.gf.add_edges_from(e)
        elif connectdist == "circle":
            n = self.size
            e = []
            for a in range(n):
                e.append([a, (a + 1) % n])
            self.gf.add_edges_from(e)
            #karate_club_graph()

        else:
            raise Exception("ERROR: UNVALID GENERATE KEY")

        self.agentsid = self.gf.nodes
        for a in self.agentsid:
            self.agents.append(self.getobj(a))

            friendsinstances = []
            for friend in self.friendsof(a):
                temp = self.getobj(friend)
                friendsinstances.append(temp)
            self.getobj(a).define_friends(friendsinstances)
        self.pos = nx.spring_layout(self.gf)
Beispiel #33
0
import networkx as nx
import matplotlib.pyplot as plt


def modularidad(g, atributo):
    A = nx.adjacency_matrix(g)
    B = 0
    m = len(g.edges())
    k = []
    name = []
    for key, value in g.degree():
        k.append(value)
        name.append(key)
    for i in range(len(k)):
        for j in range(len(k)):
            if g.node[name[i]][atributo] == g.node[name[j]][atributo]:
                B += A[i, j] - k[i] * k[j] / (2 * m)
    return float(B) / (2 * m)


if __name__ == '__main__':
    g = nx.gnp_random_graph(10, 0.3)
    for node, attrDict in dict(g.nodes()).items():
        attrDict['gender'] = 'a' if (node % 2 == 0) else 'b'

    colores = [('blue' if gender == 'a' else 'red')
               for gender in nx.get_node_attributes(g, "gender").values()]
    plt.figure()
    nx.draw(g, node_color=colores)
    print(modularidad(g, 'gender'))
Beispiel #34
0
def test_dominating_set():
    G = nx.gnp_random_graph(100, 0.1)
    D = nx.dominating_set(G)
    assert nx.is_dominating_set(G, D)
    D = nx.dominating_set(G, start_with=0)
    assert nx.is_dominating_set(G, D)
    posS[p][1] += 0.04  #offset 0.07
nx.draw_networkx_labels(condensation_graph_relabeled, posS)
# plt.savefig('foo3.png')

### ΔΙΣΥΝΔΕΣΙΜΟΤΗΤΑ ΜΗ ΚΑΤΕΥΘΥΝΟΜΕΝΩΝ ΓΡΑΦΩΝ

# G = nx.barbell_graph(4,2)
#
#
# # G=nx.Graph()
# # G.add_edges_from([(0,1),(1,2),(2,0),(3,4)])
# # G.add_node(5)
# # pos={0:(0,0),1:(0,1),2:(0.5,1),3:(0.5,0),4:(1,0),5:(0.75,0.5)}
#
#
G = nx.gnp_random_graph(20, 0.1)
# G = nx.gnp_random_graph(15,0.04)
# G = nx.gnm_random_graph(15,10)
# # G = nx.barabasi_albert_graph(50,2)
# # G = nx.newman_watts_strogatz_graph(20,2,0.9)
# # G.add_node(55)
# # G.add_edges_from([(50,51),(51,52),(52,50),(53,54)])
#
# # G = nx.erdos_renyi_graph(15,0.06)
# pos=nx.spring_layout(G,k=0.15,iterations=10)
# # pos=nx.graphviz_layout(G)
# # pos=layout(G)

##### ΑΝΑΖΗΤΗΣΗ

number_of_biconnected_components = 2
Beispiel #36
0
 def test_result_gnp_20_0_95_4(self):
     assert (calc_and_compare(NX.gnp_random_graph(20, 0.95, 11)))
def erdos_renyi_lap(
    G
):  #ER build graphs based on individual proteins, so number of nodes and probability of those edges being created

    lap_test = []
    lap_test1 = []
    lap_test2 = []
    N = nx.number_of_nodes(G)
    E = nx.number_of_edges(G)
    prob_edges = ((
        (N * (N - 1)) / 2) / E) / 100  #divide by 100 float not percentage
    #print prob_edges
    '''start_time = time.time()
	for i in range(500):
		er_graph = nx.gnp_random_graph(N,prob_edges,seed=None) #number of nodes, probability for edge creation
		lap = nx.normalized_laplacian_matrix(er_graph, weight='weight')
		lap = np.eye(lap.shape[0])-lap 
		eigenvalues,eigenvectors = scipy.sparse.linalg.eigsh(lap,k=2)
		lap_sum = (eigenvalues[1]-eigenvalues[0]) 
		lap_test1.append(lap_sum)
	print lap_test1
	print ("--- %s seconds ---" % (time.time() - start_time))
	start_time = time.time()
	for i in range(500):
		er_graph = nx.fast_gnp_random_graph(N,prob_edges,seed=None) #number of nodes, probability for edge creation
		lap = nx.normalized_laplacian_matrix(er_graph, weight='weight')
		lap = np.eye(lap.shape[0])-lap 
		eigenvalues,eigenvectors = scipy.sparse.linalg.eigsh(lap,k=2)
		lap_sum = (eigenvalues[1]-eigenvalues[0]) 
		lap_test2.append(lap_sum)
	print lap_test2
	print ("--- %s seconds ---" % (time.time() - start_time))'''
    start_time = time.time()
    for i in range(500):
        er_graph = nx.erdos_renyi_graph(
            N, prob_edges,
            seed=None)  #number of nodes, probability for edge creation
        lap = nx.normalized_laplacian_matrix(er_graph, weight='weight')
        lap = np.eye(lap.shape[0]) - lap
        eigenvalues, eigenvectors = scipy.sparse.linalg.eigsh(lap, k=2)
        lap_sum = (eigenvalues[1] - eigenvalues[0])
        lap_test.append(lap_sum)
    print lap_test
    print("--- %s seconds ---" % (time.time() - start_time))
    start_time = time.time()
    for i in range(500):
        er_graph = nx.erdos_renyi_graph(
            N, prob_edges,
            seed=None)  #number of nodes, probability for edge creation
        lap = nx.normalized_laplacian_matrix(er_graph, weight='weight')
        lap = np.eye(lap.shape[0]) - lap
        eigenvalues, eigenvectors = np.linalg.eigh(lap)
        lap_sum = (eigenvalues[1] - eigenvalues[0])
        lap_test1.append(eigenvalues)
    print lap_test1
    print("--- %s seconds ---" % (time.time() - start_time))
    # using IGRAPH
    start_time = time.time()
    for i in range(500):
        er_graph = Graph.Erdos_Renyi(
            n=N, p=prob_edges, directed=True,
            loops=False)  #number of nodes, probability for edge creation
        lap = er_graph.laplacian(normalized=True)
        e = np.linalg.eigvals(lap)
        lap_test2.append(e)
    print lap_test2
    print("--- %s seconds ---" % (time.time() - start_time))
    start_time = time.time()

    for i in range(500):
        er_graph = nx.gnp_random_graph(
            N, prob_edges,
            seed=None)  #number of nodes, probability for edge creation
        '''lap = nx.normalized_laplacian_matrix(er_graph, weight='weight')
		lap = np.eye(lap.shape[0])-lap 
		eigenvalues,eigenvectors = scipy.sparse.linalg.eigsh(lap,k=2)
		lap_sum = (eigenvalues[1]-eigenvalues[0]) 
		lap_test1.append(lap_sum)'''
    print er_graph
    print("--- %s seconds ---" % (time.time() - start_time))
    start_time = time.time()
    for i in range(500):
        er_graph = nx.fast_gnp_random_graph(
            N, prob_edges,
            seed=None)  #number of nodes, probability for edge creation
        '''lap = nx.normalized_laplacian_matrix(er_graph, weight='weight')
		lap = np.eye(lap.shape[0])-lap 
		eigenvalues,eigenvectors = scipy.sparse.linalg.eigsh(lap,k=2)
		lap_sum = (eigenvalues[1]-eigenvalues[0]) 
		lap_test2.append(lap_sum)'''
    print er_graph
    print("--- %s seconds ---" % (time.time() - start_time))
    start_time = time.time()
    for i in range(500):
        er_graph = nx.erdos_renyi_graph(
            N, prob_edges,
            seed=None)  #number of nodes, probability for edge creation
        '''lap = nx.normalized_laplacian_matrix(er_graph, weight='weight')
		lap = np.eye(lap.shape[0])-lap 
		eigenvalues,eigenvectors = scipy.sparse.linalg.eigsh(lap,k=2)
		lap_sum = (eigenvalues[1]-eigenvalues[0]) 
		lap_test.append(lap_sum)'''
    print er_graph
    print("--- %s seconds ---" % (time.time() - start_time))
Beispiel #38
0
    def __init__(self, init_type, **kwargs): #init_type: {Directly, Random, From File, Random Tree, Random Chimera}
        
        
        if (init_type == "Directly"):
            if 'Const' in kwargs.keys():
                Const = kwargs['Const']
            else:
                Const = 0.0
            
            if 'Pot' in kwargs.keys():
                Pot = kwargs['Pot']
            else:
                Pot = np.zeros((1, len(kwargs['Inter'])))
                
            (self.Inter, self.Pot, self.Const) = (kwargs['Inter'], Pot, Const)
        elif (init_type == "Random"):
            
            if 'n' in kwargs.keys():
                n = kwargs['n']
            else:
                print("Should specify number of vertices n=")
                
            if 'p' in kwargs.keys():
                p = kwargs['p']
            else:
                print("Should specify the probability of an edge p=")    
            
            if 'seed' in kwargs.keys():
                seed = kwargs['seed']
            else:
                seed = None

            G = nx.gnp_random_graph(n, p, seed)
            A = csr_matrix.todense(nx.adjacency_matrix(G))

            (self.Inter, self.Pot, self.Const) = (Laplacian(A)/4, np.zeros((n)), 0)
            
        elif (init_type == "From File"):
            
            if 'filename' in kwargs.keys():
                filename = kwargs['filename']
            else:
                print("You should specify the filename!")
                
            import os
            name, extension = os.path.splitext(filename)

            if (extension == '.json'):
                (self.Inter, self.Pot, self.Const) = BQPJSON(filename)
                self.Inter = 1*self.Inter
                self.Pot = 1*self.Pot
                self.Const = 1*self.Const
            #elif (file_extension == '.mat'):
                #retrieve a dense graph from .mat file
            #elif (file_extension == '.sparse'):
                #retrieve a sparse graph from .sparse file
            else:
                print("Wrong File Extension")
                
        elif (init_type == "Random Chimera"):
            import dwave_networkx as dnx

            G = dnx.chimera_graph(kwargs['M'], kwargs['N'], kwargs['L'])
            A = csr_matrix.todense(nx.adjacency_matrix(G))

            (self.Inter, self.Pot, self.Const) = (Laplacian(A)/4, np.zeros((n)), 0)
        
        elif (init_type == "Random Tree"):
            
            if 'seed' in kwargs.keys():
                seed = kwargs['seed']
            else:
                seed = None
    
            if 'n' in kwargs.keys():
                n = kwargs['n']
            else:
                n = random.randint(10, 100)

            G = nx.random_tree(n, seed)
            A = csr_matrix.todense(nx.adjacency_matrix(G))
            
            (self.Inter, self.Pot, self.Const) = (Laplacian(A)/4, np.zeros((n)), 0)
Beispiel #39
0
import matplotlib.pyplot as plt
import seaborn as sns
import random
import numpy as np

n = 2
m = 10
numberOfneb = 1000
result = [[0 for i in range(m)] for j in range(n)]
numOfIterations = 0

for iz in range(10):
    print("iteraion i = ", iz, " % ", (iz + 1) / 10)
    result[0][iz] = (iz + 1) / 10
    gr2 = nx.gnp_random_graph(numberOfneb, (iz + 1) / 10,
                              seed=354,
                              directed=False)
    '''nx.draw(gr2, with_labels=True)'''
    pos = nx.spring_layout(gr2)

    labels = {}
    for x in range(len(gr2)):
        labels[x] = random.choice(['A', 'B', 'C'])
    '''print("Labels :", labels)'''

    neighbors = gr2.edges
    '''print("the neighbors: ", neighbors)'''

    m2 = 3
    votes = [[0 for i in range(m2)] for j in range(numberOfneb)]
    votes2 = [[0 for i in range(m2)] for j in range(numberOfneb)]
            continue
        in_flow = 0
        out_flow = 0
        for u in graph.predecessors(v):
            in_flow += graph.edges[u, v]["flow"]
        for w in graph.successors(v):
            out_flow += graph.edges[v, w]["flow"]
        if in_flow != out_flow:
            return False
    return True


if __name__ == "__main__":
    import random
    for i in range(100):
        G = nx.gnp_random_graph(100, 0.5, directed=True)
        DAG = nx.DiGraph([(u, v, {
            'capacity': random.randint(0, 10)
        }) for (u, v) in G.edges() if u < v])
        #visualize.visualize_graph(DAG, weight="capacity", filename="1.png")

        graph = compute_blocking_flow(DAG, 0, 99, 150)
        # l = list(graph.edges(data=True))
        # for u, v, attr in l:
        #     if attr["flow"] == 0:
        #         graph.remove_edge(u, v)
        # for u in graph.nodes:
        #     pass
        #     # print(graph.nodes[u]["excess"])
        # visualize.visualize_graph(graph, weight="flow", filename="2.png")
def random_graph():
    return nx.gnp_random_graph(rd.randint(1, 100), rd.random(), None,
                               rd.choice([True, False]))
Beispiel #42
0
    def update_item_graph(self, i, kk):
        Sinv1 = np.linalg.inv(self.S[i])
        theta1 = np.dot(Sinv1, self.b[i])

        C0 = set(nx.node_connected_component(self.GI, kk))
        # H = GI.subgraph(C0)
        A = [a for a in self.GI.neighbors(kk)]

        N0 = []
        N = [[] for l in range(len(A))]

        num_users = len(self.S)
        for j in range(num_users):
            if j == i:
                continue
            if invertible(self.S[j]):
                Sinv = np.linalg.inv(self.S[j])
                theta = np.dot(Sinv, self.b[j])
                if np.abs(np.dot(theta - theta1,
                                 self.items[kk, :])) < self.alpha * (
                                     fracT(self.T[i]) + fracT(self.T[j])):
                    N0.append(j)
                for a in range(len(A)):
                    l = A[a]
                    if np.abs(np.dot(theta - theta1,
                                     self.items[l, :])) < self.alpha * (
                                         fracT(self.T[i]) + fracT(self.T[j])):
                        N[a].append(j)
            else:
                N0.append(j)
                for a in range(len(A)):
                    N[a].append(j)

        N0 = set(N0)
        for a in range(len(A)):
            l = A[a]
            if l == kk:
                continue
            N[a] = set(N[a])
            if N0 != N[a]:
                self.GI.remove_edge(kk, l)
                # H.remove_edge(kk, l)

        C = set(nx.node_connected_component(self.GI, kk))
        if C != C0:
            c = self.i_ind[kk]
            self.G[c] = nx.gnp_random_graph(num_users,
                                            edge_probability(num_users))
            self.i_clusters[c] = [l for l in C]
            C0 = C0 - C
            while len(C0) > 0:
                l = next(iter(C0))
                C1 = set(nx.node_connected_component(self.GI, l))
                c1 = self.find_available_index()
                self.G[c1] = nx.gnp_random_graph(num_users,
                                                 edge_probability(num_users))
                self.i_clusters[c1] = [l for l in C1]
                for l1 in C1:
                    self.i_ind[l1] = c1
                C0 = C0 - C1
        return
Beispiel #43
0
def nxg_gnp_random(directed):
    return nx.gnp_random_graph(100, 0.3, seed=1234, directed=directed)
Beispiel #44
0
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 10:04:39 2020

@author: bijuangalees
"""

import networkx as nx
#G=nx.barbell_graph(5,3)
#G=nx.complete_graph(4)
#G=nx.cycle_graph(5)
#G=nx.ladder_graph(5)
#G=nx.path_graph(6)
#G=nx.star_graph(1000)
#G=nx.wheel_graph(9)
G = nx.gnp_random_graph(5, 0.5)

nx.draw(G)
def test_random_gnp():
    G = nx.gnp_random_graph(100, 0.1)
    _check_separating_sets(G)
Beispiel #46
0
def generate_graph(N):
    G = nx.gnp_random_graph(N, p_edge)
    nx.write_gml(G, graph_file_path)
    return G
Beispiel #47
0
def fast_gnp_random_graph(n, p, seed=None, directed=False):
    """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph or
    a binomial graph.

    Parameters
    ----------
    n : int
        The number of nodes.
    p : float
        Probability for edge creation.
    seed : integer, random_state, or None (default)
        Indicator of random number generation state.
        See :ref:`Randomness<randomness>`.
    directed : bool, optional (default=False)
        If True, this function returns a directed graph.

    Notes
    -----
    The $G_{n,p}$ graph algorithm chooses each of the $[n (n - 1)] / 2$
    (undirected) or $n (n - 1)$ (directed) possible edges with probability $p$.

    This algorithm [1]_ runs in $O(n + m)$ time, where `m` is the expected number of
    edges, which equals $p n (n - 1) / 2$. This should be faster than
    :func:`gnp_random_graph` when $p$ is small and the expected number of edges
    is small (that is, the graph is sparse).

    See Also
    --------
    gnp_random_graph

    References
    ----------
    .. [1] Vladimir Batagelj and Ulrik Brandes,
       "Efficient generation of large random networks",
       Phys. Rev. E, 71, 036113, 2005.
    """
    G = empty_graph(n)

    if p <= 0 or p >= 1:
        return nx.gnp_random_graph(n, p, seed=seed, directed=directed)

    w = -1
    lp = math.log(1.0 - p)

    if directed:
        G = nx.DiGraph(G)
        # Nodes in graph are from 0,n-1 (start with v as the first node index).
        v = 0
        while v < n:
            lr = math.log(1.0 - seed.random())
            w = w + 1 + int(lr / lp)
            if v == w:  # avoid self loops
                w = w + 1
            while v < n <= w:
                w = w - n
                v = v + 1
                if v == w:  # avoid self loops
                    w = w + 1
            if v < n:
                G.add_edge(v, w)
    else:
        # Nodes in graph are from 0,n-1 (start with v as the second node index).
        v = 1
        while v < n:
            lr = math.log(1.0 - seed.random())
            w = w + 1 + int(lr / lp)
            while w >= v and v < n:
                w = w - v
                v = v + 1
            if v < n:
                G.add_edge(v, w)
    return G
def test_random_gnp_directed():
    # seeds = [3894723670, 500186844, 267231174, 2181982262, 1116750056]
    seeds = [2181982262]
    for seed in seeds:
        G = nx.gnp_random_graph(20, 0.2, directed=True, seed=seed)
        _check_edge_connectivity(G)
Beispiel #49
0
    bt_sc = p.map(
        _betmap,
        zip([G] * num_chunks, [True] * num_chunks, [None] * num_chunks,
            node_chunks))

    # Reduce the partial solutions
    bt_c = bt_sc[0]
    for bt in bt_sc[1:]:
        for n in bt:
            bt_c[n] += bt[n]
    return bt_c


if __name__ == "__main__":
    G_ba = nx.barabasi_albert_graph(1000, 3)
    G_er = nx.gnp_random_graph(1000, 0.01)
    G_ws = nx.connected_watts_strogatz_graph(1000, 4, 0.1)
    for G in [G_ba, G_er, G_ws]:
        print("")
        print("Computing betweenness centrality for:")
        print(nx.info(G))
        print("\tParallel version")
        start = time.time()
        bt = betweenness_centrality_parallel(G)
        print("\t\tTime: %.4F" % (time.time() - start))
        print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0]))
        print("\tNon-Parallel version")
        start = time.time()
        bt = nx.betweenness_centrality(G)
        print("\t\tTime: %.4F seconds" % (time.time() - start))
        print("\t\tBetweenness centrality for node 0: %.5f" % (bt[0]))
Beispiel #50
0
def get_edge_array(node_count, node_start):
    edges = []
    for edge in nx.gnp_random_graph(node_count, 0.1).edges():
        edges.append([edge[0] + node_start, edge[1] + node_start])
    return np.array(edges)
Beispiel #51
0
        Returns
        -------
        adj_iter : iterator
           An iterator of (node, adjacency set) for all nodes in
           the graph.

        """
        for n in self.adj:
            yield (n, set(self.adj) - set(self.adj[n]) - set([n]))


if __name__ == '__main__':
    # Build several pairs of graphs, a regular graph
    # and the AntiGraph of it's complement, which behaves
    # as if it were the original graph.
    Gnp = nx.gnp_random_graph(20, 0.8)
    Anp = AntiGraph(nx.complement(Gnp))
    Gd = nx.davis_southern_women_graph()
    Ad = AntiGraph(nx.complement(Gd))
    Gk = nx.karate_club_graph()
    Ak = AntiGraph(nx.complement(Gk))
    pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
    # test connected components
    for G, A in pairs:
        gc = [set(c) for c in nx.connected_components(G)]
        ac = [set(c) for c in nx.connected_components(A)]
        for comp in ac:
            assert comp in gc
    # test biconnected components
    for G, A in pairs:
        gc = [set(c) for c in nx.biconnected_components(G)]
Beispiel #52
0
def RandomGNP(n, p, seed=None, fast=True, algorithm='Sage'):
    r"""
    Returns a random graph on `n` nodes. Each edge is inserted independently
    with probability `p`.

    INPUT:

    - ``n`` -- number of nodes of the graph

    - ``p`` -- probability of an edge

    - ``seed`` -- integer seed for random number generator (default=None).

    - ``fast`` -- boolean set to True (default) to use the algorithm with
      time complexity in `O(n+m)` proposed in [BatBra2005]_. It is designed
      for generating large sparse graphs. It is faster than other algorithms for
      *LARGE* instances (try it to know whether it is useful for you).

    - ``algorithm`` -- By default (```algorithm='Sage'``), this function uses the
      algorithm implemented in ```sage.graphs.graph_generators_pyx.pyx``. When
      ``algorithm='networkx'``, this function calls the NetworkX function
      ``fast_gnp_random_graph``, unless ``fast=False``, then
      ``gnp_random_graph``. Try them to know which algorithm is the best for
      you. The ``fast`` parameter is not taken into account by the 'Sage'
      algorithm so far.

    REFERENCES:

    .. [ErdRen1959] P. Erdos and A. Renyi. On Random Graphs, Publ.
       Math. 6, 290 (1959).

    .. [Gilbert1959] E. N. Gilbert. Random Graphs, Ann. Math. Stat.,
       30, 1141 (1959).

    .. [BatBra2005] V. Batagelj and U. Brandes. Efficient generation of
       large random networks. Phys. Rev. E, 71, 036113, 2005.

    PLOTTING: When plotting, this graph will use the default spring-layout
    algorithm, unless a position dictionary is specified.

    EXAMPLES: We show the edge list of a random graph on 6 nodes with
    probability `p = .4`::

        sage: set_random_seed(0)
        sage: graphs.RandomGNP(6, .4).edges(labels=False)
        [(0, 1), (0, 5), (1, 2), (2, 4), (3, 4), (3, 5), (4, 5)]

    We plot a random graph on 12 nodes with probability `p = .71`::

        sage: gnp = graphs.RandomGNP(12,.71)
        sage: gnp.show() # long time

    We view many random graphs using a graphics array::

        sage: g = []
        sage: j = []
        sage: for i in range(9):
        ....:     k = graphs.RandomGNP(i+3,.43)
        ....:     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
        sage: graphs.RandomGNP(4,1)
        Complete graph: Graph on 4 vertices

    TESTS::

        sage: graphs.RandomGNP(50,.2,algorithm=50)
        Traceback (most recent call last):
        ...
        ValueError: 'algorithm' must be equal to 'networkx' or to 'Sage'.
        sage: set_random_seed(0)
        sage: graphs.RandomGNP(50,.2, algorithm="Sage").size()
        243
        sage: graphs.RandomGNP(50,.2, algorithm="networkx").size()
        258
    """
    if n < 0:
        raise ValueError("The number of nodes must be positive or null.")
    if 0.0 > p or 1.0 < p:
        raise ValueError("The probability p must be in [0..1].")

    if seed is None:
        seed = current_randstate().long_seed()
    if p == 1:
        from sage.graphs.generators.basic import CompleteGraph
        return CompleteGraph(n)

    if algorithm == 'networkx':
        import networkx
        if fast:
            G = networkx.fast_gnp_random_graph(n, p, seed=seed)
        else:
            G = networkx.gnp_random_graph(n, p, seed=seed)
        return Graph(G)
    elif algorithm in ['Sage', 'sage']:
        # We use the Sage generator
        from sage.graphs.graph_generators_pyx import RandomGNP as sageGNP
        return sageGNP(n, p)
    else:
        raise ValueError(
            "'algorithm' must be equal to 'networkx' or to 'Sage'.")
        dydt[i] = s[0] + n_W[i] * W[0]
        dydt[i + N] = s[1] + n_W[i] * W[1]
        dydt[i + 2 * N] = s[2] + n_W[i] * W[2]

    return dydt


#Parametros
N = int(input("N= "))
ti = int(input("ti= "))
tf = int(input("tf= "))
s = [ti, tf]
mu = float(input("mu= "))
delta = float(input("delta= "))
p = float(input("p= "))
G = nx.gnp_random_graph(N, p)
A = nx.adjacency_matrix(G).A
D = np.zeros(N)
for i in range(N):
    S = 0
    for j in range(N):
        S = S + A[i, j]
    D[i] = S

#Frequencias naturais
W = np.random.normal(mu, delta, (3, N))
w = np.zeros((3, N))
n_W = np.zeros(N)
for i in range(N):

    H = np.zeros((3, 3))
    nodecount = g2.vertices.count()
    print("Graph has " + str(nodecount) + " vertices.")

    out = filename.split("/")[-1]
    print("Writing distribution to file " + out + ".csv")
    distrib.toPandas().to_csv(out + ".csv")

# Otherwise, generate some random graphs.
else:
    print("Generating random graphs.")
    vschema = StructType([StructField("id", IntegerType())])
    eschema = StructType(
        [StructField("src", IntegerType()),
         StructField("dst", IntegerType())])

    gnp1 = nx.gnp_random_graph(100, 0.05, seed=1234)
    gnp2 = nx.gnp_random_graph(2000, 0.01, seed=5130303)
    gnm1 = nx.gnm_random_graph(100, 1000, seed=27695)
    gnm2 = nx.gnm_random_graph(1000, 100000, seed=9999)

    todo = {"gnp1": gnp1, "gnp2": gnp2, "gnm1": gnm1, "gnm2": gnm2}
    for gx in todo:
        print("Processing graph " + gx)
        v = sqlContext.createDataFrame(sc.parallelize(todo[gx].nodes()),
                                       vschema)
        e = sqlContext.createDataFrame(sc.parallelize(todo[gx].edges()),
                                       eschema)
        g = simple(GraphFrame(v, e))
        distrib = degreedist(g)
        print("Writing distribution to file " + gx + ".csv")
        distrib.toPandas().to_csv(gx + ".csv")
Beispiel #55
0
#!/usr/bin/env python
"""
===========
Degree Rank
===========

Random graph from given degree sequence.
Draw degree rank plot and graph with matplotlib.
"""
# Author: Aric Hagberg <*****@*****.**>
import networkx as nx
import matplotlib.pyplot as plt

G = nx.gnp_random_graph(100, 0.02)

degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
# print "Degree sequence", degree_sequence
dmax = max(degree_sequence)

plt.loglog(degree_sequence, 'b-', marker='o')
plt.title("Degree rank plot")
plt.ylabel("degree")
plt.xlabel("rank")

# draw graph in inset
plt.axes([0.45, 0.45, 0.45, 0.45])
Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
pos = nx.spring_layout(Gcc)
plt.axis('off')
nx.draw_networkx_nodes(Gcc, pos, node_size=20)
nx.draw_networkx_edges(Gcc, pos, alpha=0.4)
Beispiel #56
0
        Returns
        -------
        adj_iter : iterator
           An iterator of (node, adjacency set) for all nodes in
           the graph.

        """
        for n in self.adj:
            yield (n, set(self.adj) - set(self.adj[n]) - set([n]))


# Build several pairs of graphs, a regular graph
# and the AntiGraph of it's complement, which behaves
# as if it were the original graph.
Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
Anp = AntiGraph(nx.complement(Gnp))
Gd = nx.davis_southern_women_graph()
Ad = AntiGraph(nx.complement(Gd))
Gk = nx.karate_club_graph()
Ak = AntiGraph(nx.complement(Gk))
pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
# test connected components
for G, A in pairs:
    gc = [set(c) for c in nx.connected_components(G)]
    ac = [set(c) for c in nx.connected_components(A)]
    for comp in ac:
        assert comp in gc
# test biconnected components
for G, A in pairs:
    gc = [set(c) for c in nx.biconnected_components(G)]
Beispiel #57
0
 def test_result_gnp_50_0_5_4(self):
     assert (calc_and_compare(NX.gnp_random_graph(50, 0.5, 4)))
Beispiel #58
0
def fast_gnp_random_graph(n, p, seed=None, directed=False):
    """Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph).

    Parameters
    ----------
    n : int
        The number of nodes.
    p : float
        Probability for edge creation.
    seed : int, optional
        Seed for random number generator (default=None).
    directed : bool, optional (default=False)
        If True return a directed graph

    Notes
    -----
    The G_{n,p} graph algorithm chooses each of the [n(n-1)]/2
    (undirected) or n(n-1) (directed) possible edges with probability p.

    This algorithm is O(n+m) where m is the expected number of
    edges m=p*n*(n-1)/2.

    It should be faster than gnp_random_graph when p is small and
    the expected number of edges is small (sparse graph).

    See Also
    --------
    gnp_random_graph

    References
    ----------
    .. [1] Vladimir Batagelj and Ulrik Brandes,
       "Efficient generation of large random networks",
       Phys. Rev. E, 71, 036113, 2005.
    """
    G = empty_graph(n)
    G.name="fast_gnp_random_graph(%s,%s)"%(n,p)

    if not seed is None:
        random.seed(seed)

    if p <= 0 or p >= 1:
        return nx.gnp_random_graph(n,p,directed=directed)

    w = -1
    lp = math.log(1.0 - p)

    if directed:
        G = nx.DiGraph(G)
        # Nodes in graph are from 0,n-1 (start with v as the first node index).
        v = 0
        while v < n:
            lr = math.log(1.0 - random.random())
            w = w + 1 + int(lr/lp)
            if v == w: # avoid self loops
                w = w + 1
            while  w >= n and v < n:
                w = w - n
                v = v + 1
                if v == w: # avoid self loops
                    w = w + 1
            if v < n:
                G.add_edge(v, w)
    else:
        # Nodes in graph are from 0,n-1 (start with v as the second node index).
        v = 1
        while v < n:
            lr = math.log(1.0 - random.random())
            w = w + 1 + int(lr/lp)
            while w >= v and v < n:
                w = w - v
                v = v + 1
            if v < n:
                G.add_edge(v, w)
    return G
Beispiel #59
0
            if v1 == t: return (cost, path)

            for c, v2 in g.get(v1, ()):
                if v2 in seen: continue
                prev = mins.get(v2, None)
                next = cost + c
                if prev is None or next < prev:
                    mins[v2] = next
                    heappush(q, (next, v2, path))

    return float("inf"), None

# initialize the graph
n = NODE_COUNT
p = EDGE_PROBABILITY
G = nx.gnp_random_graph(n, p, directed=True)
edgelist = []

# gives all nodes weights
for i in G.edges:
    G[i[0]][i[1]]["weight"] = 1 + random.randint(0, 20)
    edgelist.append((i[0], i[1], G[i[0]][i[1]]["weight"]))

print(edgelist)

# initial graph
pos = nx.spring_layout(G)
nx.draw(G, pos, node_color='blue', with_labels=False, node_size=250)


# select two random nodes as long as they
from DBK import DBK
import networkx as nx
import random


def maximum_clique_exact_solve_np_hard(G):
    max_clique_number = nx.graph_clique_number(G)
    cliques = nx.find_cliques(G)
    for cl in cliques:
        if len(cl) == max_clique_number:
            return cl


for i in range(500):
    G = nx.gnp_random_graph(random.randint(66, 100),
                            random.uniform(0.01, 0.99))
    print(len(G))
    solution = DBK(G, 65, maximum_clique_exact_solve_np_hard)
    assert len(solution) == nx.graph_clique_number(G)