12
12
from sqlalchemy .orm import contains_eager , joinedload
13
13
from sqlalchemy .orm .session import Session
14
14
15
+
15
16
from nowcasting_datamodel import N_GSP
16
17
from nowcasting_datamodel .models import (
17
18
ForecastSQL ,
@@ -212,6 +213,7 @@ def get_all_gsp_ids_latest_forecast(
212
213
start_target_time : Optional [datetime ] = None ,
213
214
preload_children : Optional [bool ] = False ,
214
215
historic : bool = False ,
216
+ forecast_horizon_hours : Optional [int ] = None ,
215
217
) -> List [ForecastSQL ]:
216
218
"""
217
219
Read forecasts
@@ -235,6 +237,7 @@ def get_all_gsp_ids_latest_forecast(
235
237
preload_children = preload_children ,
236
238
historic = historic ,
237
239
gsp_ids = list (range (0 , N_GSP + 1 )),
240
+ forecast_horizon_hours = forecast_horizon_hours ,
238
241
)
239
242
240
243
@@ -244,6 +247,7 @@ def get_latest_forecast_for_gsps(
244
247
start_target_time : Optional [datetime ] = None ,
245
248
preload_children : Optional [bool ] = False ,
246
249
historic : bool = False ,
250
+ forecast_horizon_hours : Optional [int ] = None ,
247
251
gsp_ids : List [int ] = None ,
248
252
):
249
253
"""
@@ -256,6 +260,9 @@ def get_latest_forecast_for_gsps(
256
260
:param preload_children: Option to preload children. This is a speed up, if we need them.
257
261
:param historic: Option to load historic values or not
258
262
:param gsp_ids: Option to filter on gsps. If None, then only the lastest forecast is loaded.
263
+ :param forecast_horizon_hours: Optional filter on forecast horizon. For example
264
+ forecast_horizon_hours=2, means load the forecast than was made 2 hours before the target time.
265
+ Note this only works for non-historic data.
259
266
260
267
return: List of forecasts objects from database
261
268
@@ -293,6 +300,16 @@ def get_latest_forecast_for_gsps(
293
300
query = query , start_target_time = start_target_time , historic = historic
294
301
)
295
302
303
+ from sqlalchemy import text
304
+ if forecast_horizon_hours is not None :
305
+ assert historic is False , Exception (
306
+ "Loading a forecast horizon only works on non latest data."
307
+ )
308
+ query = query .join (ForecastValueSQL ).filter (
309
+ ForecastValueSQL .target_time - ForecastValueSQL .created_utc
310
+ >= text (f"interval '{ forecast_horizon_hours } hour'" )
311
+ )
312
+
296
313
query = query .join (LocationSQL )
297
314
298
315
# option to preload values, makes querying quicker
0 commit comments