MCPcopy Create free account
hub / github.com/ahalev/python-microgrid / get_log

Method get_log

src/pymgrid/microgrid/microgrid.py:455–525  ·  view source on GitHub ↗

Collect a log of controls and responses of the microgrid. Parameters ---------- as_frame : bool, default True Whether to return the log as a pd.DataFrame. If False, returns a nested dict. drop_singleton_key : bool, default False Whet

(self, as_frame=True, drop_singleton_key=False, drop_forecasts=False)

Source from the content-addressed store, hash-verified

453 for module_name, module_list in self._modules.iterdict() if module_name in data_dict}
454
455 def get_log(self, as_frame=True, drop_singleton_key=False, drop_forecasts=False):
456 """
457
458 Collect a log of controls and responses of the microgrid.
459
460 Parameters
461 ----------
462 as_frame : bool, default True
463 Whether to return the log as a pd.DataFrame. If False, returns a nested dict.
464 drop_singleton_key : bool, default False
465 Whether to drop index level enumerating the modules by name if each module name has only one module.
466 Ignored otherwise.
467 drop_forecasts : bool, default False
468 Whether to drop columns that are of time series forecasts.
469
470 Returns
471 -------
472 pd.DataFrame or dict
473
474 """
475 _log_dict = dict()
476 for name, modules in self._modules.iterdict():
477 for j, module in enumerate(modules):
478 for key, value in module.log_dict().items():
479 _log_dict[(name, j, key)] = value
480
481 _log_dict = dict(sorted(_log_dict.items(), key=lambda k: k[0]))
482
483 for key, value in self._balance_logger.to_dict().items():
484 _log_dict[('balance', 0, key)] = value
485
486 pad = (0, '')
487
488 for key, value in self._microgrid_logger.items():
489 key = key if pd.api.types.is_list_like(key) else [key]
490 _log_dict[(*key, *pad[len(key)-1:])] = value
491
492 col_names = ['module_name', 'module_number', 'field']
493
494 initial_step = self._modules.get_attrs('initial_step', unique=True)
495
496 try:
497 df = pd.DataFrame(_log_dict, index=pd.RangeIndex(start=initial_step, stop=self.current_step))
498 except ValueError as e:
499 if 'Length of values' in e.args[0]:
500 module_log_lengths = pd.Series([len(log_dict) for log_dict in _log_dict.values()])
501
502 msg = f"Length of module log dicts ({module_log_lengths.unique()}) " \
503 f"do not match self.current_step-initial_step ({self.current_step-initial_step}). " \
504 f"Did you set a trajectory attribute " \
505 f"('initial_step', 'final_step', 'trajectory_func') without calling Microgrid.reset()?"
506
507 raise ValueError(msg)
508
509 else:
510 raise
511
512 df.columns = pd.MultiIndex.from_tuples(df.columns.to_list(), names=col_names)

Callers 3

logMethod · 0.95
runMethod · 0.80
_run_mpc_on_modularMethod · 0.80

Calls 6

iterdictMethod · 0.80
log_dictMethod · 0.80
get_attrsMethod · 0.80
containsMethod · 0.80
to_dictMethod · 0.45
to_listMethod · 0.45

Tested by

no test coverage detected