### Dynamic NSGA-II Example Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/nsgaii_dynamic.html A practical example demonstrating how to use the DynamicNSGAII algorithm with FDA2 problem, including observer setup and algorithm execution. ```python from jmetal.algorithm.multiobjective.nsgaii import DynamicNSGAII from jmetal.operator.crossover import SBXCrossover from jmetal.operator.mutation import PolynomialMutation from jmetal.problem.multiobjective.fda import FDA2 from jmetal.util.observable import TimeCounter from jmetal.util.observer import PlotFrontToFileObserver, WriteFrontToFileObserver from jmetal.util.termination_criterion import StoppingByEvaluations problem = FDA2() time_counter = TimeCounter(delay=1) time_counter.observable.register(problem) time_counter.start() max_evaluations = 25000 algorithm = DynamicNSGAII( problem=problem, population_size=100, offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.observable.register(observer=PlotFrontToFileObserver('front_plot')) algorithm.observable.register(observer=WriteFrontToFileObserver('front_files')) algorithm.run() ``` -------------------------------- ### Install jMetalPy with specific options Source: https://jmetal.github.io/jMetalPy/getting-started.html Alternative installation commands for specific dependency sets. ```bash $ pip install "jmetalpy[core]" # Core components only $ pip install "jmetalpy[docs]" # Documentation building $ pip install "jmetalpy[distributed]" # Parallel computing $ pip install "jmetalpy[complete]" # All dependencies ``` -------------------------------- ### Install jMetalPy from source Source: https://jmetal.github.io/jMetalPy/getting-started.html Commands to clone the repository and install the package from source code. ```bash $ git clone https://github.com/jMetal/jMetalPy.git $ python setup.py install ``` -------------------------------- ### ProgressBar Output Example Source: https://jmetal.github.io/jMetalPy/tutorials/observer.html Example of the console output generated by the ProgressBarObserver. ```text $ Progress: 50%|##### | 12500/25000 [13:59<14:12, 14.66it/s] ``` -------------------------------- ### Quick Example of NSGA-II Algorithm Source: https://jmetal.github.io/jMetalPy/index.html This snippet demonstrates how to initialize and run the NSGA-II algorithm with the ZDT1 problem. Ensure jmetalpy is installed and necessary imports are available. ```python from jmetal.algorithm.multiobjective.nsgaii import NSGAII from jmetal.problem import ZDT1 problem = ZDT1() algorithm = NSGAII(problem=problem, population_size=100) algorithm.run() solutions = algorithm.get_result() ``` -------------------------------- ### OMOPSO Usage Example Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/psos/omopso.html Example demonstrating how to use the OMOPSO algorithm with ZDT1 problem. ```APIDOC ## Example Usage of OMOPSO This example shows how to instantiate and run the OMOPSO algorithm for the ZDT1 problem. ### Setup ```python from jmetal.algorithm.multiobjective.omopso import OMOPSO from jmetal.operator.mutation import UniformMutation from jmetal.operator.mutation import NonUniformMutation from jmetal.problem import ZDT1 from jmetal.util.archive import CrowdingDistanceArchive from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT1() mutation_probability = 1.0 / problem.number_of_variables max_evaluations = 25000 swarm_size = 100 algorithm = OMOPSO( problem=problem, swarm_size=swarm_size, epsilon=0.0075, uniform_mutation=UniformMutation(probability=mutation_probability, perturbation=0.5), non_uniform_mutation=NonUniformMutation(mutation_probability, perturbation=0.5, max_iterations=int(max_evaluations / swarm_size)), leaders=CrowdingDistanceArchive(100), termination_criterion=StoppingByEvaluations(max=max_evaluations) ) ``` ### Running the Algorithm ```python algorithm.run() solutions = algorithm.get_result() ``` ### Visualizing Results ```python from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='OMOPSO-ZDT1') ``` ``` -------------------------------- ### NSGA-II Example Usage Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/nsgaii.html Example of how to instantiate and run the NSGA-II algorithm with ZDT1 problem. ```APIDOC ## Example: Running NSGA-II ### Description This example demonstrates how to configure and execute the NSGA-II algorithm using the ZDT1 problem, and then visualize the resulting Pareto front approximation. ### Method N/A (Script execution) ### Endpoint N/A ### Code Example ```python from jmetal.algorithm.multiobjective.nsgaii import NSGAII from jmetal.operator.crossover import SBXCrossover from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT1 from jmetal.util.termination_criterion import StoppingByEvaluations from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions # Problem definition problem = ZDT1() # Algorithm configuration max_evaluations = 25000 algorithm = NSGAII( problem=problem, population_size=100, offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations(max=max_evaluations) ) # Run the algorithm algorithm.run() solutions = algorithm.get_result() # Visualize the Pareto front approximation front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='NSGAII-ZDT1') ``` ### Response Example (Execution of the script will generate a plot visualizing the Pareto front approximation. No direct API response is applicable here.) ``` -------------------------------- ### SMPSO/RP Example Usage Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/psos/smpso_preference.html Example demonstrating how to use the SMPSO/RP algorithm with ZDT4 problem and visualization. ```APIDOC ## SMPSO/RP Example This example demonstrates the usage of the SMPSO/RP algorithm for solving the ZDT4 problem and visualizing the Pareto front approximation. ### Setup ```python from jmetal.algorithm.multiobjective.smpso import SMPSORP from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT4 from jmetal.util.archive import CrowdingDistanceArchiveWithReferencePoint from jmetal.util.termination_criterion import StoppingByEvaluations from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions problem = ZDT4() swarm_size = 100 reference_point = [[0.1, 0.8],[0.6, 0.1]] archives_with_reference_points = [] for point in reference_point: archives_with_reference_points.append( CrowdingDistanceArchiveWithReferencePoint(int(swarm_size / len(reference_point)), point) ) max_evaluations = 50000 algorithm = SMPSORP( problem=problem, swarm_size=swarm_size, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), reference_points=reference_point, leaders=archives_with_reference_points, termination_criterion=StoppingByEvaluations(max=max_evaluations) ) ``` ### Execution ```python algorithm.run() solutions = algorithm.get_result() ``` ### Visualization ```python front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y'], reference_point=reference_point) plot_front.plot(front, label='SMPSORP-ZDT4') ``` ``` -------------------------------- ### IBEA Algorithm Example Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/ibea.html Example of how to use the IBEA algorithm with ZDT1 problem, SBXCrossover, PolynomialMutation, and plotting the results. ```APIDOC ## Example Usage of IBEA ### Description This example demonstrates how to instantiate and run the IBEA algorithm for a multi-objective optimization problem (ZDT1), and then visualize the obtained Pareto front approximation. ### Code ```python from jmetal.algorithm.multiobjective.ibea import IBEA from jmetal.operator.crossover import SBXCrossover from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT1 from jmetal.util.termination_criterion import StoppingByEvaluations from jmetal.lab.visualization.plotting import Plot # 1. Define the problem problem = ZDT1() # 2. Set termination criterion max_evaluations = 25000 termination_criterion = StoppingByEvaluations(max_evaluations) # 3. Instantiate the IBEA algorithm algorithm = IBEA( problem=problem, kappa=1., population_size=100, offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=termination_criterion ) # 4. Run the algorithm algorithm.run() front = algorithm.get_result() # 5. Visualize the results plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='IBEA-ZDT1') ``` ### Explanation - The code first imports necessary classes from `jmetalpy`. - It defines the `ZDT1` problem. - A `StoppingByEvaluations` termination criterion is set. - The `IBEA` algorithm is instantiated with specified parameters, including population size, mutation, and crossover operators. - The `run()` method executes the optimization process. - `get_result()` retrieves the approximated Pareto front. - Finally, a `Plot` object is used to visualize the obtained front. ``` -------------------------------- ### SPEA2 Usage Example Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/spea2.html Example demonstrating how to use the SPEA2 algorithm with ZDT1 problem. ```APIDOC ## Example Usage of SPEA2 ### Description This example shows how to initialize and run the SPEA2 algorithm to solve the ZDT1 multi-objective optimization problem. ### Code ```python from jmetal.algorithm.multiobjective.spea2 import SPEA2 from jmetal.operator.crossover import SBXCrossover from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT1 from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT1() max_evaluations = 20000 algorithm = SPEA2( problem=problem, population_size=40, offspring_population_size=40, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.run() solutions = algorithm.get_result() # To visualize the Pareto front approximation: from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='SPEA2-ZDT1') ``` ``` -------------------------------- ### GDE3 Algorithm Example Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/gde3.html Example demonstrating how to use the GDE3 algorithm with the ZDT1 problem and visualize the results. ```APIDOC ## Example Usage of GDE3 This example shows how to instantiate and run the GDE3 algorithm for the ZDT1 problem and then visualize the obtained Pareto front approximation. ### Initialization ```python from jmetal.algorithm.multiobjective.gde3 import GDE3 from jmetal.problem import ZDT1 from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT1() max_evaluations = 25000 algorithm = GDE3( problem=problem, population_size=100, cr=0.5, f=0.5, termination_criterion=StoppingByEvaluations(max_evaluations) ) ``` ### Running the Algorithm ```python algorithm.run() solutions = algorithm.get_result() ``` ### Visualization ```python from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='GDE3-ZDT1') ``` ``` -------------------------------- ### CLI Output Formats Source: https://jmetal.github.io/jMetalPy/tutorials/quality_indicators_cli.html Examples of the default text output and the JSON output format. ```text Result (epsilon): 0.1 Result (igd): 0.1414213562373095 Result (igdplus): 0.1 Result (hv): 0.84 Result (nhv): -0.037037037037037 ``` ```json { "epsilon": 0.1, "igd": 0.1414213562373095, "igdplus": 0.1, "hv": 0.84, "nhv": -0.037037037037037 } ``` -------------------------------- ### Install jMetalPy via pip Source: https://jmetal.github.io/jMetalPy/getting-started.html Standard installation command for the jMetalPy package. ```bash $ pip install jmetalpy # or "jmetalpy[distributed]" ``` -------------------------------- ### Preference Point-Based NSGA-II Example Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/nsgaii_preference.html Example demonstrating how to use the preference point-based NSGA-II algorithm with ZDT2 problem and visualization. ```APIDOC ## Preference Point-Based NSGA-II Example ### Description This example shows how to configure and run the NSGAII algorithm with a reference point for preference-based multi-objective optimization, followed by visualizing the obtained Pareto front approximation. ### Method ```python from jmetal.algorithm.multiobjective.nsgaii import NSGAII from jmetal.operator.crossover import SBXCrossover from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT2 from jmetal.util.comparator import GDominanceComparator from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT2() max_evaluations = 25000 reference_point = [0.2, 0.5] algorithm = NSGAII( problem=problem, population_size=100, offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), dominance_comparator=GDominanceComparator(reference_point), termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.run() solutions = algorithm.get_result() from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y'], reference_point=reference_point) plot_front.plot(front, label='gNSGAII-ZDT1') ``` ### Visualization ```python from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y'], reference_point=reference_point) plot_front.plot(front, label='gNSGAII-ZDT1') ``` ``` -------------------------------- ### Run NSGA-II algorithm Source: https://jmetal.github.io/jMetalPy/getting-started.html A basic example demonstrating how to configure and execute the NSGA-II algorithm on the ZDT1 problem. ```python from jmetal.algorithm.multiobjective.nsgaii import NSGAII from jmetal.operator import SBXCrossover, PolynomialMutation from jmetal.operator.selection import BinaryTournamentSelection from jmetal.problem import ZDT1 from jmetal.util.termination_criterion import StoppingByEvaluations # Define the problem problem = ZDT1() # Configure the algorithm algorithm = NSGAII( problem=problem, population_size=100, offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), selection=BinaryTournamentSelection(), termination_criterion=StoppingByEvaluations(max_evaluations=25000) ) # Run the algorithm algorithm.run() solutions = algorithm.get_result() # Print results print(f"Found {len(solutions)} solutions") ``` -------------------------------- ### Integrate DistanceBasedArchive with Algorithms Source: https://jmetal.github.io/jMetalPy/advanced-topics/distance-based-archive.html Conceptual example of initializing an algorithm with a custom archive. ```python from jmetal.algorithm.multiobjective.nsgaii import NSGAII from jmetal.util.archive import DistanceBasedArchive from jmetal.problem import ZDT1 # Create algorithm with custom archive problem = ZDT1() archive = DistanceBasedArchive(maximum_size=100) # Note: This is conceptual - actual integration depends on algorithm design # Some algorithms may need modification to accept custom archives ``` -------------------------------- ### Compute Quality Indicators Source: https://jmetal.github.io/jMetalPy/tutorials/quality_indicators_cli.html Examples of computing specific indicators or all indicators with custom configurations. ```bash python -m jmetal.util.quality_indicator_cli front.csv reference.csv igd ``` ```bash python -m jmetal.util.quality_indicator_cli front.csv reference.csv all --ref-point 2.0,2.0 ``` ```bash python -m jmetal.util.quality_indicator_cli front.csv reference.csv all --normalize --format json ``` ```bash python -m jmetal.util.quality_indicator_cli front.csv reference.csv epsilon ``` -------------------------------- ### DistributedNSGAII Initialization and Execution Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/nsgaii.html Setup and execution logic for DistributedNSGAII, utilizing Dask for parallel evaluation. ```python 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(), CrowdingDistanceDensityEstimator.get_comparator()]) ), termination_criterion: TerminationCriterion = store.default_termination_criteria, dominance_comparator: DominanceComparator = DominanceComparator(), ): super(DistributedNSGAII, self).__init__() self.problem = problem self.population_size = population_size self.mutation_operator = mutation self.crossover_operator = crossover self.selection_operator = selection self.dominance_comparator = dominance_comparator self.termination_criterion = termination_criterion self.observable.register(termination_criterion) self.number_of_cores = number_of_cores self.client = client [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]: return self.client.map(self.problem.evaluate, solutions) [docs] def stopping_condition_is_met(self) -> bool: return self.termination_criterion.is_met [docs] def observable_data(self) -> dict: ctime = time.time() - self.start_computing_time return { "PROBLEM": self.problem, "EVALUATIONS": self.evaluations, "SOLUTIONS": self.result(), "COMPUTING_TIME": ctime, } [docs] def init_progress(self) -> None: self.evaluations = self.number_of_cores observable_data = self.observable_data() self.observable.notify_all(**observable_data) [docs] def step(self) -> None: pass [docs] def update_progress(self): observable_data = self.observable_data() self.observable.notify_all(**observable_data) [docs] def run(self): """Execute the algorithm.""" self.start_computing_time = time.time() create_solution = dask.delayed(self.problem.create_solution) evaluate_solution = dask.delayed(self.problem.evaluate) task_pool = as_completed([], with_results=True) for _ in range(self.number_of_cores): new_solution = create_solution() new_evaluated_solution = evaluate_solution(new_solution) future = self.client.compute(new_evaluated_solution) task_pool.add(future) batches = task_pool.batches() auxiliar_population = [] while len(auxiliar_population) < self.population_size: batch = next(batches) for _, received_solution in batch: auxiliar_population.append(received_solution) if len(auxiliar_population) < self.population_size: break # submit as many new tasks as we collected for _ in batch: ``` -------------------------------- ### MOEA/D Algorithm Usage Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/moead.html Example demonstrating how to use the MOEA/D algorithm for multi-objective optimization. ```APIDOC ## MOEA/D Algorithm Usage Example ### Description This example shows how to instantiate and run the MOEA/D algorithm with a specific problem, operators, and termination criterion. ### Method ```python from jmetal.algorithm.multiobjective.moead import MOEAD from jmetal.operator.mutation import PolynomialMutation from jmetal.operator.crossover import DifferentialEvolutionCrossover from jmetal.problem import LZ09_F2 from jmetal.util.aggregative_function import Tschebycheff from jmetal.util.termination_criterion import StoppingByEvaluations problem = LZ09_F2() max_evaluations = 150000 algorithm = MOEAD( problem=problem, population_size=300, crossover=DifferentialEvolutionCrossover(CR=1.0, F=0.5, K=0.5), mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), aggregative_function=Tschebycheff(dimension=problem.number_of_objectives), neighbor_size=20, neighbourhood_selection_probability=0.9, max_number_of_replaced_solutions=2, weight_files_path='resources/MOEAD_weights', termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.run() solutions = algorithm.get_result() ``` ### Visualization Example ### Description This example shows how to visualize the Pareto front approximation obtained from the MOEA/D algorithm. ### Method ```python from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='MOEAD-LZ09_F2') ``` ``` -------------------------------- ### Initialize Progress Method Source: https://jmetal.github.io/jMetalPy/api/algorithm/singleobjective/local.search.html Initializes the algorithm's progress tracking. This should be called before starting the algorithm's execution. ```python init_progress() → None[source]¶ Initialize the algorithm. ``` -------------------------------- ### Initialize algorithm progress Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/omopso.html Sets up initial evaluations, density estimation, and velocity/best solution states. ```python def init_progress(self) -> None: self.evaluations = self.swarm_size self.leaders.compute_density_estimator() self.initialize_velocity(self.solutions) self.initialize_particle_best(self.solutions) self.initialize_global_best(self.solutions) ``` -------------------------------- ### Run MOEA/D Algorithm Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/moead.html Example demonstrating how to instantiate and run the MOEA/D algorithm with specified problem, operators, and termination criterion. Ensure the 'resources/MOEAD_weights' directory exists. ```python from jmetal.algorithm.multiobjective.moead import MOEAD from jmetal.operator.mutation import PolynomialMutation from jmetal.operator.crossover import DifferentialEvolutionCrossover from jmetal.problem import LZ09_F2 from jmetal.util.aggregative_function import Tschebycheff from jmetal.util.termination_criterion import StoppingByEvaluations problem = LZ09_F2() max_evaluations = 150000 algorithm = MOEAD( problem=problem, population_size=300, crossover=DifferentialEvolutionCrossover(CR=1.0, F=0.5, K=0.5), mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), aggregative_function=Tschebycheff(dimension=problem.number_of_objectives), neighbor_size=20, neighbourhood_selection_probability=0.9, max_number_of_replaced_solutions=2, weight_files_path='resources/MOEAD_weights', termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.run() solutions = algorithm.get_result() ``` -------------------------------- ### Initialize and run Dynamic GDE3 Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/gde3_dynamic.html Demonstrates how to configure and execute the Dynamic GDE3 algorithm with a dynamic problem, time-based updates, and observers for tracking progress. ```python from jmetal.algorithm.multiobjective.gde3 import DynamicGDE3 from jmetal.problem.multiobjective.fda import FDA2 from jmetal.util.observable import TimeCounter from jmetal.util.observer import PlotFrontToFileObserver, WriteFrontToFileObserver from jmetal.util.termination_criterion import StoppingByEvaluations problem = FDA2() time_counter = TimeCounter(delay=1) time_counter.observable.register(problem) time_counter.start() algorithm = DynamicGDE3( problem=problem, population_size=100, cr=0.5, f=0.5, termination_criterion=StoppingByEvaluations(max=500) ) algorithm.observable.register(observer=PlotFrontToFileObserver('front_plot')) algorithm.observable.register(observer=WriteFrontToFileObserver('front_files')) algorithm.run() ``` -------------------------------- ### Configure and run SMPSO/RP Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/psos/smpso_preference.html Initializes the SMPSO/RP algorithm with specific reference points and archives, then executes the optimization process. ```python from jmetal.algorithm.multiobjective.smpso import SMPSORP from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT4 from jmetal.util.archive import CrowdingDistanceArchiveWithReferencePoint from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT4() swarm_size = 100 reference_point = [[0.1, 0.8],[0.6, 0.1]] archives_with_reference_points = [] for point in reference_point: archives_with_reference_points.append( CrowdingDistanceArchiveWithReferencePoint(int(swarm_size / len(reference_point)), point) ) max_evaluations = 50000 algorithm = SMPSORP( problem=problem, swarm_size=swarm_size, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), reference_points=reference_point, leaders=archives_with_reference_points, termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.run() solutions = algorithm.get_result() ``` -------------------------------- ### Generate Sample Data Files Source: https://jmetal.github.io/jMetalPy/tutorials/quality_indicators_cli.html Use numpy to create sample solution and reference fronts for quality indicator computation. Save these fronts as CSV files. ```python import numpy as np # Create a sample solution front front = np.array([[0.1, 0.9], [0.3, 0.7], [0.5, 0.5], [0.7, 0.3], [0.9, 0.1]]) np.savetxt('my_front.csv', front, delimiter=',') # Create a reference front (e.g., true Pareto front) reference = np.array([[0.0, 1.0], [0.2, 0.8], [0.4, 0.6], [0.6, 0.4], [0.8, 0.2], [1.0, 0.0]]) np.savetxt('reference_front.csv', reference, delimiter=',') ``` -------------------------------- ### Run SMPSO Algorithm and Visualize Results Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/psos/smpso.html This example demonstrates how to instantiate and run the SMPSO algorithm with the ZDT4 problem. It configures the algorithm with a specific swarm size, mutation operator, leader selection mechanism (CrowdingDistanceArchive), and termination criterion based on the maximum number of evaluations. After running, it retrieves the solutions and visualizes the Pareto front approximation. ```python from jmetal.algorithm.multiobjective.smpso import SMPSO from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT4 from jmetal.util.archive import CrowdingDistanceArchive from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT4() max_evaluations = 25000 algorithm = SMPSO( problem=problem, swarm_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), leaders=CrowdingDistanceArchive(100), termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.run() solutions = algorithm.get_result() ``` ```python from jmetal.lab.visualization.plotting import Plot from jmetal.util.solution import get_non_dominated_solutions front = get_non_dominated_solutions(solutions) plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='SMPSO-ZDT4') ``` -------------------------------- ### Initialize Experiment Execution Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/lab/experiment.html Sets up an experiment to run a list of jobs. Specify the output directory for results and the maximum number of parallel workers. ```python class Experiment: def __init__(self, output_dir: str, jobs: List[Job], m_workers: int = 6): """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. :param m_workers: Maximum number of workers to execute the Jobs in parallel. """ self.jobs = jobs self.m_workers = m_workers self.output_dir = output_dir self.job_data = [] ``` -------------------------------- ### Initialize LZ09_F2 Problem Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/multiobjective/lz09.html Constructor for the LZ09_F2 benchmark problem. ```python class LZ09_F2(LZ09): def __init__(self, number_of_variables=30): super(LZ09_F2, self).__init__( ``` -------------------------------- ### Generic Type Constraint Example Source: https://jmetal.github.io/jMetalPy/contributing.html This example demonstrates a type warning when a type not allowed by the `TypeVar` constraint is used. The `TypeVar('S', int, float)` restricts `S` to only `int` or `float`. ```python from typing import TypeVar _TypeVar('S', int, float) # IDE will display a warning here if 'str' is passed for S ``` -------------------------------- ### Get algorithm name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/omopso.html Returns the name of the algorithm. ```python def get_name(self) -> str: return "OMOPSO" ``` -------------------------------- ### FDA2 Get Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/multiobjective/fda.html Returns the name of the problem, which is 'FDA2'. ```python def get_name(self): return "FDA2" ``` -------------------------------- ### FDA1 Get Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/multiobjective/fda.html Returns the name of the problem, which is 'FDA1'. ```python def get_name(self): return "FDA1" ``` -------------------------------- ### HYPE Algorithm Implementation Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/hype.html Example of how to implement and run the HYPE algorithm for multi-objective optimization. Requires setting up a problem, reference point, and various genetic algorithm operators. Note the mandatory objective assignment for the reference point. ```python from jmetal.algorithm.multiobjective.hype import HYPE from jmetal.core.solution import FloatSolution from jmetal.operator.crossover import SBXCrossover from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT1 from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT1() reference_point = FloatSolution([0], [1], problem.number_of_objectives, ) reference_point.objectives = [1., 1.] # Mandatory for HYPE algorithm = HYPE( problem=problem, reference_point=reference_point, population_size=100, offspring_population_size=100, mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations(2500) ) algorithm.run() solutions = algorithm.get_result() ``` -------------------------------- ### NSGA-III Get Name Method Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/nsgaiii.html Returns the name of the algorithm. ```APIDOC ## NSGA-III Get Name Method ### Description Returns the name of the algorithm. ### Method `get_name(self) -> str` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns the string "NSGAIII". #### Response Example None ``` -------------------------------- ### Initialize SMPSO Algorithm Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/smpso.html Constructor for the SMPSO algorithm. Requires the problem, swarm size, mutation operator, and a leaders archive. It sets up various parameters for the optimization process. ```python 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: ``_. The implementation of SMPSO provided in jMetalPy follows the algorithm template described in the algorithm templates section of the documentation. :param problem: The problem to solve. :param swarm_size: Size of the swarm. :param max_evaluations: Maximum number of evaluations/iterations. :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) self.swarm_generator = swarm_generator self.swarm_evaluator = swarm_evaluator self.termination_criterion = termination_criterion self.observable.register(termination_criterion) self.mutation_operator = mutation self.leaders = leaders self.c1_min = 1.5 self.c1_max = 2.5 self.c2_min = 1.5 self.c2_max = 2.5 self.r1_min = 0.0 self.r1_max = 1.0 self.r2_min = 0.0 self.r2_max = 1.0 self.min_weight = 0.1 self.max_weight = 0.1 self.change_velocity1 = -1 self.change_velocity2 = -1 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()), ) ``` -------------------------------- ### MOEAD_DRA Get Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/moead.html Returns the name of the MOEAD-DRA algorithm. ```python def get_name(self): return "MOEAD-DRA" ``` -------------------------------- ### MOEAD Get Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/moead.html Returns the name of the MOEAD algorithm. ```python [docs] def get_name(self): return "MOEAD" ``` -------------------------------- ### Create Many-Objective Solutions and Archive Source: https://jmetal.github.io/jMetalPy/advanced-topics/distance-based-archive.html Demonstrates creating a set of solutions with diverse trade-offs and managing them using a DistanceBasedArchive. ```python import random from jmetal.util.archive import DistanceBasedArchive from jmetal.core.solution import FloatSolution def create_many_objective_solutions(n_solutions=100, n_objectives=5): """Create diverse solutions in many-objective space""" solutions = [] random.seed(42) # For reproducibility for i in range(n_solutions): solution = FloatSolution([], [], n_objectives) # Create solutions with different trade-offs objectives = [] for j in range(n_objectives): # Some solutions excel in specific objectives if i % n_objectives == j: objectives.append(random.uniform(0.0, 0.3)) # Good in this objective else: objectives.append(random.uniform(0.4, 1.0)) # Worse in others solution.objectives = objectives solutions.append(solution) return solutions # Create archive for 5-objective problem archive = DistanceBasedArchive(maximum_size=10) solutions = create_many_objective_solutions(100, 5) for solution in solutions: archive.add(solution) print(f"Selected {archive.size()} solutions from {len(solutions)} candidates") print("Selected solutions (5 objectives):") for i in range(archive.size()): sol = archive.get(i) obj_str = [f"{obj:.3f}" for obj in sol.objectives] print(f" Solution {i}: [{', '.join(obj_str)}]") ``` -------------------------------- ### Get problem name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/core/problem.html Returns the stored name of the problem. ```python def name(self) -> str: return self.problem_name ``` -------------------------------- ### Get DTLZ6 Problem Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/multiobjective/dtlz.html Returns the name of the DTLZ6 problem. ```python def name(self): return "DTLZ6" ``` -------------------------------- ### Initialize OMOPSO Algorithm Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/omopso.html The OMOPSO class constructor requires a problem, swarm size, mutation operators, and an archive for leaders. ```python 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 The implementation of OMOPSO provided in jMetalPy follows the algorithm template described in the algorithm templates section of the documentation. :param problem: The problem to solve. :param swarm_size: Size of the swarm. :param leaders: Archive for leaders. """ super(OMOPSO, self).__init__(problem=problem, swarm_size=swarm_size) self.swarm_generator = swarm_generator self.swarm_evaluator = swarm_evaluator self.termination_criterion = termination_criterion self.observable.register(termination_criterion) self.uniform_mutation = uniform_mutation self.non_uniform_mutation = non_uniform_mutation self.leaders = leaders self.epsilon = epsilon self.epsilon_archive = NonDominatedSolutionsArchive(EpsilonDominanceComparator(epsilon)) self.c1_min = 1.5 self.c1_max = 2.0 self.c2_min = 1.5 self.c2_max = 2.0 self.r1_min = 0.0 self.r1_max = 1.0 self.r2_min = 0.0 self.r2_max = 1.0 self.weight_min = 0.1 self.weight_max = 0.5 self.change_velocity1 = -1 self.change_velocity2 = -1 self.dominance_comparator = DominanceComparator() self.speed = numpy.zeros((self.swarm_size, self.problem.number_of_variables()), dtype=float) ``` -------------------------------- ### Get DTLZ5 Problem Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/multiobjective/dtlz.html Returns the name of the DTLZ5 problem. ```python def name(self): return "DTLZ5" ``` -------------------------------- ### Get DTLZ4 Problem Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/multiobjective/dtlz.html Returns the name of the DTLZ4 problem. ```python def name(self): return "DTLZ4" ``` -------------------------------- ### MOEAD Progress Initialization Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/moead.html Sets up the initial state of the algorithm, including fitness function updates and permutation generation. ```python 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.observable_data() self.observable.notify_all(**observable_data) ``` -------------------------------- ### Get Problem Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/singleobjective/unconstrained.html Returns the name of the problem, which is 'Subset Sum'. ```python def name(self) -> str: return "Subset Sum" ``` -------------------------------- ### Progress and Reference Point Methods Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/smpso.html Methods to initialize progress, update state, and manage reference points. ```python def init_progress(self) -> None: self.evaluations = self.swarm_size for leader in self.leaders: leader.compute_density_estimator() self.initialize_velocity(self.solutions) self.initialize_particle_best(self.solutions) self.initialize_global_best(self.solutions) ``` ```python def update_progress(self) -> None: self.evaluations += self.swarm_size for leader in self.leaders: leader.filter() leader.compute_density_estimator() observable_data = self.observable_data() observable_data["REFERENCE_POINT"] = self.get_reference_point() self.observable.notify_all(**observable_data) ``` ```python 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]) ``` ```python def get_reference_point(self): with self.lock: return self.reference_points ``` -------------------------------- ### Get Knapsack Problem Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/problem/singleobjective/knapsack.html Returns the name of the problem, which is 'Knapsack'. ```python def name(self): return "Knapsack" ``` -------------------------------- ### GET /result Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/smpso.html Retrieves the final set of solutions found by the algorithm. ```APIDOC ## GET /result ### Description Aggregates and returns all solutions stored in the algorithm's leaders. ### Method GET ### Response #### Success Response (200) - **result** (List[FloatSolution]) - A list of solutions collected from all archives. ``` -------------------------------- ### Get number of constraints Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/core/problem.html Returns the count of constraints defined for the problem. ```python def number_of_constraints(self) -> int: return len(self.constraints) ``` -------------------------------- ### Run MOCell Algorithm and Visualize Pareto Front Source: https://jmetal.github.io/jMetalPy/api/algorithm/multiobjective/eas/mocell.html This example demonstrates how to instantiate and run the MOCell algorithm for a multi-objective problem (ZDT4). It includes setting up the problem, population size, neighborhood, archive, mutation, crossover, and termination criterion. Finally, it visualizes the obtained Pareto front approximation using the Plot utility. ```python from jmetal.algorithm.multiobjective.mocell import MOCell from jmetal.operator.crossover import SBXCrossover from jmetal.operator.mutation import PolynomialMutation from jmetal.problem import ZDT4 from jmetal.util.archive import CrowdingDistanceArchive from jmetal.util.neighborhood import C9 from jmetal.util.termination_criterion import StoppingByEvaluations problem = ZDT4() max_evaluations = 25000 algorithm = MOCell( problem=problem, population_size=100, neighborhood=C9(10, 10), archive=CrowdingDistanceArchive(100), mutation=PolynomialMutation(probability=1.0 / problem.number_of_variables, distribution_index=20), crossover=SBXCrossover(probability=1.0, distribution_index=20), termination_criterion=StoppingByEvaluations(max=max_evaluations) ) algorithm.run() front = algorithm.get_result() ``` ```python from jmetal.lab.visualization.plotting import Plot plot_front = Plot(plot_title='Pareto front approximation', axis_labels=['x', 'y']) plot_front.plot(front, label='MOCell-ZDT4') ``` -------------------------------- ### Get GDE3 Algorithm Name Source: https://jmetal.github.io/jMetalPy/_modules/jmetal/algorithm/multiobjective/gde3.html Returns the name of the GDE3 algorithm. ```python def get_name(self) -> str: return "GDE3" ```