pandas_reporter.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. from __future__ import annotations
  2. from typing import Any
  3. from datetime import datetime, timedelta
  4. from copy import deepcopy, copy
  5. from flask import current_app
  6. from flexmeasures.utils.unit_utils import convert_units
  7. import timely_beliefs as tb
  8. import pandas as pd
  9. from flexmeasures.data.models.reporting import Reporter
  10. from flexmeasures.data.schemas.reporting.pandas_reporter import (
  11. PandasReporterConfigSchema,
  12. PandasReporterParametersSchema,
  13. )
  14. from flexmeasures.data.models.time_series import Sensor
  15. from flexmeasures.utils.time_utils import server_now
  16. class PandasReporter(Reporter):
  17. """This reporter applies a series of pandas methods on"""
  18. __version__ = "1"
  19. __author__ = "Seita"
  20. _config_schema = PandasReporterConfigSchema()
  21. _parameters_schema = PandasReporterParametersSchema()
  22. input: list[str] = None
  23. transformations: list[dict[str, Any]] = None
  24. final_df_output: str = None
  25. data: dict[str, tb.BeliefsDataFrame | pd.DataFrame] = None
  26. def _get_input_target_unit(self, name: str) -> str | None:
  27. for required_input in self._config["required_input"]:
  28. if name in required_input.get("name"):
  29. return required_input.get("unit")
  30. return None
  31. def _get_output_target_unit(self, name: str) -> str | None:
  32. for required_output in self._config["required_output"]:
  33. if name in required_output.get("name"):
  34. return required_output.get("unit")
  35. return None
  36. def fetch_data(
  37. self,
  38. start: datetime,
  39. end: datetime,
  40. input: dict,
  41. resolution: timedelta | None = None,
  42. belief_time: datetime | None = None,
  43. use_latest_version_only: bool | None = None, # deprecated
  44. ):
  45. """
  46. Fetches the timed_beliefs from the database
  47. """
  48. # todo: deprecate the 'use_latest_version_only' argument (announced v0.25.0)
  49. if use_latest_version_only is not None:
  50. current_app.logger.warning(
  51. """The `use_latest_version_only` argument to `PandasReporter.compute()` is deprecated. By default, data is sourced by the latest version of a data generator by default. You can still override this behaviour by calling `PandasReporter().compute(input=[dict(use_latest_version_per_event=False)])` instead."""
  52. )
  53. droplevels = self._config.get("droplevels", False)
  54. self.data = {}
  55. for input_search_parameters in input:
  56. _input_search_parameters = input_search_parameters.copy()
  57. if use_latest_version_only is not None:
  58. _input_search_parameters["use_latest_version_per_event"] = (
  59. use_latest_version_only
  60. )
  61. sensor: Sensor = _input_search_parameters.pop("sensor", None)
  62. name = _input_search_parameters.pop("name", f"sensor_{sensor.id}")
  63. # using start / end instead of event_starts_after/event_ends_before when not defined
  64. event_starts_after = _input_search_parameters.pop(
  65. "event_starts_after", start
  66. )
  67. event_ends_before = _input_search_parameters.pop("event_ends_before", end)
  68. resolution = _input_search_parameters.pop("resolution", resolution)
  69. belief_time = _input_search_parameters.pop("belief_time", belief_time)
  70. source = _input_search_parameters.pop(
  71. "source", _input_search_parameters.pop("sources", None)
  72. )
  73. bdf = sensor.search_beliefs(
  74. event_starts_after=event_starts_after,
  75. event_ends_before=event_ends_before,
  76. resolution=resolution,
  77. beliefs_before=belief_time,
  78. source=source,
  79. **_input_search_parameters,
  80. )
  81. # store data source as local variable
  82. for source in bdf.sources.unique():
  83. self.data[f"source_{source.id}"] = source
  84. unit = self._get_input_target_unit(name)
  85. if unit is not None:
  86. bdf *= convert_units(
  87. 1,
  88. from_unit=sensor.unit,
  89. to_unit=unit,
  90. event_resolution=sensor.event_resolution,
  91. )
  92. if droplevels:
  93. # dropping belief_time, source and cumulative_probability columns
  94. bdf = bdf.droplevel([1, 2, 3])
  95. assert (
  96. bdf.index.is_unique
  97. ), "BeliefDataframe has more than one row per event."
  98. # store BeliefsDataFrame as local variable
  99. self.data[name] = bdf
  100. def _compute_report(self, **kwargs) -> list[dict[str, Any]]:
  101. """
  102. This method applies the transformations and outputs the dataframe
  103. defined in `final_df_output` field of the report_config.
  104. """
  105. # report configuration
  106. start: datetime = kwargs.get("start")
  107. end: datetime = kwargs.get("end")
  108. input: dict = kwargs.get("input")
  109. resolution: timedelta | None = kwargs.get("resolution", None)
  110. belief_time: datetime | None = kwargs.get("belief_time", None)
  111. belief_horizon: timedelta | None = kwargs.get("belief_horizon", None)
  112. output: list[dict[str, Any]] = kwargs.get("output")
  113. use_latest_version_only: bool = kwargs.get("use_latest_version_only", None)
  114. # by default, use the minimum resolution among the input sensors
  115. if resolution is None:
  116. resolution = min([i["sensor"].event_resolution for i in input])
  117. # fetch sensor data
  118. self.fetch_data(
  119. start, end, input, resolution, belief_time, use_latest_version_only
  120. )
  121. if belief_time is None:
  122. belief_time = server_now()
  123. # apply pandas transformations to the dataframes in `self.data`
  124. self._apply_transformations()
  125. results = []
  126. for output_description in output:
  127. result = copy(output_description)
  128. name = output_description["name"]
  129. output_data = self.data[name]
  130. if isinstance(output_data, tb.BeliefsDataFrame):
  131. # if column is missing, use the first column
  132. column = output_description.get("column", output_data.columns[0])
  133. output_data = output_data.rename(columns={column: "event_value"})[
  134. ["event_value"]
  135. ]
  136. output_data = self._clean_belief_dataframe(
  137. output_data, belief_time, belief_horizon
  138. )
  139. elif isinstance(output_data, tb.BeliefsSeries):
  140. output_data = self._clean_belief_series(
  141. output_data, belief_time, belief_horizon
  142. )
  143. output_unit = self._get_output_target_unit(name)
  144. if output_unit is not None:
  145. output_data *= convert_units(
  146. 1,
  147. from_unit=output_unit,
  148. to_unit=output_description["sensor"].unit,
  149. event_resolution=output_description["sensor"].event_resolution,
  150. )
  151. result["data"] = output_data
  152. results.append(result)
  153. return results
  154. def _clean_belief_series(
  155. self,
  156. belief_series: tb.BeliefsSeries,
  157. belief_time: datetime | None = None,
  158. belief_horizon: timedelta | None = None,
  159. ) -> tb.BeliefsDataFrame:
  160. """Create a BeliefDataFrame from a BeliefsSeries creating the necessary indexes."""
  161. belief_series = belief_series.to_frame("event_value")
  162. if belief_horizon is not None:
  163. belief_time = (
  164. belief_series["event_start"]
  165. + belief_series.event_resolution
  166. - belief_horizon
  167. )
  168. belief_series["belief_time"] = belief_time
  169. belief_series["cumulative_probability"] = 0.5
  170. belief_series["source"] = self.data_source
  171. belief_series = belief_series.set_index(
  172. ["belief_time", "source", "cumulative_probability"], append=True
  173. )
  174. return belief_series
  175. def _clean_belief_dataframe(
  176. self,
  177. bdf: tb.BeliefsDataFrame,
  178. belief_time: datetime | None = None,
  179. belief_horizon: timedelta | None = None,
  180. ) -> tb.BeliefsDataFrame:
  181. """Add missing indexes to build a proper BeliefDataFrame."""
  182. # filing the missing indexes with default values:
  183. if "belief_time" not in bdf.index.names:
  184. if belief_horizon is not None:
  185. # In case that all the index but `event_start` are dropped
  186. if (
  187. isinstance(bdf.index, pd.DatetimeIndex)
  188. and bdf.index.name == "event_start"
  189. ):
  190. event_start = bdf.index
  191. else:
  192. event_start = bdf.index.get_event_values("event_start")
  193. belief_time = event_start + bdf.event_resolution - belief_horizon
  194. else:
  195. belief_time = [belief_time] * len(bdf)
  196. bdf["belief_time"] = belief_time
  197. bdf = bdf.set_index("belief_time", append=True)
  198. if "cumulative_probability" not in bdf.index.names:
  199. bdf["cumulative_probability"] = [0.5] * len(bdf)
  200. bdf = bdf.set_index("cumulative_probability", append=True)
  201. if "source" not in bdf.index.names:
  202. bdf["source"] = [self.data_source] * len(bdf)
  203. bdf = bdf.set_index("source", append=True)
  204. return bdf
  205. def get_object_or_literal(self, value: Any, method: str) -> Any:
  206. """This method allows using the dataframes as inputs of the Pandas methods that
  207. are run in the transformations. Make sure that they have been created before accessed.
  208. This works by putting the symbol `@` in front of the name of the dataframe that we want to reference.
  209. For instance, to reference the dataframe test_df, which lives in self.data, we would do `@test_df`.
  210. This functionality is disabled for methods `eval`and `query` to avoid interfering their internal behaviour
  211. given that they also use `@` to allow using local variables.
  212. Example:
  213. >>> self.get_object_or_literal(["@df_wind", "@df_solar"], "sum")
  214. [<BeliefsDataFrame for Wind Turbine sensor>, <BeliefsDataFrame for Solar Panel sensor>]
  215. """
  216. if method in ["eval", "query"]:
  217. if isinstance(value, str) and value.startswith("@"):
  218. current_app.logger.debug(
  219. "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."
  220. )
  221. return value
  222. if isinstance(value, str) and value.startswith("@"):
  223. value = value.replace("@", "")
  224. return self.data[value]
  225. if isinstance(value, list):
  226. return [self.get_object_or_literal(v, method) for v in value]
  227. return value
  228. def _process_pandas_args(self, args: list, method: str) -> list:
  229. """This method applies the function get_object_or_literal to all the arguments
  230. to detect where to replace a string "@<object-name>" with the actual object stored in `self.data["<object-name>"]`.
  231. """
  232. for i in range(len(args)):
  233. args[i] = self.get_object_or_literal(args[i], method)
  234. return args
  235. def _process_pandas_kwargs(self, kwargs: dict, method: str) -> dict:
  236. """This method applies the function get_object_or_literal to all the keyword arguments
  237. to detect where to replace a string "@<object-name>" with the actual object stored in `self.data["<object-name>"]`.
  238. """
  239. for k, v in kwargs.items():
  240. kwargs[k] = self.get_object_or_literal(v, method)
  241. return kwargs
  242. def _apply_transformations(self):
  243. """Convert the series using the given list of transformation specs, which is called in the order given.
  244. Each transformation specs should include a 'method' key specifying a method name of a Pandas DataFrame.
  245. Optionally, 'args' and 'kwargs' keys can be specified to pass on arguments or keyword arguments to the given method.
  246. All data exchange is made through the dictionary `self.data`. The superclass Reporter already fetches BeliefsDataFrames of
  247. 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
  248. split the operations in several steps and saving the intermediate results using the parameters `df_input` and `df_output` for the
  249. input and output dataframes, respectively.
  250. Example:
  251. The example below converts from hourly meter readings in kWh to electricity demand in kW.
  252. transformations = [
  253. {"method": "diff"},
  254. {"method": "shift", "kwargs": {"periods": -1}},
  255. {"method": "head", "args": [-1]},
  256. ],
  257. """
  258. previous_df = None
  259. for _transformation in self._config.get("transformations"):
  260. transformation = deepcopy(_transformation)
  261. df_input = transformation.get(
  262. "df_input", previous_df
  263. ) # default is using the previous transformation output
  264. df_output = transformation.get(
  265. "df_output", df_input
  266. ) # default is OUTPUT = INPUT.method()
  267. method = transformation.get("method")
  268. args = self._process_pandas_args(transformation.get("args", []), method)
  269. kwargs = self._process_pandas_kwargs(
  270. transformation.get("kwargs", {}), method
  271. )
  272. self.data[df_output] = getattr(self.data[df_input], method)(*args, **kwargs)
  273. previous_df = df_output