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:
BaseModellingManagerThe
Simulatoris 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:
- 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
SimulatorScenariostable.- Returns:
A list of
Scenarioobjects.
- 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, parallel_mode: Literal['process', 'thread'] | None = None)
Run simulations in parallel.
If
parallel_modeis explicitly set, that mode is used directly. If it is left asNone, Melodie auto-selects"thread"on Python 3.13+ and"process"on older Python versions.In process mode, this method uses a separate worker manager to distribute simulation runs across CPU cores. In thread mode, it uses a thread pool.
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.
parallel_mode –
"process"or"thread". If omitted, Melodie chooses automatically based on the Python version.