Python networkx.erdos_renyi_graph() Examples

The following are 30 code examples of networkx.erdos_renyi_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_seir.py    From epydemic with GNU General Public License v3.0 6 votes vote down vote up
def setUp( self ):
        '''Set up the experimental parameters and experiment.'''
        
        # single experiment
        self._params = dict()
        self._params[SEIR.P_INFECT_SYMPTOMATIC] = 0.2
        self._params[SEIR.P_INFECT_ASYMPTOMATIC] = 0.1
        self._params[SEIR.P_EXPOSED] = 0.01
        self._params[SEIR.P_SYMPTOMS] = 0.05
        self._params[SEIR.P_REMOVE] = 0.05
        self._network = networkx.erdos_renyi_graph(1000, 0.005)

        # lab run
        self._lab = epyc.Lab()
        self._lab[SEIR.P_INFECT_SYMPTOMATIC] = 0.1
        self._lab[SEIR.P_INFECT_ASYMPTOMATIC] = [ 0.1,  0.3 ]
        self._lab[SEIR.P_EXPOSED] = 0.01
        self._lab[SEIR.P_SYMPTOMS] = [ 0.05, 1 ]
        self._lab[SEIR.P_REMOVE] = 0.05

        # model
        self._model = SEIR() 
Example #2
Source File: test_nn.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_gat_conv():
    ctx = F.ctx()

    g = dgl.DGLGraph(nx.erdos_renyi_graph(20, 0.3))
    gat = nn.GATConv(10, 20, 5) # n_heads = 5
    gat.initialize(ctx=ctx)
    print(gat)

    # test#1: basic
    feat = F.randn((20, 10))
    h = gat(g, feat)
    assert h.shape == (20, 5, 20)

    # test#2: bipartite
    g = dgl.bipartite(sp.sparse.random(100, 200, density=0.1))
    gat = nn.GATConv((5, 10), 2, 4)
    gat.initialize(ctx=ctx)
    feat = (F.randn((100, 5)), F.randn((200, 10)))
    h = gat(g, feat)
    assert h.shape == (200, 4, 2) 
Example #3
Source File: test_transform.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_laplacian_lambda_max():
    N = 20
    eps = 1e-6
    # test DGLGraph
    g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))
    l_max = dgl.laplacian_lambda_max(g)
    assert (l_max[0] < 2 + eps)
    # test batched DGLGraph
    N_arr = [20, 30, 10, 12]
    bg = dgl.batch([
        dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))
        for N in N_arr
    ])
    l_max_arr = dgl.laplacian_lambda_max(bg)
    assert len(l_max_arr) == len(N_arr)
    for l_max in l_max_arr:
        assert l_max < 2 + eps 
Example #4
Source File: test_nn.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_gin_conv():
    g = dgl.DGLGraph(nx.erdos_renyi_graph(20, 0.3))
    ctx = F.ctx()

    gin_conv = nn.GINConv(lambda x: x, 'mean', 0.1)
    gin_conv.initialize(ctx=ctx)
    print(gin_conv)

    # test #1: basic
    feat = F.randn((g.number_of_nodes(), 5))
    h = gin_conv(g, feat)
    assert h.shape == (20, 5)

    # test #2: bipartite
    g = dgl.bipartite(sp.sparse.random(100, 200, density=0.1))
    feat = (F.randn((100, 5)), F.randn((200, 5)))
    h = gin_conv(g, feat)
    return h.shape == (20, 5) 
Example #5
Source File: sample.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def seed(value: Optional[int]) -> None:
    """Seed for random number generators.

    Wrapper function for `numpy.random.seed <https://docs.scipy.org/doc/numpy//reference/generated
    /numpy.random.seed.html>`_ to seed all NumPy-based random number generators. This allows for
    repeatable sampling.

    **Example usage:**

    >>> g = nx.erdos_renyi_graph(5, 0.7)
    >>> a = nx.to_numpy_array(g)
    >>> seed(1967)
    >>> sample(a, 3, 4)
    [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 0, 0, 0, 0]]
    >>> seed(1967)
    >>> sample(a, 3, 4)
    [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 0, 0, 0, 0]]

    Args:
        value (int): random seed
    """
    np.random.seed(value) 
Example #6
Source File: test_mpl_viz.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_visualize_dynamic(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 4):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = dyn.DynSIModel(dg)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.1)
        config.add_model_parameter("fraction_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        trends = model.build_trends(iterations)

        # Visualization
        viz = DiffusionPrevalence(model, trends)
        viz.plot("prevd.pdf")
        os.remove("prevd.pdf") 
Example #7
Source File: test_dynamic_models.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_DynSI(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = dyn.DynSIModel(dg)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.1)
        config.add_model_parameter("fraction_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(len(trends[0]['trends']['status_delta'][1]),
                         len([x for x in dg.stream_interactions() if x[2] == "+"])) 
Example #8
Source File: test_dynamic_models.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_DynSIS(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = dyn.DynSISModel(dg)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.1)
        config.add_model_parameter('lambda', 0.1)
        config.add_model_parameter("fraction_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(len(trends[0]['trends']['status_delta'][1]),
                         len([x for x in dg.stream_interactions() if x[2] == "+"])) 
Example #9
Source File: test_dynamic_models.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_DynSIR(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = dyn.DynSIRModel(dg)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.1)
        config.add_model_parameter('gamma', 0.1)
        config.add_model_parameter("fraction_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3)

        iterations = model.execute_iterations()
        trends = model.build_trends(iterations)
        self.assertEqual(len(trends[0]['trends']['status_delta'][1]),
                         len([x for x in dg.stream_interactions() if x[2] == "+"])) 
Example #10
Source File: test_dynamic_models.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_DynProfile(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = dyn.DynProfileModel(dg)
        config = mc.Configuration()
        config.add_model_parameter("fraction_infected", 0.1)
        config.add_model_parameter("blocked", 0.1)
        config.add_model_parameter("adopter_rate", 0.001)

        profile = 0.1
        for i in g.nodes():
            config.add_node_configuration("profile", i, profile)

        model.set_initial_status(config)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3) 
Example #11
Source File: test_dynamic_models.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_DynProfileThreshold(self):
        dg = dn.DynGraph()

        for t in past.builtins.xrange(0, 3):
            g = nx.erdos_renyi_graph(200, 0.05)
            dg.add_interactions_from(g.edges(), t)

        model = dyn.DynProfileThresholdModel(dg)
        config = mc.Configuration()
        config.add_model_parameter("fraction_infected", 0.1)
        config.add_model_parameter("blocked", 0.1)
        config.add_model_parameter("adopter_rate", 0.001)

        threshold = 0.2
        profile = 0.1
        for i in g.nodes():
            config.add_node_configuration("threshold", i, threshold)
            config.add_node_configuration("profile", i, profile)

        model.set_initial_status(config)
        model.set_initial_status(config)
        iterations = model.execute_snapshots()
        self.assertEqual(len(iterations), 3) 
Example #12
Source File: test_parallel.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_multi_initial_set(self):
        # Network topology
        g = nx.erdos_renyi_graph(1000, 0.1)

        # Model selection
        model1 = epd.SIRModel(g)

        # Model Configuration
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.001)
        config.add_model_parameter('gamma', 0.01)
        model1.set_initial_status(config)

        # Simulation multiple execution
        infection_sets = [(1, 2, 3, 4, 5), (3, 23, 22, 54, 2), (98, 2, 12, 26, 3), (4, 6, 9)]
        trends = multi_runs(model1, execution_number=4, iteration_number=100, infection_sets=infection_sets,
                            nprocesses=4)
        self.assertIsNotNone(trends) 
Example #13
Source File: test_compartment.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_node_stochastic(self):
        g = nx.erdos_renyi_graph(1000, 0.1)
        model = gc.CompositeModel(g)

        model.add_status("Susceptible")
        model.add_status("Infected")
        model.add_status("Removed")

        c1 = cpm.NodeStochastic(0.02, "Infected")
        c2 = cpm.NodeStochastic(0.01)
        c3 = cpm.NodeStochastic(0.5)

        model.add_rule("Susceptible", "Infected", c1)
        model.add_rule("Infected", "Removed", c2)
        model.add_rule("Infected", "Susceptible", c3)

        config = mc.Configuration()
        config.add_model_parameter('fraction_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(100)
        self.assertEqual(len(iterations), 100) 
Example #14
Source File: test_compartment.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_conditional_composition(self):
        g = nx.erdos_renyi_graph(1000, 0.1)
        model = gc.CompositeModel(g)

        model.add_status("Susceptible")
        model.add_status("Infected")
        model.add_status("Removed")

        # conditional composition
        c1 = cpm.NodeStochastic(0.5)
        c2 = cpm.NodeStochastic(0.2)
        c3 = cpm.NodeStochastic(0.1)

        cc = cpm.ConditionalComposition(c1, c2, c3)

        model.add_rule("Susceptible", "Infected", cc)

        config = mc.Configuration()
        config.add_model_parameter('fraction_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(100)
        self.assertEqual(len(iterations), 100) 
Example #15
Source File: initialization_test.py    From Cirq with Apache License 2.0 6 votes vote down vote up
def test_initialization_reproducible_between_runs():
    seed = 45
    logical_graph = nx.erdos_renyi_graph(6, 0.5, seed=seed)
    logical_graph = nx.relabel_nodes(logical_graph, cirq.LineQubit)
    device_graph = ccr.get_grid_device_graph(2, 3)
    initial_mapping = ccr.initialization.get_initial_mapping(
        logical_graph, device_graph, seed)
    expected_mapping = {
        cirq.GridQubit(0, 0): cirq.LineQubit(5),
        cirq.GridQubit(0, 1): cirq.LineQubit(0),
        cirq.GridQubit(0, 2): cirq.LineQubit(2),
        cirq.GridQubit(1, 0): cirq.LineQubit(3),
        cirq.GridQubit(1, 1): cirq.LineQubit(4),
        cirq.GridQubit(1, 2): cirq.LineQubit(1),
    }
    assert initial_mapping == expected_mapping 
Example #16
Source File: test_sis.py    From epydemic with GNU General Public License v3.0 6 votes vote down vote up
def setUp( self ):
        '''Set up the experimental parameters and experiment.'''
        
        # single experiment
        self._params = dict()
        self._params[SIS.P_INFECT] = 0.1
        self._params[SIS.P_INFECTED] = 0.01
        self._params[SIS.P_RECOVER] = 0.05
        self._network = networkx.erdos_renyi_graph(1000, 0.005)

        # lab run
        self._lab = epyc.Lab()
        self._lab[SIS.P_INFECT] = [ 0.1, 0.3 ]
        self._lab[SIS.P_INFECTED] = 0.01
        self._lab[SIS.P_RECOVER] = 0.05

        # model
        self._model = SIS()

        # maximum time needed as disease may be endemic
        self._model.setMaximumTime(200) 
Example #17
Source File: test_parallel.py    From ndlib with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_multi(self):

        # Network topology
        g = nx.erdos_renyi_graph(1000, 0.1)

        # Model selection
        model1 = epd.SIRModel(g)

        # Model Configuration
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.001)
        config.add_model_parameter('gamma', 0.01)
        config.add_model_parameter("fraction_infected", 0.05)
        model1.set_initial_status(config)

        # Simulation multiple execution
        trends = multi_runs(model1, execution_number=10, iteration_number=100, infection_sets=None, nprocesses=4)
        self.assertIsNotNone(trends) 
Example #18
Source File: test_sir.py    From epydemic with GNU General Public License v3.0 6 votes vote down vote up
def setUp( self ):
        '''Set up the experimental parameters and experiment.'''
        
        # single experiment
        self._params = dict()
        self._params[SIR.P_INFECT] = 0.1
        self._params[SIR.P_INFECTED] = 0.01
        self._params[SIR.P_REMOVE] = 0.05
        self._network = networkx.erdos_renyi_graph(1000, 0.005)

        # lab run
        self._lab = epyc.Lab()
        self._lab[SIR.P_INFECT] = [ 0.1,  0.3 ]
        self._lab[SIR.P_INFECTED] = 0.01
        self._lab[SIR.P_REMOVE] = [ 0.05, 1 ]

        # model
        self._model = SIR() 
Example #19
Source File: test_monitor.py    From epydemic with GNU General Public License v3.0 6 votes vote down vote up
def testSimple( self ):
        '''Test we capture the right time series.'''
        m = MonitoredSIR()
        m.setMaximumTime(100)
        e = StochasticDynamics(m, networkx.erdos_renyi_graph(1000, 5.0 / 1000))

        param = dict()
        param[SIR.P_INFECTED] = 0.01
        param[SIR.P_INFECT] = 0.002
        param[SIR.P_REMOVE] = 0.002
        param[Monitor.DELTA] = 1.0

        rc = e.set(param).run()
        self.assertIn(Monitor.TIMESERIES, rc[epyc.Experiment.RESULTS])
        self.assertSetEqual(set(rc[epyc.Experiment.RESULTS].keys()), set([Monitor.TIMESERIES, SIR.SUSCEPTIBLE, SIR.INFECTED, SIR.REMOVED]))
        self.assertSetEqual(set(rc[epyc.Experiment.RESULTS][Monitor.TIMESERIES].keys()), set([Monitor.OBSERVATIONS, SIR.SI, SIR.INFECTED]))
        # the next test is >=, not =, because some events may be drawn after the maxiumum time,
        # but the time is short enough that the number of infecteds won't be exhausted beforehand
        self.assertGreaterEqual(len(rc[epyc.Experiment.RESULTS][Monitor.TIMESERIES][Monitor.OBSERVATIONS]), 100)
        n = len(rc[epyc.Experiment.RESULTS][Monitor.TIMESERIES][Monitor.OBSERVATIONS])
        for k in [SIR.SI, SIR.INFECTED]:
            self.assertEqual(len(rc[epyc.Experiment.RESULTS][Monitor.TIMESERIES][k]), n) 
Example #20
Source File: test_sirs.py    From epydemic with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        '''Set up the experimental parameters and experiment.'''

        # single experiment
        self._params = dict()
        self._params[SIR.P_INFECT] = 0.1
        self._params[SIR.P_INFECTED] = 0.01
        self._params[SIR.P_REMOVE] = 0.05
        self._params[SIRS.P_RESUSCEPT] = 0.01
        self._network = networkx.erdos_renyi_graph(1000, 0.005)

        # lab run
        self._lab = epyc.Lab()
        self._lab[SIR.P_INFECT] = 0.1
        self._lab[SIR.P_INFECTED] = 0.01
        self._lab[SIR.P_REMOVE] = [0.05, 1]
        self._lab[SIRS.P_RESUSCEPT] = 0.01

        # model
        self._model = SIRS()

        # maximum time needed as disease may be endemic
        self._model.setMaximumTime(200) 
Example #21
Source File: test_transform.py    From dgl with Apache License 2.0 6 votes vote down vote up
def test_khop_graph():
    N = 20
    feat = F.randn((N, 5))

    def _test(g):
        for k in range(4):
            g_k = dgl.khop_graph(g, k)
            # use original graph to do message passing for k times.
            g.ndata['h'] = feat
            for _ in range(k):
                g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
            h_0 = g.ndata.pop('h')
            # use k-hop graph to do message passing for one time.
            g_k.ndata['h'] = feat
            g_k.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
            h_1 = g_k.ndata.pop('h')
            assert F.allclose(h_0, h_1, rtol=1e-3, atol=1e-3)

    # Test for random undirected graphs
    g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))
    _test(g)
    # Test for random directed graphs
    g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3, directed=True))
    _test(g) 
Example #22
Source File: test_transform.py    From dgl with Apache License 2.0 5 votes vote down vote up
def test_khop_adj():
    N = 20
    feat = F.randn((N, 5))
    g = dgl.DGLGraph(nx.erdos_renyi_graph(N, 0.3))
    for k in range(3):
        adj = F.tensor(dgl.khop_adj(g, k))
        # use original graph to do message passing for k times.
        g.ndata['h'] = feat
        for _ in range(k):
            g.update_all(fn.copy_u('h', 'm'), fn.sum('m', 'h'))
        h_0 = g.ndata.pop('h')
        # use k-hop adj to do message passing for one time.
        h_1 = F.matmul(adj, feat)
        assert F.allclose(h_0, h_1, rtol=1e-3, atol=1e-3) 
Example #23
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_lexicographic_product_random():
    G = nx.erdos_renyi_graph(10, 2 / 10.)
    H = nx.erdos_renyi_graph(10, 2 / 10.)
    GH = lexicographic_product(G, H)

    for (u_G, u_H) in GH.nodes():
        for (v_G, v_H) in GH.nodes():
            if G.has_edge(u_G, v_G) or (u_G == v_G and H.has_edge(u_H, v_H)):
                assert_true(GH.has_edge((u_G, u_H), (v_G, v_H)))
            else:
                assert_true(not GH.has_edge((u_G, u_H), (v_G, v_H))) 
Example #24
Source File: data.py    From diffpool with MIT License 5 votes vote down vote up
def gen_er(n_range, p, num_graphs, feature_generator=None):
    graphs = []
    for i in np.random.choice(n_range, num_graphs):
        graphs.append(nx.erdos_renyi_graph(i,p))

    if feature_generator is None:
        feature_generator = ConstFeatureGen(0)
    for G in graphs:
        feature_generator.gen_node_features(G)
    return graphs 
Example #25
Source File: test_product.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_cartesian_product_random():
    G = nx.erdos_renyi_graph(10, 2 / 10.)
    H = nx.erdos_renyi_graph(10, 2 / 10.)
    GH = cartesian_product(G, H)

    for (u_G, u_H) in GH.nodes():
        for (v_G, v_H) in GH.nodes():
            if (u_G == v_G and H.has_edge(u_H, v_H)) or \
               (u_H == v_H and G.has_edge(u_G, v_G)):
                assert_true(GH.has_edge((u_G, u_H), (v_G, v_H)))
            else:
                assert_true(not GH.has_edge((u_G, u_H), (v_G, v_H))) 
Example #26
Source File: test_compartmentedmodel.py    From epydemic with GNU General Public License v3.0 5 votes vote down vote up
def setUp( self ):
        '''Set up the experimental parameters and experiment.'''
        self._er = networkx.erdos_renyi_graph(1000, 0.005)
        self._params = dict()
        self._params[SIR.P_INFECT] = 0.1
        self._params[SIR.P_INFECTED] = 0.01
        self._params[SIR.P_REMOVE] = 0.05 
Example #27
Source File: batch_utils.py    From gnn-comparison with GNU General Public License v3.0 5 votes vote down vote up
def mock_batch(batch_size):
    """construct pyG batch"""
    graphs = []
    while len(graphs) < batch_size:
        G = nx.erdos_renyi_graph(np.random.choice([300, 500]), 0.5)
        if G.number_of_edges() > 1:
            graphs.append(G)

    adjs = [torch.from_numpy(nx.to_numpy_array(G)) for G in graphs]
    graph_data = [dense_to_sparse(A) for A in adjs]
    data_list = [Data(x=x, edge_index=e) for (e, x) in graph_data]
    return Batch.from_data_list(data_list) 
Example #28
Source File: gen_er_components.py    From graph_adversarial_attack with MIT License 5 votes vote down vote up
def get_component():
    cur_n = np.random.randint(max_n - min_n + 1) + min_n
    g = nx.erdos_renyi_graph(n = cur_n, p = p)

    comps = [c for c in nx.connected_component_subgraphs(g)]
    random.shuffle(comps)
    for i in range(1, len(comps)):
        x = random.choice(comps[i - 1].nodes())
        y = random.choice(comps[i].nodes())
        g.add_edge(x, y)
    assert nx.is_connected(g)
    return g 
Example #29
Source File: reservoir.py    From Reservoir with MIT License 5 votes vote down vote up
def train(self):
        # collection of reservoir state vectors
        self.R = np.zeros(
            (1 + self.N + self.M, self.train_len - self.init_len))
        # collection of input signals
        self.S = np.vstack((x[self.init_len + 1: self.train_len + 1] for x in self.dataset))
        self.r = np.zeros((self.N, 1))
        np.random.seed(42)
        self.Win = np.random.uniform(-self.sigma,
                                     self.sigma, (self.N, self.M + 1))
        # TODO: the values of non-zero elements are randomly drawn from uniform dist [-1, 1]
        g = nx.erdos_renyi_graph(self.N, self.D / self.N, 42, True)
        # nx.draw(g, node_size=self.N)
        self.A = nx.adjacency_matrix(g).todense()
        # spectral radius: rho
        self.rho = max(abs(np.linalg.eig(self.A)[0]))
        self.A *= 1.25 / self.rho
        # run the reservoir with the data and collect r
        for t in range(self.train_len):
            u = np.vstack((x[t] for x in self.dataset))
            # r(t + \Delta t) = (1 - alpha)r(t) + alpha * tanh(A * r(t) + Win * u(t) + bias)
            self.r = (1 - self.alpha) * self.r + self.alpha * np.tanh(np.dot(self.A,
                                                                             self.r) + np.dot(self.Win, np.vstack((self.bias, u))))
            if t >= self.init_len:
                self.R[:, [t - self.init_len]
                       ] = np.vstack((self.bias, u, self.r))[:, 0]
        # train the output
        R_T = self.R.T  # Transpose
        # Wout = (s * r^T) * ((r * r^T) + beta * I)
        self.Wout = np.dot(np.dot(self.S, R_T), np.linalg.inv(
            np.dot(self.R, R_T) + self.beta * np.eye(self.M + self.N + 1))) 
Example #30
Source File: test_fixed_recovery.py    From epydemic with GNU General Public License v3.0 5 votes vote down vote up
def setUp( self ):
        '''Set up the experimental parameters and experiment.'''
        
        # single experiment
        self._params = dict()
        self._params[SIR_FixedRecovery.P_INFECT] = 0.1
        self._params[SIR_FixedRecovery.P_INFECTED] = 0.01
        self._params[SIR_FixedRecovery.T_INFECTED] = 1
        self._network = networkx.erdos_renyi_graph(1000, 0.005)