Example #1
0
def make_hybrid_contacts(pop_size,
                         ages,
                         contacts,
                         school_ages=None,
                         work_ages=None):
    '''
    Create "hybrid" contacts -- microstructured contacts for households and
    random contacts for schools and workplaces, both of which have extremely
    basic age structure. A combination of both make_random_contacts() and
    make_microstructured_contacts().
    '''

    # Handle inputs and defaults
    layer_keys = ['h', 's', 'w', 'c']
    contacts = sc.mergedicts({
        'h': 4,
        's': 20,
        'w': 20,
        'c': 20
    }, contacts)  # Ensure essential keys are populated
    if school_ages is None:
        school_ages = [6, 22]
    if work_ages is None:
        work_ages = [22, 65]

    # Create the empty contacts list -- a list of {'h':[], 's':[], 'w':[]}
    contacts_list = [{key: [] for key in layer_keys} for i in range(pop_size)]

    # Start with the household contacts for each person
    h_contacts, _, clusters = make_microstructured_contacts(
        pop_size, {'h': contacts['h']})

    # Make community contacts
    c_contacts, _ = make_random_contacts(pop_size, {'c': contacts['c']})

    # Get the indices of people in each age bin
    ages = np.array(ages)
    s_inds = sc.findinds((ages >= school_ages[0]) * (ages < school_ages[1]))
    w_inds = sc.findinds((ages >= work_ages[0]) * (ages < work_ages[1]))

    # Create the school and work contacts for each person
    s_contacts, _ = make_random_contacts(len(s_inds), {'s': contacts['s']})
    w_contacts, _ = make_random_contacts(len(w_inds), {'w': contacts['w']})

    # Construct the actual lists of contacts
    for i in range(pop_size):
        contacts_list[i]['h'] = h_contacts[i][
            'h']  # Copy over household contacts -- present for everyone
    for i, ind in enumerate(s_inds):
        contacts_list[ind]['s'] = s_inds[s_contacts[i]
                                         ['s']]  # Copy over school contacts
    for i, ind in enumerate(w_inds):
        contacts_list[ind]['w'] = w_inds[w_contacts[i]
                                         ['w']]  # Copy over work contacts
    for i in range(pop_size):
        contacts_list[i]['c'] = c_contacts[i][
            'c']  # Copy over community contacts -- present for everyone

    return contacts_list, layer_keys, clusters
Example #2
0
    def sample_hypershell(self):
        ''' Sample points from a hypershell. '''

        # Initialize
        fitinds = sc.findinds(
            self.fittable)  # The indices of the fittable parameters
        nfittable = len(fitinds)  # How many fittable parameters
        npars = len(self.x)  # Total number of parameters
        standard_normal = st.norm(
            loc=0, scale=1)  # Initialize a standard normal distribution
        radius_normal = st.norm(loc=self.relstepsize * self.mp.mu_r,
                                scale=self.relstepsize *
                                self.mp.sigma_r)  # And a scaled one

        # Calculate deviations
        deviations = np.zeros(
            (self.mp.N, nfittable))  # Deviations from current center point
        for r in range(self.mp.N):  # Loop over repeats
            sn_rvs = standard_normal.rvs(
                size=nfittable)  # Sample from the standard distribution
            sn_nrm = np.linalg.norm(
                sn_rvs)  # Calculate the norm of these samples
            radius = radius_normal.rvs()  # Sample from the scaled distribution
            deviations[
                r, :] = radius / sn_nrm * sn_rvs  # Deviation is the scaled sample adjusted by the rescaled standard sample

        # Calculate parameter samples
        samples = np.zeros((self.mp.N, npars))  # New samples
        for p in range(npars):  # Loop over all parameters
            if self.fittable[p]:
                ind = sc.findinds(
                    fitinds == p
                )[0]  # Convert the parameter index back to the fittable parameter index
                delta = deviations[:, ind] * (
                    self.xmax[p] - self.xmin[p]
                )  # Scale the deviation by the allowed parameter range
            else:
                delta = 0  # If not fittable, set to zero
            samples[:, p] = self.x[p] + delta  # Set new parameter value

        # Overwrite with center repeats
        for r in range(self.mp.center_repeats):
            samples[r, :] = self.x  # Just replace with the current center

        # Clamp
        for p in range(npars):
            samples[:, p] = np.minimum(
                self.xmax[p],
                np.maximum(self.xmin[p],
                           samples[:,
                                   p]))  # Ensure all samples are within range

        self.samples = samples
        self.allsamples[self.key] = sc.dcp(samples)
        self.iteration += 1
        return self.samples
def ftest_num_subtarg5(sim, sev=5.0):
    ''' Subtarget '''
    drop_inds = sc.findinds(sim.people.age < 80)
    sev_inds = np.intersect1d(sim.people.true('severe'),
                              sc.findinds(sim.people.age > 79))

    drop_vals = np.zeros(len(drop_inds))
    sev_vals = sev * np.ones(len(sev_inds))

    inds = np.concatenate([drop_inds, sev_inds])
    vals = np.concatenate([drop_vals, sev_vals])
    return {'inds': inds, 'vals': vals}
def remove_ltcf_community(sim, debug=False):
    ''' Ensure LTCF residents don't have community contacts '''
    over_65 = sc.findinds(sim.people.age > 65)
    llayer = sim.people.contacts['l']
    clayer = sim.people.contacts['c']
    in_ltcf = np.union1d(llayer['p1'], llayer['p2'])
    over_65_in_ltcf = np.intersect1d(over_65, in_ltcf)
    p1inds = sc.findinds(np.isin(clayer['p1'], over_65_in_ltcf))
    p2inds = sc.findinds(np.isin(clayer['p2'], over_65_in_ltcf))
    popinds = np.union1d(p1inds, p2inds)
    clayer.pop_inds(popinds)
    return clayer
def ftest_num_subtarg3(sim, sev=5.0):
    ''' Subtarget '''
    drop_inds = sc.findinds(np.logical_or(sim.people.age < 40, sim.people.age > 59))
    sev_inds = np.intersect1d(sim.people.true('severe'),
                              sc.findinds(np.logical_and(sim.people.age > 39, sim.people.age < 60)))

    drop_vals = np.zeros(len(drop_inds))
    sev_vals = sev * np.ones(len(sev_inds))

    inds = np.concatenate([drop_inds, sev_inds])
    vals = np.concatenate([drop_vals, sev_vals])
    return {'inds': inds, 'vals': vals}
Example #6
0
def find_day(arr, t=None, which='first'):
    '''
    Helper function to find if the current simulation time matches any day in the
    intervention. Although usually never more than one index is returned, it is
    returned as a list for the sake of easy iteration.

    Args:
        arr (list): list of days in the intervention, or else a boolean array
        t (int): current simulation time (can be None if a boolean array is used)
        which (str): what to return: 'first', 'last', or 'all' indices

    Returns:
        inds (list): list of matching days; length zero or one unless which is 'all'
    '''
    all_inds = sc.findinds(val1=arr, val2=t)
    if len(all_inds) == 0 or which == 'all':
        inds = all_inds
    elif which == 'first':
        inds = [all_inds[0]]
    elif which == 'last':
        inds = [all_inds[-1]]
    else:
        errormsg = f'Argument "which" must be "first", "last", or "all", not "{which}"'
        raise ValueError(errormsg)
    return inds
Example #7
0
    def compute_r_eff(self):
        '''
        Effective reproductive number based on number of people each person infected.
        '''

        # Initialize arrays to hold sources and targets infected each day
        sources = np.zeros(self.npts)
        targets = np.zeros(self.npts)

        for t in self.tvec:

            # Sources are easy -- count up the arrays
            recov_inds = cvu.true(
                t == self.people.date_recovered
            )  # Find people who recovered on this timestep
            dead_inds = cvu.true(
                t ==
                self.people.date_dead)  # Find people who died on this timestep
            outcome_inds = np.concatenate((recov_inds, dead_inds))
            sources[t] = len(outcome_inds)

            # Targets are hard -- loop over the transmission tree
            for ind in outcome_inds:
                targets[t] += len(self.people.transtree.targets[ind])

        # Populate the array -- to avoid divide-by-zero, skip indices that are 0
        inds = sc.findinds(sources > 0)
        r_eff = targets[inds] / sources[inds]
        self.results['r_eff'].values[inds] = r_eff

        return
Example #8
0
def plotdata(trendselection=None, startdate='2000-01-01', enddate='2018-01-01', trendline=False):
    
    # Handle inputs
    startyear = convertdate(startdate, '%Y-%m-%d')
    endyear   = convertdate(enddate,   '%Y-%m-%d')
    trendoptions = getoptions(tojson=False)
    if trendselection is None: trendselection  = trendoptions.keys()[0]
    datatype = trendoptions[trendselection]

    # Make graph
    fig = pl.figure()
    fig.add_subplot(111)
    thesedata = df.findrows(key=datatype, col='type')
    years = thesedata['date']
    vals = thesedata['close']
    validinds = sc.findinds(pl.logical_and(years>=startyear, years<=endyear))
    x = years[validinds]
    y = vals[validinds]
    pl.plot(x, y)
    pl.xlabel('Date')
    pl.ylabel('Trend index')
    
    # Add optional trendline
    if trendline:
        newy = sc.smoothinterp(x, x, y, smoothness=200)
        pl.plot(x, newy, lw=3)
    
    # Convert to FE
    graphjson = sw.mpld3ify(fig, jsonify=False)  # Convert to dict
    return graphjson  # Return the JSON representation of the Matplotlib figure
Example #9
0
File: sim.py Project: willf/covasim
    def compute_r_eff(self):
        '''
        Effective reproductive number based on number of people each person infected.
        '''

        # Initialize arrays to hold sources and targets infected each day
        sources = np.zeros(self.npts)
        targets = np.zeros(self.npts)

        # Loop over each person to pull out the transmission
        for person in self.people:
            if person.date_exposed is not None:  # Skip people who were never exposed
                if person.date_recovered is not None:
                    outcome_date = person.date_recovered
                elif person.date_dead is not None:
                    outcome_date = person.date_dead
                else:
                    errormsg = f'No outcome (death or recovery) can be determined for the following person:\n{person}'
                    raise ValueError(errormsg)

                if outcome_date is not None and outcome_date < self.npts:
                    outcome_date = int(outcome_date)
                    sources[outcome_date] += 1
                    targets[outcome_date] += len(person.infected)

        # Populate the array -- to avoid divide-by-zero, skip indices that are 0
        inds = sc.findinds(sources > 0)
        r_eff = targets[inds] / sources[inds]
        self.results['r_eff'].values[inds] = r_eff

        return
Example #10
0
    def apply(self, sim):
        t = sim.t
        if t < self.start_day:
            return
        elif self.end_day is not None and t > self.end_day:
            return

        adults = sim.people.age > 18
        adults_inds = sc.findinds(adults)
        screen_inds = cvu.choose(
            len(adults_inds),
            self.daily_screens)  # Who will we screen today - untargeted
        screen_inds = np.unique(screen_inds)

        screened_adult_inds = adults_inds[screen_inds]
        is_symptomatic = cvu.itruei(sim.people.symptomatic,
                                    screened_adult_inds)
        pos_screen = cvu.n_binomial(self.sensitivity, len(is_symptomatic))
        is_sym_pos = is_symptomatic[pos_screen]

        not_diagnosed = is_sym_pos[np.isnan(
            sim.people.date_diagnosed[is_sym_pos])]
        will_quar = cvu.n_binomial(self.prob_quar_after_fever,
                                   len(not_diagnosed))
        final_inds = not_diagnosed[will_quar]

        sim.people.quarantine(final_inds)
        sim.results['new_quarantined'][t] += len(final_inds)

        #print(f'{final_inds} put into quarantine by screening.')

        return
Example #11
0
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
Example #12
0
def make_hybrid_contacts(pop_size,
                         ages,
                         contacts,
                         school_ages=None,
                         work_ages=None):
    '''
    Create "hybrid" contacts -- microstructured contacts for households and
    random contacts for schools and workplaces, both of which have extremely
    basic age structure. A combination of both make_random_contacts() and
    make_microstructured_contacts().
    '''

    # Handle inputs and defaults
    contacts = sc.mergedicts({
        'h': 4,
        's': 20,
        'w': 20,
        'c': 20
    }, contacts)  # Ensure essential keys are populated
    if school_ages is None:
        school_ages = [6, 22]
    if work_ages is None:
        work_ages = [22, 65]

    contacts_dict = {}

    # Start with the household contacts for each person
    contacts_dict['h'] = make_microstructured_contacts(pop_size, contacts['h'])

    # Make community contacts
    contacts_dict['c'] = make_random_contacts(pop_size, contacts['c'])

    # Get the indices of people in each age bin
    ages = np.array(ages)
    s_inds = sc.findinds((ages >= school_ages[0]) * (ages < school_ages[1]))
    w_inds = sc.findinds((ages >= work_ages[0]) * (ages < work_ages[1]))

    # Create the school and work contacts for each person
    contacts_dict['s'] = make_random_contacts(len(s_inds),
                                              contacts['s'],
                                              mapping=s_inds)
    contacts_dict['w'] = make_random_contacts(len(w_inds),
                                              contacts['w'],
                                              mapping=w_inds)

    return contacts_dict
Example #13
0
    def plot_cascade(self, vertical=True):
        if vertical:
            fig_size = (12, 12)
            ax_size = [0.45, 0.05, 0.5, 0.9]
        else:
            fig_size = (16, 8)
            ax_size = [0.05, 0.45, 0.9, 0.5]
        df = sc.dcp(self.data)
        cutoff = 200e3
        fig = pl.figure(figsize=fig_size)
        df.sort(col='icer', reverse=False)
        DA_data = hp.arr(df['opt_spend'])
        inds = sc.findinds(DA_data > cutoff)
        DA_data = DA_data[inds]
        DA_data /= 1e6
        DA_labels = df['shortname'][inds]
        npts = len(DA_data)
        colors = sc.gridcolors(npts, limits=(0.25, 0.75))
        x = np.arange(len(DA_data))
        pl.axes(ax_size)
        for pt in range(npts):
            loc = x[pt:]
            this = DA_data[pt]
            start = sum(DA_data[:pt])
            prop = 0.9
            color = colors[pt]
            amount = sum(DA_data[:pt + 1])
            amountstr = '%0.1f' % amount
            if vertical:
                pl.barh(loc, width=this, left=start, height=prop, color=color)
                pl.text(amount,
                        x[pt],
                        amountstr,
                        verticalalignment='center',
                        color=colors[pt])
            else:
                pl.bar(loc, height=this, bottom=start, width=prop, color=color)
                pl.text(x[pt],
                        amount + 1,
                        amountstr,
                        horizontalalignment='center',
                        color=colors[pt])
        if vertical:
            pl.xlabel('Spending for optimized investment cascade')
            pl.gca().set_yticks(x)
            ticklabels = pl.gca().set_yticklabels(DA_labels)
        else:
            pl.ylabel('Optimized investment cascade')
            pl.gca().set_xticks(x)
            ticklabels = pl.gca().set_xticklabels(DA_labels, rotation=90)
        for t, tl in enumerate(ticklabels):
            tl.set_color(colors[t])

        pl.gca().set_facecolor('none')
        pl.title('Investment cascade')
        return fig
Example #14
0
def vacc_subtarg(sim):
    ''' Subtarget by age'''

    # retrieves the first ind that is = or < sim.t
    ind = get_ind_of_min_value(sim.vxsubtarg.days, sim.t)
    age = sim.vxsubtarg.age[ind]
    prob = sim.vxsubtarg.prob[ind]
    inds = sc.findinds((sim.people.age >= age) * ~sim.people.vaccinated)
    vals = prob * np.ones(len(inds))
    return {'inds': inds, 'vals': vals}
def test_num_subtarg(sim, sev=100.0, u20=0.5, quar=1.0):
    ''' Subtarget severe people with more testing, and young people with less '''
    inds = np.arange(len(sim.people))
    vals = np.ones(len(sim.people))
    vals[sc.findinds(
        (sim.people.age < 20) * (~sim.people.severe)
    )] *= u20  # People who are under 20 and severe test as if they're severe; * is element-wise "and"
    vals[sim.people.true('severe')] *= sev
    vals[sim.people.true('quarantined')] *= quar
    return {'inds': inds, 'vals': vals}
def test_num_subtarg(sim, sev=100.0, u20=0.5):
    ''' Subtarget severe people with more testing, and young people with less '''
    sev_inds = sim.people.true('severe')
    u20_inds = sc.findinds(
        (sim.people.age < 20) * (~sim.people.severe)
    )  # People who are under 20 and severe test as if they're severe; * is element-wise "and"
    u20_vals = u20 * np.ones(len(u20_inds))
    sev_vals = sev * np.ones(len(sev_inds))
    inds = np.concatenate([u20_inds, sev_inds])
    vals = np.concatenate([u20_vals, sev_vals])
    return {'inds': inds, 'vals': vals}
Example #17
0
 def apply(self, sim, t):
     ''' Loop over the parameters, and then loop over the days, applying them if any are found '''
     for parkey, parval in self.pars.items():
         inds = sc.findinds(parval['days'], t)  # Look for matches
         if len(inds):
             if len(inds) > 1:
                 raise ValueError(
                     f'Duplicate days are not allowed for Dynamic interventions (day={t}, indices={inds})'
                 )
             else:
                 sim[parkey] = parval['vals'][
                     inds[0]]  # Actually set the parameter
     return
Example #18
0
    def apply(self, sim):

        # If this day is found in the list, apply the intervention
        inds = sc.findinds(self.days, sim.t)
        if len(inds):
            for lkey, new_beta in self.orig_betas.items():
                for ind in inds:
                    new_beta = new_beta * self.changes[ind]
                if lkey == 'overall':
                    sim['beta'] = new_beta
                else:
                    sim['beta_layer'][lkey] = new_beta

        return
Example #19
0
    def compute_r_eff(self, window=7):
        '''
        Effective reproductive number based on number of people each person infected.

        Args:
            window (int): the size of the window used (larger values are more accurate but less precise)

        '''

        # Initialize arrays to hold sources and targets infected each day
        sources = np.zeros(self.npts)
        targets = np.zeros(self.npts)
        window = int(window)

        for t in self.tvec:

            # Sources are easy -- count up the arrays
            recov_inds = cvu.true(
                t == self.people.date_recovered
            )  # Find people who recovered on this timestep
            dead_inds = cvu.true(
                t ==
                self.people.date_dead)  # Find people who died on this timestep
            outcome_inds = np.concatenate((recov_inds, dead_inds))
            sources[t] = len(outcome_inds)

            # Targets are hard -- loop over the transmission tree
            for ind in outcome_inds:
                targets[t] += len(self.people.transtree.targets[ind])

        # Populate the array -- to avoid divide-by-zero, skip indices that are 0
        inds = sc.findinds(sources > 0)
        r_eff = np.zeros(self.npts) * np.nan
        r_eff[inds] = targets[inds] / sources[inds]

        # use stored weights calculate the moving average over the window of timesteps, n
        num = np.nancumsum(r_eff * sources)
        num[window:] = num[window:] - num[:-window]
        den = np.cumsum(sources)
        den[window:] = den[window:] - den[:-window]

        # avoid dividing by zero
        values = np.zeros(num.shape) * np.nan
        ind = den > 0
        values[ind] = num[ind] / den[ind]

        self.results['r_eff'].values = values

        return
Example #20
0
    def apply(self, sim, t):

        # If this is the first time it's being run, store beta
        if self.orig_beta is None:
            self.orig_beta = sim['beta']

        # If this day is found in the list, apply the intervention
        inds = sc.findinds(self.days, t)
        if len(inds):
            new_beta = self.orig_beta
            for ind in inds:
                new_beta = new_beta * self.changes[ind]
            sim['beta'] = new_beta

        return
Example #21
0
 def apply(self, sim):
     ''' Loop over the parameters, and then loop over the days, applying them if any are found '''
     t = sim.t
     for parkey,parval in self.pars.items():
         inds = sc.findinds(parval['days'], t) # Look for matches
         if len(inds):
             if len(inds)>1:
                 raise ValueError(f'Duplicate days are not allowed for Dynamic interventions (day={t}, indices={inds})')
             else:
                 val = parval['vals'][inds[0]]
                 if isinstance(val, dict):
                     sim[parkey].update(val) # Set the parameter if a nested dict
                 else:
                     sim[parkey] = val # Set the parameter if not a dict
     return
def modify_sim(sim, scenpars, label=None, runinfo=None):
    ''' Modify the simulation for the scenarios '''

    print(
        f'  Note: modifying simulation {label} at day={sim.t}, date={sim.date(sim.t)}, scenpars:\n{scenpars}'
    )

    # Do reopening: modify clip_edges
    last_calib_day = sim.day(sim.sceninfo.calib_end)
    first_scen_day = sim.day(sim.sceninfo.scen_start)
    for ilabel in ['clip_w', 'clip_c']:
        interv = get_interv(sim, ilabel)
        valid_days = sc.findinds(interv.days <= last_calib_day)
        interv.days = np.append(
            interv.days[valid_days], first_scen_day
        )  # NB, repr of intervention will be wrong with direct modification!
        interv.changes = np.append(interv.changes[valid_days],
                                   scenpars['reopen'])

    # Change iso_factor and quar_factor
    sim.pars['iso_factor'] = sc.dcp(scenpars['i_factor'])
    sim.pars['quar_factor'] = sc.dcp(scenpars['q_factor'])

    # Implement testing & tracing interventions
    tppars = {
        k: scenpars[k]
        for k in [
            'symp_prob', 'asymp_prob', 'symp_quar_prob', 'asymp_quar_prob',
            'test_delay'
        ]
    }
    ctpars = {k: scenpars[k] for k in ['trace_probs', 'trace_time']}
    tp = cv.test_prob(start_day=first_scen_day, quar_policy=[0], **tppars)
    ct = cv.contact_tracing(start_day=first_scen_day,
                            label='contact_tracing',
                            **ctpars)
    sim['interventions'] += [tp, ct]

    # Final tidying
    sim.label = label
    sim.runinfo = runinfo
    sim.sceninfo.scenpars = scenpars

    return sim
def filter_people(pop, ages=None, uids=None):
    """
    Helper function to filter people based on their uid and age.

    Args:
        pop (sp.Pop)         : population
        ages (list or array) : ages of people to include
        uids (list or array) : ids of people to include

    Returns:
        array: An array of the ids of people to include for further analysis.
    """
    output = np.arange(pop.n)
    if uids is not None:  # catch instance where the only uids supplied is the first one, 0
        output = np.intersect1d(output, uids)

    if ages is not None:  # catch instance where the only ages supplied is age 0
        output = np.intersect1d(output, sc.findinds(np.isin(pop.age_by_uid, ages)))
    return output
Example #24
0
    def apply(self, sim):

        # If this is the first time it's being run, store beta
        if self.orig_betas is None:
            self.orig_betas = {}
            for layer in self.layers:
                if layer is None:
                    self.orig_betas['overall'] = sim['beta']
                else:
                    self.orig_betas[layer] = sim['beta_layers'][layer]

        # If this day is found in the list, apply the intervention
        inds = sc.findinds(self.days, sim.t)
        if len(inds):
            for layer,new_beta in self.orig_betas.items():
                for ind in inds:
                    new_beta = new_beta * self.changes[ind]
                if layer == 'overall':
                    sim['beta'] = new_beta
                else:
                    sim['beta_layers'][layer] = new_beta
        return
Example #25
0
    def count_targets(self, start_day=None, end_day=None):
        '''
        Count the number of targets each infected person has. If start and/or end
        days are given, it will only count the targets of people who got infected
        between those dates (it does not, however, filter on the date the target
        got infected).

        Args:
            start_day (int/str): the day on which to start counting people who got infected
            end_day (int/str): the day on which to stop counting people who got infected
        '''

        # Handle start and end days
        start_day = self.day(start_day, which='start')
        end_day   = self.day(end_day,   which='end')

        n_targets = np.nan+np.zeros(self.pop_size)
        for i in range(self.pop_size):
            if self.sources[i] is not None:
                if self.source_dates[i] >= start_day and self.source_dates[i] <= end_day:
                    n_targets[i] = len(self.targets[i])
        n_target_inds = sc.findinds(~np.isnan(n_targets))
        n_targets = n_targets[n_target_inds]
        return n_targets
    for i in range(nsims):
        pl.subplot(nsims // 2, 2, i + 1)
        data = results[i, :, :]
        for j in range(seeds):
            pl.plot(s0.tvec, results[i, j, :])

dur = 10  # Duration of symptoms
mintest = 0.0
maxtest = 0.2
test_vals = np.linspace(mintest, maxtest, nsims)  # TODO: remove duplication
test_pct = (1 - (1 - test_vals)**dur) * 100

# Trim indices
only_high_testing = True
if not only_high_testing:
    low_inds = sc.findinds(test_pct <= 4)
    med_inds = sc.findinds(np.logical_and(test_pct > 4, test_pct <= 20))
    high_inds = sc.findinds(test_pct > 20)
    inds = low_inds[::1].tolist() + med_inds[::2].tolist(
    ) + high_inds[::10].tolist()
else:
    med_inds = sc.findinds(np.logical_and(test_pct > 28, test_pct <= 50))
    high_inds = sc.findinds(test_pct > 50)
    inds = med_inds[::2].tolist() + high_inds[::8].tolist()

xlims = [s0.tvec[0], s0.tvec[-1]]
ylims = [0, results[inds, :, :].max()]

# Actually plot
if plot_movie:
    fig = pl.figure(figsize=(10, 6))  # Create a new figure
Example #27
0
    [0.905, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
     0.0])  # Equally susceptible
prognoses['severe_probs'] = np.array(
    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])  # Zero'd out
prognoses['crit_probs'] = np.array(
    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])  # Zero'd out
prognoses['death_probs'] = np.array(
    [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])  # Zero'd out
pars['prognoses'] = prognoses
pars['start_day'] = '2020-01-01'
pars['n_days'] = 60
pars['quar_period'] = 140
sim = cv.Sim(pars=pars)  # Setup sim
sim.initialize()
people = cv.make_people(sim)  # Make the actual people for the simulation
inds_o5 = sc.findinds(people.age >= 10)
people.rel_sus[inds_o5] = 0
inds_u5 = sc.findinds(people.age < 10)
imm_frac = 0.8
inds_u5imm = inds_u5[sc.findinds(
    np.random.uniform(low=0.0, high=1.0, size=len(inds_u5)) < imm_frac)]
people.rel_sus[inds_u5imm] = 0
sim.people = people
# sim['interventions'] = [cv.test_prob(symp_prob=1.00, asymp_prob=0.00)] # Test 100% of symptomatics and 0% of asymptomatics
sim['interventions'] = [
    cv.test_prob(symp_prob=1.00, asymp_prob=0.00),
    cv.contact_tracing()
]
sim.run()
sim.plot()
        'days': tti_day,
        'vals': iso_vals
    }})
]
pars['interventions'] = [ttq_june_2, isolation_june_2, june_tests_extra]
sim.update_pars(interventions=interventions)
for intervention in sim['interventions']:
    intervention.do_plot = False

# Changing kids' transmissability
sim.initialize()  # Create the population
reduce_kids = True  #set tgis to True to change the transmissibility numbers below
if reduce_kids:
    print('Reducing transmission among kids')
    children = sim.people.age < 18  # Find people who are children
    child_inds = sc.findinds(
        children)  # Turn the boolean array into a list of indices
    for lkey in sim.people.layer_keys():  # Loop over each layer
        child_contacts = np.isin(
            sim.people.contacts[lkey]['p1'],
            child_inds)  # Find contacts where the source is a child
        child_contact_inds = sc.findinds(child_contacts)  # Convert to indices
        sim.people.contacts[lkey]['beta'][
            child_contact_inds] = 1.0  # MODIFY TRANSMISSION
        #sim.people.contacts[lkey]['beta'][:] = 0.0 # MODIFY TRANSMISSION

if __name__ == '__main__':
    #msim = cv.MultiSim(n_runs=10)
    msim.run(n_runs=8, keep_people=True)  # Run with uncertainty

    # Recalculate R_eff with a larger window
    for sim in msim.sims:
Example #29
0
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}
Example #30
0
transition = mplt.colors.LinearSegmentedColormap.from_list(
    "transition", [cmap1(1.), cmap2(0)])(np.linspace(0, 1, transition_steps))
colors = np.vstack((colors1, transition, colors2))
colors = np.flipud(colors)

new_cmap = mplt.colors.LinearSegmentedColormap.from_list(new_cmap_name, colors)
cmap = new_cmap

# Assign colors to age groups
age_cutoffs = np.arange(
    0, 101, 10)  # np.array([0, 4, 6, 18, 22, 30, 45, 65, 80, 90, 100])
if discrete:
    raw_colors = sc.vectocolor(len(age_cutoffs), cmap=cmap)
    colors = []
    for age in sim.people.age:
        ind = sc.findinds(age_cutoffs <= age)[-1]
        colors.append(raw_colors[ind])
    colors = np.array(colors)
else:
    age_map = sim.people.age * 0.1 + np.sqrt(sim.people.age)
    colors = sc.vectocolor(age_map, cmap=cmap)

# Create the legend
if plot_stacked:
    ax = fig.add_axes([0.85, 0.05, 0.14, 0.93])
elif len(keys_to_plot) % 2 != 0:
    ax = fig.add_axes([0.85, 0.05, 0.14, 0.93])
else:
    ax = fig.add_axes([0.82, 0.05, 0.14, 0.90])

ax.axis('off')