-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolarprophet.py
executable file
·2073 lines (1852 loc) · 88.2 KB
/
solarprophet.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
########## Imports ##########
# Standard Library
from copy import copy, deepcopy
import os
import datetime
from joblib import Parallel, delayed
from multiprocessing import Pool
# import IPython
# import IPython.display
# import pytz
import time
import h5py
# import json
# Anaconda / Colab Standards
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as md
import numpy as np
# import seaborn as sns
from tqdm import tqdm
# Machine Learning
## SKLearn
from sklearn import preprocessing
# from sklearn.metrics import mean_absolute_error
# import imageio
## Tensorflow
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import (
TimeDistributed,
LSTM,
Dense,
Flatten,
Conv1D,
Reshape,
Dropout,
Concatenate,
Lambda,
Input,
GaussianNoise,
)
import dask
import dask.dataframe as dd
# from neptune.integrations.tensorflow_keras import NeptuneCallback
from neptune.integrations.tensorflow_keras import NeptuneCallback
import neptune
# user libraries
import constants
import utils
# Declarations
pd.options.display.max_rows = 300
pd.options.display.max_columns = 300
pd.plotting.register_matplotlib_converters()
rng = np.random.default_rng(seed=42)
# TODO use dataclasses to initialize parameters and handle default values (https://docs.python.org/3/library/dataclasses.html) (Python 3.7+)
class TabularTest:
""" """
def __init__(
self,
# Required Parameters
n_steps_in: int, # number of timesteps used in input
n_steps_out: int, # number of timesteps used in output prediction
selected_features: list = None, # Features to be used as inputs (NOTE: either selected_features or selected_groups should be passed, not both)
selected_groups: list = None, # Groups of features to be used as inputs (NOTE: either selected_features or selected_groups should be passed, not both)
selected_responses: list = [
"GHI"
], # response variable to be predicted (NOTE: format required is a list but currently only one response variable is supported)
scaler_type: str = "minmax", # scaler for raw data {minmax, normalizer, powertransformer, quantiletransformer, robustscaler, standardscaler} (default is minmax)
data_path: str = None, # path to measurement data. Eiter .h5 or .csv format is accepted. See data gathering script for more details on data format (str or path-like)
## Saving and cache parameters (optional)
model_save_path: str = None,
datetimes_cache_path: str = None,
window_cache_path: str = None, # path to saved windows with datetimes, features, responses, etc.
all_past_features: list = constants.PAST_FEATURES,
all_future_features: list = constants.FUTURE_FEATURES,
all_scalar_responses: list = constants.SCALAR_RESPONSES,
all_relative_responses: list = constants.RELATIVE_RESPONSES,
noise_model: int = 0, # noise model to use for unmeasured disturbances (default is 0)
# Model (optional)
model=None, # specified tensorflow model (default will build CNN-LSTM model) (tf model)
# model must have input shape: (batch_size, n_steps_in, n_features)
# model must have output shape: (batch_size, n_steps_out) when multiple regressed features are used: (batch_size, n_steps_out, n_regressed_variables)
model_name: str = None, # name of model if desired. Only letters,numbers, and spaces
# Optimizer and training tuning parameters (optional)
scale_responses: bool = True, # scale responses
epochs: int = 200, # maximum number of epochs to train model (default is 200)
shuffle_training_order: bool = False, # shuffle training order of windows (default is False)
batch_size: int = 1000, # batch size for training (default is 1000 windows)
loss: str = "mae", # loss function for model {mae or mse} (default is mae)
optimizer=None, # custom tf optimizer if desired (default is Adam optimizer)
learning_rate: float = 1e-3, # learning rate may be a static value or a tf.optimizers.schedules object
callbacks=[], # list of tf.keras.callbacks to be used during training (default is empty list)
early_stopping: bool = False, # implement early stopping (default is False)
stopping_patience: int = 50, # (early stopping only) number of epochs to wait without improvement before stopping training (default is 50)
stopping_min_delta: float = 1e-7, # (early stopping only) minimum objective function improvement to reset the patience counter (default is 1e-7)
metrics=None, # list of metrics to be used during training (default is None)
dropout_ratio=0,
fit_verbose: int = 0, # verbosity of model.fit() (default is 0)
# Utility Parameters (optional)
data_cols: list = constants.DATA_COLS, # columns of raw data to be read in (default is constants.CSV_COLS)
feature_groups: dict = constants.FEATURE_GROUPS, # dictionary pairing of feature groups and the features the group contains (default is constants.FEATURE_GROUPS)
scalar_response: list = constants.SCALAR_RESPONSES, #
relative_response: list = constants.RELATIVE_RESPONSES,
seed: int = 42, # random seed for reproducibility used in all rng-based functions (default is 42)
n_job_workers: int = 1, # number of workers to use for parallel processing (default is 1)
# Neptune Parameters (optional)
neptune_log: bool = False, # log results to neptune (default is False)
neptune_run_name: str = None, # name of neptune run (default is None)
tags: list = None, # tags to be added to neptune run (default is None)
):
"""Initialize TabularTest object for irradiance prediction with tabular features"""
# initialize object attributes
## Required Parameters
self.n_steps_in = n_steps_in
self.n_steps_out = n_steps_out
if selected_groups and (
selected_features is None
): # if selected_groups is passed and selected_features is None
self.selected_groups = selected_groups
self.selected_features = utils.create_features_list_from_groups(
selected_groups,
selected_responses[0],
constants.FEATURE_GROUPS,
constants.RESPONSE_FEATURES,
add_response_variable=False,
)
elif selected_features and (selected_groups is None):
self.selected_features = selected_features
else:
error_string = f"Either Selected groups or selected responses should be passed and both."
error_string += f"\n\tselected_groups: {selected_groups}\n\tselected_features: {selected_features}"
ValueError(error_string)
self.selected_responses = selected_responses
self.n_features = len(self.selected_features)
self.n_responses = len(self.selected_responses)
assert os.path.isfile(data_path), f"Data path {data_path} does not exist."
self.data_path = data_path
### Scaler
if scaler_type.lower() == "minmax":
self.scaler = (
preprocessing.MinMaxScaler
) # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler
elif scaler_type.lower() == "normalizer":
self.scaler = (
preprocessing.Normalizer
) # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer
elif scaler_type.lower() == "powertransformer":
self.scaler = (
preprocessing.PowerTransformer
) # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PowerTransformer.html#sklearn.preprocessing.PowerTransformer
elif scaler_type.lower() == "quantiletransformer":
self.scaler = (
preprocessing.QuantileTransformer
) # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.QuantileTransformer.html#sklearn.preprocessing.QuantileTransformer
elif scaler_type.lower() == "robustscaler":
self.scaler = (
preprocessing.RobustScaler
) # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html#sklearn.preprocessing.RobustScaler
elif scaler_type.lower() == "standardscaler":
self.scaler = (
preprocessing.StandardScaler
) # https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler
else:
ValueError("scaler_type must be one of those listed in __init__")
## Saving and cache parameters
self.model_save_path = model_save_path
self.datetimes_cache_path = datetimes_cache_path
if datetimes_cache_path:
assert os.path.isfile(
datetimes_cache_path
), f"datetimes_cache_path {datetimes_cache_path} does not exist."
self.cache_datetimes = utils.get_experiment_datetimes(n_steps_in)
self.window_cache_path = window_cache_path
self.all_past_features = all_past_features
self.all_future_features = all_future_features
self.all_scalar_responses = all_scalar_responses
self.all_relative_responses = all_relative_responses
self.noise_model = noise_model
## Model (optional)
self.model = model
self.model_name = model_name
## Optimizer and training tuning parameters (optional)
self.scale_responses = scale_responses
self.epochs = epochs
self.shuffle_training_order = shuffle_training_order
self.batch_size = batch_size
self.loss = loss
self.optimizer = optimizer
self.learning_rate = learning_rate
self.callbacks = callbacks
self.early_stopping = early_stopping
self.stopping_patience = stopping_patience
self.stopping_min_delta = stopping_min_delta
self.metrics = metrics
self.dropout_ratio = dropout_ratio
self.fit_verbose = fit_verbose
self.metrics_dict = {
"mae": self.rescaled_MAE,
"mae_t": self.rescaled_MAE_stepwise,
}
## Utility Parameters (optional)
self.data_cols = data_cols
self.feature_groups = feature_groups
self.scalar_response = scalar_response
self.relative_response = relative_response
self.seed = seed
self.n_job_workers = n_job_workers
tf.random.set_seed(seed)
## Neptune Parameters (optional)
self.neptune_log = neptune_log
self.neptune_run_name = neptune_run_name
self.tags = tags
if neptune_log:
self.run = neptune.init_run(
project=constants.NEPTUNE_PROJECT,
api_token=constants.NEPTUNE_TOKEN,
tags=tags,
)
else:
# TODO do neptune ANONYMOUS mode when not logging
self.run = {}
self.run["name"] = self.neptune_run_name
self.run["selected features"] = self.selected_features
self.run["selected groups"] = selected_groups
self.run["selected responses"] = self.selected_responses
self.run["scaler type"] = scaler_type
self.run["loss function"] = loss
# Initialization not directly related to arguments
self.df_total = None # import data on initialization so it only happens once
return None
# TODO Create copy and deep copy methods
def __copy__(self):
return type(self)(**self.__dict__)
# TODO understand memoization better
# def __deepcopy__(self, memo):
# """memo is a dict of ids to copies"""
# id_self = id(self) # memoization avoids unnecesary recursion
# _copy = memo.get(id_self)
# if _copy is None:
# _copy = type(self)(
# deepcopy(self.a, memo),
# deepcopy(self.b, memo))
# memo[id_self] = _copy
# return _copy
# def __deepcopy__(self):
# return deepcopy(self.__dict__)
def import_data(self, data_path: str) -> pd.DataFrame:
"""
Import raw data from .h5 of .csv file using load_joint_data function from utils.py
:param data_path(str or path-like): path to .h5 or .csv file containing raw data
:(implicit) param self.data_cols(list): list of column names to import from .h5 or .csv file
:return: pandas dataframe with datetime index
"""
df = utils.load_joint_data(
path=data_path, data_cols=self.data_cols
) # takes .h5 or csv, reads in, and returns df with datetime index
df = df.dropna(
subset=[
"GHI",
"DNI",
"DHI",
"BRBG Total Cloud Cover [%]",
"CDOC Total Cloud Cover [%]",
"CDOC Thick Cloud Cover [%]",
"CDOC Thin Cloud Cover [%]",
]
) # drop rows with NaN in any of these columns (no data from ASI-16 or solar data)
df = df.fillna(value=0)
print("Data imported")
print(
f"Data from {min(df.index)} to {max(df.index)} containing {df.shape[0]} rows and {df.shape[1]} columns"
)
print(f"Duplicated rows: {df.index.duplicated().sum()}")
print(f"Rows with Na/inf: {df.isna().any(axis=1).sum()}")
return df
def split_df(
self,
df: pd.DataFrame,
iso_split_date: str = "2021-09-27",
verbose: bool = False,
) -> tuple:
"""
split a datetime indexed pd.DataFrame into two parts, before and after a given date
:param df: pd.DataFrame to split
:param iso_split_date: str, date to split df on, in ISO format (YYYY-MM-DD)
:param verbose: bool, whether to print info about split
:return: tuple of pd.DataFrames, (before_df, after_df)
"""
iso_time_and_tz = " 00:00:00-07:00" # midnight MST
before, after = (
df.loc[: iso_split_date + iso_time_and_tz],
df.loc[iso_split_date + iso_time_and_tz :],
)
if verbose:
print(
f"Splitting df from {before.index[0]} to {before.index[-1]} and {after.index[0]} to {after.index[-1]}"
)
return before, after
def preprocess_joint_data(
self, train_validate_date: str, end_date: str, verbose: bool
) -> None:
"""
import data if unimported, split to before and after a given datem and fit scalers based on the data before the given date
:param train_validate_date: str, date to split the data into training and validation sets in ISO format (YYYY-MM-DD)
:param end_date: str, date to end validation set spanning from train_validate_date to end_date in ISO format (YYYY-MM-DD)
:param verbose: bool, whether to print info about split
:return: None
"""
# import data if unimported
if self.df_total is None:
self.df_total = self.import_data(self.data_path)
# declare local variable
df = self.df_total
# split
if end_date:
df, _ = self.split_df(self.df_total, iso_split_date=end_date, verbose=False)
self.df_train, self.df_validate = self.split_df(
df, iso_split_date=train_validate_date, verbose=verbose
) # "2020-09-27
if verbose:
for i in [self.df_train, self.df_validate]:
print(
f"Beginning {i.index[0]} through {i.index[-1]}: {i.shape[0]} points"
)
# scale
## Create Dictionary to store scaling parameters and scaled df
self.scalers = {}
## Get Training scales - one scaler per feature or data column
for column_name in self.selected_features:
column_scaler = self.scaler()
self.scalers[column_name] = column_scaler.fit(
self.df_train[column_name].values.reshape(-1, 1)
)
if self.selected_responses[0] in self.df_train.columns.values:
column_scaler = self.scaler()
self.scalers[self.selected_responses[0]] = column_scaler.fit(
self.df_train[self.selected_responses[0]].values.reshape(-1, 1)
)
self.response_scaler = self.scalers[
self.selected_responses[0]
] # TODO change to allow for multiple responses
else:
# relative responses scale to the response relative to the value at t=0, and as such use a seperate function
self.response_scaler = self.fit_relative_response(
self.df_train,
self.scalers,
self.selected_responses[0],
self.n_steps_out,
)
return None
def transform_(
self, scales: dict, sequence_name: str, sequence: np.ndarray
) -> np.ndarray:
"""
Use a scaler selected from self.scalers to transform an array of data according to selected scaler method
:param scales(dict): dict, dictionary of scalers to use - one for each data column
:param sequence_name(str): str, name of the sequence to be scaled (Column name)
:param sequence(np.ndarray): np.ndarray, 2d array of data to be scaled
:return: np.ndarray, scaled data
"""
# if sequence_name.startswith("Future "): # future feature: rescale with same scale
# sequence_name = sequence_name.replace("Future ", "")
return scales[sequence_name].transform(sequence)[
:, 0
] # indexed to [:,0 ] due to dims [# samples, # features] but we do this feature-wise
def inverse_transform_(
self, scales: dict, sequence_name: str, sequence: np.ndarray, n_steps_in: int
) -> np.ndarray:
"""
Convert scaled data back to original units
:param scales(dict): dict, dictionary of scalers to use - one for each data column
:param sequence_name(str): str, name of the sequence to be scaled (Column name)
:param sequence(np.ndarray): np.ndarray, 2d array of data to be scaled
:param n_steps_in(int): int, number of steps in the past used as input to the model
:return: np.ndarray, scaled data
"""
# if sequence_name.startswith("Future "): # future feature: rescale with same scale
# sequence_name = sequence_name.replace("Future ", "")
if sequence_name.startswith("Delta "):
# TODO how to rescale delta_based forecasts?
rescaled_difference = scales[sequence_name].inverse_transform(sequence)
t0_value = 0
return rescaled_difference # t0_value - rescaled_difference
return scales[sequence_name].inverse_transform(sequence)[
:, 0
] # indexed to [:,0 ] due to dims [# samples, # features] but we do this feature-wise
def fit_relative_response(
self,
df: pd.DataFrame,
scales: dict,
relative_response_name: str,
n_steps_out: int,
) -> object:
"""
Relative responses are relative to the time of prediction. As such, the measured value must be subtracted from the time of prediction.
This function fits the scaler for use in the relative response.
:param df: pd.DataFrame, dataframe containing the data to be scaled
:param scales: dict, dictionary of scalers to use - one for each data column
:param relative_response_name: str, name of the response to be scaled
:param n_steps_out: int, number of steps in the future to predict
:return: scaler, scaler used to scale the data
"""
response_name = relative_response_name.replace(
"Delta ", ""
) # Measured quantity name (Column name)
response_data = df[response_name] # measured quantity data
response_deltas = np.array([])
for i in range(
n_steps_out
): # get the difference between the measured quantity and itself up to n_steps_out in the future shifted
response_deltas = np.concatenate(
(
response_deltas,
response_data.diff(periods=i + 1).fillna(value=0).values,
)
)
column_scaler = self.scaler() # initialize scaler object
scales[relative_response_name] = column_scaler.fit(
response_deltas.reshape(-1, 1)
) # fit to flattened data
return column_scaler
def split_past_features(
self, df: pd.DataFrame, feature: str, start_indices: int, n_steps_in: int
) -> np.ndarray:
"""
return a scaled array of shape (# windows, steps in, # features)
:param df(pd.DataFrame): pd.DataFrame, dataframe containing the data to be scaled)
:param feature(str): str, name of the feature to be scaled (Column name)
:param start_indices(int): int, index (row) of the window to be scaled
:param n_steps_in(int): int, number of steps in the past used as input to the model
:param (implicit) self.scalers(dict): dict, dictionary of scalers to use - one for each data column
:return: np.ndarray, scaled data
"""
past_features = df[feature].values[start_indices : start_indices + n_steps_in]
scaled_past_features = self.transform_(
self.scalers, feature, past_features.reshape(-1, 1)
)
return scaled_past_features
def split_scalar_response(
self,
df: pd.DataFrame,
response: str,
start_indices: int,
n_steps_in: int,
n_steps_out: int,
) -> np.ndarray:
"""
return an array of shape (# windows, steps in, # features). Also works for scalar future features
:param df(pd.DataFrame): pd.DataFrame, dataframe containing the data to be scaled)
:param response(str): str, name of the response to be scaled (Column name)
:param start_indices(int): int, index (row) of the window to be scaled
:param n_steps_in(int): int, number of steps in the past used as input to the model
:param n_steps_out(int): int, number of steps in the future to predict
:param (implicit) self.scalers(dict): dict, dictionary of scalers to use - one for each data column
:return: np.ndarray, scaled data
"""
scalar_response = df[response].values[
start_indices + n_steps_in : start_indices + n_steps_in + n_steps_out
]
if self.scale_responses:
scaled_scalar_response = self.transform_(
self.scalers, response, scalar_response.reshape(-1, 1)
)
return scaled_scalar_response
else:
return scalar_response.reshape(-1, 1)
def split_relative_response(
self,
df: pd.DataFrame,
response_name: str,
start_indices: int,
n_steps_in: int,
n_steps_out: int,
) -> np.ndarray:
"""
calculate the relative response and return the data scaled
:param df(pd.DataFrame): dataframe containing the data to be scaled
:param response_name(str): name of the response to be scaled (Column name)
:param start_indices(int): index (row) of the window to be scaled
:param n_steps_in(int): number of steps in the past used as input to the model
:param n_steps_out(int): number of steps in the future to predict
:param (implicit) self.scalers(dict): dictionary of scalers to use - one for each data column
:return: np.ndarray, scaled data
"""
scalar_response_name = response_name.replace("Delta ", "")
sequence = df[scalar_response_name].values
response = sequence[
start_indices + n_steps_in : start_indices + n_steps_in + n_steps_out
]
relative_response = response - sequence[start_indices + n_steps_in - 1]
if self.scale_responses:
scaled_relative_response = self.transform_(
self.scalers, response_name, relative_response.reshape(-1, 1)
)
return scaled_relative_response
else:
return relative_response.reshape(-1, 1)
def create_single_window(
self,
window_datetimes: list,
df: pd.DataFrame,
selected_features: list,
selected_responses: list,
scalers: dict,
n_steps_in: int,
n_steps_out: int,
) -> list:
"""
function for use with cached datetimes for the windows already available
:param window_datetimes(list): list, list of datetimes for the windows
:param df(pd.DataFrame): pd.DataFrame, dataframe containing the data
:param selected_features(list): list, list of features to be used
:param selected_responses(list): list, list of responses to be used
:param scalers(dict): dict, dictionary containing the scalers for the features
:param n_steps_in(int): int, number of steps in the past
:param n_steps_out(int): int, number of steps in the future
:return: list, list of lists containing the windows
[datetimes, selected_past_features, selected_future_features, selected_scalar_responses, selected_relative_responses, clear_sky_indexes, clear_sky_irradiances]
"""
window_data = df.loc[window_datetimes]
# initialize other values
window_past_features = []
window_future_features = []
window_scalar_responses = []
window_relative_responses = []
window_clear_sky_indexes = []
window_clear_sky_irradiances = []
for feature in selected_features:
if not feature.startswith("Future "): # past feature
window_past_features.append(
self.split_past_features(window_data, feature, 0, n_steps_in)
)
else: # future feature
window_future_features.append(
self.split_scalar_response(
window_data, feature, 0, n_steps_in, n_steps_out
)
)
for response in selected_responses:
if not response.startswith("Delta "): # Scalar response
window_scalar_responses.append(
self.split_scalar_response(
window_data, response, 0, n_steps_in, n_steps_out
)
)
else:
window_relative_responses.append(
self.split_relative_response(
window_data, response, 0, n_steps_in, n_steps_out
)
)
window_clear_sky_indexes = window_data["CSI GHI"].values
window_clear_sky_irradiances = window_data["clearsky ghi"].values
# append but first change dimensions from n_features, n_steps to n_steps, n_features
window_past_features = [list(map(list, zip(*window_past_features)))]
window_future_features = [list(map(list, zip(*window_future_features)))]
return (
window_datetimes,
window_past_features,
window_future_features,
window_scalar_responses,
window_relative_responses,
window_clear_sky_indexes,
window_clear_sky_irradiances,
)
# general windowing:
def window_sequential(
self,
df: pd.DataFrame,
selected_features: list,
selected_responses: list,
scalers: dict,
n_steps_in: int,
n_steps_out: int,
step_time: datetime.timedelta = datetime.timedelta(minutes=10),
) -> list:
"""
loop through all the data and if the time is continuous and the correct length, scale datetimes, features, responses, clear sky indices, and clear sky irradiances
and add to lists. Then convert the lists to numpy arrays and return them.
:param df(pd.DataFrame): pd.DataFrame, dataframe containing the data to be windowed
:param selected_features(list[str]): list[str], list of features to be used in the model
:param selected_responses(list[str]): list[str], list of responses to be used in the model
:param scalers(dict): dict, dictionary of scalers to use - one for each data column
:param n_steps_in(int): int, number of steps in the past used as input to the model
:param n_steps_out(int): int, number of steps in the future to predict
:param step_time(datetime.timedelta): datetime.timedelta, time between each step in the data
:return: list(np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray), tuple of numpy arrays containing the datetimes, features, responses, clear sky indices, and clear sky irradiances
[datetimes, selected_past_features, selected_future_features, selected_scalar_responses, selected_relative_responses, clear_sky_indexes, clear_sky_irradiances]
"""
# lists for storage
datetimes = []
selected_past_features = []
selected_future_features = []
selected_scalar_responses = []
selected_relative_responses = []
clear_sky_indexes = []
clear_sky_irradiances = []
start_idx = 0
end_idx = n_steps_in + n_steps_out
count = 0
for start_idx in tqdm(
range(df.shape[0] - n_steps_in - n_steps_out - 1)
): # TODO vectorize
end_idx = start_idx + n_steps_in + n_steps_out
# check that time is continuous
if (
pd.to_timedelta(df.index.values[end_idx] - df.index.values[start_idx])
== (n_steps_in + n_steps_out) * step_time
):
count += 1
window_datetimes = df.index[start_idx:end_idx]
# window and scale
window_results = self.create_single_window(
window_datetimes,
df,
selected_features,
selected_responses,
scalers,
n_steps_in,
n_steps_out,
)
datetimes.append(window_results[0])
selected_past_features.append(window_results[1])
selected_future_features.append(window_results[2])
selected_scalar_responses.append(window_results[3])
selected_relative_responses.append(window_results[4])
clear_sky_indexes.append(window_results[5])
clear_sky_irradiances.append(window_results[6])
# convert lists to numpy arrays
datetimes = np.array(datetimes).squeeze()
selected_past_features = np.array(selected_past_features).squeeze()
selected_future_features = np.array(selected_future_features).squeeze()
selected_scalar_responses = np.array(selected_scalar_responses).squeeze()
selected_relative_responses = np.array(selected_relative_responses).squeeze()
clear_sky_indexes = np.array(clear_sky_indexes).squeeze()
clear_sky_irradiances = np.array(clear_sky_irradiances).squeeze()
return [
datetimes,
selected_past_features,
selected_future_features,
selected_scalar_responses,
selected_relative_responses,
clear_sky_indexes,
clear_sky_irradiances,
]
def window_cached(
self,
df: pd.DataFrame,
selected_features: list,
selected_responses: list,
scalers: dict,
n_steps_in: int,
n_steps_out: int,
) -> list:
"""
loop through all the data and if the time is continuous and the correct length, scale datetimes, features, responses, clear sky indices, and clear sky irradiances
and add to lists. Then convert the lists to numpy arrays and return them.
:param df(pd.DataFrame): pd.DataFrame, dataframe containing the data to be windowed
:param selected_features(list[str]): list[str], list of features to be used in the model
:param selected_responses(list[str]): list[str], list of responses to be used in the model
:param scalers(dict): dict, dictionary of scalers to use - one for each data column
:param n_steps_in(int): int, number of steps in the past used as input to the model
:param n_steps_out(int): int, number of steps in the future to predict
:param (implicit) cache_datetimes_path(str): str, path to the cache file containing the datetimes TODO utils does not use this path, only # steps
:return: list(np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray), tuple of numpy arrays containing the datetimes, features, responses, clear sky indices, and clear sky irradiances
[datetimes, selected_past_features, selected_future_features, selected_scalar_responses, selected_relative_responses, clear_sky_indexes, clear_sky_irradiances]
"""
# lists for storage
datetimes = []
selected_past_features = []
selected_future_features = []
selected_scalar_responses = []
selected_relative_responses = []
clear_sky_indexes = []
clear_sky_irradiances = []
cache_datetimes = utils.get_experiment_datetimes(n_steps_in).to_numpy()
# compare as datetime64[ns] to avoid type issues
after_df_start_mask = cache_datetimes[:, 0] >= df.index[0]
before_df_end_mask = cache_datetimes[:, -1] <= df.index[-1]
cache_datetimes = cache_datetimes[after_df_start_mask & before_df_end_mask]
n_windows, _ = cache_datetimes.shape
for i in tqdm(range(n_windows)): # TODO vectorize
window_datetimes = cache_datetimes[i]
# window and scale
window_results = self.create_single_window(
window_datetimes,
df,
selected_features,
selected_responses,
scalers,
n_steps_in,
n_steps_out,
)
datetimes.append(window_results[0])
selected_past_features.append(window_results[1])
selected_future_features.append(window_results[2])
selected_scalar_responses.append(window_results[3])
selected_relative_responses.append(window_results[4])
clear_sky_indexes.append(window_results[5])
clear_sky_irradiances.append(window_results[6])
# convert lists to numpy arrays
datetimes = np.array(datetimes).squeeze()
selected_past_features = np.array(selected_past_features).squeeze()
selected_future_features = np.array(selected_future_features).squeeze()
selected_scalar_responses = np.array(selected_scalar_responses).squeeze()
selected_relative_responses = np.array(selected_relative_responses).squeeze()
clear_sky_indexes = np.array(clear_sky_indexes).squeeze()
clear_sky_irradiances = np.array(clear_sky_irradiances).squeeze()
return [
datetimes,
selected_past_features,
selected_future_features,
selected_scalar_responses,
selected_relative_responses,
clear_sky_indexes,
clear_sky_irradiances,
]
def create_windows(self, verbose):
"""
Create windows for prediction either in parallel or serially based on n_workers argument
:
"""
if self.datetimes_cache_path is not None:
if verbose:
print(f"Forming windows from cache".center(40, "="))
print(f"Training Set")
(
self.train_dates,
self.train_past_features,
self.train_future_features,
self.train_scalar_responses,
self.train_relative_responses,
self.train_clear_sky_indexes,
self.train_clear_sky_irradiances,
) = self.window_cached(
self.df_train,
self.selected_features,
self.selected_responses,
self.scalers,
self.n_steps_in,
self.n_steps_out,
)
if verbose:
print(f"Validation Set")
(
self.validate_dates,
self.validate_past_features,
self.validate_future_features,
self.validate_scalar_responses,
self.validate_relative_responses,
self.validate_clear_sky_indexes,
self.validate_clear_sky_irradiances,
) = self.window_cached(
self.df_validate,
self.selected_features,
self.selected_responses,
self.scalers,
self.n_steps_in,
self.n_steps_out,
)
else:
if verbose:
print("Forming Windows Sequentially".center(40, "="))
print(f"Training Set")
(
self.train_dates,
self.train_past_features,
self.train_future_features,
self.train_scalar_responses,
self.train_relative_responses,
self.train_clear_sky_indexes,
self.train_clear_sky_irradiances,
) = self.window_sequential(
self.df_train,
self.selected_features,
self.selected_responses,
self.scalers,
self.n_steps_in,
self.n_steps_out,
)
if verbose:
print(f"Validation Set")
(
self.validate_dates,
self.validate_past_features,
self.validate_future_features,
self.validate_scalar_responses,
self.validate_relative_responses,
self.validate_clear_sky_indexes,
self.validate_clear_sky_irradiances,
) = self.window_sequential(
self.df_validate,
self.selected_features,
self.selected_responses,
self.scalers,
self.n_steps_in,
self.n_steps_out,
)
# convenience attributes
# pass either relative or scalar responses to model
if self.selected_responses[0] in self.relative_response:
print("Relative Response")
self.y_train_true = self.train_relative_responses
self.y_validate_true = self.validate_relative_responses
else:
self.y_train_true = self.train_scalar_responses
self.y_validate_true = self.validate_scalar_responses
if verbose:
print(f"Train windows: {len(self.train_dates)}")
print(f"\n{self.train_dates.shape=}")
print(f"\n{self.train_past_features.shape=}")
print(f"\n{self.train_future_features.shape=}")
print(f"\n{self.train_scalar_responses.shape=}")
print(f"\n{self.train_relative_responses.shape=}")
print(f"\n{self.train_clear_sky_indexes.shape=}")
print(f"\n{self.train_clear_sky_irradiances.shape=}")
print(f"Validate windows: {len(self.validate_dates)}")
return None
def import_preprocess_cached_windows(self, train_validate_date, end_date, verbose):
"""
Use h5 cache with precomputed windows for the given window range. Load, split, scale, and return windows.
:param window_cache_path(str): path to h5py cache
:param train_validate_date(str): date to split train and validate sets in ISO format: YYYY-MM-DD
:param end_date(str): end date of window range in ISO format: YYYY-MM-DD
:param all_past_features(list): list of all possible past features. IMPORTANT: needs to match the order of the features in the cache. use constants.py
:param all_future_features(list): list of all possible future features. See note in all_past_features
:param all_scalar_responses(list): list of all possible scalar responses. See note in all_past_features
:param all_relative_responses(list): list of all possible relative responses. See note in all_past_features
:verbose(bool): print statements
implicit args: self.n_steps_in, self.selected_features, self.selected_responses, self.scaler
:return: None
implicit returns in self. namespace: scalers, train_dates, train_past_features, train_future_features, train_scalar_responses,
train_relative_responses, train_clear_sky_indexes, train_clear_sky_irradiances, validate_dates, validate_past_features,
validate_future_features, validate_scalar_responses, validate_relative_responses, validate_clear_sky_indexes, validate_clear_sky_irradiances
"""
# read h5py cache
if verbose:
print(f" Reading windows from cache ".center(40, "="))
with h5py.File(self.window_cache_path, "r") as f:
datetimes = f[f"{self.n_steps_in}/datetimes"][
:
] # (n_windows, n_steps_in + n_steps_out)
past_features = f[f"{self.n_steps_in}/past_features"][
:
] # (n_windows, n_steps_in, n_scalar_features(134))
future_features = f[f"{self.n_steps_in}/future_features"][
:
] # (n_windows, n_steps_out, n_future_features(7))
scalar_responses = f[f"{self.n_steps_in}/scalar_responses"][
:
] # (n_windows, n_steps_out, n_scalar_responses(3)
relative_responses = f[f"{self.n_steps_in}/relative_responses"][
:
] # (n_windows, n_steps_out, n_relative_responses(2))
clear_sky_indexes = f[f"{self.n_steps_in}/clear_sky_indexes"][
:
] # (n_windows, n_steps_in + n_steps_out)
clear_sky_irradiances = f[f"{self.n_steps_in}/clear_sky_irradiances"][
:
] # (n_windows, n_steps_in + n_steps_out)
if self.n_steps_in == 1:
past_features = np.expand_dims(past_features, axis=1)
print(f"past_features.shape: {past_features.shape}")
if verbose:
print("\nDone")
if verbose >= 2:
print(
f" Selecting and scaling relevant features and responses ".center(
40, "="
)
)
print(f"datetimes.shape: {datetimes.shape}")
print(f"past_features.shape: {past_features.shape}")
print(f"future_features.shape: {future_features.shape}")
print(f"scalar_responses.shape: {scalar_responses.shape}")
print(f"relative_responses.shape: {relative_responses.shape}")
print(f"clear_sky_indexes.shape: {clear_sky_indexes.shape}")
print(f"clear_sky_irradiances.shape: {clear_sky_irradiances.shape}")
# convert datetimes from int64 to tz-aware datetime
datetimes = (
pd.DatetimeIndex(datetimes).tz_localize("UTC").tz_convert("MST").to_numpy()
)
# get indices of relevant datetimes
train_validate_date = pd.to_datetime(
train_validate_date + " 00:00:00"
).tz_localize("MST")
end_date = pd.to_datetime(end_date + " 00:00:00").tz_localize("MST")
train_mask = datetimes[:, -1] < train_validate_date
validate_mask = (datetimes[:, 0] >= train_validate_date) & (
datetimes[:, -1] < end_date
)