forked from intelligent-environments-lab/CityLearn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.py
250 lines (199 loc) · 11.2 KB
/
agent.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
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import random
import copy
class Buffer:
def __init__(self):
self.buffer = []
def append_sample(self, sample):
self.buffer.append(sample)
def sample(self, sample_size):
s, a, r, s_next, done = [],[],[],[],[]
if sample_size > len(self.buffer):
sample_size = len(self.buffer)
rand_sample = random.sample(self.buffer, sample_size)
for values in rand_sample:
s.append(values[0])
a.append(values[1])
r.append(values[2])
s_next.append(values[3])
done.append([4])
return torch.tensor(s,dtype=torch.float32), torch.tensor(a,dtype=torch.float32), torch.tensor(r,dtype=torch.float32), torch.tensor(s_next,dtype=torch.float32), done
def __len__(self):
return len(self.buffer)
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(Actor, self).__init__()
self.l1 = nn.Linear(state_dim, 5)
self.l2 = nn.Linear(5, 3)
self.l3 = nn.Linear(3, action_dim)
self.max_action = max_action
def forward(self, state):
a = F.relu(self.l1(state))
a = F.relu(self.l2(a))
return self.max_action * torch.tanh(self.l3(a))
class Critic(nn.Module):
def __init__(self, state_dim, action_dim):
super(Critic, self).__init__()
# Q1 architecture
self.l1 = nn.Linear(state_dim + action_dim, 7)
self.l2 = nn.Linear(7, 6)
self.l3 = nn.Linear(6, 1)
# Q2 architecture
self.l4 = nn.Linear(state_dim + action_dim, 7)
self.l5 = nn.Linear(7, 6)
self.l6 = nn.Linear(6, 1)
def forward(self, state, action):
sa = torch.cat([state, action], 1)
q1 = F.relu(self.l1(sa))
q1 = F.relu(self.l2(q1))
q1 = self.l3(q1)
q2 = F.relu(self.l4(sa))
q2 = F.relu(self.l5(q2))
q2 = self.l6(q2)
return q1, q2
def Q1(self, state, action):
sa = torch.cat([state, action], 1)
q1 = F.relu(self.l1(sa))
q1 = F.relu(self.l2(q1))
q1 = self.l3(q1)
return q1
class RL_Agents:
def __init__(self, building_info, observation_spaces = None, action_spaces = None):
#Hyper-parameters
self.discount = 0.992 #Discount factor
self.batch_size = 100 #Size of each MINI-BATCH
self.iterations = 1 # Number of updates of the actor-critic networks every time-step
self.policy_freq = 2 # Number of iterations after which the actor and target networks are updated
self.tau = 5e-3 #Rate at which the target networks are updated
self.lr_init = 1e-3 #5e-2
self.lr_final = 1e-3 #3e-3
self.lr_decay_rate = 1/(78*8760)
self.expl_noise_init = 0.75 # Exploration noise at time-step 0
self.expl_noise_final = 0.01 # Magnitude of the minimum exploration noise
self.expl_noise_decay_rate = 1/(290*8760) # Decay rate of the exploration noise in 1/h
self.policy_noise = 0.025*0
self.noise_clip = 0.04*0
self.max_action = 0.25
self.min_samples_training = 400 #Min number of tuples that are stored in the batch before the training process begins
# Parameters
self.device = "cpu"
self.time_step = 0
self.building_info = building_info # Can be used to create different RL agents based on basic building attributes or climate zones
self.observation_spaces = observation_spaces
self.action_spaces = action_spaces
self.n_buildings = len(observation_spaces)
self.buffer = {i: Buffer() for i in range(self.n_buildings)}
self.networks_initialized = False
# Monitoring variables (one per agent)
self.actor_loss_list = {i: [] for i in range(self.n_buildings)}
self.critic1_loss_list = {i: [] for i in range(self.n_buildings)}
self.critic2_loss_list = {i: [] for i in range(self.n_buildings)}
self.q_val_list = {i: [] for i in range(self.n_buildings)}
self.q1_list = {i: [] for i in range(self.n_buildings)}
self.q2_list = {i: [] for i in range(self.n_buildings)}
self.a_track1 = []
self.a_track2 = []
#Networks and optimizers (one per agent)
self.actor, self.critic, self.actor_target, self.critic_target, self.actor_optimizer, self.critic_optimizer = {}, {}, {}, {}, {}, {}
for i, (o, a) in enumerate(zip(observation_spaces, action_spaces)):
self.actor[i] = Actor(o.shape[0], a.shape[0], self.max_action).to(self.device)
self.critic[i] = Critic(o.shape[0], a.shape[0]).to(self.device)
self.actor_target[i] = copy.deepcopy(self.actor[i])
self.critic_target[i] = copy.deepcopy(self.critic[i])
self.actor_optimizer[i] = optim.Adam(self.actor[i].parameters(), lr=self.lr_init)
self.critic_optimizer[i] = optim.Adam(self.critic[i].parameters(), lr=self.lr_init)
def select_action(self, states):
expl_noise = max(self.expl_noise_final, self.expl_noise_init * (1 - self.time_step * self.expl_noise_decay_rate))
actions = []
for i, state in enumerate(states):
a = self.actor[i](torch.tensor(state, dtype=torch.float32))
self.a_track1.append(a)
a = a.cpu().detach().numpy() + expl_noise * np.random.normal(loc = 0, scale = self.max_action, size=a.shape)
self.a_track2.append(a)
a = np.clip(a, -self.max_action, self.max_action)
actions.append(a)
return actions
def add_to_buffer(self, states, actions, rewards, next_states, dones):
# Information contained in the building_info variable can be used to choose the number of buffers and what information goes to each buffer
dones = [dones for _ in range(self.n_buildings)]
for i, (s, a, r, s_next, done) in enumerate(zip(states, actions, rewards, next_states, dones)):
s = (s - self.observation_spaces[i].low)/(self.observation_spaces[i].high - self.observation_spaces[i].low + 0.00001)
s_next = (s_next - self.observation_spaces[i].low)/(self.observation_spaces[i].high - self.observation_spaces[i].low + 0.00001)
self.buffer[i].append_sample((s, a, r, s_next, done))
lr = max(self.lr_final, self.lr_init * (1 - self.time_step * self.lr_decay_rate))
for i in range(self.n_buildings):
self.actor_optimizer[i] = optim.Adam(self.actor[i].parameters(), lr=lr)
self.critic_optimizer[i] = optim.Adam(self.critic[i].parameters(), lr=lr)
#One TD3 control agent for each building
for i in range(self.n_buildings):
#Learning begins when a minimum number of tuples have beena added to the buffer
if len(self.buffer[i]) > self.min_samples_training:
#Every time-step we randomly sample 'self.iterations' number of minibatches from the buffer of experiences and perform 'self.iterations' number of updates of the networks.
for k in range(self.iterations):
state, action, reward, next_state, dones_mask = self.buffer[i].sample(self.batch_size)
target_Q = reward.unsqueeze(dim=-1)
with torch.no_grad():
noise = (torch.randn_like(action) * self.policy_noise).clamp(-self.noise_clip, self.noise_clip)
# Select action according to policy
next_action = (self.actor_target[i](next_state) + noise).clamp(-self.max_action, self.max_action)
# Compute the target Q value
target_Q1, target_Q2 = self.critic_target[i](next_state, next_action)
target_Q = torch.min(target_Q1, target_Q2)
target_Q = reward.unsqueeze(dim=-1) + target_Q * self.discount
# Get current Q estimates
current_Q1, current_Q2 = self.critic[i](state, action)
# Compute critic loss
critic1_loss = F.mse_loss(current_Q1, target_Q)
critic2_loss = F.mse_loss(current_Q2, target_Q)
critic_loss = critic1_loss + critic2_loss
# Optimize the critic
self.critic_optimizer[i].zero_grad()
critic_loss.backward()
self.critic_optimizer[i].step()
# Save values
self.q_val_list[i].append(target_Q)
self.q1_list[i].append(current_Q1)
self.q2_list[i].append(current_Q2)
self.critic1_loss_list[i].append(critic1_loss)
self.critic2_loss_list[i].append(critic2_loss)
# Delayed policy updates
if k % self.policy_freq == 0:
# Compute actor loss
actor_loss = -self.critic[i].Q1(state, self.actor[i](state)).mean()
self.actor_loss_list[i].append(actor_loss)
# Optimize the actor
self.actor_optimizer[i].zero_grad()
actor_loss.backward()
self.actor_optimizer[i].step()
# Update the frozen target models
for param, target_param in zip(self.critic[i].parameters(), self.critic_target[i].parameters()):
target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)
for param, target_param in zip(self.actor[i].parameters(), self.actor_target[i].parameters()):
target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)
self.time_step += 1
class RBC_Agent:
def __init__(self, actions_spaces):
self.actions_spaces = actions_spaces
self.reset_action_tracker()
def reset_action_tracker(self):
self.action_tracker = []
def select_action(self, states):
hour_day = states[0][0]
# Daytime: release stored energy
a = [[0.0 for _ in range(len(self.actions_spaces[i].sample()))] for i in range(len(self.actions_spaces))]
if hour_day >= 9 and hour_day <= 21:
a = [[-0.08 for _ in range(len(self.actions_spaces[i].sample()))] for i in range(len(self.actions_spaces))]
# Early nightime: store DHW and/or cooling energy
if (hour_day >= 1 and hour_day <= 8) or (hour_day >= 22 and hour_day <= 24):
a = []
for i in range(len(self.actions_spaces)):
if len(self.actions_spaces[i].sample()) == 2:
a.append([0.091, 0.091])
else:
a.append([0.091])
self.action_tracker.append(a)
return np.array(a)