Skip to content

Commit

Permalink
Merge pull request #217 from dos-group/line_by_line_monitoring
Browse files Browse the repository at this point in the history
Line by line monitoring
  • Loading branch information
birnbaum authored Jun 24, 2024
2 parents 310e840 + 92863fc commit 4e54015
Showing 1 changed file with 25 additions and 0 deletions.
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

0 comments on commit 4e54015

Please sign in to comment.