def plan_schedule(self): values, sets, edges, max_cost = self.formulate_problem() mult = lambda x, y: x * y factorial = lambda n: reduce(mult, range(1, n+1)) num_perms = factorial(len(sets)) * reduce(mult, [len(set) for set in sets.values()]) rospy.loginfo("Solving for %s sets connected by %s edges totalling %s permutations with a max cost of %s." \ % (len(sets), len(edges), num_perms, max_cost)) score, tour = genetic_algorithm( sets, cost(values, edges, max_cost), random_sample(sets.keys(), sets), mutate(sets), population=100, generations=500 ) self.schedule = [] for key, method in tour: self.schedule.append({ "action": method, "bin": self.items[key].bin, "item": self.items[key].name, "others": self.items[key].contents }) print score, tour print self.schedule
ant_random_new = 0 # Potential_Parent selection parent_rate = 0.10 ant_parents = max(round(parent_rate * config.pop_size), 2) potential_parents = population[0:ant_parents] ant_children = len(population) - ant_survivors - ant_random_new children = [] for i in range(ant_children): # parent = potential_parents[random.randrange(0, len(potential_parents))] # Parent selection parent1, parent2 = random.sample(potential_parents, k=2) child = crossover(parent1, parent2, config=config) mutate(child, config=config) children.append(child) population = survivers + children # replenish_population_with_new_random(pop_size, population) assert len(population) == config.pop_size non_evalutation_time = time.time() - after_evaluation print(non_evalutation_time) ### Summary best = max(population, key=lambda individual: individual.fitness) print("best Individual got score {}, and looked like: {}".format( best.fitness, best))
# Survival selection ant_survivors = round(len(population) * config.survival_rate) survivers = population[0:ant_survivors] # Potential_Parent selection ant_parents = max(round(config.parent_rate * config.pop_size), 2) potential_parents = population[0:ant_parents] ant_children = len(population) - ant_survivors children = [] for i in range(ant_children): # parent = potential_parents[random.randrange(0, len(potential_parents))] # Parent selection parent1, parent2 = random.sample(potential_parents, k=2) child = crossover(parent1, parent2) mutate(child) children.append(child) population = survivers + children assert len(population) == config.pop_size ### Summary best = max(population, key=lambda individual: individual["fitness"]) print("best Individual got score {}, and looked like: {}".format( best["fitness"], best)) average_population_fitness = mean( [individual["fitness"] for individual in population]) print( "average population fitness: {}".format(average_population_fitness)) world.env.close()
pygame.display.update() # EVOLVE NEW GENERATION most_fit = ga.get_most_fit(herbivores) offspring_population = [] while len(offspring_population) < len(herbivores): parent_a = ga.fitness_proportionate_selection(herbivores) parent_b = ga.fitness_proportionate_selection(herbivores) offspring = ga.reproduce(parent_a, parent_b) if random.random() < MUTATION_PROBABILITY: offspring = ga.mutate(offspring) offspring_population.append(offspring) plants = [] herbivores = offspring_population
def train(): """Function that begins the training process""" # Setup Graphing variables generation_fitnesses = [ ] # To store average fitness for each generation (y coordinate) figure = plt.figure(figsize=(6, 3)) fitness_graph = figure.add_subplot(1, 1, 1) fitness_graph.set_xlabel("Generation") # X axis label fitness_graph.set_ylabel("Fitness") # Y axis label # Generate Population and set up simulation population = ga.generate_population(constants.POOL_SIZE, constants.TOPOLOGY) print("Initial population generated") # Display generated population population[0].brain.print_network_structure() for i in population: i.brain.print_network_weights() generation = 0 # Stores the current generation of the training process solution_found = False # Whether the minimum criteria for the solution met print("Solution not found in initial population...Continuing evaluation") while not solution_found: # Repeat evaluation and training process until suitable solution found # Evaluate population fitness print("Evaluating current population...") env.Environment(population, generation) # Find best Code and show info solution = population[0] for solution in population: if solution.fitness > solution.fitness: solution = solution # Mark solution as fittest in population solution.fittest = True print("Best solution located and marked at: ", hex(id(solution))) # Calculate average population fitness total_population_fitness = 0 for i in population: total_population_fitness += i.fitness avg_fitness = total_population_fitness / len(population) # Visualization generation_fitnesses.append(avg_fitness) x = [i for i in range(0, len(generation_fitnesses))] # Generation number y = generation_fitnesses # Average fitness achieved on this generation fitness_graph.clear() fitness_graph.set_xlabel("Generation") fitness_graph.set_ylabel("Average Fitness") fitness_graph.plot(x, y) plt.pause(0.1) # Required for rendering # Display current generation info print("") print("Generation: ", generation) print("Average generation fitness: ", avg_fitness) print('Target Number: ' + str(constants.TARGET_TIME)) print("Best Code fitness = ", solution.time) print("") # Stop simulation if minimum criteria met if solution.time >= constants.TARGET_TIME: solution_found = True print("Minimum search criteria met, terminating simulation...") else: print("Solution criteria not met, producing new population...") # Generate new generation new_population = [] # Stores members of the next generation while len( new_population ) < constants.POOL_SIZE: # Keeps producing children until required population size met # Choose two parents parent1 = ga.choose_parent(population) parent2 = ga.choose_parent(population) # Create and add one child to next population childs = ga.produce_child_solution(parent1, parent2) for child in childs: if child not in population: # Prevent identical children if crossover doesn't occur child = ga.mutate(child) # Apply mutation new_population.append(child) # Add best solution from last iteration new_population.append(solution) population = new_population generation += 1
elif sys.argv[1] == "bruteforce": # Test simple against brute-force for filename in os.listdir(datasets): if simple not in filename: continue print(filename) values, sets, edges, max_cost = load_dataset(datasets+filename) mult = lambda x, y: x * y factorial = lambda n: reduce(mult, range(1, n+1)) num_perms = factorial(len(sets)) * reduce(mult, [len(set) for set in sets.values()]) print "Solving for %s sets connected by %s edges totalling %s permutations with a max cost of %s." \ % (len(sets), len(edges), num_perms, max_cost) score, tour, runtime = timeit(brute_force, sets, cost(values, edges, max_cost)) print "Brute Force:", score, runtime score, tour, runtime = timeit(genetic_algorithm, sets, cost(values, edges, max_cost), random_sample(sets.keys(), sets), mutate(sets)) print "Genetic Algorithm:", score, runtime elif sys.argv[1] == "ga-pop": # Compare GA population on apc for filename in os.listdir(datasets): if apc not in filename: continue print(filename) values, sets, edges, max_cost = load_dataset(datasets+filename) mult = lambda x, y: x * y factorial = lambda n: reduce(mult, range(1, n+1)) num_perms = factorial(len(sets)) * reduce(mult, [len(set) for set in sets.values()]) print "Solving for %s sets connected by %s edges totalling %s permutations with a max cost of %s." \ % (len(sets), len(edges), num_perms, max_cost) score, tour, runtime = timeit(genetic_algorithm, sets, cost(values, edges, max_cost),