run
Utilities for running in parallel
Classes
| Name | Description |
|---|---|
| MultiSim | Class for running multiple copies of a simulation in parallel. |
MultiSim
run.MultiSim(
sims=None,
base_sim=None,
label=None,
n_runs=4,
initialize=False,
inplace=True,
debug=False,
**kwargs,
)Class for running multiple copies of a simulation in parallel.
This is the most common way for running multiple simulation: for example, to do scenario analysis or to collect statistics
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| sims | Sim / list | a single sim, a list/tuple of sims, or another MultiSim (or list of MultiSims) | None |
| base_sim | Sim | the sim used for shared properties; if not supplied, the first of the sims provided | None |
| label | str | the name of the multisim | None |
| n_runs | int | if a single sim is provided, the number of replicates (default 4) | 4 |
| initialize | bool | whether or not to initialize the sims (otherwise, initialize them during run) | False |
| inplace | bool | whether to modify the sims in-place (default True); else return new sims | True |
| debug | bool | if True, run in serial | False |
| kwargs | dict | stored in run_args and passed to run() | {} |
Examples
import starsim as ss
s1 = ss.Sim(networks='random', diseases=ss.SIS(beta=0.02), label='Low transmission')
s2 = ss.Sim(networks='random', diseases=ss.SIS(beta=0.05), label='Medium transmission')
s3 = ss.Sim(networks='random', diseases=ss.SIS(beta=0.10), label='High transmission')
msim = ss.MultiSim(sims=[s1, s2, s3])
msim.run()
# Plot individual sims
msim.plot()
# Calculate mean results across sims and plot
msim.mean()
msim.plot()Methods
| Name | Description |
|---|---|
| brief | A single-line display of the MultiSim; same as print(multisim) |
| combine | Combine multiple sims into a single sim, e.g. to treat several smaller sims |
| compare | Create a dataframe comparing the sims, with one column per sim and one row per result. |
| copy | Perform a deep copy of the MultiSim (including sims contained within) |
| disp | Display the full object |
| init_sims | Initialize the sims |
| mean | Alias for reduce(use_mean=True). See reduce() for full description. |
| median | Alias for reduce(use_mean=False). See reduce() for full description. |
| merge | Merge several MultiSims into one; see also msim.split(). |
| plot | Plot all results in the MultiSim object. |
| plot_compare | Plot a bar chart comparing the sims, with one panel per result; see msim.compare(). |
| reduce | Combine multiple sims into a single sim statistically: by default, use |
| reset | Undo reduce() by resetting the base sim, which, and results |
| run | Run the sims; see ss.multi_run() for additional arguments |
| show | Print a moderate length summary of the MultiSim. See also multisim.disp() |
| shrink | Not to be confused with reduce(), this shrinks each sim in the msim; |
| split | Split one MultiSim into several; the reverse of ss.MultiSim.merge(). |
| summarize | Summarize the simulations statistically. |
brief
run.MultiSim.brief()A single-line display of the MultiSim; same as print(multisim)
combine
run.MultiSim.combine(output=False)Combine multiple sims into a single sim, e.g. to treat several smaller sims as one larger population.
Results that scale with population size (res.scale=True, e.g. counts) are summed; other results (e.g. prevalence) are averaged, weighted by each sim’s total_pop. The population sizes (n_agents and total_pop) are summed, and pop_scale is updated to match. The people are not combined: the combined sim keeps the people (if any) of the first sim.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| output | bool | whether to return the combined sim (otherwise, return the MultiSim) | False |
Examples
msim = ss.MultiSim(ss.Sim(n_agents=1e3, diseases='sis', networks='random'), n_runs=4)
msim.run()
msim.combine() # Equivalent to a single sim with n_agents=4e3
msim.plot()compare
run.MultiSim.compare(
t=None,
sim_inds=None,
output=False,
do_plot=False,
**kwargs,
)Create a dataframe comparing the sims, with one column per sim and one row per result.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| t | int / str / date | if None, compare the sim summaries (see sim.summarize()); else, the timestep index or date to compare the results at |
None |
| sim_inds | list | the indices of the sims to include (default: all) | None |
| output | bool | whether to return the dataframe (otherwise, print it) | False |
| do_plot | bool | whether to also plot the comparison (see msim.plot_compare()) |
False |
| kwargs | dict | passed to msim.plot_compare() |
{} |
Examples
s1 = ss.Sim(diseases=ss.SIS(beta=0.05), networks='random', label='Low')
s2 = ss.Sim(diseases=ss.SIS(beta=0.10), networks='random', label='High')
msim = ss.MultiSim([s1, s2]).run()
msim.compare() # Print the summaries
df = msim.compare(t='2030-01-01', output=True) # Results on that datecopy
run.MultiSim.copy(die=True)Perform a deep copy of the MultiSim (including sims contained within)
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| die | bool | whether to raise an exception if copy fails (else, try a shallow copy) | True |
disp
run.MultiSim.disp()Display the full object
init_sims
run.MultiSim.init_sims(**kwargs)Initialize the sims
mean
run.MultiSim.mean(bounds=None, **kwargs)Alias for reduce(use_mean=True). See reduce() for full description.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| bounds | float | multiplier on the standard deviation for the upper and lower bounds (default, 2) | None |
| kwargs | dict | passed to reduce() | {} |
median
run.MultiSim.median(quantiles=None, **kwargs)Alias for reduce(use_mean=False). See reduce() for full description.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| quantiles | list or dict | upper and lower quantiles (default, 0.1 and 0.9) | None |
| kwargs | dict | passed to reduce() | {} |
merge
run.MultiSim.merge(*args, base=False)Merge several MultiSims into one; see also msim.split().
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| args | MultiSim | the MultiSims to merge (either a list, or separate arguments) | () |
| base | bool | if True, make a new MultiSim from the base sims of each MultiSim (e.g. after reduce()); otherwise, merge the lists of sims |
False |
Returns
| Name | Type | Description |
|---|---|---|
| A new MultiSim |
Examples
m1 = ss.MultiSim(ss.Sim(diseases='sis', networks='random', label='SIS'), n_runs=3).run()
m2 = ss.MultiSim(ss.Sim(diseases='sir', networks='random', label='SIR'), n_runs=3).run()
msim = ss.MultiSim.merge(m1, m2) # 6 sims
m1.mean(); m2.mean()
mm = ss.MultiSim.merge(m1, m2, base=True) # 2 sims, the means of each
mm.plot()plot
run.MultiSim.plot(key=None, fig=None, legend=True, **kwargs)Plot all results in the MultiSim object.
If the MultiSim object has been reduced (i.e. mean or median), then plot the best value and uncertainty bound. Otherwise, plot individual sims.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| key | str | the results key to plot (by default, all) | None |
| fig | Figure |
if provided, plot results into an existing figure | None |
| fig_kw | dict | passed to sc.getrowscols(), then plt.subplots() and plt.figure() |
required |
| plot_kw | dict | passed to plt.plot() |
required |
| data_kw | dict | passed to plt.scatter(), for plotting the data |
required |
| style_kw | dict | passed to sc.options.with_style(), for controlling the detailed plotting style |
required |
| fill_kw | dict | passed to plt.fill_between() |
required |
| legend_kw | dict | passed to plt.legend() |
required |
| legend | bool | whether to show the legend | True |
| **kwargs | dict | known arguments (e.g. figsize, font) split between the above dicts; see ss.plot_args() for all valid options |
{} |
plot_compare
run.MultiSim.plot_compare(t=None, sim_inds=None, df=None, **kwargs)Plot a bar chart comparing the sims, with one panel per result; see msim.compare().
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| t | int / str / date | passed to msim.compare() |
None |
| sim_inds | list | passed to msim.compare() |
None |
| df | dataframe |
if supplied, plot this instead of calling msim.compare() |
None |
| kwargs | dict | see ss.plot_args() for all valid options |
{} |
Examples
msim = ss.MultiSim(ss.Sim(diseases='sis', networks='random'), n_runs=3).run()
msim.plot_compare()reduce
run.MultiSim.reduce(quantiles=None, use_mean=False, bounds=None, output=False)Combine multiple sims into a single sim statistically: by default, use the median value and the 10th and 90th percentiles for the lower and upper bounds. If use_mean=True, then use the mean and ±2 standard deviations for lower and upper bounds.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| quantiles | dict | the quantiles to use, e.g. [0.1, 0.9] or {‘low : ’0.1, ’high’ : 0.9} | None |
| use_mean | bool | whether to use the mean instead of the median | False |
| bounds | float | if use_mean=True, the multiplier on the standard deviation for upper and lower bounds (default 2) | None |
| output | bool | whether to return the “reduced” sim (in any case, modify the multisim in-place) | False |
Examples
msim = ss.MultiSim(ss.Sim())
msim.run()
msim.reduce()
msim.summarize()reset
run.MultiSim.reset()Undo reduce() by resetting the base sim, which, and results
run
run.MultiSim.run(**kwargs)Run the sims; see ss.multi_run() for additional arguments
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| n_runs | int | how many replicates of each sim to run (if a list of sims is not provided) | required |
| inplace | bool | whether to modify the sims in place (otherwise return copies) | required |
| kwargs | dict | passed to multi_run(); use run_args to pass arguments to sim.run() | {} |
Returns
| Name | Type | Description |
|---|---|---|
| None (modifies MultiSim object in place) |
show
run.MultiSim.show(output=False)Print a moderate length summary of the MultiSim. See also multisim.disp() (detailed output) and multisim.brief() (short output).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| output | bool | if true, return a string instead of printing output | False |
Examples
msim = ss.MultiSim(ss.demo(run=False), label='Example multisim')
msim.run()
msim.show() # Prints moderate length outputshrink
run.MultiSim.shrink(**kwargs)Not to be confused with reduce(), this shrinks each sim in the msim; see sim.shrink() for more information.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| kwargs | dict | passed to sim.shrink() for each sim | {} |
split
run.MultiSim.split(inds=None, chunks=None)Split one MultiSim into several; the reverse of ss.MultiSim.merge().
Specify either the indices of the sims for each new MultiSim (inds), or consecutive chunks (chunks). For a merged MultiSim, neither is needed.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| inds | list | a list of lists of indices, with each list turned into a MultiSim | None |
| chunks | int / list | if an int, split the MultiSim into that many equal chunks; if a list, the number of sims in each chunk | None |
Returns
| Name | Type | Description |
|---|---|---|
| A list of MultiSims |
Examples
msim = ss.MultiSim(ss.Sim(diseases='sis', networks='random'), n_runs=6).run()
m1, m2 = msim.split(inds=[[0,2,4], [1,3,5]])
m1, m2 = msim.split(chunks=[2,4]) # Equivalent to inds=[[0,1], [2,3,4,5]]
m1, m2 = msim.split(chunks=2) # Equivalent to inds=[[0,1,2], [3,4,5]]
m1, m2 = ss.MultiSim.merge(m1, m2).split() # Use the chunks from the mergesummarize
run.MultiSim.summarize(method='mean', quantiles=None, how='default')Summarize the simulations statistically.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| method | str | one of ‘mean’ (default: [mean, 2*std]), ‘median’ ([median, min, max]), or ‘all’ (all results) | 'mean' |
| quantiles | dict | if method=‘median’, use these quantiles | None |
| how | str | passed to sim.summarize() | 'default' |
Functions
| Name | Description |
|---|---|
| multi_run | For running multiple sims in parallel. If the first argument is a list of sims |
| parallel | A shortcut to ss.MultiSim(), allowing the quick running of multiple simulations |
| single_run | Convenience function to perform a single simulation run. Mostly used for |
multi_run
run.multi_run(
sim,
n_runs=4,
reseed=None,
iterpars=None,
shrink=None,
run_args=None,
sim_args=None,
par_args=None,
do_run=True,
parallel=True,
n_cpus=None,
copy_sim=False,
verbose=None,
**kwargs,
)For running multiple sims in parallel. If the first argument is a list of sims rather than a single sim, exactly these will be run and most other arguments will be ignored.
Note: n_cpus=1 is not the same thing as setting parallel=False. The former still uses the parallelization methods (just on a single core), while the latter simply runs in a loop.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| sim | Sim / list | the sim instance to be run, or a list of sims. | required |
| n_runs (int) | the number of parallel runs | required | |
| reseed (bool) | whether or not to generate a fresh seed for each run (default: true for single, false for list of sims) | required | |
| iterpars (dict) | any other parameters to iterate over the runs; see sc.parallelize() for syntax | required | |
| shrink (bool) | whether to shrink the sim after the sim run | required | |
| run_args (dict) | arguments passed to sim.run() | required | |
| sim_args (dict) | extra parameters to pass to the sim | required | |
| par_args (dict) | arguments passed to sc.parallelize() | required | |
| do_run (bool) | whether to actually run the sim (if not, just initialize it) | required | |
| parallel (bool) | whether to run in parallel using multiprocessing (else, just run in a loop) | required | |
| n_cpus (int) | the number of CPUs to run on (if blank, set automatically; otherwise, passed to par_args, and use all cores) | required | |
| copy_sim (bool) | whether to explicitly copy the sim before running (default: False) | required | |
| verbose (int) | detail to print | required | |
| kwargs (dict) | also passed to the sim | required |
Returns
| Name | Type | Description |
|---|---|---|
| A list of sim objects (default). |
Examples
import starsim as ss
sim = ss.Sim()
sims = ss.multi_run(sim, n_runs=6)parallel
run.parallel(*args, **kwargs)A shortcut to ss.MultiSim(), allowing the quick running of multiple simulations at once.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| args | list | The simulations to run | () |
| kwargs | dict | passed to multi_run() | {} |
Returns
| Name | Type | Description |
|---|---|---|
| A run MultiSim object. |
Examples
s1 = ss.Sim(n_agents=1000, label='Small', diseases='sis', networks='random')
s2 = ss.Sim(n_agents=2000, label='Large', diseases='sis', networks='random')
ss.parallel(s1, s2).plot()
msim = ss.parallel([s1, s2], shrink=False)single_run
run.single_run(
sim,
ind=0,
reseed=True,
shrink=True,
run_args=None,
sim_args=None,
verbose=None,
do_run=True,
copy_sim=False,
**kwargs,
)Convenience function to perform a single simulation run. Mostly used for parallelization, but can also be used directly.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| sim (Sim) | the sim instance to be run | required | |
| ind (int) | the index of this sim | required | |
| reseed (bool) | whether to generate a fresh seed for each run | required | |
| shrink (bool) | whether to shrink the sim after the sim run | required | |
| run_args (dict) | arguments passed to sim.run() | required | |
| sim_args (dict) | extra parameters to pass to the sim, e.g. ‘n_infected’ | required | |
| verbose (int) | detail to print | required | |
| do_run (bool) | whether to actually run the sim (if not, just initialize it) | required | |
| copy_sim (bool) | whether to explicitly copy the sim before running (default: False) | required | |
| kwargs (dict) | also passed to the sim | required |
Returns
| Name | Type | Description |
|---|---|---|
| sim | Sim | a single sim object with results |
Examples
import starsim as ss
sim = ss.Sim() # Create a default simulation
sim = ss.single_run(sim) # Run it, equivalent(ish) to sim.run()