BaseSim#
- class BaseSim(*args, **kwargs)[source]#
Bases:
ParsObj
The BaseSim class stores various methods useful for the Sim that are not directly related to simulating the epidemic. It is not used outside of the Sim object, so the separation of methods into the BaseSim and Sim classes is purely to keep each one of manageable size.
Attributes
Create a vector of dates
Count the number of people -- if it fails, assume none
Count the number of time points
Get the total population size, i.e. the number of agents times the scale factor -- if it fails, assume none.
Create a time vector
Methods
- update_pars(pars=None, create=False, **kwargs)[source]#
Ensure that metaparameters get used properly before being updated
- set_seed(seed=-1)[source]#
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
- 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)[source]#
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)[source]#
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(which='main')[source]#
Get the actual results objects, not other things stored in sim.results.
If which is ‘main’, return only the main results keys. If ‘variant’, return only variant keys. If ‘all’, return all keys.
- export_results(for_json=True, filename=None, indent=2, *args, **kwargs)[source]#
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)[source]#
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)[source]#
Export results and parameters 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_df(date_index=False)[source]#
Export results to a pandas dataframe
- Parameters:
date_index (bool) – if True, use the date as the index
- to_excel(filename=None, skip_pars=None)[source]#
Export parameters and results as Excel format
- Parameters:
filename (str) – if None, return string; else, write to file
skip_pars (list) – if provided, a custom list parameters to exclude
- Returns:
An sc.Spreadsheet with an Excel file, or writes the file to disk
- shrink(skip_attrs=None, in_place=True)[source]#
“Shrinks” the simulation by removing the people and other memory-intensive attributes (e.g., some interventions and analyzers), and returns a copy of the “shrunken” simulation. Used to reduce the memory required for RAM or for saved files.
- Parameters:
skip_attrs (list) – a list of attributes to skip (remove) in order to perform the shrinking; default “people”
in_palce (bool) – whether to perform the shrinking in place (default), or return a shrunken copy instead
- Returns:
a Sim object with the listed attributes removed
- Return type:
shrunken (Sim)
- save(filename=None, keep_people=None, skip_attrs=None, **kwargs)[source]#
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
- static load(filename, *args, **kwargs)[source]#
Load from disk from a gzipped pickle.
- Parameters:
filename (str) – the name or path of the file to load from
kwargs – passed to cv.load()
- Returns:
the loaded simulation object
- Return type:
sim (Sim)
Example:
sim = cv.Sim.load('my-simulation.sim')
- get_interventions(label=None, partial=False, as_inds=False)[source]#
Find the matching intervention(s) by label, index, or type. If None, return all interventions. If the label provided is “summary”, then print a summary of the interventions (index, label, type).
- Parameters:
label (str, int, Intervention, list) – the label, index, or type of intervention to get; if a list, iterate over one of those types
partial (bool) – if true, return partial matches (e.g. ‘beta’ will match all beta interventions)
as_inds (bool) – if true, return matching indices instead of the actual interventions
Examples:
tp = cv.test_prob(symp_prob=0.1) cb1 = cv.change_beta(days=5, changes=0.3, label='NPI') cb2 = cv.change_beta(days=10, changes=0.3, label='Masks') sim = cv.Sim(interventions=[tp, cb1, cb2]) cb1, cb2 = sim.get_interventions(cv.change_beta) tp, cb2 = sim.get_interventions([0,2]) ind = sim.get_interventions(cv.change_beta, as_inds=True) # Returns [1,2] sim.get_interventions('summary') # Prints a summary
- get_intervention(label=None, partial=False, first=False, die=True)[source]#
Like get_interventions(), find the matching intervention(s) by label, index, or type. If more than one intervention matches, return the last by default. If no label is provided, return the last intervention in the list.
- Parameters:
label (str, int, Intervention, list) – the label, index, or type of intervention to get; if a list, iterate over one of those types
partial (bool) – if true, return partial matches (e.g. ‘beta’ will match all beta interventions)
first (bool) – if true, return first matching intervention (otherwise, return last)
die (bool) – whether to raise an exception if no intervention is found
Examples:
tp = cv.test_prob(symp_prob=0.1) cb = cv.change_beta(days=5, changes=0.3, label='NPI') sim = cv.Sim(interventions=[tp, cb]) cb = sim.get_intervention('NPI') cb = sim.get_intervention('NP', partial=True) cb = sim.get_intervention(cv.change_beta) cb = sim.get_intervention(1) cb = sim.get_intervention() tp = sim.get_intervention(first=True)