test_forecasting_jobs.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # flake8: noqa: E402
  2. from __future__ import annotations
  3. from datetime import datetime, timedelta
  4. import os
  5. import numpy as np
  6. from rq.job import Job
  7. from flexmeasures.data.models.data_sources import DataSource
  8. from flexmeasures.data.models.time_series import Sensor, TimedBelief
  9. from flexmeasures.data.tests.utils import work_on_rq
  10. from flexmeasures.data.services.forecasting import (
  11. create_forecasting_jobs,
  12. handle_forecasting_exception,
  13. )
  14. from flexmeasures.utils.time_utils import as_server_time
  15. def custom_model_params():
  16. """little training as we have little data, turn off transformations until they let this test run (TODO)"""
  17. return dict(
  18. training_and_testing_period=timedelta(hours=2),
  19. outcome_var_transformation=None,
  20. regressor_transformation={},
  21. )
  22. def get_data_source(model_identifier: str = "linear-OLS model v2"):
  23. """This helper is a good way to check which model has been successfully used.
  24. Only when the forecasting job is successful, will the created data source entry not be rolled back.
  25. """
  26. data_source_name = "Seita (%s)" % model_identifier
  27. return DataSource.query.filter_by(
  28. name=data_source_name, type="forecasting script"
  29. ).one_or_none()
  30. def check_aggregate(overall_expected: int, horizon: timedelta, sensor_id: int):
  31. """Check that the expected number of forecasts were made for the given horizon,
  32. and check that each forecast is a number."""
  33. all_forecasts = (
  34. TimedBelief.query.filter(TimedBelief.sensor_id == sensor_id)
  35. .filter(TimedBelief.belief_horizon == horizon)
  36. .all()
  37. )
  38. assert len(all_forecasts) == overall_expected
  39. assert all([not np.isnan(f.event_value) for f in all_forecasts])
  40. def test_forecasting_an_hour_of_wind(db, run_as_cli, app, setup_test_data):
  41. """Test one clean run of one job:
  42. - data source was made,
  43. - forecasts have been made
  44. """
  45. # asset has only 1 power sensor
  46. wind_device_1: Sensor = setup_test_data["wind-asset-1"].sensors[0]
  47. # Remove each seasonality, so we don't query test data that isn't there
  48. wind_device_1.set_attribute("daily_seasonality", False)
  49. wind_device_1.set_attribute("weekly_seasonality", False)
  50. wind_device_1.set_attribute("yearly_seasonality", False)
  51. assert get_data_source() is None
  52. # makes 4 forecasts
  53. horizon = timedelta(hours=1)
  54. job = create_forecasting_jobs(
  55. start_of_roll=as_server_time(datetime(2015, 1, 1, 6)),
  56. end_of_roll=as_server_time(datetime(2015, 1, 1, 7)),
  57. horizons=[horizon],
  58. sensor_id=wind_device_1.id,
  59. custom_model_params=custom_model_params(),
  60. )
  61. print("Job: %s" % job[0].id)
  62. work_on_rq(app.queues["forecasting"], exc_handler=handle_forecasting_exception)
  63. assert get_data_source() is not None
  64. forecasts = (
  65. TimedBelief.query.filter(TimedBelief.sensor_id == wind_device_1.id)
  66. .filter(TimedBelief.belief_horizon == horizon)
  67. .filter(
  68. (TimedBelief.event_start >= as_server_time(datetime(2015, 1, 1, 7)))
  69. & (TimedBelief.event_start < as_server_time(datetime(2015, 1, 1, 8)))
  70. )
  71. .all()
  72. )
  73. assert len(forecasts) == 4
  74. check_aggregate(4, horizon, wind_device_1.id)
  75. def test_forecasting_two_hours_of_solar_at_edge_of_data_set(
  76. db, run_as_cli, app, setup_test_data
  77. ):
  78. # asset has only 1 power sensor
  79. solar_device_1: Sensor = setup_test_data["solar-asset-1"].sensors[0]
  80. last_power_datetime = (
  81. (
  82. TimedBelief.query.filter(TimedBelief.sensor_id == solar_device_1.id)
  83. .filter(TimedBelief.belief_horizon == timedelta(hours=0))
  84. .order_by(TimedBelief.event_start.desc())
  85. )
  86. .first()
  87. .event_start
  88. ) # datetime index of the last power value 11.45pm (Jan 1st)
  89. # makes 4 forecasts, 1 of which is for a new datetime index
  90. horizon = timedelta(hours=6)
  91. job = create_forecasting_jobs(
  92. start_of_roll=last_power_datetime
  93. - horizon
  94. - timedelta(minutes=30), # start of data on which forecast is based (5.15pm)
  95. end_of_roll=last_power_datetime
  96. - horizon
  97. + timedelta(minutes=30), # end of data on which forecast is based (6.15pm)
  98. horizons=[
  99. timedelta(hours=6)
  100. ], # so we want forecasts for 11.15pm (Jan 1st) to 0.15am (Jan 2nd)
  101. sensor_id=solar_device_1.id,
  102. custom_model_params=custom_model_params(),
  103. )
  104. print("Job: %s" % job[0].id)
  105. work_on_rq(app.queues["forecasting"], exc_handler=handle_forecasting_exception)
  106. forecasts = (
  107. TimedBelief.query.filter(TimedBelief.sensor_id == solar_device_1.id)
  108. .filter(TimedBelief.belief_horizon == horizon)
  109. .filter(TimedBelief.event_start > last_power_datetime)
  110. .all()
  111. )
  112. assert len(forecasts) == 1
  113. check_aggregate(4, horizon, solar_device_1.id)
  114. def check_failures(
  115. redis_queue,
  116. failure_search_words: list[str] | None = None,
  117. model_identifiers: list[str] | None = None,
  118. ):
  119. """Check that there was at least one failure.
  120. For each failure, the exception message can be checked for a search word
  121. and the model identifier can also be compared to a string.
  122. """
  123. if os.name == "nt":
  124. print("Failed job registry not working on Windows. Skipping check...")
  125. return
  126. failed = redis_queue.failed_job_registry
  127. if failure_search_words is None:
  128. failure_search_words = []
  129. if model_identifiers is None:
  130. model_identifiers = []
  131. failure_count = max(len(failure_search_words), len(model_identifiers), 1)
  132. print(
  133. "FAILURE QUEUE: %s"
  134. % [
  135. Job.fetch(jid, connection=redis_queue.connection).meta
  136. for jid in failed.get_job_ids()
  137. ]
  138. )
  139. assert failed.count == failure_count
  140. for job_idx in range(failure_count):
  141. job = Job.fetch(
  142. failed.get_job_ids()[job_idx], connection=redis_queue.connection
  143. )
  144. if len(failure_search_words) >= job_idx:
  145. assert failure_search_words[job_idx] in job.latest_result().exc_string
  146. if model_identifiers:
  147. assert job.meta["model_identifier"] == model_identifiers[job_idx]
  148. def test_failed_forecasting_insufficient_data(
  149. app, run_as_cli, clean_redis, setup_test_data
  150. ):
  151. """This one (as well as the fallback) should fail as there is no underlying data.
  152. (Power data is in 2015)"""
  153. # asset has only 1 power sensor
  154. solar_device_1: Sensor = setup_test_data["solar-asset-1"].sensors[0]
  155. create_forecasting_jobs(
  156. start_of_roll=as_server_time(datetime(2016, 1, 1, 20)),
  157. end_of_roll=as_server_time(datetime(2016, 1, 1, 22)),
  158. horizons=[timedelta(hours=1)],
  159. sensor_id=solar_device_1.id,
  160. custom_model_params=custom_model_params(),
  161. )
  162. work_on_rq(app.queues["forecasting"], exc_handler=handle_forecasting_exception)
  163. check_failures(app.queues["forecasting"], 2 * ["NotEnoughDataException"])
  164. def test_failed_forecasting_invalid_horizon(
  165. app, run_as_cli, clean_redis, setup_test_data
  166. ):
  167. """This one (as well as the fallback) should fail as the horizon is invalid."""
  168. # asset has only 1 power sensor
  169. solar_device_1: Sensor = setup_test_data["solar-asset-1"].sensors[0]
  170. create_forecasting_jobs(
  171. start_of_roll=as_server_time(datetime(2015, 1, 1, 21)),
  172. end_of_roll=as_server_time(datetime(2015, 1, 1, 23)),
  173. horizons=[timedelta(hours=18)],
  174. sensor_id=solar_device_1.id,
  175. custom_model_params=custom_model_params(),
  176. )
  177. work_on_rq(app.queues["forecasting"], exc_handler=handle_forecasting_exception)
  178. check_failures(app.queues["forecasting"], 2 * ["InvalidHorizonException"])
  179. def test_failed_unknown_model(app, clean_redis, setup_test_data):
  180. """This one should fail because we use a model search term which yields no model configurator."""
  181. # asset has only 1 power sensor
  182. solar_device_1: Sensor = setup_test_data["solar-asset-1"].sensors[0]
  183. horizon = timedelta(hours=1)
  184. cmp = custom_model_params()
  185. cmp["training_and_testing_period"] = timedelta(days=365)
  186. create_forecasting_jobs(
  187. start_of_roll=as_server_time(datetime(2015, 1, 1, 12)),
  188. end_of_roll=as_server_time(datetime(2015, 1, 1, 14)),
  189. horizons=[horizon],
  190. sensor_id=solar_device_1.id,
  191. model_search_term="no-one-knows-this",
  192. custom_model_params=cmp,
  193. )
  194. work_on_rq(app.queues["forecasting"], exc_handler=handle_forecasting_exception)
  195. check_failures(app.queues["forecasting"], ["No model found for search term"])