|
| 1 | +use genetic_algorithm::fitness::placeholders::CountTrue; |
| 2 | +use genetic_algorithm::strategy::evolve::prelude::*; |
| 3 | +use rand::Rng; |
| 4 | + |
| 5 | +/// Custom extension that demonstrates using multiple extension points. |
| 6 | +/// All extension hooks are optional as shown in default after_mutation_complete noop |
| 7 | +#[derive(Clone, Debug)] |
| 8 | +pub struct MultiPointExtension { |
| 9 | + pub selection_threshold: usize, |
| 10 | +} |
| 11 | + |
| 12 | +impl Extension for MultiPointExtension { |
| 13 | + type Genotype = BinaryGenotype; |
| 14 | + |
| 15 | + // After selection: Mass extinction if diversity is too low |
| 16 | + fn after_selection_complete<R: Rng, SR: StrategyReporter<Genotype = Self::Genotype>>( |
| 17 | + &mut self, |
| 18 | + genotype: &mut Self::Genotype, |
| 19 | + state: &mut EvolveState<Self::Genotype>, |
| 20 | + config: &EvolveConfig, |
| 21 | + reporter: &mut SR, |
| 22 | + _rng: &mut R, |
| 23 | + ) { |
| 24 | + if let Some(cardinality) = state.population_cardinality() { |
| 25 | + if cardinality <= self.selection_threshold { |
| 26 | + println!( |
| 27 | + "After selection: Low diversity detected ({}), applying mass extinction", |
| 28 | + cardinality |
| 29 | + ); |
| 30 | + |
| 31 | + reporter.on_extension_event( |
| 32 | + ExtensionEvent("MassExtinctionAfterSelection".to_string()), |
| 33 | + genotype, |
| 34 | + state, |
| 35 | + config, |
| 36 | + ); |
| 37 | + |
| 38 | + // Keep only best 20% of population |
| 39 | + let keep_size = (state.population.size() as f32 * 0.2).ceil() as usize; |
| 40 | + let mut elite = self.extract_elite_chromosomes(genotype, state, config, keep_size); |
| 41 | + state.population.truncate(2); |
| 42 | + state.population.chromosomes.append(&mut elite); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // After crossover: Log statistics |
| 48 | + fn after_crossover_complete<R: Rng, SR: StrategyReporter<Genotype = Self::Genotype>>( |
| 49 | + &mut self, |
| 50 | + _genotype: &mut Self::Genotype, |
| 51 | + state: &mut EvolveState<Self::Genotype>, |
| 52 | + _config: &EvolveConfig, |
| 53 | + _reporter: &mut SR, |
| 54 | + _rng: &mut R, |
| 55 | + ) { |
| 56 | + let avg_age = state |
| 57 | + .population |
| 58 | + .chromosomes |
| 59 | + .iter() |
| 60 | + .map(|c| c.age()) |
| 61 | + .sum::<usize>() as f64 |
| 62 | + / state.population.size() as f64; |
| 63 | + println!( |
| 64 | + "After crossover: Population size: {}, Avg age: {:.2}", |
| 65 | + state.population.size(), |
| 66 | + avg_age |
| 67 | + ); |
| 68 | + } |
| 69 | + |
| 70 | + // After mutation: Default Noop |
| 71 | + |
| 72 | + // After fitness: Remove duplicates if too many |
| 73 | + fn after_fitness_complete<R: Rng, SR: StrategyReporter<Genotype = Self::Genotype>>( |
| 74 | + &mut self, |
| 75 | + genotype: &mut Self::Genotype, |
| 76 | + state: &mut EvolveState<Self::Genotype>, |
| 77 | + config: &EvolveConfig, |
| 78 | + reporter: &mut SR, |
| 79 | + _rng: &mut R, |
| 80 | + ) { |
| 81 | + if genotype.genes_hashing() { |
| 82 | + let unique_count = state.population.unique_chromosome_indices().len(); |
| 83 | + let total_count = state.population.size(); |
| 84 | + let duplicate_ratio = 1.0 - (unique_count as f64 / total_count as f64); |
| 85 | + |
| 86 | + if duplicate_ratio > 0.5 { |
| 87 | + println!( |
| 88 | + "After fitness: High duplication ratio ({:.2}%), removing duplicates", |
| 89 | + duplicate_ratio * 100.0 |
| 90 | + ); |
| 91 | + |
| 92 | + reporter.on_extension_event( |
| 93 | + ExtensionEvent("RemoveDuplicates".to_string()), |
| 94 | + genotype, |
| 95 | + state, |
| 96 | + config, |
| 97 | + ); |
| 98 | + |
| 99 | + let mut unique = self.extract_unique_chromosomes(genotype, state, config); |
| 100 | + let remaining = 2usize.saturating_sub(unique.len()); |
| 101 | + state.population.truncate(remaining); |
| 102 | + state.population.chromosomes.append(&mut unique); |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + // After generation: Summary statistics |
| 108 | + fn after_generation_complete<R: Rng, SR: StrategyReporter<Genotype = Self::Genotype>>( |
| 109 | + &mut self, |
| 110 | + _genotype: &mut Self::Genotype, |
| 111 | + state: &mut EvolveState<Self::Genotype>, |
| 112 | + _config: &EvolveConfig, |
| 113 | + _reporter: &mut SR, |
| 114 | + _rng: &mut R, |
| 115 | + ) { |
| 116 | + if state.current_generation() % 100 == 0 { |
| 117 | + println!( |
| 118 | + "Generation {}: Best fitness: {:?}, Cardinality: {:?}", |
| 119 | + state.current_generation(), |
| 120 | + state.best_fitness_score(), |
| 121 | + state.population_cardinality() |
| 122 | + ); |
| 123 | + } |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +fn main() { |
| 128 | + println!("Starting evolution with multiple extension points...\n"); |
| 129 | + |
| 130 | + let genotype = BinaryGenotype::builder() |
| 131 | + .with_genes_size(50) |
| 132 | + .with_genes_hashing(true) // Required for deduplication |
| 133 | + .with_chromosome_recycling(true) |
| 134 | + .build() |
| 135 | + .unwrap(); |
| 136 | + |
| 137 | + let evolve = Evolve::builder() |
| 138 | + .with_genotype(genotype) |
| 139 | + .with_select(SelectElite::new(0.9, 0.02)) |
| 140 | + .with_crossover(CrossoverUniform::new(0.8, 0.8)) |
| 141 | + .with_mutate(MutateSingleGene::new(0.1)) |
| 142 | + .with_fitness(CountTrue) |
| 143 | + .with_fitness_ordering(FitnessOrdering::Maximize) |
| 144 | + .with_extension(MultiPointExtension { |
| 145 | + selection_threshold: 10, |
| 146 | + }) |
| 147 | + .with_target_population_size(50) |
| 148 | + .with_target_fitness_score(50) // All true |
| 149 | + .with_max_stale_generations(200) |
| 150 | + .with_max_generations(10_000) |
| 151 | + .with_rng_seed_from_u64(42) // Deterministic for demo |
| 152 | + .call() |
| 153 | + .unwrap(); |
| 154 | + |
| 155 | + let (best_genes, best_fitness) = evolve.best_genes_and_fitness_score().unwrap(); |
| 156 | + let true_count = best_genes.iter().filter(|&&g| g).count(); |
| 157 | + |
| 158 | + println!("\n=== Evolution complete ==="); |
| 159 | + println!("Best fitness: {}", best_fitness); |
| 160 | + println!("True genes: {}/{}", true_count, best_genes.len()); |
| 161 | + println!("Total generations: {}", evolve.state.current_generation); |
| 162 | + println!("Best found at generation: {}", evolve.state.best_generation); |
| 163 | +} |
0 commit comments