mosaik.scenario
— Classes related to the scenario creation
This module provides the interface for users to create simulation scenarios for mosaik.
The World
holds all necessary data for the simulation and allows the
user to start simulators. It provides a ModelFactory
(and
a ModelMock
) via which the user can instantiate model instances
(entities). The method World.run
finally starts the simulation.
- mosaik.scenario.SimConfig[source]
Description of all the simulators you intend to use in your simulation.
alias of
Dict
[str
,Union
[PythonModel
,ConnectModel
,CmdModel
]]
- typeddict mosaik.scenario.PythonModel[source]
-
- Required Keys:
python (
str
) – The Simulator subclass for this simulator, encoded as a string module_name:ClassName.
- Optional Keys:
- typeddict mosaik.scenario.ConnectModel[source]
-
- Required Keys:
connect (
str
) – The host:port address for this simulator.
- Optional Keys:
- typeddict mosaik.scenario.CmdModel[source]
-
- Required Keys:
cmd (
str
) – The command to start this simulator. String %(python)s will be replaced by the python command used to start this scenario, %(addr)s will be replaced by the host:port combination to which the simulator should connect.
- Optional Keys:
- class mosaik.scenario.World(sim_config, mosaik_config=None, time_resolution=1.0, debug=False, cache=True, max_loop_iterations=100, asyncio_loop=None)[source]
The world holds all data required to specify and run the scenario.
It provides a method to start a simulator process (
start
) and manages the simulator instances.You have to provide a sim_config which tells the world which simulators are available and how to start them. See
mosaik.simmanager.start
for more details.mosaik_config can be a dict or list of key-value pairs to set addional parameters overriding the defaults:
{ 'addr': ('127.0.0.1', 5555), 'start_timeout': 2, # seconds 'stop_timeout': 2, # seconds }
Here, addr is the network address that mosaik will bind its socket to. start_timeout and stop_timeout specifiy a timeout (in seconds) for starting/stopping external simulator processes.
If execution_graph is set to
True
, an execution graph will be created during the simulation. This may be useful for debugging and testing. Note, that this increases the memory consumption and simulation time.- Parameters:
sim_config (SimConfig) –
mosaik_config (Optional[MosaikConfig]) –
time_resolution (float) –
debug (bool) –
cache (bool) –
max_loop_iterations (int) –
asyncio_loop (Optional[asyncio.AbstractEventLoop]) –
- config: MosaikConfigTotal[source]
The config dictionary for general mosaik settings.
- sims: Dict[SimId, simmanager.SimRunner][source]
A dictionary of already started simulators instances.
- time_resolution: float[source]
The number of seconds that correspond to one mosaik time step in this situation. The default value is 1.0, meaning that one integer step corresponds to one second simulated time.
- max_loop_iterations: int[source]
The number of iterations allowed for same-time loops within one time step. This is checked to prevent accidental infinite loops. Increase this value if your same-time loops require many iterations to converge.
- entity_graph: networkx.Graph[FullId][source]
The
graph
of related entities. Nodes are(sid, eid)
tuples. Each note has an attribute entity with anEntity
.
- start(sim_name, sim_id=None, **sim_params)[source]
Start the simulator named sim_name and return a
ModelFactory
for it.- Parameters:
- Return type:
- connect(src, dest, *attr_pairs, async_requests=False, time_shifted=False, initial_data={}, weak=False)[source]
Connect the src entity to dest entity.
Establish a data-flow for each
(src_attr, dest_attr)
tuple in attr_pairs. If src_attr and dest_attr have the same name, you you can optionally only pass one of them as a single string.Raise a
ScenarioError
if both entities share the same simulator instance, if at least one (src. or dest.) attribute in attr_pairs does not exist, or if the connection would introduce a cycle in the data-flow (e.g., A → B → C → A).If the dest simulator may make asynchronous requests to mosaik to query data from src (or set data to it), async_requests should be set to
True
so that the src simulator stays in sync with dest.An alternative to asynchronous requests are time-shifted connections. Their data flow is always resolved after normal connections so that cycles in the data-flow can be realized without introducing deadlocks. For such a connection time_shifted should be set to
True
and initial_data should contain a dict with input data for the first simulation step of the receiving simulator.An alternative to using async_requests to realize cyclic data-flow is given by the time_shifted kwarg. If set to
True
it marks the connection as cycle-closing (e.g. C → A). It must always be used with initial_data specifying a dict with the data sent to the destination simulator at the first step (e.g. {‘src_attr’: value}).
- set_initial_event(sid, time=0)[source]
Set an initial step for simulator sid at time time (default=0).
- get_data(entity_set, *attributes)[source]
Get and return the values of all attributes for each entity of an entity_set.
The return value is a dict mapping the entities of entity_set to dicts containing the values of each attribute in attributes:
{ Entity(...): { 'attr_1': 'val_1', 'attr_2': 'val_2', ... }, ... }
- run(until, rt_factor=None, rt_strict=False, print_progress=True, lazy_stepping=True)[source]
Start the simulation until the simulation time until is reached.
Before this method returns, it stops all simulators and closes mosaik’s server socket. So this method should only be called once.
- Parameters:
until (int) – The end of the simulation in mosaik time steps (exclusive).
rt_factor (float | None) – The real-time factor. If set to a number > 0, the simulation will run in real-time mode. A real-time factor of 1. means that 1 second in simulated time takes 1 second in real time. An real-time factor of 0.5 will let the simulation run twice as fast as real time. For correct behavior of the real-time factor, the time resolution of the scenario has to be set adequately (the default is 1 second).
rt_strict (bool) – If the simulators are too slow for the real-time factor you chose, mosaik will only print a warning by default. In order to raise a
RuntimeError
instead, you can set rt_strict toTrue
.print_progress (bool | Literal['individual']) –
Whether progress bars are printed while the simulation is running. The default is to print one bar representing the global progress of the simulation. You can also set the value to
'individual'
to get one bar per simulator in your simulation (in addition to the global one). A value ofFalse
turns off the progress bars completely.The progress bars use tqdm; see their documentation on how to write to the console without interfering with the bars.
lazy_stepping (bool) – Whether to prevent simulators from running ahead of their successors by more than one step. If
False
a simulator always steps as long all input is provided. This might decrease the simulation time but increase the memory consumption.
- cache_triggering_ancestors()[source]
Collects the ancestors of each simulator and stores them in the respective simulator object.
- class mosaik.scenario.ModelFactory(world, group, sid, proxy)[source]
This is a facade for a simulator sim that allows the user to create new model instances (entities) within that simulator.
For every model that a simulator publicly exposes, the
ModelFactory
provides aModelMock
attribute that actually creates the entities.If you access an attribute that is not a model or if the model is not marked as public, an
ScenarioError
is raised.- Parameters:
world (World) –
group (SimGroup) –
sid (SimId) –
proxy (Proxy) –
- class mosaik.scenario.ModelMock(world, factory, model, proxy)[source]
Instances of this class are exposed as attributes of
ModelFactory
and allow the instantiation of simulator models.You can call an instance of this class to create exactly one entity:
sim.ModelName(x=23)
. Alternatively, you can use thecreate
method to create multiple entities with the same set of parameters at once:sim.ModelName.create(3, x=23)
.- Parameters:
world (World) –
factory (ModelFactory) –
model (ModelName) –
proxy (Proxy) –
- create(num, **model_params)[source]
Create num entities with the specified model_params and return a list with the entity dicts.
The returned list of entities is the same as returned by
mosaik_api_v3.Simulator.create
, but the simulator is prepended to every entity ID to make them globally unique.