コード例 #1
0
ファイル: sandbox.py プロジェクト: andrea-allen/epintervene
def basic_SIR_simulation():
    print('Basic SIR simulation tutorial')
    # # Create a NetworkBuilder object, to help with creating and configuring the network for the simulation:
    nb = network.NetworkBuilder
    # # Specify a degree distribution to create a configuration model network if desired:
    degree_distrb = binomial_degree_distb(400, 3)
    # # Generating a network from the above degree distribution, with 100 nodes
    G, pos = nb.from_degree_distribution(100, degree_distrb)
    # # If you already have a network, feel free to skip the above steps and generate your own NetworkX object,
    # # or skip this next step and provide a symmetric adjacency list.
    adjlist = nb.create_adjacency_list(G)

    # # Constructing the simulation object
    my_simulation = simulation.Simulation(adj_list=adjlist, N=len(adjlist))

    # # Setting required configurations
    my_simulation.set_uniform_beta(
        beta=0.9)  # .9 people per day per infected person
    my_simulation.set_uniform_gamma(gamma=0.2)  # 5 days to recover

    # # Running the simulation
    my_simulation.run_sim()

    # # Obtaining time series results
    time_series_vals, infected_time_series, recovered_time_series = my_simulation.tabulate_continuous_time(
    )
    # # Plotting the results:
    plt.plot(time_series_vals, infected_time_series, label='infected')
    plt.plot(time_series_vals, recovered_time_series, label='recovered')
    plt.legend(loc='upper left')
    plt.title('Auto generated time series values')
    plt.xlabel('Time')
    plt.ylabel('Number of nodes')
    plt.show()

    # # Obtaining time series results with a custom time series end point.
    # # ****TIP: Run at least one simulation without specifying a custom limit, in order to get a sense of what range
    # # of continuous time
    # # the simulation takes to fully run. Then on a second run after experimentation, you can specify a limit.
    time_series_vals, infected_time_series, recovered_time_series = my_simulation.tabulate_continuous_time(
        time_buckets=1000, custom_range=True, custom_t_lim=15)
    # # Plotting the results:
    plt.plot(time_series_vals, infected_time_series, label='infected')
    plt.plot(time_series_vals, recovered_time_series, label='recovered')
    plt.legend(loc='upper left')
    plt.title('Custom increments of time values')
    plt.xlabel('Time')
    plt.ylabel('Number of nodes')
    plt.show()

    # # Obtaining cumulative infections by generations of infection:
    gen_results = my_simulation.tabulate_generation_results(max_gens=30)

    # # Plotting generation results
    plt.scatter(np.arange(30), gen_results, label='cumulative infections')
    plt.plot(np.arange(30), gen_results)
    plt.title('Cumulative infections by epidemic generations')
    plt.xlabel('Generation number')
    plt.ylabel('Cumulative Infections')
    plt.show()
コード例 #2
0
    def test_beta_rate_matrix_alters_event_rates(self):
        A = np.random.random_integers(0, 1, (10, 10))
        A = (A + A.T) / 2
        sim = simulation.Simulation(A)
        good_Beta = np.full((10, 10), 0.2)
        good_Gamma = np.full(10, 0.5)
        for edge in sim._potential_IS_events._event_list:
            self.assertEqual(edge.event_rate, 0)

        sim.add_infection_event_rates(good_Beta)
        sim.add_recover_event_rates(good_Gamma)
        for edge in sim._potential_IS_events._event_list:
            self.assertEqual(edge.event_rate, 0.2)
コード例 #3
0
    def test_sim_creates_patientzero(self):
        A = np.random.random_integers(0, 1, (10, 10))
        A = (A + A.T) / 2
        sim = simulation.Simulation(A)
        self.assertRaises(AttributeError, sim._initialize_patient_zero)

        good_Beta = np.full((10, 10), 0.2)
        good_Gamma = np.full(10, 0.5)
        sim.add_recover_event_rates(good_Gamma)
        sim.add_infection_event_rates(good_Beta)

        sim._initialize_patient_zero()
        self.assertEqual(len(sim._potential_recovery_events._event_list), 1)
コード例 #4
0
    def test_custom_time_series_results(self):
        N = 100
        self.beta = 0.99
        self.gamma = 0.0001
        graph = nx.generators.erdos_renyi_graph(N, 0.02)
        N = len(graph.nodes())
        self.Beta = np.full((N, N), self.beta)
        self.Gamma = np.full(N, self.gamma)
        adjacency_matrix = np.array(nx.adjacency_matrix(graph).todense())
        sim = simulation.Simulation(adjacency_matrix)
        sim.add_infection_event_rates(self.Beta)
        sim.add_recover_event_rates(self.Gamma)
        sim._initialize_patient_zero()

        sim.run_sim()

        custom_time_results = sim.tabulate_continuous_time(time_buckets=1000,
                                                           custom_range=True,
                                                           custom_t_lim=15)
        self.assertEqual(len(custom_time_results[0]), 1000)
        self.assertEqual(max(custom_time_results[0]), 15 - 0.015)
コード例 #5
0
    def test_IS_edges_are_updated_after_single_step(self):
        N = 10
        self.beta = 0.99
        self.gamma = 0.0001
        graph = nx.generators.complete_graph(N)
        N = len(graph.nodes())
        self.Beta = np.full((N, N), self.beta)
        self.Gamma = np.full(N, self.gamma)
        adjacency_matrix = np.array(nx.adjacency_matrix(graph).todense())
        sim = simulation.Simulation(adjacency_matrix)
        sim.add_infection_event_rates(self.Beta)
        sim.add_recover_event_rates(self.Gamma)
        sim._initialize_patient_zero()
        print('before single step')

        self.assertGreaterEqual(len(sim._potential_IS_events._event_list), 1)
        self.assertEqual(len(sim._potential_recovery_events._event_list), 1)
        sim._single_step()

        print('after single step')
        self.assertEqual(len(sim._potential_recovery_events._event_list), 2)
        infected_nodes = list(
            map(lambda node: node.get_label(),
                sim._potential_recovery_events._event_list))
        for edge in sim._potential_IS_events._event_list:
            self.assertIn(edge.get_left_node().get_label(), infected_nodes)
            self.assertNotIn(edge.get_right_node().get_label(), infected_nodes)
        if len(sim._potential_IS_events._event_list) > 0:
            sim._single_step()
            print('after second single step')
            self.assertEqual(len(sim._potential_recovery_events._event_list),
                             3)
            infected_nodes = list(
                map(lambda node: node.get_label(),
                    sim._potential_recovery_events._event_list))
            for edge in sim._potential_IS_events._event_list:
                self.assertIn(edge.get_left_node().get_label(), infected_nodes)
                self.assertNotIn(edge.get_right_node().get_label(),
                                 infected_nodes)
コード例 #6
0
ファイル: sandbox.py プロジェクト: andrea-allen/epintervene
def basic_SIR_groups_simulation():
    print('Basic SIR simulation with membership groups')
    # Creating a network from a Stochastic Block Model
    nb = network.NetworkBuilder
    G, pos, _ = create_zoo_stochastic_block_model(tiger_elephant_block=.05,
                                                  tiger_bird_block=.03,
                                                  bird_elephant_block=.02)
    adjlist = nb.create_adjacency_list(G)

    # # Assigning indices for the split population
    tiger_population = int(len(adjlist) / 3)
    bird_population = int(len(adjlist) / 3)
    elephant_population = int(len(adjlist) / 3)

    # # Creating a vector of node memberships, indexed by node label (index from above)
    node_membership_vector = []
    for i in range(tiger_population):
        node_membership_vector.append('tiger')
    for j in range(bird_population):
        node_membership_vector.append('bird')
    for k in range(elephant_population):
        node_membership_vector.append('elephant')

    # # Setting up the simulation with memberships
    sim = simulation.Simulation(
        N=len(adjlist),
        adj_list=adjlist,
        membership_groups=['tiger', 'bird', 'elephant'],
        node_memberships=node_membership_vector)

    # # Configuring the disease parameters
    sim.set_uniform_beta(0.7)
    sim.set_uniform_gamma(0.21)

    # # Running the simulation, must specify to track memberships
    sim.run_sim(with_memberships=True,
                wait_for_recovery=True,
                uniform_rate=True)

    # # Recording results with group memberships
    ts, membership_ts_infc, membership_ts_rec = sim.tabulate_continuous_time_with_groups(
        time_buckets=1000, custom_range=True, custom_t_lim=30)

    # # Plotting and interpreting the results
    plt.figure(0)
    for group in membership_ts_infc.keys():
        plt.plot(ts, membership_ts_infc[group], label=f'{group} infected')
        plt.plot(ts,
                 membership_ts_rec[group],
                 label=f'{group} recovered',
                 ls='--')
    plt.xlabel('Time t')
    plt.ylabel('Number of nodes infected in network group')
    plt.legend(loc='upper left')
    plt.title('SIR Continuous time results with group membership')
    plt.box(on=False)
    plt.show()

    ts, infect_ts, recover_ts = sim.tabulate_continuous_time(time_buckets=1000,
                                                             custom_range=True,
                                                             custom_t_lim=30)
    plt.figure(1)
    plt.plot(ts, infect_ts, color='blue', label='Infected')
    plt.plot(ts, recover_ts, color='green', label='Recovered')
    plt.xlabel('Time t')
    plt.ylabel('Number of nodes in class')
    plt.title(
        'SIR Continuous time results \n(total population, without showing group membership)'
    )
    plt.legend(loc='upper left')
    plt.box(on=False)
    # plt.show()

    ts_by_gen = sim.tabulate_generation_results(20)
    plt.figure(2)
    plt.plot(np.arange(len(ts_by_gen)), ts_by_gen)
    plt.scatter(np.arange(len(ts_by_gen)), ts_by_gen)
    plt.xlabel('Generation number')
    plt.ylabel('Cumulative infections by generation')
    plt.title('SIR Cumulative Epidemic Generation size results')
    plt.box(on=False)
    plt.show()
コード例 #7
0
def random_intervention_example():
    print('Random intervention simulation tutorial')
    # # **** TIP ***** For best demonstration, if time series results show a simulation in which only a single node
    # # was infected, try running the example again to see another result.

    # # Create a NetworkBuilder object, to help with creating and configuring the network for the simulation:
    nb = network.NetworkBuilder
    # # Specify a degree distribution to create a configuration model network if desired:
    degree_distrb = binomial_degree_distb(400, 3)
    # # Generating a network from the above degree distribution, with 100 nodes
    G, pos = nb.from_degree_distribution(100, degree_distrb)
    # # If you already have a network, feel free to skip the above steps and generate your own NetworkX object,
    # # or skip this next step and provide a symmetric adjacency list.
    adjlist = nb.create_adjacency_list(G)

    # # Constructing the simulation object
    my_simulation = extended_simulation.RandomInterventionSim(adjlist=adjlist, N=len(adjlist))

    # # Setting required configurations
    my_simulation.set_uniform_beta(beta=0.9)  # .9 people per day per infected person
    my_simulation.set_uniform_gamma(gamma=0.2)  # 5 days to recover

    # # CONFIGURE THE INTERVENTION SPECIFICATION
    # # Here, this configuration means that at generation 4 (i.e. when the first person belonging to generation 4
    # # becomes infected), a random set of nodes making up 30% of the population will be reduced to 0 transmissibility
    # # For now, only beta=0 is supported for Random vaccination.
    my_simulation.configure_intervention(intervention_gen=4, proportion_reduced=0.3, beta_redux=0)

    # # Setting up a simulation object with the original parameters and no intervention:
    regular_simulation = simulation.Simulation(adj_list=adjlist, N=len(adjlist))
    regular_simulation.set_uniform_beta(beta=0.9)
    regular_simulation.set_uniform_gamma(gamma=0.2)

    # # Running the simulations
    my_simulation.run_sim()
    regular_simulation.run_sim()

    # # Obtaining time series results
    time_series_vals, infected_time_series, recovered_time_series = my_simulation.tabulate_continuous_time(
        time_buckets=1000,
        custom_range=True,
        custom_t_lim=15)
    time_series_vals_reg, infected_time_series_reg, recovered_time_series_reg = regular_simulation.tabulate_continuous_time(
        time_buckets=1000,
        custom_range=True,
        custom_t_lim=15)
    # # Plotting the results:
    plt.plot(time_series_vals, infected_time_series, label='infected w/ intervention')
    plt.plot(time_series_vals_reg, infected_time_series_reg, label='infected normally')
    plt.plot(time_series_vals, recovered_time_series, label='recovered w/ intervention')
    plt.plot(time_series_vals_reg, recovered_time_series_reg, label='recovered normally')
    plt.legend(loc='upper left')
    plt.title('Auto generated time series values')
    plt.xlabel('Time')
    plt.ylabel('Number of nodes')
    plt.show()

    # # Obtaining cumulative infections by generations of infection:
    gen_results = my_simulation.tabulate_generation_results(max_gens=30)
    gen_results_reg = regular_simulation.tabulate_generation_results(max_gens=30)

    # # Plotting generation results
    plt.scatter(np.arange(30), gen_results, label='cumulative infections w/ intervention')
    plt.scatter(np.arange(30), gen_results_reg, label='normal cumulative infections')
    plt.plot(np.arange(30), gen_results)
    plt.plot(np.arange(30), gen_results_reg)
    plt.title('Cumulative infections by epidemic generations')
    plt.xlabel('Generation number')
    plt.ylabel('Cumulative Infections')
    plt.legend(loc='lower right')
    plt.show()
コード例 #8
0
def rollout_intervention_examples():
    # # If you want to simulate a series of vaccinations, in which a progressive fraction of the population is
    #   vaccinated in either the Random or Targeted schemes, follow the below examples:
    # # In this example, we will run each simulation 10 times and take the ensemble average of the effects, to obtain
    # # a smoother picture of the type of results available.

    # # Create a NetworkBuilder object, to help with creating and configuring the network for the simulation:
    nb = network.NetworkBuilder
    # # Specify a degree distribution to create a configuration model network if desired:
    degree_distrb = binomial_degree_distb(400, 3)
    # # Generating a network from the above degree distribution, with 100 nodes
    G, pos = nb.from_degree_distribution(300, degree_distrb)
    # # If you already have a network, feel free to skip the above steps and generate your own NetworkX object,
    # # or skip this next step and provide a symmetric adjacency list.
    adjlist = nb.create_adjacency_list(G)

    # # Initializing the data structures for the ensemble of results:
    time_series_vals = None
    infected_ts_normal = None
    infected_ts_random_rollout = None
    infected_ts_targeted_rollout = None

    gen_results_reg = np.zeros(30)
    gen_results_targ = np.zeros(30)
    gen_results_rand = np.zeros(30)

    # # Looping as many times as the number of simulations we want to run, we will initialize a NEW simulation object
    # # every time, and collate the results:
    num_sims = 100
    for n in range(num_sims):
        # # Constructing the simulation object, a rollout with random vaccination
        random_rollout_simulation = extended_simulation.RandomRolloutSimulation(adjlist=adjlist, N=len(adjlist))

        # # Setting required configurations, for starting
        random_rollout_simulation.set_uniform_beta(beta=0.9)  # .9 people per day per infected person
        random_rollout_simulation.set_uniform_gamma(gamma=0.2)  # 5 days to recover

        # # Constructing a targeted rollout intervention object
        targeted_rollout_simulation = extended_simulation.TargetedRolloutSimulation(adjlist=adjlist, N=len(adjlist))
        targeted_rollout_simulation.set_uniform_beta(beta=0.9)
        targeted_rollout_simulation.set_uniform_gamma(gamma=0.2)

        # # CONFIGURE THE INTERVENTION SPECIFICATIONS
        # # Here we will configure the interventions for both random and targeted rollouts.
        # # We will define a list of which generations to intervene at, and what proportion of the population to
        # vaccinate (with 100% efficacy) at each successive generation.
        # # The ONLY DIFFERENCE between the random vs targeted scheme is the vaccination STRATEGY, for
        # Random Rollout, a random set of the designated percentage of individuals is selected.
        # # For Targeted Rollout, the designated percentage is selected by decreasing order of highest degree nodes.

        random_rollout_simulation.configure_intervention(intervention_gen_list=[3, 5, 7], beta_redux_list=[0,0,0], proportion_reduced_list=[.02, .03, .05])
        targeted_rollout_simulation.configure_intervention(intervention_gen_list=[3, 5, 7], beta_redux_list=[0,0,0], proportion_reduced_list=[.02, .03, .05])
        # # Notice how in this example, we are configuring the random and targeted interventions with the same
        # configurations, in order to observe the difference that the two strategies have compared to one another.

        # # Setting up a simulation object with the original parameters and no intervention:
        regular_simulation = simulation.Simulation(adj_list=adjlist, N=len(adjlist))
        regular_simulation.set_uniform_beta(beta=0.9)
        regular_simulation.set_uniform_gamma(gamma=0.2)

        # # Running the simulations
        regular_simulation.run_sim()
        random_rollout_simulation.run_sim()
        targeted_rollout_simulation.run_sim()

        # # Obtaining time series results
        if time_series_vals is None:
            time_series_vals, infected_ts_normal, _ = regular_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            time_series_vals, infected_ts_random_rollout, _ = random_rollout_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            time_series_vals, infected_ts_targeted_rollout, _ = targeted_rollout_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            # # Obtaining cumulative infections by generations of infection:
            gen_results_reg += regular_simulation.tabulate_generation_results(max_gens=30)
            gen_results_targ += targeted_rollout_simulation.tabulate_generation_results(max_gens=30)
            gen_results_rand += random_rollout_simulation.tabulate_generation_results(max_gens=30)
        else:
            _, i_t_t, _ = regular_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_normal += i_t_t

            _, i_t_n, _ = random_rollout_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_random_rollout += i_t_n

            _, i_t_r, _ = targeted_rollout_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_targeted_rollout += i_t_r

            # # Obtaining cumulative infections by generations of infection:
            gen_results_reg += regular_simulation.tabulate_generation_results(max_gens=30)
            gen_results_targ += targeted_rollout_simulation.tabulate_generation_results(max_gens=30)
            gen_results_rand += random_rollout_simulation.tabulate_generation_results(max_gens=30)

    # # Normalizing for the 10 simulations
    infected_ts_normal = infected_ts_normal / num_sims
    infected_ts_random_rollout = infected_ts_random_rollout / num_sims
    infected_ts_targeted_rollout = infected_ts_targeted_rollout / num_sims

    # # Plotting the results:
    plt.plot(time_series_vals, infected_ts_targeted_rollout, label='infected w/ targeted rollout intervention', color='blue')
    plt.plot(time_series_vals, infected_ts_random_rollout, label='infected w/ random rollout intervention', color='red')
    plt.plot(time_series_vals, infected_ts_normal, label='infected normally', color='orange')

    plt.legend(loc='upper left')
    plt.title('Effects of Targeted Vaccination compared \n to normal and random')
    plt.xlabel('Time')
    plt.ylabel('Number of nodes')
    plt.show()

    # # Plotting generation results
    plt.scatter(np.arange(30), gen_results_targ/num_sims, label='cumulative infections w/ targeted rollout intervention')
    plt.scatter(np.arange(30), gen_results_reg/num_sims, label='normal cumulative infections')
    plt.scatter(np.arange(30), gen_results_rand/num_sims, label='cumulative infections w/ random rollout intervention')
    plt.plot(np.arange(30), gen_results_targ/num_sims)
    plt.plot(np.arange(30), gen_results_reg/num_sims)
    plt.plot(np.arange(30), gen_results_rand/num_sims)
    plt.title('Cumulative infections by epidemic generations')
    plt.xlabel('Generation number')
    plt.ylabel('Cumulative Infections')
    plt.legend(loc='lower right')
    plt.show()
コード例 #9
0
def absolute_time_intervention_example():
    # # In this example, we will run each simulation 100 times and take the ensemble average of the effects, to obtain
    # # a smoother picture of the type of results available.

    # # This intervention allows you to switch the population network at a designated time during the run.
    # It is recommended that you first get familiar with the dynamics of the simulation on both networks, and the
    # relative time dynamics of t, so that you can provide a proper time value t for the intervention.

    # # Create a NetworkBuilder object, to help with creating and configuring the network for the simulation:
    nb = network.NetworkBuilder
    # # Specify a degree distribution to create a configuration model network if desired:
    degree_distrb = binomial_degree_distb(400, 3)
    # # Generating a network from the above degree distribution, with 100 nodes
    G, pos = nb.from_degree_distribution(100, degree_distrb)
    # # If you already have a network, feel free to skip the above steps and generate your own NetworkX object,
    # # or skip this next step and provide a symmetric adjacency list.
    adjlist_1 = nb.create_adjacency_list(G)

    # # Create a second network, for the intervention where we will switch networks:
    nb = network.NetworkBuilder
    # # Specify a degree distribution to create a configuration model network if desired:
    degree_distrb = binomial_degree_distb(400, 7)
    # # Generating a network from the above degree distribution, with 100 nodes
    G, pos = nb.from_degree_distribution(100, degree_distrb)
    # # If you already have a network, feel free to skip the above steps and generate your own NetworkX object,
    # # or skip this next step and provide a symmetric adjacency list.
    adjlist_2 = nb.create_adjacency_list(G)

    # # Initializing the data structures for the ensemble of results:
    time_series_vals = None
    infected_ts_normal = None
    infected_ts_netswitch = None
    recovered_ts_normal = None
    recovered_ts_netswitch = None

    # # Looping as many times as the number of simulations we want to run, we will initialize a NEW simulation object
    # # every time, and collate the results:
    num_runs = 100
    for n in range(num_runs):
        # # Constructing the simulation object
        my_simulation = extended_simulation.AbsoluteTimeNetworkSwitchSim(adjlist=adjlist_2, N=len(adjlist_1))

        # # Setting required configurations
        my_simulation.set_uniform_beta(beta=0.1)  # .7 people per day per infected person
        my_simulation.set_uniform_gamma(gamma=0.005)  # 5 days to recover

        # # CONFIGURE THE INTERVENTION SPECIFICATION
        # # Here, this configuration means that at time t=7, the population network will switch to that given by
        # adjlist_2.
        my_simulation.configure_intervention(intervention_time=7, new_adjlist=adjlist_1)

        # # Setting up a simulation object with the original parameters and no intervention, that only runs on
        # adjlist_1's network
        regular_simulation = simulation.Simulation(adj_list=adjlist_2, N=len(adjlist_1))
        regular_simulation.set_uniform_beta(beta=0.1)
        regular_simulation.set_uniform_gamma(gamma=0.005)

        # # Running the simulations
        my_simulation.run_sim()
        regular_simulation.run_sim()

        # # Obtaining time series results
        if time_series_vals is None:
            time_series_vals, infected_ts_netswitch, recovered_ts_netswitch = my_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            time_series_vals, infected_ts_normal, recovered_ts_normal = regular_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)

        else:
            _, i_t_t, r_t_t = my_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_netswitch += i_t_t
            recovered_ts_netswitch += r_t_t
            _, i_t_n, r_t_n = regular_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_normal += i_t_n
            recovered_ts_normal += r_t_n

    # # Normalizing for the 10 simulations
    infected_ts_normal = infected_ts_normal / num_runs
    infected_ts_netswitch = infected_ts_netswitch / num_runs
    recovered_ts_normal = recovered_ts_normal / num_runs
    recovered_ts_netswitch = recovered_ts_netswitch / num_runs

    # # Plotting the results:
    plt.plot(time_series_vals, infected_ts_netswitch, label='infected w/ net switch intervention', color='blue')
    plt.plot(time_series_vals, infected_ts_normal, label='infected normally', color='orange')
    plt.plot(time_series_vals, recovered_ts_netswitch, label='recovered w/ net switch intervention', color='blue', ls='--')
    plt.plot(time_series_vals, recovered_ts_normal, label='recovered normally', color='orange', ls='--')
    plt.legend(loc='upper left')
    plt.title('Effects of Network Switching at t=7 compared \n to normal run on Network 1')
    plt.xlabel('Time')
    plt.ylabel('Number of nodes')
    plt.show()
コード例 #10
0
def targeted_intervention_example():
    print('Targeted intervention simulation tutorial')

    # # In this example, we will run each simulation 10 times and take the ensemble average of the effects, to obtain
    # # a smoother picture of the type of results available.

    # # Create a NetworkBuilder object, to help with creating and configuring the network for the simulation:
    nb = network.NetworkBuilder
    # # Specify a degree distribution to create a configuration model network if desired:
    degree_distrb = binomial_degree_distb(400, 3)
    # # Generating a network from the above degree distribution, with 100 nodes
    G, pos = nb.from_degree_distribution(100, degree_distrb)
    # # If you already have a network, feel free to skip the above steps and generate your own NetworkX object,
    # # or skip this next step and provide a symmetric adjacency list.
    adjlist = nb.create_adjacency_list(G)

    # # Initializing the data structures for the ensemble of results:
    time_series_vals = None
    infected_ts_normal = None
    infected_ts_random = None
    infected_ts_targeted = None
    recovered_ts_normal = None
    recovered_ts_random = None
    recovered_ts_targeted = None

    # # Looping as many times as the number of simulations we want to run, we will initialize a NEW simulation object
    # # every time, and collate the results:
    for n in range(40):
        # # Constructing the simulation object
        my_simulation = extended_simulation.TargetedInterventionSim(adjlist=adjlist, N=len(adjlist))

        # # Setting required configurations
        my_simulation.set_uniform_beta(beta=0.9)  # .9 people per day per infected person
        my_simulation.set_uniform_gamma(gamma=0.2)  # 5 days to recover

        # # CONFIGURE THE INTERVENTION SPECIFICATION
        # # Here, this configuration means that at generation 4 (i.e. when the first person belonging to generation 4
        # # becomes infected), a set of nodes making up 30% of the population will be reduced to 0 transmissibility.
        # # The nodes are chosen in order of degree class, highest degree nodes included first, until 30% quota is reached.
        # # For now, only beta=0 is supported for Targeted vaccination.
        my_simulation.configure_intervention(intervention_gen=4, proportion_reduced=0.3, beta_redux=0)

        # # Setting up a simulation object with the original parameters and no intervention:
        regular_simulation = simulation.Simulation(adj_list=adjlist, N=len(adjlist))
        regular_simulation.set_uniform_beta(beta=0.9)
        regular_simulation.set_uniform_gamma(gamma=0.2)

        # # Setting up a simulation with Random vaccination (from example above) for comparison purposes.
        random_simulation = extended_simulation.RandomInterventionSim(adjlist=adjlist, N=len(adjlist))
        random_simulation.set_uniform_beta(beta=0.9)
        random_simulation.set_uniform_gamma(gamma=0.2)
        random_simulation.configure_intervention(intervention_gen=4, proportion_reduced=0.3, beta_redux=0)

        # # Running the simulations
        my_simulation.run_sim()
        regular_simulation.run_sim()
        random_simulation.run_sim()

        # # Obtaining time series results
        if time_series_vals is None:
            time_series_vals, infected_ts_targeted, recovered_ts_targeted = my_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            time_series_vals, infected_ts_normal, recovered_ts_normal = regular_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            time_series_vals, infected_ts_random, recovered_ts_random = random_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
        else:
            _, i_t_t, r_t_t = my_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_targeted += i_t_t
            recovered_ts_targeted += r_t_t
            _, i_t_n, r_t_n = regular_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_normal += i_t_n
            recovered_ts_normal += r_t_n
            _, i_t_r, r_t_r = random_simulation.tabulate_continuous_time(
                time_buckets=1000,
                custom_range=True,
                custom_t_lim=15)
            infected_ts_random += i_t_r
            recovered_ts_random += r_t_r

    # # Normalizing for the 10 simulations
    infected_ts_normal = infected_ts_normal / 10
    infected_ts_random = infected_ts_random / 10
    infected_ts_targeted = infected_ts_targeted / 10
    recovered_ts_normal = recovered_ts_normal / 10
    recovered_ts_random = recovered_ts_random / 10
    recovered_ts_targeted = recovered_ts_targeted / 10

    # # Plotting the results:
    plt.plot(time_series_vals, infected_ts_targeted, label='infected w/ targeted intervention', color='blue')
    plt.plot(time_series_vals, infected_ts_random, label='infected w/ random intervention', color='red')
    plt.plot(time_series_vals, infected_ts_normal, label='infected normally', color='orange')
    plt.plot(time_series_vals, recovered_ts_targeted, label='recovered w/ targeted intervention', color='blue', ls='--')
    plt.plot(time_series_vals, recovered_ts_normal, label='recovered normally', color='orange', ls='--')
    plt.plot(time_series_vals, recovered_ts_random, label='recovered w/ random intervention', color='red', ls='--')
    plt.legend(loc='upper left')
    plt.title('Effects of Targeted Vaccination compared \n to normal and random')
    plt.xlabel('Time')
    plt.ylabel('Number of nodes')
    plt.show()

    # # Obtaining cumulative infections by generations of infection:
    # # These results in this example are not the ensemble result, just the results from a single (the latest) run
    gen_results = my_simulation.tabulate_generation_results(max_gens=30)
    gen_results_reg = regular_simulation.tabulate_generation_results(max_gens=30)
    gen_results_rand = random_simulation.tabulate_generation_results(max_gens=30)

    # # Plotting generation results
    plt.scatter(np.arange(30), gen_results, label='cumulative infections w/ targeted intervention')
    plt.scatter(np.arange(30), gen_results_reg, label='normal cumulative infections')
    plt.scatter(np.arange(30), gen_results_rand, label='cumulative infections w/ random intervention')
    plt.plot(np.arange(30), gen_results)
    plt.plot(np.arange(30), gen_results_reg)
    plt.plot(np.arange(30), gen_results_rand)
    plt.title('Cumulative infections by epidemic generations')
    plt.xlabel('Generation number')
    plt.ylabel('Cumulative Infections')
    plt.legend(loc='lower right')
    plt.show()
コード例 #11
0
def run_single_simulation(A,
                          adjlist,
                          current,
                          results_type='generation',
                          intervention_gen=-1,
                          beta_interv=-1.0,
                          beta_init=1.0,
                          gamma_init=0.001,
                          prop_reduced=0.0,
                          intervention_gen_list=None,
                          beta_redux_list=None,
                          prop_reduced_list=None,
                          intervention_type="none",
                          viz_pos=None,
                          G=None,
                          kill_by=None,
                          active_gen_sizes_on=False,
                          Beta=None,
                          Gamma=None):
    start_time = time.time()
    N = len(adjlist)
    # Constructing the simulation of specified Intervention Type, otherwise will run a regular simulation
    if intervention_type == "random-rollout":
        sim = extended_simulation.RandomRolloutSimulation(N=N, adjlist=adjlist)
        sim.set_uniform_beta(beta_init)
        sim.set_uniform_gamma(gamma_init)
        sim.configure_intervention(intervention_gen_list=intervention_gen_list,
                                   beta_redux_list=beta_redux_list,
                                   proportion_reduced_list=prop_reduced_list)

    elif intervention_type == "random":
        sim = extended_simulation.RandomInterventionSim(N, adjlist=adjlist)
        sim.set_uniform_beta(beta_init)
        sim.set_uniform_gamma(gamma_init)
        sim.configure_intervention(intervention_gen=intervention_gen,
                                   beta_redux=beta_interv,
                                   proportion_reduced=prop_reduced)
    elif intervention_type == "universal":
        sim = extended_simulation.UniversalInterventionSim(N, adjlist=adjlist)
        sim.set_uniform_beta(beta_init)
        sim.set_uniform_gamma(gamma_init)
        sim.configure_intervention(intervention_gen=intervention_gen,
                                   beta_redux=beta_interv)
    elif intervention_type == "targeted":
        sim = extended_simulation.TargetedInterventionSim(N, adjlist=adjlist)
        sim.set_uniform_beta(beta_init)
        sim.set_uniform_gamma(gamma_init)
        sim.configure_intervention(intervention_gen=intervention_gen,
                                   beta_redux=beta_interv,
                                   proportion_reduced=prop_reduced)
    elif intervention_type == "targeted-rollout":
        sim = extended_simulation.TargetedRolloutSimulation(N=N,
                                                            adjlist=adjlist)
        sim.set_uniform_beta(beta_init)
        sim.set_uniform_gamma(gamma_init)
        sim.configure_intervention(intervention_gen_list=intervention_gen_list,
                                   beta_redux_list=beta_redux_list,
                                   proportion_reduced_list=prop_reduced_list)
    else:
        sim = simulation.Simulation(N=N, adj_list=adjlist)
        sim.set_uniform_beta(beta_init)
        sim.set_uniform_gamma(gamma_init)

    # Run the simulation
    sim.run_sim(uniform_rate=True,
                wait_for_recovery=False,
                p_zero=None,
                visualize=False,
                kill_by=kill_by,
                viz_graph=G,
                viz_pos=viz_pos,
                record_active_gen_sizes=active_gen_sizes_on)

    # Printing progress of the ensemble for the user to keep track
    if current % 50 == 0:
        print('current sim ' + str(current))
        print("--- %s seconds to run latest simulation---" %
              (time.time() - start_time))

    # Tabulating results based on user's specified input type
    if str(results_type).lower() == 'generation':
        generational_results = sim.tabulate_generation_results(100)
        return generational_results
    elif str(results_type).lower() == 'time':
        # TODO put the time buckets in here
        timeseries, timeseries_results_inf, timeseries_results_rec = sim.tabulate_continuous_time(
            100, custom_range=True, custom_t_lim=20000)
        return timeseries, timeseries_results_inf, timeseries_results_rec
    elif str(results_type).lower() == 'time_and_gen':
        if active_gen_sizes_on:
            timeseries, timeseries_results_inf, timeseries_results_rec, active_gens_ts, \
            total_gens_ts, active_gen_sizes = sim.tabulate_continuous_time(1000,
                                                                            custom_range=True,
                                                                            custom_t_lim=10000,
                                                                            active_gen_info=True,
                                                                           active_gen_sizes=True)
            generational_results = sim.tabulate_generation_results(100)
            generational_emergence = sim.get_generational_emergence()
            return generational_results, generational_emergence, timeseries, timeseries_results_inf, \
                   timeseries_results_rec, active_gens_ts, total_gens_ts, active_gen_sizes
        else:
            timeseries, timeseries_results_inf, timeseries_results_rec, active_gens_ts, total_gens_ts = sim.tabulate_continuous_time(
                1000,
                custom_range=True,
                custom_t_lim=10000,
                active_gen_info=True)
        generational_results = sim.tabulate_generation_results(100)
        generational_emergence = sim.get_generational_emergence()
        return generational_results, generational_emergence, timeseries, timeseries_results_inf, timeseries_results_rec, active_gens_ts, total_gens_ts
    elif str(results_type).lower() == 'time_groups':
        timeseries, infection_timeseries_groups = sim.tabulate_continuous_time_with_groups(
            1000)
        return timeseries, infection_timeseries_groups
    else:
        print('No results type provided, returning basic time series results')
        timeseries, timeseries_results_inf, timeseries_results_rec = sim.tabulate_continuous_time(
            1000)

    return timeseries, timeseries_results_inf
コード例 #12
0
 def test_beta_rate_matrix_throws_exception(self):
     A = np.random.random_integers(0, 1, (10, 10))
     A = (A + A.T) / 2
     sim = simulation.Simulation(A)
     bad_Beta = np.zeros((2, 2))
     self.assertRaises(ValueError, sim.add_infection_event_rates, bad_Beta)