Skip to content

Native operators

By default every algorithm searches the codes of the variables: each variable is stored as numbers in [0, 1], and decode turns them into a tour, a mask, integers and so on (see How variables work). That works for every type, but some types do better with native operators, which change the decoded values directly and follow the rules of the type. A crossover of two tours, for example, should give a tour that keeps parts of both parents.

GA, SA, NSGA-II, NSGA-III, SPEA2 and MOEA/D take space="native". They then decode each variable, apply its native operators, and encode the children back. This example solves a random 40 city traveling salesman problem (TSP) with GA in both spaces and prints the length of the best tour (shorter is better):

import ypea

problem = ypea.problems.random_tsp(40, seed=3)

for space in ("encoded", "native"):
    ga = ypea.GA(max_nfe=20_000, mutation_prob=0.5, space=space)
    result = ga.solve(problem, seed=1)
    print(f"{space:8s} {result.best.obj_value:.2f}")
encoded  1069.89
native   545.90

Differs from Python: MATLAB draws its own cities for seed=3, so the tour lengths differ from Python's.

problem = ypea.problems.random_tsp(40, seed=3);

spaces = ["encoded", "native"];
for space = spaces
    ga = ypea.GA(max_nfe=20000, mutation_prob=0.5, space=space);
    result = ga.solve(problem, seed=1);
    fprintf("%-8s %.2f\n", space, result.best.obj_value);
end
encoded  1013.09
native   527.85

Several objectives

NSGA-II, NSGA-III, SPEA2 and MOEA/D use the same native operators for every type except Real, which keeps simulated binary crossover and polynomial mutation on its codes. So a problem with only real variables runs exactly as with space="encoded", while tours, selections and integers get operators made for them. On a TSP with two distance matrices, the native space finds shorter tours with a long enough budget:

import numpy as np
import ypea

rng = np.random.default_rng(5)
maps = rng.random((2, 30, 2)) * 100  # two maps of 30 cities each

distances = []
for cities in maps:
    gaps = cities[:, None] - cities[None]
    distances.append(np.linalg.norm(gaps, axis=-1))


def lengths(sol):
    tour = sol.tour
    next_city = np.roll(tour, -1, axis=-1)
    length_1 = distances[0][tour, next_city].sum(axis=-1)
    length_2 = distances[1][tour, next_city].sum(axis=-1)
    return np.stack([length_1, length_2], axis=-1)


tours = ypea.Problem(
    ypea.Permutation("tour", 30),
    lengths,
    vectorized=True,
    n_obj=2,
)

for space in ("encoded", "native"):
    nsga = ypea.NSGAII(max_nfe=40_000, space=space)
    result = nsga.solve(tours, seed=0)
    shortest = result.front.obj_values.min(axis=0)
    print(f"{space:8s} shortest tours {shortest.round(1)}")
encoded  shortest tours [716.5 745. ]
native   shortest tours [569.8 624.2]

Differs from Python: MATLAB draws its own maps, so the lengths differ from Python's; outputs=1 says the one-line objective returns only f.

rng = ypea.Rng(5);
distances = cell(1, 2);  % two maps of 30 cities each
for k = 1:2
    cities = rng.random(30, 2) * 100;
    gaps_x = cities(:, 1) - cities(:, 1)';
    gaps_y = cities(:, 2) - cities(:, 2)';
    distances{k} = sqrt(gaps_x.^2 + gaps_y.^2);
end

tours = ypea.Problem( ...
    vars=ypea.Permutation("tour", 30), ...
    objective=@(sol) lengths(sol, distances), ...
    vectorized=true, ...
    n_obj=2, ...
    outputs=1);

spaces = ["encoded", "native"];
for space = spaces
    nsga = ypea.NSGAII(max_nfe=40000, space=space);
    result = nsga.solve(tours, seed=0);
    shortest = min(result.front.obj_values, [], 1);
    fprintf("%-8s shortest tours %s\n", space, mat2str(round(shortest, 1)));
end

function f = lengths(sol, distances)
tour = sol.tour;  % one tour per row
next_city = circshift(tour, -1, 2);
n = size(distances{1}, 1);
steps = tour + (next_city - 1) * n;  % linear indices of the legs
length_1 = sum(distances{1}(steps), 2);
length_2 = sum(distances{2}(steps), 2);
f = [length_1, length_2];
end
encoded  shortest tours [690.7 907.5]
native   shortest tours [633.9 654.4]

Default operators

Variable type Crossover (GA) Mutation (GA and SA)
Real blend crossover (BLX alpha), with alpha = crossover_inflation Gaussian steps of mutation_step_size * (ub - lb) on a share mutation_rate of the elements, at least one
Integer uniform crossover each changed element either creeps by a few steps or is reset to another value
Binary uniform crossover bit flips
Permutation order crossover (OX), partially mapped crossover (PMX) or cycle crossover (CX), one picked at random for each pair swap, inversion or insertion, one picked at random for each move
Selection takes items of the other parent where they are not used yet replaces an item with an unused one, or swaps two positions
BinarySelection keeps the common ones and shares the others between the children swaps a one and a zero
Partition, BinaryPartition the Permutation crossovers, on the ordering of the n items and k - 1 separators the Permutation moves, on the same ordering
FixedSum the code operators of the algorithm, on the codes of that variable the same

Native operators keep the rules of each type: a permutation stays a permutation, a mask keeps exactly k ones, a partition keeps every item in one group, and values stay within bounds. In a problem with several variables, each variable gets its own operators.

A partition is ordered as its encode builds it: the items of group 0, then separator n, the items of group 1, separator n + 1, and so on. The separators are thus distinct values for OX and PMX, so a routing problem with k vehicles can be Partition("routes", n=customers, k=vehicles) and still use the permutation operators.

With GA on a combinatorial problem, also set mutation_step_size_damp=1, so the step does not shrink until the search stalls. See GA.

Operators as settings

GA takes crossover= and mutation=, and SA takes mutation=, to replace the defaults with any compatible operator of ypea.operators. None (the default) keeps the defaults above.

Operator Space Use
SBX(eta=20, prob=0.9, prob_var=0.5) code simulated binary crossover, bounded to [0, 1] (Deb and Agrawal 1995)
PolynomialMutation(eta=20, prob=None) code polynomial mutation, bounded to [0, 1], each component with probability prob (default 1/d)
NativeCrossover(fn, types) native fn(x1, x2, rng) on the decoded values of the variables of the listed types
NativeMutation(fn, types) native fn(x, rng) on the decoded values of the variables of the listed types

This example runs GA on the 10 dimensional sphere function with simulated binary crossover (SBX) and polynomial mutation instead of its defaults, and prints the best value (the optimum is 0):

import ypea
from ypea.operators import SBX, PolynomialMutation

sphere = ypea.benchmarks.problem("sphere", 10)
crossover = SBX(eta=15)
mutation = PolynomialMutation(eta=20)

ga = ypea.GA(max_nfe=20_000, crossover=crossover, mutation=mutation)
result = ga.solve(sphere, seed=1)
print(f"{result.best.obj_value:.3g}")
0.0606

Differs from Python: MATLAB draws its own random numbers, so the value differs from Python's.

sphere = ypea.benchmarks.problem("sphere", 10);
crossover = ypea.operators.SBX(eta=15);
mutation = ypea.operators.PolynomialMutation(eta=20);

ga = ypea.GA(max_nfe=20000, crossover=crossover, mutation=mutation);
result = ga.solve(sphere, seed=1);
fprintf("%.3g\n", result.best.obj_value);
0.0179

A code operator needs space="encoded" (the default). A native operator needs space="native" and changes only the variables of the types it lists. An operators entry for a variable overrides it. The run raises a clear error before it starts if they do not fit, for example SBX with space="native".

eta is the distribution index: larger values keep children and mutants closer to their parents. The defaults are the NSGA-II settings of Deb et al. (2002).

To write your own code operator, subclass ypea.operators.Crossover or Mutation and implement __call__(x1, x2, rng) or __call__(x, rng) on code batches of shape (n, d).

Your own operators

operators maps a variable name to an object with crossover(x1, x2, rng) and mutate(x, rng) methods, or to a tuple (crossover, mutate). Both get decoded batches of shape (n, *shape). A crossover returns two child batches and a mutation one batch. A missing method or a None entry keeps the default.

The operator classes take lists of operators, so a subset is one line. Here GA solves the 40 city TSP from the first example with order crossover and inversion only:

import ypea
from ypea.operators import PermutationOperators, inversion, order_crossover

problem = ypea.problems.random_tsp(40, seed=3)
tour = problem.vars[0]
ops = PermutationOperators(tour, crossovers=[order_crossover], mutations=[inversion])

ga = ypea.GA(
    max_nfe=20_000,
    mutation_prob=0.5,
    space="native",
    operators={"tour": ops},
)
result = ga.solve(problem, seed=1)
print(f"{result.best.obj_value:.2f}")
531.09

Differs from Python: MATLAB draws its own cities for seed=3, so the tour length differs from Python's.

problem = ypea.problems.random_tsp(40, seed=3);
tour = problem.vars{1};
ops = ypea.operators.PermutationOperators(tour, ...
    crossovers={@ypea.operators.order_crossover}, ...
    mutations={@ypea.operators.inversion});

ga = ypea.GA( ...
    max_nfe=20000, ...
    mutation_prob=0.5, ...
    space="native", ...
    operators=struct("tour", ops));
result = ga.solve(problem, seed=1);
fprintf("%.2f\n", result.best.obj_value);
538.76

The best tour is a little shorter than the 545.90 of GA with all the default operators.

A mutation written from scratch, for SA on the same TSP. The tuple is (crossover, mutation). SA does not use a crossover, so the first item is None:

import numpy as np
import ypea

problem = ypea.problems.random_tsp(40, seed=3)


def reverse_segment(x, rng):
    """Reverse a random segment of each tour in the batch x."""
    y = x.copy()
    for row in y:
        i, j = np.sort(rng.integers(len(row), size=2))
        row[i:j + 1] = row[i:j + 1][::-1]
    return y


sa = ypea.SA(
    max_nfe=20_000,
    initial_temp=50,
    final_temp=0.1,
    space="native",
    operators={"tour": (None, reverse_segment)},
)
result = sa.solve(problem, seed=1)
print(f"{result.best.obj_value:.2f}")
535.73

Differs from Python: a cell {crossover, mutation} with [] keeps the default crossover; MATLAB draws its own cities for seed=3.

problem = ypea.problems.random_tsp(40, seed=3);

sa = ypea.SA( ...
    max_nfe=20000, ...
    initial_temp=50, ...
    final_temp=0.1, ...
    space="native", ...
    operators=struct("tour", {{[], @reverse_segment}}));
result = sa.solve(problem, seed=1);
fprintf("%.2f\n", result.best.obj_value);

function y = reverse_segment(x, rng)
% Reverse a random segment of each tour in the batch x (one tour per row).
y = x;
n = size(y, 2);
for r = 1:size(y, 1)
    ends = sort(rng.index(n, 1, 2));
    i = ends(1);
    j = ends(2);
    y(r, i:j) = y(r, j:-1:i);
end
end
528.64

The output is the length of the best tour.

Draw random numbers only from rng, so runs stay reproducible. To stay compatible with ypea.StudioRng, use only its methods: random, uniform, integers, standard_normal, standard_cauchy, geometric, choice and permutation.

Operator functions

ypea.operators also has the single operators, for your own code:

  • crossovers of arrays: uniform_crossover(x1, x2, rng) and one_point_crossover(x1, x2, rng),
  • crossovers of two permutations with cut points i <= j: order_crossover, pmx and cycle_crossover,
  • moves of one permutation at positions i and j: swap, inversion, insertion and scramble.

examples/tsp_ga_native.py compares these choices on a TSP.