covasim.run module¶
Functions and classes for running multiple Covasim runs.
-
covasim.run.
make_metapars
()¶ Create default metaparameters for a Scenarios run
-
class
covasim.run.
MultiSim
(sims=None, base_sim=None, quantiles=None, initialize=False, **kwargs)¶ Bases:
sciris.sc_utils.prettyobj
Class for running multiple copies of a simulation. The parameter n_runs controls how many copies of the simulation there will be, if a list of sims is not provided.
- Parameters
sims (Sim/list) – a single sim or a list of sims
base_sim (Sim) – the sim used for shared properties; if not supplied, the first of the sims provided
quantiles (dict) – the quantiles to use with reduce(), e.g. [0.1, 0.9] or {‘low : ‘0.1, ‘high’ : 0.9}
initialize (bool) – whether or not to initialize the sims (otherwise, initialize them during run)
kwargs (dict) – stored in run_args and passed to run()
- Returns
a MultiSim object
- Return type
msim
Examples:
sim = cv.Sim() # Create the sim msim = cv.MultiSim(sim, n_runs=5) # Create the multisim msim.run() # Run them in parallel msim.combine() # Combine into one sim msim.plot() # Plot results sim = cv.Sim() # Create the sim msim = cv.MultiSim(sim, n_runs=11, noise=0.1, keep_people=True) # Set up a multisim with noise msim.run() # Run msim.reduce() # Compute statistics msim.plot() # Plot sims = [cv.Sim(beta=0.015*(1+0.02*i)) for i in range(5)] # Create sims for sim in sims: sim.run() # Run sims in serial msim = cv.MultiSim(sims) # Convert to multisim msim.plot() # Plot as single sim
-
result_keys
()¶ Attempt to retrieve the results keys from the base sim
-
init_sims
(**kwargs)¶ Initialize the sims, but don’t actually run them. Syntax is the same as MultiSim.run(). Note: in most cases you can just call run() directly, there is no need to call this separately.
- Parameters
kwargs (dict) – passed to multi_run()
-
run
(reduce=False, combine=False, **kwargs)¶ Run the actual sims
- Parameters
reduce (bool) – whether or not to reduce after running (see reduce())
combine (bool) – whether or not to combine after running (see combine(), not compatible with reduce)
kwargs (dict) – passed to multi_run()
- Returns
None (modifies MultiSim object in place)
-
reset
()¶ Undo a combine() or reduce() by resetting the base sim, which, and results
-
reduce
(quantiles=None, output=False)¶ Combine multiple sims into a single sim with scaled results
-
combine
(output=False)¶ Combine multiple sims into a single sim with scaled results
-
compare
(t=- 1, sim_inds=None, output=False, do_plot=False, **kwargs)¶ Create a dataframe compare sims at a single point in time.
- Parameters
t (int/str) – the day (or date) to do the comparison; default, the end
sim_inds (list) – list of integers of which sims to include (default : all)
output (bool) – whether or not to return the comparison as a dataframe
do_plot (bool) – whether or not to plot the comparison (see also plot_compare())
kwargs (dict) – passed to plot_compare()
- Returns
a dataframe comparison
- Return type
df (dataframe)
-
plot
(to_plot=None, inds=None, plot_sims=False, color_by_sim=None, max_sims=5, colors=None, labels=None, alpha_range=None, plot_args=None, show_args=None, **kwargs)¶ Plot all the sims – arguments passed to Sim.plot(). The behavior depends on whether or not combine() or reduce() has been called. If so, this function by default plots only the combined/reduced sim (which you can override with plot_sims=True). Otherwise, it plots a separate line for each sim.
Note that this function is complex because it aims to capture the flexibility of both sim.plot() and scens.plot(). By default, if combine() or reduce() has been used, it will resemble sim.plot(); otherwise, it will resemble scens.plot(). This can be changed via color_by_sim, together with the other options.
- Parameters
to_plot (list) – list or dict of which results to plot; see cv.get_sim_plots() for structure
inds (list) – if not combined or reduced, the indices of the simulations to plot (if None, plot all)
plot_sims (bool) – whether to plot individual sims, even if combine() or reduce() has been used
color_by_sim (bool) – if True, set colors based on the simulation type; otherwise, color by result type; True implies a scenario-style plotting, False implies sim-style plotting
max_sims (int) – maximum number of sims to use with color-by-sim; can be overriden by other options
colors (list) – if supplied, override default colors for color_by_sim
labels (list) – if supplied, override default labels for color_by_sim
alpha_range (list) – a 2-element list/tuple/array providing the range of alpha values to use to distinguish the lines
plot_args (dict) – passed to sim.plot()
show_args (dict) – passed to sim.plot()
kwargs (dict) – passed to sim.plot()
Examples:
sim = cv.Sim() msim = cv.MultiSim(sim) msim.run() msim.plot() # Plots individual sims msim.reduce() msim.plot() # Plots the combined sim
-
plot_result
(key, colors=None, labels=None, *args, **kwargs)¶ Convenience method for plotting – arguments passed to Sim.plot_result()
-
plot_compare
(t=- 1, sim_inds=None, log_scale=True, **kwargs)¶ Plot a comparison between sims, using bars to show different values for each result.
- Parameters
t (int) – index of results, passed to compare()
sim_inds (list) – which sims to include, passed to compare()
log_scale (bool) – whether to plot with a logarithmic x-axis
kwargs (dict) – standard plotting arguments, see Sim.plot() for explanation
- Returns
the figure handle
- Return type
fig (figure)
-
save
(filename=None, keep_people=False, **kwargs)¶ Save to disk as a gzipped pickle. Load with cv.load(filename) or cv.MultiSim.load(filename).
- Parameters
filename (str) – the name or path of the file to save to; if None, uses default
keep_people (bool) – whether or not to store the population in the Sim objects (NB, very large)
kwargs (dict) – passed to makefilepath()
- Returns
the validated absolute path to the saved file
- Return type
scenfile (str)
Example:
msim.save() # Saves to an .msim file
-
static
load
(msimfile, *args, **kwargs)¶ Load from disk from a gzipped pickle.
- Parameters
msimfile (str) – the name or path of the file to load from
kwargs – passed to cv.load()
- Returns
the loaded MultiSim object
- Return type
msim (MultiSim)
Example:
msim = cv.MultiSim.load('my-multisim.msim')
-
static
merge
(*args, base=False)¶ Convenience method for merging two MultiSim objects.
- Parameters
args (MultiSim) – the MultiSims to merge (either a list, or separate)
base (bool) – if True, make a new list of sims from the multisim’s two base sims; otherwise, merge the multisim’s lists of sims
- Returns
a new MultiSim object
- Return type
msim (MultiSim)
Examples:
mm1 = cv.MultiSim.merge(msim1, msim2, base=True) mm2 = cv.MultiSim.merge([m1, m2, m3, m4], base=False)
-
split
(inds=None, chunks=None)¶ Convenience method for splitting one MultiSim into several. You can specify either individual indices of simulations to extract, via inds, or consecutive chunks of indices, via chunks. If this function is called on a merged MultiSim, the chunks can be retrieved automatically and no arguments are necessary.
- Parameters
inds (list) – a list of lists of indices, with each list turned into a MultiSim
chunks (int or list) – if an int, split the MultiSim into chunks of that length; if a list return chunks of that many sims
- Returns
A list of MultiSim objects
Examples:
m1 = cv.MultiSim(cv.Sim(label='sim1'), initialize=True) m2 = cv.MultiSim(cv.Sim(label='sim2'), initialize=True) m3 = cv.MultiSim.merge(m1, m2) m3.run() m1b, m2b = m3.split() msim = cv.MultiSim(cv.Sim(), n_runs=6) msim.run() m1, m2 = msim.split(inds=[[0,2,4], [1,3,5]]) mlist1 = msim.split(chunks=[2,4]) # Equivalent to inds=[[0,1], [2,3,4,5]] mlist2 = msim.split(chunks=3) # Equivalent to inds=[[0,1,2], [3,4,5]]
-
summarize
(output=False)¶ Print a brief summary of the MultiSim
-
class
covasim.run.
Scenarios
(sim=None, metapars=None, scenarios=None, basepars=None, scenfile=None)¶ Bases:
covasim.base.ParsObj
Class for running multiple sets of multiple simulations – e.g., scenarios.
- Parameters
sim (Sim) – if supplied, use a pre-created simulation as the basis for the scenarios
metapars (dict) – meta-parameters for the run, e.g. number of runs; see make_metapars() for structure
scenarios (dict) – a dictionary defining the scenarios; see examples folder for examples; see below for baseline
basepars (dict) – a dictionary of sim parameters to be used for the basis of the scenarios (not required if sim is provided)
scenfile (str) – a filename for saving (defaults to the creation date)
- Returns
a Scenarios object
- Return type
scens
-
result_keys
()¶ Attempt to retrieve the results keys from the base sim
-
run
(debug=False, keep_people=False, verbose=None, **kwargs)¶ Run the actual scenarios
- Parameters
debug (bool) – if True, runs a single run instead of multiple, which makes debugging easier
verbose (int) – level of detail to print, passed to sim.run()
kwargs (dict) – passed to multi_run() and thence to sim.run()
- Returns
None (modifies Scenarios object in place)
-
plot
(*args, **kwargs)¶ Plot the results of a scenario.
- Parameters
to_plot (dict) – Dict of results to plot; see get_scen_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()
fill_args (dict) – Dictionary of kwargs to be passed to pl.fill_between()
legend_args (dict) – Dictionary of kwargs to be passed to pl.legend(); if show_legend=False, do not show
show_args (dict) – Control which “extras” get shown: uncertainty bounds, data, interventions, ticks, and the legend
as_dates (bool) – Whether to plot the x-axis as dates or time points
dateformat (str) – Date string format, e.g. ‘%B %d’
interval (int) – Interval between tick marks
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 scenario, must be a dictionary with one entry per scenario key
sep_figs (bool) – Whether to show separate figures for different results instead of subplots
fig (fig) – Existing figure to plot into
- Returns
Figure handle
- Return type
fig
Example:
scens = cv.Scenarios() scens.run() scens.plot()
-
to_json
(filename=None, tostring=True, indent=2, verbose=False, *args, **kwargs)¶ Export results as JSON.
- Parameters
filename (str) – if None, return string; else, write to file
- Returns
A unicode string containing a JSON representation of the results, or writes the JSON file to disk
-
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
-
save
(scenfile=None, keep_sims=True, keep_people=False, **kwargs)¶ Save to disk as a gzipped pickle.
- Parameters
scenfile (str) – the name or path of the file to save to; if None, uses stored
keep_sims (bool) – whether or not to store the actual Sim objects in the Scenarios object
keep_people (bool) – whether or not to store the population in the Sim objects (NB, very large)
kwargs (dict) – passed to makefilepath()
- Returns
the validated absolute path to the saved file
- Return type
scenfile (str)
Example:
scens.save() # Saves to a .scens file with the date and time of creation by default
-
covasim.run.
single_run
(sim, ind=0, reseed=True, noise=0.0, noisepar=None, keep_people=False, run_args=None, sim_args=None, verbose=None, do_run=True, **kwargs)¶ Convenience function to perform a single simulation run. Mostly used for parallelization, but can also be used directly.
- Parameters
sim (Sim) – the sim instance to be run
ind (int) – the index of this sim
reseed (bool) – whether or not to generate a fresh seed for each run
noise (float) – the amount of noise to add to each run
noisepar (str) – the name of the parameter to add noise to
keep_people (bool) – whether to keep the people after the sim run
run_args (dict) – arguments passed to sim.run()
sim_args (dict) – extra parameters to pass to the sim, e.g. ‘n_infected’
verbose (int) – detail to print
do_run (bool) – whether to actually run the sim (if not, just initialize it)
kwargs (dict) – also passed to the sim
- Returns
a single sim object with results
- Return type
sim (Sim)
Example:
import covasim as cv sim = cv.Sim() # Create a default simulation sim = cv.single_run(sim) # Run it, equivalent(ish) to sim.run()
-
covasim.run.
multi_run
(sim, n_runs=4, reseed=True, noise=0.0, noisepar=None, iterpars=None, combine=False, keep_people=None, run_args=None, sim_args=None, par_args=None, do_run=True, verbose=None, **kwargs)¶ For running multiple runs in parallel. If the first argument is a list of sims, exactly these will be run and most other arguments will be ignored.
- Parameters
sim (Sim) – the sim instance to be run, or a list of sims.
n_runs (int) – the number of parallel runs
reseed (bool) – whether or not to generate a fresh seed for each run
noise (float) – the amount of noise to add to each run
noisepar (str) – the name of the parameter to add noise to
iterpars (dict) – any other parameters to iterate over the runs; see sc.parallelize() for syntax
combine (bool) – whether or not to combine all results into one sim, rather than return multiple sim objects
keep_people (bool) – whether to keep the people after the sim run
run_args (dict) – arguments passed to sim.run()
sim_args (dict) – extra parameters to pass to the sim
do_run (bool) – whether to actually run the sim (if not, just initialize it)
par_args (dict) – arguments passed to sc.parallelize()
verbose (int) – detail to print
kwargs (dict) – also passed to the sim
- Returns
If combine is True, a single sim object with the combined results from each sim. Otherwise, a list of sim objects (default).
Example:
import covasim as cv sim = cv.Sim() sims = cv.multi_run(sim, n_runs=6, noise=0.2)