/
inference.py
378 lines (299 loc) · 14.6 KB
/
inference.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
370
371
372
373
374
375
376
377
# inference.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 random
import busters
import game
class InferenceModule:
"""
An inference module tracks a belief distribution over a ghost's location.
This is an abstract class, which you should not modify.
"""
############################################
# Useful methods for all inference modules #
############################################
def __init__(self, ghostAgent):
"Sets the ghost agent for later access"
self.ghostAgent = ghostAgent
self.index = ghostAgent.index
def getPositionDistribution(self, gameState):
"""
Returns a distribution over successor positions of the ghost from the given gameState.
You must first place the ghost in the gameState, using setGhostPosition below.
"""
ghostPosition = gameState.getGhostPosition(self.index) # The position you set
actionDist = self.ghostAgent.getDistribution(gameState)
dist = util.Counter()
for action, prob in actionDist.items():
successorPosition = game.Actions.getSuccessor(ghostPosition, action)
dist[successorPosition] = prob
return dist
def setGhostPosition(self, gameState, ghostPosition):
"""
Sets the position of the ghost for this inference module to the specified
position in the supplied gameState.
"""
conf = game.Configuration(ghostPosition, game.Directions.STOP)
gameState.data.agentStates[self.index] = game.AgentState(conf, False)
return gameState
def observeState(self, gameState):
"Collects the relevant noisy distance observation and pass it along."
distances = gameState.getNoisyGhostDistances()
if len(distances) >= self.index: # Check for missing observations
obs = distances[self.index - 1]
self.observe(obs, gameState)
def initialize(self, gameState):
"Initializes beliefs to a uniform distribution over all positions."
# The legal positions do not include the ghost prison cells in the bottom left.
self.legalPositions = [p for p in gameState.getWalls().asList(False) if p[1] > 1]
self.initializeUniformly(gameState)
######################################
# Methods that need to be overridden #
######################################
def initializeUniformly(self, gameState):
"Sets the belief state to a uniform prior belief over all positions."
pass
def observe(self, observation, gameState):
"Updates beliefs based on the given distance observation and gameState."
pass
def elapseTime(self, gameState):
"Updates beliefs for a time step elapsing from a gameState."
pass
def getBeliefDistribution(self):
"""
Returns the agent's current belief state, a distribution over
ghost locations conditioned on all evidence so far.
"""
pass
class ExactInference(InferenceModule):
"""
The exact dynamic inference module should use forward-algorithm
updates to compute the exact belief function at each time step.
"""
def initializeUniformly(self, gameState):
"Begin with a uniform distribution over ghost positions."
self.beliefs = util.Counter()
for p in self.legalPositions: self.beliefs[p] = 1.0
self.beliefs.normalize()
def observe(self, observation, gameState):
"""
Updates beliefs based on the distance observation and Pacman's position.
The noisyDistance is the estimated manhattan distance to the ghost you are tracking.
The emissionModel below stores the probability of the noisyDistance for any true
distance you supply. That is, it stores P(noisyDistance | TrueDistance).
self.legalPositions is a list of the possible ghost positions (you
should only consider positions that are in self.legalPositions).
"""
noisyDistance = observation
emissionModel = busters.getObservationDistribution(noisyDistance)
pacmanPosition = gameState.getPacmanPosition()
"*** YOUR CODE HERE ***"
# Replace this code with a correct observation update
allPossible = util.Counter()
for p in self.legalPositions:
trueDistance = util.manhattanDistance(p, pacmanPosition)
if emissionModel[trueDistance] > 0:
allPossible[p] = self.beliefs[p]
allPossible[p] *= emissionModel[trueDistance]
allPossible.normalize()
self.beliefs = allPossible
def elapseTime(self, gameState):
"""
Update self.beliefs in response to a time step passing from the current state.
The transition model is not entirely stationary: it may depend on Pacman's
current position (e.g., for DirectionalGhost). However, this is not a problem,
as Pacman's current position is known.
In order to obtain the distribution over new positions for the
ghost, given its previous position (oldPos) as well as Pacman's
current position, use this line of code:
newPosDist = self.getPositionDistribution(self.setGhostPosition(gameState, oldPos))
Note that you may need to replace "oldPos" with the correct name
of the variable that you have used to refer to the previous ghost
position for which you are computing this distribution.
newPosDist is a util.Counter object, where for each position p in self.legalPositions,
newPostDist[p] = Pr( ghost is at position p at time t + 1 | ghost is at position oldPos at time t )
(and also given Pacman's current position). You may also find it useful to loop over key, value pairs
in newPosDist, like:
for newPos, prob in newPosDist.items():
prob = newPosDist[newPos]
...
As an implementation detail (with which you need not concern
yourself), the line of code above for obtaining newPosDist makes
use of two helper methods provided in InferenceModule above:
1) self.setGhostPosition(gameState, ghostPosition)
This method alters the gameState by placing the ghost we're tracking
in a particular position. This altered gameState can be used to query
what the ghost would do in this position.
2) self.getPositionDistribution(gameState)
This method uses the ghost agent to determine what positions the ghost
will move to from the provided gameState. The ghost must be placed
in the gameState with a call to self.setGhostPosition above.
"""
allPossible = util.Counter()
for oldPos in self.legalPositions:
newPosDist = self.getPositionDistribution(self.setGhostPosition(gameState, oldPos))
for newPos, prob in newPosDist.items():
allPossible[newPos] += self.beliefs[oldPos] * prob
self.beliefs = allPossible
def getBeliefDistribution(self):
return self.beliefs
class ParticleFilter(InferenceModule):
"""
A particle filter for approximately tracking a single ghost.
Useful helper functions will include random.choice, which chooses
an element from a list uniformly at random, and util.sample, which
samples a key from a Counter by treating its values as probabilities.
"""
def initializeUniformly(self, gameState, numParticles=300):
"Initializes a list of particles."
self.numParticles = numParticles
"*** YOUR CODE HERE ***"
def observe(self, observation, gameState):
"Update beliefs based on the given distance observation."
emissionModel = busters.getObservationDistribution(observation)
pacmanPosition = gam1eState.getPacmanPosition()
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
def elapseTime(self, gameState):
"""
Update beliefs for a time step elapsing.
As in the elapseTime method of ExactInference, you should use:
newPosDist = self.getPositionDistribution(self.setGhostPosition(gameState, oldPos))
to obtain the distribution over new positions for the ghost, given
its previous position (oldPos) as well as Pacman's current
position.
"""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
def getBeliefDistribution(self):
"""
Return the agent's current belief state, a distribution over
ghost locations conditioned on all evidence and time passage.
"""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
class MarginalInference(InferenceModule):
"A wrapper around the JointInference module that returns marginal beliefs about ghosts."
def initializeUniformly(self, gameState):
"Set the belief state to an initial, prior value."
if self.index == 1: jointInference.initialize(gameState, self.legalPositions)
jointInference.addGhostAgent(self.ghostAgent)
def observeState(self, gameState):
"Update beliefs based on the given distance observation and gameState."
if self.index == 1: jointInference.observeState(gameState)
def elapseTime(self, gameState):
"Update beliefs for a time step elapsing from a gameState."
if self.index == 1: jointInference.elapseTime(gameState)
def getBeliefDistribution(self):
"Returns the marginal belief over a particular ghost by summing out the others."
jointDistribution = jointInference.getBeliefDistribution()
dist = util.Counter()
for t, prob in jointDistribution.items():
dist[t[self.index - 1]] += prob
return dist
class JointParticleFilter:
"JointParticleFilter tracks a joint distribution over tuples of all ghost positions."
def initialize(self, gameState, legalPositions, numParticles = 600):
"Stores information about the game, then initializes particles."
self.numGhosts = gameState.getNumAgents() - 1
self.numParticles = numParticles
self.ghostAgents = []
self.legalPositions = legalPositions
self.initializeParticles()
def initializeParticles(self):
"Initializes particles randomly. Each particle is a tuple of ghost positions."
self.particles = []
for i in range(self.numParticles):
self.particles.append(tuple([random.choice(self.legalPositions) for j in range(self.numGhosts)]))
def addGhostAgent(self, agent):
"Each ghost agent is registered separately and stored (in case they are different)."
self.ghostAgents.append(agent)
def elapseTime(self, gameState):
"""
Samples each particle's next state based on its current state and the gameState.
To loop over the ghosts, use:
for i in range(self.numGhosts):
...
Then, assuming that "i" refers to the (0-based) index of the
ghost, to obtain the distributions over new positions for that
single ghost, given the list (prevGhostPositions) of previous
positions of ALL of the ghosts, use this line of code:
newPosDist = getPositionDistributionForGhost(setGhostPositions(gameState, prevGhostPositions),
i + 1, self.ghostAgents[i])
Note that you may need to replace "prevGhostPositions" with the
correct name of the variable that you have used to refer to the
list of the previous positions of all of the ghosts, and you may
need to replace "i" with the variable you have used to refer to
the index of the ghost for which you are computing the new
position distribution.
As an implementation detail (with which you need not concern
yourself), the line of code above for obtaining newPosDist makes
use of two helper functions defined below in this file:
1) setGhostPositions(gameState, ghostPositions)
This method alters the gameState by placing the ghosts in the supplied positions.
2) getPositionDistributionForGhost(gameState, ghostIndex, agent)
This method uses the supplied ghost agent to determine what positions
a ghost (ghostIndex) controlled by a particular agent (ghostAgent)
will move to in the supplied gameState. All ghosts
must first be placed in the gameState using setGhostPositions above.
Remember: ghosts start at index 1 (Pacman is agent 0).
The ghost agent you are meant to supply is self.ghostAgents[ghostIndex-1],
but in this project all ghost agents are always the same.
"""
newParticles = []
for oldParticle in self.particles:
newParticle = list(oldParticle) # A list of ghost positions
"*** YOUR CODE HERE ***"
newParticles.append(tuple(newParticle))
self.particles = newParticles
def observeState(self, gameState):
"""
Resamples the set of particles using the likelihood of the noisy observations.
As in elapseTime, to loop over the ghosts, use:
for i in range(self.numGhosts):
...
A correct implementation will handle two special cases:
1) When a ghost is captured by Pacman, all particles should be updated so
that the ghost appears in its prison cell, position (2 * i + 1, 1),
where "i" is the 0-based index of the ghost.
You can check if a ghost has been captured by Pacman by
checking if it has a noisyDistance of 999 (a noisy distance
of 999 will be returned if, and only if, the ghost is
captured).
2) When all particles receive 0 weight, they should be recreated from the
prior distribution by calling initializeParticles.
"""
pacmanPosition = gameState.getPacmanPosition()
noisyDistances = gameState.getNoisyGhostDistances()
if len(noisyDistances) < self.numGhosts: return
emissionModels = [busters.getObservationDistribution(dist) for dist in noisyDistances]
"*** YOUR CODE HERE ***"
def getBeliefDistribution(self):
dist = util.Counter()
for part in self.particles: dist[part] += 1
dist.normalize()
return dist
# One JointInference module is shared globally across instances of MarginalInference
jointInference = JointParticleFilter()
def getPositionDistributionForGhost(gameState, ghostIndex, agent):
"""
Returns the distribution over positions for a ghost, using the supplied gameState.
"""
ghostPosition = gameState.getGhostPosition(ghostIndex)
actionDist = agent.getDistribution(gameState)
dist = util.Counter()
for action, prob in actionDist.items():
successorPosition = game.Actions.getSuccessor(ghostPosition, action)
dist[successorPosition] = prob
return dist
def setGhostPositions(gameState, ghostPositions):
"Sets the position of all ghosts to the values in ghostPositionTuple."
for index, pos in enumerate(ghostPositions):
conf = game.Configuration(pos, game.Directions.STOP)
gameState.data.agentStates[index + 1] = game.AgentState(conf, False)
return gameState