def mutate(self, individual): genome = self.convert_to_genome(individual.brain.weights) weight_to_mutate = random.randint(0, len(genome) - 1) # genome[weight_to_mutate] = genome[weight_to_mutate] * random.uniform(0.5, 1.5) genome[weight_to_mutate] = np.random.randn() new_weights = self.convert_to_weight(genome, individual.brain.weights) return Robot(50, 300, 8, 360, 9, all, new_weights, own_weights=True)
def create_child(self, parent1, parent2): # Uniform crossover parent1_genome = self.convert_to_genome( parent1.brain.weights ) # but is DNA actually being updated over time (over the generations) parent2_genome = self.convert_to_genome(parent2.brain.weights) child_genome = [] for i in range(len(parent1_genome)): if random.random() > 0.5: child_genome.append(parent1_genome[i]) else: child_genome.append(parent2_genome[i]) child_weights = self.convert_to_weight(child_genome, parent1.brain.weights) return Robot(50, 300, 8, 360, 9, all, child_weights, own_weights=True)
from Sensor import Robot from Pedestrian import all, Darwin import numpy as np a = Robot(200, 300, 8, 360, 9, all) b = Robot(200, 300, 8, 360, 9, all) print(a, b) print(a.fitness) robot_array = [a, b] print([i.fitness for i in robot_array]) darwin = Darwin(robot_array, 2, 1) genome = darwin.convert_to_genome(a.DNA) weights = darwin.convert_to_weight(genome, a.DNA) print(np.shape(weights), np.shape(a.DNA)) c = darwin.create_child(a, b) # print(np.array_equal(a.DNA, a.brain.weights)) # print(a.DNA) # print(a.brain.weights) a.DNA = c for i in range(3): print(np.array_equal(a.DNA[i], a.brain.weights[i]))
starting_x = My_Trajectory_Dict[pedestrian][0][0] starting_y = My_Trajectory_Dict[pedestrian][0][1] all_pedestrians.append( Pedestrian(starting_x, starting_y, 8, pedestrian, My_Trajectory_Dict[pedestrian])) all = Manager(all_pedestrians, 15) # obstacleArray = [Obstacle('Circle', (500, 300), (0, 0, 255), 0, 100), Obstacle('Circle', (200, 300), (0, 255, 0), 0, 75)] population_size = 50 elitism = 4 robots = [] for i in range(population_size): robots.append(Robot(100, 300, 8, 360, 9, all, set_weights=None)) # some class here maybe to manage all robots class Darwin: def __init__(self, robot_array, elitism, mutation_rate): self.robot_array = robot_array self.generation = 0 self.population_size = population_size self.elitism = elitism self.mutation_rate = mutation_rate self.best_fitness = 0 self.number_of_parents = 4 self.dead_count = 0 self.x_data = [] self.y_data = []