Core¶
Problem
¶
Bases: ABC, Generic[G]
Describes what is being optimised. Subclass it.
Required
random_genome(rng): build one random candidate solution.fitness(genome): how good one candidate is (a finite number), orfitness_batch(genomes): the fitness of many candidates at once, e.g. vectorised with numpy.
Optional overrides
maximize: set toFalsefor minimisation problems.random_gene(rng): one random gene; enables the default mutation.mutate(...): replace the default mutation entirely.crossover(...): replace the default one-point crossover.
The defaults for crossover and mutate work on str, bytes, tuple, list and numpy array genomes.
For permutations or real values use the operators in carmelolg.galib.operators; for any other
genome type override them. Operators passed to GeneticAlgorithm take precedence over these methods.
random_genome
abstractmethod
¶
fitness
¶
Return how good genome is. Must be finite and depend only on genome.
Implement this or fitness_batch. The default delegates to fitness_batch.
Source code in src/carmelolg/galib/core/problem.py
fitness_batch
¶
Return the fitness of every genome, in order.
Override it to evaluate the whole population at once, e.g. with numpy. The default calls
fitness for each genome. With workers or executor the engine calls it on chunks of the
batch, in parallel.
Source code in src/carmelolg/galib/core/problem.py
check_fitness_implemented
¶
Raise TypeError if neither fitness nor fitness_batch is overridden.
Source code in src/carmelolg/galib/core/problem.py
random_gene
¶
Return one random gene. Needed only by the default mutate.
Source code in src/carmelolg/galib/core/problem.py
crossover
¶
mutate
¶
Return a mutated copy of genome. Default: each gene reset with probability rate.
GeneticAlgorithm
¶
GeneticAlgorithm(problem: Problem[G], *, population_size: int = 100, max_generations: int = 1000, elite_size: int = 2, crossover_rate: float = 0.9, mutation_rate: float | None = None, selection: SelectionOperator[G] | None = None, crossover: CrossoverOperator[G] | None = None, mutation: MutationOperator[G] | None = None, stop: Iterable[StopCondition] = (), callbacks: Iterable[Callback] = (), seed: int | None = None, executor: Executor | None = None, history_genome_every: int = 1, workers: int | None = None, parallel: Literal['process', 'thread'] = 'process', chunk_size: int | None = None, diversity: DiversityMeasure | None = positional_diversity)
Bases: Generic[G]
The evolutionary loop.
Three ways to customise it, from light to deep:
- Parameters:
population_size,elite_size, rates,stop,callbacks,seed,workers/executor. - Operators: pass
selection=,crossover=,mutation=(seecarmelolg.galib.operators), or overridecrossover/mutateon yourProblem. Explicit arguments win over the Problem. - Subclassing:
stepis built fromreproduceandreplace, which useselect,crossover,mutateandevaluate. Override any of them, plusinitial_populationandmeasure_diversity. The engine never relies on the population being sorted.
Default strategy: tournament selection, crossover with probability crossover_rate,
per-gene mutation, generational replacement keeping the elite_size best parents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mutation_rate
|
float | None
|
per-gene mutation probability; |
None
|
stop
|
Iterable[StopCondition]
|
extra stop conditions; the run also stops after |
()
|
seed
|
int | None
|
seed of the run's own |
None
|
executor
|
Executor | None
|
evaluate fitness in parallel on your own |
None
|
history_genome_every
|
int
|
how often |
1
|
workers
|
int | None
|
shortcut for parallel evaluation: the engine creates and manages a pool of this many
workers. Mutually exclusive with |
None
|
parallel
|
Literal['process', 'thread']
|
|
'process'
|
chunk_size
|
int | None
|
genomes per task. |
None
|
diversity
|
DiversityMeasure | None
|
how to measure diversity (see |
positional_diversity
|
Source code in src/carmelolg/galib/core/engine.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | |
effective_mutation_rate
property
¶
The per-gene mutation rate actually used (mutation_rate or 1 / genome length).
run
¶
run() -> Result[G]
Evolve until a stop condition fires or max_generations generations have been evolved.
Calling run again restarts from scratch (with the same seed, the same run).
Source code in src/carmelolg/galib/core/engine.py
close
¶
Shut down the worker pool created for workers. run calls it; call it yourself (or use the
engine in a with block) after a manual initialize / step loop. Safe to call twice; a
user-supplied executor is never closed.
Source code in src/carmelolg/galib/core/engine.py
initialize
¶
Reset the run state and build the initial population (generation 0).
run calls it; call it yourself only to drive the loop manually with step.
Source code in src/carmelolg/galib/core/engine.py
step
¶
Evolve one generation. Override the building blocks below rather than this method.
Source code in src/carmelolg/galib/core/engine.py
initial_population
¶
initial_population() -> list[Individual[G]]
Build and evaluate population_size random individuals.
evaluate
¶
evaluate(genomes: Sequence[G]) -> list[Individual[G]]
Compute the fitness of new genomes: problem.fitness_batch on the whole batch, or, with
workers / executor, on chunks of it in parallel (see evaluate_parallel).
Source code in src/carmelolg/galib/core/engine.py
evaluate_parallel
¶
Split genomes into chunks, evaluate each with problem.fitness_batch on executor and
return the values in order. Override to change how work is divided.
Source code in src/carmelolg/galib/core/engine.py
select
¶
select(population: Sequence[Individual[G]], count: int) -> list[Individual[G]]
Pick count parents.
Source code in src/carmelolg/galib/core/engine.py
reproduce
¶
reproduce(population: Sequence[Individual[G]]) -> list[Individual[G]]
Build population_size - elite_size evaluated children.
Source code in src/carmelolg/galib/core/engine.py
replace
¶
replace(population: Sequence[Individual[G]], offspring: Sequence[Individual[G]]) -> list[Individual[G]]
Build the next generation: the elite_size best parents plus all the offspring.
The result is sorted best first for convenience; the engine does not depend on it.
Source code in src/carmelolg/galib/core/engine.py
measure_diversity
¶
measure_diversity(population: Sequence[Individual[G]]) -> float | None
Diversity of the population, with the diversity measure given to the constructor
(default: :func:carmelolg.galib.metrics.positional_diversity). None if disabled or not measurable.
Source code in src/carmelolg/galib/core/engine.py
Individual
dataclass
¶
Bases: Generic[G]
A genome together with its evaluation.
fitness is the value returned by the Problem.
score is the same value oriented so that higher is always better (-fitness when
Problem.maximize is False). Operators compare score, so they never need to know
whether the problem maximises or minimises.
Individuals are immutable; treat genome as read-only even when it is a list or an array.
They compare by identity (eq=False): genomes such as numpy arrays have no single truth value
for ==. Compare genome explicitly when you need value equality.
GenerationStats
dataclass
¶
GenerationStats(generation: int, best_fitness: float, mean_fitness: float, worst_fitness: float, diversity: float | None, best_genome: G | None, evaluations: int)
Bases: Generic[G]
Snapshot of the population after a generation (generation 0 = initial population).
Result
dataclass
¶
Result(best: Individual[G], generations: int, stopped_by: str, evaluations: int, history: list[GenerationStats[G]] = list(), population: list[Individual[G]] = list())
Bases: Generic[G]
Outcome of GeneticAlgorithm.run.