Examples¶
Complete programs live in the
examples/ folder of the repository.
Run them from the project root after pip install -e ".[numpy,plot]". rastrigin.py --plot draws the history.
| Example | Genome | Shows |
|---|---|---|
phrase.py |
string | the defaults only; live progress on a single line |
knapsack.py |
list of bits | the three customisation levels: parameters, operators, a subclassed engine |
tsp.py |
permutation | minimisation, OrderCrossover, InversionMutation |
rastrigin.py |
numpy array of floats | vectorised fitness_batch, BlendCrossover, GaussianMutation, gene_spread |
monitoring.py |
string | the Result, the history, diversity metrics, plot_history |
Phrase¶
# SPDX-FileCopyrightText: 2026 CARMELO LA GAMBA
# SPDX-License-Identifier: Apache-2.0
"""Evolve random strings into a target phrase: the original genetic-algorithm-example, rebuilt on GALib.
Level 1 of customisation: only a Problem and a few parameters, everything else is default.
"""
import string
import time
from carmelolg.galib import Callback, GeneticAlgorithm, PrintProgress, Problem, TargetFitness
TARGET = "Happy Birthday! from a genetic algorithm to you :-)"
ALPHABET = string.ascii_letters + " '!?*&.:;,-()"
class PhraseProblem(Problem[str]):
def random_genome(self, rng):
return "".join(rng.choice(ALPHABET) for _ in TARGET)
def random_gene(self, rng):
return rng.choice(ALPHABET)
def fitness(self, genome):
return sum(a == b for a, b in zip(genome, TARGET, strict=True)) # matching characters
class SlowDown(Callback):
"""Demo only: pause after every generation so the progress is visible (the real run takes ~0.3 s)."""
def __init__(self, seconds=0.03):
self.seconds = seconds
def on_generation(self, stats, engine):
time.sleep(self.seconds)
if __name__ == "__main__":
result = GeneticAlgorithm(
PhraseProblem(),
population_size=300,
stop=[TargetFitness(len(TARGET))],
callbacks=[PrintProgress(every=1, in_place=True), SlowDown(0.03)],
seed=42,
).run()
print(f"best: {result.best.genome!r} after {result.generations} generations ({result.stopped_by})")
Knapsack¶
# SPDX-FileCopyrightText: 2026 CARMELO LA GAMBA
# SPDX-License-Identifier: Apache-2.0
"""0/1 knapsack: the same engine on a different genome (a list of bits), using all three customisation levels.
1. parameters population_size, elite_size, seed
2. operators a built-in selection and crossover, plus a custom stop condition
3. subclassing a (mu + lambda) replacement strategy instead of the default generational one
"""
import random
from carmelolg.galib import GeneticAlgorithm, PrintProgress, Problem, Stagnation, StopCondition
from carmelolg.galib.operators import Rank, Uniform
_items_rng = random.Random(7)
ITEMS = [(_items_rng.randint(1, 30), _items_rng.randint(1, 60)) for _ in range(40)] # (weight, value)
CAPACITY = 250
class Knapsack(Problem[list]):
def random_genome(self, rng):
return [rng.randint(0, 1) for _ in ITEMS]
def random_gene(self, rng):
return rng.randint(0, 1)
def fitness(self, genome):
weight = sum(w for (w, _), take in zip(ITEMS, genome, strict=True) if take)
value = sum(v for (_, v), take in zip(ITEMS, genome, strict=True) if take)
return value if weight <= CAPACITY else 0 # overweight bags are worthless
class Converged(StopCondition):
"""Custom stop condition: stop when the population has (almost) no diversity left."""
def __init__(self, threshold=0.01):
self.threshold = threshold
def should_stop(self, stats, engine):
return stats.diversity is not None and stats.diversity < self.threshold
class MuPlusLambda(GeneticAlgorithm):
"""Custom replacement: parents and children compete, the best population_size survive."""
def replace(self, population, offspring):
both = sorted([*population, *offspring], key=lambda i: i.score, reverse=True)
return both[: self.population_size]
if __name__ == "__main__":
result = MuPlusLambda(
Knapsack(),
population_size=150,
elite_size=0, # every parent already competes in replace()
selection=Rank(),
crossover=Uniform(),
stop=[Stagnation(80), Converged()],
callbacks=[PrintProgress(every=20)],
seed=3,
).run()
print(f"\nbest value: {result.best.fitness} after {result.generations} generations ({result.stopped_by})")
Travelling salesman¶
# SPDX-FileCopyrightText: 2026 CARMELO LA GAMBA
# SPDX-License-Identifier: Apache-2.0
"""Travelling salesman: a permutation genome, minimisation, permutation operators.
The genome is the order in which the cities are visited. Generic crossovers would duplicate cities, so the
example uses OrderCrossover and InversionMutation, which always produce valid tours.
"""
import math
import random
from carmelolg.galib import GeneticAlgorithm, PrintProgress, Problem, Stagnation
from carmelolg.galib.operators import InversionMutation, OrderCrossover
_cities_rng = random.Random(11)
CITIES = [(_cities_rng.uniform(0, 100), _cities_rng.uniform(0, 100)) for _ in range(30)]
class Tour(Problem[list]):
maximize = False # shorter is better
def random_genome(self, rng):
tour = list(range(len(CITIES)))
rng.shuffle(tour)
return tour
def fitness(self, tour):
# closed tour: from the last city back to the first one
return sum(math.dist(CITIES[tour[k - 1]], CITIES[tour[k]]) for k in range(len(tour)))
if __name__ == "__main__":
result = GeneticAlgorithm(
Tour(),
population_size=200,
crossover=OrderCrossover(),
mutation=InversionMutation(),
stop=[Stagnation(150)],
max_generations=3000,
callbacks=[PrintProgress(every=50, width=0)],
seed=1,
).run()
print(f"\nshortest tour: {result.best.fitness:.1f} after {result.generations} generations ({result.stopped_by})")
print("order:", result.best.genome)
Rastrigin function¶
# SPDX-FileCopyrightText: 2026 CARMELO LA GAMBA
# SPDX-License-Identifier: Apache-2.0
"""Minimise the Rastrigin function: real-valued numpy genomes, vectorised fitness, real-valued operators.
Rastrigin has a single global minimum, 0 at the origin, surrounded by many local minima: a classic test for
how well an algorithm keeps exploring. In 10 dimensions a plain genetic algorithm usually ends close to the
origin (best values between about 0.1 and 2 depending on the seed) rather than exactly on it; try other
settings and seeds to see how exploration changes the result.
Requires numpy: pip install "carmelolg-galib[numpy]"
Add --plot to draw the history (needs matplotlib).
"""
import sys
import numpy as np
from carmelolg.galib import GeneticAlgorithm, PrintProgress, Problem, Stagnation, TargetFitness
from carmelolg.galib.metrics import gene_spread
from carmelolg.galib.operators import BlendCrossover, GaussianMutation, Tournament
from carmelolg.galib.plot import plot_history
DIMENSIONS = 10
LOW, HIGH = -5.12, 5.12
class Rastrigin(Problem[np.ndarray]):
maximize = False
def random_genome(self, rng):
return np.array([rng.uniform(LOW, HIGH) for _ in range(DIMENSIONS)])
def fitness_batch(self, genomes):
x = np.stack(genomes) # (population, DIMENSIONS): the whole population in one expression
return 10 * DIMENSIONS + (x**2 - 10 * np.cos(2 * np.pi * x)).sum(axis=1)
if __name__ == "__main__":
result = GeneticAlgorithm(
Rastrigin(),
population_size=300,
selection=Tournament(2), # mild selection pressure: keeps exploring longer
crossover=BlendCrossover(alpha=0.3, low=LOW, high=HIGH),
mutation=GaussianMutation(sigma=0.5, low=LOW, high=HIGH),
mutation_rate=0.1,
diversity=gene_spread, # standard deviation of the genes: equality-based diversity is meaningless here
stop=[TargetFitness(1e-3), Stagnation(200)],
max_generations=5000,
callbacks=[PrintProgress(every=100, width=0)],
seed=3,
).run()
print(f"\nbest value: {result.best.fitness:.4f} after {result.generations} generations ({result.stopped_by})")
print("best point:", np.round(result.best.genome, 3))
if "--plot" in sys.argv:
plot_history(result)
Monitoring¶
# SPDX-FileCopyrightText: 2026 CARMELO LA GAMBA
# SPDX-License-Identifier: Apache-2.0
"""Read the results of a run: the Result, the per-generation history, diversity metrics and plots.
Run from the project root: python examples/monitoring.py (plots need: pip install matplotlib)
"""
from itertools import pairwise
from phrase import TARGET, PhraseProblem
from carmelolg.galib import GeneticAlgorithm, TargetFitness
from carmelolg.galib.metrics import positional_diversity
result = GeneticAlgorithm(
PhraseProblem(),
population_size=200,
stop=[TargetFitness(len(TARGET))],
seed=42,
).run()
# 1. The Result: what the run found and why it stopped.
print(f"best genome : {result.best.genome!r}")
print(f"fitness : {result.best.fitness:g} of {len(TARGET)}")
print(f"generations : {result.generations}")
print(f"stopped by : {result.stopped_by}")
print(f"evaluations : {result.evaluations}")
# 2. The history: one GenerationStats per generation, generation 0 included.
history = result.history
first, last = history[0], history[-1]
print(f"\nbest fitness went from {first.best_fitness:g} to {last.best_fitness:g}")
print(f"mean fitness went from {first.mean_fitness:.1f} to {last.mean_fitness:.1f}")
print(f"diversity went from {first.diversity:.2f} to {last.diversity:.2f}")
# 3. Series for your own analysis: any field of GenerationStats.
best_series = [s.best_fitness for s in history]
half = len(TARGET) / 2
generation_at_half = next(s.generation for s in history if s.best_fitness >= half)
print(f"half of the phrase was right at generation {generation_at_half}")
print(f"evaluations to get there: {history[generation_at_half].evaluations}")
stalled = sum(before == after for before, after in pairwise(best_series))
print(f"generations where the best did not improve: {stalled}")
# 4. Metrics on any population: here the final one (result.population holds Individual objects).
genomes = [individual.genome for individual in result.population]
print(f"\nfinal diversity measured again: {positional_diversity(genomes):.2f}")
print(f"distinct genomes in the final population: {len(set(genomes))} of {len(genomes)}")
# 5. Plots.
try:
from carmelolg.galib.plot import plot_history
figure = plot_history(result, show=False) # show=False: get the figure without opening a window
figure.savefig("history.png", dpi=150)
print("\nplot saved to history.png")
except ImportError:
print("\nmatplotlib is not installed: pip install matplotlib")