def generate_new_solution(self): for i in range(self.randomness): new_solution = modify_solution(self.graph, self.current_solution) if fitness(new_solution) > fitness(self.current_solution): self.current_solution = new_solution
n_of_elite = 10 good_solutions = 10 elite_solutions = 5 max_best_solution_len = round(vertices_number / 3) bees = [Bee(graph) for x in range(0, n_of_bees)] best_solution = None iteration = 0 for bee in bees: bee.current_solution = modify_solution(graph, path) all_time_best_solution = path for i in range(20): solutions = [bee.current_solution for bee in bees] fitnesses = [fitness(solution) for solution in solutions] fit_sol = list(zip(fitnesses, solutions)) fit_sol.sort(key=lambda x: x[0]) current_best_solution = fit_sol[-1][1] if fitness(current_best_solution) > fitness( all_time_best_solution) and len( current_best_solution) < max_best_solution_len: all_time_best_solution = current_best_solution # sort solutions and assign bees elite_sols = [s for (f, s) in fit_sol[:elite_solutions]] good_sols = [s for (f, s) in fit_sol[elite_solutions:good_solutions]] rest_sols = [s for (f, s) in fit_sol[good_solutions:]] for i, bee in enumerate(bees[:n_of_elite]): bee.current_solution = elite_sols[i % len(elite_sols)]
def testFitnessNearMean(self): self.assertEqual( fitness([1], [1], [0.1], 2)[0], multivariate_normal.pdf(0))
def testFitnessTooFar(self): self.assertLessEqual(fitness([1.5], [1], [0.1], 1)[0], 0)
def testFitnessNotNearEnough(self): self.assertGreaterEqual(fitness([0.5], [1], [0.1], 1)[0], 0)
def testFitnessFarFromMean(self): self.assertEqual(fitness([5], [1], [0.1], 2)[0], -1) self.assertEqual(fitness([5, 5], [1, 1], [0.1, 0.1], 3)[0], -2)