Compare commits

...

25 Commits
tree ... master

Author SHA1 Message Date
366716a32b Merge pull request 'Merge master with genetic_algorithms branch' (#29) from genetic_algorithms into master
Reviewed-on: #29
2024-06-09 18:40:57 +02:00
99c709d271 Merge pull request 'Merge genetic_algorithms with final_show branch' (#28) from final_show into genetic_algorithms
Reviewed-on: #28
2024-06-09 18:40:24 +02:00
b78f7f5ee7 Merge pull request 'Merge genetic2 to final_show' (#27) from genetic2 into final_show
Reviewed-on: #27
2024-06-09 18:39:27 +02:00
eb2529831a This: -added goaltressure in bfs3 call in App.py -changed def value for randomGT in BFS3 in bfs.py -added more context to readme.txt 2024-06-09 18:33:50 +02:00
d61b585827 Corrected GeneticAlgorithm2 and made a GeneticAlgorithm3 and generated fields using them. Made GeneticAccuracy to check the performance of the algorithms. 2024-06-08 23:25:08 +02:00
6c86eebd89 genetic algorithm 2 with a value of None 2024-06-07 18:41:55 +02:00
da1bfe1d8f This: -changed readme.txt 2024-06-07 15:29:26 +02:00
4339284c4b This: -changed label for decision -changed goaltressure for BFS3 2024-06-07 15:01:15 +02:00
tafit0902
51a5b13669 ladowanie pola z pliku GA, rozpoznawanie zdjec na polu, decyzja o podlaniu 2024-06-07 00:02:36 +02:00
0becd1b1f6 Made genetic algorithm and made a field using it. 2024-06-06 08:35:36 +02:00
eb9744f52f Merge pull request 'refactor' (#26) from refactor into master
Reviewed-on: #26
2024-06-04 13:25:07 +02:00
ea6a9f5204 Merge pull request 'neural_network' (#25) from neural_network into refactor
Reviewed-on: #25
2024-06-04 13:23:15 +02:00
7a3c30bd2f Added some trained models. 2024-06-04 13:18:15 +02:00
53ec8e993e Merge pull request 'Merge with model for 2 crops only' (#23) from neural_network_two_crops into neural_network
Reviewed-on: #23
2024-06-04 12:45:15 +02:00
24724fb8b7 This: -added trained model for 2 crops -added way to choose which model should we use 2024-06-04 12:40:39 +02:00
16302f4d6c Merge pull request 'Merge old branches to refactor due to merge it with master' (#22) from tree into refactor
Reviewed-on: #22
2024-06-04 11:36:13 +02:00
38c1adb054 This: -improved printing of results -fixed a bug where picking tomato fertilizer caused crash -added trained model_500_hidden.pth trained with 500 hidden layers 2024-05-27 09:01:51 +02:00
ccd1cb2359 Trained the model. 2024-05-26 18:41:55 +02:00
5d7b68fdd6 This: -removed model.pth from git tracking for now -added corn to dataset 2024-05-26 14:46:12 +02:00
34bfe78218 This: -fixed line where device for training was always cuda device 2024-05-26 14:39:05 +02:00
26c99ddc55 This: -enchanced image dataset -fixed a bug where images where not loaded -fixed a bug where tractor wasnt moving -fixed a bug where training on gpu caused a crash 2024-05-26 13:58:48 +02:00
tafit0902
d2abac6ebd roslina umiera po zlym nawiezieniu 2024-05-26 01:55:40 +02:00
tafit0902
de0740d34b losowanie bez powtorzen, poprawki w wyswieltaniu konsoli 2024-05-26 01:37:01 +02:00
tafit0902
3c6e79a1fd losowanie zdjecia dla slotu, poruszanie sie traktora, uzycie sieci 2024-05-26 01:08:47 +02:00
tafit0902
f38a52e135 dodanie podstaw sieci nuronowej 2024-05-25 02:00:19 +02:00
24 changed files with 1873 additions and 15 deletions

4
.gitignore vendored
View File

@ -1,3 +1,5 @@
__pycache__/
.idea/
tree.png
tree.png
dataset/
dataset.zip

40
App.py
View File

@ -9,6 +9,8 @@ import Osprzet
import Ui
import BFS
import AStar
import neuralnetwork
import json
bfs1_flag=False
@ -18,7 +20,10 @@ Astar = False
Astar2 = False
if bfs3_flag or Astar or Astar2:
Pole.stoneFlag = True
TreeFlag=True
TreeFlag=False
nnFlag=False
newModel=False
finalFlag = True
pygame.init()
show_console=True
@ -29,7 +34,7 @@ image_loader=Image.Image()
image_loader.load_images()
goalTreasure = AStar.getRandomGoalTreasure() # nie wiem czy to najlepsze miejsce, obecnie pole zawiera pole gasStation, które służy do renderowania odpowiedniego zdjęcia
pole=Pole.Pole(screen,image_loader, goalTreasure)
pole.draw_grid() #musi byc tutaj wywołane ponieważ inicjalizuje sloty do slownika
pole.draw_grid(nnFlag) #musi byc tutaj wywołane ponieważ inicjalizuje sloty do slownika
ui=Ui.Ui(screen)
#Tractor creation
traktor_slot = pole.get_slot_from_cord((0, 0))
@ -40,7 +45,15 @@ def init_demo(): #Demo purpose
old_info=""
traktor.draw_tractor()
time.sleep(2)
pole.randomize_colors()
if not finalFlag:
pole.randomize_colors(nnFlag)
else:
population = 120
iterat = 2500
roulette = True
with open(f'pole_pop{population}_iter{iterat}_{roulette}.json', 'r') as file:
garden_data = json.load(file)
pole.setPlantsByList(garden_data)
traktor.draw_tractor()
start_flag=True
while True:
@ -72,7 +85,7 @@ def init_demo(): #Demo purpose
print_to_console("Traktor porusza sie obliczona sciezka BFS")
traktor.move_by_root(bfsRoot2, pole, [traktor.irrigateSlot])
if(bfs3_flag):
bfsRoot3 = BFS.BFS3({'x': 0, 'y': 0, 'direction': "E"})
bfsRoot3 = BFS.BFS3({'x': 0, 'y': 0, 'direction': "E"},goalTreasure)
#displayControler: NUM_X: 20, NUM_Y: 12 (skarb) CHANGE THIS IN DCON BY HAND!!!!!!!!
bfsRoot3.reverse()
print_to_console("Traktor porusza sie obliczona sciezka BFS")
@ -116,6 +129,25 @@ def init_demo(): #Demo purpose
if(TreeFlag):
traktor.move_forward(pole)
traktor.tree_move(pole)
if(nnFlag):
global model
if (newModel):
print_to_console("uczenie sieci neuronowej")
model = neuralnetwork.trainNewModel()
neuralnetwork.saveModel(model, 'model.pth')
print_to_console("sieć nuronowa nauczona")
print('model został wygenerowany')
else:
model = neuralnetwork.loadModel('model_500_hidden.pth')
print_to_console("model został załądowny")
testset = neuralnetwork.getDataset(False)
print(neuralnetwork.accuracy(model, testset))
traktor.snake_move_predict_plant(pole, model, headers=['Coords','Real plant','Predicted plant','Result','Fertilizer'], actions=[traktor.fertilize_slot])
if(finalFlag):
pass
model = neuralnetwork.loadModel('model_500_hidden.pth')
Tractor.drzewo.treeLearn()
traktor.snake_move_predict_plant(pole, model, headers=['Coords','Real plant','Predicted plant','Result','Water decision'], actions=[traktor.irigate_slot_NN])
start_flag=False
# demo_move()
old_info=get_info(old_info)

8
BFS.py
View File

@ -133,8 +133,12 @@ def check3(tab, state):
return True
def BFS3(istate):
goalTreassuere = (random.randint(0,NUM_X-1), random.randint(0,NUM_Y-1))
def BFS3(istate,GT):
randomGT=False
if(randomGT==True):
goalTreassuere = (random.randint(0,NUM_X-1), random.randint(0,NUM_Y-1))
else:
goalTreassuere=GT
print(goalTreassuere)
fringe = []
explored = []

View File

@ -8,7 +8,7 @@ class Drzewo:
self.tree=self.treeLearn()
def treeLearn(self):
csvdata=pandas.read_csv('Data/dataTree.csv')
csvdata=pandas.read_csv('Data/dataTree2.csv')
#csvdata = pandas.read_csv('Data/dataTree2.csv')
x=csvdata[atributes]
decision=csvdata['action']

139
GeneticAccuracy.py Normal file
View File

@ -0,0 +1,139 @@
import json
import random
from displayControler import NUM_Y, NUM_X
iterat = 2500
population = 120
roulette = True
plants = ['corn', 'potato', 'tomato', 'carrot']
initial_yields = {'corn': 38, 'potato': 40, 'tomato': 43, 'carrot': 45}
yield_reduction = {
'corn': {'corn': -4.5, 'potato': -3, 'tomato': -7, 'carrot': -7},
'potato': {'corn': -7, 'potato': -5, 'tomato': -10, 'carrot': -6},
'tomato': {'corn': -4, 'potato': -5, 'tomato': -7, 'carrot': -7},
'carrot': {'corn': -11, 'potato': -5, 'tomato': -4, 'carrot': -7}
}
yield_reduction2 = {
'corn': {'corn': None, 'potato': -4, 'tomato': -2, 'carrot': -4},
'potato': {'corn': None, 'potato': -5, 'tomato': -5, 'carrot': -2},
'tomato': {'corn': -5, 'potato': -3, 'tomato': -7, 'carrot': None},
'carrot': {'corn': -3, 'potato': -6, 'tomato': -4, 'carrot': -9}
}
yield_multiplier = {'corn': 1.25, 'potato': 1.17, 'tomato': 1.22, 'carrot': 1.13}
yield_multiplier2 = {'corn': 1.25, 'potato': 1.19, 'tomato': 1.22, 'carrot': 1.15}
def calculate_yields(garden):
rows = len(garden)
cols = len(garden[0])
total_yields = 0
for i in range(rows):
for j in range(cols):
plant = garden[i][j]
yield_count = initial_yields[plant]
# Sprawdzanie sąsiadów
neighbors = [
(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)
]
for ni, nj in neighbors:
if 0 <= ni < rows and 0 <= nj < cols:
neighbor_plant = garden[ni][nj]
yield_count += yield_reduction[plant][neighbor_plant]
yield_count *= yield_multiplier[plant]
total_yields += yield_count
return total_yields
def calculate_yields2(garden):
rows = len(garden)
cols = len(garden[0])
total_yields = 0
for i in range(rows):
for j in range(cols):
plant = garden[i][j]
yield_count = initial_yields[plant]
# Sprawdzanie sąsiadów
neighbors = [
(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)
]
neighbor_flag = False
for ni, nj in neighbors:
if 0 <= ni < rows and 0 <= nj < cols:
neighbor_plant = garden[ni][nj]
if yield_reduction2[plant][neighbor_plant] is not None: # jeśli jest wartość None to plony dla tej rośliny będą wyzerowane
yield_count += yield_reduction2[plant][neighbor_plant]
else:
neighbor_flag = True
if not neighbor_flag:
yield_count *= yield_multiplier2[plant]
total_yields += yield_count
return total_yields
def generate_garden(rows=20, cols=12):
return [[random.choice(plants) for _ in range(cols)] for _ in range(rows)]
def generate_garden_with_yields(t, rows=NUM_Y, cols=NUM_X):
garden = generate_garden(rows, cols)
if t == 1:
total_yields = calculate_yields(garden)
else:
total_yields = calculate_yields2(garden)
return [garden, total_yields]
def generate():
s1 = 0
s2 = 0
n = 150
for i in range(n):
x = generate_garden_with_yields(1)
s1 += x[1]
y = generate_garden_with_yields(2)
s2 += y[1]
return [s1/n, s2/n]
data = generate()
# print(data)
# Odczyt z pliku
with open(f'pole_pop{population}_iter{iterat}_{roulette}.json', 'r') as file:
garden_data = json.load(file)
# print("Odczytane dane ogrodu:")
# for row in garden_data:
# print(row)
print("Wygenerowane przy pomocy GA: ", calculate_yields(garden_data))
print(f"Przeciętny ogród wygenerowany randomowo ma {data[0]} plonów")
print("Uśredniony przyrost plonów (ile razy więcej plonów): ", calculate_yields(garden_data)/data[0])
# Odczyt z pliku
with open(f'pole2_pop{population}_iter{iterat}_{roulette}.json', 'r') as file:
garden_data2 = json.load(file)
# print("Odczytane dane ogrodu:")
# for row in garden_data2:
# print(row)
print("Wygenerowane: przy pomocy GA2", calculate_yields2(garden_data2))
print(f"Przeciętny ogród wygenerowany randomowo ma {data[1]} plonów")
print("Uśredniony przyrost plonów (ile razy więcej plonów): ", calculate_yields2(garden_data2)/data[1])

208
GeneticAlgorithm.py Normal file
View File

@ -0,0 +1,208 @@
import copy
import json
import random
from displayControler import NUM_X, NUM_Y
# Definiowanie stałych dla roślin i plonów
plants = ['corn', 'potato', 'tomato', 'carrot']
initial_yields = {'corn': 38, 'potato': 40, 'tomato': 43, 'carrot': 45}
yield_reduction = {
'corn': {'corn': -4.5, 'potato': -3, 'tomato': -7, 'carrot': -7},
'potato': {'corn': -7, 'potato': -5, 'tomato': -10, 'carrot': -6},
'tomato': {'corn': -4, 'potato': -5, 'tomato': -7, 'carrot': -7},
'carrot': {'corn': -11, 'potato': -5, 'tomato': -4, 'carrot': -7}
}
yield_multiplier = {'corn': 1.25, 'potato': 1.17, 'tomato': 1.22, 'carrot': 1.13}
# Generowanie listy 20x12 z losowo rozmieszczonymi roślinami
def generate_garden(rows=20, cols=12):
return [[random.choice(plants) for _ in range(cols)] for _ in range(rows)]
# Funkcja do obliczania liczby plonów
def calculate_yields(garden):
rows = len(garden)
cols = len(garden[0])
total_yields = 0
for i in range(rows):
for j in range(cols):
plant = garden[i][j]
yield_count = initial_yields[plant]
# Sprawdzanie sąsiadów
neighbors = [
(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)
]
for ni, nj in neighbors:
if 0 <= ni < rows and 0 <= nj < cols:
neighbor_plant = garden[ni][nj]
yield_count += yield_reduction[plant][neighbor_plant]
yield_count *= yield_multiplier[plant]
total_yields += yield_count
return total_yields
# Funkcja do generowania planszy/ogrodu i zapisywania go jako lista z liczbą plonów
def generate_garden_with_yields(rows=NUM_Y, cols=NUM_X):
garden = generate_garden(rows, cols)
total_yields = calculate_yields(garden)
return [garden, total_yields]
# Funkcja do generowania linii cięcia i zapisywania jej jako liczba roślin w kolumnie z pierwszej planszy/ogrodu
def line():
path = []
flag = False
x = random.randint(4, 8)
position = (0, x)
path.append(position)
while not flag: # wybór punktu dopóki nie wybierze się skrajnego
# prawdopodobieństwo "ruchu" -> 0.6: w prawo, 0.2: w góre, 0.2: w dół
p = [(position[0] + 1, position[1]), (position[0], position[1] + 1), (position[0], position[1] - 1)]
w = [0.6, 0.2, 0.2]
position2 = random.choices(p, w)[0]
if position2 not in path: # sprawdzenie czy dany punkt nie był już wybrany aby nie zapętlać się
path.append(position2)
position = position2
if position[0] == NUM_X or position[1] == 0 or position[1] == NUM_Y: # sprawdzenie czy osiągnięto skrajny punkt
flag = True
info = [] # przeformatowanie sposobu zapisu na liczbę roślin w kolumnie, które będzię się dzidziczyło z pierwszej planszy/ogrodu
for i in range(len(path) - 1):
if path[i + 1][0] - path[i][0] == 1:
info.append(NUM_Y - path[i][1])
if len(info) < NUM_X: # uzupełnienie informacji o dziedziczeniu z planszy/ogrodu
if path[-1:][0][1] == 0:
x = NUM_Y
else:
x = 0
while len(info) < NUM_X:
info.append(x)
# return path, info
return info
# Funkcja do generowania potomstwa
def divide_gardens(garden1, garden2):
info = line()
new_garden1 = [[] for _ in range(NUM_Y)]
new_garden2 = [[] for _ in range(NUM_Y)]
for i in range(NUM_X):
for j in range(NUM_Y):
# do utworzonych kolumn w nowych planszach/ogrodach dodajemy dziedziczone rośliny
if j < info[i]:
new_garden1[j].append(garden1[j][i])
new_garden2[j].append(garden2[j][i])
else:
new_garden1[j].append(garden2[j][i])
new_garden2[j].append(garden1[j][i])
return [new_garden1, calculate_yields(new_garden1)], [new_garden2, calculate_yields(new_garden2)]
# Funkcja do mutacji danej planszy/ogrodu
def mutation(garden, not_used):
new_garden = copy.deepcopy(garden)
for i in range(NUM_X):
x = random.randint(0, 11) # wybieramy, w którym wierszu w i-tej kolumnie zmieniamy roślinę na inną
other_plants = [plant for plant in plants if plant != new_garden[x][i]]
new_garden[x][i] = random.choice(other_plants)
return [new_garden, calculate_yields(new_garden)]
# Funkcja do generowania pierwszego pokolenia
def generate(n):
generation = []
for i in range(n * 3):
generation.append(generate_garden_with_yields())
generation.sort(reverse=True, key=lambda x: x[1])
return generation[:n]
# Funkcja do implementacji ruletki (sposobu wyboru) - sumuje wszystkie plony generacji
def sum_yields(x):
s = 0
for i in range(len(x)):
s += x[i][1]
return s
if __name__ == '__main__':
roulette = True
attemps = 150
iterat = 2500
population = 120
best = []
for a in range(attemps):
generation = generate(population)
print(generation[0][1])
for i in range(iterat): # ile iteracji - nowych pokoleń
print(a, i)
new_generation = generation[:(population // 7)] # dziedziczenie x najlepszych osobników
j = 0
while j < (
population - (
population // 7)): # dobór reszty osobników do pełnej liczby populacji danego pokolenia
if roulette: # zasada ruletki -> "2 rzuty kulką"
s = sum_yields(generation) # suma wszystkich plnów całego pokolenia
z = []
if s == 0: # wtedy każdy osobnik ma takie same szanse
z.append(random.randint(0, population - 1))
z.append(random.randint(0, population - 1))
else:
weights = [] # wagi prawdopodobieństwa dla każdego osobnika generacji
pos = [] # numery od 0 do 49 odpowiadające numerom osobnikom w generacji
for i in range(population):
weights.append(generation[i][1] / s)
pos.append(i)
z.append(random.choices(pos, weights)[0]) # wybranie osobnika według wag prawdopodobieństwa
z.append(random.choices(pos, weights)[0]) # wybranie osobnika według wag prawdopodobieństwa
else: # metoda rankingu
z = random.sample(range(0, int(population // 1.7)), 2)
# krzyzowanie 90% szans, mutacja 10% szans
function = [divide_gardens, mutation]
weight = [0.9, 0.1]
fun = random.choices(function, weight)[0]
h = fun(generation[z[0]][0], generation[z[1]][0])
if len(h[0]) == 2:
new_generation.append(h[0])
new_generation.append(h[1])
j += 2
else:
new_generation.append(h)
j += 1
new_generation.sort(reverse=True, key=lambda x: x[1]) # sortowanie malejąco listy według wartości plonów
generation = new_generation[:population]
best.append(generation[0])
best.sort(reverse=True, key=lambda x: x[1])
# Zapis do pliku
# for i in range(len(best)):
# print(best[i][1], calculate_yields(best[i][0]))
#
#
# with open(f'pole_pop{population}_iter{iterat}_{roulette}.json', 'w') as file: # zapis planszy/ogrodu do pliku json
# json.dump(best[0][0], file, indent=4)
#
# print("Dane zapisane do pliku")
# Odczyt z pliku
# with open(f'pole_pop{population}_iter{iterat}_{roulette}.json', 'r') as file:
# garden_data = json.load(file)
#
# print("Odczytane dane ogrodu:")
# for row in garden_data:
# print(row)
#
# print(calculate_yields(garden_data))
# if best[0][0] == garden_data:
# print("POPRAWNE: ", calculate_yields(garden_data), calculate_yields(best[0][0]))

213
GeneticAlgorithm2.py Normal file
View File

@ -0,0 +1,213 @@
import copy
import json
import random
from displayControler import NUM_X, NUM_Y
# Definiowanie stałych dla roślin i plonów
plants = ['corn', 'potato', 'tomato', 'carrot']
initial_yields = {'corn': 38, 'potato': 40, 'tomato': 43, 'carrot': 45}
yield_reduction = {
'corn': {'corn': None, 'potato': -4, 'tomato': -2, 'carrot': -4},
'potato': {'corn': None, 'potato': -5, 'tomato': -5, 'carrot': -2},
'tomato': {'corn': -5, 'potato': -3, 'tomato': -7, 'carrot': None},
'carrot': {'corn': -3, 'potato': -6, 'tomato': -4, 'carrot': -9}
}
yield_multiplier = {'corn': 1.25, 'potato': 1.19, 'tomato': 1.22, 'carrot': 1.15}
# Generowanie listy 20x12 z losowo rozmieszczonymi roślinami
def generate_garden(rows=20, cols=12):
return [[random.choice(plants) for _ in range(cols)] for _ in range(rows)]
# Funkcja do obliczania liczby plonów
def calculate_yields(garden):
rows = len(garden)
cols = len(garden[0])
total_yields = 0
for i in range(rows):
for j in range(cols):
plant = garden[i][j]
yield_count = initial_yields[plant]
# Sprawdzanie sąsiadów
neighbors = [
(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)
]
neighbor_flag = False
for ni, nj in neighbors:
if 0 <= ni < rows and 0 <= nj < cols:
neighbor_plant = garden[ni][nj]
if yield_reduction[plant][neighbor_plant] is not None: # jeśli jest wartość None to plony dla tej rośliny będą wyzerowane
yield_count += yield_reduction[plant][neighbor_plant]
else:
neighbor_flag = True
if not neighbor_flag:
yield_count *= yield_multiplier[plant]
total_yields += yield_count
return total_yields
# Funkcja do generowania planszy/ogrodu i zapisywania go jako lista z liczbą plonów
def generate_garden_with_yields(rows=NUM_Y, cols=NUM_X):
garden = generate_garden(rows, cols)
total_yields = calculate_yields(garden)
return [garden, total_yields]
# Funkcja do generowania linii cięcia i zapisywania jej jako liczba roślin w kolumnie z pierwszej planszy/ogrodu
def line():
path = []
flag = False
x = random.randint(4, 8)
position = (0, x)
path.append(position)
while not flag: # wybór punktu dopóki nie wybierze się skrajnego
# prawdopodobieństwo "ruchu" -> 0.6: w prawo, 0.2: w góre, 0.2: w dół
p = [(position[0] + 1, position[1]), (position[0], position[1] + 1), (position[0], position[1] - 1)]
w = [0.6, 0.2, 0.2]
position2 = random.choices(p, w)[0]
if position2 not in path: # sprawdzenie czy dany punkt nie był już wybrany aby nie zapętlać się
path.append(position2)
position = position2
if position[0] == NUM_X or position[1] == 0 or position[1] == NUM_Y: # sprawdzenie czy osiągnięto skrajny punkt
flag = True
info = [] # przeformatowanie sposobu zapisu na liczbę roślin w kolumnie, które będzię się dzidziczyło z pierwszej planszy/ogrodu
for i in range(len(path) - 1):
if path[i + 1][0] - path[i][0] == 1:
info.append(NUM_Y - path[i][1])
if len(info) < NUM_X: # uzupełnienie informacji o dziedziczeniu z planszy/ogrodu
if path[-1:][0][1] == 0:
x = NUM_Y
else:
x = 0
while len(info) < NUM_X:
info.append(x)
# return path, info
return info
# Funkcja do generowania potomstwa
def divide_gardens(garden1, garden2):
info = line()
new_garden1 = [[] for _ in range(NUM_Y)]
new_garden2 = [[] for _ in range(NUM_Y)]
for i in range(NUM_X):
for j in range(NUM_Y):
# do utworzonych kolumn w nowych planszach/ogrodach dodajemy dziedziczone rośliny
if j < info[i]:
new_garden1[j].append(garden1[j][i])
new_garden2[j].append(garden2[j][i])
else:
new_garden1[j].append(garden2[j][i])
new_garden2[j].append(garden1[j][i])
return [new_garden1, calculate_yields(new_garden1)], [new_garden2, calculate_yields(new_garden2)]
# Funkcja do mutacji danej planszy/ogrodu
def mutation(garden, not_used):
new_garden = copy.deepcopy(garden)
for i in range(NUM_X):
x = random.randint(0, 11) # wybieramy, w którym wierszu w i-tej kolumnie zmieniamy roślinę na inną
other_plants = [plant for plant in plants if plant != new_garden[x][i]]
new_garden[x][i] = random.choice(other_plants)
return [new_garden, calculate_yields(new_garden)]
# Funkcja do generowania pierwszego pokolenia
def generate(n):
generation = []
for i in range(n * 3):
generation.append(generate_garden_with_yields())
generation.sort(reverse=True, key=lambda x: x[1])
return generation[:n]
# Funkcja do implementacji ruletki (sposobu wyboru) - sumuje wszystkie plony generacji
def sum_yields(x):
s = 0
for i in range(len(x)):
s += x[i][1]
return s
if __name__ == '__main__':
roulette = True
attemps = 20
iterat = 2500
population = 120
best = []
for a in range(attemps):
generation = generate(population)
print(generation[0][1])
for i in range(iterat): # ile iteracji - nowych pokoleń
print(a, i)
new_generation = generation[:(population // 7)] # dziedziczenie x najlepszych osobników
j = 0
while j < (
population - (
population // 7)): # dobór reszty osobników do pełnej liczby populacji danego pokolenia
if roulette: # zasada ruletki -> "2 rzuty kulką"
s = sum_yields(generation) # suma wszystkich plnów całego pokolenia
z = []
if s == 0: # wtedy każdy osobnik ma takie same szanse
z.append(random.randint(0, population - 1))
z.append(random.randint(0, population - 1))
else:
weights = [] # wagi prawdopodobieństwa dla każdego osobnika generacji
pos = [] # numery od 0 do 49 odpowiadające numerom osobnikom w generacji
for i in range(population):
weights.append(generation[i][1] / s)
pos.append(i)
z.append(random.choices(pos, weights)[0]) # wybranie osobnika według wag prawdopodobieństwa
z.append(random.choices(pos, weights)[0]) # wybranie osobnika według wag prawdopodobieństwa
else: # metoda rankingu
z = random.sample(range(0, int(population // 1.7)), 2)
# krzyzowanie 90% szans, mutacja 10% szans
function = [divide_gardens, mutation]
weight = [0.9, 0.1]
fun = random.choices(function, weight)[0]
h = fun(generation[z[0]][0], generation[z[1]][0])
if len(h[0]) == 2:
new_generation.append(h[0])
new_generation.append(h[1])
j += 2
else:
new_generation.append(h)
j += 1
new_generation.sort(reverse=True, key=lambda x: x[1]) # sortowanie malejąco listy według wartości plonów
generation = new_generation[:population]
best.append(generation[0])
best.sort(reverse=True, key=lambda x: x[1])
# Zapis do pliku
# for i in range(len(best)):
# print(best[i][1], calculate_yields(best[i][0]))
#
#
# with open(f'pole2_pop{population}_iter{iterat}_{roulette}.json', 'w') as file: # zapis planszy/ogrodu do pliku json
# json.dump(best[0][0], file, indent=4)
#
# print("Dane zapisane do pliku")
#
# Odczyt z pliku
# with open(f'pole2_pop{population}_iter{iterat}_{roulette}.json', 'r') as file:
# garden_data = json.load(file)
#
# print("Odczytane dane ogrodu:")
# for row in garden_data:
# print(row)
#
# print(calculate_yields(garden_data))
# if best[0][0] == garden_data:
# print("POPRAWNE: ", calculate_yields(garden_data), calculate_yields(best[0][0]))

211
GeneticAlgorithm3.py Normal file
View File

@ -0,0 +1,211 @@
import copy
import json
import random
from displayControler import NUM_X, NUM_Y
# Definiowanie stałych dla roślin i plonów
plants = ['corn', 'potato', 'tomato', 'carrot']
initial_yields = {'corn': 38, 'potato': 40, 'tomato': 43, 'carrot': 45}
yield_reduction = {
'corn': {'corn': None, 'potato': 0, 'tomato': 0, 'carrot': 0},
'potato': {'corn': None, 'potato': 0, 'tomato': 0, 'carrot': 0},
'tomato': {'corn': 0, 'potato': 0, 'tomato': 0, 'carrot': None},
'carrot': {'corn': 0, 'potato': 0, 'tomato': 0, 'carrot': 0}
}
yield_multiplier = {'corn': 1.25, 'potato': 1.19, 'tomato': 1.22, 'carrot': 1.13}
# Generowanie listy 20x12 z losowo rozmieszczonymi roślinami
def generate_garden(rows=20, cols=12):
return [[random.choice(plants) for _ in range(cols)] for _ in range(rows)]
# Funkcja do obliczania liczby plonów
def calculate_yields(garden):
rows = len(garden)
cols = len(garden[0])
total_yields = 0
for i in range(rows):
for j in range(cols):
plant = garden[i][j]
# Sprawdzanie sąsiadów
neighbors = [
(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)
]
neighbor_flag = False
for ni, nj in neighbors:
if 0 <= ni < rows and 0 <= nj < cols:
neighbor_plant = garden[ni][nj]
if yield_reduction[plant][neighbor_plant] is None: # jeśli jest wartość None to plony dla tej rośliny będą wyzerowane
neighbor_flag = True
if not neighbor_flag:
total_yields += 1
return total_yields
# Funkcja do generowania planszy/ogrodu i zapisywania go jako lista z liczbą plonów
def generate_garden_with_yields(rows=NUM_Y, cols=NUM_X):
garden = generate_garden(rows, cols)
total_yields = calculate_yields(garden)
return [garden, total_yields]
# Funkcja do generowania linii cięcia i zapisywania jej jako liczba roślin w kolumnie z pierwszej planszy/ogrodu
def line():
path = []
flag = False
x = random.randint(4, 8)
position = (0, x)
path.append(position)
while not flag: # wybór punktu dopóki nie wybierze się skrajnego
# prawdopodobieństwo "ruchu" -> 0.6: w prawo, 0.2: w góre, 0.2: w dół
p = [(position[0] + 1, position[1]), (position[0], position[1] + 1), (position[0], position[1] - 1)]
w = [0.6, 0.2, 0.2]
position2 = random.choices(p, w)[0]
if position2 not in path: # sprawdzenie czy dany punkt nie był już wybrany aby nie zapętlać się
path.append(position2)
position = position2
if position[0] == NUM_X or position[1] == 0 or position[1] == NUM_Y: # sprawdzenie czy osiągnięto skrajny punkt
flag = True
info = [] # przeformatowanie sposobu zapisu na liczbę roślin w kolumnie, które będzię się dzidziczyło z pierwszej planszy/ogrodu
for i in range(len(path) - 1):
if path[i + 1][0] - path[i][0] == 1:
info.append(NUM_Y - path[i][1])
if len(info) < NUM_X: # uzupełnienie informacji o dziedziczeniu z planszy/ogrodu
if path[-1:][0][1] == 0:
x = NUM_Y
else:
x = 0
while len(info) < NUM_X:
info.append(x)
# return path, info
return info
# Funkcja do generowania potomstwa
def divide_gardens(garden1, garden2):
info = line()
new_garden1 = [[] for _ in range(NUM_Y)]
new_garden2 = [[] for _ in range(NUM_Y)]
for i in range(NUM_X):
for j in range(NUM_Y):
# do utworzonych kolumn w nowych planszach/ogrodach dodajemy dziedziczone rośliny
if j < info[i]:
new_garden1[j].append(garden1[j][i])
new_garden2[j].append(garden2[j][i])
else:
new_garden1[j].append(garden2[j][i])
new_garden2[j].append(garden1[j][i])
return [new_garden1, calculate_yields(new_garden1)], [new_garden2, calculate_yields(new_garden2)]
# Funkcja do mutacji danej planszy/ogrodu
def mutation(garden, not_used):
new_garden = copy.deepcopy(garden)
for i in range(NUM_X):
x = random.randint(0, 11) # wybieramy, w którym wierszu w i-tej kolumnie zmieniamy roślinę na inną
other_plants = [plant for plant in plants if plant != new_garden[x][i]]
new_garden[x][i] = random.choice(other_plants)
return [new_garden, calculate_yields(new_garden)]
# Funkcja do generowania pierwszego pokolenia
def generate(n):
generation = []
for i in range(n * 3):
generation.append(generate_garden_with_yields())
generation.sort(reverse=True, key=lambda x: x[1])
return generation[:n]
# Funkcja do implementacji ruletki (sposobu wyboru) - sumuje wszystkie plony generacji
def sum_yields(x):
s = 0
for i in range(len(x)):
s += x[i][1]
return s
if __name__ == '__main__':
roulette = True
attemps = 1
population = 120
best = []
iter = 0
for a in range(attemps):
generation = generate(population)
print(generation[0][1])
while generation[0][1] != NUM_X*NUM_Y: # ile iteracji - nowych pokoleń
iter += 1
print(iter)
print(generation[0][1])
new_generation = generation[:(population // 7)] # dziedziczenie x najlepszych osobników
j = 0
while j < (
population - (
population // 7)): # dobór reszty osobników do pełnej liczby populacji danego pokolenia
if roulette: # zasada ruletki -> "2 rzuty kulką"
s = sum_yields(generation) # suma wszystkich plnów całego pokolenia
z = []
if s == 0: # wtedy każdy osobnik ma takie same szanse
z.append(random.randint(0, population - 1))
z.append(random.randint(0, population - 1))
else:
weights = [] # wagi prawdopodobieństwa dla każdego osobnika generacji
pos = [] # numery od 0 do 49 odpowiadające numerom osobnikom w generacji
for i in range(population):
weights.append(generation[i][1] / s)
pos.append(i)
z.append(random.choices(pos, weights)[0]) # wybranie osobnika według wag prawdopodobieństwa
z.append(random.choices(pos, weights)[0]) # wybranie osobnika według wag prawdopodobieństwa
else: # metoda rankingu
z = random.sample(range(0, int(population // 1.7)), 2)
# krzyzowanie 90% szans, mutacja 10% szans
function = [divide_gardens, mutation]
weight = [0.9, 0.1]
fun = random.choices(function, weight)[0]
h = fun(generation[z[0]][0], generation[z[1]][0])
if len(h[0]) == 2:
new_generation.append(h[0])
new_generation.append(h[1])
j += 2
else:
new_generation.append(h)
j += 1
new_generation.sort(reverse=True, key=lambda x: x[1]) # sortowanie malejąco listy według wartości plonów
generation = new_generation[:population]
best.append(generation[0])
best.sort(reverse=True, key=lambda x: x[1])
# Zapis do pliku
# for i in range(len(best)):
# print(best[i][1], calculate_yields(best[i][0]))
#
#
# with open(f'pole3_pop{population}_{iter}_{roulette}.json', 'w') as file: # zapis planszy/ogrodu do pliku json
# json.dump(best[0][0], file, indent=4)
#
# print("Dane zapisane do pliku")
#
# Odczyt z pliku
# with open(f'pole3_pop{population}_{iter}_{roulette}.json', 'r') as file:
# garden_data = json.load(file)
#
# print("Odczytane dane ogrodu:")
# for row in garden_data:
# print(row)
#
# print(calculate_yields(garden_data))
# if best[0][0] == garden_data:
# print("POPRAWNE: ", calculate_yields(garden_data), calculate_yields(best[0][0]))

View File

@ -1,6 +1,8 @@
import pygame
import displayControler as dCon
import random
import neuralnetwork
import os
class Image:
def __init__(self):
@ -53,3 +55,50 @@ class Image:
def return_gasStation(self):
return self.gasStation_image
# losowanie zdjęcia z testowego datasetu bez powtórzeń
imagePathList = []
def getRandomImageFromDataBase():
label = random.choice(neuralnetwork.labels)
folderPath = f"dataset/test/{label}"
files = os.listdir(folderPath)
random_image = random.choice(files)
imgPath = os.path.join(folderPath, random_image)
while imgPath in imagePathList:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
label = random.choice(neuralnetwork.labels)
folderPath = f"dataset/test/{label}"
files = os.listdir(folderPath)
random_image = random.choice(files)
imgPath = os.path.join(folderPath, random_image)
imagePathList.append(imgPath)
image = pygame.image.load(imgPath)
image=pygame.transform.scale(image,(dCon.CUBE_SIZE,dCon.CUBE_SIZE))
return image, label, imgPath
def getSpedifiedImageFromDatabase(label):
folderPath = f"dataset/test/{label}"
files = os.listdir(folderPath)
random_image = random.choice(files)
imgPath = os.path.join(folderPath, random_image)
while imgPath in imagePathList:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
label = random.choice(neuralnetwork.labels)
folderPath = f"dataset/test/{label}"
files = os.listdir(folderPath)
random_image = random.choice(files)
imgPath = os.path.join(folderPath, random_image)
imagePathList.append(imgPath)
image = pygame.image.load(imgPath)
image=pygame.transform.scale(image,(dCon.CUBE_SIZE,dCon.CUBE_SIZE))
return image, label, imgPath

16
Pole.py
View File

@ -6,6 +6,8 @@ import time
import Ui
import math
import random
import neuralnetwork
import Image
stoneList = [(3,3), (3,4), (3,5), (3,6), (4,6), (5,6), (6,6), (7,6), (8,6), (9,6), (10,6), (11,6), (12,6), (13,6), (14,6), (15,6), (16,6), (16,7), (16,8), (16,9)]
stoneFlag = False
@ -30,7 +32,7 @@ class Pole:
return self.slot_dict
#Draw grid and tractor (new one)
def draw_grid(self):
def draw_grid(self, nn=False):
for x in range(0,dCon.NUM_X): #Draw all cubes in X axis
for y in range(0,dCon.NUM_Y): #Draw all cubes in Y axis
new_slot=Slot.Slot(x,y,Colors.BROWN,self.screen,self.image_loader) #Creation of empty slot
@ -48,7 +50,7 @@ class Pole:
st=self.slot_dict[self.gasStation]
st.set_gasStation_image()
def randomize_colors(self):
def randomize_colors(self, nn = False):
pygame.display.update()
time.sleep(3)
#self.ui.render_text("Randomizing Crops")
@ -59,7 +61,15 @@ class Pole:
if(coordinates==(0,0)):
continue
else:
self.slot_dict[coordinates].set_random_plant()
self.slot_dict[coordinates].set_random_plant(nn)
def setPlantsByList(self, plantList):
pygame.display.update()
time.sleep(3)
for coordinates in self.slot_dict:
if(coordinates==(0,0)):
continue
else:
self.slot_dict[coordinates].set_specifided_plant(plantList[coordinates[1]][coordinates[0]])
def change_color_of_slot(self,coordinates,color): #Coordinates must be tuple (x,y) (left top slot has cord (0,0) ), color has to be from defined in Colors.py or custom in RGB value (R,G,B)
self.get_slot_from_cord(coordinates).color_change(color)

22
Slot.py
View File

@ -16,6 +16,8 @@ class Slot:
self.field=pygame.Rect(self.x_axis*dCon.CUBE_SIZE,self.y_axis*dCon.CUBE_SIZE,dCon.CUBE_SIZE,dCon.CUBE_SIZE)
self.image_loader=image_loader
self.garage_image=None
self.label = None
self.imagePath = None
def draw(self):
pygame.draw.rect(self.screen,Colors.BROWN,self.field,0) #Draw field
@ -38,9 +40,19 @@ class Slot:
self.plant=color
self.draw()
def set_random_plant(self):
(plant_name,self.plant_image)=self.random_plant()
self.plant=Roslina.Roslina(plant_name)
def set_random_plant(self, nn=False):
if not nn:
(plant_name,self.plant_image)=self.random_plant()
self.plant=Roslina.Roslina(plant_name)
else:
self.plant_image, self.label, self.imagePath = self.random_plant_dataset()
# print(self.plant_image)
self.plant=Roslina.Roslina(self.label)
self.set_image()
def set_specifided_plant(self, plant):
self.plant_image, self.label, self.imagePath = self.specified_plant_dataset(plant)
self.plant=Roslina.Roslina(self.label)
self.set_image()
def set_image(self):
@ -66,6 +78,10 @@ class Slot:
def random_plant(self): #Probably will not be used later only for demo purpouse
return self.image_loader.return_random_plant()
def random_plant_dataset(self):
return Image.getRandomImageFromDataBase()
def specified_plant_dataset(self, plant):
return Image.getSpedifiedImageFromDatabase(plant)
def return_plant(self):
return self.plant

View File

@ -9,11 +9,13 @@ import Osprzet
import Node
import Condition
import Drzewo
import neuralnetwork as nn
condition=Condition.Condition()
drzewo=Drzewo.Drzewo()
format_string = "{:<25}{:<25}{:<25}{:<10}{:<10}{:<10}{:<25}{:<15}{:<20}{:<10}{:<15}"
format_string_nn="{:<10}{:<20}{:<20}{:<15}{:<20}"
tab = [-1, 0, 0, 0, 0, 1, 1, 1, 1, 1,
@ -28,6 +30,7 @@ class Tractor:
DIRECTION_SOUTH = 'S'
DIRECTION_WEST = 'W'
DIRECTION_EAST = 'E'
def __init__(self,slot,screen, osprzet,clock,bfs2_flag):
self.tractor_images = {
Tractor.DIRECTION_NORTH: pygame.transform.scale(pygame.image.load('images/traktorN.png'),
@ -191,6 +194,48 @@ class Tractor:
self.turn_left()
print("podlanych slotów: ", str(counter))
def snake_move_predict_plant(self, pole, model, headers, actions = None):
print(format_string_nn.format(*headers))
initPos = (self.slot.x_axis, self.slot.y_axis)
count = 0
for i in range(initPos[1], dCon.NUM_Y):
for j in range(initPos[0], dCon.NUM_X):
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if self.slot.imagePath != None:
predictedLabel = nn.predictLabel(self.slot.imagePath, model)
#print(str("Coords: ({:02d}, {:02d})").format(self.slot.x_axis, self.slot.y_axis), "real:", self.slot.label, "predicted:", predictedLabel, "correct" if (self.slot.label == predictedLabel) else "incorrect", 'nawożę za pomocą:', nn.fertilizer[predictedLabel])
# print(format_string_nn.format(f"{self.slot.x_axis,self.slot.y_axis}",self.slot.label,predictedLabel,"correct" if (self.slot.label == predictedLabel) else "incorrect",nn.fertilizer[predictedLabel]))
for a in actions:
a(predictedLabel)
if self.slot.label != predictedLabel:
# self.slot.mark_visited()
count += 1
self.move_forward(pole, False)
if i % 2 == 0 and i != dCon.NUM_Y - 1:
self.turn_right()
self.move_forward(pole, False)
self.turn_right()
elif i != dCon.NUM_Y - 1:
self.turn_left()
self.move_forward(pole, False)
self.turn_left()
print(f"Dobrze rozpoznanych roślin: {20*12-count}, źle rozpoznanych roślin: {count}")
def fertilize_slot(self, predictedLabel):
print(format_string_nn.format(f"{self.slot.x_axis,self.slot.y_axis}",self.slot.label,predictedLabel,"correct" if (self.slot.label == predictedLabel) else "incorrect",nn.fertilizer[predictedLabel]))
if self.slot.label != predictedLabel:
self.slot.mark_visited()
def irigate_slot_NN(self, predictedLabel):
attributes=self.get_attributes()
decision = drzewo.makeDecision(attributes)
print(format_string_nn.format(f"{self.slot.x_axis,self.slot.y_axis}",self.slot.label,predictedLabel,"correct" if (self.slot.label == predictedLabel) else "incorrect",decision))
condition.cycle()
self.waterLevel = random.randint(0, 100)
def snake_move(self,pole,x,y):
next_slot_coordinates=(x,y)
if(self.do_move_if_valid(pole,next_slot_coordinates)):

BIN
model_2_crops.pth Normal file

Binary file not shown.

BIN
model_500_hidden.pth Normal file

Binary file not shown.

114
neuralnetwork.py Normal file
View File

@ -0,0 +1,114 @@
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import Compose, Lambda, ToTensor
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from PIL import Image
import random
imageSize = (128, 128)
labels = ['carrot','corn', 'potato', 'tomato'] # musi być w kolejności alfabetycznej
fertilizer = {labels[0]: 'kompost', labels[1]: 'saletra amonowa', labels[2]: 'superfosfat', labels[3]:'obornik kurzy'}
#labels = ['corn','tomato'] #uncomment this two lines for 2 crops only
#fertilizer = {labels[0]: 'kompost', labels[1]: 'saletra amonowa'}
torch.manual_seed(42)
#device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
# device = torch.device("mps") if torch.backends.mps.is_available() else torch.device('cpu')
# print(device)
def getTransformation():
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
transforms.Resize(imageSize),
Lambda(lambda x: x.flatten())])
return transform
def getDataset(train=True):
transform = getTransformation()
if (train):
trainset = datasets.ImageFolder(root='dataset/train', transform=transform)
return trainset
else:
testset = datasets.ImageFolder(root='dataset/test', transform=transform)
return testset
def train(model, dataset, n_iter=100, batch_size=256):
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = nn.NLLLoss()
dl = DataLoader(dataset, batch_size=batch_size)
model.train()
for epoch in range(n_iter):
for images, targets in dl:
optimizer.zero_grad()
out = model(images.to(device))
loss = criterion(out, targets.to(device))
loss.backward()
optimizer.step()
if epoch % 10 == 0:
print('epoch: %3d loss: %.4f' % (epoch, loss))
return model
def accuracy(model, dataset):
model.eval()
correct = sum([(model(images.to(device)).argmax(dim=1) == targets.to(device)).sum()
for images, targets in DataLoader(dataset, batch_size=256)])
return correct.float() / len(dataset)
def getModel():
hidden_size = 500
model = nn.Sequential(
nn.Linear(imageSize[0] * imageSize[1] * 3, hidden_size),
nn.ReLU(),
nn.Linear(hidden_size, len(labels)),
nn.LogSoftmax(dim=-1)
).to(device)
return model
def saveModel(model, path):
print("Saving model")
torch.save(model.state_dict(), path)
def loadModel(path):
print("Loading model")
model = getModel()
model.load_state_dict(torch.load(path, map_location=torch.device('cpu'))) # musiałem tutaj dodać to ładowanie z mapowaniem na cpu bo u mnie CUDA nie działa wy pewnie możecie to usunąć
return model
def trainNewModel(n_iter=100, batch_size=256):
trainset = getDataset(True)
model = getModel()
model = train(model, trainset)
return model
def predictLabel(imagePath, model):
image = Image.open(imagePath).convert("RGB")
image = preprocess_image(image)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
with torch.no_grad():
model.eval() # Ustawienie modelu w tryb ewaluacji
output = model(image)
# Znalezienie indeksu klasy o największej wartości prawdopodobieństwa
predicted_class = torch.argmax(output).item()
return labels[predicted_class]
# Znalezienie indeksu klasy o największej wartości prawdopodobieństwa
predicted_class = torch.argmax(output).item()
return labels[predicted_class]
def preprocess_image(image):
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
transform = getTransformation()
image = transform(image).unsqueeze(0) # Add batch dimension
image = image.to(device) # Move the image tensor to the same device as the model
return image

View File

@ -0,0 +1,266 @@
[
[
"tomato",
"corn",
"tomato",
"tomato",
"corn",
"tomato",
"tomato",
"corn",
"carrot",
"potato",
"potato",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato"
],
[
"corn",
"carrot",
"potato",
"potato",
"carrot",
"potato",
"potato",
"carrot",
"potato",
"potato",
"carrot",
"corn",
"tomato",
"corn",
"carrot",
"corn",
"tomato",
"corn",
"tomato",
"corn"
],
[
"carrot",
"potato",
"potato",
"carrot",
"corn",
"carrot",
"potato",
"carrot",
"potato",
"carrot",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato"
],
[
"potato",
"potato",
"carrot",
"corn",
"tomato",
"corn",
"carrot",
"corn",
"carrot",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn"
],
[
"potato",
"carrot",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato"
],
[
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn"
],
[
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato"
],
[
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn"
],
[
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"carrot",
"corn",
"tomato"
],
[
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"carrot",
"potato",
"tomato",
"potato"
],
[
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"carrot",
"corn",
"carrot",
"corn",
"carrot",
"potato",
"potato",
"tomato",
"potato"
],
[
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"corn",
"tomato",
"potato",
"potato",
"carrot",
"corn",
"tomato"
]
]

266
pole3_pop120_365_True.json Normal file
View File

@ -0,0 +1,266 @@
[
[
"potato",
"carrot",
"carrot",
"potato",
"potato",
"carrot",
"carrot",
"potato",
"tomato",
"potato",
"carrot",
"potato",
"carrot",
"potato",
"carrot",
"carrot",
"potato",
"potato",
"potato",
"carrot"
],
[
"tomato",
"potato",
"carrot",
"potato",
"tomato",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"carrot",
"carrot",
"carrot",
"carrot",
"carrot",
"potato",
"potato",
"carrot",
"potato"
],
[
"corn",
"carrot",
"corn",
"carrot",
"potato",
"carrot",
"carrot",
"corn",
"tomato",
"corn",
"carrot",
"potato",
"potato",
"carrot",
"carrot",
"corn",
"carrot",
"potato",
"potato",
"tomato"
],
[
"tomato",
"potato",
"carrot",
"corn",
"tomato",
"corn",
"carrot",
"carrot",
"corn",
"carrot",
"potato",
"carrot",
"carrot",
"corn",
"carrot",
"carrot",
"potato",
"potato",
"tomato",
"tomato"
],
[
"tomato",
"potato",
"carrot",
"carrot",
"corn",
"carrot",
"carrot",
"potato",
"tomato",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"potato",
"tomato",
"tomato",
"potato",
"potato"
],
[
"potato",
"tomato",
"potato",
"potato",
"tomato",
"corn",
"carrot",
"potato",
"potato",
"tomato",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"potato",
"tomato",
"potato",
"carrot",
"carrot"
],
[
"potato",
"potato",
"tomato",
"tomato",
"corn",
"carrot",
"carrot",
"potato",
"tomato",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"potato"
],
[
"carrot",
"potato",
"tomato",
"potato",
"carrot",
"carrot",
"potato",
"potato",
"tomato",
"tomato",
"potato",
"carrot",
"potato",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"corn",
"carrot"
],
[
"carrot",
"potato",
"tomato",
"potato",
"carrot",
"carrot",
"carrot",
"potato",
"tomato",
"potato",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"carrot",
"potato",
"tomato",
"corn"
],
[
"potato",
"tomato",
"tomato",
"potato",
"carrot",
"potato",
"potato",
"carrot",
"potato",
"potato",
"carrot",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"corn",
"tomato",
"potato",
"tomato"
],
[
"potato",
"tomato",
"corn",
"tomato",
"potato",
"potato",
"potato",
"potato",
"carrot",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"corn",
"tomato",
"potato"
],
[
"potato",
"potato",
"carrot",
"corn",
"carrot",
"potato",
"potato",
"potato",
"carrot",
"carrot",
"carrot",
"potato",
"carrot",
"carrot",
"potato",
"carrot",
"corn",
"carrot",
"corn",
"tomato"
]
]

View File

@ -0,0 +1,266 @@
[
[
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"potato",
"potato",
"carrot",
"potato"
],
[
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"potato",
"potato",
"potato"
],
[
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"potato",
"carrot"
],
[
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato"
],
[
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"corn",
"tomato",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot"
],
[
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato"
],
[
"corn",
"corn",
"tomato",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"corn",
"potato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot"
],
[
"tomato",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato"
],
[
"carrot",
"potato",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"carrot"
],
[
"potato",
"potato",
"corn",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato"
],
[
"potato",
"carrot",
"tomato",
"corn",
"tomato",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"corn",
"corn",
"tomato",
"carrot",
"carrot",
"tomato",
"carrot"
],
[
"carrot",
"tomato",
"carrot",
"tomato",
"carrot",
"tomato",
"corn",
"tomato",
"carrot",
"tomato",
"corn",
"corn",
"tomato",
"corn",
"tomato",
"carrot",
"tomato",
"tomato",
"carrot",
"tomato"
]
]

View File

@ -4,4 +4,21 @@ Required packages:
pip install pygame
pip install matplotlib
pip install scikit-learn
pip install pandas
pip install pandas
How to run:
For BFS3:
-in App.py: -change bfs3_flag to True (other flags need to be disabled) -ensure that in App.py in BFS3 you give goalTreasure
-in Image.py change range in function return_random_plant to (0,5)
For Astar:
in App.py change Astar to True (other flags need to be disabled)
-in Image.py change range in function return_random_plant to (0,7)
For Astar2:
-in App.py change Astar2 flag to True (other flags need to be disabled)
-in Image.py change range in function return_random_plant to (0,7)
For Tree:
-in App.py change TreeFlag to True (other flags need to be disabled)
-in Image.py change range in function return_random_plant to (0,5)
For neuralnetwork:
-in App.py change nnFlag to True (other flags need to be disabled)
For final_show (neuralnetwork+tree+genetic algorithm)
-in App.py change finalFlag to True (other flags need to be disabled)

Binary file not shown.

Binary file not shown.

BIN
testModels/modelMPS.pth Normal file

Binary file not shown.

BIN
testModels/modelMPS650.pth Normal file

Binary file not shown.

BIN
testModels/modelMPS_AL.pth Normal file

Binary file not shown.