Skip to content

Genetic algorithms for Python

Describe the problem. Let it evolve.

GALib runs the evolution while you only say what to optimise. Sensible defaults work out of the box, and every behaviour can be replaced, from one parameter to the whole replacement strategy.

Get started How it works

$ pip install carmelolg-galib

Three levels of control

Start with the defaults. Reach deeper only when you need to.

  • 1 · Parameters


    Tune the search without writing any operator.

    GeneticAlgorithm(
        problem,
        population_size=300,
        elite_size=5,
        mutation_rate=0.02,
    )
    

    The engine

  • 2 · Operators


    Plug in built-in operators, or any function with the right signature.

    GeneticAlgorithm(
        problem,
        selection=Rank(),
        crossover=OrderCrossover(),
        mutation=my_mutation,
    )
    

    Operators

  • 3 · Subclassing


    Replace whole phases of the loop, such as the replacement strategy.

    class MuPlusLambda(GeneticAlgorithm):
        def replace(self, population, offspring):
            pool = [*population, *offspring]
            pool.sort(key=lambda i: -i.score)
            return pool[: self.population_size]
    

    Subclassing

One engine, many problems

Strings, bits, tours, real numbers: pick the genome that fits and the matching operators.

  • Text and symbols

    Evolve a phrase with the default operators. A first program in a few lines.

    Phrase

  • Selection problems

    Knapsack as a list of bits, with a custom stop condition and replacement strategy.

    Knapsack

  • Routes and orders

    Travelling salesman with permutations, order crossover and inversion mutation.

    Salesman

  • Numeric optimisation

    Real-valued numpy genomes with a vectorised fitness over the whole population.

    Rastrigin

Under the hood

  • Typed and tested

    mypy --strict, 97% branch coverage, Python 3.10 to 3.14.

  • No dependencies

    The core needs nothing. numpy and matplotlib are optional extras.

  • Reproducible

    Every run has its own seeded generator: the same seed gives the same run.

  • Observable

    Statistics, diversity, callbacks and stop conditions for every generation.

Install

pip install carmelolg-galib
pip install "carmelolg-galib[numpy]"
pip install "carmelolg-galib[plot]"

Distribution name and import name

You install carmelolg-galib (PyPI) and import carmelolg.galib.

Thirty seconds example

import string
from carmelolg.galib import GeneticAlgorithm, Problem, TargetFitness

TARGET = "hello world"
ALPHABET = string.ascii_lowercase + " "


class Phrase(Problem[str]):
    def random_genome(self, rng):  # one random candidate solution
        return "".join(rng.choice(ALPHABET) for _ in TARGET)

    def random_gene(self, rng):  # enables the default mutation
        return rng.choice(ALPHABET)

    def fitness(self, genome):  # how good a candidate is: higher is better
        return sum(a == b for a, b in zip(genome, TARGET))


result = GeneticAlgorithm(Phrase(), stop=[TargetFitness(len(TARGET))], seed=1).run()
print(result.best.genome)  # hello world

Continue with Getting started, or read the Concepts if genetic algorithms are new to you.