From 8a2d14b8a39a088102a97628f010a65eee15aafe Mon Sep 17 00:00:00 2001 From: JakubPaszke Date: Sun, 18 Jun 2023 15:00:45 +0200 Subject: [PATCH] Created genetic algorithm. Added returned matrix of genetic algorithm into settings file. Replaced fields with map generated by algorithm. --- genetic_algorithm_matrix.pkl | Bin 0 -> 86 bytes main.py | 3 +- settings.py | 10 ++- src/genetic_algorithm.py | 161 +++++++++++++++++++++++++++++++++++ src/map.py | 6 +- 5 files changed, 176 insertions(+), 4 deletions(-) create mode 100644 genetic_algorithm_matrix.pkl create mode 100644 src/genetic_algorithm.py diff --git a/genetic_algorithm_matrix.pkl b/genetic_algorithm_matrix.pkl new file mode 100644 index 0000000000000000000000000000000000000000..532187ae62b082e0f11670b96c18a479c8c211f7 GIT binary patch literal 86 zcmZo*nd;2|0kKmwdf1W^i;D6~ru49uXQU 0 and chromosome[row][col - 1] == plant_type: + fitness += 1 + # Check top neighbor + if row > 0 and chromosome[row - 1][col] == plant_type: + fitness += 1 + + + for row in chromosome: + appearances[0] = appearances[0] + row.count(1) + appearances[1] = appearances[1] + row.count(2) + appearances[2] = appearances[2] + row.count(3) + + for i in range(len(appearances)): + if appearances[i] < 7 and appearances[i] > 9: + fitness = fitness + abs(appearances[i]-8) + return fitness + +def selection(population): + # Perform tournament selection to choose parents for reproduction + tournament_size = 5 + parents = [] + + for _ in range(len(population)): + tournament = random.sample(population, tournament_size) + tournament.sort(key=lambda chromosome: calculate_fitness(chromosome)) + parents.append(tournament[0]) + + return parents + +def crossover(parent1, parent2): + # Perform single-point crossover to create two offspring + crossover_point = random.randint(0, (GRID_SIZE*GRID_SIZE)-1) + + row = crossover_point // GRID_SIZE + column = crossover_point % GRID_SIZE + offspring1 = [] + offspring2 = [] + counter = 0 + while counter