示例#1
0
    def test_should_compare_work_properly_case_1(self):
        """Case 1: a comparator returning 0."""
        solution1 = Solution(2, 2)
        solution2 = Solution(2, 2)

        mocked_comparator: Comparator = mock()
        when(mocked_comparator).compare(solution1, solution2).thenReturn(0)

        comparator_list = [mocked_comparator]

        multi_comparator = MultiComparator(comparator_list)
        self.assertEqual(0, multi_comparator.compare(solution1, solution2))

        verify(mocked_comparator, times=1).compare(solution1, solution2)
示例#2
0
    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()
        ])
示例#3
0
    def __init__(
        self,
        problem: Problem,
        population_size: int,
        offspring_population_size: int,
        mutation: Mutation,
        crossover: Crossover,
        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,
    ):
        """
        :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`).
        """
        multi_comparator = MultiComparator(
            [StrengthRanking.get_comparator(), KNearestNeighborDensityEstimator.get_comparator()]
        )
        selection = BinaryTournamentSelection(comparator=multi_comparator)

        super(SPEA2, 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
示例#4
0
    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)
示例#5
0
    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
示例#6
0
 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
示例#7
0
    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)
示例#8
0
    def test_should_compare_work_properly_case_3(self):
        """Case 2: two comparators; the first returns 0 and the second one returns -1.
        Expected result: -1
        """
        solution1 = Solution(2, 2)
        solution2 = Solution(2, 2)

        mocked_comparator1: Comparator = mock()
        when(mocked_comparator1).compare(solution1, solution2).thenReturn(0)
        mocked_comparator2: Comparator = mock()
        when(mocked_comparator2).compare(solution1, solution2).thenReturn(-1)

        comparator_list = [mocked_comparator1, mocked_comparator2]

        multi_comparator = MultiComparator(comparator_list)
        self.assertEqual(-1, multi_comparator.compare(solution1, solution2))

        verify(mocked_comparator1, times=1).compare(solution1, solution2)
        verify(mocked_comparator2, times=1).compare(solution1, solution2)
示例#9
0
    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
示例#10
0
文件: moga.py 项目: ufvceiec/MOGA
    def __init__(self,
                 problem: Problem,
                 population_size: int,
                 offspring_population_size: int,
                 mutation: Mutation,
                 crossover: Crossover,
                 selection: Selection = BinaryTournamentSelection(MultiComparator([SolutionAttributeComparator(key = "fitness")])),
                 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):

        super(MOGA, 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
示例#11
0
    def test_should_compare_return_zero_if_the_comparator_list_is_empty(self):
        solution1 = Solution(2, 2)
        solution2 = Solution(2, 2)

        multi_comparator = MultiComparator([])
        self.assertEqual(0, multi_comparator.compare(solution1, solution2))
示例#12
0
    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)
示例#13
0
from jmetal.util.density_estimator import CrowdingDistance
from jmetal.util.ranking import FastNonDominatedRanking
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.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))