-
Notifications
You must be signed in to change notification settings - Fork 16
/
my_DQN.py
253 lines (205 loc) · 10.8 KB
/
my_DQN.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
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 23 23:13:03 2021
@author: yanzhenliu
"""
from DQN import DQN
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from data_structures.Replay_Buffer import Replay_Buffer
from exploration_strategies.OU_Noise_Exploration import OU_Noise_Exploration
from config import Config
from WMMSE import WMMSE
from Net_module import Net_dueling_DDQN
from Beamspace_channel import beamspace_channel
from data_structures.Prioritised_Replay_Buffer import Prioritised_Replay_Buffer
import scipy.io as scio
class my_DQN(DQN):
def __init__(self, config):
self.config = config
self.H = None
self.Hnp = None
self.Pmax = np.power(10,config.snr/10)
self.selected_beam = None
self.N = config.beam_num
self.M = config.M
self.K = config.K
self.M_bar = config.M_bar
self.L = config.path_num
self.hyperparameters = config.hyperparameters
self.H_number = config.H_number
self.Hnp_set = []
self.rate_list = []
self.benchmark_rate_list = []
self.beam_energy = None
self.H_set = self.create_Hset()
self.max_sinr = 0
self.turn_off_exploration = False
DQN.__init__(self, config)
self.memory = Prioritised_Replay_Buffer(self.hyperparameters, config.seed)
self.violation_counter = 0
self.store_loss = []
self.store_rate = []
self.store_value = []
self.action_value_temp = torch.zeros(config.action_size)
def create_NN(self, input_dim, output_dim):
net = Net_dueling_DDQN(input_dim, output_dim)
return net
def create_Hset(self):
"""Create channel set"""
H_set = []
for i in range(self.H_number):
Hnp = beamspace_channel(self.M, self.K, self.L)
self.Hnp_set.append(Hnp)
tempH = np.zeros([1, 3, self.M, self.K])
tempH[0, 0, ...] = Hnp.real
tempH[0, 1, ...] = Hnp.imag
tempH[0, 2, ...] = np.ones([self.M, self.K])
"""select the biggest M_bar beam"""
torchH = torch.from_numpy(tempH)
beam_energy = np.sum(np.square(np.abs(Hnp)), 1)
index = np.argsort(beam_energy)
cut_H = torchH[:,:,index[-self.M_bar:],:]
H = cut_H.float()
H_set.append(H)
return H_set
def run_n_episodes(self, num_episodes=None, save_and_print_results=True):
"""Runs game to completion n times and then summarises results and saves model (if asked to)"""
if num_episodes is None: num_episodes = self.config.num_episodes_to_run
while self.episode_number < num_episodes:
self.reset_game()
self.step()
if self.episode_number % 50 == 0:
print("Epoch:================")
print(self.episode_number)
temp = np.array(self.loss_array)
print(temp.mean())
self.store_loss.append(np.array(temp.mean()))
self.loss_array = []
if save_and_print_results: self.save_and_print_result()
print(np.array(self.benchmark_rate_list).mean())
print(self.violation_counter)
self.violation_counter = 0
self.store_rate.append(np.array(self.rate_list).mean())
self.rate_list = []
self.store_value.append(np.array(self.action_value_temp/50))
self.action_value_temp = torch.zeros(config.action_size)
if self.episode_number == 1000:
self.turn_off_exploration = True
if self.episode_number == 10000:
path01 = 'C:/Users/Administrator/Desktop/code_DDQN_DQN/result/DQN/loss'
scio.savemat(path01,{'loss':self.store_loss})
path02 = 'C:/Users/Administrator/Desktop/code_DDQN_DQN/result/DQN/rate'
scio.savemat(path02,{'rate':self.store_rate})
path03 = 'C:/Users/Administrator/Desktop/code_DDQN_DQN/result/DQN/value'
scio.savemat(path03,{'value':self.store_value})
return
def save_and_print_result(self):
torch.save(self.q_network_local.state_dict(), 'net_params_256_40dB_DQN.pkl')
print(np.array(self.rate_list).mean())
def learn(self):
"""Runs a learning iteration for the Q network after sampling from the replay buffer in a prioritised way"""
sampled_experiences, importance_sampling_weights = self.memory.sample()
states, actions, rewards, next_states, dones = sampled_experiences
loss, td_errors = self.compute_loss_and_td_errors(states, next_states, rewards, actions, dones, importance_sampling_weights)
self.loss_array.append(loss.item())
self.take_optimisation_step(self.q_network_optimizer, self.q_network_local, loss, self.hyperparameters["gradient_clipping_norm"])
self.memory.update_td_errors(td_errors.squeeze(1))
def save_experience(self):
"""Saves the latest experience including the td_error"""
max_td_error_in_experiences = self.memory.give_max_td_error() + 1e-9
self.memory.add_experience(max_td_error_in_experiences, self.state, self.action, self.reward, self.next_state, self.done)
def compute_loss_and_td_errors(self, states, next_states, rewards, actions, dones, importance_sampling_weights):
"""Calculates the loss for the local Q network. It weighs each observations loss according to the importance
sampling weights which come from the prioritised replay buffer"""
Q_targets = self.compute_q_targets(next_states, rewards, dones)
Q_expected = self.compute_expected_q_values(states, actions)
loss = F.mse_loss(Q_expected, Q_targets)
loss = loss * importance_sampling_weights
loss = torch.mean(loss)
td_errors = Q_targets.data.cpu().numpy() - Q_expected.data.cpu().numpy()
return loss, td_errors
def reset_game(self):
"""Resets the game information so we are ready to play a new episode"""
self.state = self.reset_environment()
self.next_state = None
self.action = None
self.reward = None
self.done = False
self.episode_rewards = []
self.episode_log_probabilities = []
self.episode_step_number = 0
self.selected_beam = torch.zeros(2,self.N,self.K)
def conduct_action(self):
"""picks the beam selected"""
self.next_state = self.state.clone()
self.next_state [0,2,self.action,:] = torch.zeros(1,self.K)
self.selected_beam[:,self.episode_step_number-1,:] = self.state[0,0:2,self.action,:]
self.reward = self.compute_reward()
def compute_reward(self):
"""computes the reward brought by the action"""
if self.episode_step_number < self.N:
rate = 0
reward = self.selected_beam_sinr(self.selected_beam[:,self.episode_step_number-1,:])*0
reward += self.beam_energy[self.action]/self.beam_energy[-1]*20
if self.episode_step_number > self.N*0.63:
reward += self.average_user_energy_reward()
#reward = self.selected_beam[:,self.episode_step_number-1,:].norm()-self.H.norm()/self.M
#reward = 0
else:
rate = WMMSE(self.selected_beam,self.Pmax,1)
self.rate_list.append(rate) #save the rate
reward = rate + self.selected_beam_sinr(self.selected_beam[:,self.episode_step_number-1,:])*0 #- self.average_sinr
reward += self.beam_energy[self.action] / self.beam_energy[-1] * 20
reward += self.average_user_energy_reward()
self.done = True
if self.state[0,2,self.action,0] == 0:
reward = rate - 50
self.violation_counter += 1
return reward
def average_user_energy_reward(self):
abs_total_selected_beam = torch.pow(self.selected_beam[0, 0:self.episode_step_number,:], 2) + torch.pow(self.selected_beam[1, 0:self.episode_step_number, :], 2)
current_total_user_energy = abs_total_selected_beam.sum(0)
selected_beam_energy = torch.pow(self.selected_beam[0, self.episode_step_number-1,:], 2) + torch.pow(self.selected_beam[1, self.episode_step_number-1, :], 2)
division = selected_beam_energy/(current_total_user_energy+0.1)
rectified_reward = 0
for i in range(self.K):
if (current_total_user_energy[i]- selected_beam_energy[i])< 0.2 and division[i] >0.5:
rectified_reward += division[i]*6
return rectified_reward
def reset_environment(self):
self.H = self.H_set[self.episode_number % self.H_number]
self.Hnp = self.Hnp_set[self.episode_number % self.H_number]
self.beam_energy = self.compute_beam_energy(self.H)
if self.episode_number<self.H_number:
self.compute_bench_rate()
#self.max_sinr = self.compute_max_sinr(self.H)
return self.H.clone()
def compute_beam_energy(self,H):
absH = torch.pow(H[0, 0, :, :], 2) + torch.pow(H[0, 1, :, :], 2)
beam_energy = absH.sum(1)
return beam_energy
def compute_bench_rate(self):
bench_H = self.H[0,0:2,-self.N:,:]
bench_rate = WMMSE(bench_H, self.Pmax, 1)
self.benchmark_rate_list.append(bench_rate)
def selected_beam_sinr(self,beam):
sinr = 0
sum_beam_power = torch.pow(beam.norm(),2)
for i in range(self.K):
power = torch.pow(beam[:,i].norm(),2)
sinr += power/(sum_beam_power - power + 0.1)
return torch.log2(1+sinr)
def compute_max_sinr(self,H):
sinr_list = []
for i in range(self.M_bar):
beam_sinr = self.selected_beam_sinr(H[0, 0:2, i, :])
sinr_list.append(beam_sinr)
return max(sinr_list)
if __name__ == "__main__":
config = Config()
agent = my_DQN(config)
agent.run_n_episodes(num_episodes=config.num_episodes_to_run)