Homework 3 - Ghostbusted
This is a *group* assignment! Feel free to work in groups of up to 3 individuals.
This assignment is the fruit of a cool Berkeley grant to develop fun AI projects, which was taken with permission, but then edited by us to update to Python 3 and add some new portions (thanks for Vivek Dhingra)! See Berkeley's AI Materials Pacman Projects for more info.
In this assignment, you'll be:
Hunting invisible (but noisy) ghosts with Pacman!
Designing some simple Hidden Markov Model (HMM) of the ghost's states (position on a grid), movements (transition dynamics), and how their movements map to some noisy (literally) observed evidence (emission dynamics).
Here are some more details to wrap your head around things.
Pacman spends his life running from ghosts, but things were not always so. Legend has it that many years ago, Pacman's great grandfather Grandpac learned to hunt ghosts for sport. However, he was blinded by his power and could only track ghosts by their banging and clanging.
Ghostbusters and HMMs
In this project, the goal is to hunt down scared but invisible ghosts. Pacman, ever resourceful, is equipped with sonar (ears) that provides noisy readings of the Manhattan distance to each ghost. The game ends when Pacman has eaten all the ghosts. To start, try playing a game yourself using the keyboard.
python busters.py
The blocks of color indicate where the each ghost could possibly be, given the noisy distance readings provided to Pacman. The noisy distances at the bottom of the display are always non-negative, and always within 7 of the true distance. The probability of a distance reading decreases exponentially with its difference from the true distance.
If you want to see from where the colors are coming, you can play while "cheating" by displaying the ghosts via:
python busters.py -s
Eventually, after correctly implementing the methods described in the spec, your agent's beliefs should be more localized around the true locations of ghosts, namely:
Having completed all parts of the assignment, you can unleash your "Greedy" Pacman Ghosthunter (which hunts down the nearest, highest ghost belief) via the command:
python busters.py -p GreedyBustersAgent
Your primary task in this project is to implement inference to track the ghosts. For the keyboard based game above, a crude form of inference was implemented for you by default: all squares in which a ghost could possibly be are shaded by the color of the ghost. Naturally, we want a better estimate of the ghost's position. Fortunately, Bayes' Nets provide us with powerful tools for making the most of the information we have. Throughout the rest of this project, you will implement algorithms for performing exact inference using HMMs.
Testing
While watching and debugging your code with the unit tests, it will be helpful to have some understanding of what the tests are doing.
There are 2 types of tests in this project. For tests of class DoubleInferenceAgentTest, your will see visualizations of the inference distributions
generated by your code, but all
Pacman actions will be preselected according to the actions of the staff implementation. This is necessary in order to allow comparision of your distributions
with the staff's distributions. The second type of test is GameScoreTest, in which your BustersAgent will actually select actions for
Pacman and you will watch your Pacman play and win games.
As you implement and debug your code, you may find it useful to run a single test at a time. In order to do this you will need to use the pytest test_qN.py
syntax. For example if you only want to run the first test of question 1, use:
pytest test_q1.py
To visualize your belief distributions, use the --visualize tag:
pytest test_q1.py --visualize
Things too fast / too slow? You can also specify a frame-time argument, e.g.:
pytest test_q1.py --visualize --frame-time 0.01
Note: to use the visualization features, you'll need to first install pygame (we recommend pip install pygame-ce;
see below). pygame is only needed for --visualize: every test runs and is graded without it, so a pygame install problem
should never stop you from working on the assignment.
Getting error: failed-wheel-build-for-install (or another build error) when installing pygame? Click here.
What the error means: pip couldn't find a pre-built copy of pygame (a "wheel") for your version of Python, so it tried to
compile pygame from source. That needs C compilers and graphics libraries most machines don't have, so the build fails. The usual cause is
Python 3.14, which the original pygame package does not yet support. Check your version with:
python3 --version
The fix: install pygame-ce (the community-maintained edition of pygame) instead. It ships pre-built wheels for
Python 3.10 through 3.14 and is a drop-in replacement: you still write import pygame, and the skeleton runs unchanged.
Recommended setup (a virtual environment): if pip complained about an externally-managed-environment (which is
probably why you tried --break-system-packages), use a virtual environment instead of that flag. From inside your project folder:
macOS / Linux:
python3 -m venv .venv source .venv/bin/activate pip install pygame-ce pytest
Windows:
python -m venv .venv .venv\Scripts\activate pip install pygame-ce pytest
Then run pytest as usual from that same terminal. Re-run the activate line whenever you open a new terminal, and don't commit
the .venv folder.
Already have the original pygame installed in the same environment? Run pip uninstall pygame before installing
pygame-ce: the two use the same import pygame name and conflict if both are installed.
Still stuck? Leave off --visualize and keep working; all of the tests run without graphics. Then come see us in office
hours!
Solution Skeleton
Start with the solution skeleton for this part in-hand! Segments left for you to do are indicated in comments:
Included in the skeleton are MANY files needed for the execution of the Pacman environment, but only a few of which you'll need to worry about:
inference.pycontains all of the inference logic for implementing the Forward Algorithm's pieces, both for the exact and particle-filter versions.bustersAgents.pycontains all of the logic for controlling your automated Pacman GhostHunter once the inference components have been completed.test_qN.pycontain various unit tests to validate your agent's inference abilities.Warning: these are large files because of the hard-coded comparison belief states that can stall systems with lesser resources -- open only at your own risk!
Specifications
|
|
GenAI use for code production for the entirety of this assignment is BANNED as it will shortcut your learning and generalizable skills (besides, there's not much code to write, the exercise is meant to teach you how to implement a decision network from first-principles) though is always OK for understanding error messages, interpreting skeleton code, etc. as outlined in the syllabus. |
You will be completing 3 parts to get your Pacman to hunt effectively:
HMM Inference - Observations: implement the updates from Observations on the Belief state using the inference procedures discussed in class.
HMM Inference - Passage of Time: implement the updates from Transition Dynamics on the Belief state using the inference procedures discussed in class.
Combined Pacman Hunter: combining both of the above, design a simple, greedy Pacman agent that will hunt ghosts at what it believes are the most likely locations given their past evidence.
Note: though in class we saw the Forward Algorithm as combining both updates of the Observations and Passage of Time, each can be encoded separately as a manipulation of the belief state and then combined for the full Forward Algorithm!
Recall what we saw in class:
Computing the belief state at time t, \(B(X_t)\), follows repeated application of two steps at all previous time steps:
Passage of Time: Update the belief for the transition / time between \(X_{t-1} \rightarrow X_{t}\). Namely, define: $$\color{green}{B'(x_t)} = P(x_t | e_{1:t-1}) = \sum_{x_{t-1}} P(x_t | x_{t-1}) \color{red}{B(x_{t-1})}$$
Observation: Update for observed emission for time \(t\): \(X_{t} \rightarrow E_{t}\). Namely, define: $$\color{red}{B(x_{t})} = P(x_t | e_{1:t}) \propto P(e_t | x_t) \color{green}{B'(x_t)}$$
For the exact inference problems that follow (P1 + 2), note that \(B(x_{t})\) is just a tabular distribution represented as a dictionary of key maze locations mapped to the belief that a ghost is in that tile!
Here's how you'll do that!
BIG RED WARNING: Parts of the necessary tools for implementing each problem below are described in the methods' DOCSTRINGS in the skeleton! Make sure you've read through those alongside the plain-English descriptions that follow!
Exact Inference - Updates from Observation
In this question, you will update the observe method in ExactInference class of inference.py to correctly update the
agent's belief distribution over ghost positions given an observation from Pacman's sensors. A correct implementation should also handle one special case: when
a ghost is eaten, you should place that ghost in its prison cell, as described in the comments of observe.
To run the autograder for this question and visualize the output:
pytest test_q1.py --visualize
As you watch the test cases, be sure that you understand how the squares converge to their final coloring. In test cases where is Pacman boxed in (which is to say, he is unable to change his observation point), why does Pacman sometimes have trouble finding the exact location of the ghost?
Note: your busters agents have a separate inference module for each ghost they are tracking. That's why if you print an observation inside the
observe function, you'll only see a single number even though there may be multiple ghosts on the board.
Hints:
- You are implementing the online belief update for observing new evidence. Before any readings, Pacman believes the ghost could be anywhere: a uniform prior
(see
initializeUniformly). After receiving a reading, theobservefunction is called, which must update the belief at every position. - Try printing
noisyDistance,emissionModel, andPacmanPosition(in theobservefunction) to get started. - After that, and before typing any more code, write down the equation of the inference problem you are trying to solve.
- In the Pacman display, high posterior beliefs are represented by bright colors, while low beliefs are represented by dim colors. You should start with a large cloud of belief that shrinks over time as more evidence accumulates.
- Beliefs are stored as
util.Counterobjects (like dictionaries, but for which requests for keys that are not stored within return 0) in a field calledself.beliefs, which you should update.You would do well to examine the methods of
util.Counterbefore starting coding, some may be useful throughout! - You should not need to store any evidence. The only thing you need to store in
ExactInferenceisself.beliefs(since the belief state is being "pushed" forward in time, your updates will already account for past evidence).
Skeleton Toolkit for ExactInference.observe: the pieces of the skeleton you'll want to recruit, which term of the
Observation update each one plays, and what its data looks like.
Skeleton Tool |
What It Gives You |
Example Value (Type) |
|---|---|---|
(already defined at the top of |
Pacman's noisy sonar reading of his distance to this ghost, i.e., the evidence \(e_t\). It is |
( |
(already defined, via |
The emission term \(P(e_t | x_t)\), indexed by true distance: look it up with a true distance to get the likelihood of the reading Pacman actually got. |
For
( |
(already defined) |
Where Pacman was standing when he took the reading. |
( |
|
Every tile the ghost could be on, i.e., every value of \(x_t\) whose belief you must update. |
( |
|
The true distance between two tiles: how you turn a candidate ghost position into a key for |
( |
|
The belief going into the update, \(B'(x_t)\). You must replace it with the updated \(B(x_t)\) by the end of the method. |
( |
|
This ghost's prison tile, for the captured-ghost special case. |
( |
|
A dictionary whose missing keys default to |
→ |
Click here for a visual run-down of this method.
Exact Inference - Updates from Passage of Time
In the previous question you implemented belief updates for Pacman based on his observations. Fortunately, Pacman's observations are not his only source of knowledge about where a ghost may be. Pacman also has knowledge about the ways that a ghost may move; namely that the ghost can not move through a wall or more than one space in one timestep.
To understand why this is useful to Pacman, consider the following scenario in which there is Pacman and one Ghost. Pacman receives many observations which indicate the ghost is very near, but then one which indicates the ghost is very far. The reading indicating the ghost is very far is likely to be the result of a buggy sensor. Pacman's prior knowledge of how the ghost may move will decrease the impact of this reading since Pacman knows the ghost could not move so far in only one move.
In this question, you will implement the elapseTime method in ExactInference. Your agent has access to the action distribution for
any GhostAgent. In order to test your elapseTime implementation separately from your observe implementation in the previous
question, this question will not make use of your observe implementation.
Since Pacman is not utilizing any observations about the ghost, this means that Pacman will start with a uniform distribution over all spaces, and then update his beliefs according to how he knows the Ghost is able to move. Since Pacman is not observing the ghost, this means the ghost's actions will not impact Pacman's beliefs. Over time, Pacman's beliefs will come to reflect places on the board where he believes ghosts are most likely to be given the geometry of the board and what Pacman already knows about their valid movements.
For the tests in this question we will sometimes use a ghost with random movements and other times we will use the GoSouthGhost. This ghost tends to move south so over time, and without any observations, Pacman's belief distribution should begin to focus around the bottom of the board. To see which ghost is used for each test case you can look in the .test files.
To run the autograder for this question and visualize the output:
pytest test_q2.py --visualize
...and observe that the distribution in the end test becomes concentrated at the bottom of the board.
As you watch the autograder output, remember that lighter squares indicate that pacman believes a ghost is more likely to occupy that location, and darker squares indicate a ghost is less likely to occupy that location. For which of the test cases do you notice differences emerging in the shading of the squares? Can you explain why some squares get lighter and some squares get darker?
Hints:
- Instructions for obtaining a distribution over where a ghost will go next, given its current position and the
gameState, appears in the comments ofExactInference.elapseTimeininference.py. - We assume that ghosts still move independently of one another, so while you can develop all of your code for one ghost at a time, adding multiple ghosts should still work correctly.
Skeleton Toolkit for ExactInference.elapseTime:
Skeleton Tool |
What It Gives You |
Example Value (Type) |
|---|---|---|
|
Last step's belief, \(B(x_{t-1})\): where the ghost might have been before it moved. |
( |
|
Every tile the ghost could be on: the values of \(x_{t-1}\) the sum ranges over (and the possible values of \(x_t\)). |
( |
|
A game state with the ghost placed at |
A |
|
The transition term \(P(x_t | x_{t-1})\) for a single \(x_{t-1}\): given where the ghost is in |
A random ghost at
( |
|
A fresh accumulator for \(B'(x_t)\). |
→ |
|
Rescales values to sum to 1, in place (returns |
|
Click here for a visual run-down of this method.
Pacman Hunter
Now that Pacman knows how to use both his prior knowledge and his observations when figuring out where a ghost is, he is ready to hunt down ghosts on his own.
This question will use your observe and elapseTime implementations together, along with a simple greedy hunting strategy which you will
implement for this question. In the simple greedy strategy, Pacman assumes that each ghost is in its most likely position according to its beliefs, then moves
toward the closest ghost. Up to this point, Pacman has moved by randomly selecting a valid action.
Implement the chooseAction method in GreedyBustersAgent in bustersAgents.py. Your agent should first find the most
likely position of each remaining (uncaptured) ghost, then choose an action that minimizes the distance to the closest ghost. If correctly implemented, your
agent should win the game in q3/3-gameScoreTest with a score greater than 700 at least 8 out of 10 times. Note: the autograder will also
check the correctness of your inference directly, but the outcome of games is a reasonable sanity check.
To run the autograder for this question and visualize the output:
pytest test_q3.py --visualize
Note: If you want to run this test (or any of the other tests) without graphics you can just drop the --visualize tag.
Hints:
- When correctly implemented, your agent will thrash around a bit in order to capture a ghost.
- The comments of
chooseActionprovide you with useful method calls for computing maze distance and successor positions. - Make sure to only consider the living ghosts, as described in the comments.
Skeleton Toolkit for GreedyBustersAgent.chooseAction:
Skeleton Tool |
What It Gives You |
Example Value (Type) |
|---|---|---|
(already defined) |
Where Pacman is right now. |
( |
(already defined) |
Pacman's legal actions this turn: the candidates you choose between. |
( |
(already defined) |
One belief distribution per ghost that is still alive (captured ghosts are already filtered out for you). These are the outputs of your Problem 1 + 2 work. |
( |
|
The key with the highest value: a ghost's single most likely position. |
( |
|
The maze distance between two tiles, which accounts for walls. Use this rather than Manhattan distance. |
( |
|
Where Pacman would end up after taking |
( |
Python's built-in |
Returns the item (not its score) with the smallest key, which helps with both "closest ghost" and "best action". |
|
Particle Filtering - Updates from Observation
Next, you will implement a particle filtering algorithm for tracking a single ghost.
Implement the functions initializeUniformly, getBeliefDistribution, and observe for the ParticleFilter class
in inference.py. A correct
implementation should also handle two special cases. (1) When all your particles receive zero weight based on the evidence, you should resample
all particles from the prior to recover. (2) When a ghost is eaten, you should update all particles to place that ghost in its prison cell,
as described in the comments of observe. When complete, you should be able to track ghosts nearly as effectively as with exact inference.
To run the autograder for this question and visualize the output:
pytest test_q4.py --visualize
Hints:
A particle (sample) is a ghost position in this inference problem.
The belief cloud generated by a particle filter will look noisy compared to the one for exact inference.
util.sampleorutil.nSamplewill help you obtain samples from a distribution. If you useutil.sampleand your implementation is timing out / failing in later tests, try usingutil.nSample.
Skeleton Toolkit for ParticleFilter.initializeUniformly, getBeliefDistribution, and observe:
Skeleton Tool |
What It Gives You |
Example Value (Type) |
|---|---|---|
(you create this in |
Your belief representation: a plain list with one position per particle. Duplicates are expected, since more particles on a tile means more
belief there. It must be a |
( |
|
How many particles to keep at all times. |
( |
|
The tiles to spread particles across in |
( |
(in |
Tally how many particles sit on each tile, then normalize. The result is what gets drawn on screen. |
Particles ( |
(in |
Same as Problem 1: together they give you the weight \(P(e_t | x_t)\) of a particle at position \(x_t\). |
See the Problem 1 table. |
|
The sum of all values. Use it to detect the special case where every particle got zero weight. |
|
|
The captured-ghost special case: every particle goes to jail. |
|
|
Draws one value at random according to its probability. Accepts a Warning: some students have reported issues using this with efficiency, you might need to use nSample (next method) instead. |
( |
|
Draws |
( |
Particle Filtering - Updates from Passage of Time
Implement the elapseTime function for the ParticleFilter class in inference.py. When complete, you should be able to
track ghosts nearly as effectively as with exact inference.
Note that in this question, we will test both the elapseTime function in isolation, as well as the full implementation of the particle filter combining
elapseTime and observe.
To run the autograder for this question and visualize the output:
pytest test_q5.py --visualize
Skeleton Toolkit for ParticleFilter.elapseTime:
Skeleton Tool |
What It Gives You |
Example Value (Type) |
|---|---|---|
|
Each particle is one guess at \(x_{t-1}\), and each needs to move to a guess at \(x_t\). |
( |
|
The same pair you used in Problem 2: the transition distribution \(P(x_t | x_{t-1} = \text{pos})\) for a particle at |
( |
|
Picks one successor for one particle from its transition distribution. |
( |
A plain |
Many particles share a tile, so compute each tile's transition distribution once and reuse it. The docstring suggests this, and it helps if the tests time out. |
( |
A new |
Collect the moved particles in a new list, then assign it back to |
( |
Incorporating Empirical Data
Notice that in the previous problem's tests, we will sometimes use a ghost with random movements and other times we will use the GoSouthGhost. This ghost
tends to move south so over time, and without any observations, Pacman's belief distribution should begin to focus around the bottom of the board.
Thanks to Parker Jazayeri for forwarding the following video that explains the original Ghost decision-process; notably, different Ghosts have different "personalities" that could be captured with different transition distributions!
However, we are still assuming that each ghost has a uniform transition distribution, i.e., that it has an equal chance to move into any adjacent spot.
In general, this may not be a fair assumption; we may, in fact, know something about the transitions from past empirical (i.e., collected from observation) data that could help us better deduce the ghost's movements.
To give us a means of turning such data into a more customized distribution, we'll complete the following pipeline:
(Done for you) Collect empirical data: you can take a look at the included transition data in the
/data/directory. Inside, you'll see a few csv files with each row being a single transition demonstrated by a single ghost, e.g., the following row indicates that we witnessed ghost 1 move from (6,5) to (6,4):ghost_id, true_pos_x_t, true_pos_y_t, true_pos_x_t+1, true_pos_y_t+1 1 6 5 6 4
(Done for you) We'll then count and smooth those transitions so that they are in a format ready to be converted into a distribution. We use nested dictionaries for this purpose, e.g., the following showing that a ghost moved from (1,1) to (2,1) 3 times, (1,2) 2 times, and (0,1) 1 time:
{(1, 1): {(2, 1): 3, (1, 2): 2, (0, 1): 1}}Your task: convert these counts into a transition distribution, \(P(X_{t+1}|X_t)\) in the
_create_position_distribution_from_transitionshelper method. For example, from the transition counts above, if the current position was (1,1) and the reachable positions were each in the dictionary, you would return:{(2, 1): 0.5, (1, 2): 0.3333333333333333, (0, 1): 0.16666666666666666}
Skeleton Toolkit for InferenceModule._create_position_distribution_from_transitions:
Skeleton Tool |
What It Gives You |
Example Value (Type) |
|---|---|---|
(parameter) |
This ghost's (already smoothed) transition counts: previous position → (next position → count). |
( |
(parameter) |
Where the ghost is now, i.e., the \(x_t\) you are conditioning on. |
( |
(parameter) |
The tiles the ghost can legally move to from here. Your distribution should contain only these keys. |
( |
|
The inner count dictionary for the ghost's current tile, or an empty dict if the ghost was never seen there (this avoids a
|
( |
|
The return type: turn counts into probabilities \(P(X_{t+1} | X_t)\) for |
( |
|
The name of the move between two adjacent tiles. It's handy for debugging prints, but you don't need it to compute the distribution. |
( |
Edge cases checked by |
If there is no usable data for the current tile (it was never seen, all of its counts are 0, or none of its recorded moves are reachable),
fall back to a uniform distribution over |
or |
Once you've accomplished the above, you can run the test for position distributions:
pytest test_position_distribution.py
Finally, to see it in action as your hunter now takes into account each ghost's no-longer-uniform movement predilections, run:
pytest test_q6.py --visualize
Once you're done with that, you're all set, congrats! Hope you enjoyed this hauntingly fun assignment.
Submission
You will be submitting your assignments through PostCommit!
What
Complete all classes that accomplishes the specification above, in the project structure given in the skeleton above. You will fill in the relevant portions of the
bustersAgents.py and inference.py files.
How
To clone this assignment (if you need a refresher), consult the guide here:
To submit this assignment:
Simply push your final, submission copy to the PostCommit repository associated with you or your group.
If you worked in a group, ensure that your PostCommit group includes all members, and place all group members' names at the top of *all* submitted files (in appropriate commenting fashion).