-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgent.py
More file actions
299 lines (235 loc) · 9.88 KB
/
Copy pathAgent.py
File metadata and controls
299 lines (235 loc) · 9.88 KB
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
import random
import sys
import copy
import operator
from Observation import *
from Reward import *
from Action import *
from Environment import *
from random import Random
class Agent:
# Random generator
randGenerator=Random()
# Remember last action
lastAction=Action()
# Remember last observation (state)
lastObservation=Observation()
# Q-learning stuff: Step size, epsilon, gamma, learning rate
stepsize = 0.1
epsilon = 0.5
gamma = 0.9
learningRate = 0.5
# Value table
v_table = None
# The environment
gridEnvironment = None
#Initial observation
initialObs = None
#Current observation
currentObs = None
# The environment will run for no more than this many steps
numSteps = 500
# Total reward
totalReward = 0.0
# action trace
trace = []
# agent memory. A list of traces. Memory is not ever reset.
memory = []
# Print debugging statements
verbose = True
# Number of actions in the environment
numActions = 5
# Constructor, takes a reference to an Environment
def __init__(self, env):
# Initialize value table
self.v_table={}
# Set dummy action and observation
self.lastAction=Action()
self.lastObservation=Observation()
# Set the environment
self.gridEnvironment = env
# Get first observation and start the environment
self.initialObs = self.gridEnvironment.env_start()
self.initializeInitialObservation(env)
def initializeInitialObservation(self, env):
if self.calculateFlatState(self.initialObs.worldState) not in self.v_table.keys():
self.v_table[self.calculateFlatState(self.initialObs.worldState)] = self.numActions*[0.0]
# Once learning is done, use this to run the agent
# observation is the initial observation
def executePolicy(self, observation):
# Start the counter
count = 0
# reset total reward
self.totalReward = 0.0
# Copy the initial observation
self.workingObservation = self.copyObservation(observation)
# Make sure the value table has the starting observation
if self.calculateFlatState(self.workingObservation.worldState) not in self.v_table.keys():
self.v_table[self.calculateFlatState(self.workingObservation.worldState)] = self.numActions*[0.0]
if self.verbose:
print("START")
# While a terminal state has not been hit and the counter hasn't expired, take the best action for the current state
while not self.workingObservation.isTerminal and count < self.numSteps:
newAction = Action()
# Get the best action for this state
newAction.actionValue = self.greedy(self.workingObservation)
# Store the action
self.trace.append((self.workingObservation, newAction))
if self.verbose:
print self.gridEnvironment.actionToString(newAction.actionValue)
# execute the step and get a new observation and reward
currentObs, reward = self.gridEnvironment.env_step(newAction)
# update the value table
if self.calculateFlatState(currentObs.worldState) not in self.v_table.keys():
self.v_table[self.calculateFlatState(currentObs.worldState)] = self.numActions*[0.0]
self.totalReward = self.totalReward + reward.rewardValue
self.workingObservation = copy.deepcopy(currentObs)
# increment counter
count = count + 1
if self.verbose:
print("END")
# replay a specific memory trace
def replayMemory(self, observation, activeTrace):
# copy the initial observation
self.workingObservation = self.copyObservation(observation)
self.totalReward = 0.0
count = 0
lastAction = -1
while not self.workingObservation.isTerminal and count < self.numSteps:
# Get the next action from the memory trace
currentTraceItem = activeTrace.pop(0)
nextTraceItem = None
if len(activeTrace) > 0:
nextTraceItem = activeTrace[0] #if this is the end of the trace, there is no next
newAction = currentTraceItem[1]
if self.verbose:
print "action", newAction.actionValue
lastAction = newAction.actionValue
# Get the new state and reward from the environment
currentObs, reward = self.gridEnvironment.env_step(newAction)
# if new observation doesn't match the expected next observation, terminate
if nextTraceItem is not None and currentObs.worldState != nextTraceItem[0].worldState:
if self.verbose:
print "replay failed", currentObs.worldState, "!=", nextTraceItem[0].worldState
return
rewardValue = reward.rewardValue
#update value table
if self.calculateFlatState(currentObs.worldState) not in self.v_table.keys():
self.v_table[self.calculateFlatState(currentObs.worldState)] = self.numActions*[0.0]
lastFlatState = self.calculateFlatState(self.workingObservation.worldState[:])
newFlatState = self.calculateFlatState(currentObs.worldState[:])
if not currentObs.isTerminal:
Q_sa=self.v_table[lastFlatState][newAction.actionValue]
Q_sprime_aprime=self.v_table[newFlatState][self.returnMaxIndex(currentObs)]
new_Q_sa=Q_sa + self.stepsize * (rewardValue + self.gamma * Q_sprime_aprime - Q_sa)
self.v_table[lastFlatState][lastAction]=new_Q_sa
else:
Q_sa=self.v_table[lastFlatState][lastAction]
new_Q_sa=Q_sa + self.stepsize * (rewardValue - Q_sa)
self.v_table[lastFlatState][lastAction] = new_Q_sa
# increment counter
count = count + 1
self.workingObservation = self.copyObservation(currentObs)
# increment total reward
self.totalReward = self.totalReward + reward.rewardValue
# Done learning, reset environment
self.gridEnvironment.env_reset()
# q-learning implementation
# observation is the initial observation
def qLearn(self, observation):
# copy the initial observation
self.workingObservation = self.copyObservation(observation)
# start the counter
count = 0
lastAction = -1
# reset total reward
self.totalReward = 0.0
# while terminal state not reached and counter hasn't expired, use epsilon-greedy search
while not self.workingObservation.isTerminal and count < self.numSteps:
# Make sure table is populated correctly
if self.calculateFlatState(self.workingObservation.worldState) not in self.v_table.keys():
self.v_table[self.calculateFlatState(self.workingObservation.worldState)] = self.numActions*[0.0]
# Take the epsilon-greedy action
newAction = Action()
newAction.actionValue = self.egreedy(self.workingObservation)
lastAction = newAction.actionValue
# Get the new state and reward from the environment
currentObs, reward = self.gridEnvironment.env_step(newAction)
rewardValue = reward.rewardValue
# Make sure table is populated correctly
if self.calculateFlatState(currentObs.worldState) not in self.v_table.keys():
self.v_table[self.calculateFlatState(currentObs.worldState)] = self.numActions*[0.0]
# update the value table
if self.calculateFlatState(currentObs.worldState) not in self.v_table.keys():
self.v_table[self.calculateFlatState(currentObs.worldState)] = self.numActions*[0.0]
lastFlatState = self.calculateFlatState(self.workingObservation.worldState)
newFlatState = self.calculateFlatState(currentObs.worldState)
if not currentObs.isTerminal:
Q_sa=self.v_table[lastFlatState][newAction.actionValue]
Q_sprime_aprime=self.v_table[newFlatState][self.returnMaxIndex(currentObs)]
new_Q_sa=Q_sa + self.stepsize * (rewardValue + self.gamma * Q_sprime_aprime - Q_sa)
self.v_table[lastFlatState][lastAction]=new_Q_sa
else:
Q_sa=self.v_table[lastFlatState][lastAction]
new_Q_sa=Q_sa + self.stepsize * (rewardValue - Q_sa)
self.v_table[lastFlatState][lastAction] = new_Q_sa
# increment counter
count = count + 1
self.workingObservation = self.copyObservation(currentObs)
# increment total reward
self.totalReward = self.totalReward + reward.rewardValue
# Done learning, reset environment
self.gridEnvironment.env_reset()
def returnMaxIndex(self, observation):
flatState = self.calculateFlatState(observation.worldState)
actions = observation.availableActions
qValueArray = []
qValueIndexArray = []
for i in range(len(actions)):
qValueArray.append(self.v_table[flatState][actions[i]])
qValueIndexArray.append(actions[i])
return qValueIndexArray[qValueArray.index(max(qValueArray))]
# Return the best action according to the policy, or a random action epsilon percent of the time
def egreedy(self, observation):
maxIndex=0
actualAvailableActions = []
for i in range(len(observation.availableActions)):
actualAvailableActions.append(observation.availableActions[i])
if self.randGenerator.random() < self.epsilon:
randNum = self.randGenerator.randint(0,len(actualAvailableActions)-1)
return actualAvailableActions[randNum]
else:
v_table_values = []
flatState = self.calculateFlatState(observation.worldState)
for i in actualAvailableActions:
v_table_values.append(self.v_table[flatState][i])
return actualAvailableActions[v_table_values.index(max(v_table_values))]
# Return the best action according to the policy
def greedy(self, observation):
actualAvailableActions = []
for i in range(len(observation.availableActions)):
actualAvailableActions.append(observation.availableActions[i])
v_table_values = []
flatState = self.calculateFlatState(observation.worldState)
for i in actualAvailableActions:
v_table_values.append(self.v_table[flatState][i])
return actualAvailableActions[v_table_values.index(max(v_table_values))]
# Reset the agent
def agent_reset(self):
self.lastAction = Action()
self.lastObservation = Observation()
self.initialObs = self.gridEnvironment.env_start()
self.trace = []
# Create a copy of the observation
def copyObservation(self, obs):
returnObs = Observation()
if obs.worldState != None:
returnObs.worldState = obs.worldState[:]
if obs.availableActions != None:
returnObs.availableActions = obs.availableActions[:]
if obs.isTerminal != None:
returnObs.isTerminal = obs.isTerminal
return returnObs
# Turn the state into a tuple for bookkeeping
def calculateFlatState(self, theState):
return tuple(theState)