tlo.simulation module

The main simulation controller.

exception SimulationPreviouslyInitialisedError

Bases: Exception

Exception raised when trying to initialise an already initialised simulation.

exception SimulationNotInitialisedError

Bases: Exception

Exception raised when trying to run simulation before initialising.

class Simulation(*, start_date: Timestamp, seed: int | None = None, log_config: dict | None = None, show_progress_bar: bool = False, resourcefilepath: Path | None = None)

Bases: object

The main control centre for a simulation.

This class contains the core simulation logic and event queue, and holds references to all the information required to run a complete simulation: the population, disease modules, etc.

Key attributes include:

Variables:
  • date – The current simulation date.

  • modules – A dictionary of the disease modules used in this simulation, keyed by the module name.

  • population – The population being simulated.

  • rng – The simulation-level random number generator.

Note

Individual modules also have their own random number generator with independent state.

Create a new simulation.

Parameters:
  • start_date – The date the simulation begins; must be given as a keyword parameter for clarity.

  • seed – The seed for random number generator. class will create one if not supplied

  • log_config – Dictionary specifying logging configuration for this simulation. Can have entries: filename - prefix for log file name, final file name will have a date time appended, if not present default is to not output log to a file; directory - path to output directory to write log file to, default if not specified is to output to the outputs folder; custom_levels - dictionary to set logging levels, ‘*’ can be used as a key for all registered modules; suppress_stdout - if True, suppresses logging to standard output stream (default is False).

  • show_progress_bar – Whether to show a progress bar instead of the logger output during the simulation.

  • resourcefilepath – Path to resource files folder. Assign ``None` if no path is provided.

Note

The custom_levels entry in log_config argument can be used to disable logging on all disease modules by setting a high level to *, and then enabling logging on one module of interest by setting a low level, for example {'*': logging.CRITICAL 'tlo.methods.hiv': logging.INFO}.

property log_filepath: Path

The path to the log file, if one has been set.

register(*modules: Module, sort_modules: bool = True, check_all_dependencies: bool = True, auto_register_dependencies: bool = False) None

Register one or more disease modules with the simulation.

Parameters:
  • modules – The disease module(s) to use as part of this simulation. Multiple modules may be given as separate arguments to one call.

  • sort_modules – Whether to topologically sort the modules so that any initialisation dependencies (specified by the INIT_DEPENDENCIES attribute) of a module are initialised before the module itself is. A ModuleDependencyError exception will be raised if there are missing initialisation dependencies or circular initialisation dependencies between modules that cannot be resolved. If this flag is set to True there is also a requirement that at most one instance of each module is registered and MultipleModuleInstanceError will be raised if this is not the case.

  • check_all_dependencies – Whether to check if all of each module’s declared dependencies (that is, the union of the INIT_DEPENDENCIES and ADDITIONAL_DEPENDENCIES attributes) have been included in the set of modules to be registered. A ModuleDependencyError exception will be raised if there are missing dependencies.

  • auto_register_dependencies – Whether to register missing module dependencies or not. If this argument is set to True, all module dependencies will be automatically registered.

make_initial_population(*, n: int) None

Create the initial population to simulate.

Parameters:

n – The number of individuals to create; must be given as a keyword parameter for clarity.

initialise(*, end_date: Timestamp) None

Initialise all modules in simulation.

Parameters:

end_date – Date to end simulation on - accessible to modules to allow initialising data structures which may depend (in size for example) on the date range being simulated.

finalise(wall_clock_time: float | None = None) None

Finalise all modules in simulation and close logging file if open.

Parameters:

wall_clock_time – Optional argument specifying total time taken to simulate, to be written out to log before closing.

close_output_file() None

Close logging file if open.

run_simulation_to(*, to_date: Timestamp) None

Run simulation up to a specified date.

Unlike simulate() this method does not initialise or finalise simulation and the date simulated to can be any date before or equal to simulation end date.

Parameters:

to_date – Date to simulate up to but not including - must be before or equal to simulation end date specified in call to initialise().

simulate(*, end_date: Timestamp) None

Simulate until the given end date

Parameters:

end_date – When to stop simulating. Only events strictly before this date will be allowed to occur. Must be given as a keyword parameter for clarity.

schedule_event(event: Event, date: Timestamp) None

Schedule an event to happen on the given future date.

Parameters:
  • event – The event to schedule.

  • date – wWen the event should happen.

fire_single_event(event: Event, date: Timestamp) None

Fires the event once for the given date

Parameters:
  • eventEvent to fire.

  • date – The date of the event.

do_birth(mother_id: int) int

Create a new child person.

We create a new person in the population and then call the on_birth method in all modules to initialise the child’s properties.

Parameters:

mother_id – Row index label of the maternal parent.

Returns:

Row index label of the new child.

find_events_for_person(person_id: int) list[tuple[Timestamp, Event]]

Find the events in the queue for a particular person.

Parameters:

person_id – The row index of the person of interest.

Returns:

List of tuples (date_of_event, event) for that person_id in the queue.

Note

This is for debugging and testing only. Not for use in real simulations as it is slow.

save_to_pickle(pickle_path: Path) None

Save simulation state to a pickle file using dill.

Requires dill to be importable.

Parameters:

pickle_path – File path to save simulation state to.

static load_from_pickle(pickle_path: Path, log_config: dict | None = None) Simulation

Load simulation state from a pickle file using dill.

Requires dill to be importable.

Parameters:
  • pickle_path – File path to load simulation state from.

  • log_config – New log configuration to override previous configuration. If None previous configuration (including output file) will be retained.

Returns:

Loaded Simulation object.

class EventQueue

Bases: object

A simple priority queue for events.

This doesn’t really care what events and dates are, provided dates are comparable.

Create an empty event queue.

schedule(event: Event, date: Timestamp) None

Schedule a new event.

Parameters:
  • event – The event to schedule.

  • date – When it should happen.

pop_next_event_and_date() tuple[Event, Timestamp]

Get and remove the earliest event and corresponding date in the queue.

Returns:

An (event, date) pair.

property date_of_next_event: Timestamp

Get the date of the earliest event in queue without removing from queue.

Returns:

Date of next event in queue.