def test_reproducibility(): sc.heading('Test that sims are reproducible') fn = 'save-load-test.sim' # Name of the test file to save #The results of the sim shouldn't be affected by what you do or don't do prior to sim.run() s1 = cv.Sim(pars) s1.initialize() s2 = s1.copy() s1.run() s2.run() r1ci = s1.summary['cum_infections'] r2ci = s2.summary['cum_infections'] assert r1ci == r2ci # If you run a sim and save it, you should be able to re-run it on load s3 = cv.Sim(pars) s3.run() s3.save(fn) s4 = cv.load(fn) s4.initialize() s4.run() r3ci = s3.summary['cum_infections'] r4ci = s4.summary['cum_infections'] assert r3ci == r4ci if os.path.exists( fn): # Tidy up -- after the assert to allow inspection if it fails os.remove(fn) return s4
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 run_sim(index, scenpars=None, label=None, runinfo=None, do_shrink=True, from_cache=True, verbose=True): ''' Load, modify, and run the simulation ''' if scenpars is None: print('WARNING, loading default parameters!') scenpars = sc.dcp(d_pars) if label is None: label = f'full_sim_trial{index}_nolabel' # Run sim or load up until scenarios start sim_loaded = 0 filename = f'./simcache/projection_trial{index}.sim' if from_cache and os.path.exists(filename): tries = 0 while not sim_loaded and tries < 3: try: print(f'run_sim(): Loading sim from cache ({filename})...') sim = cv.load(filename) assert isinstance( sim, cv.Sim ) # Sometimes unpickling fails, but can reload locally tn = sim.get_interventions('tn') tn.subtarget = test_num_subtarg sim_loaded = 1 except Exception as E: print(f'Loading failed on try {tries}! {E}') string = '\n\n'.join([ f'Index {index}', filename, f'Try {tries}', str(E), sc.traceback() ]) fn = f'simcache_exception_index{index}_try{tries}.err' sc.savetext(fn, string) tries += 1 sc.timedsleep(0.5) if not sim_loaded: print(f'run_sim(): Creating new sim (and saving to {filename})...') sim = create_sim(index, verbose=verbose) sim.run(until=sim.sceninfo.calib_end) sim.save(filename, keep_people=True) # Modify the sim with these scenario values sim = modify_sim(sim, scenpars=scenpars, label=label, runinfo=runinfo) # Rerun till the end and optionally shrink sim.run(restore_pars=False) # So we can see the changes made if do_shrink: sim.shrink() return sim sc.toc(T)
def test_regression(): sc.heading('Testing regression...') sim1 = cv.load(filename) sim2 = make_sim() # Check that they match cv.diff_sims(sim1, sim2, skip_key_diffs=True, die=True) # Confirm that non-matching sims don't match sim3 = make_sim(beta=0.02123) with pytest.raises(ValueError): cv.diff_sims(sim1, sim3, skip_key_diffs=True, die=True) return sim1, sim2
def test_reproducibility(): sc.heading('Test that sims are reproducible') fn = 'save-load-test.sim' # Name of the test file to save key = 'cum_infections' #The results of the sim shouldn't be affected by what you do or don't do prior to sim.run() s1 = cv.Sim(pars) s1.initialize() s2 = s1.copy() s1.run() s2.run() r1 = s1.summary[key] r2 = s2.summary[key] assert r1 == r2 # If you run a sim and save it, you should be able to re-run it on load s3 = cv.Sim(pars, pop_infected=44) s3.run() s3.save(fn) s4 = cv.load(fn) s4.initialize() s4.run() r3 = s3.summary[key] r4 = s4.summary[key] assert r3 == r4 if os.path.exists( fn): # Tidy up -- after the assert to allow inspection if it fails os.remove(fn) # Running a sim and resetting people should result in the same result; otherwise they should differ s5 = cv.Sim(pars) s5.run() r5 = s5.summary[key] s5.initialize(reset=True) s5.run() r6 = s5.summary[key] s5.initialize(reset=False) with pytest.raises(cv.AlreadyRunError): s5.run() s5.people.t = s5.t # Manually reset s5.run() r7 = s5.summary[key] assert r5 == r6 assert r5 != r7 return s4
do_save = 0 do_show = 1 verbose = 0 fig_path = 'ttq_fig4.png' dffile1 = 'sensitivity_scenarios_sep28_final.df' dffile2 = 'reopening_sweeps_sep28_final.df' T = sc.tic() # Figure configuration figw, figh = 24, 20 pl.rcParams['font.size'] = 20 # Set general figure options #%% Top row: scatter plots print('Calculating slopes...') df1 = cv.load(dffile1) ykey = ['cum_infections', 'r_eff'][0] # r_eff just for debugging logy = ykey in ['cum_infections'] # Boolean for what to do with y kcpop = 2.25e6 # Process baseline sims f = rs.get_f_a() fkeys = list(f.keys()) baseinds = np.arange(len(df1)) for k in fkeys: naninds = sc.findinds(np.isnan(df1[k].values)) baseinds = np.intersect1d(baseinds, naninds) df1map = sc.objdict( iqfactor='Isolation/quarantine effectiveness',
# General settings do_save = 0 do_show = 1 fig_path = 'ttq_fig2.png' simfile = 'fig2.sim' # File to load -- produced by fig2_run.py T = sc.tic() # Set general figure options wf = 2 # Make web fonts smaller pl.rcParams['font.size'] = 20 pieargs = dict(startangle=90, counterclock=False, labeldistance=1.25) # Load the sim print('Loading data... (takes ~5 s)') sim = cv.load(simfile) tt = sim.results.transtree # Make the plots def plot(): fig = pl.figure(num='Fig. 2: Transmission dynamics', figsize=(20,14)) piey, tsy, r3y = 0.68, 0.50, 0.07 piedx, tsdx, r3dx = 0.2, 0.9, 0.25 piedy, tsdy, r3dy = 0.2, 0.47, 0.35 pie1x, pie2x = 0.12, 0.65 tsx = 0.07 dispx, cumx, sympx = tsx, 0.33+tsx, 0.66+tsx ts_ax = pl.axes([tsx, tsy, tsdx, tsdy]) pie_ax1 = pl.axes([pie1x, piey, piedx, piedy]) pie_ax2 = pl.axes([pie2x, piey, piedx, piedy]) symp_ax = pl.axes([sympx, r3y, r3dx, r3dy])
print(f'Original parameters for index {index}:') json = sc.loadjson(jsonfile) entry = json[index] sc.pp(entry) pars = entry['pars'] pars['rand_seed'] = int(entry['index']) + 0 # To run with a different seed # Adjust for the larger population pars['pop_size'] = 2.25e6 # Reset for the full population pars[ 'beta'] *= 0.99 # Adjust the calibration slightly for the larger population pars['verbose'] = verbose print('Loading population file...') with sc.Timer(): people = cv.load(pplfile) print('Creating sim...') with sc.Timer(): sim = cs.create_sim(pars=pars, people=people, use_safegraph=sg) print('Running sim...') with sc.Timer(): sim, fit = cs.run_sim(sim=sim, use_safegraph=sg, interactive=do_plot) print('Analyzing sim...') with sc.Timer(): sim.make_transtree(output=False) if do_save: print('Saving sim...')
verbose = 0 fig_path = 'ttq_fig3_sep25.png' tt_filename = 'fig3_transtrees.obj' pl.rcParams['font.size'] = 20 # Set general figure options T = sc.tic() # Configure right hand side betadict = dict(best=0.018, low=0.014, high=0.022) scenkeys = ['beta', 'test', 'trace'] n_seeds = 10 simsfile = 'fig3.sims' print('Loading data...') sims = sc.objdict() simsobj = cv.load(simsfile) for sim in simsobj: sims[sim.label] = sim #%% Left hand side: transmission trees p,s,t = cv.load(tt_filename) # Load saved data a = sc.objdict() def plot(): fig = pl.figure(num='Fig. 3: Theoretical TTQ', figsize=(24,14)) euclid = False ay0 = 0.06 adx = 0.2
pop_scale = 10, rescale = True, ) tn = cv.test_num(start_day=10, daily_tests=2000, symp_test=100) tp = cv.test_prob(start_day=10, symp_prob=0.1, asymp_prob=0.01) ct = cv.contact_tracing(start_day=20, trace_probs={k:0.5 for k in 'hswc'}) # Run for label,ti in {'test_num':tn, 'test_prob':tp}.items(): ver = cv.__version__ sim = cv.Sim(pars, interventions=sc.dcp([ti, ct]), label=f'Version {ver}, {label}') m1 = cv.MultiSim(sim) m1.run(n_runs=n_runs) m1.reduce() old_fn = f'intervention_regression_{label}_1.6.1.msim' if ver == vers.old: m1.save(filename=old_fn) print(f'Multisim saved as {old_fn}') elif ver == vers.new: m0 = cv.load(old_fn) msim = cv.MultiSim.merge([m0, m1], base=True) fig = msim.plot(to_plot='overview') cv.maximize() else: raise NotImplementedError(f'You have asked to compare versions {vers.old} and {vers.new}, but Covasim is version {ver}')
def test_misc(): sc.heading('Testing miscellaneous functions') sim_path = 'test_misc.sim' json_path = 'test_misc.json' gitinfo_path = 'test_misc.gitinfo' fig_path = 'test_misc.png' fig_comments = 'Test comment' # Data loading cv.load_data(csv_file) cv.load_data(xlsx_file) with pytest.raises(NotImplementedError): cv.load_data('example_data.unsupported_extension') with pytest.raises(ValueError): cv.load_data(xlsx_file, columns=['missing_column']) # Dates d1 = cv.date('2020-04-04') d2 = cv.date(sc.readdate('2020-04-04')) ds = cv.date('2020-04-04', d2) assert d1 == d2 assert d2 == ds[0] with pytest.raises(ValueError): cv.date([(2020, 4, 4)]) # Raises a TypeError which raises a ValueError with pytest.raises(ValueError): cv.date('Not a date') cv.daydiff('2020-04-04') # Run sim for more investigations sim = cv.Sim(pop_size=500, verbose=0) sim.run() sim.plot(do_show=False) # Saving and loading cv.savefig(fig_path, comments=fig_comments) cv.save(filename=sim_path, obj=sim) cv.load(filename=sim_path) # Version checks cv.check_version('0.0.0') # Nonsense version print('↑ Should complain about version') with pytest.raises(ValueError): cv.check_version('0.0.0', die=True) # Git checks cv.git_info(json_path) cv.git_info(json_path, check=True) # Poisson tests c1 = 5 c2 = 8 for alternative in ['two-sided', 'larger', 'smaller']: cv.poisson_test(c1, c2, alternative=alternative) for method in ['score', 'wald', 'sqrt', 'exact-cond']: cv.poisson_test(c1, c2, method=method) with pytest.raises(ValueError): cv.poisson_test(c1, c2, method='not a method') # Test locations for location in [None, 'viet-nam']: cv.data.show_locations(location) # Test versions with pytest.raises(ValueError): cv.check_save_version('1.3.2', die=True) cv.check_save_version(cv.__version__, filename=gitinfo_path, comments='Test') # Test PNG try: metadata = cv.get_png_metadata(fig_path, output=True) assert metadata['Covasim version'] == cv.__version__ assert metadata['Covasim comments'] == fig_comments except ImportError as E: print( f'Cannot test PNG function since pillow not installed ({str(E)}), skipping' ) # Tidy up remove_files(sim_path, json_path, fig_path, gitinfo_path) return
fns = [ f'{base}_baseline.msim', f'{base}_lower_sens_spec.msim', f'{base}_no_NPI_reduction.msim', f'{base}_lower_random_screening.msim', f'{base}_no_screening.msim', f'{base}_lower_coverage.msim', f'{base}_alt_symp.msim', f'{base}_children_equally_sus.msim', f'{base}_increased_mobility.msim', f'{base}_broken_bubbles.msim', ] fns = [os.path.join(folder, 'msims', fn) for fn in fns] sims = [] for fn in fns: print(f'Loading {fn}') ext = os.path.splitext(fn)[1] if ext == '.sims': sims += cv.load(fn) elif ext == '.msim': msim = cv.MultiSim.load(fn) sims += msim.sims else: print('ERROR') fn = os.path.join(folder, 'msims', f'{base}.msim') print(f'Saving to {fn}') cv.save(fn, sims)
import covasim as cv fn = 'tmp.sim' s1 = cv.Sim() s1.run() s2 = cv.Sim() s2.run(until=30) s2.save(fn) s3 = cv.load(fn) s3.run() assert s3.summary == s1.summary
def test_misc(): sc.heading('Testing miscellaneous functions') sim_path = 'test_misc.sim' json_path = 'test_misc.json' # Data loading cv.load_data(csv_file) cv.load_data(xlsx_file) with pytest.raises(NotImplementedError): cv.load_data('example_data.unsupported_extension') with pytest.raises(ValueError): cv.load_data(xlsx_file, columns=['missing_column']) # Dates d1 = cv.date('2020-04-04') d2 = cv.date(sc.readdate('2020-04-04')) ds = cv.date('2020-04-04', d2) assert d1 == d2 assert d2 == ds[0] with pytest.raises(ValueError): cv.date([(2020, 4, 4)]) # Raises a TypeError which raises a ValueError with pytest.raises(ValueError): cv.date('Not a date') cv.daydiff('2020-04-04') # Saving and loading sim = cv.Sim() cv.save(filename=sim_path, obj=sim) cv.load(filename=sim_path) # Version checks cv.check_version('0.0.0') # Nonsense version print('↑ Should complain about version') with pytest.raises(ValueError): cv.check_version('0.0.0', die=True) # Git checks cv.git_info(json_path) cv.git_info(json_path, check=True) # Poisson tests c1 = 5 c2 = 8 for alternative in ['two-sided', 'larger', 'smaller']: cv.poisson_test(c1, c2, alternative=alternative) for method in ['score', 'wald', 'sqrt', 'exact-cond']: cv.poisson_test(c1, c2, method=method) with pytest.raises(ValueError): cv.poisson_test(c1, c2, method='not a method') # Tidy up remove_files(sim_path, json_path) return
''' Demonstration of saving and resuming a partially-run sim ''' import covasim as cv sim_orig = cv.Sim(start_day='2020-04-01', end_day='2020-06-01', label='Load & save example') sim_orig.run(until='2020-05-01') sim_orig.save('my-half-finished-sim.sim') sim = cv.load('my-half-finished-sim.sim') sim['beta'] *= 0.3 sim.run() sim.plot(to_plot=['new_infections', 'n_infectious', 'cum_infections'])
result_dir = 'results_delay' files = os.listdir(result_dir) print(files) # load data df = {} for file in files: print(file) if len(df) == 0: df.update({'reff_apr19': []}) df.update({'reff_mar08': []}) df.update({'scenario': []}) df.update({'index': []}) scenario = file.split('.')[0] msim = cv.load(os.path.join(result_dir, file)) mar08 = msim.sims[0].day('2021-03-08') apr30 = msim.sims[0].day('2021-04-19') for ix, sim in enumerate(msim.sims): df['reff_mar08'].append(sim.results['r_eff'].values[mar08]) df['reff_apr19'].append(sim.results['r_eff'].values[mar08:apr30 + 1].mean()) df['scenario'].append(scenario) df['index'].append(ix) df = pd.DataFrame(df) # make figure labs = { 'uk_sim_FNL': 'FNL', 'uk_sim_fullPNL': 'Full PNL', 'uk_sim_primaryPNL': 'Primary PNL',
] res = ['0.9'] cases = ['20', '50', '110'] es_by_scen = [] ms_by_scen = [] hs_by_scen = [] for re in res: for case in cases: es_with_a_case = [] ms_with_a_case = [] hs_with_a_case = [] for i, scen in enumerate(schools_reopening_scenarios): analysis_name = f'{scen}_{case}_cases_re_{re}' filename = f'msims/{analysis_name}.msim' msim = cv.load(filename) es = [] ms = [] hs = [] df = [] for j in range(len(msim.sims)): results = pd.DataFrame(msim.sims[j].results) df.append(results) num_es = msim.sims[j].school_info['num_es'] * msim.sims[j][ 'pop_scale'] num_ms = msim.sims[j].school_info['num_ms'] * msim.sims[j][ 'pop_scale'] num_hs = msim.sims[j].school_info['num_hs'] * msim.sims[j][ 'pop_scale'] es.append( pd.DataFrame(msim.sims[j].school_info['es_with_a_case']))
def findinds(df, *args): ''' Find matching indices in a large dataframe ''' inds = np.arange(len(df)) for arg in args: filterinds = sc.findinds(arg) inds = np.intersect1d(inds, filterinds) return inds if __name__ == '__main__': if regenerate: print('Loading...') msim = cv.load(msimfile) print('Processing...') data = [] for sim in msim.sims: info = splitlabel(sim.label) pars = get_params(sim.pars) results = get_results(sim.results) data.append(sc.mergedicts(info, pars, results)) df = pd.DataFrame(data) cv.save(dffile, df) else: print('Reloading...') df = cv.load(dffile)
for k in keys: q1 = 0.025 q2 = 0.975 sgb = np.median(df1[k]) sgl = np.quantile(df1[k], q1) sgh = np.quantile(df1[k], q2) nsgb = np.median(df2[k]) nsgl = np.quantile(df2[k], q1) nsgh = np.quantile(df2[k], q2) print( f'{k:8s}: SG={sgb:5.2f} ({sgl:5.2f}, {sgh:5.2f}) NSG={nsgb:5.2f} ({nsgl:5.2f}, {nsgh:5.2f})' ) #%% Do the actual plotting sims = cv.load(simsfile) base_sim = sims[0] # For having a sim to refer to def plot(): # Create the figure fig = pl.figure(num='Fig. 1: Calibration', figsize=(24, 20)) tx1, ty1 = 0.005, 0.97 tx2, ty2 = 0.545, 0.66 ty3 = 0.34 fsize = 40 pl.figtext(tx1, ty1, 'a', fontsize=fsize) pl.figtext(tx1, ty2, 'b', fontsize=fsize) pl.figtext(tx2, ty1, 'c', fontsize=fsize) pl.figtext(tx2, ty2, 'd', fontsize=fsize)
version = int(sys.argv[1]) pars = dict( pop_size=100000, # Number of nodes pop_type= 'hybrid', # Hybrid population: household, school, work, community layer location='Seattle', # Location and demographic based on Seattle # pop_infected = 100, start_day='2020-01-01', # Simulation start end_day='2020-04-30' # Simulation end ) # sim = cv.Sim(pars) # sim.run(until='2020-01-30') # Let it run for the first 30 days # sim.save('Seattle100kV' + str(version) + '.sim') # Save the sim sim = cv.load('Seattle100kV' + str(version) + '.sim') # Load the sim G = nx.DiGraph( ) # Directed graph because for all (p1, p2) there exists an edge from p1 -> p2 and from p2 -> p1 G.add_nodes_from(sim.people.uid) layers = ['h', 's', 'c', 'w'] for layer in layers: contacts = sim.people.contacts[layer] for i in range(len(contacts)): p1 = contacts['p1'][i] # Source p2 = contacts['p2'][i] # Destination # For the weight on p1 -> p2
do_show = 1 fig_path = 'ttq_fig5.png' pl.rcParams['font.size'] = 20 # Set general figure options T = sc.tic() # Load data print('Loading data...') msimsfile = 'fig5.msims' tsfn = './kc_data/20200614chop5_KingCounty_Covasim_extended.xlsx' # Time series data ctfn = './kc_data/contact_tracing.xlsx' # Contact tracing tsdf = pd.read_excel(tsfn, engine='openpyxl') ctdf = pd.read_excel(ctfn, sheet_name='final', engine='openpyxl') ctdf['date'] = pd.to_datetime(ctdf['date']).dt.date tsdf['date'] = pd.to_datetime(tsdf['date']).dt.date msims = cv.load(msimsfile) refsim = msims[0].sims[0] # A reference simulation, any will do #%% Plot setup scargs = dict(color='k', marker='d', linestyle='none', alpha=0.5, markersize=10, lw=3) plargs = dict(lw=4) fillargs = dict(alpha=0.2) xlims1 = refsim.day('2020-06-01', '2020-08-31') xlims2 = refsim.day('2020-01-27', '2020-08-31') intervcolor = [1, 0.5, 0.05] # Was [0.1, 0.4, 0.1]
import pylab as pl import sciris as sc import covasim as cv import datetime as dt import matplotlib.ticker as ticker fn = 'uk-tti-movie.msim' nsims = 201 seeds = 10 plot_diagnostic = False plot_movie = True n_total = nsims * seeds T = sc.tic() msim = cv.load(fn) s0 = msim.sims[0] results = np.zeros((nsims, seeds, s0.npts)) count = -1 for i in range(nsims): for j in range(seeds): count += 1 vals = msim.sims[count].results['new_infections'].values results[i, j, :] = vals print('Plotting...') if plot_diagnostic: fig = pl.figure(figsize=(26, 18)) for i in range(nsims): pl.subplot(nsims // 2, 2, i + 1)
import covasim as cv simB = cv.load('Seattle100kV0.sim') sim0 = cv.load('Seattle100kV1.sim') # sim1 = cv.load('Seattle100kV2.sim') # sim2 = cv.load('Seattle100kV3.sim') # sim3 = cv.load('Seattle100kV4.sim') # sim4 = cv.load('6MarSeattle100k.sim') # sim5 = cv.load('13MarSeattle100k.sim') # sim6 = cv.load('Seattle100kV7.sim') # sim7 = cv.load('27MarSeattle100k.sim') # sim8 = cv.load('3AprSeattle100k.sim') # sim9 = cv.load('10AprSeattle100k.sim') # sim10 = cv.load('Seattle100kV11.sim') # sim11 = cv.load('24AprSeattle100k.sim') sim12 = cv.load('Seattle100kV13.sim') simB.label = 'Baseline' sim0.label = 'V0' # sim1.label = 'V1' # sim2.label = 'V2' # sim3.label = 'V3' # sim4.label = 'V4' # sim5.label = 'V5' # sim6.label = 'V6' # sim7.label = 'V7' # sim8.label = 'V8' # sim9.label = 'V9' # sim10.label = 'V10' # sim11.label = 'V11' sim12.label = 'V12'
import covasim as cv filename = 'all_scens.msims' msims = cv.load(filename) sim = msims[0].sims[0] sim.plot(to_plot='overview') tt = sim.make_transtree() tt.plot() print('Done')
# Returns a dict of node indices as key and their probability of getting vaccinated as values def vaccinateSeeds(sim, seeds): inds = sim.people.uid vals = np.zeros(len(sim.people)) # set of seeds chosen by PREEMPT to have a 100% probability of getting vaccinated for seed in seeds: vals[seed] = 1.0 output = dict(inds=inds, vals=vals) return output # Load the sim sim2 = cv.load('Seattle100kV' + str(version) + '.sim') if (choice == 0): seeds = generateSeeds(version) if (choice == 1): seeds = generateRandomSeeds(version) if (choice == 2): seeds = generateDegreeSeeds(version) # Define the vaccine and add it to the sim vaccine = cv.simple_vaccine(days=31 + (version * 7), rel_sus=0.0, rel_symp=0.02, subtarget=vaccinateSeeds(sim2, seeds)) vaccine.vaccinations = vaccine.subtarget['vals'].astype(int) vaccine.initialize(sim2)
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' fig = msim.plot(to_plot=to_plot, n_cols=1, fig_args=fig_args, scatter_args=scatter_args, dateformat=dateformat)
msim = cv.MultiSim(sims) msim.run() # msim.run(par_args={'n_cpus':24}) # Figure out the seeds that give a good fit mismatches = np.array( [sim.compute_fit().mismatch for sim in msim.sims]) threshold = np.quantile(mismatches, 0.01) # Take the best 1% goodseeds = [ i for i in range(len(mismatches)) if mismatches[i] < threshold ] cv.save(f'{resfolder}/goodseeds.obj', goodseeds) # Run calibration with best-fitting seeds and parameters elif whattorun == 'finalisefit': goodseeds = cv.load(f'{resfolder}/goodseeds.obj') s0 = make_sim(seed=1, end_day='2020-08-25', verbose=-1) sims = [] for seed in goodseeds: sim = s0.copy() sim['rand_seed'] = seed sim.set_seed() sim.label = f"Sim {seed}" sims.append(sim) msim = cv.MultiSim(sims) msim.run() if save_sim: msim.save(f'{resfolder}/uk_sim.obj') if do_plot: msim.reduce()
mplt.rcParams['font.size'] = font_size mplt.rcParams['font.family'] = font_style pop_size = 2.25e5 folder = 'v20201019' variant = 'sensitivity_v3' cachefn = os.path.join(folder, 'msims', f'{variant}.sims') debug_plot = False imgdir = os.path.join(folder, 'img_' + variant) Path(imgdir).mkdir(parents=True, exist_ok=True) print(f'loading {cachefn}') #sims = cv.MultiSim.load(cachefn).sims sims = cv.load(cachefn) #sims = cv.MultiSim.load(os.path.join(folder, 'msims','sensitivity_v2_alt_symp_0-30.msim')).sims #sims += cv.load(os.path.join(folder, 'msims','sensitivity_v2_0-30.sims')) results = [] byschool = [] groups = ['students', 'teachers', 'staff'] scen_names = sc.odict({ # key1 'as_normal': 'As Normal', 'with_countermeasures': 'Normal with\nCountermeasures', 'all_hybrid': 'Hybrid with\nCountermeasures', 'k5': 'K-5 In-Person\nOthers Remote', 'all_remote': 'All Remote', })
import covasim as cv import pylab as pl sdict = cv.load('sdict.obj') print(sdict['as_normal_20_cases_re_0.9'].results['cum_infections'][-1]) print(sdict['as_normal_110_cases_re_0.9'].results['cum_infections'][-1]) print(sdict['as_normal_20_cases_re_0.9'].school_info['num_student_cases']) print(sdict['as_normal_110_cases_re_0.9'].school_info['num_student_cases']) fig = pl.figure(figsize=(20, 12), dpi=150) schools_reopening_scenarios = [ 'as_normal', 'with_screening', 'with_hybrid_scheduling', 'ES_MS_inperson_HS_remote', 'ES_inperson_MS_HS_remote', 'ES_hybrid', 'all_remote', ] for i, scen in enumerate(schools_reopening_scenarios): ax = pl.subplot(4, 2, i + 1) colors = [ [0.1, 0.1, 0.9], [0.9, 0.1, 0.1], [0.1, 0.6, 0.9], [0.9, 0.6, 0.1], ] factor = 1