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:

PostCommit


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.py contains all of the inference logic for implementing the Forward Algorithm's pieces, both for the exact and particle-filter versions.

  • bustersAgents.py contains all of the logic for controlling your automated Pacman GhostHunter once the inference components have been completed.

  • test_qN.py contain 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:

  1. 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})}$$

  2. 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, the observe function is called, which must update the belief at every position.
  • Try printing noisyDistance, emissionModel, and PacmanPosition (in the observe function) 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.Counter objects (like dictionaries, but for which requests for keys that are not stored within return 0) in a field called self.beliefs, which you should update.

    You would do well to examine the methods of util.Counter before starting coding, some may be useful throughout!

  • You should not need to store any evidence. The only thing you need to store in ExactInference is self.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)

noisyDistance

(already defined at the top of observe)

Pacman's noisy sonar reading of his distance to this ghost, i.e., the evidence \(e_t\). It is None if and only if the ghost has been captured.

5 or None

(int | None)

emissionModel

(already defined, via busters.getObservationDistribution(noisyDistance))

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 noisyDistance = 5:

{5.0: 0.335, 4.0: 0.168, 6.0: 0.168, 3.0: 0.084, 7.0: 0.084, ..., 12.0: 0.003}

(util.Counter: true distance → probability. Keys are floats, but emissionModel[5] works just fine.)

pacmanPosition

(already defined)

Where Pacman was standing when he took the reading.

(4, 6)

(tuple of int)

self.legalPositions

Every tile the ghost could be on, i.e., every value of \(x_t\) whose belief you must update.

[(1, 2), (1, 3), (1, 4), (2, 2), ...]

(list of tuple)

util.manhattanDistance(p1, p2)

The true distance between two tiles: how you turn a candidate ghost position into a key for emissionModel.

util.manhattanDistance((1, 2), (4, 6)) → 7

(int)

self.beliefs

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.

{(1, 2): 0.0125, (1, 3): 0.0125, ...} (uniform, at the start of the game)

(util.Counter: position → probability)

self.getJailPosition()

This ghost's prison tile, for the captured-ghost special case.

(1, 1) for ghost 1, (3, 1) for ghost 2

(tuple)

util.Counter(), .normalize(), .totalCount()

A dictionary whose missing keys default to 0. .normalize() rescales its values to sum to 1 in place and returns None, so don't write x = c.normalize()! (util.normalize(c) returns a normalized copy instead.)

c = util.Counter()
c[(1, 2)] = 3
c[(1, 3)] = 1
c.normalize()

→ c is now {(1, 2): 0.75, (1, 3): 0.25}

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 of ExactInference.elapseTime in inference.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)

self.beliefs

Last step's belief, \(B(x_{t-1})\): where the ghost might have been before it moved.

{(5, 3): 0.7, (6, 3): 0.3, ...}

(util.Counter: position → probability)

self.legalPositions

Every tile the ghost could be on: the values of \(x_{t-1}\) the sum ranges over (and the possible values of \(x_t\)).

[(1, 2), (1, 3), (1, 4), (2, 2), ...]

(list of tuple)

self.setGhostPosition(gameState, oldPos)

A game state with the ghost placed at oldPos, so you can ask "if the ghost were here, where would it go next?" (It modifies and returns the gameState you pass in.)

A GameState object: pass it straight into getPositionDistribution, below.

self.getPositionDistribution(state)

The transition term \(P(x_t | x_{t-1})\) for a single \(x_{t-1}\): given where the ghost is in state, the probability of each tile it could be on next. Ghosts may also choose to stay put.

A random ghost at (5, 3) with a wall to its south:

{(5, 4): 0.25, (6, 3): 0.25, (4, 3): 0.25, (5, 3): 0.25}

(util.Counter: next position → probability; a GoSouthGhost would put more weight on southward moves)

util.Counter()

A fresh accumulator for \(B'(x_t)\). += on a missing key starts from 0. Build a new Counter rather than editing self.beliefs while you're still reading from it!

c = util.Counter()
c[(5, 4)] += 0.1
c[(5, 4)] += 0.2

→ {(5, 4): 0.3} (give or take float rounding)

Counter.normalize()

Rescales values to sum to 1, in place (returns None).

{(5, 4): 2, (6, 3): 2} → {(5, 4): 0.5, (6, 3): 0.5}

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 chooseAction provide 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)

pacmanPosition

(already defined)

Where Pacman is right now.

(4, 6)

(tuple of int)

legal

(already defined)

Pacman's legal actions this turn: the candidates you choose between.

['North', 'East', 'Stop']

(list of str)

livingGhostPositionDistributions

(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.

[{(5, 3): 0.6, (6, 3): 0.3, ...}, {(1, 4): 0.9, ...}]

(list of util.Counter)

Counter.argMax()

The key with the highest value: a ghost's single most likely position.

{(5, 3): 0.6, (6, 3): 0.4}.argMax() → (5, 3)

(tuple)

self.distancer.getDistance(pos1, pos2)

The maze distance between two tiles, which accounts for walls. Use this rather than Manhattan distance.

self.distancer.getDistance((4, 6), (5, 3)) → 6

(int; can be larger than the Manhattan distance of 4 when walls are in the way)

Actions.getSuccessor(position, action)

Where Pacman would end up after taking action from position.

Actions.getSuccessor((4, 6), 'North') → (4, 7)

(tuple)

Python's built-in min(iterable, key=...)

Returns the item (not its score) with the smallest key, which helps with both "closest ghost" and "best action".

dists = {'North': 5, 'East': 3}
min(dists, key=lambda a: dists[a]) → 'East'


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.sample or util.nSample will help you obtain samples from a distribution. If you use util.sample and your implementation is timing out / failing in later tests, try using util.nSample.


Skeleton Toolkit for ParticleFilter.initializeUniformly, getBeliefDistribution, and observe:

Skeleton Tool

What It Gives You

Example Value (Type)

self.particles

(you create this in initializeUniformly)

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 list, not a Counter.

[(1, 2), (1, 3), (2, 2), ..., (1, 2), (1, 3), ...]

(list of tuple, with len == self.numParticles)

self.numParticles

How many particles to keep at all times.

300

(int)

self.legalPositions

The tiles to spread particles across in initializeUniformly. The docstring asks you to cycle through them in order (round-robin) rather than placing particles randomly.

[(1, 2), (1, 3), (2, 2)] with 100 particles → 34 at (1, 2), 33 at (1, 3), 33 at (2, 2)

(list of tuple)

util.Counter()

(in getBeliefDistribution)

Tally how many particles sit on each tile, then normalize. The result is what gets drawn on screen.

Particles [(5, 3), (5, 3), (6, 3), (5, 3)] → {(5, 3): 0.75, (6, 3): 0.25}

(util.Counter)

emissionModel, pacmanPosition, util.manhattanDistance

(in observe)

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.

Counter.totalCount()

The sum of all values. Use it to detect the special case where every particle got zero weight.

0 → time to recover by calling self.initializeUniformly(gameState)

self.getJailPosition()

The captured-ghost special case: every particle goes to jail.

(1, 1) → particles become [(1, 1), (1, 1), ..., (1, 1)]

util.sample(distribution, values=None)

Draws one value at random according to its probability. Accepts a util.Counter directly (in which case leave out values).

Warning: some students have reported issues using this with efficiency, you might need to use nSample (next method) instead.

util.sample(util.Counter({(5, 3): 0.75, (6, 3): 0.25})) → (5, 3) (75% of the time)

(tuple)

util.nSample(distribution, values, n)

Draws n values at once, which is much faster than calling util.sample n times. Takes two parallel lists, not a Counter, e.g., list(c.values()) and list(c.keys()).

util.nSample([0.75, 0.25], [(5, 3), (6, 3)], 4) → e.g., [(5, 3), (5, 3), (5, 3), (6, 3)]

(list of length n)


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)

self.particles

Each particle is one guess at \(x_{t-1}\), and each needs to move to a guess at \(x_t\).

[(5, 3), (5, 3), (6, 3), ...]

(list of tuple)

self.setGhostPosition(gameState, pos) + self.getPositionDistribution(state)

The same pair you used in Problem 2: the transition distribution \(P(x_t | x_{t-1} = \text{pos})\) for a particle at pos.

{(5, 4): 0.25, (6, 3): 0.25, (4, 3): 0.25, (5, 3): 0.25}

(util.Counter: next position → probability)

util.sample(distribution)

Picks one successor for one particle from its transition distribution.

util.sample(util.Counter({(5, 4): 0.5, (6, 3): 0.5})) → (6, 3)

(tuple)

A plain dict cache (optional)

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.

{(5, 3): {(5, 4): 0.25, ...}, (6, 3): {(6, 4): 0.5, ...}}

(dict: position → util.Counter)

A new list

Collect the moved particles in a new list, then assign it back to self.particles.

[(5, 4), (6, 3), (6, 4), ...]

(list of tuple, still len == self.numParticles)



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_transitions helper 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)

position_transitions_for_ghost

(parameter)

This ghost's (already smoothed) transition counts: previous position → (next position → count).

{(1, 1): {(2, 1): 3, (1, 2): 2, (0, 1): 1}, (2, 1): {(3, 1): 4, ...}}

(dict of dict)

current_position

(parameter)

Where the ghost is now, i.e., the \(x_t\) you are conditioning on.

(1, 1)

(tuple)

reachable_positions

(parameter)

The tiles the ghost can legally move to from here. Your distribution should contain only these keys.

{(2, 1), (1, 2), (0, 1)}

(set of tuple)

position_transitions_for_ghost.get(current_position, {})

The inner count dictionary for the ghost's current tile, or an empty dict if the ghost was never seen there (this avoids a KeyError).

{(2, 1): 3, (1, 2): 2, (0, 1): 1}

(dict: next position → count)

util.Counter(), .totalCount(), .normalize()

The return type: turn counts into probabilities \(P(X_{t+1} | X_t)\) for X_t = current_position.

{(2, 1): 0.5, (1, 2): 0.333, (0, 1): 0.167}

(util.Counter: next position → probability)

util.position_to_action(prev_pos, next_pos) (optional)

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.

util.position_to_action((1, 1), (2, 1)) → 'East'

(str, or None if the tiles aren't adjacent)

Edge cases checked by test_position_distribution.py

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 reachable_positions. If reachable_positions is empty, return an empty Counter.

{(2, 1): 0.333, (1, 2): 0.333, (0, 1): 0.333}

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:

PostCommit Tutorial

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).



  PDF / Print