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_school_pop(do_plot=False):
    ''' Test basic population creation '''

    pop = cvsch.make_population(pop_size=20e3, rand_seed=1, do_save=False)

    if do_plot:
        pop.plot()

    return pop
          "pop_infected": 242.11186358945181,
          "change_beta": 0.5313884845187986,
          "symp_prob": 0.08250498122080606
        }
      }
    print(f'Warning: could not load calibration file "{calibfile}" due to "{str(E)}", using hard-coded parameters')
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 bypass and 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)

# Create the scenarios
divider = ' -- '
def joinkeys(skey, tkey):
    ''' Turn scenario and testing keys into a single key '''
    return divider.join([skey, tkey])

def splitkey(key):
    ''' Oppostite of joinkeys() '''
    return key.split(divider)

scens = generate_scenarios()
testings = generate_testing()
s_keys = list(scens.keys())
t_keys = list(testings.keys())
Example #5
0
'''
Pre-generate the synthpops population including school types. Takes ~102s per seed
'''

import psutil
import sciris as sc
import covasim_schools as cvsch

pop_size = 20e3
seeds = [0, 1, 2, 3, 4]
parallelize = True
# parallelize = False

if parallelize:
    ram = psutil.virtual_memory().available / 1e9
    required = 1 * len(seeds) * pop_size / 225e3  # 8 GB per 225e3 people
    if required < ram:
        print(
            f'You have {ram} GB of RAM, and this is estimated to require {required} GB: you should be fine'
        )
    else:
        print(
            f'You have {ram:0.2f} GB of RAM, but this is estimated to require {required} GB -- you are in trouble!!!!!!!!!'
        )
    sc.parallelize(cvsch.make_population,
                   kwargs={'pop_size': pop_size},
                   iterkwargs={'rand_seed': seeds})  # Run them in parallel
else:
    for seed in seeds:
        cvsch.make_population(pop_size=pop_size, rand_seed=seed)
Example #6
0
def create_sim(params=None, pop_size=2.25e5, rand_seed=1, folder=None, popfile_stem=None,
               children_equally_sus=False, alternate_symptomaticity=False, max_pop_seeds=5, load_pop=True, save_pop=False, people=None,
               label=None, verbose=0, **kwargs):
    '''
    Create the simulation for use with schools. This is the main function used to
    create the sim object.

    Args:
        params (dict): the parameters to use for the simulation
        pop_size (int): the number of people (merged into parameters)
        rand_seed (int): the random seed to use (merged into parameters)
        folder (str): where to look for the population file
        popfile_stem (str): filename of population file, minus random seed (which gets added)
        children_equally_sus (bool): whether children should be equally susceptible as adults (for sensitivity)
        alternate_symptomaticity (bool): whether to use symptoms by age from Table 1 in https://arxiv.org/pdf/2006.08471.pdf
        max_pop_seeds (int): maximum number of populations to generate (for use with different random seeds)
        load_pop (bool): whether to load people from disk (otherwise, use supplied or create afresh)
        save_pop (bool): if a population is being generated, whether to save
        people (People): if supplied, use instead of loading from file
        label (str): a name for the simulation
        verbose (float): level of verbosity to use (merged into parameters)
        kwargs (dict): merged with params

    Returns:
        A sim instance
    '''

    # Handle parameters and merge together different sets of defaults

    default_pars = dict(
        pop_size       = pop_size,
        pop_scale      = 1,
        pop_type       = 'synthpops',
        rescale        = False, # True causes problems
        verbose        = verbose,
        start_day      = '2020-09-01',
        end_day        = '2021-01-31',
        rand_seed      = rand_seed
    )

    p = sc.objdict(sc.mergedicts(default_pars, define_pars(which='best', kind='both'), params, kwargs)) # Get default parameter values


    #%% Define interventions
    symp_prob = p.pop('symp_prob')
    change_beta = p.pop('change_beta')

    tp_pars = dict(
        symp_prob = symp_prob, # 0.10
        asymp_prob = 0.0022,
        symp_quar_prob = symp_prob, # 0.10
        asymp_quar_prob = 0.001,
        test_delay = 2.0,
    )

    ct_pars = dict(
        trace_probs = {'w': 0.1, 'c': 0, 'h': 0.9, 's': 0.8}, # N.B. 's' will be ignored if using the Schools class
        trace_time  = {'w': 2,   'c': 0, 'h': 1,   's': 2},
    )

    cb_pars = dict(
        changes=change_beta,
        layers=['w', 'c'],
        label='NPI_work_community',
    )

    ce_pars = dict(
        changes=0.65,
        layers=['w', 'c'],
        label='close_work_community'
    )

    interventions = [
        cv.test_prob(start_day=p.start_day, **tp_pars),
        cv.contact_tracing(start_day=p.start_day, **ct_pars),
        cv.change_beta(days=p.start_day, **cb_pars),
        cv.clip_edges(days=p.start_day, **ce_pars),
        # N.B. Schools are not closed in create_sim, must be handled outside this function
    ]
    for interv in interventions:
        interv.do_plot = False


    #%% Handle population -- NB, although called popfile, might be a People object
    if load_pop: # Load from disk -- normal usage
        if popfile_stem is None:
            popfile_stem = os.path.join('inputs', f'kc_synthpops_clustered_{int(pop_size)}_withstaff_seed')
        if folder is not None:
            popfile_stem = os.path.join(folder, popfile_stem) # Prepend user folder
        pop_seed = p.rand_seed % max_pop_seeds
        popfile = popfile_stem + str(pop_seed) + '.ppl'
        print(f'Note: loading population from {popfile}')
    elif people is not None: # People is supplied; use that
        popfile = people
        print('Note: using supplied people')
    else: # Generate
        print('Note: population not supplied; regenerating...')
        popfile = cvsch.make_population(pop_size=p.pop_size, rand_seed=p.rand_seed, max_pop_seeds=max_pop_seeds, do_save=False)

    # Create sim
    sim = cv.Sim(p, popfile=popfile, load_pop=True, label=label, interventions=interventions)

    # Modify sim
    if children_equally_sus:
        prog = sim.pars['prognoses']
        ages = prog['age_cutoffs']
        sus_ORs = prog['sus_ORs']
        sus_ORs[ages<=20] = 1
        prog['sus_ORs'] = sus_ORs

    if alternate_symptomaticity:
        prog = sim.pars['prognoses']
        ages = prog['age_cutoffs']
        symp_probs = prog['symp_probs']
        # Source: table 1 from https://arxiv.org/pdf/2006.08471.pdf
        symp_probs[:] = 0.6456
        symp_probs[ages<80] = 0.3546
        symp_probs[ages<60] = 0.3054
        symp_probs[ages<40] = 0.2241
        symp_probs[ages<20] = 0.1809
        prog['symp_probs'] = symp_probs

    return sim