Compare commits

...

2 Commits

Author SHA1 Message Date
MarRac
0f92ffd53f improved decision tree implementation 2024-06-09 21:34:39 +02:00
MarRac
21681b7ef1 tractor moves in loop now 2024-06-09 16:37:41 +02:00
17 changed files with 137 additions and 49 deletions

View File

@ -7,6 +7,7 @@ import matplotlib.pyplot as plt
from NN.model import * from NN.model import *
from PIL import Image from PIL import Image
import pygame import pygame
from area.constants import GREY
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
@ -84,16 +85,22 @@ def load_image(image_path):
testImage = testImage.unsqueeze(0) testImage = testImage.unsqueeze(0)
return testImage return testImage
#display the image for prediction next to the field
def display_image(screen, image_path, position): def display_image(screen, image_path, position):
image = pygame.image.load(image_path) image = pygame.image.load(image_path)
image = pygame.transform.scale(image, (250, 250)) image = pygame.transform.scale(image, (250, 250))
screen.blit(image, position) screen.blit(image, position)
#display result of the guessed image (text under the image)
def display_result(screen, position, predicted_class): def display_result(screen, position, predicted_class):
font = pygame.font.Font(None, 30) font = pygame.font.Font(None, 30)
displayed_text = font.render("The predicted image is: "+str(predicted_class), 1, (255,255,255)) displayed_text = font.render("The predicted image is: "+str(predicted_class), 1, (255,255,255))
screen.blit(displayed_text, position) screen.blit(displayed_text, position)
def clear_text_area(win, x, y, width, height, color=GREY):
pygame.draw.rect(win, color, (x, y, width, height))
pygame.display.update()
def guess_image(model, image_tensor): def guess_image(model, image_tensor):
with torch.no_grad(): with torch.no_grad():
testOutput = model(image_tensor) testOutput = model(image_tensor)

Binary file not shown.

Binary file not shown.

View File

@ -1,5 +1,6 @@
from NN.neural_network import clear_text_area
from crop_protection_product import CropProtectionProduct from crop_protection_product import CropProtectionProduct
from area.constants import TILE_SIZE, DIRECTION_EAST, DIRECTION_SOUTH, DIRECTION_WEST, DIRECTION_NORTH from area.constants import TILE_SIZE, DIRECTION_EAST, DIRECTION_SOUTH, DIRECTION_WEST, DIRECTION_NORTH, WIDTH
from area.field import fieldX, fieldY, tiles from area.field import fieldX, fieldY, tiles
import pygame import pygame
import time import time
@ -38,16 +39,19 @@ class Tractor:
self.image = pygame.image.load('resources/images/tractor_left.png').convert_alpha() self.image = pygame.image.load('resources/images/tractor_left.png').convert_alpha()
def work_on_field(self, tile, ground, plant1): def work_on_field(self, screen, tile, ground, plant1):
results = []
if plant1 is None: if plant1 is None:
tile.randomizeContent() tile.randomizeContent()
# sprobuj zasadzic cos # sprobuj zasadzic cos
print("Tarctor planted something") print("Tarctor planted something")
results.append("Tarctor planted something")
elif plant1.growth_level == 100: elif plant1.growth_level == 100:
tile.plant = None tile.plant = None
ground.nutrients_level -= 40 ground.nutrients_level -= 40
ground.water_level -= 40 ground.water_level -= 40
print("Tractor collected something") print("Tractor collected something")
results.append("Tractor collected something")
else: else:
plant1.try_to_grow(50,50) #mozna dostosowac jeszcze plant1.try_to_grow(50,50) #mozna dostosowac jeszcze
ground.nutrients_level -= 11 ground.nutrients_level -= 11
@ -61,6 +65,7 @@ class Tractor:
elif plant1.plant_type == self.spinosad.plant_type: elif plant1.plant_type == self.spinosad.plant_type:
t = "Tractor used Spinosad" t = "Tractor used Spinosad"
print(t) print(t)
results.append(t)
ground.pest = False ground.pest = False
if ground.weed: if ground.weed:
# traktor pozbywa się chwastow # traktor pozbywa się chwastow
@ -71,13 +76,21 @@ class Tractor:
elif plant1.plant_type == self.metazachlor.plant_type: elif plant1.plant_type == self.metazachlor.plant_type:
t = "Tractor used Metazachlor" t = "Tractor used Metazachlor"
print(t) print(t)
results.append(t)
ground.weed = False ground.weed = False
if ground.water_level < plant1.water_requirements: if ground.water_level < plant1.water_requirements:
ground.water_level += 20 ground.water_level += 20
print("Tractor watered the plant") print("Tractor watered the plant")
results.append("Tractor watered the plant")
if ground.nutrients_level < plant1.nutrients_requirements: if ground.nutrients_level < plant1.nutrients_requirements:
ground.nutrients_level += 20 ground.nutrients_level += 20
print("Tractor added some nutrients") print("Tractor added some nutrients")
results.append("Tractor added some nutrients")
clear_text_area(screen, WIDTH-90, 100, 400, 100)
for idx, result in enumerate(results):
display_work_results(screen, result, (WIDTH-90, 100 + idx * 30))
@ -156,6 +169,13 @@ def do_actions(tractor, WIN, move_list):
tractor.rotate_to_left() tractor.rotate_to_left()
tractor.draw_tractor(WIN) tractor.draw_tractor(WIN)
pygame.display.update() pygame.display.update()
time.sleep(1) time.sleep(0.5)
#displays results of the "work_on_field" function next to the field:
def display_work_results(screen, text, position):
font = pygame.font.Font(None, 30)
displayed_text = font.render(text, 1, (255,255,255))
screen.blit(displayed_text, position)
pygame.display.update()

View File

@ -5,14 +5,14 @@ import pandas as pd
import joblib import joblib
from area.constants import WIDTH, HEIGHT, TILE_SIZE from area.constants import WIDTH, HEIGHT, TILE_SIZE
from area.field import drawWindow from area.field import drawWindow
from area.tractor import Tractor, do_actions from area.tractor import Tractor, do_actions, display_work_results
from area.field import tiles, fieldX, fieldY from area.field import tiles, fieldX, fieldY
from area.field import get_tile_coordinates, get_tile_index from area.field import get_tile_coordinates, get_tile_index
from ground import Dirt from ground import Dirt
from plant import Plant from plant import Plant
from bfs import graphsearch, Istate, succ from bfs import graphsearch, Istate, succ
from astar import a_star from astar import a_star
from NN.neural_network import load_model, load_image, guess_image, display_image, display_result from NN.neural_network import load_model, load_image, guess_image, display_image, display_result, clear_text_area
from PIL import Image from PIL import Image
from genetic import genetic_algorithm from genetic import genetic_algorithm
@ -30,6 +30,24 @@ def main():
window = drawWindow(WIN) window = drawWindow(WIN)
pygame.display.update() pygame.display.update()
#Tractor initialization:
tractor = Tractor(0*TILE_SIZE, 0*TILE_SIZE, 2, None, None)
tractor.rect.x += fieldX
tractor.rect.y += fieldY
tractor.tractor_start = ((170, 100))
istate = Istate(170, 100, 2) #initial state
#main loop:
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
time.sleep(1)
#getting coordinates of our "goal tile": #getting coordinates of our "goal tile":
tile_index = get_tile_index() tile_index = get_tile_index()
tile_x, tile_y = get_tile_coordinates(tile_index) tile_x, tile_y = get_tile_coordinates(tile_index)
@ -45,34 +63,20 @@ def main():
pygame.display.flip() pygame.display.flip()
#graphsearch activation: tractor.tractor_end = ((tile_x, tile_y))
istate = Istate(170, 100, 2) #initial state goaltest = [] #final state (consists of x and y because direction doesnt matter)
goaltest.append(tile_x)
goaltest = []
goaltest.append(tile_x) #final state (consists of x and y because direction doesnt matter)
goaltest.append(tile_y) goaltest.append(tile_y)
goaltest[0] = tile_x
goaltest[1]=tile_y
tractor = Tractor(0*TILE_SIZE, 0*TILE_SIZE, 2, None, None) #moves = (graphsearch(istate, succ, goaltest, tractor)) #<-------BFS
tractor.rect.x += fieldX
tractor.rect.y += fieldY
tractor.tractor_start = ((istate.get_x(), istate.get_y()))
#tractor.tractor_start = ((istate.get_x(), istate.get_y(), istate.get_direction))
tractor.tractor_end = ((goaltest[0], goaltest[1]))
#moves = (graphsearch(istate, succ, goaltest, tractor))
moves = (a_star(istate, succ, goaltest, tractor)) moves = (a_star(istate, succ, goaltest, tractor))
print(moves) print(moves)
#main loop: # movement based on route-planning:
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
time.sleep(1)
# movement based on route-planning (test):
tractor.draw_tractor(WIN) tractor.draw_tractor(WIN)
time.sleep(1) time.sleep(1)
@ -89,6 +93,7 @@ def main():
image_tensor = load_image(image_path) image_tensor = load_image(image_path)
prediction = guess_image(load_model(), image_tensor) prediction = guess_image(load_model(), image_tensor)
clear_text_area(WIN, WIDTH - 50, 600, 400, 50)
display_result(WIN, (WIDTH - 50 , 600), prediction) #display text under the photo display_result(WIN, (WIDTH - 50 , 600), prediction) #display text under the photo
pygame.display.update() pygame.display.update()
print(f"The predicted image is: {prediction}") print(f"The predicted image is: {prediction}")
@ -102,6 +107,7 @@ def main():
#getting the name and type of the recognized plant: #getting the name and type of the recognized plant:
p1.update_name(prediction) p1.update_name(prediction)
#decission tree test: #decission tree test:
if d1.pest: if d1.pest:
pe = 1 pe = 1
@ -131,19 +137,71 @@ def main():
t3 = True t3 = True
t4 = False t4 = False
weather_n = random.randint(1, 4)
if weather_n == 1:
h1 = True
h2 = False
h3 = False
h4 = False
else:
h1 = False
if weather_n == 2:
h2 = True
h3 = False
h4 = False
else:
h2 = False
if weather_n == 3:
h3 = True
h4 = False
else:
h3 = False
h4 = True
season_n = random.randint(1,4)
if season_n == 1:
s1 = True
s2 = False
s3 = False
s4 = False
temp_n = random.randint(0,22)
else:
s1 = False
if season_n == 2:
s2 = True
s3 = False
s4 = False
temp_n = random.randint(0,22)
else:
s2 = False
if season_n == 3:
s3 = True
s4 = False
temp_n = random.randint(20,39)
else:
s3 = False
s4 = True
temp_n = random.randint(-20, 10)
anomaly_n = random.randint(1, 10)
if anomaly_n == 1:
a1 = True
else:
a1 = False
dane = { dane = {
'anomalies': [True], 'anomalies': [a1],
'temp': [17], 'temp': [temp_n],
'water': [d1.water_level], 'water': [d1.water_level],
'nutri': [d1.nutrients_level], 'nutri': [d1.nutrients_level],
'pests': [pe], 'pests': [pe],
'weeds': [we], 'weeds': [we],
'ripeness': [p1.growth_level], 'ripeness': [p1.growth_level],
'season_autumn': [True], 'season_spring': [False], 'season_summer': [False], 'season_winter': [False], 'season_autumn': [s1], 'season_spring': [s2], 'season_summer': [s3], 'season_winter': [s4],
'weather_heavyCloudy': [False], 'weather_partCloudy': [False], 'weather_precipitation': [False], 'weather_heavyCloudy': [h1], 'weather_partCloudy': [h2], 'weather_precipitation': [h3],
'weather_sunny': [True], 'weather_sunny': [h4],
'type_cereal': [t1], 'type_fruit': [t2], 'type_none': [t3], 'type_vegetable': [t4] 'type_cereal': [t1], 'type_fruit': [t2], 'type_none': [t3], 'type_vegetable': [t4]
} }
df = pd.DataFrame(dane) df = pd.DataFrame(dane)
df.to_csv('model_data.csv', index=False) df.to_csv('model_data.csv', index=False)
@ -154,8 +212,11 @@ def main():
#work on field: #work on field:
if predykcje == 'work': if predykcje == 'work':
tractor.work_on_field(goalTile, d1, p1) tractor.work_on_field(WIN, goalTile, d1, p1)
time.sleep(50)
#update the initial state for the next target:
istate = Istate(tile_x, tile_y, tractor.direction)
time.sleep(2)
print("\n") print("\n")