### Run Examples Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/CLAUDE.md Executes example binaries, typically in release mode for performance. ```bash cargo run --example evolve_nqueens --release cargo run --example hill_climb_nqueens --release cargo run --example permutate_knapsack --release ``` -------------------------------- ### Profile Evolve Binary Example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/README.md Run this command to profile the 'profile_evolve_binary' example, generating a flamegraph for performance analysis. ```bash cargo run --example profile_evolve_binary --release -- --bench --profile-time 5 ``` -------------------------------- ### Basic Evolve Setup with Binary Genotype Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/README.md Demonstrates the fundamental setup for evolving a binary genotype. It configures selection, crossover, mutation, fitness function, and population targets. ```rust let genotype = BinaryGenotype::builder() .with_genes_size(100) .build()?; let evolve = Evolve::builder() .with_genotype(genotype) .with_select(SelectElite::new(0.5, 0.02)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .with_fitness(MyFitness) .with_target_population_size(100) .with_target_fitness_score(100) .call()?; ``` -------------------------------- ### Minimal Evolve strategy example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md A basic end-to-end example demonstrating the flow from genotype definition to fitness calculation, strategy execution, and result retrieval using the Evolve strategy. ```rust use genetic_algorithm::strategy::evolve::prelude::*; #[derive(Clone, Debug)] struct CountTrue; impl Fitness for CountTrue { type Genotype = BinaryGenotype; fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype, ) -> Option { Some(chromosome.genes.iter().filter(|&&v| v).count() as FitnessValue) } } fn main() { let genotype = BinaryGenotype::builder() .with_genes_size(10) .build() .unwrap(); let evolve = Evolve::builder() .with_genotype(genotype) .with_target_population_size(100) .with_max_stale_generations(100) .with_fitness(CountTrue) .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .call() .unwrap(); let (best_genes, best_fitness_score) = evolve.best_genes_and_fitness_score().unwrap(); println!("genes: {:?}, score: {}", best_genes, best_fitness_score); } ``` -------------------------------- ### Evolve Large Genotype Example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/README.md This link points to an example demonstrating the 'evolve_large_genotype' functionality, relevant for performance considerations with large chromosomes. ```rust ../main/examples/evolve_large_genotype.rs ``` -------------------------------- ### Duration Examples Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Illustrates how to create and use `std::time::Duration` for representing time intervals. Examples include creating durations from seconds, milliseconds, and with nanosecond precision. ```rust pub use std::time::Duration; // Examples: let d = Duration::from_secs(5); let d = Duration::from_millis(100); let d = std::time::Duration::new(1, 500_000_000); // 1.5 seconds ``` -------------------------------- ### Permutate Configuration Example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/configuration.md Configures a Permutate genetic algorithm with binary genotype, custom fitness, exhaustive variant, and a target fitness score. ```rust let permutate = Permutate::builder() .with_genotype(BinaryGenotype::builder().with_genes_size(16).build()) .with_fitness(MyFitness) .with_variant(PermutateVariant::Exhaustive) .with_target_fitness_score(16) .call()?; ``` -------------------------------- ### MassExtinction Example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Instantiates a `MassExtinction` extension, configuring it to trigger when the population size reaches 10, culling 10% and retaining the best 2%. ```rust let extension = ExtensionMassExtinction::new(10, 0.1, 0.02); // When cardinality drops to 10, remove 10% and keep best 2% ``` -------------------------------- ### Visualize Permutation Mutation Types Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/README.md Run this example to generate a visualization of different permutation mutation types used for numeric/continuous genotypes. ```bash cargo run --example visualize_permutate_mutation_types --release ``` -------------------------------- ### HillClimb Strategy Configuration Example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/configuration.md Shows how to configure the HillClimb strategy with required options like genotype and fitness, and optional parameters such as variant, population size, and reporter. ```rust let hill_climb = HillClimb::builder() .with_genotype(UniqueGenotype::::builder().with_genes_size(8).build()?) .with_fitness(NQueensFitness) .with_variant(HillClimbVariant::SteepestAscent) .with_max_stale_generations(100) .with_target_population_size(200) .with_reporter(HillClimbReporterSimple::new(10)) .call()?; ``` -------------------------------- ### Evolve Strategy Full Configuration Example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/configuration.md Demonstrates how to configure all available options for the Evolve strategy, including genotype, selection, crossover, mutation, fitness, ending conditions, and various optional parameters like population size, fitness ordering, parallel fitness evaluation, and abort flags. ```rust use genetic_algorithm::strategy::evolve::prelude::*; use std::sync::Arc; use std::sync::atomic::AtomicBool; let genotype = BinaryGenotype::builder() .with_genes_size(100) .with_genes_hashing(true) .with_chromosome_recycling(true) .build()?; let abort_flag = Arc::new(AtomicBool::new(false)); let evolve = Evolve::builder() // Required .with_genotype(genotype) .with_select(SelectElite::new(0.5, 0.02)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .with_fitness(CountTrue) // Ending conditions (at least one) .with_target_fitness_score(100) .with_max_stale_generations(1000) .with_max_generations(100_000) // Optional .with_target_population_size(100) .with_fitness_ordering(FitnessOrdering::Maximize) .with_par_fitness(true) .with_fitness_cache(1000) .with_valid_fitness_score(50) .with_max_chromosome_age(50) .with_replace_on_equal_fitness(true) .with_abort_flag(abort_flag.clone()) .with_extension(ExtensionMassExtinction::new(10, 0.1, 0.02)) .with_reporter(EvolveReporterSimple::new(100)) .with_rng_seed_from_u64(12345) .call()?; let (best_genes, best_score) = evolve.best_genes_and_fitness_score().unwrap(); ``` -------------------------------- ### Rust Genetic Algorithm Quick Usage Example Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/README.md Demonstrates how to set up and run a genetic algorithm for binary optimization. It includes defining the genotype, fitness function, and evolution strategy with specific parameters for selection, crossover, and mutation. ```rust use genetic_algorithm::strategy::evolve::prelude::*; // the search space let genotype = BinaryGenotype::builder() // boolean alleles .with_genes_size(100) // 100 genes per chromosome .build() .unwrap(); println!("{}", genotype); // the search goal to optimize towards (maximize or minimize) #[derive(Clone, Debug)] pub struct CountTrue; impl Fitness for CountTrue { type Genotype = BinaryGenotype; // Genes = Vec fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype ) -> Option { Some(chromosome.genes.iter().filter(|&value| *value).count() as FitnessValue) } } // the search strategy let evolve = Evolve::builder() .with_genotype(genotype) .with_select(SelectElite::new(0.5, 0.02)) // sort the chromosomes by fitness to determine crossover order. Strive to replace 50% of the population with offspring. Allow 2% through the non-generational best chromosomes gate before selection and replacement .with_crossover(CrossoverUniform::new(0.7, 0.8)) // crossover all individual genes between 2 chromosomes for offspring with 70% parent selection (30% do not produce offspring) and 80% chance of crossover (20% of parents just clone) .with_mutate(MutateSingleGene::new(0.2)) // mutate offspring for a single gene with a 20% probability per chromosome .with_fitness(CountTrue) // count the number of true values in the chromosomes .with_fitness_ordering(FitnessOrdering::Maximize) // optional, default is Maximize, aim towards the most true values .with_target_population_size(100) // evolve with 100 chromosomes .with_target_fitness_score(100) // goal is 100 times true in the best chromosome .with_reporter(EvolveReporterSimple::new(100)) // optional builder step, report every 100 generations .call() .unwrap(); println!("{}", evolve); // it's all about the best genes after all let (best_genes, best_fitness_score) = evolve.best_genes_and_fitness_score().unwrap(); assert_eq!(best_genes, vec![true; 100]); assert_eq!(best_fitness_score, 100); ``` -------------------------------- ### Example: EuclideanDistance Fitness Implementation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md An example implementation of the Fitness trait for a RangeGenotype that calculates the Euclidean distance to a target vector. It negates the distance for minimization. ```rust use genetic_algorithm::fitness::prelude::*; #[derive(Clone, Debug)] pub struct EuclideanDistance { pub target: Vec, pub precision: f32, } impl Fitness for EuclideanDistance { type Genotype = RangeGenotype; fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype ) -> Option { let distance: f32 = chromosome .genes .iter() .zip(self.target.iter()) .map(|(actual, target)| (actual - target).powi(2)) .sum::() .sqrt(); // Negate for minimization: smaller distance = higher fitness Some((distance / self.precision).neg() as FitnessValue) } } ``` -------------------------------- ### Genotype with Hashing for Fitness Cache Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Example of building a genotype with hashing enabled, which is a prerequisite for using the fitness cache. ```rust let genotype = BinaryGenotype::builder() .with_genes_size(100) .with_genes_hashing(true) // Required for cache .build()?; Evolve::builder() .with_genotype(genotype) .with_fitness_cache(500) // Enable LRU caching // ... rest of config ``` -------------------------------- ### Profile Flamegraph Location Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/README.md The flamegraph generated by profiling the 'profile_evolve_binary' example can be found at this path. ```text ./target/criterion/profile_evolve_binary/profile/flamegraph.svg ``` -------------------------------- ### Custom Extension Implementation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Example of implementing a custom genetic algorithm extension. Use for custom logic, such as injecting diversity when population cardinality is low. ```rust use genetic_algorithm::strategy::evolve::prelude::*; #[derive(Clone, Debug)] pub struct MyExtension; impl Extension for MyExtension { type Genotype = BinaryGenotype; fn after_selection_complete>( &mut self, genotype: &mut Self::Genotype, state: &mut EvolveState, config: &EvolveConfig, reporter: &mut SR, rng: &mut R, ) { // Custom logic here if let Some(cardinality) = state.population_cardinality() { if cardinality < 5 { // Inject diversity } } } } ``` -------------------------------- ### BinaryGenotype Example Usage Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/genotypes.md Demonstrates creating a random chromosome using a configured BinaryGenotype. The resulting chromosome's genes will be a Vec of the specified size. ```rust use genetic_algorithm::strategy::evolve::prelude::*; let genotype = BinaryGenotype::builder() .with_genes_size(100) .build()?; let chromosome = genotype.chromosome_constructor_random(&mut rng); // chromosome.genes is Vec with 100 elements ``` -------------------------------- ### Example: CountTrue Fitness Implementation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md An example implementation of the Fitness trait for a BinaryGenotype that counts the number of true values (genes) in a chromosome. ```rust use genetic_algorithm::fitness::prelude::*; #[derive(Clone, Debug)] pub struct CountTrue; impl Fitness for CountTrue { type Genotype = BinaryGenotype; fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype ) -> Option { Some( chromosome .genes .iter() .filter(|&value| *value) .count() as FitnessValue ) } } ``` -------------------------------- ### Execute HillClimb Search Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/hillclimb-permutate.md Example of executing a single HillClimb run with specific configurations. Requires importing prelude and defining a genotype and fitness function. ```rust use genetic_algorithm::strategy::hill_climb::prelude::*; let genotype = UniqueGenotype::::builder() .with_genes_size(8) .build()?; let hill_climb = HillClimb::builder() .with_genotype(genotype) .with_fitness(MyFitness) .with_variant(HillClimbVariant::SteepestAscent) .with_max_stale_generations(1000) .call()?; let (best_genes, score) = hill_climb.best_genes_and_fitness_score()?; ``` -------------------------------- ### Custom Allele Implementation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Provides an example of implementing the `Allele` trait for a custom struct `MyAllele` containing an `i32`. ```rust #[derive(Clone, Debug, PartialEq)] pub struct MyAllele(i32); impl Allele for MyAllele {} ``` -------------------------------- ### ListGenotype Construction Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/genotypes.md Example of constructing a ListGenotype using its builder pattern. Requires setting gene size and the set of possible alleles. ```rust let genotype = ListGenotype::builder() .with_genes_size(50) .with_alleles(vec!['a', 'b', 'c', 'd']) .build()?; ``` -------------------------------- ### Heterogeneous Optimization with MultiRangeGenotype Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS_TEMPLATES.md Employ Evolve with MultiRangeGenotype for optimizing parameters with diverse types and ranges. This example optimizes four parameters: a boolean, an algorithm choice, a learning rate, and a batch size. ```rust use genetic_algorithm::strategy::evolve::prelude::*; // Optimize 4 parameters with different ranges and mutation behaviors: // Gene 0: boolean flag (0 or 1) // Gene 1: algorithm choice (0, 1, 2, 3, or 4) // Gene 2: learning rate (0.001 to 1.0, continuous) // Gene 3: batch size (16 to 512, discrete integer steps) #[derive(Clone, Debug)] struct HyperparamFitness { precision: f32 } impl Fitness for HyperparamFitness { type Genotype = MultiRangeGenotype; fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype, ) -> Option { let flag = chromosome.genes[0]; // 0.0 or 1.0 (Discrete) let algorithm = chromosome.genes[1]; // 0.0..4.0 (Discrete) let learning_rate = chromosome.genes[2]; // 0.001..1.0 (continuous) let batch_size = chromosome.genes[3]; // 16.0..512.0 (Discrete) // ... your evaluation logic ... let score = learning_rate * flag + algorithm * 0.1 - batch_size * 0.001; Some((score / self.precision) as FitnessValue) } } fn main() { let genotype = MultiRangeGenotype::::builder() .with_allele_ranges(vec![ 0.0..=1.0, // Gene 0: boolean 0.0..=4.0, // Gene 1: algorithm choice 0.001..=1.0, // Gene 2: learning rate 16.0..=512.0, // Gene 3: batch size ]) .with_mutation_types(vec![ MutationType::Discrete, // boolean: 0 or 1 MutationType::Discrete, // enum: 0,1,2,3,4 MutationType::StepScaled(vec![0.1, 0.01, 0.001]), // continuous refinement MutationType::Discrete, // integer steps ]) .build() .unwrap(); let evolve = Evolve::builder() .with_genotype(genotype) .with_target_population_size(100) .with_max_stale_generations(1000) .with_fitness(HyperparamFitness { precision: 1e-5 }) .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .call() .unwrap(); let (best_genes, best_fitness_score) = evolve.best_genes_and_fitness_score().unwrap(); println!("genes: {:?}, score: {}", best_genes, best_fitness_score); } ``` -------------------------------- ### BinaryGenotype Construction Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/genotypes.md Example of constructing a BinaryGenotype using its builder pattern. Allows setting gene size, hashing, and chromosome recycling options. ```rust let genotype = BinaryGenotype::builder() .with_genes_size(100) .with_genes_hashing(true) .with_chromosome_recycling(true) .build()?; ``` -------------------------------- ### ListGenotype Example Usage Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/genotypes.md Demonstrates creating a random chromosome using a configured ListGenotype. The resulting chromosome's genes will be a Vec of the specified size, with values from the provided alleles. ```rust use genetic_algorithm::strategy::evolve::prelude::*; let genotype = ListGenotype::builder() .with_genes_size(100) .with_alleles(vec!['a', 'b', 'c']) .build()?; let chromosome = genotype.chromosome_constructor_random(&mut rng); // chromosome.genes is Vec with 100 elements ``` -------------------------------- ### Handling Genotype Configuration Errors Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/errors.md Example of how to handle TryFromGenotypeBuilderError when building a genotype. This pattern is useful for logging or taking corrective action on invalid configurations. ```rust use genetic_algorithm::genotype::*; let result = BinaryGenotype::builder() .with_genes_size(0) // Invalid! .build(); match result { Ok(genotype) => { // Use genotype } Err(TryFromGenotypeBuilderError(msg)) => { eprintln!("Genotype configuration error: {}", msg); // Handle error - typically log and exit } } ``` -------------------------------- ### Build MultiListGenotype with Heterogeneous Gene Types Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/genotypes.md Constructs a MultiListGenotype with genes of different types, each sampled from its own list of alleles. This example demonstrates using characters, strings, and booleans as gene values. ```rust use genetic_algorithm::strategy::evolve::prelude::*; let genotype = MultiListGenotype::builder() .with_genes_size(3) .with_alleles_list(vec![ vec!['a', 'b'], vec!['x', 'y', 'z'], vec![true, false], ]) .build()?; ``` -------------------------------- ### Exhaustive Search with Permutate Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS_TEMPLATES.md Use Permutate for exhaustive search when the genotype size is small enough to iterate through all combinations. This example demonstrates optimizing a binary genotype of size 16. ```rust use genetic_algorithm::strategy::permutate::prelude::*; #[derive(Clone, Debug)] struct MyFitness; impl Fitness for MyFitness { type Genotype = BinaryGenotype; fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype, ) -> Option { Some(chromosome.genes.iter().filter(|&&v| v).count() as FitnessValue) } } fn main() { let genotype = BinaryGenotype::builder() .with_genes_size(16) // 2^16 = 65536 combinations, feasible .build() .unwrap(); let permutate = Permutate::builder() .with_genotype(genotype) .with_fitness(MyFitness) .call() .unwrap(); let (best_genes, best_fitness_score) = permutate.best_genes_and_fitness_score().unwrap(); println!("best: {:?}, score: {}", best_genes, best_fitness_score); } ``` -------------------------------- ### Generate Documentation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/CLAUDE.md Generates and opens project documentation. ```bash cargo doc --open ``` -------------------------------- ### Build Project Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/CLAUDE.md Builds the Rust project. Use --release for optimized builds. ```bash cargo build cargo build --release ``` -------------------------------- ### Get Population Size Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Returns the current number of chromosomes within the population. ```rust pub fn size(&self) -> usize ``` -------------------------------- ### Retrieve Best Generation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md Get the generation number in which the best solution was found. This is available on all strategy types. ```rust let best_generation = evolve.best_generation(); ``` -------------------------------- ### Run All Tests Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/CLAUDE.md Executes all tests in the project. Use -- --nocapture for verbose output. ```bash cargo test cargo test -- --nocapture ``` -------------------------------- ### Get Chromosome Age Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Returns the number of generations a chromosome has existed. Newly created offspring have an age of 0. ```rust pub fn age(&self) -> usize ``` ```rust if chromosome.age() > max_age { // Remove old chromosome } ``` -------------------------------- ### One-shot vs. Build-then-Run Execution Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md Demonstrates two patterns for running an Evolve strategy: a one-shot call that builds and runs in a single step, and a pattern where the strategy is built first and then executed separately, allowing for state inspection. ```rust // Pattern 1: One-shot (build + run in one call) let evolve = Evolve::builder() .with_genotype(genotype) // ... other builder steps ... .call() // builds AND runs .unwrap(); // Pattern 2: Build then run (inspect state after) let mut evolve = Evolve::builder() .with_genotype(genotype) // ... other builder steps ... .build() // only builds .unwrap(); evolve.call(); // runs separately ``` -------------------------------- ### Quick Optimization Configuration Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/configuration.md Use this configuration for general-purpose optimization tasks. It sets up basic selection, crossover, and mutation rates with a target population size and maximum stale generations. ```rust Evolve::builder() .with_select(SelectElite::new(0.5, 0.02)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .with_target_population_size(100) .with_max_stale_generations(1000) ``` -------------------------------- ### Get Chromosome Fitness Score Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Returns the calculated fitness score for a chromosome. Returns `None` if the fitness has not yet been evaluated. ```rust pub fn fitness_score(&self) -> Option ``` ```rust match chromosome.fitness_score() { Some(score) => println!("Fitness: {}", score), None => println!("Not evaluated yet"), } ``` -------------------------------- ### Import prelude for Evolve strategy Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md This single import brings in all necessary types for the Evolve strategy. Similar preludes are available for other strategies like HillClimb and Permutate. ```rust use genetic_algorithm::strategy::evolve::prelude::* ``` -------------------------------- ### FitnessCache Construction Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/types.md Illustrates how to initialize a `FitnessCache` with a specified maximum size. This is typically done via a builder pattern. ```rust .with_fitness_cache(1000) // Size = 1000 entries ``` -------------------------------- ### Handle Strategy Configuration Errors Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/errors.md Demonstrates how to catch and report errors when configuring an Evolve strategy. This is useful when many configuration steps are optional or can lead to invalid states. ```Rust use genetic_algorithm::strategy::evolve::prelude::*; let result = Evolve::builder() .with_genotype(genotype) // Missing: .with_select() // Missing: .with_crossover() // Missing: .with_mutate() // Missing: .with_fitness() // Missing: ending condition .call(); match result { Ok(evolve) => { let (best_genes, score) = evolve.best_genes_and_fitness_score().unwrap(); println!("Best score: {}", score); } Err(TryFromStrategyBuilderError(msg)) => { eprintln!("Strategy configuration error: {}", msg); // Errors: // "Evolve: missing fitness" // "Evolve: missing select" // "Evolve: missing crossover" // "Evolve: missing mutate" // "Evolve: missing at least one ending condition" } } ``` -------------------------------- ### Get Chromosome Genes Hash Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Retrieves the cached hash of the chromosome's genes if gene hashing is enabled. This is useful for deduplication or caching. ```rust pub fn genes_hash(&self) -> Option ``` ```rust if let Some(hash) = chromosome.genes_hash() { // Use hash for deduplication or caching } ``` -------------------------------- ### Setting FitnessOrdering in Evolve Builder Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Shows how to configure the genetic algorithm to minimize fitness scores by using the `with_fitness_ordering` method on the Evolve builder. ```rust Evolve::builder() .with_fitness_ordering(FitnessOrdering::Minimize) // ... rest of config ``` -------------------------------- ### Repeatedly Execute Permutation Search Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/hillclimb-permutate.md Runs multiple permutation search runs sequentially. Useful for exploring different starting points or variations. ```rust pub fn call_repeatedly( self, max_repeats: usize ) -> Result<(Permutate<...>, Vec>), TryFromBuilderError> ``` -------------------------------- ### Configure Permutate with Builder Methods Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md Use builder methods to configure a Permutate strategy. Requires genotype and fitness. It exhaustively evaluates all possibilities. ```rust let mut builder = Permutate::new(); builder .with_genotype(genotype) .with_fitness(fitness) .with_fitness_ordering(FitnessOrdering::Minimize) .with_par_fitness(true) .with_replace_on_equal_fitness(false) .with_reporter(reporter) .with_abort_flag(flag); let permute = builder.call().unwrap(); ``` -------------------------------- ### UniqueGenotype Construction Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/genotypes.md Example of constructing a UniqueGenotype using its builder pattern. Requires setting the gene size. The type parameter T specifies the type of alleles. ```rust let genotype = UniqueGenotype::::builder() .with_genes_size(8) .build()?; ``` -------------------------------- ### Run Benchmarks Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/CLAUDE.md Executes benchmarks. Use bench_name to run a specific benchmark. ```bash cargo bench cargo bench bench_name ``` -------------------------------- ### MassExtinction Constructor Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Creates a new `MassExtinction` extension with specified parameters for triggering extinction and managing population reduction. ```rust pub fn new(cardinality_threshold: usize, cull_percentage: f32, keep_best_rate: f32) -> Self ``` -------------------------------- ### Configure HillClimb with Builder Methods Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md Use builder methods to configure a HillClimb strategy. Requires genotype, fitness, and at least one ending condition. ```rust let mut builder = HillClimb::new(); builder .with_genotype(genotype) .with_fitness(fitness) .with_target_fitness_score(score) .with_max_stale_generations(n) .with_max_generations(n) .with_variant(HillClimbVariant::SteepestAscent) .with_fitness_ordering(FitnessOrdering::Minimize) .with_par_fitness(true) .with_fitness_cache(size) .with_replace_on_equal_fitness(false) .with_valid_fitness_score(score) .with_reporter(reporter) .with_rng_seed_from_u64(seed) .with_abort_flag(flag); let hill_climb = builder.call().unwrap(); ``` -------------------------------- ### Fix Missing Ending Condition Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/errors.md Provides examples of how to add ending conditions to the Evolve builder to avoid the 'missing at least one ending condition' error. ```Rust .with_target_fitness_score(100) // AND/OR .with_max_stale_generations(1000) // AND/OR .with_max_generations(100_000) ``` -------------------------------- ### MassExtinction Extension Constructor Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Details the constructor for the `MassExtinction` extension, which simulates a mass extinction event to manage population size and diversity. ```APIDOC ## MassExtinction Extension Constructor ### Description Initializes the `MassExtinction` extension. This extension simulates a mass extinction event by removing a percentage of the population when the population size drops below a specified threshold, while retaining the best individuals. ### Constructor Signature ```rust pub fn new(cardinality_threshold: usize, cull_percentage: f32, keep_best_rate: f32) -> Self ``` ### Parameters - **cardinality_threshold** (`usize`): When the population's cardinality (size) drops to or below this value, the extinction process is triggered. Must be greater than 0. - **cull_percentage** (`f32`): The fraction of the population to remove during the extinction event. Must be between 0.0 and 1.0. - **keep_best_rate** (`f32`): The fraction of the best individuals to retain after culling. Must be between 0.0 and 1.0. ### Example ```rust use genetic_algorithm::extension::mass_extinction::MassExtinction; // Create an extension that triggers extinction when population size is 10 or less, // removes 10% of the population, and keeps the best 2%. let extension = MassExtinction::new(10, 0.1, 0.02); ``` ``` -------------------------------- ### HillClimbState Methods Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Provides access to the same methods as EvolveState for retrieving the best solution and managing durations. ```APIDOC ## HillClimbState Methods ### Description Tracks state during hill climbing. Provides the same methods as `EvolveState` for accessing the best solution and timing information. ### Methods - `best_genes_and_fitness_score() -> Option<(Vec, FitnessValue)>`: Returns the best solution found. - `add_duration(action: StrategyAction, duration: Duration)`: Adds execution time for a strategy action. ### Example Usage (best_genes_and_fitness_score) ```rust let (best_genes, best_score) = hill_climb_state.best_genes_and_fitness_score().unwrap(); ``` ### Example Usage (add_duration) ```rust hill_climb_state.add_duration(StrategyAction::Fitness, Duration::from_secs(1)); ``` ``` -------------------------------- ### Evolve Strategy Error Type Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/evolve-strategy.md Defines the error type returned when issues occur during the Evolve builder setup. This includes missing required components or invalid configurations. ```rust pub struct TryFromEvolveBuilderError(pub &'static str) ``` -------------------------------- ### Get Best Genes and Fitness Score Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Retrieves the best solution found so far. Returns a tuple of the best genes and their fitness score, or None if no valid solution has been found. ```rust pub fn best_genes_and_fitness_score(&self) -> Option<(Vec, FitnessValue)> ``` ```rust let (best_genes, best_score) = evolve.state.best_genes_and_fitness_score().unwrap(); assert_eq!(best_score, 100); ``` -------------------------------- ### Binary Optimization (Knapsack Problem) Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS_TEMPLATES.md Use this template to solve optimization problems where solutions are represented by binary choices, like the Knapsack problem. It defines a fitness function based on item values and weights, with a penalty for exceeding maximum weight. ```rust use genetic_algorithm::strategy::evolve::prelude::*; const ITEMS: [(isize, isize); 10] = [ // (value, weight) (60, 10), (100, 20), (120, 30), (80, 15), (50, 10), (90, 25), (70, 18), (40, 8), (110, 22), (65, 12), ]; const MAX_WEIGHT: isize = 80; #[derive(Clone, Debug)] struct KnapsackFitness; impl Fitness for KnapsackFitness { type Genotype = BinaryGenotype; fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype, ) -> Option { let (total_value, total_weight) = chromosome.genes.iter().enumerate() .filter(|(_, &included)| included) .fold((0, 0), |(v, w), (i, _)| (v + ITEMS[i].0, w + ITEMS[i].1)); if total_weight > MAX_WEIGHT { Some(total_value - (total_weight - MAX_WEIGHT) * 10) // penalty } else { Some(total_value) } } } fn main() { let genotype = BinaryGenotype::builder() .with_genes_size(ITEMS.len()) .build() .unwrap(); let evolve = Evolve::builder() .with_genotype(genotype) .with_target_population_size(100) .with_max_stale_generations(100) .with_fitness(KnapsackFitness) .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .call() .unwrap(); let (best_genes, best_fitness_score) = evolve.best_genes_and_fitness_score().unwrap(); println!("score: {}", best_fitness_score); } ``` -------------------------------- ### SelectElite Configuration Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/configuration.md Configures the SelectElite strategy, specifying the replacement rate and elitism rate. ```rust .with_select(SelectElite::new(0.5, 0.02)) // Replace 50%, preserve best 2% ``` -------------------------------- ### Create Dynamic Single Gene Mutation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/selection-crossover-mutation.md Initializes a dynamic single gene mutation strategy. Use when mutation probability should decrease over generations, starting high and ending low. ```rust let mutate = MutateSingleGeneDynamic::new(0.3, 0.05); // Start high (0.3) to explore, reduce to (0.05) for convergence ``` -------------------------------- ### Population Methods Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/types.md Offers methods for managing a `Population`, including creation, size retrieval, extension, truncation, and cardinality calculation. ```rust pub fn new(chromosomes: Vec>, chromosome_recycling: bool) -> Self pub fn size(&self) -> usize pub fn extend_from_within(&mut self, count: usize) pub fn truncate(&mut self, len: usize) pub fn cardinality(&self) -> Option ``` -------------------------------- ### PermutateState Methods Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Offers the same core methods as EvolveState for retrieving the best solution and tracking execution durations. ```APIDOC ## PermutateState Methods ### Description Tracks state during permutation search. Provides the same methods as `EvolveState` for accessing the best solution and timing information. ### Methods - `best_genes_and_fitness_score() -> Option<(Vec, FitnessValue)>`: Returns the best solution found. ### Example Usage (best_genes_and_fitness_score) ```rust let (best_genes, best_score) = permutate_state.best_genes_and_fitness_score().unwrap(); ``` ``` -------------------------------- ### Get Best Genes and Fitness Score from HillClimbState Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/hillclimb-permutate.md Retrieves the best genes and their corresponding fitness score found during the hill climbing process. Returns None if no solution has been found yet. ```rust pub fn best_genes_and_fitness_score(&self) -> Option<(Vec, FitnessValue)> ``` -------------------------------- ### SelectTournament Constructor Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/selection-crossover-mutation.md Initializes Tournament selection strategy. Configures tournament size and elitism rate. Useful for mimicking Elite selection with more randomness. ```rust pub struct Tournament { pub tournament_size: usize, pub elitism_rate: f32, } pub fn new(tournament_size: usize, elitism_rate: f32) -> Self ``` ```rust let select = SelectTournament::new(3, 0.02); // 3-way tournaments, 2% elite preservation ``` -------------------------------- ### Build RangeGenotype with RangeScaled Mutation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/genotypes.md Creates a RangeGenotype using the RangeScaled mutation strategy. The mutation radius starts at a specified value and scales down over a given number of steps, allowing for adaptive exploration. ```rust use genetic_algorithm::strategy::evolve::prelude::*; let genotype = RangeGenotype::::builder() .with_genes_size(5) .with_allele_range((-10.0, 10.0)) .with_mutation_type(MutationType::RangeScaled(5.0, 3)) .build()?; // RangeScaled: mutation radius starts at 5.0, scales down 3 times ``` -------------------------------- ### Running Strategy with Repeated Calls Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md Example of using `call_repeatedly` to perform multiple independent runs of a strategy, returning the best result found across all runs and a tuple containing the best run and all runs. ```rust let (best, _all_runs) = Evolve::builder() // ... builder steps ... .call_repeatedly(5) .unwrap(); ``` -------------------------------- ### Genetic Algorithm Builder: Required Methods Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md Configures the core components of the genetic algorithm. Requires genotype, fitness, selection, crossover, mutation, and at least one ending condition. ```rust .with_genotype(genotype) .with_fitness(fitness) .with_select(select) .with_crossover(crossover) .with_mutate(mutate) ``` -------------------------------- ### Thread-Local State for Parallel Fitness Evaluation Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/core-structures.md Demonstrates the use of `ThreadLocal` for managing thread-specific fitness instances during parallel evaluation. Each thread gets its own `RefCell` to enable reusable buffers and avoid lock contention. ```rust pub use thread_local::ThreadLocal; // Used internally in parallel evaluation: let thread_local: ThreadLocal> = ThreadLocal::new(); population.par_iter_mut().for_each_init( || thread_local.get_or(|| RefCell::new(fitness.clone())).borrow_mut(), |fitness_clone, chromosome| { // Each thread has its own fitness instance }, ); ``` -------------------------------- ### Use Custom Allele Types with ListGenotype Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/AGENTS.md Example of using custom enum types as alleles within a ListGenotype. Ensure the custom type implements Clone, Copy, PartialEq, Hash, and Debug, and is registered with the impl_allele! macro. ```rust use genetic_algorithm::strategy::evolve::prelude::*; #[derive(Clone, Copy, PartialEq, Hash, Debug)] enum Color { Red, Green, Blue } genetic_algorithm::impl_allele!(Color); let genotype = ListGenotype::::builder() .with_genes_size(10) .with_allele_list(vec![Color::Red, Color::Green, Color::Blue]) .build() .unwrap(); ``` -------------------------------- ### Using fitness_value Helper Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Demonstrates direct usage of the `fitness_value` function and its application within a fitness implementation. ```rust use genetic_algorithm::fitness::fitness_value; // Direct call let result = fitness_value(3.14159, 0.001); // Returns 3141 // In fitness implementation Some(fitness_value(calculated_score, 0.01)) ``` -------------------------------- ### EvolveBuilder::new() Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/evolve-strategy.md Initializes a new EvolveBuilder with default settings. This function returns a builder instance ready for further configuration of the genetic algorithm's parameters. ```rust pub fn new() -> Builder, StrategyReporterNoop> ``` -------------------------------- ### Implement Custom Fitness Function Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/README.md Shows how to implement a custom fitness function for a genetic algorithm. The `calculate_for_chromosome` method should contain the specific optimization logic. ```rust #[derive(Clone, Debug)] struct MyFitness; impl Fitness for MyFitness { type Genotype = BinaryGenotype; fn calculate_for_chromosome( &mut self, chromosome: &FitnessChromosome, _genotype: &FitnessGenotype ) -> Option { // Your optimization logic here Some(score as FitnessValue) } } ``` -------------------------------- ### Usage of TryFromStrategyBuilderError Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/types.md Demonstrates how to handle `TryFromStrategyBuilderError` when building a strategy. This pattern is useful for catching and reporting configuration issues during strategy creation. ```rust match strategy_builder.build() { Ok(strategy) => { /* execute it */ }, Err(TryFromStrategyBuilderError(msg)) => { eprintln!("Failed to build strategy: {}", msg); } } ``` -------------------------------- ### Early Exit on Configuration Errors Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/errors.md Illustrates using the `?` operator for early exit when building genetic algorithm components. This pattern simplifies error propagation in functions that return a Result. ```Rust use genetic_algorithm::strategy::evolve::prelude::*; fn main() -> Result<(), Box> { let genotype = BinaryGenotype::builder() .with_genes_size(100) .build()?; // Fails early let evolve = Evolve::builder() .with_genotype(genotype) .with_select(SelectElite::new(0.5, 0.02)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .with_fitness(MyFitness) .with_target_population_size(100) .with_target_fitness_score(100) .call()?; // Fails if any builder step missing let (best_genes, score) = evolve.best_genes_and_fitness_score().unwrap(); println!("Best score: {}", score); Ok(()) } ``` -------------------------------- ### SelectTournament Configuration Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/configuration.md Configures the SelectTournament strategy, specifying the tournament size and elitism rate. ```rust .with_select(SelectTournament::new(3, 0.02)) // 3-way tournaments, 2% elite preservation ``` -------------------------------- ### SelectElite Constructor Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/selection-crossover-mutation.md Initializes Elite selection strategy. Controls replacement and elitism rates. Use when ensuring the strongest genes propagate is critical. ```rust pub struct Elite { pub replacement_rate: f32, pub elitism_rate: f32, } pub fn new(replacement_rate: f32, elitism_rate: f32) -> Self ``` ```rust use genetic_algorithm::strategy::evolve::prelude::*; let select = SelectElite::new(0.5, 0.02); // Replace 50% of population, ensure 2% are best chromosomes ``` -------------------------------- ### Using fitness_value Helper Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/api-reference/fitness-and-extensions.md Shows how to use the `fitness_value` helper function to convert a float to an `isize` FitnessValue with a specified precision. ```rust use genetic_algorithm::fitness::fitness_value; Some(fitness_value(3.14159, 0.001)) // Returns 3141 ``` -------------------------------- ### Continuous Optimization Configuration Source: https://github.com/basvanwesting/genetic-algorithm/blob/main/_autodocs/configuration.md A configuration for continuous optimization problems, employing tournament selection, multi-point crossover, and multi-gene range mutation. It also enables parallel fitness evaluation and sets a high maximum generation count. ```rust Evolve::builder() .with_select(SelectTournament::new(3, 0.02)) .with_crossover(CrossoverMultiPoint::new(0.6, 0.7, 2)) .with_mutate(MutateMultiGeneRange::new(2, 0.1, MutationType::RangeScaled(5.0, 3))) .with_target_population_size(200) .with_par_fitness(true) .with_max_generations(50_000) ```