Пример #1
0
def test_AddPolicyInfectedRate():
    model = CovidModel()
    listener = AddPolicyInfectedRate(model, SocialPolicy.LOCKDOWN_ALL, 0.5)
    model.add_listener(listener)

    model.global_count.total_population = 10
    model.global_count.infected_count = 4
    assert SocialPolicy.LOCKDOWN_ALL not in get_parameters(
    ).params['social_policies']
    model.step()
    assert SocialPolicy.LOCKDOWN_ALL not in get_parameters(
    ).params['social_policies']
    model.global_count.infected_count = 5
    model.step()
    assert SocialPolicy.LOCKDOWN_ALL in get_parameters(
    ).params['social_policies']
population_size = 1000
simulation_cycles = 180 # days

################################################################################
# Scenarios

scenario = {}

# ------------------------------------------------------------------------------

sc = 1 # Do nothing
print(f"Setting up scenario {sc}")
scenario[sc] = {}
scenario[sc]['parameters'] = copy.deepcopy(common_parameters)
set_parameters(scenario[sc]['parameters'])
scenario[sc]['model'] = CovidModel()
np.random.seed(seed)
setup_city_layout(scenario[sc]['model'], population_size)

# ------------------------------------------------------------------------------

sc = 2 # complete lockdown
print(f"Setting up scenario {sc}")
scenario[sc] = {}
scenario[sc]['parameters'] = copy.deepcopy(common_parameters)
scenario[sc]['parameters'].params['social_policies'] = [
    SocialPolicy.LOCKDOWN_OFFICE,
    SocialPolicy.LOCKDOWN_FACTORY,
    SocialPolicy.LOCKDOWN_RETAIL,
    SocialPolicy.LOCKDOWN_ELEMENTARY_SCHOOL,
    SocialPolicy.LOCKDOWN_MIDDLE_SCHOOL,
Пример #3
0
def test_propaganda():
    model = CovidModel()
    get_parameters().params['risk_tolerance_mean'] = 1.0
    propaganda = Propaganda(model, 5)
    model.add_listener(propaganda)
    assert get_parameters().params['risk_tolerance_mean'] == 1.0
    for i in range(5):
        model.step()
        assert get_parameters().params['risk_tolerance_mean'] == 1.0
    model.step()
    assert get_parameters().params['risk_tolerance_mean'] == 0.9

    model.step()
    assert get_parameters().params['risk_tolerance_mean'] == 0.9
    model.step()
    assert get_parameters().params['risk_tolerance_mean'] == 0.9
    model.step()
    assert get_parameters().params['risk_tolerance_mean'] == 0.8

    for i in range(2):
        model.step()
    assert get_parameters().params['risk_tolerance_mean'] == 0.8

    for i in range(7):
        for j in range(3):
            model.step()
            assert (get_parameters().params['risk_tolerance_mean'] -
                    (0.7 - (0.1 * i))) < 0.001

    for i in range(100):
        model.step()
        assert get_parameters().params['risk_tolerance_mean'] == 0.1
Пример #4
0
    mask_efficacy=mask_efficacy,
    imune_rate=imune_rate,
    initial_infection_rate=initial_infection_rate,
    hospitalization_capacity=hospitalization_capacity,
    latency_period_mean=latency_period_mean,
    latency_period_stdev=latency_period_stdev,
    incubation_period_mean=incubation_period_mean,
    incubation_period_stdev=incubation_period_stdev,
    disease_period_mean=disease_period_mean,
    disease_period_stdev=disease_period_stdev,
    daily_interaction_count=daily_interaction_count,
    contagion_probability=contagion_probability,
    asymptomatic_isolation_rate=asymptomatic_isolation_rate,
    symptomatic_isolation_rate=symptomatic_isolation_rate)
set_parameters(scenario[sc]['parameters'])
scenario[sc]['model'] = CovidModel()
scenario[sc]['location'] = SimpleLocation(0, scenario[sc]['model'],
                                          population_size)

# ------------------------------------------------------------------------------

sc = 2  # Restrict the mobility only for infected people - no weareables
scenario[sc] = {}
scenario[sc]['parameters'] = SimulationParameters(
    weareable_adoption_rate=0.0,
    mask_user_rate=mask_user_rate,
    mask_efficacy=mask_efficacy,
    imune_rate=imune_rate,
    initial_infection_rate=initial_infection_rate,
    hospitalization_capacity=hospitalization_capacity,
    latency_period_mean=latency_period_mean,
Пример #5
0
from model import location
from model.base import CovidModel, SimulationParameters, set_parameters
from model.human import Human, Adult, InfectionStatus
from model.utils import SimulationState, RestaurantType

parameters = SimulationParameters(mask_user_rate=0.0)
set_parameters(parameters)
model = CovidModel()
capacity = 2000


def check_spread(sample_location,
                 spreading_states=None,
                 check_step=True,
                 in_social_event=False):
    if spreading_states is None:
        spreading_states = list(SimulationState)
    # Creates an infected and a susceptible human
    sample_human_1 = Human.factory(covid_model=model, forced_age=20)
    sample_human_1.infection_status = InfectionStatus.INFECTED
    sample_human_1.infection_days_count = 1
    sample_human_1.infection_latency = 0
    assert sample_human_1.is_infected() and sample_human_1.is_contagious()
    sample_human_2 = Adult(covid_model=model,
                           age=50,
                           msp=0.05,
                           hsp=0.1,
                           mfd=False)
    sample_human_2.strid = 'human_2'
    sample_human_2.infection_status = InfectionStatus.SUSCEPTIBLE
    assert not sample_human_2.is_infected()
Пример #6
0
def multiple_runs(params,
                  population_size,
                  simulation_cycles,
                  num_runs=5,
                  seeds=[],
                  debug=False,
                  desired_stats=None,
                  fname="scenario",
                  listeners=[],
                  do_print=False,
                  home_grid_height=1,
                  home_grid_width=1,
                  work_height=1,
                  work_width=1,
                  school_height=1,
                  school_width=1):
    color = {
        'susceptible': 'lightblue',
        'infected': 'gray',
        'recovered': 'lightgreen',
        'death': 'black',
        'hospitalization': 'orange',
        'icu': 'red',
        'income': 'magenta'
    }
    if desired_stats is None:
        desired_stats = [
            "susceptible", "infected", "recovered", "hospitalization", "icu",
            "death", "income"
        ]
    randomlist = random.sample(range(10000),
                               num_runs) if len(seeds) == 0 else seeds
    if do_print:
        print("Save these seeds if you want to rerun a scenario")
        print(randomlist)

    all_runs = {}
    avg = {}
    last = {}
    peak = {}
    average = {}
    lower = {}
    upper = {}
    for stat in desired_stats:
        all_runs[stat] = {}
        avg[stat] = []
        last[stat] = []
        peak[stat] = []
        average[stat] = []
        upper[stat] = []
        lower[stat] = []
    for s in randomlist:
        paramcopy = copy.deepcopy(params)
        set_parameters(paramcopy)
        model = CovidModel(debug=debug)
        np.random.seed(s + 1)
        random.seed(s + 2)
        model.reset_randomizer(s)

        l = []
        ls = copy.deepcopy(listeners)
        for listener in ls:
            funct = listener.pop(0)
            listener[:0] = [model]
            l.append(globals()[funct](*listener))
        for k in l:
            model.add_listener(k)
        #for m in model.ls:
        #print(m)
        if debug:
            model.debug_each_n_cycles = 20
        setup_grid_layout(model, population_size, home_grid_height,
                          home_grid_width, work_height, work_width,
                          school_height, school_width)
        if do_print:
            print("run with seed {0}:".format(str(s)))
        statistics = BasicStatistics(model)
        model.add_listener(statistics)
        for i in range(simulation_cycles):
            model.step()
        for stat in desired_stats:
            all_runs[stat][s] = getattr(statistics, stat)
            if stat is "income":
                all_runs[stat][s].pop(1)
            avg[stat].append(np.mean(all_runs[stat][s]))
            last[stat].append(all_runs[stat][s][-1])
            peak[stat].append(max(all_runs[stat][s]))

    fig, ax = plt.subplots()
    ax.set_title('Contagion Evolution')
    ax.set_xlim((0, simulation_cycles))
    ax.set_ylim((-0.1, 1.1))
    ax.axhline(y=get_parameters().get('icu_capacity'),
               c="black",
               ls='--',
               label='Critical limit')

    for s in randomlist:
        adict = {stat: all_runs[stat][s] for stat in desired_stats}
        df = pd.DataFrame(data=adict)
        df.to_csv(fname + "-" + str(s) + ".csv")

    each_step = {}
    for stat in desired_stats:
        each_step[stat] = []
        for i in range(simulation_cycles):
            each_step[stat].append([all_runs[stat][s][i] for s in randomlist])
        for i in range(simulation_cycles):
            loweri, averagei, upperi = confidence_interval(each_step[stat][i],
                                                           confidence=0.95)
            lower[stat].append(loweri)
            average[stat].append(averagei)
            upper[stat].append(upperi)
        #print (stat)
        #print (lower[stat])
        #print (upper[stat])


#Plotting:
        ax.plot(lower[stat], color=color[stat], linewidth=2)  #mean curve.
        ax.plot(average[stat], color=color[stat], linewidth=2)
        ax.plot(upper[stat], color=color[stat], linewidth=2)
        ax.fill_between(simulation_cycles,
                        lower[stat],
                        upper[stat],
                        color=color[stat],
                        alpha=.1,
                        label=stat)  #std curves.

    ax.set_xlabel("Days")
    ax.set_ylabel("% of Population")
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles, labels, loc='upper right')
    fig.show()
    fig.savefig(fname + ".png")

    if do_print:
        for stat, x in avg.items():
            print("using average of time series:")
            print("stats on {}:".format(stat))
            print("data: {}".format(x))
            print("min:")
            print(np.min(x))
            print("max:")
            print(np.max(x))
            print("std:")
            print(np.std(x))
            low, mean, high = confidence_interval(x, confidence=0.95)
            print("mean:")
            print(mean)
            print("median:")
            print(np.median(x))
            print("95% confidence interval for the mean:")
            print("({0},{1})".format(low, high))
        for stat, x in last.items():
            print("using last of time series:")
            print("stats on {}:".format(stat))
            print("data: {}".format(x))
            print("min:")
            print(np.min(x))
            print("max:")
            print(np.max(x))
            print("std:")
            print(np.std(x))
            low, mean, high = confidence_interval(x, confidence=0.95)
            print("mean:")
            print(mean)
            print("median:")
            print(np.median(x))
            print("95% confidence interval for the mean:")
            print("({0},{1})".format(low, high))
        for stat, x in peak.items():
            print("using peak of time series:")
            print("stats on {}:".format(stat))
            print("data: {}".format(x))
            print("min:")
            print(np.min(x))
            print("max:")
            print(np.max(x))
            print("std:")
            print(np.std(x))
            low, mean, high = confidence_interval(x, confidence=0.95)
            print("mean:")
            print(mean)
            print("median:")
            print(np.median(x))
            print("95% confidence interval for the mean:")
            print("({0},{1})".format(low, high))
    return avg.items, last.items, peak.items
    mask_efficacy=mask_efficacy,
    imune_rate=imune_rate,
    initial_infection_rate=initial_infection_rate,
    hospitalization_capacity=hospitalization_capacity,
    latency_period_mean=latency_period_mean,
    latency_period_stdev=latency_period_stdev,
    incubation_period_mean=incubation_period_mean,
    incubation_period_stdev=incubation_period_stdev,
    disease_period_mean=disease_period_mean,
    disease_period_stdev=disease_period_stdev,
    daily_interaction_count=daily_interaction_count,
    contagion_probability=contagion_probability,
    asymptomatic_isolation_rate=asymptomatic_isolation_rate,
    symptomatic_isolation_rate=symptomatic_isolation_rate)
set_parameters(scenario[sc]['parameters'])
scenario[sc]['model'] = CovidModel()
scenario[sc]['location'] = SimpleLocation(0, scenario[sc]['model'],
                                          population_size)

# ------------------------------------------------------------------------------

sc = 2  # Restrict the mobility only for infected people
scenario[sc] = {}
scenario[sc]['parameters'] = SimulationParameters(
    mask_user_rate=mask_user_rate,
    mask_efficacy=mask_efficacy,
    imune_rate=imune_rate,
    initial_infection_rate=initial_infection_rate,
    hospitalization_capacity=hospitalization_capacity,
    latency_period_mean=latency_period_mean,
    latency_period_stdev=latency_period_stdev,
Пример #8
0
        initial_infection_rate=initial_infection_rate,
        hospitalization_capacity=hospitalization_capacity,
        latency_period_mean=latency_period_mean,
        latency_period_stdev=latency_period_stdev,
        incubation_period_mean=incubation_period_mean,
        incubation_period_stdev=incubation_period_stdev,
        disease_period_mean=disease_period_mean,
        disease_period_stdev=disease_period_stdev,
        asymptomatic_isolation_rate=asymptomatic_isolation_rate,
        symptomatic_isolation_rate=symptomatic_isolation_rate,
        daily_interaction_count=daily_interaction_count,
        contagion_probability=contagion_probability))

sum = 0.0
for k in range(epochs):
    model = CovidModel()
    location = SimpleLocation(0, model, population_size)
    statistics = BasicStatistics(model)
    model.add_location(location)
    model.add_listener(statistics)
    for i in range(simulation_cycles):
        model.step()
    sum += statistics.death[-1]
baseline_deaths = sum / epochs

# Parameter variation

ME = float(sys.argv[1])
difference = [None] * len(ICR)
for i in range(len(ICR)):
    difference[i] = [None] * len(ICS)
Пример #9
0
def multiple_runs(params,
                  population_size,
                  simulation_cycles,
                  num_runs=5,
                  seeds=None,
                  debug=False,
                  desired_stats=[
                      "susceptible", "infected", "recovered",
                      "hospitalization", "icu", "death", "income"
                  ],
                  do_print=False):

    randomlist = random.sample(range(10000),
                               num_runs) if seeds is None else seeds
    if (do_print):
        print("Save these seeds if you want to rerun a scenario")
        print(randomlist)

    all_runs = {}
    avg = {}
    last = {}
    peak = {}
    for stat in desired_stats:
        all_runs[stat] = {}
        avg[stat] = []
        last[stat] = []
        peak[stat] = []
    for s in randomlist:
        set_parameters(params)
        model = CovidModel(debug=debug)
        if debug:
            model.debug_each_n_cycles = 20
        np.random.seed(s + 1)
        random.seed(s + 2)
        setup_city_layout(model, population_size)
        if (do_print):
            print("run with seed {0}:".format(str(s)))
        model.reset_randomizer(s)
        statistics = BasicStatistics(model)
        model.add_listener(statistics)
        for i in range(simulation_cycles):
            model.step()
        for stat in desired_stats:
            all_runs[stat][s] = getattr(statistics, stat)
            avg[stat].append(np.mean(all_runs[stat][s]))
            last[stat].append(all_runs[stat][s][-1])
            peak[stat].append(max(all_runs[stat][s]))
    if (do_print):
        for stat, x in avg.items():
            print("using average of time series:")
            print("stats on {}:".format(stat))
            print("data: {}".format(x))
            print("min:")
            print(np.min(x))
            print("max:")
            print(np.max(x))
            print("std:")
            print(np.std(x))
            print("mean:")
            print(np.mean(x))
            print("median:")
            print(np.median(x))
            print("95% confidence interval for the mean:")
            low, high = confidence_interval(x, confidence=0.95)
            print("({0},{1})".format(low, high))
        for stat, x in last.items():
            print("using last of time series:")
            print("stats on {}:".format(stat))
            print("data: {}".format(x))
            print("min:")
            print(np.min(x))
            print("max:")
            print(np.max(x))
            print("std:")
            print(np.std(x))
            print("mean:")
            print(np.mean(x))
            print("median:")
            print(np.median(x))
            print("95% confidence interval for the mean:")
            low, high = confidence_interval(x, confidence=0.95)
            print("({0},{1})".format(low, high))
        for stat, x in peak.items():
            print("using peak of time series:")
            print("stats on {}:".format(stat))
            print("data: {}".format(x))
            print("min:")
            print(np.min(x))
            print("max:")
            print(np.max(x))
            print("std:")
            print(np.std(x))
            print("mean:")
            print(np.mean(x))
            print("median:")
            print(np.median(x))
            print("95% confidence interval for the mean:")
            low, high = confidence_interval(x, confidence=0.95)
            print("({0},{1})".format(low, high))
    return (avg.items, last.items, peak.items)
Пример #10
0
multiple_runs = 5

single_var = ('risk_tolerance_mean', [0.1, 0.5, 0.9])

infections_in_restaurants = {}

var_name, var_values = single_var
for value in var_values:

    infections_in_restaurants[value] = []

    for k in range(multiple_runs):
        params = copy.deepcopy(basic_parameters)
        params.params[var_name] = value
        set_parameters(params)
        model = CovidModel()
        setup_city_layout(model, population_size)
        model.add_listener(Propaganda(model, 30))
        model.add_listener(
            RemovePolicy(model, SocialPolicy.LOCKDOWN_ELEMENTARY_SCHOOL, 30))
        model.add_listener(
            RemovePolicy(model, SocialPolicy.LOCKDOWN_MIDDLE_SCHOOL, 60))
        model.add_listener(
            RemovePolicy(model, SocialPolicy.LOCKDOWN_HIGH_SCHOOL, 90))
        statistics = BasicStatistics(model)
        model.add_listener(statistics)
        debug = DebugUtils(model)
        logger().model = model
        for i in range(simulation_cycles):
            model.step()
        statistics.export_chart(f'scenario_{var_name}_{value}_{k}.png')