### HillClimb Setup and Execution Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/hill_climb/struct.HillClimb.html?search=u32+-%3E+bool An example demonstrating how to configure and run the Hill Climb algorithm with various options. ```APIDOC ## POST /websites/rs_genetic_algorithm_0_27_1_genetic_algorithm/call ### Description This endpoint demonstrates the setup and execution of a single Hill Climb strategy using a provided example configuration. ### Method POST ### Endpoint `/websites/rs_genetic_algorithm_0_27_1_genetic_algorithm/call` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This endpoint does not accept a request body. The configuration is provided within the code example. ### Request Example ```rust use genetic_algorithm::strategy::hill_climb::prelude::*; use genetic_algorithm::fitness::placeholders::SumGenes; // the search space let genotype = RangeGenotype::builder() // f32 alleles .with_genes_size(16) // 16 genes .with_chromosome_recycling(true) // recycle genes memory allocations, maybe useful .with_allele_range(0.0..=1.0) // allow gene values between 0.0 and 1.0 .with_mutation_type(MutationType::Range(0.1)) // optional, neighbouring step size randomly sampled from range .with_mutation_type(MutationType::StepScaled(vec![0.1, 0.01, 0.001])) // optional, neighbouring step size equal to start/end of each scaled range .build() .unwrap(); // the search strategy let hill_climb = HillClimb::builder() .with_genotype(genotype) .with_variant(HillClimbVariant::SteepestAscent) // check all neighbours for each round .with_fitness(SumGenes::new_with_precision(1e-5)) // sum the gene values of the chromosomes with precision 0.00001, which means multiply fitness score (isize) by 100_000 .with_fitness_ordering(FitnessOrdering::Minimize) // aim for the lowest sum .with_fitness_cache(1000) // enable caching of fitness values (LRU size 1000), only works when genes_hash is stored in chromosome. Only useful for long stale runs .with_par_fitness(true) // optional, defaults to false, use parallel fitness calculation .with_target_fitness_score(0) // ending condition if sum of genes is <= 0.00001 in the best chromosome .with_valid_fitness_score(100) // block ending conditions until at least the sum of genes <= 0.00100 is reached in the best chromosome .with_max_stale_generations(1000) // stop searching if there is no improvement in fitness score for 1000 generations (per scaled_range) .with_max_generations(1_000_000) // optional, stop searching after 1M generations .with_replace_on_equal_fitness(true) // optional, defaults to true .with_reporter(HillClimbReporterSimple::new(100)) // optional, report every 100 generations .with_rng_seed_from_u64(0) // for testing with deterministic results .call() .unwrap(); // it's all about the best genes after all let (best_genes, best_fitness_score) = hill_climb.best_genes_and_fitness_score().unwrap(); assert_eq!(best_genes.into_iter().map(|v| v <= 1e-3).collect::>(), vec![true; 16]); assert_eq!(best_fitness_score, 0); ``` ### Response #### Success Response (200) - **best_genes** (Vec) - The best set of genes found by the algorithm. - **best_fitness_score** (isize) - The fitness score corresponding to the best genes. #### Response Example ```json { "best_genes": [ 0.0001, 0.0002, // ... other genes 0.0003 ], "best_fitness_score": 0 } ``` ``` -------------------------------- ### Genetic Algorithm Configuration Examples Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/index.html Provides example configurations for setting up a genetic algorithm pipeline, tailored for different genotype types. These examples demonstrate how to chain configuration methods like `with_select`, `with_crossover`, and `with_mutate`. ```Rust // also requires: genotype, fitness, target_population_size, ending condition .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) ``` ```Rust // also requires: genotype, fitness, target_population_size, ending condition .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateMultiGene::new(10, 0.8)) ``` ```Rust // also requires: genotype, fitness, target_population_size, ending condition .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverClone::new(0.7)) .with_mutate(MutateSingleGene::new(0.8)) ``` -------------------------------- ### Recommended Starting Configurations Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/index.html Provides recommended configurations for common genotype types as a starting point. ```APIDOC ## Recommended Starting Configurations For binary/list genotypes: ```rust // also requires: genotype, fitness, target_population_size, ending condition .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) ``` For range/float genotypes (>50 genes, see Troubleshooting for tuning): ```rust // also requires: genotype, fitness, target_population_size, ending condition .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateMultiGene::new(10, 0.8)) ``` For unique genotypes (swap-only problems): ```rust // also requires: genotype, fitness, target_population_size, ending condition .with_select(SelectTournament::new(0.5, 0.02, 4)) .with_crossover(CrossoverClone::new(0.7)) .with_mutate(MutateSingleGene::new(0.8)) ``` ``` -------------------------------- ### Minimal End-to-End Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/index.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E A basic example demonstrating the core flow of the genetic algorithm: genotype creation, fitness calculation, evolution strategy, and result retrieval. ```APIDOC ## Minimal End-to-End Example ### Description This example shows the general flow of a genetic algorithm, from defining a genotype and fitness function to configuring and running an evolution strategy. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A ### Request Example N/A ### Response N/A ### Code Snippet ```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); } ``` ``` -------------------------------- ### Minimal End-to-End Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/index.html?search=u32+-%3E+bool A basic example demonstrating the general flow of the genetic algorithm: genotype creation, fitness calculation, strategy application, and result retrieval. ```APIDOC ## Minimal End-to-End Example ### Description This example shows the fundamental workflow of the genetic algorithm, from defining a genotype and fitness function to evolving a population and retrieving the best solution. ### Method N/A (Illustrative Code Example) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ```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); } ``` ``` -------------------------------- ### RangeScaled Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/genotype/enum.MutationType.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Illustrates the application of pre-clamping and post-clamping in the `RangeScaled` mutation strategy with an example. ```APIDOC ## RangeScaled Example ### Description An example demonstrating the use of pre-clamping and post-clamping within the `RangeScaled` mutation strategy for different phases. ### Example For `RangeScaled(vec![50.0, 20.0, 5.0, 1.0])` on allele range `[0.0, 100.0]`: * Phases 0-2: Use pre-clamping (avoid boundary oversampling) * Phase 3: Uses post-clamping (ensure boundaries reachable) ``` -------------------------------- ### ListGenotype Builder Example (usize) Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/genotype/struct.ListGenotype.html?search= Example demonstrating how to build a ListGenotype with usize alleles, using default settings. ```APIDOC ## Example: ListGenotype with usize alleles ### Description This example shows the creation of a `ListGenotype` using the builder pattern, with `usize` as the allele type. Default options for hashing and chromosome recycling are used. ### Code ```rust use genetic_algorithm::genotype::{Genotype, ListGenotype}; let genotype = ListGenotype::builder() .with_genes_size(100) .with_allele_list((0..10).collect()) .with_genes_hashing(true) // optional, defaults to true .with_chromosome_recycling(true) // optional, defaults to true .build() .unwrap(); ``` ``` -------------------------------- ### Permutate Strategy Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/permutate/struct.Permutate.html An example demonstrating how to use the Permutate strategy with a BinaryGenotype and CountTrue fitness function to find the chromosome with the minimum number of true values. ```rust use genetic_algorithm::strategy::permutate::prelude::*; use genetic_algorithm::fitness::placeholders::CountTrue; // the search space let genotype = BinaryGenotype::builder() // boolean alleles .with_genes_size(12) // 12 genes per chromosome .build() .unwrap(); // the search strategy let permutate = Permutate::builder() .with_genotype(genotype) .with_fitness(CountTrue) // count the number of true values in the chromosomes .with_fitness_ordering(FitnessOrdering::Minimize) // aim for the least true values .with_par_fitness(true) // optional, defaults to false, use parallel fitness calculation .with_reporter(PermutateReporterSimple::new(100)) // optional builder step, report every 100 generations .call() .unwrap(); // it's all about the best genes after all let (best_genes, best_fitness_score) = permutate.best_genes_and_fitness_score().unwrap(); assert_eq!(best_genes, vec![false; 12]); assert_eq!(best_fitness_score, 0); ``` -------------------------------- ### ListGenotype Builder Example (Custom Struct with Macro) Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/genotype/struct.ListGenotype.html?search= Example demonstrating how to build a ListGenotype with a custom struct as alleles, using the `impl_allele!` macro for convenience. ```APIDOC ## Example: ListGenotype with custom struct alleles (macro Allele impl) ### Description This example shows the creation of a `ListGenotype` with a custom `Item` struct as alleles, utilizing the `genetic_algorithm::impl_allele!` macro for a concise implementation of the `Allele` trait. ### Code ```rust use genetic_algorithm::genotype::{Allele, Genotype, ListGenotype}; #[derive(Clone, Copy, PartialEq, Hash, Debug)] struct Item(pub u16, pub u16); genetic_algorithm::impl_allele!(Item); let genotype = ListGenotype::builder() .with_genes_size(100) .with_allele_list(vec![ Item(23, 505), Item(26, 352), Item(20, 458), ]) .with_genes_hashing(true) // optional, defaults to true .with_chromosome_recycling(true) // optional, defaults to true .build() .unwrap(); ``` ``` -------------------------------- ### Importing Permutate Strategy Components Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/permutate/prelude/index.html?search=std%3A%3Avec Example of how to import the core components for the Permutate strategy from the genetic_algorithm crate. ```rust use genetic_algorithm::strategy::permutate::{Permutate, PermutateBuilder, PermutateConfig}; use genetic_algorithm::genotype::PermutateGenotype; ``` -------------------------------- ### EvolveReporterSimple Example Output (Log) Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/evolve/struct.EvolveReporterSimple.html An example log output from the EvolveReporterSimple, illustrating the information captured during a genetic algorithm's evolution. It shows 'new best' entries with generation and fitness scores, as well as 'periodic' reports detailing population status and event counts. ```Log enter - evolve, iteration: 8 new best - generation: 0, fitness_score: Some(-2403), scale_index: None, genes: None new best - generation: 2, fitness_score: Some(-2204), scale_index: None, genes: None new best - generation: 6, fitness_score: Some(-2007), scale_index: None, genes: None new best - generation: 9, fitness_score: Some(-1607), scale_index: None, genes: None new best - generation: 11, fitness_score: Some(-1589), scale_index: None, genes: None new best - generation: 14, fitness_score: Some(-1400), scale_index: None, genes: None new best - generation: 17, fitness_score: Some(-994), scale_index: None, genes: None new best - generation: 25, fitness_score: Some(-576), scale_index: None, genes: None new best - generation: 27, fitness_score: Some(-561), scale_index: None, genes: None new best - generation: 37, fitness_score: Some(-559), scale_index: None, genes: None new best - generation: 40, fitness_score: Some(-553), scale_index: None, genes: None periodic - current_generation: 50, stale_generations: 9, best_generation: 40, scale_index: None, population_cardinality: Some(13), current_population_size: 1000 (517p/483o,700r), fitness_cache_hit_miss_ratio: None, #events(S/E/C/M): 0/0/0/0 new best - generation: 53, fitness_score: Some(-549), scale_index: None, genes: None new best - generation: 91, fitness_score: Some(-548), scale_index: None, genes: None new best - generation: 92, fitness_score: Some(-141), scale_index: None, genes: None periodic - current_generation: 100, stale_generations: 7, best_generation: 92, scale_index: None, population_cardinality: Some(3), current_population_size: 1000 (517p/483o,700r), fitness_cache_hit_miss_ratio: None, #events(S/E/C/M): 0/4/0/0 new best - generation: 142, fitness_score: Some(-130), scale_index: None, genes: None periodic - current_generation: 150, stale_generations: 7, best_generation: 142, scale_index: None, population_cardinality: Some(3), current_population_size: 1000 (517p/483o,700r), fitness_cache_hit_miss_ratio: None, #events(S/E/C/M): 0/5/0/0 periodic - current_generation: 200, stale_generations: 57, best_generation: 142, scale_index: None, population_cardinality: Some(702), current_population_size: 1000 (516p/484o,700r), fitness_cache_hit_miss_ratio: None, #events(S/E/C/M): 0/7/0/0 periodic - current_generation: 250, stale_generations: 107, best_generation: 142, scale_index: None, population_cardinality: Some(549), current_population_size: 1000 (515p/485o,700r), fitness_cache_hit_miss_ratio: None, #events(S/E/C/M): 0/7/0/0 periodic - current_generation: 300, stale_generations: 157, best_generation: 142, scale_index: None, population_cardinality: Some(347), current_population_size: 1000 (517p/483o,700r), fitness_cache_hit_miss_ratio: None, #events(S/E/C/M): 0/7/0/0 periodic - current_generation: 350, stale_generations: 207, best_generation: 142, scale_index: None, population_cardinality: Some(147), current_population_size: 1000 (516p/484o,700r), fitness_cache_hit_miss_ratio: None, #events(S/E/C/M): 0/7/0/0 exit - evolve, iteration: 8 SetupAndCleanup: 145.999µs Extension: 4.771ms Select: 17.371ms Crossover: 11.509ms Mutate: 3.090ms Fitness: 138.344ms UpdateBestChromosome: 1.416ms Other: 3.359ms Total: 180.007ms (77% fitness) ``` -------------------------------- ### Permutate Strategy Implementation - setup method Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/permutate/struct.Permutate.html?search=u32+-%3E+bool Initializes the Permutate strategy before the main loop begins. This method is called once at the start of the algorithm execution. ```rust pub fn setup(&mut self) ``` -------------------------------- ### Rust Vec capacity() Method Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/chromosome/type.Genes.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to get the current capacity of a Vec using the `capacity()` method. It also illustrates that vectors with zero-sized elements have a capacity of `usize::MAX`. ```rust let mut vec: Vec = Vec::with_capacity(10); vec.push(42); assert!(vec.capacity() >= 10); ``` ```rust #[derive(Clone)] struct ZeroSized; fn main() { assert_eq!(std::mem::size_of::(), 0); let v = vec![ZeroSized; 0]; assert_eq!(v.capacity(), usize::MAX); } ``` -------------------------------- ### Rust Genetic Algorithm Builder Initialization Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/evolve/struct.Evolve.html This code snippet shows how to obtain a builder for the genetic algorithm, specifically for a configuration that uses no-operation (noop) extensions and reporters. This is typically used as a starting point for configuring a custom genetic algorithm setup. ```rust pub fn builder() -> EvolveBuilder, StrategyReporterNoop> ``` -------------------------------- ### EvolveBuilder Initialization and Configuration (Rust) Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/evolve/struct.Evolve.html Demonstrates how to initialize and configure the EvolveBuilder for a genetic algorithm. This includes setting up the genotype, selection, crossover, mutation, fitness functions, and various evolutionary control parameters. It highlights options for parallel fitness calculation and different ending conditions. ```Rust use genetic_algorithm::strategy::evolve::prelude::*; use genetic_algorithm::fitness::placeholders::CountTrue; // the search space let genotype = BinaryGenotype::builder() // boolean alleles .with_genes_size(100) // 100 genes per chromosome .with_genes_hashing(true) // store genes_hash on chromosome (required for fitness_cache and deduplication extension, optional for better population cardinality estimation) .with_chromosome_recycling(true) // recycle genes memory allocations .build() .unwrap(); // 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_extension(ExtensionMassExtinction::new(10, 0.1, 0.02)) // optional builder step, simulate cambrian explosion by mass extinction, when population cardinality drops to 10 after the selection, trim to 10% of population .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::Minimize) // aim for the least true values .with_fitness_cache(1000) // enable caching of fitness values (LRU size 1000), only works when genes_hash is stored in chromosome. Only useful for long stale runs, but better to increase population diversity .with_par_fitness(true) // optional, defaults to false, use parallel fitness calculation .with_target_population_size(100) // evolve with 100 chromosomes .with_target_fitness_score(0) // ending condition if 0 times true in the best chromosome .with_valid_fitness_score(10) // block ending conditions until at most a 10 times true in the best chromosome .with_max_stale_generations(1000) // stop searching if there is no improvement in fitness score for 1000 generations (per scaled_range) .with_max_generations(1_000_000) // optional, stop searching after 1M generations ; ``` -------------------------------- ### Configure and Initialize StrategyBuilder Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/index.html?search=u32+-%3E+bool Demonstrates how to define a search space using BinaryGenotype and configure a StrategyBuilder with selection, crossover, mutation, and fitness parameters. This setup allows for flexible execution of various genetic algorithm strategies. ```rust use genetic_algorithm::strategy::prelude::*; use genetic_algorithm::fitness::placeholders::CountTrue; let genotype = BinaryGenotype::builder() .with_genes_size(10) .with_genes_hashing(true) .with_chromosome_recycling(true) .build() .unwrap(); let builder = StrategyBuilder::new() .with_genotype(genotype) .with_select(SelectElite::new(0.5, 0.02)) .with_extension(ExtensionMassExtinction::new(10, 0.1, 0.02)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .with_fitness(CountTrue) .with_fitness_ordering(FitnessOrdering::Minimize) .with_fitness_cache(1000) .with_par_fitness(true) .with_target_population_size(100) .with_target_fitness_score(0) .with_valid_fitness_score(1) .with_max_stale_generations(100) .with_max_generations(1_000_000) .with_max_chromosome_age(10) .with_reporter(StrategyReporterSimple::new(usize::MAX)) .with_replace_on_equal_fitness(true) .with_rng_seed_from_u64(0); let (strategy, _) = builder .with_variant(StrategyVariant::Permutate(PermutateVariant::Standard)); ``` -------------------------------- ### RangeGenotype Example (i32) Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/genotype/struct.RangeGenotype.html Example demonstrating how to build and configure a RangeGenotype for i32 genes. ```APIDOC ## §Example (i32): ```rust use genetic_algorithm::genotype::{Genotype, RangeGenotype, MutationType}; let genotype = RangeGenotype::::builder() .with_genes_size(100) .with_allele_range(0..=100) // also default mutation range .with_mutation_type(MutationType::Random) // default .with_mutation_type(MutationType::Step(2)) // optional, restricts mutations to a relative step up or down .with_mutation_type(MutationType::Range(2)) // optional, restricts mutations to a smaller relative range bandwidth: [-2..=2] uniformly sampled .with_mutation_type(MutationType::StepScaled(vec![10, 3, 1])) // optional, restricts mutations to relative step up or down of each scale .with_mutation_type(MutationType::RangeScaled(vec![100, 100, 10, 1])) // optional, optional, restricts mutations to relative bandwidth up or down of each scale .with_genes_hashing(true) // optional, defaults to true .with_chromosome_recycling(true) // optional, defaults to true .build() .unwrap(); ``` ``` -------------------------------- ### EvolveBuilder Initialization and Configuration Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/evolve/struct.Evolve.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to build and configure an Evolve strategy with various components like genotype, selection, crossover, mutation, and fitness functions. ```APIDOC ## EvolveBuilder Configuration Example ### Description This example shows how to initialize and configure an `Evolve` strategy using the `EvolveBuilder`. It covers setting up the genotype, selection, crossover, mutation, fitness calculation, and various termination conditions. ### Method POST (Conceptual - Builder pattern) ### Endpoint N/A (Builder pattern) ### Parameters #### Genotype Configuration - **genotype** (Genotype) - Required - The definition of the search space (e.g., `BinaryGenotype`). - **with_genes_size** (usize) - Required - Number of genes per chromosome. - **with_genes_hashing** (bool) - Optional - Enable gene hashing for caching and deduplication. - **with_chromosome_recycling** (bool) - Optional - Enable chromosome memory allocation recycling. #### Evolve Strategy Configuration - **with_genotype** (Genotype) - Required - Assigns the configured genotype to the Evolve strategy. - **with_select** (SelectionStrategy) - Required - Defines the selection mechanism (e.g., `SelectElite`). - **parent_selection_rate** (f64) - Required - Rate at which parents are selected for reproduction. - **elite_rate** (f64) - Required - Proportion of elite individuals to preserve. - **with_extension** (Extension) - Optional - Adds extensions to the evolution process (e.g., `ExtensionMassExtinction`). - **extinction_threshold** (usize) - Required - Population size threshold for extinction. - **extinction_rate** (f64) - Required - Proportion of population to trim during extinction. - **trim_rate** (f64) - Required - Proportion of population to trim. - **with_crossover** (CrossoverStrategy) - Required - Defines the crossover mechanism (e.g., `CrossoverUniform`). - **parent_selection_rate** (f64) - Required - Probability of selecting parents for crossover. - **crossover_rate** (f64) - Required - Probability of performing crossover. - **with_mutate** (MutationStrategy) - Required - Defines the mutation mechanism (e.g., `MutateSingleGene`). - **mutation_rate** (f64) - Required - Probability of mutating a gene. - **with_fitness** (FitnessFunction) - Required - The function to evaluate chromosome fitness (e.g., `CountTrue`). - **with_fitness_ordering** (FitnessOrdering) - Required - Specifies whether to minimize or maximize fitness. - **with_fitness_cache** (usize) - Optional - Enables fitness caching with a specified LRU size. - **with_par_fitness** (bool) - Optional - Enables parallel fitness calculation (defaults to false). - **with_target_population_size** (usize) - Required - The target number of chromosomes in the population. - **with_target_fitness_score** (f64) - Optional - The target fitness score to achieve for termination. - **with_valid_fitness_score** (f64) - Optional - Minimum fitness score threshold before considering termination conditions. - **with_max_stale_generations** (usize) - Optional - Maximum generations without fitness improvement before termination. - **with_max_generations** (usize) - Optional - Absolute maximum number of generations for the evolution. ### Request Example ```rust use genetic_algorithm::strategy::evolve::prelude::*; use genetic_algorithm::fitness::placeholders::CountTrue; let genotype = BinaryGenotype::builder() .with_genes_size(100) .with_genes_hashing(true) .with_chromosome_recycling(true) .build() .unwrap(); let evolve = Evolve::builder() .with_genotype(genotype) .with_select(SelectElite::new(0.5, 0.02)) .with_extension(ExtensionMassExtinction::new(10, 0.1, 0.02)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .with_fitness(CountTrue) .with_fitness_ordering(FitnessOrdering::Minimize) .with_fitness_cache(1000) .with_par_fitness(true) .with_target_population_size(100) .with_target_fitness_score(0.0) .with_valid_fitness_score(10.0) .with_max_stale_generations(1000) .with_max_generations(1_000_000) .build() .unwrap(); ``` ### Response #### Success Response (200) - **Evolve** (object) - The configured Evolve strategy object. #### Response Example (Conceptual - Builder pattern returns the built object) ```rust // The 'evolve' variable now holds the configured Evolve strategy. ``` ``` -------------------------------- ### RangeGenotype Example (f32) Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/genotype/struct.RangeGenotype.html Example demonstrating how to build and configure a RangeGenotype for f32 genes. ```APIDOC ## §Example (f32, default): ```rust use genetic_algorithm::genotype::{Genotype, RangeGenotype, MutationType}; let genotype = RangeGenotype::builder() .with_genes_size(100) .with_allele_range(0.0..=1.0) // also default mutation range .with_mutation_type(MutationType::Random) // default .with_mutation_type(MutationType::Step(0.1)) // optional, restricts mutations to a relative step up or down .with_mutation_type(MutationType::Range(0.1)) // optional, restricts mutations to a smaller relative range bandwidth: [-0.1..=0.1] uniformly sampled .with_mutation_type(MutationType::StepScaled(vec![0.1, 0.01, 0.001])) // optional, restricts mutations to relative step up or down of each scale .with_mutation_type(MutationType::RangeScaled(vec![1.0, 1.0, 0.1, 0.1, 0.01])) // optional, optional, restricts mutations to relative bandwidth up or down of each scale .with_genes_hashing(true) // optional, defaults to true .with_chromosome_recycling(true) // optional, defaults to true .build() .unwrap(); ``` ``` -------------------------------- ### POST /reporter/simple/new Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/reporter/struct.Simple.html?search=std%3A%3Avec Initializes a new Simple strategy reporter with a specified reporting period. ```APIDOC ## POST /reporter/simple/new ### Description Creates a new instance of the Simple reporter. The reporter will trigger reports every 'period' generations. ### Method POST ### Endpoint /reporter/simple/new ### Parameters #### Request Body - **period** (usize) - Required - The number of generations between reports. ### Request Example { "period": 10 } ### Response #### Success Response (200) - **status** (string) - Success message #### Response Example { "status": "Reporter initialized" } ``` -------------------------------- ### Configure and Initialize StrategyBuilder Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/index.html Demonstrates how to define a BinaryGenotype and configure a StrategyBuilder with various parameters such as selection, crossover, mutation, and fitness evaluation. This setup allows for flexible execution of different genetic algorithm variants. ```rust use genetic_algorithm::strategy::prelude::*; use genetic_algorithm::fitness::placeholders::CountTrue; let genotype = BinaryGenotype::builder() .with_genes_size(10) .with_genes_hashing(true) .with_chromosome_recycling(true) .build() .unwrap(); let builder = StrategyBuilder::new() .with_genotype(genotype) .with_select(SelectElite::new(0.5, 0.02)) .with_extension(ExtensionMassExtinction::new(10, 0.1, 0.02)) .with_crossover(CrossoverUniform::new(0.7, 0.8)) .with_mutate(MutateSingleGene::new(0.2)) .with_fitness(CountTrue) .with_fitness_ordering(FitnessOrdering::Minimize) .with_fitness_cache(1000) .with_par_fitness(true) .with_target_population_size(100) .with_target_fitness_score(0) .with_valid_fitness_score(1) .with_max_stale_generations(100) .with_max_generations(1_000_000) .with_max_chromosome_age(10) .with_reporter(StrategyReporterSimple::new(usize::MAX)) .with_replace_on_equal_fitness(true) .with_rng_seed_from_u64(0); let (strategy, _) = builder .with_variant(StrategyVariant::Permutate(PermutateVariant::Standard)); ``` -------------------------------- ### Mutation Type Examples Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/genotype/enum.MutationType.html?search=std%3A%3Avec Examples demonstrating the usage of different mutation types for RangeGenotype and MultiRangeGenotype. ```APIDOC ## Examples ```rust use genetic_algorithm::genotype::{Genotype, MutationType, RangeGenotype, MultiRangeGenotype}; // Integer genotype with range mutations let genotype = RangeGenotype::::builder() .with_allele_range(0..=100) .with_mutation_type(MutationType::Range(10)) // ±10 uniform mutations (post-clamped) .build(); // Integer genotype with step mutations let genotype = RangeGenotype::::builder() .with_allele_range(0..=100) .with_mutation_type(MutationType::Step(5)) // exactly +5 or -5 .build(); // Float genotype with range mutations let genotype = RangeGenotype::::builder() .with_allele_range(0.0..=100.0) .with_mutation_type(MutationType::Range(10.0)) // ±10.0 uniform mutations (post-clamped) .build(); // Scaled exploration with proper clamping strategy // Strategy controls when to advance phases let genotype = RangeGenotype::::builder() .with_allele_range(0..=100) .with_mutation_type(MutationType::RangeScaled(vec![ 50, // Broad exploration (pre-clamped, no boundary bias) 20, // Medium range (pre-clamped) 5, // Focused search (pre-clamped) 1, // Fine-tuning (post-clamped, can reach boundaries) ])) .build(); // Progressive step refinement // Strategy decides when to move to finer steps let genotype = RangeGenotype::::builder() .with_allele_range(0.0..=100.0) .with_mutation_type(MutationType::StepScaled(vec![ 10.0, // Coarse steps 1.0, // Medium steps 0.1, // Fine steps ])) .build(); // Mixed mutation types for heterogeneous chromosome let genotype = MultiRangeGenotype::::builder() .with_allele_ranges(vec![ 0.0..=1.0, // Gene 0: Boolean flag 0.0..=4.0, // Gene 1: Algorithm choice (5 options) 0.0..=100.0, // Gene 2: Continuous parameter -1.0..=1.0, // Gene 3: Direction parameter ]) .with_mutation_types(vec![ MutationType::Discrete, // Boolean as 0 or 1 MutationType::Discrete, // One of 5 algorithms MutationType::Range(10.0), // Uniform search within ±10.0 (post-clamped) MutationType::StepScaled(vec![0.5, 0.1, 0.01]), // Decreasing steps ]) .build(); ``` ``` -------------------------------- ### Initialize CrossoverSingleGene Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/crossover/struct.CrossoverSingleGene.html Demonstrates how to create a new instance of the CrossoverSingleGene strategy by providing the required selection and crossover rates. ```rust pub fn new(selection_rate: f32, crossover_rate: f32) -> Self { Self { selection_rate, crossover_rate, crossover_sampler: Bernoulli::new(crossover_rate as f64).unwrap(), } } ``` -------------------------------- ### Permutate Setup Function Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/permutate/struct.Permutate.html The setup method for the Permutate strategy, responsible for initializing the strategy before execution. ```rust pub fn setup(&mut self) ``` -------------------------------- ### Rust Genetic Algorithm Quick Usage Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/index.html Demonstrates how to use the genetic_algorithm crate in Rust to implement a genetic algorithm. It covers defining the search space (Genotype), the search goal (Fitness function), and the search strategy (Evolve). The example shows how to configure parameters like selection, crossover, mutation, and fitness ordering, and how to retrieve the best genes and fitness score. ```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); ``` -------------------------------- ### Custom Reporter Example Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/trait.StrategyReporter.html?search=u32+-%3E+bool An example implementation of the StrategyReporter trait for custom reporting during genetic algorithm evolution. ```APIDOC ## Custom Reporter Example ### Description This code demonstrates how to implement the `StrategyReporter` trait to create a custom reporter that logs information at specified generation intervals and when a new best chromosome is found. ### Method `impl StrategyReporter for CustomReporter` ### Endpoint N/A (This is a trait implementation, not an API endpoint) ### Parameters N/A ### Request Example ```rust use genetic_algorithm::strategy::evolve::prelude::*; #[derive(Clone)] pub struct CustomReporter { pub period: usize } impl StrategyReporter for CustomReporter { type Genotype = BinaryGenotype; fn on_generation_complete, C: StrategyConfig>( &mut self, genotype: &Self::Genotype, state: &S, _config: &C, ) { if state.current_generation() % self.period == 0 { println!( "periodic - current_generation: {}, stale_generations: {}, best_generation: {}, scale_index: ?", state.current_generation(), state.stale_generations(), state.best_generation(), genotype.current_scale_index(), ); } } fn on_new_best_chromosome, C: StrategyConfig>( &mut self, genotype: &Self::Genotype, state: &S, _config: &C, ) { println!( "new best - generation: {}, fitness_score: {:?}, scale_index: ?", state.current_generation(), state.best_fitness_score(), genotype.current_scale_index(), ); } fn on_exit, C: StrategyConfig>( &mut self, _genotype: &Self::Genotype, state: &S, _config: &C, ) { println!("exit - iteration: {}", state.current_iteration()); STRATEGY_ACTIONS.iter().for_each(|action| { if let Some(duration) = state.durations().get(action) { println!(" {:?}: {:.3?}", action, duration); } }); println!( " Total: {:.3?} ({:.0}% fitness)", &state.total_duration(), state.fitness_duration_rate() * 100.0 ); } } ``` ### Response N/A (This is a trait implementation, not an API endpoint) ### Response Example N/A ``` -------------------------------- ### Importing Genetic Algorithm Prelude Components Source: https://docs.rs/genetic_algorithm/0.27.1/genetic_algorithm/strategy/evolve/prelude/index.html?search= Demonstrates how to import the core components of the genetic algorithm library using the re-exported modules from the prelude. ```rust use genetic_algorithm::strategy::evolve::{Evolve, EvolveBuilder, EvolveConfig}; use genetic_algorithm::genotype::{Genotype, GenotypeBuilder, BinaryGenotype}; use genetic_algorithm::fitness::Fitness; ```