Compare commits

..

9 Commits

40 changed files with 256 additions and 54 deletions

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_19" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (pythonProject)" project-jdk-type="Python SDK" />
</project>

View File

@ -1,8 +1,7 @@
{
"ExpandedNodes": [
"",
"\\decisionTree"
""
],
"SelectedNode": "\\decisionTree\\treemaker.py",
"SelectedNode": "\\C:\\Users\\zmysz\\Desktop\\nowy-inteligentny-traktor",
"PreviewInSolutionExplorer": false
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

82
NN/Generator.py Normal file
View File

@ -0,0 +1,82 @@
from PIL import Image
import random
plants = [[], [], []]
plants[0].append(Image.open("w1.png"))
plants[0].append(Image.open("w2.png"))
plants[0].append(Image.open("w3.png"))
plants[1].append(Image.open("c1.png"))
plants[1].append(Image.open("c2.png"))
plants[1].append(Image.open("c3.png"))
plants[2].append(Image.open("ca1.png"))
plants[2].append(Image.open("ca2.png"))
plants[2].append(Image.open("ca3.png"))
b = [Image.open("b1.png").convert('RGBA'), Image.open("b2.png").convert('RGBA'), Image.open("b3.png").convert('RGBA')]
def generate(water, fertilizer, plantf):
if water == 1:
new_im = Image.new('RGB', (100, 100),
(160 + random.randint(-10, 10), 80 + random.randint(-10, 10), 40 + random.randint(-10, 10)))
tmp = plants[plantf][random.randint(0, 2)].resize(
(25 + random.randint(-10, 25), 25 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 50), random.randint(0, 50)), tmp)
if fertilizer:
tmp = b[random.randint(0, 2)].resize(
(20 + random.randint(0, 25), 20 + random.randint(0, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(25, 75), random.randint(25, 75)), tmp)
else:
if fertilizer:
new_im = Image.new('RGB', (100, 100),
(
50 + random.randint(-10, 10), 25 + random.randint(-10, 10),
0 + random.randint(-10, 10)))
tmp = plants[plantf][random.randint(0, 2)].resize(
(25 + random.randint(-10, 25), 25 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 50), random.randint(0, 50)), tmp)
tmp = b[random.randint(0, 2)].resize(
(20 + random.randint(0, 25), 20 + random.randint(0, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(25, 75), random.randint(25, 75)), tmp)
else:
if random.randint(0, 1) == 1:
new_im = Image.new('RGB', (100, 100),
(50 + random.randint(-10, 10), 25 + random.randint(-10, 10),
0 + random.randint(-10, 10)))
else:
new_im = Image.new('RGB', (100, 100),
(160 + random.randint(-10, 10), 80 + random.randint(-10, 10),
40 + random.randint(-10, 10)))
if random.randint(0, 1) == 1: # big
tmp = plants[plantf][random.randint(0, 2)].resize(
(75 + random.randint(-10, 25), 75 + random.randint(-10, 25))).rotate(random.randint(0, 359))
new_im.paste(tmp, (random.randint(0, 15), random.randint(0, 15)), tmp)
else:
tmp = plants[plantf][random.randint(0, 2)].resize(
(random.randint(10, 80), random.randint(10, 80))).rotate(random.randint(0, 359))
datas = tmp.getdata()
new_image_data = []
for item in datas:
# change all white (also shades of whites) pixels to yellow
if item[0] in list(range(190, 256)):
new_image_data.append(
(random.randint(0, 10), 255 + random.randint(-150, 0), random.randint(0, 10)))
else:
new_image_data.append(item)
# update image data
tmp.putdata(new_image_data)
new_im.paste(tmp, (random.randint(0, 30), random.randint(0, 30)), tmp)
return new_im
for x in range(0, 1000):
generate(0, 0, random.randint(0, 2)).save('datasets/00/' + str(x) + '.png')
for x in range(0, 1000):
generate(1, 0, random.randint(0, 2)).save('datasets/10/' + str(x) + '.png')
for x in range(0, 1000):
generate(0, 1, random.randint(0, 2)).save('datasets/01/' + str(x) + '.png')
for x in range(0, 1000):
generate(1, 1, random.randint(0, 2)).save('datasets/11/' + str(x) + '.png')

BIN
NN/b1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

BIN
NN/b2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 205 KiB

BIN
NN/b3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

BIN
NN/c1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

BIN
NN/c2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

BIN
NN/c3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

BIN
NN/ca1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 448 KiB

BIN
NN/ca2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 397 KiB

BIN
NN/ca3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 821 KiB

48
NN/trainer.py Normal file
View File

@ -0,0 +1,48 @@
import pathlib
import random
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torchvision.transforms import Lambda
device = torch.device('cpu')
def train(model, dataset, n_iter=100, batch_size=2560000):
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))
image_path_list = list(pathlib.Path('./').glob("*/*/*.png"))
random_image_path = random.choice(image_path_list)
data_transform = transforms.Compose([
transforms.Resize(size=(100, 100)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
Lambda(lambda x: x.flatten())
])
train_data = datasets.ImageFolder(root="./datasets",
transform=data_transform,
target_transform=None)
model1 = nn.Sequential(nn.Linear(30000, 10000), nn.ReLU(), nn.Linear(10000, 10000), nn.ReLU(), nn.Linear(10000, 0000), nn.Linear(10000, 4), nn.LogSoftmax(dim=-1)).to(device)
model1.load_state_dict(torch.load("./trained"))
train(model1, train_data)
torch.save(model1.state_dict(), "./trained")

BIN
NN/w1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

BIN
NN/w2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

BIN
NN/w3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

View File

@ -1,7 +1,6 @@
from operator import itemgetter
import cart
import copy
from classes import Field
class Istate:
@ -68,23 +67,23 @@ class Node:
self.y = y
def fieldCost(T,node):
def fieldCost(T, node):
c = 0
if T[node.x-1][node.y-1].plantType == 1:
c =2
c = 2
elif T[node.x-1][node.y-1].plantType == 2:
c =5
c = 5
elif T[node.x-1][node.y-1].plantType == 3:
c =13
c = 13
elif T[node.x-1][node.y-1].plantType == 4:
c =100000
c = 100000
else:
c=0
c = 0
if T[node.x-1][node.y-1].isWet == 1:
c = c + 4
else:
c=c+1
c = c+1
return c
@ -92,7 +91,7 @@ def fieldCost(T,node):
def cost(T, node):
cost = 0
while (node.get_parent() != None):
while node.get_parent() is not None:
cost = cost + fieldCost(T, node)
node = node.get_parent()
@ -103,7 +102,7 @@ def f(goaltest, map, node):
return cost(map, node) + heuristic(goaltest, node)
def goal_test(elem,goaltest):
def goal_test(elem, goaltest):
if elem.get_x() == goaltest[0] and elem.get_y() == goaltest[1]:
return True
else:
@ -132,7 +131,7 @@ def graphsearch(explored, f, fringe, goaltest, istate, map, succ): # przeszukiw
explored_tuple.append((x.get_direction(), x.get_x(), x.get_y()))
x = Node(action, state[0], elem[0], state[1], state[2]) # stworzenie nowego wierzchołka, którego rodzicem jest elem
p = f(goaltest, map, x) # liczy priorytet
#print('Koszt =', p)
# print('Koszt =', p)
if state not in fringe_tuple and state not in explored_tuple: # jeżeli stan nie znajduje się na fringe oraz nie znajduje się w liście wierzchołków odwiedzonych
fringe.append((x, p)) # dodanie wierzchołka na fringe
fringe = sorted(fringe, key=itemgetter(1)) # sortowanie fringe'a według priorytetu
@ -141,7 +140,7 @@ def graphsearch(explored, f, fringe, goaltest, istate, map, succ): # przeszukiw
for (state_prio, r) in fringe_tuple_prio:
if str(state_prio) == str(state):
if r > p:
fringe.insert(i, (x,p)) # zamiana state, który należy do fringe z priorytetem r na state z priorytetem p (niższym)
fringe.insert(i, (x, p)) # zamiana state, który należy do fringe z priorytetem r na state z priorytetem p (niższym)
fringe.pop(i + 1)
fringe = sorted(fringe, key=itemgetter(1)) # sortowanie fringe'a według priorytetu
break
@ -154,7 +153,7 @@ def heuristic(goaltest, node):
def print_moves(elem):
moves_list = []
while (elem.get_parent() != None):
while elem.get_parent() is not None:
moves_list.append(elem.get_action())
elem = elem.get_parent()
moves_list.reverse()
@ -184,7 +183,6 @@ def succ(elem):
temp_move_east = elem.get_x() + 1
temp_move_north = elem.get_y() + 1
if cart.Cart.is_move_allowed_succ(elem) == "x + 1":
actions_list.append(("move", (elem.get_direction(), temp_move_east, elem.get_y())))
elif cart.Cart.is_move_allowed_succ(elem) == "y + 1":
@ -194,8 +192,4 @@ def succ(elem):
elif cart.Cart.is_move_allowed_succ(elem) == "x - 1":
actions_list.append(("move", (elem.get_direction(), temp_move_west, elem.get_y())))
return actions_list
return actions_list

18
bfs.py
View File

@ -1,4 +1,3 @@
import sys
import cart
import copy
@ -67,23 +66,19 @@ class Node:
self.y = y
def goal_test(goaltest,elem):
def goal_test(goaltest, elem):
if elem.get_x() == goaltest[0] and elem.get_y() == goaltest[1]:
return True
else:
return False
# def graphsearch(explored, fringe, goaltest, istate, succ): # przeszukiwanie grafu wszerz
def graphsearch(explored, fringe, goaltest, istate): # przeszukiwanie grafu wszerz
def graphsearch(goaltest, istate): # przeszukiwanie grafu wszerz
node = Node(None, istate.get_direction(), None, istate.get_x(), istate.get_y())
fringe = []
#elem = []
explored = []
#action = []
fringe.append(node) # wierzchołki do odwiedzenia
# fringe = [node]
while True:
if not fringe:
return False
@ -109,7 +104,7 @@ def graphsearch(explored, fringe, goaltest, istate): # przeszukiwanie grafu wsz
def print_moves(elem):
moves_list = []
while (elem.get_parent() != None):
while elem.get_parent() is not None:
moves_list.append(elem.get_action())
elem = elem.get_parent()
moves_list.reverse()
@ -139,7 +134,6 @@ def succ(elem):
temp_move_east = elem.get_x() + 1
temp_move_north = elem.get_y() + 1
if cart.Cart.is_move_allowed_succ(elem) == "x + 1":
actions_list.append(("move", (elem.get_direction(), temp_move_east, elem.get_y())))
elif cart.Cart.is_move_allowed_succ(elem) == "y + 1":
@ -149,8 +143,4 @@ def succ(elem):
elif cart.Cart.is_move_allowed_succ(elem) == "x - 1":
actions_list.append(("move", (elem.get_direction(), temp_move_west, elem.get_y())))
return actions_list
return actions_list

View File

@ -1,6 +1,5 @@
import pygame
from screen import SCREEN
global BLACK
# global SCREEN
global BLACK
@ -8,9 +7,9 @@ global gridObjects
global imgTree
global imgTree
imgTree = pygame.image.load('img/tree.png')
gridObjects = {} # Store grid-box objects from Grid Class
class Grid(object):
# ta klasa rysuje kratę na ekranie
def __init__(self, x, y, sx, sy):
@ -27,6 +26,7 @@ class Grid(object):
BLACK = (0, 0, 0)
pygame.draw.rect(SCREEN, BLACK, (self.x, self.y, self.sx, self.sy), self.width)
class Box(object):
# global SCREEN
@ -43,6 +43,7 @@ class Box(object):
# global BLACK
pygame.draw.rect(SCREEN, self.color, pygame.Rect(self.x, self.y, self.sx, self.sy))
class Obstacle(object):
def __init__(self, mouseObj):
self.mseX = mouseObj[0]
@ -54,8 +55,8 @@ class Obstacle(object):
self.y = g.y
self.sx = g.sx
self.sy = g.sy
if self.mseX > self.x and self.mseX < self.x + self.sx:
if self.mseY > self.y and self.mseY < self.y + self.sy:
if self.x < self.mseX < self.x + self.sx:
if self.y < self.mseY < self.y + self.sy:
self.posX = self.x
self.posY = self.y
self.gridBox = grid
@ -66,6 +67,7 @@ class Obstacle(object):
SCREEN.blit(imgTree, (self.posX, self.posY))
# pygame.display.update()
def getGridBoxes(grid_box):
global gridObjects
return gridObjects[grid_box]
global gridObjects
return gridObjects[grid_box]

View File

@ -25,9 +25,7 @@ class Cart:
def set_y(self, y):
self.y = y
def is_move_allowed(self,
cart_rect): # sprawdza czy dany ruch, który chce wykonać wózek jest możliwy, zwraca prawdę lub fałsz
def is_move_allowed(self, cart_rect): # sprawdza czy dany ruch, który chce wykonać wózek jest możliwy, zwraca prawdę lub fałsz
if self.direction == definitions.CART_DIRECTION_EAST and cart_rect.x + definitions.BLOCK_SIZE < definitions.WIDTH_MAP:
return True
elif self.direction == definitions.CART_DIRECTION_SOUTH and cart_rect.y - definitions.BLOCK_SIZE > 0:
@ -74,4 +72,3 @@ class Cart:
self.direction = 1
else:
self.direction = self.direction + 1

View File

@ -1,5 +1,6 @@
import random
# Generowanie unikalnej losowej linii tekstu
def generate_unique_line(existing_lines):
while True:
@ -9,6 +10,7 @@ def generate_unique_line(existing_lines):
if line not in existing_lines:
return line
# Generowanie 200 unikalnych linii tekstu
lines = []
while len(lines) < 200:
@ -18,4 +20,4 @@ while len(lines) < 200:
# Zapisywanie linii tekstu do pliku
with open('decisionTree/database.txt', 'w') as file:
for line in lines:
file.write(line + '\n')
file.write(line + '\n')

View File

@ -53,7 +53,7 @@ with open("database.txt", 'r') as f:
view.append(x)
X1.append(test_list)
f = open("learning_set.txt", "w") # zapisuje atrybuty s?ownie
f = open("learning_set.txt", "w") # zapisuje atrybuty swnie
for i in view:
f.write(str(i)+"\n")
f.close()

View File

@ -1,5 +1,3 @@
# definicje
import os
import pygame
pygame.init()
@ -21,4 +19,4 @@ HEIGHT_AMOUNT, WIDTH_AMOUNT = 11, 11
HEIGHT_MAP, WIDTH_MAP = BLOCK_SIZE * HEIGHT_AMOUNT, BLOCK_SIZE * WIDTH_AMOUNT
HEIGHT, WIDTH = HEIGHT_MAP + BLOCK_SIZE, WIDTH_MAP
IMAGE_SIZE_NEURAL_NETWORK = 16
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))

90
genetic_algorithm.py Normal file
View File

@ -0,0 +1,90 @@
import random
import math
def create_initial_population(population_size, new_list, player):
population = []
for _ in range(population_size):
chromosome = new_list.copy()
chromosome.remove((player.x+1, player.y+1))
random.shuffle(chromosome)
chromosome.insert(0, (player.x+1, player.y+1))
population.append(chromosome)
return population
def calculate_distance(node1, node2):
x1, y1 = node1
x2, y2 = node2
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return distance
def calculate_fitness(individual):
total_distance = 0
num_nodes = len(individual)
for i in range(num_nodes - 1):
node1 = individual[i]
node2 = individual[i + 1]
distance = calculate_distance(node1, node2)
total_distance += distance
if total_distance == 0:
fitness = float('inf')
return fitness
fitness = 1 / total_distance
return fitness
def crossover(parent1, parent2, player):
child = [(player.x+1, player.y+1)] + [None] * (len(parent1) - 1)
start_index = random.randint(1, len(parent1) - 1)
end_index = random.randint(start_index + 1, len(parent1))
child[start_index:end_index] = parent1[start_index:end_index]
remaining_nodes = [node for node in parent2 if node not in child]
child[1:start_index] = remaining_nodes[:start_index - 1]
child[end_index:] = remaining_nodes[start_index - 1:]
return child
def mutate(individual, mutation_rate):
for i in range(1, len(individual)):
if random.random() < mutation_rate:
j = random.randint(1, len(individual) - 1)
individual[i], individual[j] = individual[j], individual[i]
return individual
def genetic_algorithm(new_list, player):
max_generations = 200
population_size = 200
mutation_rate = 0.1
population = create_initial_population(population_size, new_list, player)
best_individual = None
best_fitness = float('-inf')
for generation in range(max_generations):
fitness_values = [calculate_fitness(individual) for individual in population]
population = [x for _, x in sorted(zip(fitness_values, population), reverse=True)]
fitness_values.sort(reverse=True)
best_individuals = population[:10]
new_population = best_individuals.copy()
while len(new_population) < population_size:
parent1, parent2 = random.choices(best_individuals, k=2)
child = crossover(parent1, parent2, player)
child = mutate(child, mutation_rate)
new_population.append(child)
for individual in best_individuals:
fitness = calculate_fitness(individual)
if fitness > best_fitness:
best_fitness = fitness
best_individual = individual
population = new_population[:population_size]
return best_individual

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

View File

@ -413,7 +413,7 @@ def eventHandler(kbdObj, mouseObj):
# Wczytywanie modelu z pliku
labels = ['Rain', 'Planted', 'Temperature', 'Sun', 'Snow', 'Moisture', 'Rotten', 'Time']
loaded_model = joblib.load('decisionTree/decisionTreeFinal.sav')
loaded_model = joblib.load('decisionTree/decisionTree.sav')
sample = W[goalNode[0]-1][goalNode[1]-1]
# Klasyfikacja przy użyciu wczytanego modelu

View File

@ -1,2 +1,2 @@
import pygame
SCREEN = pygame.display.set_mode([600,665])
SCREEN = pygame.display.set_mode([600, 690])

BIN
test/00/test.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB