Problems, results and runs¶
All core classes are in the ypea namespace, for example ypea.Problem.
ypea.Problem¶
An optimization problem: decision variables, objective, and how solutions are compared.
problem = ypea.Problem(vars=..., objective=..., sense="min", ...)
vars One variable, or several in braces: {ypea.Real(...), ypea.Permutation(...)}.
Square brackets also work. Names must be unique.
objective Called with a decoded solution (a struct with one field per
variable). Returns the objective value f, or [f, g] where g
holds inequality constraints (each satisfied when g <= 0), or
[f, g, h] where h holds equality constraints (each satisfied
when h is close to 0, see equality_atol). g may be [] when
there are only equalities. Pass [] to evaluate the solutions
yourself (ask and tell).
outputs Number of outputs of the objective: 1, 2 or 3. Needed only
for a one-line function @(sol) ... that returns constraints,
because MATLAB cannot tell how many values it returns. A
named function needs nothing.
sense "min" or "max", or one per objective.
n_obj Number of objectives (default 1, or the number of senses).
vectorized If true, the objective is called once per batch with a
solution whose fields have one row per solution, and returns
f as an n x 1 column (n x n_obj with several objectives) and g
and h with one row per solution.
constraints "feasibility" (default, Deb's rules) or "penalty".
penalty Penalty coefficient for constraints="penalty" (default 1e6).
equality_atol, equality_rtol, equality_scale
An equality h = 0 counts as satisfied when
|h| <= atol + rtol * scale. Otherwise its violation
|h| - (atol + rtol * scale) adds to the total. Defaults 1e-4
(the CEC rule), 1e-6 and 1 (one value, or one per equality).
constraint_scaling true (default): each constraint is divided by its
largest violation among the first solutions of a run (at least
20), so constraints of different sizes count alike. false adds
the raw violations. A list gives fixed scales, one per
constraint (the inequalities, then the equalities).
name Name for results and reports.
optimum Known optimal objective value. Results then report the error.
info A struct of free metadata.
evaluate¶
Objective value and total (unscaled) violation of one decoded solution.
random_codes¶
n random code vectors in [0, 1], drawn with the ypea.Rng rng.
encode¶
Code vector of a solution given as a struct of variable values.
decode_one¶
Decode one code vector into a solution struct.
decode¶
Decode codes (n x code_size).
Returns an n x 1 struct array of solutions, or one struct
with batch fields when the problem is vectorized.
| Property | Meaning |
|---|---|
vars |
cell array of variables |
objective |
function handle, or [] |
outputs |
1, 2 or 3, or [] to find out at the first evaluation |
sense |
"min" or "max", or a string array with one per objective |
n_obj |
number of objectives |
vectorized |
true when the objective takes a batch |
constraints |
"feasibility" or "penalty" |
penalty |
penalty coefficient |
comparator |
ypea.Comparator |
equality_atol |
absolute tolerance of the equality constraints |
equality_rtol |
relative tolerance of the equality constraints |
equality_scale |
scale of the relative tolerance, one value or one per equality |
constraint_scaling |
true, false, or a row of fixed scales |
name |
problem name |
optimum |
known optimal value, or [] |
code_size |
total number of codes |
info |
struct of free metadata |
Solution¶
Not in this toolbox under this name. A solution is a struct with one field per variable (sol.x), not a Solution object.
Writing your own algorithm by subclassing ypea.Algorithm is provisional: the methods below are stable, but the helpers that the built-in algorithms use may change.
ypea.Algorithm¶
Base class of all algorithms.
Settings are given as name-value pairs when the algorithm is made,
for example ypea.RandomSearch(max_nfe=5000, pop_size=50), and can be
changed later as properties. solve(problem) runs the algorithm and
returns a ypea.Result.
Common settings
max_iter Maximum number of iterations. If empty (the default),
the run is limited only by max_nfe and max_time, and when
neither is set, max_iter is 100.
pop_size Population size.
max_nfe Maximum number of objective evaluations. Never exceeded.
target Stop when a feasible solution at least this good is found.
max_time Stop after this many seconds (checked between iterations).
display Print one line per iteration.
x0 Starting solutions: code rows in [0, 1] (1 x d or k x d),
decoded solutions (structs), ypea.Individual objects, or a
ypea.Result, alone or in a cell array. They become the first
members of the initial population, and the rest is random.
local_search An algorithm, or empty (default). Makes the run memetic:
each newly evaluated solution is improved, with probability
local_search_prob (default 0.1), by a short run of this
algorithm (for example ypea.HillClimbing()) of at most
local_search_nfe evaluations (default 100), started from
it. The solution is replaced by the best of that run when
it is better. Single-solution methods and Sequence do not
take local_search.
During a run, callbacks can read iter, nfe, best, pop, problem,
front, rng and seed.
solve¶
Solve problem and return a ypea.Result.
result = alg.solve(problem, seed=1, callbacks={...}, keep_evaluations=false, parallel=false)
The same integer seed gives the same result. A callback is a
function of the algorithm, called after every iteration (it
stops the run by returning true), or a ypea.callbacks.Callback
object. With parallel=true, each batch of solutions is evaluated
with parfor on the current parallel pool (MATLAB starts one if
needed), for a slow objective. It needs the Parallel Computing
Toolbox and runs serially without it. The result is the same as
without it. Vectorized problems ignore it.
ask_tell¶
Start a run whose solutions you evaluate yourself, and return its ypea.AskTell.
run = alg.ask_tell(problem, seed=1, callbacks={...}, keep_evaluations=false)
run.ask() gives the next batch of decoded solutions, run.tell(f), run.tell(f, g)
or run.tell(f, g, h) takes their values, and run.result() gives the same
ypea.Result that solve gives with the same values and seed. The run uses a
copy of this algorithm. The problem may have no objective. See ypea.AskTell.
params¶
The settings of this algorithm, as a struct.
validate¶
Check the settings. Subclasses extend it and call validate@ypea.Algorithm(obj).
initialize¶
ypea.Algorithm/initialize is a function.
obj = ypea.Algorithm
iterate¶
ypea.Algorithm/iterate is a function.
obj = ypea.Algorithm
request_stop¶
Stop the run after the current iteration, with reason as the stop reason.
progress¶
Fraction of the run used before the current iteration, from 0 to 1.
planned_iterations¶
Expected number of iterations, for schedules that must end with the run.
result_extra¶
Algorithm specific information for Result.extra (override it).
check_problem¶
Check settings that depend on the problem (override it).
dominates¶
Element-wise: does a dominate b? A one-row population is compared with every row.
nondominated_sort¶
Front of each solution, 0 for the non-dominated ones (Deb et al. 2002).
crowding_distance¶
Crowding distance of each solution within its front (Deb et al. 2002).
| Property | Meaning |
|---|---|
name |
full name of the algorithm |
short_name |
short name, used in results |
max_iter |
maximum number of iterations, or [] (see the class help) |
pop_size |
population size |
max_nfe |
maximum number of objective evaluations, or [] for no limit |
target |
stop when a feasible solution at least this good is found, or [] |
max_time |
stop after this many seconds, or [] |
display |
print one line per iteration |
x0 |
starting solutions, or [] (see the class help) |
local_search |
an algorithm that improves new solutions (a memetic run), or [] |
local_search_prob |
chance that a new solution gets a local search |
local_search_nfe |
evaluations of each local search, at most |
problem |
the problem of the current run |
seed |
the seed of the current run |
rng |
the run's ypea.Rng |
iter |
the current iteration (0 during initialization) |
pop |
the current population |
nfe |
evaluations so far |
best |
the best solution so far, a ypea.Population of one row |
front |
the non-dominated solutions so far (several objectives) |
ypea.AskTell¶
A run whose solutions you evaluate yourself. Create it with Algorithm.ask_tell.
run = ypea.PSO(max_nfe=500).ask_tell(problem, seed=0);
while ~run.done
solutions = run.ask();
f = zeros(numel(solutions), 1);
for i = 1:numel(solutions)
f(i) = my_objective(solutions(i));
end
run.tell(f);
end
result = run.result();
ask() returns the next batch of decoded solutions, a struct array (for
a vectorized problem, one struct whose fields hold the whole batch,
one row per solution). Their codes are in codes. tell takes what the
objective would return, for the whole batch:
run.tell(f), run.tell(f, g) or run.tell(f, g, h)
f has one row per solution (n x n_obj), and so do g (inequality
constraints) and h (equality constraints). Each of them may also be a
cell array with one entry per solution, for example when solutions
return different numbers of constraints. For a vectorized problem the
arguments are exactly what the objective would return for the batch.
The batch size changes from call to call (some algorithms ask for one
solution at a time), and the run never asks for more than max_nfe
evaluations. Told the true values, the run gives exactly the Result
that solve gives with the same seed.
How it works: MATLAB has no threads, so each ask replays the run from
its start with the same seed, answers every batch already told from
memory, and stops at the first batch with no values yet. The
objective is never evaluated twice, but the algorithm's own work is
repeated on every ask, so a run of B batches costs about B times B / 2
batches of algorithm work. Callbacks and display lines run once each,
at the same points as in solve. A callback that changes the algorithm's
settings during the run is not supported (the change is lost on the
next replay). The clock is replayed too, so max_time counts the time
spent evaluating, as in solve.
Properties: done (true when the run has ended, then result() gives its
Result), codes (codes of the batch that ask() returned last, n x
code_size) and algorithm (the copy of the algorithm that runs, to
read iter or pop while the run waits for values).
ask¶
The next batch of decoded solutions to evaluate (their codes are in codes).
tell¶
Give the values of the batch that ask() returned, in the same order.
run.tell(f), run.tell(f, g) or run.tell(f, g, h). The run then continues
until it asks for the next batch or ends. An error of the algorithm or
of a callback is raised here.
stop¶
End the run now and return its Result, with reason (default "stopped")
as the stop reason.
result¶
The ypea.Result of the run, once it is done.
| Property | Meaning |
|---|---|
done |
true when the run has ended, then result() gives its Result |
codes |
codes of the batch that ask() returned last, n x code_size |
algorithm |
the copy of the algorithm that runs, to read iter or pop between calls |
ypea.Result¶
What Algorithm.solve returns.
best is the best solution by the problem's comparison rules (with
constraints="penalty" it may be infeasible). best_feasible is the
best feasible solution by objective value alone, or empty when no
feasible solution was found. With the default feasibility rules it
equals best once a feasible solution exists.
With several objectives, best and best_feasible are empty, and front
holds the non-dominated solutions (a ypea.Front).
evaluations holds every evaluated solution when the run was started
with keep_evaluations=true. constraint_scale holds the scale of each
constraint (the inequalities, then the equalities) when the problem
scales its constraints. Every violation in the result is the sum of
the violations divided by these scales.
summary¶
A short text summary: the best value (or the front), the budget used and the stop reason.
to_dict¶
Plain data, ready for jsonencode: settings, seed, best solution (or the
front), history and trace, and the evaluations when they were kept. The
same fields as Python's Result.to_dict. Non-finite numbers become the text
"inf", "-inf" or "nan".
| Property | Meaning |
|---|---|
best |
ypea.Individual, or [] with several objectives |
history |
ypea.History |
algorithm |
short name of the algorithm |
params |
struct of the algorithm settings |
problem |
name of the problem |
seed |
the seed of the run ([] when none was given) |
nfe |
number of objective evaluations |
iterations |
number of iterations |
run_time |
seconds |
stop_reason |
"max_iter", "max_nfe", "max_time", "target", "callback", ... |
optimum |
known optimal value of the problem, or [] |
extra |
algorithm specific information |
front |
ypea.Front: the non-dominated solutions (several objectives), or [] |
best_feasible |
ypea.Individual, or [] |
evaluations |
ypea.Evaluations, or [] |
constraint_scale |
scale of each constraint, or [] |
error |
distance of the best objective value from the known optimum, or [] |
ypea.History¶
Per iteration records, plus the exact trace of improvements.
iteration, nfe, best_obj_value, best_violation and time have one
entry per iteration (iteration 0 is the initialization). trace_nfe,
trace_obj_value and trace_violation have one entry per improvement
of the best. trace_feasible_nfe and trace_feasible_obj_value have
one entry per improvement of the best feasible solution.
With several objectives, best_obj_value is NaN, best_violation is the
smallest violation in the front, and archive_size gives the size of
the front, all per iteration. The trace then logs the front exactly:
one entry per solution that entered it, with trace_obj_value of size
entries x n_obj, and trace_removed_nfe the NFE at which that solution
left the front (-1 if it is still there). front_at(nfe) rebuilds the
front at any number of evaluations, for example to compute an indicator.
front_mask¶
Several objectives: a logical column marking the trace entries
that formed the front after nfe evaluations, for example
trace_violation(mask).
front_at¶
Several objectives: the objective values of the front after nfe
evaluations, one row per solution.
at_nfe¶
Best objective value found within each number of evaluations in points.
A number for a single point, an array of the same size for
several. NaN before the first evaluation. One objective only.
| Property | Meaning |
|---|---|
iteration |
iteration number, one per iteration (0 is the initialization) |
nfe |
evaluations used at the end of each iteration |
best_obj_value |
best objective value at each iteration (NaN with several objectives) |
best_violation |
violation of the best at each iteration (several objectives: the smallest in the front) |
time |
seconds since the start, at each iteration |
trace_nfe |
evaluation number of each improvement (several objectives: of each front entry) |
trace_obj_value |
objective value of each improvement (several objectives: entries x n_obj) |
trace_violation |
violation of each improvement |
trace_feasible_nfe |
evaluation number of each improvement of the best feasible solution |
trace_feasible_obj_value |
objective value of each improvement of the best feasible solution |
archive_size |
several objectives: size of the front at each iteration |
trace_removed_nfe |
several objectives: NFE at which each trace entry left the front, or -1 |
ypea.Front¶
The non-dominated solutions of a multi-objective run (Result.front).
positions is k x code_size, obj_values k x n_obj and violations k x 1.
solutions holds the k decoded solutions (a struct array). The rows
are sorted by the first objective (then the second, and so on), best
first. front.at(i) gives a ypea.Individual whose obj_value is a row.
at¶
The i-th solution as a ypea.Individual.
length¶
length - Length of largest array dimension
Syntax
L = length(X)
Input Arguments
X - Input array
scalar | vector | matrix | multidimensional array
Examples
openExample('matlab/NumberofVectorElementsExample')
openExample('matlab/LengthofRectangularMatrixExample')
openExample('matlab/StringArrayExample')
openExample('matlab/LengthofStructureFieldsExample')
See also strlength, ndims, numel, size
Introduced in MATLAB before R2006a
| Property | Meaning |
|---|---|
positions |
codes, one row per solution (k x code_size) |
obj_values |
objective values, k x n_obj |
violations |
total constraint violations, k x 1 |
solutions |
the decoded solutions, a struct array |
feasible |
true for each feasible solution |
ypea.Evaluations¶
Every evaluated solution of a run, in evaluation order.
nfe is the evaluation number of each row (1, 2, ...), positions the
codes, obj_values the objective values and violations the total
constraint violations. Non-finite objective values are stored as the
worst value, as the run saw them. Use rows(idx) to filter or sort, and
problem.decode(ev.positions) to decode.
to_dict¶
Plain data of every field, ready for jsonencode.
rows¶
The evaluations at idx (indices or a logical mask).
length¶
length - Length of largest array dimension
Syntax
L = length(X)
Input Arguments
X - Input array
scalar | vector | matrix | multidimensional array
Examples
openExample('matlab/NumberofVectorElementsExample')
openExample('matlab/LengthofRectangularMatrixExample')
openExample('matlab/StringArrayExample')
openExample('matlab/LengthofStructureFieldsExample')
See also strlength, ndims, numel, size
Introduced in MATLAB before R2006a
| Property | Meaning |
|---|---|
nfe |
evaluation number of each row (1, 2, ...) |
positions |
codes, one row per evaluated solution |
obj_values |
objective values (non-finite ones stored as the worst value) |
violations |
total constraint violations |
feasible |
true for each row whose violation is 0 |
ypea.scalarize¶
A single-objective problem from a multi-objective one, to minimize.
q = ypea.scalarize(problem, weights, method="weighted_sum", ideal=[])
weights One nonnegative weight per objective, not all zero.
method "weighted_sum" minimizes sum(w_i * s_i * f_i), with s_i = 1 for an
objective to minimize and -1 for one to maximize. It finds only
points on the convex parts of the front. "tchebycheff" minimizes
max(w_i * |f_i - z_i|) (Zhang and Li 2007), which can reach every
point of the front.
ideal The ideal point z for "tchebycheff", in the units of the
objectives: a value at least as good as the best possible value
of each objective. Required for "tchebycheff".
The new problem has the same variables, constraints and settings. Its
objective calls the original one and combines the values, so constraint
values pass through. info.scalarized holds the weights, method and ideal.
Example:
single = ypea.scalarize(problem, [0.5 0.5]);
result = ypea.PSO(max_nfe=5000).solve(single, seed=1);
method and ideal may come by position (method is text, so parse_args cannot tell it from a name)
ypea.Individual¶
One solution: its codes, decoded solution, objective value and constraint violation.
| Property | Meaning |
|---|---|
position |
codes in [0, 1], a row |
solution |
the decoded solution, a struct with one field per variable |
obj_value |
objective value (a row with several objectives) |
violation |
total constraint violation, 0 when feasible |
feasible |
true when the violation is 0 |
ypea.Population¶
A set of solutions stored as arrays.
X holds the codes in [0, 1] (n x d), F the objective values (n x m,
m = 1 with one objective) and V the total constraint violation
(n x 1, 0 when feasible).
replace¶
Rows where mask is true come from the same rows of other.
rows¶
The solutions at idx (indices or a logical mask).
length¶
Number of solutions.
concat¶
Join populations, in order.
| Property | Meaning |
|---|---|
X |
- codes, n x d |
F |
- objective values, n x m |
V |
- total constraint violation, n x 1 |
obj_value |
objective value of each row (the first column of F) |
violation |
constraint violation of each row (the same as V) |
Best¶
Not in this toolbox under this name. The best solution so far (alg.best) is a one-row ypea.Population, with F(1) and V(1) in place of Best's obj_value and violation.
ypea.Comparator¶
Compares solutions by the sense of the objectives and the constraint handling.
This is the only code that knows about min or max and constraints.
Solutions are compared by two keys, both minimized, in order:
"feasibility" (Deb 2000): first the total constraint violation,
then the objective. A feasible solution beats an infeasible one.
"penalty": first the penalized objective f + penalty * violation,
then the violation.
F has one row per solution (n x 1 with one objective), V is n x 1.
dominates¶
Element-wise: does solution 1 dominate solution 2? One row of
either side is compared with every row of the other. F has one row per
solution (n x n_obj), V is n x 1. rule is the constraint handling,
"feasibility" or "penalty", by default the comparator's own.
"feasibility" (constrained domination, Deb et al. 2002): a feasible
solution dominates an infeasible one, an infeasible one dominates another
with a larger violation, and two feasible ones are compared by Pareto
dominance. Two infeasible solutions with exactly the same violation are
also compared by Pareto dominance (the paper leaves both non-dominated).
"penalty": Pareto dominance of the penalized objectives f + penalty * v
(each objective turned into minimization first). Equal penalized
objectives are decided by the lower violation.
With one objective both rules give the same answer as better.
nondominated_sort¶
Fast non-dominated sorting (Deb et al. 2002), a column.
The front of each solution: 0 for the solutions that no other one
dominates, 1 for those dominated only by solutions of front 0, and so
on. Uses memory for an n by n matrix.
crowding_distance¶
Crowding distance of Deb et al. (2002), a column,
computed within each front (all solutions form one front when ranks
is omitted). Larger means less crowded.
For each objective, the front is sorted by that objective, the two
boundary solutions get an infinite distance, and every other solution
adds the gap between its two neighbors divided by the range of that
objective in the front. A front of one or two solutions gets infinite
distances, and an objective with no range adds nothing. The sort is
stable, so of two equal values the first one comes first.
| Property | Meaning |
|---|---|
sense |
"min" or "max", or a string array with one per objective |
sign |
1 or -1, or a row with one per objective |
n_obj |
number of objectives |
constraint_handling |
"feasibility" or "penalty" |
penalty |
penalty coefficient |
ypea.callbacks.Print¶
Print progress every few iterations.
ypea.callbacks.Print(every=1)
Example:
result = alg.solve(problem, callbacks={ypea.callbacks.Print(every=10)});
StudioRng¶
Not in this toolbox under this name. Not available: MATLAB uses its own random numbers, so runs cannot reproduce YPEA Studio's.
ypea.derive_seed¶
The seed of run run_index of an experiment with base seed base.
s = ypea.derive_seed(base, run_index) gives the same number as Python's
ypea.derive_seed and YPEA Studio: Philox2x32-10 with key base on the
counter (run_index, 2^32 - 1). base and run_index are integers from 0 to
2^32 - 1, and so is s. MATLAB runs draw from MATLAB's own generator, so
a run with this seed does not repeat Python's or Studio's draws.