Getting started¶
Install¶
pip install ypea
NumPy is the only required dependency. Two optional groups add more, for example pip install "ypea[plot]", and "ypea[all]" installs both:
| Group | Adds | Needed for |
|---|---|---|
ypea[plot] |
matplotlib | ypea.plot, the figures of experiment reports, plot_tour and plot_routes |
ypea[stats] |
SciPy | the Wilcoxon rank sum marks and the Friedman p values in experiment tables |
Download ypea-2.0.0.mltbx from the latest release and open it in MATLAB, which installs it as an add-on. Or clone smkalami/ypea and add its folder (the one that holds +ypea) to the path:
addpath("path/to/ypea")
YPEA for MATLAB needs R2021a or newer and no other toolbox. With the Parallel Computing Toolbox, experiments, tuning and solve(..., parallel=true) run in parallel.
Three steps¶
Define the problem, choose an algorithm, and call solve.
%%{init: {"flowchart": {"curve": "monotoneY"}}}%%
flowchart LR
A("1. Problem<br>variables and objective") --> B("2. Algorithm<br>settings and stopping rule")
B --> C("3. solve(problem, seed)")
C --> D("Result<br>best solution, history")
1. Define the problem. A problem has decision variables and an objective. Here the variable is x, ten real numbers in [-5.12, 5.12]. The objective gets a decoded solution, with one attribute per variable (so sol.x is the array of ten numbers), and returns a number. The default sense is minimization. Use sense="max" to maximize.
2. Choose an algorithm. Settings go to the constructor, which checks them. Every algorithm takes max_iter, pop_size, max_nfe, target, max_time and display. max_nfe is the budget: the run stops after this many evaluations of the objective (NFE means number of function evaluations). pop_size is the number of solutions a population algorithm works with in each iteration. Algorithms explains the other stopping rules.
3. Solve. solve runs the algorithm and returns a Result. The seed fixes the random numbers, so the same seed always gives the same result.
The code below does all three steps for the Rastrigin function, a standard test with many local minima. Its best value is 0, at x = 0.
import numpy as np
import ypea
def rastrigin(sol):
x = sol.x
return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
problem = ypea.Problem(ypea.Real("x", shape=10, lb=-5.12, ub=5.12), rastrigin)
de = ypea.DE(max_nfe=30_000, pop_size=50, crossover_prob=0.2) # 0.2 suits separable functions such as Rastrigin
result = de.solve(problem, seed=1)
print(result.summary())
print(result.best.solution.x.round(3))
DE on rastrigin
best objective value: 0
feasible: True (violation 0)
evaluations: 30000, iterations: 599, time: 0.506 s, stopped by: max_nfe
[-0. 0. 0. -0. -0. 0. -0. -0. -0. 0.]
problem = ypea.Problem(vars=ypea.Real("x", shape=10, lb=-5.12, ub=5.12), objective=@rastrigin);
de = ypea.DE(max_nfe=30000, pop_size=50, crossover_prob=0.2); % 0.2 suits separable functions such as Rastrigin
result = de.solve(problem, seed=1);
disp(result.summary())
disp(round(result.best.solution.x, 3))
function value = rastrigin(sol)
x = sol.x;
value = 10 * numel(x) + sum(x.^2 - 10 * cos(2 * pi * x));
end
DE on rastrigin
best objective value: 0
feasible: true (violation 0)
evaluations: 30000, iterations: 599, time: 2.03 s, stopped by: max_nfe
0 0 0 0 0 0 0 0 0 0
The summary names the algorithm and the problem, then gives the best objective value (0 is the global minimum of Rastrigin) and whether the best solution meets the constraints. This problem has none, so it is feasible with violation 0. The last line counts the evaluations and iterations, and says which limit stopped the run. The second print shows the best x, all zeros.
Try other algorithms¶
Every algorithm takes the same problem, so comparing them is a loop:
import numpy as np
import ypea
def rastrigin(sol):
x = sol.x
return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))
problem = ypea.Problem(ypea.Real("x", shape=10, lb=-5.12, ub=5.12), rastrigin)
algorithms = [
ypea.PSO(max_nfe=10_000),
ypea.GA(max_nfe=10_000),
ypea.LSHADE(max_nfe=10_000),
ypea.IPOPCMAES(max_nfe=10_000),
]
for alg in algorithms:
result = alg.solve(problem, seed=1)
print(f"{alg.short_name:12s} {result.best.obj_value:10.4g}")
PSO 7.299
GA 1.013
L-SHADE 1.208
IPOP-CMA-ES 11.94
Differs from Python: MATLAB draws its own random numbers, so the values differ from Python's.
problem = ypea.Problem(vars=ypea.Real("x", shape=10, lb=-5.12, ub=5.12), objective=@rastrigin);
algorithms = {
ypea.PSO(max_nfe=10000)
ypea.GA(max_nfe=10000)
ypea.LSHADE(max_nfe=10000)
ypea.IPOPCMAES(max_nfe=10000)
};
for k = 1:numel(algorithms)
alg = algorithms{k};
result = alg.solve(problem, seed=1);
fprintf("%-12s %10.4g\n", alg.short_name, result.best.obj_value);
end
function value = rastrigin(sol)
x = sol.x;
value = 10 * numel(x) + sum(x.^2 - 10 * cos(2 * pi * x));
end
PSO 10.36
GA 0.9969
L-SHADE 1.333
IPOP-CMA-ES 5.97
Each line gives the best value one algorithm found. Lower is better here, and 0 is the optimum. max_nfe gives every algorithm the same budget. One run proves little, so for a fair comparison with many runs, statistics and tables, use an experiment.
Constraints¶
The objective may also return constraint values g. A constraint holds when its value is at most 0. A solution that meets all constraints is feasible. This example finds the point of the unit circle closest to (2, 1):
import ypea
def circle(sol):
x, y = sol.x
f = (x - 2) ** 2 + (y - 1) ** 2
g = x**2 + y**2 - 1 # stay inside the unit circle
return f, g
problem = ypea.Problem(ypea.Real("x", shape=2, lb=-2, ub=2), circle)
result = ypea.LSHADE(max_nfe=5_000).solve(problem, seed=1)
print(result.best.solution.x.round(4), result.best.feasible)
[0.8944 0.4472] True
Differs from Python: a constrained objective returns [f, g] as two outputs.
problem = ypea.Problem(vars=ypea.Real("x", shape=2, lb=-2, ub=2), objective=@circle);
result = ypea.LSHADE(max_nfe=5000).solve(problem, seed=1);
disp(round(result.best.solution.x, 4))
disp(result.best.feasible)
function [f, g] = circle(sol)
x = sol.x(1);
y = sol.x(2);
f = (x - 2)^2 + (y - 1)^2;
g = x^2 + y^2 - 1; % stay inside the unit circle
end
0.8944 0.4472
1
The exact solution is (2, 1) / sqrt(5), about (0.8944, 0.4472), and True says the best solution is feasible. Objectives and constraints explains how feasible and infeasible solutions compare.
A combinatorial problem¶
Variables of other types work the same way. In a traveling salesman problem (TSP), a salesman visits every city once and returns home, and the goal is the shortest tour. ypea.problems.circle_tsp builds one with cities on a circle, so the best tour is known. Its solution is one permutation variable, tour, the order of the cities:
import ypea
problem = ypea.problems.circle_tsp(20, seed=1) # 20 cities on a circle
result = ypea.GA(max_nfe=20_000, space="native").solve(problem, seed=1)
print(result.best.obj_value, problem.optimum)
print(result.best.solution.tour)
250.29514406436937 250.2951440643694
[14 0 9 10 11 12 18 4 13 15 1 5 6 17 16 8 3 7 2 19]
Differs from Python: MATLAB draws its own cities, and tours count cities from 1.
problem = ypea.problems.circle_tsp(20, seed=1); % 20 cities on a circle
result = ypea.GA(max_nfe=20000, space="native").solve(problem, seed=1);
disp([result.best.obj_value, problem.optimum])
disp(result.best.solution.tour)
250.2951 250.2951
10 11 15 14 18 8 20 2 17 13 16 4 7 12 19 1 9 5 3 6
The first line shows the tour length found and the known optimum. They are equal up to rounding, so the tour is optimal. The second line is the tour itself, the cities by index from 0.
space="native" lets GA use crossovers and moves made for permutations. See Native operators.
Plot the convergence¶
A convergence plot shows the best value against the number of evaluations. It needs matplotlib (pip install "ypea[plot]"). This block saves the two plots of the figure below: the convergence of the TSP run to convergence.png, and its best tour to tour.png:
import ypea
problem = ypea.problems.circle_tsp(20, seed=1)
result = ypea.GA(max_nfe=20_000, space="native").solve(problem, seed=1)
ax = ypea.plot.convergence(result)
ax.figure.savefig("convergence.png")
ax = ypea.problems.plot_tour(problem, result)
ax.figure.savefig("tour.png")
Differs from Python: figures are saved with exportgraphics, here to tempdir.
problem = ypea.problems.circle_tsp(20, seed=1);
result = ypea.GA(max_nfe=20000, space="native").solve(problem, seed=1);
ax = ypea.plot.convergence(result);
exportgraphics(ax.Parent, fullfile(tempdir, "convergence.png"));
ax = ypea.problems.plot_tour(problem, result);
exportgraphics(ax.Parent, fullfile(tempdir, "tour.png"));

Examples¶
The examples folder of the repository has complete scripts:
| Script | What it shows |
|---|---|
sphere_pso.py |
PSO on the sphere function, constriction coefficients, a convergence plot |
sphere_all.py |
every single-objective algorithm on the sphere function |
max_problem.py |
a maximization problem with three variables |
knapsack.py |
a binary knapsack with a constraint, feasibility rules and a penalty |
tsp_sa.py |
a TSP solved with Simulated Annealing, with a plot of the tour |
tsp_ga_native.py |
GA and SA with native permutation operators, and custom operators |
ask_tell.py |
evaluating the solutions outside the toolbox with ask and tell |
variables.py |
every variable type with decoded samples |
experiment_cec2017.py |
three algorithms on CEC 2017 with tables and an HTML report |
Each runs in a few seconds, for example python examples/tsp_sa.py.
Next steps¶
- Problems and variables: every variable type.
- Algorithms: choosing one, stopping rules and seeds.
- Results and plots: what a run returns.
- Changes from the original toolbox, if you used it.