forked from wboag/Obstacles
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
executable file
·349 lines (280 loc) · 11.2 KB
/
agent.py
File metadata and controls
executable file
·349 lines (280 loc) · 11.2 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
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
####
#
# Agents
# Jake Kinsman
# 11/28/2014
#
####
###
# README:
#
# 1. If you want a dictionary with a default value (util.counters from UC Berkeley Problem Sets),
# use a defaultdict as shown: a = defaultdict(lambda: <DEFAULT-VALUE> )
#
# 2. Choose action should use your current model of the world (however you choose to store it),
# and compute the optimal action to be taken. If you are in a terminal state, the only action is "finish"
#
# 3. Update needs to perform whatever learning is needed to your model after each action is performed.
#
# 4. the gameworld variable passed to your agents methods should contain all information required to perform your computations.
#
# 5. Feel free to add more methods as needed! training the agents only calls the methods provided,
# and racing only calls chooseAction()
###
###
# GAMEWORLD FUNCTIONALITY:
# def getDiscount(self):
# returns discount factor [0,1)
# def getLivingReward(self):
# returns reward for staying alive
#
###
import random
from collections import defaultdict
from empiricalMDP import EmpiricalMDP
from valueIterationAgent import ValueIterationAgent
from policyIterationAgent import PolicyIterationAgent
def flipCoin( p ):
r = random.random()
return r < p
class agent(object):
def __init__(self):
self.rewardValues = { 'mountain':3, 'forest':4, 'water':4, 'grass':5 }
self.skillLevels = { 'mountain':1, 'forest':1, 'water':1, 'grass':1 }
self.index = None
self.state = None
def getSkill(self, skill):
return self.skillLevels[skill]
def getWaterSkill(self):
return self.getSkill('water')
def getGrassSkill(self):
return self.getSkill('grass')
def getForestSkill(self):
return self.getSkill('forest')
def getMountainSkill(self):
return self.getSkill('mountain')
def setSkill(self, skill, val):
self.skillLevels[skill] = val
def setWaterSkill(self, val):
self.setSkill('water', val)
def setGrassSkill(self, val):
self.setSkill('grass', val)
def setForestSkill(self, val):
self.setSkill('forest', val)
def setMountainSkill(self, val):
self.setSkill('mountain', val)
def __eq__(self, arg):
return arg.type == self.type and arg.index == self.index
def getIndex(self):
return self.index
def setIndex(self, value):
self.index = value
def getState(self):
return self.state
def setState(self, state):
self.state = state
def endTraining(self):
self.epsilon = 0.02
self.alpha = 1.
self.discount = 1.
class randomAgent(agent):
def __init__(self):
super(randomAgent, self).__init__()
self.type = "random"
def chooseAction(self, actions):
if flipCoin(0.08):
filteredActions = filter(lambda n: n == 'south' or n == 'west' or n == 'finish', actions)
if filteredActions == []: filteredActions = actions
else:
filteredActions = filter(lambda n: n == 'north' or n == 'east' or n == 'finish', actions)
return random.choice(filteredActions)
def update(self):
pass
class adpAgent(agent):
def __init__(self, gameworld, all_qstate_results, discount=0.5):
super(adpAgent, self).__init__()
self.type = "adp"
# Parameters
self.epsilon = 0.4
self.discount = discount
# Estimate of model
self.inferredSkills = { k:1 for k in ['water','grass','forest','mountain'] }
self.empirical_mdp = EmpiricalMDP(all_qstate_results, self.rewardValues, self.inferredSkills)
#print 'solving MDP'
self.solver = PolicyIterationAgent(self.empirical_mdp, discount=discount, iterations=10)
#print 'solved MDP'
#exit()
# Keep track of number of completed episodes
self.converged = False
self.completed = 0
self.nextUpdate = 1
def setEpsilon(self, epsilon):
self.epsilon = epsilon
def update(self, state, terrain, action, nextState, reward):
# If already converged, then skip update
if self.converged:
return
# update empirical MDP
self.empirical_mdp.update(state, action, nextState, reward, terrain)
# If converged AFTER most recent update, then solve MDP for final time
if self.empirical_mdp.converged():
#print str(self.completed) + ': final solving'
self.solver = self.solver = PolicyIterationAgent(self.empirical_mdp, discount=self.discount, iterations=50)
#print 'solved MDP'
self.converged = True
return
# If finished epsiode
if action == 'finish':
#print 'finished\n\n\n'
# Backoff how often you re-solve (speeds up training)
if self.completed == self.nextUpdate:
#print str(self.completed) + ': solving again'
self.solver = self.solver = PolicyIterationAgent(self.empirical_mdp, discount=self.discount, iterations=50)
#print 'solved MDP'
self.nextUpdate *= 2
self.completed += 1
def chooseAction(self, state):
###Your Code Here :)###
#return random.choice(filter(lambda a: (a=='north') or (a=='east') or (a=='finish'), self.empirical_mdp.getPossibleActions(state)))
if flipCoin(self.epsilon):
#print 'random'
return random.choice(self.empirical_mdp.getPossibleActions(state))
else:
#print 'policy'
return self.solver.getAction(state)
class tdAgent(agent):
def __init__(self, goalPosition, eps = 0.5, alp = 0.9, gam = 0.9):
super(tdAgent, self).__init__()
self.type = "td"
self.x, self.y = goalPosition
self.weights = dict()
self.qvalues = dict()
self.epsilon = eps
self.alpha = alp
self.discount = gam
self.its = 0
self.oldAct = None
###Your Code Here :)###
def __dirToVect(self, action):
if action == 'north':
return (0,-1)
elif action == 'south':
return (0,1)
elif action == 'east':
return (1,0)
elif action == 'west':
return (-1,0)
else:
return (0,0)
def __getFeatures(self, state, action):
x,y = state.getPosition()
dx, dy = self.__dirToVect(action)
next_x, next_y = x + dx, y + dy
dy = next_y - self.y + 1
dx = self.x - next_x + 1
norm = 1. / (dx + dy)
# print (x,y)
# if (x,y) == (8,0) or (x,y) == (9,1):
# print ((x,y), action), (dx, dy)
return dict({(state, action) : 1.})
if (x,y) != (float('inf'), float('inf')):
# feat = dict({state.getTerrainType() : .01})
# feat = dict({state : 1.})
feat = dict({'dy %d' %(dy) : 1.,
'dx %d' %(dx) : 1.,
'action %s' %(action) : 1.,
'world %d' %(state.getWorld()) : 1.,
state.getTerrainType() : 1.})
# feat = dict({'dy %d' %(dx) : norm,
# 'dx %d' %(dx): norm,
# state.getTerrainType() : .01})
# feat = dict({'dy %d' %(dy) : .1 / dy,
# 'dx %d' %(dx) : .1 / dx,
# 'action %s' %(action) : 1.,
# state.getTerrainType() : .01})
# feat = dict({'dy' : .1 / dy,
# 'dx' : .1 / dx,
# state.getTerrainType() : .01})
# feat = dict({'dy %d' %(dx) : .1**dy,
# 'dx %d' %(dx): .1**dx,
# state.getTerrainType() : .01})
#feat = dict({'dy %d' %(dy) : .1 / (dy * dy),
#'dx %d' %(dx): .1 / (dx * dx),
#state.getTerrainType() : .01})
else:
feat = dict({'finish' : 1000})
return feat
def computeValueFromQValues(self, state):
actions = self.getLegalActions(state)
if not actions:
return 0.0
return max(self.getQValue(state, action) for action in actions)
def getLegalActions(self, state):
return self.actions
def computeActionFromQValues(self, state):
actions = self.getLegalActions(state)
if not actions:
return None
# actvals = map(lambda action: self.getQValue(state, action) + random.uniform(0, .00001), actions)
actvals = map(lambda action: self.getQValue(state, action), actions)
# if len(frozenset(actvals)) == 1:
# print "all the same"
# elif not self.its % 1:
# print zip(actions, actvals)
return max(actions, key = lambda action: self.getQValue(state, action) + random.uniform(0,.00001))
def getAction(self, state):
return random.choice(self.getLegalActions(state)) if flipCoin(self.epsilon) else self.computeActionFromQValues(state)
# return random.choice(
# filter(
# lambda action: action not in ('west', 'south'),
# self.getLegalActions(state))
# ) if flipCoin(self.epsilon) else self.computeActionFromQValues(state)
def getQValue(self, state, action):
features = self.__getFeatures(state, action)
# print features
return sum(self.weights.get(feature,0.) * features[feature] for feature in features.keys())
def __printWeights(self):
for key, val in self.weights.items():
print key, val
print
def update(self, state, terrainType, action, nextState, reward, nextActions):
###Your Code Here :)###
DEBUG = 0
p = False if not DEBUG else not (self.its % 50000)
# p = True
self.its += 1
features = self.__getFeatures(state, action)
# self.actions = filter(lambda action : action not in ['west', 'south'], nextActions)
self.actions = nextActions
pos = state.getPosition()
qv = self.computeValueFromQValues(nextState)
difference = reward + \
self.discount * qv - \
self.getQValue(state, action)
#print features
#print reward
# print reward, difference, [(feature,
# self.weights.get(feature, 0.) + \
# self.alpha * difference * features[feature])
# for feature in features.keys()]
if p:
print
# print features
self.__printWeights()
# print reward, difference
self.weights.update((feature, self.weights.get(feature,0.) + \
self.alpha * difference * features[feature])
for feature in features.keys())
if p:
self.__printWeights()
print
def chooseAction(self, actions, state, terrainType):
###Your Code Here :)###
# self.actions = filter(lambda action : action not in ['west', 'south'], actions)
self.actions = actions
act = self.getAction(state)
self.oldAct = act
pos = state.getPosition()
#if pos == (8, 0) or pos == (9,1):# or not self.its % 1000:
# print state, act
return act