/
featureExtractors.py
369 lines (307 loc) · 10.4 KB
/
featureExtractors.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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# featureExtractors.py
# --------------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
import util
import numpy.linalg
import numpy as np
import humanWorld
import warnings
from game import Actions
class FeatureExtractor:
def getFeatures(self, state, action):
"""
Returns a dict from features to counts
Usually, the count will just be 1.0 for
indicator functions.
"""
util.raiseNotDefined()
class IdentityExtractor(FeatureExtractor):
def getFeatures(self, state, action):
feats = util.Counter()
feats[(state,action)] = 1.0
return feats
class ContinousRadiusLogExtractor(FeatureExtractor):
"""
An feature extractor for the ContinuousWorld
"""
def __init__(self, mdp, label):
self.mdp = mdp
self.label = label
def getFeatures(self, state, action):
feats = util.Counter()
loc, orient = state
newLoc, newOrient = self.mdp.getTransitionStatesAndProbs(state, action)[0][0]
if self.label == 'segs':
if len(self.mdp.objs['segs']) > 0:
minObj = self.mdp.objs['segs'][0]
minDist = numpy.linalg.norm(np.subtract(loc, minObj))
else:
minObj = loc; minDist = np.inf
else:
[minObj, minDist] = getClosestObj(newLoc, self.mdp.objs[self.label])
if minDist == np.inf:
return None
else:
feats['dist'] = np.log(1 + minDist)
feats['bias'] = 1
return feats
class HumanViewExtractor(ContinousRadiusLogExtractor):
"""
Feature extractors for the HumanWorld
"""
def __init__(self, mdp, label):
ContinousRadiusLogExtractor.__init__(self, mdp, label)
# enable then add squared term for angle
# keep the label for convenience
self.label = label
def getFeatures(self, state, action):
"""
This has to assume that the transition is known.
"""
newState = self.mdp.getTransitionStatesAndProbs(state, action)[0][0]
return self.getStateFeatures(newState)
def getStateFeatures(self, state):
feats = util.Counter()
loc, orient = state
if self.label == 'segs':
# rubber band
# get features for waypoints
if len(self.mdp.objs['segs']) > 1:
obj = self.mdp.objs['segs'][1] # look at the NEXT waypoint
curObj = self.mdp.objs['segs'][0]
elif len(self.mdp.objs['segs']) == 1:
obj = curObj = self.mdp.objs['segs'][0] # this is the last segment
else:
obj = curObj = None
feats['dist'], feats['angle'] = getDistAngle(loc, obj, orient)
feats['curDist'], feats['curAngle'] = getDistAngle(loc, curObj, orient)
else:
# get features for targets / objects
# get both closest and the second closest -- may not be both used though
l = getSortedObjs(loc, self.mdp.objs[self.label])
if len(l) > 0:
minObj = l[0]
else:
minObj = None
if len(l) > 1:
# if there are more than two objects
secMinObj = l[1]
else:
secMinObj = None
feats['dist'], feats['angle'] = getDistAngle(loc, minObj, orient)
feats['dist2'], feats['angle2'] = getDistAngle(loc, secMinObj, orient)
feats['bias'] = 1
return feats
def getHumanContinuousMapper(mdp):
"""
Return ((targDist, targAngle)*2, (obstDist, obstAngle)*2, (segDist, segAngle)*2)
"""
extractors = [HumanViewExtractor(mdp, label) for label in ['targs', 'obsts', 'segs']]
def getDistAngelList(state, action):
ret = []
for extractor in extractors:
feats = extractor.getStateFeatures(state)
ret.append((feats['dist'], feats['angle']))
if extractor.label != 'segs':
ret.append((feats['dist2'], feats['angle2']))
else:
ret.append((feats['curDist'], feats['curAngle']))
return (ret, action)
return getDistAngelList
def getHumanDiscreteMapper(mdp, category = None):
"""
Return ((targDist, targAngle)_1^2, (obstDist, obstAngle)_1^2, (segDist, segAngle)) and action
"""
if category == None:
# assume need all the classes
extractors = [HumanViewExtractor(mdp, label) for label in ['targs', 'obsts', 'segs']]
else:
extractors = [HumanViewExtractor(mdp, category)]
def getDistAngelList(state, action):
states = []
for extractor in extractors:
feats = extractor.getStateFeatures(state)
state, action = discreteQTableCompressor((feats['dist'], feats['angle']), action)
states.append(state)
if not extractor.label == 'segs':
# add second closest objects
if feats['dist2'] != None and feats['angle2'] != None:
state, action = discreteQTableCompressor((feats['dist2'], feats['angle2']), action)
states.append(state)
else:
states.append((None, None))
return (states, action)
if category != None:
uncoupleState = lambda (s, a): (s[0], a)
ret = lambda s, a: uncoupleState(getDistAngelList(s, a))
else:
ret = getDistAngelList
return ret
def gridGetNext(mdp, state, action):
# simulate the next state
x, y = state
dx, dy = Actions.directionToVector(action)
next_x, next_y = int(x + dx), int(y + dy)
if next_x < 0 or next_x >= mdp.grid.width:
next_x = x
if next_y < 0 or next_y >= mdp.grid.height:
next_y = y
return [next_x, next_y]
def getGridMapper(mdp):
moduleClasses = map(lambda _: _[0], mdp.spec)
def getDists(state, action):
"""
Compute a Q value responding to an object, considering the distance to it.
This is used by obstacle avoidance, and target obtaining.
Args:
r: the reward of the module class to be found
idx: the id of the class
"""
states = []
x, y = state
# find the distance to the nearest object
for moduleClass in moduleClasses:
dists = []
for xt in range(mdp.grid.width):
for yt in range(mdp.grid.height):
cell = mdp.grid[xt][yt]
if cell == moduleClass:
dist = np.sqrt((xt - x) ** 2 + (yt - y) ** 2)
dists.append(dist)
states.append(dists)
return (states, action)
return getDists
def discreteQTableCompressor(state, action):
dist, angle = state
if dist == None or angle == None:
return state
newAction = action
if action == 'G':
# force table to be symmetric
angle = abs(angle)
elif action == 'L':
# use R table
angle = -angle
newAction = 'R'
elif action == 'SL':
# use SR table
angle = -angle
newAction = 'SR'
newState = mapStateToBin((dist, angle))
return (newState, newAction)
"""
Some util functions for feature extraction.
"""
def getClosestObj(loc, l):
"""
Args:
loc: location of the agent
l: list of objects
"""
minDist = np.inf
minObj = loc
for obj in l:
dist = numpy.linalg.norm(np.subtract(loc, obj))
if dist < minDist:
minDist = dist
minObj = obj
return [minObj, minDist]
def getProjectionToSegment(loc, segs):
"""
Compute the projection from loc to the segment with vertices of seg0 and seg1
"""
if len(segs) == 0:
return [loc, np.inf]
elif len(segs) == 1:
seg = segs[0]
return [seg, numpy.linalg.norm(np.subtract(loc, seg))]
else:
# FIXME better way to compute projection?
from shapely.geometry import LineString, Point
segVec = np.subtract(segs[1], segs[0])
line = LineString([np.add(segs[0], - 100 * segVec), np.add(segs[0], 100 * segVec)])
p = Point(loc)
interceptPoint = line.interpolate(line.project(p))
intercept = (interceptPoint.x, interceptPoint.y)
return intercept
def getProjectionToSegmentLocalView(s0, s1):
"""
If we only have distance, angle to the segments, use this function.
This will call getProjectionToSegment.
"""
loc = (0, 0)
segs = [(dist * np.cos(orient), dist * np.sin(orient)) for (dist, orient) in [s0, s1]]
obj = getProjectionToSegment(loc, segs)
return getDistAngle(loc, obj, 0)
def getDistAngle(f, t, orient):
if t == None:
return (None, None)
else:
vector = np.subtract(t, f)
dist = numpy.linalg.norm(vector)
objOrient = np.angle(vector[0] + vector[1] * 1j)
return [dist, adjustAngle(objOrient - orient)]
def getSortedObjs(loc, l):
"""
Sort l out-of-place wrt the distance to loc
"""
newl = list(l)
newl.sort(key = lambda obj : numpy.linalg.norm(np.subtract(loc, obj)))
return newl
def adjustAngle(angle):
while angle < - np.pi:
angle += 2 * np.pi
while angle > np.pi:
angle -= 2 * np.pi
return angle
distances = [.1, .2, .3, .5, .75, 1, 1.5, 2, 2.5, 10]
angles = [-90, -60, -30, -10, -5, -2, 0, 2, 5, 10, 30, 60, 90, 181] # human readable
# original setting
"""
distances = map(lambda _: _ * humanWorld.HumanWorld.step, [.5, 1, 1.5, 2, 2.5, 3, 4, 10])
angles = [-135, -90, -60, -30, -20, -10, 0, 10, 20, 30, 60, 90, 135, 180]
"""
anglesArc = map(lambda x: 1.0 * x / 180 * np.pi, angles)
def mapStateToBin((dist, angle)):
if dist == None or angle == None:
return (dist, angle)
distBin = len(distances)
for idx in xrange(len(distances)):
if dist < distances[idx]:
distBin = idx
break
angleBin = len(distances)
for idx in xrange(len(anglesArc)):
if angle < anglesArc[idx]:
angleBin = idx
break
if distBin == len(distances):
warnings.warn("distance too long: " + str(dist))
if angleBin == len(angles):
raise Exception('observing unexpected angle of ' + str(angle))
return (distBin, angleBin)
def binsGaussianKernel(key):
"""
Discrete approximation of gausian kernel.
key -> {key : weight}
"""
(distBin, angleBin), action = key
retSet = util.Counter()
retSet[key] = 4
# don't worry about edges
if distBin > 0 and distBin < len(distances) - 1 and angleBin > 0 and angleBin < len(angles) - 1:
retSet[(distBin - 1, angleBin), action] = 2
retSet[(distBin + 1, angleBin), action] = 2
retSet[(distBin, angleBin - 1), action] = 2
retSet[(distBin, angleBin + 1), action] = 2
retSet[(distBin - 1, angleBin - 1), action] = 1
retSet[(distBin - 1, angleBin + 1), action] = 1
retSet[(distBin + 1, angleBin - 1), action] = 1
retSet[(distBin + 1, angleBin + 1), action] = 1
normalizer = sum(retSet.values())
normedRetSet = {key: 1.0 * value / normalizer for key, value in retSet.items()}
return normedRetSet