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.
$ pip install carmelolg-galib
$ python phrase.pygen 0 | best 3 | mean 0.27 | div 0.963 | HaQ JtQgiqhgVJjgen 5 | best 7 | mean 3.17 | div 0.735 | HaqPi IajthdOB!gen 10 | best 9 | mean 6.28 | div 0.562 | HapdhvBErthdakagen 15 | best 12 | mean 8.88 | div 0.398 | Hapry virthdaG!gen 20 | best 14 | mean 10.59 | div 0.278 | Happy Birthdak!Happy Birthday!21 TargetFitness
Three levels of control¶
Start with the defaults. Reach deeper only when you need to.
-
1 · Parameters
Tune the search without writing any operator.
-
2 · Operators
Plug in built-in operators, or any function with the right signature.
-
3 · Subclassing
Replace whole phases of the loop, such as the replacement strategy.
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.
-
Selection problems
Knapsack as a list of bits, with a custom stop condition and replacement strategy.
-
Routes and orders
Travelling salesman with permutations, order crossover and inversion mutation.
-
Numeric optimisation
Real-valued numpy genomes with a vectorised fitness over the whole population.
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¶
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.