-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
1710 lines (1411 loc) · 66.5 KB
/
utils.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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from dotenv import load_dotenv
import tempfile
import pretty_errors
import os
import mlflow
import pandas as pd
import yaml
import darts
from pandas.tseries.frequencies import to_offset
from math import ceil
cur_dir = os.path.dirname(os.path.realpath(__file__))
import numpy as np
load_dotenv()
from tqdm import tqdm
import logging
from exceptions import MandatoryArgNotSet, NotValidConfig, EmptySeries, DifferentFrequenciesMultipleTS
import json
from urllib3.exceptions import InsecureRequestWarning
from urllib3 import disable_warnings
disable_warnings(InsecureRequestWarning)
import requests
from datetime import date
import pvlib
import pandas as pd
import matplotlib.pyplot as plt
from pvlib.pvsystem import PVSystem
from pvlib.location import Location
from pvlib.modelchain import ModelChain
from pvlib.temperature import TEMPERATURE_MODEL_PARAMETERS
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
import plotly.io as pi
from darts.utils.timeseries_generation import datetime_attribute_timeseries
from darts.utils.timeseries_generation import holidays_timeseries
import math
from datetime import timezone
from darts.dataprocessing.transformers import MissingValuesFiller
import tempfile
import holidays
from pytz import timezone
import pytz
from datetime import datetime
class ConfigParser:
def __init__(self, config_file=f'{cur_dir}/config.yml', config_string=None):
import yaml
try:
with open(config_file, "r") as ymlfile:
self.config = yaml.safe_load(ymlfile)
if config_string != None:
assert config_string in self.config['hyperparameters']
except:
try:
assert "{" in config_string
self.config = yaml.safe_load(config_string)
except:
raise NotValidConfig()
def read_hyperparameters(self, hyperparams_entrypoint=""):
try:
return self.config['hyperparameters'][hyperparams_entrypoint]
except:
return self.config
def read_entrypoints(self):
return self.config['hyperparameters']
def download_file_from_s3_bucket(object_name, dst_filename, dst_dir=None, bucketName='mlflow-bucket'):
import boto3
import tempfile
if dst_dir is None:
dst_dir = tempfile.mkdtemp()
else:
os.makedirs(dst_dir, exist_ok=True)
os.makedirs(dst_dir, exist_ok=True)
s3_resource = boto3.resource(
's3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
bucket = s3_resource.Bucket(bucketName)
local_path = os.path.join(dst_dir, dst_filename)
bucket.download_file(object_name, local_path)
return local_path
def get_pv_forecast(ts_id, start=None, end=None, inference=False, kW=185, use_saved=False, format="long"):
# start = ts[0].index[0] - pd.Timedelta("1d"),
# end = ts[0].index[-1] + pd.Timedelta("1d"),
#TODO Add parameters to mlflow
#TODO Add visualization
if use_saved:
covs_list, cov_id_l, cov_ts_id_l = multiple_ts_file_to_dfs("/new_vol_300/opt/energy-forecasting-theo/uc7-data-ops/pvlib/UC6_covs_final.csv", True, "60", format=format)
covs_list = covs_list[0]
covs_list_final = [covs_list]
#[['diffuse_radiation_W4 positive_active', 'direct_normal_irradiance_W4 positive_active', 'shortwave_radiation_W4 positive_active', 'temperature_W4 positive_active', 'windspeed_10m_W4 positive_active']]
#temp_air, wind_speed, ghi, dhi, dni
covs_list_final = []
covs_list_final.append(covs_list[3])
covs_list_final.append(covs_list[4])
covs_list_final.append(covs_list[2])
covs_list_final.append(covs_list[0])
covs_list_final.append(covs_list[1])
covs_list_final = [covs_list_final]
print(f"Using covs of {cov_id_l[0][0]}")
return darts.TimeSeries.from_dataframe(pvlib_forecast(covs_weather=covs_list_final[0], start=start, end=end, kW=kW))
else:
covs_list, cov_id_l, cov_ts_id_l = add_weather_covariates(start-pd.Timedelta("1d"),
end+pd.Timedelta("1d"),
[],
[],
[],
[ts_id],
fields=["temperature","windspeed_10m","shortwave_radiation","diffuse_radiation","direct_normal_irradiance"],
inference=inference)
covs_list_final = []
for ts, id_t in zip(covs_list, cov_id_l):
new = []
for comp, id in zip(ts, id_t):
temp = impute(comp,
holidays.IT(),
max_thr = 2000,
a = 0.3,
wncutoff = 0.000694,
ycutoff = 3,
ydcutoff = 30,
resolution = "60min",
debug = False,
name = id,
l_interpolation = False,
cut_date_val = "20231022",
min_non_nan_interval = -1)
new.append(temp)
covs_list_final.append(new)
print(f"Using covs of {ts_id[0]}")
return darts.TimeSeries.from_dataframe(pvlib_forecast(covs_weather=covs_list_final[0], start=start, end=end, kW=kW))
def pvlib_forecast(covs_weather=[], start=None, end=None, kW=185):
#init params
latitude=42.567055
longitude=12.607027
surface_tilt=0
surface_azimuth=180
modules_per_string=25
strings_per_inverter=215
altitude=0
location=Location(latitude, longitude, altitude=altitude)
#make weather
weather = covs_weather[3].copy()
weather.columns = ["dhi"]
weather["dni"] = covs_weather[4]
weather["ghi"] = covs_weather[2]
weather["temp_air"] = covs_weather[0]
weather["wind_speed"] = covs_weather[1]
if start:
weather = weather.loc[(weather.index >= start)]
if end:
weather = weather.loc[(weather.index <= end)]
#initialize system
module_name = 'Canadian_Solar_CS5P_220M___2009_'
inverter_name = 'ABB__ULTRA_1100_TL_OUTD_2_US_690_x_y_z__690V_' #'Power_Electronics__FS3000CU15__690V_' #'ABB__PVS980_58_2000kVA_K__660V_' #'ABB__ULTRA_1100_TL_OUTD_2_US_690_x_y_z__690V_'
sandia_modules = pvlib.pvsystem.retrieve_sam('SandiaMod')
sapm_inverters = pvlib.pvsystem.retrieve_sam('cecinverter')
module = sandia_modules[module_name]
inverter = sapm_inverters[inverter_name]
temperature_model_parameters = {'a': -2.4, 'b': -0.0455, 'deltaT': 8}
system=PVSystem(surface_tilt=surface_tilt, surface_azimuth=surface_azimuth,
module_parameters=module, inverter_parameters=inverter,
temperature_model_parameters=temperature_model_parameters,
modules_per_string=modules_per_string, strings_per_inverter=strings_per_inverter
)
modelchain=ModelChain(system, location)
modelchain.run_model(weather)
solar_data=modelchain.results.ac
solar_data=pd.DataFrame(solar_data, columns=(['Value']))
# Convert to our kW
solar_data = solar_data * kW / 1000000.0
return solar_data
def load_yaml_as_dict(filepath):
import yaml
with open(filepath, 'r') as stream:
try:
parsed_yaml = yaml.safe_load(stream)
return parsed_yaml
except yaml.YAMLError as exc:
print(exc)
return
def save_dict_as_yaml(filepath, data):
with open(filepath, 'w') as savefile:
yaml.dump(data, savefile, default_flow_style=False)
def load_local_pkl_as_object(local_path):
import pickle
pkl_object = pickle.load(open(local_path, "rb"))
return pkl_object
def download_online_file(client, url, dst_filename=None, dst_dir=None):
import sys
import tempfile
import requests
print("Donwloading_online_file")
print(url)
if dst_dir is None:
dst_dir = tempfile.mkdtemp()
else:
os.makedirs(dst_dir, exist_ok=True)
if dst_filename is None:
dst_filename = url.split('/')[-1]
filepath = os.path.join(dst_dir, dst_filename)
url = url.split('mlflow-bucket')[-1]
client.fget_object("mlflow-bucket", url, filepath)
# print(req)
# if req.status_code != 200:
# raise Exception(f"\nResponse is not 200\nProblem downloading: {url}")
# sys.exit()
# url_content = req.content
# filepath = os.path.join(dst_dir, dst_filename)
# file = open(filepath, 'wb')
# file.write(url_content)
# file.close()
return filepath
def download_mlflow_file(client, url, dst_dir=None):
S3_ENDPOINT_URL = os.environ.get('MLFLOW_S3_ENDPOINT_URL')
if dst_dir is None:
dst_dir = tempfile.mkdtemp()
else:
os.makedirs(dst_dir, exist_ok=True)
if url.startswith('s3://mlflow-bucket/'):
url = url.replace("s3:/", S3_ENDPOINT_URL)
local_path = download_online_file(
client, url, dst_dir=dst_dir)
elif url.startswith('runs:/'):
mlflow_client = mlflow.tracking.MlflowClient()
run_id = url.split('/')[1]
mlflow_path = '/'.join(url.split('/')[3:])
local_path = mlflow_client.download_artifacts(run_id, mlflow_path, dst_dir)
elif url.startswith('http://') or url.startswith('https://'):
local_path = download_online_file(client, url, dst_dir=dst_dir)
print("\nLocal path:", local_path)
return local_path
def load_pkl_model_from_server(client, model_uri):
print("\nLoading remote PKL model...")
model_path = download_mlflow_file(client, f'{model_uri}/_model.pkl')
print(model_path)
best_model = load_local_pkl_as_object(model_path)
return best_model
def load_local_pl_model(model_root_dir):
from darts.models.forecasting.lgbm import LightGBMModel
from darts.models.forecasting.random_forest import RandomForest
from darts.models import RNNModel, BlockRNNModel, NBEATSModel, TFTModel, NaiveDrift, NaiveSeasonal, TCNModel, NHiTSModel, TransformerModel
print("\nLoading local PL model...")
model_info_dict = load_yaml_as_dict(
os.path.join(model_root_dir, 'model_info.yml'))
darts_forecasting_model = model_info_dict[
"darts_forecasting_model"]
model = eval(darts_forecasting_model)
# model_root_dir = model_root_dir.replace('/', os.path.sep)
print(f"Loading model from local directory:{model_root_dir}")
best_model = model.load_from_checkpoint(model_root_dir, best=True)
return best_model
def load_pl_model_from_server(model_root_dir):
import tempfile
print("\nLoading remote PL model...")
mlflow_client = mlflow.tracking.MlflowClient()
print(model_root_dir)
model_run_id = model_root_dir.split("/")[5]
mlflow_relative_model_root_dir = model_root_dir.split("/artifacts/")[1]
local_dir = tempfile.mkdtemp()
mlflow_client.download_artifacts(
run_id=model_run_id, path=mlflow_relative_model_root_dir, dst_path=local_dir)
best_model = load_local_pl_model(os.path.join(
local_dir, mlflow_relative_model_root_dir))
return best_model
def load_model(client, model_root_dir, mode="remote"):
# Get model type as tag of model's run
import mlflow
print(model_root_dir)
if mode == 'remote':
mlflow_client = mlflow.tracking.MlflowClient()
run_id = model_root_dir.split('/')[-1]
model_run = mlflow_client.get_run(run_id)
model_type = model_run.data.tags.get('model_type')
else:
if "_model.pth.tar" in os.listdir(model_root_dir):
model_type = 'pl'
else:
model_type = "pkl"
# Load accordingly
if mode == "remote" and model_type == "pl":
model = load_pl_model_from_server(model_root_dir=model_root_dir)
#TODO Check if working with pl models
elif mode == "remote" and model_type == "pkl":
model = load_pkl_model_from_server(client, model_root_dir)
elif mode == "local" and model_type == 'pl':
model = load_local_pl_model(model_root_dir=model_root_dir)
else:
print("\nLoading local PKL model...")
# pkl loads the exact model file so:
model_uri = os.path.join(model_root_dir, '_model.pkl')
model = load_local_pkl_as_object(model_uri)
return model
def load_scaler(scaler_uri=None, mode="remote"):
import tempfile
if scaler_uri is None:
print("\nNo scaler loaded.")
return None
if mode == "remote":
run_id = scaler_uri.split("/")[-2]
mlflow_filepath = scaler_uri.split("/artifacts/")[1]
mlflow_client = mlflow.tracking.MlflowClient()
local_dir = tempfile.mkdtemp()
print("Scaler: ", scaler_uri)
print("Run: ", run_id)
mlflow_client.download_artifacts(
run_id=run_id,
path=mlflow_filepath,
dst_path=local_dir
)
# scaler_path = download_online_file(
# scaler_uri, "scaler.pkl") if mode == 'remote' else scaler_uri
scaler = load_local_pkl_as_object(
os.path.join(local_dir, mlflow_filepath))
else:
scaler = load_local_pkl_as_object(scaler_uri)
return scaler
def load_ts_id(load_ts_id_uri=None, mode="remote"):
import tempfile
if load_ts_id_uri is None:
print("\nNo ts id list loaded.")
return None
if mode == "remote":
run_id = load_ts_id_uri.split("/")[-2]
mlflow_filepath = load_ts_id_uri.split("/artifacts/")[1]
mlflow_client = mlflow.tracking.MlflowClient()
local_dir = tempfile.mkdtemp()
print("ts id list: ", load_ts_id_uri)
print("Run: ", run_id)
mlflow_client.download_artifacts(
run_id=run_id,
path=mlflow_filepath,
dst_path=local_dir
)
ts_id_l = load_local_pkl_as_object(
os.path.join(local_dir, mlflow_filepath))
else:
ts_id_l = load_local_pkl_as_object(load_ts_id_uri)
return ts_id_l
def truth_checker(argument):
""" Returns True if string has specific truth values else False"""
return argument.lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'on']
def none_checker(argument):
""" Returns True if string has specific truth values else False"""
if argument is None:
return None
if argument.lower() in ['none', 'nope', 'nan', 'na', 'null', 'nope', 'n/a', 'mlflow_artifact_uri']:
return None
else:
return argument
def load_artifacts(run_id, src_path, dst_path=None):
import tempfile
import os
import mlflow
mlflow_client = mlflow.tracking.MlflowClient()
if dst_path is None:
dst_dir = tempfile.mkdtemp()
else:
dst_dir = os.path.sep.join(dst_path.split("/")[-1])
os.makedirs(dst_dir, exist_ok=True)
fname = src_path.split("/")[-1]
print(src_path, dst_dir)
return mlflow_client.download_artifacts(
run_id=run_id,
path=src_path,
dst_path=dst_dir
)
# return mlflow.artifacts.download_artifacts(artifact_path=src_path, dst_path="/".join([dst_dir, fname]), run_id=run_id)
def load_local_model_as_torch(local_path):
import torch
device = torch.device(
'cuda') if torch.cuda.is_available() else torch.device('cpu')
model = torch.load(local_path, map_location=device)
model.device = device
return model
def isholiday(x, holiday_list):
if x in holiday_list:
return True
return False
def isweekend(x):
if x == 6 or x == 0:
return True
return False
def create_calendar(timeseries, timestep_minutes, holiday_list, local_timezone):
calendar = pd.DataFrame(
timeseries.index.tolist(),
columns=['datetime']
)
calendar['year'] = calendar['datetime'].apply(lambda x: x.year)
calendar['month'] = calendar['datetime'].apply(lambda x: x.month)
calendar['yearweek'] = calendar['datetime'].apply(
lambda x: int(x.strftime("%V")) - 1)
calendar['day'] = calendar['datetime'].apply(lambda x: x.day)
calendar['hour'] = calendar['datetime'].apply(lambda x: x.hour)
calendar['minute'] = calendar['datetime'].apply(lambda x: x.minute)
calendar['second'] = calendar['datetime'].apply(lambda x: x.second)
calendar['weekday'] = calendar['datetime'].apply(lambda x: x.weekday())
calendar['dayofyear'] = calendar['datetime'].apply(lambda x: x.day_of_year)
calendar['monthday'] = calendar['datetime'].apply(
lambda x: int(x.strftime("%d")) - 1)
calendar['weekend'] = calendar['weekday'].apply(lambda x: isweekend(x))
calendar['yearday'] = calendar['datetime'].apply(
lambda x: int(x.strftime("%j")) - 1)
# first convert to utc and then to timestamp
calendar['timestamp'] = calendar['datetime'].apply(lambda x: local_timezone.localize(
x).replace(tzinfo=pytz.utc).timestamp()).astype(int)
# national_holidays = Province(name="valladolid").national_holidays()
# regional_holidays = Province(name="valladolid").regional_holidays()
# local_holidays = Province(name="valladolid").local_holidays()
# holiday_list = national_holidays + regional_holidays + local_holidays
calendar['holiday'] = calendar['datetime'].apply(
lambda x: isholiday(x.date(), holiday_list))
WNweekday = calendar['datetime'].apply(
lambda x: x.weekday() if not isholiday(x.date(), holiday_list) else 5 if x.weekday() == 4 else 6)
calendar['WN'] = WNweekday + calendar['hour']/24 + calendar['minute']/(24*60)
calendar['DN'] = calendar['hour'] + calendar['minute']/(60)
return calendar
def add_cyclical_time_features(calendar):
"""
The function below is useful to create sinusoidal transformations of time features.
This article explains why 2 transformations are necessary:
https://ianlondon.github.io/blog/encoding-cyclical-features-24hour-time/
"""
calendar['month_sin'] = calendar['month'].apply(
lambda x: math.sin(2*math.pi/12*(x-1)))
calendar['weekday_sin'] = calendar['weekday'].apply(
lambda x: math.sin(2*math.pi/7*(x)))
calendar['monthday_sin'] = calendar['monthday'].apply(
lambda x: math.sin(2*math.pi/30*(x)))
calendar['yearday_sin'] = calendar['yearday'].apply(
lambda x: math.sin(2*math.pi/365*(x)))
calendar['hour_sin'] = calendar['hour'].apply(
lambda x: math.sin(2*math.pi/24*(x)))
calendar['yearday_sin'] = calendar['yearday'].apply(
lambda x: math.sin(2*math.pi/52.1428*(x)))
calendar['month_cos'] = calendar['month'].apply(
lambda x: math.cos(2*math.pi/12*(x-1)))
calendar['weekday_cos'] = calendar['weekday'].apply(
lambda x: math.cos(2*math.pi/7*(x)))
calendar['monthday_cos'] = calendar['monthday'].apply(
lambda x: math.cos(2*math.pi/30*(x)))
calendar['yearday_cos'] = calendar['yearday'].apply(
lambda x: math.cos(2*math.pi/365*(x)))
calendar['hour_cos'] = calendar['hour'].apply(
lambda x: math.cos(2*math.pi/24*(x)))
calendar['yearday_cos'] = calendar['yearday'].apply(
lambda x: math.cos(2*math.pi/52.1428*(x)))
plt.figure(figsize=(15, 8))
plt.subplot(2, 5, 1)
calendar['month_sin'][:50000].plot()
plt.subplot(2, 5, 2)
calendar['weekday_sin'][:1000].plot()
plt.subplot(2, 5, 3)
calendar['monthday_sin'][:1000].plot()
plt.subplot(2, 5, 4)
calendar['yearday_sin'][:1000000].plot()
plt.subplot(2, 5, 5)
calendar['hour_sin'][:96].plot()
plt.subplot(2, 5, 6)
calendar['month_cos'][:50000].plot()
plt.subplot(2, 5, 7)
calendar['weekday_cos'][:1000].plot()
plt.subplot(2, 5, 8)
calendar['monthday_cos'][:1000].plot()
plt.subplot(2, 5, 9)
calendar['yearday_cos'][:1000000].plot()
plt.subplot(2, 5, 10)
calendar['hour_cos'][:96].plot()
return calendar
def get_time_covariates(series, country_code='PT', id_name='0'):
""" Do it the darts way"""
if isinstance(series, pd.Series):
series = darts.TimeSeries.from_series(series)
year = datetime_attribute_timeseries(
time_index=series, attribute='year')
month = datetime_attribute_timeseries(
time_index=series, attribute='month', cyclic=True)
dayofyear = datetime_attribute_timeseries(
time_index=series, attribute='dayofyear', cyclic=True)
hour = datetime_attribute_timeseries(
time_index=series, attribute='hour', cyclic=True)
# minute = datetime_attribute_timeseries(
# time_index=series, attribute='minute', cyclic=True)
dayofweek = datetime_attribute_timeseries(
time_index=series, attribute='dayofweek', cyclic=True)
weekofyear = datetime_attribute_timeseries(
time_index=series, attribute='weekofyear', cyclic=True)
# dayofyear = datetime_attribute_timeseries(
# time_index=series, attribute='dayofyear')
holidays = holidays_timeseries(
time_index=series.time_index, country_code=country_code)
# weekofyear = darts.TimeSeries.from_series(
# series.time_index.isocalendar().week)
ts_list_covariates = year.stack(month). \
stack(dayofyear). \
stack(hour). \
stack(dayofweek). \
stack(weekofyear). \
stack(holidays)
ts_list_covariates = [ts_list_covariates.univariate_component(i).pd_dataframe() for i in range(ts_list_covariates.n_components)]
id_l_covariates = ["year",
"month_sin",
"month_cos",
"dayofyear_sin",
"dayofyear_cos",
"hour_sin",
"hour_cos",
"dayofweek_sin",
"dayofweek_cos",
"weekofyear_sin",
"weekofyear_cos",
"holidays"]
ts_id_l_covariates = [id_name for _ in range(12)]
return ts_list_covariates, id_l_covariates, ts_id_l_covariates
def impute(ts: pd.DataFrame,
holidays,
max_thr: int = -1,
a: float = 0.3,
wncutoff: float = 0.000694,
ycutoff: int = 3,
ydcutoff: int = 30,
resolution: str = "15min",
debug: bool = False,
name: str = "PT",
l_interpolation: bool = False,
cut_date_val: str = "20221208",
min_non_nan_interval: int = 24):
"""
Reads the input dataframe and imputes the timeseries using a weighted average of historical data
and simple interpolation. The weights of each method are exponentially dependent on the distance
to the nearest non NaN value. More specifficaly, with increasing distance, the weight of
simple interpolation decreases, and the weight of the historical data increases. If there is
a consecutive subseries of NaNs longer than max_thr, then it is not imputed and returned with NaN
values.
Parameters
----------
ts
The pandas.DataFrame to be processed
holidays
The holidays of the country this timeseries belongs to
max_thr
If there is a consecutive subseries of NaNs longer than max_thr,
then it is not imputed and returned with NaN values. If -1, every
value will be imputed regardless of how long the consecutive
subseries of NaNs it belongs to is
a
The weight that shows how quickly simple interpolation's weight decreases as
the distacne to the nearest non NaN value increases
wncutoff
Historical data will only take into account dates that have at most wncutoff distance
from the current null value's WN(Week Number)
ycutoff
Historical data will only take into account dates that have at most ycutoff distance
from the current null value's year
ydcutoff
Historical data will only take into account dates that have at most ydcutoff distance
from the current null value's yearday
resolution
The resolution of the dataset
debug
If true it will print helpfull intermediate results
l_interpolation
Whether to only use linear interpolation
cut_date_val
All dates before cut_date_val that have nan values are imputed using historical data
from dates which are also before cut_date_val. Datetimes after cut_date_val are not affected
by this
min_non_nan_interval
If after imputation there exist continuous intervals of non nan values that are smaller than min_non_nan_interval
hours, these intervals are all replaced by nan values
Returns
-------
pandas.DataFrame
The imputed dataframe
"""
if max_thr == -1: max_thr = len(ts)
if l_interpolation:
imputed_values = ts[ts[ts.columns[0]].isnull()]
#null_dates: Series with all null dates to be imputed
null_dates = imputed_values.index
if debug:
for date in null_dates:
print(date)
#isnull: An array which stores whether each value is null or not
isnull = ts[ts.columns[0]].isnull().values
#d: List with distances to the nearest non null value
d = [len(null_dates) for _ in range(len(null_dates))]
#leave_nan: List with all the values to be left NaN because there are
#more that max_thr consecutive ones
leave_nan = [False for _ in range(len(null_dates))]
#Calculating the distances to the nearest non null value that is earlier in the series
count = 1
for i in range(len(null_dates)):
d[i] = min(d[i], count)
if i < len(null_dates) - 1:
if null_dates[i+1] == null_dates[i] + pd.offsets.DateOffset(seconds=to_seconds(resolution)):
count += 1
else:
count = 1
#Calculating the distances to the nearest non null value that is later in the series
count = 1
for i in range(len(null_dates)-1, -1, -1):
d[i] = min(d[i], count)
if i > 0:
if null_dates[i-1] == null_dates[i] - pd.offsets.DateOffset(seconds=to_seconds(resolution)):
count += 1
else:
count = 1
#If d[i] >= max_thr // 2, that means we have a consecutive subseries of NaNs longer than max_thr.
#We mark this subseries so that it does not get imputed
for i in range(len(null_dates)):
if d[i] == max_thr // 2:
for ii in range(max(0, i - max_thr // 2 + 1), min(i + max_thr // 2, len(null_dates))):
leave_nan[ii] = True
elif d[i] > max_thr // 2:
leave_nan[i] = True
#using max_thr for linear interp. for UC7
res = ts.interpolate(inplace=False)
null_zip = [(i, null_date) for (i, null_date) in enumerate(null_dates) if leave_nan[i]]
for i, null_date in tqdm(null_zip):
res.loc[null_date] = np.NaN
imputed_values = res[ts[ts.columns[0]].isnull()].copy()
else:
#Returning calendar of the country ts belongs to
calendar = create_calendar(ts, resolution, holidays, timezone("UTC"))
calendar.index = calendar["datetime"]
imputed_values = ts[ts[ts.columns[0]].isnull()].copy()
#null_dates: Series with all null dates to be imputed
null_dates = imputed_values.index
if debug:
for date in null_dates:
print(date)
#isnull: An array which stores whether each value is null or not
isnull = ts[ts.columns[0]].isnull().values
#d: List with distances to the nearest non null value
d = [len(null_dates) for _ in range(len(null_dates))]
#leave_nan: List with all the values to be left NaN because there are
#more that max_thr consecutive ones
leave_nan = [False for _ in range(len(null_dates))]
#Calculating the distances to the nearest non null value that is earlier in the series
count = 1
for i in range(len(null_dates)):
d[i] = min(d[i], count)
if i < len(null_dates) - 1:
if null_dates[i+1] == null_dates[i] + pd.offsets.DateOffset(seconds=to_seconds(resolution)):
count += 1
else:
count = 1
#Calculating the distances to the nearest non null value that is later in the series
count = 1
for i in range(len(null_dates)-1, -1, -1):
d[i] = min(d[i], count)
if i > 0:
if null_dates[i-1] == null_dates[i] - pd.offsets.DateOffset(seconds=to_seconds(resolution)):
count += 1
else:
count = 1
#If d[i] >= max_thr // 2, that means we have a consecutive subseries of NaNs longer than max_thr.
#We mark this subseries so that it does not get imputed
for i in range(len(null_dates)):
if d[i] == max_thr // 2:
for ii in range(max(0, i - max_thr // 2 + 1), min(i + max_thr // 2, len(null_dates))):
leave_nan[ii] = True
elif d[i] > max_thr // 2:
leave_nan[i] = True
#This is the interpolated version of the time series
ts_interpolatied = ts.interpolate(inplace=False)
#We copy the time series so that we don't change it while iterating
res = ts.copy()
null_zip = [(i, null_date) for (i, null_date) in enumerate(null_dates) if not leave_nan[i]]
for i, null_date in tqdm(null_zip):
#WN: Day of the week + hour/24 + minute/(24*60). Holidays are handled as
#either Saturdays(if the real day is a Friday) or Sundays(in every other case)
currWN = calendar.loc[null_date]['WN']
currYN = calendar.loc[null_date]['yearday']
currY = calendar.loc[null_date]['year']
currDayOfYear = calendar.loc[null_date]['dayofyear']
currH = calendar.loc[null_date]['hour']
currDN = calendar.loc[null_date]['DN']
#weight of interpolated series, decreases as distance to nearest known value increases
w = np.e ** (-a * d[i])
#Historical value is calculated as the mean of values that have at most wncutoff distance to the current null value's
#WN, ycutoff distance to its year, and ydcutoff distance to its yearday
#All dates before cut_date_val that have nan values are imputed using historical data
#from dates which are also before cut_date_val
dcutoff = 6
while True:
if null_date < pd.Timestamp(cut_date_val):
historical = ts[(~isnull) & (ts[ts.columns[0]].index < pd.Timestamp(cut_date_val)) &\
((((calendar['yearday'] - currYN) < 0) &\
((-calendar['yearday'] + currYN) < dcutoff)) &\
((calendar['DN'] - currDN < to_seconds(resolution)/(120*60)) & (- calendar['DN'] + currDN < to_seconds(resolution)/(120*60))))][ts.columns[0]]
#Dates after cut_date_val are not affected by cut_date_val
else:
historical = ts[(~isnull) & ((((calendar['yearday'] - currYN) < 0) &\
((-calendar['yearday'] + currYN) < dcutoff)) &\
((calendar['DN'] - currDN < to_seconds(resolution)/(120*60)) & (- calendar['DN'] + currDN < to_seconds(resolution)/(120*60))))][ts.columns[0]]
if historical.empty:
dcutoff += 1
if dcutoff>20:
break
continue
historical = historical.mean()
#imputed value is calculated as a wheighted average of the histrorical value and the value from intrepolation
res.loc[null_date] = w * ts_interpolatied.loc[null_date] + (1 - w) * historical
imputed_values.loc[null_date] = res.loc[null_date]
if debug:
print(res.loc[null_date])
break
non_nan_intervals_to_nan = {}
if min_non_nan_interval != -1:
#UC7 Do that for l_interpolation also
#If after imputation there exist continuous intervals of non nan values in the train set that are smaller
#than min_non_nan_interval time steps, these intervals are all replaced by nan values
not_nan_values = res[(~res[res.columns[0]].isnull())]
not_nan_dates = not_nan_values.index
prev = not_nan_dates[0]
start = prev
for not_nan_day in not_nan_dates[1:]:
if (not_nan_day - prev)!= pd.Timedelta(resolution):
if prev - start < pd.Timedelta(to_seconds(resolution) * min_non_nan_interval, "sec"):
print(f"Non Nan interval from {start} to {prev} is smaller than {min_non_nan_interval} time steps. Making this also Nan")
for date in pd.date_range(start=start, end=prev, freq=resolution):
non_nan_intervals_to_nan[date] = res.loc[date].values[0]
res.loc[date] = pd.NA
imputed_values.loc[date] = pd.NA
start = not_nan_day
prev = not_nan_day
if prev - start < pd.Timedelta(to_seconds(resolution) * min_non_nan_interval, "sec"):
for date in pd.date_range(start=start, end=prev, freq=resolution):
non_nan_intervals_to_nan[date] = res.loc[date].values[0]
res.loc[date] = pd.NA
imputed_values.loc[date] = pd.NA
imputed_values = imputed_values[(~imputed_values[imputed_values.columns[0]].isnull())]
imputed_values.to_csv("inputed.csv")
non_nan_intervals_to_nan = pd.DataFrame.from_dict(non_nan_intervals_to_nan, columns=[res.columns[0]], orient='index')
non_nan_intervals_to_nan.index.name = "Datetime"
non_nan_intervals_to_nan.to_csv("non_nan_intervals_to_nan.csv")
res.to_csv("res.csv")
if not res.empty:
full_res = res.asfreq(resolution)
else:
full_res = res.copy()
if not imputed_values.empty:
full_imputed_values = imputed_values.asfreq(resolution)
else:
full_imputed_values = imputed_values.copy()
if not non_nan_intervals_to_nan.empty:
full_non_nan_intervals_to_nan = non_nan_intervals_to_nan.asfreq(resolution)
else:
full_non_nan_intervals_to_nan = non_nan_intervals_to_nan.copy()
#plot(full_res, full_imputed_values, full_non_nan_intervals_to_nan, name)
return res#, imputed_values
def get_weather_covariates(start, end, fields=["shortwave_radiation"], name="W6 positive_active", inference=False):
if type(fields) == str:
fields = [fields]
if inference:
req_fields = ",".join(fields)
result = requests.get(
f"https://api.open-meteo.com/v1/gfs?latitude=42.564&longitude=12.643&hourly={req_fields}&forecast_days=10&timezone=auto"
).text
result = json.loads(result)
df_list = []
for field in fields:
data = result['hourly'][field]
index = pd.to_datetime(result['hourly']['time'])
assert len(data) == len(index)
df = pd.DataFrame(data=data, index=index, columns=[field]).asfreq("60min")
df.index.name = "Datetime"
df_list.append(df)
if name in ["W6 positive_active", "W6 positive_reactive"]:
result_db = requests.get(
f"http://38.242.137.200:8000/api/v1/query?source=gfs_forecast&coordinates=(42.569,%2012.608)&start_date={start}&end_date={end}&fields={req_fields}"
).text
elif name in ["W4 positive_active", "W4 positive_reactive"]:
result_db = requests.get(
f"http://38.242.137.200:8000/api/v1/query?source=gfs_forecast&coordinates=(42.567,%2012.607)&start_date={start}&end_date={end}&fields={req_fields}"
).text
else:
result_db = requests.get(
f"http://38.242.137.200:8000/api/v1/query?source=gfs_forecastt&coordinates=(42.564,%2012.643)&start_date={start}&end_date={end}&fields={req_fields}"
).text
result_db = json.loads(result_db)
df_list_db = []
for field in fields:
data = result_db['results'][field]['value']
index = pd.to_datetime(result_db['time'])
assert len(data) == len(index)
df = pd.DataFrame(data=data, index=index, columns=[field]).asfreq("60min")
df.index.name = "Datetime"
end_date = '2023-10-28'
# Specify the shift time
shift_time = 0
# Select the subset of the dataframe within the specified date range
subset_df = df.loc[:end_date]
# Shift the values forward by the specified time for the selected subset
subset_df_shifted = subset_df.shift(periods=shift_time)
# Update the original dataframe with the shifted values
df.loc[:end_date] = subset_df_shifted
start_date = '2023-10-06'
end_date = '2023-10-13'
# Specify the shift time
shift_time = 3
# Select the subset of the dataframe within the specified date range
subset_df = df.loc[start_date:end_date]
# Shift the values forward by the specified time for the selected subset
subset_df_shifted = subset_df.shift(periods=shift_time)
# Update the original dataframe with the shifted values
df.loc[start_date:end_date] = subset_df_shifted
start_date = '2023-10-14'
end_date = '2023-10-18'
# Specify the shift time
shift_time = 2
# Select the subset of the dataframe within the specified date range
subset_df = df.loc[start_date:end_date]
# Shift the values forward by the specified time for the selected subset
subset_df_shifted = subset_df.shift(periods=shift_time)
# Update the original dataframe with the shifted values
df.loc[start_date:end_date] = subset_df_shifted
start_date = '2023-10-29'
end_date = '2023-10-29'
# Specify the shift time
shift_time = -4
# Select the subset of the dataframe within the specified date range
subset_df = df.loc[start_date:end_date]
# Shift the values forward by the specified time for the selected subset
subset_df_shifted = subset_df.shift(periods=shift_time)
# Update the original dataframe with the shifted values
df.loc[start_date:end_date] = subset_df_shifted
start_date = '2023-10-29'
# Specify the shift time
shift_time = -1