eevee 0.2.1

Generalized NeuroEvolution toolkit, based on NEAT
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
use super::{Connection, Genome, InnoGen};
use crate::crossover::crossover;
use core::cmp::{max, Ordering};
use rand::{seq::IteratorRandom, RngCore};
use std::collections::HashSet;

/// A genome that allows recurrent connections
#[derive(Debug, Clone)]
#[cfg_attr(
    all(feature = "serialize", not(feature = "serialize_json")),
    derive(serde::Serialize, serde::Deserialize),
    serde(bound(
        serialize = "C: serde::Serialize",
        deserialize = "C: serde::Deserialize<'de>"
    ))
)]
pub struct Recurrent<C: Connection> {
    pub(crate) sensory: usize,
    pub(crate) action: usize,
    pub(crate) node_count: usize,
    pub(crate) connections: Vec<C>,
}

impl<C: Connection> Recurrent<C> {
    fn static_idx(&self) -> usize {
        self.sensory + self.action
    }
}

impl<C: Connection> Genome<C> for Recurrent<C> {
    fn new(sensory: usize, action: usize) -> (Self, usize) {
        let node_count = sensory + action;

        let mut inno = InnoGen::new(0);
        let mut connections = Vec::new();
        for from in 0..sensory {
            for to in sensory..sensory + action {
                connections.push(C::new(from, to, &mut inno));
            }
        }

        (
            Self {
                sensory,
                action,
                node_count,
                connections,
            },
            inno.head,
        )
    }

    fn sensory(&self) -> std::ops::Range<usize> {
        0..self.sensory
    }

    fn action(&self) -> std::ops::Range<usize> {
        self.sensory..self.sensory + self.action
    }

    fn node_count(&self) -> usize {
        self.node_count
    }

    fn push_node(&mut self) {
        self.node_count += 1;
    }

    fn connections(&self) -> &[C] {
        &self.connections
    }

    fn connections_mut(&mut self) -> &mut [C] {
        &mut self.connections
    }

    fn push_connection(&mut self, connection: C) {
        self.connections.push(connection);
    }

    fn open_path(&self, rng: &mut impl RngCore) -> Option<(usize, usize)> {
        let mut saturated = HashSet::new();
        loop {
            let (from, _) = (0..self.node_count)
                .map(|i| (i, ()))
                .filter(|(i, _)| {
                    // not action
                    (*i < self.sensory || *i >= self.sensory + self.action)
                        && !saturated.contains(i)
                })
                .choose(rng)?;

            let exclude = self
                .connections
                .iter()
                .filter_map(|c| (c.from() == from).then_some(c.to()))
                .collect::<HashSet<_>>();

            if let Some((to, _)) = (0..self.node_count)
                .map(|i| (i, ()))
                .filter(|(i, _)| {
                    // not sensory
                    *i >= self.sensory && !exclude.contains(i)
                })
                .choose(rng)
            {
                break Some((from, to));
            }

            saturated.insert(from);
        }
    }

    fn reproduce_with(&self, other: &Self, self_fit: Ordering, rng: &mut impl RngCore) -> Self {
        let connections = crossover(&self.connections, &other.connections, self_fit, rng);
        let max_idx = connections
            .iter()
            .fold(0usize, |prev, c| max(prev, max(c.from(), c.to())));
        let node_count = (max_idx + 1).max(self.sensory + self.action);

        Self {
            sensory: self.sensory,
            action: self.action,
            node_count,
            connections,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::genome::{connection::BWConnection, WConnection};
    use crate::random::default_rng;
    use eevee_macros::fn_matrix;

    type GenomeWConn = Recurrent<WConnection>;
    type GenomeBConn = Recurrent<BWConnection>;

    fn_matrix! {
        G: GenomeWConn | GenomeBConn,

        /// new(3,2) creates 3 sensory, 2 action, 5 total, 6 fully-connected S→A connections
        #[test]
        fn test_genome_creation() {
            let (genome, inno_head) = G::new(3, 2);
            assert_eq!(inno_head, 6);
            assert_eq!(genome.sensory().len(), 3);
            assert_eq!(genome.action().len(), 2);
            assert_eq!(genome.node_count(), 5);
            assert_eq!(genome.connections().len(), 6);
        }

        /// new(0,0) creates zero nodes and zero connections
        #[test]
        fn test_genome_creation_empty() {
            let (genome, inno_head) = G::new(0, 0);
            assert_eq!(inno_head, 0);
            assert_eq!(genome.sensory().len(), 0);
            assert_eq!(genome.action().len(), 0);
            assert_eq!(genome.node_count(), 0);
            assert_eq!(genome.connections().len(), 0);
        }

        /// new(3,0) creates sensory nodes with no action nodes
        #[test]
        fn test_genome_creation_only_sensory() {
            let (genome, inno_head) = G::new(3, 0);
            assert_eq!(inno_head, 0);
            assert_eq!(genome.sensory().len(), 3);
            assert_eq!(genome.action().len(), 0);
            assert_eq!(genome.node_count(), 3);
            assert_eq!(genome.connections().len(), 0);
        }

        /// new(0,3) creates action nodes with no sensory nodes
        #[test]
        fn test_genome_creation_only_action() {
            let (genome, inno_head) = G::new(0, 3);
            assert_eq!(inno_head, 0);
            assert_eq!(genome.sensory().len(), 0);
            assert_eq!(genome.action().len(), 3);
            assert_eq!(genome.node_count(), 3);
            assert_eq!(genome.connections().len(), 0);
        }

        /// Ranges don't overlap and cover expected node indices
        #[test]
        fn test_genome_sensory_action_ranges() {
            let (genome, _) = G::new(4, 3);
            let sensory = genome.sensory();
            let action = genome.action();
            assert_eq!(sensory.start, 0);
            assert_eq!(sensory.end, 4);
            assert_eq!(action.start, 4);
            assert_eq!(action.end, 7);
            assert_eq!(sensory.len(), 4);
            assert_eq!(action.len(), 3);
        }

        /// push_node() increments node_count by exactly 1
        #[test]
        fn test_push_node_increments_count() {
            let (mut genome, _) = G::new(2, 2);
            let initial_count = genome.node_count();
            genome.push_node();
            assert_eq!(genome.node_count(), initial_count + 1);
            genome.push_node();
            assert_eq!(genome.node_count(), initial_count + 2);
        }

        /// connections() returns read-only slice of all connections
        #[test]
        fn test_connections_access() {
            let (genome, _) = G::new(2, 2);
            let conns = genome.connections();
            assert_eq!(conns.len(), 4);
        }

        /// push_connection() adds exactly 1 connection, length +1
        #[test]
        fn test_push_connection_appends() {
            let (mut genome, _) = G::new(2, 2);
            let initial_len = genome.connections().len();
            let mut new_conn = genome.connections()[0].clone();
            new_conn.enable();
            genome.push_connection(new_conn);
            assert_eq!(genome.connections().len(), initial_len + 1);
        }

        /// mutate_connection() mutates existing params only (100 iterations)
        #[test]
        fn test_mutate_connection_stochastic() {
            let (mut genome, _) = G::new(4, 4);
            let initial_conns = genome.connections().len();
            for _ in 0..100 {
                genome.mutate_connection(&mut default_rng());
            }
            assert_eq!(genome.connections().len(), initial_conns);
        }

        /// open_path() returns (from,to) where from ∉ action, to ∉ sensory
        #[test]
        fn test_open_path_valid_path() {
            let (mut genome, _) = G::new(1, 1);
            genome.connections = vec![];
            for _ in 0..100 {
                match genome.open_path(&mut default_rng()) {
                    Some((0, 1)) => {},
                    Some(p) => panic!("invalid pair {p:?} generated"),
                    None => panic!("no path generated"),
                }
            }
        }

        /// open_path() returns None when all valid paths are occupied
        #[test]
        fn test_open_path_saturation() {
            // new(1,1) already has the only possible connection (0→1)
            let (genome, _) = G::new(1, 1);
            for _ in 0..100 {
                assert_eq!(genome.open_path(&mut default_rng()), None);
            }
        }

        /// open_path() returns None for 0×0 genome (no valid paths)
        #[test]
        fn test_open_path_empty_genome() {
            let (genome, _) = G::new(0, 0);
            assert_eq!(genome.open_path(&mut default_rng()), None);
        }

        /// open_path() returns (from,to) where from ∉ action, to ∉ sensory
        #[test]
        fn test_open_path_from_not_in_action() {
            let (mut genome, _) = G::new(2, 2);
            genome.connections = vec![];
            for _ in 0..50 {
                if let Some((from, to)) = genome.open_path(&mut default_rng()) {
                    assert!(!(2..4).contains(&from));
                    assert!(to >= 2);
                }
            }
        }

        /// new_connection() increases connections().len() by exactly 1
        #[test]
        fn test_new_connection_appends_and_increments() {
            let (mut genome, _) = G::new(4, 4);
            genome.connections = vec![];
            let before_len = genome.connections().len();
            genome
                .new_connection(&mut default_rng(), &mut InnoGen::new(0))
                .expect("new_connection should succeed");
            assert_eq!(genome.connections().len(), before_len + 1);
        }

        /// new_connection() appends connection with unique path from open_path()
        #[test]
        fn test_new_connection_unique() {
            let (mut genome, _) = G::new(4, 4);
            genome.connections = vec![];
            let before_paths: std::collections::HashSet<_> =
                genome.connections().iter().map(|c| c.path()).collect();
            genome
                .new_connection(&mut default_rng(), &mut InnoGen::new(0))
                .expect("new_connection should succeed");
            let new_path = genome.connections().last().unwrap().path();
            assert!(!before_paths.contains(&new_path));
        }

        /// new_connection() returns Err when all paths are fully occupied
        #[test]
        fn test_new_connection_saturated_error() {
            // new(1,1) already has the only possible connection (0→1)
            let (mut genome, initial_inno) = G::new(1, 1);
            let mut inno = InnoGen::new(initial_inno);
            let result = genome.new_connection(&mut default_rng(), &mut inno);
            assert!(result.is_err());
        }

        /// new_connection() works correctly on empty 0×0 genome
        #[test]
        fn test_new_connection_empty_genome() {
            let (mut genome, _) = G::new(2, 2);
            genome.connections = vec![];
            let result = genome.new_connection(&mut default_rng(), &mut InnoGen::new(0));
            assert!(result.is_ok());
            assert_eq!(genome.connections().len(), 1);
        }

        /// bisect_connection() increases connections by 2, node_count by 1
        #[test]
        fn test_bisect_connection_structure_change() {
            let (mut genome, initial_inno) = G::new(1, 1);
            let initial_node_count = genome.node_count();
            let initial_conn_count = genome.connections().len();
            genome
                .bisect_connection(&mut default_rng(), &mut InnoGen::new(initial_inno))
                .expect("bisect_connection should succeed");
            assert_eq!(genome.node_count(), initial_node_count + 1);
            assert_eq!(genome.connections().len(), initial_conn_count + 2);
        }

        /// Original connection is disabled after bisection
        #[test]
        fn test_bisect_connection_original_disabled() {
            let (mut genome, initial_inno) = G::new(1, 1);
            genome
                .bisect_connection(&mut default_rng(), &mut InnoGen::new(initial_inno))
                .expect("bisect_connection should succeed");
            assert!(!genome.connections()[0].enabled);
        }

        /// Bisected connections have correct from→center→to paths
        #[test]
        fn test_bisect_connection_new_paths_valid() {
            let (mut genome, initial_inno) = G::new(1, 1);
            genome
                .bisect_connection(&mut default_rng(), &mut InnoGen::new(initial_inno))
                .expect("bisect_connection should succeed");
            let node_count = genome.node_count();
            assert_eq!(genome.connections()[1].from(), 0);
            assert_eq!(genome.connections()[1].to(), node_count - 1);
            assert_eq!(genome.connections()[2].from(), node_count - 1);
            assert_eq!(genome.connections()[2].to(), 1);
        }

        /// All three innos (original, upper, lower) are unique
        #[test]
        fn test_bisect_connection_new_innos_unique() {
            let (mut genome, initial_inno) = G::new(1, 1);
            let original_inno = genome.connections()[0].inno();
            genome
                .bisect_connection(&mut default_rng(), &mut InnoGen::new(initial_inno))
                .expect("bisect_connection should succeed");
            let new_inno_1 = genome.connections()[1].inno();
            let new_inno_2 = genome.connections()[2].inno();
            assert_ne!(original_inno, new_inno_1);
            assert_ne!(original_inno, new_inno_2);
            assert_ne!(new_inno_1, new_inno_2);
        }

        /// bisect_connection() returns Err on 0×0 genome
        #[test]
        fn test_bisect_connection_empty_genome_error() {
            let (mut genome, _) = G::new(0, 0);
            genome.connections = vec![];
            let result = genome.bisect_connection(&mut default_rng(), &mut InnoGen::new(0));
            assert!(result.is_err());
        }

        /// bisect_connection() returns Err when no connections to bisect
        #[test]
        fn test_bisect_connection_no_connections_error() {
            let (mut genome, _) = G::new(2, 2);
            genome.connections = vec![];
            let result = genome.bisect_connection(&mut default_rng(), &mut InnoGen::new(0));
            assert!(result.is_err());
        }

        /// mutate() always adds connection to completely empty genome first
        #[test]
        fn test_mutate_empty_genome_gets_connection() {
            let (mut genome, _) = G::new(2, 2);
            genome.connections = vec![];
            let initial_len = genome.connections().len();
            genome
                .mutate(&mut default_rng(), &mut InnoGen::new(0))
                .expect("mutate on empty genome should succeed");
            assert_eq!(genome.connections().len(), initial_len + 1);
        }

        /// mutate() calls new_connection, bisect_connection, or mutate_connection (100 iterations)
        #[test]
        fn test_mutate_dispatches() {
            let (mut genome, _) = G::new(3, 3);
            for _ in 0..100 {
                // mutate can legitimately fail when all paths are saturated
                let _ = genome.mutate(&mut default_rng(), &mut InnoGen::new(0));
            }
            assert!(genome.node_count() >= 6);
            assert!(!genome.connections().is_empty());
        }

        /// reproduce_with() produces offspring with mixed parent connections
        #[test]
        fn test_reproduce_with_crossover() {
            let (parent1, _) = G::new(2, 2);
            let (parent2, _) = G::new(2, 2);
            let child = parent1.reproduce_with(
                &parent2,
                std::cmp::Ordering::Equal,
                &mut default_rng(),
            );
            assert_eq!(child.sensory(), parent1.sensory());
            assert_eq!(child.action(), parent1.action());
        }

        /// offspring node_count == (max_conn_idx + 1).max(sensory+action)
        #[test]
        fn test_reproduce_with_node_count_recomputation() {
            let (mut parent1, initial_inno) = G::new(2, 2);
            let (parent2, _) = G::new(2, 2);
            parent1
                .bisect_connection(&mut default_rng(), &mut InnoGen::new(initial_inno))
                .expect("bisect should succeed");
            let child = parent1.reproduce_with(
                &parent2,
                std::cmp::Ordering::Greater,
                &mut default_rng(),
            );
            assert!(child.node_count() >= 4);
        }

        /// reproduce_with() correctly handles Equal, Less, Greater fitness ordering
        #[test]
        fn test_reproduce_with_ordering_dispatch() {
            let (parent1, _) = G::new(2, 2);
            let (parent2, _) = G::new(2, 2);
            let _child_equal = parent1.reproduce_with(
                &parent2,
                std::cmp::Ordering::Equal,
                &mut default_rng(),
            );
            let _child_greater = parent1.reproduce_with(
                &parent2,
                std::cmp::Ordering::Greater,
                &mut default_rng(),
            );
            let _child_less =
                parent1.reproduce_with(&parent2, std::cmp::Ordering::Less, &mut default_rng());
        }
    }
}