def test_run(): sc.heading('Testing run') msim_path = 'run_test.msim' scens_path = 'run_test.scens' # Test creation s1 = cv.Sim(pop_size=100) s2 = s1.copy() msim = cv.MultiSim(sims=[s1, s2]) with pytest.raises(TypeError): cv.MultiSim(sims='not a sim') # Test other properties len(msim) msim.result_keys() msim.base_sim = None with pytest.raises(ValueError): msim.result_keys() msim.base_sim = msim.sims[0] # Restore # Run msim.run(verbose=verbose) msim.reduce(quantiles=[0.1, 0.9], output=True) with pytest.raises(ValueError): msim.reduce(quantiles='invalid') msim.compare(output=True, do_plot=True, log_scale=False) # Plot for i in range(2): if i == 1: msim.reset() # Reset as if reduce() was not called msim.plot() msim.plot_result('r_eff') print('↑ May print some plotting warnings') # Save for keep_people in [True, False]: msim.save(filename=msim_path, keep_people=keep_people) # Scenarios scens = cv.Scenarios(sim=s1, metapars={'n_runs': 1}) scens.run(keep_people=True, verbose=verbose, debug=debug) for keep_people in [True, False]: scens.save(scens_path, keep_people=keep_people) cv.Scenarios.load(scens_path) # Tidy up remove_files(msim_path, scens_path) return
def test_migration(): sc.heading('Testing migration...') # Create sim and people base = make_sim() base.people.version = version sim = cv.load(filename) sim.people = base.people # Create msim msim = cv.MultiSim(base_sim=sim) del msim.version # To simulate <2.0.0 msim.init_sims() # Create scenarios scens = cv.Scenarios(sim=sim) del scens.version # To simulate <2.0.0 # Try migrations new_sim = cv.migrate(sim, die=True) new_msim = cv.migrate(msim, die=True) new_scens = cv.migrate(scens, die=True) # Try something un-migratable with pytest.raises(TypeError): cv.migrate('Strings are not migratable', die=True) return new_sim, new_msim, new_scens
def test_msim(do_plot=False): sc.heading('Testing multisim...') # basic test for vaccine b117 = cv.variant('b117', days=0) sim = cv.Sim(use_waning=True, variants=[b117], **base_pars) msim = cv.MultiSim(sim, n_runs=2) msim.run() msim.reduce() to_plot = sc.objdict({ 'Total infections': ['cum_infections'], 'New infections per day': ['new_infections'], 'New Re-infections per day': ['new_reinfections'], }) if do_plot: msim.plot(to_plot=to_plot, do_save=0, do_show=1, legend_args={'loc': 'upper left'}, axis_args={'hspace': 0.4}, interval=35) return msim
def run_msim(self, new_deaths=False): ''' Run the simulation -- if new_deaths, fit to daily deaths rather than cumulative cases + deaths ''' if self.n_runs == 1: sim = self.sim sim.run() else: msim = cv.MultiSim(base_sim=self.sim) msim.run(n_runs=self.n_runs) sim = msim.reduce(output=True) if new_deaths: offset = cv.daydiff(sim['start_day'], sim.data['date'][0]) d_data = self.smooth(sim.data['new_deaths'].values) d_sim = self.smooth(sim.results['new_deaths'].values[offset:]) minlen = min(len(d_data), len(d_sim)) d_data = d_data[:minlen] d_sim = d_sim[:minlen] deaths = {'deaths': dict(data=d_data, sim=d_sim, weights=1)} sim.compute_fit(custom=deaths, keys=['cum_diagnoses', 'cum_deaths'], weights={ 'cum_diagnoses': 0.2, 'cum_deaths': 0.2 }, output=False) else: sim.compute_fit(output=False) self.sim = sim self.mismatch = sim.results.fit.mismatch return sim
def test_multisim_combine( do_plot=do_plot): # If being run via pytest, turn off sc.heading('Combine results test') n_runs = 3 pop_infected = 10 print('Running first sim...') sim = cv.Sim(pop_size=pop_size, pop_infected=pop_infected, verbose=verbose) msim = cv.MultiSim(sim) msim.run(n_runs=n_runs, keep_people=True) sim1 = msim.combine(output=True) assert sim1['pop_size'] == pop_size * n_runs print( 'Running second sim, results should be similar but not identical (stochastic differences)...' ) sim2 = cv.Sim(pop_size=pop_size * n_runs, pop_infected=pop_infected * n_runs) sim2.run(verbose=verbose) if do_plot: msim.plot() sim2.plot() return msim
def test_multisim_advanced(): sc.heading('Advanced multisim options') # Settings msim_path = 'msim_test.msim' # Creat the sims/msims sims = sc.objdict() for i in range(4): sims[f's{i}'] = cv.Sim(label=f'Sim {i}', pop_size=pop_size, beta=0.01 * i) m1 = cv.MultiSim(sims=[sims.s0, sims.s1]) m2 = cv.MultiSim(sims=[sims.s2, sims.s3]) # Test methods m1.init_sims() m1.run() m2.run(reduce=True) m1.reduce() m1.mean() m1.median() m1.shrink() m1.disp() m1.summarize() m1.brief() # Check save/load m1.save(msim_path) m1b = cv.MultiSim.load(msim_path) assert np.allclose(m1.summary[:], m1b.summary[:], rtol=0, atol=0, equal_nan=True) os.remove(msim_path) # Check merging/splitting merged1 = cv.MultiSim.merge(m1, m2) merged2 = cv.MultiSim.merge([m1, m2], base=True) m1c, m2c = merged1.split() m1d, m2d = merged1.split(chunks=[2, 2]) return merged1, merged2
def bypass(): do_plot = True # Whether to plot results n_seeds = 6 # Number of seeds to run each simulation with rand_seed = 1 # Overwrite the default random seed bypass_popfile = 'trans_r0_medium.ppl' pop_size = int(100e3) entry = { "index": 376.0, "mismatch": 0.03221581045452142, "pars": { "pop_infected": 0, "change_beta": 0.5313884845187986, "symp_prob": 0.08250498122080606 } } params = sc.dcp(entry['pars']) if rand_seed is None: params['rand_seed'] = int(entry['index']) else: params['rand_seed'] = rand_seed # Ensure the population file exists if not os.path.exists(bypass_popfile): print(f'Population file {bypass_popfile} not found, recreating...') cvsch.make_population(pop_size=pop_size, rand_seed=params['rand_seed'], max_pop_seeds=5, popfile=bypass_popfile, do_save=True) scen = generate_scenarios()['as_normal'] # Create the sim people = sc.loadobj(bypass_popfile) base_sim = cs.create_sim(params, pop_size=pop_size, load_pop=False, people=people, verbose=0.1) # Run the sims sims = [] for seed in range(n_seeds): sim = sc.dcp(base_sim) sim.set_seed(seed=sim['rand_seed'] + seed) sim.label = f'Sim {seed}' sim['interventions'] += [cvsch.schools_manager(scen), seed_schools()] sim['beta_layer'] = dict( h=0.0, s=0.0, w=0.0, c=0.0, l=0.0 ) # Turn off transmission in other layers, looking for in-school R0 sims.append(sim) msim = cv.MultiSim(sims) msim.run(keep_people=True) return msim
def longway(): pop_size = 2.25e5 calibfile = os.path.join( folder, 'pars_cases_begin=75_cases_end=75_re=1.0_prevalence=0.002_yield=0.024_tests=225_pop_size=225000.json' ) par_list = sc.loadjson(calibfile)[par_inds[0]:par_inds[1]] scen = generate_scenarios()['as_normal'] for stype, cfg in scen.items(): if cfg: cfg['start_day'] = '2020-09-07' # Move school start earlier # Configure and run the sims sims = [] for eidx, entry in enumerate(par_list): par = sc.dcp(entry['pars']) par['rand_seed'] = int(entry['index']) # Clunky, but check that the population exists pop_seed = par['rand_seed'] % 5 popfile = os.path.join( folder, 'inputs', f'kc_synthpops_clustered_{int(pop_size)}_withstaff_seed') + str( pop_seed) + '.ppl' if not os.path.exists(popfile): print(f'Population file {popfile} not found, recreating...') cvsch.make_population(pop_size=pop_size, rand_seed=par['rand_seed'], max_pop_seeds=5, popfile=popfile, do_save=True) par['pop_infected'] = 0 # Do NOT seed infections par['beta_layer'] = dict( h=0.0, s=0.0, w=0.0, c=0.0, l=0.0 ) # Turn off transmission in other layers, looking for in-school R0 sim = cs.create_sim(par, pop_size=pop_size, folder=folder) delay = sim.day('2020-09-16') # Pick a Monday sim['interventions'] += [ cvsch.schools_manager(scen), seed_schools(delay=delay, n_infections=1, choose_students=False) ] sims.append(sim) msim = cv.MultiSim(sims) msim.run(keep_people=True) return msim
def test_multisim_reduce(do_plot=do_plot): # If being run via pytest, turn off sc.heading('Combine results test') n_runs = 3 pop_infected = 10 sim = cv.Sim(pop_size=pop_size, pop_infected=pop_infected) msim = cv.MultiSim(sim, n_runs=n_runs, noise=0.1) msim.run(verbose=verbose, reduce=True) if do_plot: msim.plot() return msim
def test_waning(do_plot=False): sc.heading('Testing with and without waning') msims = dict() for rescale in [0, 1]: print(f'Checking with rescale = {rescale}...') # Define parameters specific to this test pars = dict(n_days=90, beta=0.008, nab_decay=dict(form='nab_decay', decay_rate1=0.1, decay_time1=250, decay_rate2=0.001)) # Optionally include rescaling if rescale: pars.update( pop_scale=10, rescale_factor= 2.0, # Use a large rescale factor to make differences more obvious ) # Run the simulations and pull out the results s0 = cv.Sim(base_pars, **pars, use_waning=False, label='No waning').run() s1 = cv.Sim(base_pars, **pars, use_waning=True, label='With waning').run() res0 = s0.summary res1 = s1.summary msim = cv.MultiSim([s0, s1]) msims[rescale] = msim # Check results for key in [ 'n_susceptible', 'cum_infections', 'cum_reinfections', 'pop_nabs', 'pop_protection', 'pop_symp_protection' ]: v0 = res0[key] v1 = res1[key] print(f'Checking {key:20s} ... ', end='') assert v1 > v0, f'Expected {key} to be higher with waning than without' print(f'✓ ({v1} > {v0})') # Optionally plot if do_plot: msim.plot('overview-strain', rotation=30) return msims
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
def test_multisim_reduce(do_plot=False): # If being run via pytest, turn off sc.heading('Combine results test') n_runs = 3 pop_size = 1000 pop_infected = 10 print('Running first sim...') sim = cv.Sim(pop_size=pop_size, pop_infected=pop_infected) msim = cv.MultiSim(sim, n_runs=n_runs, noise=0.1) msim.run(verbose=verbose) msim.reduce() if do_plot: msim.plot() return msim
def test_sims(do_plot=False): s1 = cs.create_sim(pop_size=10e3, load_pop=False, label='Default') s2 = cs.create_sim(pop_size=10e3, load_pop=False, rand_seed=23948, label='Different seed') s3 = cs.create_sim(pop_size=10e3, load_pop=False, beta=0.03, label='High beta') msim = cv.MultiSim([s1, s2, s3]) msim.run() if do_plot: msim.plot() return msim
def make_msims(sims): ''' Take a slice of sims and turn it into a multisim ''' msim = cv.MultiSim(sims) draw, seed = sims[0].meta.inds for s, sim in enumerate(sims): # Check that everything except seed matches assert draw == sim.meta.inds[0] assert (s == 0) or seed != sim.meta.inds[1] msim.meta = sc.objdict() msim.meta.inds = [draw] msim.meta.vals = sc.dcp(sims[0].meta.vals) msim.meta.vals.pop('seed') print(f'Processing multisim {msim.meta.vals.values()}...') if save_sim: # NB, generates ~2 GB of files for a full run id_str = '_'.join([str(i) for i in msim.meta.inds]) msimfile = f'{cachefolder}/final_msim{id_str}.msim' # File to save the partially run sim to msim.save(msimfile) return msim
import covasim as cv sim = cv.Sim() # Create the sim msim1 = cv.MultiSim(sim, n_runs=5) # Create the multisim msim1.run() # Run them in parallel msim1.combine() # Combine into one sim msim1.plot() # Plot results sim = cv.Sim() # Create the sim msim2 = cv.MultiSim(sim, n_runs=11, noise=0.1) # Set up a multisim with noise msim2.run() # Run msim2.reduce() # Compute statistics msim2.plot() # Plot # Run multiple sims n_sims = 5 betas = [0.015 * (1 + 0.02 * i) for i in range(n_sims)] labels = [f'beta={beta}' for beta in betas] sims = [cv.Sim(beta=betas[i], label=labels[i]) for i in range(n_sims)] # Create sims for sim in sims: sim.run() msim3 = cv.MultiSim(sims) # Convert to multisim msim3.plot() # Plot as single sim
p.static2 = dict( pop_size=basepop, pop_infected=popinfected // popscale2, pop_scale=popscale2, rescale=False, ) # Create and run the sims keys = p.keys() for key in keys: p[key].update(shared) for key in keys: s[key] = cv.Sim(pars=p[key], label=key) m[key] = cv.MultiSim(base_sim=s[key], n_runs=10) for key in keys: m[key].run() m[key].reduce() # Plot to_plot = { 'Totals': ['cum_infections', 'cum_diagnoses'], 'New': ['new_infections', 'new_diagnoses'], 'Total tests': ['cum_tests'], 'New tests': ['new_tests'], } log_scale = ['Total tests'] for key in keys:
''' Test MultiSim merging and splitting ''' import covasim as cv; cv m1 = cv.MultiSim(cv.Sim(label='sim1'), initialize=True) m2 = cv.MultiSim(cv.Sim(label='sim2'), initialize=True) m3 = cv.MultiSim.merge(m1, m2) m3.run() m1b, m2b = m3.split() msim = cv.MultiSim(cv.Sim(), n_runs=6) msim.run() m1, m2 = msim.split(inds=[[0,2,4], [1,3,5]]) mlist1 = msim.split(chunks=[2,4]) # Equivalent to inds=[[0,1], [2,3,4,5]] mlist2 = msim.split(chunks=3) # Equivalent to inds=[[0,1,2], [3,4,5]]
''' Illustrate different ways of printing a sim. ''' import sciris as sc import covasim as cv sim = cv.Sim(label='sim1', verbose=0) sim.run() sc.heading('print(sim)') print(sim) sc.heading('sim.summarize()') sim.summarize() sc.heading('sim.brief()') sim.brief() sc.heading('msim.summarize()') msim = cv.MultiSim(sim, verbose=0) msim.run(reduce=True) msim.summarize()
''' Test that parallel and serial MultiSims give the same results ''' import numpy as np import covasim as cv m1 = cv.MultiSim(cv.Sim()) m1.run() m1.reduce() m2 = cv.MultiSim(cv.Sim()) m2.run(parallel=False) m2.reduce() assert np.all( m1.results['cum_infections'].values == m2.results['cum_infections'].values) m1.plot(plot_sims=True) m2.plot(plot_sims=True)
pop_size=pop_size, load_pop=False, people=people, verbose=0.1) base_sim['interventions'] = [] # Remove all interventions #%% Run the sims sims = [] for key, scen in all_scens.items(): for seed in range(n_seeds): sim = sc.dcp(base_sim) sim.set_seed(seed=sim['rand_seed'] + seed) sim.label = key sim['interventions'] += [cvsch.schools_manager(scen)] sims.append(sim) msim_raw = cv.MultiSim(sims) msim_raw.run() msims = msim_raw.split(chunks=[n_seeds] * (len(sims) // n_seeds)) msims = list(msims) res = sc.odict() for msim in msims: msim.reduce() base = msim.base_sim sc.heading(base.label) print(base.school_results) res[base.label] = base.school_results #%% Plotting sc.heading('Plotting...') if do_plot: msim_base = cv.MultiSim.merge(msims, base=True)
######################################################################## if __name__ == '__main__': #betas = [i / 10000 for i in range(72, 77, 1)] # Quick calibration if whattorun == 'quickfit': s0 = make_sim(seed=1, beta=0.0077, end_day=data_end, verbose=0.1) sims = [] for seed in range(6): sim = s0.copy() sim['rand_seed'] = seed sim.set_seed() sim.label = f"Sim {seed}" sims.append(sim) msim = cv.MultiSim(sims) msim.run() msim.reduce() if do_plot: msim.plot(to_plot=to_plot, do_save=True, do_show=False, fig_path=f'uk.png', legend_args={'loc': 'upper left'}, axis_args={'hspace': 0.4}, interval=50, n_cols=2) # Full parameter/seed search elif whattorun == 'fullfit': fitsummary = []
pars = sc.objdict( pop_size=pop_size, pop_infected=pop_infected // pop_scale, pop_scale=pop_scale, pop_type=pop_type, start_day=start_day, n_days=n_days, asymp_factor=1.9, beta=beta, contacts=cons, ) # Create the baseline simulation sim = cv.Sim(pars=pars, datafile=data_path, popfile=pop_path, location='uk') msim = cv.MultiSim(base_sim=sim) # Create using your existing sim as the base # Interventions #opening and closing schools intervention changing the h,s,w,c values and ti_start to #account for changes in Table 1 in the ms #baseline scenario # Create the baseline simulation #interventions = [] #intervention of some testing (tc) starts on 19th March and we run until 1st April when it increases tc_start = '2020-03-16' tc_day = (sc.readdate(tc_start) - start_day).days #intervention of some testing (te) starts on 1st April and we run until 1st May when it increases te_start = '2020-04-01'
pl.figure() pl.plot(self.tvec, self.exposed) 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.MultiSim([orig_sim, sim]) msim.run() msim.plot() # Plot intervention protect = msim.sims[1].get_intervention(protect_elderly) # Find intervention by type protect.plot()
if __name__ == '__main__': T = sc.tic() use_multisim = 1 use_safegraph = 1 # Settings reps = 5 # Set multiple runs to average over likelihood base_sim = create_sim(use_safegraph=use_safegraph) # Plot calibration if use_multisim: msim = cv.MultiSim(base_sim, n_runs=reps) msim.run(reseed=True, noise=0.0, keep_people=True, par_args={'ncpus': 5}) sims = msim.sims msim.plot(to_plot='overview', plot_sims=True) msim.reduce() sim = msim.base_sim else: sim = base_sim sim.run() sims = [sim] # Do plotting sim, fit = run_sim(sim=sim, use_safegraph=use_safegraph, interactive=True)
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 to_plot = ['cum_diagnoses', 'new_diagnoses', 'cum_deaths', 'new_deaths'] fig_args = dict(figsize=(18, 18)) scatter_args = dict(alpha=0.3, marker='o') dateformat = '%d %b'
''' Illustrate different Numba options ''' import covasim as cv # Create a standard 32-bit simulation sim32 = cv.Sim(label='32-bit, single-threaded (default)', verbose='brief') sim32.run() # Use 64-bit instead of 32 cv.options.set(precision=64) sim64 = cv.Sim(label='64-bit, single-threaded', verbose='brief') sim64.run() # Use parallel threading cv.options.set(numba_parallel=True) sim_par = cv.Sim(label='64-bit, multi-threaded', verbose='brief') sim_par.run() # Reset to defaults cv.options.set('defaults') sim32b = cv.Sim(label='32-bit, single-threaded (restored)', verbose='brief') sim32b.run() # Plot msim = cv.MultiSim([sim32, sim64, sim_par, sim32b]) msim.plot()
######################################################################## if __name__ == '__main__': #betas = [i / 10000 for i in range(72, 77, 1)] # Quick calibration if whattorun == 'quickfit': s0 = make_sim(seed=1, beta=0.008, end_day='2021-06-20', verbose=0.1) sims = [] for seed in range(4): sim = s0.copy() sim['rand_seed'] = seed sim.set_seed() sim.label = f"Sim {seed}" sims.append(sim) msim = cv.MultiSim(sims) msim.run() #msim.reduce() msim.reduce(quantiles=[0.25, 0.75]) #sim.to_excel('my-sim.xlsx') if do_plot: msim.plot(to_plot=to_plot, do_save=True, do_show=False, fig_path=f'uk.png', legend_args={'loc': 'upper left'}, axis_args={'hspace': 0.4}, interval=60, n_cols=2) msim.plot('strains', do_save=True,
sim.label = f'{skey} + {tkey}' sim.key1 = skey sim.key2 = tkey sim.scen = this_scen sim.tscen = test sim.dynamic_par = par sims.append(sim) proc += 1 if len( sims ) == batch_size or proc == tot: # or (tidx == len(testing)-1 and eidx == len(par_list)-1): print( f'Running sims {proc-len(sims)}-{proc-1} of {tot}') msim = cv.MultiSim(sims) msims.append(msim) msim.run(reseed=False, par_args={'ncpus': 16}, noise=0.0, keep_people=False) sims = [] print(f'*** Saving after completing {skey}') sims_this_scenario = [ s for msim in msims for s in msim.sims if s.key1 == skey ] msim = cv.MultiSim(sims_this_scenario) msim = cv.MultiSim.merge(msims) msim.save(os.path.join(folder, 'msims', f'{stem}.msim'),
#%% for seed in [2, 3, 4, 6, 8, 9, 10, 16, 20, 25, 27, 33, 37, 39, 43, 44, 50, 58]: print(str('Sim') + str(seed) + str('; ratio=') + str('1.8')) sim = create_sim(seed=seed, ratio=1.8) sim.run() sims5.append(sim) #%% for seed in [2, 3, 4, 6, 8, 9, 10, 16, 20, 25, 27, 33, 37, 39, 43, 44, 50, 58]: print(str('Sim') + str(seed) + str('; ratio=') + str('1.9')) sim = create_sim(seed=seed, ratio=1.9) sim.run() sims6.append(sim) #%% msim1 = cv.MultiSim(sims1) msim1.reduce() msim1.plot(to_plot=['new_infections'], do_show=False, legend_args={'loc': 'best'}, axis_args={'hspace': 0.4}, interval=50, n_cols=1) pl.axvline(sim.day('2020-12-14'), linestyle='--') pl.text(sim.day('2020-12-14') + 2, 7600, 'Introduction of B.1.1.7') pl.title('Ratio = 1.4: Number of new infections') msim1.plot(to_plot=['cum_infections'], do_show=False, legend_args={'loc': 'upper left'}, axis_args={'hspace': 0.4}, interval=50,
v1 = cv.vaccine(days=20, prob=1.0, rel_sus=1.0, rel_symp=0.0) # Prevent symptoms but not transmission v2 = cv.vaccine(days=50, prob=1.0, rel_sus=0.0, rel_symp=0.0) # Prevent both sim = cv.Sim(interventions=[v1, v2]) sim.run() sim.plot() # Age targeting def target_over_65(sim, prob=1.0): ''' Subtarget ''' inds = sc.findinds(sim.people.age > 65) vals = prob * np.ones(len(inds)) return {'inds': inds, 'vals': vals} v3 = cv.vaccine(days=20, prob=0.0, rel_sus=0.5, rel_symp=0.2, subtarget=target_over_65) # Age targeting sim2 = cv.Sim(label='Status quo', n_days=180) sim3 = cv.Sim(label='Vaccinate over 65s', n_days=180, interventions=v3) msim = cv.MultiSim([sim2, sim3]) msim.run() msim.plot() sim4 = cv.Sim(interventions=cv.vaccine( days=[10, 20, 30, 40], prob=0.8, rel_sus=0.5, cumulative=[1, 0.5, 0.5, 0])) sim4.run() sim4.plot()