Exemplo n.º 1
0
def parse_interventions(int_pars):
    '''
    Parse interventions. Format

    Args:
        int_pars = {
            'social_distance': [
                {'start': 1,  'end': 19, 'level': 'aggressive'},
                {'start': 20, 'end': 30, 'level': 'mild'},
                ],
            'school_closures': [
                {'start': 12, 'end': 14}
                ],
            'symptomatic_testing': [
                {'start': 8, 'end': 25, 'level': 60}
                ]}

    '''
    intervs = []

    if int_pars is not None:
        masterlist = []
        for ikey,intervlist in int_pars.items():
            for iconfig in intervlist:
                iconfig['ikey'] = ikey
                masterlist.append(dict(iconfig))

        for iconfig in masterlist:
            ikey  = iconfig['ikey']
            start = iconfig['start']
            end   = iconfig['end']
            if ikey == 'social_distance':
                level = iconfig['level']
                mapping = {
                    'mild': 0.8,
                    'moderate': 0.5,
                    'aggressive': 0.2,
                    }
                change = mapping[level]
                interv = cv.change_beta(days=[start, end], changes=[change, 1.0])
            elif ikey == 'school_closures':
                change = 0.7
                interv = cv.change_beta(days=[start, end], changes=[change, 1.0], layers='a')
            elif ikey == 'symptomatic_testing':
                level = iconfig['level']
                level = float(level)/100
                asymp_prob = 0.0
                delay = 0.0
                interv = cv.test_prob(start_day=start, end_day=end, symp_prob=level, asymp_prob=asymp_prob, test_delay=delay)
            elif ikey == 'contact_tracing':
                trace_prob = {'a':1.0}
                trace_time = {'a':0.0}
                interv = cv.contact_tracing(start_day=start, end_day=end, trace_probs=trace_prob, trace_time=trace_time)
            else:
                raise NotImplementedError

            intervs.append(interv)

    return intervs
Exemplo n.º 2
0
def test_beta_edges(do_plot=False, do_show=True, do_save=False, fig_path=None):

    pars = dict(
        pop_size=1000,
        pop_infected=20,
        pop_type='hybrid',
    )

    start_day = 25  # Day to start the intervention
    end_day = 40  # Day to end the intervention
    change = 0.3  # Amount of change

    sims = sc.objdict()
    sims.b = cv.Sim(pars)  # Beta intervention
    sims.e = cv.Sim(pars)  # Edges intervention

    beta_interv = cv.change_beta(days=[start_day, end_day],
                                 changes=[change, 1.0])
    edge_interv = cv.clip_edges(start_day=start_day,
                                end_day=end_day,
                                change=change,
                                verbose=True)
    sims.b.update_pars(interventions=beta_interv)
    sims.e.update_pars(interventions=edge_interv)

    for sim in sims.values():
        sim.run()
        if do_plot:
            sim.plot(do_save=do_save, do_show=do_show, fig_path=fig_path)
            sim.plot_result('r_eff')

    return sims
Exemplo n.º 3
0
def make_sim(use_defaults=False, do_plot=False):
    '''
    Define a default simulation for testing the baseline -- use hybrid and include
    interventions to increase coverage. If run directly (not via pytest), also
    plot the sim by default.
    '''

    # Define the parameters
    intervs = [
        cv.change_beta(days=40, changes=0.5),
        cv.test_prob(start_day=20, symp_prob=0.1, asymp_prob=0.01)
    ]  # Common interventions
    pars = dict(
        pop_size=20000,  # Population size
        pop_infected=
        100,  # Number of initial infections -- use more for increased robustness
        pop_type=
        'hybrid',  # Population to use -- "hybrid" is random with household, school,and work structure
        verbose=0,  # Don't print details of the run
        interventions=intervs  # Include the most common interventions
    )

    # Create the sim
    if use_defaults:
        sim = cv.Sim()
    else:
        sim = cv.Sim(pars)

    # Optionally plot
    if do_plot:
        s2 = sim.copy()
        s2.run()
        s2.plot()

    return sim
Exemplo n.º 4
0
 def intervention_set_changebeta(self,
                                 days_array,
                                 multiplier_array,
                                 layers=None):
     self.interventions = cv.change_beta(days=days_array,
                                         changes=multiplier_array,
                                         layers=layers)
Exemplo n.º 5
0
    def test_no_infected(self):
        SIM_PARAMS2 = {
            'pop_size': 10e3,
            'pop_type': 'synthpops',
            'pop_infected': 0,
            'verbose': 1,
            'start_day': '2020-08-01',
            'end_day': '2020-09-01',
            'rand_seed': 0,
        }
        popfile = f'inputs/kc_synthpops_clustered_withstaff_10e3.ppl'

        sim = cv.Sim(SIM_PARAMS2, popfile=popfile, load_pop=True)

        interventions = [
            cv.close_schools(day_schools_closed='2020-08-01',
                             label='close_schools'),
            cv.reopen_schools(start_day='2020-08-01',
                              test=0.99,
                              ili_prev=0,
                              num_pos=None,
                              label='reopen_schools'),
            cv.change_beta(1, 0)
        ]

        sim['interventions'] = interventions

        sim.run()
        num_school_days_lost = sim.school_info['school_days_lost']
        num_student_school_days = sim.school_info['total_student_school_days']

        #assertinhg that all school days are lost
        self.assertEqual(num_school_days_lost, 0)
        self.assertGreater(num_student_school_days, 0)
Exemplo n.º 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]

        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
Exemplo n.º 7
0
    def test_change_beta_layers_clustered(self):
        # Define the interventions
        days = dict(h=30, s=35, w=40, c=45)
        interventions = []
        for key, day in days.items():
            interventions.append(
                cv.change_beta(days=day, changes=0, layers=key))

        # Create and run the sim
        sim = cv.Sim(pop_size=AGENT_COUNT,
                     pop_type='hybrid',
                     n_days=60,
                     interventions=interventions)
        sim.run()
        assert sim.results['new_infections'].values[days['c']:].sum() == 0
        return
Exemplo n.º 8
0
def bldEducLevelBeta(intrvList):
    '''convert list of (datestr,elev,endDate) into per-level beta changes
		return list of per-layer changes
	'''

    levIntrv = {}
    for idate, edate in intrvList:
        bdates = [idate, edate]
        for lev in ClosedSchoolBeta.keys():
            newBeta = ClosedSchoolBeta[lev]
            bvec = [newBeta, 1.0]
            levIntrv[lev] = cv.change_beta(days=bdates,
                                           changes=bvec,
                                           layers=lev)

    return [levIntrv[elayer] for elayer in levIntrv.keys()]
Exemplo n.º 9
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
Exemplo n.º 10
0
def make_sim(use_defaults=False, do_plot=False, **kwargs):
    '''
    Define a default simulation for testing the baseline -- use hybrid and include
    interventions to increase coverage. If run directly (not via pytest), also
    plot the sim by default.
    '''

    # Define the interventions
    tp = cv.test_prob(start_day=20, symp_prob=0.1, asymp_prob=0.01)
    vx = cv.vaccinate_prob('pfizer', days=30, prob=0.1)
    cb = cv.change_beta(days=40, changes=0.5)
    ct = cv.contact_tracing(trace_probs=0.3, start_day=50)

    # Define the parameters
    pars = dict(
        use_waning=True,  # Whether or not to use waning and NAb calculations
        pop_size=20e3,  # Population size
        pop_infected=
        100,  # Number of initial infections -- use more for increased robustness
        pop_type=
        'hybrid',  # Population to use -- "hybrid" is random with household, school,and work structure
        n_days=60,  # Number of days to simulate
        verbose=0,  # Don't print details of the run
        rand_seed=2,  # Set a non-default seed
        interventions=[cb, tp, ct,
                       vx],  # Include the most common interventions
    )
    pars = sc.mergedicts(pars, kwargs)

    # Create the sim
    if use_defaults:
        sim = cv.Sim()
    else:
        sim = cv.Sim(pars)

    # Optionally plot
    if do_plot:
        s2 = sim.copy()
        s2.run()
        s2.plot()

    return sim
Exemplo n.º 11
0
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
Exemplo n.º 12
0
def test_import2strains_changebeta(do_plot=False, do_show=True, do_save=False):
    sc.heading(
        'Test introducing 2 new strains partway through a sim, with a change_beta intervention'
    )

    strain2 = {'rel_beta': 1.5, 'rel_severe_prob': 1.3}

    strain3 = {'rel_beta': 2, 'rel_symp_prob': 1.6}

    intervs = cv.change_beta(days=[5, 20, 40], changes=[0.8, 0.7, 0.6])
    strains = [
        cv.strain(strain=strain2, days=10, n_imports=20),
        cv.strain(strain=strain3, days=30, n_imports=20),
    ]
    sim = cv.Sim(use_waning=True,
                 interventions=intervs,
                 strains=strains,
                 label='With imported infections',
                 **base_pars)
    sim.run()

    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
Exemplo n.º 14
0
# Community contacts reduction by 30% means 49% of normal during termtime and 42% during holidays from 24th Jul
# Schools contacts reduction by 30% means 63% of normal during termtime from 1st Sep
# masks in secondary schools from 1st September
if scenario == 'med_comp':
   
    h_beta_changes = [1.00, 1.00, 1.29, 1.29, 1.29, 1.00, 1.00, 1.29, 1.29, 1.00, 1.00, 1.00, 1.29, 1.00, 1.29, 1.00, 1.00, 1.29, 1.00]
    s_beta_changes = [1.00, 0.90, 0.02, 0.02, 0.02, 0.23, 0.38, 0.00, 0.00, 0.63, 0.63, 0.63, 0.00, 0.63, 0.00, 0.63, 0.63, 0.00, 0.63]
    #w_beta_changes = [0.90, 0.80, 0.20, 0.20, 0.20, 0.40, 0.50, 0.50, 0.50, 0.60, 0.50, 0.60, 0.50, 0.60]
    w_beta_changes = [0.90, 0.80, 0.20, 0.20, 0.20, 0.40, 0.40, 0.60, 0.60, 0.60, 0.60, 0.60, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50, 0.50]
    c_beta_changes = [0.90, 0.80, 0.20, 0.20, 0.20, 0.40, 0.50, 0.60, 0.60, 0.70, 0.70, 0.70, 0.60, 0.60, 0.50, 0.60, 0.60, 0.50, 0.50]

else:
    print(f'Scenario {scenario} not recognised')

# 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')

#next line to save the intervention
interventions = [h_beta, w_beta, s_beta, c_beta]


# to fit data in September better
#def more_young_infections(sim):
#if sim.t == sim.day('2020-08-01'):
#        sim.people.rel_trans[sim.people.age<30] *= 2
#interventions = [more_young_infections]
#sim = cv.Sim(interventions=more_young_infections)
beta_change_2 = {}
beta_change_2[
    's'] = 0.9  # Scenario 1: schools are reopened and contact there is 90%
beta_change_2[
    'w'] = 0.5  # some increase in contact at work after schools are reopened - decide what that value should be
beta_change_2[
    'c'] = 0.5  # some increase in contact in the community after schools are reopened - decide what that values should be
beta_change_2[
    'h'] = 1.0  #0.8  # with schools reopened household contact may go back to previous levels or even less if people are practicing better habits at home

interventions = []

for lkey, ch in beta_change_1.items():
    interventions.append(
        cv.change_beta(days=['2020-03-28'],
                       changes=beta_change_1[lkey],
                       layers=lkey,
                       label=f'beta_{lkey}'))

# create a list of the different age ranges in different school types
# for example, the order can be primary school ages, secondary school ages, and tertiary school ages
# each sublist will have two numbers: the youngest age in the school type, followed by the oldest age + 1 in the school type

school_type_ages = []
school_type_ages.append([6, 15
                         ])  # primary school ages range from 6 to 14 years old
school_type_ages.append(
    [15, 19])  # secondary school ages range from 15 to 18 years old
school_type_ages.append(
    [19, 23])  # tertiary school ages range from 19 to 22 years old

# define a dictionary with reopening school interventions on different days by the type of school: the key is the index for the school type and value is the day to restart those schools
Exemplo n.º 16
0
def make_sim(seed,
             beta,
             calibration=True,
             scenario=None,
             delta_beta=1.6,
             future_symp_test=None,
             end_day=None,
             verbose=0):

    # Set the parameters
    total_pop = 67.86e6  # UK population size
    pop_size = 100e3  # Actual simulated population
    pop_scale = int(total_pop / pop_size)
    pop_type = 'hybrid'
    pop_infected = 1500
    beta = beta
    asymp_factor = 2
    contacts = {'h': 3.0, 's': 20, 'w': 20, 'c': 20}
    beta_layer = {'h': 3.0, 's': 1.0, 'w': 0.6, 'c': 0.3}
    if end_day is None: end_day = '2021-03-31'

    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,
        contacts=contacts,
        rescale=True,
        rand_seed=seed,
        verbose=verbose,
        rel_severe_prob=0.4,
        rel_crit_prob=2.3,
        #rel_death_prob=1.5,
    )

    sim = cv.Sim(pars=pars, datafile=data_path, location='uk')
    sim['prognoses']['sus_ORs'][0] = 1.0  # ages 20-30
    sim['prognoses']['sus_ORs'][1] = 1.0  # ages 20-30

    # ADD BETA INTERVENTIONS
    sbv = 0.63
    beta_past = sc.odict({
        '2020-02-14': [1.00, 1.00, 0.90, 0.90],
        '2020-03-16': [1.00, 0.90, 0.80, 0.80],
        '2020-03-23': [1.29, 0.02, 0.20, 0.20],
        '2020-06-01': [1.00, 0.23, 0.40, 0.40],
        '2020-06-15': [1.00, 0.38, 0.50, 0.50],
        '2020-07-22': [1.29, 0.00, 0.30, 0.50],
        '2020-09-02': [1.25, sbv, 0.50, 0.70],
        '2020-10-01': [1.25, sbv, 0.50, 0.70],
        '2020-10-16': [1.25, sbv, 0.50, 0.70],
        '2020-10-26': [1.00, 0.00, 0.50, 0.70],
        '2020-11-05': [1.25, sbv, 0.30, 0.40],
        '2020-11-14': [1.25, sbv, 0.30, 0.40],
        '2020-11-21': [1.25, sbv, 0.30, 0.40],
        '2020-11-30': [1.25, sbv, 0.30, 0.40],
        '2020-12-03': [1.50, sbv, 0.50, 0.70],
        '2020-12-20': [1.25, 0.00, 0.50, 0.70],
        '2020-12-25': [1.50, 0.00, 0.20, 0.90],
        '2020-12-26': [1.50, 0.00, 0.20, 0.90],
        '2020-12-31': [1.50, 0.00, 0.20, 0.90],
        '2021-01-01': [1.50, 0.00, 0.20, 0.90],
        '2021-01-04': [1.25, 0.14, 0.30, 0.40],
        '2021-01-11': [1.25, 0.14, 0.30, 0.40],
        '2021-01-18': [1.25, 0.14, 0.30, 0.40],
        '2021-01-18': [1.25, 0.14, 0.30, 0.40]
    })

    if not calibration:
        ##no schools until 1st March but assue 20% (1 in 5) in schools between 04/01-22/02;
        ##model transmission remaining at schools as 14% (to account for 30% reduction due to school measures)
        if scenario == 'FNL':
            beta_s_feb22, beta_s_mar01, beta_s_mar08, beta_s_mar15, beta_s_mar22, beta_s_mar29, beta_s_apr01 = 0.14, 0.14, 0.14, 0.14, 0.14, 0.14, 0.02
        ##primaries and yars 11 and 13 back on 22/02 all other years 01/03
        ##9/14 years back -30% transmission reduction = 45% reduction remaining from 22/02
        ##transmision increases to 63% remaining from 01/03
        ##Easter holiday 01/04-08/04
        elif scenario == 'staggeredPNL':
            beta_s_feb22, beta_s_mar01, beta_s_mar08, beta_s_mar15, beta_s_mar22, beta_s_mar29, beta_s_apr01 = 0.14, 0.14, 0.40, sbv, sbv, sbv, 0.02,
        ##primaries and secondaries back fully 22/02; 14/14 years but assume 90% attendence and
        ##30% reduction in transmission due to hygiene, masks etc to remaining transmision to 0.63
        ##Easter holiday 01/04-08/04
        elif scenario == 'fullPNL':
            beta_s_feb22, beta_s_mar01, beta_s_mar08, beta_s_mar15, beta_s_mar22, beta_s_mar29, beta_s_apr01 = 0.14, 0.14, sbv, sbv, sbv, sbv, 0.02
        elif scenario == 'primaryPNL':
            beta_s_feb22, beta_s_mar01, beta_s_mar08, beta_s_mar15, beta_s_mar22, beta_s_mar29, beta_s_apr01 = 0.14, 0.14, 0.31, 0.31, 0.40, 0.40, 0.02
        elif scenario == 'rotasecondaryPNL':
            beta_s_feb22, beta_s_mar01, beta_s_mar08, beta_s_mar15, beta_s_mar22, beta_s_mar29, beta_s_apr01 = 0.14, 0.14, 0.31, 0.31, sbv, sbv, 0.02

        beta_scens = sc.odict({
            '2021-01-30': [1.25, 0.14, 0.30, 0.40],
            '2021-02-08': [1.25, 0.14, 0.30, 0.40],
            '2021-02-15': [1.25, 0.14, 0.30, 0.40],
            '2021-02-22': [1.25, beta_s_feb22, 0.30, 0.40],
            '2021-03-01': [1.25, beta_s_mar01, 0.30, 0.40],
            '2021-03-08': [1.25, beta_s_mar08, 0.30, 0.50],
            '2021-03-15': [1.25, beta_s_mar15, 0.30, 0.50],
            '2021-03-22': [1.25, beta_s_mar22, 0.30, 0.50],
            '2021-03-29': [1.25, beta_s_mar29, 0.30, 0.50],
            '2021-04-01': [1.25, beta_s_apr01, 0.30, 0.50],
            '2021-04-12': [1.25, 0.02, 0.30, 0.50],
            '2021-04-19': [1.25, sbv, 0.50, 0.70],
            '2021-04-26': [1.25, sbv, 0.50, 0.70],
            '2021-05-03': [1.25, sbv, 0.50, 0.70]
        })

        beta_dict = sc.mergedicts(beta_past, beta_scens)
    else:
        beta_dict = beta_past

    beta_days = list(beta_dict.keys())
    h_beta = cv.change_beta(days=beta_days,
                            changes=[c[0] for c in beta_dict.values()],
                            layers='h')
    s_beta = cv.change_beta(days=beta_days,
                            changes=[c[1] for c in beta_dict.values()],
                            layers='s')
    w_beta = cv.change_beta(days=beta_days,
                            changes=[c[2] for c in beta_dict.values()],
                            layers='w')
    c_beta = cv.change_beta(days=beta_days,
                            changes=[c[3] for c in beta_dict.values()],
                            layers='c')

    # Add a new change in beta to represent the takeover of the novel variant VOC 202012/01
    # Assume that the new variant is 60% more transmisible (https://cmmid.github.io/topics/covid19/uk-novel-variant.html,
    # Assume that between Nov 1 and Jan 30, the new variant grows from 0-100% of cases
    voc_days = np.linspace(sim.day('2020-08-01'), sim.day('2021-01-30'), 31)
    voc_prop = 0.6 / (
        1 + np.exp(-0.075 * (voc_days - sim.day('2020-09-30')))
    )  # Use a logistic growth function to approximate fig 2A of https://cmmid.github.io/topics/covid19/uk-novel-variant.html
    voc_change = voc_prop * 1.63 + (1 - voc_prop) * 1.
    voc_beta = cv.change_beta(days=voc_days, changes=voc_change)

    interventions = [h_beta, w_beta, s_beta, c_beta, voc_beta]

    # ADD TEST AND TRACE INTERVENTIONS
    tc_day = sim.day(
        '2020-03-16'
    )  #intervention of some testing (tc) starts on 16th March and we run until 1st April when it increases
    te_day = sim.day(
        '2020-04-01'
    )  #intervention of some testing (te) starts on 1st April and we run until 1st May when it increases
    tt_day = sim.day(
        '2020-05-01'
    )  #intervention of increased testing (tt) starts on 1st May
    tti_day = sim.day(
        '2020-06-01'
    )  #intervention of tracing and enhanced testing (tti) starts on 1st June
    tti_day_july = sim.day(
        '2020-07-01'
    )  #intervention of tracing and enhanced testing (tti) at different levels starts on 1st July
    tti_day_august = sim.day(
        '2020-08-01'
    )  #intervention of tracing and enhanced testing (tti) at different levels starts on 1st August
    tti_day_sep = sim.day('2020-09-01')
    tti_day_oct = sim.day('2020-10-01')
    tti_day_nov = sim.day('2020-11-01')
    tti_day_dec = sim.day('2020-12-01')
    tti_day_jan = sim.day('2021-01-01')
    tti_day_vac = sim.day('2020-12-20')

    s_prob_april = 0.009
    s_prob_may = 0.012
    s_prob_june = 0.02769
    s_prob_july = 0.02769
    s_prob_august = 0.03769
    tn = 0.09
    s_prob_sept = 0.08769
    s_prob_oct = 0.08769
    s_prob_nov = 0.08769
    s_prob_may = 0.02769
    s_prob_june = 0.02769
    s_prob_july = 0.02769
    s_prob_august = 0.03769
    s_prob_sep = 0.08769
    s_prob_oct = 0.08769
    s_prob_nov = 0.08769
    s_prob_dec = 0.08769

    if future_symp_test is None: future_symp_test = s_prob_dec
    t_delay = 1.0

    #isolation may-july
    iso_vals = [{k: 0.1 for k in 'hswc'}]
    #isolation august
    iso_vals1 = [{k: 0.7 for k in 'hswc'}]
    #isolation september
    iso_vals2 = [{k: 0.5 for k in 'hswc'}]
    #isolation october
    iso_vals3 = [{k: 0.5 for k in 'hswc'}]
    #isolation november
    iso_vals4 = [{k: 0.5 for k in 'hswc'}]
    #isolation december
    iso_vals5 = [{k: 0.5 for k in 'hswc'}]

    #testing and isolation intervention
    interventions += [
        cv.test_prob(symp_prob=0.0075,
                     asymp_prob=0.0,
                     symp_quar_prob=0.0,
                     start_day=tc_day,
                     end_day=te_day - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_april,
                     asymp_prob=0.0,
                     symp_quar_prob=0.0,
                     start_day=te_day,
                     end_day=tt_day - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_may,
                     asymp_prob=0.00076,
                     symp_quar_prob=0.0,
                     start_day=tt_day,
                     end_day=tti_day - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_june,
                     asymp_prob=0.00076,
                     symp_quar_prob=0.0,
                     start_day=tti_day,
                     end_day=tti_day_july - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_july,
                     asymp_prob=0.00076,
                     symp_quar_prob=0.0,
                     start_day=tti_day_july,
                     end_day=tti_day_august - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_august,
                     asymp_prob=0.0028,
                     symp_quar_prob=0.0,
                     start_day=tti_day_august,
                     end_day=tti_day_sep - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_sep,
                     asymp_prob=0.0028,
                     symp_quar_prob=0.0,
                     start_day=tti_day_sep,
                     end_day=tti_day_oct - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_oct,
                     asymp_prob=0.0028,
                     symp_quar_prob=0.0,
                     start_day=tti_day_oct,
                     end_day=tti_day_nov - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_nov,
                     asymp_prob=0.0063,
                     symp_quar_prob=0.0,
                     start_day=tti_day_nov,
                     end_day=tti_day_dec - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=s_prob_dec,
                     asymp_prob=0.0063,
                     symp_quar_prob=0.0,
                     start_day=tti_day_dec,
                     end_day=tti_day_jan - 1,
                     test_delay=t_delay),
        cv.test_prob(symp_prob=future_symp_test,
                     asymp_prob=0.0063,
                     symp_quar_prob=0.0,
                     start_day=tti_day_jan,
                     test_delay=t_delay),
        cv.contact_tracing(trace_probs={
            'h': 1,
            's': 0.5,
            'w': 0.5,
            'c': 0.05
        },
                           trace_time={
                               'h': 0,
                               's': 1,
                               'w': 1,
                               'c': 2
                           },
                           start_day='2020-06-01',
                           quar_period=10),
        cv.dynamic_pars({'iso_factor': {
            'days': te_day,
            'vals': iso_vals
        }}),
        cv.dynamic_pars(
            {'iso_factor': {
                'days': tti_day_august,
                'vals': iso_vals1
            }}),
        cv.dynamic_pars(
            {'iso_factor': {
                'days': tti_day_sep,
                'vals': iso_vals2
            }}),
        cv.dynamic_pars(
            {'iso_factor': {
                'days': tti_day_oct,
                'vals': iso_vals3
            }}),
        cv.dynamic_pars(
            {'iso_factor': {
                'days': tti_day_nov,
                'vals': iso_vals4
            }}),
        cv.dynamic_pars(
            {'iso_factor': {
                'days': tti_day_dec,
                'vals': iso_vals5
            }})
    ]
    #cv.dynamic_pars({'rel_death_prob': {'days': tti_day_vac, 'vals': 0.9}})]
    #cv.vaccine(days=[0,14], rel_sus=0.4, rel_symp=0.2, cumulative=[0.7, 0.3])]

    # vaccination interventions
    interventions += [
        utils.two_dose_daily_delayed(200e3,
                                     start_day=tti_day_vac,
                                     dose_delay=14,
                                     delay=10 * 7,
                                     take_prob=1.0,
                                     rel_symp=0.05,
                                     rel_trans=0.9,
                                     cumulative=[0.7, 1.0],
                                     dose_priority=[1, 0.1])
    ]

    analyzers = []
    analyzers += [
        utils.record_dose_flows(vacc_class=utils.two_dose_daily_delayed)
    ]

    # Finally, update the parameters
    sim.update_pars(interventions=interventions, analyzers=analyzers)

    # Change death and critical probabilities
    #    interventions += [cv.dynamic_pars({'rel_death_prob':{'days':sim.day('2020-07-01'), 'vals':0.6}})]

    # Finally, update the parameters
    #sim.update_pars(interventions=interventions)
    for intervention in sim['interventions']:
        intervention.do_plot = False

    sim.initialize()

    return sim
Exemplo n.º 17
0
def run_sim(sim_pars=None, epi_pars=None, show_animation=False, verbose=True):
    ''' Create, run, and plot everything '''

    err = ''

    try:
        # Fix up things that JavaScript mangles
        orig_pars = cv.make_pars(set_prognoses=True,
                                 prog_by_age=False,
                                 use_layers=False)

        defaults = get_defaults(merge=True)
        web_pars = {}
        web_pars['verbose'] = verbose  # Control verbosity here

        for key, entry in {**sim_pars, **epi_pars}.items():
            print(key, entry)

            best = defaults[key]['best']
            minval = defaults[key]['min']
            maxval = defaults[key]['max']

            try:
                web_pars[key] = np.clip(float(entry['best']), minval, maxval)
            except Exception:
                user_key = entry['name']
                user_val = entry['best']
                err1 = f'Could not convert parameter "{user_key}", value "{user_val}"; using default value instead\n'
                print(err1)
                err += err1
                web_pars[key] = best
            if key in sim_pars: sim_pars[key]['best'] = web_pars[key]
            else: epi_pars[key]['best'] = web_pars[key]

        # Convert durations
        web_pars['dur'] = sc.dcp(
            orig_pars['dur'])  # This is complicated, so just copy it
        web_pars['dur']['exp2inf']['par1'] = web_pars.pop('web_exp2inf')
        web_pars['dur']['inf2sym']['par1'] = web_pars.pop('web_inf2sym')
        web_pars['dur']['crit2die']['par1'] = web_pars.pop('web_timetodie')
        web_dur = web_pars.pop('web_dur')
        for key in ['asym2rec', 'mild2rec', 'sev2rec', 'crit2rec']:
            web_pars['dur'][key]['par1'] = web_dur

        # Add the intervention
        web_pars['interventions'] = []
        if web_pars['web_int_day'] is not None:
            web_pars['interventions'] = cv.change_beta(
                days=web_pars.pop('web_int_day'),
                changes=(1 - web_pars.pop('web_int_eff')))

        # Handle CFR -- ignore symptoms and set to 1
        web_pars['prognoses'] = sc.dcp(orig_pars['prognoses'])
        web_pars['rel_symp_prob'] = 1e4  # Arbitrarily large
        web_pars['rel_severe_prob'] = 1e4
        web_pars['rel_crit_prob'] = 1e4
        web_pars['prognoses']['death_probs'][0] = web_pars.pop('web_cfr')
        if web_pars['rand_seed'] == 0:
            web_pars['rand_seed'] = None
        web_pars['timelimit'] = max_time  # Set the time limit
        web_pars['pop_size'] = int(web_pars['pop_size'])  # Set data type
        web_pars['contacts'] = int(web_pars['contacts'])  # Set data type

    except Exception as E:
        err2 = f'Parameter conversion failed! {str(E)}\n'
        print(err2)
        err += err2

    # Create the sim and update the parameters
    try:
        sim = cv.Sim(web_pars)
    except Exception as E:
        err3 = f'Sim creation failed! {str(E)}\n'
        print(err3)
        err += err3

    if verbose:
        print('Input parameters:')
        print(web_pars)

    # Core algorithm
    try:
        sim.run(do_plot=False)
    except TimeoutError:
        day = sim.t
        err4 = f"The simulation stopped on day {day} because run time limit ({sim['timelimit']} seconds) was exceeded. Please reduce the population size and/or number of days simulated."
        err += err4
    except Exception as E:
        err4 = f'Sim run failed! {str(E)}\n'
        print(err4)
        err += err4

    # Core plotting
    graphs = []
    try:
        to_plot = sc.dcp(cv.default_sim_plots)
        for p, title, keylabels in to_plot.enumitems():
            fig = go.Figure()
            for key in keylabels:
                label = sim.results[key].name
                this_color = sim.results[key].color
                y = sim.results[key][:]
                fig.add_trace(
                    go.Scatter(x=sim.results['t'][:],
                               y=y,
                               mode='lines',
                               name=label,
                               line_color=this_color))

            if sim['interventions']:
                interv_day = sim['interventions'][0].days[0]
                if interv_day > 0 and interv_day < sim['n_days']:
                    fig.add_shape(
                        dict(type="line",
                             xref="x",
                             yref="paper",
                             x0=interv_day,
                             x1=interv_day,
                             y0=0,
                             y1=1,
                             name='Intervention',
                             line=dict(width=0.5, dash='dash')))
                    fig.update_layout(annotations=[
                        dict(x=interv_day,
                             y=1.07,
                             xref="x",
                             yref="paper",
                             text="Intervention start",
                             showarrow=False)
                    ])

            fig.update_layout(title={'text': title},
                              xaxis_title='Day',
                              yaxis_title='Count',
                              autosize=True)

            output = {'json': fig.to_json(), 'id': str(sc.uuid())}
            d = json.loads(output['json'])
            d['config'] = {'responsive': True}
            output['json'] = json.dumps(d)
            graphs.append(output)

        graphs.append(plot_people(sim))

        if show_animation:
            graphs.append(animate_people(sim))

    except Exception as E:
        err5 = f'Plotting failed! {str(E)}\n'
        print(err5)
        err += err5

    # Create and send output files (base64 encoded content)
    files = {}
    summary = {}
    try:
        datestamp = sc.getdate(dateformat='%Y-%b-%d_%H.%M.%S')

        ss = sim.to_excel()
        files['xlsx'] = {
            'filename':
            f'Covasim_results_{datestamp}.xlsx',
            'content':
            'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'
            + base64.b64encode(ss.blob).decode("utf-8"),
        }

        json_string = sim.to_json(verbose=False)
        files['json'] = {
            'filename':
            f'Covasim_results_{datestamp}.json',
            'content':
            'data:application/text;base64,' +
            base64.b64encode(json_string.encode()).decode("utf-8"),
        }

        # Summary output
        summary = {
            'days': sim.npts - 1,
            'cases': round(sim.results['cum_infections'][-1]),
            'deaths': round(sim.results['cum_deaths'][-1]),
        }
    except Exception as E:
        err6 = f'File saving failed! {str(E)}\n'
        print(err6)
        err += err6

    output = {}
    output['err'] = err
    output['sim_pars'] = sim_pars
    output['epi_pars'] = epi_pars
    output['graphs'] = graphs
    output['files'] = files
    output['summary'] = summary

    return output
Exemplo n.º 18
0
basename = f'{folder}/covasim_scenarios_{date}_{version}'
fig_path = f'{basename}.png'
obj_path = f'{basename}.scens'

# Define the scenarios
scenarios = {
    'baseline': {
        'name': 'Baseline',
        'pars': {
            'interventions': None,
        }
    },
    'distance': {
        'name': 'Social distancing',
        'pars': {
            'interventions': cv.change_beta(days=interv_day,
                                            changes=interv_eff)
        }
    },
    # 'distance2': { # With noise = 0.0, this should be identical to the above
    #   'name':'Social distancing, version 2',
    #   'pars': {
    #       'interventions': cv.dynamic_pars({'beta':dict(days=interv_day, vals=interv_eff*default_beta)})
    #       }
    #   },
}

if __name__ == "__main__":  # Required for parallel processing on Windows

    sc.tic()

    # If we're rerunning...
Exemplo n.º 19
0
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
w_beta_changes = [
    0.90, 0.80, 0.20, 0.20, 0.20, 0.20, 0.70, 0.50, 0.70, 0.50, 0.70, 0.50,
    0.70, 0.50, 0.70, 0.50, 0.70
]
c_beta_changes = [
    0.90, 0.80, 0.20, 0.20, 0.20, 0.20, 0.70, 0.50, 0.90, 0.50, 0.90, 0.50,
    0.90, 0.50, 0.90, 0.50, 0.90
]
#Phased-delayed opening with only schools opening
#h_beta_changes = [1.00, 1.00, 1.29, 1.29, 1.29, 1.29, 1.00, 1.29, 1.00, 1.29, 1.00, 1.29, 1.00, 1.29, 1.00, 1.29, 1.00]
#s_beta_changes = [1.00, 0.90, 0.02, 0.02, 0.02, 0.02, 0.70, 0.00, 0.90, 0.00, 0.90, 0.00, 0.90, 0.00, 0.90, 0.00, 1.00]
#w_beta_changes = [0.90, 0.80, 0.20, 0.20, 0.20, 0.20, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40]
#c_beta_changes = [0.90, 0.80, 0.20, 0.20, 0.20, 0.20, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40, 0.40]

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

#next two lines to save the intervention
Exemplo n.º 21
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
    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
Exemplo n.º 22
0
version = 'v0'
date = '2020apr06'
folder = 'results'
basename = f'{folder}/covasim_run_{date}_{version}'
fig_path = f'{basename}.png'

# Configure the sim -- can also just use a normal dictionary
pars = sc.objdict(
    pop_size=20000,  # Population size
    pop_infected=1,  # Number of initial infections
    n_days=60,  # Number of days to simulate
    rand_seed=1,  # Random seed
    pop_type='random',
    use_layers=True,
)

# Optionally add an intervention
if interv:
    pars.interventions = cv.change_beta(
        days=45, changes=0.5)  # Optionally add an intervention

print('Making sim...')
sim = cv.Sim(pars=pars)

print('Running...')
sim.run(verbose=verbose)

if do_plot:
    print('Plotting...')
    fig = sim.plot(do_save=do_save, do_show=do_show, fig_path=fig_path)
Exemplo n.º 23
0
    quantiles={
        'low': 0.1,
        'high': 0.9
    },
)

n_ICU_beds = 256
# Define the actual scenarios
start_day = '2020-03-28'
scenarios = {
    'June': {
        'name': 'Open School June & August(90)',
        'pars': {
            'interventions': [
                cv.change_beta(days=['2020-03-28'],
                               changes=[s_beta_change],
                               layers=['s'],
                               do_plot=s_beta_change < 1.0),
                # cv.change_beta(days=['2020-06-02'], changes=[s_beta_change2], layers=['s'], do_plot=s_beta_change2<1.0),
                # cv.change_beta(days=['2020-08-14'], changes=[s_beta_change], layers=['s'], do_plot=s_beta_change<1.0),
                cv.change_beta(days=['2020-08-31'],
                               changes=[s_beta_change2],
                               layers=['s'],
                               do_plot=s_beta_change2 < 1.0),
                # cv.change_beta(days=['2020-10-23'], changes=[s_beta_change], layers=['s'], do_plot=s_beta_change<1.0),
                cv.change_beta(days=['2020-03-28'],
                               changes=[h_beta_change],
                               layers=['h'],
                               do_plot=h_beta_change < 1.0),
                # cv.change_beta(days=['2020-06-02'], changes=[h_beta_change2], layers=['h'], do_plot=h_beta_change2<1.0),
                # cv.change_beta(days=['2020-08-14'], changes=[h_beta_change], layers=['h'], do_plot=h_beta_change<1.0),
                cv.change_beta(days=['2020-08-31'],
Exemplo n.º 24
0
import covasim as cv

sc.toc()

do_plot = 1
do_save = 0
do_show = 1
verbose = 1
seed = 4
interv = 1

version = 'v0'
date = '2020mar21'
folder = 'results'
basename = f'{folder}/covasim_run_{date}_{version}'
fig_path = f'{basename}.png'

print('Making sim...')
sc.tic()
sim = cv.Sim()
sim.set_seed(seed)
if interv:
    sim['interventions'] = cv.change_beta(days=45, changes=0.5)

print('Running...')
sim.run(verbose=verbose)

if do_plot:
    print('Plotting...')
    fig = sim.plot(do_save=do_save, do_show=do_show, fig_path=fig_path)
Exemplo n.º 25
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
Exemplo n.º 26
0
# 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')
interv_eff_60 = 0.4
interv_eff_70 = 0.3
interv_eff_80 = 0.2

scenarios = {
    'baseline': {
        'name': 'Baseline',
        'pars': {
            'interventions': None,
        }
    },
    'distance1': {
        'name': 'Stable Work Beta',
        'pars': {
            'interventions': [
                cv.change_beta(days=interv_day, changes=0.75, layers='c'),
                cv.change_beta(days=interv_day,
                               changes=interv_eff_60,
                               layers='w'),
                cv.change_beta([s_close, s_open], [0, 1], layers='s'),
            ]
        }
    },
    'distance2': {
        'name': 'unstable work beta',
        'pars': {
            'interventions': [
                cv.change_beta(days=interv_day, changes=0.75, layers='c'),
                cv.change_beta(days=s_close, changes=0, layers='s'),
                cv.change_beta([12, 20, 28, 39, 48, 59, 70, 90, 130],
                               [.4, .8, 0.5, 0.7, 0.6, .5, 0.8, 0.6, 1],
Exemplo n.º 28
0
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