You are on page 1of 32

Introduction to Artificial Intelligence

Assignment

Bui Trung Hai La Vi Luong


Nguyen Tran Minh Phuoc Nguyen Hoang Anh Thu

Ho Chi Minh City University of Technology


Faculty of Computer Science and Engineering

April 4, 2024

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 1 / 32


Contents

1 Task 1: 8-Puzzle
Code structure
Class Node
Class Utils
Class Heuristics
Class PuzzleSearchStrategy
Class BFSPuzzle
Class AStarPuzzle
Class UserInteraction
Class BarChart

2 Task 2: Pacman

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 2 / 32


8 puzzle
Code structure

We define these classes to implement the problem solving:


1 Node
2 Utils
3 Heuristic
4 PuzzleSearchStrategy
5 BFSPuzzle
6 AStarPuzzle
7 UserInteraction
8 BarChart

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 3 / 32


8 puzzle
Class Node

This class represents a state of an 8-puzzle. Each node holds information about the
current state of the puzzle and its relation to other nodes in the search process.
• Attributes:
• state: a 2D list represents the current state of the puzzle.
• id: an identifier for the node generated from the string representation of the state.
• action: the action that led to the state from its parent node.
• parent: a reference to the parent node in the search tree.
• Methods:
• str (): defines how to print a node.
• lt (): enables comparison between nodes based on their IDs.
• get successors(): generates the list of successor nodes reachable from the current
state.
• get dest pos(): calculates the new position of the tile based on the applied action.
• get blank pos(): finds the position of the blank tile.
• get id(), get node str(), get action(): get the ID, string representation of the state,
the action that led to this node from its parent, respectively.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 4 / 32


8 puzzle
Class Utils

This class provides functions for generating and validating the puzzle
configurations for the 8-puzzle problem.
• generate unique matrix(): this method generates a unique 3x3 matrix for the
8-puzzle problem.
• is puzzle solvable(): this method checks if a given 3x3 matrix represents a
solvable 8-puzzle configuration.
• generate n solvable unique matrices(): this method generates a specified
number of unique and solvable matrices for the 8-puzzle problem.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 5 / 32


8 puzzle
Class Heuristics

This class provides 2 heuristic functions used in our assignment to estimate the
cost of reaching the goal state from a given node.
• get misplaced num(): counts the number of tiles that are not in their correct
positions in the current node’s state compared to the goal state.
• get manhattan distance(): calculates the sum of the Manhattan distances
between each tile’s current position and its goal position.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 6 / 32


8 puzzle
Class PuzzleSearchStrategy

This class defines a frame for searching solutions to the 8 puzzle problem.
• Attributes:
• self.goal1, self.goal2: store instances of the Node class representing the 2 possible
goals for the 8-puzzle.
• self.dot: used for creating visual representations of the search process.
• self.dst: holds the destination node reached during a search.
• Methods:
• get path(): returns the sequence of actions that leads from the source node to the
destination node.
• draw path(): visualizes the search path.
• graph search(): is the abstract method for the specific search algorithms (BFS and
A*).

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 7 / 32


8 puzzle
Class BFSPuzzle

This class inherits from PuzzleSearchStrategy and implements the Breadth-First


Search (BFS) algorithm to solve the 8-puzzle problem.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 8 / 32


8 Puzzle
BFS Algorithm - Pseudo Code

Algorithm 1
0: expanded ← set(); frontier ← Queue()
0: frontier .push(problem.initial state)
0: while !frontier .isEmpty() do
0: node ← frontier .pop()
0: expanded.add(node.get id())
0: if problem.goal test(node) then
0: return find path(node)
0: end if
0: for successor in problem.get successor (node) do
0: if successor .get id() not in expanded then
0: frontier .push(successor , successor .path cost)
0: parents[successor .get id()] = node
0:
0:
return path

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 9 / 32


8 puzzle
Class AStarPuzzle

This class inherits from PuzzleSearchStrategy and implements the A* search


algorithm to solve the 8-puzzle problem.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 10 / 32


8 Puzzle
A* Algorithm - Pseudo Code

Algorithm 2
0: expanded ← set(); frontier ← PriorityQueue()
0: frontier .push(problem.initial state, 0)
0: while !frontier .isEmpty() do
0: node ← frontier .pop()
0: if problem.goal test(node) then
0: expanded.add(node.get id())
0: return find path(problem.initial state, node)
0: end if
0: expanded.add(node.get id())
0: for successor in problem.get successor (node) do
0: if successor .get id() not in expanded then
0: f score ← successor .path cost + heuristic(node, successor .state)
0: frontier .push(successor , f score)
0:
0:
return path

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 11 / 32


8 puzzle
Class UserInteraction

This class main purpose is to prompt user to input a valid state of 8 puzzle and
choose the algorithm to run (BFS, A* with number of misplaced tiles heuristic, A*
with Manhattan distance heuristic). The output method will return the path, path
cost, the number of nodes generated and the visualization of the path.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 12 / 32


8 puzzle
Class BarChart

This class main purpose is to draw bar chart to visualize the average path cost,
average time cost (seconds), and average number of nodes generated.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 13 / 32


8 Puzzle
A* Algorithm - Number of misplaced tiles

The Number of misplaced tiles heuristic counts the number of tiles not in correct
position of the goal state. It is both admissible and consistent for the 8 puzzle
problem.
• Admissibility: The number of misplaced tiles heuristic is admissible since every
misplaced tile requires at least one move to get back to its correct spot, and
every move contributes to solving the puzzle, the number of misplaced tiles
directly represents the minimum number of moves needed to solve the 8
puzzle.
• Consistency: The number of misplaced tiles heuristic is consistent as for an
arbitrary state of the 8 puzzle, we make a valid move and move that state to
the neighboring state, the number of misplaced tiles can only decrease by at
most one (since at most one misplaced tile can be corrected in one move). And
also the cost to reach a successor state is always equal the cost to reach the
current state plus one. Hence, the heuristic satisfies the consistency property.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 14 / 32


8 Puzzle
A* Algorithm - Manhattan distance

The Manhattan distance heuristic calculates the sum of the Manhattan distances
between each tile’s current position and its goal position.. It is both admissible and
consistent for the 8 puzzle problem.
• Admissibility: The Manhattan distance heuristic calculates the sum of the
distances (in terms of rows and columns) that each tile is away from its
desired position, ignoring any obstacles. Since each tile must move at least the
number of squares equal to its Manhattan distance to reach its goal position,
the Manhattan distance heuristic always underestimates the actual cost.
Therefore, it is admissible for the 8 puzzle problem.
• Consistency: the Manhattan distance is the sum of horizontal and vertical
distances, moving a tile one step closer to its goal reduces its Manhattan
distance by at least one. Therefore, the total Manhattan distance from the
start state to the goal state strictly decreases as we move towards the goal
making the heuristic consistent.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 15 / 32


Pacman
Code structure

We define 6 classes to complete the structure:


1 Maze
2 GameState
3 Problem
4 SearchStrategy
5 Node
6 PacmanAgent

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 16 / 32


Pacman
Class Maze

• Contains information about the maze (the current status of a maze to print).
• Check the status of a position in a maze (is wall?, is food?, etc.)
• Provide the method to get the food locations and the corners for each the
maze layout file.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 17 / 32


Pacman
Class GameState

• Contains information about the of a game state


(food remains, corner visited, current location of pacman, etc.)
• Methods:
• Check is goal state,
• Get next state given the action (Transition Model)
• Print the maze
• Initialize the food locations and the corners from the maze

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 18 / 32


Pacman
Class Node

• This is an intermediate class.


• Contains a GameState, action leads to the state, parent of the state, stateID,
path cost.
• Methods:
• Access to the Transistion model of GameState - get successor, print the state, etc.
• Calculate the path cost

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 19 / 32


Pacman
Class Problem

• Contains additional information so that the SearchStrategy can use to solve


the maze (actions, actions weight).
• Take initial state and register it as a Node.
• Methods:
• get successors: take a Node and return all possible successors
• goal test: take a Node and return if the Node is the final goal
• sub goal test: take a Node and return if the Node is at food location or
corner location (for A*)
• get nearest goal: return a food or corner location as the next sub goal
• get heuristic: take the next goal and get heuristic for all successor from the
current node

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 20 / 32


Pacman
Class PacmanAgent

• Take the initial state and initialize the problem for the search.
• Methods:
• get actions: take the problem and return the list of actions and nodes from initial
state to final goal

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 21 / 32


Pacman
Main Program - Pseudo Code

Algorithm 3 Program(file name, algo, visualize, time frame)


0: maze data ← read file(file name)
0: maze ← Maze(maze data)
0: action list ← list()
0: initial state ← GameState(maze)
0: pacman ← PacmanAgent(initial state, algo)
0: result ← pacman.get actions()
0: if visualize then
0: print(result.actions list)
0: else
0: print(result.nodes list)

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 22 / 32


Pacman
UCS Algorithm - Pseudo Code

Algorithm 4 ucs(problem:Problem)
0: expanded ← set(); frontier ← PriorityQueue()
0: frontier .push(problem.initial state, 0)
0: while !frontier .isEmpty() do
0: node ← frontier .pop()
0: if problem.goal test(node) then
0: return find path(node)
0: end if
0: expanded.add(node.get id())
0: for successor in problem.get successors(node) do
0: if successor .get id() not in expanded or successor .path cost <
node.path cost then
0: frontier .push(successor , successor .path cost)
0: parents[successor .get id()] = node
0:
0:
return path

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 23 / 32


Pacman
UCS Algorithm - Action weight

• How to determined the weight to go from 1 state to another?


• If using all action = 1. So ucs is the same as bfs
• Solution:
• weight = 1 if the position is a food dot or corner
• weight = number of food at beginning + 4 (represent 4 corners)

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 24 / 32


Pacman
A* Algorithm - Pseudo Code

Algorithm 5 a star(problem: Problem)


0: expanded ← set(); frontier ← PriorityQueue()
0: frontier .push(problem.initial state, 0)
0: while !frontier .isEmpty() do
0: node ← frontier .pop()
0: if problem.goal test(node) then
0: expanded.add(node.get id())
0: return find path(problem.initial state, node)
0: end if
0: expanded.add(node.get id())
0: end while
0: for successor in problem.get successor (node) do
0: if successor .get id() not in expanded then
0: f score ← successor .path cost + get manhattan heuristic(successor .state)
0: frontier .push(successor , f score)
0:
return path

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 25 / 32


Pacman
A* Algorithm - Heuristic Criteria

We will evaluate the chosen heuristic algorithm as below criteria:


• Admissibility: A heuristic is admissible if it never overestimates the true cost to
reach the goal from any node.
• Consistency: A heuristic is consistent if the estimated cost from a node to the
goal is always less than or equal to the direct step cost to its successor plus
the successor’s estimated cost to the goal.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 26 / 32


Pacman
A* Algorithm - Manhattan Distance

The Manhattan Distance heuristic is used in A* search for grid-based problems


with only vertical and horizontal movements allowed, excluding diagonals.

ManhattanDistance(P1 , P2 ) = |x1 − x2 | + |y1 − y2 | where P1 (x1 , y1 ) and P2 (x2 , y2 )

• Admissibility: It never overestimates the distance on a grid where movement


is restricted to horizontal and vertical steps because it is exactly equal to the
number of steps needed if there are no obstacles.
• Consistency: It is consistent as it precisely reflects the cost reduction with
each grid step towards the goal.
* However, the Manhattan distance is used as heuristic is only admissible if we
want to calculate the distance between any point to a specific goal. But in this
problem, there are several goal destinations (food dots and corners) to make a
final goal (eat all foods and visit all corners), therefore it is difficult come up with a
solution that only use Manhattan distance for the 1 final goal.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 27 / 32


Pacman
A* Algorithm - Manhattan Distance

One of the solution we have tried is to get the Manhattan distance from the
current position to the nearest food dot as the heuristic for each point.

Algorithm 6 get manhattan heuristic(node: Node)


0: goal remains ← get foods remains(node) + get corners remains(node)
0: mht dis ← list()
0: for loc in goal remains do
0: mht dis ← manhattan distance()
0: end for
0: return min(mht dis)
0: =0

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 28 / 32


Pacman
A* Algorithm - Minimum Spanning Tree (MST)

The Minimum Spanning Tree (MST) heuristic provides a lower bound on the cost
to eat all the remaining food. It treats each food pellet as a node in a graph and
calculates the weight of the MST that connects all these nodes, including pacman’s
current position.

MST (n) = weight(MST (all food positions ∪ n))


where weight(MST (all food positions ∪ n)) is the weight of the MST connecting all
the remaining food pellets and node n.
• Admissibility: It is admissible because the weight is always less than or equal
to the actual cost of visiting all the remaining food pellets.
• Consistency: It is consistent because the MST for a node’s successors will
always be equal to or less than the MST for the node plus the step cost to any
successor.

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 29 / 32


Pacman
A* Algorithm - Minimum Spanning Tree (MST)

Algorithm 7 Prim MST (graph)


0: mst weight ← 0; mst edges ← list(); priority queue ← MinHeap(); start vertex ∈
graph; visited ← set()
0: Add start vertex to visited
0: Add all edges from start vertex to priority queue with their weights
0: while priority queue is not empty do
0: (weight, vertex) ← extract min from priority queue
0: if vertex ∈/ visited then
0: Add vertex to visited
0: mst weight ← mst weight + weight
0: Add (weight, vertex) to mst edges
0: for all (adj weight, adj vertex) connected to vertex do
0: if adj vertex ∈/ visited then
0: Add (adj weight, adj vertex) to priority queue
0: end if
0: end for
0: end if
0: end while
return (mst weight, mst edges)
=0
Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 30 / 32
Thank you for listening!
Appendix

ID Full Name Assigned Task Percent


2052082 Bui Trung Hai 8-puzzle Search 100%
2052590 La Vi Luong 8-puzzle Search 100%
2052662 Nguyen Tran Minh Phuoc Pacman Search 100%
2053478 Nguyen Hoang Anh Thu Pacman Search 100%

Hai, Luong, Phuoc, Thu (HCMUT) Short Title April 4, 2024 32 / 32

You might also like