Skip to content

Commit c489588

Browse files
committed
add horizon minutes
1 parent 0721112 commit c489588

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

nowcasting_datamodel/models/forecast.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,17 @@ def create_partition(
105105
return super().__new__(cls, clsname, bases, attrs)
106106

107107

108+
def default_horizon_minutes(context):
109+
columns = context.get_current_parameters()
110+
target_time = columns["target_time"]
111+
created_utc = columns["created_utc"]
112+
113+
if created_utc is None:
114+
created_utc = datetime.now(tz=target_time.tzinfo)
115+
delta = (target_time - created_utc).total_seconds() / 60.0 # convert to minutes
116+
return delta
117+
118+
108119
class ForecastValueSQLMixin(CreatedMixin):
109120
"""One Forecast of generation at one timestamp
110121
@@ -119,6 +130,17 @@ class ForecastValueSQLMixin(CreatedMixin):
119130
# Want to keep it as json so that we can store different properties for different forecasts
120131
properties = Column(MutableDict.as_mutable(JSON), nullable=True)
121132

133+
# we want to store the forecast horizon. This is the difference between target_time and created_utc.
134+
# By storing the value, and index, queries should be faster when looking for an N hour forecast.
135+
# I tried to use server_default = "CAST(EXTRACT(EPOCH FROM (target_time - created_utc))/60 as INT)"
136+
# but this does not work.
137+
horizon_minutes = Column(
138+
Integer,
139+
nullable=True,
140+
index=True,
141+
default=default_horizon_minutes,
142+
)
143+
122144
@declared_attr
123145
def forecast_id(self):
124146
"""Link with Forecast table"""

nowcasting_datamodel/read/read.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -519,11 +519,9 @@ def get_forecast_values(
519519
query = query.filter(model.created_utc <= created_utc_limit)
520520

521521
if forecast_horizon_minutes is not None:
522+
query = query.filter(model.horizon_minutes >= forecast_horizon_minutes)
523+
522524
# this seems to only work for postgres
523-
query = query.filter(
524-
model.target_time - model.created_utc
525-
>= text(f"interval '{forecast_horizon_minutes} minute'")
526-
)
527525
query = query.filter(
528526
model.created_utc - datetime.now(tz=timezone.utc)
529527
<= text(f"interval '{forecast_horizon_minutes} minute'")

0 commit comments

Comments
 (0)