commonpower.modeling.history.ModelHistory
- class ModelHistory(model_entities: list[ModelEntity], retention: int = -1)[source]
Bases:
objectThis class provides a lightweight interface to log “snapshots” of a pyomo model and some methods to retrieve this information. The logs are stored in self.history in the form:
[(<time stamp>, {<global model element id>: <value>, …}), …].
- Parameters:
model_entities (list[ModelEntity]) – Model entities to create a history for. Note that all Vars/Params of the entity and all its subordinate entities will be included. Technically, we are including everything within the pyomo blocks that correspond to the given entities.
retention (int, optional) – How many logs are kept before deleting from the top (essentially a ring buffer). When set to -1, all logs will be kept. Defaults to -1.
Methods
Filters the history to only contain model elements of the given local names.
Filters the history to only contain data from the given entity instances.
Filters the history to only contain entities of the given types.
Filters all element histories for a certain time index.
Filters all element histories for a given time period
DEPRECATED! Use .filter_for_entities() and .filter_for_element_names() instead.
Creates a "snapshot" of the values of all model elements corresponding to the given entities and stores them together with the given timestamp.
Plots entire history and, if given, even multiple histories.
Clears self.history.
Converts the history to a pandas DataFrame.
- filter_for_element_names(names: str | List[str]) ModelHistory[source]
Filters the history to only contain model elements of the given local names.
- Parameters:
names (Union[str, List[str]]) – Local names to filter for.
- Returns:
ModelHistory – Filtered model history.
- filter_for_entities(entities: ModelEntity | List[ModelEntity], follow_node_tree: bool = False) ModelHistory[source]
Filters the history to only contain data from the given entity instances.
- Parameters:
entities (Union[ModelEntity, List[ModelEntity]]) – Entites to filter for.
follow_node_tree (bool, optional) – If True, all entites which are subordinate to the given entites will be included. Defaults to False.
- Returns:
ModelHistory – Filtered model history.
- filter_for_entity_types(entity_types: Type[ModelEntity] | List[Type[ModelEntity]]) ModelHistory[source]
Filters the history to only contain entities of the given types.
- Parameters:
entity_types (Union[Type[ModelEntity], List[Type[ModelEntity]]]) – Entity types to filter for.
- Returns:
ModelHistory – Filtered model history.
- filter_for_time_index(t_index: int = 0) ModelHistory[source]
Filters all element histories for a certain time index.
- Parameters:
t_index (int, optional) – Time index. A time index of 0 represents the realized values at each timestep. Defaults to 0.
- Returns:
ModelHistory – Filtered model history.
- filter_for_time_period(start: str | Timestamp, end: str | Timestamp) ModelHistory[source]
Filters all element histories for a given time period
- Parameters:
start (Union[str, pd.Timestamp]) – beginning of the time period.
str (If) – 00:00”.
00 (should be in format "2016-09-04) – 00:00”.
end (Union[str, pd.Timestamp]) – end of the time period. If str, should be in format “2016-09-04 00:00:00”.
- Returns:
(ModelHistory) – the filtered history.
- get_history_for_element(entity: ModelEntity, name: str, only_realized_values=True) list[tuple[str, int | float | ndarray]][source]
DEPRECATED! Use .filter_for_entities() and .filter_for_element_names() instead. Interface to extract the history of a single model element.
- Parameters:
entity (ModelEntity) – Entity the element is associated with.
name (str) – Local name of the element. This is a utility since the elements are stored in the history with their global id.
only_realized_values (bool, optional) – Every log of an indexed element is a np.ndarray. If this argument is set to True, only the first element of this array is retrieved for every log. The intuition is that in an MPC-type setup, only the value at time index 0 is actually realized (the rest only “predicted”). Defaults to True.
- Returns:
list[tuple[str, Union[int, float, np.ndarray]]] – Element history in the form: [(<time stamp>, <values(s)>, …].
- log(model: ConcreteModel, timestamp: datetime | str | int) None[source]
Creates a “snapshot” of the values of all model elements corresponding to the given entities and stores them together with the given timestamp. If self.history is already “full” (specified by self.retention), the first entry of self.history is deleted.
- Parameters:
model (ConcreteModel) – Model to extract the values from.
timestamp (Union[datetime, str, int]) – Timestamp information. Can technically be of any type but should be unique to avoid downstream issues.
- plot(histories: ModelHistory | List[ModelHistory] = [], timestamp_format: str = '%Y-%m-%d %H:%M', return_time_series=False, show: bool = True, x_label_interval=1, plot_styles: Dict[str, dict] = {}, **plt_show_kwargs) None | dict[source]
Plots entire history and, if given, even multiple histories. We assume here that all elements have been consistently logged within the histories.
- Parameters:
histories (Union[ModelHistory, List[ModelHistory]], optional) – Additional histories to plot. Defaults to [].
timestamp_format (str, optional) – Format to display the timestamp in. Defaults to “%Y-%m-%d %H:%M”.
return_time_series (bool, optional) – If true, returns the time series of realized element values. Defaults to False.
show (bool, optional) – Determines if the plot is shown. Defaults to True.
x_label_interval (int, optional) – Only print labels on the x-axis every n timesteps (to reduce clutter)
plot_styles (dict[str, dict], optional) –
Dictionary of regular expressions to pyplot.plot kwargs. For every element that is plotted, the id is matched (re.search) against all keys of this dict. The kwargs of the first match are used for the call to plot. Additionally, a drawstyle of stairs is supported, which calls pyplot.stairs instead of plot. (VAR, CONSTANT, DATA and INPUT default to stairs) Example: ``` history.plot(plot_styles={
- ’soc’: { # color all elements that have “soc” in their id green
’color’: ‘green’,
}, ‘p$’: { # draw all elements that end in “…p” as dotted lines
’linestyle’: ‘:’, ‘alpha’: 0.5,
}, ‘’: { # fallback: draw all remaining as lines even if they would default to “stairs”
’drawstyle’: ‘default’,
},
- to_df(at_time_index: int = 0) DataFrame[source]
Converts the history to a pandas DataFrame. All available elements are columns, the timestamps are the index.
- Parameters:
at_time_index (int, optional) – Index of the forecast horizon to select for each time step. An index of 0 represents the realized values, a value of 1 represents the values that were predicted one time step into the future, etc. Defaults to 0.
- Returns:
pd.DataFrame – Pandas DataFrame representation of the history.