Skip to content

Operators

Protocols

protocols

Signatures every operator must follow.

Any callable with the right signature works: a plain function, a lambda, or an instance of a class with __call__ (the built-ins are classes, so they can be subclassed). Parameters are positional-only, so your own functions may name them as they like.

Contract: never modify the genomes or individuals you receive, return new ones.

SelectionOperator

Bases: Protocol[G]

Pick count parents from population (repetitions allowed). Prefer a higher score.

CrossoverOperator

Bases: Protocol[G]

Combine two parent genomes into two child genomes.

MutationOperator

Bases: Protocol[G]

Return a mutated copy of genome. rate is the engine's per-gene mutation rate.

Selection

selection

Built-in parent selection operators. All of them prefer a higher Individual.score.

Tournament

Tournament(size: int = 3)

Each parent is the best of size individuals drawn at random.

Larger size means stronger selection pressure (faster convergence, less diversity).

Source code in src/carmelolg/galib/operators/selection.py
def __init__(self, size: int = 3) -> None:
    if size < 1:
        raise ValueError("tournament size must be >= 1")
    self.size = size

Roulette

Fitness-proportionate selection.

Scores are shifted so that the worst individual weighs 0 ("windowing"), which also makes negative scores work. If every individual has the same score the choice is uniform.

Rank

Rank-based selection: the worst individual weighs 1, the best weighs N.

Unlike Roulette, the probability does not depend on how large the fitness gaps are.

Crossover

crossover

Built-in crossover operators.

  • Sequences (str, bytes, tuple, list, numpy array) of equal length: OnePoint, TwoPoint, Uniform.
  • Permutations (every gene appears exactly once, e.g. a TSP tour): OrderCrossover, PartiallyMappedCrossover.
  • Real-valued genes: BlendCrossover.

Every operator returns two new children and never modifies the parents.

OnePoint

Swap the tails of the two parents after a random cut point.

TwoPoint

Swap the segment between two random cut points. Falls back to OnePoint below 3 genes.

Uniform

Uniform(swap_probability: float = 0.5)

Swap each gene between the two children with probability swap_probability.

Source code in src/carmelolg/galib/operators/crossover.py
def __init__(self, swap_probability: float = 0.5) -> None:
    if not 0 <= swap_probability <= 1:
        raise ValueError("swap_probability must be in [0, 1]")
    self.swap_probability = swap_probability

OrderCrossover

Order crossover (OX1) for permutations.

Each child keeps a random segment of one parent in place, and fills the remaining positions with the missing genes in the order they appear in the other parent (starting after the segment, wrapping around). Children are always valid permutations.

PartiallyMappedCrossover

Partially mapped crossover (PMX) for permutations.

Each child copies a random segment of one parent; the genes of the other parent are placed at the same positions when possible, otherwise through the mapping defined by the segment. Children are always valid permutations, and keep more absolute positions than OrderCrossover.

BlendCrossover

BlendCrossover(alpha: float = 0.5, low: Bound = None, high: Bound = None)

Blend crossover (BLX-alpha) for real-valued genes.

For each gene, with parents p and q and d = |p - q|, each child gets a value drawn uniformly from [min(p, q) - alpha * d, max(p, q) + alpha * d], then clipped to [low, high]. alpha = 0 stays between the parents; larger values explore further. Bounds may be a single value or one value per gene.

Source code in src/carmelolg/galib/operators/crossover.py
def __init__(self, alpha: float = 0.5, low: Bound = None, high: Bound = None) -> None:
    if alpha < 0:
        raise ValueError("alpha must be >= 0")
    validate_bounds(low, high)
    self.alpha = alpha
    self.low = low
    self.high = high

Mutation

mutation

Built-in mutation operators.

All of them use the engine's per-gene rate, so that the expected number of mutation events per child is rate * len(genome) (one on average with the default rate 1 / len(genome)). Mutated positions are drawn with geometric jumps, so the cost grows with the number of mutations, not with the genome length.

  • Any sequence genome: RandomReset (also the default Problem.mutate).
  • Permutations: SwapMutation, InversionMutation (children stay valid permutations).
  • Real-valued genes: GaussianMutation.

Every operator returns a new genome and never modifies its input.

GeneFactory module-attribute

GeneFactory = Callable[[Random], Any]

Returns one random gene, e.g. lambda rng: rng.choice("abc").

RandomReset

RandomReset(random_gene: GeneFactory)

Operator form of :func:random_reset, for use as mutation=RandomReset(...).

Source code in src/carmelolg/galib/operators/mutation.py
def __init__(self, random_gene: GeneFactory) -> None:
    self.random_gene = random_gene

SwapMutation

For each position, with probability rate, swap its gene with the gene at a random position.

InversionMutation

With probability min(1, rate * len(genome)), reverse the order of a random segment.

Well suited to routing problems: reversing a segment of a tour changes only two edges.

GaussianMutation

GaussianMutation(sigma: float | Sequence[float], low: Bound = None, high: Bound = None)

For each gene, with probability rate, add noise drawn from a normal distribution N(0, sigma), then clip to [low, high].

sigma, low and high may be a single value or one value per gene.

Source code in src/carmelolg/galib/operators/mutation.py
def __init__(self, sigma: float | Sequence[float], low: Bound = None, high: Bound = None) -> None:
    sigmas = [sigma] if isinstance(sigma, (int, float)) else list(sigma)
    if any(s <= 0 for s in sigmas):
        raise ValueError("sigma must be > 0")
    validate_bounds(low, high)
    self.sigma = sigma
    self.low = low
    self.high = high

random_reset

random_reset(genome: G, rng: Random, rate: float, random_gene: GeneFactory) -> G

Replace each gene independently, with probability rate, by random_gene(rng).

A child can therefore get 0, 1 or more mutations; on average len(genome) * rate.

Source code in src/carmelolg/galib/operators/mutation.py
def random_reset(genome: G, rng: Random, rate: float, random_gene: GeneFactory) -> G:
    """Replace each gene independently, with probability ``rate``, by ``random_gene(rng)``.

    A child can therefore get 0, 1 or more mutations; on average ``len(genome) * rate``.
    """
    value = cast(Any, genome)
    genes = _copy(value)
    for index in bernoulli_positions(len(genes), rate, rng):
        genes[index] = random_gene(rng)
    return cast(G, _finish(value, genes))