genetic_algorithm #7

Merged
s481894 merged 8 commits from genetic_algorithm into master 2024-06-10 11:47:16 +02:00
34 changed files with 157 additions and 6 deletions
Showing only changes of commit 0d967ac051 - Show all commits

View File

@ -4,7 +4,7 @@
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" /> <excludeFolder url="file://$MODULE_DIR$/venv" />
</content> </content>
<orderEntry type="jdk" jdkName="Python 3.10 (Traktor)" jdkType="Python SDK" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
</component> </component>
</module> </module>

4
.idea/misc.xml Normal file
View File

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

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -6,6 +6,9 @@ from area.constants import WIDTH,FIELD_WIDTH,TILE_SIZE,GREY,ROWS,COLS
from tile import Tile from tile import Tile
from ground import Dirt from ground import Dirt
from genetic import genetic_algorithm
import os
tiles = [] tiles = []
fieldX = (WIDTH-FIELD_WIDTH)/2 fieldX = (WIDTH-FIELD_WIDTH)/2
@ -20,7 +23,7 @@ def positionFieldElements():
t.y += fieldY t.y += fieldY
def createTiles(): ''' def createTiles():
for y in range(0, COLS): for y in range(0, COLS):
for x in range(0, ROWS): for x in range(0, ROWS):
tile = Tile(x*TILE_SIZE, y*TILE_SIZE) tile = Tile(x*TILE_SIZE, y*TILE_SIZE)
@ -30,8 +33,47 @@ def createTiles():
tile.randomizeContent() tile.randomizeContent()
tiles.append(tile) tiles.append(tile)
positionFieldElements() positionFieldElements()
return tiles '''
def createTiles():
best = genetic_algorithm(50, 20, 0.7, 10)
for y in range(COLS):
for x in range (ROWS):
tile = Tile(x * TILE_SIZE, y * TILE_SIZE)
dirt = Dirt(random.randint(1, 100), random.randint(1, 100))
dirt.pests_and_weeds()
crop = best[y][x]
if crop == 'apple':
tile.image = "resources/images/sampling.png"
photo_path = random.choice(os.listdir("resources/images/plant_photos/apples"))
tile.photo = os.path.join("resources/images/plant_photos/apples", photo_path)
elif crop == 'cauliflower':
tile.image = "resources/images/sampling.png"
photo_path = random.choice(os.listdir("resources/images/plant_photos/cauliflowers"))
tile.photo = os.path.join("resources/images/plant_photos/cauliflowers", photo_path)
elif crop == 'radish':
tile.image = "resources/images/sampling.png"
photo_path = random.choice(os.listdir("resources/images/plant_photos/radishes"))
tile.photo = os.path.join("resources/images/plant_photos/radishes", photo_path)
elif crop == 'wheat':
tile.image = "resources/images/sampling.png"
photo_path = random.choice(os.listdir("resources/images/plant_photos/wheats"))
tile.photo = os.path.join("resources/images/plant_photos/wheats", photo_path)
elif crop == 'rock_dirt':
tile.image = "resources/images/rock_dirt.png"
dirt.set_ocstacle(True)
else:
tile.image = "resources/images/dirt.png"
tile.ground = "resources/images/background.jpg"
tile.ground = dirt
tiles.append(tile)
positionFieldElements()
return tiles return tiles
def createField(win): def createField(win):
createTiles() createTiles()
for t in tiles: for t in tiles:

98
source/genetic.py Normal file
View File

@ -0,0 +1,98 @@
import random
def make_population(population_s, field_s):
population = []
crops = ['apple', 'cauliflower', 'radish', 'wheat', 'rock_dirt', 'dirt']
for _ in range(population_s):
i = []
for _ in range(field_s):
row = random.choices(crops, k=field_s)
i.append(row)
population.append(i)
return population
def calculate_fitness(individual):
cost = 0
for i in range(len(individual)):
for j in range(len(individual[i])):
crop = individual[i][j]
neighbors = [
individual[x][y]
for x in range(max(0, i-1), min(len(individual), i+2))
for y in range(max(0, j-1), min(len(individual), j+2))
if (x,y) != (i,j)
]
for n in neighbors:
if crop == 'wheat' and n == 'apple':
cost += 2
elif crop == 'cauliflower' and n == 'radish':
cost += 4
fitness = 1/(1+cost)
return fitness
def select_parents(population, fitnesses):
fitnesses_sum = sum(fitnesses)
selection_parts = [fitness / fitnesses_sum for fitness in fitnesses]
parents = random.choices(population, weights=selection_parts, k=2)
return parents
def crossover(parent_1, parent_2):
crossover_point = random.randint(1, (len(parent_1)-1))
child_1 = parent_1[:crossover_point] + parent_2[crossover_point:]
child_2 = parent_2[:crossover_point] + parent_1[crossover_point:]
return child_1, child_2
def mutation(individual, chance):
crops = ['apple', 'cauliflower', 'radish', 'wheat', 'rock_dirt', 'dirt']
if random.random() < chance:
row = random.randint(0, len(individual) - 1)
column = random.randint(0, len(individual[0]) - 1)
individual[row][column] = random.choice(crops)
return individual
def genetic_algorithm(population_s, field_s, chance, limit):
population = make_population(population_s, field_s)
best_fitness = 0
count = 0
while best_fitness < 1:
fitnesses = [calculate_fitness(individual) for individual in population]
new_population = []
for _ in range(population_s // 2):
parent_1, parent_2 = select_parents(population, fitnesses)
p1c = calculate_fitness(parent_1)
p2c = calculate_fitness(parent_2)
print("p1c: ",p1c,"\np2c: ",p2c)
child_1, child_2 = crossover(parent_1, parent_2)
child_1 = mutation(child_1, chance)
child_2 = mutation(child_2, chance)
new_population.append(child_1)
new_population.append(child_2)
combined_population = population + new_population
combined_population = sorted(combined_population, key=calculate_fitness, reverse=True)
population = combined_population[:population_s]
current_best_fitness = calculate_fitness(population[0])
if current_best_fitness > best_fitness:
best_fitness = current_best_fitness
count = 0
else:
count += 1
if count >= limit:
break
best_child = max(population, key=calculate_fitness)
bsf = calculate_fitness(best_child)
print("bsf: ", bsf)
return best_child

View File

@ -20,7 +20,10 @@ class Dirt:
elif i == 4: elif i == 4:
self.weed = True self.weed = True
self.pest = True self.pest = True
elif i == 5: '''elif i == 5:
self.obstacle = True self.obstacle = True'''
def set_ocstacle(self, obstacle_status):
self.obstacle = obstacle_status
# add init, getters,setters # add init, getters,setters

View File

@ -13,7 +13,10 @@ 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
from PIL import Image from PIL import Image
from genetic import genetic_algorithm
from area.field import createTiles
pygame.init() pygame.init()
WIN_WIDTH = WIDTH + 300 WIN_WIDTH = WIDTH + 300
@ -23,6 +26,7 @@ pygame.display.set_caption('Intelligent tractor')
def main(): def main():
run = True run = True
window = drawWindow(WIN) window = drawWindow(WIN)
pygame.display.update() pygame.display.update()

View File

@ -1,2 +1,2 @@
anomalies,temp,water,nutri,pests,weeds,ripeness,season_autumn,season_spring,season_summer,season_winter,weather_heavyCloudy,weather_partCloudy,weather_precipitation,weather_sunny,type_cereal,type_fruit,type_none,type_vegetable anomalies,temp,water,nutri,pests,weeds,ripeness,season_autumn,season_spring,season_summer,season_winter,weather_heavyCloudy,weather_partCloudy,weather_precipitation,weather_sunny,type_cereal,type_fruit,type_none,type_vegetable
True,17,32,2,0,0,54,True,False,False,False,False,False,False,True,True,False,False,False True,17,72,73,0,0,60,True,False,False,False,False,False,False,True,False,True,False,False

1 anomalies temp water nutri pests weeds ripeness season_autumn season_spring season_summer season_winter weather_heavyCloudy weather_partCloudy weather_precipitation weather_sunny type_cereal type_fruit type_none type_vegetable
2 True 17 32 72 2 73 0 0 54 60 True False False False False False False True True False False True False False

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 743 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 245 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 281 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB