-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
read.py
624 lines (458 loc) · 17.4 KB
/
read.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
""" Read database functions
1. Get the latest forecast
2. get the latest forecasts for all gsp ids
3. get all forecast values
"""
import logging
from datetime import datetime, timedelta, timezone
from typing import List, Optional
from sqlalchemy import desc
from sqlalchemy.orm import contains_eager, joinedload
from sqlalchemy.orm.session import Session
from nowcasting_datamodel import N_GSP
from nowcasting_datamodel.models import (
ForecastSQL,
ForecastValueLatestSQL,
ForecastValueSQL,
InputDataLastUpdatedSQL,
LocationSQL,
MLModelSQL,
PVSystemSQL,
StatusSQL,
national_gb_label,
)
logger = logging.getLogger(__name__)
def get_latest_input_data_last_updated(
session: Session,
) -> InputDataLastUpdatedSQL:
"""
Read last input data last updated
:param session: database session
return: Latest input data object
"""
# start main query
query = session.query(InputDataLastUpdatedSQL)
# this make the newest ones comes to the top
query = query.order_by(InputDataLastUpdatedSQL.created_utc.desc())
# get all results
input_data = query.first()
logger.debug("Found latest input data")
return input_data
def get_latest_status(
session: Session,
) -> StatusSQL:
"""
Read last input data last updated
:param session: database session
return: Latest input data object
"""
# start main query
query = session.query(StatusSQL)
# this make the newest ones comes to the top
query = query.order_by(StatusSQL.created_utc.desc())
# get all results
input_data = query.first()
logger.debug("Found latest status")
return input_data
def update_latest_input_data_last_updated(
session: Session, component: str, update_datetime: Optional[datetime] = None
):
"""
Update the table InputDataLastUpdatedSQL with a new valye
:param session:
:param component: This should be gsp, pv, nwp or satellite
:param update_datetime: the datetime is should be updated.
Default is None, so will be set to now
:return:
"""
# For the moment we load the latest, update it and save a new one.
# This may be a problem if these function is run at the same twice,
# but for the moment lets ignore this
if update_datetime is None:
update_datetime = datetime.now(tz=timezone.utc)
# get latest
latest_input_data_last_updated = get_latest_input_data_last_updated(session=session)
if latest_input_data_last_updated is None:
logger.warning("Could not find any 'InputDataLastUpdatedSQL' so will create one.")
now = datetime(1960, 1, 1, tzinfo=timezone.utc)
latest_input_data_last_updated = InputDataLastUpdatedSQL(
gsp=now, nwp=now, pv=now, satellite=now
)
# set new value
setattr(latest_input_data_last_updated, component, update_datetime)
# save to database
session.add(latest_input_data_last_updated)
session.commit()
def get_latest_forecast(
session: Session,
gsp_id: Optional[int] = None,
historic: bool = False,
start_target_time: Optional[datetime] = None,
) -> ForecastSQL:
"""
Read forecasts
:param session: database session
:param gsp_id: optional to gsp id, to filter query on
If None is given then all are returned.
:param session: database session
:param historic: Option to load historic values or not
:param start_target_time:
Filter: forecast values target time should be larger than this datetime
return: List of forecasts objects from database
"""
logger.debug(f"Getting latest forecast for gsp {gsp_id}")
if gsp_id is not None:
gsp_ids = [gsp_id]
else:
gsp_ids = None
forecasts = get_latest_forecast_for_gsps(
session=session, start_target_time=start_target_time, historic=historic, gsp_ids=gsp_ids
)
if forecasts is None:
return None
if len(forecasts) == 0:
return None
forecast = forecasts[0]
# sort list
logger.debug(
f"sorting 'forecast_values_latest' values. "
f"There are {len(forecast.forecast_values_latest)}"
)
if forecast.forecast_values_latest is not None:
forecast.forecast_values_latest = sorted(
forecast.forecast_values_latest, key=lambda d: d.target_time
)
logger.debug(f"Found forecasts for gsp id: {gsp_id} {historic=} {forecast=}")
return forecast
def sort_forecast_values(forecast: ForecastSQL):
"""Sort forecast values"""
if forecast.historic:
variable = "forecast_values_latest"
else:
variable = "forecast_values"
if getattr(forecast, variable) is not None:
setattr(
forecast, variable, sorted(getattr(forecast, variable), key=lambda d: d.target_time)
)
return forecast
def sort_all_forecast_value(forecasts: List[ForecastSQL]):
"""
Sorting all forecasts
This may be possible in the sql query, but so far have found it hard to do it.
Can't just add it to ORDER BY items, due to sub query.
:param forecasts: list of forecasts
:return: list of forecasts, but with sorted forecat values
"""
""" Sorting all forecasts"""
logger.debug("sorting 'forecast_values_latest' or 'forecast_values' values.")
for forecast in forecasts:
sort_forecast_values(forecast=forecast)
logger.debug("sorting done")
return forecasts
def get_all_gsp_ids_latest_forecast(
session: Session,
start_created_utc: Optional[datetime] = None,
start_target_time: Optional[datetime] = None,
preload_children: Optional[bool] = False,
historic: bool = False,
forecast_horizon_hours: Optional[int] = None,
) -> List[ForecastSQL]:
"""
Read forecasts
:param session: database session
:param start_created_utc: Filter: forecast creation time should be larger than this datetime
:param start_target_time:
Filter: forecast values target time should be larger than this datetime
:param preload_children: Option to preload children. This is a speed up, if we need them.
:param historic: Option to load historic values or not
return: List of forecasts objects from database
"""
logger.debug("Getting latest forecast for all gsps")
return get_latest_forecast_for_gsps(
session=session,
start_created_utc=start_created_utc,
start_target_time=start_target_time,
preload_children=preload_children,
historic=historic,
gsp_ids=list(range(0, N_GSP + 1)),
forecast_horizon_hours=forecast_horizon_hours,
)
def get_latest_forecast_for_gsps(
session: Session,
start_created_utc: Optional[datetime] = None,
start_target_time: Optional[datetime] = None,
preload_children: Optional[bool] = False,
historic: bool = False,
forecast_horizon_hours: Optional[int] = None,
gsp_ids: List[int] = None,
):
"""
Read forecasts
:param session: database session
:param start_created_utc: Filter: forecast creation time should be larger than this datetime
:param start_target_time:
Filter: forecast values target time should be larger than this datetime
:param preload_children: Option to preload children. This is a speed up, if we need them.
:param historic: Option to load historic values or not
:param gsp_ids: Option to filter on gsps. If None, then only the lastest forecast is loaded.
:param forecast_horizon_hours: Optional filter on forecast horizon. For example
forecast_horizon_hours=2, means load the forecast than was made 2 hours before the
target time. Note this only works for non-historic data.
return: List of forecasts objects from database
:param session:
:param start_created_utc:
:param start_target_time:
:param preload_children:
:param historic:
:param gsp_ids:
:return:
"""
order_by_cols = []
# start main query
query = session.query(ForecastSQL)
# filter on created_utc
if start_created_utc is not None:
query = query.filter(ForecastSQL.created_utc >= start_created_utc)
# join with location table and filter
if gsp_ids is not None:
if not historic:
# for historic they are already distinct
query = query.distinct(LocationSQL.gsp_id)
query = query.filter(LocationSQL.gsp_id.in_(gsp_ids))
order_by_cols.append(LocationSQL.gsp_id)
# filter on historic
query = query.filter(ForecastSQL.historic == historic)
# filter on target time
if start_target_time is not None:
query = filter_query_on_target_time(
query=query, start_target_time=start_target_time, historic=historic
)
from sqlalchemy import text
if forecast_horizon_hours is not None:
assert historic is False, Exception(
"Loading a forecast horizon only works on non latest data."
)
query = query.join(ForecastValueSQL).filter(
ForecastValueSQL.target_time - ForecastValueSQL.created_utc
>= text(f"interval '{forecast_horizon_hours} hour'")
)
query = query.join(LocationSQL)
# option to preload values, makes querying quicker
if preload_children:
query = query.options(joinedload(ForecastSQL.location))
query = query.options(joinedload(ForecastSQL.model))
query = query.options(joinedload(ForecastSQL.input_data_last_updated))
query = query.options(joinedload(ForecastSQL.forecast_values))
order_by_cols.append(desc(ForecastSQL.created_utc))
query = query.order_by(*order_by_cols)
forecasts = query.all()
logger.debug(f"Found {len(forecasts)} forecasts")
if len(forecasts) > 0:
logger.debug(f"The first forecast has {len(forecasts[0].forecast_values)} forecast_values")
forecasts = sort_all_forecast_value(forecasts)
return forecasts
def filter_query_on_target_time(query, start_target_time, historic: bool):
"""
Filter query on start target time
:param query: sql query
:param start_target_time: datetime, target times only included after this
:param historic: bool, if data is historic or latest
:return: query
"""
if historic:
forecast_value_model = ForecastValueLatestSQL
join_object = ForecastSQL.forecast_values_latest
else:
forecast_value_model = ForecastValueSQL
join_object = ForecastSQL.forecast_values
if start_target_time is not None:
logger.debug(f"Filtering '{start_target_time=}'")
query = query.join(join_object).filter(
forecast_value_model.target_time >= start_target_time
)
if historic:
query = query.options(contains_eager(join_object)).populate_existing()
query.order_by(join_object)
return query
def get_forecast_values(
session: Session,
gsp_id: Optional[int] = None,
start_datetime: Optional[datetime] = None,
only_return_latest: Optional[bool] = False,
) -> List[ForecastValueSQL]:
"""
Get forecast values
:param session: database session
:param gsp_id: optional to gsp id, to filter query on
If None is given then all are returned.
:param start_datetime: optional to filterer target_time by start_datetime
If None is given then all are returned.
:param only_return_latest: Optional to only return the latest forecast, not all of them.
Default is False
return: List of forecasts values objects from database
"""
# start main query
query = session.query(ForecastValueSQL)
if only_return_latest:
query = query.distinct(ForecastValueSQL.target_time)
if start_datetime is not None:
query = query.filter(ForecastValueSQL.target_time >= start_datetime)
# also filter on creation time, to speed up things
created_utc_filter = start_datetime - timedelta(days=1)
query = query.filter(ForecastValueSQL.created_utc >= created_utc_filter)
query = query.filter(ForecastSQL.created_utc >= created_utc_filter)
# filter on gsp_id
if gsp_id is not None:
query = query.join(ForecastSQL)
query = query.join(LocationSQL)
query = query.filter(LocationSQL.gsp_id == gsp_id)
# order by target time and created time desc
query = query.order_by(ForecastValueSQL.target_time, ForecastValueSQL.created_utc.desc())
# get all results
forecasts = query.all()
return forecasts
def get_latest_national_forecast(
session: Session,
) -> ForecastSQL:
"""
Get forecast values
:param session: database session
:param gsp_id: optional to gsp id, to filter query on
If None is given then all are returned.
return: List of forecasts values objects from database
"""
# start main query
query = session.query(ForecastSQL)
# filter on gsp_id
query = query.join(LocationSQL)
query = query.filter(LocationSQL.label == national_gb_label)
# order, so latest is at the top
query = query.order_by(ForecastSQL.created_utc.desc())
# get first results
forecast = query.first()
return forecast
def get_latest_forecast_created_utc(session: Session, gsp_id: Optional[int] = None) -> datetime:
"""
Get the latest forecast created utc value. Can choose for different gsps
:param session: database session
:param gsp_id: gsp id to filter query on
:return:
"""
# start main query
query = session.query(ForecastSQL.created_utc)
# filter on gsp_id
if gsp_id is not None:
query = query.join(LocationSQL)
query = query.filter(LocationSQL.gsp_id == gsp_id)
# order, so latest is at the top
query = query.order_by(ForecastSQL.created_utc.desc())
# get first results
created_utc = query.first()
assert len(created_utc) == 1
return created_utc[0]
def get_location(session: Session, gsp_id: int, label: Optional[str] = None) -> LocationSQL:
"""
Get location object from gsp id
:param session: database session
:param gsp_id: gsp id of the location
:param label: label of the location
return: List of forecasts values objects from database
"""
# start main query
query = session.query(LocationSQL)
# filter on gsp_id
query = query.filter(LocationSQL.gsp_id == gsp_id)
if label is not None:
query = query.filter(LocationSQL.label == label)
# get all results
locations = query.all()
if len(locations) == 0:
logger.debug(f"Location for gsp_id {gsp_id} does not exist so going to add it")
if label is None:
label = f"GSP_{gsp_id}"
location = LocationSQL(gsp_id=gsp_id, label=label)
if gsp_id == 0:
location.label = national_gb_label
session.add(location)
session.commit()
else:
location = locations[0]
return location
def get_all_locations(session: Session, gsp_ids: List[int] = None) -> List[LocationSQL]:
"""
Get all location object from gsp id
:param session: database session
:param gsp_ids: list of gsp id of the location
return: List of GSP locations
"""
# start main query
query = session.query(LocationSQL)
query = query.distinct(LocationSQL.gsp_id)
get_national = True
if gsp_ids is not None:
# see if gsp_id==0 is in list
# if gsp id 0 is in list, then get national gsp location
# if gsp id 0 is not in list, then don't get national gsp location
if 0 in gsp_ids:
get_national = True
gsp_ids.remove(0)
else:
get_national = False
# filter on gsp_id
query = query.filter(LocationSQL.gsp_id.in_(gsp_ids))
else:
query = query.filter(LocationSQL.gsp_id != 0)
# make sure gsp is not null
query = query.filter(LocationSQL.gsp_id.isnot(None))
# query
query = query.order_by(LocationSQL.gsp_id)
# get all results
locations = query.all()
if get_national:
nation = get_location(session=session, gsp_id=0, label=national_gb_label)
locations = [nation] + locations
return locations
def get_model(session: Session, name: str, version: str) -> MLModelSQL:
"""
Get model object from name and version
:param session: database session
:param name: name of the model
:param version: version of the model
return: Model object
"""
# start main query
query = session.query(MLModelSQL)
# filter on gsp_id
query = query.filter(MLModelSQL.name == name)
query = query.filter(MLModelSQL.version == version)
# get all results
models = query.all()
if len(models) == 0:
logger.debug(
f"Model for name {name} and version {version }does not exist so going to add it"
)
model = MLModelSQL(name=name, version=version)
session.add(model)
session.commit()
else:
model = models[0]
return model
def get_pv_system(
session: Session, pv_system_id: int, provider: Optional[str] = "pvoutput.org"
) -> PVSystemSQL:
"""
Get model object from name and version
:param session: database session
:param pv_system_id: pv system id
:param provider: the pv provider, defaulted to pvoutput.org
return: PVSystem object
"""
# start main query
query = session.query(PVSystemSQL)
# filter on pv_system_id and provider
query = query.filter(PVSystemSQL.pv_system_id == pv_system_id)
query = query.filter(PVSystemSQL.provider == provider)
# get all results
pv_systems = query.all()
pv_system = pv_systems[0]
return pv_system