Simulator

class Melodie.Simulator(config: Config, scenario_cls: Type[Scenario], model_cls: Type[Model], data_loader_cls: Type[DataLoader] = None, visualizer_cls: type[BaseVisualizer] = None)

Bases: BaseModellingManager

The Simulator is the primary manager for running model simulations.

It orchestrates the entire simulation process, including initializing the model and scenarios, running the simulation for each scenario, and handling data collection and visualization.

Parameters:
  • config – The project Config object.

  • scenario_cls – The Scenario subclass for the model.

  • model_cls – The Model subclass for the model.

  • data_loader_cls – The DataLoader subclass for the model.

  • visualizer_cls – The BaseVisualizer subclass for the model, if visualization is needed.

generate_scenarios() List[Scenario]

Generate scenarios using the data loader.

This method calls the data loader to generate a list of scenario objects based on the SimulatorScenarios table.

Returns:

A list of Scenario objects.

run_model(config, scenario, id_run, model_class: Type[Model], visualizer=None)

Run a single simulation for one scenario and one run ID.

setup()

A hook for custom simulator setup. This method is called before pre_run.

run()

The main entry point for running batch simulations without visualization.

This method iterates through all defined scenarios and their specified number of runs, executing the model for each.

run_visual()

The main entry point for running a simulation with visualization.

This method starts the visualizer and runs the model for the first scenario in a loop, allowing for interactive parameter changes and resets from the web interface.

run_parallel(cores: int = 1)

Run simulations in parallel using multiple processes.

This method uses Python’s multiprocessing.Pool to distribute the simulation runs across a specified number of CPU cores.

To avoid race conditions during database table creation, the first simulation run is executed in the main process. This ensures that all necessary tables are created before the parallel workers start writing to them.

Parameters:

cores – The number of CPU cores to use for parallel execution. It is recommended to set this to the number of physical cores on your machine for optimal performance.

run_parallel_multithread(cores: int = 1)

Experimental parallel execution utilizing Python 3.13+ Free-threaded mode (No-GIL).

This method uses a ThreadPoolExecutor. In Python 3.13+ (free-threaded build), it can leverage multiple cores without the overhead of process creation or object pickling. In older Python versions, it still runs concurrently but is limited by the GIL, so CPU-bound workloads may not see a speedup.

Parameters:

cores – Number of threads to use.