feat: Added genetic algo

This commit is contained in:
Jager72 2024-06-23 22:03:39 +02:00
parent cf186c2ef1
commit 07190773ac
3 changed files with 149 additions and 91 deletions

118
app.py
View File

@ -19,12 +19,13 @@ from classes.Jimmy_Neuron.predict_image import predict_image
pygame.init() pygame.init()
window = pygame.display.set_mode((prefs.WIDTH, prefs.HEIGHT)) window = pygame.display.set_mode((prefs.WIDTH, prefs.HEIGHT))
pygame.display.set_caption("Game Window") pygame.display.set_caption("Game Window")
table_coords = [(4, 4), (4, prefs.GRID_SIZE-5), (prefs.GRID_SIZE-5, 4), (prefs.GRID_SIZE-5, prefs.GRID_SIZE-5)] table_coords = [(12, 2), (16, 11), (4, 4), (15, 4), (2, 9), (15, 15), (12, 12), (7, 8), (4, 15)]
table_ordered = [(4, 4), (12, 2), (15, 4), (16, 11), (15, 15), (12, 12), (7, 8), (4, 15), (2, 9)]
from classes.data.data_initializer import clients from classes.data.data_initializer import clients
chosen_coords = random.choice(table_coords) orders = []
chosen_index = random.randint(0, len(table_coords)-1) chosen_index = 0
chosen_coords = table_coords[chosen_index] chosen_coords = table_ordered[chosen_index]
klientx_target = chosen_coords[0] + 1 klientx_target = chosen_coords[0] + 1
klienty_target = chosen_coords[1] + 1 klienty_target = chosen_coords[1] + 1
# klientx_target = 16 # klientx_target = 16
@ -65,11 +66,8 @@ def initBoard():
cells[6][6].interactableItem = BeerKeg(cells[6][6], "Beer Keg") cells[6][6].interactableItem = BeerKeg(cells[6][6], "Beer Keg")
cells[4][10].interactableItem = CoffeMachine(cells[4][10], "Coffe Machine") cells[4][10].interactableItem = CoffeMachine(cells[4][10], "Coffe Machine")
cells[4][4].interactableItem = Table(cells[4][4], "Table") for cell in table_ordered:
cells[4][prefs.GRID_SIZE-5].interactableItem = Table(cells[4][prefs.GRID_SIZE-5], "Table") cells[cell[0]][cell[1]].interactableItem = Table(cells[cell[0]][cell[1]], "Table")
cells[prefs.GRID_SIZE-5][4].interactableItem = Table(cells[prefs.GRID_SIZE-5][4], "Table")
cells[prefs.GRID_SIZE-5][prefs.GRID_SIZE-5].interactableItem = Table(cells[prefs.GRID_SIZE-5][prefs.GRID_SIZE-5], "Table")
# cells[9][9].waga = 2 # cells[9][9].waga = 2
# cells[9][8].waga = 10 # cells[9][8].waga = 10
@ -99,17 +97,17 @@ def draw_grid(window, cells, agent):
initBoard() initBoard()
agent = Agent(prefs.SPAWN_POINT[0], prefs.SPAWN_POINT[1], cells) agent = Agent(prefs.SPAWN_POINT[0], prefs.SPAWN_POINT[1], cells)
klient = Klient(prefs.GRID_SIZE-1, 17,cells) klients = [ Klient(table_ordered[i][0]+ 1, table_ordered[i][1]+ 1, cells) for i in range(len(table_ordered)) ]
target_x, target_y = klientx_target-1, klienty_target target_x, target_y = klientx_target-1, klienty_target
def watekDlaSciezkiAgenta(): def watekDlaSciezkiAgenta():
assigned = False assigned = False
has_visited_beer_keg = False global chosen_index
has_visited_coffee = False
adult = False
time.sleep(1.5) time.sleep(1.5)
while True: while True:
if len(path) > 0: if len(path) > 0:
print(path)
element = path.pop(0) element = path.pop(0)
if element == "left": if element == "left":
agent.rotate_left() agent.rotate_left()
@ -125,7 +123,7 @@ def watekDlaSciezkiAgenta():
if not assigned: if not assigned:
neighbors = agent.get_neighbors(agent.current_cell, agent.cells) neighbors = agent.get_neighbors(agent.current_cell, agent.cells)
for neighbor in neighbors: for neighbor in neighbors:
if neighbor == klient.current_cell: if neighbor == klients[chosen_index].current_cell and len(path) == 0:
if not assigned: if not assigned:
random_client_data = random.choice(clients) random_client_data = random.choice(clients)
glasses = predict_image(random_client_data.zdjecie) glasses = predict_image(random_client_data.zdjecie)
@ -135,65 +133,52 @@ def watekDlaSciezkiAgenta():
print(random_client_data) print(random_client_data)
print("Prediction (Glasses):", glasses) print("Prediction (Glasses):", glasses)
print("Prediction (Adult):", prediction) print("Prediction (Adult):", prediction)
print("Prediction: ", prediction)
orders.append(prediction)
assigned = True assigned = True
if prediction == "Yes":
path_beer = agent.bfs2(6,6)
if path_beer:
path.extend(path_beer)
elif prediction == "No":
path_coffee = agent.bfs2(4,10)
if path_coffee:
path.extend(path_coffee)
if assigned: if assigned:
if prediction == "Yes": if(chosen_index < len(klients) - 1):
if not has_visited_beer_keg: chosen_index += 1
if agent.current_cell == cells[6][6]: target_x, target_y = table_ordered[chosen_index][0], table_ordered[chosen_index][1]+1
has_visited_beer_keg = True move_back = agent.bfs2(target_x,target_y)
move_back = agent.bfs2(target_x,target_y) if move_back:
if move_back: path.extend(move_back)
path.extend(move_back) assigned = False
else:
elif prediction == "No": print("Orders: ", orders)
if not has_visited_coffee: return
if agent.current_cell == cells[4][10]: time.sleep(0.3)
has_visited_coffee = True
move_back = agent.bfs2(target_x,target_y)
if move_back:
path.extend(move_back)
time.sleep(0.5) # def watekDlaSciezkiKlienta():
# time.sleep(1)
# while True:
# if len(path2) > 0:
# element2 = path2.pop(0)
# print(element2)
# if element2 == "left":
# klient.rotate_left()
# if element2 == "right":
# klient.rotate_right()
# if element2 == "forward":
# klient.move_direction()
# elif isinstance(element2, tuple): # Check if it's a tuple indicating movement coordinates
# x, y = element2
# klient.moveto(x, y)
def watekDlaSciezkiKlienta(): # if klient.current_cell == cells[klientx_target][klienty_target]:
time.sleep(1) # klient.przyStoliku = True
while True: # klient.stolik = klient.current_cell
if len(path2) > 0:
element2 = path2.pop(0)
print(element2)
if element2 == "left":
klient.rotate_left()
if element2 == "right":
klient.rotate_right()
if element2 == "forward":
klient.move_direction()
elif isinstance(element2, tuple): # Check if it's a tuple indicating movement coordinates
x, y = element2
klient.moveto(x, y)
if klient.current_cell == cells[klientx_target][klienty_target]: # time.sleep(0.5)
klient.przyStoliku = True
klient.stolik = klient.current_cell
time.sleep(0.5)
path2 = klient.bfs2(klientx_target, klienty_target) # path2 = klient.bfs2(klientx_target, klienty_target)
print("Najkrótsza ścieżka:", path2) # print("Najkrótsza ścieżka:", path2)
watek = threading.Thread(target=watekDlaSciezkiKlienta) # watek = threading.Thread(target=watekDlaSciezkiKlienta)
watek.daemon = True # watek.daemon = True
watek.start() # watek.start()
path = agent.bfs2(target_x, target_y) path = agent.bfs2(target_x, target_y)
print("Najkrótsza ścieżka:", path) print("Najkrótsza ścieżka:", path)
@ -246,7 +231,8 @@ while running:
window.fill((255, 0, 0)) window.fill((255, 0, 0))
draw_grid(window, cells, agent) draw_grid(window, cells, agent)
agent.update(window) agent.update(window)
klient.update(window) for klient in klients:
klient.update(window)
pygame.display.update() pygame.display.update()
time.sleep(0.05) time.sleep(0.05)

View File

@ -0,0 +1,71 @@
import random
table_coords = [(12, 2), (16, 11), (4, 4), (15, 4), (2, 9), (15, 15), (12, 12), (7, 8), (4, 15)]
def krzyzowanie(rodzic1, rodzic2, pnkt):
dzieciak1 = rodzic1[:]
for i in range(pnkt):
tempInd = dzieciak1.index(rodzic2[i])
dzieciak1[tempInd] = dzieciak1[i]
dzieciak1[i] = rodzic2[i]
dzieciak2 = rodzic2[:]
for i in range(pnkt):
tempInd = dzieciak2.index(rodzic1[i])
dzieciak2[tempInd] = dzieciak2[i]
dzieciak2[i] = rodzic1[i]
return dzieciak1, dzieciak2
def stworzOsobnika():
return random.sample(table_coords, len(table_coords))
def rankuj(populacja):
return sorted(populacja, key=lambda x: funkcjaCelu(x))
def funkcjaCelu(osobnik):
sum = 0
for i in range(len(osobnik)):
j = i + 1
if i == len(osobnik) - 1:
j = 0
sum += abs(osobnik[i][0] - osobnik[j][0]) + abs(osobnik[i][1] - osobnik[j][1])
sum += abs(5 - osobnik[0][0]) + abs(5 - osobnik[0][1]) #dodawanie odległości od punktu (5,5), spawn agenta
return sum
def mutacja(osobnik):
if random.random() < 0.01:
ind1 = random.randint(0, len(osobnik)-1)
ind2 = random.randint(0, len(osobnik)-1)
osobnik[ind1], osobnik[ind2] = osobnik[ind2], osobnik[ind1]
return osobnik
def genetyk(liczebnosc, iteracje):
populacja = [stworzOsobnika() for _ in range(liczebnosc)]
for i in range(iteracje):
rankingowaPopulacja = rankuj(populacja)
populacja = rankingowaPopulacja[:liczebnosc]
nowePokolenie = []
for j in range(0, liczebnosc, 2):
rodzic1 = rankingowaPopulacja[j]
rodzic2 = rankingowaPopulacja[j+1]
punktKrzyzowania = random.randint(0, 7)
dzeciak1, dzieciak2 = krzyzowanie(rodzic1, rodzic2, punktKrzyzowania)
dzeciak1 = mutacja(dzeciak1)
dzieciak2 = mutacja(dzieciak2)
nowePokolenie.extend([dzeciak1, dzieciak2])
populacja.extend(nowePokolenie)
najlepszy = rankuj(populacja)[0]
return najlepszy
data = genetyk(50, 30)
print(funkcjaCelu(data))
print(data)

View File

@ -149,41 +149,42 @@ for server in root.findall('server'):
# Prezentacja uzycia przykładowego # Prezentacja uzycia przykładowego
import random # import random
stoliki = [] # stoliki = []
for i in range(3): # for i in range(3):
stolik = Stolik(i+1) # stolik = Stolik(i+1)
stoliki.append(stolik) # stoliki.append(stolik)
stolik.przypisz_kelner(servers[i%len(servers)]) # stolik.przypisz_kelner(servers[i%len(servers)])
zamowienia = [] # zamowienia = []
for i in range(6): # for i in range(6):
zamowienie = [] # zamowienie = []
for j in range(random.randint(1, 5)): # for j in range(random.randint(1, 5)):
zamowienie.append(meals[random.randint(0, len(meals)-1)]) # zamowienie.append(meals[random.randint(0, len(meals)-1)])
zamowienia.append(Zamowienie(i+1, zamowienie)) # zamowienia.append(Zamowienie(i+1, zamowienie))
i=0 # i=0
for stolik in stoliki: # for stolik in stoliki:
klient = clients[i%len(clients)] # klient = clients[i%len(clients)]
i=i+1 # i=i+1
klient.zloz_zamowienie(zamowienia[random.randint(0, len(zamowienia)-1)], stolik) # klient.zloz_zamowienie(zamowienia[random.randint(0, len(zamowienia)-1)], stolik)
for klient in [k for k in clients if k.stolik is not None]: # for klient in [k for k in clients if k.stolik is not None]:
print(f"Klient {klient.imie} {klient.nazwisko} ma następujące Zamowienia:") # print(f"Klient {klient.imie} {klient.nazwisko} ma następujące Zamowienia:")
print(f"\t{klient.rachunek} i sumą {klient.rachunek.suma()}") # print(f"\t{klient.rachunek} i sumą {klient.rachunek.suma()}")
print("----------------\n\n") # print("----------------\n\n")
import classes.data.logic_test as logic # import classes.data.logic_test as logic
# for klient in [k for k in clients if k.stolik is not None]:
# for zamownienie in klient.rachunek.zamowienia:
# print(logic.diet_restriction(zamowienie, klient))
for klient in [k for k in clients if k.stolik is not None]:
for zamownienie in klient.rachunek.zamowienia:
print(logic.diet_restriction(zamowienie, klient))
# for meal in meals: # for meal in meals:
# print(meal) # print(meal)