8000 Sim name logging by marvin-steinke · Pull Request #216 · dos-group/vessim · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Sim name logging #216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/building-and-installation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jobs:
uses: actions/cache@v3
with:
path: .venv
key: venv-${{ steps.setup-python.outputs.python-version }}
key: venv-${{ matrix.python-version }}

# build package
- name: Build package out of local poject
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/linting-and-testing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ jobs:
uses: actions/cache@v3
with:
path: .venv
key: venv-${{ steps.setup-python.outputs.python-version }}
key: venv-${{ matrix.python-version }}

# install dependencies if cache not available
- name: Install dependencies
Expand Down
26 changes: 13 additions & 13 deletions examples/basic_example.ipynb

Large diffs are not rendered by default.

22 changes: 11 additions & 11 deletions examples/controller_example.ipynb

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion examples/signal_example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.2"
"version": "3.8.19"
}
},
"nbformat": 4,
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ numpy = [
{ version = "^1.26.0", python = ">=3.12" }
]
pandas = "^2.0.0"
mosaik = "^3.2.0"
mosaik = "^3.3.0"
mosaik-api-v3 = "^3.0.4"
loguru = "^0.6.0"

Expand Down
21 changes: 17 additions & 4 deletions vessim/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from abc import ABC, abstractmethod
from collections import defaultdict
from datetime import datetime
from itertools import count
from collections.abc import Iterator
from typing import Any, MutableMapping, Optional, Callable, TYPE_CHECKING

import mosaik_api_v3 # type: ignore
Expand All @@ -17,10 +19,19 @@


class Controller(ABC):
def __init__(self, step_size: Optional[int] = None):
_counters: dict[type[Controller], Iterator[int]] = {}

def __init_subclass__(cls, **kwargs) -> None:
"""Initializes the subclass and sets up a counter for naming."""
super().__init_subclass__(**kwargs)
cls._counters[cls] = count()

def __init__(self, step_size: Optional[int] = None) -> None:
cls = self.__class__
self.name: str = f"{cls.__name__}-{next(cls._counters[cls])}"
self.step_size = step_size

def start(self, microgrid: Microgrid):
def start(self, microgrid: Microgrid) -> None:
"""Function to be executed before simulation is started. Can be overridden."""
pass

Expand Down Expand Up @@ -139,6 +150,8 @@ def create(self, num, model, **model_params):

def step(self, time, inputs, max_advance):
assert self.controller is not None
assert self.clock is not None
assert self.step_size is not None
now = self.clock.to_datetime(time)
self.controller.step(now, *self._parse_controller_inputs(inputs[self.eid]))
return time + self.step_size
Expand All @@ -152,8 +165,8 @@ def finalize(self) -> None:
self.controller.finalize()

def _parse_controller_inputs(
self, inputs: dict[str, dict[str, Any]]
) -> tuple[float,float, dict]:
self, inputs: dict[str, dict[str, Any]]
) -> tuple[float, float, dict]:
p_delta = _get_val(inputs, "p_delta")
last_e = self.e
self.e = _get_val(inputs, "e")
Expand Down
28 changes: 16 additions & 12 deletions vessim/cosim.py
341A
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ def __init__(
actor_step_size = actor.step_size if actor.step_size else step_size
if actor_step_size % step_size != 0:
raise ValueError("Actor step size has to be a multiple of grids step size.")
actor_sim = world.start("Actor", clock=clock, step_size=actor_step_size)
actor_sim = world.start(
"Actor", sim_id=actor.name, clock=clock, step_size=actor_step_size
)
# We initialize all actors before the grid simulation to make sure that
# there is already a valid p_delta at step 0
actor_entity = actor_sim.Actor(actor=actor)
Expand All @@ -52,13 +54,13 @@ def __init__(
controller_step_size = controller.step_size if controller.step_size else step_size
if controller_step_size % step_size != 0:
raise ValueError("Controller step size has to be a multiple of grids step size.")
controller_sim = world.start("Controller", clock=clock, step_size=controller_step_size)
controller_sim = world.start(
"Controller", sim_id=controller.name, clock=clock, step_size=controller_step_size
)
controller_entity = controller_sim.Controller(controller=controller)
world.connect(aggregator_entity, controller_entity, "p_delta")
for actor_name, actor_entity in actor_names_and_entities:
world.connect(
actor_entity, controller_entity, ("state", f"actor.{actor_name}")
)
world.connect(actor_entity, controller_entity, ("state", f"actor.{actor_name}"))
controller_entities.append(controller_entity)

grid_sim = world.start("Grid", step_size=step_size)
Expand Down Expand Up @@ -91,7 +93,7 @@ def finalize(self):


class Environment:
COSIM_CONFIG = {
COSIM_CONFIG: mosaik.SimConfig = {
"Actor": {"python": "vessim.actor:_ActorSim"},
"Aggregator": {"python": "vessim.cosim:_AggregatorSim"},
"Controller": {"python": "vessim.controller:_ControllerSim"},
Expand All @@ -101,7 +103,7 @@ class Environment:
def __init__(self, sim_start):
self.clock = Clock(sim_start)
self.microgrids = []
self.world = mosaik.World(self.COSIM_CONFIG) # type: ignore
self.world = mosaik.World(self.COSIM_CONFIG, skip_greetings=True)

def add_microgrid(
self,
Expand Down Expand Up @@ -131,17 +133,16 @@ def run(
until: Optional[int] = None,
rt_factor: Optional[float] = None,
print_progress: bool | Literal["individual"] = True,
behind_threshold: float = 0.01
behind_threshold: float = 0.01,
):
if until is None:
# there is no integer representing infinity in python
until = float("inf") # type: ignore
until = float("inf") # type: ignore
assert until is not None
if rt_factor:
disable_rt_warnings(behind_threshold)
try:
self.world.run(
until=until, rt_factor=rt_factor, print_progress=print_progress
)
self.world.run(until=until, rt_factor=rt_factor, print_progress=print_progress)
except Exception:
for microgrid in self.microgrids:
microgrid.finalize()
Expand Down Expand Up @@ -176,6 +177,7 @@ def create(self, num, model, **model_params):

def step(self, time, inputs, max_advance):
self.p_delta = sum(inputs[self.eid]["p"].values())
assert self.step_size is not None
return time + self.step_size

def get_data(self, outputs):
Expand Down Expand Up @@ -214,7 +216,9 @@ def create(self, num, model, **model_params):

def step(self, time, inputs, max_advance):
p_delta = list(inputs[self.eid]["p_delta"].values())[0]
assert self.policy is not None
self.e += self.policy.apply(p_delta, duration=self.step_size, storage=self.storage)
assert self.step_size is not None
return time + self.step_size

def get_data(self, outputs):
Expand Down
Loading
0