### Install Python __init__.py Source: https://github.com/esa/pygmo2/blob/master/pygmo/plotting/CMakeLists.txt Installs the __init__.py file to the specified Python installation directory for the plotting module. ```cmake install(FILES __init__.py DESTINATION ${_PYGMO_INSTALL_DIR}/plotting) ``` -------------------------------- ### Install Pygmo2 Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Install the Pygmo2 library after it has been built. ```console $ cmake --build . --target install ``` -------------------------------- ### Algorithm Comparison Setup and Execution Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/cmaes_vs_xnes.rst This script sets up an experiment to compare pygmo's xNES and CMA-ES algorithms. It defines experiment parameters, instantiates the problem and algorithms, and iterates through different population sizes to collect performance data. ```python # 1 We import what is needed import pygmo as pg import numpy as np from matplotlib import pyplot as plt # doctest: +SKIP from random import shuffle import itertools # 2 - We define the details of the experiment trials = 100 # Number of algorithmic runs bootstrap = 100 # Number of shuffles of the trials target = 1e-6 # value of the objective function to consider success n_bins = 100 # Number of bins to divide the ECDF udp = pg.rosenbrock # Problem to be solved dim = 10 # Problem dimension # 3 - We instantiate here the problem, algorithms to compare and on what population size prob = pg.problem(udp(dim)) algos = [pg.algorithm(pg.xnes(gen=4000, ftol=1e-8, xtol = 1e-10)), pg.algorithm(pg.cmaes(gen=4000, ftol=1e-8, xtol = 1e-10))] popsizes = [10,20,30] # For each of the popsizes and algorithms for algo, popsize in itertools.product(algos, popsizes): # 4 - We run the algorithms trials times run = [] for i in range(trials): pop = pg.population(prob, popsize) pop = algo.evolve(pop) # doctest: +SKIP run.append([pop.problem.get_fevals(), pop.champion_f[0]]) # 5 - We assemble the restarts in a random order (a run) and compute the number # of function evaluations needed to reach the target for each run target_reached_at = [] for i in range(bootstrap): shuffle(run) tmp = [r[1] for r in run] t1 = np.array([min(tmp[:(i + 1)]) for i in range(len(tmp))]) t2 = np.cumsum([r[0] for r in run]) idx = np.where(t1 < target) target_reached_at.append(t2[idx][0]) target_reached_at = np.array(target_reached_at) # 6 - We build the ECDF fevallim = 2 * max(target_reached_at) bins = np.linspace(0, fevallim, n_bins) ecdf = [] for b in bins: s = sum((target_reached_at) < b) / len(target_reached_at) ecdf.append(s) plt.plot(bins, ecdf, label=algo.get_name().split(":")[0] + " - " + str(popsize)) # doctest: +SKIP plt.legend() # doctest: +SKIP ax = plt.gca() # doctest: +SKIP ax.set_xscale('log') # doctest: +SKIP plt.title(prob.get_name() + " - dimension " + str(dim)) # doctest: +SKIP plt.xlabel("N. fevals") # doctest: +SKIP ``` -------------------------------- ### Benchmarking Setup and Initialization Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nspso_tutorial_zdt1_2.rst This code block sets up the benchmarking process by defining population size and problems. It then initializes empty lists to store performance metrics (p-distance and mean crowding distance) for different algorithms across multiple runs. ```Python from pygmo import * from pygmo import * import numpy as np pop_size=200 problems=[1,2] #We declare empty arrays for storing the p-distance and mean crowding distance values for all #the algorithms and problems over 10 runs: #p-distance p_dist_nspso_cd_zdt1=[] p_dist_nspso_cd_zdt2=[] p_dist_nspso_nc_zdt1=[] p_dist_nspso_nc_zdt2=[] p_dist_nsga2_zdt1=[] p_dist_nsga2_zdt2=[] #crowding distance mean_cd_nspso_cd_zdt1=[] mean_cd_nspso_cd_zdt2=[] mean_cd_nspso_nc_zdt1=[] mean_cd_nspso_nc_zdt2=[] mean_cd_nsga2_zdt1=[] mean_cd_nsga2_zdt2=[] ``` -------------------------------- ### Instantiate and time JIT-compiled problem Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udp_simple.rst This example demonstrates how to instantiate the JIT-compiled Rosenbrock problem and measure the time taken to compute fitness for multiple iterations. ```python import time prob_jit2 = pg.problem(jit_rosenbrock2(2000)) start_time = time.time(); [prob_jit2.fitness(dummy_x) for i in range(1000)]; print(time.time() - start_time) #doctest: +SKIP ``` -------------------------------- ### Install pygmo2 via PyPI Source: https://github.com/esa/pygmo2/blob/master/README.md Alternatively, pygmo2 can be installed from the Python Package Index (PyPI). Note that PyPI wheels are currently only provided for Linux x86_64 and aarch64. ```bash pip install pygmo ``` -------------------------------- ### Install Pygmo for a single user using pip Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Installs Pygmo for a single user, which is generally recommended over system-wide installation. Virtual environments are also suggested. ```console $ pip install --user pygmo ``` -------------------------------- ### Verify Pygmo2 Installation Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Run the test suite from a Python session to confirm a successful installation. ```python >>> import pygmo >>> pygmo.test.run_test_suite() ``` -------------------------------- ### Install Pygmo from AUR using yay Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Installs the python-pygmo package from the Arch User Repository (AUR) using the yay helper. ```console $ yay -S python-pygmo ``` -------------------------------- ### Install Pygmo using pip Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Installs Pygmo using the pip package installer. It is recommended to use virtual environments. ```console $ pip install pygmo ``` -------------------------------- ### Monitoring and Visualizing Evolution Runs Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/evolving_a_population.rst This example shows how to monitor the progress of a stochastic algorithm over multiple generations and visualize the results. It involves setting verbosity, performing an evolution, extracting the algorithm's log, and plotting the best fitness against generations using matplotlib. ```python # We set the verbosity to 100 (i.e. each 100 gen there will be a log line) algo.set_verbosity(100) # We perform an evolution pop = pg.population(prob, size = 20) pop = algo.evolve(pop) # doctest: +SKIP Gen: Fevals: Best: F: CR: dx: df: 1 20 135745 0.264146 0.541101 61.4904 2.55547e+06 101 2020 36.7951 0.252116 0.380181 7.01344 179.332 201 4020 4.06502 0.254534 0.740681 6.00596 59.3928 301 6020 2.96096 0.147331 0.790883 0.402499 7.95054 401 8020 2.43639 0.452624 0.922214 5.28217 6.80877 501 10020 1.65288 0.981585 0.975004 1.34442 0.897989 601 12020 1.16901 0.97663 0.783304 1.70733 1.36504 701 14020 0.750577 0.398881 0.922214 2.11136 1.78254 801 16020 0.438464 0.36723 0.960114 1.65512 1.18982 901 18020 0.18011 0.25882 0.932028 2.34781 1.4481 1001 20020 0.0792334 0.412775 0.887402 1.07089 0.211411 1101 22020 0.00875321 0.852287 0.472265 1.17808 0.170671 1201 24020 0.000820125 0.529034 0.633499 0.207262 0.0122566 1301 26020 2.13261e-05 0.176605 0.896106 0.060826 0.000706859 1401 28020 6.06571e-07 0.105885 0.81249 0.00852982 4.93967e-05 Exit condition -- generations = 1500 ``` ```python uda = algo.extract(pg.sade) log = uda.get_log() import matplotlib.pyplot as plt # doctest: +SKIP plt.semilogy([entry[0] for entry in log],[entry[2]for entry in log], 'k--') # doctest: +SKIP plt.show() # doctest: +SKIP ``` -------------------------------- ### Displaying Decorated Problem Information Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/udp_meta_decorator.rst This example demonstrates how the string representation of a decorated problem reflects the applied decorators. It shows the problem's properties and lists the registered decorators, such as 'fitness'. ```python >>> drb #doctest: +NORMALIZE_WHITESPACE Problem name: Multidimensional Rosenbrock Function [decorated] C++ class name: ... Global dimension: 2 Integer dimension: 0 Fitness dimension: 1 Number of objectives: 1 Equality constraints dimension: 0 Inequality constraints dimension: 0 Lower bounds: [-5, -5] Upper bounds: [10, 10] Has batch fitness evaluation: false Has gradient: true User implemented gradient sparsity: false Expected gradients: 2 Has hessians: false User implemented hessians sparsity: false Fitness evaluations: 0 Gradient evaluations: 0 Thread safety: none Extra info: Registered decorators: fitness ``` -------------------------------- ### Solving CEC2006 'g07' with SQP and Numerical Gradients Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udp_constrained.rst This snippet demonstrates how to apply a Sequential Quadratic Programming (SQP) method to the CEC2006 'g07' problem after adding numerical gradients. It shows the setup of the problem, algorithm, and population, followed by the evolution process. ```python # Start adding the numerical gradient (low-precision) to the UDP prob = pg.problem(add_gradient(pg.cec2006(prob_id = 7))) # Define a solution strategy (SQP method) algo = pg.algorithm(uda = pg.mbh(pg.nlopt("slsqp"), 20, .2)) pop = pg.population(prob, 1) # Solve the problem pop = algo.evolve(pop) # doctest: +SKIP ``` -------------------------------- ### UDP with numerically estimated gradient Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nlopt_basics.rst This example shows how to augment a UDP to provide gradients using `pygmo.estimate_gradient_h()`. This allows gradient-based optimizers to function correctly even when the analytical gradient is complex or unavailable. The `gradient` method calls `pygmo.estimate_gradient_h` with a lambda function that computes the fitness. ```python class my_udp: def fitness(self, x): return (np.sin(x[0]+x[1]-x[2]), x[0] + np.cos(x[2]*x[1]), x[2]) def get_bounds(self): return ([-1,-1,-1],[1,1,1]) def get_nec(self): return 1 def get_nic(self): return 1 def gradient(self, x): return pg.estimate_gradient_h(lambda x: self.fitness(x), x) >>> pop = pg.population(prob = my_udp(), size = 1) >>> pop = algo.evolve(pop) # doctest: +SKIP fevals: fitness: violated: viol. norm: 1 0.694978 2 1.92759 i 2 -0.97723 1 9.87066e-05 i 3 -0.999189 1 0.00295056 i 4 -1 1 3.2815e-05 i 5 -1 1 1.11149e-08 i 6 -1 1 8.12683e-14 i 7 -1 0 0 ``` -------------------------------- ### Initialize NLopt Solver Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nlopt_basics.rst Instantiate a pygmo algorithm with an NLopt solver like 'slsqp'. This sets up the optimization framework. ```python import pygmo as pg uda = pg.nlopt("slsqp") algo = pg.algorithm(uda) print(algo) ``` -------------------------------- ### Install pygmo2 via Conda-Forge Source: https://github.com/esa/pygmo2/blob/master/README.md The recommended installation method for pygmo2 is using conda-forge. This command installs the pygmo package from the conda-forge channel. ```bash conda install -c conda-forge pygmo ``` -------------------------------- ### Instantiating and Using a Simple UDI Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udi.rst Demonstrates how to create a `pygmo.island` using a custom UDI and display its representation. ```python isl = pg.island(algo = pg.de(100), prob = pg.ackley(5), udi = my_isl(), size = 20) print(isl) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS Island name: It's my island! C++ class name: ... Status: idle Algorithm: DE: Differential Evolution Problem: Ackley Function Replacement policy: Fair replace Selection policy: Select best Population size: 20 Champion decision vector: [... Champion fitness: [... ``` -------------------------------- ### Initialize Populations Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/using_population.rst Demonstrates initializing an empty population and a population with a specified size and random seed. ```python import pygmo as pg prob = pg.problem(pg.rosenbrock(dim = 4)) pop1 = pg.population(prob) pop2 = pg.population(prob, size = 5, seed= 723782378) ``` -------------------------------- ### Install Pygmo using Conda Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Installs Pygmo via the conda package manager. Ensure conda-forge is added as a channel and channel priority is set to strict. ```console $ conda config --add channels conda-forge $ conda config --set channel_priority strict $ conda install pygmo ``` -------------------------------- ### Find Python3 Dependency Source: https://github.com/esa/pygmo2/blob/master/CMakeLists.txt This finds the Python3 interpreter and development components. It then prints the paths for the executable and installation directory, and sets a cache variable for the module installation path. ```cmake find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Module) message(STATUS "Python3 interpreter: ${Python3_EXECUTABLE}") message(STATUS "Python3 installation directory: ${Python3_SITEARCH}") set(PYGMO_INSTALL_PATH "" CACHE STRING "pygmo module installation path") mark_as_advanced(PYGMO_INSTALL_PATH) ``` -------------------------------- ### Navigate to Pygmo2 Source Directory Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Change to the pygmo source directory and create a build directory. ```console $ cd /path/to/pygmo $ mkdir build $ cd build ``` -------------------------------- ### Initialize NSPSO with Niche Count Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nspso_tutorial_zdt1_2.rst This snippet demonstrates initializing the NSPSO algorithm using the 'niche count' diversity mechanism. It shares many parameters with the crowding distance version but differs in its diversity strategy. ```Python algo = algorithm(nspso(gen = 100, omega=0.001, c1 = 2.0, c2 = 2.0, chi = 1.0, v_coeff = 0.5, leader_selection_range = 100, diversity_mechanism = 'niche count', memory = False, seed = 20)) ``` -------------------------------- ### pygmo.ipopt Source: https://github.com/esa/pygmo2/blob/master/doc/algorithms.rst Documentation for the ipopt algorithm, exposed from C++. ```APIDOC ## Class: pygmo.ipopt ### Description This class provides access to the IPOPT (Interior Point Optimizer) solver, exposed from the C++ backend. ### Members (Details of members would be listed here if available in the source) ``` -------------------------------- ### Clone Pygmo from GitHub Source: https://github.com/esa/pygmo2/blob/master/doc/install.rst Clones the Pygmo source code repository from GitHub to get the latest version for development or bleeding-edge use. ```console $ git clone https://github.com/esa/pygmo2.git ``` -------------------------------- ### Inspect a Pygmo problem Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/cec2013_comp.rst Print a pygmo.problem object to the console to inspect its properties, such as dimensions, bounds, and evaluation status. This is useful for verifying problem setup. ```python print(prob) #doctest: +NORMALIZE_WHITESPACE Problem name: CEC2013 - f24(cf04) C++ class name: ... Global dimension: 10 Integer dimension: 0 Fitness dimension: 1 Number of objectives: 1 Equality constraints dimension: 0 Inequality constraints dimension: 0 Lower bounds: [-100, -100, -100, -100, -100, ... ] Upper bounds: [100, 100, 100, 100, 100, ... ] Has batch fitness evaluation: false Has gradient: false User implemented gradient sparsity: false Has hessians: false User implemented hessians sparsity: false Fitness evaluations: 0 Thread safety: basic ``` -------------------------------- ### Instantiate and Print pygmo.algorithm with CMA-ES Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/using_algorithm.rst Demonstrates how to import pygmo, create an instance of the pygmo.algorithm class using the cmaes UDA with specific parameters (generations and initial standard deviation), and print the algorithm's details. ```python import pygmo as pg algo = pg.algorithm(pg.cmaes(gen = 100, sigma0=0.3)) print(algo) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE Algorithm name: CMA-ES: Covariance Matrix Adaptation Evolutionary Strategy [stochastic] C++ class name: ... Thread safety: basic Extra info: Generations: 100 cc: auto cs: auto c1: auto cmu: auto sigma0: 0.3 Stopping xtol: 1e-06 Stopping ftol: 1e-06 Memory: false Verbosity: 0 Force bounds: false Seed: ... ``` -------------------------------- ### Initialize NSGA-II Algorithm Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nspso_tutorial_zdt1_2.rst This snippet shows the initialization of the NSGA-II algorithm with parameters recommended in the original paper, including generations, crossover rate, mutation rate, and distribution indices. ```Python algo_3 = algorithm(nsga2(gen = 100, cr=0.9, m=1/30, eta_c=20, eta_m=20, seed = 20)) ``` -------------------------------- ### Algorithm Initialization and Evolution Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nspso_tutorial_zdt1_2.rst Initializes three populations and defines three algorithms: NSPSO with crowding distance, NSPSO with niche count, and NSGA-II. It then evolves each population using its respective algorithm. ```python pop_1 = population(prob = udp, size = pop_size, seed = ii+3) pop_2 = population(prob = udp, size = pop_size, seed = ii+3) pop_3 = population(prob = udp, size = pop_size, seed = ii+3) # 3. We declare the algorithms to be used: NSPSO with crowding distance, NSPSO with niche count and NSGA-II: algo = algorithm(nspso(gen = 100, omega=0.001, c1 = 2.0, c2 = 2.0, chi = 1.0, v_coeff = 0.5, leader_selection_range = 100, diversity_mechanism = 'crowding distance', memory = False, seed = 20)) algo_2 = algorithm(nspso(gen = 100, omega=0.001, c1 = 2.0, c2 = 2.0, chi = 1.0, v_coeff = 0.5, leader_selection_range = 100, diversity_mechanism = 'niche count', memory = False, seed = 20)) algo_3 = algorithm(nsga2(gen = 100, cr=0.9, m=1/30, eta_c=20, eta_m=20, seed = 20)) # 4. We evolve the populations for the three algorithms: pop_1 = algo.evolve(pop_1) pop_2 = algo_2.evolve(pop_2) pop_3 = algo_3.evolve(pop_3) ``` -------------------------------- ### UDP Incorrect Fitness Return Type Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udp_simple.rst This example demonstrates a UDP where the `fitness()` method returns a scalar instead of an array-like object, causing an `AttributeError` when the method is invoked. ```python class sphere_function: def fitness(self, x): return sum(x*x) def get_bounds(self): return ([-1,-1],[1,1]) prob = pg.problem(sphere_function()) prob.fitness([1,2]) ``` -------------------------------- ### pygmo.maco Source: https://github.com/esa/pygmo2/blob/master/doc/algorithms.rst Documentation for the maco algorithm, exposed from C++. ```APIDOC ## Class: pygmo.maco ### Description This class implements the MACO (Multi-Agent Cultural Optimization) algorithm, exposed from the C++ backend. ### Members (Details of members would be listed here if available in the source) ``` -------------------------------- ### Initialize and Run Benchmarking Algorithms on ZDT3 Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/zdt3_maco_benchmark.rst This code initializes the ZDT3 problem, sets up population sizes and seeds, and runs MOEA/D, MACO, and NSGA-II algorithms. It collects results for hypervolume and p-distance calculations. ```python from pygmo import * import numpy as np from matplotlib import pyplot as plt #doctest: +SKIP pop_sizes=[32, 64, 128] udp = zdt(prob_id = 3) hv_moead=[0, 0, 0] hv_maco=[0, 0, 0] hv_nsga2=[0, 0, 0] p_dist_moead=[0, 0, 0] p_dist_maco=[0, 0, 0] p_dist_nsga2=[0, 0, 0] #We run the algos three times each, for 3 different pop-sizes for j in pop_sizes: for i in range(0,3): pop_1 = population(prob = udp, size = j, seed = i) pop_2 = population(prob = udp, size = j, seed = i) pop_3 = population(prob = udp, size = j, seed = i) hv=hypervolume(pop_1) ref_point=hv.refpoint(offset=0.01) #I store all the pop-sizes results for all the runs: #1st seed: if j==pop_sizes[0] and i==0: first_pop_32_1=pop_1.get_f() if j==pop_sizes[1] and i==0: first_pop_64_1=pop_1.get_f() if j==pop_sizes[2] and i==0: first_pop_128_1=pop_1.get_f() #2nd seed: if j==pop_sizes[0] and i==1: first_pop_32_2=pop_1.get_f() if j==pop_sizes[1] and i==1: first_pop_64_2=pop_1.get_f() if j==pop_sizes[2] and i==1: first_pop_128_2=pop_1.get_f() #3rd seed: if j==pop_sizes[0] and i==2: first_pop_32_3=pop_1.get_f() if j==pop_sizes[1] and i==2: first_pop_64_3=pop_1.get_f() if j==pop_sizes[2] and i==2: first_pop_128_3=pop_1.get_f() algo = algorithm(moead(250, 'random')) algo_2 = algorithm(maco(gen = 250, ker = j-20, q = 1.0, threshold = 250, n_gen_mark = 47, evalstop=10000, focus=0.0, memory=False)) algo_3 = algorithm(nsga2(gen = 250)) algo.set_seed(i+1) algo_2.set_seed(i+1) algo_3.set_seed(i+1) pop_1 = algo.evolve(pop_1) pop_2=algo_2.evolve(pop_2) pop_3 = algo_3.evolve(pop_3) #This returns a series of arrays: in each of them it is contained (in this order), the -non-dominated front, -domination list, #-domination count, -non-domination rank fnds=fast_non_dominated_sorting(pop_1.get_f()) fnds_2=fast_non_dominated_sorting(pop_2.get_f()) fnds_3=fast_non_dominated_sorting(pop_3.get_f()) #This returns the first (i.e., best) non-dominated front: first_ndf_moead=fnds[0][0] first_ndf_maco=fnds_2[0][0] first_ndf_nsga2=fnds_3[0][0] ``` -------------------------------- ### UDP Missing get_bounds Method Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udp_simple.rst This example shows a common mistake where a User Defined Problem (UDP) is missing the mandatory `get_bounds()` method, leading to a `NotImplementedError` upon problem instantiation. ```python class sphere_function: def fitness(self, x): return [sum(x*x)] pg.problem(sphere_function()) ``` -------------------------------- ### pygmo.nlopt Source: https://github.com/esa/pygmo2/blob/master/doc/algorithms.rst Documentation for the nlopt algorithm, exposed from C++. ```APIDOC ## Class: pygmo.nlopt ### Description This class provides access to algorithms from the NLopt library, exposed from the C++ backend. ### Members (Details of members would be listed here if available in the source) ``` -------------------------------- ### Multiprocessing UDI Class Structure Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udi.rst An example of a UDI class that utilizes Python's `multiprocessing` module to offload the `algo.evolve(pop)` task to a separate process, thereby releasing the GIL. ```python class mp_island(object): def __init__(self): # Init the process pool, if necessary. mp_island.init_pool() def run_evolve(self, algo, pop): with mp_island._pool_lock: res = mp_island._pool.apply_async(_evolve_func, (algo, pop)) return res.get() ``` -------------------------------- ### Inspect pygmo Problem Object Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udp_minlp.rst This snippet demonstrates how to construct a pygmo problem object from a user-defined problem and print its properties. This is useful for verifying the problem setup, including dimensions, bounds, and constraint types. ```python import pygmo as pg prob = pg.problem(my_minlp()) print(prob) ``` -------------------------------- ### Compute hypervolume using a specific algorithm (hvwfg) Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/hypervolume_advanced.rst Explicitly pass the desired algorithm (e.g., pg.hvwfg()) to the compute method to bypass default algorithm selection. This example uses the Walking Fish Group algorithm. ```python import pygmo as pg hv = pg.hypervolume([[1,0,1],[1,1,0],[-1,2,2]]) hv.compute([5,5,5], hv_algo=pg.hvwfg()) 114.0 ``` -------------------------------- ### Inspect MOEAD Algorithm Settings Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/moo_moead.rst Prints the details of the MOEAD algorithm instance, including its name, C++ class, thread safety, and specific parameters like generations, weight generation method, and decomposition method. ```python print(algo) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ``` -------------------------------- ### Define and Prepare Optimization Problem Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nlopt_basics.rst Create a pygmo problem instance using a UDP (User Defined Problem) like 'luksan_vlcek1' and initialize a population. Constraint tolerances are also set. ```python udp = pg.luksan_vlcek1(dim = 20) prob = pg.problem(udp) pop = pg.population(prob, size = 1) pop.problem.c_tol = [1e-8] * prob.get_nc() ``` -------------------------------- ### Shortened Problem Initialization Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nlopt_basics.rst A more concise way to initialize a pygmo population with a problem and set constraint tolerances. ```python pop = pg.population(pg.luksan_vlcek1(dim = 20), size = 1) pop.problem.c_tol = [1e-8] * pop.problem.get_nc() ``` -------------------------------- ### UDP without explicit gradient Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/nlopt_basics.rst This example defines a User Defined Problem (UDP) that only implements the `fitness` and `get_bounds` methods, without providing an explicit gradient. Attempting to use a gradient-based NLopt algorithm like 'slsqp' with this UDP will result in a ValueError. ```python class my_udp: def fitness(self, x): return (np.sin(x[0]+x[1]-x[2]), x[0] + np.cos(x[2]*x[1]), x[2]) def get_bounds(self): return ([-1,-1,-1],[1,1,1]) def get_nec(self): return 1 def get_nic(self): return 1 >>> import numpy as np >>> pop = pg.population(prob = my_udp(), size = 1) >>> pop = algo.evolve(pop) ``` -------------------------------- ### Instantiate and Configure Archipelago Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/using_archipelago.rst This Python code demonstrates how to instantiate a pyGOM2 Archipelago with a specific algorithm, problem, and population size. It sets up 32 parallel islands for optimization. ```python import pygmo as pg a_cstrs_sa = pg.algorithm(pg.cstrs_self_adaptive(iters=1000)) p_toy = pg.problem(toy_problem(50)) p_toy.c_tol = [1e-4, 1e-4] archi = pg.archipelago(n=32,algo=a_cstrs_sa, prob=p_toy, pop_size=70) print(archi) #doctest: +SKIP ``` -------------------------------- ### pygmo.moead Source: https://github.com/esa/pygmo2/blob/master/doc/algorithms.rst Documentation for the moead algorithm, exposed from C++. ```APIDOC ## Class: pygmo.moead ### Description This class implements the MOEA/D (Multi-Objective Evolutionary Algorithm based on Decomposition) algorithm, exposed from the C++ backend. ### Members (Details of members would be listed here if available in the source) ``` -------------------------------- ### Define a Toy Problem UDP Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/using_archipelago.rst This Python code defines a custom User Defined Problem (UDP) for optimization. It includes methods for fitness calculation, gradient estimation, constraint handling, bounds, and problem naming. This UDP is used as an example for the Archipelago tutorial. ```python class toy_problem: def __init__(self, dim): self.dim = dim def fitness(self, x): return [sum(x), 1 - sum(x*x), - sum(x)] def gradient(self, x): return pg.estimate_gradient(lambda x: self.fitness(x), x) # numerical gradient def get_nec(self): return 1 def get_nic(self): return 1 def get_bounds(self): return ([-1] * self.dim, [1] * self.dim) def get_name(self): return "A toy problem" def get_extra_info(self): return "\tDimensions: " + str(self.dim) ``` -------------------------------- ### Basic Population Evolution Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/evolving_a_population.rst This snippet demonstrates the fundamental process of evolving a population using a specified problem and algorithm. It initializes a problem, creates a population, sets up an algorithm, evolves the population, and retrieves the best fitness. ```python import pygmo as pg # The problem prob = pg.problem(pg.rosenbrock(dim = 10)) # The initial population pop = pg.population(prob, size = 20) # The algorithm (a self-adaptive form of Differential Evolution (sade - jDE variant) algo = pg.algorithm(pg.sade(gen = 1000)) # The actual optimization process pop = algo.evolve(pop) # Getting the best individual in the population best_fitness = pop.get_f()[pop.best_idx()] print(best_fitness) # doctest: +SKIP ``` -------------------------------- ### Implement Fitness Function for Constrained UDP Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udp_constrained.rst This snippet implements the mandatory `fitness` function for a constrained UDP. It calculates the objective function and all equality and inequality constraints, returning them in a list ordered as [objective, equality_constraints, inequality_constraints]. It also includes the `get_bounds`, `get_nic`, `get_nec` methods and an example of gradient estimation. ```python import math class my_constrained_udp: def fitness(self, x): obj = 0 for i in range(3): obj += (x[2*i-2]-3)**2 / 1000. - (x[2*i-2]-x[2*i-1]) + math.exp(20.*(x[2*i - 2]-x[2*i-1])) ce1 = 4*(x[0]-x[1])**2+x[1]-x[2]**2+x[2]-x[3]**2 ce2 = 8*x[1]*(x[1]**2-x[0])-2*(1-x[1])+4*(x[1]-x[2])**2+x[0]**2+x[2]-x[3]**2+x[3]-x[4]**2 ce3 = 8*x[2]*(x[2]**2-x[1])-2*(1-x[2])+4*(x[2]-x[3])**2+x[1]**2-x[0]+x[3]-x[4]**2+x[0]**2+x[4]-x[5]**2 ce4 = 8*x[3]*(x[3]**2-x[2])-2*(1-x[3])+4*(x[3]-x[4])**2+x[2]**2-x[1]+x[4]-x[5]**2+x[1]**2+x[5]-x[0] ci1 = 8*x[4]*(x[4]**2-x[3])-2*(1-x[4])+4*(x[4]-x[5])**2+x[3]**2-x[2]+x[5]+x[2]**2-x[1] ci2 = -(8*x[5] * (x[5]**2-x[4])-2*(1-x[5]) +x[4]**2-x[3]+x[3]**2 - x[4]) return [obj, ce1,ce2,ce3,ce4,ci1,ci2] def get_bounds(self): return ([-5]*6,[5]*6) def get_nic(self): return 2 def get_nec(self): return 4 def gradient(self, x): return pg.estimate_gradient_h(lambda x: self.fitness(x), x) ``` -------------------------------- ### Instantiate and Solve Multi-Objective Problem Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/coding_udp_multi_objective.rst Create a pygmo problem instance from the custom UDP and solve it using the NSGA2 algorithm. This snippet shows population creation, algorithm selection, optimization execution, and result extraction. ```python import pygmo as pg # create UDP prob = pg.problem(Schaffer()) # create population pop = pg.population(prob, size=20) # select algorithm algo = pg.algorithm(pg.nsga2(gen=40)) # run optimization pop = algo.evolve(pop) # extract results fits, vectors = pop.get_f(), pop.get_x() # extract and print non-dominated fronts ndf, dl, dc, ndr = pg.fast_non_dominated_sorting(fits) print(ndf) #doctest: +SKIP ``` -------------------------------- ### Instantiate DTLZ Problem, Population, and MOEAD Algorithm Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/moo_moead.rst Initializes a DTLZ problem, creates a population, and sets up the MOEAD algorithm for optimization. The population size is set to 105 and the algorithm runs for 100 generations. ```python from pygmo import * udp = dtlz(prob_id = 1) pop = population(prob = udp, size = 105) algo = algorithm(moead(gen = 100)) ``` -------------------------------- ### Benchmark Initialization and Data Storage Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/zdt3_maco_benchmark.rst This code snippet initializes and stores non-dominated front data for multiple runs, seeds, and algorithms (MOEA/D, MACO, NSGA2) for different population sizes. It calculates hypervolume and point distance metrics. ```python #I store all the pop-sizes non-dominated fronts for all the runs: #1st seed: if j==pop_sizes[0] and i==0: #MOEA/D hv_moead[0]=hypervolume(pop_1).compute(ref_point) p_dist_moead[0]=udp.p_distance(pop_1) first_col_moead_32_1=pop_1.get_f()[first_ndf_moead,0] second_col_moead_32_1=pop_1.get_f()[first_ndf_moead,1] #MACO hv_maco[0]=hypervolume(pop_2).compute(ref_point) p_dist_maco[0]=udp.p_distance(pop_2) first_col_maco_32_1=pop_2.get_f()[first_ndf_maco,0] second_col_maco_32_1=pop_2.get_f()[first_ndf_maco,1] #NSGA2 hv_nsga2[0]=hypervolume(pop_3).compute(ref_point) p_dist_nsga2[0]=udp.p_distance(pop_3) first_col_nsga2_32_1=pop_3.get_f()[first_ndf_nsga2,0] second_col_nsga2_32_1=pop_3.get_f()[first_ndf_nsga2,1] if j==pop_sizes[1] and i==0: #MOEA/D hv_moead[1]=hypervolume(pop_1).compute(ref_point) p_dist_moead[1]=udp.p_distance(pop_1) hv_moead[1]=hypervolume(pop_1).compute(ref_point) p_dist_moead[1]=udp.p_distance(pop_1) first_col_moead_64_1=pop_1.get_f()[first_ndf_moead,0] second_col_moead_64_1=pop_1.get_f()[first_ndf_moead,1] #MACO hv_maco[1]=hypervolume(pop_2).compute(ref_point) p_dist_maco[1]=udp.p_distance(pop_2) first_col_maco_64_1=pop_2.get_f()[first_ndf_maco,0] second_col_maco_64_1=pop_2.get_f()[first_ndf_maco,1] #NSGA2 hv_nsga2[1]=hypervolume(pop_3).compute(ref_point) p_dist_nsga2[1]=udp.p_distance(pop_3) first_col_nsga2_64_1=pop_3.get_f()[first_ndf_nsga2,0] second_col_nsga2_64_1=pop_3.get_f()[first_ndf_nsga2,1] if j==pop_sizes[2] and i==0: #MOEA/D hv_moead[2]=hypervolume(pop_1).compute(ref_point) p_dist_moead[2]=udp.p_distance(pop_1) first_col_moead_128_1=pop_1.get_f()[first_ndf_moead,0] second_col_moead_128_1=pop_1.get_f()[first_ndf_moead,1] #MACO hv_maco[2]=hypervolume(pop_2).compute(ref_point) p_dist_maco[2]=udp.p_distance(pop_2) first_col_maco_128_1=pop_2.get_f()[first_ndf_maco,0] second_col_maco_128_1=pop_2.get_f()[first_ndf_maco,1] #NSGA2 hv_nsga2[2]=hypervolume(pop_3).compute(ref_point) p_dist_nsga2[2]=udp.p_distance(pop_3) first_col_nsga2_128_1=pop_3.get_f()[first_ndf_nsga2,0] second_col_nsga2_128_1=pop_3.get_f()[first_ndf_nsga2,1] #2nd seed: if j==pop_sizes[0] and i==1: #MOEA/D hv_moead[0]+=hypervolume(pop_1).compute(ref_point) p_dist_moead[0]+=udp.p_distance(pop_1) first_col_moead_32_2=pop_1.get_f()[first_ndf_moead,0] second_col_moead_32_2=pop_1.get_f()[first_ndf_moead,1] #MACO hv_maco[0]+=hypervolume(pop_2).compute(ref_point) p_dist_maco[0]+=udp.p_distance(pop_2) first_col_maco_32_2=pop_2.get_f()[first_ndf_maco,0] second_col_maco_32_2=pop_2.get_f()[first_ndf_maco,1] #NSGA2 hv_nsga2[0]+=hypervolume(pop_3).compute(ref_point) p_dist_nsga2[0]+=udp.p_distance(pop_3) first_col_nsga2_32_2=pop_3.get_f()[first_ndf_nsga2,0] second_col_nsga2_32_2=pop_3.get_f()[first_ndf_nsga2,1] if j==pop_sizes[1] and i==1: #MOEA/D hv_moead[1]+=hypervolume(pop_1).compute(ref_point) p_dist_moead[1]+=udp.p_distance(pop_1) first_col_moead_64_2=pop_1.get_f()[first_ndf_moead,0] second_col_moead_64_2=pop_1.get_f()[first_ndf_moead,1] #MACO hv_maco[1]+=hypervolume(pop_2).compute(ref_point) p_dist_maco[1]+=udp.p_distance(pop_2) first_col_maco_64_2=pop_2.get_f()[first_ndf_maco,0] second_col_maco_64_2=pop_2.get_f()[first_ndf_maco,1] ``` -------------------------------- ### pygmo.wfg Source: https://github.com/esa/pygmo2/blob/master/doc/problems.rst Provides documentation for the wfg problem exposed from C++. ```APIDOC ## pygmo.wfg ### Description Documentation for the wfg problem exposed from C++. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Instantiating and Running Archipelago with an Exception-Raising Problem Source: https://github.com/esa/pygmo2/blob/master/doc/tutorials/using_archipelago.rst Creates an archipelago with 5 islands, using simulated annealing and a custom problem that intentionally raises an exception. The evolution is then triggered. ```python >>> archi = pg.archipelago(n = 5, algo = pg.simulated_annealing(Ts = 10, Tf = 0.1, n_T_adj = 40), prob = raise_exception(), pop_size = 20) >>> archi.evolve() #doctest: +SKIP ``` -------------------------------- ### pygmo.nsga2 Source: https://github.com/esa/pygmo2/blob/master/doc/algorithms.rst Documentation for the nsga2 algorithm, exposed from C++. ```APIDOC ## Class: pygmo.nsga2 ### Description This class implements the NSGA-II (Non-dominated Sorting Genetic Algorithm II) algorithm, exposed from the C++ backend. ### Members (Details of members would be listed here if available in the source) ``` -------------------------------- ### Copy Python __init__.py Source: https://github.com/esa/pygmo2/blob/master/pygmo/plotting/CMakeLists.txt Copies the __init__.py file to the current binary directory for import during the build process. This is primarily for single-configuration generators. ```cmake configure_file("${CMAKE_CURRENT_SOURCE_DIR}/__init__.py" "${CMAKE_CURRENT_BINARY_DIR}/__init__.py" COPYONLY) ```