radiate-engines 1.2.22

Engines for the Radiate genetic algorithm library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
mod alters;
mod evaluators;
mod objectives;
mod population;
mod problem;
mod selectors;
mod species;

use crate::builder::evaluators::EvaluationParams;
use crate::builder::objectives::OptimizeParams;
use crate::builder::population::PopulationParams;
use crate::builder::problem::ProblemParams;
use crate::builder::selectors::SelectionParams;
use crate::builder::species::SpeciesParams;
use crate::genome::phenotype::Phenotype;
#[cfg(feature = "serde")]
use crate::io::CheckpointReader;
use crate::objectives::{Objective, Optimize};
use crate::pipeline::Pipeline;
use crate::steps::{AuditStep, EngineStep, FilterStep, FrontStep, RecombineStep, SpeciateStep};
use crate::{Chromosome, EvaluateStep, GeneticEngine};
use crate::{
    Crossover, EncodeReplace, EngineProblem, EventBus, EventHandler, Front, Mutate, Problem,
    ReplacementStrategy, RouletteSelector, Select, TournamentSelector, context::Context,
};
use crate::{Generation, Result};
use radiate_alters::{UniformCrossover, UniformMutator};
use radiate_core::evaluator::BatchFitnessEvaluator;
use radiate_core::problem::BatchEngineProblem;
use radiate_core::{
    Alterer, Diversity, Ecosystem, Evaluator, Executor, FitnessEvaluator, Genotype, Lineage, Rate,
    Valid,
};
use radiate_core::{RadiateError, ensure, radiate_err};
use radiate_expr::NamedExpr;
#[cfg(feature = "serde")]
use serde::Deserialize;
use std::sync::{Arc, Mutex, RwLock};

#[derive(Clone)]
pub struct EngineParams<C, T>
where
    C: Chromosome + 'static,
    T: Clone + 'static,
{
    pub population_params: PopulationParams<C>,
    pub evaluation_params: EvaluationParams<C, T>,
    pub species_params: SpeciesParams<C>,
    pub selection_params: SelectionParams<C>,
    pub optimization_params: OptimizeParams<C>,
    pub problem_params: ProblemParams<C, T>,

    pub alterers: Vec<Alterer<C>>,
    pub replacement_strategy: Arc<dyn ReplacementStrategy<C>>,
    pub handlers: Vec<Arc<Mutex<dyn EventHandler<T>>>>,
    pub generation: Option<Generation<C, T>>,
    pub exprs: Option<Arc<Mutex<Vec<NamedExpr>>>>,
}

/// Parameters for the genetic engine.
/// This struct is used to configure the genetic engine before it is created.
///
/// When the `GeneticEngineBuilder`  calls the `build` method, it will create a new instance
/// of the [GeneticEngine] with the given parameters. If any of the required parameters are not
/// set, the `build` method will panic. At a minimum, the `codec` and `fitness_fn` must be set.
/// The `GeneticEngineBuilder` struct is a builder pattern that allows you to set the parameters of
/// the [GeneticEngine] in a fluent and functional way.
///
/// # Type Parameters
/// - `C`: The type of chromosome used in the genotype, which must implement the [Chromosome] trait.
/// - `T`: The type of the best individual in the population.
pub struct GeneticEngineBuilder<C, T>
where
    C: Chromosome + Clone + 'static,
    T: Clone + 'static,
{
    params: EngineParams<C, T>,
    errors: Vec<RadiateError>,
}

impl<C, T> GeneticEngineBuilder<C, T>
where
    C: Chromosome + PartialEq + Clone,
    T: Clone + Send,
{
    pub(self) fn add_error_if<F>(&mut self, condition: F, message: &str)
    where
        F: Fn() -> bool,
    {
        if condition() {
            self.errors.push(radiate_err!(Builder: "{}", message));
        }
    }

    /// The [ReplacementStrategy] is used to determine how a new individual is added to the [Population]
    /// if an individual is deemed to be either invalid or reaches the maximum age.
    ///
    /// Default is [EncodeReplace], which means that a new individual will be created
    /// be using the `Codec` to encode a new individual from scratch.
    pub fn replace_strategy<R: ReplacementStrategy<C> + 'static>(mut self, replace: R) -> Self {
        self.params.replacement_strategy = Arc::new(replace);
        self
    }

    /// Subscribe to engine events with the given event handler.
    /// The event handler will be called whenever an event is emitted by the engine.
    /// You can use this to log events, or to perform custom actions
    /// based on the events emitted by the engine.
    pub fn subscribe<H>(mut self, handler: H) -> Self
    where
        H: EventHandler<T> + 'static,
    {
        self.params.handlers.push(Arc::new(Mutex::new(handler)));
        self
    }

    /// Set the generation for the engine. This is typically used
    /// when resuming a previously paused or stopped engine.
    pub fn generation(mut self, generation: Generation<C, T>) -> Self {
        self.params.generation = Some(generation);
        self
    }

    pub fn register_metrics(mut self, exprs: Vec<impl Into<NamedExpr>>) -> Self {
        self.params.exprs = Some(Arc::new(Mutex::new(
            exprs.into_iter().map(|e| e.into()).collect(),
        )));
        self
    }

    /// Load a checkpoint from the given file path. This will
    /// load the generation from the file and set it as the current generation
    /// for the engine.
    #[cfg(feature = "serde")]
    pub fn load_checkpoint<P: AsRef<std::path::Path>>(
        mut self,
        path: P,
        reader: impl CheckpointReader<C, T>,
    ) -> Self
    where
        C: for<'de> Deserialize<'de>,
        T: for<'de> Deserialize<'de>,
    {
        let read_generation = reader.read_checkpoint(path.as_ref().to_path_buf());
        if let Err(e) = &read_generation {
            self.add_error_if(|| true, &format!("Failed to read checkpoint: {}", e));
        }
        let generation = read_generation.expect("Failed to read checkpoint file");
        self.generation(generation)
    }
}

/// Static step builder for the genetic engine.
impl<C, T> GeneticEngineBuilder<C, T>
where
    C: Chromosome + Clone + PartialEq + 'static,
    T: Clone + Send + Sync + 'static,
{
    /// Build the genetic engine with the given parameters. This will create a new
    /// instance of the [GeneticEngine] with the given parameters.
    pub fn build(self) -> GeneticEngine<C, T> {
        match self.try_build() {
            Ok(engine) => engine,
            Err(e) => panic!("{e}"),
        }
    }

    pub fn try_build(mut self) -> Result<GeneticEngine<C, T>> {
        if !self.errors.is_empty() {
            return Err(radiate_err!(
                Builder: "Failed to build GeneticEngine: {:?}",
                self.errors
            ));
        }

        self.build_problem()?;
        self.build_population()?;
        self.build_alterer()?;
        self.build_front()?;

        let config = EngineConfig::<C, T>::from(&self.params);

        let mut pipeline = Pipeline::<C>::default();

        pipeline.add_step(Self::build_eval_step(&config));
        pipeline.add_step(Self::build_recombine_step(&config));
        pipeline.add_step(Self::build_filter_step(&config));
        pipeline.add_step(Self::build_eval_step(&config));
        pipeline.add_step(Self::build_front_step(&config));
        pipeline.add_step(Self::build_species_step(&config));
        pipeline.add_step(Self::build_audit_step(&config));

        let event_bus = EventBus::new(config.bus_executor(), config.handlers());
        let context = Context::from(config);

        Ok(GeneticEngine::<C, T>::new(context, pipeline, event_bus))
    }

    /// Build the problem of the genetic engine. This will create a new problem
    /// using the codec and fitness function if the problem is not set. If the
    /// problem is already set, this function will do nothing. Else, if the fitness function is
    /// a batch fitness function, it will create a new [BatchEngineProblem] and swap the evaluator
    /// to use a [BatchFitnessEvaluator].
    fn build_problem(&mut self) -> Result<()> {
        if self.params.problem_params.problem.is_some() {
            return Ok(());
        }

        ensure!(
            self.params.problem_params.codec.is_some(),
            Builder: "Codec not set"
        );

        let raw_fitness_fn = self.params.problem_params.raw_fitness_fn.clone();
        let fitness_fn = self.params.problem_params.fitness_fn.clone();
        let batch_fitness_fn = self.params.problem_params.batch_fitness_fn.clone();
        let raw_batch_fitness_fn = self.params.problem_params.raw_batch_fitness_fn.clone();

        if batch_fitness_fn.is_some() || raw_batch_fitness_fn.is_some() {
            self.params.problem_params.problem = Some(Arc::new(BatchEngineProblem {
                objective: self.params.optimization_params.objectives.clone(),
                codec: self.params.problem_params.codec.clone().unwrap(),
                batch_fitness_fn,
                raw_batch_fitness_fn,
            }));

            // Replace the evaluator with BatchFitnessEvaluator
            self.params.evaluation_params.evaluator = Arc::new(BatchFitnessEvaluator::new(
                self.params.evaluation_params.fitness_executor.clone(),
            ));

            Ok(())
        } else if fitness_fn.is_some() || raw_fitness_fn.is_some() {
            self.params.problem_params.problem = Some(Arc::new(EngineProblem {
                objective: self.params.optimization_params.objectives.clone(),
                codec: self.params.problem_params.codec.clone().unwrap(),
                fitness_fn,
                raw_fitness_fn,
            }));

            Ok(())
        } else {
            Err(radiate_err!(Builder: "Fitness function not set"))
        }
    }

    /// Build the population of the genetic engine. This will create a new population
    /// using the codec if the population is not set.
    fn build_population(&mut self) -> Result<()> {
        if self.params.population_params.ecosystem.is_some() {
            return Ok(());
        }

        let ecosystem = match &self.params.population_params.ecosystem {
            None => Some(match self.params.problem_params.problem.as_ref() {
                Some(problem) => {
                    let size = self.params.population_params.population_size;
                    let mut phenotypes = Vec::with_capacity(size);

                    for _ in 0..size {
                        let genotype = problem.encode();

                        if !genotype.is_valid() {
                            return Err(radiate_err!(
                                Builder: "Encoded genotype is not valid",
                            ));
                        }

                        phenotypes.push(Phenotype::from((genotype, 0)));
                    }

                    Ecosystem::from(phenotypes)
                }
                None => return Err(radiate_err!(Builder: "Codec not set")),
            }),
            Some(ecosystem) => Some(ecosystem.clone()),
        };

        if let Some(ecosystem) = ecosystem {
            self.params.population_params.ecosystem = Some(ecosystem);
        }

        Ok(())
    }

    /// Build the alterer of the genetic engine. This will create a
    /// new `UniformCrossover` and `UniformMutator` if the alterer is not set.
    /// with a 0.5 crossover rate and a 0.1 mutation rate.
    fn build_alterer(&mut self) -> Result<()> {
        if !self.params.alterers.is_empty() {
            for alter in self.params.alterers.iter_mut() {
                if !alter.rate().is_valid() {
                    return Err(radiate_err!(
                        Builder: "Alterer {} is not valid. Ensure rate {:?} is valid.", alter.name(), alter.rate()
                    ));
                }
            }

            return Ok(());
        }

        let crossover = UniformCrossover::new(0.5).alterer();
        let mutator = UniformMutator::new(0.1).alterer();

        self.params.alterers.push(crossover);
        self.params.alterers.push(mutator);

        Ok(())
    }

    /// Build the pareto front of the genetic engine. This will create a new `Front`
    /// if the front is not set. The `Front` is used to store the best individuals
    /// in the population and is used for multi-objective optimization problems.
    fn build_front(&mut self) -> Result<()> {
        if self.params.optimization_params.front.is_some() {
            return Ok(());
        } else if let Some(generation) = &self.params.generation {
            if let Some(front) = generation.front() {
                self.params.optimization_params.front = Some(front.clone());
                return Ok(());
            }
        }

        let front_obj = self.params.optimization_params.objectives.clone();
        self.params.optimization_params.front = Some(Front::new(
            self.params.optimization_params.front_range.clone(),
            front_obj,
        ));

        Ok(())
    }

    fn build_eval_step(config: &EngineConfig<C, T>) -> Option<Box<dyn EngineStep<C>>> {
        let eval_step = EvaluateStep {
            objective: config.objective(),
            problem: config.problem(),
            evaluator: config.evaluator(),
        };

        Some(Box::new(eval_step))
    }

    fn build_recombine_step(config: &EngineConfig<C, T>) -> Option<Box<dyn EngineStep<C>>> {
        let offspring_selector = config.offspring_selector();
        let survivor_selector = config.survivor_selector();

        let off_name = offspring_selector.name();
        let offspring_base_name = radiate_utils::intern!(off_name);
        let offspring_time_name = radiate_utils::intern!(format!("{}.time", offspring_base_name));

        let surv_name = survivor_selector.name();
        let survivor_base_name = radiate_utils::intern!(surv_name);
        let survivor_time_name = radiate_utils::intern!(format!("{}.time", survivor_base_name));

        let recombine_step = RecombineStep {
            survivor_handle: crate::steps::SurvivorRecombineHandle {
                count: config.survivor_count(),
                objective: config.objective(),
                selector: survivor_selector,
                names: (survivor_base_name, survivor_time_name),
            },
            offspring_handle: crate::steps::OffspringRecombineHandle {
                count: config.offspring_count(),
                objective: config.objective(),
                selector: offspring_selector,
                alters: config.alters().to_vec(),
                lineage: config.lineage(),
                names: (offspring_base_name, offspring_time_name),
            },
        };

        Some(Box::new(recombine_step))
    }

    fn build_filter_step(config: &EngineConfig<C, T>) -> Option<Box<dyn EngineStep<C>>> {
        let filter_step = FilterStep {
            replacer: config.replacement_strategy(),
            encoder: config.encoder(),
            max_age: config.max_age(),
            max_species_age: config.max_species_age(),
        };

        Some(Box::new(filter_step))
    }

    fn build_audit_step(config: &EngineConfig<C, T>) -> Option<Box<dyn EngineStep<C>>> {
        Some(Box::new(AuditStep::new(
            config.objective().clone(),
            config.lineage(),
        )))
    }

    fn build_front_step(config: &EngineConfig<C, T>) -> Option<Box<dyn EngineStep<C>>> {
        if config.objective().is_single() {
            return None;
        }

        let front_step = FrontStep {
            front: config.front(),
        };

        Some(Box::new(front_step))
    }

    fn build_species_step(config: &EngineConfig<C, T>) -> Option<Box<dyn EngineStep<C>>> {
        if config.diversity().is_none() {
            return None;
        }

        let species_step = SpeciateStep {
            threshold: config.species_threshold(),
            distance: config.diversity().unwrap(),
            executor: config.species_executor(),
            objective: config.objective(),
            distances: Arc::new(Mutex::new(Vec::new())),
            assignments: Arc::new(Mutex::new(Vec::new())),
        };

        Some(Box::new(species_step))
    }
}

impl<C, T> Default for GeneticEngineBuilder<C, T>
where
    C: Chromosome + Clone + 'static,
    T: Clone + Send + 'static,
{
    fn default() -> Self {
        GeneticEngineBuilder {
            params: EngineParams {
                population_params: PopulationParams {
                    population_size: 100,
                    max_age: 20,
                    ecosystem: None,
                },
                species_params: SpeciesParams {
                    diversity: None,
                    species_threshold: Rate::Fixed(0.5),
                    max_species_age: 25,
                },
                evaluation_params: EvaluationParams {
                    evaluator: Arc::new(FitnessEvaluator::default()),
                    fitness_executor: Arc::new(Executor::default()),
                    species_executor: Arc::new(Executor::default()),
                    bus_executor: Arc::new(Executor::default()),
                },
                selection_params: SelectionParams {
                    offspring_fraction: 0.8,
                    survivor_selector: Arc::new(TournamentSelector::new(3)),
                    offspring_selector: Arc::new(RouletteSelector::new()),
                },
                optimization_params: OptimizeParams {
                    objectives: Objective::Single(Optimize::Maximize),
                    front_range: 800..900,
                    front: None,
                },
                problem_params: ProblemParams {
                    codec: None,
                    problem: None,
                    fitness_fn: None,
                    batch_fitness_fn: None,
                    raw_fitness_fn: None,
                    raw_batch_fitness_fn: None,
                },

                replacement_strategy: Arc::new(EncodeReplace),
                alterers: Vec::new(),
                handlers: Vec::new(),
                exprs: None,
                generation: None,
            },
            errors: Vec::new(),
        }
    }
}

#[derive(Clone)]
pub(crate) struct EngineConfig<C: Chromosome, T: Clone> {
    ecosystem: Ecosystem<C>,
    problem: Arc<dyn Problem<C, T>>,
    survivor_selector: Arc<dyn Select<C>>,
    offspring_selector: Arc<dyn Select<C>>,
    replacement_strategy: Arc<dyn ReplacementStrategy<C>>,
    alterers: Vec<Alterer<C>>,
    species_threshold: Rate,
    diversity: Option<Arc<dyn Diversity<C>>>,
    evaluator: Arc<dyn Evaluator<C, T>>,
    objective: Objective,
    max_age: usize,
    max_species_age: usize,
    front: Arc<RwLock<Front<Phenotype<C>>>>,
    lineage: Arc<RwLock<Lineage>>,
    offspring_fraction: f32,
    executor: EvaluationParams<C, T>,
    handlers: Vec<Arc<Mutex<dyn EventHandler<T>>>>,
    exprs: Option<Arc<Mutex<Vec<NamedExpr>>>>,
    generation: Option<Generation<C, T>>,
}

impl<C: Chromosome, T: Clone> EngineConfig<C, T> {
    pub fn ecosystem(&self) -> &Ecosystem<C> {
        &self.ecosystem
    }

    pub fn survivor_selector(&self) -> Arc<dyn Select<C>> {
        Arc::clone(&self.survivor_selector)
    }

    pub fn offspring_selector(&self) -> Arc<dyn Select<C>> {
        Arc::clone(&self.offspring_selector)
    }

    pub fn replacement_strategy(&self) -> Arc<dyn ReplacementStrategy<C>> {
        Arc::clone(&self.replacement_strategy)
    }

    pub fn alters(&self) -> &[Alterer<C>] {
        &self.alterers
    }

    pub fn objective(&self) -> Objective {
        self.objective.clone()
    }

    pub fn max_age(&self) -> usize {
        self.max_age
    }

    pub fn max_species_age(&self) -> usize {
        self.max_species_age
    }

    pub fn species_threshold(&self) -> Rate {
        self.species_threshold.clone()
    }

    pub fn diversity(&self) -> Option<Arc<dyn Diversity<C>>> {
        self.diversity.clone()
    }

    pub fn front(&self) -> Arc<RwLock<Front<Phenotype<C>>>> {
        Arc::clone(&self.front)
    }

    pub fn lineage(&self) -> Arc<RwLock<Lineage>> {
        Arc::clone(&self.lineage)
    }

    pub fn evaluator(&self) -> Arc<dyn Evaluator<C, T>> {
        Arc::clone(&self.evaluator)
    }

    pub fn survivor_count(&self) -> usize {
        self.ecosystem.population().len() - self.offspring_count()
    }

    pub fn offspring_count(&self) -> usize {
        (self.ecosystem.population().len() as f32 * self.offspring_fraction) as usize
    }

    pub fn bus_executor(&self) -> Arc<Executor> {
        Arc::clone(&self.executor.bus_executor)
    }

    pub fn species_executor(&self) -> Arc<Executor> {
        Arc::clone(&self.executor.species_executor)
    }

    pub fn handlers(&self) -> Vec<Arc<Mutex<dyn EventHandler<T>>>> {
        self.handlers.clone()
    }

    pub fn problem(&self) -> Arc<dyn Problem<C, T>> {
        Arc::clone(&self.problem)
    }

    pub fn generation(&self) -> Option<Generation<C, T>>
    where
        C: Clone,
        T: Clone,
    {
        self.generation.clone()
    }

    pub fn encoder(&self) -> Arc<dyn Fn() -> Genotype<C> + Send + Sync>
    where
        C: 'static,
        T: 'static,
    {
        let problem = Arc::clone(&self.problem);
        Arc::new(move || problem.encode())
    }

    pub fn exprs(&self) -> Option<Arc<Mutex<Vec<NamedExpr>>>> {
        self.exprs.clone()
    }
}

impl<C, T> From<&EngineParams<C, T>> for EngineConfig<C, T>
where
    C: Chromosome + Clone + 'static,
    T: Clone + Send + Sync + 'static,
{
    fn from(params: &EngineParams<C, T>) -> Self {
        Self {
            ecosystem: params.population_params.ecosystem.clone().unwrap(),
            problem: params.problem_params.problem.clone().unwrap(),
            survivor_selector: params.selection_params.survivor_selector.clone(),
            offspring_selector: params.selection_params.offspring_selector.clone(),
            replacement_strategy: params.replacement_strategy.clone(),
            alterers: params.alterers.clone(),
            objective: params.optimization_params.objectives.clone(),
            max_age: params.population_params.max_age,
            max_species_age: params.species_params.max_species_age,
            species_threshold: params.species_params.species_threshold.clone(),
            diversity: params.species_params.diversity.clone(),
            front: Arc::new(RwLock::new(
                params.optimization_params.front.clone().unwrap(),
            )),
            lineage: Arc::new(RwLock::new(Lineage::default())),
            offspring_fraction: params.selection_params.offspring_fraction,
            evaluator: params.evaluation_params.evaluator.clone(),
            executor: params.evaluation_params.clone(),
            handlers: params.handlers.clone(),
            generation: params.generation.clone(),
            exprs: params.exprs.clone(),
        }
    }
}

impl<C, T> Into<GeneticEngineBuilder<C, T>> for EngineConfig<C, T>
where
    C: Chromosome + Clone + 'static,
    T: Clone + Send + Sync + 'static,
{
    fn into(self) -> GeneticEngineBuilder<C, T> {
        GeneticEngineBuilder {
            params: EngineParams {
                population_params: PopulationParams {
                    population_size: self.ecosystem.population().len(),
                    max_age: self.max_age,
                    ecosystem: Some(self.ecosystem),
                },
                species_params: SpeciesParams {
                    diversity: self.diversity,
                    species_threshold: self.species_threshold,
                    max_species_age: self.max_species_age,
                },
                evaluation_params: self.executor,
                selection_params: SelectionParams {
                    offspring_fraction: self.offspring_fraction,
                    survivor_selector: self.survivor_selector,
                    offspring_selector: self.offspring_selector,
                },
                optimization_params: OptimizeParams {
                    objectives: self.objective,
                    front_range: self.front.read().unwrap().range().clone(),
                    front: Some(self.front.read().unwrap().clone()),
                },
                problem_params: ProblemParams {
                    codec: None,
                    problem: Some(self.problem),
                    fitness_fn: None,
                    batch_fitness_fn: None,
                    raw_fitness_fn: None,
                    raw_batch_fitness_fn: None,
                },

                replacement_strategy: self.replacement_strategy,
                alterers: self.alterers,
                handlers: self.handlers,
                exprs: self.exprs,
                generation: self.generation,
            },
            errors: Vec::new(),
        }
    }
}