evolve 0.3.0

A generic, composable genetic algorithm framework for Rust
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
#![cfg(feature = "parallel")]

use evolve::{
    algorithm::EvolutionaryAlgorithm,
    core::{context::Context, individual::Individual, population::Population, state::State},
    fitness::{FitnessEvaluator, Maximize},
    initialization::Random,
    operators::{
        GeneticOperator,
        parallel::{
            combinator::{Fill, Repeat},
            crossover::SinglePoint,
            mutation::RandomReset,
        },
    },
    termination::MaxGenerations,
};
use rand::SeedableRng;
use rand::rngs::SmallRng;
use std::num::NonZero;

fn make_state(genomes: &[[u8; 4]]) -> State<[u8; 4], u32> {
    let pop: Population<[u8; 4], u32> = genomes.iter().map(|g| Individual::new(*g)).collect();
    State::new(pop, 0)
}

fn nz(n: usize) -> NonZero<usize> {
    NonZero::new(n).unwrap()
}

// ── Parallel mutation ──

#[test]
fn parallel_random_reset_preserves_population_size() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]);
    let op = RandomReset::<u8>::new();
    let offspring = op.apply(&state, &mut ctx);
    assert_eq!(offspring.num_offspring(), 3);
}

// ── Parallel crossover ──

#[test]
fn parallel_single_point_even_population() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]);
    let op = SinglePoint::<u8>::new();
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 4);
}

// ── Parallel Fill ──

#[test]
fn parallel_fill_produces_exact_target_size() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 2, 3, 4], [5, 6, 7, 8]]);
    let op = Fill::new(RandomReset::<u8>::new(), 20);
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 20);
}

// ── Parallel Repeat ──

#[test]
fn parallel_repeat_produces_output() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 2, 3, 4], [5, 6, 7, 8]]);
    let op = Repeat::new(RandomReset::<u8>::new(), 5);
    assert!(op.apply(&state, &mut ctx).num_offspring() >= 5);
}

// ── Full GA with parallel operators ──

#[test]
fn parallel_ga_improves_over_generations() {
    let fitness_fn = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();

    let mut ga_short = EvolutionaryAlgorithm::builder(nz(100))
        .initializer(Random::new())
        .termination(MaxGenerations::new(1))
        .fitness(fitness_fn)
        .operators(Fill::new(RandomReset::<u8>::new(), 100))
        .rng(SmallRng::seed_from_u64(42))
        .comparator(Maximize)
        .runtime(pooled::Runtime::new(2))
        .build();

    let mut ga_long = EvolutionaryAlgorithm::builder(nz(100))
        .initializer(Random::new())
        .termination(MaxGenerations::new(100))
        .fitness(fitness_fn)
        .operators(Fill::new(RandomReset::<u8>::new(), 100))
        .rng(SmallRng::seed_from_u64(42))
        .comparator(Maximize)
        .runtime(pooled::Runtime::new(2))
        .build();

    let short_best = *ga_short
        .run()
        .population()
        .best(&fitness_fn, &Maximize)
        .fitness(&fitness_fn);
    let long_best = *ga_long
        .run()
        .population()
        .best(&fitness_fn, &Maximize)
        .fitness(&fitness_fn);

    assert!(
        long_best >= short_best,
        "100 generations ({long_best}) should be >= 1 generation ({short_best})"
    );
}

// ── Parallel Combine ──

#[test]
fn parallel_combine_runs_all_operators() {
    use evolve::operators::parallel::combinator::Combine;

    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]);

    // 3 operators, each produces 3 mutated individuals = 9 total
    let op = Combine::new(vec![
        RandomReset::<u8>::new(),
        RandomReset::<u8>::new(),
        RandomReset::<u8>::new(),
    ]);
    let offspring = op.apply(&state, &mut ctx);
    assert_eq!(offspring.num_offspring(), 9);
}

// ── Mutation actually mutates ──

#[test]
fn parallel_mutation_changes_genomes() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(99);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let genomes = [[0u8; 4]; 10];
    let state = make_state(&genomes);
    let op = RandomReset::<u8>::new();
    let pop = op.apply(&state, &mut ctx).into_population();

    // At least one individual should differ from all-zeros
    let any_changed = pop.iter().any(|ind| *ind.genome() != [0u8; 4]);
    assert!(any_changed, "mutation should change at least one genome");
}

// ── Crossover actually recombines ──

#[test]
fn parallel_crossover_produces_recombined_children() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(99);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[0, 0, 0, 0], [255, 255, 255, 255]]);
    let op = SinglePoint::<u8>::new();
    let pop = op.apply(&state, &mut ctx).into_population();

    // Children should not both be identical to parents (crossover happened)
    let child1 = pop.as_slice()[0].genome();
    let child2 = pop.as_slice()[1].genome();
    let is_recombined = *child1 != [0, 0, 0, 0] || *child2 != [255, 255, 255, 255];
    assert!(is_recombined, "crossover should recombine parent genomes");
}

// ── Parallel Combine with Box<[O]> ──

#[test]
fn parallel_combine_boxed_slice() {
    use evolve::operators::parallel::combinator::Combine;

    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 2, 3, 4], [5, 6, 7, 8]]);
    let ops: Box<[RandomReset<u8>]> =
        vec![RandomReset::new(), RandomReset::new()].into_boxed_slice();
    let op = Combine::new(ops);
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 4);
}

// ── Deterministic results with same seed ──

#[test]
fn parallel_mutation_deterministic_with_same_seed() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();

    let state = make_state(&[[10, 20, 30, 40], [50, 60, 70, 80]]);
    let op = RandomReset::<u8>::new();

    let mut rng1 = SmallRng::seed_from_u64(123);
    let mut ctx1 = Context::new(&fe, &mut rng1, &Maximize, &runtime);
    let result1 = op.apply(&state, &mut ctx1).into_population();

    let mut rng2 = SmallRng::seed_from_u64(123);
    let mut ctx2 = Context::new(&fe, &mut rng2, &Maximize, &runtime);
    let result2 = op.apply(&state, &mut ctx2).into_population();

    for (a, b) in result1.iter().zip(result2.iter()) {
        assert_eq!(a.genome(), b.genome());
    }
}

// ── Larger population exercises chunking ──

#[test]
fn parallel_mutation_large_population() {
    let runtime = pooled::Runtime::new(4);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let genomes: Vec<[u8; 4]> = (0..200).map(|i| [i as u8; 4]).collect();
    let pop: Population<[u8; 4], u32> = genomes.iter().map(|g| Individual::new(*g)).collect();
    let state = State::new(pop, 0);

    let op = RandomReset::<u8>::new();
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 200);
}

#[test]
fn parallel_crossover_large_population() {
    let runtime = pooled::Runtime::new(4);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let genomes: Vec<[u8; 4]> = (0..100).map(|i| [i as u8; 4]).collect();
    let pop: Population<[u8; 4], u32> = genomes.iter().map(|g| Individual::new(*g)).collect();
    let state = State::new(pop, 0);

    let op = SinglePoint::<u8>::new();
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 100);
}

// ── Crossover with odd-sized population ──

#[test]
fn parallel_crossover_odd_population_drops_remainder() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]);
    let op = SinglePoint::<u8>::new();
    // 3 individuals = 1 pair + 1 remainder, so 2 children
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 2);
}

// ── Fill with larger target ──

#[test]
fn parallel_fill_large_target() {
    let runtime = pooled::Runtime::new(4);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 2, 3, 4], [5, 6, 7, 8]]);
    let op = Fill::new(RandomReset::<u8>::new(), 500);
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 500);
}

// ── Repeat with larger count ──

#[test]
fn parallel_repeat_large_count() {
    let runtime = pooled::Runtime::new(4);
    let fe = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let state = make_state(&[[1, 2, 3, 4], [5, 6, 7, 8]]);
    let op = Repeat::new(RandomReset::<u8>::new(), 50);
    // Each rep produces 2 individuals (one per input), so 50 * 2 = 100
    assert_eq!(op.apply(&state, &mut ctx).num_offspring(), 100);
}

// ── Full GA with parallel pipeline operators ──

#[test]
fn parallel_ga_full_pipeline() {
    let fitness_fn = |g: &[u8; 4]| g.iter().map(|x| *x as u32).sum::<u32>();

    let mut ga = EvolutionaryAlgorithm::builder(nz(200))
        .initializer(Random::new())
        .termination(MaxGenerations::new(100))
        .fitness(fitness_fn)
        .operators(Fill::new(RandomReset::<u8>::new(), 200))
        .rng(SmallRng::seed_from_u64(42))
        .comparator(Maximize)
        .runtime(pooled::Runtime::new(4))
        .build();

    let result = ga.run();
    let best = *result
        .population()
        .best(&fitness_fn, &Maximize)
        .fitness(&fitness_fn);

    // With 200 generations and pop 200, maximize sum of 4 bytes should get close to max (1020)
    assert!(
        best > 500,
        "parallel GA should find good solutions, got {best}"
    );
}

// ── GE with parallel operators ──

#[test]
fn parallel_ge_runs_to_completion() {
    use evolve::{
        fitness::GeFitness,
        grammar::Grammar,
        initialization::RangedRandom,
        phenotype::{Event, PhenotypeBuilder},
    };

    struct TerminalCount(usize);
    impl TerminalCount {
        fn run(&self, _: &()) -> usize {
            self.0
        }
    }

    #[derive(Default)]
    struct CountBuilder(usize);
    impl PhenotypeBuilder<&'static str> for CountBuilder {
        type Output = TerminalCount;
        fn push(&mut self, event: Event<&'static str>) {
            if let Event::Terminal(_) = event {
                self.0 += 1;
            }
        }
        fn finish(self) -> TerminalCount {
            TerminalCount(self.0)
        }
    }

    let grammar = Grammar::builder()
        .rule("expr", &[&["expr", "op", "expr"], &["var"], &["const"]])
        .rule("op", &[&["+"], &["-"], &["*"]])
        .rule("var", &[&["x"], &["y"]])
        .rule("const", &[&["1"], &["2"]])
        .start("expr")
        .build();

    let fitness = GeFitness::<_, u8, f64, _, CountBuilder>::new(
        grammar,
        3,
        |p: &TerminalCount| p.run(&()) as f64,
        -1.0,
    );

    let mut ga = EvolutionaryAlgorithm::builder(nz(100))
        .initializer(RangedRandom::<u8>::new(5..20))
        .termination(MaxGenerations::new(50))
        .fitness(fitness)
        .operators(Fill::new(RandomReset::<u8>::new(), 100))
        .rng(SmallRng::seed_from_u64(42))
        .comparator(Maximize)
        .runtime(pooled::Runtime::new(2))
        .build();

    let result = ga.run();

    let fe = GeFitness::<_, u8, f64, _, CountBuilder>::new(
        Grammar::builder()
            .rule("expr", &[&["expr", "op", "expr"], &["var"], &["const"]])
            .rule("op", &[&["+"], &["-"], &["*"]])
            .rule("var", &[&["x"], &["y"]])
            .rule("const", &[&["1"], &["2"]])
            .start("expr")
            .build(),
        3,
        |p: &TerminalCount| p.run(&()) as f64,
        -1.0,
    );

    let best_fitness = fe.evaluate(result.population().best(&fe, &Maximize).genome());
    assert!(
        best_fitness > 0.0,
        "parallel GE should produce valid phenotypes, got {best_fitness}"
    );
}

// ── Parallel Vec<T> crossover ──

#[test]
fn parallel_single_point_vec_crossover() {
    let runtime = pooled::Runtime::new(2);
    let fe = |g: &Vec<u8>| g.iter().map(|x| *x as u32).sum::<u32>();
    let mut rng = SmallRng::seed_from_u64(42);
    let mut ctx = Context::new(&fe, &mut rng, &Maximize, &runtime);

    let pop: Population<Vec<u8>, u32> = vec![
        Individual::new(vec![0u8; 10]),
        Individual::new(vec![255u8; 10]),
        Individual::new(vec![1u8; 8]),
        Individual::new(vec![128u8; 12]),
    ]
    .into_iter()
    .collect();
    let state = State::new(pop, 0);

    let op = SinglePoint::<u8>::new();
    let offspring = op.apply(&state, &mut ctx);
    assert_eq!(offspring.num_offspring(), 4);

    // Verify recombination occurred
    let result = offspring.into_population();
    let child1 = result.as_slice()[0].genome();
    let child2 = result.as_slice()[1].genome();
    let is_recombined = child1 != &vec![0u8; 10] || child2 != &vec![255u8; 10];
    assert!(
        is_recombined,
        "Vec crossover should recombine parent genomes"
    );
}