/
pandas_reporter.py
131 lines (98 loc) · 5.45 KB
/
pandas_reporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from __future__ import annotations
from typing import Any
from flask import current_app
import timely_beliefs as tb
from flexmeasures.data.models.reporting import Reporter
from flexmeasures.data.schemas.reporting.pandas_reporter import (
PandasReporterConfigSchema,
)
class PandasReporter(Reporter):
"""This reporter applies a series of pandas methods on"""
__version__ = "1"
__author__ = None
schema = PandasReporterConfigSchema()
transformations: list[dict[str, Any]] = None
final_df_output: str = None
def deserialize_reporter_config(self):
# call super class deserialize_reporter_config
super().deserialize_reporter_config()
# extract PandasReporter specific fields
self.transformations = self.reporter_config.get("transformations")
self.final_df_output = self.reporter_config.get("final_df_output")
def _compute(self) -> tb.BeliefsDataFrame:
"""
This method applies the transformations and outputs the dataframe
defined in `final_df_output` field of the report_config.
"""
# apply pandas transformations to the dataframes in `self.data`
self._apply_transformations()
final_output = self.data[self.final_df_output]
return final_output
def get_object_or_literal(self, value: Any, method: str) -> Any:
"""This method allows using the dataframes as inputs of the Pandas methods that
are run in the transformations. Make sure that they have been created before accessed.
This works by putting the symbol `@` in front of the name of the dataframe that we want to reference.
For instance, to reference the dataframe test_df, which lives in self.data, we would do `@test_df`.
This functionality is disabled for methods `eval`and `query` to avoid interfering their internal behaviour
given that they also use `@` to allow using local variables.
Example:
>>> self.get_object_or_literal(["@df_wind", "@df_solar"], "sum")
[<BeliefsDataFrame for Wind Turbine sensor>, <BeliefsDataFrame for Solar Panel sensor>]
"""
if method in ["eval", "query"]:
if isinstance(value, str) and value.startswith("@"):
current_app.logger.debug(
"Cannot reference objects in self.data using the method eval or query. That is because these methods use the symbol `@` to make reference to local variables."
)
return value
if isinstance(value, str) and value.startswith("@"):
value = value.replace("@", "")
return self.data[value]
if isinstance(value, list):
return [self.get_object_or_literal(v, method) for v in value]
return value
def _process_pandas_args(self, args: list, method: str) -> list:
"""This method applies the function get_object_or_literal to all the arguments
to detect where to replace a string "@<object-name>" with the actual object stored in `self.data["<object-name>"]`.
"""
for i in range(len(args)):
args[i] = self.get_object_or_literal(args[i], method)
return args
def _process_pandas_kwargs(self, kwargs: dict, method: str) -> dict:
"""This method applies the function get_object_or_literal to all the keyword arguments
to detect where to replace a string "@<object-name>" with the actual object stored in `self.data["<object-name>"]`.
"""
for k, v in kwargs.items():
kwargs[k] = self.get_object_or_literal(v, method)
return kwargs
def _apply_transformations(self):
"""Convert the series using the given list of transformation specs, which is called in the order given.
Each transformation specs should include a 'method' key specifying a method name of a Pandas DataFrame.
Optionally, 'args' and 'kwargs' keys can be specified to pass on arguments or keyword arguments to the given method.
All data exchange is made through the dictionary `self.data`. The superclass Reporter already fetches BeliefsDataFrames of
the sensors and saves them in the self.data dictionary fields `sensor_<sensor_id>`. In case you need to perform complex operations on dataframes, you can
split the operations in several steps and saving the intermediate results using the parameters `df_input` and `df_output` for the
input and output dataframes, respectively.
Example:
The example below converts from hourly meter readings in kWh to electricity demand in kW.
transformations = [
{"method": "diff"},
{"method": "shift", "kwargs": {"periods": -1}},
{"method": "head", "args": [-1]},
],
"""
previous_df = None
for transformation in self.transformations:
df_input = transformation.get(
"df_input", previous_df
) # default is using the previous transformation output
df_output = transformation.get(
"df_output", df_input
) # default is OUTPUT = INPUT.method()
method = transformation.get("method")
args = self._process_pandas_args(transformation.get("args", []), method)
kwargs = self._process_pandas_kwargs(
transformation.get("kwargs", {}), method
)
self.data[df_output] = getattr(self.data[df_input], method)(*args, **kwargs)
previous_df = df_output