Skip to content

Commit

Permalink
Format all code
Browse files Browse the repository at this point in the history
  • Loading branch information
GrahamStrickland committed Oct 16, 2024
1 parent 780452a commit c71b89e
Show file tree
Hide file tree
Showing 31 changed files with 329 additions and 298 deletions.
3 changes: 1 addition & 2 deletions src/agents/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from .model_based_reflex_agent import ModelBasedReflexAgent
from .model_based_reflex_agent import ModelBasedReflexAgent
from .randomized_reflex_agent import RandomizedReflexAgent
from .reflex_vacuum_agent import reflex_vacuum_agent
from .simple_reflex_agent import SimpleReflexAgent

85 changes: 44 additions & 41 deletions src/agents/model_based_reflex_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,24 @@
class ModelBasedReflexAgent:
def __init__(self, possible_locations: list[list[str]]):
self._state = {
'Environment': Environment(
name='VacuumWorld',
"Environment": Environment(
name="VacuumWorld",
state=dict(
(location, None) for locations in possible_locations for location in locations
)
(location, None)
for locations in possible_locations
for location in locations
),
),
'Geography': possible_locations,
'Current': None,
'Next': None,
'Points': 0
"Geography": possible_locations,
"Current": None,
"Next": None,
"Points": 0,
}
self._transition_model = {'Suck': 1,
'Move': -1}
self._transition_model = {"Suck": 1, "Move": -1}
self._sensor_model = Sensor(None, None)
self._rules = {'Dirty': 'Suck',
'Clean': 'Move',
'Blocked': 'Stay'}
self._action = Actuator('action', None)
self._directions = ['Up', 'Right', 'Down', 'Left']
self._rules = {"Dirty": "Suck", "Clean": "Move", "Blocked": "Stay"}
self._action = Actuator("action", None)
self._directions = ["Up", "Right", "Down", "Left"]
self._direction = 0

def get_action(self, percept: Sensor) -> str:
Expand All @@ -34,38 +33,43 @@ def get_action(self, percept: Sensor) -> str:
return self._action.value

def get_points(self) -> int:
return self._state['Points']
return self._state["Points"]

def _update_state(self, percept: Sensor) -> None:
self._sensor_model = percept

if self._state['Current'] == self._sensor_model.name and self._action.value in self._directions:
self._state['Environment'].state[self._state['Next']] = 'Blocked'
if (
self._state["Current"] == self._sensor_model.name
and self._action.value in self._directions
):
self._state["Environment"].state[self._state["Next"]] = "Blocked"

self._state['Current'] = self._sensor_model.name
self._state['Environment'].state[self._sensor_model.name] = self._sensor_model.value
self._state["Current"] = self._sensor_model.name
self._state["Environment"].state[self._sensor_model.name] = (
self._sensor_model.value
)

def _get_next_position(self, move: str, row_num: int, col_num: int) -> str:
possible_locations = self._state['Geography']
possible_locations = self._state["Geography"]

match move:
case 'Up':
case "Up":
if row_num - 1 >= 0:
return possible_locations[row_num-1][col_num]
case 'Right':
return possible_locations[row_num - 1][col_num]
case "Right":
if col_num + 1 < len(possible_locations[0]):
return possible_locations[row_num][col_num+1]
case 'Down':
return possible_locations[row_num][col_num + 1]
case "Down":
if row_num + 1 < len(possible_locations):
return possible_locations[row_num+1][col_num]
case 'Left':
return possible_locations[row_num + 1][col_num]
case "Left":
if col_num - 1 >= 0:
return possible_locations[row_num][col_num-1]
return possible_locations[row_num][col_num - 1]

return possible_locations[row_num][col_num]

def _get_current_position(self, curr: str) -> tuple[int]:
possible_locations = self._state['Geography']
possible_locations = self._state["Geography"]

for row_num in range(len(possible_locations)):
for col_num in range(len(possible_locations[row_num])):
Expand All @@ -75,25 +79,24 @@ def _get_current_position(self, curr: str) -> tuple[int]:
raise IndexError("Incorrect row and column reference")

def _rule_match(self) -> None:
curr = self._state['Current']
state = self._state['Environment'].state
curr = self._state["Current"]
state = self._state["Environment"].state
action = self._rules[state[curr]]

if action == 'Move':
if action == "Move":
row_num, col_num = self._get_current_position(curr)

while action == 'Move':
while action == "Move":
move = self._directions[self._direction]
next = self._get_next_position(move, row_num, col_num)
self._state['Next'] = next
if next != curr and state[next] != ('Blocked' or 'Clean'):
self._state["Next"] = next
if next != curr and state[next] != ("Blocked" or "Clean"):
action = move
else:
self._direction = randint(0, len(self._directions) - 1)

self._action.value = action
if action in self._directions:
self._state['Points'] += self._transition_model['Move']
self._state["Points"] += self._transition_model["Move"]
else:
self._state['Points'] += self._transition_model[self._action.value]

self._state["Points"] += self._transition_model[self._action.value]
16 changes: 6 additions & 10 deletions src/agents/randomized_reflex_agent.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
#!/usr/bin/env python3
from random import randint

from ..data_structures import Actuator, Environment, Sensor
from ..data_structures import Actuator, Sensor


class RandomizedReflexAgent:
def __init__(self):
self._rules = {'Dirty': 'Suck',
'Clean': ['Left', 'Right', 'Up', 'Down']}
self._rules = {"Dirty": "Suck", "Clean": ["Left", "Right", "Up", "Down"]}

def get_action(self, percept: Sensor) -> Actuator:
state: dict[str, str] = self._interpret_input(percept)
Expand All @@ -21,16 +20,13 @@ def _interpret_input(percept: Sensor) -> dict:
return {percept.name: percept.value}

def _rule_match(self, state: dict[str, str]) -> Actuator:
action: str = ''
action: str = ""

for _, v in state.items():
if v == 'Dirty':
if v == "Dirty":
action = self._rules[v]
else:
action = self._rules[v][
randint(0, len(self._rules['Clean']) - 1)
]
action = self._rules[v][randint(0, len(self._rules["Clean"]) - 1)]
break

return Actuator(name='action', value=action)

return Actuator(name="action", value=action)
17 changes: 8 additions & 9 deletions src/agents/reflex_vacuum_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ def reflex_vacuum_agent(location_status: Sensor) -> Actuator:
location: str = location_status.name
status: str = location_status.value

action: str = ''
if status == 'Dirty':
action = 'Suck'
elif location == 'A':
action = 'Right'
elif location == 'B':
action = 'Left'

return Actuator('action', action)
action: str = ""
if status == "Dirty":
action = "Suck"
elif location == "A":
action = "Right"
elif location == "B":
action = "Left"

return Actuator("action", action)
15 changes: 5 additions & 10 deletions src/agents/simple_reflex_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,7 @@

class SimpleReflexAgent:
def __init__(self):
self._rules = {'Dirty': 'Suck',
'Clean': {
'A': 'Right',
'B': 'Left'
}
}
self._rules = {"Dirty": "Suck", "Clean": {"A": "Right", "B": "Left"}}

def get_action(self, percept: Sensor) -> Actuator:
state: dict[str, str] = self._interpret_input(percept)
Expand All @@ -23,13 +18,13 @@ def _interpret_input(percept: Sensor) -> dict:
return {percept.name: percept.value}

def _rule_match(self, state: dict[str, str]) -> Actuator:
action: str = ''
action: str = ""

for k, v in state.items():
if v == 'Dirty':
if v == "Dirty":
action = self._rules[v]
else:
action = self._rules['Clean'][k]
action = self._rules["Clean"][k]
break

return Actuator(name='action', value=action)
return Actuator(name="action", value=action)
4 changes: 2 additions & 2 deletions src/algorithms/best_first_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

def best_first_search(problem: Problem, f: Callable) -> Node | None:
"""On each iteration choose a node on the frontier with minimum f(n) value,
return it if its state is a goal state, and otherwise apply expand() to
return it if its state is a goal state, and otherwise apply expand() to
generate child nodes.
Args:
Expand All @@ -28,7 +28,7 @@ def best_first_search(problem: Problem, f: Callable) -> Node | None:
node: Node = frontier.pop()
if problem.is_goal(node.state):
return node

for child in expand(problem, node):
s: str = child.state
if s not in reached.keys():
Expand Down
53 changes: 34 additions & 19 deletions src/algorithms/bibf_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,41 @@ def terminated(
def join_nodes(dir: Direction, node_f: Node, node_b: Node) -> Node:
if dir == Direction.F:
while node_b.parent is not None:
node = Node(state=node_b.state, path_cost=node_b.path_cost, parent=node_f, action=("To" + node_b.state))
node = Node(
state=node_b.state,
path_cost=node_b.path_cost,
parent=node_f,
action=("To" + node_b.state),
)
node_f = node
node_b = node_b.parent

return node_b
else:
while node_f.parent is not None:
node = Node(state=node_f.state, path_cost=node_f.path_cost, parent=node_b, action=("To" + node_f.state))
node = Node(
state=node_f.state,
path_cost=node_f.path_cost,
parent=node_b,
action=("To" + node_f.state),
)
node_b = node
node_f = node_f.parent

return node_f


def proceed(
dir: Direction, problem: Problem, frontier: PriorityQueue, reached: dict[str, Node],
reached2: dict[str, Node], solution: Node | None) -> Node | None:
dir: Direction,
problem: Problem,
frontier: PriorityQueue,
reached: dict[str, Node],
reached2: dict[str, Node],
solution: Node | None,
) -> Node | None:
"""Expand node on frontier; check against the other frontier in reached2.
Args:
Args:
dir: The direction: either 'F' for forward or 'B' for backward.
"""
node = frontier.pop()
Expand All @@ -65,7 +80,7 @@ def proceed(
def bibf_search(
problem_f: Problem, ff: Callable, problem_b: Problem, fb: Callable
) -> Node | None:
"""Keeps two frontiers and two tables of reached states, joining the two
"""Keeps two frontiers and two tables of reached states, joining the two
frontiers once the same state has been reached in both to yield a solution.
Args:
Expand Down Expand Up @@ -97,21 +112,21 @@ def bibf_search(
):
if ff(frontier_f.top()) < fb(frontier_b.top()):
solution = proceed(
dir=Direction.F,
problem=problem_f,
frontier=frontier_f,
reached=reached_f,
reached2=reached_b,
solution=solution
dir=Direction.F,
problem=problem_f,
frontier=frontier_f,
reached=reached_f,
reached2=reached_b,
solution=solution,
)
else:
solution = proceed(
dir=Direction.B,
problem=problem_b,
frontier=frontier_b,
reached=reached_b,
reached2=reached_f,
solution=solution
dir=Direction.B,
problem=problem_b,
frontier=frontier_b,
reached=reached_b,
reached2=reached_f,
solution=solution,
)

return solution
Loading

0 comments on commit c71b89e

Please sign in to comment.