78 lines
2.5 KiB
Python
78 lines
2.5 KiB
Python
"""Simulation package.
|
|
|
|
This package provides a way to easily define simulations in such a way that
|
|
they can be paused and resumed.
|
|
|
|
General Structure
|
|
=================
|
|
The package consists of 3 main components:
|
|
- The 'SimulationDeSerializer': Responsible for file IO
|
|
- The 'Simulator': Responsible for the actual simulating
|
|
- The 'SimulationManager': Delegates work to the DeSerializer and the
|
|
Simulator
|
|
|
|
The Simulator Class
|
|
===================
|
|
For each new simulating task, a new 'Simulator' must be defined. The
|
|
requirements for this class are the following:
|
|
- Must define the 'start_or_continue()', 'stop()' and
|
|
'get_current_results()' functions
|
|
- Must be picklable in order to store the simulation state
|
|
|
|
An example simulator could look as follows:
|
|
----------------------------------------------------------------
|
|
class SomeSimulator:
|
|
def __init__(self, num_iterations):
|
|
self._num_iterations = num_iterations
|
|
self._current_iter = 0
|
|
|
|
self._simulation_running = False
|
|
|
|
self._results = pd.DataFrame()
|
|
|
|
def _perform_iteration(self):
|
|
# Perform iteration and append results
|
|
...
|
|
|
|
def start_or_continue(self) -> None:
|
|
self._simulation_running = True
|
|
|
|
while self._simulation_running and (
|
|
self._current_iter < self._num_iterations):
|
|
self._perform_iteration()
|
|
|
|
def stop(self) -> None:
|
|
self._simulation_running = False
|
|
|
|
def get_current_results(self) -> pd.DataFrame:
|
|
return self._results
|
|
----------------------------------------------------------------
|
|
|
|
Usage
|
|
=====
|
|
To start a new simulation:
|
|
----------------------------------------------------------------
|
|
sim_mgr = SimulationManager(results_dir="results", saves_dir="saves")
|
|
|
|
sim = SomeSimulator(num_iterations=100)
|
|
sim_mgr.configure_simulation(simulator=sim, name='Some Simulation', \
|
|
column_labels=['label1', 'label2'])
|
|
sim_mgr.start()
|
|
----------------------------------------------------------------
|
|
|
|
To check for a previously interrupted simulation and continue:
|
|
----------------------------------------------------------------
|
|
sim_mgr = SimulationManager(results_dir="results", saves_dir="saves")
|
|
|
|
unfinished_sims = sim_mgr.get_unfinished()
|
|
|
|
if len(unfinished_sims) > 0:
|
|
sim_mgr.load_unfinished(unfinished_sims[0])
|
|
sim_mgr.simulate()
|
|
----------------------------------------------------------------
|
|
"""
|
|
|
|
|
|
from utility.simulation.management import SimulationManager, \
|
|
SimulationDeSerializer
|