def update_external_archive(self): feasible_solutions = [] for solution in self.solutions: if is_feasible(solution): feasible_solutions.append(copy.deepcopy(solution)) if len(feasible_solutions) > 0: feasible_solutions = feasible_solutions + self.archive ranking = FastNonDominatedRanking() ranking.compute_ranking(feasible_solutions) first_rank_solutions = ranking.get_subfront(0) if len(first_rank_solutions) <= self.population_size: self.archive = [] for solution in first_rank_solutions: self.archive.append(copy.deepcopy(solution)) else: crowding_distance = CrowdingDistance() while len(first_rank_solutions) > self.population_size: crowding_distance.compute_density_estimator( first_rank_solutions) first_rank_solutions = sorted( first_rank_solutions, key=lambda x: x.attributes['crowding_distance'], reverse=True) first_rank_solutions.pop() self.archive = [] for solution in first_rank_solutions: self.archive.append(copy.deepcopy(solution))
def get_result(self) -> R: ranking = FastNonDominatedRanking(self.dominance_comparator) ranking.compute_ranking(self.solutions) try: non_dominated = ranking.get_nondominated() except IndexError: non_dominated = None return non_dominated if non_dominated else self.solutions
def __init__( self, problem: Problem, population_size: int, neighborhood: Neighborhood, archive: BoundedArchive, mutation: Mutation, crossover: Crossover, selection: Selection = BinaryTournamentSelection( MultiComparator([ FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator() ])), termination_criterion: TerminationCriterion = store. default_termination_criteria, population_generator: Generator = store.default_generator, population_evaluator: Evaluator = store.default_evaluator, dominance_comparator: Comparator = store.default_comparator, ): """ MOCEll implementation as described in: :param problem: The problem to solve. :param population_size: Size of the population. :param mutation: Mutation operator (see :py:mod:`jmetal.operator.mutation`). :param crossover: Crossover operator (see :py:mod:`jmetal.operator.crossover`). :param selection: Selection operator (see :py:mod:`jmetal.operator.selection`). """ super(MOCell, self).__init__( problem=problem, population_size=population_size, offspring_population_size=1, mutation=mutation, crossover=crossover, selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, population_generator=population_generator, ) self.dominance_comparator = dominance_comparator self.neighborhood = neighborhood self.archive = archive self.current_individual = 0 self.current_neighbors = [] self.comparator = MultiComparator([ FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator() ])
def __init__( self, problem: Problem, population_size: int, mutation: Mutation, crossover: Crossover, number_of_cores: int, client, selection: Selection = BinaryTournamentSelection( MultiComparator([ FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator() ])), termination_criterion: TerminationCriterion = store. default_termination_criteria, dominance_comparator: DominanceComparator = DominanceComparator()): super(DistributedNSGAII, self).__init__() self.problem = problem self.population_size = population_size self.mutation_operator = mutation self.crossover_operator = crossover self.selection_operator = selection self.dominance_comparator = dominance_comparator self.termination_criterion = termination_criterion self.observable.register(termination_criterion) self.number_of_cores = number_of_cores self.client = client
def __init__( self, problem: Problem, dominance_comparator: Comparator = store.default_comparator, max_evaluations: int = 250, individual_population_size: int = 100, report_interval: int = 100, dataDirectory: str = "./decmopy/decmo2/weigths", ): super().__init__() self.problem = problem self.population_size = individual_population_size self.max_evaluations = max_evaluations self.report_interval = report_interval self.dataDirectory = dataDirectory self.mix_interval = 1 """Replacement""" ranking = FastNonDominatedRanking(dominance_comparator) density_estimator = CrowdingDistance() self.r = RankingAndDensityEstimatorReplacement( ranking, density_estimator, RemovalPolicyType.SEQUENTIAL) self.MIN_VALUES = 0 self.MAX_VALUES = 1 min_values: List[float] = [] max_values: List[float] = [] for _ in range(problem.number_of_objectives): min_values.append(sys.float_info.max) max_values.append(sys.float_info.min) self.extreme_values: List[List[float]] = [] self.extreme_values.append(min_values) self.extreme_values.append(max_values)
def __init__(self, reference_directions, problem: Problem, mutation: Mutation, crossover: Crossover, population_size: int = None, selection: Selection = BinaryTournamentSelection( MultiComparator([FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator()])), termination_criterion: TerminationCriterion = store.default_termination_criteria, population_generator: Generator = store.default_generator, population_evaluator: Evaluator = store.default_evaluator, dominance_comparator: Comparator = store.default_comparator): self.reference_directions = reference_directions.compute() if not population_size: population_size = len(self.reference_directions) if self.reference_directions.shape[1] != problem.number_of_objectives: raise Exception('Dimensionality of reference points must be equal to the number of objectives') super(NSGAIII, self).__init__( problem=problem, population_size=population_size, offspring_population_size=population_size, mutation=mutation, crossover=crossover, selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, population_generator=population_generator, dominance_comparator=dominance_comparator ) self.extreme_points = None self.ideal_point = np.full(self.problem.number_of_objectives, np.inf) self.worst_point = np.full(self.problem.number_of_objectives, -np.inf)
def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: result = self.dominance_comparator.compare(population[self.current_individual], offspring_population[0]) if result == 1: # the offspring individual dominates the current one population[self.current_individual] = offspring_population[0] self.archive.add(offspring_population[0]) elif result == 0: # the offspring and current individuals are non-dominated new_individual = offspring_population[0] self.current_neighbors.append(new_individual) ranking: Ranking = FastNonDominatedRanking() ranking.compute_ranking(self.current_neighbors) density_estimator: DensityEstimator = CrowdingDistance() for i in range(ranking.get_number_of_subfronts()): density_estimator.compute_density_estimator(ranking.get_subfront(i)) self.current_neighbors.sort(key=cmp_to_key(self.comparator.compare)) worst_solution = self.current_neighbors[-1] self.archive.add(new_individual) if worst_solution != new_individual: population[self.current_individual] = new_individual return population
def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: """ This method joins the current and offspring populations to produce the population of the next generation by applying the ranking and crowding distance selection. :param population: Parent population. :param offspring_population: Offspring population. :return: New population after ranking and crowding distance selection is applied. """ ranking = FastNonDominatedRanking(self.dominance_comparator) density_estimator = CrowdingDistance() r = RankingAndDensityEstimatorReplacement(ranking, density_estimator, RemovalPolicyType.ONE_SHOT) solutions = r.replace(population, offspring_population) front = self.get_result() if type(front) is not list: solutions = [front] for solution in front: print(solution.variables[0]) for solution in front: print(str(front.index(solution)) + ": ", sep=' ', end='', flush=True) print(solution.objectives, sep=' ', end='', flush=True) print() return solutions
def __init__( self, problem: DynamicProblem[S], population_size: int, offspring_population_size: int, mutation: Mutation, crossover: Crossover, selection: Selection = BinaryTournamentSelection( MultiComparator([ FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator() ])), termination_criterion: TerminationCriterion = store. default_termination_criteria, population_generator: Generator = store.default_generator, population_evaluator: Evaluator = store.default_evaluator, dominance_comparator: DominanceComparator = DominanceComparator()): super(DynamicNSGAII, self).__init__( problem=problem, population_size=population_size, offspring_population_size=offspring_population_size, mutation=mutation, crossover=crossover, selection=selection, population_evaluator=population_evaluator, population_generator=population_generator, termination_criterion=termination_criterion, dominance_comparator=dominance_comparator) self.completed_iterations = 0 self.start_computing_time = 0 self.total_computing_time = 0
def get_result(self): """ Return only non dominated solutions.""" ranking = FastNonDominatedRanking(self.dominance_comparator) ranking.compute_ranking(self.solutions, k=self.population_size) for solution in self.solutions: # print(solution.objectives, self.target_pattern) goal_flag = np.zeros((7), dtype=int) for j in range(7): if solution.objectives[j] < self.target_value_threshold[j]: goal_flag[j] = 1 else: goal_flag[j] = 0 if (goal_flag == np.array(self.target_pattern)).all(): # print(goal_flag, self.target_pattern) self.problem_solved = True return ranking.get_subfront(0)
def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: """ Implements NSGA-III selection as described in * Deb, K., & Jain, H. (2014). An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point-Based Nondominated Sorting Approach, Part I: Solving Problems With Box Constraints. IEEE Transactions on Evolutionary Computation, 18(4), 577–601. doi:10.1109/TEVC.2013.2281535. """ # Algorithm 1 steps 4--8 ranking = FastNonDominatedRanking(self.dominance_comparator) ranking.compute_ranking(population + offspring_population) ranking_index = 0 pop = [] while len(pop) < self.population_size: if len(ranking.get_subfront( ranking_index)) < self.population_size - len(pop): pop += ranking.get_subfront(ranking_index) ranking_index += 1 else: break # complete selected individuals using the reference point based approach selection = EnvironmentalSelection( number_of_objectives=self.problem.number_of_objectives, k=self.population_size - len(pop)) pop += selection.execute(ranking.get_subfront(ranking_index)) return pop
def execute(self, front: List[S]) -> List[S]: if front is None: raise Exception('The front is null') elif len(front) == 0: raise Exception('The front is empty') ranking = FastNonDominatedRanking(self.dominance_comparator) crowding_distance = CrowdingDistance() ranking.compute_ranking(front) ranking_index = 0 new_solution_list = [] while len(new_solution_list) < self.max_population_size: if len(ranking.get_subfront(ranking_index)) < (self.max_population_size - len(new_solution_list)): new_solution_list = new_solution_list + ranking.get_subfront(ranking_index) ranking_index += 1 else: subfront = ranking.get_subfront(ranking_index) crowding_distance.compute_density_estimator(subfront) sorted_subfront = sorted(subfront, key=lambda x: x.attributes['crowding_distance'], reverse=True) for i in range((self.max_population_size - len(new_solution_list))): new_solution_list.append(sorted_subfront[i]) return new_solution_list
def execute(self, front: List[S]) -> List[S]: if front is None: raise Exception('The front is null') elif len(front) == 0: raise Exception('The front is empty') ranking = FastNonDominatedRanking(self.dominance_comparator) ranking.compute_ranking(front) ranking_index = 0 new_solution_list = [] while len(new_solution_list) < self.max_population_size: if len(ranking.get_subfront(ranking_index)) < self.max_population_size - len(new_solution_list): subfront = ranking.get_subfront(ranking_index) new_solution_list = new_solution_list + subfront ranking_index += 1 else: subfront = ranking.get_subfront(ranking_index) parameter_K = len(subfront) - (self.max_population_size - len(new_solution_list)) while parameter_K > 0: subfront = self.compute_hypervol_fitness_values(subfront, self.reference_point, parameter_K) subfront = sorted(subfront, key=lambda x: x.attributes['fitness'], reverse=True) subfront = subfront[:-1] parameter_K = parameter_K - 1 new_solution_list = new_solution_list + subfront return new_solution_list
def execute(self, solution_list: List[S]) -> List[S]: ranking = FastNonDominatedRanking() crowding_distance = CrowdingDistance() ranking.compute_ranking(solution_list) ranking_index = 0 new_solution_list = [] while len(new_solution_list) < self.max_population_size: if len(ranking.get_subfront(ranking_index) ) < self.max_population_size - len(new_solution_list): new_solution_list = new_solution_list + ranking.get_subfront( ranking_index) ranking_index += 1 else: subfront = ranking.get_subfront(ranking_index) crowding_distance.compute_density_estimator(subfront) sorted_subfront = sorted( subfront, key=lambda x: x.attributes["crowding_distance"], reverse=True) for i in range( (self.max_population_size - len(new_solution_list))): new_solution_list.append(sorted_subfront[i]) return new_solution_list
def __init__(self, problem: Problem, population_size: int, offspring_population_size: int, mutation: Mutation, crossover: Crossover, selection: Selection = BinaryTournamentSelection( MultiComparator([ FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator() ])), termination_criterion: TerminationCriterion = store. default_termination_criteria, population_generator: Generator = store.default_generator, population_evaluator: Evaluator = store.default_evaluator, dominance_comparator: Comparator = store.default_comparator, target_value_threshold: List[float] = None, target_pattern: List[int] = None): """ NSGA-II implementation as described in * K. Deb, A. Pratap, S. Agarwal and T. Meyarivan, "A fast and elitist multiobjective genetic algorithm: NSGA-II," in IEEE Transactions on Evolutionary Computation, vol. 6, no. 2, pp. 182-197, Apr 2002. doi: 10.1109/4235.996017 NSGA-II is a genetic algorithm (GA), i.e. it belongs to the evolutionary algorithms (EAs) family. The implementation of NSGA-II provided in jMetalPy follows the evolutionary algorithm template described in the algorithm module (:py:mod:`jmetal.core.algorithm`). .. note:: A steady-state version of this algorithm can be run by setting the offspring size to 1. :param problem: The problem to solve. :param population_size: Size of the population. :param mutation: Mutation operator (see :py:mod:`jmetal.operator.mutation`). :param crossover: Crossover operator (see :py:mod:`jmetal.operator.crossover`). :param selection: Selection operator (see :py:mod:`jmetal.operator.selection`). """ super(NSGAII, self).__init__( problem=problem, population_size=population_size, offspring_population_size=offspring_population_size, mutation=mutation, crossover=crossover, selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, population_generator=population_generator) self.dominance_comparator = dominance_comparator self.generation = 0 self.target_pattern = target_pattern self.problem_solved = False self.target_value_threshold = target_value_threshold self.file_pareto_front = os.getcwd() + '/' + str( time.strftime("%Y_%m_%d")) + '_PARETO_' if not os.path.exists(self.file_pareto_front): os.mkdir(self.file_pareto_front)
def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: ranking = FastNonDominatedRanking(self.dominance_comparator) density_estimator = CrowdingDistance() r = RankingAndDensityEstimatorReplacement(ranking, density_estimator, RemovalPolicyType.ONE_SHOT) solutions = r.replace(population, offspring_population) return solutions
def test_should_replacement_return_the_right_value_case3(self): """""" points_population = [ [0.13436424411240122, 4.323216008886963], [0.23308445025757263, 4.574937990387161], [0.17300740157905092, 4.82329350808847], [0.9571162814602269, 3.443495331489301], [0.25529404008730594, 3.36387501100745], [0.020818108509287336, 5.1051826661880515], [0.8787178982088466, 3.2716009445324103], [0.6744550697237632, 3.901350307095427], [0.7881164487252263, 3.1796004913916516], [0.1028341459863098, 4.9409270526888935], ] points_offspring_population = [ [0.3150521745650882, 4.369120371847888], [0.8967291504209932, 2.506948771242972], [0.6744550697237632, 3.9361442668874504], [0.9571162814602269, 3.4388386707431433], [0.13436424411240122, 4.741872175943253], [0.25529404008730594, 2.922302861104415], [0.23308445025757263, 4.580180404770213], [0.23308445025757263, 4.591260299892424], [0.9571162814602269, 2.9865495383518694], [0.25529404008730594, 3.875587748122183], ] ranking = FastNonDominatedRanking() density_estimator = KNearestNeighborDensityEstimator(1) population = [] for i in range(len(points_population)): population.append(Solution(2, 2)) population[i].objectives = points_population[i] offspring_population = [] for i in range(len(points_offspring_population)): offspring_population.append(Solution(2, 2)) offspring_population[i].objectives = points_offspring_population[i] replacement = RankingAndDensityEstimatorReplacement(ranking, density_estimator) result_list = replacement.replace(population, offspring_population) self.assertEqual(10, len(result_list)) for solution in result_list[0:4]: self.assertEqual(0, solution.attributes["dominance_ranking"]) for solution in result_list[5:9]: self.assertEqual(1, solution.attributes["dominance_ranking"])
def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: """ This method joins the current and offspring populations to produce the population of the next generation by applying the ranking and crowding distance selection. :param population: Parent population. :param offspring_population: Offspring population. :return: New population after ranking and crowding distance selection is applied. """ ranking = FastNonDominatedRanking(self.dominance_comparator) density_estimator = CrowdingDistance() r = RankingAndDensityEstimatorReplacement(ranking, density_estimator, RemovalPolicyType.ONE_SHOT) solutions = r.replace(population, offspring_population) return solutions
def __init__(self, problem: MultiTransfer.MultiTransferProblem, population_size: int, offspring_population_size: int, mutation: Mutation, crossover: Crossover, selection: Selection = BinaryTournamentSelection( MultiComparator([FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator()])), termination_criterion: TerminationCriterion = store.default_termination_criteria, population_generator: Generator = store.default_generator, population_evaluator: Evaluator = store.default_evaluator, dominance_comparator: Comparator = store.default_comparator): """ NSGA-II implementation as described in * K. Deb, A. Pratap, S. Agarwal and T. Meyarivan, "A fast and elitist multiobjective genetic algorithm: NSGA-II," in IEEE Transactions on Evolutionary Computation, vol. 6, no. 2, pp. 182-197, Apr 2002. doi: 10.1109/4235.996017 NSGA-II is a genetic algorithm (GA), i.e. it belongs to the evolutionary algorithms (EAs) family. The implementation of NSGA-II provided in jMetalPy follows the evolutionary algorithm template described in the algorithm module (:py:mod:`jmetal.core.algorithm`). .. note:: A steady-state version of this algorithm can be run by setting the offspring size to 1. :param problem: The problem to solve. :param population_size: Size of the population. :param mutation: Mutation operator (see :py:mod:`jmetal.operator.mutation`). :param crossover: Crossover operator (see :py:mod:`jmetal.operator.crossover`). :param selection: Selection operator (see :py:mod:`jmetal.operator.selection`). """ super(NSGAII_MEDA, self).__init__( problem=problem, population_size=population_size, offspring_population_size=offspring_population_size, mutation=mutation, crossover=crossover, selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, population_generator=population_generator ) self.dominance_comparator = dominance_comparator
def __init__( self, problem: Problem, dominance_comparator: Comparator = store.default_comparator, max_iterations: int = 250, individual_population_size: int = 100, report_interval: int = 100, ): super().__init__() self.problem = problem self.population_size = individual_population_size self.max_iterations = max_iterations self.report_interval = report_interval self.mix_interval = self.population_size / 10 """Replacement""" ranking = FastNonDominatedRanking(dominance_comparator) density_estimator = CrowdingDistance() self.r = RankingAndDensityEstimatorReplacement( ranking, density_estimator, RemovalPolicyType.SEQUENTIAL)
if __name__ == '__main__': # random.seed(145600) random.seed(1) instance = DTLZInstance() path = '/home/thinkpad/Documents/jemoa/src/main/resources/DTLZ_INSTANCES/DTLZ7_Instance.txt' # path = '/home/thinkpad/PycharmProjects/jMetalPy/resources/DTLZ_INSTANCES/DTLZ1P_10.txt' instance.read_(path) isObjective = False problem = DTLZ7P(instance) _best = problem.generate_existing_solution(problem.instance_.attributes['best_compromise'][0], isObjective) for s in problem.instance_.initial_solutions: problem.evaluate(s) print(s) fndr = FastNonDominatedRanking() fndr.compute_ranking(problem.instance_.initial_solutions) print(fndr.get_number_of_subfronts()) classifier = InterClassNC(problem) print('Best compromise:', _best.objectives,classifier.classify(_best)) # validate_interclass(problem) # loadDataWithClass(problem, # '/home/thinkpad/PycharmProjects/jMetalPy/results/Solutions.bag._class_enfoque_fronts_NSGAIII_custom.DTLZ1P_10.csv', # 'enfoque_fronts_') # load_objectives_from_gdm_file(problem, '/home/thinkpad/PycharmProjects/jMetalPy/resources/DTLZ_INSTANCES/objetivos_nelson.csv') # dm_generator(obj, 14, obj * [Interval(0, (9 / 8) * k * 100)]) # dtlz_test(problem, 'enfoque_fronts') print(problem) reference_set(problem,is_objective=isObjective) # looking_for_compromise(problem)
def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: # print("replacement") """ Implements NSGA-III environmental selection based on reference points as described in: * Deb, K., & Jain, H. (2014). An Evolutionary Many-Objective Optimization Algorithm Using Reference-Point-Based Nondominated Sorting Approach, Part I: Solving Problems With Box Constraints. IEEE Transactions on Evolutionary Computation, 18(4), 577–601. doi:10.1109/TEVC.2013.2281535. """ F = np.array([s.objectives for s in population]) # find or usually update the new ideal point - from feasible solutions # note that we are assuming minimization here! self.ideal_point = np.min(np.vstack((self.ideal_point, F)), axis=0) self.worst_point = np.max(np.vstack((self.worst_point, F)), axis=0) # calculate the fronts of the population ranking = FastNonDominatedRanking(self.dominance_comparator) ranking.compute_ranking(population + offspring_population, k=self.population_size) fronts, non_dominated = ranking.ranked_sublists, ranking.get_subfront(0) # find the extreme points for normalization self.extreme_points = get_extreme_points(F=np.array([s.objectives for s in non_dominated]), n_objs=self.problem.number_of_objectives, ideal_point=self.ideal_point, extreme_points=self.extreme_points) # find the intercepts for normalization and do backup if gaussian elimination fails worst_of_population = np.max(F, axis=0) worst_of_front = np.max(np.array([s.objectives for s in non_dominated]), axis=0) nadir_point = get_nadir_point(extreme_points=self.extreme_points, ideal_point=self.ideal_point, worst_point=self.worst_point, worst_of_population=worst_of_population, worst_of_front=worst_of_front) # consider only the population until we come to the splitting front pop = np.concatenate(ranking.ranked_sublists) F = np.array([s.objectives for s in pop]) # update the front indices for the current population counter = 0 for i in range(len(fronts)): for j in range(len(fronts[i])): fronts[i][j] = counter counter += 1 last_front = np.array(fronts[-1]) # associate individuals to niches niche_of_individuals, dist_to_niche = associate_to_niches(F=F, niches=self.reference_directions, ideal_point=self.ideal_point, nadir_point=nadir_point) # if we need to select individuals to survive if len(pop) > self.population_size: # if there is only one front if len(fronts) == 1: until_last_front = np.array([], dtype=np.int) niche_count = np.zeros(len(self.reference_directions), dtype=np.int) n_remaining = self.population_size # if some individuals already survived else: until_last_front = np.concatenate(fronts[:-1]) niche_count = compute_niche_count(len(self.reference_directions), niche_of_individuals[until_last_front]) n_remaining = self.population_size - len(until_last_front) S_idx = niching(pop=pop[last_front], n_remaining=n_remaining, niche_count=niche_count, niche_of_individuals=niche_of_individuals[last_front], dist_to_niche=dist_to_niche[last_front]) survivors_idx = np.concatenate((until_last_front, last_front[S_idx].tolist())) pop = pop[survivors_idx] return list(pop)
def dtlz_test(p: FloatProblemGD, label: str = '', experiment: int = 50): # problem.reference_front = read_solutions(filename='resources/reference_front/DTLZ2.3D.pf') max_evaluations = 25000 # references = ReferenceDirectionFromSolution(p) algorithm = NSGA3C( problem=p, population_size=100, reference_directions=UniformReferenceDirectionFactory(p.instance_.n_obj, n_points=92), mutation=PolynomialMutation(probability=1.0 / p.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=30), termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations) ) bag = [] total_time = 0 for i in range(experiment): algorithm = NSGA3C( problem=p, population_size=92, reference_directions=UniformReferenceDirectionFactory(p.instance_.n_obj, n_points=91), mutation=PolynomialMutation(probability=1.0 / p.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=30), termination_criterion=StoppingByEvaluations(max_evaluations=max_evaluations) ) progress_bar = ProgressBarObserver(max=max_evaluations) algorithm.observable.register(progress_bar) algorithm.run() total_time += algorithm.total_computing_time bag = bag + algorithm.get_result() print(len(bag)) print('Total computing time:', total_time) print('Average time: ', str(total_time / experiment)) print_solutions_to_file(bag, DIRECTORY_RESULTS + 'Solutions.bag._class_' + label + algorithm.label) ranking = FastNonDominatedRanking() ranking.compute_ranking(bag) front_ = ranking.get_subfront(0) print('Front 0 size : ', len(front_)) alabels = [] for obj in range(p.number_of_objectives): alabels.append('Obj-' + str(obj)) plot_front = Plot(title='Pareto front approximation' + ' ' + label, axis_labels=alabels) plot_front.plot(front_, label=label + 'F0 ' + algorithm.label, filename=DIRECTORY_RESULTS + 'F0_class_' + 'original_' + label + algorithm.label, format='png') class_fronts = [[], [], [], []] for s in front_: _class = problem.classifier.classify(s) if _class[0] > 0: class_fronts[0].append(s) elif _class[1] > 0: class_fronts[1].append(s) elif _class[2] > 0: class_fronts[2].append(s) else: class_fronts[3].append(s) print(len(class_fronts[0]), len(class_fronts[1]), len(class_fronts[2]), len(class_fronts[3])) _front = class_fronts[0] + class_fronts[1] if len(_front) == 0: _front = class_fronts[2] + class_fronts[3] print('Class : ', len(_front)) # Save results to file print_solutions_to_file(_front, DIRECTORY_RESULTS + 'Class_F0' + label + algorithm.label) print(f'Algorithm: ${algorithm.get_name()}') print(f'Problem: ${p.get_name()}') plot_front = Plot(title=label + 'F_' + p.get_name(), axis_labels=alabels) plot_front.plot(_front, label=label + 'F_' + p.get_name(), filename=DIRECTORY_RESULTS + 'Class_F0' + label + p.get_name(), format='png')
from jmetal.util.termination_criterion import StoppingByEvaluations if __name__ == '__main__': problem = TSP(instance='../../resources/TSP_instances/kroA100.tsp') print('Cities: ', problem.number_of_variables) algorithm = GeneticAlgorithm( problem=problem, population_size=100, offspring_population_size=100, mutation=PermutationSwapMutation(1.0 / problem.number_of_variables), crossover=PMXCrossover(0.8), selection=BinaryTournamentSelection( MultiComparator([ FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator() ])), termination_criterion=StoppingByEvaluations(max=2500000)) algorithm.observable.register(observer=PrintObjectivesObserver(1000)) algorithm.run() result = algorithm.get_result() print('Algorithm: {}'.format(algorithm.get_name())) print('Problem: {}'.format(problem.get_name())) print('Solution: {}'.format(result.variables)) print('Fitness: {}'.format(result.objectives[0])) print('Computing time: {}'.format(algorithm.total_computing_time))
def run(self): """ Execute the algorithm. """ self.start_computing_time = time.time() create_solution = dask.delayed(self.problem.create_solution) evaluate_solution = dask.delayed(self.problem.evaluate) task_pool = as_completed([], with_results=True) for _ in range(self.number_of_cores): new_solution = create_solution() new_evaluated_solution = evaluate_solution(new_solution) future = self.client.compute(new_evaluated_solution) task_pool.add(future) batches = task_pool.batches() auxiliar_population = [] while len(auxiliar_population) < self.population_size: batch = next(batches) for _, received_solution in batch: auxiliar_population.append(received_solution) if len(auxiliar_population) < self.population_size: break # submit as many new tasks as we collected for _ in batch: new_solution = create_solution() new_evaluated_solution = evaluate_solution(new_solution) future = self.client.compute(new_evaluated_solution) task_pool.add(future) self.init_progress() # perform an algorithm step to create a new solution to be evaluated while not self.stopping_condition_is_met(): batch = next(batches) for _, received_solution in batch: offspring_population = [received_solution] # replacement ranking = FastNonDominatedRanking(self.dominance_comparator) density_estimator = CrowdingDistance() r = RankingAndDensityEstimatorReplacement( ranking, density_estimator, RemovalPolicyType.ONE_SHOT) auxiliar_population = r.replace(auxiliar_population, offspring_population) # selection mating_population = [] for _ in range(2): solution = self.selection_operator.execute( auxiliar_population) mating_population.append(solution) # Reproduction and evaluation new_task = self.client.submit(reproduction, mating_population, self.problem, self.crossover_operator, self.mutation_operator) task_pool.add(new_task) # update progress self.evaluations += 1 self.solutions = auxiliar_population self.update_progress() if self.stopping_condition_is_met(): break self.total_computing_time = time.time() - self.start_computing_time # at this point, computation is done for future, _ in task_pool: future.cancel()
class FastNonDominatedRankingTestCases(unittest.TestCase): def setUp(self): self.ranking = FastNonDominatedRanking() def test_should_constructor_create_a_valid_object(self): self.assertIsNotNone(self.ranking) def test_should_compute_ranking_of_an_emtpy_solution_list_return_a_empty_list_of_subranks(self): solution_list = [] self.assertEqual(0, len(self.ranking.compute_ranking(solution_list))) def test_should_compute_ranking_return_a_subfront_if_the_solution_list_contains_one_solution(self): solution = Solution(2, 3) solution_list = [solution] ranking = self.ranking.compute_ranking(solution_list) self.assertEqual(1, self.ranking.get_number_of_subfronts()) self.assertEqual(solution, ranking[0][0]) def test_should_compute_ranking_return_a_subfront_if_the_solution_list_contains_two_nondominated_solutions(self): solution = Solution(2, 2) solution.objectives = [1, 2] solution2 = Solution(2, 2) solution2.objectives = [2, 1] solution_list = [solution, solution2] ranking = self.ranking.compute_ranking(solution_list) self.assertEqual(1, self.ranking.get_number_of_subfronts()) self.assertEqual(2, len(self.ranking.get_subfront(0))) self.assertEqual(solution, ranking[0][0]) self.assertEqual(solution2, ranking[0][1]) def test_should_compute_ranking_work_properly_case1(self): """ The list contains two solutions and one of them is dominated by the other one. """ solution = Solution(2, 2) solution.objectives = [2, 3] solution2 = Solution(2, 2) solution2.objectives = [3, 6] solution_list = [solution, solution2] ranking = self.ranking.compute_ranking(solution_list) self.assertEqual(2, self.ranking.get_number_of_subfronts()) self.assertEqual(1, len(self.ranking.get_subfront(0))) self.assertEqual(1, len(self.ranking.get_subfront(1))) self.assertEqual(solution, ranking[0][0]) self.assertEqual(solution2, ranking[1][0]) def test_should_ranking_of_a_population_with_three_dominated_solutions_return_three_subfronts(self): solution = Solution(2, 2) solution.objectives = [2, 3] solution2 = Solution(2, 2) solution2.objectives = [3, 6] solution3 = Solution(2, 2) solution3.objectives = [4, 8] solution_list = [solution, solution2, solution3] ranking = self.ranking.compute_ranking(solution_list) self.assertEqual(3, self.ranking.get_number_of_subfronts()) self.assertEqual(1, len(self.ranking.get_subfront(0))) self.assertEqual(1, len(self.ranking.get_subfront(1))) self.assertEqual(1, len(self.ranking.get_subfront(2))) self.assertEqual(solution, ranking[0][0]) self.assertEqual(solution2, ranking[1][0]) self.assertEqual(solution3, ranking[2][0]) def test_should_ranking_of_a_population_with_five_solutions_work_properly(self): solution1 = Solution(2, 2) solution2 = Solution(2, 2) solution3 = Solution(2, 2) solution4 = Solution(2, 2) solution5 = Solution(2, 2) solution1.objectives[0] = 1.0 solution1.objectives[1] = 0.0 solution2.objectives[0] = 0.5 solution2.objectives[1] = 0.5 solution3.objectives[0] = 0.0 solution3.objectives[1] = 1.0 solution4.objectives[0] = 0.6 solution4.objectives[1] = 0.6 solution5.objectives[0] = 0.7 solution5.objectives[1] = 0.5 solutions = [solution1, solution2, solution3, solution4, solution5] ranking = self.ranking.compute_ranking(solutions) self.assertEqual(2, self.ranking.get_number_of_subfronts()) self.assertEqual(3, len(self.ranking.get_subfront(0))) self.assertEqual(2, len(self.ranking.get_subfront(1))) self.assertEqual(solution1, ranking[0][0]) self.assertEqual(solution2, ranking[0][1]) self.assertEqual(solution3, ranking[0][2]) self.assertEqual(solution4, ranking[1][0]) self.assertEqual(solution5, ranking[1][1])
def get_result(self): """ Return only non dominated solutions.""" ranking = FastNonDominatedRanking(self.dominance_comparator) ranking.compute_ranking(self.solutions, k=self.population_size) return ranking.get_subfront(0)
def validate_interclass(problem): with open('/home/thinkpad/Documents/jemoa/experiments/dtlz_preferences/Class_F0DTLZ1_P3.out') as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] solutions = [] print(problem.get_preference_model(0)) for idx, line in enumerate(content): split = line.split('*')[1].split(',') _s = problem.generate_existing_solution([float(x) for x in split],is_objectives=True) _s.bag = 'java' solutions.append(_s) with open('/home/thinkpad/PycharmProjects/jMetalPy/results/Class_F0enfoque_frontsNSGAIII_custom.DTLZ1P_3.csv') as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] for idx, line in enumerate(content): if not 'variables' in line: split = line.split('*')[1].split(',') _s = problem.generate_existing_solution([float(x) for x in split], is_objectives=True) _s.bag = 'python' solutions.append(_s) ranking = FastNonDominatedRanking() ranking.compute_ranking(solutions) front_ = ranking.get_subfront(0) print('Solutions:',len(solutions)) print('Front 0:', len(front_)) class_fronts = [[], [], [], []] fjava = 0 fpython = 0 classifier = InterClassNC(problem) for s in front_: if s.bag == 'java': fjava += 1 else: fpython += 1 # problem.evaluate(s) _class = classifier.classify(s) if _class[0] > 0: class_fronts[0].append(s) elif _class[1] > 0: class_fronts[1].append(s) elif _class[2] > 0: class_fronts[2].append(s) else: class_fronts[3].append(s) print('Java solutions:', (fjava / len(front_))) print('Python solutions:', (fpython / len(front_))) print('HSat : ', len(class_fronts[0]), ', Sat : ', len(class_fronts[1]), ', Dis : ', len(class_fronts[2]), ', HDis : ', len(class_fronts[3])) _sat = class_fronts[0] + class_fronts[1] fjava = 0 fpython = 0 for s in _sat: if s.bag == 'java': fjava += 1 else: fpython += 1 print('Sat Java solutions:', (fjava / len(_sat))) print('Sat Python solutions:', (fpython / len(_sat))) plot_front = Plot(title='Sat and HSat Front') plot_front.plot(_sat, label= 'Sat and HSat Front', filename=DIRECTORY_RESULTS + 'SatFront' + problem.get_name(), format='png')
def construct(self, hyperparameters: Mapping, scenario: Mapping, warm_startup_info: Mapping) -> None: # Constructing meta-heuristics initialization arguments (components + simple hyperparameters) init_args = dict(copy(hyperparameters)) if "crossover_type" in init_args: import jmetal.operator.crossover as crossover crossover_class = JMetalPyWrapper._get_class_from_module( name=init_args.pop("crossover_type"), module=crossover) init_args["crossover"] = crossover_class( init_args.pop("crossover_probability")) if "mutation_type" in init_args: import jmetal.operator.mutation as mutation mutation_class = JMetalPyWrapper._get_class_from_module( name=init_args.pop("mutation_type"), module=mutation) init_args["mutation"] = mutation_class( init_args.pop("mutation_probability")) if "selection_type" in init_args: selection_type = init_args.pop('selection_type') if selection_type == 'ReuletteWheelSelection': from jmetal.util.comparator import MultiComparator from jmetal.util.density_estimator import CrowdingDistance from jmetal.util.ranking import FastNonDominatedRanking init_args["selection"] = MultiComparator([ FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator() ]) else: import jmetal.operator.selection as selection selection_class = JMetalPyWrapper._get_class_from_module( name=selection_type, module=selection) init_args["selection"] = selection_class() # Add all non-component Metaheuristic parameters if "offspring_population_size" in init_args: offsp_population = init_args.pop("offspring_population_size") # offspring_population_size should be even offsp_population += offsp_population % 2 init_args['offspring_population_size'] = offsp_population # elitist should be bool if "elitist" in init_args: init_args['elitist'] = True if init_args.pop( 'elitist') == "True" else False if "population_size" in init_args: init_args["population_size"] = init_args.pop("population_size") termination_class = JMetalPyWrapper._get_class_from_module( name=scenario["Budget"]["Type"], module=termination) init_args["termination_criterion"] = termination_class( scenario["Budget"]["Amount"]) # making dict hashable enables using LRU cache problem_init_params = HashableDict( scenario['problem_initialization_parameters']) problem = JMetalPyWrapper._get_problem( problem_name=scenario['Problem'], init_params=problem_init_params) init_args["problem"] = problem # Attach initial solutions. self.load_initial_solutions(warm_startup_info, problem) llh_name = init_args.pop("low level heuristic") if llh_name == "jMetalPy.SimulatedAnnealing": init_args["solution_generator"] = self._solution_generator else: init_args['population_generator'] = self._solution_generator # Instantiate Metaheuristic object self._llh_algorithm = JMetalPyWrapper._get_algorithm_class(llh_name)( **init_args)
def setUp(self): self.ranking = FastNonDominatedRanking()