-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.py
370 lines (305 loc) · 13.5 KB
/
env.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
import gymnasium as gym
from gymnasium import spaces
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import torch
from torch import nn
from tqdm import tqdm
from datetime import datetime
#TODO Create simple MLP or RNN to do actions
#TODO incorporate price fluctuations.
class SolarEnv(gym.Env):
metadata = {'render.modes': ['human', 'rgb_array'], 'render_modes': ['human', 'rgb_array'], 'render_fps': 30} # Add 'render_fps'
def __init__(self, is_dummy=False):
super(SolarEnv, self).__init__()
data = pd.read_excel('./Solar data_2016.xlsx')
self.energy_prices = pd.read_excel('Energy Price_2016.xlsx')
self.energy_prices = self.energy_prices[self.energy_prices["Price hub"].replace(' ', '') == 'Mid C Peak']
self.energy_prices = self.energy_prices[1:]#because it has January 30th
self.energy_dates = self.energy_prices['Trade date'].values
self.energy_prices = self.energy_prices['Avg price $/MWh'].values
self.energy_step = 0
self.energy_buffer = 0
self.last_date = np.datetime64("2016-01-01T00:00:00.000000000")
self.start_date = np.datetime64("2016-01-01T00:00:00.000000000")
# self.fig, self.ax = plt.subplots(2, 2)
# self.ax[0][0].set_xlabel('Timestep')
# self.ax[0][0].set_ylabel('Balance')
# self.ax[0][1].set_xlabel('Timestep')
# self.ax[0][1].set_ylabel('VMP')
# self.ax[1][0].set_xlabel('Timestep')
# self.ax[1][0].set_ylabel('IMP')
# self.ax[1][1].set_xlabel('Timestep')
# self.ax[1][1].set_ylabel('Reward')
# plt.ion()
# plt.show(block=False)
self.df = data
self.train_sz = len(self.df)-1
self.action_space = spaces.Discrete(2)
self.observation_space = spaces.Box(
low=0, high=np.inf, shape=(4,), dtype=np.float32
)
#Key for the AI network
self.balance = 0
self.wattage_balance = 0
#Smart home manager, smart home speaker , Electric vehicle charging
self.power_day = 0
self.wattage_rate = 0
self.recent_holds = 0
self.hour = 1
self.vimp = []
self.imp = []
self.actions = []
self.last_reward = 0
def calc_reward(self, aux=1):
reward = (self.wattage_balance + self.power_day) * self.wattage_rate
self.balance += reward
reward += max(0, self.last_reward)
reward += self.balance
return reward
def get_wattage(self, vmp, imp):
pmax = vmp * imp
return pmax
def step(self, action):
reward = 0
if action == 0:
#hold for
self.wattage_balance += self.power_day
else:
#sell
reward = self.calc_reward()
self.last_reward = reward
#reward *= 100
# reward = self.balance
self.wattage_balance = 0
self.recent_holds = 0
self.power_day = 0
done = truncated = self.train_sz <= self.current_step
#Get the day ahead for the observation
self.wattage_rate = 0
self.power_day = 0
if not done:
last_price = self.wattage_rate
for i in range(48):
vimp = self.df['Vmp'][self.current_step]
imp = self.df['Imp'][self.current_step]
#Account for weekend
yearday = self.current_step
dayahead = pd.to_datetime( self.energy_dates[self.energy_step+1] )
start = pd.to_datetime( self.start_date )
day_diff = (dayahead - start).days
if day_diff < yearday / 48:
start = dayahead
self.energy_step += 1
self.wattage_rate = self.energy_prices[self.energy_step]/1000
kilo_watts = self.get_wattage(vimp, imp)/1000#Lets assum Kilo Watts for now
self.power_day += kilo_watts
self.current_step += 1
# if last_price < self.wattage_rate and action == 1:
# reward -= 10
#Day of the year, price, wattage stored, power generated in the day self.current_step//48,
observation = np.array([ self.wattage_rate, self.wattage_balance, self.power_day, reward])
else:
print(f'Balance: {self.balance:.2f}') #0,
observation = np.array([ 0, 0, 0, reward])
if action == 1:
reward = -100 #Discourage holding till the end
return observation,reward, done, truncated, {}
def reset(self, seed=None, options=None):
self.current_step = 0
self.energy_step = 0
self.balance = 0
self.wattage_rate = 0
self.power_day = 0
for i in range(48):
vimp = self.df['Vmp'][self.current_step]
imp = self.df['Imp'][self.current_step]
#Account for weekend
yearday = self.current_step
dayahead = pd.to_datetime( self.energy_dates[self.energy_step+1] )
start = pd.to_datetime( self.start_date )
day_diff = (dayahead - start).days
if day_diff < yearday / 48:
start = dayahead
self.energy_step += 1
self.wattage_rate = self.energy_prices[self.energy_step]/1000
kilo_watts = self.get_wattage(vimp, imp)/1000#Lets assum Kilo Watts for now
self.power_day += kilo_watts
self.current_step += 1
#Day of the year, price, wattage stored, power generated in the day self.current_step//48,
observation = np.array([ self.wattage_rate, self.wattage_balance, self.power_day, 0])
return observation,{}
def render(self, mode='human'):
log_val = 100
# x_data = range(0, min(len(self.actions), log_val))
# self.ax[0][0].clear()
# self.ax[0][1].clear()
# self.ax[1][0].clear()
# self.ax[1][1].clear()
# self.ax[0][0].set_xlim(min(x_data), max(x_data))
# self.ax[0][0].set_ylim(min(self.actions[-log_val:]), max(self.actions[-log_val:]))
# self.ax[0][0].plot(x_data, self.actions[-log_val:])
# self.ax[0][1].set_xlim(min(x_data), max(x_data))
# self.ax[0][1].set_ylim(min(self.vimp[-log_val:]), max(self.vimp[-log_val:]))
# self.ax[0][1].plot(x_data, self.vimp[-log_val:])
# self.ax[1][0].set_xlim(min(x_data), max(x_data))
# self.ax[1][0].set_ylim(min(self.imp[-log_val:]), max(self.imp[-log_val:]))
# self.ax[1][0].plot(x_data, self.imp[-log_val:])
# self.ax[1][1].set_xlim(min(x_data), max(x_data))
# self.ax[1][1].set_ylim(min(self.rewards[-log_val:]), max(self.rewards[-log_val:]))
# self.ax[1][1].plot(x_data, self.rewards[-log_val:])
# self.fig.canvas.draw()
# plt.pause(1e-40)
class SolarEnv4Step(gym.Env):
metadata = {'render.modes': ['human', 'rgb_array'], 'render_modes': ['human', 'rgb_array'], 'render_fps': 30} # Add 'render_fps'
def __init__(self, is_dummy=False):
super(SolarEnv4Step, self).__init__()
data = pd.read_excel('./Solar data_2016.xlsx')
self.energy_prices = pd.read_excel('Energy Price_2016.xlsx')
self.energy_prices = self.energy_prices[self.energy_prices["Price hub"].replace(' ', '') == 'Mid C Peak']
self.energy_prices = self.energy_prices[1:]#because it has January 30th
self.energy_dates = self.energy_prices['Trade date'].values
self.energy_prices = self.energy_prices['Avg price $/MWh'].values
self.energy_step = 0
self.energy_buffer = 0
self.last_date = np.datetime64("2016-01-01T00:00:00.000000000")
self.start_date = np.datetime64("2016-01-01T00:00:00.000000000")
# self.fig, self.ax = plt.subplots(2, 2)
# self.ax[0][0].set_xlabel('Timestep')
# self.ax[0][0].set_ylabel('Balance')
# self.ax[0][1].set_xlabel('Timestep')
# self.ax[0][1].set_ylabel('VMP')
# self.ax[1][0].set_xlabel('Timestep')
# self.ax[1][0].set_ylabel('IMP')
# self.ax[1][1].set_xlabel('Timestep')
# self.ax[1][1].set_ylabel('Reward')
# plt.ion()
# plt.show(block=False)
self.df = data
self.train_sz = len(self.df)-1
self.action_space = spaces.Discrete(2)
self.observation_space = spaces.Box(
low=0, high=np.inf, shape=(4,), dtype=np.float32
)
#Key for the AI network
self.balance = 0
self.wattage_balance = 0
#Smart home manager, smart home speaker , Electric vehicle charging
self.power_day = 0
self.wattage_rate = 0
self.hour = 1
self.vimp = []
self.imp = []
self.actions = []
self.rewards = []
def calc_reward(self, aux=1):
reward = (self.wattage_balance + self.power_day) * self.wattage_rate
return reward
def get_wattage(self, vmp, imp):
pmax = vmp * imp
return pmax
def get_next_day(self, reward):
for _ in range(48):
vimp = self.df['Vmp'][self.current_step]
imp = self.df['Imp'][self.current_step]
#Account for weekend
yearday = self.current_step
dayahead = pd.to_datetime( self.energy_dates[self.energy_step+1] )
start = pd.to_datetime( self.start_date )
day_diff = (dayahead - start).days
if day_diff < yearday / 48:
start = dayahead
self.energy_step += 1
self.wattage_rate = self.energy_prices[self.energy_step]/1000
kilo_watts = self.get_wattage(vimp, imp)/1000#Lets assum Kilo Watts for now
self.power_day += kilo_watts
self.current_step += 1
#Day of the year, price, wattage stored, power generated in the day
observation = np.array([self.current_step//48, self.wattage_rate, self.wattage_balance, self.power_day, reward])
return observation
def step(self, action):
reward = 0
day_skip = 1
if action == 0:
#hold for next 3 days
self.wattage_balance += self.power_day
day_skip = 3
elif action == 1:
#sell on the first day
reward = self.calc_reward()
self.balance += reward
reward = self.balance
self.wattage_balance = 0
self.power_day = 0
elif action == 2:
#sell on the second day
day_skip = 1
elif action == 3:
day_skip = 2
#sell on the third say
done = truncated = self.train_sz <= self.current_step
#Get the day ahead for the observation
self.wattage_rate = 0
self.power_day = 0
if not done:
for _ in range(day_skip):
observation = self.get_next_day(reward)
done = truncated = self.train_sz <= self.current_step
if done:
break
if action == 2 or action == 3:
#sell on the third say
reward = self.calc_reward()
self.balance += reward
reward = self.balance
self.wattage_balance = 0
self.power_day = 0
if not done:
observation = self.get_next_day(reward)
if done:
print(f'Balance: {self.balance:.2f}')
if action == 1:
reward = -100 #Discourage holding till the end
observation = np.array([0, 0, 0, 0, reward])
else:
print(f'Balance: {self.balance:.2f}')
if action == 1:
reward = -100 #Discourage holding till the end
observation = np.array([0, 0, 0, 0, reward])
return observation,reward, done, truncated, {}
def reset(self, seed=None, options=None):
self.current_step = 0
self.energy_step = 0
self.balance = 0
self.wattage_rate = 0
self.power_day = 0
#Day of the year, price, wattage stored, power generated in the day
observation = self.get_next_day(0)
return observation,{}
def render(self, mode='human'):
log_val = 100
# x_data = range(0, min(len(self.actions), log_val))
# self.ax[0][0].clear()
# self.ax[0][1].clear()
# self.ax[1][0].clear()
# self.ax[1][1].clear()
# self.ax[0][0].set_xlim(min(x_data), max(x_data))
# self.ax[0][0].set_ylim(min(self.actions[-log_val:]), max(self.actions[-log_val:]))
# self.ax[0][0].plot(x_data, self.actions[-log_val:])
# self.ax[0][1].set_xlim(min(x_data), max(x_data))
# self.ax[0][1].set_ylim(min(self.vimp[-log_val:]), max(self.vimp[-log_val:]))
# self.ax[0][1].plot(x_data, self.vimp[-log_val:])
# self.ax[1][0].set_xlim(min(x_data), max(x_data))
# self.ax[1][0].set_ylim(min(self.imp[-log_val:]), max(self.imp[-log_val:]))
# self.ax[1][0].plot(x_data, self.imp[-log_val:])
# self.ax[1][1].set_xlim(min(x_data), max(x_data))
# self.ax[1][1].set_ylim(min(self.rewards[-log_val:]), max(self.rewards[-log_val:]))
# self.ax[1][1].plot(x_data, self.rewards[-log_val:])
# self.fig.canvas.draw()
# plt.pause(1e-40)
gym.register(id='SolarEnv-v1', entry_point=SolarEnv)