sim
sim
Defines the Sim class, Covasim’s core class.
Classes
| Name | Description |
|---|---|
| AlreadyRunError | This error is raised if a simulation is run in such a way that no timesteps |
| Sim | The Sim class handles the running of the simulation: the creation of the |
AlreadyRunError
sim.AlreadyRunError()This error is raised if a simulation is run in such a way that no timesteps will be taken. This error is a distinct type so that it can be safely caught and ignored if required, but it is anticipated that most of the time, calling sim.run() and not taking any timesteps, would be an inadvertent error.
Sim
sim.Sim(
pars=None,
datafile=None,
label=None,
simfile=None,
popfile=None,
people=None,
version=None,
**kwargs,
)The Sim class handles the running of the simulation: the creation of the population and the dynamics of the epidemic. This class handles the mechanics of the actual simulation, while BaseSim takes care of housekeeping (saving, loading, exporting, etc.). Please see the BaseSim class for additional methods.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| pars | dict | parameters to modify from their default values | None |
| datafile | str / df |
filename of (Excel, CSV) data file to load, or a pandas dataframe of the data | None |
| datacols | list | list of column names of the data to load | required |
| label | str | the name of the simulation (useful to distinguish in batch runs) | None |
| simfile | str | the filename for this simulation, if it’s saved | None |
| popfile | str | if supplied, load the population from this file | None |
| people | varies |
if supplied, use these pre-generated people (as a dict, SynthPop, or People object) instead of loading or generating new ones | None |
| version | str | if supplied, use default parameters from this version of Covasim instead of the latest | None |
| kwargs | dict | additional parameters; passed to cv.make_pars() |
{} |
Examples::
sim = cv.Sim()
sim = cv.Sim(pop_size=10e3, datafile='my_data.xlsx', label='Sim with data')
Methods
| Name | Description |
|---|---|
| brief | Print a one-line description of a sim. See also sim.disp() (detailed output) |
| calibrate | Automatically calibrate the simulation, returning a Calibration object |
| compute_doubling | Calculate doubling time using exponential approximation – a more detailed |
| compute_fit | Compute the fit between the model and the data. See cv.Fit() for more |
| compute_gen_time | Calculate the generation time (or serial interval). There are two |
| compute_r_eff | Effective reproduction number based on number of people each person infected. |
| compute_results | Perform final calculations on the results |
| compute_states | Compute prevalence, incidence, and other states. Prevalence is the current |
| compute_summary | Compute the summary dict and string for the sim. Used internally; see |
| compute_yield | Compute test yield – number of positive tests divided by the total number |
| disp | Display a verbose description of a sim. See also sim.summarize() (medium |
| finalize | Compute final results |
| init_analyzers | Initialize the analyzers |
| init_immunity | Initialize immunity matrices and precompute nab waning for each variant |
| init_infections | Initialize prior immunity and seed infections. |
| init_interventions | Initialize and validate the interventions |
| init_people | Create the people. |
| init_results | Create the main results structure. |
| init_variants | Initialize the variants |
| initialize | Perform all initializations on the sim. |
| layer_keys | Attempt to retrieve the current layer keys, in the following order: from |
| load_data | Load the data to calibrate against, if provided |
| load_population | Load the population dictionary from file – typically done automatically |
| make_age_histogram | Calculate the age histograms of infections, deaths, diagnoses, etc. See |
| make_transtree | Create a TransTree (transmission tree) object, for analyzing the pattern |
| plot | Plot the results of a single simulation. |
| plot_result | Simple method to plot a single result. Useful for results that aren’t |
| rescale | Dynamically rescale the population – used during step() |
| reset_layer_pars | Reset the parameters to match the population. |
| run | Run the simulation. |
| step | Step the simulation forward in time. Usually, the user would use sim.run() |
| summarize | Print a medium-length summary of the simulation, drawing from the last time |
| validate_layer_pars | Handle layer parameters, since they need to be validated after the population |
| validate_pars | Some parameters can take multiple types; this makes them consistent. |
brief
sim.Sim.brief(output=False)Print a one-line description of a sim. See also sim.disp() (detailed output) and sim.summarize() (medium length output). The symbol “⚙” is used to show infections, and “☠” is used to show deaths.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| output | bool | if true, return a string instead of printing output | False |
Example::
sim = cv.Sim(label='Example sim', verbose=0) # Set to run silently
sim.run() # Run the sim
sim.brief() # Prints one-line output
calibrate
sim.Sim.calibrate(calib_pars, **kwargs)Automatically calibrate the simulation, returning a Calibration object (a type of analyzer). See the documentation on that class for more information.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| calib_pars | dict | a dictionary of the parameters to calibrate of the format dict(key1=[best, low, high]) | required |
| kwargs | dict | passed to cv.Calibration() | {} |
Returns
| Name | Type | Description |
|---|---|---|
| A Calibration object |
Example::
sim = cv.Sim(datafile='data.csv')
calib_pars = dict(beta=[0.015, 0.010, 0.020])
calib = sim.calibrate(calib_pars, n_trials=50)
calib.plot()
compute_doubling
sim.Sim.compute_doubling(window=3, max_doubling_time=30)Calculate doubling time using exponential approximation – a more detailed approach is in utils.py. Compares infections at time t to infections at time t-window, and uses that to compute the doubling time. For example, if there are 100 cumulative infections on day 12 and 200 infections on day 19, doubling time is 7 days.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| window | float | the size of the window used (larger values are more accurate but less precise) | 3 |
| max_doubling_time | float | doubling time could be infinite, so this places a bound on it | 30 |
Returns
| Name | Type | Description |
|---|---|---|
| doubling_time | array | the doubling time results array |
compute_fit
sim.Sim.compute_fit(*args, **kwargs)Compute the fit between the model and the data. See cv.Fit() for more information.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| args | list | passed to cv.Fit() | () |
| kwargs | dict | passed to cv.Fit() | {} |
Returns
| Name | Type | Description |
|---|---|---|
| A Fit object |
Example::
sim = cv.Sim(datafile='data.csv')
sim.run()
fit = sim.compute_fit()
fit.plot()
compute_gen_time
sim.Sim.compute_gen_time()Calculate the generation time (or serial interval). There are two ways to do this calculation. The ‘true’ interval (exposure time to exposure time) or ‘clinical’ (symptom onset to symptom onset).
Returns
| Name | Type | Description |
|---|---|---|
| gen_time | dict | the generation time results |
compute_r_eff
sim.Sim.compute_r_eff(method='daily', smoothing=2, window=7)Effective reproduction number based on number of people each person infected.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| method | str | ‘daily’ uses daily infections, ‘infectious’ counts from the date infectious, ‘outcome’ counts from the date recovered/dead | 'daily' |
| smoothing | int | the number of steps to smooth over for the ‘daily’ method | 2 |
| window | int | the size of the window used for ‘infectious’ and ‘outcome’ calculations (larger values are more accurate but less precise) | 7 |
Returns
| Name | Type | Description |
|---|---|---|
| r_eff | array | the r_eff results array |
compute_results
sim.Sim.compute_results(verbose=None)Perform final calculations on the results
compute_states
sim.Sim.compute_states()Compute prevalence, incidence, and other states. Prevalence is the current number of infected people divided by the number of people who are alive. Incidence is the number of new infections per day divided by the susceptible population. Also calculates the number of people alive, the number preinfectious, the number removed, and recalculates susceptibles to handle scaling.
compute_summary
sim.Sim.compute_summary(
full=None,
t=None,
update=True,
output=False,
require_run=False,
)Compute the summary dict and string for the sim. Used internally; see sim.summarize() for the user version.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| full | bool | whether or not to print all results (by default, only cumulative) | None |
| t | int / str | day or date to compute summary for (by default, the last point) | None |
| update | bool | whether to update the stored sim.summary | True |
| output | bool | whether to return the summary | False |
| require_run | bool | whether to raise an exception if simulations have not been run yet | False |
compute_yield
sim.Sim.compute_yield()Compute test yield – number of positive tests divided by the total number of tests, also called test positivity rate. Relative yield is with respect to prevalence: i.e., how the yield compares to what the yield would be from choosing a person at random from the population.
disp
sim.Sim.disp(output=False)Display a verbose description of a sim. See also sim.summarize() (medium length output) and sim.brief() (short output).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| output | bool | if true, return a string instead of printing output | False |
Example::
sim = cv.Sim(label='Example sim', verbose=0) # Set to run silently
sim.run() # Run the sim
sim.disp() # Displays detailed output
finalize
sim.Sim.finalize(verbose=None, restore_pars=True)Compute final results
init_analyzers
sim.Sim.init_analyzers()Initialize the analyzers
init_immunity
sim.Sim.init_immunity(create=False)Initialize immunity matrices and precompute nab waning for each variant
init_infections
sim.Sim.init_infections(force=False, verbose=None)Initialize prior immunity and seed infections.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| force | bool | initialize prior infections even if already initialized | False |
init_interventions
sim.Sim.init_interventions()Initialize and validate the interventions
init_people
sim.Sim.init_people(
popdict=None,
init_infections=False,
reset=False,
verbose=None,
**kwargs,
)Create the people.
Use init_infections=False for creating a fresh People object for use in future simulations
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| popdict | any | pre-generated people of various formats | None |
| init_infections | bool | whether to initialize infections (default false when called directly) | False |
| reset | bool | whether to regenerate the people even if they already exist | False |
| verbose | int | detail to print | None |
| kwargs | dict | passed to cv.make_people() | {} |
init_results
sim.Sim.init_results()Create the main results structure. We differentiate between flows, stocks, and cumulative results The prefix “new” is used for flow variables, i.e. counting new events (infections/deaths/recoveries) on each timestep The prefix “n” is used for stock variables, i.e. counting the total number in any given state (sus/inf/rec/etc) on any particular timestep The prefix “cum” is used for cumulative variables, i.e. counting the total number that have ever been in a given state at some point in the sim Note that, by definition, n_dead is the same as cum_deaths and n_recovered is the same as cum_recoveries, so we only define the cumulative versions
init_variants
sim.Sim.init_variants()Initialize the variants
initialize
sim.Sim.initialize(reset=False, init_infections=True, **kwargs)Perform all initializations on the sim.
This includes validating the parameters, setting the random number seed, creating the results structure, initializing the people, validating the layer parameters (which requires the people), and initializing the interventions.
Note: to create a population to save for later use, use init_infections=False. This will then create a fresh People object which other sims can finish initializing.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| reset | bool | whether or not to reset people even if they already exist | False |
| init_infections | bool | whether to initialize infections (default true so sim is ready, but can’t reuse people then) | True |
| kwargs | dict | passed to init_people | {} |
layer_keys
sim.Sim.layer_keys()Attempt to retrieve the current layer keys, in the following order: from the people object (for an initialized sim), from the popdict (for one in the process of being initialized), from the beta_layer parameter (for an uninitialized sim), or by assuming a default (if none of the above are available).
load_data
sim.Sim.load_data(datafile=None, verbose=None, **kwargs)Load the data to calibrate against, if provided
load_population
sim.Sim.load_population(popfile=None, init_people=True, **kwargs)Load the population dictionary from file – typically done automatically as part of sim.initialize().
Supports loading either saved population dictionaries (popdicts, file ending .pop by convention), or ready-to-go People objects (file ending .ppl by convention). Either object an also be supplied directly. Once a population file is loaded, it is removed from the Sim object.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| popfile | str or obj |
if a string, name of the file; otherwise, the popdict or People object to load | None |
| init_people | bool | whether to immediately convert the loaded popdict into an initialized People object | True |
| kwargs | dict | passed to sim.init_people() |
{} |
make_age_histogram
sim.Sim.make_age_histogram(*args, output=True, **kwargs)Calculate the age histograms of infections, deaths, diagnoses, etc. See cv.age_histogram() for more information. This can be used alternatively to supplying the age histogram as an analyzer to the sim. If used this way, it can only record the final time point since the states of each person are not saved during the sim.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| output | bool | whether or not to return the age histogram; if not, store in sim.results | True |
| args | list | passed to cv.age_histogram() | () |
| kwargs | dict | passed to cv.age_histogram() | {} |
Example::
sim = cv.Sim()
sim.run()
agehist = sim.make_age_histogram()
agehist.plot()
make_transtree
sim.Sim.make_transtree(*args, output=True, **kwargs)Create a TransTree (transmission tree) object, for analyzing the pattern of transmissions in the simulation. See cv.TransTree() for more information.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| output | bool | whether or not to return the TransTree; if not, store in sim.results | True |
| args | list | passed to cv.TransTree() | () |
| kwargs | dict | passed to cv.TransTree() | {} |
Example::
sim = cv.Sim()
sim.run()
tt = sim.make_transtree()
plot
sim.Sim.plot(*args, **kwargs)Plot the results of a single simulation.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| to_plot | dict | Dict of results to plot; see get_default_plots() for structure | required |
| do_save | bool | Whether or not to save the figure | required |
| fig_path | str | Path to save the figure | required |
| fig_args | dict | Dictionary of kwargs to be passed to pl.figure() |
required |
| plot_args | dict | Dictionary of kwargs to be passed to pl.plot() |
required |
| scatter_args | dict | Dictionary of kwargs to be passed to pl.scatter() |
required |
| axis_args | dict | Dictionary of kwargs to be passed to pl.subplots_adjust() |
required |
| legend_args | dict | Dictionary of kwargs to be passed to pl.legend(); if show_legend=False, do not show |
required |
| date_args | dict | Control how the x-axis (dates) are shown (see below for explanation) | required |
| show_args | dict | Control which “extras” get shown: uncertainty bounds, data, interventions, ticks, the legend; additionally, “outer” will show the axes only on the outer plots | required |
| style_args | dict | Dictionary of kwargs to be passed to Matplotlib; options are dpi, font, fontsize, plus any valid key in pl.rcParams |
required |
| n_cols | int | Number of columns of subpanels to use for subplot | required |
| font_size | int | Size of the font | required |
| font_family | str | Font face | required |
| grid | bool | Whether or not to plot gridlines | required |
| commaticks | bool | Plot y-axis with commas rather than scientific notation | required |
| setylim | bool | Reset the y limit to start at 0 | required |
| log_scale | bool | Whether or not to plot the y-axis with a log scale; if a list, panels to show as log | required |
| do_show | bool | Whether or not to show the figure | required |
| colors | dict | Custom color for each result, must be a dictionary with one entry per result key in to_plot | required |
| sep_figs | bool | Whether to show separate figures for different results instead of subplots | required |
| fig | fig |
Handle of existing figure to plot into | required |
| ax | axes |
Axes instance to plot into | required |
| kwargs | dict | Parsed among figure, plot, scatter, date, and other settings (will raise an error if not recognized) | {} |
The optional dictionary “date_args” allows several settings for controlling how the x-axis of plots are shown, if this axis is dates. These options are:
- ``as_dates``: whether to format them as dates (else, format them as days since the start)
- ``dateformat``: string format for the date (if not provided, choose based on timeframe)
- ``rotation``: whether to rotate labels
- ``start``: the first day to plot
- ``end``: the last day to plot
- ``outer``: only show the date labels on the outer (bottom) plots
The show_args dictionary allows several other formatting options, such as:
- ``tight``: use tight layout for the figure (default false)
- ``maximize``: try to make the figure full screen (default false)
- ``outer``: only show outermost (bottom) date labels (default false)
Date, show, and other arguments can also be passed directly, e.g. sim.plot(tight=True).
For additional style options, see cv.options.with_style(), which is the final refuge of arguments that are not picked up by any of the other parsers, e.g. sim.plot(**{'ytick.direction':'in'}).
Returns
| Name | Type | Description |
|---|---|---|
| fig | Figure handle |
Examples::
sim = cv.Sim().run()
sim.plot() # Default plotting
sim.plot('overview') # Show overview
sim.plot('overview', maximize=True, outer=True, rotation=15) # Make some modifications to make plots easier to see
sim.plot(style='seaborn-whitegrid') # Use a built-in Matplotlib style
sim.plot(style='simple', font='Rosario', dpi=200) # Use the other house style with several customizations
New in version 3.1.2: updated date arguments; mpl_args renamed style_args
plot_result
sim.Sim.plot_result(key, *args, **kwargs)Simple method to plot a single result. Useful for results that aren’t standard outputs. See sim.plot() for explanation of other arguments.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| key | str | the key of the result to plot | required |
Returns
| Name | Type | Description |
|---|---|---|
| fig | Figure handle |
Example::
sim = cv.Sim().run()
sim.plot_result('r_eff')
rescale
sim.Sim.rescale()Dynamically rescale the population – used during step()
reset_layer_pars
sim.Sim.reset_layer_pars(layer_keys=None, force=False)Reset the parameters to match the population.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| layer_keys | list | override the default layer keys (use stored keys by default) | None |
| force | bool | reset the parameters even if they already exist | False |
run
sim.Sim.run(
do_plot=False,
until=None,
restore_pars=True,
reset_seed=True,
verbose=None,
)Run the simulation.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| do_plot | bool | whether to plot | False |
| until | int / str | day or date to run until | None |
| restore_pars | bool | whether to make a copy of the parameters before the run and restore it after, so runs are repeatable | True |
| reset_seed | bool | whether to reset the random number stream immediately before run | True |
| verbose | float | level of detail to print, e.g. -1 = one-line output, 0 = no output, 0.1 = print every 10th day, 1 = print every day | None |
Returns
| Name | Type | Description |
|---|---|---|
| A pointer to the sim object (with results modified in-place) |
step
sim.Sim.step()Step the simulation forward in time. Usually, the user would use sim.run() rather than calling sim.step() directly.
summarize
sim.Sim.summarize(full=False, t=None, sep=None, output=False)Print a medium-length summary of the simulation, drawing from the last time point in the simulation by default. Called by default at the end of a sim run. See also sim.disp() (detailed output) and sim.brief() (short output).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| full | bool | whether or not to print all results (by default, only cumulative) | False |
| t | int / str | day or date to compute summary for (by default, the last point) | None |
| sep | str | thousands separator (default ‘,’) | None |
| output | bool | whether to return the summary instead of printing it | False |
Examples::
sim = cv.Sim(label='Example sim', verbose=0) # Set to run silently
sim.run() # Run the sim
sim.summarize() # Print medium-length summary of the sim
sim.summarize(t=24, full=True) # Print a "slice" of all sim results on day 24
validate_layer_pars
sim.Sim.validate_layer_pars()Handle layer parameters, since they need to be validated after the population creation, rather than before.
validate_pars
sim.Sim.validate_pars(validate_layers=True)Some parameters can take multiple types; this makes them consistent.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| validate_layers | bool | whether to validate layer parameters as well via validate_layer_pars() – usually yes, except during initialization | True |
Functions
| Name | Description |
|---|---|
| demo | Shortcut for cv.Sim().run().plot(). |
| diff_sims | Compute the difference of the summaries of two simulations, and print any |
demo
sim.demo(
preset=None,
to_plot=None,
scens=None,
run_args=None,
plot_args=None,
**kwargs,
)Shortcut for cv.Sim().run().plot().
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| preset | str | use a preset run configuration; currently the only option is “full” | None |
| to_plot | str | what to plot | None |
| scens | dict | dictionary of scenarios to run as a multisim, if preset=‘full’ | None |
| kwargs | dict | passed to Sim() | {} |
| run_args | dict | passed to sim.run() | None |
| plot_args | dict | passed to sim.plot() | None |
Examples::
cv.demo() # Simplest example
cv.demo('full') # Full example
cv.demo('full', overview=True) # Plot all results
cv.demo(beta=0.020, run_args={'verbose':0}, plot_args={'to_plot':'overview'}) # Pass in custom values
diff_sims
sim.diff_sims(
sim1,
sim2,
skip_key_diffs=False,
skip=None,
output=False,
die=False,
)Compute the difference of the summaries of two simulations, and print any values which differ.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| sim1 | sim / dict | either a simulation object or the sim.summary dictionary | required |
| sim2 | sim / dict | ditto | required |
| skip_key_diffs | bool | whether to skip keys that don’t match between sims | False |
| skip | list | a list of values to skip | None |
| output | bool | whether to return the output as a string (otherwise print) | False |
| die | bool | whether to raise an exception if the sims don’t match | False |
| require_run | bool | require that the simulations have been run | required |
Example::
s1 = cv.Sim(beta=0.01)
s2 = cv.Sim(beta=0.02)
s1.run()
s2.run()
cv.diff_sims(s1, s2)