Merge pull request 'a-star-implementation' (#22) from a-star-implementation into main

Reviewed-on: #22
Reviewed-by: Tim Barvenov <timbar@st.amu.edu.pl>
This commit is contained in:
Tim Barvenov 2023-05-14 14:27:45 +02:00
commit ddb69cc1ec
4 changed files with 189 additions and 62 deletions

View File

@ -0,0 +1,113 @@
import heapq
from domain.world import World
class State:
def __init__(self, x, y, direction=(1, 0), entity=None):
self.x = x
self.y = y
self.direction = direction
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return (
self.x == other.x
and self.y == other.y
and self.direction == other.direction
)
def heuristic(self, goal_state):
return abs(self.x - goal_state.x) + abs(self.y - goal_state.y)
class Node:
def __init__(self, state: State, g_score: int, goal_state: State):
self.state = state
self.g_score = g_score
self.f_score = g_score + state.heuristic(goal_state)
self.parent = None
self.action = None
def __lt__(self, other):
return self.f_score < other.f_score
def action_sequence(node: Node):
actions = []
while node.parent:
actions.append(node.action)
node = node.parent
actions.reverse()
return actions
class RotateAndGoAStar:
def __init__(self, world: World, start_state: State, goal_state: State):
self.world = world
self.start_state = start_state
self.goal_state = goal_state
self.fringe = []
self.enqueued_states = set()
self.explored = set()
self.actions = []
def get_g_score(self, state):
return self.world.get_cost(state.x, state.y)
def search(self):
heapq.heappush(
self.fringe, Node(self.start_state, 0, self.goal_state)
)
while self.fringe:
elem = heapq.heappop(self.fringe)
if self.is_goal(elem.state):
self.actions = action_sequence(elem)
return True
self.explored.add(elem.state)
for action, state in self.successors(elem.state):
if state in self.explored:
continue
new_g_score = new_g_score = elem.g_score + self.world.get_cost(state.x, state.y)
if state not in self.enqueued_states:
next_node = Node(state, new_g_score, self.goal_state)
next_node.action = action
next_node.parent = elem
heapq.heappush(self.fringe, next_node)
self.enqueued_states.add(state)
elif new_g_score < self.get_g_score(state):
for node in self.fringe:
if node.state == state:
node.g_score = new_g_score
node.f_score = (
new_g_score + node.state.heuristic(self.goal_state)
)
node.parent = elem
node.action = action
heapq.heapify(self.fringe)
break
return False
def successors(self, state: State):
new_successors = [
("RR", State(state.x, state.y, (-state.direction[1], state.direction[0]))),
("RL", State(state.x, state.y, (state.direction[1], -state.direction[0]))),
]
next_x = state.x + state.direction[0]
next_y = state.y + state.direction[1]
if self.world.accepted_move(next_x, next_y):
new_successors.append(
("GO", State(next_x, next_y, state.direction))
)
return new_successors
def is_goal(self, state: State) -> bool:
return (
state.x == self.goal_state.x
and state.y == self.goal_state.y )

View File

@ -1,58 +1,60 @@
******
Dokumentacja projektu "Automatyczny robot sprzątający"
Wprowadzenie:
Projekt "Automatyczny robot sprzątający" jest projektem bazującym się na symulacji pracy robota sprzątającego w pomieszczeniu za pomocą sztucznej inteligencji. Robot ma za zadanie wyznaczać miejsca do sprzątania oraz uniknąć przeszkód oraz reagować na zdarzenia losowe. Projekt jest napisany w języku Python.
Instrukcja obsługi:
Uruchomienie projektu:
Aby uruchomić projekt należy uruchomić plik "main.py" za pomocą interpretera Python. Projektu wyświetli się w konsoli.Po uruchomieniu projektu na ekranie wyświetli się plansza o wymiarach NxN (default: 10x10). Robot "Cleaner" (oznaczony jako "R" na planszy) startuje z pozycji (0,0). użytkownik ma za zadanie wprowadzić pozycje do sprzątania, które są oznaczone na planszy jako litery "D". Możliwe pozycje to liczby od 0 do N-1.
Użytkownik wprowadza pozycje za pomocą terminala. Wprowadzenie koordynat odbywa się w następujący sposób:
Najpierw wprowadzamy numer wiersza, a następnie numer kolumny, oddzielając je spacją.
Przykładowo, jeśli chcemy wskazać pozycję (4,5) wpisujemy: "4 5".
Po wskazaniu pozycji do sprzątania, użytkownik musi uniknąć przeszkód, które są oznaczone na planszy jako znak "X". Robot nie może przejść przez przeszkody. Jeśli użytkownik wskazuje pozycję przeszkody, projektu zwróci błąd i będzie wymagała podania nowych współrzędnych.
Przebieg projektu:
Robot, zgodnie z zbudowaną mapą, musi obliczyć najkrótszą ścieżkę do sprzątania wszystkich pozycji oraz uniknąć przeszkód. Podczas sprzątania mogą wystąpić przypadkowe zdarzenia, na które robot będzie reagował. W tym celu, z pomocą sieci neuronowych, robot analizuje zdjęcie zdarzenia, aby wybrać najlepsze rozwiązania.
Zakończenie projektu:
Program kończy swoje działanie w momencie, gdy robot posprząta wszystkie przez użytkownika wybrane pola do sprzątania. Na zakończenie programu zostanie wyświetlona liczba wykonanych ruchów przez robota oraz podjęte decyzje w przypadku zaistnienia zdarzeń.
Możliwe modyfikacje:
Projekt zostanie napisany z myślą o możliwości łatwej modyfikacji. Można zmienić wymiary planszy, dodać lub usunąć przeszkody oraz ilość przypadkowych zdarzeń i pozycji do sprzątania. Wszystkie te zmiany można wprowadzić w pliku "config.py".
Podsumowanie:
Projekt "Automatyczny robot sprzątający" to prosty, ale edukacyjny projekt programistyczny. Użytkownik ma za zadanie wskazanie pozycji, które robot powinien posprzątać, a także koordynat przeszkody. Natomiast zadaniem robota, który został zbudowany przy użyciu sztucznej inteligencji, jest unikanie przeszkód, podejmowanie decyzji w przypadku wystąpienia przypadkowych zdarzeń oraz sprzątanie wyznaczonych punktów. Projekt został napisany w języku Python z wykorzystaniem sztucznej inteligencji. Analiza zdjęć jest oparta na sieciach neuronowych.
******
Documentation of the "Automatic Cleaning Robot" project
Introduction:
The "Automatic Cleaning Robot" project is based on simulating the work of a cleaning robot in a room using artificial intelligence. The robot is tasked with determining the areas to be cleaned, avoiding obstacles, and reacting to random events. The project is written in Python.
User Guide:
Starting the project:
To start the project, you need to run the "main.py" file using a Python interpreter. The project will be displayed on the console. Once the project is launched, a 10x10 board will be displayed on the screen. The "Cleaner" robot (marked as "R" on the board) starts from the position (0,0). The user needs to enter the positions to be cleaned, which are marked as the letter "D" on the board. The possible positions are numbers from 0 to 9.
The user enters the positions through the terminal. The entry of coordinates is done as follows:
First, we enter the row number, and then the column number, separating them with a space.
For example, if we want to indicate the position (4,5), we enter "4 5".
After indicating the positions to be cleaned, the user must avoid obstacles, which are marked on the board as the "X" symbol. The robot cannot pass through obstacles. If the user points to an obstacle position, the project will return an error and require new coordinates.
Project process:
Based on the built map, the robot must calculate the shortest path to clean all positions and avoid obstacles. Random events may occur during cleaning, to which the robot will react. To do this, with the help of neural networks, the robot analyzes the image of the event to choose the best solutions.
Project conclusion:
The program is ending when the robot cleans all the fields selected by the user. At the end of the program, the number of robot moves performed and the decisions made in case of events will be displayed.
Possible modifications:
The "Automatic cleaning robot" project has been designed with the possibility of easy modifications in mind. Users can change the dimensions of the board, add or remove obstacles, and adjust the number of random events and cleaning positions. All these changes can be made in the "config.py" file.
Summary:
The "Automatic cleaning robot" project is a simple yet educational programming project. Users are tasked with specifying the positions that the robot should clean, as well as the coordinates of obstacles. The robot, built using artificial intelligence, is responsible for avoiding obstacles, making decisions in case of random events, and cleaning the designated points. The project was written in Python with the use of artificial intelligence. The analysis of images is based on neural networks.
******
******
Dokumentacja projektu "Automatyczny robot sprzątający"
Wprowadzenie:
Projekt "Automatyczny robot sprzątający" jest projektem bazującym się na symulacji pracy robota sprzątającego w pomieszczeniu za pomocą sztucznej inteligencji. Robot ma za zadanie wyznaczać miejsca do sprzątania oraz uniknąć przeszkód oraz reagować na zdarzenia losowe. Projekt jest napisany w języku Python.
Instrukcja obsługi:
Uruchomienie projektu:
Aby uruchomić projekt należy uruchomić plik "main.py" za pomocą interpretera Python. Projektu wyświetli się w konsoli.Po uruchomieniu projektu na ekranie wyświetli się plansza o wymiarach NxN (default: 10x10). Robot "Cleaner" (oznaczony jako "R" na planszy) startuje z pozycji (0,0). użytkownik ma za zadanie wprowadzić pozycje do sprzątania, które są oznaczone na planszy jako litery "D". Możliwe pozycje to liczby od 0 do N-1.
Użytkownik wprowadza pozycje za pomocą terminala. Wprowadzenie koordynat odbywa się w następujący sposób:
Najpierw wprowadzamy numer wiersza, a następnie numer kolumny, oddzielając je spacją.
Przykładowo, jeśli chcemy wskazać pozycję (4,5) wpisujemy: "4 5".
Po wskazaniu pozycji do sprzątania, użytkownik musi uniknąć przeszkód, które są oznaczone na planszy jako znak "X". Robot nie może przejść przez przeszkody. Jeśli użytkownik wskazuje pozycję przeszkody, projektu zwróci błąd i będzie wymagała podania nowych współrzędnych.
Przebieg projektu:
Robot, zgodnie z zbudowaną mapą, musi obliczyć najkrótszą ścieżkę do sprzątania wszystkich pozycji oraz uniknąć przeszkód. Podczas sprzątania mogą wystąpić przypadkowe zdarzenia, na które robot będzie reagował. W tym celu, z pomocą sieci neuronowych, robot analizuje zdjęcie zdarzenia, aby wybrać najlepsze rozwiązania.
Zakończenie projektu:
Program kończy swoje działanie w momencie, gdy robot posprząta wszystkie przez użytkownika wybrane pola do sprzątania. Na zakończenie programu zostanie wyświetlona liczba wykonanych ruchów przez robota oraz podjęte decyzje w przypadku zaistnienia zdarzeń.
Możliwe modyfikacje:
Projekt zostanie napisany z myślą o możliwości łatwej modyfikacji. Można zmienić wymiary planszy, dodać lub usunąć przeszkody oraz ilość przypadkowych zdarzeń i pozycji do sprzątania. Wszystkie te zmiany można wprowadzić w pliku "config.py".
Podsumowanie:
Projekt "Automatyczny robot sprzątający" to prosty, ale edukacyjny projekt programistyczny. Użytkownik ma za zadanie wskazanie pozycji, które robot powinien posprzątać, a także koordynat przeszkody. Natomiast zadaniem robota, który został zbudowany przy użyciu sztucznej inteligencji, jest unikanie przeszkód, podejmowanie decyzji w przypadku wystąpienia przypadkowych zdarzeń oraz sprzątanie wyznaczonych punktów. Projekt został napisany w języku Python z wykorzystaniem sztucznej inteligencji. Analiza zdjęć jest oparta na sieciach neuronowych.
******
Documentation of the "Automatic Cleaning Robot" project
Introduction:
The "Automatic Cleaning Robot" project is based on simulating the work of a cleaning robot in a room using artificial intelligence. The robot is tasked with determining the areas to be cleaned, avoiding obstacles, and reacting to random events. The project is written in Python.
User Guide:
Starting the project:
To start the project, you need to run the "main.py" file using a Python interpreter. The project will be displayed on the console. Once the project is launched, a 10x10 board will be displayed on the screen. The "Cleaner" robot (marked as "R" on the board) starts from the position (0,0). The user needs to enter the positions to be cleaned, which are marked as the letter "D" on the board. The possible positions are numbers from 0 to 9.
The user enters the positions through the terminal. The entry of coordinates is done as follows:
First, we enter the row number, and then the column number, separating them with a space.
For example, if we want to indicate the position (4,5), we enter "4 5".
After indicating the positions to be cleaned, the user must avoid obstacles, which are marked on the board as the "X" symbol. The robot cannot pass through obstacles. If the user points to an obstacle position, the project will return an error and require new coordinates.
Project process:
Based on the built map, the robot must calculate the shortest path to clean all positions and avoid obstacles. Random events may occur during cleaning, to which the robot will react. To do this, with the help of neural networks, the robot analyzes the image of the event to choose the best solutions.
Project conclusion:
The program is ending when the robot cleans all the fields selected by the user. At the end of the program, the number of robot moves performed and the decisions made in case of events will be displayed.
Possible modifications:
The "Automatic cleaning robot" project has been designed with the possibility of easy modifications in mind. Users can change the dimensions of the board, add or remove obstacles, and adjust the number of random events and cleaning positions. All these changes can be made in the "config.py" file.
Summary:
The "Automatic cleaning robot" project is a simple yet educational programming project. Users are tasked with specifying the positions that the robot should clean, as well as the coordinates of obstacles. The robot, built using artificial intelligence, is responsible for avoiding obstacles, making decisions in case of random events, and cleaning the designated points. The project was written in Python with the use of artificial intelligence. The analysis of images is based on neural networks.
******
******

View File

@ -4,6 +4,7 @@ from domain.entities.entity import Entity
class World:
def __init__(self, width: int, height: int) -> object:
self.costs = [[1000 for j in range(height)] for i in range(width)]
self.width = width
self.height = height
self.dust = [[[] for j in range(height)] for i in range(width)]
@ -53,3 +54,5 @@ class World:
return False
return True
def get_cost(self, x, y):
return self.costs[x][y]

17
main.py
View File

@ -14,7 +14,8 @@ from domain.entities.docking_station import Doc_Station
from domain.world import World
from view.renderer import Renderer
# from AI_brain.movement import GoAnyDirectionBFS, State
from AI_brain.rotate_and_go_bfs import RotateAndGoBFS, State
# from AI_brain.rotate_and_go_bfs import RotateAndGoBFS, State
from AI_brain.rotate_and_go_astar import RotateAndGoAStar, State
config = configparser.ConfigParser()
@ -52,7 +53,8 @@ class Main:
end_state = State(self.world.doc_station.x, self.world.doc_station.y)
# path_searcher = GoAnyDirectionBFS(self.world, start_state, end_state)
path_searcher = RotateAndGoBFS(self.world, start_state, end_state)
# path_searcher = RotateAndGoBFS(self.world, start_state, end_state)
path_searcher = RotateAndGoAStar(self.world, start_state, end_state)
if not path_searcher.search():
print("No solution")
exit(0)
@ -134,7 +136,7 @@ class Main:
def generate_world(tiles_x: int, tiles_y: int) -> World:
world = World(tiles_x, tiles_y)
for _ in range(10):
for _ in range(35):
temp_x = randint(0, tiles_x - 1)
temp_y = randint(0, tiles_y - 1)
world.add_entity(Garbage(temp_x, temp_y))
@ -149,8 +151,15 @@ def generate_world(tiles_x: int, tiles_y: int) -> World:
world.add_entity(Entity(8, 8, "PLANT2"))
world.add_entity(Entity(9, 3, "PLANT3"))
world.add_entity(Earring(5, 5))
return world
for x in range(world.width):
for y in range(world.height):
if world.is_garbage_at(x, y):
world.costs[x][y] = 1
else:
world.costs[x][y] = 10
return world
if __name__ == "__main__":
app = Main()