covasim.base module¶
Base classes for Covasim. These classes handle a lot of the boilerplate of the People and Sim classes (e.g. loading, saving, key lookups, etc.), so those classes can be focused on the disease-specific functionality.
-
class
covasim.base.
ParsObj
(pars)¶ Bases:
sciris.sc_utils.prettyobj
A class based around performing operations on a self.pars dict.
-
update_pars
(pars=None, create=False)¶ Update internal dict with new pars.
- Parameters
pars (dict) – the parameters to update (if None, do nothing)
create (bool) – if create is False, then raise a KeyNotFoundError if the key does not already exist
-
-
class
covasim.base.
Result
(name=None, npts=None, scale='dynamic', color=None)¶ Bases:
object
Stores a single result – by default, acts like an array.
- Parameters
name (str) – name of this result, e.g. new_infections
npts (int) – if values is None, precreate it to be of this length
scale (str) – whether or not the value scales by population size; options are “dynamic”, “static”, or False
color (str/arr) – default color for plotting (hex or RGB notation)
Example:
import covasim as cv r1 = cv.Result(name='test1', npts=10) r1[:5] = 20 print(r1.values)
-
property
npts
¶
-
class
covasim.base.
BaseSim
(*args, **kwargs)¶ Bases:
covasim.base.ParsObj
The BaseSim class handles the running of the simulation: the number of people, number of time points, and the parameters of the simulation.
-
set_seed
(seed=- 1)¶ Set the seed for the random number stream from the stored or supplied value
- Parameters
seed (None or int) – if no argument, use current seed; if None, randomize; otherwise, use and store supplied seed
- Returns
None
-
property
n
¶ Count the number of people – if it fails, assume none
-
property
scaled_pop_size
¶ Get the total population size, i.e. the number of agents times the scale factor – if it fails, assume none
-
property
npts
¶ Count the number of time points
-
property
tvec
¶ Create a time vector
-
property
datevec
¶ Create a vector of dates
- Returns
Array of datetime instances containing the date associated with each simulation time step
-
day
(day, *args)¶ Convert a string, date/datetime object, or int to a day (int).
- Parameters
day (str, date, int, or list) – convert any of these objects to a day relative to the simulation’s start day
- Returns
the day(s) in simulation time
- Return type
days (int or str)
Example:
sim.day('2020-04-05') # Returns 35
-
date
(ind, *args, dateformat=None, as_date=False)¶ Convert one or more integer days of simulation time to a date/list of dates – by default returns a string, or returns a datetime Date object if as_date is True. See also cv.date(), which provides a partly overlapping set of date conversion features.
- Parameters
ind (int, list, or array) – the index day(s) in simulation time (NB: strings and date objects are accepted, and will be passed unchanged)
args (list) – additional day(s)
dateformat (str) – the format to return the date in
as_date (bool) – whether to return as a datetime date instead of a string
- Returns
the date(s) corresponding to the simulation day(s)
- Return type
dates (str, Date, or list)
Examples:
sim = cv.Sim() sim.date(34) # Returns '2020-04-04' sim.date([34, 54]) # Returns ['2020-04-04', '2020-04-24'] sim.date([34, '2020-04-24']) # Returns ['2020-04-04', '2020-04-24'] sim.date(34, 54, as_date=True) # Returns [datetime.date(2020, 4, 4), datetime.date(2020, 4, 24)]
-
result_keys
()¶ Get the actual results objects, not other things stored in sim.results
-
copy
()¶ Returns a deep copy of the sim
-
export_results
(for_json=True, filename=None, indent=2, *args, **kwargs)¶ Convert results to dict – see also to_json().
The results written to Excel must have a regular table shape, whereas for the JSON output, arbitrary data shapes are supported.
- Parameters
for_json (bool) – if False, only data associated with Result objects will be included in the converted output
filename (str) – filename to save to; if None, do not save
indent (int) – indent (int): if writing to file, how many indents to use per nested level
args (list) – passed to savejson()
kwargs (dict) – passed to savejson()
- Returns
dictionary representation of the results
- Return type
resdict (dict)
-
export_pars
(filename=None, indent=2, *args, **kwargs)¶ Return parameters for JSON export – see also to_json().
This method is required so that interventions can specify their JSON-friendly representation.
- Parameters
filename (str) – filename to save to; if None, do not save
indent (int) – indent (int): if writing to file, how many indents to use per nested level
args (list) – passed to savejson()
kwargs (dict) – passed to savejson()
- Returns
a dictionary containing all the parameter values
- Return type
pardict (dict)
-
to_json
(filename=None, keys=None, tostring=False, indent=2, verbose=False, *args, **kwargs)¶ Export results as JSON.
- Parameters
filename (str) – if None, return string; else, write to file
keys (str or list) – attributes to write to json (default: results, parameters, and summary)
tostring (bool) – if not writing to file, whether to write to string (alternative is sanitized dictionary)
indent (int) – if writing to file, how many indents to use per nested level
verbose (bool) – detail to print
args (list) – passed to savejson()
kwargs (dict) – passed to savejson()
- Returns
A unicode string containing a JSON representation of the results, or writes the JSON file to disk
Examples:
json = sim.to_json() sim.to_json('results.json') sim.to_json('summary.json', keys='summary')
-
to_excel
(filename=None)¶ Export results as XLSX
- Parameters
filename (str) – if None, return string; else, write to file
- Returns
An sc.Spreadsheet with an Excel file, or writes the file to disk
-
shrink
(skip_attrs=None, in_place=True)¶ “Shrinks” the simulation by removing the people, and returns a copy of the “shrunken” simulation. Used to reduce the memory required for saved files.
- Parameters
skip_attrs (list) – a list of attributes to skip in order to perform the shrinking; default “people”
- Returns
a Sim object with the listed attributes removed
- Return type
shrunken_sim (Sim)
-
save
(filename=None, keep_people=None, skip_attrs=None, **kwargs)¶ Save to disk as a gzipped pickle.
- Parameters
filename (str or None) – the name or path of the file to save to; if None, uses stored
kwargs – passed to sc.makefilepath()
- Returns
the validated absolute path to the saved file
- Return type
filename (str)
Example:
sim.save() # Saves to a .sim file with the date and time of creation by default
-
-
class
covasim.base.
BasePeople
(pars=None, **kwargs)¶ Bases:
sciris.sc_utils.prettyobj
A class to handle all the boilerplate for people – note that everything interesting happens in the People class.
- Parameters
pars (dict) – a dictionary with, at minimum, keys ‘pop_size’ and ‘n_days’
-
set
(key, value, die=True)¶ Ensure sizes and dtypes match
-
get
(key)¶ Convenience method – key can be string or list of strings
-
true
(key)¶ Return indices matching the condition
-
false
(key)¶ Return indices not matching the condition
-
defined
(key)¶ Return indices of people who are not-nan
-
not_defined
(key)¶ Return indices of people who are nan
-
count
(key)¶ Count the number of people for a given key
-
count_not
(key)¶ Count the number of people who do not have a property for a given key
-
set_pars
(pars)¶ Very simple method to re-link the parameters stored in the people object to the sim containing it: included simply for the sake of being explicit.
-
keys
()¶ Returns keys for all properties of the people object
-
person_keys
()¶ Returns keys specific to a person (e.g., their age)
-
state_keys
()¶ Returns keys for different states of a person (e.g., symptomatic)
-
date_keys
()¶ Returns keys for different event dates (e.g., date a person became symptomatic)
-
dur_keys
()¶ Returns keys for different durations (e.g., the duration from exposed to infectious)
-
layer_keys
()¶ Get the available contact keys – try contacts first, then beta_layer
-
indices
()¶ The indices of each people array
-
validate
(die=True, verbose=False)¶
-
to_df
()¶ Convert to a Pandas dataframe
-
to_arr
()¶ Return as numpy array
-
person
(ind)¶ Method to create person from the people
-
to_people
()¶ Return all people as a list
-
from_people
(people, resize=True)¶ Convert a list of people back into a People object
-
init_contacts
(reset=False)¶ Initialize the contacts dataframe with the correct columns and data types
-
add_contacts
(contacts, lkey=None, beta=None)¶ Add new contacts to the array
-
make_edgelist
(contacts)¶ Parse a list of people with a list of contacts per person and turn it into an edge list.
-
static
remove_duplicates
(df)¶ Sort the dataframe and remove duplicates – note, not extensively tested
-
class
covasim.base.
Person
(pars=None, uid=None, age=- 1, sex=- 1, contacts=None)¶ Bases:
sciris.sc_utils.prettyobj
Class for a single person. Note: this is largely deprecated since sim.people is now based on arrays rather than being a list of people.
-
class
covasim.base.
FlexDict
¶ Bases:
dict
A dict that allows more flexible element access: in addition to obj[‘a’], also allow obj[0]. Lightweight implementation of the Sciris odict class.
-
keys
() → a set-like object providing a view on D’s keys¶
-
values
() → an object providing a view on D’s values¶
-
items
() → a set-like object providing a view on D’s items¶
-
-
class
covasim.base.
Contacts
(layer_keys=None)¶ Bases:
covasim.base.FlexDict
A simple (for now) class for storing different contact layers.
-
class
covasim.base.
Layer
(**kwargs)¶ Bases:
covasim.base.FlexDict
A small class holding a single layer of contacts
-
meta_keys
()¶ Return the keys for the layer’s meta information – i.e., p1, p2, beta
-
validate
()¶ Check the integrity of the layer: right types, right lengths
-
pop_inds
(inds)¶ “Pop” the specified indices from the edgelist and return them as a dict. Returns in the right format to be used with layer.append().
- Parameters
inds (int, array, slice) – the indices to be removed
-
append
(contacts)¶ Append contacts to the current layer.
- Parameters
contacts (dict) – a dictionary of arrays with keys p1,p2,beta, as returned from layer.pop_inds()
-
to_df
()¶ Convert to dataframe
-
from_df
(df)¶ Convert from a dataframe
-
find_contacts
(inds, as_array=True)¶ Find all contacts of the specified people
For some purposes (e.g. contact tracing) it’s necessary to find all of the contacts associated with a subset of the people in this layer. Since contacts are bidirectional it’s necessary to check both P1 and P2 for the target indices. The return type is a Set so that there is no duplication of indices (otherwise if the Layer has explicit symmetric interactions, they could appear multiple times). This is also for performance so that the calling code doesn’t need to perform its own unique() operation. Note that this cannot be used for cases where multiple connections count differently than a single infection, e.g. exposure risk.
- Parameters
inds (array) – indices of people whose contacts to return
as_array (bool) – if true, return as sorted array (otherwise, return as unsorted set)
- Returns
a set of indices for pairing partners
- Return type
contact_inds (array)
Example: If there were a layer with - P1 = [1,2,3,4] - P2 = [2,3,1,4] Then find_contacts([1,3]) would return {1,2,3}
-