Python networkx.fast_gnp_random_graph() Examples

The following are 30 code examples of networkx.fast_gnp_random_graph(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: test_distance.py    From netrd with MIT License 6 votes vote down vote up
def test_directed_input():
    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore", message="Coercing directed graph to undirected."
        )
        G = nx.fast_gnp_random_graph(100, 0.3, directed=True)

        for label, obj in distance.__dict__.items():
            if isinstance(obj, type) and BaseDistance in obj.__bases__:
                dist = obj().dist(G, G)
                assert np.isclose(dist, 0.0)

        G1 = nx.fast_gnp_random_graph(100, 0.3, directed=True)
        G2 = nx.fast_gnp_random_graph(100, 0.3, directed=True)

        for label, obj in distance.__dict__.items():
            if isinstance(obj, type) and BaseDistance in obj.__bases__:
                dist1 = obj().dist(G1, G2)
                dist2 = obj().dist(G2, G1)
                assert np.isclose(dist1, dist2)

        for obj in distance.__dict__.values():
            if isinstance(obj, type) and BaseDistance in obj.__bases__:
                dist = obj().dist(G1, G2)
                assert dist > 0.0 
Example #2
Source File: test_distance.py    From netrd with MIT License 6 votes vote down vote up
def test_quantum_jsd():
    """Run the above tests again using the collision entropy instead of the
    Von Neumann entropy to ensure that all the logic of the JSD implementation
    is tested.
    """

    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", message="JSD is only a metric for 0 ≤ q < 2.")
        JSD = distance.QuantumJSD()
        G = nx.karate_club_graph()
        dist = JSD.dist(G, G, beta=0.1, q=2)
        assert np.isclose(dist, 0.0)

        G1 = nx.fast_gnp_random_graph(100, 0.3)
        G2 = nx.barabasi_albert_graph(100, 5)
        dist = JSD.dist(G1, G2, beta=0.1, q=2)
        assert dist > 0.0

        G1 = nx.barabasi_albert_graph(100, 4)
        G2 = nx.fast_gnp_random_graph(100, 0.3)
        dist1 = JSD.dist(G1, G2, beta=0.1, q=2)
        dist2 = JSD.dist(G2, G1, beta=0.1, q=2)
        assert np.isclose(dist1, dist2) 
Example #3
Source File: test_from_joel.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def test_fast_nonMarkov_SIR(self):
        def rec_time_fxn_gamma(u):
            # gamma(shape, scale = 1.0)
            return np.random.gamma(3, 0.5)

        def trans_time_fxn(u, v, tau):
            if tau > 0:
                return np.random.exponential(1. / tau)
            else:
                return float('Inf')

        N = 10 ** 6  # number of individuals
        kave = 5  # expected number of partners
        G = nx.fast_gnp_random_graph(N, kave / (N - 1))  # Erdős-Rényi graph
        tau = 0.3

        for cntr in range(10):
            t, S, I, R = EoN.fast_nonMarkov_SIR(G, trans_time_fxn=trans_time_fxn,
                                                rec_time_fxn=rec_time_fxn_gamma, trans_time_args=(tau,))
            plt.plot(t, R)

        plt.savefig('test_fast_nonMarkov_SIR') 
Example #4
Source File: test_from_joel.py    From Mathematics-of-Epidemics-on-Networks with MIT License 6 votes vote down vote up
def test_ErdősRényi_million_Fast_Gillespie_SIR(self):
        print("testing ErdősRényi_million_Fast_Gillespie_SIR")
        N = 10 ** 6  # number of individuals
        kave = 5  # expected number of partners
        G = nx.fast_gnp_random_graph(N, kave / (N - 1))  # Erdős-Rényi graph

        rho = 0.005  # initial fraction infected
        tau = 0.3  # transmission rate
        gamma = 1.0  # recovery rate
        t1, S1, I1, R1 = EoN.fast_SIR(G, tau, gamma, rho=rho)
        t2, S2, I2, R2 = EoN.Gillespie_SIR(G, tau, gamma, rho=rho)

        plt.plot(t1, I1, label='fast_SIR')
        plt.plot(t2, I2, label='Gillespie_SIR')
        plt.legend()
        plt.savefig('test_ErdősRényi_million_Fast_Gillespie_SIR') 
Example #5
Source File: test_kcutsets.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_disconnected_graph():
    G = nx.fast_gnp_random_graph(100, 0.01, seed=42)
    cuts = nx.all_node_cuts(G)
    assert_raises(nx.NetworkXError, next, cuts) 
Example #6
Source File: test_kcutsets.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_disconnected_graph():
    G = nx.fast_gnp_random_graph(100, 0.01)
    cuts = nx.all_node_cuts(G)
    assert_raises(nx.NetworkXError, next, cuts) 
Example #7
Source File: test_cuts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100,0.0575)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph."%attempts
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #8
Source File: test_cuts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_node_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = next(ccs)[0]
                G.add_edges_from((start, c[0]) for c in ccs)
            cutset = nx.minimum_node_cut(G, flow_func=flow_func)
            assert_equal(nx.node_connectivity(G), len(cutset),
                         msg=msg.format(flow_func.__name__))
            G.remove_nodes_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__)) 
Example #9
Source File: test_cuts.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_edge_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = next(ccs)[0]
                G.add_edges_from( (start,c[0]) for c in ccs )
            cutset = nx.minimum_edge_cut(G, flow_func=flow_func)
            assert_equal(nx.edge_connectivity(G), len(cutset),
                         msg=msg.format(flow_func.__name__))
            G.remove_edges_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__)) 
Example #10
Source File: test_coloring.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_equitable_color(self):
        G = nx.fast_gnp_random_graph(n=10, p=0.2, seed=42)
        coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
        assert is_equitable(G, coloring) 
Example #11
Source File: test_coloring.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_equitable_color_large(self):
        G = nx.fast_gnp_random_graph(100, 0.1, seed=42)
        coloring = nx.coloring.equitable_color(G, max_degree(G) + 1)
        assert is_equitable(G, coloring, num_colors=max_degree(G) + 1) 
Example #12
Source File: test_kcutsets.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100, 0.0575, seed=42)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph." % attempts
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #13
Source File: test_degree_seq.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_random_degree_sequence_large():
    G1 = nx.fast_gnp_random_graph(100, 0.1)
    d1 = (d for n, d in G1.degree())
    G2 = nx.random_degree_sequence_graph(d1, seed=0)
    d2 = (d for n, d in G2.degree())
    assert_equal(sorted(d1), sorted(d2)) 
Example #14
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100, 0.0575, seed=42)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph." % attempts
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #15
Source File: test_cuts.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_edge_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25, seed=42)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = arbitrary_element(next(ccs))
                G.add_edges_from((start, arbitrary_element(c)) for c in ccs)
            cutset = nx.minimum_edge_cut(G, flow_func=flow_func)
            assert_equal(nx.edge_connectivity(G), len(cutset),
                         msg=msg.format(flow_func.__name__))
            G.remove_edges_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__)) 
Example #16
Source File: test_connectivity.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100, 0.0575, seed=42)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph."
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #17
Source File: test_degree_seq.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_random_degree_sequence_large():
    G1 = nx.fast_gnp_random_graph(100, 0.1)
    d1 = (d for n, d in G1.degree())
    G2 = nx.random_degree_sequence_graph(d1, seed=42)
    d2 = (d for n, d in G2.degree())
    assert_equal(sorted(d1), sorted(d2)) 
Example #18
Source File: test_kcutsets.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100, 0.0575)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph." % attempts
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #19
Source File: test_kcutsets.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_disconnected_graph():
    G = nx.fast_gnp_random_graph(100, 0.01)
    cuts = nx.all_node_cuts(G)
    assert_raises(nx.NetworkXError, next, cuts) 
Example #20
Source File: test_cuts.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def _generate_no_biconnected(max_attempts=50):
    attempts = 0
    while True:
        G = nx.fast_gnp_random_graph(100,0.0575)
        if nx.is_connected(G) and not nx.is_biconnected(G):
            attempts = 0
            yield G
        else:
            if attempts >= max_attempts:
                msg = "Tried %d times: no suitable Graph."%attempts
                raise Exception(msg % max_attempts)
            else:
                attempts += 1 
Example #21
Source File: test_cuts.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_node_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = arbitrary_element(next(ccs))
                G.add_edges_from((start, arbitrary_element(c)) for c in ccs)
            cutset = nx.minimum_node_cut(G, flow_func=flow_func)
            assert_equal(nx.node_connectivity(G), len(cutset),
                         msg=msg.format(flow_func.__name__))
            G.remove_nodes_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__)) 
Example #22
Source File: test_cuts.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_edge_cutset_random_graphs():
    for flow_func in flow_funcs:
        for i in range(3):
            G = nx.fast_gnp_random_graph(50, 0.25)
            if not nx.is_connected(G):
                ccs = iter(nx.connected_components(G))
                start = arbitrary_element(next(ccs))
                G.add_edges_from((start, arbitrary_element(c)) for c in ccs)
            cutset = nx.minimum_edge_cut(G, flow_func=flow_func)
            assert_equal(nx.edge_connectivity(G), len(cutset),
                         msg=msg.format(flow_func.__name__))
            G.remove_edges_from(cutset)
            assert_false(nx.is_connected(G), msg=msg.format(flow_func.__name__)) 
Example #23
Source File: get_graph_data.py    From LanczosNetwork with MIT License 5 votes vote down vote up
def gen_data(min_num_nodes=20,
             max_num_nodes=100,
             num_graphs=10,
             node_emb_dim=10,
             graph_emb_dim=2,
             edge_prob=0.5,
             seed=123):
  """
    Generate synthetic graph data for graph regression, i.e., given node 
    embedding and graph structure as input, predict a graph embedding 
    as output.

    N.B.: modification to other tasks like node classification is straightforward

    A single graph in your dataset should contin:
      X: Node embedding, numpy array, shape N X D where N is # nodes
      A: Graph structure, numpy array, shape N X N X E where E is # edge types
      Y: Graph embedding, numpy array, shape N X O
  """
  npr = np.random.RandomState(seed)
  N = npr.randint(min_num_nodes, high=max_num_nodes+1, size=num_graphs)

  data = []
  for ii in range(num_graphs):    
    data_dict = {}
    data_dict['X'] = npr.randn(N[ii], node_emb_dim)
    # we assume # edge type = 1, but you can easily extend it to be more than 1
    data_dict['A'] = np.expand_dims(
        nx.to_numpy_matrix(
            nx.fast_gnp_random_graph(N[ii], edge_prob, seed=npr.randint(1000))),
        axis=2)
    data_dict['Y'] = npr.randn(1, graph_emb_dim)
    data += [data_dict]

  return data 
Example #24
Source File: graph_util.py    From GEM with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def addChaos(di_graphs, k):
    anomaly_time_steps = sorted(random.sample(range(len(di_graphs)), k))
    for t in anomaly_time_steps:
        n = len(di_graphs[t].nodes)
        e = len(di_graphs[t].edges)
        di_graphs[t] = nx.fast_gnp_random_graph(n, e / float(n * (n - 1)),
                                                seed=None, directed=False)
        di_graphs[t] = di_graphs[t].to_directed()
    return di_graphs, anomaly_time_steps 
Example #25
Source File: citation_graph.py    From dgl with Apache License 2.0 5 votes vote down vote up
def get_gnp_generator(args):
    n = args.syn_gnp_n
    p = (2 * np.log(n) / n) if args.syn_gnp_p == 0. else args.syn_gnp_p
    def _gen(seed):
        return nx.fast_gnp_random_graph(n, p, seed, True)
    return _gen 
Example #26
Source File: graph_util.py    From GEM-Benchmark with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def addChaos(di_graphs, k):
    anomaly_time_steps = sorted(random.sample(range(len(di_graphs)), k))
    for t in anomaly_time_steps:
        n = di_graphs[t].number_of_nodes()
        e = di_graphs[t].number_of_edges()
        di_graphs[t] = nx.fast_gnp_random_graph(n, e / float(n * (n - 1)),
                                                seed=None, directed=False)
        di_graphs[t] = di_graphs[t].to_directed()
    return di_graphs, anomaly_time_steps 
Example #27
Source File: nx_utils.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def random_k_edge_connected_graph(size, k, p=.1, rng=None):
    """
    Super hacky way of getting a random k-connected graph

    Example:
        >>> # ENABLE_DOCTEST
        >>> import plottool_ibeis as pt
        >>> from ibeis.algo.graph.nx_utils import *  # NOQA
        >>> size, k, p = 25, 3, .1
        >>> rng = ut.ensure_rng(0)
        >>> gs = []
        >>> for x in range(4):
        >>>     G = random_k_edge_connected_graph(size, k, p, rng)
        >>>     gs.append(G)
        >>> ut.quit_if_noshow()
        >>> pnum_ = pt.make_pnum_nextgen(nRows=2, nSubplots=len(gs))
        >>> fnum = 1
        >>> for g in gs:
        >>>     pt.show_nx(g, fnum=fnum, pnum=pnum_())
    """
    import sys
    for count in it.count(0):
        seed = None if rng is None else rng.randint(sys.maxsize)
        # Randomly generate a graph
        g = nx.fast_gnp_random_graph(size, p, seed=seed)
        conn = nx.edge_connectivity(g)
        # If it has exactly the desired connectivity we are one
        if conn == k:
            break
        # If it has more, then we regenerate the graph with fewer edges
        elif conn > k:
            p = p / 2
        # If it has less then we add a small set of edges to get there
        elif conn < k:
            # p = 2 * p - p ** 2
            # if count == 2:
            aug_edges = list(k_edge_augmentation(g, k))
            g.add_edges_from(aug_edges)
            break
    return g 
Example #28
Source File: graph.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def sample(self):
    return nx.fast_gnp_random_graph(
        self.num_nodes, self.p, directed=self.directed) 
Example #29
Source File: fig9p4.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def ER_graph_generation(N, kave):
    return nx.fast_gnp_random_graph(N, kave/(N-1.)) 
Example #30
Source File: test_from_joel.py    From Mathematics-of-Epidemics-on-Networks with MIT License 5 votes vote down vote up
def test_discrete_SIR(self):
        print('testing discrete_SIR')
        passed = True
        G = nx.fast_gnp_random_graph(1000, 0.004)

        def test_trans_fxn(u, v):
            '''
            Transmissions occur if one odd and one even.  So it is basically bipartite.
            '''
            if (u + v) % 2 == 0:
                return False
            else:
                return True

        sim = EoN.discrete_SIR(G, test_transmission=test_trans_fxn, args=(), initial_infecteds=[0, 2, 4, 6, 8, 10],
                               return_full_data=True)
        # by initial condition and transmission rule, infection generations alternate parity.
        for node in G:
            if 'I' in sim.node_history(node)[1]:
                idx = sim.node_history(node)[1].index('I')

                if (node + sim.node_history(node)[0][idx]) % 2 == 1:  # should always be False
                    print('Error', node, sim.node_history(node))
                    passed = False
        print('number infected', sim.R()[-1])
        if not passed:
            print('failed')
        else:
            print('passed')
        assert passed