covasim.interventions module¶
Specify the core interventions available in Covasim. Other interventions can be defined by the user by inheriting from these classes.

InterventionDict
(which, pars)[source]¶ Generate an intervention from a dictionary. Although a function, it acts like a class, since it returns a class instance.
Example:
interv = cv.InterventionDict(which='change_beta', pars={'days': 30, 'changes': 0.5, 'layers': None})

class
Intervention
(label=None, show_label=False, do_plot=None, line_args=None)[source]¶ Bases:
object
Base class for interventions. By default, interventions are printed using a dict format, which they can be recreated from. To display all the attributes of the intervention, use disp() instead.
To retrieve a particular intervention from a sim, use sim.get_intervention().
Parameters:  label (str) – a label for the intervention (used for plotting, and for ease of identification)
 show_label (bool) – whether or not to include the label in the legend
 do_plot (bool) – whether or not to plot the intervention
 line_args (dict) – arguments passed to pl.axvline() when plotting

initialize
(sim=None)[source]¶ Initialize intervention – this is used to make modifications to the intervention that can’t be done until after the sim is created.

finalize
(sim=None)[source]¶ Finalize intervention
This method is run once as part of sim.finalize() enabling the intervention to perform any final operations after the simulation is complete (e.g. rescaling)

apply
(sim)[source]¶ Apply the intervention. This is the core method which each derived intervention class must implement. This method gets called at each timestep and can make arbitrary changes to the Sim object, as well as storing or modifying the state of the intervention.
Parameters: sim – the Sim instance Returns: None

shrink
(in_place=False)[source]¶ Remove any excess stored data from the intervention; for use with sim.shrink().
Parameters: in_place (bool) – whether to shrink the intervention (else shrink a copy)

plot_intervention
(sim, ax=None, **kwargs)[source]¶ Plot the intervention
This can be used to do things like add vertical lines on days when interventions take place. Can be disabled by setting self.do_plot=False.
Note 1: you can modify the plotting style via the
line_args
argument when creating the intervention.Note 2: By default, the intervention is plotted at the days stored in self.days. However, if there is a self.plot_days attribute, this will be used instead.
Parameters:  sim – the Sim instance
 ax – the axis instance
 kwargs – passed to ax.axvline()
Returns: None

to_json
()[source]¶ Return JSONcompatible representation
Custom classes can’t be directly represented in JSON. This method is a oneway export to produce a JSONcompatible representation of the intervention. In the first instance, the object dict will be returned. However, if an intervention itself contains nonstandard variables as attributes, then its to_json method will need to handle those.
Note that simply printing an intervention will usually return a representation that can be used to recreate it.
Returns: JSONserializable representation (typically a dict, but could be anything else)

class
dynamic_pars
(pars=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
A generic intervention that modifies a set of parameters at specified points in time.
The intervention takes a single argument, pars, which is a dictionary of which parameters to change, with following structure: keys are the parameters to change, then subkeys ‘days’ and ‘vals’ are either a scalar or list of when the change(s) should take effect and what the new value should be, respectively.
You can also pass parameters to change directly as keyword arguments.
Parameters:  pars (dict) – described above
 kwargs (dict) – passed to Intervention()
Examples:
interv = cv.dynamic_pars(n_imports=dict(days=10, vals=100)) interv = cv.dynamic_pars({'beta':{'days':[14, 28], 'vals':[0.005, 0.015]}, 'rel_death_prob':{'days':30, 'vals':2.0}}) # Change beta, and make diagnosed people stop transmitting

class
sequence
(days, interventions, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
This is an example of a metaintervention which switches between a sequence of interventions.
Parameters:  days (list) – the days on which to start applying each intervention
 interventions (list) – the interventions to apply on those days
 kwargs (dict) – passed to Intervention()
Example:
interv = cv.sequence(days=[10, 51], interventions=[ cv.test_num(n_tests=[100]*npts), cv.test_prob(symptomatic_prob=0.2, asymptomatic_prob=0.002), ])

class
change_beta
(days, changes, layers=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
The most basic intervention – change beta (transmission) by a certain amount on a given day or days. This can be used to represent physical distancing (although clip_edges() is more appropriate for overall changes in mobility, e.g. school or workplace closures), as well as handwashing, masks, and other behavioral changes that affect transmission rates.
Parameters:  days (int/arr) – the day or array of days to apply the interventions
 changes (float/arr) – the changes in beta (1 = no change, 0 = no transmission)
 layers (str/list) – the layers in which to change beta (default: all)
 kwargs (dict) – passed to Intervention()
Examples:
interv = cv.change_beta(25, 0.3) # On day 25, reduce overall beta by 70% to 0.3 interv = cv.change_beta([14, 28], [0.7, 1], layers='s') # On day 14, reduce beta by 30%, and on day 28, return to 1 for schools

class
clip_edges
(days, changes, layers=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
Isolate contacts by removing them from the simulation. Contacts are treated as “edges”, and this intervention works by removing them from sim.people.contacts and storing them internally. When the intervention is over, they are moved back. This intervention has quite similar effects as change_beta(), but is more appropriate for modeling the effects of mobility reductions such as school and workplace closures. The main difference is that since clip_edges() actually removes contacts, it affects the number of people who would be traced and placed in quarantine if an individual tests positive. It also alters the structure of the network – i.e., compared to a baseline case of 20 contacts and a 2% chance of infecting each, there are slightly different statistics for a beta reduction (i.e., 20 contacts and a 1% chance of infecting each) versus an edge clipping (i.e., 10 contacts and a 2% chance of infecting each).
Parameters:  days (int or array) – the day or array of days to isolate contacts
 changes (float or array) – the changes in the number of contacts (1 = no change, 0 = no contacts)
 layers (str or list) – the layers in which to isolate contacts (if None, then all layers)
 kwargs (dict) – passed to Intervention()
Examples:
interv = cv.clip_edges(25, 0.3) # On day 25, reduce overall contacts by 70% to 0.3 interv = cv.clip_edges([14, 28], [0.7, 1], layers='s') # On day 14, remove 30% of school contacts, and on day 28, restore them

class
test_num
(daily_tests, symp_test=100.0, quar_test=1.0, quar_policy=None, subtarget=None, ili_prev=None, sensitivity=1.0, loss_prob=0, test_delay=0, start_day=0, end_day=None, swab_delay=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
Test the specified number of people per day. Useful for including historical testing data. The probability of a given person getting a test is dependent on the total number of tests, population size, and odds ratios. Compare this intervention with cv.test_prob().
Parameters:  daily_tests (arr) – number of tests per day, can be int, array, or dataframe/series; if integer, use that number every day; if ‘data’ or another string, use loaded data
 symp_test (float) – odds ratio of a symptomatic person testing (default: 100x more likely)
 quar_test (float) – probability of a person in quarantine testing (default: no more likely)
 quar_policy (str) – policy for testing in quarantine: options are ‘start’ (default), ‘end’, ‘both’ (start and end), ‘daily’; can also be a number or a function, see get_quar_inds()
 subtarget (dict) – subtarget intervention to people with particular indices (format: {‘ind’: array of indices, or function to return indices from the sim, ‘vals’: value(s) to apply}
 ili_prev (arr) – prevalence of influenzalikeillness symptoms in the population; can be float, array, or dataframe/series
 sensitivity (float) – test sensitivity (default 100%, i.e. no false negatives)
 loss_prob (float) – probability of the person being losttofollowup (default 0%, i.e. no one lost to followup)
 test_delay (int) – days for test result to be known (default 0, i.e. results available instantly)
 start_day (int) – day the intervention starts (default: 0, i.e. first day of the simulation)
 end_day (int) – day the intervention ends
 swab_delay (dict) – distribution for the delay from onset to swab; if this is present, it is used instead of test_delay
 kwargs (dict) – passed to Intervention()
Examples:
interv = cv.test_num(daily_tests=[0.10*n_people]*npts) interv = cv.test_num(daily_tests=[0.10*n_people]*npts, subtarget={'inds': cv.true(sim.people.age>50), 'vals': 1.2}) # People over 50 are 20% more likely to test interv = cv.test_num(daily_tests=[0.10*n_people]*npts, subtarget={'inds': lambda sim: cv.true(sim.people.age>50), 'vals': 1.2}) # People over 50 are 20% more likely to test interv = cv.test_num(daily_tests='data') # Take number of tests from loaded data using default column name (new_tests) interv = cv.test_num(daily_tests='swabs_per_day') # Take number of tests from loaded data using a custom column name

class
test_prob
(symp_prob, asymp_prob=0.0, symp_quar_prob=None, asymp_quar_prob=None, quar_policy=None, subtarget=None, ili_prev=None, sensitivity=1.0, loss_prob=0.0, test_delay=0, start_day=0, end_day=None, swab_delay=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
Assign each person a probability of being tested for COVID based on their symptom state, quarantine state, and other states. Unlike test_num, the total number of tests not specified, but rather is an output.
Parameters:  symp_prob (float) – probability of testing a symptomatic (unquarantined) person
 asymp_prob (float) – probability of testing an asymptomatic (unquarantined) person (default: 0)
 symp_quar_prob (float) – probability of testing a symptomatic quarantined person (default: same as symp_prob)
 asymp_quar_prob (float) – probability of testing an asymptomatic quarantined person (default: same as asymp_prob)
 quar_policy (str) – policy for testing in quarantine: options are ‘start’ (default), ‘end’, ‘both’ (start and end), ‘daily’; can also be a number or a function, see get_quar_inds()
 subtarget (dict) – subtarget intervention to people with particular indices (see test_num() for details)
 ili_prev (float/arr) – prevalence of influenzalikeillness symptoms in the population; can be float, array, or dataframe/series
 sensitivity (float) – test sensitivity (default 100%, i.e. no false negatives)
 loss_prob (float) – probability of the person being losttofollowup (default 0%, i.e. no one lost to followup)
 test_delay (int) – days for test result to be known (default 0, i.e. results available instantly)
 start_day (int) – day the intervention starts (default: 0, i.e. first day of the simulation)
 end_day (int) – day the intervention ends (default: no end)
 swab_delay (dict) – distribution for the delay from onset to swab; if this is present, it is used instead of test_delay
 kwargs (dict) – passed to Intervention()
Examples:
interv = cv.test_prob(symp_prob=0.1, asymp_prob=0.01) # Test 10% of symptomatics and 1% of asymptomatics interv = cv.test_prob(symp_quar_prob=0.4) # Test 40% of those in quarantine with symptoms

class
contact_tracing
(trace_probs=None, trace_time=None, start_day=0, end_day=None, presumptive=False, quar_period=None, capacity=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
Contact tracing of people who are diagnosed. When a person is diagnosed positive (by either test_num() or test_prob(); this intervention has no effect if there is not also a testing intervention active), a certain proportion of the index case’s contacts (defined by trace_prob) are contacted after a certain number of days (defined by trace_time). After they are contacted, they are placed into quarantine (with effectiveness quar_factor, a simulation parameter) for a certain period (defined by quar_period, another simulation parameter). They may also change their testing probability, if test_prob() is defined.
Parameters:  trace_probs (float/dict) – probability of tracing, per layer (default: 100%, i.e. everyone is traced)
 trace_time (float/dict) – days required to trace, per layer (default: 0, i.e. no delay)
 start_day (int) – intervention start day (default: 0, i.e. the start of the simulation)
 end_day (int) – intervention end day (default: no end)
 presumptive (bool) – whether or not to begin isolation and contact tracing on the presumption of a positive diagnosis (default: no)
 capacity (int) – optionally specify a maximum number of newly diagnosed people to trace each day
 quar_period (int) – number of days to quarantine when notified as a known contact. Default value is
pars['quar_period']
 kwargs (dict) – passed to Intervention()
Example:
tp = cv.test_prob(symp_prob=0.1, asymp_prob=0.01) ct = cv.contact_tracing(trace_probs=0.5, trace_time=2) sim = cv.Sim(interventions=[tp, ct]) # Note that without testing, contact tracing has no effect

apply
(sim)[source]¶ Trace and notify contacts
Tracing involves three steps that can independently be overloaded or extended by derived classes
 Select which confirmed cases get interviewed by contact tracers
 Identify the contacts of the confirmed case
 Notify those contacts that they have been exposed and need to take some action

identify_contacts
(sim, trace_inds)[source]¶ Return contacts to notify by trace time
In the base class, the trace time is the same perlayer, but derived classes might provide different functionality e.g. sampling the trace time from a distribution. The return value of this method is a dict keyed by trace time so that the Person object can be easily updated in contact_tracing.notify_contacts
Parameters:  sim – Simulation object
 trace_inds – Indices of people to trace
Returns: {trace_time: np.array(inds)} dictionary storing which people to notify

notify_contacts
(sim, contacts)[source]¶ Notify contacts
This method represents notifying people that they have had contact with a confirmed case. In this base class, that involves
 Setting the ‘known_contact’ flag and recording the ‘date_known_contact’
 Scheduling quarantine
Parameters:  sim – Simulation object
 contacts – {trace_time: np.array(inds)} dictionary storing which people to notify

class
simple_vaccine
(days, prob=1.0, rel_sus=0.0, rel_symp=0.0, subtarget=None, cumulative=False, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
Apply a simple vaccine to a subset of the population. In addition to changing the relative susceptibility and the probability of developing symptoms if still infected, this intervention stores several types of data:
doses
: the number of vaccine doses per personvaccination_dates
: list of dates per personorig_rel_sus
: relative susceptibility per person at the beginning of the simulationorig_symp_prob
: probability of developing symptoms per person at the beginning of the simulationmod_rel_sus
: modifier on default susceptibility due to the vaccinemod_symp_prob
: modifier on default symptom probability due to the vaccine
Parameters:  days (int or array) – the day or array of days to apply the interventions
 prob (float) – probability of being vaccinated (i.e., fraction of the population)
 rel_sus (float) – relative change in susceptibility; 0 = perfect, 1 = no effect
 rel_symp (float) – relative change in symptom probability for people who still get infected; 0 = perfect, 1 = no effect
 subtarget (dict) – subtarget intervention to people with particular indices (see test_num() for details)
 cumulative (bool) – whether cumulative doses have cumulative effects (default false); can also be an array for efficacy per dose, with the last entry used for multiple doses; thus True = [1] and False = [1,0]
 kwargs (dict) – passed to Intervention()
Note: this intervention is still under development and should be used with caution. It is intended for use with use_waning=False.
Examples:
interv = cv.simple_vaccine(days=50, prob=0.3, rel_sus=0.5, rel_symp=0.1) interv = cv.simple_vaccine(days=[10,20,30,40], prob=0.8, rel_sus=0.5, cumulative=[1, 0.3, 0.1, 0]) # A vaccine with efficacy up to the 3rd dose

class
BaseVaccination
(vaccine, label=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
Apply a vaccine to a subset of the population.
This base class implements the mechanism of vaccinating people to modify their immunity. It does not implement allocation of the vaccines, which is implemented by derived classes such as cv.vaccinate. The idea is that vaccination involves a series of standard operations to modify cv.People and applications will likely need to modify the vaccine parameters and test potentially complex allocation strategies. These should be accounted for by:
 Custom vaccine parameters being passed in as a dictionary to the vaccine intervention
 Custom vaccine allocations being implemented by a derived class overloading BaseVaccination.select_people. Any additional attributes required to manage the allocation can be defined in the derived class. Refer to cv.vaccinate or cv.vaccinate_sequential for an example of how to implement this.
Some quantities are tracked during execution for reporting after running the simulation. These are:
doses
: the number of vaccine doses per personvaccination_dates
: integer; dates of all doses for this vaccine
Parameters:  vaccine (dict/str) – which vaccine to use; see below for dict parameters
 label (str) – if vaccine is supplied as a dict, the name of the vaccine
 booster (boolean) – whether the vaccine is a booster, i.e. whether vaccinated people are eligible
 kwargs (dict) – passed to Intervention()
If
vaccine
is supplied as a dictionary, it must have the following parameters:EITHER nab_init
: the initial antibody level (higher = more protection) nab_boost
: how much of a boost being vaccinated on top of a previous dose or natural infection provides OR target_eff
: the target efficacy from which to calculate initial antibody and boosting. must be supplied as a list, where length of list is equal to number of doses nab_eff
: the waning efficacy of neutralizing antibodies at preventing infection doses
: the number of doses required to be fully vaccinated with this vaccine interval
: the interval between doses (integer)  entries for efficacy against each of the variants (e.g.b117
)See
parameters.py
for additional examples of these parameters.
select_people
(sim)[source]¶ Return an array of indices of people to vaccinate Derived classes must implement this function to determine who to vaccinate at each timestep :param sim: A cv.Sim instance
Returns: Array of person indices

vaccinate
(sim, vacc_inds, t=None)[source]¶ Vaccinate people
This method applies the vaccine to the requested people indices. The indices of people vaccinated is returned. These may be different to the requested indices, because anyone that is dead will be skipped, as well as anyone already fully vaccinated (if booster=False). This could occur if a derived class does not filter out such people in its select_people method.
Parameters:  sim – A cv.Sim instance
 vacc_inds – An array of person indices to vaccinate
 t – Optionally override the day on which vaccinations are recorded for historical vaccination
Returns: An array of person indices of people vaccinated

vaccinate
(*args, **kwargs)[source]¶ Wrapper function for
vaccinate_prob()
andvaccinate_num()
. If thenum_doses
argument is used, will callvaccinate_num()
; else, callsvaccinate_prob()
.Examples:
vx1 = cv.vaccinate(vaccine='pfizer', days=30, prob=0.7) vx2 = cv.vaccinate(vaccine='pfizer', num_doses=100)

class
vaccinate_prob
(vaccine, days, label=None, prob=None, subtarget=None, booster=False, **kwargs)[source]¶ Bases:
covasim.interventions.BaseVaccination
Probabilitybased vaccination
This vaccine intervention allocates vaccines parametrized by the daily probability of being vaccinated.
Parameters:  vaccine (dict/str) – which vaccine to use; see below for dict parameters
 label (str) – if vaccine is supplied as a dict, the name of the vaccine
 days (int/arr) – the day or array of days to apply the interventions
 prob (float) – probability of being vaccinated (i.e., fraction of the population)
 booster (bool) – whether it’s a booster (i.e. targeted to vaccinated people) or not
 subtarget (dict) – subtarget intervention to people with particular indices (see test_num() for details)
 kwargs (dict) – passed to Intervention()
If
vaccine
is supplied as a dictionary, it must have the following parameters:nab_eff
: the waning efficacy of neutralizing antibodies at preventing infectionnab_init
: the initial antibody level (higher = more protection)nab_boost
: how much of a boost being vaccinated on top of a previous dose or natural infection providesdoses
: the number of doses required to be fully vaccinatedinterval
: the interval between doses (integer) entries for efficacy against each of the strains (e.g.
b117
)
See
parameters.py
for additional examples of these parameters.Example:
pfizer = cv.vaccinate_prob(vaccine='pfizer', days=30, prob=0.7) cv.Sim(interventions=pfizer, use_waning=True).run().plot()

class
vaccinate_num
(vaccine, num_doses, booster=False, subtarget=None, sequence=None, **kwargs)[source]¶ Bases:
covasim.interventions.BaseVaccination
This vaccine intervention allocates vaccines in a precomputed order of distribution, at a specified rate of doses per day. Second doses are prioritized each day.
Parameters:  vaccine (dict/str) – which vaccine to use; see below for dict parameters
 label (str) – if vaccine is supplied as a dict, the name of the vaccine
 booster (bool) – whether it’s a booster (i.e. targeted to vaccinated people) or not
 subtarget (dict) – subtarget intervention to people with particular indices (see test_num() for details)
 sequence –
Specify the order in which people should get vaccinated. This can be
 An array of person indices in order of vaccination priority
 A callable that takes in cv.People and returns an ordered sequence. For example, to
vaccinate people in descending age order,
def age_sequence(people): return np.argsort(people.age)
would be suitable.  The shortcut ‘age’, which does prioritization by age (see below for implementation) If not specified, people will be randomly ordered.
 num_doses –
Specify the number of doses per day. This can take three forms
 A scalar number of doses per day
 A dict keyed by day/date with the number of doses e.g.
{2:10000, '20210501':20000}
. Any dates are converted to simulation days in initialize() which will also copy the dictionary passed in.  A callable that takes in a
cv.Sim
and returns a scalar number of doses. For example,def doses(sim): return 100 if sim.t > 10 else 0
would be suitable
 **kwargs – Additional arguments passed to
cv.BaseVaccination
 Example::
 pfizer = cv.vaccinate_num(vaccine=’pfizer’, sequence=’age’, num_doses=100) cv.Sim(interventions=pfizer, use_waning=True).run().plot()

prior_immunity
(*args, **kwargs)[source]¶ Wrapper function for
historical_wave
andhistorical_vaccinate_prob
. If thevaccine
keyword is present thenhistorical_vaccinate_prob
will be used. Otherwisehistorical_wave
is used.Examples:
pim1 = cv.prior_immunity(vaccine='pfizer', days=[30], prob=0.7) pim2 = cv.prior_immunity(120, 0.05)
New in version 3.1.0.

class
historical_vaccinate_prob
(vaccine, days, label=None, prob=1.0, subtarget=None, compliance=1.0, **kwargs)[source]¶ Bases:
covasim.interventions.BaseVaccination
Probabilitybased historical vaccination
This vaccine intervention allocates vaccines parametrized by the daily probability of being vaccinated. Unlike cv.vaccinate_prob this function allows vaccination prior to t=0 (and continuing into the simulation).
If any people are infected at the t=0 timestep (e.g. seed infections), this finds those people and will reinfect them at the end of the historical vaccination. Thus you may have breakthrough infections and this might affect other interventions to initialize a population.
Parameters:  vaccine (dict/str) – which vaccine to use; see below for dict parameters
 label (str) – if vaccine is supplied as a dict, the name of the vaccine
 days (int/arr) – the day or array of days to apply the interventions
 prob (float) – probability of being vaccinated (i.e., fraction of the population)
 subtarget (dict) – subtarget intervention to people with particular indices (see test_num() for details)
 compliance (float/arr) – compliance of the person to take each dose (if scalar then applied per dose)
 kwargs (dict) – passed to Intervention()
If
vaccine
is supplied as a dictionary, it must have the following parameters:nab_eff
: the waning efficacy of neutralizing antibodies at preventing infectionnab_init
: the initial antibody level (higher = more protection)nab_boost
: how much of a boost being vaccinated on top of a previous dose or natural infection providesdoses
: the number of doses required to be fully vaccinatedinterval
: the interval between doses entries for efficacy against each of the strains (e.g.
b117
)
See
parameters.py
for additional examples of these parameters.Example:
pfizer = cv.historical_vaccinate_prob(vaccine='pfizer', days=np.arange(30,0), prob=0.007) # 30day vaccination campaign cv.Sim(interventions=pfizer).run().plot()
New in version 3.1.0.

static
process_days
(sim, days, return_dates=False)[source]¶ Ensure lists of days are in consistent format. Used by change_beta, clip_edges, and some analyzers. Optionally return dates as well as days. If days is callable, leave unchanged.

static
estimate_prob
(duration, coverage)[source]¶ Estimate the perday probability to achieve desired population coverage for a campaign of fixed duration and fixed perday probability of a person being vaccinated
Parameters:  duration – length of campign in days
 coverage – target coverage of campaign
Example:
prob = historical_vaccinate.estimate_prob(duration=180, coverage=0.70)

class
historical_wave
(days_prior, prob, dist=None, subtarget=None, variant=None, **kwargs)[source]¶ Bases:
covasim.interventions.Intervention
Imprint a historical (pre t=0) wave of infections in the population NAbs
Parameters:  days_prior (int/str/list) – offset relative to t=0 for the wave (median/par1 value) or median date if a string like “20211115”
 prob (float/list) – probability of infection during the wave
 dist (dict/list) – passed to covasim.utils.sample to set wave shape (default gaussian with FWHM of 5 weeks)
 subtarget (dict/list) – subtarget intervention to people with particular indices (see test_num() for details)
 variants (str/list) – name of variant associated with the wave
 kwargs (dict) – passed to Intervention()
 Example::
 cv.Sim(interventions=cv.historical_wave(120, 0.30)).run().plot()
New in version 3.1.0.