我正在尝试将 q-learning 应用于代表储能套利的自定义强化学习环境(用电池进行电力交易,价格低时充电,价格上涨时放电)。环境有效,但我无法对其应用 q-learning。环境下方是一个能够运行环境的脚本,但我不确定我应该将状态变量设为什么。关于如何应用 q-learning 来优化充电/放电循环的任何想法?重置功能从具有每小时电价的数据集开始第二天。数据框的图片如下。
类 BatteryEnv(gym.Env):
def __init__(self, df):
self.dict_actions = {0:'discharge',1:'charge',2:'wait'}
self.df = df
self.action_space = spaces.Discrete(3)
self.observation_space = spaces.Box(low=0, high=100, shape=(1,1))
self.reward_list = []
self.actual_load_list = []#observations
self.SOE_list=[] #State of energy
self.state_idx = 0 #iteration (hour of the day)
self.SOE = 0 #SOE
self.MAX_charge = 20 #C-rate kinda
self.Capacity =100
def step(self, action):
#mapping integer to action for actual load calculation
str_action = self.dict_actions[action]
#increase state idx within episode (1= 1 hour)
self.state_idx+=1
#calculating our actual load
if str_action == 'charge' and self.SOE < self.Capacity:
SOE_charge = np.clip(self.Capacity - self.SOE, 0, self.MAX_charge)
self.SOE += SOE_charge
obs = SOE_charge * self.df['prices'][self.state_idx]
elif str_action == 'discharge' and self.SOE > 0:
SOE_discharge = np.clip(self.SOE, 0, self.MAX_charge)
self.SOE -= SOE_discharge
obs = -SOE_discharge * self.df['prices'][self.state_idx]
else:
self.SOE += 0
obs = 0 * self.df['prices'][self.state_idx]
# appending actual load to list for monitoring and comparison purposes
self.actual_load_list.append(obs)
self.SOE_list.append(self.SOE)
#reward system
if obs<0: #if observation is positive we spending money. if negative we earning
reward =1
else:
reward =-1
# appending curr reward to list for monitoring and comparison purposes
self.reward_list.append(reward)
#checking whether our episode (day interval) ends
if self.df.iloc[self.state_idx,:].Daynum != self.df.iloc[self.state_idx-1].Daynum:
done = True
else:
done = False
return obs, reward, done
def reset(self):
return df.iloc[self.state_idx,:]
def render():
pass
以下代码能够表明环境正在运行。
for episode in range(7):
observation = env.reset()
for t in range(24): #can't be smaller than 24 as 24 time points equal to 1 episode (1 day)
#print(observation)
action = env.action_space.sample() #random actions
observation, reward, done = env.step(action)
if done:
print("Episode finished after {} timesteps".format(t+1)), print (observation), print(reward)
break