Skip to content

Objectives and constraints

The objective function

The objective gets one decoded Solution and returns one of:

  • a number f,
  • a tuple (f, g), where g is one constraint value or a list or array of them,
  • a tuple (f, g, h), where h holds equality constraints.

A constraint is satisfied when its value is at most 0: write a <= b as g = a - b and a >= b as g = b - a. A solution that satisfies every constraint is feasible. With several objectives, f is a list or array (see Multiple objectives).

The example below is a knapsack problem. There are 20 items, each with a value and a weight. x has one 0 or 1 per item (1 means the item is packed), and the goal is the largest total value with a total weight of at most 20:

import numpy as np
import ypea

v = np.array([9, 6, 8, 7, 6, 3, 6, 1, 6, 6, 7, 9, 9, 7, 6, 9, 6, 1, 2, 8])  # values
w = np.array([5, 8, 2, 5, 6, 1, 6, 4, 1, 5, 2, 2, 2, 2, 2, 1, 6, 3, 5, 7])  # weights


def knapsack(sol):
    return v @ sol.x, w @ sol.x - 20  # total value, and total weight at most 20


problem = ypea.Problem(ypea.Binary("x", shape=20), knapsack, sense="max")
result = ypea.DE(max_nfe=10_000).solve(problem, seed=1)
print(result.best.obj_value, result.best.feasible, w @ result.best.solution.x)
73.0 True 20

Differs from Python: a constrained objective returns [value, g] as two outputs, and outputs=2 says that the one-line function @(sol) knapsack(sol, v, w) returns [value, g].

v = [9 6 8 7 6 3 6 1 6 6 7 9 9 7 6 9 6 1 2 8];  % values
w = [5 8 2 5 6 1 6 4 1 5 2 2 2 2 2 1 6 3 5 7];  % weights

problem = ypea.Problem(vars=ypea.Binary("x", shape=20), objective=@(sol) knapsack(sol, v, w), sense="max", outputs=2);
result = ypea.DE(max_nfe=10000).solve(problem, seed=1);
fprintf("%g %d %g\n", result.best.obj_value, result.best.feasible, w * result.best.solution.x(:));

function [value, g] = knapsack(sol, v, w)
value = v * sol.x(:);   % total value
g = w * sol.x(:) - 20;  % total weight at most 20
end
73 1 20

The best packing has a total value of 73, is feasible, and weighs exactly 20.

The violation measures how far a solution is from feasible. The total violation is sum(max(g, 0)) plus the violations of the equalities. result.best.violation holds it, and result.best.feasible is True when it is 0.

Equality constraints

Return (f, g, h) for equalities h(x) = 0. g may be None or an empty list. This example minimizes x + y for a point (x, y) on the unit circle:

import ypea


def circle(sol):
    x, y = sol.x
    return x + y, None, x**2 + y**2 - 1  # minimize x + y on the unit circle


problem = ypea.Problem(ypea.Real("x", shape=2, lb=-2, ub=2), circle)
result = ypea.LSHADE(max_nfe=50_000).solve(problem, seed=0)
print(result.best.obj_value, result.best.feasible)
-1.414251871054271 True

Differs from Python: equality constraints are the third output, with g = [] when there are none; MATLAB draws its own random numbers, and this run stops at -1.364 where Python's reaches -1.414.

problem = ypea.Problem(vars=ypea.Real("x", shape=2, lb=-2, ub=2), objective=@circle);
result = ypea.LSHADE(max_nfe=50000).solve(problem, seed=0);
fprintf("%.15g %d\n", result.best.obj_value, result.best.feasible);

function [f, g, h] = circle(sol)
% minimize x + y on the unit circle
x = sol.x(1);
y = sol.x(2);
f = x + y;
g = [];
h = x^2 + y^2 - 1;
end
-1.36430302859484 1

A search over real numbers almost never lands exactly on h(x) = 0, so an equality counts as satisfied when it is close, as in numpy.isclose:

|h| <= atol + rtol * scale

Otherwise it adds |h| - (atol + rtol * scale) to the violation. That tolerance is why the result above lies slightly below the true minimum, -1.41421.... A smaller equality_atol gives a more exact answer but a thinner feasible region to find.

Setting Default Meaning
equality_atol 1e-4 absolute tolerance, the value the CEC competitions use
equality_rtol 1e-6 relative tolerance, multiplied by the scale
equality_scale 1 the typical size of each equality, one number for all or a list with one per equality

The absolute tolerance suits terms of about size 1. For an equality that balances large quantities, give their typical size as its scale. For a mass balance in kilograms around 10 000, equality_scale=10_000, equality_rtol=1e-5 satisfies it within 1e-4 + 1e-5 * 10 000 = 0.1 kg.

Comparing solutions with constraints

The problem compares solutions, so every algorithm handles constraints the same way, for minimization and maximization alike.

Feasibility rules (constraints="feasibility", the default), after Deb (2000), need no tuning:

  1. A feasible solution beats an infeasible one.
  2. Of two infeasible solutions, the smaller total violation wins.
  3. Of two feasible solutions, the better objective value wins.

Two infeasible solutions with exactly the same violation are ordered by their objective values.

DE on a constrained problem with two variables
DE with the feasibility rules on min (x - 2)² + (y - 1)² with x² ≤ y and x + y ≤ 2. The population at iteration 1 (open circles) is mostly infeasible. By iteration 8 (red) it has moved into the feasible region. After 40 iterations the best solution (star) sits where the two boundaries meet, at (1, 1), not at the unconstrained minimum (2, 1).

Scaling of the constraints. Constraints often differ in size, say a stress in megapascals and a length in meters, and the largest would decide every raw sum. So, as Deb (2000) recommends, each constraint is scaled before the sum. With constraint_scaling=True (the default) a run divides each constraint by its largest violation among its first solutions and keeps these scales for the whole run.

  • The scales come from at least 20 solutions. When an algorithm starts with fewer (CMA-ES, Nelder-Mead, SA, HS), the run first evaluates random solutions to make up 20. They count as evaluations and can become the best solution.
  • A constraint that no early solution violates keeps the scale 1.
  • Result.constraint_scale holds the scales. Every violation in the result is scaled, while problem.evaluate(solution) gives the raw sum.
  • Feasibility does not depend on the scales.

constraint_scaling=False adds the raw violations. A list gives your own scales, one per constraint, the inequalities first, then the equalities: for a stress limit of 200 MPa and a ratio limit, constraint_scaling=[200, 1].

Penalty (constraints="penalty"): solutions are compared by f + penalty * violation, with the penalty always making a solution worse, and ties by the violation. penalty defaults to 1e6. The violation is scaled, so one penalty suits constraints of any size. result.best.obj_value stays the raw f.

import numpy as np
import ypea

v = np.array([9, 6, 8, 7, 6, 3, 6, 1, 6, 6, 7, 9, 9, 7, 6, 9, 6, 1, 2, 8])  # values
w = np.array([5, 8, 2, 5, 6, 1, 6, 4, 1, 5, 2, 2, 2, 2, 2, 1, 6, 3, 5, 7])  # weights


def knapsack(sol):
    return v @ sol.x, w @ sol.x - 20  # total value, and total weight at most 20


penalized = ypea.Problem(
    ypea.Binary("x", shape=20),
    knapsack,
    sense="max",
    constraints="penalty",
    penalty=100,
)
result = ypea.DE(max_nfe=10_000).solve(penalized, seed=1)
print(result.best.obj_value)
73.0

Differs from Python: outputs=2 says that the one-line function @(sol) knapsack(sol, v, w) returns [value, g].

v = [9 6 8 7 6 3 6 1 6 6 7 9 9 7 6 9 6 1 2 8];  % values
w = [5 8 2 5 6 1 6 4 1 5 2 2 2 2 2 1 6 3 5 7];  % weights

penalized = ypea.Problem( ...
    vars=ypea.Binary("x", shape=20), ...
    objective=@(sol) knapsack(sol, v, w), ...
    sense="max", ...
    outputs=2, ...
    constraints="penalty", ...
    penalty=100);
result = ypea.DE(max_nfe=10000).solve(penalized, seed=1);
disp(result.best.obj_value)

function [value, g] = knapsack(sol, v, w)
value = v * sol.x(:);   % total value
g = w * sol.x(:) - 20;  % total weight at most 20
end
    73

Here the penalty version finds the same best value, 73, as the feasibility rules.

Some algorithms use objective values directly, for example the fitness of ABC and the seed counts of IWO. On constrained problems they switch to ranks from these rules. GA, ICA and the probabilistic mode of BA always use ranks.

Values that are not finite

An objective value of NaN, inf or -inf counts as the worst possible value, and a NaN constraint value as an infinite violation. So an objective may return np.inf for a solution it cannot evaluate.

Vectorized objectives

By default the objective gets one solution per call. With vectorized=True it gets a whole batch at once, which lets NumPy do the work in a few array operations. Each attribute of the solution then has a leading batch axis, and the objective returns f with shape (n,), or (n, m) with several objectives, and g and h with shape (n,) or (n, k) for k constraints:

import numpy as np
import ypea

v = np.array([9, 6, 8, 7, 6, 3, 6, 1, 6, 6, 7, 9, 9, 7, 6, 9, 6, 1, 2, 8])  # values
w = np.array([5, 8, 2, 5, 6, 1, 6, 4, 1, 5, 2, 2, 2, 2, 2, 1, 6, 3, 5, 7])  # weights


def knapsack_batch(sol):
    x = sol.x  # shape (n, 20)
    return x @ v, x @ w - 20


problem = ypea.Problem(
    ypea.Binary("x", shape=20),
    knapsack_batch,
    sense="max",
    vectorized=True,
)
result = ypea.DE(max_nfe=10_000).solve(problem, seed=1)
print(result.best.obj_value)
73.0

Differs from Python: outputs=2 says that the one-line function @(sol) knapsack(sol, v, w) returns [value, g].

v = [9 6 8 7 6 3 6 1 6 6 7 9 9 7 6 9 6 1 2 8];  % values
w = [5 8 2 5 6 1 6 4 1 5 2 2 2 2 2 1 6 3 5 7];  % weights

problem = ypea.Problem( ...
    vars=ypea.Binary("x", shape=20), ...
    objective=@(sol) knapsack_batch(sol, v, w), ...
    sense="max", ...
    outputs=2, ...
    vectorized=true);
result = ypea.DE(max_nfe=10000).solve(problem, seed=1);
disp(result.best.obj_value)

function [value, g] = knapsack_batch(sol, v, w)
x = sol.x;  % n by 20, one solution per row
value = x * v';
g = x * w' - 20;
end
    73

The result is the same as with the plain objective, and the run is often many times faster. Every function and ready-made problem in ypea.benchmarks and ypea.problems is vectorized. A problem with a Partition variable cannot be, because its groups differ in size.

Parallel evaluation

For an expensive objective, pass a concurrent.futures executor to solve, and each batch is evaluated in parallel. The result is the same as without the executor:

from concurrent.futures import ThreadPoolExecutor

import numpy as np
import ypea

v = np.array([9, 6, 8, 7, 6, 3, 6, 1, 6, 6, 7, 9, 9, 7, 6, 9, 6, 1, 2, 8])  # values
w = np.array([5, 8, 2, 5, 6, 1, 6, 4, 1, 5, 2, 2, 2, 2, 2, 1, 6, 3, 5, 7])  # weights


def knapsack(sol):
    return v @ sol.x, w @ sol.x - 20  # total value, and total weight at most 20


problem = ypea.Problem(ypea.Binary("x", shape=20), knapsack, sense="max")
with ThreadPoolExecutor(max_workers=4) as pool:
    result = ypea.DE(max_nfe=10_000).solve(problem, seed=1, executor=pool)
print(result.best.obj_value)
73.0

Differs from Python: parallel=true evaluates each batch with parfor on a parallel pool (Parallel Computing Toolbox), where Python takes an executor; outputs=2 says that the one-line function returns [value, g].

v = [9 6 8 7 6 3 6 1 6 6 7 9 9 7 6 9 6 1 2 8];  % values
w = [5 8 2 5 6 1 6 4 1 5 2 2 2 2 2 1 6 3 5 7];  % weights

problem = ypea.Problem( ...
    vars=ypea.Binary("x", shape=20), ...
    objective=@(sol) knapsack(sol, v, w), ...
    sense="max", ...
    outputs=2);
pool = parpool(2);  % or leave it out, and parfor starts the default pool
result = ypea.DE(max_nfe=10000).solve(problem, seed=1, parallel=true);
disp(result.best.obj_value)
delete(pool)

function [value, g] = knapsack(sol, v, w)
value = v * sol.x(:);       % total value
g = w * sol.x(:) - 20;      % total weight at most 20
end
Starting parallel pool (parpool) using the 'Processes' profile ...
Connected to parallel pool with 2 workers.
    73

Parallel pool using the 'Processes' profile is shutting down.

Threads help when the objective releases the GIL, Python's global interpreter lock (NumPy, external programs, file input and output). For pure Python use a ProcessPoolExecutor, with a top-level objective function (not a lambda) and, on Windows and macOS, an if __name__ == "__main__": guard. Vectorized problems ignore the executor.