diff --git a/docs/.buildinfo b/docs/.buildinfo index 93767c9e..da73e819 100644 --- a/docs/.buildinfo +++ b/docs/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: d5baa1b64aedad170a2f4617683d66c9 +config: 4b780489226086b8db31ab45dede2a32 tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/_images/abstract.png b/docs/_images/abstract.png deleted file mode 100644 index 6a530e6a..00000000 Binary files a/docs/_images/abstract.png and /dev/null differ diff --git a/docs/_images/bad_access.png b/docs/_images/bad_access.png deleted file mode 100644 index f2511892..00000000 Binary files a/docs/_images/bad_access.png and /dev/null differ diff --git a/docs/_images/class_header.png b/docs/_images/class_header.png deleted file mode 100644 index ea734158..00000000 Binary files a/docs/_images/class_header.png and /dev/null differ diff --git a/docs/_images/generic_class1.png b/docs/_images/generic_class1.png deleted file mode 100644 index 5679412f..00000000 Binary files a/docs/_images/generic_class1.png and /dev/null differ diff --git a/docs/_images/generic_class2.png b/docs/_images/generic_class2.png deleted file mode 100644 index 38a2a5fb..00000000 Binary files a/docs/_images/generic_class2.png and /dev/null differ diff --git a/docs/_images/generic_types.png b/docs/_images/generic_types.png deleted file mode 100644 index fa8cb9e1..00000000 Binary files a/docs/_images/generic_types.png and /dev/null differ diff --git a/docs/_images/generic_types_fixed.png b/docs/_images/generic_types_fixed.png deleted file mode 100644 index 91d2ebe0..00000000 Binary files a/docs/_images/generic_types_fixed.png and /dev/null differ diff --git a/docs/_images/good_access.png b/docs/_images/good_access.png deleted file mode 100644 index c3d4ab85..00000000 Binary files a/docs/_images/good_access.png and /dev/null differ diff --git a/docs/_images/inheritance_generic_to_generic.png b/docs/_images/inheritance_generic_to_generic.png deleted file mode 100644 index 04312537..00000000 Binary files a/docs/_images/inheritance_generic_to_generic.png and /dev/null differ diff --git a/docs/_images/inheritance_non_generic_to_generic.png b/docs/_images/inheritance_non_generic_to_generic.png deleted file mode 100644 index c6c78787..00000000 Binary files a/docs/_images/inheritance_non_generic_to_generic.png and /dev/null differ diff --git a/docs/_images/instance_with_generic_class_wearning.png b/docs/_images/instance_with_generic_class_wearning.png deleted file mode 100644 index 0b02e6dc..00000000 Binary files a/docs/_images/instance_with_generic_class_wearning.png and /dev/null differ diff --git a/docs/_images/instance_with_generic_types1_wearning.png b/docs/_images/instance_with_generic_types1_wearning.png deleted file mode 100644 index 03891cb2..00000000 Binary files a/docs/_images/instance_with_generic_types1_wearning.png and /dev/null differ diff --git a/docs/_images/instance_with_generic_types2_wearning.png b/docs/_images/instance_with_generic_types2_wearning.png deleted file mode 100644 index a392af70..00000000 Binary files a/docs/_images/instance_with_generic_types2_wearning.png and /dev/null differ diff --git a/docs/_images/method_way_sphinx.png b/docs/_images/method_way_sphinx.png deleted file mode 100644 index 6d14a595..00000000 Binary files a/docs/_images/method_way_sphinx.png and /dev/null differ diff --git a/docs/_images/property_annotation.png b/docs/_images/property_annotation.png deleted file mode 100644 index f821a255..00000000 Binary files a/docs/_images/property_annotation.png and /dev/null differ diff --git a/docs/_images/property_functional.png b/docs/_images/property_functional.png deleted file mode 100644 index 248f0e06..00000000 Binary files a/docs/_images/property_functional.png and /dev/null differ diff --git a/docs/_images/python_functional_programming.png b/docs/_images/python_functional_programming.png deleted file mode 100644 index 10fddcfd..00000000 Binary files a/docs/_images/python_functional_programming.png and /dev/null differ diff --git a/docs/_images/python_imperative_programming.png b/docs/_images/python_imperative_programming.png deleted file mode 100644 index 40a59b44..00000000 Binary files a/docs/_images/python_imperative_programming.png and /dev/null differ diff --git a/docs/_images/python_poo_programming.png b/docs/_images/python_poo_programming.png deleted file mode 100644 index 5d8aefe2..00000000 Binary files a/docs/_images/python_poo_programming.png and /dev/null differ diff --git a/docs/_images/types_in_methods.png b/docs/_images/types_in_methods.png deleted file mode 100644 index 5ea9076b..00000000 Binary files a/docs/_images/types_in_methods.png and /dev/null differ diff --git a/docs/_images/with_getter_setter.png b/docs/_images/with_getter_setter.png deleted file mode 100644 index e96691d7..00000000 Binary files a/docs/_images/with_getter_setter.png and /dev/null differ diff --git a/docs/_images/without_getter_setter.png b/docs/_images/without_getter_setter.png deleted file mode 100644 index 36f68675..00000000 Binary files a/docs/_images/without_getter_setter.png and /dev/null differ diff --git a/docs/_modules/index.html b/docs/_modules/index.html index 97c8bd93..895b27d7 100644 --- a/docs/_modules/index.html +++ b/docs/_modules/index.html @@ -1,9 +1,9 @@ - - + + @@ -12,18 +12,15 @@ - Overview: module code — jMetalPy 1.5.3 documentation - - - - - - - - - - - + Overview: module code — jMetalPy 1.7.0 documentation + + + + + + + + @@ -39,7 +36,8 @@

Navigation

  • modules |
  • - + +
    @@ -50,7 +48,7 @@

    Navigation

    - - - - - - - + jmetal.algorithm.multiobjective.gde3 — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,39 +106,43 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.gde3

    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     from jmetal.config import store
    -from jmetal.core.algorithm import EvolutionaryAlgorithm, DynamicAlgorithm
    -from jmetal.core.problem import Problem, DynamicProblem
    +from jmetal.core.algorithm import DynamicAlgorithm, EvolutionaryAlgorithm
    +from jmetal.core.problem import DynamicProblem, Problem
     from jmetal.core.solution import FloatSolution
    -from jmetal.operator import DifferentialEvolutionCrossover, RankingAndCrowdingDistanceSelection
    +from jmetal.operator.crossover import DifferentialEvolutionCrossover
    +from jmetal.operator.selection import DifferentialEvolutionSelection
    +
     from jmetal.operator.selection import DifferentialEvolutionSelection
     from jmetal.util.comparator import Comparator, DominanceComparator
     from jmetal.util.evaluator import Evaluator
     from jmetal.util.generator import Generator
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    +S = TypeVar("S")
     R = List[S]
     
     
    -
    [docs]class GDE3(EvolutionaryAlgorithm[FloatSolution, FloatSolution]): - - def __init__(self, - problem: Problem, - population_size: int, - cr: float, - f: float, - termination_criterion: TerminationCriterion = store.default_termination_criteria, - k: float = 0.5, - population_generator: Generator = store.default_generator, - population_evaluator: Evaluator = store.default_evaluator, - dominance_comparator: Comparator = store.default_comparator): +
    +[docs] +class GDE3(EvolutionaryAlgorithm[FloatSolution, FloatSolution]): + def __init__( + self, + problem: Problem, + population_size: int, + cr: float, + f: float, + termination_criterion: TerminationCriterion = store.default_termination_criteria, + k: float = 0.5, + population_generator: Generator = store.default_generator, + population_evaluator: Evaluator = store.default_evaluator, + dominance_comparator: Comparator = store.default_comparator, + ): super(GDE3, self).__init__( - problem=problem, - population_size=population_size, - offspring_population_size=population_size) + problem=problem, population_size=population_size, offspring_population_size=population_size + ) self.dominance_comparator = dominance_comparator self.selection_operator = DifferentialEvolutionSelection() self.crossover_operator = DifferentialEvolutionCrossover(cr, f, k) @@ -152,7 +153,9 @@

    Source code for jmetal.algorithm.multiobjective.gde3

    self.termination_criterion = termination_criterion self.observable.register(termination_criterion) -
    [docs] def selection(self, population: List[FloatSolution]) -> List[FloatSolution]: +
    +[docs] + def selection(self, population: List[FloatSolution]) -> List[FloatSolution]: mating_pool = [] for i in range(self.population_size): @@ -162,20 +165,26 @@

    Source code for jmetal.algorithm.multiobjective.gde3

    return mating_pool
    -
    [docs] def reproduction(self, mating_pool: List[S]) -> List[S]: + +
    +[docs] + def reproduction(self, mating_pool: List[S]) -> List[S]: offspring_population = [] first_parent_index = 0 for solution in self.solutions: self.crossover_operator.current_individual = solution - parents = mating_pool[first_parent_index:first_parent_index + 3] + parents = mating_pool[first_parent_index : first_parent_index + 3] first_parent_index += 3 offspring_population.append(self.crossover_operator.execute(parents)[0]) return offspring_population
    -
    [docs] def replacement(self, population: List[S], offspring_population: List[FloatSolution]) -> List[List[FloatSolution]]: + +
    +[docs] + def replacement(self, population: List[S], offspring_population: List[FloatSolution]) -> List[List[FloatSolution]]: tmp_list = [] for solution1, solution2 in zip(self.solutions, offspring_population): @@ -194,62 +203,100 @@

    Source code for jmetal.algorithm.multiobjective.gde3

    self.population_size, dominance_comparator=self.dominance_comparator ).execute(join_population)
    -
    [docs] def create_initial_solutions(self) -> List[FloatSolution]: + +
    +[docs] + def create_initial_solutions(self) -> List[FloatSolution]: return [self.population_generator.new(self.problem) for _ in range(self.population_size)]
    -
    [docs] def evaluate(self, solution_list: List[FloatSolution]) -> List[FloatSolution]: + +
    +[docs] + def evaluate(self, solution_list: List[FloatSolution]) -> List[FloatSolution]: return self.population_evaluator.evaluate(solution_list, self.problem)
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def get_result(self) -> List[FloatSolution]: + +
    +[docs] + def result(self) -> List[FloatSolution]: return self.solutions
    -
    [docs] def get_name(self) -> str: - return 'GDE3'
    + +
    +[docs] + def get_name(self) -> str: + return "GDE3"
    +
    -
    [docs]class DynamicGDE3(GDE3, DynamicAlgorithm): - def __init__(self, - problem: DynamicProblem, - population_size: int, - cr: float, - f: float, - termination_criterion: TerminationCriterion, - k: float = 0.5, - population_generator: Generator = store.default_generator, - population_evaluator: Evaluator = store.default_evaluator, - dominance_comparator: Comparator = DominanceComparator()): +
    +[docs] +class DynamicGDE3(GDE3, DynamicAlgorithm): + def __init__( + self, + problem: DynamicProblem, + population_size: int, + cr: float, + f: float, + termination_criterion: TerminationCriterion, + k: float = 0.5, + population_generator: Generator = store.default_generator, + population_evaluator: Evaluator = store.default_evaluator, + dominance_comparator: Comparator = DominanceComparator(), + ): super(DynamicGDE3, self).__init__( - problem, population_size, cr, f, termination_criterion, k, - population_generator, population_evaluator, dominance_comparator) + problem, + population_size, + cr, + f, + termination_criterion, + k, + population_generator, + population_evaluator, + dominance_comparator, + ) self.completed_iterations = 0 -
    [docs] def restart(self) -> None: +
    +[docs] + def restart(self) -> None: pass
    -
    [docs] def update_progress(self): + +
    +[docs] + def update_progress(self): if self.problem.the_problem_has_changed(): self.restart() self.problem.clear_changed() - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data) self.evaluations += self.offspring_population_size
    -
    [docs] def stopping_condition_is_met(self): + +
    +[docs] + def stopping_condition_is_met(self): if self.termination_criterion.is_met: - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data) self.restart() self.init_progress() - self.completed_iterations += 1
    + self.completed_iterations += 1
    +
    +
    @@ -266,8 +313,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.hype — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,39 +106,41 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.hype

    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     from jmetal.algorithm.singleobjective.genetic_algorithm import GeneticAlgorithm
     from jmetal.config import store
    -from jmetal.core.operator import Mutation, Crossover
    +from jmetal.core.operator import Crossover, Mutation
     from jmetal.core.problem import Problem
     from jmetal.core.solution import Solution
    -from jmetal.operator import BinaryTournamentSelection
    +from jmetal.operator.selection import BinaryTournamentSelection
     from jmetal.operator.selection import RankingAndFitnessSelection
    -from jmetal.util.comparator import Comparator
    -from jmetal.util.comparator import SolutionAttributeComparator
    +from jmetal.util.comparator import Comparator, SolutionAttributeComparator
     from jmetal.util.evaluator import Evaluator
     from jmetal.util.generator import Generator
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    -R = TypeVar('R')
    -
    -
    -
    [docs]class HYPE(GeneticAlgorithm[S, R]): - - def __init__(self, - problem: Problem, - reference_point: Solution, - 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): - """ This is an implementation of the Hypervolume Estimation Algorithm for Multi-objective Optimization +S = TypeVar("S") +R = TypeVar("R") + + +
    +[docs] +class HYPE(GeneticAlgorithm[S, R]): + def __init__( + self, + problem: Problem, + reference_point: Solution, + 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, + ): + """This is an implementation of the Hypervolume Estimation Algorithm for Multi-objective Optimization proposed in: * J. Bader and E. Zitzler. HypE: An Algorithm for Fast Hypervolume-Based Many-Objective @@ -160,10 +159,11 @@

    Source code for jmetal.algorithm.multiobjective.hype

    """ selection = BinaryTournamentSelection( - comparator=SolutionAttributeComparator(key='fitness', lowest_is_best=False)) - self.ranking_fitness = RankingAndFitnessSelection(population_size, - dominance_comparator=dominance_comparator, - reference_point=reference_point) + comparator=SolutionAttributeComparator(key="fitness", lowest_is_best=False) + ) + self.ranking_fitness = RankingAndFitnessSelection( + population_size, dominance_comparator=dominance_comparator, reference_point=reference_point + ) self.reference_point = reference_point self.dominance_comparator = dominance_comparator @@ -176,24 +176,38 @@

    Source code for jmetal.algorithm.multiobjective.hype

    selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, - population_generator=population_generator + population_generator=population_generator, ) -
    [docs] def evaluate(self, population: List[S]): +
    +[docs] + def evaluate(self, population: List[S]): population = self.population_evaluator.evaluate(population, self.problem) - population = self.ranking_fitness.compute_hypervol_fitness_values(population, self.reference_point, - len(population)) + population = self.ranking_fitness.compute_hypervol_fitness_values( + population, self.reference_point, len(population) + ) return population
    -
    [docs] def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: + +
    +[docs] + def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: join_population = population + offspring_population return self.ranking_fitness.execute(join_population)
    -
    [docs] def get_result(self) -> R: + +
    +[docs] + def result(self) -> R: return self.solutions
    -
    [docs] def get_name(self) -> str: - return 'HYPE'
    + +
    +[docs] + def get_name(self) -> str: + return "HYPE"
    +
    +
    @@ -210,8 +224,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.ibea — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,38 +106,41 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.ibea

    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     import numpy as np
     
     from jmetal.algorithm.singleobjective.genetic_algorithm import GeneticAlgorithm
     from jmetal.config import store
    -from jmetal.core.operator import Mutation, Crossover
    +from jmetal.core.operator import Crossover, Mutation
     from jmetal.core.problem import Problem
     from jmetal.core.quality_indicator import EpsilonIndicator
    -from jmetal.operator import BinaryTournamentSelection
    +from jmetal.operator.selection import BinaryTournamentSelection
     from jmetal.util.comparator import SolutionAttributeComparator
     from jmetal.util.evaluator import Evaluator
     from jmetal.util.generator import Generator
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    -R = TypeVar('R')
    -
    +S = TypeVar("S")
    +R = TypeVar("R")
     
    -
    [docs]class IBEA(GeneticAlgorithm[S, R]): - def __init__(self, - problem: Problem, - population_size: int, - offspring_population_size: int, - mutation: Mutation, - crossover: Crossover, - kappa: float, - termination_criterion: TerminationCriterion = store.default_termination_criteria, - population_generator: Generator = store.default_generator, - population_evaluator: Evaluator = store.default_evaluator): - """ Epsilon IBEA implementation as described in +
    +[docs] +class IBEA(GeneticAlgorithm[S, R]): + def __init__( + self, + problem: Problem, + population_size: int, + offspring_population_size: int, + mutation: Mutation, + crossover: Crossover, + kappa: float, + termination_criterion: TerminationCriterion = store.default_termination_criteria, + population_generator: Generator = store.default_generator, + population_evaluator: Evaluator = store.default_evaluator, + ): + """Epsilon IBEA implementation as described in * Zitzler, Eckart, and Simon Künzli. "Indicator-based selection in multiobjective search." In International Conference on Parallel Problem Solving from Nature, pp. 832-842. Springer, @@ -161,7 +161,8 @@

    Source code for jmetal.algorithm.multiobjective.ibea

    """ selection = BinaryTournamentSelection( - comparator=SolutionAttributeComparator(key='fitness', lowest_is_best=False)) + comparator=SolutionAttributeComparator(key="fitness", lowest_is_best=False) + ) self.kappa = kappa super(IBEA, self).__init__( @@ -173,48 +174,69 @@

    Source code for jmetal.algorithm.multiobjective.ibea

    selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, - population_generator=population_generator + population_generator=population_generator, ) -
    [docs] def compute_fitness_values(self, population: List[S], kappa: float) -> List[S]: +
    +[docs] + def compute_fitness_values(self, population: List[S], kappa: float) -> List[S]: for i in range(len(population)): - population[i].attributes['fitness'] = 0 + population[i].attributes["fitness"] = 0 for j in range(len(population)): if j != i: - population[i].attributes['fitness'] += -np.exp( - -EpsilonIndicator([population[i]]).compute([population[j]]) / self.kappa) + population[i].attributes["fitness"] += -np.exp( + -EpsilonIndicator([population[i].objectives]).compute([population[j].objectives]) / self.kappa + ) return population
    -
    [docs] def create_initial_solutions(self) -> List[S]: + +
    +[docs] + def create_initial_solutions(self) -> List[S]: population = [self.population_generator.new(self.problem) for _ in range(self.population_size)] population = self.compute_fitness_values(population, self.kappa) return population
    -
    [docs] def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: + +
    +[docs] + def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: join_population = population + offspring_population join_population_size = len(join_population) join_population = self.compute_fitness_values(join_population, self.kappa) while join_population_size > self.population_size: - current_fitnesses = [individual.attributes['fitness'] for individual in join_population] + current_fitnesses = [individual.attributes["fitness"] for individual in join_population] index_worst = current_fitnesses.index(min(current_fitnesses)) for i in range(join_population_size): - join_population[i].attributes['fitness'] += np.exp( - - EpsilonIndicator([join_population[i]]).compute([join_population[index_worst]]) / self.kappa) + join_population[i].attributes["fitness"] += np.exp( + -EpsilonIndicator([join_population[i].objectives]).compute( + [join_population[index_worst].objectives] + ) + / self.kappa + ) join_population.pop(index_worst) join_population_size = join_population_size - 1 return join_population
    -
    [docs] def get_result(self) -> R: + +
    +[docs] + def result(self) -> R: return self.solutions
    -
    [docs] def get_name(self) -> str: - return 'Epsilon-IBEA'
    + +
    +[docs] + def get_name(self) -> str: + return "Epsilon-IBEA"
    +
    +
    @@ -231,8 +253,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.mocell — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -111,24 +108,24 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.mocell

     import copy
     from functools import cmp_to_key
    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     from jmetal.algorithm.singleobjective.genetic_algorithm import GeneticAlgorithm
     from jmetal.config import store
    -from jmetal.core.operator import Mutation, Crossover, Selection
    +from jmetal.core.operator import Crossover, Mutation, Selection
     from jmetal.core.problem import Problem
    -from jmetal.operator import BinaryTournamentSelection
    +from jmetal.operator.selection import BinaryTournamentSelection
     from jmetal.util.archive import BoundedArchive
    +from jmetal.util.comparator import Comparator, MultiComparator
     from jmetal.util.density_estimator import CrowdingDistance, DensityEstimator
     from jmetal.util.evaluator import Evaluator
     from jmetal.util.generator import Generator
     from jmetal.util.neighborhood import Neighborhood
     from jmetal.util.ranking import FastNonDominatedRanking, Ranking
    -from jmetal.util.comparator import Comparator, MultiComparator
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    -R = TypeVar('R')
    +S = TypeVar("S")
    +R = TypeVar("R")
     
     """
     .. module:: MOCell
    @@ -138,23 +135,26 @@ 

    Source code for jmetal.algorithm.multiobjective.mocell

    """ -
    [docs]class MOCell(GeneticAlgorithm[S, R]): - - 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): - """ +
    +[docs] +class MOCell(GeneticAlgorithm[S, R]): + 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. @@ -172,7 +172,7 @@

    Source code for jmetal.algorithm.multiobjective.mocell

    selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, - population_generator=population_generator + population_generator=population_generator, ) self.dominance_comparator = dominance_comparator self.neighborhood = neighborhood @@ -180,19 +180,26 @@

    Source code for jmetal.algorithm.multiobjective.mocell

    self.current_individual = 0 self.current_neighbors = [] - self.comparator = MultiComparator([FastNonDominatedRanking.get_comparator(), - CrowdingDistance.get_comparator()]) + self.comparator = MultiComparator([FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator()]) -
    [docs] def init_progress(self) -> None: +
    +[docs] + def init_progress(self) -> None: super().init_progress() for solution in self.solutions: self.archive.add(copy.copy(solution))
    -
    [docs] def update_progress(self) -> None: + +
    +[docs] + def update_progress(self) -> None: super().update_progress() self.current_individual = (self.current_individual + 1) % self.population_size
    -
    [docs] def selection(self, population: List[S]): + +
    +[docs] + def selection(self, population: List[S]): parents = [] self.current_neighbors = self.neighborhood.get_neighbors(self.current_individual, population) @@ -206,23 +213,29 @@

    Source code for jmetal.algorithm.multiobjective.mocell

    return parents
    -
    [docs] def reproduction(self, mating_population: List[S]) -> List[S]: + +
    +[docs] + def reproduction(self, mating_population: List[S]) -> List[S]: number_of_parents_to_combine = self.crossover_operator.get_number_of_parents() if len(mating_population) % number_of_parents_to_combine != 0: - raise Exception('Wrong number of parents') + raise Exception("Wrong number of parents") offspring_population = self.crossover_operator.execute(mating_population) - self.mutation_operator.execute(offspring_population[0]) + offspring_population[0] = self.mutation_operator.execute(offspring_population[0]) return [offspring_population[0]]
    -
    [docs] def replacement(self, population: List[S], offspring_population: List[S]) -> List[List[S]]: + +
    +[docs] + 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]) + self.archive.add(copy.deepcopy(offspring_population[0])) elif result == 0: # the offspring and current individuals are non-dominated new_individual = offspring_population[0] @@ -238,17 +251,25 @@

    Source code for jmetal.algorithm.multiobjective.mocell

    self.current_neighbors.sort(key=cmp_to_key(self.comparator.compare)) worst_solution = self.current_neighbors[-1] - self.archive.add(new_individual) + self.archive.add(copy.deepcopy(new_individual)) if worst_solution != new_individual: population[self.current_individual] = new_individual return population
    -
    [docs] def get_result(self) -> R: + +
    +[docs] + def result(self) -> R: return self.archive.solution_list
    -
    [docs] def get_name(self) -> str: - return 'MOCell'
    + +
    +[docs] + def get_name(self) -> str: + return "MOCell"
    +
    +
    @@ -265,8 +286,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.moead — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -112,7 +109,7 @@

    Source code for jmetal.algorithm.multiobjective.moead

    import copy import random from math import ceil -from typing import TypeVar, List, Generator +from typing import Generator, List, TypeVar import numpy as np @@ -120,36 +117,46 @@

    Source code for jmetal.algorithm.multiobjective.moead

    from jmetal.config import store from jmetal.core.operator import Mutation from jmetal.core.problem import Problem -from jmetal.operator import DifferentialEvolutionCrossover, NaryRandomSolutionSelection -from jmetal.util.aggregative_function import AggregativeFunction -from jmetal.util.constraint_handling import feasibility_ratio, \ - overall_constraint_violation_degree, is_feasible +from jmetal.operator.crossover import DifferentialEvolutionCrossover +from jmetal.operator.selection import NaryRandomSolutionSelection +from jmetal.util.aggregation_function import AggregationFunction +from jmetal.util.constraint_handling import ( + feasibility_ratio, + is_feasible, + overall_constraint_violation_degree, +) from jmetal.util.density_estimator import CrowdingDistance from jmetal.util.evaluator import Evaluator from jmetal.util.neighborhood import WeightVectorNeighborhood from jmetal.util.ranking import FastNonDominatedRanking -from jmetal.util.termination_criterion import TerminationCriterion, StoppingByEvaluations +from jmetal.util.termination_criterion import ( + StoppingByEvaluations, + TerminationCriterion, +) -S = TypeVar('S') +S = TypeVar("S") R = List[S] -
    [docs]class MOEAD(GeneticAlgorithm): - - def __init__(self, - problem: Problem, - population_size: int, - mutation: Mutation, - crossover: DifferentialEvolutionCrossover, - aggregative_function: AggregativeFunction, - neighbourhood_selection_probability: float, - max_number_of_replaced_solutions: int, - neighbor_size: int, - weight_files_path: str, - termination_criterion: TerminationCriterion = store.default_termination_criteria, - population_generator: Generator = store.default_generator, - population_evaluator: Evaluator = store.default_evaluator): - """ +
    +[docs] +class MOEAD(GeneticAlgorithm): + def __init__( + self, + problem: Problem, + population_size: int, + mutation: Mutation, + crossover: DifferentialEvolutionCrossover, + aggregation_function: AggregationFunction, + neighbourhood_selection_probability: float, + max_number_of_replaced_solutions: int, + neighbor_size: int, + weight_files_path: str, + termination_criterion: TerminationCriterion = store.default_termination_criteria, + population_generator: Generator = store.default_generator, + population_evaluator: Evaluator = store.default_evaluator, + ): + """ :param max_number_of_replaced_solutions: (eta in Zhang & Li paper). :param neighbourhood_selection_probability: Probability of mating with a solution in the neighborhood rather than the entire population (Delta in Zhang & Li paper). @@ -163,36 +170,41 @@

    Source code for jmetal.algorithm.multiobjective.moead

    selection=NaryRandomSolutionSelection(2), population_evaluator=population_evaluator, population_generator=population_generator, - termination_criterion=termination_criterion + termination_criterion=termination_criterion, ) self.max_number_of_replaced_solutions = max_number_of_replaced_solutions - self.fitness_function = aggregative_function + self.fitness_function = aggregation_function self.neighbourhood = WeightVectorNeighborhood( number_of_weight_vectors=population_size, neighborhood_size=neighbor_size, - weight_vector_size=problem.number_of_objectives, - weights_path=weight_files_path + weight_vector_size=problem.number_of_objectives(), + weights_path=weight_files_path, ) self.neighbourhood_selection_probability = neighbourhood_selection_probability self.permutation = None self.current_subproblem = 0 self.neighbor_type = None -
    [docs] def init_progress(self) -> None: +
    +[docs] + def init_progress(self) -> None: self.evaluations = self.population_size for solution in self.solutions: self.fitness_function.update(solution.objectives) self.permutation = Permutation(self.population_size) - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data)
    -
    [docs] def selection(self, population: List[S]): + +
    +[docs] + def selection(self, population: List[S]): self.current_subproblem = self.permutation.get_next_value() self.neighbor_type = self.choose_neighbor_type() - if self.neighbor_type == 'NEIGHBOR': + if self.neighbor_type == "NEIGHBOR": neighbors = self.neighbourhood.get_neighbors(self.current_subproblem, population) mating_population = self.selection_operator.execute(neighbors) else: @@ -202,7 +214,10 @@

    Source code for jmetal.algorithm.multiobjective.moead

    return mating_population
    -
    [docs] def reproduction(self, mating_population: List[S]) -> List[S]: + +
    +[docs] + def reproduction(self, mating_population: List[S]) -> List[S]: self.crossover_operator.current_individual = self.solutions[self.current_subproblem] offspring_population = self.crossover_operator.execute(mating_population) @@ -210,7 +225,10 @@

    Source code for jmetal.algorithm.multiobjective.moead

    return offspring_population
    -
    [docs] def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: + +
    +[docs] + def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: new_solution = offspring_population[0] self.fitness_function.update(new_solution.objectives) @@ -219,7 +237,10 @@

    Source code for jmetal.algorithm.multiobjective.moead

    return new_population
    -
    [docs] def update_current_subproblem_neighborhood(self, new_solution, population): + +
    +[docs] + def update_current_subproblem_neighborhood(self, new_solution, population): permuted_neighbors_indexes = self.generate_permutation_of_neighbors(self.current_subproblem) replacements = 0 @@ -238,8 +259,11 @@

    Source code for jmetal.algorithm.multiobjective.moead

    return population
    -
    [docs] def generate_permutation_of_neighbors(self, subproblem_id): - if self.neighbor_type == 'NEIGHBOR': + +
    +[docs] + def generate_permutation_of_neighbors(self, subproblem_id): + if self.neighbor_type == "NEIGHBOR": neighbors = self.neighbourhood.get_neighborhood()[subproblem_id] permuted_array = copy.deepcopy(neighbors.tolist()) else: @@ -247,34 +271,64 @@

    Source code for jmetal.algorithm.multiobjective.moead

    return permuted_array
    -
    [docs] def choose_neighbor_type(self): + +
    +[docs] + def choose_neighbor_type(self): rnd = random.random() if rnd < self.neighbourhood_selection_probability: - neighbor_type = 'NEIGHBOR' + neighbor_type = "NEIGHBOR" else: - neighbor_type = 'POPULATION' + neighbor_type = "POPULATION" return neighbor_type
    -
    [docs] def get_name(self): - return 'MOEAD'
    -
    [docs] def get_result(self): - return self.solutions
    +
    +[docs] + def get_name(self): + return "MOEAD"
    + + +
    +[docs] + def result(self): + return self.solutions
    +
    + class MOEAD_DRA(MOEAD): - def __init__(self, problem, population_size, mutation, crossover, aggregative_function, - neighbourhood_selection_probability, max_number_of_replaced_solutions, neighbor_size, - weight_files_path, termination_criterion=store.default_termination_criteria, - population_generator=store.default_generator, population_evaluator=store.default_evaluator): - super(MOEAD_DRA, self).__init__(problem, population_size, mutation, crossover, aggregative_function, - neighbourhood_selection_probability, max_number_of_replaced_solutions, - neighbor_size, weight_files_path, - termination_criterion=termination_criterion, - population_generator=population_generator, - population_evaluator=population_evaluator) + def __init__( + self, + problem, + population_size, + mutation, + crossover, + aggregation_function, + neighbourhood_selection_probability, + max_number_of_replaced_solutions, + neighbor_size, + weight_files_path, + termination_criterion=store.default_termination_criteria, + population_generator=store.default_generator, + population_evaluator=store.default_evaluator, + ): + super(MOEAD_DRA, self).__init__( + problem, + population_size, + mutation, + crossover, + aggregation_function, + neighbourhood_selection_probability, + max_number_of_replaced_solutions, + neighbor_size, + weight_files_path, + termination_criterion=termination_criterion, + population_generator=population_generator, + population_evaluator=population_evaluator, + ) self.saved_values = [] self.utility = [1.0 for _ in range(population_size)] @@ -294,7 +348,7 @@

    Source code for jmetal.algorithm.multiobjective.moead

    self.order = self.__tour_selection(10) self.current_order_index = 0 - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data) def update_progress(self): @@ -316,7 +370,7 @@

    Source code for jmetal.algorithm.multiobjective.moead

    self.neighbor_type = self.choose_neighbor_type() - if self.neighbor_type == 'NEIGHBOR': + if self.neighbor_type == "NEIGHBOR": neighbors = self.neighbourhood.get_neighbors(self.current_subproblem, population) mating_population = self.selection_operator.execute(neighbors) else: @@ -327,7 +381,7 @@

    Source code for jmetal.algorithm.multiobjective.moead

    return mating_population def get_name(self): - return 'MOEAD-DRA' + return "MOEAD-DRA" def __utility_function(self): for i in range(len(self.solutions)): @@ -343,8 +397,8 @@

    Source code for jmetal.algorithm.multiobjective.moead

    self.saved_values[i] = copy.copy(self.solutions[i]) def __tour_selection(self, depth): - selected = [i for i in range(self.problem.number_of_objectives)] - candidate = [i for i in range(self.problem.number_of_objectives, self.population_size)] + selected = [i for i in range(self.problem.number_of_objectives())] + candidate = [i for i in range(self.problem.number_of_objectives(), self.population_size)] while len(selected) < int(self.population_size / 5.0): best_idd = int(random.random() * len(candidate)) @@ -362,20 +416,22 @@

    Source code for jmetal.algorithm.multiobjective.moead

    class MOEADIEpsilon(MOEAD): - def __init__(self, - problem: Problem, - population_size: int, - mutation: Mutation, - crossover: DifferentialEvolutionCrossover, - aggregative_function: AggregativeFunction, - neighbourhood_selection_probability: float, - max_number_of_replaced_solutions: int, - neighbor_size: int, - weight_files_path: str, - termination_criterion: TerminationCriterion = StoppingByEvaluations(300000), - population_generator: Generator = store.default_generator, - population_evaluator: Evaluator = store.default_evaluator): - """ + def __init__( + self, + problem: Problem, + population_size: int, + mutation: Mutation, + crossover: DifferentialEvolutionCrossover, + aggregation_function: AggregationFunction, + neighbourhood_selection_probability: float, + max_number_of_replaced_solutions: int, + neighbor_size: int, + weight_files_path: str, + termination_criterion: TerminationCriterion = StoppingByEvaluations(300000), + population_generator: Generator = store.default_generator, + population_evaluator: Evaluator = store.default_evaluator, + ): + """ :param max_number_of_replaced_solutions: (eta in Zhang & Li paper). :param neighbourhood_selection_probability: Probability of mating with a solution in the neighborhood rather than the entire population (Delta in Zhang & Li paper). @@ -385,14 +441,14 @@

    Source code for jmetal.algorithm.multiobjective.moead

    population_size=population_size, mutation=mutation, crossover=crossover, - aggregative_function=aggregative_function, + aggregation_function=aggregation_function, neighbourhood_selection_probability=neighbourhood_selection_probability, max_number_of_replaced_solutions=max_number_of_replaced_solutions, neighbor_size=neighbor_size, weight_files_path=weight_files_path, population_evaluator=population_evaluator, population_generator=population_generator, - termination_criterion=termination_criterion + termination_criterion=termination_criterion, ) self.constraints = [] self.epsilon_k = 0 @@ -409,8 +465,9 @@

    Source code for jmetal.algorithm.multiobjective.moead

    # for i in range(self.population_size): # self.constraints[i] = get_overall_constraint_violation_degree(self.permutation[i]) - self.constraints = [overall_constraint_violation_degree(self.solutions[i]) - for i in range(0, self.population_size)] + self.constraints = [ + overall_constraint_violation_degree(self.solutions[i]) for i in range(0, self.population_size) + ] sorted(self.constraints) self.epsilon_zero = abs(self.constraints[int(ceil(0.05 * self.population_size))]) @@ -489,20 +546,20 @@

    Source code for jmetal.algorithm.multiobjective.moead

    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 = 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): + def result(self): return self.archive class Permutation: - def __init__(self, length: int): self.counter = 0 self.length = length @@ -536,8 +593,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.nsgaii — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,29 +107,32 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.nsgaii

     import time
    -from typing import TypeVar, List, Generator
    +from typing import Generator, List, TypeVar
     
     try:
         import dask
    -    from distributed import as_completed, Client
    +    from distributed import Client, as_completed
     except ImportError:
         pass
     
     from jmetal.algorithm.singleobjective.genetic_algorithm import GeneticAlgorithm
     from jmetal.config import store
    -from jmetal.core.algorithm import DynamicAlgorithm, Algorithm
    -from jmetal.core.operator import Mutation, Crossover, Selection
    -from jmetal.core.problem import Problem, DynamicProblem
    -from jmetal.operator import BinaryTournamentSelection
    +from jmetal.core.algorithm import Algorithm, DynamicAlgorithm
    +from jmetal.core.operator import Crossover, Mutation, Selection
    +from jmetal.core.problem import DynamicProblem, Problem
    +from jmetal.operator.selection import BinaryTournamentSelection
    +from jmetal.util.comparator import Comparator, DominanceComparator, MultiComparator
     from jmetal.util.density_estimator import CrowdingDistance
     from jmetal.util.evaluator import Evaluator
     from jmetal.util.ranking import FastNonDominatedRanking
    -from jmetal.util.replacement import RankingAndDensityEstimatorReplacement, RemovalPolicyType
    -from jmetal.util.comparator import DominanceComparator, Comparator, MultiComparator
    +from jmetal.util.replacement import (
    +    RankingAndDensityEstimatorReplacement,
    +    RemovalPolicyType,
    +)
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    -R = TypeVar('R')
    +S = TypeVar("S")
    +R = TypeVar("R")
     
     """
     .. module:: NSGA-II
    @@ -143,22 +143,25 @@ 

    Source code for jmetal.algorithm.multiobjective.nsgaii

    """ -
    [docs]class NSGAII(GeneticAlgorithm[S, R]): - - 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): - """ +
    +[docs] +class NSGAII(GeneticAlgorithm[S, R]): + 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, + ): + """ NSGA-II implementation as described in * K. Deb, A. Pratap, S. Agarwal and T. Meyarivan, "A fast and elitist @@ -175,7 +178,6 @@

    Source code for jmetal.algorithm.multiobjective.nsgaii

    :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, @@ -186,12 +188,14 @@

    Source code for jmetal.algorithm.multiobjective.nsgaii

    selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, - population_generator=population_generator + population_generator=population_generator, ) self.dominance_comparator = dominance_comparator -
    [docs] 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 +
    +[docs] + 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. @@ -206,28 +210,39 @@

    Source code for jmetal.algorithm.multiobjective.nsgaii

    return solutions
    -
    [docs] def get_result(self) -> R: + +
    +[docs] + def result(self) -> R: return self.solutions
    -
    [docs] def get_name(self) -> str: - return 'NSGAII'
    - - -
    [docs]class DynamicNSGAII(NSGAII[S, R], DynamicAlgorithm): - - 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()): + +
    +[docs] + def get_name(self) -> str: + return "NSGAII"
    +
    + + + +
    +[docs] +class DynamicNSGAII(NSGAII[S, R], DynamicAlgorithm): + 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, @@ -238,50 +253,64 @@

    Source code for jmetal.algorithm.multiobjective.nsgaii

    population_evaluator=population_evaluator, population_generator=population_generator, termination_criterion=termination_criterion, - dominance_comparator=dominance_comparator) + dominance_comparator=dominance_comparator, + ) self.completed_iterations = 0 self.start_computing_time = 0 self.total_computing_time = 0 -
    [docs] def restart(self): +
    +[docs] + def restart(self): self.solutions = self.evaluate(self.solutions)
    -
    [docs] def update_progress(self): + +
    +[docs] + def update_progress(self): if self.problem.the_problem_has_changed(): self.restart() self.problem.clear_changed() - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data) self.evaluations += self.offspring_population_size
    -
    [docs] def stopping_condition_is_met(self): + +
    +[docs] + def stopping_condition_is_met(self): if self.termination_criterion.is_met: - observable_data = self.get_observable_data() - observable_data['TERMINATION_CRITERIA_IS_MET'] = True + observable_data = self.observable_data() + observable_data["TERMINATION_CRITERIA_IS_MET"] = True self.observable.notify_all(**observable_data) self.restart() self.init_progress() - self.completed_iterations += 1
    + self.completed_iterations += 1
    +
    -
    [docs]class DistributedNSGAII(Algorithm[S, R]): - 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()): +
    +[docs] +class DistributedNSGAII(Algorithm[S, R]): + 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 @@ -296,38 +325,63 @@

    Source code for jmetal.algorithm.multiobjective.nsgaii

    self.number_of_cores = number_of_cores self.client = client -
    [docs] def create_initial_solutions(self) -> List[S]: +
    +[docs] + def create_initial_solutions(self) -> List[S]: return [self.problem.create_solution() for _ in range(self.number_of_cores)]
    -
    [docs] def evaluate(self, solutions: List[S]) -> List[S]: + +
    +[docs] + def evaluate(self, solutions: List[S]) -> List[S]: return self.client.map(self.problem.evaluate, solutions)
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def get_observable_data(self) -> dict: + +
    +[docs] + def observable_data(self) -> dict: ctime = time.time() - self.start_computing_time - return {'PROBLEM': self.problem, - 'EVALUATIONS': self.evaluations, - 'SOLUTIONS': self.get_result(), - 'COMPUTING_TIME': ctime}
    + return { + "PROBLEM": self.problem, + "EVALUATIONS": self.evaluations, + "SOLUTIONS": self.result(), + "COMPUTING_TIME": ctime, + }
    -
    [docs] def init_progress(self) -> None: + +
    +[docs] + def init_progress(self) -> None: self.evaluations = self.number_of_cores - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data)
    -
    [docs] def step(self) -> None: + +
    +[docs] + def step(self) -> None: pass
    -
    [docs] def update_progress(self): - observable_data = self.get_observable_data() + +
    +[docs] + def update_progress(self): + observable_data = self.observable_data() self.observable.notify_all(**observable_data)
    -
    [docs] def run(self): - """ Execute the algorithm. """ + +
    +[docs] + def run(self): + """Execute the algorithm.""" self.start_computing_time = time.time() create_solution = dask.delayed(self.problem.create_solution) @@ -384,8 +438,9 @@

    Source code for jmetal.algorithm.multiobjective.nsgaii

    mating_population.append(solution) # Reproduction and evaluation - new_task = self.client.submit(reproduction, mating_population, self.problem, - self.crossover_operator, self.mutation_operator) + new_task = self.client.submit( + reproduction, mating_population, self.problem, self.crossover_operator, self.mutation_operator + ) task_pool.add(new_task) # update progress @@ -403,11 +458,19 @@

    Source code for jmetal.algorithm.multiobjective.nsgaii

    for future, _ in task_pool: future.cancel()
    -
    [docs] def get_result(self) -> R: + +
    +[docs] + def result(self) -> R: return self.solutions
    -
    [docs] def get_name(self) -> str: - return 'dNSGA-II'
    + +
    +[docs] + def get_name(self) -> str: + return "dNSGA-II"
    +
    + def reproduction(mating_population: List[S], problem, crossover_operator, mutation_operator) -> S: @@ -438,8 +501,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - - + jmetal.algorithm.multiobjective.nsgaiii — jMetalPy 1.7.0 documentation + + + + + + + @@ -40,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -52,7 +48,7 @@

    Navigation

    @@ -74,8 +70,6 @@

    Table Of Contents

  • Single-objective algorithms
  • Operators
  • Problems
  • -
  • Contributing
  • -
  • About
  • @@ -112,27 +106,27 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    -from abc import abstractmethod, ABC
    -from typing import TypeVar, List
    +from abc import ABC, abstractmethod
    +from typing import List, TypeVar
     
     import numpy as np
    -from numpy.linalg import LinAlgError
    -from scipy import special
    -
    -from jmetal.algorithm.multiobjective.nsgaii import NSGAII
    -from jmetal.config import store
    -from jmetal.core.operator import Mutation, Crossover, Selection
    -from jmetal.core.problem import Problem
    -from jmetal.operator import BinaryTournamentSelection
    -from jmetal.util.comparator import Comparator, MultiComparator
    -from jmetal.util.density_estimator import CrowdingDistance
    -from jmetal.util.evaluator import Evaluator
    -from jmetal.util.generator import Generator
    -from jmetal.util.ranking import FastNonDominatedRanking
    -from jmetal.util.termination_criterion import TerminationCriterion
    -
    -S = TypeVar('S')
    -R = TypeVar('R')
    +from numpy.linalg import LinAlgError
    +from scipy import special
    +
    +from jmetal.algorithm.multiobjective.nsgaii import NSGAII
    +from jmetal.config import store
    +from jmetal.core.operator import Crossover, Mutation, Selection
    +from jmetal.core.problem import Problem
    +from jmetal.operator.selection import BinaryTournamentSelection
    +from jmetal.util.comparator import Comparator, MultiComparator
    +from jmetal.util.density_estimator import CrowdingDistance
    +from jmetal.util.evaluator import Evaluator
    +from jmetal.util.generator import Generator
    +from jmetal.util.ranking import FastNonDominatedRanking
    +from jmetal.util.termination_criterion import TerminationCriterion
    +
    +S = TypeVar("S")
    +R = TypeVar("R")
     
     """
     .. module:: NSGA-III
    @@ -144,8 +138,7 @@ 

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    class ReferenceDirectionFactory(ABC): - - def __init__(self, n_dim: int, scaling=None) -> None: + def __init__(self, n_dim: int, scaling=None) -> None: self.n_dim = n_dim self.scaling = scaling @@ -164,8 +157,7 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    class UniformReferenceDirectionFactory(ReferenceDirectionFactory): - - def __init__(self, n_dim: int, scaling=None, n_points: int = None, n_partitions: int = None) -> None: + def __init__(self, n_dim: int, scaling=None, n_points: int = None, n_partitions: int = None) -> None: super().__init__(n_dim, scaling) if n_points is not None: self.n_partitions = self.get_partition_closest_to_points(n_points, n_dim) @@ -191,8 +183,7 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    else: for i in range(beta + 1): ref_dir[depth] = 1.0 * i / (1.0 * n_partitions) - self.__uniform_reference_directions(ref_dirs, np.copy(ref_dir), n_partitions, beta - i, - depth + 1) + self.__uniform_reference_directions(ref_dirs, np.copy(ref_dir), n_partitions, beta - i, depth + 1) @staticmethod def get_partition_closest_to_points(n_points, n_dim): @@ -214,7 +205,7 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    def get_extreme_points(F, n_objs, ideal_point, extreme_points=None): - """ Calculate the Achievement Scalarization Function which is used for the extreme point decomposition. """ + """Calculate the Achievement Scalarization Function which is used for the extreme point decomposition.""" asf = np.eye(n_objs) asf[asf == 0] = 1e6 @@ -236,7 +227,7 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    def get_nadir_point(extreme_points, ideal_point, worst_point, worst_of_front, worst_of_population): - """ Calculate the axis intersects for a set of individuals and its extremes (construct hyperplane). """ + """Calculate the axis intersects for a set of individuals and its extremes (construct hyperplane).""" try: # find the intercepts using gaussian elimination M = extreme_points - ideal_point @@ -295,7 +286,7 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    # add the selected individual to the survivors mask[next_ind] = False - pop[next_ind].attributes['is_closest'] = is_closest + pop[next_ind].attributes["is_closest"] = is_closest survivors.append(int(next_ind)) # increase the corresponding niche count @@ -305,7 +296,7 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    def associate_to_niches(F, niches, ideal_point, nadir_point, utopian_epsilon: float = 0.0): - """ Associate each solution to a reference point. """ + """Associate each solution to a reference point.""" utopian_point = ideal_point - utopian_epsilon denom = nadir_point - utopian_point @@ -343,27 +334,30 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    return niche_count -
    [docs]class NSGAIII(NSGAII): - - 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): +
    +[docs] +class NSGAIII(NSGAII): + 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') + 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, @@ -375,15 +369,17 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    termination_criterion=termination_criterion, population_evaluator=population_evaluator, population_generator=population_generator, - dominance_comparator=dominance_comparator + 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) + self.ideal_point = np.full(self.problem.number_of_objectives(), np.inf) + self.worst_point = np.full(self.problem.number_of_objectives(), -np.inf) -
    [docs] def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: - """ Implements NSGA-III environmental selection based on reference points as described in: +
    +[docs] + def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: + """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, @@ -404,20 +400,24 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    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) + 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) + 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) @@ -432,10 +432,9 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    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) + 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: @@ -447,30 +446,41 @@

    Source code for jmetal.algorithm.multiobjective.nsgaiii

    # 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]) + 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]) + 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)
    -
    [docs] def get_result(self): - """ Return only non dominated solutions.""" + +
    +[docs] + def 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)
    -
    [docs] def get_name(self) -> str: - return 'NSGAIII'
    + +
    +[docs] + def get_name(self) -> str: + return "NSGAIII"
    +
    +
    @@ -487,8 +497,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.omopso — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -111,8 +108,7 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.omopso

     import random
     from copy import copy
    -from math import sqrt
    -from typing import TypeVar, List, Optional
    +from typing import List, Optional, TypeVar
     
     import numpy
     
    @@ -120,7 +116,7 @@ 

    Source code for jmetal.algorithm.multiobjective.omopso

    from jmetal.core.algorithm import ParticleSwarmOptimization from jmetal.core.problem import FloatProblem from jmetal.core.solution import FloatSolution -from jmetal.operator import UniformMutation +from jmetal.operator.mutation import UniformMutation from jmetal.operator.mutation import NonUniformMutation from jmetal.util.archive import BoundedArchive, NonDominatedSolutionsArchive from jmetal.util.comparator import DominanceComparator, EpsilonDominanceComparator @@ -128,7 +124,7 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    from jmetal.util.generator import Generator from jmetal.util.termination_criterion import TerminationCriterion -R = TypeVar('R') +R = TypeVar("R") """ .. module:: OMOPSO @@ -139,19 +135,22 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    """ -
    [docs]class OMOPSO(ParticleSwarmOptimization): - - def __init__(self, - problem: FloatProblem, - swarm_size: int, - uniform_mutation: UniformMutation, - non_uniform_mutation: NonUniformMutation, - leaders: Optional[BoundedArchive], - epsilon: float, - termination_criterion: TerminationCriterion, - swarm_generator: Generator = store.default_generator, - swarm_evaluator: Evaluator = store.default_evaluator): - """ This class implements the OMOPSO algorithm as described in +
    +[docs] +class OMOPSO(ParticleSwarmOptimization): + def __init__( + self, + problem: FloatProblem, + swarm_size: int, + uniform_mutation: UniformMutation, + non_uniform_mutation: NonUniformMutation, + leaders: Optional[BoundedArchive], + epsilon: float, + termination_criterion: TerminationCriterion, + swarm_generator: Generator = store.default_generator, + swarm_evaluator: Evaluator = store.default_evaluator, + ): + """This class implements the OMOPSO algorithm as described in todo Update this reference * SMPSO: A new PSO-based metaheuristic for multi-objective optimization @@ -163,9 +162,7 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    :param swarm_size: Size of the swarm. :param leaders: Archive for leaders. """ - super(OMOPSO, self).__init__( - problem=problem, - swarm_size=swarm_size) + super(OMOPSO, self).__init__(problem=problem, swarm_size=swarm_size) self.swarm_generator = swarm_generator self.swarm_evaluator = swarm_evaluator @@ -195,34 +192,54 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    self.dominance_comparator = DominanceComparator() - self.speed = numpy.zeros((self.swarm_size, self.problem.number_of_variables), dtype=float) + self.speed = numpy.zeros((self.swarm_size, self.problem.number_of_variables()), dtype=float) -
    [docs] def create_initial_solutions(self) -> List[FloatSolution]: +
    +[docs] + def create_initial_solutions(self) -> List[FloatSolution]: return [self.swarm_generator.new(self.problem) for _ in range(self.swarm_size)]
    -
    [docs] def evaluate(self, solution_list: List[FloatSolution]): + +
    +[docs] + def evaluate(self, solution_list: List[FloatSolution]): return self.swarm_evaluator.evaluate(solution_list, self.problem)
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def initialize_global_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def initialize_global_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: if self.leaders.add(particle): self.epsilon_archive.add(copy(particle))
    -
    [docs] def initialize_particle_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def initialize_particle_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: - particle.attributes['local_best'] = copy(particle)
    + particle.attributes["local_best"] = copy(particle)
    -
    [docs] def initialize_velocity(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def initialize_velocity(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): - for j in range(self.problem.number_of_variables): + for j in range(self.problem.number_of_variables()): self.speed[i][j] = 0.0
    -
    [docs] def update_velocity(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def update_velocity(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): - best_particle = copy(swarm[i].attributes['local_best']) + best_particle = copy(swarm[i].attributes["local_best"]) best_global = self.select_global_best() r1 = round(random.uniform(self.r1_min, self.r1_max), 1) @@ -232,11 +249,16 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    w = round(random.uniform(self.weight_min, self.weight_max), 1) for var in range(swarm[i].number_of_variables): - self.speed[i][var] = w * self.speed[i][var] \ - + (c1 * r1 * (best_particle.variables[var] - swarm[i].variables[var])) \ - + (c2 * r2 * (best_global.variables[var] - swarm[i].variables[var]))
    + self.speed[i][var] = ( + w * self.speed[i][var] + + (c1 * r1 * (best_particle.variables[var] - swarm[i].variables[var])) + + (c2 * r2 * (best_global.variables[var] - swarm[i].variables[var])) + )
    + -
    [docs] def update_position(self, swarm: List[FloatSolution]) -> None: +
    +[docs] + def update_position(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): particle = swarm[i] @@ -251,20 +273,27 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    particle.variables[j] = self.problem.upper_bound[j] self.speed[i][j] *= self.change_velocity2
    -
    [docs] def update_global_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def update_global_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: if self.leaders.add(copy(particle)): self.epsilon_archive.add(copy(particle))
    -
    [docs] def update_particle_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def update_particle_best(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): - flag = self.dominance_comparator.compare( - swarm[i], - swarm[i].attributes['local_best']) + flag = self.dominance_comparator.compare(swarm[i], swarm[i].attributes["local_best"]) if flag != 1: - swarm[i].attributes['local_best'] = copy(swarm[i])
    + swarm[i].attributes["local_best"] = copy(swarm[i])
    + -
    [docs] def perturbation(self, swarm: List[FloatSolution]) -> None: +
    +[docs] + def perturbation(self, swarm: List[FloatSolution]) -> None: self.non_uniform_mutation.set_current_iteration(self.evaluations / self.swarm_size) for i in range(self.swarm_size): if (i % 3) == 0: @@ -272,7 +301,10 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    else: self.uniform_mutation.execute(swarm[i])
    -
    [docs] def select_global_best(self) -> FloatSolution: + +
    +[docs] + def select_global_best(self) -> FloatSolution: leaders = self.leaders.solution_list if len(leaders) > 2: @@ -287,28 +319,10 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    return best_global
    - def __velocity_constriction(self, value: float, delta_max: [], delta_min: [], variable_index: int) -> float: - result = value - if value > delta_max[variable_index]: - result = delta_max[variable_index] - if value < delta_min[variable_index]: - result = delta_min[variable_index] - - return result - - def __inertia_weight(self, wmax: float): - return wmax - - def __constriction_coefficient(self, c1: float, c2: float) -> float: - rho = c1 + c2 - if rho <= 4: - result = 1.0 - else: - result = 2.0 / (2.0 - rho - sqrt(pow(rho, 2.0) - 4.0 * rho)) - - return result -
    [docs] def init_progress(self) -> None: +
    +[docs] + def init_progress(self) -> None: self.evaluations = self.swarm_size self.leaders.compute_density_estimator() @@ -316,19 +330,30 @@

    Source code for jmetal.algorithm.multiobjective.omopso

    self.initialize_particle_best(self.solutions) self.initialize_global_best(self.solutions)
    -
    [docs] def update_progress(self) -> None: + +
    +[docs] + def update_progress(self) -> None: self.evaluations += self.swarm_size self.leaders.compute_density_estimator() - observable_data = self.get_observable_data() - observable_data['SOLUTIONS'] = self.epsilon_archive.solution_list + observable_data = self.observable_data() + observable_data["SOLUTIONS"] = self.epsilon_archive.solution_list self.observable.notify_all(**observable_data)
    -
    [docs] def get_result(self) -> List[FloatSolution]: + +
    +[docs] + def result(self) -> List[FloatSolution]: return self.epsilon_archive.solution_list
    -
    [docs] def get_name(self) -> str: - return 'OMOPSO'
    + +
    +[docs] + def get_name(self) -> str: + return "OMOPSO"
    +
    +
    @@ -345,8 +370,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.smpso — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -113,22 +110,22 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    import threading from copy import copy from math import sqrt -from typing import TypeVar, List, Optional +from typing import List, Optional, TypeVar import numpy from jmetal.config import store -from jmetal.core.algorithm import ParticleSwarmOptimization, DynamicAlgorithm +from jmetal.core.algorithm import DynamicAlgorithm, ParticleSwarmOptimization from jmetal.core.operator import Mutation -from jmetal.core.problem import FloatProblem, DynamicProblem +from jmetal.core.problem import DynamicProblem, FloatProblem from jmetal.core.solution import FloatSolution -from jmetal.util.archive import BoundedArchive, ArchiveWithReferencePoint -from jmetal.util.comparator import DominanceComparator +from jmetal.util.archive import ArchiveWithReferencePoint, BoundedArchive +from jmetal.util.comparator import DominanceComparator, Comparator from jmetal.util.evaluator import Evaluator from jmetal.util.generator import Generator from jmetal.util.termination_criterion import TerminationCriterion -R = TypeVar('R') +R = TypeVar("R") """ .. module:: SMPSO @@ -139,17 +136,21 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    """ -
    [docs]class SMPSO(ParticleSwarmOptimization): - - def __init__(self, - problem: FloatProblem, - swarm_size: int, - mutation: Mutation, - leaders: Optional[BoundedArchive], - termination_criterion: TerminationCriterion = store.default_termination_criteria, - swarm_generator: Generator = store.default_generator, - swarm_evaluator: Evaluator = store.default_evaluator): - """ This class implements the SMPSO algorithm as described in +
    +[docs] +class SMPSO(ParticleSwarmOptimization): + def __init__( + self, + problem: FloatProblem, + swarm_size: int, + mutation: Mutation, + leaders: Optional[BoundedArchive], + dominance_comparator: Comparator = DominanceComparator(), + termination_criterion: TerminationCriterion = store.default_termination_criteria, + swarm_generator: Generator = store.default_generator, + swarm_evaluator: Evaluator = store.default_evaluator, + ): + """This class implements the SMPSO algorithm as described in * SMPSO: A new PSO-based metaheuristic for multi-objective optimization * MCDM 2009. DOI: `<http://dx.doi.org/10.1109/MCDM.2009.4938830/>`_. @@ -163,9 +164,7 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    :param mutation: Mutation operator (see :py:mod:`jmetal.operator.mutation`). :param leaders: Archive for leaders. """ - super(SMPSO, self).__init__( - problem=problem, - swarm_size=swarm_size) + super(SMPSO, self).__init__(problem=problem, swarm_size=swarm_size) self.swarm_generator = swarm_generator self.swarm_evaluator = swarm_evaluator self.termination_criterion = termination_criterion @@ -186,38 +185,60 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    self.change_velocity1 = -1 self.change_velocity2 = -1 - self.dominance_comparator = DominanceComparator() + self.dominance_comparator = dominance_comparator - self.speed = numpy.zeros((self.swarm_size, self.problem.number_of_variables), dtype=float) - self.delta_max, self.delta_min = numpy.empty(problem.number_of_variables), \ - numpy.empty(problem.number_of_variables) + self.speed = numpy.zeros((self.swarm_size, self.problem.number_of_variables()), dtype=float) + self.delta_max, self.delta_min = ( + numpy.empty(problem.number_of_variables()), + numpy.empty(problem.number_of_variables()), + ) -
    [docs] def create_initial_solutions(self) -> List[FloatSolution]: +
    +[docs] + def create_initial_solutions(self) -> List[FloatSolution]: return [self.swarm_generator.new(self.problem) for _ in range(self.swarm_size)]
    -
    [docs] def evaluate(self, solution_list: List[FloatSolution]): + +
    +[docs] + def evaluate(self, solution_list: List[FloatSolution]): return self.swarm_evaluator.evaluate(solution_list, self.problem)
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def initialize_global_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def initialize_global_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: self.leaders.add(copy(particle))
    -
    [docs] def initialize_particle_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def initialize_particle_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: - particle.attributes['local_best'] = copy(particle)
    + particle.attributes["local_best"] = copy(particle)
    -
    [docs] def initialize_velocity(self, swarm: List[FloatSolution]) -> None: - for i in range(self.problem.number_of_variables): + +
    +[docs] + def initialize_velocity(self, swarm: List[FloatSolution]) -> None: + for i in range(self.problem.number_of_variables()): self.delta_max[i] = (self.problem.upper_bound[i] - self.problem.lower_bound[i]) / 2.0 self.delta_min = -1.0 * self.delta_max
    -
    [docs] def update_velocity(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def update_velocity(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): - best_particle = copy(swarm[i].attributes['local_best']) + best_particle = copy(swarm[i].attributes["local_best"]) best_global = self.select_global_best() r1 = round(random.uniform(self.r1_min, self.r1_max), 1) @@ -227,22 +248,27 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    wmax = self.max_weight wmin = self.min_weight - for var in range(swarm[i].number_of_variables): - self.speed[i][var] = \ - self.__velocity_constriction( - self.__constriction_coefficient(c1, c2) * - ((self.__inertia_weight(wmax) - * self.speed[i][var]) - + (c1 * r1 * (best_particle.variables[var] - swarm[i].variables[var])) - + (c2 * r2 * (best_global.variables[var] - swarm[i].variables[var])) - ), - self.delta_max, self.delta_min, var)
    - -
    [docs] def update_position(self, swarm: List[FloatSolution]) -> None: + for var in range(len(swarm[i].variables)): + self.speed[i][var] = self.__velocity_constriction( + self.__constriction_coefficient(c1, c2) + * ( + (self.__inertia_weight(wmax) * self.speed[i][var]) + + (c1 * r1 * (best_particle.variables[var] - swarm[i].variables[var])) + + (c2 * r2 * (best_global.variables[var] - swarm[i].variables[var])) + ), + self.delta_max, + self.delta_min, + var, + )
    + + +
    +[docs] + def update_position(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): particle = swarm[i] - for j in range(particle.number_of_variables): + for j in range(len(particle.variables)): particle.variables[j] += self.speed[i][j] if particle.variables[j] < self.problem.lower_bound[j]: @@ -253,24 +279,34 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    particle.variables[j] = self.problem.upper_bound[j] self.speed[i][j] *= self.change_velocity2
    -
    [docs] def update_global_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def update_global_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: self.leaders.add(copy(particle))
    -
    [docs] def update_particle_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def update_particle_best(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): - flag = self.dominance_comparator.compare( - swarm[i], - swarm[i].attributes['local_best']) + flag = self.dominance_comparator.compare(swarm[i], swarm[i].attributes["local_best"]) if flag != 1: - swarm[i].attributes['local_best'] = copy(swarm[i])
    + swarm[i].attributes["local_best"] = copy(swarm[i])
    -
    [docs] def perturbation(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def perturbation(self, swarm: List[FloatSolution]) -> None: for i in range(self.swarm_size): if (i % 6) == 0: self.mutation_operator.execute(swarm[i])
    -
    [docs] def select_global_best(self) -> FloatSolution: + +
    +[docs] + def select_global_best(self) -> FloatSolution: leaders = self.leaders.solution_list if len(leaders) > 2: @@ -285,6 +321,7 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    return best_global
    + def __velocity_constriction(self, value: float, delta_max: [], delta_min: [], variable_index: int) -> float: result = value if value > delta_max[variable_index]: @@ -306,7 +343,9 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    return result -
    [docs] def init_progress(self) -> None: +
    +[docs] + def init_progress(self) -> None: self.evaluations = self.swarm_size self.leaders.compute_density_estimator() @@ -314,31 +353,45 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    self.initialize_particle_best(self.solutions) self.initialize_global_best(self.solutions)
    -
    [docs] def update_progress(self) -> None: + +
    +[docs] + def update_progress(self) -> None: self.evaluations += self.swarm_size self.leaders.compute_density_estimator() - observable_data = self.get_observable_data() - observable_data['SOLUTIONS'] = self.leaders.solution_list + observable_data = self.observable_data() + observable_data["SOLUTIONS"] = self.leaders.solution_list self.observable.notify_all(**observable_data)
    -
    [docs] def get_result(self) -> List[FloatSolution]: + +
    +[docs] + def result(self) -> List[FloatSolution]: return self.leaders.solution_list
    -
    [docs] def get_name(self) -> str: - return 'SMPSO'
    +
    +[docs] + def get_name(self) -> str: + return "SMPSO"
    +
    -
    [docs]class DynamicSMPSO(SMPSO, DynamicAlgorithm): - def __init__(self, - problem: DynamicProblem[FloatSolution], - swarm_size: int, - mutation: Mutation, - leaders: BoundedArchive, - termination_criterion: TerminationCriterion = store.default_termination_criteria, - swarm_generator: Generator = store.default_generator, - swarm_evaluator: Evaluator = store.default_evaluator): + +
    +[docs] +class DynamicSMPSO(SMPSO, DynamicAlgorithm): + def __init__( + self, + problem: DynamicProblem[FloatSolution], + swarm_size: int, + mutation: Mutation, + leaders: BoundedArchive, + termination_criterion: TerminationCriterion = store.default_termination_criteria, + swarm_generator: Generator = store.default_generator, + swarm_evaluator: Evaluator = store.default_evaluator, + ): super(DynamicSMPSO, self).__init__( problem=problem, swarm_size=swarm_size, @@ -346,10 +399,13 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    leaders=leaders, termination_criterion=termination_criterion, swarm_generator=swarm_generator, - swarm_evaluator=swarm_evaluator) + swarm_evaluator=swarm_evaluator, + ) self.completed_iterations = 0 -
    [docs] def restart(self) -> None: +
    +[docs] + def restart(self) -> None: self.solutions = self.create_initial_solutions() self.solutions = self.evaluate(self.solutions) @@ -361,40 +417,51 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    self.init_progress()
    -
    [docs] def update_progress(self): + +
    +[docs] + def update_progress(self): if self.problem.the_problem_has_changed(): self.restart() self.problem.clear_changed() - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data) self.evaluations += self.swarm_size self.leaders.compute_density_estimator()
    -
    [docs] def stopping_condition_is_met(self): + +
    +[docs] + def stopping_condition_is_met(self): if self.termination_criterion.is_met: - observable_data = self.get_observable_data() - observable_data['termination_criterion_is_met'] = True + observable_data = self.observable_data() + observable_data["termination_criterion_is_met"] = True self.observable.notify_all(**observable_data) self.restart() self.init_progress() - self.completed_iterations += 1
    + self.completed_iterations += 1
    +
    -
    [docs]class SMPSORP(SMPSO): - def __init__(self, - problem: FloatProblem, - swarm_size: int, - mutation: Mutation, - reference_points: List[List[float]], - leaders: List[ArchiveWithReferencePoint], - termination_criterion: TerminationCriterion, - swarm_generator: Generator = store.default_generator, - swarm_evaluator: Evaluator = store.default_evaluator): - """ This class implements the SMPSORP algorithm. +
    +[docs] +class SMPSORP(SMPSO): + def __init__( + self, + problem: FloatProblem, + swarm_size: int, + mutation: Mutation, + reference_points: List[List[float]], + leaders: List[ArchiveWithReferencePoint], + termination_criterion: TerminationCriterion, + swarm_generator: Generator = store.default_generator, + swarm_evaluator: Evaluator = store.default_evaluator, + ): + """This class implements the SMPSORP algorithm. :param problem: The problem to solve. :param swarm_size: @@ -409,7 +476,8 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    leaders=None, swarm_generator=swarm_generator, swarm_evaluator=swarm_evaluator, - termination_criterion=termination_criterion) + termination_criterion=termination_criterion, + ) self.leaders = leaders self.reference_points = reference_points self.lock = threading.Lock() @@ -417,17 +485,25 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    thread = threading.Thread(target=_change_reference_point, args=(self,)) thread.start() -
    [docs] def initialize_global_best(self, swarm: List[FloatSolution]) -> None: +
    +[docs] + def initialize_global_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: for leader in self.leaders: leader.add(copy(particle))
    -
    [docs] def update_global_best(self, swarm: List[FloatSolution]) -> None: + +
    +[docs] + def update_global_best(self, swarm: List[FloatSolution]) -> None: for particle in swarm: for leader in self.leaders: leader.add(copy(particle))
    -
    [docs] def select_global_best(self) -> FloatSolution: + +
    +[docs] + def select_global_best(self) -> FloatSolution: selected = False selected_swarm_index = 0 @@ -450,7 +526,10 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    return best_global
    -
    [docs] def init_progress(self) -> None: + +
    +[docs] + def init_progress(self) -> None: self.evaluations = self.swarm_size for leader in self.leaders: @@ -460,29 +539,41 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    self.initialize_particle_best(self.solutions) self.initialize_global_best(self.solutions)
    -
    [docs] def update_progress(self) -> None: + +
    +[docs] + def update_progress(self) -> None: self.evaluations += self.swarm_size for leader in self.leaders: leader.filter() leader.compute_density_estimator() - observable_data = self.get_observable_data() - observable_data['REFERENCE_POINT'] = self.get_reference_point() + observable_data = self.observable_data() + observable_data["REFERENCE_POINT"] = self.get_reference_point() self.observable.notify_all(**observable_data)
    -
    [docs] def update_reference_point(self, new_reference_points: list): + +
    +[docs] + def update_reference_point(self, new_reference_points: list): with self.lock: self.reference_points = new_reference_points for index, archive in enumerate(self.leaders): archive.update_reference_point(new_reference_points[index])
    -
    [docs] def get_reference_point(self): + +
    +[docs] + def get_reference_point(self): with self.lock: return self.reference_points
    -
    [docs] def get_result(self) -> List[FloatSolution]: + +
    +[docs] + def result(self) -> List[FloatSolution]: result = [] for leader in self.leaders: @@ -491,24 +582,28 @@

    Source code for jmetal.algorithm.multiobjective.smpso

    return result
    -
    [docs] def get_name(self) -> str: - return 'SMPSO/RP'
    + +
    +[docs] + def get_name(self) -> str: + return "SMPSO/RP"
    +
    + def _change_reference_point(algorithm: SMPSORP): - """ Auxiliar function to read new reference points from the keyboard for the SMPSO/RP algorithm - """ + """Auxiliar function to read new reference points from the keyboard for the SMPSO/RP algorithm""" number_of_reference_points = len(algorithm.reference_points) number_of_objectives = algorithm.problem.number_of_objectives while True: - print(f'Enter {number_of_reference_points}-points of dimension {number_of_objectives}: ') + print(f"Enter {number_of_reference_points}-points of dimension {number_of_objectives}: ") read = [float(x) for x in input().split()] # Update reference points reference_points = [] for i in range(0, len(read), number_of_objectives): - reference_points.append(read[i:i + number_of_objectives]) + reference_points.append(read[i : i + number_of_objectives]) algorithm.update_reference_point(reference_points)
    @@ -527,8 +622,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.multiobjective.spea2 — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,23 +106,23 @@

    Table Of Contents

    Source code for jmetal.algorithm.multiobjective.spea2

    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     from jmetal.algorithm.singleobjective.genetic_algorithm import GeneticAlgorithm
     from jmetal.config import store
    -from jmetal.core.operator import Mutation, Crossover
    +from jmetal.core.operator import Crossover, Mutation
     from jmetal.core.problem import Problem
    -from jmetal.operator import BinaryTournamentSelection
    +from jmetal.operator.selection import BinaryTournamentSelection
    +from jmetal.util.comparator import Comparator, MultiComparator
     from jmetal.util.density_estimator import KNearestNeighborDensityEstimator
     from jmetal.util.evaluator import Evaluator
     from jmetal.util.generator import Generator
     from jmetal.util.ranking import StrengthRanking
     from jmetal.util.replacement import RankingAndDensityEstimatorReplacement, RemovalPolicyType
    -from jmetal.util.comparator import Comparator, MultiComparator
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    -R = TypeVar('R')
    +S = TypeVar("S")
    +R = TypeVar("R")
     
     """
     .. module:: SPEA2
    @@ -143,26 +140,30 @@ 

    Source code for jmetal.algorithm.multiobjective.spea2

    """ -
    [docs]class SPEA2(GeneticAlgorithm[S, R]): - - 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): - """ +
    +[docs] +class SPEA2(GeneticAlgorithm[S, R]): + 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()]) + multi_comparator = MultiComparator( + [StrengthRanking.get_comparator(), KNearestNeighborDensityEstimator.get_comparator()] + ) selection = BinaryTournamentSelection(comparator=multi_comparator) super(SPEA2, self).__init__( @@ -174,12 +175,14 @@

    Source code for jmetal.algorithm.multiobjective.spea2

    selection=selection, termination_criterion=termination_criterion, population_evaluator=population_evaluator, - population_generator=population_generator + population_generator=population_generator, ) self.dominance_comparator = dominance_comparator -
    [docs] 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 +
    +[docs] + 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. @@ -194,11 +197,19 @@

    Source code for jmetal.algorithm.multiobjective.spea2

    return solutions
    -
    [docs] def get_result(self) -> R: + +
    +[docs] + def result(self) -> R: return self.solutions
    -
    [docs] def get_name(self) -> str: - return 'SPEA2'
    + +
    +[docs] + def get_name(self) -> str: + return "SPEA2"
    +
    +
    @@ -215,8 +226,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.singleobjective.evolution_strategy — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,17 +107,18 @@

    Table Of Contents

    Source code for jmetal.algorithm.singleobjective.evolution_strategy

     from copy import copy
    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     from jmetal.core.algorithm import EvolutionaryAlgorithm
     from jmetal.core.operator import Mutation
     from jmetal.core.problem import Problem
    +from jmetal.util.constraint_handling import overall_constraint_violation_degree
     from jmetal.util.evaluator import Evaluator, SequentialEvaluator
     from jmetal.util.generator import Generator, RandomGenerator
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    -R = TypeVar('R')
    +S = TypeVar("S")
    +R = TypeVar("R")
     
     """
     .. module:: evolutionary_algorithm
    @@ -131,21 +129,21 @@ 

    Source code for jmetal.algorithm.singleobjective.evolution_strategy

    """ -
    [docs]class EvolutionStrategy(EvolutionaryAlgorithm[S, R]): - - def __init__(self, - problem: Problem, - mu: int, - lambda_: int, - elitist: bool, - mutation: Mutation, - termination_criterion: TerminationCriterion, - population_generator: Generator = RandomGenerator(), - population_evaluator: Evaluator = SequentialEvaluator()): - super(EvolutionStrategy, self).__init__( - problem=problem, - population_size=mu, - offspring_population_size=lambda_) +
    +[docs] +class EvolutionStrategy(EvolutionaryAlgorithm[S, R]): + def __init__( + self, + problem: Problem, + mu: int, + lambda_: int, + elitist: bool, + mutation: Mutation, + termination_criterion: TerminationCriterion, + population_generator: Generator = RandomGenerator(), + population_evaluator: Evaluator = SequentialEvaluator(), + ): + super(EvolutionStrategy, self).__init__(problem=problem, population_size=mu, offspring_population_size=lambda_) self.mu = mu self.lambda_ = lambda_ self.elitist = elitist @@ -158,20 +156,33 @@

    Source code for jmetal.algorithm.singleobjective.evolution_strategy

    self.termination_criterion = termination_criterion self.observable.register(termination_criterion) -
    [docs] def create_initial_solutions(self) -> List[S]: - return [self.population_generator.new(self.problem) - for _ in range(self.population_size)]
    +
    +[docs] + def create_initial_solutions(self) -> List[S]: + return [self.population_generator.new(self.problem) for _ in range(self.population_size)]
    + -
    [docs] def evaluate(self, solution_list: List[S]): +
    +[docs] + def evaluate(self, solution_list: List[S]): return self.population_evaluator.evaluate(solution_list, self.problem)
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def selection(self, population: List[S]) -> List[S]: + +
    +[docs] + def selection(self, population: List[S]) -> List[S]: return population
    -
    [docs] def reproduction(self, population: List[S]) -> List[S]: + +
    +[docs] + def reproduction(self, population: List[S]) -> List[S]: offspring_population = [] for solution in population: for j in range(int(self.lambda_ / self.mu)): @@ -180,7 +191,10 @@

    Source code for jmetal.algorithm.singleobjective.evolution_strategy

    return offspring_population
    -
    [docs] def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: + +
    +[docs] + def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: population_pool = [] if self.elitist: @@ -189,7 +203,7 @@

    Source code for jmetal.algorithm.singleobjective.evolution_strategy

    else: population_pool.extend(offspring_population) - population_pool.sort(key=lambda s: s.objectives[0]) + population_pool.sort(key=lambda s: (overall_constraint_violation_degree(s), s.objectives[0])) new_population = [] for i in range(self.mu): @@ -197,11 +211,19 @@

    Source code for jmetal.algorithm.singleobjective.evolution_strategy

    return new_population
    -
    [docs] def get_result(self) -> R: + +
    +[docs] + def result(self) -> R: return self.solutions[0]
    -
    [docs] def get_name(self) -> str: - return 'Elitist evolution Strategy'
    + +
    +[docs] + def get_name(self) -> str: + return "Elitist evolution Strategy"
    +
    +
    @@ -218,8 +240,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.singleobjective.genetic_algorithm — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,18 +106,21 @@

    Table Of Contents

    Source code for jmetal.algorithm.singleobjective.genetic_algorithm

    -from typing import TypeVar, List
    +from functools import cmp_to_key
    +from typing import List, TypeVar
     
     from jmetal.config import store
     from jmetal.core.algorithm import EvolutionaryAlgorithm
    -from jmetal.core.operator import Mutation, Crossover, Selection
    +from jmetal.core.operator import Crossover, Mutation, Selection
     from jmetal.core.problem import Problem
    +from jmetal.operator.selection import BinaryTournamentSelection
    +from jmetal.util.comparator import Comparator, ObjectiveComparator
     from jmetal.util.evaluator import Evaluator
     from jmetal.util.generator import Generator
     from jmetal.util.termination_criterion import TerminationCriterion
     
    -S = TypeVar('S')
    -R = TypeVar('R')
    +S = TypeVar("S")
    +R = TypeVar("R")
     
     """
     .. module:: genetic_algorithm
    @@ -130,24 +130,29 @@ 

    Source code for jmetal.algorithm.singleobjective.genetic_algorithm

    """ -
    [docs]class GeneticAlgorithm(EvolutionaryAlgorithm[S, R]): - - def __init__(self, - problem: Problem, - population_size: int, - offspring_population_size: int, - mutation: Mutation, - crossover: Crossover, - selection: Selection, - termination_criterion: TerminationCriterion = store.default_termination_criteria, - population_generator: Generator = store.default_generator, - population_evaluator: Evaluator = store.default_evaluator): +
    +[docs] +class GeneticAlgorithm(EvolutionaryAlgorithm[S, R]): + def __init__( + self, + problem: Problem, + population_size: int, + offspring_population_size: int, + mutation: Mutation, + crossover: Crossover, + selection: Selection = BinaryTournamentSelection(ObjectiveComparator(0)), + termination_criterion: TerminationCriterion = store.default_termination_criteria, + population_generator: Generator = store.default_generator, + population_evaluator: Evaluator = store.default_evaluator, + solution_comparator: Comparator = ObjectiveComparator(0) + ): super(GeneticAlgorithm, self).__init__( - problem=problem, - population_size=population_size, - offspring_population_size=offspring_population_size) + problem=problem, population_size=population_size, offspring_population_size=offspring_population_size + ) self.mutation_operator = mutation self.crossover_operator = crossover + self.solution_comparator = solution_comparator + self.selection_operator = selection self.population_generator = population_generator @@ -156,37 +161,52 @@

    Source code for jmetal.algorithm.singleobjective.genetic_algorithm

    self.termination_criterion = termination_criterion self.observable.register(termination_criterion) - self.mating_pool_size = \ - self.offspring_population_size * \ - self.crossover_operator.get_number_of_parents() // self.crossover_operator.get_number_of_children() + self.mating_pool_size = ( + self.offspring_population_size + * self.crossover_operator.get_number_of_parents() + // self.crossover_operator.get_number_of_children() + ) if self.mating_pool_size < self.crossover_operator.get_number_of_children(): self.mating_pool_size = self.crossover_operator.get_number_of_children() -
    [docs] def create_initial_solutions(self) -> List[S]: - return [self.population_generator.new(self.problem) - for _ in range(self.population_size)]
    +
    +[docs] + def create_initial_solutions(self) -> List[S]: + return [self.population_generator.new(self.problem) for _ in range(self.population_size)]
    -
    [docs] def evaluate(self, population: List[S]): + +
    +[docs] + def evaluate(self, population: List[S]): return self.population_evaluator.evaluate(population, self.problem)
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def selection(self, population: List[S]): + +
    +[docs] + def selection(self, population: List[S]): mating_population = [] - for i in range(self.mating_pool_size): + for _ in range(self.mating_pool_size): solution = self.selection_operator.execute(population) mating_population.append(solution) return mating_population
    -
    [docs] def reproduction(self, mating_population: List[S]) -> List[S]: + +
    +[docs] + def reproduction(self, mating_population: List[S]) -> List[S]: number_of_parents_to_combine = self.crossover_operator.get_number_of_parents() if len(mating_population) % number_of_parents_to_combine != 0: - raise Exception('Wrong number of parents') + raise Exception("Wrong number of parents") offspring_population = [] for i in range(0, self.offspring_population_size, number_of_parents_to_combine): @@ -204,18 +224,29 @@

    Source code for jmetal.algorithm.singleobjective.genetic_algorithm

    return offspring_population
    -
    [docs] def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: + +
    +[docs] + def replacement(self, population: List[S], offspring_population: List[S]) -> List[S]: population.extend(offspring_population) - population.sort(key=lambda s: s.objectives[0]) + population.sort(key=cmp_to_key(self.solution_comparator.compare)) + + return population[: self.population_size]
    - return population[:self.population_size]
    -
    [docs] def get_result(self) -> R: +
    +[docs] + def result(self) -> R: return self.solutions[0]
    -
    [docs] def get_name(self) -> str: - return 'Genetic algorithm'
    + +
    +[docs] + def get_name(self) -> str: + return "Genetic algorithm"
    +
    +
    @@ -232,8 +263,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.singleobjective.local_search — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -113,7 +110,7 @@

    Source code for jmetal.algorithm.singleobjective.local_search

    import random import threading import time -from typing import TypeVar, List +from typing import List, TypeVar from jmetal.config import store from jmetal.core.algorithm import Algorithm @@ -123,8 +120,8 @@

    Source code for jmetal.algorithm.singleobjective.local_search

    from jmetal.util.comparator import Comparator from jmetal.util.termination_criterion import TerminationCriterion -S = TypeVar('S') -R = TypeVar('R') +S = TypeVar("S") +R = TypeVar("R") """ .. module:: local_search @@ -135,13 +132,16 @@

    Source code for jmetal.algorithm.singleobjective.local_search

    """ -
    [docs]class LocalSearch(Algorithm[S, R], threading.Thread): - - def __init__(self, - problem: Problem[S], - mutation: Mutation, - termination_criterion: TerminationCriterion = store.default_termination_criteria, - comparator: Comparator = store.default_comparator): +
    +[docs] +class LocalSearch(Algorithm[S, R], threading.Thread): + def __init__( + self, + problem: Problem[S], + mutation: Mutation, + termination_criterion: TerminationCriterion = store.default_termination_criteria, + comparator: Comparator = store.default_comparator, + ): super(LocalSearch, self).__init__() self.comparator = comparator self.problem = problem @@ -149,20 +149,34 @@

    Source code for jmetal.algorithm.singleobjective.local_search

    self.termination_criterion = termination_criterion self.observable.register(termination_criterion) -
    [docs] def create_initial_solutions(self) -> List[S]: +
    +[docs] + def create_initial_solutions(self) -> List[S]: self.solutions.append(self.problem.create_solution()) return self.solutions
    -
    [docs] def evaluate(self, solutions: List[S]) -> List[S]: + +
    +[docs] + def evaluate(self, solutions: List[S]) -> List[S]: return [self.problem.evaluate(solutions[0])]
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def init_progress(self) -> None: + +
    +[docs] + def init_progress(self) -> None: self.evaluations = 0
    -
    [docs] def step(self) -> None: + +
    +[docs] + def step(self) -> None: mutated_solution = copy.deepcopy(self.solutions[0]) mutated_solution: Solution = self.mutation.execute(mutated_solution) mutated_solution = self.evaluate([mutated_solution])[0] @@ -176,22 +190,40 @@

    Source code for jmetal.algorithm.singleobjective.local_search

    if random.random() < 0.5: self.solutions[0] = mutated_solution
    -
    [docs] def update_progress(self) -> None: + +
    +[docs] + def update_progress(self) -> None: self.evaluations += 1 - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data)
    -
    [docs] def get_observable_data(self) -> dict: + +
    +[docs] + def observable_data(self) -> dict: ctime = time.time() - self.start_computing_time - return {'PROBLEM': self.problem, 'EVALUATIONS': self.evaluations, 'SOLUTIONS': self.get_result(), - 'COMPUTING_TIME': ctime}
    + return { + "PROBLEM": self.problem, + "EVALUATIONS": self.evaluations, + "SOLUTIONS": self.result(), + "COMPUTING_TIME": ctime, + }
    + -
    [docs] def get_result(self) -> R: +
    +[docs] + def result(self) -> R: return self.solutions[0]
    -
    [docs] def get_name(self) -> str: - return 'LS'
    + +
    +[docs] + def get_name(self) -> str: + return "LS"
    +
    +
    @@ -208,8 +240,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.algorithm.singleobjective.simulated_annealing — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -113,73 +110,95 @@

    Source code for jmetal.algorithm.singleobjective.simulated_annealing

    import random import threading import time -from typing import TypeVar, List +from typing import List, TypeVar import numpy +from jmetal.config import store from jmetal.core.algorithm import Algorithm from jmetal.core.operator import Mutation from jmetal.core.problem import Problem from jmetal.core.solution import Solution +from jmetal.util.generator import Generator from jmetal.util.termination_criterion import TerminationCriterion -S = TypeVar('S') -R = TypeVar('R') +S = TypeVar("S") +R = TypeVar("R") """ .. module:: simulated_annealing :platform: Unix, Windows - :synopsis: Implementation of Local search. + :synopsis: Implementation of Simulated Annealing. .. moduleauthor:: Antonio J. Nebro <antonio@lcc.uma.es>, Antonio Benítez-Hidalgo <antonio.b@uma.es> """ -
    [docs]class SimulatedAnnealing(Algorithm[S, R], threading.Thread): - - def __init__(self, - problem: Problem[S], - mutation: Mutation, - termination_criterion: TerminationCriterion): +
    +[docs] +class SimulatedAnnealing(Algorithm[S, R], threading.Thread): + def __init__( + self, + problem: Problem[S], + mutation: Mutation, + termination_criterion: TerminationCriterion, + solution_generator: Generator = store.default_generator, + ): super(SimulatedAnnealing, self).__init__() self.problem = problem self.mutation = mutation self.termination_criterion = termination_criterion + self.solution_generator = solution_generator self.observable.register(termination_criterion) self.temperature = 1.0 self.minimum_temperature = 0.000001 self.alpha = 0.95 self.counter = 0 -
    [docs] def create_initial_solutions(self) -> List[S]: - self.solutions.append(self.problem.create_solution()) - return self.solutions
    +
    +[docs] + def create_initial_solutions(self) -> List[S]: + return [self.solution_generator.new(self.problem)]
    -
    [docs] def evaluate(self, solutions: List[S]) -> List[S]: + +
    +[docs] + def evaluate(self, solutions: List[S]) -> List[S]: return [self.problem.evaluate(solutions[0])]
    -
    [docs] def stopping_condition_is_met(self) -> bool: + +
    +[docs] + def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met
    -
    [docs] def init_progress(self) -> None: + +
    +[docs] + def init_progress(self) -> None: self.evaluations = 0
    -
    [docs] def step(self) -> None: + +
    +[docs] + def step(self) -> None: mutated_solution = copy.deepcopy(self.solutions[0]) mutated_solution: Solution = self.mutation.execute(mutated_solution) mutated_solution = self.evaluate([mutated_solution])[0] acceptance_probability = self.compute_acceptance_probability( - self.solutions[0].objectives[0], - mutated_solution.objectives[0], - self.temperature) + self.solutions[0].objectives[0], mutated_solution.objectives[0], self.temperature + ) if acceptance_probability > random.random(): self.solutions[0] = mutated_solution self.temperature *= self.alpha
    -
    [docs] def compute_acceptance_probability(self, current: float, new: float, temperature: float) -> float: + +
    +[docs] + def compute_acceptance_probability(self, current: float, new: float, temperature: float) -> float: if new < current: return 1.0 else: @@ -187,22 +206,40 @@

    Source code for jmetal.algorithm.singleobjective.simulated_annealing

    value = (new - current) / t return numpy.exp(-1.0 * value)
    -
    [docs] def update_progress(self) -> None: + +
    +[docs] + def update_progress(self) -> None: self.evaluations += 1 - observable_data = self.get_observable_data() + observable_data = self.observable_data() self.observable.notify_all(**observable_data)
    -
    [docs] def get_observable_data(self) -> dict: + +
    +[docs] + def observable_data(self) -> dict: ctime = time.time() - self.start_computing_time - return {'PROBLEM': self.problem, 'EVALUATIONS': self.evaluations, 'SOLUTIONS': self.get_result(), - 'COMPUTING_TIME': ctime}
    + return { + "PROBLEM": self.problem, + "EVALUATIONS": self.evaluations, + "SOLUTIONS": self.result(), + "COMPUTING_TIME": ctime, + }
    + -
    [docs] def get_result(self) -> R: +
    +[docs] + def result(self) -> R: return self.solutions[0]
    -
    [docs] def get_name(self) -> str: - return 'Simulated Annealing'
    + +
    +[docs] + def get_name(self) -> str: + return "Simulated Annealing"
    +
    +
    @@ -219,8 +256,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.core.observer — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,7 +106,7 @@

    Table Of Contents

    Source code for jmetal.core.observer

    -from abc import abstractmethod, ABC
    +from abc import ABC, abstractmethod
     
     """
     .. module:: Observable
    @@ -120,33 +117,49 @@ 

    Source code for jmetal.core.observer

     """
     
     
    -
    [docs]class Observer(ABC): - -
    [docs] @abstractmethod +
    +[docs] +class Observer(ABC): +
    +[docs] + @abstractmethod def update(self, *args, **kwargs): - """ Update method. - """ - pass
    + """Update method.""" + pass
    +
    -
    [docs]class Observable(ABC): -
    [docs] @abstractmethod +
    +[docs] +class Observable(ABC): +
    +[docs] + @abstractmethod def register(self, observer): pass
    -
    [docs] @abstractmethod + +
    +[docs] + @abstractmethod def deregister(self, observer): pass
    -
    [docs] @abstractmethod + +
    +[docs] + @abstractmethod def deregister_all(self): pass
    -
    [docs] @abstractmethod - def notify_all(self, *args, **kwargs): - pass
    +
    +[docs] + @abstractmethod + def notify_all(self, *args, **kwargs): + pass
    +
    @@ -164,8 +177,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.core.problem — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,123 +106,209 @@

    Table Of Contents

    Source code for jmetal.core.problem

    -import logging
    -import random
    +import random
     from abc import ABC, abstractmethod
    -from typing import Generic, TypeVar, List
    +from typing import Generic, List, TypeVar
     
     from jmetal.core.observer import Observer
    -from jmetal.core.solution import BinarySolution, FloatSolution, IntegerSolution, PermutationSolution
    +from jmetal.core.solution import (
    +    BinarySolution,
    +    FloatSolution,
    +    IntegerSolution,
    +    PermutationSolution,
    +)
    +from jmetal.logger import get_logger
     
    -LOGGER = logging.getLogger('jmetal')
    +logger = get_logger(__name__)
     
    -S = TypeVar('S')
    +S = TypeVar("S")
     
     
    -
    [docs]class Problem(Generic[S], ABC): - """ Class representing problems. """ +
    +[docs] +class Problem(Generic[S], ABC): + """Class representing problems.""" MINIMIZE = -1 MAXIMIZE = 1 def __init__(self): - self.number_of_variables: int = 0 - self.number_of_objectives: int = 0 - self.number_of_constraints: int = 0 - - self.reference_front: List[S] = None - + self.reference_front: List[S] = [] self.directions: List[int] = [] self.labels: List[str] = [] -
    [docs] @abstractmethod +
    +[docs] + @abstractmethod + def number_of_variables(self) -> int: + pass
    + + +
    +[docs] + @abstractmethod + def number_of_objectives(self) -> int: + pass
    + + +
    +[docs] + @abstractmethod + def number_of_constraints(self) -> int: + pass
    + + +
    +[docs] + @abstractmethod def create_solution(self) -> S: - """ Creates a random_search solution to the problem. + """Creates a random_search solution to the problem. - :return: Solution. """ + :return: Solution.""" pass
    -
    [docs] @abstractmethod + +
    +[docs] + @abstractmethod def evaluate(self, solution: S) -> S: - """ Evaluate a solution. For any new problem inheriting from :class:`Problem`, this method should be - replaced. Note that this framework ASSUMES minimization, thus solutions must be evaluated in consequence. + """Evaluate a solution. For any new problem inheriting from :class:`Problem`, this method should be replaced. + Note that this framework ASSUMES minimization, thus solutions must be evaluated in consequence. - :return: Evaluated solution. """ + :return: Evaluated solution.""" pass
    -
    [docs] @abstractmethod - def get_name(self) -> str: - pass
    + +
    +[docs] + @abstractmethod + def name(self) -> str: + pass
    +
    -
    [docs]class DynamicProblem(Problem[S], Observer, ABC): -
    [docs] @abstractmethod +
    +[docs] +class DynamicProblem(Problem[S], Observer, ABC): +
    +[docs] + @abstractmethod def the_problem_has_changed(self) -> bool: pass
    -
    [docs] @abstractmethod + +
    +[docs] + @abstractmethod def clear_changed(self) -> None: - pass
    + pass
    +
    + -
    [docs]class BinaryProblem(Problem[BinarySolution], ABC): - """ Class representing binary problems. """ +
    +[docs] +class BinaryProblem(Problem[BinarySolution], ABC): + """Class representing binary problems.""" def __init__(self): - super(BinaryProblem, self).__init__()
    + super(BinaryProblem, self).__init__() + + self.number_of_bits_per_variable = [] +
    +[docs] + def number_of_bits_per_variable_list(self): + return self.number_of_bits_per_variable
    + + +
    +[docs] + def total_number_of_bits(self): + return sum(self.number_of_bits_per_variable)
    +
    -
    [docs]class FloatProblem(Problem[FloatSolution], ABC): - """ Class representing float problems. """ + + +
    +[docs] +class FloatProblem(Problem[FloatSolution], ABC): + """Class representing float problems.""" def __init__(self): super(FloatProblem, self).__init__() self.lower_bound = [] self.upper_bound = [] -
    [docs] def create_solution(self) -> FloatSolution: +
    +[docs] + def number_of_variables(self) -> int: + return len(self.lower_bound)
    + + +
    +[docs] + def create_solution(self) -> FloatSolution: new_solution = FloatSolution( - self.lower_bound, - self.upper_bound, - self.number_of_objectives, - self.number_of_constraints) - new_solution.variables = \ - [random.uniform(self.lower_bound[i]*1.0, self.upper_bound[i]*1.0) for i in range(self.number_of_variables)] + self.lower_bound, self.upper_bound, self.number_of_objectives(), self.number_of_constraints() + ) + new_solution.variables = [ + random.uniform(self.lower_bound[i] * 1.0, self.upper_bound[i] * 1.0) + for i in range(self.number_of_variables()) + ] + + return new_solution
    +
    - return new_solution
    -
    [docs]class IntegerProblem(Problem[IntegerSolution], ABC): - """ Class representing integer problems. """ +
    +[docs] +class IntegerProblem(Problem[IntegerSolution], ABC): + """Class representing integer problems.""" def __init__(self): super(IntegerProblem, self).__init__() - self.lower_bound = None - self.upper_bound = None + self.lower_bound = [] + self.upper_bound = [] + +
    +[docs] + def number_of_variables(self) -> int: + return len(self.lower_bound)
    + -
    [docs] def create_solution(self) -> IntegerSolution: +
    +[docs] + def create_solution(self) -> IntegerSolution: new_solution = IntegerSolution( - self.lower_bound, - self.upper_bound, - self.number_of_objectives, - self.number_of_constraints) - new_solution.variables = \ - [int(random.uniform(self.lower_bound[i]*1.0, self.upper_bound[i]*1.0)) - for i in range(self.number_of_variables)] + self.lower_bound, self.upper_bound, self.number_of_objectives(), self.number_of_constraints() + ) + new_solution.variables = [ + round(random.uniform(self.lower_bound[i] * 1.0, self.upper_bound[i] * 1.0)) + for i in range(self.number_of_variables()) + ] + + return new_solution
    +
    - return new_solution
    -
    [docs]class PermutationProblem(Problem[PermutationSolution], ABC): - """ Class representing permutation problems. """ +
    +[docs] +class PermutationProblem(Problem[PermutationSolution], ABC): + """Class representing permutation problems.""" def __init__(self): super(PermutationProblem, self).__init__()
    -
    [docs]class OnTheFlyFloatProblem(FloatProblem): - """ Class for defining float problems on the fly. + +
    +[docs] +class OnTheFlyFloatProblem(FloatProblem): + """ Class for defining float problems on the fly. Example: @@ -251,45 +334,74 @@

    Source code for jmetal.core.problem

                 .add_constraint(c1)\
                 .add_constraint(c2)
         """
    +
         def __init__(self):
             super(OnTheFlyFloatProblem, self).__init__()
             self.functions = []
             self.constraints = []
    -        self.name = None
    +        self.problem_name = None
     
    -
    [docs] def set_name(self, name): - self.name = name +
    +[docs] + def set_name(self, name) -> "OnTheFlyFloatProblem": + self.problem_name = name return self
    -
    [docs] def add_function(self, function): + +
    +[docs] + def add_function(self, function) -> "OnTheFlyFloatProblem": self.functions.append(function) - self.number_of_objectives += 1 return self
    -
    [docs] def add_constraint(self, constraint): + +
    +[docs] + def add_constraint(self, constraint) -> "OnTheFlyFloatProblem": self.constraints.append(constraint) - self.number_of_constraints += 1 return self
    -
    [docs] def add_variable(self, lower_bound, upper_bound): + +
    +[docs] + def add_variable(self, lower_bound, upper_bound) -> "OnTheFlyFloatProblem": self.lower_bound.append(lower_bound) self.upper_bound.append(upper_bound) - self.number_of_variables += 1 return self
    -
    [docs] def evaluate(self, solution: FloatSolution): - for i in range(self.number_of_objectives): + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.functions)
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return len(self.constraints)
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> None: + for i in range(self.number_of_objectives()): solution.objectives[i] = self.functions[i](solution.variables) - for i in range(self.number_of_constraints): + for i in range(self.number_of_constraints()): solution.constraints[i] = self.constraints[i](solution.variables)
    -
    [docs] def get_name(self) -> str: - return self.name
    + +
    +[docs] + def name(self) -> str: + return self.problem_name
    +
    +
    @@ -306,8 +418,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.experiment — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,7 +107,6 @@

    Table Of Contents

    Source code for jmetal.lab.experiment

     import io
    -import logging
     import os
     from concurrent.futures import ProcessPoolExecutor
     from pathlib import Path
    @@ -120,13 +116,18 @@ 

    Source code for jmetal.lab.experiment

     import matplotlib.pyplot as plt
     import numpy as np
     import pandas as pd
    -from scipy.stats import mannwhitneyu
    +from scipy.stats import mannwhitneyu, iqr, ks_2samp
     
     from jmetal.core.algorithm import Algorithm
     from jmetal.core.quality_indicator import QualityIndicator
    -from jmetal.util.solution import print_function_values_to_file, print_variables_to_file, read_solutions
    +from jmetal.logger import get_logger
    +from jmetal.util.solution import (
    +    print_function_values_to_file,
    +    print_variables_to_file,
    +    read_solutions,
    +)
     
    -LOGGER = logging.getLogger('jmetal')
    +logger = get_logger(__name__)
     
     """
     .. module:: laboratory
    @@ -137,33 +138,45 @@ 

    Source code for jmetal.lab.experiment

     """
     
     
    -
    [docs]class Job: - +
    +[docs] +class Job: def __init__(self, algorithm: Algorithm, algorithm_tag: str, problem_tag: str, run: int): self.algorithm = algorithm self.algorithm_tag = algorithm_tag self.problem_tag = problem_tag self.run_tag = run -
    [docs] def execute(self, output_path: str = ''): +
    +[docs] + def execute(self, output_path: str = ""): self.algorithm.run() if output_path: - file_name = os.path.join(output_path, 'FUN.{}.tsv'.format(self.run_tag)) - print_function_values_to_file(self.algorithm.get_result(), filename=file_name) + file_name = os.path.join(output_path, "FUN.{}.tsv".format(self.run_tag)) + print_function_values_to_file(self.algorithm.result(), filename=file_name) - file_name = os.path.join(output_path, 'VAR.{}.tsv'.format(self.run_tag)) - print_variables_to_file(self.algorithm.get_result(), filename=file_name) + file_name = os.path.join(output_path, "VAR.{}.tsv".format(self.run_tag)) + print_variables_to_file(self.algorithm.result(), filename=file_name) - file_name = os.path.join(output_path, 'TIME.{}'.format(self.run_tag)) - with open(file_name, 'w+') as of: - of.write(str(self.algorithm.total_computing_time))
    + file_name = os.path.join(output_path, "TIME.{}".format(self.run_tag)) + with open(file_name, "w+") as of: + of.write(str(self.algorithm.total_computing_time))
    -
    [docs]class Experiment: +
    +[docs] + def get_algorithm_data(self): + return self.algorithm.observable_data()
    +
    + + +
    +[docs] +class Experiment: def __init__(self, output_dir: str, jobs: List[Job], m_workers: int = 6): - """ Run an experiment to execute a list of jobs. + """Run an experiment to execute a list of jobs. :param output_dir: Base directory where each job will save its results. :param jobs: List of Jobs (from :py:mod:`jmetal.util.laboratory)`) to be executed. @@ -172,17 +185,26 @@

    Source code for jmetal.lab.experiment

             self.jobs = jobs
             self.m_workers = m_workers
             self.output_dir = output_dir
    +        self.job_data = []
     
    -
    [docs] def run(self) -> None: +
    +[docs] + def run(self) -> None: with ProcessPoolExecutor(max_workers=self.m_workers) as executor: for job in self.jobs: output_path = os.path.join(self.output_dir, job.algorithm_tag, job.problem_tag) - executor.submit(job.execute(output_path))
    + executor.submit(job.execute(output_path)) + self.job_data.append(job.get_algorithm_data())
    +
    + -
    [docs]def generate_summary_from_experiment(input_dir: str, quality_indicators: List[QualityIndicator], - reference_fronts: str = ''): - """ Compute a list of quality indicators. The input data directory *must* met the following structure (this is generated +
    +[docs] +def generate_summary_from_experiment( + input_dir: str, quality_indicators: List[QualityIndicator], reference_fronts: str = "" +): + """Compute a list of quality indicators. The input data directory *must* met the following structure (this is generated automatically by the Experiment class): * <base_dir> @@ -206,52 +228,57 @@

    Source code for jmetal.lab.experiment

         if not quality_indicators:
             quality_indicators = []
     
    -    with open('QualityIndicatorSummary.csv', 'w+') as of:
    -        of.write('Algorithm,Problem,ExecutionId,IndicatorName,IndicatorValue\n')
    +    with open("QualityIndicatorSummary.csv", "w+") as of:
    +        of.write("Algorithm,Problem,ExecutionId,IndicatorName,IndicatorValue\n")
     
         for dirname, _, filenames in os.walk(input_dir):
             for filename in filenames:
                 try:
                     # Linux filesystem
    -                algorithm, problem = dirname.split('/')[-2:]
    +                algorithm, problem = dirname.split("/")[-2:]
                 except ValueError:
                     # Windows filesystem
    -                algorithm, problem = dirname.split('\\')[-2:]
    +                algorithm, problem = dirname.split("\\")[-2:]
     
    -            if 'TIME' in filename:
    -                run_tag = [s for s in filename.split('.') if s.isdigit()].pop()
    +            if "TIME" in filename:
    +                run_tag = [s for s in filename.split(".") if s.isdigit()].pop()
     
    -                with open(os.path.join(dirname, filename), 'r') as content_file:
    +                with open(os.path.join(dirname, filename), "r") as content_file:
                         content = content_file.read()
     
    -                with open('QualityIndicatorSummary.csv', 'a+') as of:
    -                    of.write(','.join([algorithm, problem, run_tag, 'Time', str(content)]))
    -                    of.write('\n')
    +                with open("QualityIndicatorSummary.csv", "a+") as of:
    +                    of.write(",".join([algorithm, problem, run_tag, "Time", str(content)]))
    +                    of.write("\n")
     
    -            if 'FUN' in filename:
    +            if "FUN" in filename:
                     solutions = read_solutions(os.path.join(dirname, filename))
    -                run_tag = [s for s in filename.split('.') if s.isdigit()].pop()
    -
    +                run_tag = [s for s in filename.split(".") if s.isdigit()].pop()
                     for indicator in quality_indicators:
    -                    reference_front_file = os.path.join(reference_fronts, problem + '.pf')
    +                    reference_front_file = os.path.join(reference_fronts, problem + ".pf")
     
                         # Add reference front if any
    -                    if hasattr(indicator, 'reference_front'):
    +                    if hasattr(indicator, "reference_front"):
                             if Path(reference_front_file).is_file():
    -                            indicator.reference_front = read_solutions(reference_front_file)
    +                            reference_front = []
    +                            with open(reference_front_file) as file:
    +                                for line in file:
    +                                    reference_front.append([float(x) for x in line.split()])
    +
    +                            indicator.reference_front = reference_front
                             else:
    -                            LOGGER.warning('Reference front not found at', reference_front_file)
    +                            logger.warning("Reference front not found at", reference_front_file)
     
    -                    result = indicator.compute(solutions)
    +                    result = indicator.compute([solutions[i].objectives for i in range(len(solutions))])
     
                         # Save quality indicator value to file
    -                    with open('QualityIndicatorSummary.csv', 'a+') as of:
    -                        of.write(','.join([algorithm, problem, run_tag, indicator.get_name(), str(result)]))
    -                        of.write('\n')
    + with open("QualityIndicatorSummary.csv", "a+") as of: + of.write(",".join([algorithm, problem, run_tag, indicator.get_short_name(), str(result)])) + of.write("\n")
    + -def generate_boxplot(filename: str, output_dir: str = 'boxplot'): - """ Generate boxplot diagrams. +def generate_boxplot(filename: str, output_dir: str = "boxplot"): + """Generate boxplot diagrams. :param filename: Input filename (summary). :param output_dir: Output path. @@ -259,31 +286,32 @@

    Source code for jmetal.lab.experiment

         df = pd.read_csv(filename, skipinitialspace=True)
     
         if len(set(df.columns.tolist())) != 5:
    -        raise Exception('Wrong number of columns')
    +        raise Exception("Wrong number of columns")
     
         if Path(output_dir).is_dir():
    -        LOGGER.warning('Directory {} exists. Removing contents.'.format(output_dir))
    +        logger.warning("Directory {} exists. Removing contents.".format(output_dir))
             for file in os.listdir(output_dir):
    -            os.remove('{0}/{1}'.format(output_dir, file))
    +            os.remove("{0}/{1}".format(output_dir, file))
         else:
    -        LOGGER.warning('Directory {} does not exist. Creating it.'.format(output_dir))
    +        logger.warning("Directory {} does not exist. Creating it.".format(output_dir))
             Path(output_dir).mkdir(parents=True)
     
    -    algorithms = pd.unique(df['Algorithm'])
    -    problems = pd.unique(df['Problem'])
    -    indicators = pd.unique(df['IndicatorName'])
    +    algorithms = pd.unique(df["Algorithm"])
    +    problems = pd.unique(df["Problem"])
    +    indicators = pd.unique(df["IndicatorName"])
     
         # We consider the quality indicator indicator_name
     
         for indicator_name in indicators:
    -        data = df[df['IndicatorName'] == indicator_name]
    +        data = df[df["IndicatorName"] == indicator_name]
     
             for pr in problems:
                 data_to_plot = []
     
                 for alg in algorithms:
    -                data_to_plot.append(data['IndicatorValue'][np.logical_and(
    -                    data['Algorithm'] == alg, data['Problem'] == pr)])
    +                data_to_plot.append(
    +                    data["IndicatorValue"][np.logical_and(data["Algorithm"] == alg, data["Problem"] == pr)]
    +                )
     
                 # Create a figure instance
                 fig = plt.figure(1, figsize=(9, 6))
    @@ -295,13 +323,13 @@ 

    Source code for jmetal.lab.experiment

                 ax.set_xticklabels(algorithms)
                 ax.tick_params(labelsize=20)
     
    -            plt.savefig(os.path.join(output_dir, 'boxplot-{}-{}.png'.format(pr, indicator_name)), bbox_inches='tight')
    -            plt.savefig(os.path.join(output_dir, 'boxplot-{}-{}.eps'.format(pr, indicator_name)), bbox_inches='tight')
    +            plt.savefig(os.path.join(output_dir, "boxplot-{}-{}.png".format(pr, indicator_name)), bbox_inches="tight")
    +            plt.savefig(os.path.join(output_dir, "boxplot-{}-{}.eps".format(pr, indicator_name)), bbox_inches="tight")
                 plt.close(fig)
     
     
    -def generate_latex_tables(filename: str, output_dir: str = 'latex/statistical'):
    -    """ Computes a number of statistical values (mean, median, standard deviation, interquartile range).
    +def generate_latex_tables(filename: str, output_dir: str = "latex/statistical"):
    +    """Computes a number of statistical values (mean, median, standard deviation, interquartile range).
     
         :param filename: Input filename (summary).
         :param output_dir: Output path.
    @@ -309,24 +337,24 @@ 

    Source code for jmetal.lab.experiment

         df = pd.read_csv(filename, skipinitialspace=True)
     
         if len(set(df.columns.tolist())) != 5:
    -        raise Exception('Wrong number of columns')
    +        raise Exception("Wrong number of columns")
     
         if Path(output_dir).is_dir():
    -        LOGGER.warning('Directory {} exists. Removing contents.'.format(output_dir))
    +        logger.warning("Directory {} exists. Removing contents.".format(output_dir))
             for file in os.listdir(output_dir):
    -            os.remove('{0}/{1}'.format(output_dir, file))
    +            os.remove("{0}/{1}".format(output_dir, file))
         else:
    -        LOGGER.warning('Directory {} does not exist. Creating it.'.format(output_dir))
    +        logger.warning("Directory {} does not exist. Creating it.".format(output_dir))
             Path(output_dir).mkdir(parents=True)
     
         # Generate median & iqr tables
         median, iqr = pd.DataFrame(), pd.DataFrame()
         mean, std = pd.DataFrame(), pd.DataFrame()
     
    -    for algorithm_name, subset in df.groupby('Algorithm', sort=False):
    -        subset = subset.drop('Algorithm', axis=1)
    -        subset = subset.rename(columns={'IndicatorValue': algorithm_name})
    -        subset = subset.set_index(['Problem', 'IndicatorName', 'ExecutionId'])
    +    for algorithm_name, subset in df.groupby("Algorithm", sort=False):
    +        subset = subset.drop("Algorithm", axis=1)
    +        subset = subset.rename(columns={"IndicatorValue": algorithm_name})
    +        subset = subset.set_index(["Problem", "IndicatorName", "ExecutionId"])
     
             # Compute Median and Interquartile range
             median_ = subset.groupby(level=[0, 1]).median()
    @@ -343,83 +371,83 @@ 

    Source code for jmetal.lab.experiment

             std = pd.concat([std, std_], axis=1)
     
         # Generate mean & std tables
    -    for indicator_name, subset in std.groupby('IndicatorName', sort=False):
    -        subset = median.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +    for indicator_name, subset in std.groupby("IndicatorName", sort=False):
    +        subset = median.groupby("IndicatorName", sort=False).get_group(indicator_name)
             subset.index = subset.index.droplevel(1)
    -        subset.to_csv(os.path.join(output_dir, 'Median-{}.csv'.format(indicator_name)), sep='\t', encoding='utf-8')
    +        subset.to_csv(os.path.join(output_dir, "Median-{}.csv".format(indicator_name)), sep="\t", encoding="utf-8")
     
    -        subset = iqr.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +        subset = iqr.groupby("IndicatorName", sort=False).get_group(indicator_name)
             subset.index = subset.index.droplevel(1)
    -        subset.to_csv(os.path.join(output_dir, 'IQR-{}.csv'.format(indicator_name)), sep='\t', encoding='utf-8')
    +        subset.to_csv(os.path.join(output_dir, "IQR-{}.csv".format(indicator_name)), sep="\t", encoding="utf-8")
     
    -        subset = mean.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +        subset = mean.groupby("IndicatorName", sort=False).get_group(indicator_name)
             subset.index = subset.index.droplevel(1)
    -        subset.to_csv(os.path.join(output_dir, 'Mean-{}.csv'.format(indicator_name)), sep='\t', encoding='utf-8')
    +        subset.to_csv(os.path.join(output_dir, "Mean-{}.csv".format(indicator_name)), sep="\t", encoding="utf-8")
     
    -        subset = std.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +        subset = std.groupby("IndicatorName", sort=False).get_group(indicator_name)
             subset.index = subset.index.droplevel(1)
    -        subset.to_csv(os.path.join(output_dir, 'Std-{}.csv'.format(indicator_name)), sep='\t', encoding='utf-8')
    +        subset.to_csv(os.path.join(output_dir, "Std-{}.csv".format(indicator_name)), sep="\t", encoding="utf-8")
     
         # Generate LaTeX tables
    -    for indicator_name in df.groupby('IndicatorName', sort=False).groups.keys():
    +    for indicator_name in df.groupby("IndicatorName", sort=False).groups.keys():
             # Median & IQR
    -        md = median.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +        md = median.groupby("IndicatorName", sort=False).get_group(indicator_name)
             md.index = md.index.droplevel(1)
     
    -        i = iqr.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +        i = iqr.groupby("IndicatorName", sort=False).get_group(indicator_name)
             i.index = i.index.droplevel(1)
     
    -        with open(os.path.join(output_dir, 'MedianIQR-{}.tex'.format(indicator_name)), 'w') as latex:
    +        with open(os.path.join(output_dir, "MedianIQR-{}.tex".format(indicator_name)), "w") as latex:
                 latex.write(
                     __averages_to_latex(
                         md,
                         i,
    -                    caption='Median and Interquartile Range of the {} quality indicator.'.format(indicator_name),
    +                    caption="Median and Interquartile Range of the {} quality indicator.".format(indicator_name),
                         minimization=check_minimization(indicator_name),
    -                    label='table:{}'.format(indicator_name)
    +                    label="table:{}".format(indicator_name),
                     )
                 )
     
             # Mean & Std
    -        mn = mean.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +        mn = mean.groupby("IndicatorName", sort=False).get_group(indicator_name)
             mn.index = mn.index.droplevel(1)
     
    -        s = std.groupby('IndicatorName', sort=False).get_group(indicator_name)
    +        s = std.groupby("IndicatorName", sort=False).get_group(indicator_name)
             s.index = s.index.droplevel(1)
     
    -        with open(os.path.join(output_dir, 'MeanStd-{}.tex'.format(indicator_name)), 'w') as latex:
    +        with open(os.path.join(output_dir, "MeanStd-{}.tex".format(indicator_name)), "w") as latex:
                 latex.write(
                     __averages_to_latex(
                         mn,
                         s,
    -                    caption='Mean and Standard Deviation of the {} quality indicator.'.format(indicator_name),
    +                    caption="Mean and Standard Deviation of the {} quality indicator.".format(indicator_name),
                         minimization=check_minimization(indicator_name),
    -                    label='table:{}'.format(indicator_name)
    +                    label="table:{}".format(indicator_name),
                     )
                 )
     
     
    -def compute_wilcoxon(filename: str, output_dir: str = 'latex/wilcoxon'):
    -    """
    +def compute_wilcoxon(filename: str, output_dir: str = "latex/wilcoxon"):
    +    """
         :param filename: Input filename (summary).
         :param output_dir: Output path.
         """
         df = pd.read_csv(filename, skipinitialspace=True)
     
         if len(set(df.columns.tolist())) != 5:
    -        raise Exception('Wrong number of columns')
    +        raise Exception("Wrong number of columns")
     
         if Path(output_dir).is_dir():
    -        LOGGER.warning('Directory {} exists. Removing contents.'.format(output_dir))
    +        logger.warning("Directory {} exists. Removing contents.".format(output_dir))
             for file in os.listdir(output_dir):
    -            os.remove('{0}/{1}'.format(output_dir, file))
    +            os.remove("{0}/{1}".format(output_dir, file))
         else:
    -        LOGGER.warning('Directory {} does not exist. Creating it.'.format(output_dir))
    +        logger.warning("Directory {} does not exist. Creating it.".format(output_dir))
             Path(output_dir).mkdir(parents=True)
     
    -    algorithms = pd.unique(df['Algorithm'])
    -    problems = pd.unique(df['Problem'])
    -    indicators = pd.unique(df['IndicatorName'])
    +    algorithms = pd.unique(df["Algorithm"])
    +    problems = pd.unique(df["Problem"])
    +    indicators = pd.unique(df["IndicatorName"])
     
         table = pd.DataFrame(index=algorithms[0:-1], columns=algorithms[1:])
     
    @@ -431,10 +459,16 @@ 

    Source code for jmetal.lab.experiment

     
                     if i <= j:
                         for problem in problems:
    -                        df1 = df[(df["Algorithm"] == row_algorithm) & (df["Problem"] == problem) & (
    -                                df["IndicatorName"] == indicator_name)]
    -                        df2 = df[(df["Algorithm"] == col_algorithm) & (df["Problem"] == problem) & (
    -                                df["IndicatorName"] == indicator_name)]
    +                        df1 = df[
    +                            (df["Algorithm"] == row_algorithm)
    +                            & (df["Problem"] == problem)
    +                            & (df["IndicatorName"] == indicator_name)
    +                            ]
    +                        df2 = df[
    +                            (df["Algorithm"] == col_algorithm)
    +                            & (df["Problem"] == problem)
    +                            & (df["IndicatorName"] == indicator_name)
    +                            ]
     
                             data1 = df1["IndicatorValue"]
                             data2 = df2["IndicatorValue"]
    @@ -447,49 +481,51 @@ 

    Source code for jmetal.lab.experiment

                             if p <= 0.05:
                                 if check_minimization(indicator_name):
                                     if median1 <= median2:
    -                                    line.append('+')
    +                                    line.append("+")
                                     else:
    -                                    line.append('o')
    +                                    line.append("o")
                                 else:
                                     if median1 >= median2:
    -                                    line.append('+')
    +                                    line.append("+")
                                     else:
    -                                    line.append('o')
    +                                    line.append("o")
                             else:
    -                            line.append('-')
    -                    wilcoxon.append(''.join(line))
    +                            line.append("-")
    +                    wilcoxon.append("".join(line))
     
    -            if len(wilcoxon) < len(algorithms): wilcoxon = [''] * (len(algorithms) - len(wilcoxon) - 1) + wilcoxon
    +            if len(wilcoxon) < len(algorithms):
    +                wilcoxon = [""] * (len(algorithms) - len(wilcoxon) - 1) + wilcoxon
                 table.loc[row_algorithm] = wilcoxon
     
    -        table.to_csv(os.path.join(output_dir, 'Wilcoxon-{}.csv'.format(indicator_name)), sep='\t', encoding='utf-8')
    +        table.to_csv(os.path.join(output_dir, "Wilcoxon-{}.csv".format(indicator_name)), sep="\t", encoding="utf-8")
     
    -        with open(os.path.join(output_dir, 'Wilcoxon-{}.tex'.format(indicator_name)), 'w') as latex:
    +        with open(os.path.join(output_dir, "Wilcoxon-{}.tex".format(indicator_name)), "w") as latex:
                 latex.write(
                     __wilcoxon_to_latex(
                         table,
    -                    caption='Wilcoxon values of the {} quality indicator ({}).'.format(indicator_name,
    -                                                                                       ', '.join(problems)),
    -                    label='table:{}'.format(indicator_name)
    +                    caption="Wilcoxon values of the {} quality indicator ({}).".format(
    +                        indicator_name, ", ".join(problems)
    +                    ),
    +                    label="table:{}".format(indicator_name),
                     )
                 )
     
     
     def compute_mean_indicator(filename: str, indicator_name: str):
    -    """ Compute the mean values of an indicator.
    +    """Compute the mean values of an indicator.
         :param filename:
         :param indicator_name: Quality indicator name.
         """
         df = pd.read_csv(filename, skipinitialspace=True)
     
         if len(set(df.columns.tolist())) != 5:
    -        raise Exception('Wrong number of columns')
    +        raise Exception("Wrong number of columns")
     
    -    algorithms = pd.unique(df['Algorithm'])
    -    problems = pd.unique(df['Problem'])
    +    algorithms = pd.unique(df["Algorithm"])
    +    problems = pd.unique(df["Problem"])
     
         # We consider the quality indicator indicator_name
    -    data = df[df['IndicatorName'] == indicator_name]
    +    data = df[df["IndicatorName"] == indicator_name]
     
         # Compute for each pair algorithm/problem the average of IndicatorValue
         average_values = np.zeros((problems.size, algorithms.size))
    @@ -497,8 +533,9 @@ 

    Source code for jmetal.lab.experiment

         for alg in algorithms:
             i = 0
             for pr in problems:
    -            average_values[i, j] = data['IndicatorValue'][np.logical_and(
    -                data['Algorithm'] == alg, data['Problem'] == pr)].mean()
    +            average_values[i, j] = data["IndicatorValue"][
    +                np.logical_and(data["Algorithm"] == alg, data["Problem"] == pr)
    +            ].mean()
                 i += 1
             j += 1
     
    @@ -509,9 +546,170 @@ 

    Source code for jmetal.lab.experiment

         return df
     
     
    -def __averages_to_latex(central_tendency: pd.DataFrame, dispersion: pd.DataFrame,
    -                        caption: str, label: str, minimization=True, alignment: str = 'c'):
    -    """ Convert a pandas DataFrame to a LaTeX tabular. Prints labels in bold and does use math mode.
    +
    +[docs] +def generate_median_and_wilcoxon_latex_tables(filename: str, output_dir: str = "latex/meansAndWilcoxon"): + """Generate Latex tables including medians and IQRs. Additionally, the last algorithm is considered as the reference + algorithm, and the cells include a symbol indicating whether the differences with the reference algorithm + are significant or not according to the Wilcoxon rank sum test. + + :param filename: Input filename (summary). + :param output_dir: Output path. + """ + data = pd.read_csv(filename, skipinitialspace=True) + + if len(set(data.columns.tolist())) != 5: + raise Exception("Wrong number of columns") + + if Path(output_dir).is_dir(): + logger.warning("Directory {} exists. Removing contents.".format(output_dir)) + for file in os.listdir(output_dir): + os.remove("{0}/{1}".format(output_dir, file)) + else: + logger.warning("Directory {} does not exist. Creating it.".format(output_dir)) + Path(output_dir).mkdir(parents=True) + + algorithms = pd.unique(data["Algorithm"]) + problems = pd.unique(data["Problem"]) + indicators = pd.unique(data["IndicatorName"]) + + control_algorithm = algorithms[-1] + + # Compute medians and IQRs + medians = data.groupby(["Algorithm", "Problem", "IndicatorName"])["IndicatorValue"].median() + iqrs = data.groupby(["Algorithm", "Problem", "IndicatorName"])["IndicatorValue"].apply(lambda x: iqr(x)) + + # Create data frame to store the Wilcoxon test results + wilcoxon_data = pd.DataFrame(columns=["Indicator", "Algorithm", "Problem", "PValue", "Median", "TestResult"]) + + for indicator in indicators: + for algorithm in algorithms: + for problem in problems: + algorithm_data = data[(data["Problem"] == problem) & (data["Algorithm"] == algorithm) & ( + data["IndicatorName"] == indicator)] + ref_data = data[(data["Problem"] == problem) & (data["Algorithm"] == control_algorithm) & ( + data["IndicatorName"] == indicator)] + stat, p_value = mannwhitneyu(algorithm_data["IndicatorValue"], ref_data["IndicatorValue"]) + + test_result = "" + if p_value <= 0.05: + if check_minimization(indicator): + if medians[algorithm][problem][indicator] <= medians[control_algorithm][problem][indicator]: + test_result = '+' + else: + test_result = '-' + else: + if medians[algorithm][problem][indicator] >= medians[control_algorithm][problem][indicator]: + test_result = '+' + else: + test_result = '-' + else: + test_result = '=' + + new_row = {'Indicator': indicator, 'Algorithm': algorithm, "Problem": problem, + "PValue": p_value, + "Median": medians[algorithm][problem][indicator], + "IQR": iqrs[algorithm][problem][indicator], + "TestResult": test_result + } + wilcoxon_data = wilcoxon_data._append(new_row, ignore_index=True) + + # Generate LaTeX tables + caption = "Median and interquartile range (IQR) of the results of the {} quality indicator. " + \ + "Cells with dark and light gray background highlights, respectively, the best and second best indicator values. " + \ + "The algorithm in the last column is the reference " + \ + "algorithm, and the symbols $+$, $-$ and $\\approx$ indicate that the differences with the reference " + \ + "algorithm are significantly better, worse, or there is no difference according to the Wilcoxon rank " + \ + "sum test (confidence level: 95\%)." + for indicator_name in indicators: + with open(os.path.join(output_dir, "MedianIQRWilcoxon-{}.tex".format(indicator_name)), "w") as latex: + latex.write( + __median_wilcoxon_to_latex( + indicator_name, + wilcoxon_data, + caption=caption.format(indicator_name), + label="table:{}".format(indicator_name), + ) + )
    + + + +
    +[docs] +def generate_kolmogorov_smirnov_latex_tables(filename: str, output_dir: str = "latex/KolmogorovSmirnov"): + """Generate Latex tables with the results of the Kolmogorov-Smirnov test. The last algorithm is considered as + the reference algorithm, and the cells include a symbol with the p-value < 0.05. + + :param filename: Input filename (summary). + :param output_dir: Output path. + """ + data = pd.read_csv(filename, skipinitialspace=True) + + if len(set(data.columns.tolist())) != 5: + raise Exception("Wrong number of columns") + + if Path(output_dir).is_dir(): + logger.warning("Directory {} exists. Removing contents.".format(output_dir)) + for file in os.listdir(output_dir): + os.remove("{0}/{1}".format(output_dir, file)) + else: + logger.warning("Directory {} does not exist. Creating it.".format(output_dir)) + Path(output_dir).mkdir(parents=True) + + algorithms = pd.unique(data["Algorithm"]) + problems = pd.unique(data["Problem"]) + indicators = pd.unique(data["IndicatorName"]) + + control_algorithm = algorithms[-1] + + # Create data frame to store the Kolmogorov Smirnov test results + test_data = pd.DataFrame(columns=["Indicator", "Algorithm", "Problem", "PValue", "TestResult"]) + + for indicator in indicators: + for algorithm in algorithms: + for problem in problems: + algorithm_data = data[(data["Problem"] == problem) & (data["Algorithm"] == algorithm) & ( + data["IndicatorName"] == indicator)] + ref_data = data[(data["Problem"] == problem) & (data["Algorithm"] == control_algorithm) & ( + data["IndicatorName"] == indicator)] + stat, p_value = ks_2samp(algorithm_data["IndicatorValue"], ref_data["IndicatorValue"]) + + test_result = stat + + new_row = {'Indicator': indicator, 'Algorithm': algorithm, "Problem": problem, + "PValue": p_value, + "TestResult": test_result + } + test_data = test_data._append(new_row, ignore_index=True) + + # Generate LaTeX tables + caption = "Kolmogorov-Smirnov Test of the {} quality indicator. " \ + "The algorithm in the last column is the reference " + \ + "algorithm and each cell contain the p-value obtained when applying the test with the reference " \ + "algorithm. Cells with gray background highlight p-values less than 0.05 (i.e., the null hypothesis" \ + " -- the two distributions are identical -- is rejected)." + for indicator_name in indicators: + with open(os.path.join(output_dir, "KolmogorovSmirnov-{}.tex".format(indicator_name)), "w") as latex: + latex.write( + __kolmogorov_smirnov_to_latex( + indicator_name, + test_data, + caption=caption.format(indicator_name), + label="table:{}".format(indicator_name), + ) + )
    + + + +def __averages_to_latex( + central_tendency: pd.DataFrame, + dispersion: pd.DataFrame, + caption: str, + label: str, + minimization=True, + alignment: str = "c", +): + """Convert a pandas DataFrame to a LaTeX tabular. Prints labels in bold and does use math mode. :param caption: LaTeX table caption. :param label: LaTeX table label. @@ -520,40 +718,40 @@

    Source code for jmetal.lab.experiment

         num_columns, num_rows = central_tendency.shape[1], central_tendency.shape[0]
         output = io.StringIO()
     
    -    col_format = '{}|{}'.format(alignment, alignment * num_columns)
    -    column_labels = ['\\textbf{{{0}}}'.format(label.replace('_', '\\_')) for label in central_tendency.columns]
    +    col_format = "{}|{}".format(alignment, alignment * num_columns)
    +    column_labels = ["\\textbf{{{0}}}".format(label.replace("_", "\\_")) for label in central_tendency.columns]
     
         # Write header
    -    output.write('\\documentclass{article}\n')
    +    output.write("\\documentclass{article}\n")
     
    -    output.write('\\usepackage[utf8]{inputenc}\n')
    -    output.write('\\usepackage{tabularx}\n')
    -    output.write('\\usepackage{colortbl}\n')
    -    output.write('\\usepackage[table*]{xcolor}\n')
    +    output.write("\\usepackage[utf8]{inputenc}\n")
    +    output.write("\\usepackage{tabularx}\n")
    +    output.write("\\usepackage{colortbl}\n")
    +    output.write("\\usepackage[table*]{xcolor}\n")
     
    -    output.write('\\xdefinecolor{gray95}{gray}{0.65}\n')
    -    output.write('\\xdefinecolor{gray25}{gray}{0.8}\n')
    +    output.write("\\xdefinecolor{gray95}{gray}{0.65}\n")
    +    output.write("\\xdefinecolor{gray25}{gray}{0.8}\n")
     
    -    output.write('\\title{Median and IQR}\n')
    -    output.write('\\author{}\n')
    +    output.write("\\title{Median and IQR}\n")
    +    output.write("\\author{}\n")
     
    -    output.write('\\begin{document}\n')
    -    output.write('\\maketitle\n')
    +    output.write("\\begin{document}\n")
    +    output.write("\\maketitle\n")
     
    -    output.write('\\section{Table}\n')
    +    output.write("\\section{Table}\n")
     
    -    output.write('\\begin{table}[!htp]\n')
    -    output.write('  \\caption{{{}}}\n'.format(caption))
    -    output.write('  \\label{{{}}}\n'.format(label))
    -    output.write('  \\centering\n')
    -    output.write('  \\begin{scriptsize}\n')
    -    output.write('  \\begin{tabular}{%s}\n' % col_format)
    -    output.write('      & {} \\\\\\hline\n'.format(' & '.join(column_labels)))
    +    output.write("\\begin{table}[!htp]\n")
    +    output.write("  \\caption{{{}}}\n".format(caption))
    +    output.write("  \\label{{{}}}\n".format(label))
    +    output.write("  \\centering\n")
    +    output.write("  \\begin{scriptsize}\n")
    +    output.write("  \\begin{tabular}{%s}\n" % col_format)
    +    output.write("      & {} \\\\\\hline\n".format(" & ".join(column_labels)))
     
         # Write data lines
         for i in range(num_rows):
    -        central_values = [v for v in central_tendency.ix[i]]
    -        dispersion_values = [v for v in dispersion.ix[i]]
    +        central_values = [v for v in central_tendency.iloc[i]]
    +        dispersion_values = [v for v in dispersion.iloc[i]]
     
             # Sort mean/median values (the lower the better if minimization)
             # Note that mean/median values could be the same: in that case, sort by Std/IQR (the lower the better)
    @@ -567,29 +765,32 @@ 

    Source code for jmetal.lab.experiment

                 second_best, best = sorted_values[-1][2], sorted_values[-2][2]
     
             # Compose cell
    -        values = ['{:.2e}_{{{:.2e}}}'.format(central_values[i], dispersion_values[i]) for i in
    -                  range(len(central_values))]
    +        values = [
    +            "{:.2e}_{{{:.2e}}}".format(central_values[i], dispersion_values[i]) for i in range(len(central_values))
    +        ]
     
             # Highlight values
    -        values[best] = '\\cellcolor{gray25} ' + values[best]
    -        values[second_best] = '\\cellcolor{gray95} ' + values[second_best]
    +        values[best] = "\\cellcolor{gray25} " + values[best]
    +        values[second_best] = "\\cellcolor{gray95} " + values[second_best]
     
    -        output.write('      \\textbf{{{0}}} & ${1}$ \\\\\n'.format(
    -            central_tendency.index[i], ' $ & $ '.join([str(val) for val in values]))
    +        output.write(
    +            "      \\textbf{{{0}}} & ${1}$ \\\\\n".format(
    +                central_tendency.index[i], " $ & $ ".join([str(val) for val in values])
    +            )
             )
     
         # Write footer
    -    output.write('  \\end{tabular}\n')
    -    output.write('  \\end{scriptsize}\n')
    -    output.write('\\end{table}\n')
    +    output.write("  \\end{tabular}\n")
    +    output.write("  \\end{scriptsize}\n")
    +    output.write("\\end{table}\n")
     
    -    output.write('\\end{document}')
    +    output.write("\\end{document}")
     
         return output.getvalue()
     
     
    -def __wilcoxon_to_latex(df: pd.DataFrame, caption: str, label: str, minimization=True, alignment: str = 'c'):
    -    """ Convert a pandas DataFrame to a LaTeX tabular. Prints labels in bold and does use math mode.
    +def __wilcoxon_to_latex(df: pd.DataFrame, caption: str, label: str, minimization=True, alignment: str = "c"):
    +    """Convert a pandas DataFrame to a LaTeX tabular. Prints labels in bold and does use math mode.
     
         :param df: Pandas dataframe.
         :param caption: LaTeX table caption.
    @@ -599,58 +800,242 @@ 

    Source code for jmetal.lab.experiment

         num_columns, num_rows = df.shape[1], df.shape[0]
         output = io.StringIO()
     
    -    col_format = '{}|{}'.format(alignment, alignment * num_columns)
    -    column_labels = ['\\textbf{{{0}}}'.format(label.replace('_', '\\_')) for label in df.columns]
    +    col_format = "{}|{}".format(alignment, alignment * num_columns)
    +    column_labels = ["\\textbf{{{0}}}".format(label.replace("_", "\\_")) for label in df.columns]
     
         # Write header
    -    output.write('\\documentclass{article}\n')
    +    output.write("\\documentclass{article}\n")
     
    -    output.write('\\usepackage[utf8]{inputenc}\n')
    -    output.write('\\usepackage{tabularx}\n')
    -    output.write('\\usepackage{amssymb}\n')
    -    output.write('\\usepackage{amsmath}\n')
    +    output.write("\\usepackage[utf8]{inputenc}\n")
    +    output.write("\\usepackage{tabularx}\n")
    +    output.write("\\usepackage{amssymb}\n")
    +    output.write("\\usepackage{amsmath}\n")
     
    -    output.write('\\title{Wilcoxon - Mann-Whitney rank sum test}\n')
    -    output.write('\\author{}\n')
    +    output.write("\\title{Wilcoxon - Mann-Whitney rank sum test}\n")
    +    output.write("\\author{}\n")
     
    -    output.write('\\begin{document}\n')
    -    output.write('\\maketitle\n')
    +    output.write("\\begin{document}\n")
    +    output.write("\\maketitle\n")
     
    -    output.write('\\section{Table}\n')
    +    output.write("\\section{Table}\n")
     
    -    output.write('\\begin{table}[!htp]\n')
    -    output.write('  \\caption{{{}}}\n'.format(caption))
    -    output.write('  \\label{{{}}}\n'.format(label))
    -    output.write('  \\centering\n')
    -    output.write('  \\begin{scriptsize}\n')
    -    output.write('  \\begin{tabular}{%s}\n' % col_format)
    -    output.write('      & {} \\\\\\hline\n'.format(' & '.join(column_labels)))
    +    output.write("\\begin{table}[!htp]\n")
    +    output.write("  \\caption{{{}}}\n".format(caption))
    +    output.write("  \\label{{{}}}\n".format(label))
    +    output.write("  \\centering\n")
    +    output.write("  \\begin{scriptsize}\n")
    +    output.write("  \\begin{tabular}{%s}\n" % col_format)
    +    output.write("      & {} \\\\\\hline\n".format(" & ".join(column_labels)))
     
    -    symbolo = '\\triangledown\ '
    -    symbolplus = '\\blacktriangle\ '
    +    symbolo = "\\triangledown\ "
    +    symbolplus = "\\blacktriangle\ "
     
         if not minimization:
             symbolo, symbolplus = symbolplus, symbolo
     
         # Write data lines
         for i in range(num_rows):
    -        values = [val.replace('-', '\\text{--}\ ').replace('o', symbolo).replace('+', symbolplus) for val in df.ix[i]]
    -        output.write('      \\textbf{{{0}}} & ${1}$ \\\\\n'.format(
    -            df.index[i], ' $ & $ '.join([str(val) for val in values]))
    +        values = [val.replace("-", "\\text{--}\ ").replace("o", symbolo).replace("+", symbolplus) for val in df.iloc[i]]
    +        output.write(
    +            "      \\textbf{{{0}}} & ${1}$ \\\\\n".format(df.index[i], " $ & $ ".join([str(val) for val in values]))
    +        )
    +
    +    # Write footer
    +    output.write("  \\end{tabular}\n")
    +    output.write("  \\end{scriptsize}\n")
    +    output.write("\\end{table}\n")
    +
    +    output.write("\\end{document}")
    +
    +    return output.getvalue()
    +
    +
    +def __median_wilcoxon_to_latex(
    +        indicator_name: str,
    +        wilcoxon_data: pd.DataFrame,
    +        caption: str,
    +        label):
    +    indicator_data = wilcoxon_data[wilcoxon_data["Indicator"] == indicator_name]
    +
    +    problems = pd.unique(indicator_data["Problem"])
    +    algorithms = pd.unique(indicator_data["Algorithm"])
    +
    +    num_columns = len(algorithms)
    +    columns = algorithms
    +
    +    alignment = "c"
    +    col_format = "{}|{}".format(alignment, alignment * num_columns)
    +    column_labels = ["\\textbf{{{0}}}".format(label.replace("_", "\\_")) for label in columns]
    +
    +    output = io.StringIO()
    +
    +    output.write("\\documentclass{article}\n")
    +
    +    output.write("\\usepackage[utf8]{inputenc}\n")
    +    output.write("\\usepackage{tabularx}\n")
    +    output.write("\\usepackage{colortbl}\n")
    +    output.write("\\usepackage[table*]{xcolor}\n")
    +
    +    output.write("\\xdefinecolor{gray95}{gray}{0.65}\n")
    +    output.write("\\xdefinecolor{gray25}{gray}{0.8}\n")
    +
    +    output.write("\\title{Median and Wilcoxon}\n")
    +    output.write("\\author{}\n")
    +
    +    output.write("\\begin{document}\n")
    +    output.write("\\maketitle\n")
    +
    +    output.write("\\section{Table}\n")
    +
    +    output.write("\\begin{table}[!htp]\n")
    +    output.write("  \\caption{{{}}}\n".format(caption))
    +    output.write("  \\label{{{}}}\n".format(label))
    +    output.write("  \\centering\n")
    +    output.write("  \\begin{tiny}\n")
    +    output.write("  \\begin{tabular}{%s}\n" % col_format)
    +    output.write("      & {} \\\\\\hline\n".format(" & ".join(column_labels)))
    +
    +    # Counts the number of times that an algorithm performs better, worse or equal than the reference algorithm
    +    counters = {}
    +    for algorithm in algorithms:
    +        counters[algorithm] = [0, 0, 0]  # best, equal, worse
    +
    +    for problem in problems:
    +        values = []
    +
    +        for algorithm in algorithms:
    +            row = indicator_data[(indicator_data["Problem"] == problem) & (indicator_data["Algorithm"] == algorithm)]
    +            value = "{:.2e}({:.2e})".format(row["Median"].tolist()[0], row["IQR"].tolist()[0])
    +
    +            # Include the symbol according to the Wilcoxon rank sum test with the reference algorithm
    +            if algorithm != algorithms[-1]:
    +                if row["TestResult"].tolist()[0] == "-":
    +                    value = "{{{}-}}".format(value)
    +                    counters[algorithm][2] = counters[algorithm][2] + 1
    +                elif row["TestResult"].tolist()[0] == "+":
    +                    value = "{{{}+}}".format(value)
    +                    counters[algorithm][0] = counters[algorithm][0] + 1
    +                else:
    +                    value = "{{{}\\approx}}".format(value)
    +                    counters[algorithm][1] = counters[algorithm][1] + 1
    +            values.append(value)
    +
    +        # Find the best and second best values
    +        medians = indicator_data[(indicator_data["Problem"] == problem)]["Median"]
    +        iqrs = indicator_data[(indicator_data["Problem"] == problem)]["IQR"]
    +        pairs = list(zip(medians, iqrs))
    +        indexes = sorted(range(len(pairs)), key=lambda x: pairs[x])
    +
    +        if check_minimization(indicator_name):
    +            best = indexes[0]
    +            second_best = indexes[1]
    +        else:
    +            best = indexes[-1]
    +            second_best = indexes[-2]
    +
    +        values[best] = "\\cellcolor{gray95} " + values[best]
    +        values[second_best] = "\\cellcolor{gray25} " + values[second_best]
    +
    +        output.write(
    +            "\\textbf{{{0}}} & ${1}$ \\\\\n".format(problem, " $ & $ ".join(
    +                [str(val).replace("e-", "e\makebox[0.1cm]{-}").replace("e+", "e\makebox[0.1cm]{+}") for val in values])
    +                                                    )
             )
     
    +    # Select all but the last counter
    +    counter_summary = []
    +    for algorithm in algorithms[:-1]:
    +        counter_summary.append(counters[algorithm])
    +
    +    output.write("  \\hline\n")
    +    output.write(
    +        "\\textbf{{{0}}} & ${1}$ \\\\\n".format("$+/\\approx/-$", " $ & $ ".join(
    +            [str(val[0]) + "/" + str(val[1]) + "/" + str(val[2]) for val in counter_summary])))
    +
    +    # Write footer
    +    output.write("  \\end{tabular}\n")
    +    output.write("  \\end{tiny}\n")
    +    output.write("\\end{table}\n")
    +
    +    output.write("\\end{document}")
    +
    +    return output.getvalue()
    +
    +
    +def __kolmogorov_smirnov_to_latex(indicator_name: str, test_data: pd.DataFrame, caption: str, label: str):
    +    indicator_data = test_data[test_data["Indicator"] == indicator_name]
    +
    +    problems = pd.unique(indicator_data["Problem"])
    +    algorithms = pd.unique(indicator_data["Algorithm"])
    +
    +    num_columns = len(algorithms)
    +    columns = algorithms
    +
    +    alignment = "c"
    +    col_format = "{}|{}".format(alignment, alignment * num_columns)
    +    column_labels = ["\\textbf{{{0}}}".format(label.replace("_", "\\_")) for label in columns]
    +
    +    output = io.StringIO()
    +
    +    output.write("\\documentclass{article}\n")
    +
    +    output.write("\\usepackage[utf8]{inputenc}\n")
    +    output.write("\\usepackage{tabularx}\n")
    +    output.write("\\usepackage{colortbl}\n")
    +    output.write("\\usepackage[table*]{xcolor}\n")
    +
    +    output.write("\\xdefinecolor{gray95}{gray}{0.65}\n")
    +    output.write("\\xdefinecolor{gray25}{gray}{0.8}\n")
    +
    +    output.write("\\title{Kolmogorov-Smirnov Test}\n")
    +    output.write("\\author{}\n")
    +
    +    output.write("\\begin{document}\n")
    +    output.write("\\maketitle\n")
    +
    +    output.write("\\section{Table}\n")
    +
    +    output.write("\\begin{table}[!htp]\n")
    +    output.write("  \\caption{{{}}}\n".format(caption))
    +    output.write("  \\label{{{}}}\n".format(label))
    +    output.write("  \\centering\n")
    +    output.write("  \\begin{tiny}\n")
    +    output.write("  \\begin{tabular}{%s}\n" % col_format)
    +    output.write("      & {} \\\\\\hline\n".format(" & ".join(column_labels)))
    +
    +    for problem in problems:
    +        values = []
    +
    +        for algorithm in algorithms[:-1]:
    +            row = indicator_data[(indicator_data["Problem"] == problem) & (indicator_data["Algorithm"] == algorithm)]
    +            value = "{:.2e}".format(row["PValue"].tolist()[0])
    +
    +            if (row["PValue"].tolist()[0] < 0.05):
    +                value = "\\cellcolor{gray25} " + value
    +
    +            values.append(value)
    +        values.append("-")
    +
    +        output.write(
    +            "\\textbf{{{0}}} & ${1}$ \\\\\n".format(problem, " $ & $ ".join(
    +                [str(val).replace("e-", "e\makebox[0.1cm]{-}").replace("e+", "e\makebox[0.1cm]{+}") for val in values])
    +                                                    )
    +        )
    +
    +    output.write("  \\hline\n")
    +
         # Write footer
    -    output.write('  \\end{tabular}\n')
    -    output.write('  \\end{scriptsize}\n')
    -    output.write('\\end{table}\n')
    +    output.write("  \\end{tabular}\n")
    +    output.write("  \\end{tiny}\n")
    +    output.write("\\end{table}\n")
     
    -    output.write('\\end{document}')
    +    output.write("\\end{document}")
     
         return output.getvalue()
     
     
     def check_minimization(indicator) -> bool:
    -    if indicator == 'HV':
    +    if indicator == "HV":
             return False
         else:
             return True
    @@ -670,8 +1055,9 @@ 

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.statistical_test.apv_procedures — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -113,8 +110,10 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    import pandas as pd -
    [docs]def bonferroni_dunn(p_values, control): - """ +
    +[docs] +def bonferroni_dunn(p_values, control): + """ Bonferroni-Dunn's procedure for the adjusted p-value computation. Parameters: @@ -132,14 +131,12 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if type(control) == str: control = int(np.where(algorithms == control)[0]) if control is None: - raise ValueError( - 'Initialization ERROR. Incorrect value for control.') + raise ValueError("Initialization ERROR. Incorrect value for control.") k = p_values.shape[1] @@ -149,14 +146,16 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    APVs = np.zeros((k - 1, 1)) comparison = [] for i in range(k - 1): - comparison.append(algorithms[control] + - ' vs ' + algorithms[argsorted_pvals[i]]) + comparison.append(algorithms[control] + " vs " + algorithms[argsorted_pvals[i]]) APVs[i, 0] = np.min([(k - 1) * p_values[0, argsorted_pvals[i]], 1]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Bonferroni'])
    + return pd.DataFrame(data=APVs, index=comparison, columns=["Bonferroni"])
    + -
    [docs]def holland(p_values, control): - """ +
    +[docs] +def holland(p_values, control): + """ Holland's procedure for the adjusted p-value computation. Parameters: @@ -174,14 +173,12 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if type(control) == str: control = int(np.where(algorithms == control)[0]) if control is None: - raise ValueError( - 'Initialization ERROR. Incorrect value for control.') + raise ValueError("Initialization ERROR. Incorrect value for control.") # -------------------------------------------------------------------------- # ------------------------------- Procedure -------------------------------- @@ -194,16 +191,18 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    APVs = np.zeros((k - 1, 1)) comparison = [] for i in range(k - 1): - comparison.append(algorithms[control] + - ' vs ' + algorithms[argsorted_pvals[i]]) + comparison.append(algorithms[control] + " vs " + algorithms[argsorted_pvals[i]]) aux = k - 1 - np.arange(i + 1) - v = np.max(1 - (1 - p_values[0, argsorted_pvals[:(i + 1)]]) ** aux) + v = np.max(1 - (1 - p_values[0, argsorted_pvals[: (i + 1)]]) ** aux) APVs[i, 0] = np.min([v, 1]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Holland'])
    + return pd.DataFrame(data=APVs, index=comparison, columns=["Holland"])
    + -
    [docs]def finner(p_values, control): - """ +
    +[docs] +def finner(p_values, control): + """ Finner's procedure for the adjusted p-value computation. Parameters: @@ -221,14 +220,12 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if type(control) == str: control = int(np.where(algorithms == control)[0]) if control is None: - raise ValueError( - 'Initialization ERROR. Incorrect value for control.') + raise ValueError("Initialization ERROR. Incorrect value for control.") k = p_values.shape[1] @@ -238,16 +235,18 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    APVs = np.zeros((k - 1, 1)) comparison = [] for i in range(k - 1): - comparison.append(algorithms[control] + - ' vs ' + algorithms[argsorted_pvals[i]]) + comparison.append(algorithms[control] + " vs " + algorithms[argsorted_pvals[i]]) aux = float(k - 1) / (np.arange(i + 1) + 1) - v = np.max(1 - (1 - p_values[0, argsorted_pvals[:(i + 1)]]) ** aux) + v = np.max(1 - (1 - p_values[0, argsorted_pvals[: (i + 1)]]) ** aux) APVs[i, 0] = np.min([v, 1]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Finner'])
    + return pd.DataFrame(data=APVs, index=comparison, columns=["Finner"])
    -
    [docs]def hochberg(p_values, control): - """ + +
    +[docs] +def hochberg(p_values, control): + """ Hochberg's procedure for the adjusted p-value computation. Parameters: @@ -265,14 +264,12 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if type(control) == str: control = int(np.where(algorithms == control)[0]) if control is None: - raise ValueError( - 'Initialization ERROR. Incorrect value for control.') + raise ValueError("Initialization ERROR. Incorrect value for control.") k = p_values.shape[1] @@ -282,16 +279,18 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    APVs = np.zeros((k - 1, 1)) comparison = [] for i in range(k - 1): - comparison.append(algorithms[control] + - ' vs ' + algorithms[argsorted_pvals[i]]) + comparison.append(algorithms[control] + " vs " + algorithms[argsorted_pvals[i]]) aux = np.arange(k, i, -1).astype(np.uint8) v = np.max(p_values[0, argsorted_pvals[aux - 1]] * (k - aux)) APVs[i, 0] = np.min([v, 1]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Hochberg'])
    + return pd.DataFrame(data=APVs, index=comparison, columns=["Hochberg"])
    + -
    [docs]def li(p_values, control): - """ +
    +[docs] +def li(p_values, control): + """ Li's procedure for the adjusted p-value computation. Parameters: @@ -311,14 +310,12 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if type(control) == str: control = int(np.where(algorithms == control)[0]) if control is None: - raise ValueError( - 'Initialization ERROR. Incorrect value for control.') + raise ValueError("Initialization ERROR. Incorrect value for control.") k = p_values.shape[1] @@ -328,15 +325,22 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    APVs = np.zeros((k - 1, 1)) comparison = [] for i in range(k - 1): - comparison.append(algorithms[control] + - ' vs ' + algorithms[argsorted_pvals[i]]) - APVs[i, 0] = np.min([p_values[0, argsorted_pvals[-2]], p_values[0, argsorted_pvals[i]] / ( - p_values[0, argsorted_pvals[i]] + 1 - p_values[0, argsorted_pvals[-2]])]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Li'])
    - - -
    [docs]def holm(p_values, control=None): - """ + comparison.append(algorithms[control] + " vs " + algorithms[argsorted_pvals[i]]) + APVs[i, 0] = np.min( + [ + p_values[0, argsorted_pvals[-2]], + p_values[0, argsorted_pvals[i]] + / (p_values[0, argsorted_pvals[i]] + 1 - p_values[0, argsorted_pvals[-2]]), + ] + ) + return pd.DataFrame(data=APVs, index=comparison, columns=["Li"])
    + + + +
    +[docs] +def holm(p_values, control=None): + """ Holm's procedure for the adjusted p-value computation. Parameters: @@ -356,8 +360,7 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if type(control) == str: control = int(np.where(algorithms == control)[0]) @@ -372,9 +375,8 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    comparison = [] for i in range(k - 1): aux = k - 1 - np.arange(i + 1) - comparison.append( - algorithms[control] + ' vs ' + algorithms[argsorted_pvals[i]]) - v = np.max(aux * p_values[0, argsorted_pvals[:(i + 1)]]) + comparison.append(algorithms[control] + " vs " + algorithms[argsorted_pvals[i]]) + v = np.max(aux * p_values[0, argsorted_pvals[: (i + 1)]]) APVs[i, 0] = np.min([v, 1]) elif control is None: @@ -392,14 +394,17 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    for i in range(m): row = pairs_index[0][pairs_sorted[i]] col = pairs_index[1][pairs_sorted[i]] - comparison.append(algorithms[row] + ' vs ' + algorithms[col]) - v = np.max(aux[:i + 1]) + comparison.append(algorithms[row] + " vs " + algorithms[col]) + v = np.max(aux[: i + 1]) APVs[i, 0] = np.min([v, 1]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Holm'])
    + return pd.DataFrame(data=APVs, index=comparison, columns=["Holm"])
    + -
    [docs]def shaffer(p_values): - """ +
    +[docs] +def shaffer(p_values): + """ Shaffer's procedure for adjusted p_value ccmputation. Parameters: @@ -412,7 +417,7 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    """ def S(k): - """ + """ Computes the set of possible numbers of true hoypotheses. Parameters: @@ -431,8 +436,7 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    TrueHset = [0] if k > 1: for j in np.arange(k, 0, -1, dtype=int): - TrueHset = list(set(TrueHset) | set( - [binomial(j, 2) + x for x in S(k - j)])) + TrueHset = list(set(TrueHset) | set([binomial(j, 2) + x for x in S(k - j)])) return TrueHset # Initial Checking @@ -440,15 +444,12 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if p_values.ndim != 2: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions.') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions.") elif p_values.shape[0] != p_values.shape[1]: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions.') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions.") # define parameters k = p_values.shape[0] @@ -467,19 +468,22 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    # Adjust p-values APVs = np.zeros((m, 1)) - aux = (pairs_pvals[pairs_sorted] * t) + aux = pairs_pvals[pairs_sorted] * t comparison = [] for i in range(m): row = pairs_index[0][pairs_sorted[i]] col = pairs_index[1][pairs_sorted[i]] - comparison.append(algorithms[row] + ' vs ' + algorithms[col]) - v = np.max(aux[:i + 1]) + comparison.append(algorithms[row] + " vs " + algorithms[col]) + v = np.max(aux[: i + 1]) APVs[i, 0] = np.min([v, 1]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Shaffer'])
    + return pd.DataFrame(data=APVs, index=comparison, columns=["Shaffer"])
    -
    [docs]def nemenyi(p_values): - """ + +
    +[docs] +def nemenyi(p_values): + """ Nemenyi's procedure for adjusted p_value computation. Parameters: @@ -496,15 +500,12 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    algorithms = p_values.columns p_values = p_values.values elif type(p_values) == np.ndarray: - algorithms = np.array( - ['Alg%d' % alg for alg in range(p_values.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(p_values.shape[1])]) if p_values.ndim != 2: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions.') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions.") elif p_values.shape[0] != p_values.shape[1]: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions.') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions.") # define parameters k = p_values.shape[0] @@ -521,9 +522,10 @@

    Source code for jmetal.lab.statistical_test.apv_procedures

    for i in range(m): row = pairs_index[0][pairs_sorted[i]] col = pairs_index[1][pairs_sorted[i]] - comparison.append(algorithms[row] + ' vs ' + algorithms[col]) + comparison.append(algorithms[row] + " vs " + algorithms[col]) APVs[i, 0] = np.min([pairs_pvals[pairs_sorted[i]] * m, 1]) - return pd.DataFrame(data=APVs, index=comparison, columns=['Nemenyi'])
    + return pd.DataFrame(data=APVs, index=comparison, columns=["Nemenyi"])
    +
    @@ -540,8 +542,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.statistical_test.bayesian — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -113,9 +110,12 @@

    Source code for jmetal.lab.statistical_test.bayesian

    import pandas as pd -
    [docs]def bayesian_sign_test(data, rope_limits=[-0.01, 0.01], prior_strength=0.5, prior_place='rope', sample_size=50000, - return_sample=False): - """ Bayesian version of the sign test. +
    +[docs] +def bayesian_sign_test( + data, rope_limits=[-0.01, 0.01], prior_strength=0.5, prior_place="rope", sample_size=50000, return_sample=False +): + """Bayesian version of the sign test. :param data: An (n x 2) array or DataFrame contaning the results. In data, each column represents an algorithm and, and each row a problem. :param rope_limits: array_like. Default [-0.01, 0.01]. Limits of the practical equivalence. @@ -138,16 +138,13 @@

    Source code for jmetal.lab.statistical_test.bayesian

    sample1, sample2 = data[:, 0], data[:, 1] n = data.shape[0] else: - raise ValueError( - 'Initialization ERROR. Incorrect number of dimensions for axis 1') + raise ValueError("Initialization ERROR. Incorrect number of dimensions for axis 1") if prior_strength <= 0: - raise ValueError( - 'Initialization ERROR. prior_strength mustb be a positive float') + raise ValueError("Initialization ERROR. prior_strength mustb be a positive float") - if prior_place not in ['left', 'rope', 'right']: - raise ValueError( - 'Initialization ERROR. Incorrect value fro prior_place') + if prior_place not in ["left", "rope", "right"]: + raise ValueError("Initialization ERROR. Incorrect value fro prior_place") # Compute the differences Z = sample1 - sample2 @@ -164,7 +161,7 @@

    Source code for jmetal.lab.statistical_test.bayesian

    # Parameters of the Dirichlet distribution alpha = np.array([Nleft, Nequiv, Nright], dtype=float) + 1e-6 - alpha[['left', 'rope', 'right'].index(prior_place)] += prior_strength + alpha[["left", "rope", "right"].index(prior_place)] += prior_strength # Simulate dirichlet process Dprocess = np.random.dirichlet(alpha, sample_size) @@ -180,10 +177,13 @@

    Source code for jmetal.lab.statistical_test.bayesian

    return np.array([win_left, win_rope, win_rifht]) / float(sample_size)
    -
    [docs]def bayesian_signed_rank_test(data, rope_limits=[-0.01, 0.01], prior_strength=1.0, prior_place='rope', - sample_size=10000, - return_sample=False): - """ Bayesian version of the signed rank test. + +
    +[docs] +def bayesian_signed_rank_test( + data, rope_limits=[-0.01, 0.01], prior_strength=1.0, prior_place="rope", sample_size=10000, return_sample=False +): + """Bayesian version of the signed rank test. :param data: An (n x 2) array or DataFrame contaning the results. In data, each column represents an algorithm and, and each row a problem. :param rope_limits: array_like. Default [-0.01, 0.01]. Limits of the practical equivalence. @@ -209,21 +209,17 @@

    Source code for jmetal.lab.statistical_test.bayesian

    sample1, sample2 = data[:, 0], data[:, 1] n = data.shape[0] else: - raise ValueError( - 'Initialization ERROR. Incorrect number of dimensions for axis 1') + raise ValueError("Initialization ERROR. Incorrect number of dimensions for axis 1") if prior_strength <= 0: - raise ValueError( - 'Initialization ERROR. prior_strength must be a positive float') + raise ValueError("Initialization ERROR. prior_strength must be a positive float") - if prior_place not in ['left', 'rope', 'right']: - raise ValueError( - 'Initialization ERROR. Incorrect value for prior_place') + if prior_place not in ["left", "rope", "right"]: + raise ValueError("Initialization ERROR. Incorrect value for prior_place") # Compute the differences Z = sample1 - sample2 - Z0 = [-float('Inf'), 0.0, float('Inf')][['left', - 'rope', 'right'].index(prior_place)] + Z0 = [-float("Inf"), 0.0, float("Inf")][["left", "rope", "right"].index(prior_place)] Z = np.concatenate(([Z0], Z), axis=None) # compute the the probabilities that the mean difference of accuracy is in @@ -253,6 +249,7 @@

    Source code for jmetal.lab.statistical_test.bayesian

    return np.array([win_left, win_rope, win_rifht]) / float(sample_size), Dprocess else: return np.array([win_left, win_rope, win_rifht]) / float(sample_size)
    +
    @@ -269,8 +266,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.statistical_test.critical_distance — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -117,8 +114,10 @@

    Source code for jmetal.lab.statistical_test.critical_distance

    from jmetal.lab.statistical_test.functions import ranks -
    [docs]def NemenyiCD(alpha: float, num_alg, num_dataset): - """ Computes Nemenyi's critical difference: +
    +[docs] +def NemenyiCD(alpha: float, num_alg, num_dataset): + """Computes Nemenyi's critical difference: * CD = q_alpha * sqrt(num_alg*(num_alg + 1)/(6*num_prob)) where q_alpha is the critical value, of the Studentized range statistic divided by sqrt(2). :param alpha: {0.1, 0.999}. Significance level. @@ -135,8 +134,17 @@

    Source code for jmetal.lab.statistical_test.critical_distance

    return cd
    -
    [docs]def CDplot(results, alpha: float = 0.05, higher_is_better: bool=False, alg_names: list = None, output_filename: str = 'cdplot.eps'): - """ CDgraph plots the critical difference graph show in Janez Demsar's 2006 work: + +
    +[docs] +def CDplot( + results, + alpha: float = 0.05, + higher_is_better: bool = False, + alg_names: list = None, + output_filename: str = "cdplot.eps", +): + """CDgraph plots the critical difference graph show in Janez Demsar's 2006 work: * Statistical Comparisons of Classifiers over Multiple Data Sets. :param results: A 2-D array containing results from each algorithm. Each row of 'results' represents an algorithm, and each column a dataset. :param alpha: {0.1, 0.999}. Significance level for the critical difference. @@ -144,15 +152,14 @@

    Source code for jmetal.lab.statistical_test.critical_distance

    """ def _join_alg(avranks, num_alg, cd): - """ + """ join_alg returns the set of non significant methods """ # get all pairs sets = (-1) * np.ones((num_alg, 2)) for i in range(num_alg): - elements = np.where(np.logical_and( - avranks - avranks[i] > 0, avranks - avranks[i] < cd))[0] + elements = np.where(np.logical_and(avranks - avranks[i] > 0, avranks - avranks[i] < cd))[0] if elements.size > 0: sets[i, :] = [avranks[i], avranks[elements[-1]]] sets = np.delete(sets, np.where(sets[:, 0] < 0)[0], axis=0) @@ -170,14 +177,12 @@

    Source code for jmetal.lab.statistical_test.critical_distance

    alg_names = results.index results = results.values elif type(results) == np.ndarray and alg_names is None: - alg_names = np.array( - ['Alg%d' % alg for alg in range(results.shape[1])]) + alg_names = np.array(["Alg%d" % alg for alg in range(results.shape[1])]) if results.ndim == 2: num_alg, num_dataset = results.shape else: - raise ValueError( - 'Initialization ERROR: In CDplot(...) results must be 2-D array') + raise ValueError("Initialization ERROR: In CDplot(...) results must be 2-D array") # Get the critical difference cd = NemenyiCD(alpha, num_alg, num_dataset) @@ -201,9 +206,9 @@

    Source code for jmetal.lab.statistical_test.critical_distance

    highest = np.ceil(np.max(avranks)).astype(np.uint8) # highest shown rank lowest = np.floor(np.min(avranks)).astype(np.uint8) # lowest shown rank width = 6 # default figure width (in inches) - height = (0.575 * (rows + 1)) # figure height + height = 0.575 * (rows + 1) # figure height - """ + """ FIGURE (1,0) +-----+---------------------------+-------+ @@ -229,60 +234,79 @@

    Source code for jmetal.lab.statistical_test.critical_distance

    lline = sright - sleft # Initialize figure - fig = plt.figure(figsize=(width, height), facecolor='white') + fig = plt.figure(figsize=(width, height), facecolor="white") ax = fig.add_axes([0, 0, 1, 1]) ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_axis_off() # Main horizontal axis - ax.hlines(stop, sleft, sright, color='black', linewidth=0.7) + ax.hlines(stop, sleft, sright, color="black", linewidth=0.7) for xi in range(highest - lowest + 1): # Plot mayor ticks - ax.vlines(x=sleft + (lline * xi) / (highest - lowest), - ymin=stop, ymax=stop + 0.05, color='black', linewidth=0.7) + ax.vlines( + x=sleft + (lline * xi) / (highest - lowest), ymin=stop, ymax=stop + 0.05, color="black", linewidth=0.7 + ) # Mayor ticks labels - ax.text(x=sleft + (lline * xi) / (highest - lowest), - y=stop + 0.06, - s=str(lowest + xi), ha='center', va='bottom') + ax.text( + x=sleft + (lline * xi) / (highest - lowest), y=stop + 0.06, s=str(lowest + xi), ha="center", va="bottom" + ) # Minor ticks if xi < highest - lowest: - ax.vlines(x=sleft + (lline * (xi + 0.5)) / (highest - lowest), - ymin=stop, ymax=stop + 0.025, color='black', linewidth=0.7) + ax.vlines( + x=sleft + (lline * (xi + 0.5)) / (highest - lowest), + ymin=stop, + ymax=stop + 0.025, + color="black", + linewidth=0.7, + ) # Plot lines/names for left models vspace = 0.5 * (stop - sbottom) / (spoint + 1) for i in range(spoint): - ax.vlines(x=sleft + (lline * (leftalg[i] - lowest)) / (highest - lowest), - ymin=sbottom + (spoint - 1 - i) * vspace, ymax=stop, color='black', linewidth=0.7) - ax.hlines(y=sbottom + (spoint - 1 - i) * vspace, xmin=sleft, - xmax=sleft + - (lline * (leftalg[i] - lowest)) / (highest - lowest), - color='black', linewidth=0.7) - ax.text(x=sleft - 0.01, y=sbottom + (spoint - 1 - i) * vspace, - s=alg_names[indices][i], ha='right', va='center') + ax.vlines( + x=sleft + (lline * (leftalg[i] - lowest)) / (highest - lowest), + ymin=sbottom + (spoint - 1 - i) * vspace, + ymax=stop, + color="black", + linewidth=0.7, + ) + ax.hlines( + y=sbottom + (spoint - 1 - i) * vspace, + xmin=sleft, + xmax=sleft + (lline * (leftalg[i] - lowest)) / (highest - lowest), + color="black", + linewidth=0.7, + ) + ax.text(x=sleft - 0.01, y=sbottom + (spoint - 1 - i) * vspace, s=alg_names[indices][i], ha="right", va="center") # Plot lines/names for right models vspace = 0.5 * (stop - sbottom) / (num_alg - spoint + 1) for i in range(num_alg - spoint): - ax.vlines(x=sleft + (lline * (rightalg[i] - lowest)) / (highest - lowest), - ymin=sbottom + i * vspace, ymax=stop, color='black', linewidth=0.7) - ax.hlines(y=sbottom + i * vspace, - xmin=sleft + - (lline * (rightalg[i] - lowest)) / (highest - lowest), - xmax=sright, color='black', linewidth=0.7) - ax.text(x=sright + 0.01, y=sbottom + i * vspace, - s=alg_names[indices][spoint + i], ha='left', va='center') + ax.vlines( + x=sleft + (lline * (rightalg[i] - lowest)) / (highest - lowest), + ymin=sbottom + i * vspace, + ymax=stop, + color="black", + linewidth=0.7, + ) + ax.hlines( + y=sbottom + i * vspace, + xmin=sleft + (lline * (rightalg[i] - lowest)) / (highest - lowest), + xmax=sright, + color="black", + linewidth=0.7, + ) + ax.text(x=sright + 0.01, y=sbottom + i * vspace, s=alg_names[indices][spoint + i], ha="left", va="center") # Plot critical difference rule if sleft + (cd * lline) / (highest - lowest) <= sright: - ax.hlines(y=stop + 0.2, xmin=sleft, xmax=sleft + - (cd * lline) / (highest - lowest), linewidth=1.5) - ax.text(x=sleft + 0.5 * (cd * lline) / - (highest - lowest), y=stop + 0.21, s='CD=%.3f' % cd, ha='center', va='bottom') + ax.hlines(y=stop + 0.2, xmin=sleft, xmax=sleft + (cd * lline) / (highest - lowest), linewidth=1.5) + ax.text( + x=sleft + 0.5 * (cd * lline) / (highest - lowest), y=stop + 0.21, s="CD=%.3f" % cd, ha="center", va="bottom" + ) else: - ax.text(x=(sleft + sright) / 2, y=stop + 0.2, s='CD=%.3f' % - cd, ha='center', va='bottom') + ax.text(x=(sleft + sright) / 2, y=stop + 0.2, s="CD=%.3f" % cd, ha="center", va="bottom") # Get pair of non-significant methods nonsig = _join_alg(avranks, num_alg, cd) @@ -291,32 +315,35 @@

    Source code for jmetal.lab.statistical_test.critical_distance

    left_lines = np.reshape(nonsig[0, :], (1, 2)) right_lines = np.reshape(nonsig[1, :], (1, 2)) else: - left_lines = nonsig[:np.round( - nonsig.shape[0] / 2.0).astype(np.uint8), :] - right_lines = nonsig[np.round( - nonsig.shape[0] / 2.0).astype(np.uint8):, :] + left_lines = nonsig[: np.round(nonsig.shape[0] / 2.0).astype(np.uint8), :] + right_lines = nonsig[np.round(nonsig.shape[0] / 2.0).astype(np.uint8) :, :] else: left_lines = np.reshape(nonsig, (1, nonsig.shape[0])) # plot from the left vspace = 0.5 * (stop - sbottom) / (left_lines.shape[0] + 1) for i in range(left_lines.shape[0]): - ax.hlines(y=stop - (i + 1) * vspace, - xmin=sleft + lline * (left_lines[i, 0] - - lowest - 0.025) / (highest - lowest), - xmax=sleft + lline * (left_lines[i, 1] - lowest + 0.025) / (highest - lowest), linewidth=2) + ax.hlines( + y=stop - (i + 1) * vspace, + xmin=sleft + lline * (left_lines[i, 0] - lowest - 0.025) / (highest - lowest), + xmax=sleft + lline * (left_lines[i, 1] - lowest + 0.025) / (highest - lowest), + linewidth=2, + ) # plot from the rigth if nonsig.ndim == 2: vspace = 0.5 * (stop - sbottom) / (left_lines.shape[0]) for i in range(right_lines.shape[0]): - ax.hlines(y=stop - (i + 1) * vspace, - xmin=sleft + lline * (right_lines[i, 0] - - lowest - 0.025) / (highest - lowest), - xmax=sleft + lline * (right_lines[i, 1] - lowest + 0.025) / (highest - lowest), linewidth=2) - - plt.savefig(output_filename, bbox_inches='tight') + ax.hlines( + y=stop - (i + 1) * vspace, + xmin=sleft + lline * (right_lines[i, 0] - lowest - 0.025) / (highest - lowest), + xmax=sleft + lline * (right_lines[i, 1] - lowest + 0.025) / (highest - lowest), + linewidth=2, + ) + + plt.savefig(output_filename, bbox_inches="tight") plt.show()
    +
    @@ -333,8 +360,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.statistical_test.functions — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,13 +106,15 @@

    Table Of Contents

    Source code for jmetal.lab.statistical_test.functions

    -from scipy.stats import chi2, f, binom, norm
    +from scipy.stats import binom, chi2, f, norm
     
     from jmetal.lab.statistical_test.apv_procedures import *
     
     
    -
    [docs]def ranks(data: np.array, descending=False): - """ Computes the rank of the elements in data. +
    +[docs] +def ranks(data: np.array, descending=False): + """Computes the rank of the elements in data. :param data: 2-D matrix :param descending: boolean (default False). If true, rank is sorted in descending order. @@ -128,23 +127,30 @@

    Source code for jmetal.lab.statistical_test.functions

    ranks = np.ones(data.shape) for i in range(data.shape[0]): values, indices, rep = np.unique( - (-1) ** s * np.sort((-1) ** s * data[i, :]), return_index=True, return_counts=True, ) + (-1) ** s * np.sort((-1) ** s * data[i, :]), + return_index=True, + return_counts=True, + ) for j in range(data.shape[1]): - ranks[i, j] += indices[values == data[i, j]] + \ - 0.5 * (rep[values == data[i, j]] - 1) + ranks[i, j] += indices[values == data[i, j]] + 0.5 * (rep[values == data[i, j]] - 1) return ranks elif data.ndim == 1: ranks = np.ones((data.size,)) values, indices, rep = np.unique( - (-1) ** s * np.sort((-1) ** s * data), return_index=True, return_counts=True, ) + (-1) ** s * np.sort((-1) ** s * data), + return_index=True, + return_counts=True, + ) for i in range(data.size): - ranks[i] += indices[values == data[i]] + \ - 0.5 * (rep[values == data[i]] - 1) + ranks[i] += indices[values == data[i]] + 0.5 * (rep[values == data[i]] - 1) return ranks
    -
    [docs]def sign_test(data): - """ Given the results drawn from two algorithms/methods X and Y, the sign test analyses if + +
    +[docs] +def sign_test(data): + """Given the results drawn from two algorithms/methods X and Y, the sign test analyses if there is a difference between X and Y. .. note:: Null Hypothesis: Pr(X<Y)= 0.5 @@ -161,8 +167,7 @@

    Source code for jmetal.lab.statistical_test.functions

    X, Y = data[:, 0], data[:, 1] n_perf = data.shape[0] else: - raise ValueError( - 'Initialization ERROR. Incorrect number of dimensions for axis 1') + raise ValueError("Initialization ERROR. Incorrect number of dimensions for axis 1") # Compute the differences Z = X - Y @@ -178,12 +183,16 @@

    Source code for jmetal.lab.statistical_test.functions

    p_value = 2 * min([p_value_minus, p_value_plus]) - return pd.DataFrame(data=np.array([Wminus, Wplus, p_value]), index=['Num X<Y', 'Num X>Y', 'p-value'], - columns=['Results'])
    + return pd.DataFrame( + data=np.array([Wminus, Wplus, p_value]), index=["Num X<Y", "Num X>Y", "p-value"], columns=["Results"] + )
    + -
    [docs]def friedman_test(data): - """ Friedman ranking test. +
    +[docs] +def friedman_test(data): + """Friedman ranking test. ..note:: Null Hypothesis: In a set of k (>=2) treaments (or tested algorithms), all the treatments are equivalent, so their average ranks should be equal. @@ -199,11 +208,9 @@

    Source code for jmetal.lab.statistical_test.functions

    if data.ndim == 2: n_samples, k = data.shape else: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions") if k < 2: - raise ValueError( - 'Initialization Error. Incorrect number of dimensions for axis 1.') + raise ValueError("Initialization Error. Incorrect number of dimensions for axis 1.") # Compute ranks. datarank = ranks(data) @@ -212,18 +219,21 @@

    Source code for jmetal.lab.statistical_test.functions

    avranks = np.mean(datarank, axis=0) # Get Friedman statistics - friedman_stat = (12.0 * n_samples) / (k * (k + 1.0)) * \ - (np.sum(avranks ** 2) - (k * (k + 1) ** 2) / 4.0) + friedman_stat = (12.0 * n_samples) / (k * (k + 1.0)) * (np.sum(avranks**2) - (k * (k + 1) ** 2) / 4.0) # Compute p-value - p_value = (1.0 - chi2.cdf(friedman_stat, df=(k - 1))) + p_value = 1.0 - chi2.cdf(friedman_stat, df=(k - 1)) - return pd.DataFrame(data=np.array([friedman_stat, p_value]), index=['Friedman-statistic', 'p-value'], - columns=['Results'])
    + return pd.DataFrame( + data=np.array([friedman_stat, p_value]), index=["Friedman-statistic", "p-value"], columns=["Results"] + )
    -
    [docs]def friedman_aligned_rank_test(data): - """ Method of aligned ranks for the Friedman test. + +
    +[docs] +def friedman_aligned_rank_test(data): + """Method of aligned ranks for the Friedman test. ..note:: Null Hypothesis: In a set of k (>=2) treaments (or tested algorithms), all the treatments are equivalent, so their average ranks should be equal. @@ -239,11 +249,9 @@

    Source code for jmetal.lab.statistical_test.functions

    if data.ndim == 2: n_samples, k = data.shape else: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions") if k < 2: - raise ValueError( - 'Initialization Error. Incorrect number of dimensions for axis 1.') + raise ValueError("Initialization Error. Incorrect number of dimensions for axis 1.") # Compute the average value achieved by all algorithms in each problem control = np.mean(data, axis=1) @@ -251,27 +259,31 @@

    Source code for jmetal.lab.statistical_test.functions

    diff = [data[:, j] - control for j in range(data.shape[1])] # rank diff alignedRanks = ranks(np.ravel(diff)) - alignedRanks = np.reshape(alignedRanks, newshape=(n_samples, k), order='F') + alignedRanks = np.reshape(alignedRanks, newshape=(n_samples, k), order="F") # Compute statistic Rhat_i = np.sum(alignedRanks, axis=1) Rhat_j = np.sum(alignedRanks, axis=0) - si, sj = np.sum(Rhat_i ** 2), np.sum(Rhat_j ** 2) + si, sj = np.sum(Rhat_i**2), np.sum(Rhat_j**2) - A = sj - (k * n_samples ** 2 / 4.0) * (k * n_samples + 1) ** 2 - B1 = (k * n_samples * (k * n_samples + 1) * (2 * k * n_samples + 1) / 6.0) + A = sj - (k * n_samples**2 / 4.0) * (k * n_samples + 1) ** 2 + B1 = k * n_samples * (k * n_samples + 1) * (2 * k * n_samples + 1) / 6.0 B2 = si / float(k) alignedRanks_stat = ((k - 1) * A) / (B1 - B2) p_value = 1 - chi2.cdf(alignedRanks_stat, df=k - 1) - return pd.DataFrame(data=np.array([alignedRanks_stat, p_value]), index=['Aligned Rank stat', 'p-value'], - columns=['Results'])
    + return pd.DataFrame( + data=np.array([alignedRanks_stat, p_value]), index=["Aligned Rank stat", "p-value"], columns=["Results"] + )
    + -
    [docs]def quade_test(data): - """ Quade test. +
    +[docs] +def quade_test(data): + """Quade test. ..note:: Null Hypothesis: In a set of k (>=2) treaments (or tested algorithms), all the treatments are equivalent, so their average ranks should be equal. @@ -287,11 +299,9 @@

    Source code for jmetal.lab.statistical_test.functions

    if data.ndim == 2: n_samples, k = data.shape else: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions") if k < 2: - raise ValueError( - 'Initialization Error. Incorrect number of dimensions for axis 1.') + raise ValueError("Initialization Error. Incorrect number of dimensions for axis 1.") # Compute ranks. datarank = ranks(data) @@ -308,8 +318,8 @@

    Source code for jmetal.lab.statistical_test.functions

    Salg = np.sum(S_stat, axis=0) # Compute Fq (Quade Test statistic) and associated p_value - A = np.sum(S_stat ** 2) - B = np.sum(Salg ** 2) / float(n_samples) + A = np.sum(S_stat**2) + B = np.sum(Salg**2) / float(n_samples) if A == B: Fq = np.Inf @@ -318,11 +328,14 @@

    Source code for jmetal.lab.statistical_test.functions

    Fq = (n_samples - 1.0) * B / (A - B) p_value = 1 - f.cdf(Fq, k - 1, (k - 1) * (n_samples - 1)) - return pd.DataFrame(data=np.array([Fq, p_value]), index=['Quade Test statistic', 'p-value'], columns=['Results'])
    + return pd.DataFrame(data=np.array([Fq, p_value]), index=["Quade Test statistic", "p-value"], columns=["Results"])
    -
    [docs]def friedman_ph_test(data, control=None, apv_procedure=None): - """ Friedman post-hoc test. + +
    +[docs] +def friedman_ph_test(data, control=None, apv_procedure=None): + """Friedman post-hoc test. :param data: An (n x 2) array or DataFrame contaning the results. In data, each column represents an algorithm and, and each row a problem. :param control: optional int or string. Default None. Index or Name of the control algorithm. If control = None all FriedmanPosHocTest considers all possible comparisons among algorithms. @@ -344,7 +357,7 @@

    Source code for jmetal.lab.statistical_test.functions

    algorithms = data.columns data = data.values elif type(data) == np.ndarray: - algorithms = np.array(['Alg%d' % alg for alg in range(data.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(data.shape[1])]) if control is None: index = algorithms @@ -356,24 +369,29 @@

    Source code for jmetal.lab.statistical_test.functions

    if data.ndim == 2: n_samples, k = data.shape else: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions.') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions.") if k < 2: - raise ValueError( - 'Initialization Error. Incorrect number of dimensions for axis 1.') + raise ValueError("Initialization Error. Incorrect number of dimensions for axis 1.") if control is not None: if type(control) == int and control >= data.shape[1]: - raise ValueError('Initialization ERROR. control is out of bounds') + raise ValueError("Initialization ERROR. control is out of bounds") if type(control) == str and control not in algorithms: - raise ValueError( - 'Initialization ERROR. %s is not a column name of data' % control) + raise ValueError("Initialization ERROR. %s is not a column name of data" % control) if apv_procedure is not None: - if apv_procedure not in ['Bonferroni', 'Holm', 'Hochberg', 'Hommel', 'Holland', 'Finner', 'Li', 'Shaffer', - 'Nemenyi']: - raise ValueError( - 'Initialization ERROR. Incorrect value for APVprocedure.') + if apv_procedure not in [ + "Bonferroni", + "Holm", + "Hochberg", + "Hommel", + "Holland", + "Finner", + "Li", + "Shaffer", + "Nemenyi", + ]: + raise ValueError("Initialization ERROR. Incorrect value for APVprocedure.") # Compute ranks. datarank = ranks(data) @@ -405,28 +423,31 @@

    Source code for jmetal.lab.statistical_test.functions

    if apv_procedure is None: return zvalues_df, pvalues_df else: - if apv_procedure == 'Bonferroni': + if apv_procedure == "Bonferroni": ap_vs_df = bonferroni_dunn(pvalues_df, control=control) - elif apv_procedure == 'Holm': + elif apv_procedure == "Holm": ap_vs_df = holm(pvalues_df, control=control) - elif apv_procedure == 'Hochberg': + elif apv_procedure == "Hochberg": ap_vs_df = hochberg(pvalues_df, control=control) - elif apv_procedure == 'Holland': + elif apv_procedure == "Holland": ap_vs_df = holland(pvalues_df, control=control) - elif apv_procedure == 'Finner': + elif apv_procedure == "Finner": ap_vs_df = finner(pvalues_df, control=control) - elif apv_procedure == 'Li': + elif apv_procedure == "Li": ap_vs_df = li(pvalues_df, control=control) - elif apv_procedure == 'Shaffer': + elif apv_procedure == "Shaffer": ap_vs_df = shaffer(pvalues_df) - elif apv_procedure == 'Nemenyi': + elif apv_procedure == "Nemenyi": ap_vs_df = nemenyi(pvalues_df) return zvalues_df, pvalues_df, ap_vs_df
    -
    [docs]def friedman_aligned_ph_test(data, control=None, apv_procedure=None): - """ Friedman Aligned Ranks post-hoc test. + +
    +[docs] +def friedman_aligned_ph_test(data, control=None, apv_procedure=None): + """Friedman Aligned Ranks post-hoc test. :param data: An (n x 2) array or DataFrame contaning the results. In data, each column represents an algorithm and, and each row a problem. :param control: optional int or string. Default None. Index or Name of the control algorithm. If control = None all FriedmanPosHocTest considers all possible comparisons among algorithms. @@ -448,7 +469,7 @@

    Source code for jmetal.lab.statistical_test.functions

    algorithms = data.columns data = data.values elif type(data) == np.ndarray: - algorithms = np.array(['Alg%d' % alg for alg in range(data.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(data.shape[1])]) if control is None: index = algorithms @@ -460,18 +481,15 @@

    Source code for jmetal.lab.statistical_test.functions

    if data.ndim == 2: n_samples, k = data.shape else: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions.') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions.") if k < 2: - raise ValueError( - 'Initialization Error. Incorrect number of dimensions for axis 1.') + raise ValueError("Initialization Error. Incorrect number of dimensions for axis 1.") if control is not None: if type(control) == int and control >= data.shape[1]: - raise ValueError('Initialization ERROR. control is out of bounds') + raise ValueError("Initialization ERROR. control is out of bounds") if type(control) == str and control not in algorithms: - raise ValueError( - 'Initialization ERROR. %s is not a column name of data' % control) + raise ValueError("Initialization ERROR. %s is not a column name of data" % control) # Compute the average value achieved by all algorithms in each problem problemmean = np.mean(data, axis=1) @@ -510,28 +528,31 @@

    Source code for jmetal.lab.statistical_test.functions

    if apv_procedure is None: return zvalues_df, pvalues_df else: - if apv_procedure == 'Bonferroni': + if apv_procedure == "Bonferroni": ap_vs_df = bonferroni_dunn(pvalues_df, control=control) - elif apv_procedure == 'Holm': + elif apv_procedure == "Holm": ap_vs_df = holm(pvalues_df, control=control) - elif apv_procedure == 'Hochberg': + elif apv_procedure == "Hochberg": ap_vs_df = hochberg(pvalues_df, control=control) - elif apv_procedure == 'Holland': + elif apv_procedure == "Holland": ap_vs_df = holland(pvalues_df, control=control) - elif apv_procedure == 'Finner': + elif apv_procedure == "Finner": ap_vs_df = finner(pvalues_df, control=control) - elif apv_procedure == 'Li': + elif apv_procedure == "Li": ap_vs_df = li(pvalues_df, control=control) - elif apv_procedure == 'Shaffer': + elif apv_procedure == "Shaffer": ap_vs_df = shaffer(pvalues_df) - elif apv_procedure == 'Nemenyi': + elif apv_procedure == "Nemenyi": ap_vs_df = nemenyi(pvalues_df) return zvalues_df, pvalues_df, ap_vs_df
    -
    [docs]def quade_ph_test(data, control=None, apv_procedure=None): - """ Quade post-hoc test. + +
    +[docs] +def quade_ph_test(data, control=None, apv_procedure=None): + """Quade post-hoc test. :param data: An (n x 2) array or DataFrame contaning the results. In data, each column represents an algorithm and, and each row a problem. :param control: optional int or string. Default None. Index or Name of the control algorithm. If control = None all FriedmanPosHocTest considers all possible comparisons among algorithms. @@ -553,7 +574,7 @@

    Source code for jmetal.lab.statistical_test.functions

    algorithms = data.columns data = data.values elif type(data) == np.ndarray: - algorithms = np.array(['Alg%d' % alg for alg in range(data.shape[1])]) + algorithms = np.array(["Alg%d" % alg for alg in range(data.shape[1])]) if control is None: index = algorithms @@ -565,18 +586,15 @@

    Source code for jmetal.lab.statistical_test.functions

    if data.ndim == 2: n_samples, k = data.shape else: - raise ValueError( - 'Initialization ERROR. Incorrect number of array dimensions.') + raise ValueError("Initialization ERROR. Incorrect number of array dimensions.") if k < 2: - raise ValueError( - 'Initialization Error. Incorrect number of dimensions for axis 1.') + raise ValueError("Initialization Error. Incorrect number of dimensions for axis 1.") if control is not None: if type(control) == int and control >= data.shape[1]: - raise ValueError('Initialization ERROR. control is out of bounds') + raise ValueError("Initialization ERROR. control is out of bounds") if type(control) == str and control not in algorithms: - raise ValueError( - 'Initialization ERROR. %s is not a column name of data' % control) + raise ValueError("Initialization ERROR. %s is not a column name of data" % control) # Compute ranks. datarank = ranks(data) @@ -591,8 +609,7 @@

    Source code for jmetal.lab.statistical_test.functions

    W[i, :] = problemRank[i] * datarank[i, :] avranks = 2 * np.sum(W, axis=0) / (n_samples * (n_samples + 1)) # Compute test statistics - aux = 1.0 / np.sqrt(k * (k + 1) * (2 * n_samples + 1) * (k - 1) / - (18.0 * n_samples * (n_samples + 1))) + aux = 1.0 / np.sqrt(k * (k + 1) * (2 * n_samples + 1) * (k - 1) / (18.0 * n_samples * (n_samples + 1))) if control is None: z = np.zeros((k, k)) for i in range(k): @@ -615,24 +632,25 @@

    Source code for jmetal.lab.statistical_test.functions

    if apv_procedure is None: return zvalues_df, pvalues_df else: - if apv_procedure == 'Bonferroni': + if apv_procedure == "Bonferroni": ap_vs_df = bonferroni_dunn(pvalues_df, control=control) - elif apv_procedure == 'Holm': + elif apv_procedure == "Holm": ap_vs_df = holm(pvalues_df, control=control) - elif apv_procedure == 'Hochberg': + elif apv_procedure == "Hochberg": ap_vs_df = hochberg(pvalues_df, control=control) - elif apv_procedure == 'Holland': + elif apv_procedure == "Holland": ap_vs_df = holland(pvalues_df, control=control) - elif apv_procedure == 'Finner': + elif apv_procedure == "Finner": ap_vs_df = finner(pvalues_df, control=control) - elif apv_procedure == 'Li': + elif apv_procedure == "Li": ap_vs_df = li(pvalues_df, control=control) - elif apv_procedure == 'Shaffer': + elif apv_procedure == "Shaffer": ap_vs_df = shaffer(pvalues_df) - elif apv_procedure == 'Nemenyi': + elif apv_procedure == "Nemenyi": ap_vs_df = nemenyi(pvalues_df) return zvalues_df, pvalues_df, ap_vs_df
    +
    @@ -649,8 +667,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.visualization.chord_plot — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -121,34 +118,50 @@

    Source code for jmetal.lab.visualization.chord_plot

    from jmetal.core.solution import FloatSolution -
    [docs]def polar_to_cartesian(r, theta): +
    +[docs] +def polar_to_cartesian(r, theta): return np.array([r * np.cos(theta), r * np.sin(theta)])
    -
    [docs]def draw_sector(start_angle=0, end_angle=60, radius=1.0, width=0.2, lw=2, ls='-', ax=None, fc=(1, 0, 0), ec=(0, 0, 0), - z_order=1): + +
    +[docs] +def draw_sector( + start_angle=0, end_angle=60, radius=1.0, width=0.2, lw=2, ls="-", ax=None, fc=(1, 0, 0), ec=(0, 0, 0), z_order=1 +): if start_angle > end_angle: start_angle, end_angle = end_angle, start_angle - start_angle *= np.pi / 180. - end_angle *= np.pi / 180. + start_angle *= np.pi / 180.0 + end_angle *= np.pi / 180.0 # https://stackoverflow.com/questions/1734745/how-to-create-circle-with-b%C3%A9zier-curves - opt = 4. / 3. * np.tan((end_angle - start_angle) / 4.) * radius + opt = 4.0 / 3.0 * np.tan((end_angle - start_angle) / 4.0) * radius inner = radius * (1 - width) - vertsPath = [polar_to_cartesian(radius, start_angle), - polar_to_cartesian(radius, start_angle) + polar_to_cartesian(opt, start_angle + 0.5 * np.pi), - polar_to_cartesian(radius, end_angle) + polar_to_cartesian(opt, end_angle - 0.5 * np.pi), - polar_to_cartesian(radius, end_angle), - polar_to_cartesian(inner, end_angle), - polar_to_cartesian(inner, end_angle) + polar_to_cartesian(opt * (1 - width), end_angle - 0.5 * np.pi), - polar_to_cartesian(inner, start_angle) + polar_to_cartesian(opt * (1 - width), - start_angle + 0.5 * np.pi), - polar_to_cartesian(inner, start_angle), - polar_to_cartesian(radius, start_angle)] - - codesPaths = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.LINETO, Path.CURVE4, Path.CURVE4, - Path.CURVE4, Path.CLOSEPOLY] + vertsPath = [ + polar_to_cartesian(radius, start_angle), + polar_to_cartesian(radius, start_angle) + polar_to_cartesian(opt, start_angle + 0.5 * np.pi), + polar_to_cartesian(radius, end_angle) + polar_to_cartesian(opt, end_angle - 0.5 * np.pi), + polar_to_cartesian(radius, end_angle), + polar_to_cartesian(inner, end_angle), + polar_to_cartesian(inner, end_angle) + polar_to_cartesian(opt * (1 - width), end_angle - 0.5 * np.pi), + polar_to_cartesian(inner, start_angle) + polar_to_cartesian(opt * (1 - width), start_angle + 0.5 * np.pi), + polar_to_cartesian(inner, start_angle), + polar_to_cartesian(radius, start_angle), + ] + + codesPaths = [ + Path.MOVETO, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.LINETO, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CLOSEPOLY, + ] if ax is None: return vertsPath, codesPaths @@ -156,38 +169,67 @@

    Source code for jmetal.lab.visualization.chord_plot

    path = Path(vertsPath, codesPaths) patch = patches.PathPatch(path, facecolor=fc, edgecolor=ec, lw=lw, linestyle=ls, zorder=z_order) ax.add_patch(patch) - return (patch)
    - - -
    [docs]def draw_chord(start_angle1=0, end_angle1=60, start_angle2=180, end_angle2=240, radius=1.0, chord_width=0.7, ax=None, - color=(1, 0, 0), z_order=1): + return patch
    + + + +
    +[docs] +def draw_chord( + start_angle1=0, + end_angle1=60, + start_angle2=180, + end_angle2=240, + radius=1.0, + chord_width=0.7, + ax=None, + color=(1, 0, 0), + z_order=1, +): if start_angle1 > end_angle1: start_angle1, end_angle1 = end_angle1, start_angle1 if start_angle2 > end_angle2: start_angle2, end_angle2 = end_angle2, start_angle2 - start_angle1 *= np.pi / 180. - end_angle1 *= np.pi / 180. - start_angle2 *= np.pi / 180. - end_angle2 *= np.pi / 180. + start_angle1 *= np.pi / 180.0 + end_angle1 *= np.pi / 180.0 + start_angle2 *= np.pi / 180.0 + end_angle2 *= np.pi / 180.0 - optAngle1 = 4. / 3. * np.tan((end_angle1 - start_angle1) / 4.) * radius - optAngle2 = 4. / 3. * np.tan((end_angle2 - start_angle2) / 4.) * radius + optAngle1 = 4.0 / 3.0 * np.tan((end_angle1 - start_angle1) / 4.0) * radius + optAngle2 = 4.0 / 3.0 * np.tan((end_angle2 - start_angle2) / 4.0) * radius rchord = radius * (1 - chord_width) - vertsPath = [polar_to_cartesian(radius, start_angle1), - polar_to_cartesian(radius, start_angle1) + polar_to_cartesian(optAngle1, start_angle1 + 0.5 * np.pi), - polar_to_cartesian(radius, end_angle1) + polar_to_cartesian(optAngle1, end_angle1 - 0.5 * np.pi), - polar_to_cartesian(radius, end_angle1), - polar_to_cartesian(rchord, end_angle1), polar_to_cartesian(rchord, start_angle2), - polar_to_cartesian(radius, start_angle2), - polar_to_cartesian(radius, start_angle2) + polar_to_cartesian(optAngle2, start_angle2 + 0.5 * np.pi), - polar_to_cartesian(radius, end_angle2) + polar_to_cartesian(optAngle2, end_angle2 - 0.5 * np.pi), - polar_to_cartesian(radius, end_angle2), - polar_to_cartesian(rchord, end_angle2), polar_to_cartesian(rchord, start_angle1), - polar_to_cartesian(radius, start_angle1)] - - codesPath = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, - Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CURVE4] + vertsPath = [ + polar_to_cartesian(radius, start_angle1), + polar_to_cartesian(radius, start_angle1) + polar_to_cartesian(optAngle1, start_angle1 + 0.5 * np.pi), + polar_to_cartesian(radius, end_angle1) + polar_to_cartesian(optAngle1, end_angle1 - 0.5 * np.pi), + polar_to_cartesian(radius, end_angle1), + polar_to_cartesian(rchord, end_angle1), + polar_to_cartesian(rchord, start_angle2), + polar_to_cartesian(radius, start_angle2), + polar_to_cartesian(radius, start_angle2) + polar_to_cartesian(optAngle2, start_angle2 + 0.5 * np.pi), + polar_to_cartesian(radius, end_angle2) + polar_to_cartesian(optAngle2, end_angle2 - 0.5 * np.pi), + polar_to_cartesian(radius, end_angle2), + polar_to_cartesian(rchord, end_angle2), + polar_to_cartesian(rchord, start_angle1), + polar_to_cartesian(radius, start_angle1), + ] + + codesPath = [ + Path.MOVETO, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + Path.CURVE4, + ] if ax == None: return vertsPath, codesPath @@ -195,10 +237,13 @@

    Source code for jmetal.lab.visualization.chord_plot

    path = Path(vertsPath, codesPath) patch = patches.PathPatch(path, facecolor=color + (0.5,), edgecolor=color + (0.4,), lw=2, alpha=0.5) ax.add_patch(patch) - return (patch)
    + return patch
    + -
    [docs]def hover_over_bin(event, handle_tickers, handle_plots, colors, fig): +
    +[docs] +def hover_over_bin(event, handle_tickers, handle_plots, colors, fig): is_found = False for iobj in range(len(handle_tickers)): @@ -220,8 +265,17 @@

    Source code for jmetal.lab.visualization.chord_plot

    fig.canvas.draw_idle()
    -
    [docs]def chord_diagram(solutions: List[FloatSolution], nbins='auto', ax=None, obj_labels=None, - prop_labels=dict(fontsize=13, ha='center', va='center'), pad=6): + +
    +[docs] +def chord_diagram( + solutions: List[FloatSolution], + nbins="auto", + ax=None, + obj_labels=None, + prop_labels=dict(fontsize=13, ha="center", va="center"), + pad=6, +): points_matrix = np.array([s.objectives for s in solutions]) (NPOINTS, NOBJ) = np.shape(points_matrix) @@ -230,13 +284,13 @@

    Source code for jmetal.lab.visualization.chord_plot

    if ax is None: fig = plt.figure(figsize=(6, 6)) - ax = plt.axes([0, 0, 1, 1], aspect='equal') + ax = plt.axes([0, 0, 1, 1], aspect="equal") ax.set_xlim(-2.3, 2.3) ax.set_ylim(-2.3, 2.3) - ax.axis('off') + ax.axis("off") - y = np.array([1. / NOBJ] * NOBJ) * (360 - pad * NOBJ) + y = np.array([1.0 / NOBJ] * NOBJ) * (360 - pad * NOBJ) sector_angles = [] labels_pos_and_ros = [] @@ -256,9 +310,13 @@

    Source code for jmetal.lab.visualization.chord_plot

    angleText -= 270 labels_pos_and_ros.append( - tuple(polar_to_cartesian(1.0, 0.5 * (start_angle + end_angle) * np.pi / 180.)) + (angle_diff,) + - tuple(polar_to_cartesian(0.725, (start_angle - 2.5) * np.pi / 180.)) + (angleText,) + - tuple(polar_to_cartesian(0.85, (start_angle - 2.5) * np.pi / 180.)) + (angleText,)) + tuple(polar_to_cartesian(1.0, 0.5 * (start_angle + end_angle) * np.pi / 180.0)) + + (angle_diff,) + + tuple(polar_to_cartesian(0.725, (start_angle - 2.5) * np.pi / 180.0)) + + (angleText,) + + tuple(polar_to_cartesian(0.85, (start_angle - 2.5) * np.pi / 180.0)) + + (angleText,) + ) start_angle = end_angle + pad arc_points = [] @@ -275,15 +333,41 @@

    Source code for jmetal.lab.visualization.chord_plot

    handle_tickers = [] handle_plots = [] - for iobj in tqdm(range(NOBJ), ascii=True, desc='Chord diagram'): - draw_sector(start_angle=sector_angles[iobj][0], end_angle=sector_angles[iobj][1], radius=0.925, width=0.225, - ax=ax, - fc=(1, 1, 1, 0.0), ec=(0, 0, 0), lw=2, z_order=10) - draw_sector(start_angle=sector_angles[iobj][0], end_angle=sector_angles[iobj][1], radius=0.925, width=0.05, - ax=ax, - fc=colors[iobj], ec=(0, 0, 0), lw=2, z_order=10) - draw_sector(start_angle=sector_angles[iobj][0], end_angle=sector_angles[iobj][1], radius=0.7 + 0.15, width=0.0, - ax=ax, fc=colors[iobj], ec=colors[iobj], lw=2, ls=':', z_order=5) + for iobj in tqdm(range(NOBJ), ascii=True, desc="Chord diagram"): + draw_sector( + start_angle=sector_angles[iobj][0], + end_angle=sector_angles[iobj][1], + radius=0.925, + width=0.225, + ax=ax, + fc=(1, 1, 1, 0.0), + ec=(0, 0, 0), + lw=2, + z_order=10, + ) + draw_sector( + start_angle=sector_angles[iobj][0], + end_angle=sector_angles[iobj][1], + radius=0.925, + width=0.05, + ax=ax, + fc=colors[iobj], + ec=(0, 0, 0), + lw=2, + z_order=10, + ) + draw_sector( + start_angle=sector_angles[iobj][0], + end_angle=sector_angles[iobj][1], + radius=0.7 + 0.15, + width=0.0, + ax=ax, + fc=colors[iobj], + ec=colors[iobj], + lw=2, + ls=":", + z_order=5, + ) histValues, binsDim = np.histogram(points_matrix[:, iobj], bins=nbins) relativeHeightBinPre = 0.025 @@ -292,73 +376,126 @@

    Source code for jmetal.lab.visualization.chord_plot

    handle_plots.append([]) for indexBin in range(len(histValues)): - startAngleBin = sector_angles[iobj][0] + (sector_angles[iobj][1] - sector_angles[iobj][0]) * binsDim[ - indexBin] - endAngleBin = sector_angles[iobj][0] + (sector_angles[iobj][1] - sector_angles[iobj][0]) * binsDim[ - indexBin + 1] + startAngleBin = ( + sector_angles[iobj][0] + (sector_angles[iobj][1] - sector_angles[iobj][0]) * binsDim[indexBin] + ) + endAngleBin = ( + sector_angles[iobj][0] + (sector_angles[iobj][1] - sector_angles[iobj][0]) * binsDim[indexBin + 1] + ) relativeHeightBin = 0.15 * histValues[indexBin] / max(histValues) handle_tickers[-1].append( - draw_sector(start_angle=startAngleBin, end_angle=endAngleBin, radius=0.69, width=0.08, ax=ax, lw=1, - fc=(1, 1, 1), ec=(0, 0, 0))) + draw_sector( + start_angle=startAngleBin, + end_angle=endAngleBin, + radius=0.69, + width=0.08, + ax=ax, + lw=1, + fc=(1, 1, 1), + ec=(0, 0, 0), + ) + ) handle_plots[-1].append([]) if histValues[indexBin] > 0: - draw_sector(start_angle=startAngleBin, end_angle=endAngleBin, radius=0.7 + relativeHeightBin, width=0, - ax=ax, lw=1, fc=colors[iobj], ec=colors[iobj]) - plotPoint1 = polar_to_cartesian(0.7 + relativeHeightBinPre, startAngleBin * np.pi / 180.) - plotPoint2 = polar_to_cartesian(0.7 + relativeHeightBin, startAngleBin * np.pi / 180.) + draw_sector( + start_angle=startAngleBin, + end_angle=endAngleBin, + radius=0.7 + relativeHeightBin, + width=0, + ax=ax, + lw=1, + fc=colors[iobj], + ec=colors[iobj], + ) + plotPoint1 = polar_to_cartesian(0.7 + relativeHeightBinPre, startAngleBin * np.pi / 180.0) + plotPoint2 = polar_to_cartesian(0.7 + relativeHeightBin, startAngleBin * np.pi / 180.0) plt.plot([plotPoint1[0], plotPoint2[0]], [plotPoint1[1], plotPoint2[1]], c=colors[iobj], lw=1) relativeHeightBinPre = relativeHeightBin else: - plotPoint1 = polar_to_cartesian(0.7 + relativeHeightBinPre, startAngleBin * np.pi / 180.) - plotPoint2 = polar_to_cartesian(0.725 + relativeHeightBin, startAngleBin * np.pi / 180.) + plotPoint1 = polar_to_cartesian(0.7 + relativeHeightBinPre, startAngleBin * np.pi / 180.0) + plotPoint2 = polar_to_cartesian(0.725 + relativeHeightBin, startAngleBin * np.pi / 180.0) plt.plot([plotPoint1[0], plotPoint2[0]], [plotPoint1[1], plotPoint2[1]], c=colors[iobj], lw=1) relativeHeightBinPre = 0.025 if indexBin == len(histValues) - 1: - plotPoint1 = polar_to_cartesian(0.7 + relativeHeightBin, endAngleBin * np.pi / 180.) - plotPoint2 = polar_to_cartesian(0.725, endAngleBin * np.pi / 180.) + plotPoint1 = polar_to_cartesian(0.7 + relativeHeightBin, endAngleBin * np.pi / 180.0) + plotPoint2 = polar_to_cartesian(0.725, endAngleBin * np.pi / 180.0) plt.plot([plotPoint1[0], plotPoint2[0]], [plotPoint1[1], plotPoint2[1]], c=colors[iobj], lw=1) for ipoint in range(len(points_matrix)): - plotPoint1 = polar_to_cartesian(0.6, arc_points[ipoint][iobj][0] * np.pi / 180.) - plotPoint2 = polar_to_cartesian(0.6, arc_points[ipoint][iobj][0] * np.pi / 180.) - plt.plot([plotPoint1[0], plotPoint2[0]], [plotPoint1[1], plotPoint2[1]], marker='o', markersize=3, - c=colors[iobj], lw=2) - - if binsDim[indexBin] < points_matrix[ipoint, iobj] <= binsDim[ - indexBin + 1]: + plotPoint1 = polar_to_cartesian(0.6, arc_points[ipoint][iobj][0] * np.pi / 180.0) + plotPoint2 = polar_to_cartesian(0.6, arc_points[ipoint][iobj][0] * np.pi / 180.0) + plt.plot( + [plotPoint1[0], plotPoint2[0]], + [plotPoint1[1], plotPoint2[1]], + marker="o", + markersize=3, + c=colors[iobj], + lw=2, + ) + + if binsDim[indexBin] < points_matrix[ipoint, iobj] <= binsDim[indexBin + 1]: for jdim in range(NOBJ): if jdim >= 1: handle_plots[iobj][indexBin].append( - draw_chord(arc_points[ipoint][jdim - 1][0], arc_points[ipoint][jdim - 1][1], - arc_points[ipoint][jdim][0], arc_points[ipoint][jdim][1], radius=0.55, - color=colors[iobj], chord_width=1, ax=ax)) + draw_chord( + arc_points[ipoint][jdim - 1][0], + arc_points[ipoint][jdim - 1][1], + arc_points[ipoint][jdim][0], + arc_points[ipoint][jdim][1], + radius=0.55, + color=colors[iobj], + chord_width=1, + ax=ax, + ) + ) handle_plots[iobj][indexBin][-1].set_visible(False) handle_plots[iobj][indexBin].append( - draw_chord(arc_points[ipoint][-1][0], arc_points[ipoint][-1][1], arc_points[ipoint][0][0], - arc_points[ipoint][0][1], radius=0.55, color=colors[iobj], chord_width=1, ax=ax)) + draw_chord( + arc_points[ipoint][-1][0], + arc_points[ipoint][-1][1], + arc_points[ipoint][0][0], + arc_points[ipoint][0][1], + radius=0.55, + color=colors[iobj], + chord_width=1, + ax=ax, + ) + ) handle_plots[iobj][indexBin][-1].set_visible(False) if obj_labels is None: - obj_labels = ['$f_{' + str(i) + '}(\mathbf{x})$' for i in range(NOBJ)] + obj_labels = ["$f_{" + str(i) + "}(\mathbf{x})$" for i in range(NOBJ)] - prop_legend_bins = dict(fontsize=9, ha='center', va='center') + prop_legend_bins = dict(fontsize=9, ha="center", va="center") for i in range(NOBJ): - p0, p1 = polar_to_cartesian(0.975, sector_angles[i][0] * np.pi / 180.) - ax.text(p0, p1, '0', **prop_legend_bins) - p0, p1 = polar_to_cartesian(0.975, sector_angles[i][1] * np.pi / 180.) - ax.text(p0, p1, '1', **prop_legend_bins) - ax.text(labels_pos_and_ros[i][0], labels_pos_and_ros[i][1], obj_labels[i], rotation=labels_pos_and_ros[i][2], - **prop_labels) - ax.text(labels_pos_and_ros[i][3], labels_pos_and_ros[i][4], '0', **prop_legend_bins, color=colors[i]) - ax.text(labels_pos_and_ros[i][6], labels_pos_and_ros[i][7], str(max_hist_values[i]), **prop_legend_bins, - color=colors[i]) + p0, p1 = polar_to_cartesian(0.975, sector_angles[i][0] * np.pi / 180.0) + ax.text(p0, p1, "0", **prop_legend_bins) + p0, p1 = polar_to_cartesian(0.975, sector_angles[i][1] * np.pi / 180.0) + ax.text(p0, p1, "1", **prop_legend_bins) + ax.text( + labels_pos_and_ros[i][0], + labels_pos_and_ros[i][1], + obj_labels[i], + rotation=labels_pos_and_ros[i][2], + **prop_labels + ) + ax.text(labels_pos_and_ros[i][3], labels_pos_and_ros[i][4], "0", **prop_legend_bins, color=colors[i]) + ax.text( + labels_pos_and_ros[i][6], + labels_pos_and_ros[i][7], + str(max_hist_values[i]), + **prop_legend_bins, + color=colors[i] + ) plt.axis([-1.2, 1.2, -1.2, 1.2]) - fig.canvas.mpl_connect("motion_notify_event", - lambda event: hover_over_bin(event, handle_tickers, handle_plots, colors, fig)) + fig.canvas.mpl_connect( + "motion_notify_event", lambda event: hover_over_bin(event, handle_tickers, handle_plots, colors, fig) + ) plt.show()
    +
    @@ -375,8 +512,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.visualization.interactive — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,7 +107,7 @@

    Table Of Contents

    Source code for jmetal.lab.visualization.interactive

     import logging
    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     import pandas as pd
     from plotly import graph_objs as go
    @@ -119,25 +116,30 @@ 

    Source code for jmetal.lab.visualization.interactive

    from jmetal.lab.visualization.plotting import Plot -LOGGER = logging.getLogger('jmetal') - -S = TypeVar('S') +logger = logging.getLogger(__name__) +S = TypeVar("S") -
    [docs]class InteractivePlot(Plot): - def __init__(self, - title: str = 'Pareto front approximation', - reference_front: List[S] = None, - reference_point: list = None, - axis_labels: list = None): +
    +[docs] +class InteractivePlot(Plot): + def __init__( + self, + title: str = "Pareto front approximation", + reference_front: List[S] = None, + reference_point: list = None, + axis_labels: list = None, + ): super(InteractivePlot, self).__init__(title, reference_front, reference_point, axis_labels) self.figure = None self.layout = None self.data = [] -
    [docs] def plot(self, front, label=None, normalize: bool = False, filename: str = None, format: str = 'HTML'): - """ Plot a front of solutions (2D, 3D or parallel coordinates). +
    +[docs] + def plot(self, front, label=None, normalize: bool = False, filename: str = None, format: str = "HTML"): + """Plot a front of solutions (2D, 3D or parallel coordinates). :param front: List of solutions. :param label: Front name. @@ -150,109 +152,127 @@

    Source code for jmetal.lab.visualization.interactive

    self.layout = go.Layout( margin=dict(l=80, r=80, b=80, t=150), height=800, - title='{}<br>{}'.format(self.plot_title, label[0]), + title="{}<br>{}".format(self.plot_title, label[0]), scene=dict( xaxis=dict(title=self.axis_labels[0:1][0] if self.axis_labels[0:1] else None), yaxis=dict(title=self.axis_labels[1:2][0] if self.axis_labels[1:2] else None), - zaxis=dict(title=self.axis_labels[2:3][0] if self.axis_labels[2:3] else None) + zaxis=dict(title=self.axis_labels[2:3][0] if self.axis_labels[2:3] else None), ), - hovermode='closest' + hovermode="closest", ) # If any reference front, plot if self.reference_front: points, _ = self.get_points(self.reference_front) - trace = self.__generate_trace(points=points, legend='Reference front', normalize=normalize, - color='black', size=2) + trace = self.__generate_trace( + points=points, legend="Reference front", normalize=normalize, color="black", size=2 + ) self.data.append(trace) # If any reference point, plot if self.reference_point: points = pd.DataFrame(self.reference_point) - trace = self.__generate_trace(points=points, legend='Reference point', color='red', size=8) + trace = self.__generate_trace(points=points, legend="Reference point", color="red", size=8) self.data.append(trace) # Get points and metadata points, _ = self.get_points(front) metadata = list(solution.__str__() for solution in front) - trace = self.__generate_trace(points=points, metadata=metadata, legend='Front approximation', - normalize=normalize) + trace = self.__generate_trace( + points=points, metadata=metadata, legend="Front approximation", normalize=normalize + ) self.data.append(trace) self.figure = go.Figure(data=self.data, layout=self.layout) # Plot the figure if filename: - if format == 'HTML': + if format == "HTML": self.export_to_html(filename) + logger.info("Figure {_filename} exported to HTML file") else: - pio.write_image(self.figure, filename + '.' + format)
    + _filename = filename + "." + format -
    [docs] def export_to_html(self, filename: str) -> str: - """ Export the graph to an interactive HTML (solutions can be selected to show some metadata). + pio.write_image(self.figure, _filename) + logger.info("Figure {_filename} saved to file")
    + + +
    +[docs] + def export_to_html(self, filename: str) -> str: + """Export the graph to an interactive HTML (solutions can be selected to show some metadata). :param filename: Output file name. - :return: Script as string. """ - html_string = ''' - <!DOCTYPE html> - <html> - <head> - <meta charset="utf-8"/> - <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> - <script src="https://unpkg.com/sweetalert2@7.7.0/dist/sweetalert2.all.js"></script> - <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> - </head> - <body> - ''' + self.export_to_div(filename=None, include_plotlyjs=False) + ''' - <script> - var myPlot = document.querySelectorAll('div')[0]; - myPlot.on('plotly_click', function(data){ - var pts = ''; - - for(var i=0; i < data.points.length; i++){ - pts = '(x, y) = ('+data.points[i].x +', '+ data.points[i].y.toPrecision(4)+')'; - cs = data.points[i].customdata - } - - if(typeof cs !== "undefined"){ - swal({ - title: 'Closest solution clicked:', - text: cs, - type: 'info', - position: 'bottom-end' - }) - } - }); - - window.onresize = function() { - Plotly.Plots.resize(myPlot); - }; - </script> - </body> - </html>''' - - with open(filename + '.html', 'w') as outf: + :return: Script as string.""" + html_string = ( + """ + <!DOCTYPE html> + <html> + <head> + <meta charset="utf-8"/> + <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> + <script src="https://unpkg.com/sweetalert2@7.7.0/dist/sweetalert2.all.js"></script> + <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> + </head> + <body> + """ + + self.export_to_div(filename=None, include_plotlyjs=False) + + """ + <script> + var myPlot = document.querySelectorAll('div')[0]; + myPlot.on('plotly_click', function(data){ + var pts = ''; + + for(var i=0; i < data.points.length; i++){ + pts = '(x, y) = ('+data.points[i].x +', '+ data.points[i].y.toPrecision(4)+')'; + cs = data.points[i].customdata + } + + if(typeof cs !== "undefined"){ + swal({ + title: 'Closest solution clicked:', + text: cs, + type: 'info', + position: 'bottom-end' + }) + } + }); + + window.onresize = function() { + Plotly.Plots.resize(myPlot); + }; + </script> + </body> + </html>""" + ) + + with open(filename + ".html", "w") as outf: outf.write(html_string) return html_string
    -
    [docs] def export_to_div(self, filename=None, include_plotlyjs: bool = False) -> str: - """ Export as a `div` for embedding the graph in an HTML file. + +
    +[docs] + def export_to_div(self, filename=None, include_plotlyjs: bool = False) -> str: + """Export as a `div` for embedding the graph in an HTML file. :param filename: Output file name (if desired, default to None). :param include_plotlyjs: If True, include plot.ly JS script (default to False). :return: Script as string. """ - script = offline.plot(self.figure, output_type='div', include_plotlyjs=include_plotlyjs, show_link=False) + script = offline.plot(self.figure, output_type="div", include_plotlyjs=include_plotlyjs, show_link=False) if filename: - with open(filename + '.html', 'w') as outf: + with open(filename + ".html", "w") as outf: outf.write(script) return script
    - def __generate_trace(self, points: pd.DataFrame, legend: str, metadata: list = None, normalize: bool = False, - **kwargs): + + def __generate_trace( + self, points: pd.DataFrame, legend: str, metadata: list = None, normalize: bool = False, **kwargs + ): dimension = points.shape[1] # tweak points size for 3D plots @@ -265,54 +285,39 @@

    Source code for jmetal.lab.visualization.interactive

    points = (points - points.min()) / (points.max() - points.min()) marker = dict( - color='#236FA4', - size=marker_size, - symbol='circle', - line=dict( - color='#236FA4', - width=1 - ), - opacity=0.8 + color="#236FA4", size=marker_size, symbol="circle", line=dict(color="#236FA4", width=1), opacity=0.8 ) marker.update(**kwargs) if dimension == 2: trace = go.Scattergl( - x=points[0], - y=points[1], - mode='markers', - marker=marker, - name=legend, - customdata=metadata + x=points[0], y=points[1], mode="markers", marker=marker, name=legend, customdata=metadata ) elif dimension == 3: trace = go.Scatter3d( - x=points[0], - y=points[1], - z=points[2], - mode='markers', - marker=marker, - name=legend, - customdata=metadata + x=points[0], y=points[1], z=points[2], mode="markers", marker=marker, name=legend, customdata=metadata ) else: dimensions = list() for column in points: dimensions.append( - dict(range=[0, 1], - label=self.axis_labels[column:column + 1][0] if self.axis_labels[column:column + 1] else None, - values=points[column]) + dict( + range=[0, 1], + label=self.axis_labels[column : column + 1][0] + if self.axis_labels[column : column + 1] + else None, + values=points[column], + ) ) trace = go.Parcoords( - line=dict( - color='#236FA4' - ), + line=dict(color="#236FA4"), dimensions=dimensions, name=legend, ) return trace
    +
    @@ -329,8 +334,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.visualization.plotting — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,26 +107,28 @@

    Table Of Contents

    Source code for jmetal.lab.visualization.plotting

     import logging
    -from typing import TypeVar, List, Tuple
    +from typing import List, Tuple, TypeVar
     
     import numpy as np
     import pandas as pd
     from matplotlib import pyplot as plt
    -from pandas import plotting
    -
    -LOGGER = logging.getLogger('jmetal')
     
    -S = TypeVar('S')
    +logger = logging.getLogger(__name__)
     
    +S = TypeVar("S")
     
    -
    [docs]class Plot: - def __init__(self, - title: str = 'Pareto front approximation', - reference_front: List[S] = None, - reference_point: list = None, - axis_labels: list = None): - """ +
    +[docs] +class Plot: + def __init__( + self, + title: str = "Pareto front approximation", + reference_front: List[S] = None, + reference_point: list = None, + axis_labels: list = None, + ): + """ :param title: Title of the graph. :param axis_labels: List of axis labels. :param reference_point: Reference point (e.g., [0.4, 1.2]). @@ -145,21 +144,26 @@

    Source code for jmetal.lab.visualization.plotting

    self.reference_front = reference_front self.dimension = None -
    [docs] @staticmethod +
    +[docs] + @staticmethod def get_points(solutions: List[S]) -> Tuple[pd.DataFrame, int]: - """ Get points for each solution of the front. + """Get points for each solution of the front. :param solutions: List of solutions. :return: Pandas dataframe with one column for each objective and one row for each solution. """ if solutions is None: - raise Exception('Front is none!') + raise Exception("Front is none!") points = pd.DataFrame(list(solution.objectives for solution in solutions)) return points, points.shape[1]
    -
    [docs] def plot(self, front, label='', normalize: bool = False, filename: str = None, format: str = 'eps'): - """ Plot any arbitrary number of fronts in 2D, 3D or p-coords. + +
    +[docs] + def plot(self, front, label="", normalize: bool = False, filename: str = None, format: str = "eps"): + """Plot any arbitrary number of fronts in 2D, 3D or p-coords. :param front: Pareto front or a list of them. :param label: Pareto front title or a list of them. @@ -174,9 +178,9 @@

    Source code for jmetal.lab.visualization.plotting

    label = [label] if len(front) != len(label): - raise Exception('Number of fronts and labels must be the same') + raise Exception("Number of fronts and labels must be the same") - dimension = front[0][0].number_of_objectives + dimension = len(front[0][0].objectives) if dimension == 2: self.two_dim(front, label, filename, format) @@ -185,8 +189,11 @@

    Source code for jmetal.lab.visualization.plotting

    else: self.pcoords(front, normalize, filename, format)
    -
    [docs] def two_dim(self, fronts: List[list], labels: List[str] = None, filename: str = None, format: str = 'eps'): - """ Plot any arbitrary number of fronts in 2D. + +
    +[docs] + def two_dim(self, fronts: List[list], labels: List[str] = None, filename: str = None, format: str = "eps"): + """Plot any arbitrary number of fronts in 2D. :param fronts: List of fronts (containing solutions). :param labels: List of fronts title (if any). @@ -204,33 +211,39 @@

    Source code for jmetal.lab.visualization.plotting

    points, _ = self.get_points(fronts[i]) ax = fig.add_subplot(n, n, i + 1) - points.plot(kind='scatter', x=0, y=1, ax=ax, s=10, color='#236FA4', alpha=1.0) + points.plot(kind="scatter", x=0, y=1, ax=ax, s=10, color="#236FA4", alpha=1.0) if labels: ax.set_title(labels[i]) if self.reference_front: - reference.plot(x=0, y=1, ax=ax, color='k', legend=False) + reference.plot(x=0, y=1, ax=ax, color="k", legend=False) if self.reference_point: for point in self.reference_point: - plt.plot([point[0]], [point[1]], marker='o', markersize=5, color='r') - plt.axvline(x=point[0], color='r', linestyle=':') - plt.axhline(y=point[1], color='r', linestyle=':') + plt.plot([point[0]], [point[1]], marker="o", markersize=5, color="r") + plt.axvline(x=point[0], color="r", linestyle=":") + plt.axhline(y=point[1], color="r", linestyle=":") if self.axis_labels: plt.xlabel(self.axis_labels[0]) plt.ylabel(self.axis_labels[1]) if filename: - plt.savefig(filename + '.' + format, format=format, dpi=200) + _filename = filename + "." + format + + plt.savefig(_filename, format=format, dpi=1000) + logger.info("Figure {_filename} saved to file") else: plt.show() plt.close(fig=fig)
    -
    [docs] def three_dim(self, fronts: List[list], labels: List[str] = None, filename: str = None, format: str = 'eps'): - """ Plot any arbitrary number of fronts in 3D. + +
    +[docs] + def three_dim(self, fronts: List[list], labels: List[str] = None, filename: str = None, format: str = "eps"): + """Plot any arbitrary number of fronts in 3D. :param fronts: List of fronts (containing solutions). :param labels: List of fronts title (if any). @@ -241,18 +254,22 @@

    Source code for jmetal.lab.visualization.plotting

    fig.suptitle(self.plot_title, fontsize=16) for i, _ in enumerate(fronts): - ax = fig.add_subplot(n, n, i + 1, projection='3d') - ax.scatter([s.objectives[0] for s in fronts[i]], - [s.objectives[1] for s in fronts[i]], - [s.objectives[2] for s in fronts[i]]) + ax = fig.add_subplot(n, n, i + 1, projection="3d") + ax.scatter( + [s.objectives[0] for s in fronts[i]], + [s.objectives[1] for s in fronts[i]], + [s.objectives[2] for s in fronts[i]], + ) if labels: ax.set_title(labels[i]) if self.reference_front: - ax.scatter([s.objectives[0] for s in self.reference_front], - [s.objectives[1] for s in self.reference_front], - [s.objectives[2] for s in self.reference_front]) + ax.scatter( + [s.objectives[0] for s in self.reference_front], + [s.objectives[1] for s in self.reference_front], + [s.objectives[2] for s in self.reference_front], + ) if self.reference_point: # todo @@ -264,14 +281,20 @@

    Source code for jmetal.lab.visualization.plotting

    ax.locator_params(nbins=4) if filename: - plt.savefig(filename + '.' + format, format=format, dpi=1000) + _filename = filename + "." + format + + plt.savefig(_filename, format=format, dpi=1000) + logger.info("Figure {_filename} saved to file") else: plt.show() plt.close(fig=fig)
    -
    [docs] def pcoords(self, fronts: List[list], normalize: bool = False, filename: str = None, format: str = 'eps'): - """ Plot any arbitrary number of fronts in parallel coordinates. + +
    +[docs] + def pcoords(self, fronts: List[list], normalize: bool = False, filename: str = None, format: str = "eps"): + """Plot any arbitrary number of fronts in parallel coordinates. :param fronts: List of fronts (containing solutions). :param filename: Output filename. @@ -289,8 +312,8 @@

    Source code for jmetal.lab.visualization.plotting

    ax = fig.add_subplot(n, n, i + 1) min_, max_ = points.values.min(), points.values.max() - points['scale'] = np.linspace(0, 1, len(points)) * (max_ - min_) + min_ - pd.plotting.parallel_coordinates(points, 'scale', ax=ax) + points["scale"] = np.linspace(0, 1, len(points)) * (max_ - min_) + min_ + pd.plotting.parallel_coordinates(points, "scale", ax=ax) ax.get_legend().remove() @@ -298,11 +321,13 @@

    Source code for jmetal.lab.visualization.plotting

    ax.set_xticklabels(self.axis_labels) if filename: - plt.savefig(filename + '.' + format, format=format, dpi=1000) + plt.savefig(filename + "." + format, format=format, dpi=1000) else: plt.show() - plt.close(fig=fig)
    + plt.close(fig=fig)
    +
    +
    @@ -319,8 +344,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.visualization.posterior — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,14 +106,25 @@

    Table Of Contents

    Source code for jmetal.lab.visualization.posterior

    -import numpy as np
    +import logging
    +
    +import numpy as np
     import pandas as pd
     from matplotlib import pyplot as plt
     
    +logger = logging.getLogger(__name__)
     
    -
    [docs]def plot_posterior(sample, higher_is_better: bool = False, min_points_per_hexbin: int = 2, alg_names: list = None, - filename: str = 'posterior.eps'): - """ + +
    +[docs] +def plot_posterior( + sample, + higher_is_better: bool = False, + min_points_per_hexbin: int = 2, + alg_names: list = None, + filename: str = "posterior.eps", +): + """ Plots the sample from posterior distribution of a Bayesian statistical test. Parameters: ----------- @@ -135,20 +143,18 @@

    Source code for jmetal.lab.visualization.posterior

    if sample.ndim == 2: nrow, ncol = sample.shape if ncol != 3: - raise ValueError( - 'Initialization ERROR. Incorrect number of dimensions in axis 1.') + raise ValueError("Initialization ERROR. Incorrect number of dimensions in axis 1.") else: - raise ValueError( - 'Initialization ERROR. Incorrect number of dimensions for sample') + raise ValueError("Initialization ERROR. Incorrect number of dimensions for sample") def transform(p): lambda1, lambda2, lambda3 = p.T - x = (0.1 * lambda1 + 0.5 * lambda2 + 0.9 * lambda3) + x = 0.1 * lambda1 + 0.5 * lambda2 + 0.9 * lambda3 y = (0.2 * lambda1 + 1.4 * lambda2 + 0.2 * lambda3) / np.sqrt(3) return np.vstack((x, y)).T # Initialize figure - fig = plt.figure(figsize=(5, 5), facecolor='white') + fig = plt.figure(figsize=(5, 5), facecolor="white") ax = fig.add_axes([0, 0, 1, 1]) ax.set_xlim(0, 1) ax.set_ylim(0, 1) @@ -158,34 +164,22 @@

    Source code for jmetal.lab.visualization.posterior

    if not higher_is_better: if not alg_names: - ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, - s='P(rope)', ha='center', va='bottom') - ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, - s='P(alg1<alg2)', ha='right', va='top') - ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, - s='P(alg1>alg2)', ha='left', va='top') + ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, s="P(rope)", ha="center", va="bottom") + ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, s="P(alg1<alg2)", ha="right", va="top") + ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, s="P(alg1>alg2)", ha="left", va="top") else: - ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, - s='P(rope)', ha='center', va='bottom') - ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, - s='P(' + alg_names[0] + ')', ha='right', va='top') - ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, - s='P(' + alg_names[1] + ')', ha='left', va='top') + ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, s="P(rope)", ha="center", va="bottom") + ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, s="P(" + alg_names[0] + ")", ha="right", va="top") + ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, s="P(" + alg_names[1] + ")", ha="left", va="top") else: if not alg_names: - ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, - s='P(rope)', ha='center', va='bottom') - ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, - s='P(alg2<alg1)', ha='right', va='top') - ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, - s='P(alg2>alg1)', ha='left', va='top') + ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, s="P(rope)", ha="center", va="bottom") + ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, s="P(alg2<alg1)", ha="right", va="top") + ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, s="P(alg2>alg1)", ha="left", va="top") else: - ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, - s='P(rope)', ha='center', va='bottom') - ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, - s='P(' + alg_names[1] + ')', ha='right', va='top') - ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, - s='P(' + alg_names[0] + ')', ha='left', va='top') + ax.text(x=0.5, y=1.4 / np.sqrt(3) + 0.005, s="P(rope)", ha="center", va="bottom") + ax.text(x=0.15, y=0.175 / np.sqrt(3) - 0.005, s="P(" + alg_names[1] + ")", ha="right", va="top") + ax.text(x=0.85, y=0.175 / np.sqrt(3) - 0.005, s="P(" + alg_names[0] + ")", ha="left", va="top") # Conversion between barycentric and Cartesian coordinates sample2d = np.zeros((sample.shape[0], 2)) @@ -197,32 +191,25 @@

    Source code for jmetal.lab.visualization.posterior

    # Plot triangle - ax.plot([0.095, 0.505], [0.2 / np.sqrt(3), 1.4 / np.sqrt(3)], - linewidth=3.0, color='white') - ax.plot([0.505, 0.905], [1.4 / np.sqrt(3), 0.2 / np.sqrt(3)], - linewidth=3.0, color='white') - ax.plot([0.09, 0.905], [0.2 / np.sqrt(3), 0.2 / np.sqrt(3)], - linewidth=3.0, color='white') + ax.plot([0.095, 0.505], [0.2 / np.sqrt(3), 1.4 / np.sqrt(3)], linewidth=3.0, color="white") + ax.plot([0.505, 0.905], [1.4 / np.sqrt(3), 0.2 / np.sqrt(3)], linewidth=3.0, color="white") + ax.plot([0.09, 0.905], [0.2 / np.sqrt(3), 0.2 / np.sqrt(3)], linewidth=3.0, color="white") - ax.plot([0.1, 0.5], [0.2 / np.sqrt(3), 1.4 / np.sqrt(3)], - linewidth=3.0, color='gray') - ax.plot([0.5, 0.9], [1.4 / np.sqrt(3), 0.2 / np.sqrt(3)], - linewidth=3.0, color='gray') - ax.plot([0.1, 0.9], [0.2 / np.sqrt(3), 0.2 / np.sqrt(3)], - linewidth=3.0, color='gray') + ax.plot([0.1, 0.5], [0.2 / np.sqrt(3), 1.4 / np.sqrt(3)], linewidth=3.0, color="gray") + ax.plot([0.5, 0.9], [1.4 / np.sqrt(3), 0.2 / np.sqrt(3)], linewidth=3.0, color="gray") + ax.plot([0.1, 0.9], [0.2 / np.sqrt(3), 0.2 / np.sqrt(3)], linewidth=3.0, color="gray") # plot division lines - ax.plot([0.5, 0.5], [0.2 / np.sqrt(3), 0.6 / np.sqrt(3)], - linewidth=3.0, color='gray') - ax.plot([0.3, 0.5], [0.8 / np.sqrt(3), 0.6 / np.sqrt(3)], - linewidth=3.0, color='gray') - ax.plot([0.5, 0.7], [0.6 / np.sqrt(3), 0.8 / np.sqrt(3)], - linewidth=3.0, color='gray') + ax.plot([0.5, 0.5], [0.2 / np.sqrt(3), 0.6 / np.sqrt(3)], linewidth=3.0, color="gray") + ax.plot([0.3, 0.5], [0.8 / np.sqrt(3), 0.6 / np.sqrt(3)], linewidth=3.0, color="gray") + ax.plot([0.5, 0.7], [0.6 / np.sqrt(3), 0.8 / np.sqrt(3)], linewidth=3.0, color="gray") if filename: - plt.savefig(filename, bbox_inches='tight') + plt.savefig(filename, bbox_inches="tight") + logger.info("Figure {filename} saved to file") plt.show()
    +
    @@ -239,8 +226,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.lab.visualization.streaming — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,7 +107,7 @@

    Table Of Contents

    Source code for jmetal.lab.visualization.streaming

     import logging
    -from typing import TypeVar, List
    +from typing import List, TypeVar
     
     import matplotlib
     from matplotlib import pyplot as plt
    @@ -118,9 +115,9 @@ 

    Source code for jmetal.lab.visualization.streaming

    from jmetal.lab.visualization.plotting import Plot -LOGGER = logging.getLogger('jmetal') +logger = logging.getLogger(__name__) -S = TypeVar('S') +S = TypeVar("S") """ .. module:: streaming @@ -131,14 +128,17 @@

    Source code for jmetal.lab.visualization.streaming

    """ -
    [docs]class StreamingPlot: - - def __init__(self, - plot_title: str = 'Pareto front approximation', - reference_front: List[S] = None, - reference_point: list = None, - axis_labels: list = None): - """ +
    +[docs] +class StreamingPlot: + def __init__( + self, + plot_title: str = "Pareto front approximation", + reference_front: List[S] = None, + reference_point: list = None, + axis_labels: list = None, + ): + """ :param plot_title: Title of the graph. :param axis_labels: List of axis labels. :param reference_point: Reference point (e.g., [0.4, 1.2]). @@ -155,13 +155,16 @@

    Source code for jmetal.lab.visualization.streaming

    self.dimension = None import warnings + warnings.filterwarnings("ignore", ".*GUI is implemented.*") self.fig, self.ax = plt.subplots() self.sc = None self.axis = None -
    [docs] def plot(self, front): +
    +[docs] + def plot(self, front): # Get data points, dimension = Plot.get_points(front) @@ -171,24 +174,33 @@

    Source code for jmetal.lab.visualization.streaming

    # If any reference point, plot if self.reference_point: for point in self.reference_point: - self.scp, = self.ax.plot(*[[p] for p in point], c='r', ls='None', marker='*', markersize=3) + (self.scp,) = self.ax.plot(*[[p] for p in point], c="r", ls="None", marker="*", markersize=3) # If any reference front, plot if self.reference_front: rpoints, _ = Plot.get_points(self.reference_front) - self.scf, = self.ax.plot(*[rpoints[column].tolist() for column in rpoints.columns.values], - c='k', ls='None', marker='*', markersize=1) + (self.scf,) = self.ax.plot( + *[rpoints[column].tolist() for column in rpoints.columns.values], + c="k", + ls="None", + marker="*", + markersize=1 + ) # Plot data - self.sc, = self.ax.plot(*[points[column].tolist() for column in points.columns.values], - ls='None', marker='o', markersize=4) + (self.sc,) = self.ax.plot( + *[points[column].tolist() for column in points.columns.values], ls="None", marker="o", markersize=4 + ) # Show plot plt.show(block=False)
    -
    [docs] def update(self, front: List[S], reference_point: list = None) -> None: + +
    +[docs] + def update(self, front: List[S], reference_point: list = None) -> None: if self.sc is None: - raise Exception('Figure is none') + raise Exception("Figure is none") points, dimension = Plot.get_points(front) @@ -214,31 +226,38 @@

    Source code for jmetal.lab.visualization.streaming

    pause(0.01)
    -
    [docs] def create_layout(self, dimension: int) -> None: - self.fig.canvas.set_window_title(self.plot_title) + +
    +[docs] + def create_layout(self, dimension: int) -> None: + logger.info("Creating figure layout") + + self.fig.canvas.manager.set_window_title(self.plot_title) self.fig.suptitle(self.plot_title, fontsize=16) if dimension == 2: # Stylize axis - self.ax.spines['top'].set_visible(False) - self.ax.spines['right'].set_visible(False) + self.ax.spines["top"].set_visible(False) + self.ax.spines["right"].set_visible(False) self.ax.get_xaxis().tick_bottom() self.ax.get_yaxis().tick_left() elif dimension == 3: self.ax = Axes3D(self.fig) - self.ax.autoscale(enable=True, axis='both') + self.ax.autoscale(enable=True, axis="both") else: - raise Exception('Dimension must be either 2 or 3') + raise Exception("Dimension must be either 2 or 3") self.ax.set_autoscale_on(True) self.ax.autoscale_view(True, True, True) # Style options - self.ax.grid(color='#f0f0f5', linestyle='-', linewidth=0.5, alpha=0.5)
    + self.ax.grid(color="#f0f0f5", linestyle="-", linewidth=0.5, alpha=0.5)
    +
    + def pause(interval: float): - backend = plt.rcParams['backend'] + backend = plt.rcParams["backend"] if backend in matplotlib.rcsetup.interactive_bk: figManager = matplotlib._pylab_helpers.Gcf.get_active() @@ -264,8 +283,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.operator.crossover — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -114,7 +111,15 @@

    Source code for jmetal.operator.crossover

     from typing import List
     
     from jmetal.core.operator import Crossover
    -from jmetal.core.solution import Solution, FloatSolution, BinarySolution, PermutationSolution
    +from jmetal.core.solution import (
    +    BinarySolution,
    +    CompositeSolution,
    +    FloatSolution,
    +    IntegerSolution,
    +    PermutationSolution,
    +    Solution,
    +)
    +from jmetal.util.ckecking import Check
     
     """
     .. module:: crossover
    @@ -125,38 +130,55 @@ 

    Source code for jmetal.operator.crossover

     """
     
     
    -
    [docs]class NullCrossover(Crossover[Solution, Solution]): - +
    +[docs] +class NullCrossover(Crossover[Solution, Solution]): def __init__(self): super(NullCrossover, self).__init__(probability=0.0) -
    [docs] def execute(self, parents: List[Solution]) -> List[Solution]: +
    +[docs] + def execute(self, parents: List[Solution]) -> List[Solution]: if len(parents) != 2: - raise Exception('The number of parents is not two: {}'.format(len(parents))) + raise Exception("The number of parents is not two: {}".format(len(parents))) return parents
    -
    [docs] def get_number_of_parents(self) -> int: + +
    +[docs] + def get_number_of_parents(self) -> int: return 2
    -
    [docs] def get_number_of_children(self) -> int: + +
    +[docs] + def get_number_of_children(self) -> int: return 2
    -
    [docs] def get_name(self): - return 'Null crossover'
    + +
    +[docs] + def get_name(self): + return "Null crossover"
    +
    -
    [docs]class PMXCrossover(Crossover[PermutationSolution, PermutationSolution]): +
    +[docs] +class PMXCrossover(Crossover[PermutationSolution, PermutationSolution]): def __init__(self, probability: float): super(PMXCrossover, self).__init__(probability=probability) -
    [docs] def execute(self, parents: List[PermutationSolution]) -> List[PermutationSolution]: +
    +[docs] + def execute(self, parents: List[PermutationSolution]) -> List[PermutationSolution]: if len(parents) != 2: - raise Exception('The number of parents is not two: {}'.format(len(parents))) + raise Exception("The number of parents is not two: {}".format(len(parents))) - offspring = [copy.deepcopy(parents[0]), copy.deepcopy(parents[1])] - permutation_length = offspring[0].number_of_variables + offspring = copy.deepcopy(parents) + permutation_length = len(offspring[0].variables) rand = random.random() if rand <= self.probability: @@ -188,81 +210,112 @@

    Source code for jmetal.operator.crossover

                                     swapped[i_son][i_chromosome] = map_[1 - i_son][map_index]
                     return s1, s2
     
    -            swapped = _swap(parents[0].variables, parents[1].variables, cross_points)
    +            swapped = _swap(offspring[0].variables, offspring[1].variables, cross_points)
                 mapped = _map(swapped, cross_points)
     
                 offspring[0].variables, offspring[1].variables = mapped
     
             return offspring
    -
    [docs] def get_number_of_parents(self) -> int: + +
    +[docs] + def get_number_of_parents(self) -> int: return 2
    -
    [docs] def get_number_of_children(self) -> int: + +
    +[docs] + def get_number_of_children(self) -> int: return 2
    -
    [docs] def get_name(self): - return 'Partially Matched crossover'
    + +
    +[docs] + def get_name(self): + return "Partially Matched crossover"
    +
    -
    [docs]class CXCrossover(Crossover[PermutationSolution, PermutationSolution]): +
    +[docs] +class CXCrossover(Crossover[PermutationSolution, PermutationSolution]): def __init__(self, probability: float): super(CXCrossover, self).__init__(probability=probability) -
    [docs] def execute(self, parents: List[PermutationSolution]) -> List[PermutationSolution]: +
    +[docs] + def execute(self, parents: List[PermutationSolution]) -> List[PermutationSolution]: if len(parents) != 2: - raise Exception('The number of parents is not two: {}'.format(len(parents))) + raise Exception("The number of parents is not two: {}".format(len(parents))) - offspring = [copy.deepcopy(parents[1]), copy.deepcopy(parents[0])] + offspring = copy.deepcopy(parents[::-1]) rand = random.random() if rand <= self.probability: - for i in range(parents[0].number_of_variables): - idx = random.randint(0, len(parents[0].variables[i]) - 1) - curr_idx = idx - cycle = [] + idx = random.randint(0, len(parents[0].variables) - 1) + curr_idx = idx + cycle = [] - while True: - cycle.append(curr_idx) - curr_idx = parents[0].variables[i].index(parents[1].variables[i][curr_idx]) + while True: + cycle.append(curr_idx) + curr_idx = parents[0].variables.index(parents[1].variables[curr_idx]) - if curr_idx == idx: - break + if curr_idx == idx: + break - for j in range(len(parents[0].variables[i])): - if j in cycle: - offspring[0].variables[i][j] = parents[0].variables[i][j] - offspring[1].variables[i][j] = parents[0].variables[i][j] + for j in range(len(parents[0].variables)): + if j in cycle: + offspring[0].variables[j] = parents[0].variables[j] + offspring[1].variables[j] = parents[1].variables[j] return offspring
    -
    [docs] def get_number_of_parents(self) -> int: + +
    +[docs] + def get_number_of_parents(self) -> int: return 2
    -
    [docs] def get_number_of_children(self) -> int: + +
    +[docs] + def get_number_of_children(self) -> int: return 2
    -
    [docs] def get_name(self): - return 'Cycle crossover'
    + +
    +[docs] + def get_name(self): + return "Cycle crossover"
    +
    -
    [docs]class SBXCrossover(Crossover[FloatSolution, FloatSolution]): + +
    +[docs] +class SBXCrossover(Crossover[FloatSolution, FloatSolution]): __EPS = 1.0e-14 def __init__(self, probability: float, distribution_index: float = 20.0): super(SBXCrossover, self).__init__(probability=probability) self.distribution_index = distribution_index + if distribution_index < 0: + raise Exception("The distribution index is negative: " + str(distribution_index)) -
    [docs] def execute(self, parents: List[FloatSolution]) -> List[FloatSolution]: - if len(parents) != 2: - raise Exception('The number of parents is not two: {}'.format(len(parents))) +
    +[docs] + def execute(self, parents: List[FloatSolution]) -> List[FloatSolution]: + Check.that(issubclass(type(parents[0]), FloatSolution), "Solution type invalid: " + str(type(parents[0]))) + Check.that(issubclass(type(parents[1]), FloatSolution), "Solution type invalid") + Check.that(len(parents) == 2, "The number of parents is not two: {}".format(len(parents))) - offspring = [copy.deepcopy(parents[0]), copy.deepcopy(parents[1])] + offspring = copy.deepcopy(parents) rand = random.random() if rand <= self.probability: - for i in range(parents[0].number_of_variables): + for i in range(len(parents[0].variables)): value_x1, value_x2 = parents[0].variables[i], parents[1].variables[i] if random.random() <= 0.5: @@ -317,26 +370,137 @@

    Source code for jmetal.operator.crossover

                         offspring[1].variables[i] = value_x2
             return offspring
    -
    [docs] def get_number_of_parents(self) -> int: + +
    +[docs] + def get_number_of_parents(self) -> int: + return 2
    + + +
    +[docs] + def get_number_of_children(self) -> int: + return 2
    + + +
    +[docs] + def get_name(self) -> str: + return "SBX crossover"
    +
    + + + +
    +[docs] +class IntegerSBXCrossover(Crossover[IntegerSolution, IntegerSolution]): + __EPS = 1.0e-14 + + def __init__(self, probability: float, distribution_index: float = 20.0): + super(IntegerSBXCrossover, self).__init__(probability=probability) + self.distribution_index = distribution_index + +
    +[docs] + def execute(self, parents: List[IntegerSolution]) -> List[IntegerSolution]: + Check.that(issubclass(type(parents[0]), IntegerSolution), "Solution type invalid") + Check.that(issubclass(type(parents[1]), IntegerSolution), "Solution type invalid") + Check.that(len(parents) == 2, "The number of parents is not two: {}".format(len(parents))) + + offspring = copy.deepcopy(parents) + rand = random.random() + + if rand <= self.probability: + for i in range(len(parents[0].variables)): + value_x1, value_x2 = parents[0].variables[i], parents[1].variables[i] + + if random.random() <= 0.5: + if abs(value_x1 - value_x2) > self.__EPS: + if value_x1 < value_x2: + y1, y2 = value_x1, value_x2 + else: + y1, y2 = value_x2, value_x1 + + lower_bound, upper_bound = parents[0].lower_bound[i], parents[1].upper_bound[i] + + beta = 1.0 + (2.0 * (y1 - lower_bound) / (y2 - y1)) + alpha = 2.0 - pow(beta, -(self.distribution_index + 1.0)) + + rand = random.random() + if rand <= (1.0 / alpha): + betaq = pow(rand * alpha, (1.0 / (self.distribution_index + 1.0))) + else: + betaq = pow(1.0 / (2.0 - rand * alpha), 1.0 / (self.distribution_index + 1.0)) + + c1 = 0.5 * (y1 + y2 - betaq * (y2 - y1)) + beta = 1.0 + (2.0 * (upper_bound - y2) / (y2 - y1)) + alpha = 2.0 - pow(beta, -(self.distribution_index + 1.0)) + + if rand <= (1.0 / alpha): + betaq = pow((rand * alpha), (1.0 / (self.distribution_index + 1.0))) + else: + betaq = pow(1.0 / (2.0 - rand * alpha), 1.0 / (self.distribution_index + 1.0)) + + c2 = 0.5 * (y1 + y2 + betaq * (y2 - y1)) + + if c1 < lower_bound: + c1 = lower_bound + if c2 < lower_bound: + c2 = lower_bound + if c1 > upper_bound: + c1 = upper_bound + if c2 > upper_bound: + c2 = upper_bound + + if random.random() <= 0.5: + offspring[0].variables[i] = int(c2) + offspring[1].variables[i] = int(c1) + else: + offspring[0].variables[i] = int(c1) + offspring[1].variables[i] = int(c2) + else: + offspring[0].variables[i] = value_x1 + offspring[1].variables[i] = value_x2 + else: + offspring[0].variables[i] = value_x1 + offspring[1].variables[i] = value_x2 + return offspring
    + + +
    +[docs] + def get_number_of_parents(self) -> int: return 2
    -
    [docs] def get_number_of_children(self) -> int: + +
    +[docs] + def get_number_of_children(self) -> int: return 2
    -
    [docs] def get_name(self) -> str: - return 'SBX crossover'
    +
    +[docs] + def get_name(self) -> str: + return "Integer SBX crossover"
    +
    -
    [docs]class SPXCrossover(Crossover[BinarySolution, BinarySolution]): + +
    +[docs] +class SPXCrossover(Crossover[BinarySolution, BinarySolution]): def __init__(self, probability: float): super(SPXCrossover, self).__init__(probability=probability) -
    [docs] def execute(self, parents: List[BinarySolution]) -> List[BinarySolution]: - if len(parents) != 2: - raise Exception('The number of parents is not two: {}'.format(len(parents))) +
    +[docs] + def execute(self, parents: List[BinarySolution]) -> List[BinarySolution]: + Check.that(type(parents[0]) is BinarySolution, "Solution type invalid") + Check.that(type(parents[1]) is BinarySolution, "Solution type invalid") + Check.that(len(parents) == 2, "The number of parents is not two: {}".format(len(parents))) - offspring = [copy.deepcopy(parents[0]), copy.deepcopy(parents[1])] + offspring = copy.deepcopy(parents) rand = random.random() if rand <= self.probability: @@ -370,30 +534,43 @@

    Source code for jmetal.operator.crossover

                 offspring[1].variables[variable_to_cut] = bitset2
     
                 # 6. Apply the crossover to the other variables
    -            for i in range(variable_to_cut + 1, parents[0].number_of_variables):
    +            for i in range(variable_to_cut + 1, len(parents[0].variables)):
                     offspring[0].variables[i] = copy.deepcopy(parents[1].variables[i])
                     offspring[1].variables[i] = copy.deepcopy(parents[0].variables[i])
     
             return offspring
    -
    [docs] def get_number_of_parents(self) -> int: + +
    +[docs] + def get_number_of_parents(self) -> int: return 2
    -
    [docs] def get_number_of_children(self) -> int: + +
    +[docs] + def get_number_of_children(self) -> int: return 2
    -
    [docs] def get_name(self) -> str: - return 'Single point crossover'
    + +
    +[docs] + def get_name(self) -> str: + return "Single point crossover"
    +
    + -
    [docs]class DifferentialEvolutionCrossover(Crossover[FloatSolution, FloatSolution]): - """ This operator receives two parameters: the current individual and an array of three parent individuals. The +
    +[docs] +class DifferentialEvolutionCrossover(Crossover[FloatSolution, FloatSolution]): + """This operator receives two parameters: the current individual and an array of three parent individuals. The best and rand variants depends on the third parent, according whether it represents the current of the "best" individual or a random_search one. The implementation of both variants are the same, due to that the parent selection is external to the crossover operator. """ - def __init__(self, CR: float, F: float, K: float): + def __init__(self, CR: float, F: float, K: float = 0.5): super(DifferentialEvolutionCrossover, self).__init__(probability=1.0) self.CR = CR self.F = F @@ -401,15 +578,16 @@

    Source code for jmetal.operator.crossover

     
             self.current_individual: FloatSolution = None
     
    -
    [docs] def execute(self, parents: List[FloatSolution]) -> List[FloatSolution]: - """ Execute the differential evolution crossover ('best/1/bin' variant in jMetal). - """ +
    +[docs] + def execute(self, parents: List[FloatSolution]) -> List[FloatSolution]: + """Execute the differential evolution crossover ('best/1/bin' variant in jMetal).""" if len(parents) != self.get_number_of_parents(): - raise Exception('The number of parents is not {}: {}'.format(self.get_number_of_parents(), len(parents))) + raise Exception("The number of parents is not {}: {}".format(self.get_number_of_parents(), len(parents))) child = copy.deepcopy(self.current_individual) - number_of_variables = parents[0].number_of_variables + number_of_variables = len(parents[0].variables) rand = random.randint(0, number_of_variables - 1) for i in range(number_of_variables): @@ -427,14 +605,81 @@

    Source code for jmetal.operator.crossover

     
             return [child]
    -
    [docs] def get_number_of_parents(self) -> int: + +
    +[docs] + def get_number_of_parents(self) -> int: return 3
    -
    [docs] def get_number_of_children(self) -> int: + +
    +[docs] + def get_number_of_children(self) -> int: return 1
    -
    [docs] def get_name(self) -> str: - return 'Differential Evolution crossover'
    + +
    +[docs] + def get_name(self) -> str: + return "Differential Evolution crossover"
    +
    + + + +
    +[docs] +class CompositeCrossover(Crossover[CompositeSolution, CompositeSolution]): + __EPS = 1.0e-14 + + def __init__(self, crossover_operator_list: [Crossover]): + super(CompositeCrossover, self).__init__(probability=1.0) + + Check.is_not_none(crossover_operator_list) + Check.collection_is_not_empty(crossover_operator_list) + + self.crossover_operators_list = [] + for operator in crossover_operator_list: + Check.that(issubclass(operator.__class__, Crossover), "Object is not a subclass of Crossover") + self.crossover_operators_list.append(operator) + +
    +[docs] + def execute(self, solutions: List[CompositeSolution]) -> List[CompositeSolution]: + Check.is_not_none(solutions) + Check.that(len(solutions) == 2, "The number of parents is not two: " + str(len(solutions))) + + offspring1 = [] + offspring2 = [] + + number_of_solutions_in_composite_solution = len(solutions[0].variables) + + for i in range(number_of_solutions_in_composite_solution): + parents = [solutions[0].variables[i], solutions[1].variables[i]] + children = self.crossover_operators_list[i].execute(parents) + offspring1.append(children[0]) + offspring2.append(children[1]) + + return [CompositeSolution(offspring1), CompositeSolution(offspring2)]
    + + +
    +[docs] + def get_number_of_parents(self) -> int: + return 2
    + + +
    +[docs] + def get_number_of_children(self) -> int: + return 2
    + + +
    +[docs] + def get_name(self) -> str: + return "Composite crossover"
    +
    +
    @@ -451,8 +696,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.operator.mutation — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -112,7 +109,15 @@

    Source code for jmetal.operator.mutation

     import random
     
     from jmetal.core.operator import Mutation
    -from jmetal.core.solution import BinarySolution, Solution, FloatSolution, IntegerSolution, PermutationSolution
    +from jmetal.core.solution import (
    +    BinarySolution,
    +    CompositeSolution,
    +    FloatSolution,
    +    IntegerSolution,
    +    PermutationSolution,
    +    Solution,
    +)
    +from jmetal.util.ckecking import Check
     
     """
     .. module:: mutation
    @@ -123,25 +128,38 @@ 

    Source code for jmetal.operator.mutation

     """
     
     
    -
    [docs]class NullMutation(Mutation[Solution]): - +
    +[docs] +class NullMutation(Mutation[Solution]): def __init__(self): super(NullMutation, self).__init__(probability=0) -
    [docs] def execute(self, solution: Solution) -> Solution: +
    +[docs] + def execute(self, solution: Solution) -> Solution: return solution
    -
    [docs] def get_name(self): - return 'Null mutation'
    + +
    +[docs] + def get_name(self): + return "Null mutation"
    +
    -
    [docs]class BitFlipMutation(Mutation[BinarySolution]): +
    +[docs] +class BitFlipMutation(Mutation[BinarySolution]): def __init__(self, probability: float): super(BitFlipMutation, self).__init__(probability=probability) -
    [docs] def execute(self, solution: BinarySolution) -> BinarySolution: - for i in range(solution.number_of_variables): +
    +[docs] + def execute(self, solution: BinarySolution) -> BinarySolution: + Check.that(type(solution) is BinarySolution, "Solution type invalid") + + for i in range(len(solution.variables)): for j in range(len(solution.variables[i])): rand = random.random() if rand <= self.probability: @@ -149,18 +167,27 @@

    Source code for jmetal.operator.mutation

     
             return solution
    -
    [docs] def get_name(self): - return 'BitFlip mutation'
    +
    +[docs] + def get_name(self): + return "BitFlip mutation"
    +
    -
    [docs]class PolynomialMutation(Mutation[FloatSolution]): + +
    +[docs] +class PolynomialMutation(Mutation[FloatSolution]): def __init__(self, probability: float, distribution_index: float = 0.20): super(PolynomialMutation, self).__init__(probability=probability) self.distribution_index = distribution_index -
    [docs] def execute(self, solution: FloatSolution) -> FloatSolution: - for i in range(solution.number_of_variables): +
    +[docs] + def execute(self, solution: FloatSolution) -> FloatSolution: + Check.that(issubclass(type(solution), FloatSolution), "Solution type invalid") + for i in range(len(solution.variables)): rand = random.random() if rand <= self.probability: @@ -193,18 +220,28 @@

    Source code for jmetal.operator.mutation

     
             return solution
    -
    [docs] def get_name(self): - return 'Polynomial mutation'
    + +
    +[docs] + def get_name(self): + return "Polynomial mutation"
    +
    -
    [docs]class IntegerPolynomialMutation(Mutation[IntegerSolution]): +
    +[docs] +class IntegerPolynomialMutation(Mutation[IntegerSolution]): def __init__(self, probability: float, distribution_index: float = 0.20): super(IntegerPolynomialMutation, self).__init__(probability=probability) self.distribution_index = distribution_index -
    [docs] def execute(self, solution: IntegerSolution) -> IntegerSolution: - for i in range(solution.number_of_variables): +
    +[docs] + def execute(self, solution: IntegerSolution) -> IntegerSolution: + Check.that(issubclass(type(solution), IntegerSolution), "Solution type invalid") + + for i in range(len(solution.variables)): if random.random() <= self.probability: y = solution.variables[i] yl, yu = solution.lower_bound[i], solution.upper_bound[i] @@ -219,11 +256,11 @@

    Source code for jmetal.operator.mutation

                         if rnd <= 0.5:
                             xy = 1.0 - delta1
                             val = 2.0 * rnd + (1.0 - 2.0 * rnd) * (xy ** (self.distribution_index + 1.0))
    -                        deltaq = val ** mut_pow - 1.0
    +                        deltaq = val**mut_pow - 1.0
                         else:
                             xy = 1.0 - delta2
                             val = 2.0 * (1.0 - rnd) + 2.0 * (rnd - 0.5) * (xy ** (self.distribution_index + 1.0))
    -                        deltaq = 1.0 - val ** mut_pow
    +                        deltaq = 1.0 - val**mut_pow
     
                         y += deltaq * (yu - yl)
                         if y < solution.lower_bound[i]:
    @@ -234,35 +271,56 @@ 

    Source code for jmetal.operator.mutation

                     solution.variables[i] = int(round(y))
             return solution
    -
    [docs] def get_name(self): - return 'Polynomial mutation (Integer)'
    + +
    +[docs] + def get_name(self): + return "Polynomial mutation (Integer)"
    +
    -
    [docs]class SimpleRandomMutation(Mutation[FloatSolution]): +
    +[docs] +class SimpleRandomMutation(Mutation[FloatSolution]): def __init__(self, probability: float): super(SimpleRandomMutation, self).__init__(probability=probability) -
    [docs] def execute(self, solution: FloatSolution) -> FloatSolution: - for i in range(solution.number_of_variables): +
    +[docs] + def execute(self, solution: FloatSolution) -> FloatSolution: + Check.that(type(solution) is FloatSolution, "Solution type invalid") + + for i in range(len(solution.variables)): rand = random.random() if rand <= self.probability: - solution.variables[i] = solution.lower_bound[i] + \ - (solution.upper_bound[i] - solution.lower_bound[i]) * random.random() + solution.variables[i] = ( + solution.lower_bound[i] + (solution.upper_bound[i] - solution.lower_bound[i]) * random.random() + ) return solution
    -
    [docs] def get_name(self): - return 'Simple random_search mutation'
    + +
    +[docs] + def get_name(self): + return "Simple random_search mutation"
    +
    -
    [docs]class UniformMutation(Mutation[FloatSolution]): +
    +[docs] +class UniformMutation(Mutation[FloatSolution]): def __init__(self, probability: float, perturbation: float = 0.5): super(UniformMutation, self).__init__(probability=probability) self.perturbation = perturbation -
    [docs] def execute(self, solution: FloatSolution) -> FloatSolution: - for i in range(solution.number_of_variables): +
    +[docs] + def execute(self, solution: FloatSolution) -> FloatSolution: + Check.that(type(solution) is FloatSolution, "Solution type invalid") + + for i in range(len(solution.variables)): rand = random.random() if rand <= self.probability: @@ -278,20 +336,30 @@

    Source code for jmetal.operator.mutation

     
             return solution
    -
    [docs] def get_name(self): - return 'Uniform mutation'
    +
    +[docs] + def get_name(self): + return "Uniform mutation"
    +
    -
    [docs]class NonUniformMutation(Mutation[FloatSolution]): + +
    +[docs] +class NonUniformMutation(Mutation[FloatSolution]): def __init__(self, probability: float, perturbation: float = 0.5, max_iterations: int = 0.5): super(NonUniformMutation, self).__init__(probability=probability) self.perturbation = perturbation self.max_iterations = max_iterations self.current_iteration = 0 -
    [docs] def execute(self, solution: FloatSolution) -> FloatSolution: - for i in range(solution.number_of_variables): +
    +[docs] + def execute(self, solution: FloatSolution) -> FloatSolution: + Check.that(type(solution) is FloatSolution, "Solution type invalid") + + for i in range(len(solution.variables)): if random.random() <= self.probability: rand = random.random() @@ -311,58 +379,123 @@

    Source code for jmetal.operator.mutation

     
             return solution
    -
    [docs] def set_current_iteration(self, current_iteration: int): + +
    +[docs] + def set_current_iteration(self, current_iteration: int): self.current_iteration = current_iteration
    + def __delta(self, y: float, b_mutation_parameter: float): - return (y * (1.0 - pow(random.random(), - pow((1.0 - 1.0 * self.current_iteration / self.max_iterations), b_mutation_parameter)))) + return y * ( + 1.0 + - pow( + random.random(), pow((1.0 - 1.0 * self.current_iteration / self.max_iterations), b_mutation_parameter) + ) + ) + +
    +[docs] + def get_name(self): + return "Uniform mutation"
    +
    -
    [docs] def get_name(self): - return 'Uniform mutation'
    -
    [docs]class PermutationSwapMutation(Mutation[PermutationSolution]): +
    +[docs] +class PermutationSwapMutation(Mutation[PermutationSolution]): +
    +[docs] + def execute(self, solution: PermutationSolution) -> PermutationSolution: + Check.that(type(solution) is PermutationSolution, "Solution type invalid") -
    [docs] def execute(self, solution: PermutationSolution) -> PermutationSolution: rand = random.random() if rand <= self.probability: - pos_one, pos_two = random.sample(range(solution.number_of_variables - 1), 2) - solution.variables[pos_one], solution.variables[pos_two] = \ - solution.variables[pos_two], solution.variables[pos_one] + pos_one, pos_two = random.sample(range(len(solution.variables)), 2) + solution.variables[pos_one], solution.variables[pos_two] = ( + solution.variables[pos_two], + solution.variables[pos_one], + ) return solution
    -
    [docs] def get_name(self): - return 'Permutation Swap mutation'
    +
    +[docs] + def get_name(self): + return "Permutation Swap mutation"
    +
    -
    [docs]class ScrambleMutation(Mutation[PermutationSolution]): -
    [docs] def execute(self, solution: PermutationSolution) -> PermutationSolution: - for i in range(solution.number_of_variables): - rand = random.random() - if rand <= self.probability: - point1 = random.randint(0, len(solution.variables[i])) - point2 = random.randint(0, len(solution.variables[i]) - 1) +
    +[docs] +class CompositeMutation(Mutation[Solution]): + def __init__(self, mutation_operator_list: [Mutation]): + super(CompositeMutation, self).__init__(probability=1.0) - if point2 >= point1: - point2 += 1 - else: - point1, point2 = point2, point1 + Check.is_not_none(mutation_operator_list) + Check.collection_is_not_empty(mutation_operator_list) + + self.mutation_operators_list = [] + for operator in mutation_operator_list: + Check.that(issubclass(operator.__class__, Mutation), "Object is not a subclass of Mutation") + self.mutation_operators_list.append(operator) + +
    +[docs] + def execute(self, solution: CompositeSolution) -> CompositeSolution: + Check.is_not_none(solution) + + mutated_solution_components = [] + for i in range(len(solution.variables)): + mutated_solution_components.append(self.mutation_operators_list[i].execute(solution.variables[i])) + + return CompositeSolution(mutated_solution_components)
    + + +
    +[docs] + def get_name(self) -> str: + return "Composite mutation operator"
    +
    - if point2 - point1 >= 20: - point2 = point1 + 20 - values = solution.variables[i][point1:point2] - solution.variables[i][point1:point2] = random.sample(values, len(values)) + +
    +[docs] +class ScrambleMutation(Mutation[PermutationSolution]): +
    +[docs] + def execute(self, solution: PermutationSolution) -> PermutationSolution: + rand = random.random() + + if rand <= self.probability: + point1 = random.randint(0, len(solution.variables)) + point2 = random.randint(0, len(solution.variables) - 1) + + if point2 >= point1: + point2 += 1 + else: + point1, point2 = point2, point1 + + if point2 - point1 >= 20: + point2 = point1 + 20 + + values = solution.variables[point1:point2] + solution.variables[point1:point2] = random.sample(values, len(values)) return solution
    -
    [docs] def get_name(self): - return 'Scramble'
    + +
    +[docs] + def get_name(self): + return "Scramble"
    +
    +
    @@ -379,8 +512,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.operator.selection — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -115,11 +112,12 @@

    Source code for jmetal.operator.selection

     import numpy as np
     
     from jmetal.core.operator import Selection
    +from jmetal.core.solution import Solution
    +from jmetal.util.comparator import Comparator, DominanceComparator
     from jmetal.util.density_estimator import CrowdingDistance
     from jmetal.util.ranking import FastNonDominatedRanking
    -from jmetal.util.comparator import Comparator, DominanceComparator
     
    -S = TypeVar('S')
    +S = TypeVar("S", bound=Solution)
     
     """
     .. module:: selection
    @@ -130,18 +128,21 @@ 

    Source code for jmetal.operator.selection

     """
     
     
    -
    [docs]class RouletteWheelSelection(Selection[List[S], S]): - """Performs roulette wheel selection. - """ +
    +[docs] +class RouletteWheelSelection(Selection[List[S], S]): + """Performs roulette wheel selection.""" def __init__(self): super(RouletteWheelSelection).__init__() -
    [docs] def execute(self, front: List[S]) -> S: +
    +[docs] + def execute(self, front: List[S]) -> S: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") maximum = sum([solution.objectives[0] for solution in front]) rand = random.uniform(0.0, maximum) @@ -155,21 +156,29 @@

    Source code for jmetal.operator.selection

     
             return None
    -
    [docs] def get_name(self) -> str: - return 'Roulette wheel selection'
    +
    +[docs] + def get_name(self) -> str: + return "Roulette wheel selection"
    +
    -
    [docs]class BinaryTournamentSelection(Selection[List[S], S]): + +
    +[docs] +class BinaryTournamentSelection(Selection[List[S], S]): def __init__(self, comparator: Comparator = DominanceComparator()): super(BinaryTournamentSelection, self).__init__() self.comparator = comparator -
    [docs] def execute(self, front: List[S]) -> S: +
    +[docs] + def execute(self, front: List[S]) -> S: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") if len(front) == 1: result = front[0] @@ -190,20 +199,28 @@

    Source code for jmetal.operator.selection

     
             return result
    -
    [docs] def get_name(self) -> str: - return 'Binary tournament selection'
    + +
    +[docs] + def get_name(self) -> str: + return "Binary tournament selection"
    +
    -
    [docs]class BestSolutionSelection(Selection[List[S], S]): +
    +[docs] +class BestSolutionSelection(Selection[List[S], S]): def __init__(self): super(BestSolutionSelection, self).__init__() -
    [docs] def execute(self, front: List[S]) -> S: +
    +[docs] + def execute(self, front: List[S]) -> S: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") result = front[0] @@ -213,47 +230,63 @@

    Source code for jmetal.operator.selection

     
             return result
    -
    [docs] def get_name(self) -> str: - return 'Best solution selection'
    + +
    +[docs] + def get_name(self) -> str: + return "Best solution selection"
    +
    -
    [docs]class NaryRandomSolutionSelection(Selection[List[S], S]): +
    +[docs] +class NaryRandomSolutionSelection(Selection[List[S], S]): def __init__(self, number_of_solutions_to_be_returned: int = 1): super(NaryRandomSolutionSelection, self).__init__() if number_of_solutions_to_be_returned < 0: - raise Exception('The number of solutions to be returned must be positive integer') + raise Exception("The number of solutions to be returned must be positive integer") self.number_of_solutions_to_be_returned = number_of_solutions_to_be_returned -
    [docs] def execute(self, front: List[S]) -> S: +
    +[docs] + def execute(self, front: List[S]) -> S: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") if len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") if len(front) < self.number_of_solutions_to_be_returned: - raise Exception('The front contains less elements than required') + raise Exception("The front contains less elements than required") # random_search sampling without replacement return random.sample(front, self.number_of_solutions_to_be_returned)
    -
    [docs] def get_name(self) -> str: - return 'Nary random_search solution selection'
    + +
    +[docs] + def get_name(self) -> str: + return "Nary random_search solution selection"
    +
    -
    [docs]class DifferentialEvolutionSelection(Selection[List[S], List[S]]): +
    +[docs] +class DifferentialEvolutionSelection(Selection[List[S], List[S]]): def __init__(self): super(DifferentialEvolutionSelection, self).__init__() self.index_to_exclude = None -
    [docs] def execute(self, front: List[S]) -> List[S]: +
    +[docs] + def execute(self, front: List[S]) -> List[S]: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") elif len(front) < 4: - raise Exception('The front has less than four solutions: ' + str(len(front))) + raise Exception("The front has less than four solutions: " + str(len(front))) selected_indexes = random.sample(range(len(front)), 3) while self.index_to_exclude in selected_indexes: @@ -261,42 +294,61 @@

    Source code for jmetal.operator.selection

     
             return [front[i] for i in selected_indexes]
    -
    [docs] def set_index_to_exclude(self, index: int): + +
    +[docs] + def set_index_to_exclude(self, index: int): self.index_to_exclude = index
    -
    [docs] def get_name(self) -> str: - return "Differential evolution selection"
    +
    +[docs] + def get_name(self) -> str: + return "Differential evolution selection"
    +
    -
    [docs]class RandomSolutionSelection(Selection[List[S], S]): + +
    +[docs] +class RandomSolutionSelection(Selection[List[S], S]): def __init__(self): super(RandomSolutionSelection, self).__init__() -
    [docs] def execute(self, front: List[S]) -> S: +
    +[docs] + def execute(self, front: List[S]) -> S: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") return random.choice(front)
    -
    [docs] def get_name(self) -> str: - return 'Random solution selection'
    + +
    +[docs] + def get_name(self) -> str: + return "Random solution selection"
    +
    -
    [docs]class RankingAndCrowdingDistanceSelection(Selection[List[S], List[S]]): +
    +[docs] +class RankingAndCrowdingDistanceSelection(Selection[List[S], List[S]]): def __init__(self, max_population_size: int, dominance_comparator: Comparator = DominanceComparator()): super(RankingAndCrowdingDistanceSelection, self).__init__() self.max_population_size = max_population_size self.dominance_comparator = dominance_comparator -
    [docs] def execute(self, front: List[S]) -> List[S]: +
    +[docs] + def execute(self, front: List[S]) -> List[S]: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") ranking = FastNonDominatedRanking(self.dominance_comparator) crowding_distance = CrowdingDistance() @@ -312,27 +364,35 @@

    Source code for jmetal.operator.selection

                 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)
    +                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
    -
    [docs] def get_name(self) -> str: - return 'Ranking and crowding distance selection'
    + +
    +[docs] + def get_name(self) -> str: + return "Ranking and crowding distance selection"
    +
    -
    [docs]class RankingAndFitnessSelection(Selection[List[S], List[S]]): - def __init__(self, - max_population_size: int, reference_point: S, - dominance_comparator: Comparator = DominanceComparator()): +
    +[docs] +class RankingAndFitnessSelection(Selection[List[S], List[S]]): + def __init__( + self, max_population_size: int, reference_point: S, dominance_comparator: Comparator = DominanceComparator() + ): super(RankingAndFitnessSelection, self).__init__() self.max_population_size = max_population_size self.dominance_comparator = dominance_comparator self.reference_point = reference_point -
    [docs] def hypesub(self, l, A, actDim, bounds, pvec, alpha, k): +
    +[docs] + def hypesub(self, l, A, actDim, bounds, pvec, alpha, k): h = [0 for _ in range(l)] Adim = [a[actDim - 1] for a in A] indices_sort = sorted(range(len(Adim)), key=Adim.__getitem__) @@ -353,12 +413,17 @@

    Source code for jmetal.operator.selection

                             h[p] = h[p] + extrusion * alpha[i - 1]
                 else:
                     if extrusion > 0:
    -                    h = [h[j] + extrusion * self.hypesub(l, S[0:i], actDim - 1, bounds, pvec[0:i], alpha, k)[j] for j in
    -                         range(l)]
    +                    h = [
    +                        h[j] + extrusion * self.hypesub(l, S[0:i], actDim - 1, bounds, pvec[0:i], alpha, k)[j]
    +                        for j in range(l)
    +                    ]
     
             return h
    -
    [docs] def compute_hypervol_fitness_values(self, population: List[S], reference_point: S, k: int): + +
    +[docs] + def compute_hypervol_fitness_values(self, population: List[S], reference_point: S, k: int): points = [ind.objectives for ind in population] bounds = reference_point.objectives population_size = len(points) @@ -376,15 +441,18 @@

    Source code for jmetal.operator.selection

             f = self.hypesub(population_size, points, actDim, bounds, pvec, alpha, k)
     
             for i in range(len(population)):
    -            population[i].attributes['fitness'] = f[i]
    +            population[i].attributes["fitness"] = f[i]
     
             return population
    -
    [docs] def execute(self, front: List[S]) -> List[S]: + +
    +[docs] + def execute(self, front: List[S]) -> List[S]: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") ranking = FastNonDominatedRanking(self.dominance_comparator) ranking.compute_ranking(front) @@ -402,29 +470,37 @@

    Source code for jmetal.operator.selection

                     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 = 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
    -
    [docs] def get_name(self) -> str: - return 'Ranking and fitness selection'
    + +
    +[docs] + def get_name(self) -> str: + return "Ranking and fitness selection"
    +
    -
    [docs]class BinaryTournament2Selection(Selection[List[S], S]): +
    +[docs] +class BinaryTournament2Selection(Selection[List[S], S]): def __init__(self, comparator_list: List[Comparator]): super(BinaryTournament2Selection, self).__init__() self.comparator_list = comparator_list -
    [docs] def execute(self, front: List[S]) -> S: +
    +[docs] + def execute(self, front: List[S]) -> S: if front is None: - raise Exception('The front is null') + raise Exception("The front is null") elif len(front) == 0: - raise Exception('The front is empty') + raise Exception("The front is empty") elif not self.comparator_list: - raise Exception('The comparators\' list is empty') + raise Exception("The comparators' list is empty") winner = None @@ -442,6 +518,7 @@

    Source code for jmetal.operator.selection

     
             return winner
    + def __winner(self, front: List[S], comparator: Comparator): # Sampling without replacement i, j = random.sample(range(0, len(front)), 2) @@ -460,8 +537,12 @@

    Source code for jmetal.operator.selection

     
             return result
     
    -
    [docs] def get_name(self) -> str: - return 'Binary tournament selection (experimental)'
    +
    +[docs] + def get_name(self) -> str: + return "Binary tournament selection (experimental)"
    +
    +
    @@ -478,8 +559,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.multiobjective.constrained — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,7 +106,7 @@

    Table Of Contents

    Source code for jmetal.problem.multiobjective.constrained

    -from math import pi, cos, atan
    +from math import atan, cos, pi
     
     from jmetal.core.problem import FloatProblem
     from jmetal.core.solution import FloatSolution
    @@ -123,22 +120,36 @@ 

    Source code for jmetal.problem.multiobjective.constrained

    """ -
    [docs]class Srinivas(FloatProblem): - """ Class representing problem Srinivas. """ +
    +[docs] +class Srinivas(FloatProblem): + """Class representing problem Srinivas.""" def __init__(self): super(Srinivas, self).__init__() - self.number_of_variables = 2 - self.number_of_objectives = 2 - self.number_of_constraints = 2 + number_of_variables = 2 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] + + self.lower_bound = [-20.0 for _ in range(number_of_variables)] + self.upper_bound = [20.0 for _ in range(number_of_variables)] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + - self.lower_bound = [-20.0 for _ in range(self.number_of_variables)] - self.upper_bound = [20.0 for _ in range(self.number_of_variables)] +
    +[docs] + def number_of_constraints(self) -> int: + return 2
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x1 = solution.variables[0] x2 = solution.variables[1] @@ -149,6 +160,7 @@

    Source code for jmetal.problem.multiobjective.constrained

    return solution
    + def __evaluate_constraints(self, solution: FloatSolution) -> None: x1 = solution.variables[0] x2 = solution.variables[1] @@ -156,27 +168,44 @@

    Source code for jmetal.problem.multiobjective.constrained

    solution.constraints[0] = 1.0 - (x1 * x1 + x2 * x2) / 225.0 solution.constraints[1] = (3.0 * x2 - x1) / 10.0 - 1.0 -
    [docs] def get_name(self): - return 'Srinivas'
    +
    +[docs] + def name(self): + return "Srinivas"
    +
    -
    [docs]class Tanaka(FloatProblem): - """ Class representing problem Tanaka. """ + +
    +[docs] +class Tanaka(FloatProblem): + """Class representing problem Tanaka.""" def __init__(self): super(Tanaka, self).__init__() - self.number_of_variables = 2 - self.number_of_objectives = 2 - self.number_of_constraints = 2 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] + + number_of_variables = 2 + self.lower_bound = [10e-5 for _ in range(number_of_variables)] + self.upper_bound = [pi for _ in range(number_of_variables)] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    - self.lower_bound = [10e-5 for _ in range(self.number_of_variables)] - self.upper_bound = [pi for _ in range(self.number_of_variables)] +
    +[docs] + def number_of_constraints(self) -> int: + return 2
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: solution.objectives[0] = solution.variables[0] solution.objectives[1] = solution.variables[1] @@ -184,50 +213,61 @@

    Source code for jmetal.problem.multiobjective.constrained

    return solution
    + def __evaluate_constraints(self, solution: FloatSolution) -> None: - constraints = [0.0 for _ in range(self.number_of_constraints)] + constraints = [0.0 for _ in range(self.number_of_constraints())] x1 = solution.variables[0] x2 = solution.variables[1] - constraints[0] = (x1 * x1 + x2 * x2 - 1.0 - 0.1 * cos(16.0 * atan(x1 / x2))) + constraints[0] = x1 * x1 + x2 * x2 - 1.0 - 0.1 * cos(16.0 * atan(x1 / x2)) constraints[1] = -2.0 * ((x1 - 0.5) * (x1 - 0.5) + (x2 - 0.5) * (x2 - 0.5) - 0.5) solution.constraints = constraints - #set_overall_constraint_violation_degree(solution) + # set_overall_constraint_violation_degree(solution) +
    +[docs] + def name(self): + return "Tanaka"
    +
    -
    [docs] def get_name(self): - return 'Tanaka'
    -
    [docs]class Osyczka2(FloatProblem): - """ Class representing problem Osyczka2. """ +
    +[docs] +class Osyczka2(FloatProblem): + """Class representing problem Osyczka2.""" def __init__(self): super(Osyczka2, self).__init__() - self.number_of_variables = 6 - self.number_of_objectives = 2 - self.number_of_constraints = 6 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] self.lower_bound = [0.0, 0.0, 1.0, 0.0, 1.0, 0.0] self.upper_bound = [10.0, 10.0, 5.0, 6.0, 5.0, 10.0] - FloatSolution.lower_bound = self.lower_bound - FloatSolution.upper_bound = self.upper_bound +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def number_of_constraints(self) -> int: + return 6
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables - solution.objectives[0] = - (25.0 * - (x[0] - 2.0) ** 2 + - (x[1] - 2.0) ** 2 + - (x[2] - 1.0) ** 2 + - (x[3] - 4.0) ** 2 + - (x[4] - 1.0) ** 2) + solution.objectives[0] = -( + 25.0 * (x[0] - 2.0) ** 2 + (x[1] - 2.0) ** 2 + (x[2] - 1.0) ** 2 + (x[3] - 4.0) ** 2 + (x[4] - 1.0) ** 2 + ) solution.objectives[1] = sum([x[i] ** 2 for i in range(len(x))]) @@ -235,8 +275,9 @@

    Source code for jmetal.problem.multiobjective.constrained

    return solution
    + def __evaluate_constraints(self, solution: FloatSolution) -> None: - constraints = [0.0 for _ in range(self.number_of_constraints)] + constraints = [0.0 for _ in range(self.number_of_constraints())] x = solution.variables constraints[0] = (x[0] + x[1]) / 2.0 - 1.0 @@ -248,29 +289,43 @@

    Source code for jmetal.problem.multiobjective.constrained

    solution.constraints = constraints -
    [docs] def get_name(self): - return 'Osyczka2'
    +
    +[docs] + def name(self): + return "Osyczka2"
    +
    + -
    [docs]class Binh2(FloatProblem): - """ Class representing problem Binh2. """ +
    +[docs] +class Binh2(FloatProblem): + """Class representing problem Binh2.""" def __init__(self): super(Binh2, self).__init__() - self.number_of_variables = 2 - self.number_of_objectives = 2 - self.number_of_constraints = 2 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] self.lower_bound = [0.0, 0.0] self.upper_bound = [5.0, 3.0] - FloatSolution.lower_bound = self.lower_bound - FloatSolution.upper_bound = self.upper_bound +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def number_of_constraints(self) -> int: + return 2
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = 4.0 * x[0] * x[0] + 4 * x[1] * x[1] solution.objectives[1] = (x[0] - 5.0) * (x[0] - 5.0) + (x[1] - 5.0) * (x[1] - 5.0) @@ -279,15 +334,20 @@

    Source code for jmetal.problem.multiobjective.constrained

    return solution
    + def __evaluate_constraints(self, solution: FloatSolution) -> None: - constraints = [0.0 for _ in range(self.number_of_constraints)] + constraints = [0.0 for _ in range(self.number_of_constraints())] x = solution.variables constraints[0] = -1.0 * (x[0] - 5) * (x[0] - 5) - x[1] * x[1] + 25.0 constraints[1] = (x[0] - 8) * (x[0] - 8) + (x[1] + 3) * (x[1] + 3) - 7.7 -
    [docs] def get_name(self): - return 'Binh2'
    +
    +[docs] + def name(self): + return "Binh2"
    +
    +
    @@ -304,8 +364,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.multiobjective.dtlz — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,7 +106,7 @@

    Table Of Contents

    Source code for jmetal.problem.multiobjective.dtlz

    -from math import pi, cos, sin
    +from math import cos, pi, sin
     
     from jmetal.core.problem import FloatProblem
     from jmetal.core.solution import FloatSolution
    @@ -123,254 +120,333 @@ 

    Source code for jmetal.problem.multiobjective.dtlz

    """ -
    [docs]class DTLZ1(FloatProblem): - """ Problem DTLZ1. Continuous problem having a flat Pareto front +
    +[docs] +class DTLZ1(FloatProblem): + """Problem DTLZ1. Continuous problem having a flat Pareto front .. note:: Unconstrained problem. The default number of variables and objectives are, respectively, 7 and 3. """ def __init__(self, number_of_variables: int = 7, number_of_objectives=3): - """ :param number_of_variables: number of decision variables of the problem. - """ + """:param number_of_variables: number of decision variables of the problem.""" super(DTLZ1, self).__init__() - self.number_of_variables = number_of_variables - self.number_of_objectives = number_of_objectives - self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE] * number_of_objectives - self.obj_labels = ['$ f_{} $'.format(i) for i in range(number_of_objectives)] + self.obj_labels = ["$ f_{} $".format(i) for i in range(number_of_objectives)] + + self.lower_bound = number_of_variables * [0.0] + self.upper_bound = number_of_variables * [1.0] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def number_of_variables(self) -> int: + return len(self.lower_bound)
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    - self.lower_bound = self.number_of_variables * [0.0] - self.upper_bound = self.number_of_variables * [1.0] -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - k = self.number_of_variables - self.number_of_objectives + 1 +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + k = self.number_of_variables() - self.number_of_objectives() + 1 - g = sum([(x - 0.5) * (x - 0.5) - cos(20.0 * pi * (x - 0.5)) - for x in solution.variables[self.number_of_variables - k:]]) + g = sum( + [ + (x - 0.5) * (x - 0.5) - cos(20.0 * pi * (x - 0.5)) + for x in solution.variables[self.number_of_variables() - k :] + ] + ) g = 100 * (k + g) - solution.objectives = [(1.0 + g) * 0.5] * self.number_of_objectives + solution.objectives = [(1.0 + g) * 0.5] * self.number_of_objectives() - for i in range(self.number_of_objectives): - for j in range(self.number_of_objectives - (i + 1)): + for i in range(self.number_of_objectives()): + for j in range(self.number_of_objectives() - (i + 1)): solution.objectives[i] *= solution.variables[j] if i != 0: - solution.objectives[i] *= 1 - solution.variables[self.number_of_objectives - (i + 1)] + solution.objectives[i] *= 1 - solution.variables[self.number_of_objectives() - (i + 1)] return solution
    -
    [docs] def get_name(self): - return 'DTLZ1'
    + +
    +[docs] + def name(self): + return "DTLZ1"
    +
    -
    [docs]class DTLZ2(DTLZ1): - """ Problem DTLZ2. Continuous problem having a convex Pareto front + +
    +[docs] +class DTLZ2(DTLZ1): + """Problem DTLZ2. Continuous problem having a convex Pareto front .. note:: Unconstrained problem. The default number of variables and objectives are, respectively, 12 and 3. """ def __init__(self, number_of_variables: int = 12, number_of_objectives=3): - """:param number_of_variables: number of decision variables of the problem - """ + """:param number_of_variables: number of decision variables of the problem""" super(DTLZ2, self).__init__(number_of_variables, number_of_objectives) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - k = self.number_of_variables - self.number_of_objectives + 1 +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + k = self.number_of_variables() - self.number_of_objectives() + 1 - g = sum([(x - 0.5) * (x - 0.5) for x in solution.variables[self.number_of_variables - k:]]) + g = sum([(x - 0.5) * (x - 0.5) for x in solution.variables[self.number_of_variables() - k :]]) - solution.objectives = [1.0 + g] * self.number_of_objectives + solution.objectives = [1.0 + g] * self.number_of_objectives() - for i in range(self.number_of_objectives): - for j in range(self.number_of_objectives - (i + 1)): + for i in range(self.number_of_objectives()): + for j in range(self.number_of_objectives() - (i + 1)): solution.objectives[i] *= cos(solution.variables[j] * 0.5 * pi) if i != 0: - solution.objectives[i] *= sin(0.5 * pi * solution.variables[self.number_of_objectives - (i + 1)]) + solution.objectives[i] *= sin(0.5 * pi * solution.variables[self.number_of_objectives() - (i + 1)]) return solution
    -
    [docs] def get_name(self): - return 'DTLZ2'
    +
    +[docs] + def name(self): + return "DTLZ2"
    +
    -
    [docs]class DTLZ3(DTLZ1): - """ Problem DTLZ3. Continuous problem having a convex Pareto front + + +
    +[docs] +class DTLZ3(DTLZ1): + """Problem DTLZ3. Continuous problem having a convex Pareto front .. note:: Unconstrained problem. The default number of variables and objectives are, respectively, 12 and 3. """ def __init__(self, number_of_variables: int = 12, number_of_objectives=3): - """:param number_of_variables: number of decision variables of the problem - """ + """:param number_of_variables: number of decision variables of the problem""" super(DTLZ3, self).__init__(number_of_variables, number_of_objectives) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - k = self.number_of_variables - self.number_of_objectives + 1 +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + k = self.number_of_variables() - self.number_of_objectives() + 1 - g = sum([(x - 0.5) ** 2 - cos(20.0 * pi * (x - 0.5)) for x in solution.variables[self.number_of_variables - k:]]) + g = sum( + [(x - 0.5) ** 2 - cos(20.0 * pi * (x - 0.5)) for x in solution.variables[self.number_of_variables() - k :]] + ) g = 100.0 * (k + g) - f = [1.0 + g for _ in range(self.number_of_objectives)] + f = [1.0 + g for _ in range(self.number_of_objectives())] - for i in range(self.number_of_objectives): - for j in range(self.number_of_objectives - (i + 1)): + for i in range(self.number_of_objectives()): + for j in range(self.number_of_objectives() - (i + 1)): f[i] *= cos(solution.variables[j] * 0.5 * pi) if i != 0: - aux = self.number_of_objectives - (i + 1) + aux = self.number_of_objectives() - (i + 1) f[i] *= sin(solution.variables[aux] * 0.5 * pi) - solution.objectives = [f[x] for x in range(self.number_of_objectives)] + solution.objectives = [f[x] for x in range(self.number_of_objectives())] return solution
    -
    [docs] def get_name(self): - return 'DTLZ3'
    + +
    +[docs] + def name(self): + return "DTLZ3"
    +
    + -
    [docs]class DTLZ4(DTLZ1): - """ Problem DTLZ4. Continuous problem having a convex Pareto front +
    +[docs] +class DTLZ4(DTLZ1): + """Problem DTLZ4. Continuous problem having a convex Pareto front .. note:: Unconstrained problem. The default number of variables and objectives are, respectively, 12 and 3. """ def __init__(self, number_of_variables: int = 12, number_of_objectives=3): - """:param number_of_variables: number of decision variables of the problem - """ + """:param number_of_variables: number of decision variables of the problem""" super(DTLZ4, self).__init__(number_of_variables, number_of_objectives) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: alpha = 100.0 - k = self.number_of_variables - self.number_of_objectives + 1 + k = self.number_of_variables() - self.number_of_objectives() + 1 - g = sum([(x - 0.5) ** 2 for x in solution.variables[self.number_of_variables - k:]]) - f = [1.0 + g for _ in range(self.number_of_objectives)] + g = sum([(x - 0.5) ** 2 for x in solution.variables[self.number_of_variables() - k :]]) + f = [1.0 + g for _ in range(self.number_of_objectives())] - for i in range(self.number_of_objectives): - for j in range(self.number_of_objectives - (i + 1)): + for i in range(self.number_of_objectives()): + for j in range(self.number_of_objectives() - (i + 1)): f[i] *= cos(pow(solution.variables[j], alpha) * pi / 2.0) if i != 0: - aux = self.number_of_objectives - (i + 1) + aux = self.number_of_objectives() - (i + 1) f[i] *= sin(pow(solution.variables[aux], alpha) * pi / 2.0) - solution.objectives = [f[x] for x in range(self.number_of_objectives)] + solution.objectives = [f[x] for x in range(self.number_of_objectives())] return solution
    -
    [docs] def get_name(self): - return 'DTLZ4'
    + +
    +[docs] + def name(self): + return "DTLZ4"
    +
    -
    [docs]class DTLZ5(DTLZ1): - """ Problem DTLZ5. Continuous problem having a convex Pareto front + +
    +[docs] +class DTLZ5(DTLZ1): + """Problem DTLZ5. Continuous problem having a convex Pareto front .. note:: Unconstrained problem. The default number of variables and objectives are, respectively, 12 and 3. """ def __init__(self, number_of_variables: int = 12, number_of_objectives=3): - """:param number_of_variables: number of decision variables of the problem - """ + """:param number_of_variables: number of decision variables of the problem""" super(DTLZ5, self).__init__(number_of_variables, number_of_objectives) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - k = self.number_of_variables - self.number_of_objectives + 1 +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + k = self.number_of_variables() - self.number_of_objectives() + 1 - g = sum([(x - 0.5) ** 2 for x in solution.variables[self.number_of_variables - k:]]) - t = pi/(4.0 * (1.0 + g)) + g = sum([(x - 0.5) ** 2 for x in solution.variables[self.number_of_variables() - k :]]) + t = pi / (4.0 * (1.0 + g)) - theta = [0.0]*(self.number_of_objectives - 1) - theta[0] = solution.variables[0]*pi/2.0 - theta[1:] = [t * (1.0 + 2.0 * g * solution.variables[i]) for i in range(1,self.number_of_objectives-1)] + theta = [0.0] * (self.number_of_objectives() - 1) + theta[0] = solution.variables[0] * pi / 2.0 + theta[1:] = [t * (1.0 + 2.0 * g * solution.variables[i]) for i in range(1, self.number_of_objectives() - 1)] - f = [1.0 + g for _ in range(self.number_of_objectives)] + f = [1.0 + g for _ in range(self.number_of_objectives())] - for i in range(self.number_of_objectives): - for j in range(self.number_of_objectives - (i + 1)): + for i in range(self.number_of_objectives()): + for j in range(self.number_of_objectives() - (i + 1)): f[i] *= cos(theta[j]) if i != 0: - aux = self.number_of_objectives - (i + 1) + aux = self.number_of_objectives() - (i + 1) f[i] *= sin(theta[aux]) - solution.objectives = [f[x] for x in range(self.number_of_objectives)] + solution.objectives = [f[x] for x in range(self.number_of_objectives())] return solution
    -
    [docs] def get_name(self): - return 'DTLZ5'
    + +
    +[docs] + def name(self): + return "DTLZ5"
    +
    + -
    [docs]class DTLZ6(DTLZ1): - """ Problem DTLZ6. Continuous problem having a convex Pareto front +
    +[docs] +class DTLZ6(DTLZ1): + """Problem DTLZ6. Continuous problem having a convex Pareto front .. note:: Unconstrained problem. The default number of variables and objectives are, respectively, 12 and 3. """ def __init__(self, number_of_variables: int = 12, number_of_objectives=3): - """:param number_of_variables: number of decision variables of the problem - """ + """:param number_of_variables: number of decision variables of the problem""" super(DTLZ6, self).__init__(number_of_variables, number_of_objectives) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - k = self.number_of_variables - self.number_of_objectives + 1 +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + k = self.number_of_variables() - self.number_of_objectives() + 1 - g = sum([pow(x, 0.1) for x in solution.variables[self.number_of_variables - k:]]) - t = pi/(4.0 * (1.0 + g)) + g = sum([pow(x, 0.1) for x in solution.variables[self.number_of_variables() - k :]]) + t = pi / (4.0 * (1.0 + g)) - theta = [0.0]*(self.number_of_objectives - 1) - theta[0] = solution.variables[0]*pi/2.0 - theta[1:] = [t * (1.0 + 2.0 * g * solution.variables[i]) for i in range(1,self.number_of_objectives-1)] + theta = [0.0] * (self.number_of_objectives() - 1) + theta[0] = solution.variables[0] * pi / 2.0 + theta[1:] = [t * (1.0 + 2.0 * g * solution.variables[i]) for i in range(1, self.number_of_objectives() - 1)] - f = [1.0 + g for _ in range(self.number_of_objectives)] + f = [1.0 + g for _ in range(self.number_of_objectives())] - for i in range(self.number_of_objectives): - for j in range(self.number_of_objectives - (i + 1)): + for i in range(self.number_of_objectives()): + for j in range(self.number_of_objectives() - (i + 1)): f[i] *= cos(theta[j]) if i != 0: - aux = self.number_of_objectives - (i + 1) + aux = self.number_of_objectives() - (i + 1) f[i] *= sin(theta[aux]) - solution.objectives = [f[x] for x in range(self.number_of_objectives)] + solution.objectives = [f[x] for x in range(self.number_of_objectives())] return solution
    -
    [docs] def get_name(self): - return 'DTLZ6'
    + +
    +[docs] + def name(self): + return "DTLZ6"
    +
    + -
    [docs]class DTLZ7(DTLZ1): - """ Problem DTLZ6. Continuous problem having a disconnected Pareto front +
    +[docs] +class DTLZ7(DTLZ1): + """Problem DTLZ6. Continuous problem having a disconnected Pareto front .. note:: Unconstrained problem. The default number of variables and objectives are, respectively, 22 and 3. """ def __init__(self, number_of_variables: int = 22, number_of_objectives=3): - """:param number_of_variables: number of decision variables of the problem - """ + """:param number_of_variables: number of decision variables of the problem""" super(DTLZ7, self).__init__(number_of_variables, number_of_objectives) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - k = self.number_of_variables - self.number_of_objectives + 1 +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + k = self.number_of_variables() - self.number_of_objectives() + 1 - g = sum([x for x in solution.variables[self.number_of_variables - k:]]) + g = sum([x for x in solution.variables[self.number_of_variables() - k :]]) g = 1.0 + (9.0 * g) / k - h = sum([(x / (1.0 + g)) * (1 + sin(3.0 * pi * x)) for x in solution.variables[:self.number_of_objectives-1]]) - h = self.number_of_objectives - h + h = sum( + [(x / (1.0 + g)) * (1 + sin(3.0 * pi * x)) for x in solution.variables[: self.number_of_objectives() - 1]] + ) + h = self.number_of_objectives() - h - solution.objectives[:self.number_of_objectives-1] = solution.variables[:self.number_of_objectives-1] + solution.objectives[: self.number_of_objectives() - 1] = solution.variables[: self.number_of_objectives() - 1] solution.objectives[-1] = (1.0 + g) * h return solution
    -
    [docs] def get_name(self): - return 'DTLZ7'
    + +
    +[docs] + def name(self): + return "DTLZ7"
    +
    +
    @@ -387,8 +463,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.multiobjective.fda — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,11 +107,11 @@

    Table Of Contents

    Source code for jmetal.problem.multiobjective.fda

     from abc import ABC, abstractmethod
    -from math import sqrt, pow, sin, pi, floor, cos
    +from math import cos, floor, pi, pow, sin, sqrt
     
     import numpy
     
    -from jmetal.core.problem import FloatProblem, DynamicProblem
    +from jmetal.core.problem import DynamicProblem, FloatProblem
     from jmetal.core.solution import FloatSolution
     
     """
    @@ -126,7 +123,9 @@ 

    Source code for jmetal.problem.multiobjective.fda

    """ -
    [docs]class FDA(DynamicProblem, FloatProblem, ABC): +
    +[docs] +class FDA(DynamicProblem, FloatProblem, ABC): def __init__(self): super(FDA, self).__init__() self.tau_T = 5 @@ -134,45 +133,61 @@

    Source code for jmetal.problem.multiobjective.fda

    self.time = 1.0 self.problem_modified = False -
    [docs] def update(self, *args, **kwargs): +
    +[docs] + def update(self, *args, **kwargs): counter: int = kwargs["COUNTER"] self.time = (1.0 / self.nT) * floor(counter * 1.0 / self.tau_T) self.problem_modified = True
    -
    [docs] def the_problem_has_changed(self) -> bool: + +
    +[docs] + def the_problem_has_changed(self) -> bool: return self.problem_modified
    -
    [docs] def clear_changed(self) -> None: + +
    +[docs] + def clear_changed(self) -> None: self.problem_modified = False
    -
    [docs] @abstractmethod + +
    +[docs] + @abstractmethod def evaluate(self, solution: FloatSolution): - pass
    + pass
    +
    + -
    [docs]class FDA1(FDA): - """ Problem FDA1. +
    +[docs] +class FDA1(FDA): + """Problem FDA1. .. note:: Bi-objective dynamic unconstrained problem. The default number of variables is 100. """ def __init__(self, number_of_variables: int = 100): - """ :param number_of_variables: Number of decision variables of the problem. - """ + """:param number_of_variables: Number of decision variables of the problem.""" super(FDA1, self).__init__() self.number_of_variables = number_of_variables self.number_of_objectives = 2 self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] self.lower_bound = self.number_of_variables * [-1.0] self.upper_bound = self.number_of_variables * [1.0] self.lower_bound[0] = 0.0 self.upper_bound[0] = 1.0 -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: g = self.__eval_g(solution) h = self.__eval_h(solution.variables[0], g) @@ -181,6 +196,7 @@

    Source code for jmetal.problem.multiobjective.fda

    return solution
    + def __eval_g(self, solution: FloatSolution): gT = sin(0.5 * pi * self.time) g = 1.0 + sum([pow(v - gT, 2) for v in solution.variables[1:]]) @@ -190,33 +206,40 @@

    Source code for jmetal.problem.multiobjective.fda

    def __eval_h(self, f: float, g: float) -> float: return 1.0 - sqrt(f / g) -
    [docs] def get_name(self): - return 'FDA1'
    +
    +[docs] + def get_name(self): + return "FDA1"
    +
    + -
    [docs]class FDA2(FDA): - """ Problem FDA2 +
    +[docs] +class FDA2(FDA): + """Problem FDA2 .. note:: Bi-objective dynamic unconstrained problem. The default number of variables is 31. """ def __init__(self, number_of_variables: int = 31): - """ :param number_of_variables: Number of decision variables of the problem. - """ + """:param number_of_variables: Number of decision variables of the problem.""" super(FDA2, self).__init__() self.number_of_variables = number_of_variables self.number_of_objectives = 2 self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] self.lower_bound = self.number_of_variables * [-1.0] self.upper_bound = self.number_of_variables * [1.0] self.lower_bound[0] = 0.0 self.upper_bound[0] = 1.0 -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: g = self.__eval_g(solution, 1, len(solution.variables)) h = self.__eval_h(solution.variables[0], g) @@ -225,6 +248,7 @@

    Source code for jmetal.problem.multiobjective.fda

    return solution
    + def __eval_g(self, solution: FloatSolution, lower_limit: int, upper_limit: int): g = sum([pow(v, 2) for v in solution.variables[lower_limit:upper_limit]]) g += 1.0 + sum([pow(v + 1.0, 2.0) for v in solution.variables[upper_limit:]]) @@ -235,19 +259,24 @@

    Source code for jmetal.problem.multiobjective.fda

    ht = 0.2 + 4.8 * pow(self.time, 2.0) return 1.0 - pow(f / g, ht) -
    [docs] def get_name(self): - return 'FDA2'
    +
    +[docs] + def get_name(self): + return "FDA2"
    +
    + -
    [docs]class FDA3(FDA): - """ Problem FDA3 +
    +[docs] +class FDA3(FDA): + """Problem FDA3 .. note:: Bi-objective dynamic unconstrained problem. The default number of variables is 30. """ def __init__(self, number_of_variables: int = 30): - """ :param number_of_variables: Number of decision variables of the problem. - """ + """:param number_of_variables: Number of decision variables of the problem.""" super(FDA3, self).__init__() self.number_of_variables = number_of_variables self.number_of_objectives = 2 @@ -257,14 +286,16 @@

    Source code for jmetal.problem.multiobjective.fda

    self.limitInfII = 1 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] self.lower_bound = self.number_of_variables * [-1.0] self.upper_bound = self.number_of_variables * [1.0] self.lower_bound[0] = 0.0 self.upper_bound[0] = 1.0 -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: g = self.__eval_g(solution, self.limitInfII) h = self.__eval_h(solution.variables[0], g) @@ -273,6 +304,7 @@

    Source code for jmetal.problem.multiobjective.fda

    return solution
    + def __eval_f(self, solution: FloatSolution, lower_limit: int, upper_limit: int): f = 0.0 aux = 2.0 * sin(0.5 * pi * self.time) @@ -292,32 +324,40 @@

    Source code for jmetal.problem.multiobjective.fda

    h = 1.0 - sqrt(f / g) return h -
    [docs] def get_name(self): - return 'FDA3'
    +
    +[docs] + def get_name(self): + return "FDA3"
    +
    + -
    [docs]class FDA4(FDA): - """ Problem FDA4 +
    +[docs] +class FDA4(FDA): + """Problem FDA4 .. note:: Three-objective dynamic unconstrained problem. The default number of variables is 12. """ + M = 3 def __init__(self, number_of_variables: int = 12): - """ :param number_of_variables: Number of decision variables of the problem. - """ + """:param number_of_variables: Number of decision variables of the problem.""" super(FDA4, self).__init__() self.number_of_variables = number_of_variables self.number_of_objectives = 3 self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)', 'f(z)'] + self.obj_labels = ["f(x)", "f(y)", "f(z)"] self.lower_bound = self.number_of_variables * [0.0] self.upper_bound = self.number_of_variables * [1.0] -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: g = self.__eval_g(solution, self.M - 1) solution.objectives[0] = self.__eval_f1(solution, g) @@ -326,6 +366,7 @@

    Source code for jmetal.problem.multiobjective.fda

    return solution
    + def __eval_g(self, solution: FloatSolution, lower_limit: int): gt = abs(sin(0.5 * pi * self.time)) g = sum([pow(v - gt, 2) for v in solution.variables[lower_limit:]]) @@ -334,14 +375,14 @@

    Source code for jmetal.problem.multiobjective.fda

    def __eval_f1(self, solution: FloatSolution, g: float) -> float: f = 1.0 + g - mult = numpy.prod([cos(v * pi / 2.0) for v in solution.variables[:self.M - 1]]) + mult = numpy.prod([cos(v * pi / 2.0) for v in solution.variables[: self.M - 1]]) return f * mult def __eval_fk(self, solution: FloatSolution, g: float, k: int) -> float: f = 1.0 + g aux = sin((solution.variables[self.M - k] * pi) / 2.0) - mult = numpy.prod([cos(v * pi / 2.0) for v in solution.variables[:self.M - k]]) + mult = numpy.prod([cos(v * pi / 2.0) for v in solution.variables[: self.M - k]]) return f * mult * aux @@ -351,32 +392,40 @@

    Source code for jmetal.problem.multiobjective.fda

    return fm -
    [docs] def get_name(self): - return 'FDA4'
    +
    +[docs] + def get_name(self): + return "FDA4"
    +
    -
    [docs]class FDA5(FDA): - """ Problem FDA5 + +
    +[docs] +class FDA5(FDA): + """Problem FDA5 .. note:: Three-objective dynamic unconstrained problem. The default number of variables is 12. """ + M = 3 def __init__(self, number_of_variables: int = 12): - """ :param number_of_variables: Number of decision variables of the problem. - """ + """:param number_of_variables: Number of decision variables of the problem.""" super(FDA5, self).__init__() self.number_of_variables = number_of_variables self.number_of_objectives = 3 self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)', 'f(z)'] + self.obj_labels = ["f(x)", "f(y)", "f(z)"] self.lower_bound = self.number_of_variables * [0.0] self.upper_bound = self.number_of_variables * [1.0] -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: g = self.__eval_g(solution, self.M - 1) ft = 1.0 + 100.0 * pow(sin(0.5 * pi * self.time), 4.0) @@ -386,6 +435,7 @@

    Source code for jmetal.problem.multiobjective.fda

    return solution
    + def __eval_g(self, solution: FloatSolution, lower_limit: int): gt = abs(sin(0.5 * pi * self.time)) g = sum([pow(v - gt, 2) for v in solution.variables[lower_limit:]]) @@ -394,14 +444,14 @@

    Source code for jmetal.problem.multiobjective.fda

    def __eval_f1(self, solution: FloatSolution, g: float, ft: float) -> float: f = 1.0 + g - mult = numpy.prod([cos(pow(v, ft) * pi / 2.0) for v in solution.variables[:self.M - 1]]) + mult = numpy.prod([cos(pow(v, ft) * pi / 2.0) for v in solution.variables[: self.M - 1]]) return f * mult def __eval_fk(self, solution: FloatSolution, g: float, k: int, ft: float) -> float: f = 1.0 + g - mult = numpy.prod([cos(pow(v, ft) * pi / 2.0) for v in solution.variables[:self.M - k]]) + mult = numpy.prod([cos(pow(v, ft) * pi / 2.0) for v in solution.variables[: self.M - k]]) yy = pow(solution.variables[self.M - k], ft) mult *= sin(yy * pi / 2.0) @@ -414,8 +464,12 @@

    Source code for jmetal.problem.multiobjective.fda

    return fm * mult -
    [docs] def get_name(self): - return 'FDA5'
    +
    +[docs] + def get_name(self): + return "FDA5"
    +
    +
    @@ -432,8 +486,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.multiobjective.lircmop — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,14 +106,17 @@

    Table Of Contents

    Source code for jmetal.problem.multiobjective.lircmop

    -from math import sin, pi, cos, sqrt
    +from math import cos, pi, sin, sqrt
    +from typing import List
     
     from jmetal.core.problem import FloatProblem
     from jmetal.core.solution import FloatSolution
     
     
    -
    [docs]class LIRCMOP1(FloatProblem): - """ Class representing problem LIR-CMOP1, defined in: +
    +[docs] +class LIRCMOP1(FloatProblem): + """Class representing problem LIR-CMOP1, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -124,17 +124,28 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP1, self).__init__() - self.number_of_variables = number_of_variables - self.number_of_objectives = 2 - self.number_of_constraints = 2 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] + + self.lower_bound = [0.0 for _ in range(number_of_variables)] + self.upper_bound = [1.0 for _ in range(number_of_variables)] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 2
    - self.lower_bound = [0.0 for _ in range(self.number_of_variables)] - self.upper_bound = [1.0 for _ in range(self.number_of_variables)] -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = x[0] + self.g1(x) @@ -144,9 +155,12 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: x = solution.variables - constraints = [0.0 for _ in range(self.number_of_constraints)] + constraints = [0.0 for _ in range(len(solution.constraints))] a = 0.51 b = 0.5 @@ -158,26 +172,39 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def g1(self, x: [float]) -> float: + +
    +[docs] + def g1(self, x: List[float]) -> float: result = 0 - for i in range(2, self.number_of_variables, 2): + for i in range(2, self.number_of_variables(), 2): result += pow(x[i] - sin(0.5 * pi * x[0]), 2.0) return result
    -
    [docs] def g2(self, x: [float]) -> float: + +
    +[docs] + def g2(self, x: List[float]) -> float: result = 0 - for i in range(1, self.number_of_variables, 2): + for i in range(1, self.number_of_variables(), 2): result += pow(x[i] - cos(0.5 * pi * x[0]), 2.0) return result
    -
    [docs] def get_name(self): - return 'LIR-CMOP1'
    + +
    +[docs] + def name(self): + return "LIR-CMOP1"
    +
    + -
    [docs]class LIRCMOP2(LIRCMOP1): - """ Class representing problem LIR-CMOP1, defined in: +
    +[docs] +class LIRCMOP2(LIRCMOP1): + """Class representing problem LIR-CMOP1, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -186,7 +213,9 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP2, self).__init__(number_of_variables) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = x[0] + self.g1(x) @@ -196,12 +225,19 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP2'
    + +
    +[docs] + def name(self): + return "LIR-CMOP2"
    +
    -
    [docs]class LIRCMOP3(LIRCMOP1): - """ Class representing problem LIR-CMOP3, defined in: + +
    +[docs] +class LIRCMOP3(LIRCMOP1): + """Class representing problem LIR-CMOP3, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -210,9 +246,17 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP3, self).__init__(number_of_variables) -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def number_of_constraints(self) -> int: + return 3
    + + +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: x = solution.variables - constraints = [0.0 for _ in range(self.number_of_constraints)] + constraints = [0.0 for _ in range(self.number_of_constraints())] a = 0.51 b = 0.5 @@ -226,12 +270,19 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP3'
    + +
    +[docs] + def name(self): + return "LIR-CMOP3"
    +
    -
    [docs]class LIRCMOP4(LIRCMOP2): - """ Class representing problem LIR-CMOP4, defined in: + +
    +[docs] +class LIRCMOP4(LIRCMOP2): + """Class representing problem LIR-CMOP4, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -240,9 +291,17 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP4, self).__init__(number_of_variables) -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def number_of_constraints(self) -> int: + return 3
    + + +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: x = solution.variables - constraints = [0.0 for _ in range(self.number_of_constraints)] + constraints = [0.0 for _ in range(self.number_of_constraints())] a = 0.51 b = 0.5 @@ -256,12 +315,19 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP4'
    + +
    +[docs] + def name(self): + return "LIR-CMOP4"
    +
    -
    [docs]class LIRCMOP5(FloatProblem): - """ Class representing problem LIR-CMOP5, defined in: + +
    +[docs] +class LIRCMOP5(FloatProblem): + """Class representing problem LIR-CMOP5, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -269,17 +335,28 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP5, self).__init__() - self.number_of_variables = number_of_variables - self.number_of_objectives = 2 - self.number_of_constraints = 2 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] + + self.lower_bound = [0.0 for _ in range(number_of_variables)] + self.upper_bound = [1.0 for _ in range(number_of_variables)] - self.lower_bound = [0.0 for _ in range(self.number_of_variables)] - self.upper_bound = [1.0 for _ in range(self.number_of_variables)] +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def number_of_constraints(self) -> int: + return 2
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = x[0] + 10 * self.g1(x) + 0.7057 @@ -289,8 +366,11 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] + +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] r = 0.1 theta = -0.25 * pi @@ -302,36 +382,49 @@

    Source code for jmetal.problem.multiobjective.lircmop

    f2 = solution.objectives[1] for i in range(len(x_offset)): - constraints[i] = pow( - ((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + \ - pow( - ((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], - 2) - r + constraints[i] = ( + pow(((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + + pow(((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def g1(self, x: [float]) -> float: + +
    +[docs] + def g1(self, x: [float]) -> float: result = 0 - for i in range(2, self.number_of_variables, 2): + for i in range(2, self.number_of_variables(), 2): result += pow(x[i] - sin(0.5 * i / len(x) * pi * x[0]), 2.0) return result
    -
    [docs] def g2(self, x: [float]) -> float: + +
    +[docs] + def g2(self, x: [float]) -> float: result = 0 - for i in range(1, self.number_of_variables, 2): + for i in range(1, self.number_of_variables(), 2): result += pow(x[i] - cos(0.5 * i / len(x) * pi * x[0]), 2.0) return result
    -
    [docs] def get_name(self): - return 'LIR-CMOP5'
    + +
    +[docs] + def name(self): + return "LIR-CMOP5"
    +
    -
    [docs]class LIRCMOP6(LIRCMOP5): - """ Class representing problem LIR-CMOP6, defined in: + +
    +[docs] +class LIRCMOP6(LIRCMOP5): + """Class representing problem LIR-CMOP6, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -340,7 +433,9 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP6, self).__init__(number_of_variables) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = x[0] + 10 * self.g1(x) + 0.7057 @@ -350,8 +445,11 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] + +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] r = 0.1 theta = -0.25 * pi @@ -363,22 +461,29 @@

    Source code for jmetal.problem.multiobjective.lircmop

    f2 = solution.objectives[1] for i in range(len(x_offset)): - constraints[i] = pow( - ((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + \ - pow( - ((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], - 2) - r + constraints[i] = ( + pow(((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + + pow(((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP6'
    + +
    +[docs] + def name(self): + return "LIR-CMOP6"
    +
    -
    [docs]class LIRCMOP7(LIRCMOP5): - """ Class representing problem LIR-CMOP7, defined in: + +
    +[docs] +class LIRCMOP7(LIRCMOP5): + """Class representing problem LIR-CMOP7, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -387,8 +492,10 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP7, self).__init__(number_of_variables) -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] r = 0.1 theta = -0.25 * pi @@ -400,22 +507,29 @@

    Source code for jmetal.problem.multiobjective.lircmop

    f2 = solution.objectives[1] for i in range(len(x_offset)): - constraints[i] = pow( - ((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + \ - pow( - ((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], - 2) - r + constraints[i] = ( + pow(((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + + pow(((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP7'
    +
    +[docs] + def name(self): + return "LIR-CMOP7"
    +
    -
    [docs]class LIRCMOP8(LIRCMOP6): - """ Class representing problem LIR-CMOP8, defined in: + + +
    +[docs] +class LIRCMOP8(LIRCMOP6): + """Class representing problem LIR-CMOP8, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -424,8 +538,10 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP8, self).__init__(number_of_variables) -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] r = 0.1 theta = -0.25 * pi @@ -437,22 +553,29 @@

    Source code for jmetal.problem.multiobjective.lircmop

    f2 = solution.objectives[1] for i in range(len(x_offset)): - constraints[i] = pow( - ((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + \ - pow( - ((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], - 2) - r + constraints[i] = ( + pow(((f1 - x_offset[i]) * cos(theta) - (f2 - y_offset[i]) * sin(theta)) / a_array[i], 2) + + pow(((f1 - x_offset[i]) * sin(theta) + (f2 - y_offset[i]) * cos(theta)) / b_array[i], 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP8'
    + +
    +[docs] + def name(self): + return "LIR-CMOP8"
    +
    + -
    [docs]class LIRCMOP9(LIRCMOP8): - """ Class representing problem LIR-CMOP9, defined in: +
    +[docs] +class LIRCMOP9(LIRCMOP8): + """Class representing problem LIR-CMOP9, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -461,7 +584,9 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP9, self).__init__(number_of_variables) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = 1.7057 * x[0] * (10 * self.g1(x) + 1) @@ -471,36 +596,49 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: x = solution.variables - constraints = [0.0 for _ in range(self.number_of_constraints)] + constraints = [0.0 for _ in range(self.number_of_constraints())] theta = -0.25 * pi n = 4.0 f0 = solution.objectives[0] f1 = solution.objectives[1] - constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 2; + constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 2 x_offset = 1.40 y_offset = 1.40 a = 1.5 b = 6.0 - r = 0.1; + r = 0.1 - constraints[1] = pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + pow( - ((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) - r + constraints[1] = ( + pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + + pow(((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP9'
    + +
    +[docs] + def name(self): + return "LIR-CMOP9"
    +
    + -
    [docs]class LIRCMOP10(LIRCMOP8): - """ Class representing problem LIR-CMOP10, defined in: +
    +[docs] +class LIRCMOP10(LIRCMOP8): + """Class representing problem LIR-CMOP10, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -509,7 +647,9 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP10, self).__init__(number_of_variables) -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = 1.7057 * x[0] * (10 * self.g1(x) + 1) @@ -519,35 +659,48 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] + +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] theta = -0.25 * pi n = 4.0 f0 = solution.objectives[0] f1 = solution.objectives[1] - constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 1; + constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 1 x_offset = 1.1 y_offset = 1.2 a = 2.0 b = 4.0 - r = 0.1; + r = 0.1 - constraints[1] = pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + pow( - ((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) - r + constraints[1] = ( + pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + + pow(((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP10'
    + +
    +[docs] + def name(self): + return "LIR-CMOP10"
    +
    + -
    [docs]class LIRCMOP11(LIRCMOP10): - """ Class representing problem LIR-CMOP11, defined in: +
    +[docs] +class LIRCMOP11(LIRCMOP10): + """Class representing problem LIR-CMOP11, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -556,35 +709,47 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP11, self).__init__(number_of_variables) -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] theta = -0.25 * pi n = 4.0 f0 = solution.objectives[0] f1 = solution.objectives[1] - constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 2.1; + constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 2.1 x_offset = 1.2 y_offset = 1.2 a = 1.5 b = 5.0 - r = 0.1; + r = 0.1 - constraints[1] = pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + pow( - ((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) - r + constraints[1] = ( + pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + + pow(((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP11'
    + +
    +[docs] + def name(self): + return "LIR-CMOP11"
    +
    + -
    [docs]class LIRCMOP12(LIRCMOP9): - """ Class representing problem LIR-CMOP9, defined in: +
    +[docs] +class LIRCMOP12(LIRCMOP9): + """Class representing problem LIR-CMOP9, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -593,35 +758,47 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP12, self).__init__(number_of_variables) -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] theta = -0.25 * pi n = 4.0 f0 = solution.objectives[0] f1 = solution.objectives[1] - constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 2.5; + constraints[0] = f0 * sin(theta) + f1 * cos(theta) - sin(n * pi * (f0 * cos(theta) - f1 * sin(theta))) - 2.5 x_offset = 1.6 y_offset = 1.6 a = 1.5 b = 6.0 - r = 0.1; + r = 0.1 - constraints[1] = pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + pow( - ((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) - r + constraints[1] = ( + pow(((f0 - x_offset) * cos(theta) - (f1 - y_offset) * sin(theta)) / a, 2) + + pow(((f0 - x_offset) * sin(theta) + (f1 - y_offset) * cos(theta)) / b, 2) + - r + ) solution.constraints = constraints return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP12'
    + +
    +[docs] + def name(self): + return "LIR-CMOP12"
    +
    -
    [docs]class LIRCMOP13(FloatProblem): - """ Class representing problem LIR-CMOP13, defined in: + +
    +[docs] +class LIRCMOP13(FloatProblem): + """Class representing problem LIR-CMOP13, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -629,17 +806,27 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP13, self).__init__() - self.number_of_variables = number_of_variables - self.number_of_objectives = 3 - self.number_of_constraints = 2 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] + + self.lower_bound = [0.0 for _ in range(number_of_variables)] + self.upper_bound = [1.0 for _ in range(number_of_variables)] - self.lower_bound = [0.0 for _ in range(self.number_of_variables)] - self.upper_bound = [1.0 for _ in range(self.number_of_variables)] +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def number_of_constraints(self) -> int: + return 2
    + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables solution.objectives[0] = (1.7057 + self.g1(x)) * cos(0.5 * pi * x[0]) * cos(0.5 * pi + x[1]) @@ -650,10 +837,13 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] - f = sum([pow(solution.objectives[i], 2) for i in range(solution.number_of_objectives)]) +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] + + f = sum([pow(solution.objectives[i], 2) for i in range(len(solution.objectives))]) constraints[0] = (f - 9) * (f - 4) constraints[1] = (f - 1.9 * 1.9) * (f - 1.8 * 1.8) @@ -662,19 +852,29 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def g1(self, x: [float]) -> float: + +
    +[docs] + def g1(self, x: [float]) -> float: result = 0 - for i in range(2, self.number_of_variables, 2): + for i in range(2, self.number_of_variables(), 2): result += 10 * pow(x[i] - 0.5, 2.0) return result
    -
    [docs] def get_name(self): - return 'LIR-CMOP13'
    +
    +[docs] + def name(self): + return "LIR-CMOP13"
    +
    -
    [docs]class LIRCMOP14(LIRCMOP13): - """ Class representing problem LIR-CMOP14, defined in: + + +
    +[docs] +class LIRCMOP14(LIRCMOP13): + """Class representing problem LIR-CMOP14, defined in: * An Improved epsilon-constrained Method in MOEA/D for CMOPs with Large Infeasible Regions. Fan, Z., Li, W., Cai, X. et al. Soft Comput (2019). https://doi.org/10.1007/s00500-019-03794-x @@ -682,12 +882,25 @@

    Source code for jmetal.problem.multiobjective.lircmop

    def __init__(self, number_of_variables: int = 30): super(LIRCMOP14, self).__init__(number_of_variables) - self.number_of_constraints = 3 -
    [docs] def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: - constraints = [0.0 for _ in range(self.number_of_constraints)] +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 3
    + - f = sum([pow(solution.objectives[i], 2) for i in range(solution.number_of_objectives)]) +
    +[docs] + def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution: + constraints = [0.0 for _ in range(self.number_of_constraints())] + + f = sum([pow(solution.objectives[i], 2) for i in range(len(solution.objectives))]) constraints[0] = (f - 9) * (f - 4) constraints[1] = (f - 1.9 * 1.9) * (f - 1.8 * 1.8) @@ -697,8 +910,13 @@

    Source code for jmetal.problem.multiobjective.lircmop

    return solution
    -
    [docs] def get_name(self): - return 'LIR-CMOP14'
    + +
    +[docs] + def name(self): + return "LIR-CMOP14"
    +
    +
    @@ -715,8 +933,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.multiobjective.lz09 — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -124,48 +121,53 @@

    Source code for jmetal.problem.multiobjective.lz09

    """ -
    [docs]class LZ09(FloatProblem): +
    +[docs] +class LZ09(FloatProblem): __metaclass__ = ABCMeta - def __init__(self, - number_of_variables: int, - number_of_objectives: int, - number_of_constraints: int, - ptype: int, - dtype: int, - ltype: int): - """ LZ09 benchmark family as defined in: + def __init__( + self, + number_of_variables: int, + ptype: int, + dtype: int, + ltype: int, + ): + """LZ09 benchmark family as defined in: * H. Li and Q. Zhang. Multiobjective optimization problems with complicated pareto sets, MOEA/D and NSGA-II. IEEE Transactions on Evolutionary Computation, 12(2):284-302, April 2009. """ super(LZ09, self).__init__() - self.number_of_variables = number_of_variables - self.number_of_objectives = number_of_objectives - self.number_of_constraints = number_of_constraints - - self.obj_directions = [self.MINIMIZE, self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)', 'f(z)'] - self.lower_bound = self.number_of_variables * [0.0] - self.upper_bound = self.number_of_variables * [1.0] + self.lower_bound = number_of_variables * [0.0] + self.upper_bound = number_of_variables * [1.0] self.ptype = ptype self.dtype = dtype self.ltype = ltype -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x = solution.variables y = self.objective(x) - for i in range(self.number_of_objectives): + for i in range(self.number_of_objectives()): solution.objectives[i] = y[i] return solution
    + def __ps_func2(self, x: float, t1: float, dim: int, type: int, css: int) -> float: - """ Control the PS shapes of 2-D instances. + """Control the PS shapes of 2-D instances. :param type: The type of the curve. :param css: The class of the index. @@ -175,13 +177,13 @@

    Source code for jmetal.problem.multiobjective.lz09

    if type == 21: xy = 2 * (x - 0.5) - beta = xy - math.pow(t1, 0.5 * (self.number_of_variables + 3 * dim - 8) / (self.number_of_variables - 2)) + beta = xy - math.pow(t1, 0.5 * (self.number_of_variables() + 3 * dim - 8) / (self.number_of_variables() - 2)) if type == 22: - theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables + theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables() xy = 2 * (x - 0.5) beta = xy - math.sin(theta) if type == 23: - theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables + theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables() ra = 0.8 * t1 xy = 2 * (x - 0.5) if css == 1: @@ -189,7 +191,7 @@

    Source code for jmetal.problem.multiobjective.lz09

    else: beta = xy - ra * math.sin(theta) if type == 24: - theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables + theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables() xy = 2 * (x - 0.5) ra = 0.8 * t1 if css == 1: @@ -199,7 +201,7 @@

    Source code for jmetal.problem.multiobjective.lz09

    if type == 25: rho = 0.8 phi = math.pi * t1 - theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables + theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables() xy = 2 * (x - 0.5) if css == 1: beta = xy - rho * math.sin(phi) * math.sin(theta) @@ -208,7 +210,7 @@

    Source code for jmetal.problem.multiobjective.lz09

    else: beta = xy - rho * math.cos(phi) if type == 26: - theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables + theta = 6 * math.pi * t1 + dim * math.pi / self.number_of_variables() ra = 0.3 * t1 * (t1 * math.cos(4 * theta) + 2) xy = 2 * (x - 0.5) if css == 1: @@ -219,26 +221,25 @@

    Source code for jmetal.problem.multiobjective.lz09

    return beta def __ps_func3(self, x: float, t1: float, t2: float, dim: int, type: int): - """ Control the PS shapes of 3-D instances. + """Control the PS shapes of 3-D instances. :param type: The type of curve. """ beta = 0.0 dim += 1 if type == 31: - xy = 4 * (x - .5) - rate = 1.0 * dim / self.number_of_variables + xy = 4 * (x - 0.5) + rate = 1.0 * dim / self.number_of_variables() beta = xy - 4 * (t1 * t1 * rate + t2 * (1.0 - rate)) + 2 if type == 32: - theta = 2 * math.pi * t1 + dim * math.pi / self.number_of_variables - xy = 4 * (x - .5) + theta = 2 * math.pi * t1 + dim * math.pi / self.number_of_variables() + xy = 4 * (x - 0.5) beta = xy - 2 * t2 * math.sin(theta) return beta def __alpha_func(self, x: list, dim: int, type: int) -> list: - """ Control the PF shape. - """ + """Control the PF shape.""" alpha = [0.0] * dim if dim == 2: @@ -275,8 +276,7 @@

    Source code for jmetal.problem.multiobjective.lz09

    return alpha def __beta_func(self, x: list, type: int) -> float: - """ Control the distance. - """ + """Control the distance.""" beta = 0.0 dim = len(x) @@ -294,7 +294,7 @@

    Source code for jmetal.problem.multiobjective.lz09

    sum, xx = 0, 0 for i in range(dim): xx = 2 * x[i] - sum += (xx * xx - math.cos(4 * math.pi * xx) + 1) + sum += xx * xx - math.cos(4 * math.pi * xx) + 1 beta = 2.0 * sum / dim if type == 4: sum, prod, xx = 0, 1, 0 @@ -306,16 +306,18 @@

    Source code for jmetal.problem.multiobjective.lz09

    return beta -
    [docs] def objective(self, x_variables: list) -> list: +
    +[docs] + def objective(self, x_variables: list) -> list: aa = [] bb = [] cc = [] - y_objectives = [0.0] * self.number_of_objectives + y_objectives = [0.0] * self.number_of_objectives() - if self.number_of_objectives == 2: + if self.number_of_objectives() == 2: if self.ltype in [21, 22, 23, 24, 26]: - for n in range(1, self.number_of_variables): + for n in range(1, self.number_of_variables()): if n % 2 == 0: a = self.__ps_func2(x_variables[n], x_variables[0], n, self.ltype, 1) aa.append(a) @@ -331,7 +333,7 @@

    Source code for jmetal.problem.multiobjective.lz09

    y_objectives[0] = alpha[0] + h y_objectives[1] = alpha[1] + g if self.ltype == 25: - for n in range(1, self.number_of_variables): + for n in range(1, self.number_of_variables()): if n % 3 == 0: a = self.__ps_func2(x_variables[n], x_variables[0], n, self.ltype, 1) aa.append(a) @@ -353,10 +355,10 @@

    Source code for jmetal.problem.multiobjective.lz09

    y_objectives[0] = alpha[0] + h y_objectives[1] = alpha[1] + g - if self.number_of_objectives == 3: + if self.number_of_objectives() == 3: if self.ltype == 31 or self.ltype == 32: - for n in range(2, self.number_of_variables): + for n in range(2, self.number_of_variables()): a = self.__ps_func3(x_variables[n], x_variables[0], x_variables[1], n, self.ltype) if n % 3 == 0: @@ -378,98 +380,232 @@

    Source code for jmetal.problem.multiobjective.lz09

    return y_objectives
    -
    [docs] def get_name(self): - return 'LZ09'
    +
    +[docs] + def get_name(self): + return "LZ09"
    +
    + + + +
    +[docs] +class LZ09_F1(LZ09): + def __init__(self, number_of_variables=10): + super(LZ09_F1, self).__init__( + number_of_variables, dtype=1, ltype=21, ptype=21 + ) + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def name(self): + return "LZ09_F1"
    +
    + + + +
    +[docs] +class LZ09_F2(LZ09): + def __init__(self, number_of_variables=30): + super(LZ09_F2, self).__init__( + number_of_variables, dtype=1, ltype=22, ptype=21 + ) + + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs]class LZ09_F1(LZ09): - def __init__(self): - super(LZ09_F1, self).__init__(number_of_variables=10, number_of_objectives=2, number_of_constraints=0, - dtype=1, ltype=21, ptype=21) +
    +[docs] + def name(self): + return "LZ09_F2"
    +
    -
    [docs] def get_name(self): - return 'LZ09_F1'
    -
    [docs]class LZ09_F2(LZ09): +
    +[docs] +class LZ09_F3(LZ09): + def __init__(self, number_of_variables=30): + super(LZ09_F3, self).__init__( + number_of_variables, dtype=1, ltype=23, ptype=21 + ) + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] - def __init__(self): - super(LZ09_F2, self).__init__(number_of_variables=30, number_of_objectives=2, number_of_constraints=0, - dtype=1, ltype=22, ptype=21) +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs] def get_name(self): - return 'LZ09_F2'
    +
    +[docs] + def name(self): + return "LZ09_F3"
    +
    -
    [docs]class LZ09_F3(LZ09): - def __init__(self): - super(LZ09_F3, self).__init__(number_of_variables=30, number_of_objectives=2, number_of_constraints=0, - dtype=1, ltype=23, ptype=21) -
    [docs] def get_name(self): - return 'LZ09_F3'
    +
    +[docs] +class LZ09_F4(LZ09): + def __init__(self, number_of_variables=30): + super(LZ09_F4, self).__init__( + number_of_variables, dtype=1, ltype=24, ptype=21 + ) + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs]class LZ09_F4(LZ09): - def __init__(self): - super(LZ09_F4, self).__init__(number_of_variables=30, number_of_objectives=2, number_of_constraints=0, - dtype=1, ltype=24, ptype=21) +
    +[docs] + def name(self): + return "LZ09_F4"
    +
    -
    [docs] def get_name(self): - return 'LZ09_F4'
    -
    [docs]class LZ09_F5(LZ09): +
    +[docs] +class LZ09_F5(LZ09): + def __init__(self, number_of_variables=30): + super(LZ09_F5, self).__init__( + number_of_variables, dtype=1, ltype=26, ptype=21 + ) + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] - def __init__(self): - super(LZ09_F5, self).__init__(number_of_variables=30, number_of_objectives=2, number_of_constraints=0, - dtype=1, ltype=26, ptype=21) +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs] def get_name(self): - return 'LZ09_F5'
    +
    +[docs] + def name(self): + return "LZ09_F5"
    +
    -
    [docs]class LZ09_F6(LZ09): - def __init__(self): - super(LZ09_F6, self).__init__(number_of_variables=10, number_of_objectives=3, number_of_constraints=0, - dtype=1, ltype=32, ptype=31) -
    [docs] def get_name(self): - return 'LZ09_F6'
    +
    +[docs] +class LZ09_F6(LZ09): + def __init__(self, number_of_variables=10): + super(LZ09_F6, self).__init__( + number_of_variables, dtype=1, ltype=32, ptype=31 + ) + self.obj_directions = [self.MINIMIZE, self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)", "f(z)"] +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    -
    [docs]class LZ09_F7(LZ09): - def __init__(self): - super(LZ09_F7, self).__init__(number_of_variables=10, number_of_objectives=2, number_of_constraints=0, - dtype=3, ltype=21, ptype=21) +
    +[docs] + def name(self): + return "LZ09_F6"
    +
    -
    [docs] def get_name(self): - return 'LZ09_F7'
    -
    [docs]class LZ09_F8(LZ09): +
    +[docs] +class LZ09_F7(LZ09): + def __init__(self, number_of_variables=10): + super(LZ09_F7, self).__init__( + number_of_variables, dtype=3, ltype=21, ptype=21 + ) + + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def name(self): + return "LZ09_F7"
    +
    - def __init__(self): - super(LZ09_F8, self).__init__(number_of_variables=10, number_of_objectives=2, number_of_constraints=0, - dtype=4, ltype=21, ptype=21) -
    [docs] def get_name(self): - return 'LZ09_F8'
    +
    +[docs] +class LZ09_F8(LZ09): + def __init__(self, number_of_variables=10): + super(LZ09_F8, self).__init__( + number_of_variables, dtype=4, ltype=21, ptype=21 + ) + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] -
    [docs]class LZ09_F9(LZ09): +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    - def __init__(self): - super(LZ09_F9, self).__init__(number_of_variables=30, number_of_objectives=2, number_of_constraints=0, - dtype=1, ltype=22, ptype=22) -
    [docs] def get_name(self): - return 'LZ09_F9'
    +
    +[docs] + def name(self): + return "LZ09_F8"
    +
    + + + +
    +[docs] +class LZ09_F9(LZ09): + def __init__(self, number_of_variables=30): + super(LZ09_F9, self).__init__( + number_of_variables, dtype=1, ltype=22, ptype=22 + ) + + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["f(x)", "f(y)"] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def name(self): + return "LZ09_F9"
    +
    +
    @@ -486,8 +622,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.multiobjective.unconstrained — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -110,10 +107,15 @@

    Table Of Contents

    Source code for jmetal.problem.multiobjective.unconstrained

     import random
    -from math import sqrt, exp, pow, sin
    +from math import exp, pow, sin, sqrt
     
    -from jmetal.core.problem import FloatProblem, BinaryProblem
    -from jmetal.core.solution import FloatSolution, BinarySolution
    +from jmetal.core.problem import BinaryProblem, FloatProblem, Problem
    +from jmetal.core.solution import (
    +    BinarySolution,
    +    CompositeSolution,
    +    FloatSolution,
    +    IntegerSolution,
    +)
     
     """
     .. module:: constrained
    @@ -124,31 +126,43 @@ 

    Source code for jmetal.problem.multiobjective.unconstrained

    """ -
    [docs]class Kursawe(FloatProblem): - """ Class representing problem Kursawe. """ +
    +[docs] +class Kursawe(FloatProblem): + """Class representing problem Kursawe.""" def __init__(self, number_of_variables: int = 3): super(Kursawe, self).__init__() - self.number_of_objectives = 2 - self.number_of_variables = number_of_variables - self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] self.lower_bound = [-5.0 for _ in range(number_of_variables)] self.upper_bound = [5.0 for _ in range(number_of_variables)] - FloatSolution.lower_bound = self.lower_bound - FloatSolution.upper_bound = self.upper_bound +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - fx = [0.0 for _ in range(self.number_of_objectives)] - for i in range(self.number_of_variables - 1): + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + fx = [0.0 for _ in range(self.number_of_objectives())] + for i in range(self.number_of_variables() - 1): xi = solution.variables[i] * solution.variables[i] xj = solution.variables[i + 1] * solution.variables[i + 1] aux = -0.2 * sqrt(xi + xj) fx[0] += -10 * exp(aux) + + for i in range(self.number_of_variables()): fx[1] += pow(abs(solution.variables[i]), 0.8) + 5.0 * sin(pow(solution.variables[i], 3.0)) solution.objectives[0] = fx[0] @@ -156,85 +170,129 @@

    Source code for jmetal.problem.multiobjective.unconstrained

    return solution
    -
    [docs] def get_name(self): - return 'Kursawe'
    + +
    +[docs] + def name(self): + return "Kursawe"
    +
    -
    [docs]class Fonseca(FloatProblem): +
    +[docs] +class Fonseca(FloatProblem): def __init__(self): super(Fonseca, self).__init__() - self.number_of_variables = 3 - self.number_of_objectives = 2 - self.number_of_constraints = 0 - self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] + + number_of_variables = 3 + + self.lower_bound = number_of_variables * [-4] + self.upper_bound = number_of_variables * [4] - self.lower_bound = self.number_of_variables * [-4] - self.upper_bound = self.number_of_variables * [4] +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    - FloatSolution.lower_bound = self.lower_bound - FloatSolution.upper_bound = self.upper_bound -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: - n = self.number_of_variables - solution.objectives[0] = 1 - exp(-sum([(x - 1.0 / n ** 0.5) ** 2 for x in solution.variables])) - solution.objectives[1] = 1 - exp(-sum([(x + 1.0 / n ** 0.5) ** 2 for x in solution.variables])) +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + n = self.number_of_variables() + solution.objectives[0] = 1 - exp(-sum([(x - 1.0 / n**0.5) ** 2 for x in solution.variables])) + solution.objectives[1] = 1 - exp(-sum([(x + 1.0 / n**0.5) ** 2 for x in solution.variables])) return solution
    -
    [docs] def get_name(self): - return 'Fonseca'
    + +
    +[docs] + def name(self): + return "Fonseca"
    +
    -
    [docs]class Schaffer(FloatProblem): +
    +[docs] +class Schaffer(FloatProblem): def __init__(self): super(Schaffer, self).__init__() - self.number_of_variables = 1 - self.number_of_objectives = 2 - self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)'] + self.obj_labels = ["f(x)", "f(y)"] + + self.lower_bound = [-1000] + self.upper_bound = [1000] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    - self.lower_bound = [-100000] - self.upper_bound = [100000] - FloatSolution.lower_bound = self.lower_bound - FloatSolution.upper_bound = self.upper_bound +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: value = solution.variables[0] - solution.objectives[0] = value ** 2 + solution.objectives[0] = value**2 solution.objectives[1] = (value - 2) ** 2 return solution
    -
    [docs] def get_name(self): - return 'Schaffer'
    + +
    +[docs] + def name(self): + return "Schaffer"
    +
    -
    [docs]class Viennet2(FloatProblem): +
    +[docs] +class Viennet2(FloatProblem): def __init__(self): super(Viennet2, self).__init__() - self.number_of_variables = 2 - self.number_of_objectives = 3 - self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['f(x)', 'f(y)', 'f(z)'] + self.obj_labels = ["f(x)", "f(y)", "f(z)"] + + number_of_variables = 2 + self.lower_bound = number_of_variables * [-4] + self.upper_bound = number_of_variables * [4] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + - self.lower_bound = self.number_of_variables * [-4] - self.upper_bound = self.number_of_variables * [4] +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    - FloatSolution.lower_bound = self.lower_bound - FloatSolution.upper_bound = self.upper_bound -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: x0 = solution.variables[0] x1 = solution.variables[1] @@ -248,14 +306,20 @@

    Source code for jmetal.problem.multiobjective.unconstrained

    return solution
    -
    [docs] def get_name(self): - return 'Viennet2'
    + +
    +[docs] + def name(self): + return "Viennet2"
    +
    -
    [docs]class SubsetSum(BinaryProblem): +
    +[docs] +class SubsetSum(BinaryProblem): def __init__(self, C: int, W: list): - """ The goal is to find a subset S of W whose elements sum is closest to (without exceeding) C. + """The goal is to find a subset S of W whose elements sum is closest to (without exceeding) C. :param C: Large integer. :param W: Set of non-negative integers.""" @@ -269,9 +333,11 @@

    Source code for jmetal.problem.multiobjective.unconstrained

    self.number_of_constraints = 0 self.obj_directions = [self.MAXIMIZE, self.MINIMIZE] - self.obj_labels = ['Sum', 'No. of Objects'] + self.obj_labels = ["Sum", "No. of Objects"] -
    [docs] def evaluate(self, solution: BinarySolution) -> BinarySolution: +
    +[docs] + def evaluate(self, solution: BinarySolution) -> BinarySolution: total_sum = 0.0 number_of_objects = 0 @@ -291,31 +357,61 @@

    Source code for jmetal.problem.multiobjective.unconstrained

    return solution
    -
    [docs] def create_solution(self) -> BinarySolution: - new_solution = BinarySolution(number_of_variables=self.number_of_variables, - number_of_objectives=self.number_of_objectives) - new_solution.variables[0] = \ - [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits)] + +
    +[docs] + def create_solution(self) -> BinarySolution: + new_solution = BinarySolution( + number_of_variables=self.number_of_variables, number_of_objectives=self.number_of_objectives + ) + new_solution.variables[0] = [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits)] return new_solution
    -
    [docs] def get_name(self) -> str: - return 'Subset Sum'
    + +
    +[docs] + def name(self) -> str: + return "Subset Sum"
    +
    + -
    [docs]class OneZeroMax(BinaryProblem): +
    +[docs] +class OneZeroMax(BinaryProblem): + """ The implementation of the OneZeroMax problems defines a single binary variable. This variable + will contain the bit string representing the solutions. + """ def __init__(self, number_of_bits: int = 256): super(OneZeroMax, self).__init__() - self.number_of_bits = number_of_bits - self.number_of_objectives = 2 - self.number_of_variables = 1 - self.number_of_constraints = 0 + self.number_of_bits_per_variable = [number_of_bits] + + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["Zeroes", "Ones"] + +
    +[docs] + def number_of_variables(self) -> int: + return 1
    - self.obj_directions = [self.MINIMIZE] - self.obj_labels = ['Ones'] -
    [docs] def evaluate(self, solution: BinarySolution) -> BinarySolution: +
    +[docs] + def number_of_objectives(self) -> int: + return 2
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: BinarySolution) -> BinarySolution: counter_of_ones = 0 counter_of_zeroes = 0 for bits in solution.variables[0]: @@ -329,15 +425,96 @@

    Source code for jmetal.problem.multiobjective.unconstrained

    return solution
    -
    [docs] def create_solution(self) -> BinarySolution: - new_solution = BinarySolution(number_of_variables=self.number_of_variables, - number_of_objectives=self.number_of_objectives) - new_solution.variables[0] = \ - [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits)] + +
    +[docs] + def create_solution(self) -> BinarySolution: + new_solution = BinarySolution( + number_of_variables=self.number_of_variables(), number_of_objectives=self.number_of_objectives() + ) + new_solution.variables[0] = [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits_per_variable[0])] return new_solution
    -
    [docs] def get_name(self) -> str: - return 'OneZeroMax'
    + +
    +[docs] + def name(self) -> str: + return "OneZeroMax"
    +
    + + + +
    +[docs] +class MixedIntegerFloatProblem(Problem): + def __init__( + self, + number_of_integer_variables=10, + number_of_float_variables=10, + n=100, + m=-100, + lower_bound=-1000, + upper_bound=1000, + ): + super(MixedIntegerFloatProblem, self).__init__() + self.number_of_objectives = 2 + self.number_of_variables = 2 + self.number_of_constraints = 0 + + self.n = n + self.m = m + + self.float_lower_bound = [lower_bound for _ in range(number_of_float_variables)] + self.float_upper_bound = [upper_bound for _ in range(number_of_float_variables)] + self.int_lower_bound = [lower_bound for _ in range(number_of_integer_variables)] + self.int_upper_bound = [upper_bound for _ in range(number_of_integer_variables)] + + self.obj_directions = [self.MINIMIZE] + self.obj_labels = ["Ones"] + +
    +[docs] + def evaluate(self, solution: CompositeSolution) -> CompositeSolution: + distance_to_n = sum([abs(self.n - value) for value in solution.variables[0].variables]) + distance_to_m = sum([abs(self.m - value) for value in solution.variables[0].variables]) + + distance_to_n += sum([abs(self.n - value) for value in solution.variables[1].variables]) + distance_to_m += sum([abs(self.m - value) for value in solution.variables[1].variables]) + + solution.objectives[0] = distance_to_n + solution.objectives[1] = distance_to_m + + return solution
    + + +
    +[docs] + def create_solution(self) -> CompositeSolution: + integer_solution = IntegerSolution( + self.int_lower_bound, self.int_upper_bound, self.number_of_objectives, self.number_of_constraints + ) + float_solution = FloatSolution( + self.float_lower_bound, self.float_upper_bound, self.number_of_objectives, self.number_of_constraints + ) + + float_solution.variables = [ + random.uniform(self.float_lower_bound[i] * 1.0, self.float_upper_bound[i] * 1.0) + for i in range(len(self.float_lower_bound)) + ] + integer_solution.variables = [ + random.uniform(self.int_lower_bound[i], self.int_upper_bound[i]) + for i in range(len(self.int_lower_bound)) + ] + + return CompositeSolution([integer_solution, float_solution])
    + + +
    +[docs] + def name(self) -> str: + return "Mixed Integer Float Problem"
    +
    +
    @@ -354,8 +531,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.multiobjective.zdt — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -109,10 +106,11 @@

    Table Of Contents

    Source code for jmetal.problem.multiobjective.zdt

    -from math import sqrt, pow, sin, pi, cos
    +import random
    +from math import cos, pi, pow, sin, sqrt, exp
     
    -from jmetal.core.problem import FloatProblem
    -from jmetal.core.solution import FloatSolution
    +from jmetal.core.problem import FloatProblem, BinaryProblem
    +from jmetal.core.solution import FloatSolution, BinarySolution
     
     """
     .. module:: ZDT
    @@ -123,28 +121,46 @@ 

    Source code for jmetal.problem.multiobjective.zdt

    """ -
    [docs]class ZDT1(FloatProblem): - """ Problem ZDT1. +
    +[docs] +class ZDT1(FloatProblem): + """Problem ZDT1. .. note:: Bi-objective unconstrained problem. The default number of variables is 30. .. note:: Continuous problem having a convex Pareto front """ - def __init__(self, number_of_variables: int=30): - """ :param number_of_variables: Number of decision variables of the problem. - """ + def __init__(self, number_of_variables: int = 30): + """:param number_of_variables: Number of decision variables of the problem.""" super(ZDT1, self).__init__() - self.number_of_variables = number_of_variables - self.number_of_objectives = 2 - self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE, self.MINIMIZE] - self.obj_labels = ['x', 'y'] + self.obj_labels = ["x", "y"] + + self.lower_bound = number_of_variables * [0.0] + self.upper_bound = number_of_variables * [1.0] + +
    +[docs] + def number_of_objectives(self) -> int: + return len(self.obj_directions)
    + + +
    +[docs] + def number_of_variables(self) -> int: + return len(self.lower_bound)
    - self.lower_bound = self.number_of_variables * [0.0] - self.upper_bound = self.number_of_variables * [1.0] -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: g = self.eval_g(solution) h = self.eval_h(solution.variables[0], g) @@ -153,106 +169,296 @@

    Source code for jmetal.problem.multiobjective.zdt

    return solution
    -
    [docs] def eval_g(self, solution: FloatSolution): + +
    +[docs] + def eval_g(self, solution: FloatSolution): g = sum(solution.variables) - solution.variables[0] - constant = 9.0 / (solution.number_of_variables - 1) + constant = 9.0 / (len(solution.variables) - 1) return constant * g + 1.0
    -
    [docs] def eval_h(self, f: float, g: float) -> float: + +
    +[docs] + def eval_h(self, f: float, g: float) -> float: return 1.0 - sqrt(f / g)
    -
    [docs] def get_name(self): - return 'ZDT1'
    + +
    +[docs] + def name(self): + return "ZDT1"
    +
    + + + +class ZDT1Modified(ZDT1): + """Problem ZDT1Modified. + + .. note:: Version including a loop for increasing the computing time of the evaluation functions. + """ + + def __init__(self, number_of_variables=30): + super(ZDT1Modified, self).__init__(number_of_variables) + + def evaluate(self, solution: FloatSolution) -> FloatSolution: + s: float = 0.0 + for i in range(1000): + for j in range(10000): + s += i * 0.235 / 1.234 + 1.23525 * j + return super().evaluate(solution) -
    [docs]class ZDT2(ZDT1): - """ Problem ZDT2. +
    +[docs] +class ZDT1Modified(ZDT1): + """ Problem ZDT1Modified. + + .. note:: Version including a loop for increasing the computing time of the evaluation functions. + """ + def __init__(self, number_of_variables = 30): + super(ZDT1Modified, self).__init__(number_of_variables) + +
    +[docs] + def evaluate(self, solution:FloatSolution) -> FloatSolution: + s: float = 0.0 + for i in range(1000): + for j in range(10000): + s += i * 0.235 / 1.234 + 1.23525 * j + return super().evaluate(solution)
    +
    + + + +
    +[docs] +class ZDT2(ZDT1): + """Problem ZDT2. .. note:: Bi-objective unconstrained problem. The default number of variables is 30. .. note:: Continuous problem having a non-convex Pareto front """ -
    [docs] def eval_h(self, f: float, g: float) -> float: +
    +[docs] + def eval_h(self, f: float, g: float) -> float: return 1.0 - pow(f / g, 2.0)
    -
    [docs] def get_name(self): - return 'ZDT2'
    + +
    +[docs] + def name(self): + return "ZDT2"
    +
    + -
    [docs]class ZDT3(ZDT1): - """ Problem ZDT3. +
    +[docs] +class ZDT3(ZDT1): + """Problem ZDT3. .. note:: Bi-objective unconstrained problem. The default number of variables is 30. .. note:: Continuous problem having a partitioned Pareto front """ -
    [docs] def eval_h(self, f: float, g: float) -> float: + +
    +[docs] + def eval_h(self, f: float, g: float) -> float: return 1.0 - sqrt(f / g) - (f / g) * sin(10.0 * f * pi)
    -
    [docs] def get_name(self): - return 'ZDT3'
    + +
    +[docs] + def name(self): + return "ZDT3"
    +
    -
    [docs]class ZDT4(ZDT1): - """ Problem ZDT4. + +
    +[docs] +class ZDT4(ZDT1): + """Problem ZDT4. .. note:: Bi-objective unconstrained problem. The default number of variables is 10. .. note:: Continuous multi-modal problem having a convex Pareto front """ - def __init__(self, number_of_variables: int=10): - """ :param number_of_variables: Number of decision variables of the problem. - """ - super(ZDT4, self).__init__(number_of_variables=number_of_variables) - self.lower_bound = self.number_of_variables * [-5.0] - self.upper_bound = self.number_of_variables * [5.0] + def __init__(self, number_of_variables: int = 10): + """:param number_of_variables: Number of decision variables of the problem.""" + super(ZDT4, self).__init__() + self.lower_bound = number_of_variables * [-5.0] + self.upper_bound = number_of_variables * [5.0] self.lower_bound[0] = 0.0 self.upper_bound[0] = 1.0 -
    [docs] def eval_g(self, solution: FloatSolution): +
    +[docs] + def eval_g(self, solution: FloatSolution): g = 0.0 - for i in range(1, solution.number_of_variables): + for i in range(1, len(solution.variables)): g += pow(solution.variables[i], 2.0) - 10.0 * cos(4.0 * pi * solution.variables[i]) - g += 1.0 + 10.0 * (solution.number_of_variables - 1) + g += 1.0 + 10.0 * (len(solution.variables) - 1) return g
    -
    [docs] def eval_h(self, f: float, g: float) -> float: + +
    +[docs] + def eval_h(self, f: float, g: float) -> float: return 1.0 - sqrt(f / g)
    -
    [docs] def get_name(self): - return 'ZDT4'
    + +
    +[docs] + def name(self): + return "ZDT4"
    +
    + + + +
    +[docs] +class ZDT5(BinaryProblem): + """Problem ZDT5. + + .. note:: Bi-objective binary unconstrained problem. The default number of variables is 11. + """ + + def __init__(self, number_of_variables: int = 11): + """:param number_of_bits: Number of bits of each variable of the problem.""" + super(ZDT5, self).__init__() + + self.number_of_bits_per_variable = [5 for _ in range(0, number_of_variables)] + self.number_of_bits_per_variable[0] = 30 + + self.obj_directions = [self.MINIMIZE, self.MINIMIZE] + self.obj_labels = ["x", "y"] + +
    +[docs] + def number_of_variables(self) -> int: + return len(self.number_of_bits_per_variable)
    + + +
    +[docs] + def number_of_objectives(self) -> int: + return 2
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: BinarySolution) -> BinarySolution: + solution.objectives[0] = 1.0 + solution.cardinality(0) + + g = self.eval_g(solution) + h = 1.0 / solution.objectives[0] + + solution.objectives[1] = h * g + + return solution
    + + +
    +[docs] + def eval_g(self, solution: BinarySolution): + result = 0.0 + for i in range(1, len(solution.variables)): + result = result + self.eval_v(solution.cardinality(i)) + + return result
    -
    [docs]class ZDT6(ZDT1): - """ Problem ZDT6. +
    +[docs] + def eval_v(self, value): + if value < 5.0: + return 2.0 + value + else: + return 1.0
    + + +
    +[docs] + def create_solution(self) -> BinarySolution: + new_solution = BinarySolution(number_of_variables=self.number_of_variables(), number_of_objectives=2) + for i in range(self.number_of_variables()): + new_solution.variables[i] = [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits_per_variable[i])] + return new_solution
    + + +
    +[docs] + def name(self): + return "ZDT5"
    +
    + + + +
    +[docs] +class ZDT6(ZDT1): + """Problem ZDT6. .. note:: Bi-objective unconstrained problem. The default number of variables is 10. .. note:: Continuous problem having a non-convex Pareto front """ - def __init__(self, number_of_variables: int=10): - """ :param number_of_variables: Number of decision variables of the problem. - """ + def __init__(self, number_of_variables: int = 10): + """:param number_of_variables: Number of decision variables of the problem.""" super(ZDT6, self).__init__(number_of_variables=number_of_variables) -
    [docs] def eval_g(self, solution: FloatSolution): +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: + solution.objectives[0] = ( + 1.0 - exp(-4.0 * solution.variables[0]) * (sin(6.0 * pi * solution.variables[0])) ** 6.0 + ) + + g = self.eval_g(solution) + h = self.eval_h(solution.objectives[0], g) + solution.objectives[1] = h * g + + return solution
    + + +
    +[docs] + def eval_g(self, solution: FloatSolution): g = sum(solution.variables) - solution.variables[0] - g = g / (solution.number_of_variables - 1) + g = g / (len(solution.variables) - 1) g = pow(g, 0.25) g = 9.0 * g g = 1.0 + g return g
    -
    [docs] def eval_h(self, f: float, g: float) -> float: + +
    +[docs] + def eval_h(self, f: float, g: float) -> float: return 1.0 - pow(f / g, 2.0)
    -
    [docs] def get_name(self): - return 'ZDT6'
    + +
    +[docs] + def name(self): + return "ZDT6"
    +
    +
    @@ -269,8 +475,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.singleobjective.knapsack — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -125,11 +122,20 @@

    Source code for jmetal.problem.singleobjective.knapsack

    """ -
    [docs]class Knapsack(BinaryProblem): - """ Class representing Knapsack Problem. """ - - def __init__(self, number_of_items: int = 50, capacity: float = 1000, weights: list = None, - profits: list = None, from_file: bool = False, filename: str = None): +
    +[docs] +class Knapsack(BinaryProblem): + """Class representing Knapsack Problem.""" + + def __init__( + self, + number_of_items: int = 50, + capacity: float = 1000, + weights: list = None, + profits: list = None, + from_file: bool = False, + filename: str = None, + ): super(Knapsack, self).__init__() if from_file: @@ -140,13 +146,28 @@

    Source code for jmetal.problem.singleobjective.knapsack

    self.profits = profits self.number_of_bits = number_of_items - self.number_of_variables = 1 self.obj_directions = [self.MAXIMIZE] - self.number_of_objectives = 1 - self.number_of_constraints = 1 + +
    +[docs] + def number_of_variables(self) -> int: + return 1
    + + +
    +[docs] + def number_of_objectives(self) -> int: + return 1
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 1
    + def __read_from_file(self, filename: str): - """ + """ This function reads a Knapsack Problem instance from a file. It expects the following format: @@ -159,7 +180,7 @@

    Source code for jmetal.problem.singleobjective.knapsack

    """ if filename is None: - raise FileNotFoundError('Filename can not be None') + raise FileNotFoundError("Filename can not be None") with open(filename) as file: lines = file.readlines() @@ -168,12 +189,14 @@

    Source code for jmetal.problem.singleobjective.knapsack

    self.number_of_bits = int(data[0][0]) self.capacity = float(data[1][0]) - weights_and_profits = np.asfarray(data[2:], dtype=np.float32) + weights_and_profits = np.asarray(data[2:], dtype=np.float32) self.weights = weights_and_profits[:, 0] self.profits = weights_and_profits[:, 1] -
    [docs] def evaluate(self, solution: BinarySolution) -> BinarySolution: +
    +[docs] + def evaluate(self, solution: BinarySolution) -> BinarySolution: total_profits = 0.0 total_weigths = 0.0 @@ -188,18 +211,25 @@

    Source code for jmetal.problem.singleobjective.knapsack

    solution.objectives[0] = -1.0 * total_profits return solution
    -
    [docs] def create_solution(self) -> BinarySolution: - new_solution = BinarySolution(number_of_variables=self.number_of_variables, - number_of_objectives=self.number_of_objectives) - new_solution.variables[0] = \ - [True if random.randint(0, 1) == 0 else False for _ in range( - self.number_of_bits)] +
    +[docs] + def create_solution(self) -> BinarySolution: + new_solution = BinarySolution( + number_of_variables=self.number_of_variables(), number_of_objectives=self.number_of_objectives() + ) + + new_solution.variables[0] = [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits)] return new_solution
    -
    [docs] def get_name(self): - return 'Knapsack'
    + +
    +[docs] + def name(self): + return "Knapsack"
    +
    +
    @@ -216,8 +246,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.singleobjective.tsp — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -125,23 +122,37 @@

    Source code for jmetal.problem.singleobjective.tsp

    """ -
    [docs]class TSP(PermutationProblem): - """ Class representing TSP Problem. """ +
    +[docs] +class TSP(PermutationProblem): + """Class representing TSP Problem.""" def __init__(self, instance: str = None): super(TSP, self).__init__() - distance_matrix, number_of_cities = self.__read_from_file(instance) + self.distance_matrix, self.number_of_cities = self.__read_from_file(instance) + self.obj_directions = [self.MINIMIZE] - self.distance_matrix = distance_matrix +
    +[docs] + def number_of_variables(self) -> int: + return self.number_of_cities
    + + +
    +[docs] + def number_of_objectives(self) -> int: + return 1
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    - self.obj_directions = [self.MINIMIZE] - self.number_of_variables = number_of_cities - self.number_of_objectives = 1 - self.number_of_constraints = 0 def __read_from_file(self, filename: str): - """ + """ This function reads a TSP Problem instance from a file. :param filename: File which describes the instance. @@ -149,24 +160,24 @@

    Source code for jmetal.problem.singleobjective.tsp

    """ if filename is None: - raise FileNotFoundError('Filename can not be None') + raise FileNotFoundError("Filename can not be None") with open(filename) as file: lines = file.readlines() data = [line.lstrip() for line in lines if line != ""] - dimension = re.compile(r'[^\d]+') + dimension = re.compile(r"[^\d]+") for item in data: - if item.startswith('DIMENSION'): - dimension = int(dimension.sub('', item)) + if item.startswith("DIMENSION"): + dimension = int(dimension.sub("", item)) break c = [-1.0] * (2 * dimension) for item in data: if item[0].isdigit(): - j, city_a, city_b = [int(x.strip()) for x in item.split(' ')] + j, city_a, city_b = [int(x.strip()) for x in item.split(" ")] c[2 * (j - 1)] = city_a c[2 * (j - 1) + 1] = city_b @@ -183,10 +194,12 @@

    Source code for jmetal.problem.singleobjective.tsp

    return matrix, dimension -
    [docs] def evaluate(self, solution: PermutationSolution) -> PermutationSolution: +
    +[docs] + def evaluate(self, solution: PermutationSolution) -> PermutationSolution: fitness = 0 - for i in range(self.number_of_variables - 1): + for i in range(self.number_of_variables() - 1): x = solution.variables[i] y = solution.variables[i + 1] @@ -199,19 +212,24 @@

    Source code for jmetal.problem.singleobjective.tsp

    return solution
    -
    [docs] def create_solution(self) -> PermutationSolution: - new_solution = PermutationSolution(number_of_variables=self.number_of_variables, - number_of_objectives=self.number_of_objectives) - new_solution.variables = random.sample(range(self.number_of_variables), k=self.number_of_variables) + +
    +[docs] + def create_solution(self) -> PermutationSolution: + new_solution = PermutationSolution( + number_of_variables=self.number_of_variables(), number_of_objectives=self.number_of_objectives() + ) + new_solution.variables = random.sample(range(self.number_of_variables()), k=self.number_of_variables()) return new_solution
    - @property - def number_of_cities(self): - return self.number_of_variables -
    [docs] def get_name(self): - return 'Symmetric TSP'
    +
    +[docs] + def name(self): + return "Symmetric TSP"
    +
    +
    @@ -228,8 +246,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.problem.singleobjective.unconstrained — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -124,19 +121,41 @@

    Source code for jmetal.problem.singleobjective.unconstrained

    """ -
    [docs]class OneMax(BinaryProblem): +
    +[docs] +class OneMax(BinaryProblem): + """ The implementation of the OneMax problems defines a single binary variable. This variable + will contain the bit string representing the solutions. + """ def __init__(self, number_of_bits: int = 256): super(OneMax, self).__init__() - self.number_of_bits = number_of_bits - self.number_of_objectives = 1 - self.number_of_variables = 1 - self.number_of_constraints = 0 + self.number_of_bits_per_variable = [number_of_bits] self.obj_directions = [self.MINIMIZE] - self.obj_labels = ['Ones'] + self.obj_labels = ["Ones"] + +
    +[docs] + def number_of_variables(self) -> int: + return 1
    + + +
    +[docs] + def number_of_objectives(self) -> int: + return 1
    -
    [docs] def evaluate(self, solution: BinarySolution) -> BinarySolution: + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: BinarySolution) -> BinarySolution: counter_of_ones = 0 for bits in solution.variables[0]: if bits: @@ -146,26 +165,31 @@

    Source code for jmetal.problem.singleobjective.unconstrained

    return solution
    -
    [docs] def create_solution(self) -> BinarySolution: + +
    +[docs] + def create_solution(self) -> BinarySolution: new_solution = BinarySolution(number_of_variables=1, number_of_objectives=1) - new_solution.variables[0] = \ - [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits)] + new_solution.variables[0] = [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits_per_variable[0])] return new_solution
    -
    [docs] def get_name(self) -> str: - return 'OneMax'
    + +
    +[docs] + def name(self) -> str: + return "OneMax"
    +
    -
    [docs]class Sphere(FloatProblem): +
    +[docs] +class Sphere(FloatProblem): def __init__(self, number_of_variables: int = 10): super(Sphere, self).__init__() - self.number_of_objectives = 1 - self.number_of_variables = number_of_variables - self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE] - self.obj_labels = ['f(x)'] + self.obj_labels = ["f(x)"] self.lower_bound = [-5.12 for _ in range(number_of_variables)] self.upper_bound = [5.12 for _ in range(number_of_variables)] @@ -173,7 +197,21 @@

    Source code for jmetal.problem.singleobjective.unconstrained

    FloatSolution.lower_bound = self.lower_bound FloatSolution.upper_bound = self.upper_bound -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def number_of_objectives(self) -> int: + return 1
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: total = 0.0 for x in solution.variables: total += x * x @@ -182,20 +220,23 @@

    Source code for jmetal.problem.singleobjective.unconstrained

    return solution
    -
    [docs] def get_name(self) -> str: - return 'Sphere'
    + +
    +[docs] + def name(self) -> str: + return "Sphere"
    +
    -
    [docs]class Rastrigin(FloatProblem): +
    +[docs] +class Rastrigin(FloatProblem): def __init__(self, number_of_variables: int = 10): super(Rastrigin, self).__init__() - self.number_of_objectives = 1 - self.number_of_variables = number_of_variables - self.number_of_constraints = 0 self.obj_directions = [self.MINIMIZE] - self.obj_labels = ['f(x)'] + self.obj_labels = ["f(x)"] self.lower_bound = [-5.12 for _ in range(number_of_variables)] self.upper_bound = [5.12 for _ in range(number_of_variables)] @@ -203,26 +244,46 @@

    Source code for jmetal.problem.singleobjective.unconstrained

    FloatSolution.lower_bound = self.lower_bound FloatSolution.upper_bound = self.upper_bound -
    [docs] def evaluate(self, solution: FloatSolution) -> FloatSolution: +
    +[docs] + def number_of_objectives(self) -> int: + return 1
    + + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: FloatSolution) -> FloatSolution: a = 10.0 - result = a * solution.number_of_variables + result = a * len(solution.variables) x = solution.variables - for i in range(solution.number_of_variables): + for i in range(len(solution.variables)): result += x[i] * x[i] - a * math.cos(2 * math.pi * x[i]) solution.objectives[0] = result return solution
    -
    [docs] def get_name(self) -> str: - return 'Rastrigin'
    + +
    +[docs] + def name(self) -> str: + return "Rastrigin"
    +
    -
    [docs]class SubsetSum(BinaryProblem): +
    +[docs] +class SubsetSum(BinaryProblem): def __init__(self, C: int, W: list): - """ The goal is to find a subset S of W whose elements sum is closest to (without exceeding) C. + """The goal is to find a subset S of W whose elements sum is closest to (without exceeding) C. :param C: Large integer. :param W: Set of non-negative integers.""" @@ -231,14 +292,30 @@

    Source code for jmetal.problem.singleobjective.unconstrained

    self.W = W self.number_of_bits = len(self.W) - self.number_of_objectives = 1 - self.number_of_variables = 1 - self.number_of_constraints = 0 self.obj_directions = [self.MAXIMIZE] - self.obj_labels = ['Sum'] + self.obj_labels = ["Sum"] + +
    +[docs] + def number_of_variables(self) -> int: + return 1
    + +
    +[docs] + def number_of_objectives(self) -> int: + return 1
    -
    [docs] def evaluate(self, solution: BinarySolution) -> BinarySolution: + +
    +[docs] + def number_of_constraints(self) -> int: + return 0
    + + +
    +[docs] + def evaluate(self, solution: BinarySolution) -> BinarySolution: total_sum = 0.0 for index, bits in enumerate(solution.variables[0]): @@ -255,16 +332,24 @@

    Source code for jmetal.problem.singleobjective.unconstrained

    return solution
    -
    [docs] def create_solution(self) -> BinarySolution: - new_solution = BinarySolution(number_of_variables=self.number_of_variables, - number_of_objectives=self.number_of_objectives) - new_solution.variables[0] = \ - [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits)] + +
    +[docs] + def create_solution(self) -> BinarySolution: + new_solution = BinarySolution( + number_of_variables=self.number_of_variables(), number_of_objectives=self.number_of_objectives() + ) + new_solution.variables[0] = [True if random.randint(0, 1) == 0 else False for _ in range(self.number_of_bits)] return new_solution
    -
    [docs] def get_name(self) -> str: - return 'Subset Sum'
    + +
    +[docs] + def name(self) -> str: + return "Subset Sum"
    +
    +
    @@ -281,8 +366,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.util.evaluator — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -111,8 +108,8 @@

    Table Of Contents

    Source code for jmetal.util.evaluator

     import functools
     from abc import ABC, abstractmethod
    -from multiprocessing.pool import ThreadPool, Pool
    -from typing import TypeVar, List, Generic
    +from multiprocessing.pool import Pool, ThreadPool
    +from typing import Generic, List, TypeVar
     
     try:
         import dask
    @@ -126,11 +123,10 @@ 

    Source code for jmetal.util.evaluator

     
     from jmetal.core.problem import Problem
     
    -S = TypeVar('S')
    +S = TypeVar("S")
     
     
     class Evaluator(Generic[S], ABC):
    -
         @abstractmethod
         def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]:
             pass
    @@ -140,49 +136,69 @@ 

    Source code for jmetal.util.evaluator

             problem.evaluate(solution)
     
     
    -
    [docs]class SequentialEvaluator(Evaluator[S]): - -
    [docs] def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: +
    +[docs] +class SequentialEvaluator(Evaluator[S]): +
    +[docs] + def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: for solution in solution_list: Evaluator.evaluate_solution(solution, problem) - return solution_list
    + return solution_list
    +
    -
    [docs]class MapEvaluator(Evaluator[S]): +
    +[docs] +class MapEvaluator(Evaluator[S]): def __init__(self, processes: int = None): self.pool = ThreadPool(processes) -
    [docs] def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: +
    +[docs] + def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: self.pool.map(lambda solution: Evaluator.evaluate_solution(solution, problem), solution_list) - return solution_list
    + return solution_list
    +
    + -
    [docs]class MultiprocessEvaluator(Evaluator[S]): +
    +[docs] +class MultiprocessEvaluator(Evaluator[S]): def __init__(self, processes: int = None): super().__init__() self.pool = Pool(processes) -
    [docs] def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: - return self.pool.map(functools.partial(evaluate_solution, problem=problem), solution_list)
    +
    +[docs] + def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: + return self.pool.map(functools.partial(evaluate_solution, problem=problem), solution_list)
    +
    + -
    [docs]class SparkEvaluator(Evaluator[S]): +
    +[docs] +class SparkEvaluator(Evaluator[S]): def __init__(self, processes: int = 8): - self.spark_conf = SparkConf().setAppName("jmetalpy").setMaster(f"local[{processes}]") + self.spark_conf = SparkConf().setAppName("jmetalpy").setMaster(f"local[{processes}]") self.spark_context = SparkContext(conf=self.spark_conf) logger = self.spark_context._jvm.org.apache.log4j logger.LogManager.getLogger("org").setLevel(logger.Level.WARN) -
    [docs] def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: +
    +[docs] + def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: solutions_to_evaluate = self.spark_context.parallelize(solution_list) - return solutions_to_evaluate \ - .map(lambda s: problem.evaluate(s)) \ - .collect()
    + return solutions_to_evaluate.map(lambda s: problem.evaluate(s)).collect()
    +
    + def evaluate_solution(solution, problem): @@ -190,15 +206,23 @@

    Source code for jmetal.util.evaluator

         return solution
     
     
    -
    [docs]class DaskEvaluator(Evaluator[S]): - def __init__(self, scheduler='processes'): +
    +[docs] +class DaskEvaluator(Evaluator[S]): + def __init__(self, scheduler="processes"): self.scheduler = scheduler -
    [docs] def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: +
    +[docs] + def evaluate(self, solution_list: List[S], problem: Problem) -> List[S]: with dask.config.set(scheduler=self.scheduler): - return list(dask.compute(*[ - dask.delayed(evaluate_solution)(solution=solution, problem=problem) for solution in solution_list - ]))
    + return list( + dask.compute( + *[dask.delayed(evaluate_solution)(solution=solution, problem=problem) for solution in solution_list] + ) + )
    +
    +
    @@ -215,8 +239,9 @@

    Navigation

  • modules |
  • - - + + +
    - - - - - - - + jmetal.util.observer — jMetalPy 1.7.0 documentation + + + + + + + @@ -39,8 +35,9 @@

    Navigation

  • modules |
  • - - + + +
    @@ -51,7 +48,7 @@

    Navigation

    @@ -114,17 +111,18 @@

    Source code for jmetal.util.observer

     from pathlib import Path
     from typing import List, TypeVar
     
    +import numpy as np
     from tqdm import tqdm
     
     from jmetal.core.observer import Observer
     from jmetal.core.problem import DynamicProblem
     from jmetal.core.quality_indicator import InvertedGenerationalDistance
    -from jmetal.lab.visualization import StreamingPlot, Plot
    +from jmetal.lab.visualization import Plot, StreamingPlot
     from jmetal.util.solution import print_function_values_to_file
     
    -S = TypeVar('S')
    +S = TypeVar("S")
     
    -LOGGER = logging.getLogger('jmetal')
    +LOGGER = logging.getLogger("jmetal")
     
     """
     .. module:: observer
    @@ -135,10 +133,11 @@ 

    Source code for jmetal.util.observer

     """
     
     
    -
    [docs]class ProgressBarObserver(Observer): - +
    +[docs] +class ProgressBarObserver(Observer): def __init__(self, max: int) -> None: - """ Show a smart progress meter with the number of evaluations and computing time. + """Show a smart progress meter with the number of evaluations and computing time. :param max: Number of expected iterations. """ @@ -146,31 +145,38 @@

    Source code for jmetal.util.observer

             self.progress = 0
             self._max = max
     
    -
    [docs] def update(self, *args, **kwargs): +
    +[docs] + def update(self, *args, **kwargs): if not self.progress_bar: - self.progress_bar = tqdm(total=self._max, ascii=True, desc='Progress') + self.progress_bar = tqdm(total=self._max, ascii=True, desc="Progress") - evaluations = kwargs['EVALUATIONS'] + evaluations = kwargs["EVALUATIONS"] self.progress_bar.update(evaluations - self.progress) self.progress = evaluations if self.progress >= self._max: - self.progress_bar.close()
    + self.progress_bar.close()
    +
    -
    [docs]class BasicObserver(Observer): - def __init__(self, frequency: float = 1.0) -> None: - """ Show the number of evaluations, best fitness and computing time. +
    +[docs] +class BasicObserver(Observer): + def __init__(self, frequency: int = 1) -> None: + """Show the number of evaluations, the best fitness and the computing time. + :param frequency: Display frequency.""" - :param frequency: Display frequency. """ self.display_frequency = frequency -
    [docs] def update(self, *args, **kwargs): - computing_time = kwargs['COMPUTING_TIME'] - evaluations = kwargs['EVALUATIONS'] - solutions = kwargs['SOLUTIONS'] +
    +[docs] + def update(self, *args, **kwargs): + computing_time = kwargs["COMPUTING_TIME"] + evaluations = kwargs["EVALUATIONS"] + solutions = kwargs["SOLUTIONS"] if (evaluations % self.display_frequency) == 0 and solutions: if type(solutions) == list: @@ -179,23 +185,26 @@

    Source code for jmetal.util.observer

                     fitness = solutions.objectives
     
                 LOGGER.info(
    -                'Evaluations: {} \n Best fitness: {} \n Computing time: {}'.format(
    -                    evaluations, fitness, computing_time
    -                )
    -            )
    + "Evaluations: {} \n Best fitness: {} \n Computing time: {}".format(evaluations, fitness, computing_time) + )
    +
    -
    [docs]class PrintObjectivesObserver(Observer): - def __init__(self, frequency: float = 1.0) -> None: - """ Show the number of evaluations, best fitness and computing time. +
    +[docs] +class PrintObjectivesObserver(Observer): + def __init__(self, frequency: int = 1) -> None: + """Show the number of evaluations, best fitness and computing time. - :param frequency: Display frequency. """ + :param frequency: Display frequency.""" self.display_frequency = frequency -
    [docs] def update(self, *args, **kwargs): - evaluations = kwargs['EVALUATIONS'] - solutions = kwargs['SOLUTIONS'] +
    +[docs] + def update(self, *args, **kwargs): + evaluations = kwargs["EVALUATIONS"] + solutions = kwargs["SOLUTIONS"] if (evaluations % self.display_frequency) == 0 and solutions: if type(solutions) == list: @@ -203,124 +212,137 @@

    Source code for jmetal.util.observer

                 else:
                     fitness = solutions.objectives
     
    -            LOGGER.info(
    -                'Evaluations: {}. fitness: {}'.format(
    -                    evaluations, fitness
    -                )
    -            )
    + LOGGER.info("Evaluations: {}. fitness: {}".format(evaluations, fitness))
    +
    -
    [docs]class WriteFrontToFileObserver(Observer): +
    +[docs] +class WriteFrontToFileObserver(Observer): def __init__(self, output_directory: str) -> None: - """ Write function values of the front into files. + """Write function values of the front into files. - :param output_directory: Output directory. Each front will be saved on a file `FUN.x`. """ + :param output_directory: Output directory. Each front will be saved on a file `FUN.x`.""" self.counter = 0 self.directory = output_directory if Path(self.directory).is_dir(): - LOGGER.warning('Directory {} exists. Removing contents.'.format(self.directory)) + LOGGER.warning("Directory {} exists. Removing contents.".format(self.directory)) for file in os.listdir(self.directory): - os.remove('{0}/{1}'.format(self.directory, file)) + os.remove("{0}/{1}".format(self.directory, file)) else: - LOGGER.warning('Directory {} does not exist. Creating it.'.format(self.directory)) + LOGGER.warning("Directory {} does not exist. Creating it.".format(self.directory)) Path(self.directory).mkdir(parents=True) -
    [docs] def update(self, *args, **kwargs): - problem = kwargs['PROBLEM'] - solutions = kwargs['SOLUTIONS'] +
    +[docs] + def update(self, *args, **kwargs): + problem = kwargs["PROBLEM"] + solutions = kwargs["SOLUTIONS"] if solutions: if isinstance(problem, DynamicProblem): - termination_criterion_is_met = kwargs.get('TERMINATION_CRITERIA_IS_MET', None) + termination_criterion_is_met = kwargs.get("TERMINATION_CRITERIA_IS_MET", None) if termination_criterion_is_met: - print_function_values_to_file(solutions, '{}/FUN.{}'.format(self.directory, self.counter)) + print_function_values_to_file(solutions, "{}/FUN.{}".format(self.directory, self.counter)) self.counter += 1 else: - print_function_values_to_file(solutions, '{}/FUN.{}'.format(self.directory, self.counter)) - self.counter += 1
    + print_function_values_to_file(solutions, "{}/FUN.{}".format(self.directory, self.counter)) + self.counter += 1
    +
    -
    [docs]class PlotFrontToFileObserver(Observer): +
    +[docs] +class PlotFrontToFileObserver(Observer): def __init__(self, output_directory: str, step: int = 100, **kwargs) -> None: - """ Plot and save Pareto front approximations into files. + """Plot and save Pareto front approximations into files. :param output_directory: Output directory. """ self.directory = output_directory - self.plot_front = Plot(title='Pareto front approximation', **kwargs) + self.plot_front = Plot(title="Pareto front approximation", **kwargs) self.last_front = [] self.fronts = [] self.counter = 0 self.step = step if Path(self.directory).is_dir(): - LOGGER.warning('Directory {} exists. Removing contents.'.format(self.directory)) + LOGGER.warning("Directory {} exists. Removing contents.".format(self.directory)) for file in os.listdir(self.directory): - os.remove('{0}/{1}'.format(self.directory, file)) + os.remove("{0}/{1}".format(self.directory, file)) else: - LOGGER.warning('Directory {} does not exist. Creating it.'.format(self.directory)) + LOGGER.warning("Directory {} does not exist. Creating it.".format(self.directory)) Path(self.directory).mkdir(parents=True) -
    [docs] def update(self, *args, **kwargs): - problem = kwargs['PROBLEM'] - solutions = kwargs['SOLUTIONS'] - evaluations = kwargs['EVALUATIONS'] +
    +[docs] + def update(self, *args, **kwargs): + problem = kwargs["PROBLEM"] + solutions = kwargs["SOLUTIONS"] + evaluations = kwargs["EVALUATIONS"] if solutions: if (evaluations % self.step) == 0: if isinstance(problem, DynamicProblem): - termination_criterion_is_met = kwargs.get('TERMINATION_CRITERIA_IS_MET', None) + termination_criterion_is_met = kwargs.get("TERMINATION_CRITERIA_IS_MET", None) if termination_criterion_is_met: if self.counter > 0: - igd = InvertedGenerationalDistance(self.last_front) - igd_value = igd.compute(solutions) + igd = InvertedGenerationalDistance(np.array([s.objectives for s in self.last_front])) + igd_value = igd.compute(np.array([s.objectives for s in solutions])) else: igd_value = 1 if igd_value > 0.005: self.fronts += solutions - self.plot_front.plot([self.fronts], - label=problem.get_name(), - filename=f'{self.directory}/front-{evaluations}') + self.plot_front.plot( + [self.fronts], + label=problem.get_name(), + filename=f"{self.directory}/front-{evaluations}", + ) self.counter += 1 self.last_front = solutions else: - self.plot_front.plot([solutions], - label=f'{evaluations} evaluations', - filename=f'{self.directory}/front-{evaluations}') - self.counter += 1
    + self.plot_front.plot( + [solutions], + label=f"{evaluations} evaluations", + filename=f"{self.directory}/front-{evaluations}", + ) + self.counter += 1
    +
    -
    [docs]class VisualizerObserver(Observer): - def __init__(self, - reference_front: List[S] = None, - reference_point: list = None, - display_frequency: float = 1.0) -> None: +
    +[docs] +class VisualizerObserver(Observer): + def __init__( + self, reference_front: List[S] = None, reference_point: list = None, display_frequency: int = 1 + ) -> None: self.figure = None self.display_frequency = display_frequency self.reference_point = reference_point self.reference_front = reference_front -
    [docs] def update(self, *args, **kwargs): - evaluations = kwargs['EVALUATIONS'] - solutions = kwargs['SOLUTIONS'] +
    +[docs] + def update(self, *args, **kwargs): + evaluations = kwargs["EVALUATIONS"] + solutions = kwargs["SOLUTIONS"] if solutions: if self.figure is None: - self.figure = StreamingPlot(reference_point=self.reference_point, - reference_front=self.reference_front) + self.figure = StreamingPlot(reference_point=self.reference_point, reference_front=self.reference_front) self.figure.plot(solutions) if (evaluations % self.display_frequency) == 0: # check if reference point has changed - reference_point = kwargs.get('REFERENCE_POINT', None) + reference_point = kwargs.get("REFERENCE_POINT", None) if reference_point: self.reference_point = reference_point @@ -328,7 +350,9 @@

    Source code for jmetal.util.observer

                     else:
                         self.figure.update(solutions)
     
    -                self.figure.ax.set_title('Eval: {}'.format(evaluations), fontsize=13)
    + self.figure.ax.set_title("Eval: {}".format(evaluations), fontsize=13)
    +
    +
    @@ -345,8 +369,9 @@

    Navigation

  • modules |
  • - - + + +
    + + + + + + + + + + + + +
    + +
    + +
    +
    +
    + + + + + + +
    +
    +
    + + + +
    + +
    +

    About

    +

    jMetalPy is being developed by Antonio J. Nebro, full professor at the University of Málaga.

    +
    +

    Cite us

    +
    @article{BENITEZHIDALGO2019100598,
    +   title = "jMetalPy: A Python framework for multi-objective optimization with metaheuristics",
    +   journal = "Swarm and Evolutionary Computation",
    +   pages = "100598",
    +   year = "2019",
    +   issn = "2210-6502",
    +   doi = "https://doi.org/10.1016/j.swevo.2019.100598",
    +   url = "http://www.sciencedirect.com/science/article/pii/S2210650219301397",
    +   author = "Antonio Benítez-Hidalgo and Antonio J. Nebro and José García-Nieto and Izaskun Oregi and Javier Del Ser",
    +   keywords = "Multi-objective optimization, Metaheuristics, Software framework, Python, Statistical analysis, Visualization",
    +}
    +
    +
    +
    +
    +

    References

    +
      +
    1. J.J. Durillo, A.J. Nebro jMetal: a Java Framework for Multi-Objective Optimization. Advances in Engineering Software 42 (2011) 760-771.

    2. +
    3. A.J. Nebro, J.J. Durillo, M. Vergne Redesigning the jMetal Multi-Objective Optimization Framework. GECCO (Companion) 2015, pp: 1093-1100. July 2015.

    4. +
    5. Nebro A.J. et al. (2018) Extending the Speed-Constrained Multi-objective PSO (SMPSO) with Reference Point Based Preference Articulation. In: Auger A., Fonseca C., Lourenço N., Machado P., Paquete L., Whitley D. (eds) Parallel Problem Solving from Nature – PPSN XV. PPSN 2018. Lecture Notes in Computer Science, vol 11101. Springer, Cham

    6. +
    +
    +
    + + +
    + + +
    + +
    +
    +
    + + + + + + \ No newline at end of file diff --git a/docs/api/algorithm/multiobjective/ea.html b/docs/api/algorithm/multiobjective/ea.html index e43d4443..4dab0909 100644 --- a/docs/api/algorithm/multiobjective/ea.html +++ b/docs/api/algorithm/multiobjective/ea.html @@ -1,9 +1,10 @@ - - + + + @@ -12,18 +13,16 @@ - Evolutionary Algorithms — jMetalPy 1.5.3 documentation - - - - - - - - - - - + Evolutionary Algorithms — jMetalPy 1.7.0 documentation + + + + + + + + + @@ -47,8 +46,9 @@

    Navigation

  • previous |
  • - - + + +
    @@ -59,7 +59,7 @@

    Navigation

    @@ -120,10 +120,10 @@

    Table Of Contents

    -
    -

    Evolutionary Algorithms

    +
    +

    Evolutionary Algorithms

    -

    Multi-objective evolutionary algorithms:

    +

    Multi-objective evolutionary algorithms:

    -
    +
    @@ -170,8 +170,9 @@

    Navigation

  • previous |
  • - - + + +
    - - - - - - - + GDE3 — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,20 @@

    Contents

    @@ -138,216 +152,15 @@

    Contents

    - - -
    -

    GDE3

    -
    -

    Example

    +
    +

    GDE3

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.gde3 import GDE3
    +
    from jmetal.algorithm.multiobjective.gde3 import GDE3
     from jmetal.problem import ZDT1
     from jmetal.util.termination_criterion import StoppingByEvaluations
     
    @@ -373,8 +186,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.gde3.GDE3(problem: jmetal.core.problem.Problem, population_size: int, cr: float, f: float, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, k: float = 0.5, population_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.core.algorithm.EvolutionaryAlgorithm

    -
    -
    -create_initial_solutions() → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.gde3.GDE3(problem: ~jmetal.core.problem.Problem, population_size: int, cr: float, f: float, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, k: float = 0.5, population_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: EvolutionaryAlgorithm[FloatSolution, FloatSolution]

    +
    +
    +create_initial_solutions() List[FloatSolution][source]

    Creates the initial list of solutions of a metaheuristic.

    -
    -
    -evaluate(solution_list: List[jmetal.core.solution.FloatSolution]) → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +evaluate(solution_list: List[FloatSolution]) List[FloatSolution][source]

    Evaluates a solution list.

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +get_name() str[source]
    -
    -
    -replacement(population: List[S], offspring_population: List[jmetal.core.solution.FloatSolution]) → List[List[jmetal.core.solution.FloatSolution]][source]
    +
    +
    +replacement(population: List[S], offspring_population: List[FloatSolution]) List[List[FloatSolution]][source]

    Replace least-fit population with new individuals.

    -
    -
    -reproduction(mating_pool: List[S]) → List[S][source]
    +
    +
    +reproduction(mating_pool: List[S]) List[S][source]

    Breed new individuals through crossover and mutation operations to give birth to offspring.

    -
    -
    -selection(population: List[jmetal.core.solution.FloatSolution]) → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +result() List[FloatSolution][source]
    +
    + +
    +
    +selection(population: List[FloatSolution]) List[FloatSolution][source]

    Select the best-fit individuals for reproduction (parents).

    -
    -
    -stopping_condition_is_met() → bool[source]
    +
    +
    +stopping_condition_is_met() bool[source]

    The stopping condition is met or not.

    -
    -
    + +
    @@ -482,9 +294,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + Dynamic GDE3 — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -39,7 +39,8 @@

    Navigation

  • modules |
  • - + +
    @@ -50,7 +51,7 @@

    Navigation

    @@ -84,7 +85,15 @@

    Contents

    @@ -120,216 +129,15 @@

    Contents

    - - -
    -

    Dynamic GDE3

    -
    -

    Example

    +
    +

    Dynamic GDE3

    +
    +

    Example

    [ ]:
     
    -
    -from jmetal.algorithm.multiobjective.gde3 import DynamicGDE3
    +
    from jmetal.algorithm.multiobjective.gde3 import DynamicGDE3
     from jmetal.problem.multiobjective.fda import FDA2
     from jmetal.util.observable import TimeCounter
     from jmetal.util.observer import PlotFrontToFileObserver, WriteFrontToFileObserver
    @@ -356,34 +164,34 @@ 

    Example -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.gde3.DynamicGDE3(problem: jmetal.core.problem.DynamicProblem, population_size: int, cr: float, f: float, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion, k: float = 0.5, population_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.multiobjective.gde3.GDE3, jmetal.core.algorithm.DynamicAlgorithm

    -
    -
    -restart() → None[source]
    +

    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.gde3.DynamicGDE3(problem: ~jmetal.core.problem.DynamicProblem, population_size: int, cr: float, f: float, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion, k: float = 0.5, population_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: GDE3, DynamicAlgorithm

    +
    +
    +restart() None[source]
    -
    -
    -stopping_condition_is_met()[source]
    +
    +
    +stopping_condition_is_met()[source]

    The stopping condition is met or not.

    -
    -
    -update_progress()[source]
    +
    +
    +update_progress()[source]

    Update the progress after each iteration.

    -
    -
    + +
    @@ -400,7 +208,8 @@

    Navigation

  • modules |
  • - + +
    - - - - - - - + Preference point-based GDE3 — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -39,7 +39,8 @@

    Navigation

  • modules |
  • - + +
    @@ -50,7 +51,7 @@

    Navigation

    @@ -120,216 +121,15 @@

    Contents

    - - -
    -

    Preference point-based GDE3

    -
    -

    Example

    +
    +

    Preference point-based GDE3

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.gde3 import GDE3
    +
    +
    +

    API

    .. autoclass:: jmetal.algorithm.multiobjective.gde3.GDE3 :members: :undoc-members: - :show-inheritance:
    -
    + :show-inheritance: +
    @@ -400,7 +199,8 @@

    Navigation

  • modules |
  • - + +
    - - - - - - - + HYPE — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,16 @@

    Contents

    @@ -138,216 +148,15 @@

    Contents

    - - -
    -

    HYPE

    -
    -

    Example

    +
    +

    HYPE

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.hype import HYPE
    +
    from jmetal.algorithm.multiobjective.hype import HYPE
     from jmetal.core.solution import FloatSolution
     from jmetal.operator import SBXCrossover, PolynomialMutation
     from jmetal.problem import ZDT1
    @@ -378,8 +187,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.hype.HYPE(problem: jmetal.core.problem.Problem, reference_point: jmetal.core.solution.Solution, population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -evaluate(population: List[S])[source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.hype.HYPE(problem: ~jmetal.core.problem.Problem, reference_point: ~jmetal.core.solution.Solution, population_size: int, offspring_population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: GeneticAlgorithm[S, R]

    +
    +
    +evaluate(population: List[S])[source]

    Evaluates a solution list.

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → R[source]
    +
    +
    +get_name() str[source]
    -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[List[S]][source]
    +
    +
    +replacement(population: List[S], offspring_population: List[S]) List[List[S]][source]

    Replace least-fit population with new individuals.

    +
    +
    +result() R[source]
    +
    +
    -
    -
    + +
    @@ -463,9 +271,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + IBEA — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,17 @@

    Contents

    @@ -138,216 +149,15 @@

    Contents

    - - -
    -

    IBEA

    -
    -

    Example

    +
    +

    IBEA

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.ibea import IBEA
    +
    from jmetal.algorithm.multiobjective.ibea import IBEA
     from jmetal.operator import SBXCrossover, PolynomialMutation
     from jmetal.problem import ZDT1
     from jmetal.util.termination_criterion import StoppingByEvaluations
    @@ -376,8 +186,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.ibea.IBEA(problem: jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, kappa: float, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -compute_fitness_values(population: List[S], kappa: float) → List[S][source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.ibea.IBEA(problem: ~jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, kappa: float, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    +

    Bases: GeneticAlgorithm[S, R]

    +
    +
    +compute_fitness_values(population: List[S], kappa: float) List[S][source]
    -
    -
    -create_initial_solutions() → List[S][source]
    +
    +
    +create_initial_solutions() List[S][source]

    Creates the initial list of solutions of a metaheuristic.

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → R[source]
    +
    +
    +get_name() str[source]
    -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[List[S]][source]
    +
    +
    +replacement(population: List[S], offspring_population: List[S]) List[List[S]][source]

    Replace least-fit population with new individuals.

    +
    +
    +result() R[source]
    +
    +
    -
    -
    + +
    @@ -463,9 +272,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + MOCell — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,19 @@

    Contents

    @@ -138,216 +151,15 @@

    Contents

    - - -
    -

    MOCell

    -
    -

    Example

    +
    +

    MOCell

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.mocell import MOCell
    +
    from jmetal.algorithm.multiobjective.mocell import MOCell
     from jmetal.operator import SBXCrossover, PolynomialMutation
     from jmetal.problem import ZDT4
     from jmetal.util.archive import CrowdingDistanceArchive
    @@ -378,8 +190,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.mocell.MOCell(problem: jmetal.core.problem.Problem, population_size: int, neighborhood: jmetal.util.neighborhood.Neighborhood, archive: jmetal.util.archive.BoundedArchive, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → R[source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.mocell.MOCell(problem: ~jmetal.core.problem.Problem, population_size: int, neighborhood: ~jmetal.util.neighborhood.Neighborhood, archive: ~jmetal.util.archive.BoundedArchive, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, selection: ~jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: GeneticAlgorithm[S, R]

    +
    +
    +get_name() str[source]
    -
    -
    -init_progress() → None[source]
    +
    +
    +init_progress() None[source]

    Initialize the algorithm.

    -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[List[S]][source]
    +
    +
    +replacement(population: List[S], offspring_population: List[S]) List[List[S]][source]

    Replace least-fit population with new individuals.

    -
    -
    -reproduction(mating_population: List[S]) → List[S][source]
    +
    +
    +reproduction(mating_population: List[S]) List[S][source]

    Breed new individuals through crossover and mutation operations to give birth to offspring.

    -
    -
    -selection(population: List[S])[source]
    +
    +
    +result() R[source]
    +
    + +
    +
    +selection(population: List[S])[source]

    Select the best-fit individuals for reproduction (parents).

    -
    -
    -update_progress() → None[source]
    +
    +
    +update_progress() None[source]

    Update the progress after each iteration.

    -
    -
    + +
    @@ -478,9 +289,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + MOEA/D — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,21 @@

    Contents

    @@ -138,216 +153,15 @@

    Contents

    - - -
    -

    MOEA/D

    -
    -

    Example

    +
    +

    MOEA/D

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.moead import MOEAD
    +
    from jmetal.algorithm.multiobjective.moead import MOEAD
     from jmetal.operator import PolynomialMutation, DifferentialEvolutionCrossover
     from jmetal.problem import LZ09_F2
     from jmetal.util.aggregative_function import Tschebycheff
    @@ -380,8 +194,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.moead.MOEAD(problem: jmetal.core.problem.Problem, population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.operator.crossover.DifferentialEvolutionCrossover, aggregative_function: jmetal.util.aggregative_function.AggregativeFunction, neighbourhood_selection_probability: float, max_number_of_replaced_solutions: int, neighbor_size: int, weight_files_path: str, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -choose_neighbor_type()[source]
    -
    - -
    -
    -generate_permutation_of_neighbors(subproblem_id)[source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.moead.MOEAD(problem: ~jmetal.core.problem.Problem, population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.operator.crossover.DifferentialEvolutionCrossover, aggregation_function: ~jmetal.util.aggregation_function.AggregationFunction, neighbourhood_selection_probability: float, max_number_of_replaced_solutions: int, neighbor_size: int, weight_files_path: str, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~typing.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    +

    Bases: GeneticAlgorithm

    +
    +
    +choose_neighbor_type()[source]
    -
    -
    -get_name()[source]
    +
    +
    +generate_permutation_of_neighbors(subproblem_id)[source]
    -
    -
    -get_result()[source]
    +
    +
    +get_name()[source]
    -
    -
    -init_progress() → None[source]
    +
    +
    +init_progress() None[source]

    Initialize the algorithm.

    -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[S][source]
    +
    +
    +replacement(population: List[S], offspring_population: List[S]) List[S][source]

    Replace least-fit population with new individuals.

    -
    -
    -reproduction(mating_population: List[S]) → List[S][source]
    +
    +
    +reproduction(mating_population: List[S]) List[S][source]

    Breed new individuals through crossover and mutation operations to give birth to offspring.

    -
    -
    -selection(population: List[S])[source]
    +
    +
    +result()[source]
    +
    + +
    +
    +selection(population: List[S])[source]

    Select the best-fit individuals for reproduction (parents).

    -
    -
    -update_current_subproblem_neighborhood(new_solution, population)[source]
    +
    +
    +update_current_subproblem_neighborhood(new_solution, population)[source]
    -
    -
    + +
    @@ -492,9 +305,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + NSGA-II — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,15 @@

    Contents

    @@ -138,216 +147,15 @@

    Contents

    - - -
    -

    NSGA-II

    -
    -

    Example

    +
    +

    NSGA-II

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.nsgaii import NSGAII
    +
    from jmetal.algorithm.multiobjective.nsgaii import NSGAII
     from jmetal.operator import SBXCrossover, PolynomialMutation
     from jmetal.problem import ZDT1
     from jmetal.util.termination_criterion import StoppingByEvaluations
    @@ -375,8 +183,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.nsgaii.NSGAII(problem: jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → R[source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.nsgaii.NSGAII(problem: ~jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, selection: ~jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~typing.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: GeneticAlgorithm[S, R]

    +
    +
    +get_name() str[source]
    -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[List[S]][source]
    +
    +
    +replacement(population: List[S], offspring_population: List[S]) List[List[S]][source]

    This method joins the current and offspring populations to produce the population of the next generation by applying the ranking and crowding distance selection.

    -
    Parameters
    +
    Parameters:
    • population – Parent population.

    • offspring_population – Offspring population.

    -
    Returns
    +
    Returns:

    New population after ranking and crowding distance selection is applied.

    +
    +
    +result() R[source]
    +
    +
    -
    -
    + +
    @@ -466,9 +273,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + Distributed NSGA-II — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -39,7 +39,8 @@

    Navigation

  • modules |
  • - + +
    @@ -50,7 +51,7 @@

    Navigation

    @@ -84,7 +85,22 @@

    Contents

    @@ -120,216 +136,15 @@

    Contents

    - - -
    -

    Distributed NSGA-II

    -
    -

    Example

    +
    +

    Distributed NSGA-II

    +
    +

    Example

    [ ]:
     
    -
    -from math import sqrt
    +
    -
    -from dask.distributed import Client
    +
    -
    -from jmetal.lab.visualization.plotting import Plot
    +
    from jmetal.lab.visualization.plotting import Plot
     from jmetal.util.solution import get_non_dominated_solutions
     
     front = get_non_dominated_solutions(solutions)
    @@ -438,75 +251,75 @@ 

    Example -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.nsgaii.DistributedNSGAII(problem: jmetal.core.problem.Problem, population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, number_of_cores: int, client, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, dominance_comparator: jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.core.algorithm.Algorithm

    -
    -
    -create_initial_solutions() → List[S][source]
    +

    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.nsgaii.DistributedNSGAII(problem: ~jmetal.core.problem.Problem, population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, number_of_cores: int, client, selection: ~jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, dominance_comparator: ~jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: Algorithm[S, R]

    +
    +
    +create_initial_solutions() List[S][source]

    Creates the initial list of solutions of a metaheuristic.

    -
    -
    -evaluate(solutions: List[S]) → List[S][source]
    +
    +
    +evaluate(solutions: List[S]) List[S][source]

    Evaluates a solution list.

    -
    -
    -get_name() → str[source]
    +
    +
    +get_name() str[source]
    -
    -
    -get_observable_data() → dict[source]
    -

    Get observable data, with the information that will be send to all observers each time.

    +
    +
    +init_progress() None[source]
    +

    Initialize the algorithm.

    -
    -
    -get_result() → R[source]
    -
    - -
    -
    -init_progress() → None[source]
    -

    Initialize the algorithm.

    +
    +
    +observable_data() dict[source]
    +

    Get observable data, with the information that will be seng to all observers each time.

    -
    -
    -run()[source]
    +
    +
    +result() R[source]
    +
    + +
    +
    +run()[source]

    Execute the algorithm.

    -
    -
    -step() → None[source]
    +
    +
    +step() None[source]

    Performs one iteration/step of the algorithm’s loop.

    -
    -
    -stopping_condition_is_met() → bool[source]
    +
    +
    +stopping_condition_is_met() bool[source]

    The stopping condition is met or not.

    -
    -
    -update_progress()[source]
    +
    +
    +update_progress()[source]

    Update the progress after each iteration.

    -
    -
    + +
    @@ -523,7 +336,8 @@

    Navigation

  • modules |
  • - + +
    - - - - - - - + Dynamic NSGA-II — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -39,7 +39,8 @@

    Navigation

  • modules |
  • - + +
    @@ -50,7 +51,7 @@

    Navigation

    @@ -84,7 +85,15 @@

    Contents

    @@ -120,216 +129,15 @@

    Contents

    - - -
    -

    Dynamic NSGA-II

    -
    -

    Example

    +
    +

    Dynamic NSGA-II

    +
    +

    Example

    [ ]:
     
    -
    -from jmetal.algorithm.multiobjective.nsgaii import DynamicNSGAII
    +
    from jmetal.algorithm.multiobjective.nsgaii import DynamicNSGAII
     from jmetal.operator import PolynomialMutation, SBXCrossover
     from jmetal.problem.multiobjective.fda import FDA2
     from jmetal.util.observable import TimeCounter
    @@ -359,34 +167,34 @@ 

    Example -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.nsgaii.DynamicNSGAII(problem: jmetal.core.problem.DynamicProblem[~S][S], population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.multiobjective.nsgaii.NSGAII, jmetal.core.algorithm.DynamicAlgorithm

    -
    -
    -restart()[source]
    +

    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.nsgaii.DynamicNSGAII(problem: ~jmetal.core.problem.DynamicProblem[~jmetal.algorithm.multiobjective.nsgaii.S], population_size: int, offspring_population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, selection: ~jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~typing.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: NSGAII[S, R], DynamicAlgorithm

    +
    +
    +restart()[source]
    -
    -
    -stopping_condition_is_met()[source]
    +
    +
    +stopping_condition_is_met()[source]

    The stopping condition is met or not.

    -
    -
    -update_progress()[source]
    +
    +
    +update_progress()[source]

    Update the progress after each iteration.

    -
    -
    + +
    @@ -403,7 +211,8 @@

    Navigation

  • modules |
  • - + +
    - - - - - - - + Preference point-based NSGA-II — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -39,7 +39,8 @@

    Navigation

  • modules |
  • - + +
    @@ -50,7 +51,7 @@

    Navigation

    @@ -84,7 +85,15 @@

    Contents

    @@ -120,216 +129,15 @@

    Contents

    - - -
    -

    Preference point-based NSGA-II

    -
    -

    Example

    +
    +

    Preference point-based NSGA-II

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.nsgaii import NSGAII
    +
    from jmetal.algorithm.multiobjective.nsgaii import NSGAII
     from jmetal.operator import SBXCrossover, PolynomialMutation
     from jmetal.problem import ZDT2
     from jmetal.util.comparator import GDominanceComparator
    @@ -360,8 +168,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.nsgaii.DynamicNSGAII(problem: jmetal.core.problem.DynamicProblem[~S][S], population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.multiobjective.nsgaii.NSGAII, jmetal.core.algorithm.DynamicAlgorithm

    -
    -
    -restart()[source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.nsgaii.DynamicNSGAII(problem: ~jmetal.core.problem.DynamicProblem[~jmetal.algorithm.multiobjective.nsgaii.S], population_size: int, offspring_population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, selection: ~jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~typing.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: NSGAII[S, R], DynamicAlgorithm

    +
    +
    +restart()[source]
    -
    -
    -stopping_condition_is_met()[source]
    +
    +
    +stopping_condition_is_met()[source]

    The stopping condition is met or not.

    -
    -
    -update_progress()[source]
    +
    +
    +update_progress()[source]

    Update the progress after each iteration.

    -
    -
    + +
    @@ -422,7 +229,8 @@

    Navigation

  • modules |
  • - + +
    - - - - - - - + NSGA-III — jMetalPy 1.7.0 documentation + + + + + + + + + @@ -47,9 +46,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +60,7 @@

    Navigation

    @@ -97,7 +97,15 @@

    Contents

    - - - - - - - - - - - - - - - - - -
    - -
    - -
    -
    -
    - - - - -
    -
    -
    - - - -
    - - - -
    -

    NSGA-II

    -
    -

    Examples

    -
    -
    [2]:
    -
    -
    -
    -from jmetal.algorithm.multiobjective.nsgaii import NSGAII
    -from jmetal.operator import SBXCrossover, PolynomialMutation
    -from jmetal.problem import ZDT1
    -from jmetal.util.termination_criterion import StoppingByEvaluations
    -
    -problem = ZDT1()
    -
    -max_evaluations = 2500
    -algorithm = NSGAII(
    -    problem=problem,
    -    population_size=100,
    -    offspring_population_size=100,
    -    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    -    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    -    termination_criterion=StoppingByEvaluations(max=max_evaluations)
    -)
    -
    -algorithm.run()
    -front = algorithm.get_result()
    -
    -
    -
    -

    We can now vis

    -
    -
    -

    API

    -.. automodule:: jmetal.algorithm.multiobjective.nsgaii - :members: - :undoc-members: - :show-inheritance:
    -
    - - -
    - - -
    - -
    -
    -
    - - - - - - \ No newline at end of file diff --git a/docs/api/algorithm/multiobjective/eas/oldnsgaii.html b/docs/api/algorithm/multiobjective/eas/oldnsgaii.html deleted file mode 100644 index cf1fa25a..00000000 --- a/docs/api/algorithm/multiobjective/eas/oldnsgaii.html +++ /dev/null @@ -1,421 +0,0 @@ - - - - - - - - - - - - - - - - NSGA-II — jMetalPy 1.5.3 documentation - - - - - - - - - - - - - - - - - - - -
    - -
    - -
    -
    -
    - - - - -
    -
    -
    - -
    - -
    - -
    - -
    -

    NSGA-II

    -
    -

    Examples

    -
    -

    Standard

    -
    from jmetal.algorithm.multiobjective.nsgaii import NSGAII
    -from jmetal.operator import SBXCrossover, PolynomialMutation
    -from jmetal.problem import ZDT1
    -from jmetal.util.solution import read_solutions
    -from jmetal.util.termination_criterion import StoppingByEvaluations
    -
    -problem = ZDT1()
    -problem.reference_front = read_solutions(filename='resources/reference_front/ZDT1.pf')
    -
    -max_evaluations = 25000
    -algorithm = NSGAII(
    -    problem=problem,
    -    population_size=100,
    -    offspring_population_size=100,
    -    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    -    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    -    termination_criterion=StoppingByEvaluations(max=max_evaluations)
    -)
    -
    -algorithm.run()
    -front = algorithm.get_result()
    -
    -
    -
    -
    -

    Distributed

    -
    -

    Warning

    -

    This requires some extra dependencies

    -
    -
    from dask.distributed import Client
    -from distributed import LocalCluster
    -
    -from examples.multiobjective.parallel.zdt1_modified import ZDT1Modified
    -from jmetal.algorithm.multiobjective.nsgaii import DistributedNSGAII
    -from jmetal.operator import PolynomialMutation, SBXCrossover
    -from jmetal.util.termination_criterion import StoppingByEvaluations
    -
    -problem = ZDT1Modified()
    -
    -# setup Dask client
    -client = Client(LocalCluster(n_workers=24))
    -
    -ncores = sum(client.ncores().values())
    -print(f'{ncores} cores available')
    -
    -# creates the algorithm
    -max_evaluations = 25000
    -
    -algorithm = DistributedNSGAII(
    -    problem=problem,
    -    population_size=100,
    -    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    -    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    -    termination_criterion=StoppingByEvaluations(max=max_evaluations),
    -    number_of_cores=ncores,
    -    client=client
    -)
    -
    -algorithm.run()
    -front = algorithm.get_result()
    -
    -
    -
    -
    -

    Dynamic

    -
    from jmetal.algorithm.multiobjective.nsgaii import DynamicNSGAII
    -from jmetal.operator import PolynomialMutation, SBXCrossover
    -from jmetal.problem.multiobjective.fda import FDA2
    -from jmetal.util.observable import TimeCounter
    -from jmetal.util.observer import PlotFrontToFileObserver, WriteFrontToFileObserver
    -from jmetal.util.termination_criterion import StoppingByEvaluations
    -
    -problem = FDA2()
    -
    -time_counter = TimeCounter(delay=1)
    -time_counter.observable.register(problem)
    -time_counter.start()
    -
    -max_evaluations = 25000
    -algorithm = DynamicNSGAII(
    -    problem=problem,
    -    population_size=100,
    -    offspring_population_size=100,
    -    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    -    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    -    termination_criterion=StoppingByEvaluations(max=max_evaluations)
    -)
    -
    -algorithm.observable.register(observer=PlotFrontToFileObserver('front_vis'))
    -algorithm.observable.register(observer=WriteFrontToFileObserver('front_files'))
    -
    -algorithm.run()
    -
    -
    -
    -
    -

    Preference point-based (gNSGA-II)

    -
    from jmetal.algorithm.multiobjective.nsgaii import NSGAII
    -from jmetal.operator import SBXCrossover, PolynomialMutation
    -from jmetal.problem import ZDT2
    -from jmetal.util.solutions import read_solutions
    -from jmetal.util.solutions.comparator import GDominanceComparator
    -from jmetal.util.termination_criterion import StoppingByEvaluations
    -
    -problem = ZDT2()
    -problem.reference_front = read_solutions(filename='resources/reference_front/ZDT2.pf')
    -
    -reference_point = [0.2, 0.5]
    -
    -max_evaluations = 25000
    -algorithm = NSGAII(
    -    problem=problem,
    -    population_size=100,
    -    offspring_population_size=100,
    -    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    -    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    -    dominance_comparator=GDominanceComparator(reference_point),
    -    termination_criterion=StoppingByEvaluations(max=max_evaluations)
    -)
    -
    -algorithm.run()
    -front = algorithm.get_result()
    -
    -
    -
    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.nsgaii.DistributedNSGAII(problem: jmetal.core.problem.Problem, population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, number_of_cores: int, client: distributed.client.Client, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, dominance_comparator: jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.core.algorithm.Algorithm

    -
    -
    -create_initial_solutions() → List[S][source]
    -

    Creates the initial list of solutions of a metaheuristic.

    -
    - -
    -
    -evaluate(solutions: List[S]) → List[S][source]
    -

    Evaluates a solution list.

    -
    - -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_observable_data() → dict[source]
    -

    Get observable data, with the information that will be send to all observers each time.

    -
    - -
    -
    -get_result() → R[source]
    -
    - -
    -
    -init_progress() → None[source]
    -

    Initialize the algorithm.

    -
    - -
    -
    -run()[source]
    -

    Execute the algorithm.

    -
    - -
    -
    -step() → None[source]
    -

    Performs one iteration/step of the algorithm’s loop.

    -
    - -
    -
    -stopping_condition_is_met() → bool[source]
    -

    The stopping condition is met or not.

    -
    - -
    -
    -update_progress()[source]
    -

    Update the progress after each iteration.

    -
    - -
    - -
    -
    -class jmetal.algorithm.multiobjective.nsgaii.DynamicNSGAII(problem: jmetal.core.problem.DynamicProblem[~S][S], population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.DominanceComparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.multiobjective.nsgaii.NSGAII, jmetal.core.algorithm.DynamicAlgorithm

    -
    -
    -restart()[source]
    -
    - -
    -
    -stopping_condition_is_met()[source]
    -

    The stopping condition is met or not.

    -
    - -
    -
    -update_progress()[source]
    -

    Update the progress after each iteration.

    -
    - -
    - -
    -
    -class jmetal.algorithm.multiobjective.nsgaii.NSGAII(problem: jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, selection: jmetal.core.operator.Selection = <jmetal.operator.selection.BinaryTournamentSelection object>, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → R[source]
    -
    - -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[List[S]][source]
    -

    This method joins the current and offspring populations to produce the population of the next generation -by applying the ranking and crowding distance selection.

    -
    -
    Parameters
    -
      -
    • population – Parent population.

    • -
    • offspring_population – Offspring population.

    • -
    -
    -
    Returns
    -

    New population after ranking and crowding distance selection is applied.

    -
    -
    -
    - -
    - -
    -
    -jmetal.algorithm.multiobjective.nsgaii.R = ~R
    -
    - -
    -
    -jmetal.algorithm.multiobjective.nsgaii.reproduction(mating_population: List[S], problem, crossover_operator, mutation_operator) → S[source]
    -
    - -
    -
    - - -
    - -
    -
    -
    - - - - - - \ No newline at end of file diff --git a/docs/api/algorithm/multiobjective/eas/oldspea2.html b/docs/api/algorithm/multiobjective/eas/oldspea2.html deleted file mode 100644 index b3e789e0..00000000 --- a/docs/api/algorithm/multiobjective/eas/oldspea2.html +++ /dev/null @@ -1,251 +0,0 @@ - - - - - - - - - - - - - - - - SPEA2 — jMetalPy 1.5.3 documentation - - - - - - - - - - - - - - - - - - - -
    - -
    - -
    -
    -
    - - - - -
    -
    -
    - -
    - -
    - -
    - -
    -

    SPEA2

    -
    -

    Examples

    -
    -

    Standard

    -
    from jmetal.algorithm.multiobjective.spea2 import SPEA2
    -from jmetal.operator import SBXCrossover, PolynomialMutation
    -from jmetal.problem import ZDT1
    -from jmetal.util.solutions import read_solutions
    -from jmetal.util.termination_criterion import StoppingByEvaluations
    -
    -problem = ZDT1()
    -problem.reference_front = read_solutions(filename='resources/reference_front/ZDT1.pf')
    -
    -max_evaluations = 20000
    -algorithm = SPEA2(
    -    problem=problem,
    -    population_size=40,
    -    offspring_population_size=40,
    -    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    -    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    -    termination_criterion=StoppingByEvaluations(max=max_evaluations)
    -)
    -
    -algorithm.run()
    -front = algorithm.get_result()
    -
    -
    -
    -
    -

    Preference point-based (gSPEA2)

    -
    from jmetal.algorithm.multiobjective.spea2 import SPEA2
    -from jmetal.lab.visualization import Plot, InteractivePlot
    -from jmetal.operator import SBXCrossover, PolynomialMutation
    -from jmetal.problem import ZDT1
    -from jmetal.util.solutions import read_solutions
    -from jmetal.util.solutions.comparator import GDominanceComparator
    -from jmetal.util.termination_criterion import StoppingByEvaluations
    -
    -problem = ZDT1()
    -problem.reference_front = read_solutions(filename='resources/reference_front/ZDT1.pf')
    -
    -reference_point = [0.4, 0.6]
    -
    -max_evaluations = 25000
    -algorithm = SPEA2(
    -    problem=problem,
    -    population_size=40,
    -    offspring_population_size=40,
    -    mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20),
    -    crossover=SBXCrossover(probability=1.0, distribution_index=20),
    -    termination_criterion=StoppingByEvaluations(max=max_evaluations),
    -    dominance_comparator=GDominanceComparator(reference_point)
    -)
    -
    -algorithm.run()
    -front = algorithm.get_result()
    -
    -
    -
    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.spea2.SPEA2(problem: jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → R[source]
    -
    - -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[List[S]][source]
    -

    This method joins the current and offspring populations to produce the population of the next generation -by applying the ranking and crowding distance selection.

    -
    -
    Parameters
    -
      -
    • population – Parent population.

    • -
    • offspring_population – Offspring population.

    • -
    -
    -
    Returns
    -

    New population after ranking and crowding distance selection is applied.

    -
    -
    -
    - -
    - -
    -
    - - -
    - -
    -
    -
    - - - - - - \ No newline at end of file diff --git a/docs/api/algorithm/multiobjective/eas/spea2.html b/docs/api/algorithm/multiobjective/eas/spea2.html index 4a388cb7..995f9b60 100644 --- a/docs/api/algorithm/multiobjective/eas/spea2.html +++ b/docs/api/algorithm/multiobjective/eas/spea2.html @@ -1,9 +1,10 @@ - - + + + @@ -12,18 +13,17 @@ - SPEA2 — jMetalPy 1.5.3 documentation - - - - - - - - - - - + SPEA2 — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,15 @@

    Contents

    @@ -138,216 +147,15 @@

    Contents

    - - -
    -

    SPEA2

    -
    -

    Example

    +
    +

    SPEA2

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.spea2 import SPEA2
    +
    from jmetal.algorithm.multiobjective.spea2 import SPEA2
     from jmetal.operator import SBXCrossover, PolynomialMutation
     from jmetal.problem import ZDT1
     from jmetal.util.termination_criterion import StoppingByEvaluations
    @@ -375,8 +183,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.spea2.SPEA2(problem: jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: jmetal.core.operator.Mutation, crossover: jmetal.core.operator.Crossover, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    -

    Bases: jmetal.algorithm.singleobjective.genetic_algorithm.GeneticAlgorithm

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → R[source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.spea2.SPEA2(problem: ~jmetal.core.problem.Problem, population_size: int, offspring_population_size: int, mutation: ~jmetal.core.operator.Mutation, crossover: ~jmetal.core.operator.Crossover, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, population_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, population_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>, dominance_comparator: ~jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>)[source]
    +

    Bases: GeneticAlgorithm[S, R]

    +
    +
    +get_name() str[source]
    -
    -
    -replacement(population: List[S], offspring_population: List[S]) → List[List[S]][source]
    +
    +
    +replacement(population: List[S], offspring_population: List[S]) List[List[S]][source]

    This method joins the current and offspring populations to produce the population of the next generation by applying the ranking and crowding distance selection.

    -
    Parameters
    +
    Parameters:
    • population – Parent population.

    • offspring_population – Offspring population.

    -
    Returns
    +
    Returns:

    New population after ranking and crowding distance selection is applied.

    +
    +
    +result() R[source]
    +
    +
    -
    -
    + +
    @@ -466,9 +273,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + PSO Algorithms — jMetalPy 1.7.0 documentation + + + + + + + + + @@ -47,8 +46,9 @@

    Navigation

  • previous |
  • - - + + +
    @@ -59,7 +59,7 @@

    Navigation

    @@ -120,16 +120,16 @@

    Table Of Contents

    -
    -

    PSO Algorithms

    +
    +

    PSO Algorithms

    -

    Multi-objective particle swarm optimization algorithms:

    +

    Multi-objective particle swarm optimization algorithms:

    -
    +
    @@ -164,8 +164,9 @@

    Navigation

  • previous |
  • - - + + +
    - - - - - - - + OMOPSO — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,28 @@

    Contents

    @@ -138,216 +160,15 @@

    Contents

    - - -
    -

    OMOPSO

    -
    -

    Example

    +
    +

    OMOPSO

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.omopso import OMOPSO
    +
    from jmetal.algorithm.multiobjective.omopso import OMOPSO
     from jmetal.operator import UniformMutation
     from jmetal.operator.mutation import NonUniformMutation
     from jmetal.problem import ZDT1
    @@ -381,8 +202,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.omopso.OMOPSO(problem: jmetal.core.problem.FloatProblem, swarm_size: int, uniform_mutation: jmetal.operator.mutation.UniformMutation, non_uniform_mutation: jmetal.operator.mutation.NonUniformMutation, leaders: Optional[jmetal.util.archive.BoundedArchive], epsilon: float, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion, swarm_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    -

    Bases: jmetal.core.algorithm.ParticleSwarmOptimization

    -
    -
    -create_initial_solutions() → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.omopso.OMOPSO(problem: ~jmetal.core.problem.FloatProblem, swarm_size: int, uniform_mutation: ~jmetal.operator.mutation.UniformMutation, non_uniform_mutation: ~jmetal.operator.mutation.NonUniformMutation, leaders: ~jmetal.util.archive.BoundedArchive | None, epsilon: float, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion, swarm_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    +

    Bases: ParticleSwarmOptimization

    +
    +
    +create_initial_solutions() List[FloatSolution][source]

    Creates the initial list of solutions of a metaheuristic.

    -
    -
    -evaluate(solution_list: List[jmetal.core.solution.FloatSolution])[source]
    +
    +
    +evaluate(solution_list: List[FloatSolution])[source]

    Evaluates a solution list.

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +get_name() str[source]
    -
    -
    -init_progress() → None[source]
    +
    +
    +init_progress() None[source]

    Initialize the algorithm.

    -
    -
    -initialize_global_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +initialize_global_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -initialize_particle_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +initialize_particle_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -initialize_velocity(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +initialize_velocity(swarm: List[FloatSolution]) None[source]
    -
    -
    -perturbation(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +perturbation(swarm: List[FloatSolution]) None[source]
    -
    -
    -select_global_best() → jmetal.core.solution.FloatSolution[source]
    +
    +
    +result() List[FloatSolution][source]
    -
    -
    -stopping_condition_is_met() → bool[source]
    +
    +
    +select_global_best() FloatSolution[source]
    +
    + +
    +
    +stopping_condition_is_met() bool[source]

    The stopping condition is met or not.

    -
    -
    -update_global_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_global_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -update_particle_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_particle_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -update_position(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_position(swarm: List[FloatSolution]) None[source]
    -
    -
    -update_progress() → None[source]
    +
    +
    +update_progress() None[source]

    Update the progress after each iteration.

    -
    -
    -update_velocity(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_velocity(swarm: List[FloatSolution]) None[source]
    -
    -
    + +
    @@ -529,9 +349,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + SMPSO — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -47,9 +47,10 @@

    Navigation

  • previous |
  • - + - + +
    @@ -60,7 +61,7 @@

    Navigation

    @@ -98,7 +99,28 @@

    Contents

    @@ -138,216 +160,15 @@

    Contents

    - - -
    -

    SMPSO

    -
    -

    Example

    +
    +

    SMPSO

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.smpso import SMPSO
    +
    from jmetal.algorithm.multiobjective.smpso import SMPSO
     from jmetal.operator import PolynomialMutation
     from jmetal.problem import ZDT4
     from jmetal.util.archive import CrowdingDistanceArchive
    @@ -374,8 +195,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.smpso.SMPSO(problem: jmetal.core.problem.FloatProblem, swarm_size: int, mutation: jmetal.core.operator.Mutation, leaders: Optional[jmetal.util.archive.BoundedArchive], termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, swarm_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    -

    Bases: jmetal.core.algorithm.ParticleSwarmOptimization

    -
    -
    -create_initial_solutions() → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.smpso.SMPSO(problem: ~jmetal.core.problem.FloatProblem, swarm_size: int, mutation: ~jmetal.core.operator.Mutation, leaders: ~jmetal.util.archive.BoundedArchive | None, dominance_comparator: ~jmetal.util.comparator.Comparator = <jmetal.util.comparator.DominanceComparator object>, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, swarm_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    +

    Bases: ParticleSwarmOptimization

    +
    +
    +create_initial_solutions() List[FloatSolution][source]

    Creates the initial list of solutions of a metaheuristic.

    -
    -
    -evaluate(solution_list: List[jmetal.core.solution.FloatSolution])[source]
    +
    +
    +evaluate(solution_list: List[FloatSolution])[source]

    Evaluates a solution list.

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_result() → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +get_name() str[source]
    -
    -
    -init_progress() → None[source]
    +
    +
    +init_progress() None[source]

    Initialize the algorithm.

    -
    -
    -initialize_global_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +initialize_global_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -initialize_particle_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +initialize_particle_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -initialize_velocity(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +initialize_velocity(swarm: List[FloatSolution]) None[source]
    -
    -
    -perturbation(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +perturbation(swarm: List[FloatSolution]) None[source]
    -
    -
    -select_global_best() → jmetal.core.solution.FloatSolution[source]
    +
    +
    +result() List[FloatSolution][source]
    -
    -
    -stopping_condition_is_met() → bool[source]
    +
    +
    +select_global_best() FloatSolution[source]
    +
    + +
    +
    +stopping_condition_is_met() bool[source]

    The stopping condition is met or not.

    -
    -
    -update_global_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_global_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -update_particle_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_particle_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -update_position(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_position(swarm: List[FloatSolution]) None[source]
    -
    -
    -update_progress() → None[source]
    +
    +
    +update_progress() None[source]

    Update the progress after each iteration.

    -
    -
    -update_velocity(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +update_velocity(swarm: List[FloatSolution]) None[source]
    -
    -
    + +
    @@ -522,9 +342,10 @@

    Navigation

  • previous |
  • - + - + +
    - - - - - - - + Dynamic SMPSO — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -39,7 +39,8 @@

    Navigation

  • modules |
  • - + +
    @@ -50,7 +51,7 @@

    Navigation

    @@ -84,7 +85,15 @@

    Contents

    @@ -120,216 +129,15 @@

    Contents

    - - -
    -

    Dynamic SMPSO

    -
    -

    Example

    +
    +

    Dynamic SMPSO

    +
    +

    Example

    [ ]:
     
    -
    -from jmetal.algorithm.multiobjective.smpso import DynamicSMPSO
    +
    from jmetal.algorithm.multiobjective.smpso import DynamicSMPSO
     from jmetal.operator import PolynomialMutation
     from jmetal.problem.multiobjective.fda import FDA2
     from jmetal.util.archive import CrowdingDistanceArchive
    @@ -359,34 +167,34 @@ 

    Example -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.smpso.DynamicSMPSO(problem: jmetal.core.problem.DynamicProblem[jmetal.core.solution.FloatSolution][jmetal.core.solution.FloatSolution], swarm_size: int, mutation: jmetal.core.operator.Mutation, leaders: jmetal.util.archive.BoundedArchive, termination_criterion: jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, swarm_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    -

    Bases: jmetal.algorithm.multiobjective.smpso.SMPSO, jmetal.core.algorithm.DynamicAlgorithm

    -
    -
    -restart() → None[source]
    +

    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.smpso.DynamicSMPSO(problem: ~jmetal.core.problem.DynamicProblem[~jmetal.core.solution.FloatSolution], swarm_size: int, mutation: ~jmetal.core.operator.Mutation, leaders: ~jmetal.util.archive.BoundedArchive, termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion = <jmetal.util.termination_criterion.StoppingByEvaluations object>, swarm_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    +

    Bases: SMPSO, DynamicAlgorithm

    +
    +
    +restart() None[source]
    -
    -
    -stopping_condition_is_met()[source]
    +
    +
    +stopping_condition_is_met()[source]

    The stopping condition is met or not.

    -
    -
    -update_progress()[source]
    +
    +
    +update_progress()[source]

    Update the progress after each iteration.

    -
    -
    + +
    @@ -403,7 +211,8 @@

    Navigation

  • modules |
  • - + +
    - - - - - - - + SMPSO/RP — jMetalPy 1.7.0 documentation + + + + + + + + + + @@ -39,7 +39,8 @@

    Navigation

  • modules |
  • - + +
    @@ -50,7 +51,7 @@

    Navigation

    @@ -84,7 +85,21 @@

    Contents

    @@ -120,216 +135,15 @@

    Contents

    - - -
    -

    SMPSO/RP

    -
    -

    Example

    +
    +

    SMPSO/RP

    +
    +

    Example

    [1]:
     
    -
    -from jmetal.algorithm.multiobjective.smpso import SMPSORP
    +
    from jmetal.algorithm.multiobjective.smpso import SMPSORP
     from jmetal.operator import PolynomialMutation
     from jmetal.problem import ZDT4
     from jmetal.util.archive import CrowdingDistanceArchiveWithReferencePoint
    @@ -375,8 +189,7 @@ 

    Example
    [3]:
     

    -
    -
    -

    API

    -
    -
    -class jmetal.algorithm.multiobjective.smpso.SMPSORP(problem: jmetal.core.problem.FloatProblem, swarm_size: int, mutation: jmetal.core.operator.Mutation, reference_points: List[List[float]], leaders: List[jmetal.util.archive.ArchiveWithReferencePoint], termination_criterion: jmetal.util.termination_criterion.TerminationCriterion, swarm_generator: jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    -

    Bases: jmetal.algorithm.multiobjective.smpso.SMPSO

    -
    -
    -get_name() → str[source]
    -
    - -
    -
    -get_reference_point()[source]
    +
    +
    +

    API

    +
    +
    +class jmetal.algorithm.multiobjective.smpso.SMPSORP(problem: ~jmetal.core.problem.FloatProblem, swarm_size: int, mutation: ~jmetal.core.operator.Mutation, reference_points: ~typing.List[~typing.List[float]], leaders: ~typing.List[~jmetal.util.archive.ArchiveWithReferencePoint], termination_criterion: ~jmetal.util.termination_criterion.TerminationCriterion, swarm_generator: ~jmetal.util.generator.Generator = <jmetal.util.generator.RandomGenerator object>, swarm_evaluator: ~jmetal.util.evaluator.Evaluator = <jmetal.util.evaluator.SequentialEvaluator object>)[source]
    +

    Bases: SMPSO

    +
    +
    +get_name() str[source]
    -
    -
    -get_result() → List[jmetal.core.solution.FloatSolution][source]
    +
    +
    +get_reference_point()[source]
    -
    -
    -init_progress() → None[source]
    +
    +
    +init_progress() None[source]

    Initialize the algorithm.

    -
    -
    -initialize_global_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +initialize_global_best(swarm: List[FloatSolution]) None[source]
    -
    -
    -select_global_best() → jmetal.core.solution.FloatSolution[source]
    +
    +
    +result() List[FloatSolution][source]
    -
    -
    -update_global_best(swarm: List[jmetal.core.solution.FloatSolution]) → None[source]
    +
    +
    +select_global_best() FloatSolution[source]
    -
    -
    -update_progress() → None[source]
    +
    +
    +update_global_best(swarm: List[FloatSolution]) None[source]
    +
    + +
    +
    +update_progress() None[source]

    Update the progress after each iteration.

    -
    -
    -update_reference_point(new_reference_points: list)[source]
    +
    +
    +update_reference_point(new_reference_points: list)[source]
    -
    -
    + +
    @@ -467,7 +280,8 @@

    Navigation

  • modules |
  • - + +
    - - - - - - - + Evolution Strategy — jMetalPy 1.7.0 documentation + + + + + + + @@ -47,8 +44,9 @@

    Navigation

  • previous |
  • - - + + +
    @@ -59,7 +57,7 @@

    Navigation

    @@ -92,6 +90,30 @@

    Table Of Contents

    +