Example #1
0
def test_interventions():
    sc.heading('Testing interventions')

    # Create sim
    sim = cv.Sim(pop_size=100, n_days=60, datafile=csv_file, verbose=verbose)

    # Intervention conversion
    ce = cv.InterventionDict(**{
        'which': 'clip_edges',
        'pars': {
            'days': [10, 30],
            'changes': [0.5, 1.0]
        }
    })
    print(ce)
    with pytest.raises(sc.KeyNotFoundError):
        cv.InterventionDict(**{
            'which': 'invalid',
            'pars': {
                'days': 10,
                'changes': 0.5
            }
        })

    # Test numbers and contact tracing
    tn1 = cv.test_num(10, start_day=3, end_day=20)
    tn2 = cv.test_num(daily_tests=sim.data['new_tests'])
    ct = cv.contact_tracing()

    # Create and run
    sim['interventions'] = [ce, tn1, tn2, ct]
    sim.run()

    return
def test_data_interventions():
    sc.heading('Testing data interventions and other special cases')

    # Create sim
    sim = cv.Sim(pop_size=100, n_days=60, datafile=csv_file, verbose=verbose)

    # Intervention conversion
    ce = cv.InterventionDict(**{
        'which': 'clip_edges',
        'pars': {
            'days': [10, 30],
            'changes': [0.5, 1.0]
        }
    })
    print(ce)
    with pytest.raises(sc.KeyNotFoundError):
        cv.InterventionDict(**{
            'which': 'invalid',
            'pars': {
                'days': 10,
                'changes': 0.5
            }
        })

    # Test numbers and contact tracing
    swab_dict = {'dist': 'uniform', 'par1': 1, 'par2': 3}
    tp1 = cv.test_prob(0.05,
                       start_day=5,
                       end_day=15,
                       ili_prev=0.1,
                       swab_delay=swab_dict,
                       subtarget={
                           'inds': lambda sim: cv.true(sim.people.age > 50),
                           'vals': 0.3
                       })
    tn1 = cv.test_num(10,
                      start_day=3,
                      end_day=20,
                      ili_prev=0.1,
                      swab_delay=swab_dict)
    tn2 = cv.test_num(daily_tests='data',
                      quar_policy=[0, 5],
                      subtarget={
                          'inds': lambda sim: cv.true(sim.people.age > 50),
                          'vals': 1.2
                      })
    ct = cv.contact_tracing(presumptive=True, capacity=5)

    # Create and run
    sim['interventions'] = [ce, tp1, tn1, tn2, ct]
    sim.run()

    return
def test_turnaround(do_plot=False, do_show=True, do_save=False, fig_path=None):
    sc.heading('Test impact of reducing delay time for getting test results')

    sc.heading('Setting up...')

    sc.tic()

    n_runs = 3
    verbose = 1
    base_pars = {
        'pop_size': 1000,
        'pop_type': 'hybrid',
    }

    base_sim = cv.Sim(base_pars)  # create sim object
    n_people = base_sim['pop_size']
    npts = base_sim.npts

    # Define overall testing assumptions
    testing_prop = 0.1  # Assumes we could test 10% of the population daily (!!)
    daily_tests = [testing_prop * n_people] * npts  # Number of daily tests

    # Define the scenarios
    scenarios = {
        f'{d}dayturnaround': {
            'name': f'Symptomatic testing with {d} days to get results',
            'pars': {
                'interventions': cv.test_num(daily_tests=daily_tests,
                                             test_delay=d)
            }
        }
        for d in range(1, 3 + 1, 2)
    }

    metapars = {'n_runs': n_runs}

    scens = cv.Scenarios(sim=base_sim, metapars=metapars, scenarios=scenarios)
    scens.run(verbose=verbose, debug=debug)

    to_plot = ['cum_infections', 'n_infectious', 'new_tests', 'new_diagnoses']
    fig_args = dict(figsize=(20, 24))

    if do_plot:
        scens.plot(do_save=do_save,
                   do_show=do_show,
                   fig_path=fig_path,
                   interval=7,
                   fig_args=fig_args,
                   to_plot=to_plot)

    return scens
Example #4
0
    def create_sim(self, x, verbose=0):
        ''' Create the simulation from the parameters '''

        if isinstance(x, dict):
            pars, pkeys = self.get_bounds()  # Get parameter guesses
            x = [x[k] for k in pkeys]

        self.calibration_parameters = x

        pop_infected = math.exp(x[0])
        beta = math.exp(x[1])

        # NB: optimization over only two parameters
        # 		beta_day	 = x[2]
        # 		beta_change  = x[3]
        # 		symp_test	= x[4]
        beta_day = 50
        beta_change = 0.5
        symp_test = 30

        # Create parameters
        pars = dict(
            pop_size=self.pop_size,
            pop_scale=self.total_pop / self.pop_size,
            pop_infected=pop_infected,
            beta=beta,
            start_day=self.start_day,
            end_day=self.end_day,
            rescale=True,
            verbose=verbose,
        )

        # Create the sim
        sim = cv.Sim(pars, datafile=self.datafile)

        # Add interventions
        interventions = [
            cv.change_beta(days=beta_day, changes=beta_change),
            cv.test_num(daily_tests=sim.data['new_tests'].dropna(),
                        symp_test=symp_test),
        ]

        # Update
        sim.update_pars(interventions=interventions)

        self.sim = sim

        return sim
Example #5
0
def test_vl_testing(fig_path=None):
    sc.heading('Test viral loads with different types of test')
    sc.heading('Setting up...')
    sc.tic()

    if fig_path is None:
        fig_path = f'results/test_with_vl.png'

    pars = dict(
        pop_size=50e3,
        pop_infected=100,
        start_day='2020-02-01',
        end_day='2020-03-30',
    )
    sim = cv.Sim(pars)
    sim.initialize()

    # Create interventions
    # Set parameters
    n_people = sim['pop_size']
    n_tests = 0.02 * n_people
    delay = 1
    start_day = 20

    sims = []
    for pcr_prop in np.linspace(0, 1, 5):
        tn = cv.test_num(daily_tests=n_tests,
                         lod={
                             3.0: pcr_prop,
                             5.0: 1 - pcr_prop
                         },
                         symp_test=5.0,
                         start_day=start_day,
                         test_delay=delay)
        sim = cv.Sim(interventions=tn, label=f'{pcr_prop*100:.0f}% PCR')
        sims.append(sim)

    # Run and plot results
    to_plot = [
        'new_infections', 'cum_infections', 'new_inf_neg', 'cum_inf_neg',
        'new_noninf_pos', 'cum_noninf_pos', 'new_diagnoses', 'cum_diagnoses'
    ]

    msim = cv.MultiSim(sims)
    msim.run(keep_people=True)
    msim.plot(to_plot=to_plot, do_save=True, fig_path=fig_path, do_show=False)

    return msim
Example #6
0
    def create_sim(self, x, verbose=0):
        ''' Create the simulation from the parameters '''

        if isinstance(x, dict):
            pars, pkeys = self.get_bounds()  # Get parameter guesses
            x = [x[k] for k in pkeys]

        # Define and load the data
        self.calibration_parameters = x

        # Convert parameters
        pop_infected = x[0]
        beta = x[1]
        beta_day = x[2]
        beta_change = x[3]
        symp_test = x[4]

        # Create parameters
        pars = dict(
            pop_size=self.pop_size,
            pop_scale=self.total_pop / self.pop_size,
            pop_infected=pop_infected,
            beta=beta,
            start_day=self.start_day,
            end_day=self.end_day,
            rescale=True,
            verbose=verbose,
        )

        # Create the sim
        sim = cv.Sim(pars, datafile=self.datafile)

        # Add interventions
        interventions = [
            cv.change_beta(days=beta_day, changes=beta_change),
            cv.test_num(daily_tests=sim.data['new_tests'].dropna(),
                        symp_test=symp_test),
        ]

        # Update
        sim.update_pars(interventions=interventions)

        self.sim = sim

        return sim
def run_sim(pars, label=None, return_sim=False):
    ''' Create and run a simulation '''
    print(f'Running sim for beta={pars["beta"]}, rel_death_prob={pars["rel_death_prob"]}')
    pars = dict(
        start_day      = '2020-02-01',
        end_day        = '2020-04-11',
        beta           = pars["beta"],
        rel_death_prob = pars["rel_death_prob"],
        interventions  = cv.test_num(daily_tests='data'),
        verbose        = 0,
    )
    sim = cv.Sim(pars=pars, datafile='/home/cliffk/idm/covasim/docs/tutorials/example_data.csv', label=label)
    sim.run()
    fit = sim.compute_fit()
    if return_sim:
        return sim
    else:
        return fit.mismatch
def create_sim(x):
    ''' Create the simulation from the parameters '''

    # Convert parameters
    pop_infected = x[0]
    beta = x[1]
    symp_test = x[2]
    beta_change1 = x[3]
    beta_change2 = x[4]
    beta_days = ['2020-03-15', '2020-04-01']  # Days social distancing changed

    # Define the inputs
    datafile = 'NY.csv'
    pop_size = 100e3
    pars = dict(
        pop_size=pop_size,
        pop_scale=19.45e6 / pop_size,
        pop_infected=pop_infected,
        pop_type='hybrid',
        beta=beta,
        start_day='2020-02-01',
        end_day='2020-06-14',
        rescale=True,
    )

    # Create the simulation
    sim = cv.Sim(pars, datafile=datafile)

    # Create the interventions
    interventions = [
        cv.change_beta(days=beta_days, changes=[beta_change1, beta_change2]),
        cv.test_num(daily_tests=sim.data['new_tests'].dropna(),
                    symp_test=symp_test),
    ]

    # Run the simulation
    sim['interventions'] = interventions

    return sim
def create_sim(x, vb=vb):
    ''' Create the simulation from the parameters '''

    # Convert parameters
    pop_infected = x[0]
    beta = x[1]
    beta_day = x[2]
    beta_change = x[3]
    symp_test = x[4]

    # Create parameters
    pop_size = 200e3
    pars = dict(
        pop_size=pop_size,
        pop_scale=data.popsize / pop_size,
        pop_infected=pop_infected,
        beta=beta,
        start_day='2020-03-01',
        end_day='2021-05-30',  # Run for at least a year
        rescale=True,
        verbose=vb.verbose,
    )

    #Create the sim
    sim = cv.Sim(pars, datafile=data.epi)

    # Add interventions
    interventions = [
        cv.change_beta(days=beta_day, changes=beta_change),
        cv.test_num(daily_tests=sim.data['new_tests'].dropna(),
                    symp_test=symp_test),
    ]

    # Update
    sim.update_pars(interventions=interventions)

    return sim
b_ch.c = [0.60, 0.40, 0.25]

# Define testing interventions
daily_tests = sim.data['new_tests']
test_kwargs = {
    'quar_test': 0,
    'sensitivity': 1.0,
    'test_delay': 0,
    'loss_prob': 0
}
interventions = [
    cv.test_num(daily_tests=daily_tests,
                symp_test=70,
                start_day='2020-01-27',
                end_day=None,
                swab_delay_dist={
                    'dist': 'lognormal',
                    'par1': 10,
                    'par2': 170
                },
                **test_kwargs),
]

for lkey, ch in b_ch.items():
    interventions.append(
        cv.change_beta(days=b_days, changes=b_ch[lkey], layers=lkey))

sim.update_pars(interventions=interventions)

sim.initialize()
sim = sim.run(until='2020-04-30')
Example #11
0
)

p3 = dict(
    pop_size = 20000,
    pop_infected = 50,
    pop_scale = 10,
    rescale = False,
)


tnp = dict(start_day=0, daily_tests=1000)
tpp = dict(symp_prob=0.1, asymp_prob=0.01)

sims = []
for st in [1000]:
    tn = cv.test_num(**tnp, symp_test=st)
    tp = cv.test_prob(**tpp)
    ti = tn # Switch testing interventions here
    s1 = cv.Sim(pars, **p1, interventions=sc.dcp(ti), label=f'full, symp_test={st}')
    s2 = cv.Sim(pars, **p2, interventions=sc.dcp(ti), label=f'dynamic, symp_test={st}')
    s3 = cv.Sim(pars, **p3, interventions=sc.dcp(ti), label=f'static, symp_test={st}')
    sims.extend([s1, s2, s3])

msim = cv.MultiSim(sims)
sc.tic()
msim.run()
sc.toc()

for sim in msim.sims:
    sim.results['n_quarantined'][:] = sim.rescale_vec
    sim.results['n_quarantined'].name = 'Rescale vec'
Example #12
0
def make_sim(seed,
             beta,
             change=0.42,
             policy='remain',
             threshold=5,
             symp_prob=0.01,
             end_day=None):

    start_day = '2020-06-15'
    if end_day is None: end_day = '2021-04-30'
    total_pop = 11.9e6  # Population of central Vietnam
    n_agents = 100e3
    pop_scale = total_pop / n_agents

    # Calibration parameters
    pars = {
        'pop_size': n_agents,
        'pop_infected': 0,
        'pop_scale': pop_scale,
        'rand_seed': seed,
        'beta': beta,
        'start_day': start_day,
        'end_day': end_day,
        'verbose': 0,
        'rescale': True,
        'iso_factor':
        dict(h=0.5, s=0.01, w=0.01,
             c=0.1),  # Multiply beta by this factor for people in isolation
        'quar_factor':
        dict(h=1.0, s=0.2, w=0.2,
             c=0.2),  # Multiply beta by this factor for people in quarantine
        'location': 'vietnam',
        'pop_type': 'hybrid',
        'age_imports': [50, 80],
        'rel_crit_prob':
        1.75,  # Calibration parameter due to hospital outbreak
        'rel_death_prob': 2.,  # Calibration parameter due to hospital outbreak
    }

    # Make a sim without parameters, just to load in the data to use in the testing intervention and to get the sim days
    sim = cv.Sim(start_day=start_day, datafile="vietnam_data.csv")

    # Set up import assumptions
    pars['dur_imports'] = sc.dcp(sim.pars['dur'])
    pars['dur_imports']['exp2inf'] = {
        'dist': 'lognormal_int',
        'par1': 0.0,
        'par2': 0.0
    }
    pars['dur_imports']['inf2sym'] = {
        'dist': 'lognormal_int',
        'par1': 0.0,
        'par2': 0.0
    }
    pars['dur_imports']['sym2sev'] = {
        'dist': 'lognormal_int',
        'par1': 0.0,
        'par2': 2.0
    }
    pars['dur_imports']['sev2crit'] = {
        'dist': 'lognormal_int',
        'par1': 1.0,
        'par2': 3.0
    }
    pars['dur_imports']['crit2die'] = {
        'dist': 'lognormal_int',
        'par1': 3.0,
        'par2': 3.0
    }

    # Define import array
    import_end = sim.day('2020-07-15')
    border_start = sim.day('2020-11-30')  # Open borders for one month
    border_end = sim.day('2020-12-31')  # Then close them again
    final_day_ind = sim.day('2021-04-30')
    imports = np.concatenate((
        np.array([
            1, 0, 0, 0, 2, 2, 8, 4, 1, 1, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0,
            0, 1, 0, 0, 2, 3, 1, 1, 3, 0, 3, 0, 1, 6, 1, 5, 0, 0
        ]),  # Generated from cv.n_neg_binomial(1, 0.25) but then hard-copied to remove variation when calibrating
        pl.zeros(
            border_start - import_end
        ),  # No imports from the end of the 1st importation window to the border reopening
        cv.n_neg_binomial(
            1, 0.25, border_end - border_start
        ),  # Negative-binomial distributed importations each day
        pl.zeros(final_day_ind - border_end)))
    pars['n_imports'] = imports

    # Add testing and tracing interventions
    trace_probs = {'h': 1, 's': 0.95, 'w': 0.8, 'c': 0.05}
    trace_time = {'h': 0, 's': 2, 'w': 2, 'c': 5}
    pars['interventions'] = [
        # Testing and tracing
        cv.test_num(daily_tests=sim.data['new_tests'].rolling(3).mean(),
                    start_day=2,
                    end_day=sim.day('2020-08-22'),
                    symp_test=80,
                    quar_test=80,
                    do_plot=False),
        cv.test_prob(start_day=sim.day('2020-08-23'),
                     end_day=sim.day('2020-11-30'),
                     symp_prob=0.05,
                     asymp_quar_prob=0.5,
                     do_plot=False),
        cv.test_prob(start_day=sim.day('2020-12-01'),
                     symp_prob=symp_prob,
                     asymp_quar_prob=0.5,
                     trigger=cv.trigger('date_diagnosed', 5),
                     triggered_vals={'symp_prob': 0.2},
                     do_plot=False),
        cv.contact_tracing(start_day=0,
                           trace_probs=trace_probs,
                           trace_time=trace_time,
                           do_plot=False),

        # Change death and critical probabilities
        cv.dynamic_pars(
            {
                'rel_death_prob': {
                    'days': sim.day('2020-08-31'),
                    'vals': 1.0
                },
                'rel_crit_prob': {
                    'days': sim.day('2020-08-31'),
                    'vals': 1.0
                }
            },
            do_plot=False
        ),  # Assume these were elevated due to the hospital outbreak but then would return to normal

        # Increase precautions (especially mask usage) following the outbreak, which are then abandoned after 40 weeks of low case counts
        cv.change_beta(days=0,
                       changes=change,
                       trigger=cv.trigger('date_diagnosed', 5)),

        # Close schools and workplaces
        cv.clip_edges(days=['2020-07-28', '2020-09-14'],
                      changes=[0.1, 1.],
                      layers=['s'],
                      do_plot=True),
        cv.clip_edges(days=['2020-07-28', '2020-09-05'],
                      changes=[0.1, 1.],
                      layers=['w'],
                      do_plot=False),

        # Dynamically close them again if cases go over the threshold
        cv.clip_edges(days=[170],
                      changes=[0.1],
                      layers=['s'],
                      trigger=cv.trigger('date_diagnosed', threshold)),
        cv.clip_edges(days=[170],
                      changes=[0.1],
                      layers=['w'],
                      trigger=cv.trigger('date_diagnosed', threshold)),
    ]

    if policy != 'remain':
        pars['interventions'] += [
            cv.change_beta(days=160,
                           changes=1.0,
                           trigger=cv.trigger('date_diagnosed',
                                              2,
                                              direction='below',
                                              smoothing=28))
        ]
    if policy == 'dynamic':
        pars['interventions'] += [
            cv.change_beta(days=170,
                           changes=change,
                           trigger=cv.trigger('date_diagnosed', threshold)),
        ]

    sim = cv.Sim(pars=pars, datafile="vietnam_data.csv")
    sim.initialize()

    return sim
def create_sim(pars=None,
               label=None,
               use_safegraph=True,
               show_intervs=False,
               people=None,
               school_reopening_pars=None,
               teacher_test_scen=None):
    ''' Create a single simulation for further use '''

    p = sc.objdict(
        sc.mergedicts(
            define_pars(which='best', kind='both',
                        use_safegraph=use_safegraph), pars))
    if 'rand_seed' not in p:
        seed = 1
        print(f'Note, could not find random seed in {pars}! Setting to {seed}')
        p['rand_seed'] = seed  # Ensure this exists
    if 'end_day' not in p:
        end_day = '2020-05-30'
        p['end_day'] = end_day

    # Basic parameters and sim creation
    pars = {
        'pop_size': 225e3,
        'pop_scale': 10,
        'pop_type': 'synthpops',
        'pop_infected': 400,
        'beta': p.beta,
        'start_day': '2020-01-27',
        'end_day': p['end_day'],
        'rescale': True,
        'rescale_factor': 1.1,
        'verbose': 0.1,
        'rand_seed': p.rand_seed,
        # 'analyzers'     : cv.age_histogram(datafile=age_data_file),
        'beta_layer': dict(h=p.bl_h, s=p.bl_s, w=p.bl_w, c=p.bl_c, l=p.bl_l),
    }
    pars.update({'n_days': cv.daydiff(pars['start_day'], pars['end_day'])})

    # If supplied, use an existing people object
    if people:
        popfile = people
    else:
        # Generate the population filename
        n_popfiles = 5
        popfile = popfile_stem + str(pars['rand_seed'] % n_popfiles) + '.ppl'
        popfile_change = popfile_stem_change + str(
            pars['rand_seed'] % n_popfiles) + '.ppl'

        # Check that the population file exists
        if not os.path.exists(popfile):
            errormsg = f'WARNING: could not find population file {popfile}! Please regenerate first'
            raise FileNotFoundError(errormsg)

    # Create and initialize the sim
    sim = cv.Sim(pars,
                 label=label,
                 popfile=popfile,
                 load_pop=True,
                 datafile=epi_data_file
                 )  # Create this here so can be used for test numbers etc.
    # Define testing interventions
    test_kwargs = dict(daily_tests=sim.data['new_tests'],
                       quar_test=1.0,
                       test_delay=2)
    tn1 = cv.test_num(symp_test=p.tn1,
                      start_day='2020-01-27',
                      end_day='2020-03-23',
                      **test_kwargs,
                      label='tn1')
    tn2 = cv.test_num(symp_test=p.tn2,
                      start_day='2020-03-24',
                      end_day='2020-04-14',
                      **test_kwargs,
                      label='tn2')
    tn3 = cv.test_num(symp_test=p.tn3,
                      start_day='2020-04-15',
                      end_day=None,
                      **test_kwargs,
                      label='tn3')
    interventions = [tn1, tn2, tn3]

    ttq_scen = school_reopening_pars['ttq_scen']

    if ttq_scen == 'lower':
        tp = sc.objdict(
            symp_prob=0.08,
            asymp_prob=0.001,
            symp_quar_prob=0.8,
            asymp_quar_prob=0.1,
            test_delay=2.0,
        )
        ct = sc.objdict(
            trace_probs=0.01,
            trace_time=3.0,
        )
    elif ttq_scen == 'medium':
        tp = sc.objdict(
            symp_prob=0.12,
            asymp_prob=0.0015,
            symp_quar_prob=0.8,
            asymp_quar_prob=0.1,
            test_delay=2.0,
        )
        ct = sc.objdict(
            trace_probs=0.25,
            trace_time=3.0,
        )
    elif ttq_scen == 'upper':
        tp = sc.objdict(
            symp_prob=0.24,
            asymp_prob=0.003,
            symp_quar_prob=0.8,
            asymp_quar_prob=0.1,
            test_delay=2.0,
        )
        ct = sc.objdict(
            trace_probs=0.5,
            trace_time=3.0,
        )

    if ttq_scen is not None:
        interventions += [
            cv.test_prob(start_day='2020-06-10', **tp),
            cv.contact_tracing(start_day='2020-06-10', **ct)
        ]

    # Define beta interventions (for school reopening)
    b_ch = sc.objdict()
    b_days = [
        '2020-03-04', '2020-03-12', '2020-03-23', '2020-04-25', '2020-08-30'
    ]
    b_ch.w = [1.00, p.bc_wc1, p.bc_wc2, p.bc_wc3, p.bc_wc3]
    b_ch.c = [1.00, p.bc_wc1, p.bc_wc2, p.bc_wc3, p.bc_wc3]
    NPI_schools = school_reopening_pars['NPI_schools']
    if NPI_schools is None:
        b_ch.s = [1.00, 1.00, 1.00, 1.00, 1.00]
    else:
        b_ch.s = [1.00, 1.00, 1.00, 1.00, NPI_schools]

    # LTCF intervention
    b_days_l = np.arange(sim.day(b_days[0]), sim.day(b_days[2]) + 1)
    b_ch_l = np.linspace(1.0, p.bc_lf, len(b_days_l))
    interventions += [
        cv.change_beta(days=b_days_l,
                       changes=b_ch_l,
                       layers='l',
                       label=f'beta_l')
    ]

    for lkey, ch in b_ch.items():
        interventions += [
            cv.change_beta(days=b_days,
                           changes=b_ch[lkey],
                           layers=lkey,
                           label=f'beta_{lkey}')
        ]

    # Define school closure interventions
    network_change = school_reopening_pars['network_change']
    if network_change:
        popfile_new = popfile_change
    else:
        popfile_new = None

    school_start_day = school_reopening_pars['school_start_day']
    intervention_start_day = school_reopening_pars['intervention_start_day']
    num_pos = None
    test_prob = teacher_test_scen['test_prob']
    trace_prob = teacher_test_scen['trace_prob']
    mobility_file = school_reopening_pars['mobility_file']

    interventions += [
        cv.close_schools(day_schools_closed='2020-03-12',
                         start_day=school_start_day,
                         pop_file=popfile_new,
                         label='close_schools')
    ]

    test_freq = teacher_test_scen['test_freq']

    interventions += [
        cv.reopen_schools(start_day=intervention_start_day,
                          num_pos=num_pos,
                          test=test_prob,
                          trace=trace_prob,
                          ili_prev=0.002,
                          test_freq=test_freq)
    ]

    # SafeGraph intervention
    interventions += make_safegraph(sim, mobility_file)
    sim['interventions'] = interventions

    analyzers = [cv.age_histogram(datafile=age_data_file)]

    sim['analyzers'] += analyzers

    # Don't show interventions in plots, there are too many
    if show_intervs == False:
        for interv in sim['interventions']:
            interv.do_plot = False

    # These are copied from parameters.py -- needed to get younger and 60-65 groups right
    sim['prognoses']['age_cutoffs'] = np.array(
        [0, 15, 20, 30, 40, 50, 65, 70, 80, 90])  # Age cutoffs (upper limits)

    return sim
Example #14
0
# Define the scenarios
scenarios = {
    'baseline': {
        'name': 'Baseline',
        'pars': {}
    },
    'protectelderly': {
        'name': 'Protect the elderly',
        'pars': {
            'prognoses':
            new_prognoses,
            'interventions':
            cv.test_num(start_day=start_day,
                        daily_tests=[0.005 * n_people] * n_days,
                        subtarget={
                            'inds': sim.people.age > 50,
                            'val': 2.0
                        }),
        }
    },
    'testelderly': {
        'name': 'Test the elderly',
        'pars': {
            'interventions':
            cv.test_prob(start_day=start_day,
                         symp_prob=0.1,
                         asymp_prob=0.005,
                         subtarget={
                             'inds': sim.people.age > 50,
                             'val': 2.0
                         }),
Example #15
0
def test_all_interventions():
    ''' Test all interventions supported by Covasim '''

    pars = sc.objdict(
        pop_size=1e3,
        pop_infected=10,
        pop_type='hybrid',
        n_days=90,
    )

    #%% Define the interventions

    # 1. Dynamic pars
    i1a = cv.test_prob(start_day=5, symp_prob=0.3)
    i1b = cv.dynamic_pars({
        'beta': {
            'days': [40, 50],
            'vals': [0.005, 0.015]
        },
        'rel_death_prob': {
            'days': 30,
            'vals': 2.0
        }
    })  # Starting day 30, make diagnosed people stop transmitting

    # 2. Sequence
    i2 = cv.sequence(days=[15, 30, 45],
                     interventions=[
                         cv.test_num(daily_tests=[20] * pars.n_days),
                         cv.test_prob(symp_prob=0.0),
                         cv.test_prob(symp_prob=0.2),
                     ])

    # 3. Change beta
    i3a = cv.change_beta([30, 50], [0.0, 1.0], layers='h')
    i3b = cv.change_beta([30, 40, 60], [0.0, 1.0, 0.5])

    # 4. Clip edges -- should match the change_beta scenarios -- note that intervention i07 was removed
    i4a = cv.clip_edges([30, 50], [0.0, 1.0], layers='h')
    i4b = cv.clip_edges([30, 40, 60], [0.0, 1.0, 0.5])

    # 5. Test number
    i5 = cv.test_num(daily_tests=[100, 100, 100, 0, 0, 0] * (pars.n_days // 6))

    # 6. Test probability
    i6 = cv.test_prob(symp_prob=0.1)

    # 7. Contact tracing
    i7a = cv.test_prob(start_day=20,
                       symp_prob=0.01,
                       asymp_prob=0.0,
                       symp_quar_prob=1.0,
                       asymp_quar_prob=1.0,
                       test_delay=0)
    i7b = cv.contact_tracing(start_day=20,
                             trace_probs=dict(h=0.9, s=0.7, w=0.7, c=0.3),
                             trace_time=dict(h=0, s=1, w=1, c=3))

    # 8. Combination
    i8a = cv.clip_edges(days=18, changes=0.0, layers='s')  # Close schools
    i8b = cv.clip_edges(days=[20, 32, 45],
                        changes=[0.7, 0.3, 0.9],
                        layers=['w', 'c'])  # Reduce work and community
    i8c = cv.test_prob(start_day=38,
                       symp_prob=0.01,
                       asymp_prob=0.0,
                       symp_quar_prob=1.0,
                       asymp_quar_prob=1.0,
                       test_delay=2)  # Start testing for TTQ
    i8d = cv.contact_tracing(start_day=40,
                             trace_probs=dict(h=0.9, s=0.7, w=0.7, c=0.3),
                             trace_time=dict(h=0, s=1, w=1,
                                             c=3))  # Start tracing for TTQ

    #%% Create and run the simulations
    sims = sc.objdict()
    sims.dynamic = cv.Sim(pars=pars, interventions=[i1a, i1b])
    sims.sequence = cv.Sim(pars=pars, interventions=i2)
    sims.change_beta1 = cv.Sim(pars=pars, interventions=i3a)
    sims.clip_edges1 = cv.Sim(
        pars=pars, interventions=i4a)  # Roughly equivalent to change_beta1
    sims.change_beta2 = cv.Sim(pars=pars, interventions=i3b)
    sims.clip_edges2 = cv.Sim(
        pars=pars, interventions=i4b)  # Roughly equivalent to change_beta2
    sims.test_num = cv.Sim(pars=pars, interventions=i5)
    sims.test_prob = cv.Sim(pars=pars, interventions=i6)
    sims.tracing = cv.Sim(pars=pars, interventions=[i7a, i7b])
    sims.combo = cv.Sim(pars=pars, interventions=[i8a, i8b, i8c, i8d])

    for key, sim in sims.items():
        sim.label = key
        sim.run(verbose=verbose)

    #%% Plotting
    if do_plot:
        for sim in sims.values():
            print(f'Running {sim.label}...')
            sim.plot()
            fig = pl.gcf()
            fig.axes[0].set_title(f'Simulation: {sim.label}')

    return
def create_sim(pars=None, use_safegraph=True, label=None, show_intervs=False):
    ''' Create a single simulation for further use '''

    p = sc.objdict(
        sc.mergedicts(define_pars(which='best', use_safegraph=use_safegraph),
                      pars))
    if 'rand_seed' not in p:
        seed = 1
        print(f'Note, could not find random seed in {pars}! Setting to {seed}')
        p['rand_seed'] = seed  # Ensure this exists

    # Basic parameters and sim creation
    pars = {
        'pop_size': 225e3,
        'pop_scale': 10,
        'pop_type': 'synthpops',
        'pop_infected': 300,
        'beta': p.beta,
        'start_day': '2020-01-27',
        'end_day': '2020-06-08',
        'rescale': True,
        'rescale_factor': 1.1,
        'verbose': p.get('verbose', 0.01),
        'rand_seed': int(p.rand_seed),
        'analyzers': cv.age_histogram(datafile=age_data_file),
        'beta_layer': dict(h=3.0, s=0.6, w=0.6, c=0.3, l=1.5),
    }

    # Create and initialize the sim
    if pars['verbose']:
        print(f'Creating sim! safegraph={use_safegraph}, seed={p.rand_seed}')
    sim = cv.Sim(pars,
                 label=label,
                 popfile=get_popfile(pars),
                 load_pop=True,
                 datafile=epi_data_file
                 )  # Create this here so can be used for test numbers etc.

    # Define testing interventions -- 97% sensitivity from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7177629/
    test_kwargs = dict(daily_tests=sim.data['new_tests'],
                       test_delay=2,
                       sensitivity=0.97,
                       subtarget=test_num_subtarg)
    tn = cv.test_num(symp_test=p.tn,
                     start_day='2020-01-27',
                     end_day=None,
                     **test_kwargs,
                     label='tn')
    interventions = [tn]

    # Define beta interventions
    sim.intervention_info = sc.objdict()
    hwc_days = ['2020-02-24', '2020-03-23',
                '2020-05-31']  # Change date here, 04-27 or 05-04
    hwc_days = sim.day(hwc_days)
    b_wc_ch = [1.0, p.bc_wc1, p.get('bc_wc2', p.bc_wc1)
               ]  # To allow either one or two beta change parameters
    b_h_ch = [1.0, 1.1, 1.1]  # Optional household

    all_b_days = np.arange(hwc_days[0], hwc_days[-1] + 1)  # Full time series
    all_ch_wc = np.interp(all_b_days, hwc_days,
                          b_wc_ch)  # Linearly interpolate
    all_ch_h = np.interp(all_b_days, hwc_days, b_h_ch)  # Linearly interpolate
    interventions += [
        cv.change_beta(days=all_b_days,
                       changes=all_ch_h,
                       layers='h',
                       label='beta_h')
    ]
    lkeys = ['w', 'c', 's'] if use_safegraph else [
        'w', 'c'
    ]  # Skip schools if not using SafeGraph
    for lkey in lkeys:  # Assume schools also use masks, etc. so have same non-movement beta change
        cb = cv.change_beta(days=all_b_days,
                            changes=all_ch_wc,
                            layers=lkey,
                            label=f'beta_{lkey}')
        interventions += [cb]
        sim.intervention_info.bc = sc.objdict({
            'days': all_b_days,
            'changes': all_ch_wc
        })  # Store for plotting later

    # LTCF beta change
    b_l_days = ['2020-02-24', '2020-03-23']
    b_l_days = np.arange(sim.day(b_l_days[0]), sim.day(b_l_days[1]))
    b_l_ch = np.linspace(1.0, p.bc_lf, len(b_l_days))
    interventions += [
        cv.change_beta(days=b_l_days,
                       changes=b_l_ch,
                       layers='l',
                       label='beta_l')
    ]
    sim.people.contacts['c'] = remove_ltcf_community(
        sim)  # Remove community contacts from LTCF

    # SafeGraph intervention & tidy up
    if use_safegraph:
        interventions += make_safegraph(sim)
    else:
        interventions += [
            cv.clip_edges(days='2020-03-12',
                          changes=0.1,
                          layers='s',
                          label='clip_s')
        ]
    sim['interventions'] = interventions

    # Don't show interventions in plots, there are too many
    for interv in sim['interventions']:
        interv.do_plot = False

    # These are copied from parameters.py -- modified to capture change in work status at age 65
    sim['prognoses']['age_cutoffs'] = np.array(
        [0, 10, 20, 30, 40, 50, 65, 70, 80, 90])  # Age cutoffs (upper limits)

    return sim
def test_all_interventions():
    ''' Test all interventions supported by Covasim '''

    pars = sc.objdict(
        pop_size=1e3,
        pop_infected=10,
        pop_type='hybrid',
        n_days=90,
    )

    #%% Define the interventions

    # 1. Dynamic pars
    i00 = cv.test_prob(start_day=5, symp_prob=0.3)
    i01 = cv.dynamic_pars({
        'beta': {
            'days': [40, 50],
            'vals': [0.005, 0.015]
        },
        'rel_death_prob': {
            'days': 30,
            'vals': 2.0
        }
    })  # Starting day 30, make diagnosed people stop transmitting

    # 2. Sequence
    i02 = cv.sequence(days=[15, 30, 45],
                      interventions=[
                          cv.test_num(daily_tests=[20] * pars.n_days),
                          cv.test_prob(symp_prob=0.0),
                          cv.test_prob(symp_prob=0.2),
                      ])

    # 3. Change beta
    i03 = cv.change_beta([30, 50], [0.0, 1], layers='h')
    i04 = cv.change_beta([30, 40, 60], [0.0, 1.0, 0.5])

    # 4. Clip edges -- should match the change_beta scenarios
    i05 = cv.clip_edges(start_day=30, end_day=50, change={'h': 0.0})
    i06 = cv.clip_edges(start_day=30, end_day=40, change=0.0)
    i07 = cv.clip_edges(start_day=60, end_day=None, change=0.5)

    # 5. Test number
    i08 = cv.test_num(daily_tests=[100, 100, 100, 0, 0, 0] *
                      (pars.n_days // 6))

    # 6. Test probability
    i09 = cv.test_prob(symp_prob=0.1)

    # 7. Contact tracing
    i10 = cv.test_prob(start_day=20,
                       symp_prob=0.01,
                       asymp_prob=0.0,
                       symp_quar_prob=1.0,
                       asymp_quar_prob=1.0,
                       test_delay=0)
    i11 = cv.contact_tracing(start_day=20,
                             trace_probs=dict(h=0.9, s=0.7, w=0.7, c=0.3),
                             trace_time=dict(h=0, s=1, w=1, c=3))

    # 8. Combination
    i12 = cv.clip_edges(start_day=18, change={'s': 0.0})  # Close schools
    i13 = cv.clip_edges(start_day=20, end_day=32, change={
        'w': 0.7,
        'c': 0.7
    })  # Reduce work and community
    i14 = cv.clip_edges(start_day=32, end_day=45, change={
        'w': 0.3,
        'c': 0.3
    })  # Reduce work and community more
    i15 = cv.clip_edges(start_day=45,
                        end_day=None,
                        change={
                            'w': 0.9,
                            'c': 0.9
                        })  # Reopen work and community more
    i16 = cv.test_prob(start_day=38,
                       symp_prob=0.01,
                       asymp_prob=0.0,
                       symp_quar_prob=1.0,
                       asymp_quar_prob=1.0,
                       test_delay=2)  # Start testing for TTQ
    i17 = cv.contact_tracing(start_day=40,
                             trace_probs=dict(h=0.9, s=0.7, w=0.7, c=0.3),
                             trace_time=dict(h=0, s=1, w=1,
                                             c=3))  # Start tracing for TTQ

    #%% Create and run the simulations
    sims = sc.objdict()
    sims.dynamic = cv.Sim(pars=pars, interventions=[i00, i01])
    sims.sequence = cv.Sim(pars=pars, interventions=i02)
    sims.change_beta1 = cv.Sim(pars=pars, interventions=i03)
    sims.clip_edges1 = cv.Sim(
        pars=pars, interventions=i05)  # Roughly equivalent to change_beta1
    sims.change_beta2 = cv.Sim(pars=pars, interventions=i04)
    sims.clip_edges2 = cv.Sim(
        pars=pars, interventions=[i06,
                                  i07])  # Roughly euivalent to change_beta2
    sims.test_num = cv.Sim(pars=pars, interventions=i08)
    sims.test_prob = cv.Sim(pars=pars, interventions=i09)
    sims.tracing = cv.Sim(pars=pars, interventions=[i10, i11])
    sims.combo = cv.Sim(pars=pars,
                        interventions=[i12, i13, i14, i15, i16, i17])

    for key, sim in sims.items():
        sim.label = key
        sim.run(verbose=verbose)

    #%% Plotting
    if do_plot:
        for sim in sims.values():
            print(f'Running {sim.label}...')
            sim.plot()
            fig = pl.gcf()
            fig.axes[0].set_title(f'Simulation: {sim.label}')

    return
def test_tracedelay(do_plot=False, do_show=True, do_save=False, fig_path=None):
    sc.heading(
        'Test impact of reducing delay time for finding contacts of positives')

    sc.heading('Setting up...')

    sc.tic()

    n_runs = 3
    verbose = 1
    base_pars = {
        'pop_size': 1000,
        'pop_type': 'hybrid',
    }

    base_sim = cv.Sim(base_pars)  # create sim object
    base_sim['n_days'] = 50
    base_sim['beta'] = 0.03  # Increase beta

    n_people = base_sim['pop_size']
    npts = base_sim.npts

    # Define overall testing assumptions
    testing_prop = 0.1  # Assumes we could test 10% of the population daily (way too optimistic!!)
    daily_tests = [testing_prop * n_people] * npts  # Number of daily tests

    # Define the scenarios
    scenarios = {
        'lowtrace': {
            'name': 'Poor contact tracing',
            'pars': {
                'quar_eff': {
                    'h': 1,
                    's': 0.5,
                    'w': 0.5,
                    'c': 0.25
                },
                'quar_period':
                7,
                'interventions': [
                    cv.test_num(daily_tests=daily_tests),
                    cv.contact_tracing(trace_probs={
                        'h': 0,
                        's': 0,
                        'w': 0,
                        'c': 0
                    },
                                       trace_time={
                                           'h': 1,
                                           's': 7,
                                           'w': 7,
                                           'c': 7
                                       })
                ]
            }
        },
        'modtrace': {
            'name': 'Moderate contact tracing',
            'pars': {
                'quar_eff': {
                    'h': 0.75,
                    's': 0.25,
                    'w': 0.25,
                    'c': 0.1
                },
                'quar_period':
                10,
                'interventions': [
                    cv.test_num(daily_tests=daily_tests),
                    cv.contact_tracing(trace_probs={
                        'h': 1,
                        's': 0.8,
                        'w': 0.5,
                        'c': 0.1
                    },
                                       trace_time={
                                           'h': 0,
                                           's': 3,
                                           'w': 3,
                                           'c': 8
                                       })
                ]
            }
        },
        'hightrace': {
            'name': 'Fast contact tracing',
            'pars': {
                'quar_eff': {
                    'h': 0.5,
                    's': 0.1,
                    'w': 0.1,
                    'c': 0.1
                },
                'quar_period':
                14,
                'interventions': [
                    cv.test_num(daily_tests=daily_tests),
                    cv.contact_tracing(trace_probs={
                        'h': 1,
                        's': 0.8,
                        'w': 0.8,
                        'c': 0.2
                    },
                                       trace_time={
                                           'h': 0,
                                           's': 1,
                                           'w': 1,
                                           'c': 5
                                       })
                ]
            }
        },
        'alltrace': {
            'name': 'Same-day contact tracing',
            'pars': {
                'quar_eff': {
                    'h': 0.0,
                    's': 0.0,
                    'w': 0.0,
                    'c': 0.0
                },
                'quar_period':
                21,
                'interventions': [
                    cv.test_num(daily_tests=daily_tests),
                    cv.contact_tracing(trace_probs={
                        'h': 1,
                        's': 1,
                        'w': 1,
                        'c': 1
                    },
                                       trace_time={
                                           'h': 0,
                                           's': 1,
                                           'w': 1,
                                           'c': 2
                                       })
                ]
            }
        },
    }

    metapars = {'n_runs': n_runs}

    scens = cv.Scenarios(sim=base_sim, metapars=metapars, scenarios=scenarios)
    scens.run(verbose=verbose, debug=debug)

    if do_plot:
        to_plot = [
            'cum_infections', 'cum_recoveries', 'new_infections',
            'n_quarantined', 'new_quarantined'
        ]
        fig_args = dict(figsize=(24, 16))
        scens.plot(do_save=do_save,
                   do_show=do_show,
                   to_plot=to_plot,
                   fig_path=fig_path,
                   n_cols=2,
                   fig_args=fig_args)

    return scens
def create_sim(eind, verbose=True):
    ''' Create a single simulation for further use '''

    p = load_pars(eind)

    # Basic parameters and sim creation
    pars = {
        'pop_size': 225e3,
        'pop_scale': 10,
        'pop_type': 'synthpops',
        'pop_infected': 300,
        'beta': p.beta,
        'start_day': '2020-01-27',
        'end_day': '2020-08-31',
        'rescale': True,
        'rescale_factor': 1.1,
        'verbose': p.get('verbose', 0.01 * verbose),
        'rand_seed': int(p.rand_seed),
        'analyzers': cv.daily_stats(days=[]),
        'beta_layer': dict(h=3.0, s=0.6, w=0.6, c=0.3, l=1.5),
    }

    # Create and initialize the sim
    if pars['verbose']:
        print(f'Creating sim! seed={p.rand_seed}')
    sim = cv.Sim(pars,
                 label=f'base_sim_{p.rand_seed}',
                 popfile=get_popfile(pars),
                 load_pop=True,
                 datafile=epi_data_file
                 )  # Create this here so can be used for test numbers etc.

    sim.sceninfo = sc.objdict()
    sim.sceninfo.calib_end = '2020-05-31'
    sim.sceninfo.scen_start = '2020-06-01'

    # Define testing interventions -- 97% sensitivity from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7177629/
    test_kwargs = dict(daily_tests=sim.data['new_tests'],
                       test_delay=2,
                       sensitivity=0.97,
                       subtarget=test_num_subtarg)
    tn = cv.test_num(symp_test=p.tn,
                     start_day='2020-01-27',
                     end_day=sim.sceninfo.calib_end,
                     **test_kwargs,
                     label='tn')
    interventions = [tn]

    # Define beta interventions
    hwc_days = ['2020-02-24', '2020-03-23']  # Change date here, 04-27 or 05-04
    hwc_days = sim.day(hwc_days)
    b_wc_ch = [1.0, p.bc_wc1]  # Simple interpoation
    b_h_ch = [1.0, 1.1]  # Optional household

    all_b_days = np.arange(hwc_days[0], hwc_days[-1] + 1)  # Full time series
    all_ch_wc = np.interp(all_b_days, hwc_days,
                          b_wc_ch)  # Linearly interpolate
    all_ch_h = np.interp(all_b_days, hwc_days, b_h_ch)  # Linearly interpolate
    interventions += [
        cv.change_beta(days=all_b_days,
                       changes=all_ch_h,
                       layers='h',
                       label='beta_h')
    ]
    lkeys = ['w', 'c', 's']
    for lkey in lkeys:  # Assume schools also use masks, etc. so have same non-movement beta change
        cb = cv.change_beta(days=all_b_days,
                            changes=all_ch_wc,
                            layers=lkey,
                            label=f'beta_{lkey}')
        interventions += [cb]

    # LTCF beta change
    b_l_days = ['2020-02-24', '2020-03-23']
    b_l_days = np.arange(sim.day(b_l_days[0]), sim.day(b_l_days[1]))
    b_l_ch = np.linspace(1.0, p.bc_lf, len(b_l_days))
    interventions += [
        cv.change_beta(days=b_l_days,
                       changes=b_l_ch,
                       layers='l',
                       label='beta_l')
    ]
    sim.people.contacts['c'] = remove_ltcf_community(
        sim)  # Remove community contacts from LTCF

    # SafeGraph intervention & tidy up
    interventions += make_safegraph(sim)
    sim['interventions'] = interventions

    # Don't show interventions in plots, there are too many
    for interv in sim['interventions']:
        interv.do_plot = False

    # These are copied from parameters.py -- modified to capture change in work status at age 65
    sim['prognoses']['age_cutoffs'] = np.array(
        [0, 10, 20, 30, 40, 50, 65, 70, 80, 90])  # Age cutoffs (upper limits)

    return sim
sim = cv.Sim(pars)
sim.initialize()

# Set parameters
n_people = sim['pop_size']
n_tests = 0.1 * n_people
delay = 5
start_day = 40

# Create interventions
tn = cv.test_num(daily_tests=n_tests,
                 symp_test=1.0,
                 start_day=start_day,
                 test_delay=delay,
                 label='Testing',
                 subtarget={
                     'inds': lambda sim: sim.people.age > 50,
                     'vals': 1.2
                 })
tp = cv.test_prob(symp_prob=0.1,
                  asymp_prob=0.1,
                  start_day=start_day,
                  test_delay=delay)

# Create scenarios
scenarios = {
    'test_num': {
        'name': 'test_num',
        'pars': {
            'interventions': tn
def single_sim_new(end_day='2020-05-10',
                   rand_seed=1,
                   dist='lognormal',
                   par1=10,
                   par2=170):

    pop_type = 'hybrid'
    pop_size = 225000
    pop_scale = 2.25e6 / pop_size
    start_day = '2020-01-27'
    # end_day   = '2020-05-01'   # for calibration plots
    # end_day   = '2020-06-30'  # for projection plots

    pars = {
        'verbose': 0,
        'pop_size': pop_size,
        'pop_infected': 30,  # 300
        'pop_type': pop_type,
        'start_day': start_day,
        'n_days': (sc.readdate(end_day) - sc.readdate(start_day)).days,
        'pop_scale': pop_scale,
        'rescale': True,
        'beta': 0.015,
        'rand_seed': rand_seed,
    }

    sim = cv.Sim(pars, datafile=datafile)

    # Define beta interventions
    b_days = ['2020-03-04', '2020-03-12', '2020-03-23']
    b_ch = sc.objdict()
    b_ch.h = [1.00, 1.10, 1.20]
    b_ch.s = [1.00, 0.00, 0.00]
    b_ch.w = [0.60, 0.40, 0.25]
    b_ch.c = [0.60, 0.40, 0.25]

    # Define testing interventions
    daily_tests = sim.data['new_tests']
    test_kwargs = {
        'quar_test': 0,
        'sensitivity': 1.0,
        'test_delay': 0,
        'loss_prob': 0
    }
    interventions = [
        cv.test_num(daily_tests=daily_tests,
                    symp_test=70,
                    start_day='2020-01-27',
                    end_day=None,
                    swab_delay_dist={
                        'dist': dist,
                        'par1': par1,
                        'par2': par2
                    },
                    **test_kwargs),
    ]

    for lkey, ch in b_ch.items():
        interventions.append(
            cv.change_beta(days=b_days, changes=b_ch[lkey], layers=lkey))

    sim.update_pars(interventions=interventions)

    sim.initialize()

    # Define age susceptibility
    mapping = {
        0: 0.2,
        20: 0.9,
        40: 1.0,
        70: 2.5,
        80: 5.0,
        90: 10.0,
    }

    for age, val in mapping.items():
        sim.people.rel_sus[sim.people.age > age] = val

    return sim
Example #22
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.MultiSim([sim1, sim2, sim3])
msim.run()
msim.plot(
def tests(daily_test: object) -> cv.Intervention:
    return cv.test_num(daily_tests=daily_test,
                       quar_policy='both',
                       sensitivity=0.8)
def test_all_interventions(do_plot=False):
    ''' Test all interventions supported by Covasim '''
    sc.heading('Testing default interventions')

    # Default parameters, using the random layer
    pars = sc.objdict(
        pop_size=1e3,
        scaled_pop=10e3,
        pop_infected=10,
        n_days=90,
        verbose=verbose,
    )
    hpars = sc.mergedicts(
        pars,
        {'pop_type': 'hybrid'})  # Some, but not all, tests require layers
    rsim = cv.Sim(pars)
    hsim = cv.Sim(hpars)

    def make_sim(which='r', interventions=None):
        ''' Helper function to avoid having to recreate the sim each time '''
        if which == 'r': sim = sc.dcp(rsim)
        elif which == 'h': sim = sc.dcp(hsim)
        sim['interventions'] = interventions
        sim.initialize()
        return sim

    #%% Define the interventions

    # 1. Dynamic pars
    i1a = cv.test_prob(start_day=5, symp_prob=0.3)
    i1b = cv.dynamic_pars({
        'beta': {
            'days': [40, 50],
            'vals': [0.005, 0.015]
        },
        'rel_death_prob': {
            'days': 30,
            'vals': 2.0
        }
    })  # Starting day 30, make diagnosed people stop transmitting

    # 2. Sequence
    i2 = cv.sequence(days=[15, 30, 45],
                     interventions=[
                         cv.test_num(daily_tests=[20] * pars.n_days),
                         cv.test_prob(symp_prob=0.0),
                         cv.test_prob(symp_prob=0.2),
                     ])

    # 3. Change beta
    i3a = cv.change_beta([30, 50], [0.0, 1.0], layers='h')
    i3b = cv.change_beta([30, 40, 60], [0.0, 1.0, 0.5])

    # 4. Clip edges -- should match the change_beta scenarios -- note that intervention i07 was removed
    i4a = cv.clip_edges([30, 50], [0.0, 1.0], layers='h')
    i4b = cv.clip_edges([30, 40, 60], [0.0, 1.0, 0.5])

    # 5. Test number
    i5 = cv.test_num(daily_tests=[100, 100, 100, 0, 0, 0] * (pars.n_days // 6))

    # 6. Test probability
    i6 = cv.test_prob(symp_prob=0.1)

    # 7. Contact tracing
    i7a = cv.test_prob(start_day=20,
                       symp_prob=0.01,
                       asymp_prob=0.0,
                       symp_quar_prob=1.0,
                       asymp_quar_prob=1.0,
                       test_delay=0)
    i7b = cv.contact_tracing(start_day=20,
                             trace_probs=dict(h=0.9, s=0.7, w=0.7, c=0.3),
                             trace_time=dict(h=0, s=1, w=1, c=3))

    # 8. Combination, with dynamically set days
    def check_inf(interv, sim, thresh=10, close_day=18):
        days = close_day if sim.people.infectious.sum() > thresh else np.nan
        return days

    i8a = cv.clip_edges(days=check_inf, changes=0.0,
                        layers='s')  # Close schools
    i8b = cv.clip_edges(days=[20, 32, 45],
                        changes=[0.7, 0.3, 0.9],
                        layers=['w', 'c'])  # Reduce work and community
    i8c = cv.test_prob(start_day=38,
                       symp_prob=0.01,
                       asymp_prob=0.0,
                       symp_quar_prob=1.0,
                       asymp_quar_prob=1.0,
                       test_delay=2)  # Start testing for TTQ
    i8d = cv.contact_tracing(start_day=40,
                             trace_probs=dict(h=0.9, s=0.7, w=0.7, c=0.3),
                             trace_time=dict(h=0, s=1, w=1,
                                             c=3))  # Start tracing for TTQ

    # 9. Vaccine
    i9a = cv.simple_vaccine(days=20, prob=1.0, rel_sus=1.0, rel_symp=0.0)
    i9b = cv.simple_vaccine(days=50, prob=1.0, rel_sus=0.0, rel_symp=0.0)

    #%% Create the simulations
    sims = sc.objdict()
    sims.dynamic = make_sim('r', [i1a, i1b])
    sims.sequence = make_sim('r', i2)
    sims.change_beta1 = make_sim('h', i3a)
    sims.clip_edges1 = make_sim('h', i4a)  # Roughly equivalent to change_beta1
    sims.change_beta2 = make_sim('r', i3b)
    sims.clip_edges2 = make_sim('r', i4b)  # Roughly equivalent to change_beta2
    sims.test_num = make_sim('r', i5)
    sims.test_prob = make_sim('r', i6)
    sims.tracing = make_sim('h', [i7a, i7b])
    sims.combo = make_sim('h', [i8a, i8b, i8c, i8d])
    sims.vaccine = make_sim('r', [i9a, i9b])

    # Run the simualations
    for key, sim in sims.items():
        sim.label = key
        sim.run()

    # Test intervention retrieval methods
    sim = sims.combo
    ce1, ce2 = sim.get_interventions(cv.clip_edges)
    ce, tp = sim.get_interventions([0, 2])
    inds = sim.get_interventions(cv.clip_edges, as_inds=True)  # Returns [0,1]
    assert inds == [0, 1]
    sim.get_interventions('summary')  # Prints a summary

    # Test other intervention methods
    ce.disp()
    ce.shrink()

    #%% Plotting
    if do_plot:
        for sim in sims.values():
            print(f'Running {sim.label}...')
            sim.plot()
            fig = pl.gcf()
            try:
                fig.axes[0].set_title(f'Simulation: {sim.label}')
            except:
                pass

    return
def test_interventions(do_plot=False,
                       do_show=True,
                       do_save=False,
                       fig_path=None):
    sc.heading('Test of testing interventions')

    sc.heading('Setting up...')

    sc.tic()

    n_runs = 3
    verbose = 1
    base_pars = {
        'pop_size': 1000,
        'pop_type': 'hybrid',
    }

    base_sim = cv.Sim(base_pars)  # create sim object
    n_people = base_sim['pop_size']
    npts = base_sim.npts

    # Define overall testing assumptions
    # Remember that this is the daily % of the population that gets tested. S Korea (one of the highest-testing places) tested
    # an average of 10000 people/day over March, or 270,000 in total. This is ~200 people per million every day (0.02%)....
    max_optimistic_testing = 0.1  # ... which means that this is an artificially high number, for testing purposes only!!
    optimistic_daily_tests = [
        max_optimistic_testing * n_people
    ] * npts  # Very best-case scenario for asymptomatic testing

    # Define the scenarios
    scenarios = {
        'baseline': {
            'name': 'Status quo, no testing',
            'pars': {
                'interventions': None,
            }
        },
        'test_skorea': {
            'name':
            'Assuming South Korea testing levels of 0.02% daily (untargeted); isolate positives',
            'pars': {
                'interventions':
                cv.test_num(daily_tests=optimistic_daily_tests)
            }
        },
        'floating': {
            'name': 'Test with constant probability based on symptoms',
            'pars': {
                'interventions':
                cv.test_prob(symp_prob=max_optimistic_testing, asymp_prob=0.0)
            }
        },
        'sequence': {
            'name': 'Historical switching to probability',
            'pars': {
                'interventions':
                cv.sequence(
                    days=[10, 51],
                    interventions=[
                        cv.test_num(daily_tests=optimistic_daily_tests),
                        cv.test_prob(symp_prob=0.2, asymp_prob=0.002),
                    ])
            }
        },
    }

    metapars = {'n_runs': n_runs}

    scens = cv.Scenarios(sim=base_sim, metapars=metapars, scenarios=scenarios)
    scens.run(verbose=verbose, debug=debug)

    to_plot = ['cum_infections', 'n_infectious', 'new_tests', 'new_diagnoses']
    fig_args = dict(figsize=(20, 24))

    if do_plot:
        scens.plot(do_save=do_save,
                   do_show=do_show,
                   fig_path=fig_path,
                   interval=7,
                   fig_args=fig_args,
                   to_plot=to_plot)

    return scens
'''
Compare simulating the entire population vs. dynamic rescaling vs. static rescaling.
'''

import sciris as sc
import covasim as cv

T = sc.tic()

p = sc.objdict()  # Parameters
s = sc.objdict()  # Sims
m = sc.objdict()  # Multisims

# Interventions
tn = cv.test_num(start_day=40, daily_tests=1000,
                 symp_test=10)  # Test a number of people
tp = cv.test_prob(start_day=30, symp_prob=0.1,
                  asymp_prob=0.01)  # Test a number of people
cb = cv.change_beta(days=50, changes=0.5)  # Change beta

# Properties that are shared across sims
basepop = 10e3
popinfected = 100
popscale1 = 10
popscale2 = 20  # Try a different population scale
which_interv = 2  # Which intervention to test

shared = sc.objdict(
    n_days=120,
    beta=0.015,
    rand_seed=239487,
Example #27
0
pop_size = 200e3
pars = dict(
    pop_size=pop_size,
    pop_scale=data.popsize / pop_size,
    pop_infected=5000,
    beta=0.015,
    start_day='2020-03-01',
    end_day='2020-06-17',
    rescale=True,
)

sim = cv.Sim(pars, datafile=data.epi)

interventions = [
    cv.change_beta(days=20, changes=0.49),
    cv.test_num(daily_tests=sim.data['new_tests'].dropna(), symp_test=17),
]

sim.update_pars(interventions=interventions)
if do_run:
    msim = cv.MultiSim(sim)
    msim.run(n_runs=20, par_args={'ncpus': 5})
    msim.reduce()
    msim.save(msimfile)
else:
    msim = cv.load(msimfile)

#%% Plotting
for interv in msim.base_sim['interventions']:
    interv.do_plot = False
 't&q 1': {
     'name': 'Test-and-quarantine only individual',
     'pars': {
         'interventions': [
             cv.change_beta(days=interv_day1,
                            changes=interv_eff_60,
                            layers='c'),
             cv.change_beta(
                 [interv_day1, interv_day2, interv_day3, interv_day4],
                 [0.4, 0.6, 0.4, 0.4],
                 layers='w'),
             cv.change_beta(days=s_close, changes=0, layers='s'),
             cv.test_num(start_day='2020-04-01',
                         end_day=test_day,
                         daily_tests=90,
                         loss_prob=0,
                         quar_test=1,
                         sensitivity=0.9,
                         test_delay=1.0),
             cv.test_num(start_day=test_day,
                         daily_tests=200,
                         loss_prob=0,
                         quar_test=1,
                         sensitivity=0.9,
                         test_delay=1.0),
             cv.contact_tracing(start_day=test_day,
                                trace_probs={'h': 0},
                                presumptive=True,
                                trace_time=0),
         ]
     }
def create_sim(seed, ratio):
    beta = 0.014
    pop_infected = 10
    start_day = '2020-02-01'
    #end_day   = '2020-11-30'
    end_day = '2021-03-31'
    data_file = df
    # Set the parameters
    total_pop = 5.8e6  # Denmark population size
    pop_size = 100e3  # Actual simulated population
    pop_scale = int(total_pop / pop_size)
    pop_type = 'hybrid'
    asymp_factor = 2
    pars = sc.objdict(
        pop_size=pop_size,
        pop_infected=pop_infected,
        pop_scale=pop_scale,
        pop_type=pop_type,
        start_day=start_day,
        end_day=end_day,
        beta=beta,
        asymp_factor=asymp_factor,
        rescale=True,
        verbose=0.1,
        rand_seed=seed,
    )

    # Create the baseline simulation
    sim = cv.Sim(pars=pars, datafile=data_file, location='denmark')

    relative_death = cv.dynamic_pars(rel_death_prob=dict(days=[
        sim.day('2020-02-01'),
        sim.day('2020-06-09'),
        sim.day('2020-09-17')
    ],
                                                         vals=[1.3, 0.8, 0.4]))
    interventions = [relative_death]

    ### Change beta ###
    beta_days = [
        '2020-03-15', '2020-04-15', '2020-05-10', '2020-06-22', '2020-07-20',
        '2020-08-22', '2020-09-01', '2020-09-22', '2020-10-01', '2020-10-15',
        '2020-11-01', '2020-11-20', '2020-11-30', '2020-12-14', '2021-01-01',
        '2021-03-01'
    ]
    h_beta_changes = [
        1.10, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.10, 1.10, 1.10, 1.20,
        1.30, 1.20, 1.10, 1.00
    ]
    s_beta_changes = [
        0.80, 0.50, 0.50, 0.40, 0.60, 0.60, 1.00, 0.80, 0.80, 1.00, 0.80, 1.00,
        1.20, 1.00, 0.80, 0.70
    ]
    w_beta_changes = [
        0.80, 0.50, 0.50, 0.40, 0.60, 0.60, 1.00, 0.80, 0.80, 1.00, 0.80, 1.00,
        1.20, 1.00, 0.80, 0.70
    ]
    c_beta_changes = [
        0.90, 0.60, 0.50, 0.70, 0.90, 0.80, 1.00, 0.70, 0.70, 1.00, 0.80, 1.10,
        1.30, 1.10, 1.00, 0.80
    ]

    # Define the beta changes
    h_beta = cv.change_beta(days=beta_days, changes=h_beta_changes, layers='h')
    s_beta = cv.change_beta(days=beta_days, changes=s_beta_changes, layers='s')
    w_beta = cv.change_beta(days=beta_days, changes=w_beta_changes, layers='w')
    c_beta = cv.change_beta(days=beta_days, changes=c_beta_changes, layers='c')

    ### edge clipping ###
    clip_days = [
        '2020-03-15', '2020-04-15', '2020-05-10', '2020-06-08', '2020-06-22',
        '2020-08-17', '2020-09-01', '2020-09-15', '2020-10-05', '2020-11-05',
        '2020-11-20', '2020-12-09', '2020-12-19', '2020-12-25', '2021-01-04',
        '2021-02-01', '2021-03-01'
    ]
    s_clip_changes = [
        0.01, 0.20, 0.40, 0.70, 0.05, 0.10, 0.90, 0.80, 0.70, 0.70, 0.70, 0.40,
        0.05, 0.05, 0.05, 0.30, 0.50
    ]
    w_clip_changes = [
        0.10, 0.30, 0.50, 0.70, 0.60, 0.80, 1.00, 0.80, 0.70, 0.70, 0.70, 0.60,
        0.40, 0.10, 0.50, 0.60, 0.60
    ]
    c_clip_changes = [
        0.20, 0.40, 0.60, 0.85, 1.00, 1.00, 1.00, 0.80, 0.80, 0.90, 0.90, 0.70,
        0.80, 0.50, 0.60, 0.70, 0.80
    ]

    # Define the edge clipping
    s_clip = cv.clip_edges(days=clip_days, changes=s_clip_changes, layers='s')
    w_clip = cv.clip_edges(days=clip_days, changes=w_clip_changes, layers='w')
    c_clip = cv.clip_edges(days=clip_days, changes=c_clip_changes, layers='c')
    interventions += [h_beta, w_beta, s_beta, c_beta, w_clip, s_clip, c_clip]

    # Add a new change in beta to represent the takeover of the new variant B.1.1.7
    nv_days = np.linspace(sim.day('2020-12-14'), sim.day('2021-03-28'), 15 * 7)
    nv_prop = 0.952 / (1 + np.exp(-0.099 *
                                  (nv_days - sim.day('2020-12-14') - 59)))
    nv_change = nv_prop * ratio + (1 - nv_prop) * 1.0  #r = 1.5
    nv_beta = cv.change_beta(days=nv_days, changes=nv_change)

    c = np.r_[0.8 * np.ones(sim.day('2021-02-13') - sim.day('2020-12-14')),
              0.4 * np.ones(sim.day('2021-03-29') - sim.day('2021-02-13'))]
    relative_severe = cv.dynamic_pars(rel_severe_prob=dict(
        days=nv_days, vals=nv_prop * 1.0 + (1 - nv_prop) * 1))
    relative_critical = cv.dynamic_pars(rel_crit_prob=dict(
        days=nv_days, vals=nv_prop * 1.0 + (1 - nv_prop) * 1))
    relative_death_nv = cv.dynamic_pars(rel_death_prob=dict(
        days=nv_days, vals=nv_prop * c * 1.0 + (1 - nv_prop) * c))
    interventions += [
        nv_beta, relative_severe, relative_critical, relative_death_nv
    ]

    # import infections from 2020-02-20 to 2020-03-01
    imports1 = cv.dynamic_pars(n_imports=dict(days=[25, 35], vals=[2, 0]))
    imports2 = cv.dynamic_pars(n_imports=dict(days=[171, 190], vals=[2, 0]))
    interventions += [imports1, imports2]

    iso_vals = [{
        'h': 0.5,
        's': 0.05,
        'w': 0.05,
        'c': 0.1
    }]  #dict(h=0.5, s=0.05, w=0.05, c=0.1)
    interventions += [
        cv.dynamic_pars(
            {'iso_factor': {
                'days': sim.day('2020-03-15'),
                'vals': iso_vals
            }})
    ]

    # From May 12, starting tracing and isolation strategy
    tracing_prob = dict(h=1.0, s=0.5, w=0.5, c=0.2)
    trace_time = {'h': 0, 's': 1, 'w': 1, 'c': 2}
    interventions += [
        cv.contact_tracing(trace_probs=tracing_prob,
                           trace_time=trace_time,
                           start_day='2020-05-12')
    ]

    interventions += [
        cv.test_num(daily_tests=sim.data['new_tests'],
                    start_day=0,
                    end_day=sim.day(end_day),
                    test_delay=1,
                    symp_test=50,
                    sensitivity=0.97,
                    subtarget=prior_test)
    ]

    vaccine1 = vaccine_plan(daily1,
                            start_day='2021-01-06',
                            end_day='2021-01-24',
                            delay=22,
                            rel_symp=0.5,
                            rel_sus=0.2,
                            subtarget=vaccinate_by_age)
    vaccine2 = vaccine_plan(daily2,
                            start_day='2021-01-25',
                            end_day='2021-02-15',
                            delay=27,
                            rel_symp=0.5,
                            rel_sus=0.2,
                            subtarget=vaccinate_by_age)
    vaccine3 = vaccine_plan(daily3,
                            start_day='2021-02-16',
                            end_day='2021-03-07',
                            delay=24,
                            rel_symp=0.5,
                            rel_sus=0.2,
                            subtarget=vaccinate_by_age)
    vaccine4 = vaccine_plan(daily4,
                            start_day='2021-03-08',
                            end_day='2021-04-10',
                            delay=37,
                            rel_symp=0.5,
                            rel_sus=0.2,
                            subtarget=vaccinate_by_age)

    interventions += [vaccine1, vaccine2, vaccine3, vaccine4]

    sim.update_pars(interventions=interventions)

    for intervention in sim['interventions']:
        intervention.do_plot = False

    sim.initialize()

    return sim
Example #30
0
def create_sim(pars=None,
               label=None,
               use_safegraph=True,
               show_intervs=False,
               people=None):
    ''' Create a single simulation for further use '''

    p = sc.objdict(
        sc.mergedicts(
            define_pars(which='best', kind='both',
                        use_safegraph=use_safegraph), pars))
    if 'rand_seed' not in p:
        seed = 1
        print(f'Note, could not find random seed in {pars}! Setting to {seed}')
        p['rand_seed'] = seed  # Ensure this exists
    if 'end_day' not in p:
        end_day = '2020-07-19'
        p['end_day'] = end_day

    # Basic parameters and sim creation
    pars = {
        'pop_size': 225e3,
        'pop_scale': 10,
        'pop_type': 'synthpops',
        'pop_infected': 400,
        'beta': p.beta,
        'start_day': '2020-01-27',
        'end_day': '2020-07-19',
        'rescale': True,
        'rescale_factor': 1.1,
        'verbose': 0,
        'rand_seed': p.rand_seed,
        'analyzers': cv.age_histogram(datafile=age_data_file),
        'beta_layer': dict(h=p.bl_h, s=p.bl_s, w=p.bl_w, c=p.bl_c, l=p.bl_l),
    }
    pars.update({'n_days': cv.daydiff(pars['start_day'], pars['end_day'])})

    # If supplied, use an existing people object
    if people:
        popfile = people
    else:
        # Generate the population filename
        n_popfiles = 5
        popfile = popfile_stem + str(pars['rand_seed'] % n_popfiles) + '.ppl'

        # Check that the population file exists
        if not os.path.exists(popfile):
            errormsg = f'WARNING: could not find population file {popfile}! Please regenerate first'
            raise FileNotFoundError(errormsg)

    # Create and initialize the sim
    sim = cv.Sim(pars,
                 label=label,
                 popfile=popfile,
                 load_pop=True,
                 datafile=epi_data_file
                 )  # Create this here so can be used for test numbers etc.
    # Define testing interventions
    test_kwargs = dict(daily_tests=sim.data['new_tests'],
                       quar_test=1.0,
                       test_delay=2)
    tn1 = cv.test_num(symp_test=p.tn1,
                      start_day='2020-01-27',
                      end_day='2020-03-23',
                      **test_kwargs,
                      label='tn1')
    tn2 = cv.test_num(symp_test=p.tn2,
                      start_day='2020-03-24',
                      end_day='2020-04-14',
                      **test_kwargs,
                      label='tn2')
    tn3 = cv.test_num(symp_test=p.tn3,
                      start_day='2020-04-15',
                      end_day=None,
                      **test_kwargs,
                      label='tn3')
    interventions = [tn1, tn2, tn3]

    # Define beta interventions (for calibration)
    b_ch = sc.objdict()
    b_days = ['2020-03-04', '2020-03-12', '2020-04-25']
    b_ch.s = [1.00, 0.00, 0.00]
    b_ch.w = [p.bc_wc1, p.bc_wc2, p.bc_wc3]
    b_ch.c = [p.bc_wc1, p.bc_wc2, p.bc_wc3]

    for lkey, ch in b_ch.items():
        interventions += [
            cv.change_beta(days=b_days,
                           changes=b_ch[lkey],
                           layers=lkey,
                           label=f'beta_{lkey}')
        ]

    # LTCF intervention
    b_days_l = np.arange(sim.day(b_days[0]), sim.day(b_days[2]) + 1)
    b_ch_l = np.linspace(1.0, p.bc_lf, len(b_days_l))
    interventions += [
        cv.change_beta(days=b_days_l,
                       changes=b_ch_l,
                       layers='l',
                       label=f'beta_l')
    ]

    # SafeGraph intervention & tidy up
    interventions += make_safegraph(sim)
    sim['interventions'] = interventions

    # Don't show interventions in plots, there are too many
    if show_intervs == False:
        for interv in sim['interventions']:
            interv.do_plot = False

    # These are copied from parameters.py -- needed to get younger and 60-65 groups right
    sim['prognoses']['age_cutoffs'] = np.array(
        [0, 15, 20, 30, 40, 50, 65, 70, 80, 90])  # Age cutoffs (upper limits)

    return sim