sim
sim
Define core Sim classes
Classes
Name | Description |
---|---|
AlreadyRunError | Raised if trying to re-run an already-run sim without re-initializing |
Sim | The Sim object |
AlreadyRunError
sim.AlreadyRunError()
Raised if trying to re-run an already-run sim without re-initializing
Sim
sim.Sim(self,
=None,
pars=None,
label=None,
people=None,
modules=None,
demographics=None,
diseases=None,
networks=None,
interventions=None,
analyzers=None,
connectors=True,
copy_inputs=None,
data**kwargs,
)
The Sim object
All Starsim simulations run via the Sim class. It is responsible for initializing and running all modules and generating results.
Parameters
Name | Type | Description | Default |
---|---|---|---|
pars | SimPars / dict | either an ss.SimPars object, or a nested dictionary; can include all other arguments | None |
label | str | the human-readable name of the simulation | None |
people | People | if provided, use this ss.People object | None |
modules | Module / list | if provided, use these modules (and divide among demographics, diseases, etc. based on type) | None |
demographics | str / Demographics / list | a string naming the demographics module to use, the module itself, or a list | None |
connectors | str / Connector / list | as above, for connectors | None |
networks | str / Network / list | as above, for networks | None |
interventions | str / Intervention / list | as above, for interventions | None |
diseases | str / Disease / list | as above, for diseases | None |
analyzers | str / Analyzer / list | as above, for analyzers | None |
copy_inputs | bool | if True, copy modules as they’re inserted into the sim (allowing reuse in other sims, but meaning they won’t be updated) | True |
data | df |
a dataframe (or dict) of data, with a column “time” plus data of the form “module.result”, e.g. “hiv.new_infections” (used for plotting only) | None |
kwargs | dict | merged with pars; see ss.SimPars for all parameter values | {} |
Examples:
sim = ss.Sim(diseases='sir', networks='random') # Simplest Starsim sim; equivalent to ss.demo()
sim = ss.Sim(diseases=ss.SIR(), networks=ss.RandomNet()) # Equivalent using objects instead of strings
sim = ss.Sim(diseases=['sir', ss.SIS()], networks=['random', 'mf']) # Example using list inputs; can mix and match types
Attributes
Name | Description |
---|---|
label | Get the sim label from the parameters, if available. |
module_dict | Return a dictionary of all Module instances; see sim.module_list for the list version |
module_list | Return a list of all Module instances (stored in standard places) in the Sim; see sim.module_dict for the dict version |
Methods
Name | Description |
---|---|
check_method_calls | Check if any required methods were not called. |
check_results_ready | Check that results are ready |
cprofile | Profile the performance of the simulation using a function profiler (sc.cprofile() ) |
finalize | Compute final results |
finalize_results | Scale the results and remove any “unused” results |
finish_step | Finish the simulation timestep |
init | Perform all initializations for the sim |
init_data | Initialize or add data to the sim |
init_dists | Initialize the distributions |
init_module_attrs | Move initialized modules to the sim |
init_modules_post | Initialize values in other modules, including networks and time parameters, and do any other post-processing |
init_modules_pre | Initialize all the modules with the sim |
init_people | Initialize people within the sim |
init_people_vals | Initialize the People states with actual values |
init_results | Create initial results that are present in all simulations |
init_time | Time indexing; derived values live in the sim rather than in the pars |
plot | Plot all results in the Sim object |
products | List all products across interventions; not an ndict like the other module types |
profile | Profile the performance of the simulation using a line profiler (sc.profile() ) |
reset_time_pars | Reset the time parameters in the modules; used for imposing the sim’s timestep on the modules |
run | Run the model – the main method for running a simulation. |
run_one_step | Run a single sim step; only used for debugging purposes. |
save | Save to disk as a gzipped pickle. |
shrink | “Shrinks” the simulation by removing the people and other memory-intensive |
start_step | Start the step – only print progress; all actual changes happen in the modules |
summarize | Provide a quick summary of the sim; returns the last entry for count and |
to_df | Export results as a Pandas dataframe |
to_json | Export results and parameters as JSON. |
to_yaml | Export results and parameters as YAML. |
check_method_calls
=None, warn=None, verbose=False) sim.Sim.check_method_calls(die
Check if any required methods were not called.
Typically called automatically by sim.run()
; default behavior is to warn (see options.check_method_calls
).
Parameters
Name | Type | Description | Default |
---|---|---|---|
die | bool | whether to raise an exception if missing methods were found (default False) | None |
warn | bool | whether to raise a warning if missing methods were found (default False) | None |
verbose | bool | whether to print the number of times each method was called (default False) | False |
Returns
Name | Type | Description |
---|---|---|
A list of missing method calls by module |
check_results_ready
=None) sim.Sim.check_results_ready(errormsg
Check that results are ready
cprofile
='cumtime', mintime=0.001, **kwargs) sim.Sim.cprofile(sort
Profile the performance of the simulation using a function profiler (sc.cprofile()
)
Parameters
Name | Type | Description | Default |
---|---|---|---|
sort | str | default sort column; common choices are ‘cumtime’ (total time spent in a function, includin subfunctions) and ‘selftime’ (excluding subfunctions) | 'cumtime' |
mintime | float | exclude function calls less than this time in seconds | 0.001 |
**kwargs | dict | passed to sc.cprofile() |
{} |
Example:
import starsim as ss
net = ss.RandomNet()
sis = ss.SIS()
sim = ss.Sim(networks=net, diseases=sis)
prof = sim.cprofile()
finalize
sim.Sim.finalize()
Compute final results
finalize_results
sim.Sim.finalize_results()
Scale the results and remove any “unused” results
finish_step
sim.Sim.finish_step()
Finish the simulation timestep
init
=False, timer=False, **kwargs) sim.Sim.init(force
Perform all initializations for the sim
Parameters
Name | Type | Description | Default |
---|---|---|---|
force | bool | whether to overwrite sim attributes even if they already exist | False |
timer | bool | if True, count the time required for initialization (otherwise just count run time) | False |
kwargs | dict | passed to ss.People() | {} |
init_data
=None) sim.Sim.init_data(data
Initialize or add data to the sim
init_dists
sim.Sim.init_dists()
Initialize the distributions
init_module_attrs
=False) sim.Sim.init_module_attrs(force
Move initialized modules to the sim
init_modules_post
sim.Sim.init_modules_post()
Initialize values in other modules, including networks and time parameters, and do any other post-processing
init_modules_pre
sim.Sim.init_modules_pre()
Initialize all the modules with the sim
init_people
=None, **kwargs) sim.Sim.init_people(verbose
Initialize people within the sim Sometimes the people are provided, in which case this just adds a few sim properties to them. Other time people are not provided and this method makes them.
Parameters
Name | Type | Description | Default |
---|---|---|---|
verbose | int | detail to print | None |
kwargs | (dict | passed to ss.People() | {} |
init_people_vals
sim.Sim.init_people_vals()
Initialize the People states with actual values
init_results
sim.Sim.init_results()
Create initial results that are present in all simulations
init_time
sim.Sim.init_time()
Time indexing; derived values live in the sim rather than in the pars
plot
sim.Sim.plot(=None,
key=None,
fig=True,
show_data=False,
show_skipped=None,
show_module=False,
show_label=None,
n_ticks**kwargs,
)
Plot all results in the Sim object
Parameters
Name | Type | Description | Default |
---|---|---|---|
key | str / list | the results key to plot (by default, all); if a list, plot exactly those keys | None |
fig | Figure |
if provided, plot results into an existing figure | None |
style | str | the plotting style to use | required |
show_data | bool | plot the data, if available | True |
show_skipped | bool | show even results that are skipped by default | False |
show_module | int | whether to show the module as well as the result name; if an int, show if the label is less than that length (default, 26); if -1, use a newline | None |
show_label | str | if ‘fig’, reset the fignum; if ‘title’, set the figure suptitle | False |
n_ticks | tuple of ints | if provided, specify how many x-axis ticks to use (default: (2,5) , i.e. minimum of 2 and maximum of 5) |
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 ss.style() , for controlling the detailed plotting style (default “starsim”; other options are “simple”, None, or any Matplotlib style) |
required |
**kwargs | dict | known arguments (e.g. figsize, font) split between the above dicts; see ss.plot_args() for all valid options |
{} |
Examples:
sim = ss.Sim(diseases='sis', networks='random').run()
# Basic usage
sim.plot()
# Plot a single result
sim.plot('sis.prevalence')
# Plot with a custom figure size, font, and style
sim.plot(figsize=(12,16), font='Raleway', style='fancy')
products
sim.Sim.products()
List all products across interventions; not an ndict like the other module types
profile
=True, do_run=True, plot=True, follow=None, **kwargs) sim.Sim.profile(line
Profile the performance of the simulation using a line profiler (sc.profile()
)
Parameters
Name | Type | Description | Default |
---|---|---|---|
do_run | bool | whether to immediately run the sim | True |
plot | bool | whether to plot time spent per module step | True |
follow | func / list |
a list of functions/methods to follow in detail | None |
**kwargs | dict | passed to sc.profile() |
{} |
Example:
import starsim as ss
net = ss.RandomNet()
sis = ss.SIS()
sim = ss.Sim(networks=net, diseases=sis)
prof = sim.profile(follow=[net.add_pairs, sis.infect])
reset_time_pars
=True) sim.Sim.reset_time_pars(force
Reset the time parameters in the modules; used for imposing the sim’s timestep on the modules
run
=None, verbose=None, check_method_calls=True) sim.Sim.run(until
Run the model – the main method for running a simulation.
Parameters
Name | Type | Description | Default |
---|---|---|---|
until | date / str / float | the date to run the sim until | None |
verbose | float | the level of detail to print (default 0.1, i.e. output once every 10 steps) | None |
check_method_calls | bool | whether to check that all required methods were called | True |
run_one_step
=None) sim.Sim.run_one_step(verbose
Run a single sim step; only used for debugging purposes.
Note: sim.run_one_step() runs a single simulation timestep, which involves multiple function calls. In contrast, loop.run_one_step() runs a single function call.
Note: the verbose here is only for the Loop object, not the sim.
save
=None, shrink=None, **kwargs) sim.Sim.save(filename
Save to disk as a gzipped pickle.
Parameters
Name | Type | Description | Default |
---|---|---|---|
filename | str or None | the name or path of the file to save to; if None, uses stored | None |
shrink | bool or None | whether to shrink the sim prior to saving (reduces size by ~99%) | None |
kwargs | passed to sc.makefilepath() | {} |
Returns
Name | Type | Description |
---|---|---|
filename | str | the validated absolute path to the saved file |
Example:
sim.save() # Saves to a .sim file
shrink
=True, size_limit=1.0, intercept=10, die=True) sim.Sim.shrink(inplace
“Shrinks” the simulation by removing the people and other memory-intensive attributes (e.g., some interventions and analyzers), and returns a copy of the “shrunken” simulation. Used to reduce the memory required for RAM or for saved files.
Parameters
Name | Type | Description | Default |
---|---|---|---|
inplace | bool | whether to perform the shrinking in place (default), or return a shrunken copy instead | True |
size_limit | float | print a warning if any module is larger than this size limit, in units of KB per timestep (set to None to disable) | 1.0 |
intercept | float | the size (in units of size_limit) to allow for a zero-timestep sim | 10 |
die | bool | whether to raise an exception if the shrink failed | True |
Returns
Name | Type | Description |
---|---|---|
shrunken | Sim | a Sim object with the listed attributes removed |
start_step
sim.Sim.start_step()
Start the step – only print progress; all actual changes happen in the modules
summarize
='default') sim.Sim.summarize(how
Provide a quick summary of the sim; returns the last entry for count and cumulative results, and the mean otherwise.
Parameters
Name | Type | Description | Default |
---|---|---|---|
how | str | how to summarize: can be ‘mean’, ‘median’, ‘last’, or a mapping of result keys to those | 'default' |
to_df
='_', **kwargs) sim.Sim.to_df(sep
Export results as a Pandas dataframe Args: sep (str): separator for the keys kwargs: passed to results.to_df()
to_json
sim.Sim.to_json(=None,
filename=None,
keys=False,
tostring=2,
indent=False,
verbose**kwargs,
)
Export results and parameters as JSON.
Parameters
Name | Type | Description | Default |
---|---|---|---|
filename | str | if None, return string; else, write to file | None |
keys | str / list | attributes to write to json (choices: ‘pars’, ‘summary’, and/or ‘results’) | None |
verbose | bool | detail to print | False |
**kwargs | dict | passed to sc.jsonify() |
{} |
Returns
Name | Type | Description |
---|---|---|
A dictionary representation of the parameters and/or summary results | ||
(or write that dictionary to a file) |
Examples:
json = sim.to_json() # Convert to a dict
sim.to_json('sim.json') # Write everything
sim.to_json('summary.json', keys='summary') # Just write the summary
to_yaml
=None, sort_keys=False, **kwargs) sim.Sim.to_yaml(filename
Export results and parameters as YAML.
Parameters
Name | Type | Description | Default |
---|---|---|---|
filename | str | the name of the file to write to (default {sim.label}.yaml ) |
None |
kwargs | dict | passed to sim.to_json() |
{} |
Example:
sim = ss.Sim(diseases='sis', networks='random').run()
sim.to_yaml('results.yaml', keys='results')
Functions
Name | Description |
---|---|
check_sims_match | Shortcut to using ss.diff_sims() to check if multiple sims match |
demo | Create a simple demo simulation for Starsim |
diff_sims | Compute the difference of the summaries of two simulations, and print any |
check_sims_match
*args, full=False) sim.check_sims_match(
Shortcut to using ss.diff_sims() to check if multiple sims match
Parameters
Name | Type | Description | Default |
---|---|---|---|
args | list | a list of 2 or more sims to compare | () |
full | bool | if True, return whether each sim matches the first | False |
Example:
s1 = ss.Sim(diseases='sir', networks='random')
s2 = ss.Sim(pars=dict(diseases='sir', networks='random'))
s3 = ss.Sim(diseases=ss.SIR(), networks=ss.RandomNet())
assert ss.check_sims_match(s1, s2, s3)
demo
=True, plot=True, summary=True, show=True, **kwargs) sim.demo(run
Create a simple demo simulation for Starsim
Defaults to using the SIR model with a random network, but these can be configured.
Parameters
Name | Type | Description | Default |
---|---|---|---|
run | bool | whether to run the sim | True |
plot | bool | whether to plot the results | True |
summary | bool | whether to print a summary of the results | True |
kwargs | dict | passed to ss.Sim() |
{} |
Examples:
ss.demo() # Run, plot, and show results
ss.demo(diseases='hiv', networks='mf') # Run with different defaults
diff_sims
sim.diff_sims(
sim1,
sim2,=False,
skip_key_diffs=None,
skip=False,
full=False,
output=False,
die )
Compute the difference of the summaries of two simulations, and print any values which differ.
Parameters
Name | Type | Description | Default |
---|---|---|---|
sim1 | Sim / MultiSim / dict | either a simulation/MultiSim object or the sim.summary dictionary | required |
sim2 | im / 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 |
full | bool | whether to print out all values (not just those that differ) | False |
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 = ss.Sim(rand_seed=1).run()
s2 = ss.Sim(rand_seed=2).run()
ss.diff_sims(s1, s2)