Skip to main content

Crate genetic_algorithms

Crate genetic_algorithms 

Source
Expand description

§genetic_algorithms

A modular, performant Rust library for evolutionary computation and metaheuristic optimization. Provides 11 optimization engines, 45+ composable operators, a full lifecycle observer system, and framework extensions — all generic over chromosome and gene types via traits.

Published on crates.io as genetic_algorithms. API reference on docs.rs.

§Quick Start

Minimize the Rastrigin function using 5-dimensional Range<f64> chromosomes with the standard Ga engine:

use genetic_algorithms::chromosomes::Range as RangeChromosome;
use genetic_algorithms::configuration::ProblemSolving;
use genetic_algorithms::ga::Ga;
use genetic_algorithms::genotypes::Range as RangeGenotype;
use genetic_algorithms::initializers::range_random_initialization;
use genetic_algorithms::operations::{Crossover, Mutation, Selection, Survivor};
use genetic_algorithms::traits::{ConfigurationT, CrossoverConfig, MutationConfig, SelectionConfig, StoppingConfig};
use genetic_algorithms::{CompositeObserver, LogObserver};
use std::sync::Arc;

let fitness_fn = |dna: &[RangeGenotype<f64>]| -> f64 {
    let a = 10.0;
    let n = dna.len() as f64;
    a * n + dna.iter()
        .map(|g| g.value.powi(2) - a * (2.0 * std::f64::consts::PI * g.value).cos())
        .sum::<f64>()
};

let alleles = vec![RangeGenotype::new(0, vec![(-5.12, 5.12)], 0.0_f64)];
let alleles_clone = alleles.clone();

let mut ga = Ga::new()
    .with_genes_per_chromosome(5_usize)
    .with_population_size(100)
    .with_initialization_fn(move |genes_per_chromosome, _, _| {
        range_random_initialization(genes_per_chromosome, Some(&alleles_clone), Some(false))
    })
    .with_fitness_fn(fitness_fn)
    .with_selection_method(Selection::Tournament)
    .with_crossover_method(Crossover::Uniform)
    .with_mutation_method(Mutation::Gaussian)
    .with_survivor_method(Survivor::Fitness)
    .with_problem_solving(ProblemSolving::Minimization)
    .with_max_generations(500)
    .with_observer(Arc::new(CompositeObserver::new().add(Arc::new(LogObserver))))
    .build()
    .expect("Invalid configuration");

let population = ga.run().expect("GA run failed");
println!("Best fitness: {:.4}", population.best_chromosome.fitness);

§Engines (11 total)

This crate offers 11 optimization engines, each designed for specific problem types:

EngineModuleObjectivesProblem TypeKey Strength
Ga<U>gaSingleContinuous / CombinatorialGeneral-purpose evolutionary optimization
DeEngine<U>deSingleContinuousFast convergence on real-valued problems via differential mutation
ScatterEngine<U>scatterSingleContinuous / CombinatorialReference-set based diversification
CellularEngine<U>cellularSingleContinuous / CombinatorialSpatial diversity via toroidal grid neighborhoods
AlpsEngine<U>alpsSingleContinuous / CombinatorialAge-layered population structure for sustained diversity
IslandGa<U>islandSingleAnyParallel sub-populations with configurable migration topologies
Nsga2Ga<U>nsga22Continuous / CombinatorialFast Pareto ranking with crowding distance
Nsga3Ga<U>nsga33+ContinuousReference-point based niching for many-objective problems
MoeaDGa<U>moead2+ContinuousDecomposition-based scalarization (Tchebycheff, PBI, weighted sum)
Spea2Ga<U>spea22+Continuous / CombinatorialStrength-Pareto archive with k-nearest density estimation
SmsEmoaGa<U> / IbeaGa<U>sms_emoa / ibea2+ContinuousHypervolume contribution / indicator-based selection

§Single-Objective Engines

  • Ga<U> — Standard single-population GA. The general-purpose engine with full operator support (all selection, crossover, mutation, survivor strategies), adaptive GA mode, elitism, extension strategies, niching/fitness sharing, and checkpointing.
  • DeEngine<U> — Differential Evolution engine with 5 mutation strategies (rand/1, best/1, current-to-best/1, best/2, rand/2) and two adaptive variants (JADE, L-SHADE) with binomial and exponential crossover. Best for continuous, real-valued optimization.
  • ScatterEngine<U> — Scatter Search metaheuristic that maintains a diverse reference set, combines solutions via linear combination, and applies improvement methods. Strong on combinatorial optimization with rugged landscapes.
  • CellularEngine<U> — Cellular GA that arranges the population on a 2D toroidal grid. Supports 4 neighborhood topologies (Von Neumann, Moore, Compact R2, Linear) and synchronous or asynchronous update. Preserves spatial diversity.
  • AlpsEngine<U> — Age-Layered Population Structure that organizes individuals into age layers with 3 age schemes (Linear, Fibonacci, Polynomial). Enables cross-layer mating and periodic injection for sustained exploration.
  • IslandGa<U> — Island model GA that evolves multiple sub-populations in parallel with configurable migration topology (ring, fully connected, random), frequency, and migrant selection. Works with any chromosome type and can wrap Nsga2Ga.

§Multi-Objective Engines

  • Nsga2Ga<U> — NSGA-II: fast non-dominated sorting with crowding distance for diversity. Efficient O(MN²) ranking. Standard choice for 2-objective problems.
  • Nsga3Ga<U> — NSGA-III: reference-point based selection using Das-Dennis weights and ASF-based normalization. Scales to 3+ objectives where crowding distance loses effectiveness. Supports 2 to 15+ objectives.
  • MoeaDGa<U> — MOEA/D: decomposes multi-objective problems into scalar sub-problems using Tchebycheff, PBI, or weighted sum aggregation. Neighbor-based mating preserves convergence along the Pareto front.
  • Spea2Ga<U> — SPEA2: strength-Pareto approach with an external archive, k-nearest neighbor density estimation, and truncation mechanism. Effective on problems with irregular Pareto fronts.
  • SmsEmoaGa<U> — SMS-EMOA: steady-state (mu+1) MOEA that selects the individual with the smallest hypervolume contribution for removal. Precise hypervolume-based convergence.
  • IbeaGa<U> — IBEA: indicator-based MOEA using the I_epsilon+ binary indicator with exponential fitness scaling. No diversity preservation mechanism required — the indicator implicitly balances convergence and diversity.

§Feature Flags

FlagDescriptionDefault
serdeSerialization/deserialization for checkpoint save/load via serde_jsonOff
benchmarksStandard benchmark functions (Sphere, Rastrigin, Rosenbrock, ZDT, DTLZ) and multi-objective quality indicatorsOff
visualizationPNG/SVG fitness plots, diversity charts, and histogram generation via plottersOff
observer-tracingStructured tracing-crate spans and events in the observer systemOff
observer-metricsPer-generation metrics (gauges, counters, histograms) via the metrics facadeOff

§Key Concepts

§Genotypes & Chromosomes

The library separates the concept of a gene (a single atomic unit of information) from a chromosome (a sequence of genes that represents a candidate solution). Genes implement GeneT and chromosomes implement ChromosomeT.

Built-in gene types: Binary (boolean), Range<T> (bounded real/integer values), List<T> (finite symbolic alphabets).

Built-in chromosome types: chromosomes::Binary, chromosomes::Range<T>, chromosomes::ListChromosome<T>.

Custom chromosomes can be created by implementing ChromosomeT.

§Configuration

All engines use a fluent builder pattern via the ConfigurationT trait. Each engine has its own configuration struct (GaConfiguration, DeConfiguration, etc.) with builder methods for limits, operators, stopping criteria, and engine-specific parameters.

See the configuration module for all shared configuration types.

§Operators

Five operator categories are available, dispatched via enums with factory functions:

  • Selection (Selection): Random, RouletteWheel, SUS, Tournament, Rank, Boltzmann, Truncation, Clearing
  • Crossover (Crossover): Cycle, MultiPoint, Uniform, SinglePoint, Order (OX), PMX, SBX, BlendAlpha (BLX-alpha), Arithmetic, Edge Recombination, Clone, Rejuvenate
  • Mutation (Mutation): Swap, Inversion, Scramble, Value, BitFlip, Creep, Gaussian, Polynomial, NonUniform, Insertion, Cauchy, LevyFlight, Uniform, ListValue
  • Survivor (Survivor): Fitness, Age, MuPlusLambda, MuCommaLambda, DeterministicCrowding
  • Extension (Extension): Noop, MassExtinction, MassGenesis, MassDegeneration, MassDeduplication

See the operations module for full documentation of each operator.

§Observer System

The GaObserver<U> trait provides 11 lifecycle hooks that fire during engine execution (selection, crossover, mutation, fitness evaluation, survivor selection, new best, stagnation, extension trigger, generation end, run start/end). Built-in observers include LogObserver, CompositeObserver<U>, MetricsObserver (feature observer-metrics), TracingObserver (feature observer-tracing), and NoopObserver. Engine-specific sub-traits exist for IslandGaObserver, Nsga2Observer, Nsga3Observer, Spea2Observer, MoeaDObserver, SmsEmoaObserver, and IbeaObserver.

Zero overhead when no observer is attached (stored as Option<Arc<dyn GaObserver<U>>>).

§Constraints

The ConstraintHandling system provides constraint enforcement through penalty strategies (PenaltyStrategy — Static, Dynamic, Adaptive, Death) and feasibility rules. See the constraints module.

§Hall of Fame

The HallOfFame<U> archive stores elite solutions across generations, with configurable capacity and optional diversity enforcement via DistanceMetric. See the hall_of_fame module.

§Adaptive Operator Selection (AOS)

The AosStrategy and AosState types implement credit-assignment based operator selection. See the aos module.

§Initializers

Population initialization functions in the initializers module: binary_random_initialization, range_random_initialization, list_random_initialization, list_random_initialization_without_repetitions, generic_random_initialization, generic_random_initialization_without_repetitions.

§When to Use Which Engine

If your problem is…Use this engine…Because…
General single-objective, any variable typeGa<U>Full operator support, adaptive mode, niching, extensions
Continuous, real-valued, single-objectiveDeEngine<U>5 strategies + JADE/L-SHADE, fast convergence
Combinatorial with rugged landscapeScatterEngine<U>Reference set diversification avoids local optima
Single-objective, needs spatial diversityCellularEngine<U>Grid-based neighborhoods preserve niche exploration
Single-objective, sustained exploration neededAlpsEngine<U>Age layers prevent premature convergence
Parallel / distributed single-objectiveIslandGa<U>Independent sub-populations with periodic migration
Exactly 2 objectivesNsga2Ga<U>Fast O(MN²) ranking, well-established baseline
3+ objectives (many-objective)Nsga3Ga<U>Reference points scale beyond crowding distance
2+ objectives, continuousMoeaDGa<U>Decomposition is efficient and interpretable
2+ objectives, irregular frontSpea2Ga<U>Archive + density estimation handles complex fronts
2+ objectives, precise convergenceSmsEmoaGa<U>Hypervolume contribution directly measures quality
2+ objectives, flexible indicatorIbeaGa<U>Indicator-based selection needs no extra diversity mechanism

§Examples

The examples/ directory contains 19 runnable examples covering all engines and features. Run any example with cargo run --example <name> --features <features>.

See the README for a full examples catalog and the docs/ directory for per-engine guides with complete usage examples.

§Further Reading

Re-exports§

pub use ga::TerminationCause;
pub use observer::AllObserver;
pub use observer::CompositeObserver;
pub use observer::ExtensionEvent;
pub use observer::GaObserver;
pub use observer::IslandGaObserver;
pub use observer::LogObserver;
pub use observer::MoeaDObserver;
pub use observer::IbeaObserver;
pub use observer::SmsEmoaObserver;
pub use observer::Spea2Observer;
pub use observer::NoopObserver;
pub use observer::Nsga2Observer;
pub use observer::Nsga3Observer;
pub use constraints::ConstraintHandling;
pub use constraints::PenaltyStrategy;
pub use hall_of_fame::DistanceMetric;
pub use hall_of_fame::HallOfFame;
pub use hall_of_fame::HallOfFameConfig;
pub use aos::AosState;
pub use aos::AosStrategy;

Modules§

alps
Age-Layered Population Structure (ALPS) engine.
aos
Adaptive Operator Selection (AOS) core module.
cellular
Cellular Genetic Algorithm engine.
chromosomes
Built-in chromosome types.
configuration
Configuration — builder-based GA configuration types.
constraints
Constraints — penalty-based constraint handling for single-objective GA.
de
Differential Evolution engine.
error
Error — GaError enum and Result type alias for the crate.
extension
Extension strategies for population diversity control.
fitness
Fitness — fitness function helpers and wrappers.
ga
Standard Genetic Algorithm (Ga)
genotypes
Built-in gene (genotype) types.
hall_of_fame
Hall of Fame — bounded archive of best solutions across a GA run.
ibea
IBEA — Indicator-Based Evolutionary Algorithm.
initializers
Population initialization functions.
island
Island Model (IslandGa)
moead
MOEA/D — Decomposition-based Multi-Objective Evolutionary Algorithm.
multi_objective
Shared multi-objective optimisation primitives.
niching
Fitness sharing (niching) utilities for promoting population diversity.
nsga2
NSGA-II — Non-dominated Sorting Genetic Algorithm II.
nsga3
NSGA-III — Reference-point-based Non-dominated Sorting Genetic Algorithm.
observer
Structured lifecycle observer for the GA execution loop.
operations
Operations — operator enums, factory dispatchers, and runtime selection.
population
Population — chromosome container for evolving generations.
reporter
Reporter — deprecated lifecycle hooks for the GA execution loop.
rng
RNG — seedable random number generation for reproducible GA runs.
scatter
Scatter Search engine.
sms_emoa
SMS-EMOA — S-Metric Selection Evolutionary Multi-Objective Algorithm.
spea2
SPEA2 — Strength Pareto Evolutionary Algorithm 2.
stats
Stats — per-generation statistics for tracking GA convergence.
traits
Traits — core abstraction contracts for the genetic algorithm framework.
validators