Skip to content
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

Line by line monitoring #217

Merged
merged 2 commits into from
Jun 24, 2024
Merged
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
25 changes: 25 additions & 0 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 pathlib import Path
from csv import DictWriter
from itertools import count
from collections.abc import Iterator
from typing import Any, MutableMapping, Optional, Callable, TYPE_CHECKING
Expand Down Expand Up @@ -58,9 +60,15 @@ class Monitor(Controller):
def __init__(
self,
step_size: Optional[int] = None,
outfile: Optional[str | Path] = None,
grid_signals: Optional[dict[str, Signal]] = None,
):
super().__init__(step_size=step_size)
self.outpath: Optional[Path] = None
if outfile:
self.outpath = Path(outfile).expanduser()
self._fieldnames: Optional[list] = None

self.monitor_log: dict[datetime, dict] = defaultdict(dict)
self.custom_monitor_fns: list[Callable] = []

Expand All @@ -85,6 +93,23 @@ def step(self, time: datetime, p_delta: float, e_delta: float, state: dict) -> N
log_entry.update(monitor_fn(time))
self.monitor_log[time] = log_entry

if self.outpath:
if not self._fieldnames:
log_dict = _flatten_dict(log_entry)
self._fieldnames = list(log_dict.keys())
self._fieldnames.insert(0, "time")
log_dict["time"] = time
with self.outpath.open("w") as csvfile:
writer = DictWriter(csvfile, fieldnames=self._fieldnames)
writer.writeheader()
writer.writerow(log_dict)
else:
with self.outpath.open('a', newline='') as csvfile:
writer = DictWriter(csvfile, fieldnames=self._fieldnames)
log_dict = _flatten_dict(log_entry)
log_dict["time"] = time
writer.writerow(log_dict)

def to_csv(self, out_path: str):
df = pd.DataFrame({k: _flatten_dict(v) for k, v in self.monitor_log.items()}).T
df.to_csv(out_path)
Expand Down
Loading