def test_multirun(do_plot=do_plot):  # If being run via pytest, turn off
    sc.heading('Multirun test')

    n_days = 60

    # Method 1 -- Note: this runs 3 simulations, not 3x3!
    iterpars = {
        'beta': [0.015, 0.025, 0.035],
        'iso_factor': [0.1, 0.5, 0.9],
    }
    sim = cv.Sim(n_days=n_days, pop_size=pop_size)
    sims = cv.multi_run(sim=sim, iterpars=iterpars, verbose=verbose)

    # Method 2 -- run a list of sims
    simlist = []
    for i in range(len(iterpars['beta'])):
        sim = cv.Sim(n_days=n_days,
                     pop_size=pop_size,
                     beta=iterpars['beta'][i],
                     iso_factor=iterpars['iso_factor'][i])
        simlist.append(sim)
    sims2 = cv.multi_run(sim=simlist, verbose=verbose)

    # Method 3 -- shortcut for parallelization
    s1 = cv.Sim(n_days=n_days, pop_size=pop_size)
    s2 = s1.copy()
    s1, s2 = cv.parallel(s1, s2).sims
    assert np.allclose(s1.summary[:],
                       s2.summary[:],
                       rtol=0,
                       atol=0,
                       equal_nan=True)

    # Run in serial for debugging
    cv.multi_run(sim=cv.Sim(n_days=n_days, pop_size=pop_size),
                 n_runs=2,
                 parallel=False)

    if do_plot:
        for sim in sims + sims2:
            sim.plot()

    return sims
Пример #2
0
''' Demonstrate the vaccine intervention with subtargeting '''

import covasim as cv
import numpy as np

# Define the vaccine subtargeting
def vaccinate_by_age(sim):
    young  = cv.true(sim.people.age < 50) # cv.true() returns indices of people matching this condition, i.e. people under 50
    middle = cv.true((sim.people.age >= 50) * (sim.people.age < 75)) # Multiplication means "and" here
    old    = cv.true(sim.people.age > 75)
    inds = sim.people.uid # Everyone in the population -- equivalent to np.arange(len(sim.people))
    vals = np.ones(len(sim.people)) # Create the array
    vals[young] = 0.1 # 10% probability for people <50
    vals[middle] = 0.5 # 50% probability for people 50-75
    vals[old] = 0.9 # 90% probbaility for people >75
    output = dict(inds=inds, vals=vals)
    return output

# Define the vaccine
vaccine = cv.simple_vaccine(days=20, rel_sus=0.8, rel_symp=0.06, subtarget=vaccinate_by_age)

if __name__ == '__main__':

    # Create, run, and plot the simulations
    sim1 = cv.Sim(label='Baseline')
    sim2 = cv.Sim(interventions=vaccine, label='With age-targeted vaccine')
    msim = cv.parallel([sim1, sim2])
    msim.plot()
'''
Illustrate sinusoidally varying transmission via change beta
'''

import numpy as np
import sciris as sc
import covasim as cv

pars = sc.objdict(
    beta=0.008,
    n_agents=50e3,
    n_days=180,
    verbose=0,
)

beta_days = np.arange(pars.n_days)
beta_vals = np.cos(2 * np.pi * beta_days / 90)**2 + 0.5
beta = cv.change_beta(beta_days, beta_vals, do_plot=False)

s1 = cv.Sim(pars, label='Normal')
s2 = cv.Sim(pars, interventions=beta, label='Waves')

if __name__ == '__main__':
    msim = cv.parallel(s1, s2)
    msim.plot(['r_eff'])
Пример #4
0
        pl.xlabel('Day')
        pl.ylabel('Number infected')
        pl.title('Number of elderly people with active COVID')
        return


if __name__ == '__main__':

    # Define and run the baseline simulation
    pars = dict(
        pop_size=50e3,
        pop_infected=100,
        n_days=90,
        verbose=0,
    )
    orig_sim = cv.Sim(pars, label='Default')

    # Define the intervention and the scenario sim
    protect = protect_elderly(start_day='2020-04-01',
                              end_day='2020-05-01',
                              rel_sus=0.1)  # Create intervention
    sim = cv.Sim(pars, interventions=protect, label='Protect the elderly')

    # Run and plot
    msim = cv.parallel([orig_sim, sim])
    msim.plot()

    # Plot intervention
    protect = msim.sims[1].get_intervention(
        protect_elderly)  # Find intervention by type
    protect.plot()
'''
Demonstrate change beta and clip edges interventions
'''

import covasim as cv

# Define baseline parameters and sim
pars = dict(
    start_day = '2020-03-01',
    end_day   = '2020-06-01',
    pop_type  = 'hybrid',
)
orig_sim = cv.Sim(pars, label='Baseline')

# Define sim with change_beta
cb = cv.change_beta(days=['2020-04-15', '2020-05-01', '2020-05-15'], changes=[0.2, 1.5, 0.7])
sim = cv.Sim(pars, interventions=cb, label='With beta changes')


if __name__ == '__main__':

    # Run and plot
    msim = cv.parallel(orig_sim, sim)
    msim.plot()
    def update(self, people):
        ''' Update the contacts '''
        pop_size = len(people)
        n_new = self.contact_data[people.t] # Pull out today's contacts
        self['p1']   = np.array(cv.choose_r(max_n=pop_size, n=n_new), dtype=cv.default_int) # Choose with replacement
        self['p2']   = np.array(cv.choose_r(max_n=pop_size, n=n_new), dtype=cv.default_int) # Paired contact
        self['beta'] = np.ones(n_new, dtype=cv.default_float) # Per-contact transmission (just 1.0)
        return


# Define some simple parameters
pars = sc.objdict(
    pop_size = 1000,
    n_days = 90,
)

# Set up and run the simulation
base_sim = cv.Sim(pars, label='Default simulation')
sim = cv.Sim(pars, dynam_layer=True, label='Dynamic layers')
sim.initialize()

# Update to custom layer
for key in sim.layer_keys():
    contact_data = np.random.randint(pars.pop_size*10, pars.pop_size*20, size=pars.n_days+1) # Generate a number of contacts for today
    sim.people.contacts[key] = CustomLayer(sim.people.contacts[key], contact_data=contact_data)


# Run and plot
if __name__ == '__main__':
    msim = cv.parallel(base_sim, sim)
    msim.plot()
Пример #7
0
''' Illustrate testing options '''

import covasim as cv

# Define the testing interventions
tn_data = cv.test_num('data')
tn_fixed = cv.test_num(daily_tests=500, start_day='2020-03-01')
tp = cv.test_prob(symp_prob=0.2, asymp_prob=0.001, start_day='2020-03-01')

# Define the default parameters
pars = dict(
    pop_size=50e3,
    pop_infected=100,
    start_day='2020-02-01',
    end_day='2020-03-30',
)

# Define the simulations
sim1 = cv.Sim(pars,
              datafile='example_data.csv',
              interventions=tn_data,
              label='Number of tests from data')
sim2 = cv.Sim(pars,
              interventions=tn_fixed,
              label='Constant daily number of tests')
sim3 = cv.Sim(pars, interventions=tp, label='Probability-based testing')

# Run and plot results
msim = cv.parallel(sim1, sim2, sim3)
msim.plot(
    to_plot=['new_infections', 'new_tests', 'new_diagnoses', 'cum_diagnoses'])
Пример #8
0
'''
Illustrate waning immunity
'''

import numpy as np
import covasim as cv
import pylab as pl

# Create sims with and without waning immunity
sim_nowaning = cv.Sim(n_days=120, use_waning=False, label='No waning immunity')
sim_waning = cv.Sim(n_days=120, label='Waning immunity')

# Now create an alternative sim with faster decay for neutralizing antibodies
sim_fasterwaning = cv.Sim(label='Faster waning immunity',
                          n_days=120,
                          nab_decay=dict(form='nab_growth_decay',
                                         growth_time=21,
                                         decay_rate1=0.07,
                                         decay_time1=47,
                                         decay_rate2=0.02,
                                         decay_time2=106))

if __name__ == '__main__':
    msim = cv.parallel(sim_nowaning, sim_waning, sim_fasterwaning)
    msim.plot()