Problems and variables¶
The problem¶
ypea.Problem holds everything about the problem and nothing about the algorithm: the decision variables, the objective function, and whether to minimize or maximize. This one is the sphere function, the sum of squares of 20 real numbers:
import numpy as np
import ypea
problem = ypea.Problem(
vars=ypea.Real("x", shape=20, lb=-10, ub=10), # one variable or a list
objective=lambda sol: np.sum(sol.x**2), # gets a decoded Solution
sense="min", # or "max"
name="sphere",
optimum=0.0, # optional: results then report the error
)
Differs from Python: several variables go in braces; vars= and objective= are name=value arguments.
problem = ypea.Problem( ...
vars=ypea.Real("x", shape=20, lb=-10, ub=10), ... % one variable, or several in braces
objective=@(sol) sum(sol.x.^2), ... % gets a decoded solution
sense="min", ... % or "max"
name="sphere", ...
optimum=0); % optional: results then report the error
| Argument | Meaning |
|---|---|
vars |
a Variable or a list of them, with unique names |
objective |
a function of a decoded Solution that returns f, (f, g) or (f, g, h) (see Objectives and constraints) |
sense |
"min" (default) or "max", or a list with one per objective |
n_obj |
the number of objectives (default: one per sense, see Multiple objectives) |
vectorized |
True if the objective takes the whole population at once (see Vectorized objectives) |
constraints |
"feasibility" (default) or "penalty", how constrained solutions compare |
penalty |
the penalty coefficient, 1e6 by default |
constraint_scaling |
True (default), False or a list of scales for the constraint violations |
equality_atol, equality_rtol, equality_scale |
the tolerance of equality constraints |
name |
a name for results and reports (default: the name of the objective function) |
optimum |
the known optimal value, if any. Result.error is then abs(f - optimum). |
info |
a dict of free metadata, for example the optimal solution or the source of an instance |
How variables work¶
Every variable is stored as a block of numbers in [0, 1], called codes or random keys. The algorithms see only the codes, so every algorithm works with every variable type. A variable knows how many codes it needs (code_size), how to turn codes into values (decode) and values back into codes (encode).
| Type | Decodes to | Typical use |
|---|---|---|
Real(name, shape, lb, ub) |
real array in [lb, ub] | continuous optimization |
Integer(name, shape, lb, ub) |
integer array in [lb, ub] | integer knapsack, assignment |
Binary(name, shape) |
0/1 array | knapsack |
Permutation(name, n, count=None) |
ordering of 0 to n - 1 | TSP, QAP, n-Queens |
Selection(name, n, k, count=None) |
k distinct items out of n | feature selection, hub location |
BinarySelection(name, n, k, count=None) |
0/1 mask with k ones | feature selection |
Partition(name, n, k, count=None) |
list of k groups of items | clustering, allocation |
BinaryPartition(name, n, k, count=None) |
(k, n) 0/1 assignment matrix | allocation |
FixedSum(name, shape, target, axis=None) |
nonnegative reals with fixed totals | portfolio weights, transportation |
examples/variables.py prints random samples of every type.
decode turns codes into values. It works on batches: an array of codes with shape (n, code_size), one row per solution, gives values with shape (n, *shape). Decoded indices start at 0.
The examples below decode the same row of five codes, [0.7, 0.1, 0.4, 0.9, 0.2], with each type. It stands for one solution as the algorithms see it. The outputs have an extra outer pair of brackets because the batch holds one solution.
Real¶
Real(name, shape=None, lb=0.0, ub=1.0): continuous values in [lb, ub]. The bounds may be arrays, and the shape follows them when not given.
import numpy as np
import ypea
codes = np.array([[0.7, 0.1, 0.4, 0.9, 0.2]]) # one solution, five codes
print(ypea.Real("x", shape=5, lb=-10, ub=10).decode(codes))
[[ 4. -8. -2. 8. -6.]]
codes = [0.7, 0.1, 0.4, 0.9, 0.2]; % one solution, five codes
disp(ypea.Real("x", shape=5, lb=-10, ub=10).decode(codes))
4 -8 -2 8 -6
Each code maps linearly onto the range: 0.7 gives -10 + 0.7 * 20 = 4.
Integer and Binary¶
Integer(name, shape=None, lb=0, ub=1): integers in [lb, ub], both included, each equally likely for uniform codes. Binary(name, shape=None) is an integer in [0, 1].
import numpy as np
import ypea
codes = np.array([[0.7, 0.1, 0.4, 0.9, 0.2]]) # one solution, five codes
print(ypea.Integer("n", shape=5, lb=1, ub=6).decode(codes))
print(ypea.Binary("b", shape=5).decode(codes))
[[5 1 3 6 2]]
[[1 0 0 1 0]]
codes = [0.7, 0.1, 0.4, 0.9, 0.2]; % one solution, five codes
disp(ypea.Integer("n", shape=5, lb=1, ub=6).decode(codes))
disp(ypea.Binary("b", shape=5).decode(codes))
5 1 3 6 2
1 0 0 1 0
For Binary, a code of 0.5 or more gives 1.
Permutation¶
Permutation(name, n, count=None): an ordering of 0 to n - 1, from sorting the codes. With count, the value is a (count, n) array with one permutation per row.
import numpy as np
import ypea
codes = np.array([[0.7, 0.1, 0.4, 0.9, 0.2]]) # one solution, five codes
print(ypea.Permutation("p", n=5).decode(codes))
[[1 4 2 0 3]]
Differs from Python: MATLAB indices start at 1, so this permutation reads [2 5 3 1 4].
codes = [0.7, 0.1, 0.4, 0.9, 0.2]; % one solution, five codes
disp(ypea.Permutation("p", n=5).decode(codes))
2 5 3 1 4
Each item owns the code at its position: item 0 has 0.7, item 1 has 0.1, and so on. Sorted from smallest to largest, the codes 0.1, 0.2, 0.4, 0.7 and 0.9 belong to items 1, 4, 2, 0 and 3, and that is the permutation.
Selection and BinarySelection¶
Selection(name, n, k, count=None): an ordered selection of k distinct items out of n, the first k of the permutation. BinarySelection(name, n, k, count=None) gives the same choice as a 0/1 mask with exactly k ones.
import numpy as np
import ypea
codes = np.array([[0.7, 0.1, 0.4, 0.9, 0.2]]) # one solution, five codes
print(ypea.Selection("s", n=5, k=2).decode(codes))
print(ypea.BinarySelection("m", n=5, k=2).decode(codes))
[[1 4]]
[[0 1 0 0 1]]
Differs from Python: MATLAB indices start at 1, so the chosen items are 2 and 5.
codes = [0.7, 0.1, 0.4, 0.9, 0.2]; % one solution, five codes
disp(ypea.Selection("s", n=5, k=2).decode(codes))
disp(ypea.BinarySelection("m", n=5, k=2).decode(codes))
2 5
0 1 0 0 1
The two smallest codes, 0.1 and 0.2, belong to items 1 and 4, so those two are chosen.
Partition and BinaryPartition¶
Partition(name, n, k, count=None): splits the items 0 to n - 1 into k groups, some possibly empty. Its n + k - 1 codes (one per item and k - 1 separators) are sorted together. The value is a list of k index arrays, so a problem with a partition cannot be vectorized. BinaryPartition(name, n, k, count=None) gives the same split as a (k, n) 0/1 matrix, which can.
import numpy as np
import ypea
codes = np.array([[0.7, 0.1, 0.4, 0.9, 0.2]]) # one solution, five codes
print(ypea.Partition("g", n=4, k=2).decode(codes))
print(ypea.BinaryPartition("g", n=4, k=2).decode(codes))
[[array([1]), array([2, 0, 3])]]
[[[0 1 0 0]
[1 0 1 1]]]
Differs from Python: MATLAB indices start at 1, so the groups are [2] and [3 1 4].
codes = [0.7, 0.1, 0.4, 0.9, 0.2]; % one solution, five codes
batch = ypea.Partition("g", n=4, k=2).decode(codes);
groups = batch{1}; % the groups of the first (and only) solution
disp(groups{1})
disp(groups{2})
masks = ypea.BinaryPartition("g", n=4, k=2).decode(codes);
disp(squeeze(masks)) % k by n: one row per group
2
3 1 4
0 1 0 0
1 0 1 1
Here the first four codes belong to items 0 to 3, and the fifth (0.2) is the separator. Sorted, the order is item 1, the separator, then items 2, 0 and 3. So item 1 forms the first group and items 2, 0 and 3 the second.
FixedSum¶
FixedSum(name, shape, target=1.0, axis=None): nonnegative reals with a fixed sum. With axis=None all elements sum to target. With a 2D shape, axis=1 fixes the sum of each row and axis=0 of each column, and target may give one value per row or column. The second example draws a random value with sample (see Random samples): each row of the 2 by 3 array sums to its target.
import numpy as np
import ypea
codes = np.array([[0.7, 0.1, 0.4, 0.9, 0.2]]) # one solution, five codes
weights = ypea.FixedSum("w", shape=5, target=1)
print(weights.decode(codes).round(3))
rows = ypea.FixedSum("x", shape=(2, 3), target=[5, 10], axis=1)
rng = np.random.default_rng(1)
x = rows.sample(rng)
print(x.round(2), x.sum(axis=1))
[[0.304 0.043 0.174 0.391 0.087]]
[[1.59 2.96 0.45]
[5.63 1.85 2.51]] [ 5. 10.]
Differs from Python: dim=2 fixes the sum of each row (Python: axis=1), and MATLAB draws its own random numbers.
codes = [0.7, 0.1, 0.4, 0.9, 0.2]; % one solution, five codes
weights = ypea.FixedSum("w", shape=5, target=1);
disp(round(weights.decode(codes), 3))
rows = ypea.FixedSum("x", shape=[2 3], target=[5 10], dim=2);
x = rows.sample(ypea.Rng(1));
disp(round(x, 2))
disp(sum(x, 2))
0.3040 0.0430 0.1740 0.3910 0.0870
3.7000 0 1.3000
6.4600 2.7100 0.8300
5.0000
10.0000
In the first example the five codes add up to 2.3, so each value is its code divided by 2.3.
Random samples¶
var.sample(rng) decodes random codes into a value, which is handy for testing an objective. rng is a NumPy random generator, and n asks for several samples, one per row:
import numpy as np
import ypea
var = ypea.Permutation("tour", n=8)
print(var.sample(np.random.default_rng(1)))
print(var.sample(np.random.default_rng(1), n=2))
[2 4 7 5 0 6 3 1]
[[2 4 7 5 0 6 3 1]
[1 6 4 7 3 0 2 5]]
Differs from Python: MATLAB indices start at 1, and MATLAB draws its own random numbers, so the tours differ from Python's.
var = ypea.Permutation("tour", n=8);
disp(var.sample(ypea.Rng(1)))
disp(var.sample(ypea.Rng(1), 2))
3 6 5 7 4 8 1 2
2 8 3 4 7 5 1 6
3 2 4 5 8 6 1 7
Several variables¶
A problem can mix variables of any type. The decoded solution has one attribute per variable (sol["name"] also works), and scalar variables decode to scalars:
import ypea
def f(sol):
x, y, z = sol.x, sol.y, sol.z
return x * y - z**3 - 2 * x - 5 * y + 3 * (x + y) * z**2
variables = [
ypea.Real("x", lb=-2, ub=5),
ypea.Real("y", lb=-1, ub=1),
ypea.Real("z", lb=3, ub=10),
]
problem = ypea.Problem(variables, f, sense="max")
result = ypea.DE(max_iter=200, pop_size=20).solve(problem, seed=1)
print(result.best.obj_value, result.best.solution)
790.0 Solution(x=5.0, y=1.0, z=10.0)
variables = {
ypea.Real("x", lb=-2, ub=5)
ypea.Real("y", lb=-1, ub=1)
ypea.Real("z", lb=3, ub=10)
};
problem = ypea.Problem(vars=variables, objective=@f, sense="max");
result = ypea.DE(max_iter=200, pop_size=20).solve(problem, seed=1);
disp(result.best.obj_value)
disp(result.best.solution)
function value = f(sol)
x = sol.x;
y = sol.y;
z = sol.z;
value = x * y - z^3 - 2 * x - 5 * y + 3 * (x + y) * z^2;
end
790
x: 5
y: 1
z: 10
The best value, 790, lies at the upper bounds of all three variables. The full script is examples/max_problem.py.
Decoding and encoding solutions¶
problem.encode turns a known solution into codes, for example to check it against the result of a run, and problem.decode_one turns codes back:
import ypea
variables = [
ypea.Permutation("tour", n=4),
ypea.Integer("k", lb=0, ub=9),
]
problem = ypea.Problem(variables, lambda sol: 0.0)
code = problem.encode({"tour": [2, 0, 3, 1], "k": 7})
print(code.round(3))
print(problem.decode_one(code))
[0.375 0.875 0.125 0.625 0.75 ]
Solution(tour=array([2, 0, 3, 1]), k=7)
Differs from Python: MATLAB indices start at 1, so the tour is [3 1 4 2].
variables = {
ypea.Permutation("tour", n=4)
ypea.Integer("k", lb=0, ub=9)
};
problem = ypea.Problem(vars=variables, objective=@(sol) 0);
code = problem.encode(struct("tour", [3 1 4 2], "k", 7));
disp(round(code, 3))
disp(problem.decode_one(code))
0.3750 0.8750 0.1250 0.6250 0.7500
tour: [3 1 4 2]
k: 7
The first four codes hold the tour and the last one holds k. Decoding them gives back the same solution.
problem.decode(X) decodes a batch of codes into a list of solutions, or into one batch solution when the problem is vectorized.
Your own variable type¶
Subclass ypea.Variable with a code_size, a shape, and batch decode and encode methods. Set array_valued = False when decode returns lists, as Partition does. The built-in types in ypea/variables.py are short examples to start from.