sim

sim

Defines the Sim class for Covasim on the Starsim base.

cv.Sim(ss.Sim) is a thin wrapper that assembles the Covasim modules – a cv.People, one cv.Network per contact layer, and a cv.COVID disease – and forwards to ss.Sim with a daily timestep. Per-layer transmissibility (Covasim’s beta * beta_layer) is carried on the disease. pop_infected agents are seeded exactly at t=0.

Passing people= / networks= / diseases= overrides the corresponding default; with diseases=, the COVID parameters (e.g. pop_infected, variants) must be set on the disease rather than the sim.

Classes

Name Description
Sim The Covasim simulation, on the Starsim base.

Sim

sim.Sim(
    pars=None,
    datafile=None,
    label=None,
    simfile=None,
    popfile=None,
    people=None,
    version=None,
    **kwargs,
)

The Covasim simulation, on the Starsim base.

Parameters can be supplied as a dict and/or as keyword arguments, using the v3 names (see cv.make_pars() for the full list and their defaults), e.g. cv.Sim(pop_size=10e3, pop_type='hybrid', beta=0.02). The COVID parameters are stored on the disease module (sim.diseases.covid.pars) and the sim-level ones in sim.pars; sim['key'] gets or sets either.

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
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 not supported in v4 (v3 populations cannot be loaded) None
people People optionally, the people to use instead of creating them None
version str if supplied, use default parameters from this version of Covasim instead of the latest None
kwargs dict additional parameters; also passed to ss.Sim (e.g. networks, diseases, connectors) {}

Methods

Name Description
brief Print (or return) a one-line summary of the sim (v3 Sim.brief). The symbol “⚙” is used to show
calibrate Automatically calibrate the simulation, returning a Calibration object. See the
compute_fit Compute the goodness-of-fit against self.data (v3 Sim.compute_fit); returns a cv.Fit.
compute_gen_time Calculate the generation time (or serial interval) (v3 Sim.compute_gen_time). There are two
compute_r_eff Effective reproduction number based on number of people each person infected (v3 Sim.compute_r_eff).
date Convert day index/indices to date string(s) relative to start_day (v3 Sim.date).
day Convert date(s) to the day index/indices relative to start_day (v3 Sim.day). Numbers are
export_pars Export the sim’s parameters to a JSON-compatible dict (the v3 BaseSim.export_pars): the v3
finalize_results Scale the results, skipping the references to the COVID results, which are scaled by the module
get_analyzer Same as get_intervention(), but for analyzers (the v3 Sim.get_analyzer).
get_analyzers Same as get_interventions(), but for analyzers (the v3 Sim.get_analyzers).
get_intervention Find the matching intervention by label, index, or type (the v3 Sim.get_intervention). If more than
get_interventions Find the matching intervention(s) by label, index, or type (the v3 Sim.get_interventions).
init Create the People (with Covasim’s age distribution), then initialize as usual.
init_results Initialize the results, then make the COVID results available at the top level, as in v3, e.g.
load Load a saved sim from disk; the v3 cv.Sim.load classmethod, via cv.load.
make_age_histogram Calculate the age histograms of infections, deaths, diagnoses, etc. (v3 Sim.make_age_histogram).
make_transtree Create a TransTree (transmission tree) object (v3 Sim.make_transtree). See cv.TransTree().
plot Plot the results of a single simulation.
plot_result Simple method to plot a single result. Useful for results that aren’t
save Save the sim to disk.
to_excel Export the results and parameters to an Excel workbook (the v3 Sim.to_excel), with a “Results”
brief
sim.Sim.brief(output=False)

Print (or return) a one-line summary of the sim (v3 Sim.brief). 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 it False
calibrate
sim.Sim.calibrate(calib_pars, **kwargs)

Automatically calibrate the simulation, returning a Calibration object. 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_sims()
compute_fit
sim.Sim.compute_fit(*args, **kwargs)

Compute the goodness-of-fit against self.data (v3 Sim.compute_fit); returns a cv.Fit.

compute_gen_time
sim.Sim.compute_gen_time()

Calculate the generation time (or serial interval) (v3 Sim.compute_gen_time). 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 (v3 Sim.compute_r_eff).

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
date
sim.Sim.date(*args, **kwargs)

Convert day index/indices to date string(s) relative to start_day (v3 Sim.date).

day
sim.Sim.day(day, *args)

Convert date(s) to the day index/indices relative to start_day (v3 Sim.day). Numbers are treated as days and returned as integers; a list or array gives a list or array, and None gives None.

Example::

sim = cv.Sim(start_day='2020-03-01')
sim.day('2020-03-05') # Returns 4
export_pars
sim.Sim.export_pars(filename=None, indent=2, **kwargs)

Export the sim’s parameters to a JSON-compatible dict (the v3 BaseSim.export_pars): the v3 parameters (see cv.make_pars()), by their v3 names, followed by the other COVID parameters. Interventions and analyzers are converted with their to_json() method.

Parameters
Name Type Description Default
filename str if given, also save the parameters to this JSON file None
indent int if saving, the JSON indent 2
kwargs dict passed to sc.savejson() {}
finalize_results
sim.Sim.finalize_results()

Scale the results, skipping the references to the COVID results, which are scaled by the module

get_analyzer
sim.Sim.get_analyzer(label=None, partial=False, first=False, die=True)

Same as get_intervention(), but for analyzers (the v3 Sim.get_analyzer).

get_analyzers
sim.Sim.get_analyzers(label=None, partial=False, as_inds=False)

Same as get_interventions(), but for analyzers (the v3 Sim.get_analyzers).

get_intervention
sim.Sim.get_intervention(label=None, partial=False, first=False, die=True)

Find the matching intervention by label, index, or type (the v3 Sim.get_intervention). If more than one intervention matches, return the last by default. If no label is provided, return the last intervention.

Parameters
Name Type Description Default
label (str, int, Intervention) the label, index, or type of intervention to get None
partial bool if true, return partial matches (e.g. ‘beta’ will match all beta interventions) False
first bool if true, return first matching intervention (otherwise, return last) False
die bool whether to raise an exception if no intervention is found True
get_interventions
sim.Sim.get_interventions(label=None, partial=False, as_inds=False)

Find the matching intervention(s) by label, index, or type (the v3 Sim.get_interventions). If None, return all interventions.

Parameters
Name Type Description Default
label (str, int, Intervention, list) the label, index, or type of intervention to get; if a list, iterate over one of those types None
partial bool if true, return partial matches (e.g. ‘beta’ will match all beta interventions) False
as_inds bool if true, return matching indices instead of the actual interventions False

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]
init
sim.Sim.init(*args, **kwargs)

Create the People (with Covasim’s age distribution), then initialize as usual.

init_results
sim.Sim.init_results()

Initialize the results, then make the COVID results available at the top level, as in v3, e.g. sim.results['cum_deaths'] and sim.results['variant']['new_infections_by_variant']. These are references to the module’s results (not copies).

load
sim.Sim.load(filename, *args, **kwargs)

Load a saved sim from disk; the v3 cv.Sim.load classmethod, via cv.load.

make_age_histogram
sim.Sim.make_age_histogram(*args, output=True, **kwargs)

Calculate the age histograms of infections, deaths, diagnoses, etc. (v3 Sim.make_age_histogram). See cv.age_histogram() for more information. This can be used instead of adding the age histogram as an analyzer to the sim, but it can only record the final time point.

Parameters
Name Type Description Default
output bool whether or not to return the age histogram; if not, store in sim.agehist True
args list passed to cv.age_histogram() ()
kwargs dict passed to cv.age_histogram() {}
make_transtree
sim.Sim.make_transtree(*args, output=True, **kwargs)

Create a TransTree (transmission tree) object (v3 Sim.make_transtree). See cv.TransTree().

Parameters
Name Type Description Default
output bool whether or not to return the TransTree; if not, store in sim.transtree True
args list passed to cv.TransTree() ()
kwargs dict passed to cv.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
fontsize int Size of the font required
font 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
- ``interval``:   the interval between x-axis ticks, in days

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 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
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')
save
sim.Sim.save(filename=None, keep_people=None, shrink=None, **kwargs)

Save the sim to disk.

By default the full sim is saved, including the people, so it can be rerun or continued.

Parameters
Name Type Description Default
filename str path to save to (defaults to the sim’s simfile). None
keep_people bool whether to keep the people (v3); keep_people=False is the same as shrink=True None
shrink bool drop the people and other large objects before saving (default False). None
kwargs passed through to ss.Sim.save / sc.makefilepath. {}
to_excel
sim.Sim.to_excel(filename=None, skip_pars=None)

Export the results and parameters to an Excel workbook (the v3 Sim.to_excel), with a “Results” sheet (from sim.to_df()) and a “Parameters” sheet (from sim.export_pars(), flattened).

Parameters
Name Type Description Default
filename str if given, save the workbook to this file None
skip_pars list the parameters to leave out (default: the variant and vaccine maps, as in v3) None
Returns
Name Type Description
An sc.Spreadsheet

Functions

Name Description
demo Shortcut for cv.Sim().run().plot() (the v3 cv.demo).

demo

sim.demo(
    preset=None,
    to_plot=None,
    scens=None,
    run_args=None,
    plot_args=None,
    **kwargs,
)

Shortcut for cv.Sim().run().plot() (the v3 cv.demo).

Parameters

Name Type Description Default
preset str ignored; kept for backwards compatibility None
to_plot str what to plot None
scens dict ignored; kept for backwards compatibility None
run_args dict passed to sim.run() None
plot_args dict passed to sim.plot() None
kwargs dict passed to Sim() {}

Example::

cv.demo(beta=0.020, run_args={'verbose':0})