genetic_algorithms (v2.0.0)
Modular and concurrent Genetic Algorithms (GA) library for Rust featuring:
- Clear abstractions (traits for genes, chromosomes, and configuration).
- Composable operators (selection, crossover, mutation, survivor).
- Multi-threaded execution via
rayon(fitness evaluation, reproduction, mutation in parallel). - Adaptive GA mode (dynamic crossover and mutation probabilities based on population performance).
- Elitism support (preserve top N individuals across generations).
- Compound stopping criteria (stagnation, convergence, time limit).
Cowfor minimizing unnecessary DNA copies.
Table of Contents
- Documentation
- Changelog
- Status & Key Changes 2.0.0
- Features
- Quick Example
- Full Example (Range)
- Usage
- Development
- Roadmap / Notes
- License
Documentation
Latest published docs: docs.rs/genetic_algorithms
Status & Key Changes 2.0.0
Main differences vs 1.x:
- Crate version: 2.0.0 (update your
Cargo.toml). - Structured error handling: all operators return
Result<T, GaError>instead of panicking. - Parallelism via
rayonreplacing manual thread management. GeneT::get_id()now returnsi32directly.ChromosomeT::set_dnanow usesCow<'a, [Gene]>to avoid redundant copies.- Added
Range<T>genotype alongsideBinary(supports numeric ranges). - New operators:
SinglePoint,Order(OX),BitFlip,Value,Creep,Gaussianmutations;SBX,BlendAlphacrossovers;Rankselection. - Elitism:
with_elitism(n)preserves the top N individuals across generations. - Compound stopping criteria: stagnation detection, convergence threshold, time limit.
- Per-generation statistics tracking via
GenerationStats. - Adaptive probability helpers:
aga_probabilityfor crossover & mutation. - Expanded configuration:
FixedFitness, logging levels (Off..Trace), configurable threads. - Internal benchmarks use Criterion 0.7 (pprof integration removed due to version conflict).
Features
Traits
GeneT:- Requires:
Default + Clone + Send + Sync. - Key methods:
new(),get_id() -> i32,set_id(i32).
- Requires:
ChromosomeT:- Associated:
type Gene: GeneT. - Supports:
get_dna(),set_dna(Cow<[Gene]>),set_gene(idx, gene),set_fitness_fn(...),calculate_fitness(),get_fitness(),set_fitness(f64),get_age(),set_age(i32). - Derived metric:
get_fitness_distance(&fitness_target).
- Associated:
ConfigurationT: builder-style API forGa/GaConfiguration.
Included Genotypes & Chromosomes
genotypes::Binary(boolean gene).genotypes::Range<T>(values constrained to one or more(min,max)intervals).chromosomes::Range<T>(chromosome built fromRange<T>genes).- (Custom chromosomes can be added by implementing
ChromosomeT).
Initializers
initializers::binary_random_initialization.initializers::range_random_initialization.initializers::generic_random_initialization(takes allele slice, optional unique IDs).initializers::generic_random_initialization_without_repetitions(no allele repetition).
Operators
- Selection:
Random,RouletteWheel,StochasticUniversalSampling,Tournament,Rank. - Crossover:
Cycle,MultiPoint,Uniform,SinglePoint,Order(OX),Sbx(Simulated Binary),BlendAlpha(BLX-α). - Mutation:
Swap,Inversion,Scramble,Value(Range),BitFlip(Binary),Creep(uniform perturbation),Gaussian(normal perturbation). - Survivor:
Fitness(keep best),Age(prefer younger / age-based pruning).
GA Configuration
GaConfiguration (or the Ga builder) exposes:
- Limits:
problem_solving(Minimization | Maximization | FixedFitness),max_generations,fitness_target,population_size,genes_per_chromosome,needs_unique_ids,alleles_can_be_repeated. - Selection:
number_of_couples,method. - Crossover:
number_of_points(MultiPoint),probability_min/probability_max,method,sbx_eta(SBX distribution index),blend_alpha(BLX-α alpha parameter). - Mutation:
probability_min/probability_max,method,step(Creep step size),sigma(Gaussian standard deviation). - Survivor:
survivor. - Elitism:
elitism_count— preserve the top N individuals unchanged across generations. - Stopping criteria:
StoppingCriteriawithstagnation_generations,convergence_threshold,max_duration_secs. The GA stops when any enabled criterion is met. - Infra:
adaptive_ga,number_of_threads,log_level. - Progress (present but not yet wired):
save_progress_configuration(future/experimental).
Adaptive GA
When adaptive_ga = true:
- Crossover & mutation probabilities are recomputed per parent pair using relative fitness (
f_max,f_avg). - You must set both
probability_minandprobability_maxfor crossover and mutation. Whenadaptive_ga = false: - If
probability_maxis absent, defaults to 1.0 (operator always applied).
Multithreading & Performance
with_threads(n)configures parallelism (internally usesrayon).- Selection, crossover, mutation, and fitness evaluation are parallelized each generation.
Cowprevents needless cloning of DNA vectors.
Quick Example
Minimal GA using Range<i32> chromosomes targeting fitness 0 (minimization):
use Ga;
use ConfigurationT;
use ProblemSolving;
use ;
use Range as RangeGene;
use range_random_initialization;
use Range as RangeChromosome; // Chromosome type
let alleles = vec!;
let alleles_clone = alleles.clone;
let mut ga = new;
let _population = ga
.with_genes_per_chromosome
.with_population_size
.with_initialization_fn
.with_fitness_fn
.with_selection_method
.with_crossover_method
.with_mutation_method
.with_survivor_method
.with_problem_solving
.with_max_generations
.with_fitness_target
.with_threads
.run;
Full Example (Range)
Includes adaptive GA and probabilities:
use ;
use ProblemSolving;
use ;
use Range as RangeGene;
use Range as RangeChromosome;
use range_random_initialization;
let alleles = vec!;
let alleles_clone = alleles.clone;
let mut ga = new;
let population = ga
.with_adaptive_ga
.with_genes_per_chromosome
.with_population_size
.with_initialization_fn
.with_fitness_fn
.with_selection_method
.with_crossover_method
.with_crossover_number_of_points
.with_crossover_probability_min
.with_crossover_probability_max
.with_mutation_method
.with_mutation_probability_min
.with_mutation_probability_max
.with_survivor_method
.with_problem_solving
.with_max_generations
.with_fitness_target
.with_threads
.with_logs
.run;
println!;
Usage
Add to your Cargo.toml:
[]
= "2.0.0"
Development
Build
Run Tests
Run Benchmarks
Benchmarks use Criterion and are located in benches/.
Reports are generated in target/criterion/ and can be viewed in a browser.
Run Examples
Code Quality
Roadmap / Notes
save_progress_configuration: fields present but not wired into the main loop yet (future: periodic population / best chromosome persistence).- Optional flamegraph profiling integration removed to avoid Criterion version conflicts.
- For heavy fitness functions consider external profiling tools.
License
Apache-2.0. See LICENSE file.