### Add Metaheuristics Package Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/index.md Install the Metaheuristics package using the Pkg prompt in the Julia REPL. ```julia pkg> add Metaheuristics ``` -------------------------------- ### Import Metaheuristics Package Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/index.md Import the Metaheuristics package to start using its functionalities. ```julia using Metaheuristics ``` -------------------------------- ### Provide Initial Solutions for Optimization Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Illustrates how to provide one or multiple initial solutions to an optimization algorithm before the process begins. This can be useful for guiding the search. ```julia using Metaheuristics # hide f(x) = abs(x[1]) + x[2] + x[3]^2 # objective function algo = ECA(N = 61); # optimizer # one solution can be provided x0 = [0.5, 0.5, 0.5]; set_user_solutions!(algo, x0, f); # or multiple solutions can be given X0 = rand(30, 3); # 30 solutions with dim 3 set_user_solutions!(algo, X0, f); optimize(f, boxconstraints(lb = [0, 0, 0], ub = [1, 1, 1]), algo) ``` -------------------------------- ### Provide Custom Initial Solutions Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/faq.md Use `set_user_solutions!` to supply custom starting points for the optimization algorithm. You can provide a single solution or multiple solutions as a matrix. ```julia algorithm = ECA() x0 = [0.5, 0.5, 0.5] # single solution set_user_solutions!(algorithm, x0, f) # Or multiple solutions X0 = rand(10, 3) # 10 solutions set_user_solutions!(algorithm, X0, f) result = optimize(f, bounds, algorithm) ``` -------------------------------- ### Select best alternative from optimization results Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/mcdm.md Example of using `best_alternative` to find the best solution from an optimization run based on specified weights and the TopsisMethod. ```julia-repl julia> f, bounds, _ = Metaheuristics.TestProblems.ZDT1(); julia> res = optimize(f, bounds, NSGA2()); julia> best_sol = best_alternative(res, [0.5, 0.5], TopsisMethod()) (f = [0.32301132058506055, 0.43208538139854685], g = [0.0], h = [0.0], x = [3.230e-01, 1.919e-04, …, 1.353e-04]) ``` -------------------------------- ### Install Plots.jl Package Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Install the Plots.jl package using the Pkg prompt or directly in Julia. ```julia pkg> add Plots ``` ```julia julia> import Pkg; Pkg.add("Plots") ``` -------------------------------- ### Compare Performance of Multiple Algorithms Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md This example compares the performance of different metaheuristic algorithms (ECA, DE, PSO, ABC) on the same continuous optimization problem. It prints the minimum value found, number of function calls, and execution time for each algorithm. ```julia using Metaheuristics # Define problem f(x) = sum(x.^2) bounds = boxconstraints(lb = -10ones(5), ub = 10ones(5)) # Test multiple algorithms algorithms = [ ("ECA", ECA()), ("DE", DE()), ("PSO", PSO()), ("ABC", ABC()) ] println("Algorithm Performance Comparison") println("-" ^ 50) for (name, algo) in algorithms result = optimize(f, bounds, algo) println("$name:") println(" Minimum: $(minimum(result))") println(" F-calls: $(result.f_calls)") println(" Time: $(result.final_time - result.start_time) s") println() end ``` -------------------------------- ### Perform MCDM using a population Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/mcdm.md Example of applying an MCDM method (TopsisMethod) to a population obtained from a test problem. It shows how to retrieve the best alternative from the results. ```julia-repl julia> _, _, population = Metaheuristics.TestProblems.ZDT1(); julia> dm = mcdm(population, [0.5, 0.5], TopsisMethod()); julia> population[dm.bestIndex] (f = [0.5353535353535354, 0.2683214262030523], g = [0.0], h = [0.0], x = [5.354e-01, 0.000e+00, …, 0.000e+00]) ``` -------------------------------- ### Solve Knapsack Problem with GA Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md This example solves the Knapsack Problem using the Genetic Algorithm (GA). It defines items with profits and weights, a knapsack capacity, and then optimizes to find the items that maximize profit within the capacity. ```julia using Metaheuristics # define items and capacity items = Dict( "gold" => (profit=1000, weight=1), "silver" => (profit=500, weight=2), "bronze" => (profit=250, weight=4), "laptop" => (profit=800, weight=3), "camera" => (profit=600, weight=2), "necklace" => (profit=300, weight=1), "watch" => (profit=400, weight=1) ) capacity = 7 names = collect(keys(items)) profit = [items[k].profit for k in names] weight = [items[k].weight for k in names] # load the test problem using the provided parameters # by default, the problem is encoded as a permutation f, search_space, optimum = Metaheuristics.TestProblems.knapsack(profit, weight, capacity) population_size = 100 ga = GA( N = population_size, initializer = RandomPermutation(N=population_size), crossover = OrderCrossover(), # crossover for permutation encoding mutation = SlightMutation() ) # Solve with GA result = optimize(f, search_space, ga) selected_items = minimizer(result)[1:findfirst(w -> w > capacity, cumsum(weight[minimizer(result)]))-1] # table with the selected items println("Item Weight Value") for i in selected_items println("$(names[i]) $(weight[i]) $(profit[i])") end println("Total value: ", -minimum(result)) # negative because we minimize ``` -------------------------------- ### Constrained Optimization Example Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Solve a constrained optimization problem, defining the objective function, inequality constraints (gx), and equality constraints (hx). The bounds are also specified. ```julia using Metaheuristics function f(x) x,y = x[1], x[2] fx = (1-x)^2+100(y-x^2)^2 gx = [x^2 + y^2 - 2] # inequality constraints hx = [0.0] # equality constraints # order is important return fx, gx, hx end bounds = boxconstraints(lb = [-2.0, -2.0], ub = [2.0, 2.0]) optimize(f, bounds, ECA(N=30, K=3)) ``` -------------------------------- ### Get Optimal Permutation for 8-Queens Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/n-queens.md Retrieves the permutation representing the optimal chessboard configuration for the 8-Queens problem from an optimization result. ```julia perm = minimizer(result) ``` -------------------------------- ### Get Minimum Attacks for 8-Queens Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/n-queens.md Retrieves the minimum number of attacks found for the 8-Queens problem from an optimization result. ```julia n_attacks = minimum(result) ``` -------------------------------- ### Multi-Objective Optimization Example Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Solve a multi-objective optimization problem. The objective function returns multiple objective values (fx1, fx2). Inequality (gx) and equality (hx) constraints are also defined. ```julia using UnicodePlots # to visualize in console (optional) using Metaheuristics function f(x) # objective functions v = 1.0 + sum(x .^ 2) fx1 = x[1] * v fx2 = (1 - sqrt(x[1])) * v fx = [fx1, fx2] # constraints gx = [0.0] # inequality constraints hx = [0.0] # equality constraints # order is important return fx, gx, hx end bounds = boxconstraints(lb = zeros(30), ub = ones(30)) optimize(f, bounds, NSGA2()) ``` -------------------------------- ### Using ECA with Custom Stopping Criteria Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md This example demonstrates how to use the ECA algorithm with the custom stopping criteria defined previously. It defines a simple objective function, sets up box constraints, and then calls `optimize` with ECA. The custom stop message is printed to the console. ```julia f(x) = sum(x.^2) bounds = boxconstraints(lb = -5ones(10), ub = 5ones(10)) result = optimize(f, bounds, ECA()) println(result.stop_msg) ``` -------------------------------- ### Interactive Pareto Front Plot with Makie Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Creates an interactive 2D Pareto front plot using GLMakie.jl, allowing for zooming, panning, and hovering. Requires GLMakie to be installed. ```julia # Note: Install GLMakie first # using Pkg; Pkg.add("GLMakie") using GLMakie using Metaheuristics # Optimize f, bounds, true_pf = Metaheuristics.TestProblems.ZDT1() result = optimize(f, bounds, NSGA2()) # Get fronts approx_pf = pareto_front(result) true_front = pareto_front(true_pf) # Create interactive plot fig = Figure(resolution=(800, 600)) ax = Axis(fig[1, 1], xlabel="f₁", ylabel="f₂", title="Interactive Pareto Front") # Plot scatter!(ax, true_front[:, 1], true_front[:, 2], label="True Front", color=:blue, markersize=5) scatter!(ax, approx_pf[:, 1], approx_pf[:, 2], label="Approximation", color=:red, markersize=8) axislegend(ax, position=:rt) display(fig) ``` -------------------------------- ### Complete Optimization Workflow in a Function Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/simple-tutorial.md Encapsulates the entire optimization process, including function definition, bounds, information, options, algorithm setup, and optimization execution, within a reusable Julia function. ```julia using Metaheuristics function main() # objective function f(x) = 10length(x) + sum( x.^2 - 10cos.(2π*x) ) # limits/bounds bounds = BoxConstrainedSpace(lb = -5ones(10), ub = 5ones(10)) # information on the minimization problem information = Information(f_optimum = 0.0) # generic settings options = Options(f_calls_limit = 9000*10, f_tol = 1e-5) # metaheuristic used to optimize algorithm = ECA(information = information, options = options) # start the minimization process result = optimize(f, bounds, algorithm) fx = minimum(result) x = minimizer(result) x, fx end main() ``` -------------------------------- ### Solve Traveling Salesman Problem (TSP) with GA Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md This example demonstrates solving the Traveling Salesman Problem using the Genetic Algorithm (GA) with order crossover. It defines a distance matrix, an objective function for tour cost, and then optimizes the tour. ```julia using Metaheuristics # Distance matrix for 5 cities distances = [ 0.0 10.0 15.0 20.0 25.0; 10.0 0.0 35.0 25.0 30.0; 15.0 35.0 0.0 30.0 20.0; 20.0 25.0 30.0 0.0 15.0; 25.0 30.0 20.0 15.0 0.0 ] # Objective: minimize tour length function tsp_cost(tour) n = length(tour) total = sum(distances[tour[i], tour[i+1]] for i in 1:n-1) total += distances[tour[end], tour[1]] # return to start return total end # Solve using GA with order crossover n_cities = 5 population_size = 100 ga = GA( N = population_size, initializer = RandomPermutation(N=population_size), crossover = OrderCrossover(), # crossover for permutation encoding mutation = SlightMutation() ) result = optimize(tsp_cost, PermutationSpace(n_cities), ga) best_tour = minimizer(result) tour_length = minimum(result) println("Best tour: ", best_tour) println("Tour length: ", tour_length) ``` -------------------------------- ### Define Bilevel Optimization Objective Functions Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Define the objective functions for the upper-level (leader) and lower-level (follower) problems in a bilevel optimization setup. Ensure necessary packages are imported. ```julia using BilevelHeuristics F(x, y) = sum(x.^2) + sum(y.^2) bounds_ul = boxconstraints(lb = -ones(5), ub = ones(5)) ``` ```julia f(x, y) = sum((x - y).^2) + y[1]^2 bounds_ll = boxconstraints(lb = -ones(5), ub = ones(5)) ``` -------------------------------- ### Construct Method Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the construct method within Metaheuristics. ```julia ```@docs Metaheuristics.construct ``` ``` -------------------------------- ### Define Objective Function Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/index.md Define the objective function to be minimized. This example uses the Rastrigin function. ```julia f(x) = 10length(x) + sum( x.^2 - 10cos.(2π*x) ) nothing # hide ``` -------------------------------- ### Get Minimum Objective Value Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/simple-tutorial.md Retrieves the approximated minimum value of the objective function found by the optimization process. ```julia fx = minimum(result) ``` -------------------------------- ### WOA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the Whale Optimization Algorithm (WOA), a nature-inspired metaheuristic mimicking whale social behavior. ```julia ```@docs WOA ``` ``` -------------------------------- ### Get Minimum Value Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/index.md Retrieve the minimum value found by the optimization process from the `State` object returned by `optimize`. ```julia minimum(result) ``` -------------------------------- ### Get Problem Function Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/problems.md Retrieves a specific test problem. Used to access various optimization problem definitions. ```julia Metaheuristics.TestProblems.get_problem ``` -------------------------------- ### SHADE Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the SHADE algorithm. ```julia ```@docs SHADE ``` ``` -------------------------------- ### Define Objective Function for Minimization Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Define a single-objective function to be minimized. This example uses a custom function `f(x)`. ```julia f(x) = 10length(x) + sum( x.^2 - 10cos.(2π*x) ) ``` -------------------------------- ### GRASP Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the Greedy Randomized Adaptive Search Procedure (GRASP). ```julia ```@docs GRASP ``` ``` -------------------------------- ### Get Minimizer (Optimal Input) Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/simple-tutorial.md Retrieves the input vector (minimizer) that yields the approximated minimum objective function value. ```julia x = minimizer(result) ``` -------------------------------- ### Continue Optimization with optimize! Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/faq.md Use `optimize!` to resume optimization from the current state of a previous result. This is useful for warm-starting or implementing adaptive optimization strategies. ```julia result = optimize(f, bounds, ECA()) # fresh start optimize!(result, f, bounds) # continue from result ``` -------------------------------- ### SPEA2 Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/multiobjective.md Displays documentation for the SPEA2 algorithm, an improved strength Pareto evolutionary algorithm. ```julia using Metaheuristics # Example usage would go here, referencing SPEA2 ``` -------------------------------- ### Get Minimizer Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/index.md Retrieve the input vector that yields the minimum value found by the optimization process from the `State` object returned by `optimize`. ```julia minimizer(result) ``` -------------------------------- ### BRKGA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the Biased Random Key Genetic Algorithm (BRKGA). ```julia ```@docs BRKGA ``` ``` -------------------------------- ### SA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for Simulated Annealing (SA), a physics-inspired algorithm for optimization. ```julia ```@docs SA ``` ``` -------------------------------- ### Run Optimization Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/simple-tutorial.md Initiates the optimization process using the defined objective function, bounds, and algorithm. ```julia result = optimize(f, bounds, algorithm) ``` -------------------------------- ### NSGA-II Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/multiobjective.md Displays documentation for the NSGA-II algorithm, a fast and elitist multiobjective genetic algorithm. ```julia using Metaheuristics # Example usage would go here, referencing NSGA2 ``` -------------------------------- ### PSO Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for Particle Swarm Optimization (PSO), a population-based optimization technique inspired by flocking behavior. ```julia ```@docs PSO ``` ``` -------------------------------- ### Compare Convergence of Multiple Algorithms Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Sets up a comparison of multiple optimization algorithms (ECA, DE, PSO) on the same problem by defining the objective function and bounds. Requires Metaheuristics and Plots. ```julia using Metaheuristics using Plots gr() # Define test problem f(x) = sum(x.^2 .- 10cos.(2π*x)) .+ 10length(x) bounds = boxconstraints(lb = -5ones(10), ub = 5ones(10)) # Test multiple algorithms algorithms = [ ("ECA", ECA), ("DE", DE), ("PSO", PSO) ] ``` -------------------------------- ### Perform Multi-Objective Optimization and Decision Making Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Load a multi-objective test problem, perform optimization using NSGA2, define user preferences (weights), and then find the best alternative using CompromiseProgramming. ```julia # load the problem f, bounds, pf = Metaheuristics.TestProblems.ZDT1(); # perform multi-objective optimization res = optimize(f, bounds, NSGA2()); # user preferences w = [0.5, 0.5]; # set the decision-making algorithm dm_method = CompromiseProgramming(Tchebysheff()) # find the best decision sol = best_alternative(res, w, dm_method) (f = [0.38493217206706115, 0.38037042164979956], g = [0.0], h = [0.0], x = [3.849e-01, 7.731e-06, …, 2.362e-07]) ``` -------------------------------- ### Live Plotting Optimization Progress Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Demonstrates live plotting of optimization progress by using a logger function that updates a plot at each iteration. Requires Metaheuristics and Plots. ```julia import Metaheuristics: optimize, NSGA2, TestProblems, pareto_front, Options, fvals using Plots; gr() f, bounds, solutions = TestProblems.ZDT3(); pf = pareto_front(solutions) logger(st) = begin A = fvals(st) scatter(A[:, 1], A[:,2], label="NSGA-II", title="Gen: $(st.iteration)") plot!(pf[:, 1], pf[:,2], label="Parento Front", lw=2) gui() sleep(0.1) end result = optimize(f, bounds, NSGA2(options=Options(seed=0)), logger=logger) ``` -------------------------------- ### Parallel Evaluation of Objective Function Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/faq.md Enable parallel evaluation by defining a function that accepts a matrix of solutions (`X`) and returns a vector of objective values. Set `parallel_evaluation=true` in `Options` and start Julia with multiple threads. ```julia function f_parallel(X) # X is N×D matrix N = size(X, 1) fx = zeros(N) Threads.@threads for i in 1:N fx[i] = my_expensive_function(X[i,:]) end return fx end options = Options(parallel_evaluation=true) optimize(f_parallel, bounds, ECA(options=options)) ``` -------------------------------- ### Restart Mechanism Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the Restart mechanism, used to restart optimization when stagnation is detected. ```julia ```@docs Restart ``` ``` -------------------------------- ### MixedInteger Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the MixedInteger algorithm, often used for mixed-integer problems. ```julia ```@docs MixedInteger ``` ``` -------------------------------- ### Import Metaheuristics Methods Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/create-metaheuristic.md Import necessary base methods and specific genetic operators from the Metaheuristics module for implementing custom algorithms. ```julia # base methods using Metaheuristics import Metaheuristics: initialize!, update_state!, final_stage! import Metaheuristics: AbstractParameters, gen_initial_state, Algorithm, get_position # genetic operators import Metaheuristics: SBX_crossover, polynomial_mutation!, create_solution, is_better import Metaheuristics: reset_to_violated_bounds! ``` -------------------------------- ### set_user_solutions! Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md Allows setting specific user-defined solutions into the initial state of an optimization process. The exclamation mark suggests it modifies the state in-place. ```APIDOC ## set_user_solutions! ### Description Allows setting specific user-defined solutions into the initial state of an optimization process. The exclamation mark suggests it modifies the state in-place. ### Method Not specified (likely a function in Julia) ### Endpoint Not applicable (Julia function) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### VNS Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the General Variable Neighborhood Search (VNS) algorithm. ```julia ```@docs VNS ``` ``` -------------------------------- ### NSGA-III Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/multiobjective.md Displays documentation for the NSGA-III algorithm, an evolutionary many-objective optimization algorithm using a reference-point-based nondominated sorting approach. ```julia using Metaheuristics # Example usage would go here, referencing NSGA3 ``` -------------------------------- ### εDE Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for ε Constrained Differential Evolution (εDE), featuring gradient-based mutation. Note: Gradient mutation is not implemented. ```julia ```@docs εDE ``` ``` -------------------------------- ### Visualize Optimization Convergence Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Generates an animation to visualize the population and fitness convergence during an optimization process. Requires plotting and animation libraries. ```julia result = optimize(f, bounds, ECA(options=options)) f_calls, best_f_value = convergence(result) animation = @animate for i in 1:length(result.convergence) l = @layout [a b] p = plot( layout=l) X = positions(result.convergence[i]) scatter!(p[1], X[:,1], X[:,2], label="", xlim=(-5, 5), ylim=(-5,5), title="Population") x = minimizer(result.convergence[i]) scatter!(p[1], x[1:1], x[2:2], label="") # convergence plot!(p[2], xlabel="Generation", ylabel="fitness", title="Gen: $i") plot!(p[2], 1:length(best_f_value), best_f_value, label=false) plot!(p[2], 1:i, best_f_value[1:i], lw=3, label=false) x = minimizer(result.convergence[i]) scatter!(p[2], [i], [minimum(result.convergence[i])], label=false) end # save in different formats # gif(animation, "anim-convergence.gif", fps=30) mp4(animation, "anim-convergence.mp4", fps=30) ``` -------------------------------- ### MOEA/D-DE Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/multiobjective.md Displays documentation for the MOEA/D-DE algorithm, designed for multiobjective optimization problems with complicated Pareto sets. ```julia using Metaheuristics # Example usage would go here, referencing MOEAD_DE ``` -------------------------------- ### CCMO Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/multiobjective.md Displays documentation for the CCMO algorithm, a coevolutionary framework for constrained multiobjective optimization problems. ```julia using Metaheuristics # Example usage would go here, referencing CCMO ``` -------------------------------- ### Choose and Configure Metaheuristic Algorithm Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/simple-tutorial.md Selects a metaheuristic algorithm (ECA in this case) and configures it with problem information and general options. ```julia algorithm = ECA(information = information, options = options) ``` -------------------------------- ### DE Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for Differential Evolution (DE), an evolutionary algorithm based on vector differences. ```julia ```@docs DE ``` ``` -------------------------------- ### ABC Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the Artificial Bee Colony (ABC) algorithm, an efficient method for numerical function optimization. ```julia ```@docs ABC ``` ``` -------------------------------- ### Methods for Solutions/Individuals Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md This section details functions for accessing and manipulating properties of individual solutions or individuals within a population. ```APIDOC ## Methods for Solutions/Individuals ### Description This section details functions for accessing and manipulating properties of individual solutions or individuals within a population. ### Method Not applicable (Documentation section) ### Endpoint Not applicable (Documentation section) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### GA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the Genetic Algorithm (GA). ```julia ```@docs GA ``` ``` -------------------------------- ### Run Genetic Algorithm Optimization Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/create-metaheuristic.md Sets up and runs a genetic algorithm optimization. It defines a test problem (Rastrigin function), instantiates the custom `MyGeneticAlgorithm`, and calls the `optimize` function to find the solution. ```julia function main() # test problem f, bounds, _ = Metaheuristics.TestProblems.rastrigin() # optimize and get the results res = optimize(f, bounds, MyGeneticAlgorithm()) display(res) end main() ``` -------------------------------- ### VND Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the Variable Neighborhood Descent (VND) algorithm. ```julia ```@docs VND ``` ``` -------------------------------- ### MCCGA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for Machine-coded Compact Genetic Algorithms (MCCGA), designed for real-valued optimization problems. ```julia ```@docs MCCGA ``` ``` -------------------------------- ### GreedyRandomizedConstructor Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the GreedyRandomizedConstructor within Metaheuristics. ```julia ```@docs Metaheuristics.GreedyRandomizedConstructor ``` ``` -------------------------------- ### sample Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md A general function for sampling from a search space or distribution. ```APIDOC ## sample ### Description A general function for sampling from a search space or distribution. ### Method Not specified (likely a function in Julia) ### Endpoint Not applicable (Julia function) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### Compare NSGA-II Pareto Front with True Front Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Optimizes the ZDT3 test problem using NSGA-II and plots the obtained Pareto front against the true Pareto front. Requires Metaheuristics, Plots, and test problem modules. ```julia import Metaheuristics: optimize, NSGA2, TestProblems, pareto_front, Options using Plots; gr() f, bounds, solutions = TestProblems.ZDT3(); result = optimize(f, bounds, NSGA2(options=Options(seed=0))) A = pareto_front(result) B = pareto_front(solutions) scatter(A[:, 1], A[:,2], label="NSGA-II") plot!(B[:, 1], B[:,2], label="Parento Front", lw=2) savefig("pareto.png") ``` -------------------------------- ### ECA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the Evolutionary Centers Algorithm (ECA), used for solving global optimization problems. ```julia ```@docs ECA ``` ``` -------------------------------- ### CSO Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the CSO algorithm. ```julia ```@docs CSO ``` ``` -------------------------------- ### Optimize and Visualize Multi-Objective Problem (ZDT6) Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Optimizes the ZDT6 test problem using the SMS-EMOA algorithm and visualizes the Pareto front and convergence error. Requires Metaheuristics, Plots, and specific test problem modules. ```julia import Metaheuristics: optimize, SMS_EMOA, TestProblems, pareto_front, Options import Metaheuristics.PerformanceIndicators: Δₚ using Plots; gr() # get test function f, bounds, pf = TestProblems.ZDT6(); # optimize using SMS-EMOA result = optimize(f, bounds, SMS_EMOA(N=70,options=Options(iterations=500,seed=0, store_convergence=true))) # true pareto front B = pareto_front(pf) # error to the true front err = [ Δₚ(r.population, pf) for r in result.convergence] # generate plots a = @animate for i in 1:5:length(result.convergence) A = pareto_front(result.convergence[i]) p = plot(B[:, 1], B[:,2], label="True Pareto Front", lw=2,layout=(1,2), size=(850, 400)) scatter!(p[1], A[:, 1], A[:,2], label="SMS-EMOA", markersize=4, color=:black, title="ZDT6") plot!(p[2], eachindex(err), err, ylabel="Δₚ", legend=false) plot!(p[2], 1:i, err[1:i], title="Generation $i") scatter!(p[2], [i], err[i:i]) end # save animation gif(a, "ZDT6.gif", fps=20) ``` -------------------------------- ### Perform MCDM using optimization results Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/mcdm.md Demonstrates applying an MCDM method to the results of an optimization process. The best alternative is identified from the population within the optimization results. ```julia-repl julia> f, bounds, _ = Metaheuristics.TestProblems.ZDT1(); julia> res = optimize(f, bounds, NSGA2()); julia> dm = mcdm(res, [0.5, 0.5], TopsisMethod()); julia> res.population[dm.bestIndex] (f = [0.32301132058506055, 0.43208538139854685], g = [0.0], h = [0.0], x = [3.230e-01, 1.919e-04, …, 1.353e-04]) ``` -------------------------------- ### SMS-EMOA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/multiobjective.md Displays documentation for the SMS-EMOA algorithm, an EMO algorithm that uses the hypervolume measure as a selection criterion. ```julia using Metaheuristics # Example usage would go here, referencing SMS_EMOA ``` -------------------------------- ### Compute Cost Method Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/combinatorial.md Provides documentation for the compute_cost method within Metaheuristics. ```julia ```@docs Metaheuristics.compute_cost ``` ``` -------------------------------- ### Select Best Solution from Pareto Front using MCDM Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/faq.md Use Multi-Criteria Decision Making (MCDM) methods, such as CompromiseProgramming or TopsisMethod, to select the best alternative from a Pareto front based on defined preferences (weights). ```julia # Define preferences (weights) w = [0.5, 0.5] # Use MCDM method best_sol = best_alternative(result, w, CompromiseProgramming()) # Or use JMcDM methods best_sol = best_alternative(result, w, TopsisMethod()) ``` -------------------------------- ### Solution Feasibility and Comparison Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md This section covers functions for determining the feasibility of solutions and comparing them based on objective values and dominance. ```APIDOC ## Solution Feasibility and Comparison ### Description This section covers functions for determining the feasibility of solutions and comparing them based on objective values and dominance. ### Method Not applicable (Documentation section) ### Endpoint Not applicable (Documentation section) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### Genetic Algorithm Constructor Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/create-metaheuristic.md Constructor for the `MyGeneticAlgorithm` parameters. It sets default values and returns an `Algorithm` object configured for the GA. ```julia function MyGeneticAlgorithm(;N = 100, p_crossover = 0.9, p_mutation = 0.1, information = Information(), options = Options() ) parameters = MyGeneticAlgorithm(N, p_crossover, p_mutation) Algorithm( parameters, information = information, options = options, ) end ``` -------------------------------- ### Batch Evaluation of Solutions Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Configure an optimization problem for parallel evaluation of solutions by defining the objective function to accept a matrix of solutions and setting `parallel_evaluation=true` in Options. This can significantly reduce computation time. ```julia f(X) = begin fx = sum(X.^2, dims=2) # objective function ∑x² gx = sum(X.^2, dims=2) .-0.5 # inequality constraints ∑x² ≤ 0.5 hx = zeros(0,0) # equality constraints fx, gx, hx end options = Options(parallel_evaluation=true) res = optimize(f, boxconstraints(lb = -10ones(5), ub = 10ones(5)), ECA(options=options)) ``` -------------------------------- ### Instantiate Bounds for Optimization Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/README.md Define the search space bounds for the optimization problem. Each coordinate must be between -5 and 5. ```julia D = 10 bounds = boxconstraints(lb = -5ones(D), ub = 5ones(D)) ``` -------------------------------- ### Optimize Bilevel Problem with BCA Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/examples.md Solve a bilevel optimization problem using the BCA algorithm. This requires defining the objective functions and their respective bounds for both the upper and lower levels. ```julia res = optimize(F, f, bounds_ul, bounds_ll, BCA()) ``` -------------------------------- ### Add Metaheuristics Package via Pkg API Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/index.md Alternatively, add the Metaheuristics package using the Pkg API in the Julia REPL. ```julia julia> import Pkg; Pkg.add("Metaheuristics") ``` -------------------------------- ### Initialize State Function Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/create-metaheuristic.md Implement this function to initialize the optimization state, including population members, based on provided parameters. It should return an initialized `State` object. ```julia function initialize!( status, # an initialized State (if applicable) parameters::AbstractParameters, problem, information, options, args...; kargs... ) # initialize the stuff here return State(0.0, zeros(0)) # replace this end ``` -------------------------------- ### Generate Chessboard Configuration from Permutation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/n-queens.md Converts a permutation-based solution into a boolean matrix representing the chessboard configuration for the 8-Queens problem. ```julia chessboard = zeros(Bool, N, N) for (i,j) = enumerate(perm); chessboard[i,j] = true;end chessboard ``` -------------------------------- ### Calculate Cardinality of Solution Spaces Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/n-queens.md Calculates the number of possible solutions for N-Queens using different space representations. Requires the Metaheuristics package. ```julia using Metaheuristics N = 8 # for 8-queens cardinality(BitArraySpace(N*N)) cardinality(PermutationSpace(N)) ``` -------------------------------- ### Options Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md Represents configuration options for an optimization algorithm. This type likely allows customization of algorithm parameters. ```APIDOC ## Options ### Description Represents configuration options for an optimization algorithm. This type likely allows customization of algorithm parameters. ### Method Not applicable (Julia type) ### Endpoint Not applicable (Julia type) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### Algorithm Parameters Constructor Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/create-metaheuristic.md A constructor function for the algorithm parameters structure. It initializes the parameters and returns an `Algorithm` object. ```julia # a "constructor" function XYZ(;N = 0, p_crossover = 0.9, p_mutation = 0.1) parameters = XYZ(N, p_crossover, p_mutation) Algorithm( parameters, information = information, options = options, ) end ``` -------------------------------- ### Convergence and Results Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md This section covers functions and types related to monitoring convergence and retrieving results from optimization processes. ```APIDOC ## Convergence and Results ### Description This section covers functions and types related to monitoring convergence and retrieving results from optimization processes. ### Method Not applicable (Documentation section) ### Endpoint Not applicable (Documentation section) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### Configure Optimization Options Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/simple-tutorial.md Sets common options for the metaheuristic, including limits on function evaluations and desired accuracy tolerance. ```julia options = Options(f_calls_limit = 9000*10, f_tol = 1e-5); nothing # hide ``` -------------------------------- ### Optimize 8-Queens using Genetic Algorithm Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/n-queens.md Finds an optimal solution for the 8-Queens problem using a Genetic Algorithm (GA). Requires the Metaheuristics package and defines the search space and objective function. ```julia using Metaheuristics # hide N = 8 optimize(attacks, PermutationSpace(N), GA); # hide result = optimize(attacks, PermutationSpace(N), GA) ``` -------------------------------- ### Initialize Metaheuristic State Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/create-metaheuristic.md Defines the initialization function for a custom genetic algorithm. It sets default iteration and function call limits if they are zero and then generates the initial state for the optimization process. ```julia function initialize!( status, parameters::MyGeneticAlgorithm, problem, information, options, args...; kargs... ) if options.iterations == 0 options.iterations = 500 end if options.f_calls_limit == 0 options.f_calls_limit = options.iterations * parameters.N + 1 end # gen_initial_state require that `parameters.N` is defined. return gen_initial_state(problem,parameters,information,options,status) end ``` -------------------------------- ### Multi-objective Utilities Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md This section provides utility functions for multi-objective optimization tasks. ```APIDOC ## Multi-objective Utilities ### Description This section provides utility functions for multi-objective optimization tasks. ### Method Not applicable (Documentation section) ### Endpoint Not applicable (Documentation section) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### Plot Algorithm Convergence Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Plots the convergence of multiple algorithms for a given objective function. Ensure 'store_convergence' is enabled in Options. ```julia p = plot(xlabel="Function Evaluations", ylabel="Best Fitness", title="Algorithm Comparison", yscale=:log10) for (name, algo) in algorithms options = Options(store_convergence=true, seed=1) algo_with_opts = algo(;options=options) result = optimize(f, bounds, algo_with_opts) f_calls, best_f = convergence(result) plot!(p, f_calls, best_f, label=name, lw=2) end savefig(p, "algorithm_comparison.png") ``` -------------------------------- ### Decision Space Animation with Plots.jl Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Animates the exploration of the decision space by a population over generations using Plots.jl. Requires 'store_convergence' to be enabled in Options. ```julia using Metaheuristics using Plots gr() # 2D optimization problem f(x) = (x[1] - 1)^2 + (x[2] + 1)^2 bounds = boxconstraints(lb = [-3.0, -3.0], ub = [3.0, 3.0]) options = Options(store_convergence=true, iterations=50, seed=1) result = optimize(f, bounds, PSO(options=options)) # Create contour background x_grid = range(-3, 3, length=50) y_grid = range(-3, 3, length=50) z_grid = [f([x, y]) for y in y_grid, x in x_grid] # Animate anim = @animate for (i, state) in enumerate(result.convergence) contour(x_grid, y_grid, z_grid, levels=20, xlabel="x₁", ylabel="x₂", title="Generation $i", colorbar=true) # Plot population X = positions(state) scatter!(X[:, 1], X[:, 2], label="Population", color=:red, markersize=4) # Plot best x_best = minimizer(state) scatter!([x_best[1]], [x_best[2]], label="Best", color=:yellow, markersize=10, markershape=:star) end gif(anim, "decision_space_animation.gif", fps=10) ``` -------------------------------- ### Visualize Optimization Results with Plots.jl Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/faq.md Utilize Plots.jl to visualize optimization outcomes. This includes plotting population positions, convergence curves, and Pareto fronts for multi-objective problems. ```julia using Plots # Get population positions X = positions(result) scatter(X[:,1], X[:,2]) # Plot convergence f_calls, best_f = convergence(result) plot(f_calls, best_f) # For multi-objective: Pareto front A = pareto_front(result) scatter(A[:,1], A[:,2]) ``` -------------------------------- ### Optimize with Parallel Single-Objective Function Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/tutorials/parallelization.md Executes the optimization using the parallelized objective function `f_parallel`. This demonstrates the speedup achieved by evaluating solutions concurrently across threads. ```julia-repl julia> options = Options(iterations=10, parallel_evaluation=true); julia> optimize(f_parallel, [-10ones(5) 10ones(5)], ECA(;options)) +=========== RESULT ===========' iteration: 10 minimum: -40.3347 minimizer: [-8.584413535451635, -7.376644826521645, -7.756398645618526, -9.066386783877238, -7.550888765058555] f calls: 350 total time: 90.2019 s stop reason: Maximum number of iterations exceeded. +============================+' ``` -------------------------------- ### Metaheuristics.compare Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md A general comparison function for solutions, likely returning a value indicating their relative order (e.g., better, worse, equal, incomparable). ```APIDOC ## Metaheuristics.compare ### Description A general comparison function for solutions, likely returning a value indicating their relative order (e.g., better, worse, equal, incomparable). ### Method Not specified (likely a function in Julia) ### Endpoint Not applicable (Julia function) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### CGSA Documentation Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/algorithms/singleobjective.md Displays documentation for the Chaotic Gravitational Search Algorithm (CGSA), featuring chaotic gravitational constants. ```julia ```@docs CGSA ``` ``` -------------------------------- ### 3D Pareto Front Visualization Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/visualization.md Generates a 3D scatter plot of the Pareto front for a three-objective optimization problem. Requires a multi-objective algorithm and a problem with 3 objectives. ```julia using Metaheuristics using Plots gr() # Three-objective problem (DTLZ2) f, bounds, pf = Metaheuristics.TestProblems.DTLZ2(3) # 3 objectives result = optimize(f, bounds, NSGA3(options=Options(seed=0))) # Get Pareto front A = pareto_front(result) # 3D scatter plot scatter(A[:,1], A[:,2], A[:,3], xlabel="f₁", ylabel="f₂", zlabel="f₃", title="3D Pareto Front - DTLZ2", label="Approximation", markersize=3, camera=(135, 45)) savefig("pareto_3d.png") ``` -------------------------------- ### Sampling Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md This section covers functions and types related to sampling strategies for generating initial populations or exploring search spaces. ```APIDOC ## Sampling ### Description This section covers functions and types related to sampling strategies for generating initial populations or exploring search spaces. ### Method Not applicable (Documentation section) ### Endpoint Not applicable (Documentation section) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ``` -------------------------------- ### Metaheuristics.create_child Source: https://github.com/jmejia8/metaheuristics.jl/blob/master/docs/src/api.md This function is likely responsible for creating a child solution from one or more parent solutions, typically used in evolutionary algorithms. ```APIDOC ## Metaheuristics.create_child ### Description This function is likely responsible for creating a child solution from one or more parent solutions, typically used in evolutionary algorithms. ### Method Not specified (likely a function in Julia) ### Endpoint Not applicable (Julia function) ### Parameters Not specified in source. ### Request Example Not applicable. ### Response Not specified in source. #### Success Response (200) Not specified in source. #### Response Example Not applicable. ```