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 @@ -
-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]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 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 |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.gde3
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.hype — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.hype
@@ -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)
-
+
+
+
+
@@ -210,8 +224,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.hype
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.ibea — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.ibea
@@ -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
-
+
+
+
+
@@ -231,8 +253,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.ibea
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.mocell — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.mocell
@@ -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
-
+
+
+
+
@@ -265,8 +286,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.mocell
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.moead — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.moead
@@ -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
-
-
+
+
+
+
+
+
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 |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.moead
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.nsgaii — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.nsgaii
@@ -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]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]
+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 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 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 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()
-
+
+
+
+
def reproduction(mating_population: List[S], problem, crossover_operator, mutation_operator) -> S:
@@ -438,8 +501,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.nsgaii
-
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.nsgaiii — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -40,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.nsgaiii
@@ -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)
-
+
+
+
+
@@ -487,8 +497,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.nsgaiii
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.omopso — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.omopso
@@ -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 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)
-
+
+
+
+
@@ -345,8 +370,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.omopso
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.smpso — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.smpso
@@ -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 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]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_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
-
+
+
+
+
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 |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.smpso
-
-
-
-
-
-
-
+ jmetal.algorithm.multiobjective.spea2 — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.spea2
@@ -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
-
+
+
+
+
@@ -215,8 +226,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.multiobjective.spea2
-
-
-
-
-
-
-
+ jmetal.algorithm.singleobjective.evolution_strategy — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.evolution_strategy
@@ -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 selection(self, population: List[S]) -> List[S]:
+
+
-[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
-
+
+
+
+
@@ -218,8 +240,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.evolution_strategy
-
-
-
-
-
-
-
+ jmetal.algorithm.singleobjective.genetic_algorithm — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.genetic_algorithm
@@ -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 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]
-
+
+
+
+
@@ -232,8 +263,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.genetic_algorithm
-
-
-
-
-
-
-
+ jmetal.algorithm.singleobjective.local_search — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.local_search
@@ -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 init_progress(self) -> None:
+
+
-[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,
+ }
+
-
+
+
+
+
@@ -208,8 +240,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.local_search
-
-
-
-
-
-
-
+ jmetal.algorithm.singleobjective.simulated_annealing — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.simulated_annealing
@@ -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 init_progress(self) -> None:
+
+
-[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,
+ }
+
-
+
+
+
+
@@ -219,8 +256,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.algorithm.singleobjective.simulated_annealing
-
-
-
-
-
-
-
+ jmetal.core.observer — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.core.observer
@@ -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 Observable(ABC):
-[docs] @abstractmethod
+
@@ -164,8 +177,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.core.observer
-
-
-
-
-
-
-
+ jmetal.core.problem — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.core.problem
@@ -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 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]class DynamicProblem(Problem[S], Observer, ABC):
-[docs] @abstractmethod
+
+
+
-[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]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 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 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 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)
-
+
+
+
+
@@ -306,8 +418,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.core.problem
-
-
-
-
-
-
-
+ jmetal.lab.experiment — jMetalPy 1.7.0 documentation
+
+
+
+
+
+
+
@@ -39,8 +35,9 @@ Navigation
modules |
- jMetalPy 1.5.3 documentation »
- Module code »
+ jMetalPy 1.7.0 documentation »
+ Module code »
+ jmetal.lab.experiment
@@ -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:
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