-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_utils.py
207 lines (149 loc) · 7.58 KB
/
data_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
import pandas as pd
from datetime import datetime as dt
import pytz
from pandas.tseries.holiday import USFederalHolidayCalendar
import numpy as np
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
def get_features_labels(path = 'Data/battery_storage/storage_data.csv'):
tz = pytz.timezone('America/New_York')
df = pd.read_csv(path, parse_dates=[0])
df['date'] = df['datetime'].apply(lambda x: x.date())
df['hour'] = df['datetime'].apply(lambda x: x.hour)
# Prices
df_prices = df[['da_price']].apply(lambda x: pd.to_numeric(x), axis=1)
df_prices = df_prices.fillna(method='backfill').transpose()
df_prices = df_prices.fillna(method='ffill').transpose()
df_prices_log = np.log(df_prices)
# Load forecasts
df_load = df[['load_forecast']].apply(lambda x: pd.to_numeric(x), axis=1)
df_load = df_load.fillna(method='backfill').transpose()
df_load = df_load.fillna(method='ffill').transpose()
# Temperatures
df_temp = df[['temp_dca']].apply(lambda x: pd.to_numeric(x), axis=1)
df_temp = df_temp.fillna(method='backfill').transpose()
df_temp = df_temp.fillna(method='ffill').transpose()
holidays = USFederalHolidayCalendar().holidays(
start='2011-01-01', end='2017-01-01').to_pydatetime()
holiday_dates = set([h.date() for h in holidays])
s = df['datetime']
data={"weekend": s.apply(lambda x: x.isoweekday() >= 6).values,
"holiday": s.apply(lambda x: x.date() in holiday_dates).values,
"cos_doy": s.apply(lambda x: np.cos(
float(x.timetuple().tm_yday)/365*2*np.pi)).values,
"sin_doy": s.apply(lambda x: np.sin(
float(x.timetuple().tm_yday)/365*2*np.pi)).values,
"cos_hour": s.apply(lambda x: np.cos(
float(x.hour)/365*2*np.pi)).values,
"sin_hour": s.apply(lambda x: np.sin(
float(x.hour)/365*2*np.pi)).values,
}
df_feat = pd.DataFrame(data=data, index=df_prices_log.index)
time_series = pd.concat([df_prices_log,
df_load,
df_temp,
df_feat]
, axis = 1)
time_series.index = df['datetime']
# time_series = time_series[:500] # Delete in prod
X = time_series.copy().astype('float')
# Add features
for col in ['temp_dca']:
X[f'{col}_squared'] = X[col]**2
X[f'{col}_cubed'] = X[col]**3
X = (X - X.mean(axis=0))/ X.std(axis = 0) # Normalise
Y = time_series['da_price'].copy()
return X,Y
def get_train_holdout_test(hyperparameters,
path = 'Data/battery_storage/storage_data.csv'):
test_fraction = hyperparameters['test_fraction']
validation_fraction = hyperparameters['validation_fraction']
X, Y = get_features_labels(path = path)
test_boundary = int(X.shape[0] * test_fraction)
X_test, Y_test = X.iloc[-test_boundary:, :], Y.iloc[-test_boundary:]
arrays = {'X_test': X_test, 'Y_test': Y_test}
if validation_fraction:
validation_boundary = int(X.shape[0] * (test_fraction + validation_fraction))
X_validation, Y_validation = X.iloc[-validation_boundary:-test_boundary, :], Y.iloc[-validation_boundary:-test_boundary]
arrays['X_validation'] = X_validation
arrays['Y_validation'] = Y_validation
X_train, Y_train = X.iloc[:-validation_boundary, :], Y.iloc[:-validation_boundary]
else:
X_train, Y_train = X.iloc[:-test_boundary, :], Y.iloc[:-test_boundary]
arrays['X_train'] = X_train
arrays['Y_train'] = Y_train
return arrays
class MultistageOptimisationDataset(torch.utils.data.Dataset):
def __init__(self, X, Y, hyperparameters):
self.X = X
self.Y = Y
self.hyperparameters = hyperparameters
def __len__(self):
return self.Y.shape[0] - (self.hyperparameters['f']*2 - 1) - self.hyperparameters['l']
def __getitem__(self, idx):
Z = []
for t in range(self.hyperparameters['f']):
context_t = []
context_t.append(self.X[self.hyperparameters['backwards_variables']].iloc[
idx + t: self.hyperparameters['l'] + idx + t].stack())
context_t.append(self.X[self.hyperparameters['forwards_variables']].iloc[
self.hyperparameters['l'] + idx + t: self.hyperparameters['l'] + idx + self.hyperparameters['f'] + t].stack())
context_t.append(self.X[self.hyperparameters['static_variables']].iloc[self.hyperparameters['l'] + idx + t])
context_t = pd.concat(context_t)
Z.append(torch.tensor(context_t.values).float())
Z = torch.stack(Z, dim = 0)
initial_state = torch.tensor([self.hyperparameters['B']/2]).float()
context = {
'Z' : Z,
'initial_state' : initial_state,
}
theta = self.Y.iloc[self.hyperparameters['l']+idx:self.hyperparameters['l'] + idx + self.hyperparameters['f']]
theta = torch.tensor(theta).float().unsqueeze(-1) # Turn into a vector with unsqueeze
oracle_thetas = []
for t in range(self.hyperparameters['f']):
o_theta = self.Y.iloc[self.hyperparameters['l'] + idx + t: self.hyperparameters['l'] + idx + self.hyperparameters['f'] + t]
oracle_thetas.append(torch.tensor(o_theta).float().unsqueeze(-1))
oracle_thetas = torch.stack(oracle_thetas, dim = 0)
true_parameters = {
'theta' : theta,
'oracle_thetas' : oracle_thetas, # [Batch, Time at which forecast is performed, Stage for which the forecast is made, 1 - to make it a vector]
}
return context, true_parameters
class MultistageOptimisationDatasetEvaluation(torch.utils.data.Dataset):
def __init__(self, X, Y, hyperparameters):
self.X = X
self.Y = Y
self.hyperparameters = hyperparameters
self.length_full = self.Y.shape[0] - (self.hyperparameters['f']*2 - 1) - self.hyperparameters['l']
def __len__(self):
return 1
def __getitem__(self, idx):
Z = []
for t in range(self.length_full):
context_t = []
context_t.append(self.X[self.hyperparameters['backwards_variables']].iloc[
idx + t: self.hyperparameters['l'] + idx + t].stack())
context_t.append(self.X[self.hyperparameters['forwards_variables']].iloc[
self.hyperparameters['l'] + idx + t: self.hyperparameters['l'] + idx + self.hyperparameters['f'] + t].stack())
context_t.append(self.X[self.hyperparameters['static_variables']].iloc[self.hyperparameters['l'] + idx + t])
context_t = pd.concat(context_t)
Z.append(torch.tensor(context_t.values).float())
Z = torch.stack(Z, dim = 0)
initial_state = torch.tensor([self.hyperparameters['B']/2]).float()
context = {
'Z' : Z,
'initial_state' : initial_state,
}
theta = self.Y.iloc[self.hyperparameters['l']+idx:self.hyperparameters['l'] + idx + self.length_full]
theta = torch.tensor(theta).float().unsqueeze(-1) # Turn into a vector with unsqueeze
oracle_thetas = []
for t in range(self.length_full):
o_theta = self.Y.iloc[self.hyperparameters['l'] + idx + t: self.hyperparameters['l'] + idx + self.hyperparameters['f'] + t]
oracle_thetas.append(torch.tensor(o_theta).float().unsqueeze(-1))
oracle_thetas = torch.stack(oracle_thetas, dim = 0)
true_parameters = {
'theta' : theta,
'oracle_thetas' : oracle_thetas
}
return context, true_parameters