covasim.sim module

Defines the Sim class, Covasim’s core class.

class Sim(pars=None, datafile=None, label=None, simfile=None, popfile=None, people=None, version=None, **kwargs)[source]

Bases: covasim.base.BaseSim

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.

  • pars (dict) – parameters to modify from their default values
  • datafile (str/df) – filename of (Excel, CSV) data file to load, or a pandas dataframe of the data
  • datacols (list) – list of column names of the data to load
  • label (str) – the name of the simulation (useful to distinguish in batch runs)
  • simfile (str) – the filename for this simulation, if it’s saved
  • popfile (str) – if supplied, load the population from this file
  • people (varies) – if supplied, use these pre-generated people (as a dict, SynthPop, or People object) instead of loading or generating new ones
  • version (str) – if supplied, use default parameters from this version of Covasim instead of the latest
  • kwargs (dict) – additional parameters; passed to cv.make_pars()


sim = cv.Sim()
sim = cv.Sim(pop_size=10e3, datafile='my_data.xlsx', label='Sim with data')
load_data(datafile=None, verbose=None, **kwargs)[source]

Load the data to calibrate against, if provided

initialize(reset=False, init_infections=True, **kwargs)[source]

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.

  • reset (bool) – whether or not to reset people even if they already exist
  • init_infections (bool) – whether to initialize infections (default true so sim is ready, but can’t reuse people then)
  • kwargs (dict) – passed to init_people

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).

reset_layer_pars(layer_keys=None, force=False)[source]

Reset the parameters to match the population.

  • layer_keys (list) – override the default layer keys (use stored keys by default)
  • force (bool) – reset the parameters even if they already exist

Handle layer parameters, since they need to be validated after the population creation, rather than before.


Some parameters can take multiple types; this makes them consistent.

Parameters:validate_layers (bool) – whether to validate layer parameters as well via validate_layer_pars() – usually yes, except during initialization

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

load_population(popfile=None, init_people=True, **kwargs)[source]

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.

  • popfile (str or obj) – if a string, name of the file; otherwise, the popdict or People object to load
  • init_people (bool) – whether to immediately convert the loaded popdict into an initialized People object
  • kwargs (dict) – passed to sim.init_people()
init_people(popdict=None, init_infections=False, reset=False, verbose=None, **kwargs)[source]

Create the people.

Use init_infections=False for creating a fresh People object for use in future simulations

  • popdict (any) – pre-generated people of various formats
  • init_infections (bool) – whether to initialize infections (default false when called directly)
  • reset (bool) – whether to regenerate the people even if they already exist
  • verbose (int) – detail to print
  • kwargs (dict) – passed to cv.make_people()

Initialize and validate the interventions


Initialize the analyzers


Initialize the variants


Initialize immunity matrices and precompute nab waning for each variant

init_infections(force=False, verbose=None)[source]

Initialize prior immunity and seed infections.

Parameters:force (bool) – initialize prior infections even if already initialized

Dynamically rescale the population – used during step()


Step the simulation forward in time. Usually, the user would use rather than calling sim.step() directly.

run(do_plot=False, until=None, restore_pars=True, reset_seed=True, verbose=None)[source]

Run the simulation.

  • do_plot (bool) – whether to plot
  • until (int/str) – day or date to run until
  • restore_pars (bool) – whether to make a copy of the parameters before the run and restore it after, so runs are repeatable
  • reset_seed (bool) – whether to reset the random number stream immediately before run
  • 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

A pointer to the sim object (with results modified in-place)

finalize(verbose=None, restore_pars=True)[source]

Compute final results


Perform final calculations on the results


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 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.

compute_doubling(window=3, max_doubling_time=30)[source]

Calculate doubling time using exponential approximation – a more detailed approach is in 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.

  • window (float) – the size of the window used (larger values are more accurate but less precise)
  • max_doubling_time (float) – doubling time could be infinite, so this places a bound on it

the doubling time results array

Return type:

doubling_time (array)

compute_r_eff(method='daily', smoothing=2, window=7)[source]

Effective reproduction number based on number of people each person infected.

  • method (str) – ‘daily’ uses daily infections, ‘infectious’ counts from the date infectious, ‘outcome’ counts from the date recovered/dead
  • smoothing (int) – the number of steps to smooth over for the ‘daily’ method
  • window (int) – the size of the window used for ‘infectious’ and ‘outcome’ calculations (larger values are more accurate but less precise)

the r_eff results array

Return type:

r_eff (array)


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:the generation time results
Return type:gen_time (dict)
compute_summary(full=None, t=None, update=True, output=False, require_run=False)[source]

Compute the summary dict and string for the sim. Used internally; see sim.summarize() for the user version.

  • full (bool) – whether or not to print all results (by default, only cumulative)
  • t (int/str) – day or date to compute summary for (by default, the last point)
  • update (bool) – whether to update the stored sim.summary
  • output (bool) – whether to return the summary
  • require_run (bool) – whether to raise an exception if simulations have not been run yet
summarize(full=False, t=None, sep=None, output=False)[source]

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).

  • full (bool) – whether or not to print all results (by default, only cumulative)
  • t (int/str) – day or date to compute summary for (by default, the last point)
  • sep (str) – thousands separator (default ‘,’)
  • output (bool) – whether to return the summary instead of printing it


sim = cv.Sim(label='Example sim', verbose=0) # Set to run silently # 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

Display a verbose description of a sim. See also sim.summarize() (medium length output) and sim.brief() (short output).

Parameters:output (bool) – if true, return a string instead of printing output


sim = cv.Sim(label='Example sim', verbose=0) # Set to run silently # Run the sim
sim.disp() # Displays detailed output

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:output (bool) – if true, return a string instead of printing output


sim = cv.Sim(label='Example sim', verbose=0) # Set to run silently # Run the sim
sim.brief() # Prints one-line output
compute_fit(*args, **kwargs)[source]

Compute the fit between the model and the data. See cv.Fit() for more information.

  • args (list) – passed to cv.Fit()
  • kwargs (dict) – passed to cv.Fit()

A Fit object


sim = cv.Sim(datafile='data.csv')
fit = sim.compute_fit()
calibrate(calib_pars, **kwargs)[source]

Automatically calibrate the simulation, returning a Calibration object (a type of analyzer). See the documentation on that class for more information.

  • calib_pars (dict) – a dictionary of the parameters to calibrate of the format dict(key1=[best, low, high])
  • kwargs (dict) – passed to cv.Calibration()

A Calibration object


sim = cv.Sim(datafile='data.csv')
calib_pars = dict(beta=[0.015, 0.010, 0.020])
calib = sim.calibrate(calib_pars, n_trials=50)
make_age_histogram(*args, output=True, **kwargs)[source]

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.

  • output (bool) – whether or not to return the age histogram; if not, store in sim.results
  • args (list) – passed to cv.age_histogram()
  • kwargs (dict) – passed to cv.age_histogram()


sim = cv.Sim()
agehist = sim.make_age_histogram()
make_transtree(*args, output=True, **kwargs)[source]

Create a TransTree (transmission tree) object, for analyzing the pattern of transmissions in the simulation. See cv.TransTree() for more information.

  • output (bool) – whether or not to return the TransTree; if not, store in sim.results
  • args (list) – passed to cv.TransTree()
  • kwargs (dict) – passed to cv.TransTree()


sim = cv.Sim()
tt = sim.make_transtree()
plot(*args, **kwargs)[source]

Plot the results of a single simulation.

  • to_plot (dict) – Dict of results to plot; see get_default_plots() for structure
  • do_save (bool) – Whether or not to save the figure
  • fig_path (str) – Path to save the figure
  • fig_args (dict) – Dictionary of kwargs to be passed to pl.figure()
  • plot_args (dict) – Dictionary of kwargs to be passed to pl.plot()
  • scatter_args (dict) – Dictionary of kwargs to be passed to pl.scatter()
  • axis_args (dict) – Dictionary of kwargs to be passed to pl.subplots_adjust()
  • legend_args (dict) – Dictionary of kwargs to be passed to pl.legend(); if show_legend=False, do not show
  • date_args (dict) – Control how the x-axis (dates) are shown (see below for explanation)
  • 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
  • style_args (dict) – Dictionary of kwargs to be passed to Matplotlib; options are dpi, font, fontsize, plus any valid key in pl.rcParams
  • n_cols (int) – Number of columns of subpanels to use for subplot
  • font_size (int) – Size of the font
  • font_family (str) – Font face
  • grid (bool) – Whether or not to plot gridlines
  • commaticks (bool) – Plot y-axis with commas rather than scientific notation
  • setylim (bool) – Reset the y limit to start at 0
  • log_scale (bool) – Whether or not to plot the y-axis with a log scale; if a list, panels to show as log
  • do_show (bool) – Whether or not to show the figure
  • colors (dict) – Custom color for each result, must be a dictionary with one entry per result key in to_plot
  • sep_figs (bool) – Whether to show separate figures for different results instead of subplots
  • fig (fig) – Handle of existing figure to plot into
  • ax (axes) – Axes instance to plot into
  • 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:Figure handle
Return type:fig


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 2.1.0: argument passing, date_args, and mpl_args
New in version 3.1.2: updated date arguments; mpl_args renamed style_args
plot_result(key, *args, **kwargs)[source]

Simple method to plot a single result. Useful for results that aren’t standard outputs. See sim.plot() for explanation of other arguments.

Parameters:key (str) – the key of the result to plot
Returns:Figure handle
Return type:fig


sim = cv.Sim().run()
diff_sims(sim1, sim2, skip_key_diffs=False, skip=None, output=False, die=False)[source]

Compute the difference of the summaries of two simulations, and print any values which differ.

  • sim1 (sim/dict) – either a simulation object or the sim.summary dictionary
  • sim2 (sim/dict) – ditto
  • skip_key_diffs (bool) – whether to skip keys that don’t match between sims
  • skip (list) – a list of values to skip
  • output (bool) – whether to return the output as a string (otherwise print)
  • die (bool) – whether to raise an exception if the sims don’t match
  • require_run (bool) – require that the simulations have been run


s1 = cv.Sim(beta=0.01)
s2 = cv.Sim(beta=0.02)
cv.diff_sims(s1, s2)
demo(preset=None, to_plot=None, scens=None, run_args=None, plot_args=None, **kwargs)[source]

Shortcut for cv.Sim().run().plot().

  • preset (str) – use a preset run configuration; currently the only option is “full”
  • to_plot (str) – what to plot
  • scens (dict) – dictionary of scenarios to run as a multisim, if preset=’full’
  • kwargs (dict) – passed to Sim()
  • run_args (dict) – passed to
  • plot_args (dict) – passed to sim.plot()


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
exception AlreadyRunError[source]

Bases: RuntimeError

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 and not taking any timesteps, would be an inadvertent error.