modules

modules

General module class – base class for diseases, interventions, etc. Also defines Analyzers and Connectors.

Classes

Name Description
Base The parent class for Sim and Module objects
Module The main base class for all Starsim modules: diseases, networks, interventions, etc.

Base

modules.Base()

The parent class for Sim and Module objects

Attributes

Name Description
dt Get the current module timestep
now Shortcut to self.t.now()
ti Get the current module timestep
timevec Shortcut to self.t.timevec

Methods

Name Description
copy Perform a deep copy of the module/sim
disp Display the full object
copy
modules.Base.copy(die=True)

Perform a deep copy of the module/sim

Parameters
Name Type Description Default
die bool whether to raise an exception if copy fails (else, try a shallow copy) True
disp
modules.Base.disp(output=False, **kwargs)

Display the full object

Module

modules.Module(self, name=None, label=None, **kwargs)

The main base class for all Starsim modules: diseases, networks, interventions, etc.

By convention, keyword arguments to modules are assigned to “_“, which is an alias for None. These are then populated with defaults by mod.define_pars(), which are then updated with mod.update_pars(), which inspects the __init__ function to get these arguments.

Note that there is no functional difference between specifying arguments this way rather than simply via **kwargs, but having the arguments shown in the function signature can make it easier to read, and “_” is a convetion to indicate that the default is specified below.

It is also of course OK to specify the actual values rather than “_“; however module arguments are often complex objects (e.g. ss.bernoulli) that can’t be easily specified in the function signature.

Finally, note that you can (and should) call super().__init__() with no arguments: the name, label, and time arguments get correctly updated via self.update_pars().

Parameters

Name Type Description Default
name str a short, key-like name for the module (e.g. “randomnet”) None
label str the full, human-readable name for the module (e.g. “Random network”) None
kwargs dict passed to ss.Timeline() (e.g. start, stop, unit, dt) {}

Example:

class SIR(ss.Module):
    def __init__(self, pars=_, beta=_, init_prev=_, p_death=_, **kwargs):
        super().__init__() # Call this first with no arguments
        self.define_pars( # Then define the parameters, including their default value
            beta = ss.peryear(0.1),
            init_prev = ss.bernoulli(p=0.01),
            p_death = ss.bernoulli(p=0.3),
        )
        self.update_pars(pars, **kwargs) # Update with any user-supplied parameters, and raise an exception if trying to set a parameter that wasn't defined in define_pars()
        return

Attributes

Name Description
auto_state_list List of “automatic” states with boolean type (ss.BoolState) that were added
state_dict Return a flat dictionary (objdict) of all states
state_list Return a flat list of all states (ss.Arr objects)

Methods

Name Description
brief Show a brief representation of the module; used by repr
check_method_calls Check if any required methods were not called.
create Create a module instance by name
define_pars Create or merge Pars objects
define_results Add results to the module
define_states Define states of the module with the same attribute name as the state
finalize Perform any final operations, such as removing unneeded data
finalize_results Finalize results
finish_step Define what should happen at the end of the step; at minimum, increment ti
from_func Create an module from a function
init_mock Initialize with a mock simulation – for debugging purposes only
init_post Initialize the values of the states; the last step of initialization
init_pre Perform initialization steps
init_results Initialize results output; called during init_pre()
link_rates Find all time parameters in the module and link them to the module’s dt
match_time_inds Find the nearest matching sim time indices for the current module
plot Plot all results in the module
set_metadata Set metadata for the module
setattribute Method for setting an attribute that does not perform checking against immutable attributes
shrink Shrink the size of the module for saving to disk
start_step Tasks to perform at the beginning of the step
step Define how the module updates over time – the key part of Starsim!!
to_json Export to a JSON-compatible format
update_pars Pull out recognized parameters, returning the rest
update_results Update results; by default, compute counts of each state at each point in time
brief
modules.Module.brief(output=False)

Show a brief representation of the module; used by repr

check_method_calls
modules.Module.check_method_calls()

Check if any required methods were not called.

Typically called automatically by sim.run().

create
modules.Module.create(name, *args, **kwargs)

Create a module instance by name

Parameters
Name Type Description Default
name str A string with the name of the module class in lower case, e.g. ‘sir’ required
define_pars
modules.Module.define_pars(inherit=True, **kwargs)

Create or merge Pars objects

Note: this method also automatically pulls in keyword arguments from the calling function (which is almost always a module’s __init__() method)

define_results
modules.Module.define_results(*args, check=True)

Add results to the module

define_states
modules.Module.define_states(*args, check=True, reset=False, lock=True)

Define states of the module with the same attribute name as the state

In addition to registering the state with the module by attribute, it adds it to mod._all_states, which is used by mod.state_list and mod.state_dict.

Parameters
Name Type Description Default
args states list of states to add ()
check bool whether to check that the object being added is a state, and that it’s not already present True
reset bool whether to reset the list of module states and use only the ones provided False
lock bool if True, prevent states from being True
finalize
modules.Module.finalize()

Perform any final operations, such as removing unneeded data

finalize_results
modules.Module.finalize_results()

Finalize results

finish_step
modules.Module.finish_step()

Define what should happen at the end of the step; at minimum, increment ti

from_func
modules.Module.from_func(func)

Create an module from a function

init_mock
modules.Module.init_mock(n_agents=100, dur=10)

Initialize with a mock simulation – for debugging purposes only

init_post
modules.Module.init_post()

Initialize the values of the states; the last step of initialization

init_pre
modules.Module.init_pre(sim, force=False)

Perform initialization steps

This method is called once, as part of initializing a Sim. Note: after initialization, initialized=False until init_vals() is called (which is after distributions are initialized).

init_results
modules.Module.init_results()

Initialize results output; called during init_pre()

By default, modules all report on counts for any explicitly defined “States”, e.g. if a disease contains an ss.BoolState called ‘susceptible’ it will automatically contain a Result for ‘n_susceptible’. For identical behavior that does not automatically generate results, use ss.BoolArr instead of ss.BoolState.

match_time_inds
modules.Module.match_time_inds(inds=None)

Find the nearest matching sim time indices for the current module

plot
modules.Module.plot()

Plot all results in the module

set_metadata
modules.Module.set_metadata(name=None, label=None)

Set metadata for the module

setattribute
modules.Module.setattribute(attr, value)

Method for setting an attribute that does not perform checking against immutable attributes

shrink
modules.Module.shrink()

Shrink the size of the module for saving to disk

start_step
modules.Module.start_step()

Tasks to perform at the beginning of the step

step
modules.Module.step()

Define how the module updates over time – the key part of Starsim!!

to_json
modules.Module.to_json()

Export to a JSON-compatible format

update_pars
modules.Module.update_pars(pars=None, **kwargs)

Pull out recognized parameters, returning the rest

update_results
modules.Module.update_results()

Update results; by default, compute counts of each state at each point in time

This function is executed after transmission in all modules has been resolved. This allows result updates at this point to capture outcomes dependent on multiple modules, where relevant.

Functions

Name Description
find_modules Find all subclasses of Module present in Starsim, divided by type
module_map Define the mapping between module names and types; this is the source of truth about module types and ordering
module_types Return a list of known module types; based on module_map()
register_modules Register custom modules with Starsim so they can be referred to by string.
required Decorator to mark module methods as required.

find_modules

modules.find_modules(key=None, flat=False, verbose=False)

Find all subclasses of Module present in Starsim, divided by type

module_map

modules.module_map(key=None)

Define the mapping between module names and types; this is the source of truth about module types and ordering

module_types

modules.module_types()

Return a list of known module types; based on module_map()

register_modules

modules.register_modules(*args)

Register custom modules with Starsim so they can be referred to by string.

Note: “modules” here refers to Starsim modules. But this function registers Starsim “modules” (e.g. ss.SIR) that are found within Python “modules” (e.g. starsim).

Parameters

Name Type Description Default
args list the additional modules to register; can be either a module or a list of objects ()

Examples:

# Standard use case, register modules automatically
import my_custom_disease_model as mcdm
ss.register_modules(mcdm)
ss.Sim(diseases='mydisease', networks='random').run() # This will work if mcdm.MyDisease() is defined

# Manual usage
my_modules = [mcdm.MyDisease, mcdm.MyNetwork]
ss.register_modules(my_modules)
ss.Sim(diseases='mydisease', networks='mynetwork').run()

required

modules.required(val=True)

Decorator to mark module methods as required.

A common gotcha in Starsim is to forget to call super(), or to mistype a method name so it’s never called. This decorator lets you mark methods (of Modules only) to be sure that they are called either on sim initialization or on sim run.

Parameters

Name Type Description Default
val True / disable by default, mark method as required; if set to ‘disable’, then disable method checking for parent classes as well (i.e. remove previous “required” calls) True

Example:

class CustomSIS(ss.SIS):

    def step(self):
        super().step()
        self.custom_step() # Will raise an exception if this line is not here
        return

    @ss.required() # Mark this method as required on run
    def custom_step(self):
        pass