fugue-evo 0.3.1

An implementation of fugue for running evolutionary algorithms as Bayesian inference: priors and likelihoods as probabilistic programs, tempered SMC in trace space, annealed optimization, Pareto posteriors - plus a standalone classical EC toolkit
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
//! Core genome traits
//!
//! This module defines the `EvolutionaryGenome` trait and related types. The
//! classic evolutionary-computation layer is defined entirely in terms of this
//! trait and carries **no** probabilistic-programming dependency; the fugue
//! trace encoding lives in the separate
//! [`TraceGenome`](crate::genome::trace_genome::TraceGenome) extension trait
//! behind the `ppl` feature.

use rand::Rng;
use serde::{de::DeserializeOwned, Serialize};

use crate::error::GenomeError;
use crate::genome::bounds::MultiBounds;

/// Core genome abstraction for evolutionary algorithms.
///
/// This trait defines the interface for evolvable solution representations.
/// Genomes must be cloneable, serializable, and thread-safe.
///
/// Genomes that additionally support the fugue trace encoding (for the
/// PPL-native inference layer) implement the
/// [`TraceGenome`](crate::genome::trace_genome::TraceGenome) extension trait,
/// available behind the `ppl` feature.
pub trait EvolutionaryGenome: Clone + Send + Sync + Serialize + DeserializeOwned + 'static {
    /// The allele type for individual genes
    type Allele: Clone + Send;

    /// The phenotype or decoded solution type
    type Phenotype;

    /// Decode genome into phenotype for fitness evaluation
    fn decode(&self) -> Self::Phenotype;

    /// Compute dimensionality for adaptive operators
    fn dimension(&self) -> usize;

    /// Generate a random genome within the given bounds.
    ///
    /// # Interpretation of `bounds`
    ///
    /// `MultiBounds` semantically describes a set of per-dimension numeric
    /// `[min, max]` intervals, but only the real-valued genome types
    /// ([`RealVector`](crate::genome::real_vector::RealVector),
    /// [`DynamicRealVector`](crate::genome::dynamic_real_vector::DynamicRealVector))
    /// actually consult the `min`/`max` fields. For every other built-in genome
    /// type, **only `bounds.dimension()` (the *count* of intervals) is
    /// consulted** — it is repurposed as a stand-in for the genome's structural
    /// size, and the `min`/`max` values are ignored:
    ///
    /// - [`BitString`](crate::genome::bit_string::BitString): `dimension()` is
    ///   the number of bits. Prefer
    ///   [`BitString::generate_with_len`](crate::genome::bit_string::BitString::generate_with_len).
    /// - [`Permutation`](crate::genome::permutation::Permutation): `dimension()`
    ///   is the permutation length. Prefer
    ///   [`Permutation::generate_with_len`](crate::genome::permutation::Permutation::generate_with_len).
    /// - [`TreeGenome`](crate::genome::tree::TreeGenome): `dimension()` is
    ///   remapped to a maximum tree depth. Prefer
    ///   [`TreeGenome::generate_with_depth`](crate::genome::tree::TreeGenome::generate_with_depth).
    ///
    /// When you are not generating real-valued genomes, use the per-type honest
    /// constructors listed above; they make the size/depth parameter explicit
    /// instead of overloading `MultiBounds`.
    fn generate<R: Rng>(rng: &mut R, bounds: &MultiBounds) -> Self;

    /// Get the genome's genes as a slice (for numeric genomes)
    fn as_slice(&self) -> Option<&[Self::Allele]> {
        None
    }

    /// Get the genome's genes as a mutable slice (for numeric genomes)
    fn as_mut_slice(&mut self) -> Option<&mut [Self::Allele]> {
        None
    }

    /// Distance metric between two genomes.
    ///
    /// This is a **required** method: there is deliberately no default
    /// implementation, because a silent fallback (e.g. always `0.0`) would make
    /// every pair of genomes look identical and silently break diversity-driven
    /// mechanisms (niching, crowding, speciation).
    ///
    /// # Panics
    ///
    /// Implementations panic when the two genomes are structurally incompatible
    /// (for fixed-structure genomes, this means different lengths / dimensions).
    /// A structural mismatch is an invariant violation by the caller rather than
    /// a recoverable condition. Use [`try_distance`](Self::try_distance) when a
    /// fallible comparison is required.
    ///
    /// (Genome types whose comparison is meaningfully defined across differing
    /// structures — e.g. [`DynamicRealVector`](crate::genome::dynamic_real_vector::DynamicRealVector),
    /// which adds a length penalty, and [`TreeGenome`](crate::genome::tree::TreeGenome),
    /// which compares size/depth — never panic.)
    fn distance(&self, other: &Self) -> f64;

    /// Fallible distance metric.
    ///
    /// Returns `Err(GenomeError::DimensionMismatch { .. })` (or another
    /// [`GenomeError`]) when the two genomes are structurally incompatible,
    /// instead of panicking as [`distance`](Self::distance) does. For genome
    /// types whose distance is defined across differing structures this always
    /// returns `Ok`.
    fn try_distance(&self, other: &Self) -> Result<f64, GenomeError>;
}

/// Trait for genomes that can be represented as real vectors
pub trait RealValuedGenome: EvolutionaryGenome<Allele = f64> {
    /// Get the genes as a slice of f64 values
    fn genes(&self) -> &[f64];

    /// Get the genes as a mutable slice of f64 values
    fn genes_mut(&mut self) -> &mut [f64];

    /// Create from a vector of genes
    fn from_genes(genes: Vec<f64>) -> Result<Self, GenomeError>;

    /// Apply bounds to all genes
    fn apply_bounds(&mut self, bounds: &MultiBounds) {
        bounds.clamp_vec(self.genes_mut());
    }
}

/// Trait for genomes that can be represented as bit strings
pub trait BinaryGenome: EvolutionaryGenome<Allele = bool> {
    /// Get the bits as a slice
    fn bits(&self) -> &[bool];

    /// Get the bits as a mutable slice
    fn bits_mut(&mut self) -> &mut [bool];

    /// Create from a vector of bits
    fn from_bits(bits: Vec<bool>) -> Result<Self, GenomeError>;

    /// Count the number of true bits (ones)
    fn count_ones(&self) -> usize {
        self.bits().iter().filter(|&&b| b).count()
    }

    /// Count the number of false bits (zeros)
    fn count_zeros(&self) -> usize {
        self.bits().iter().filter(|&&b| !b).count()
    }
}

/// Trait for genomes that represent permutations
pub trait PermutationGenome: EvolutionaryGenome<Allele = usize> {
    /// Get the permutation as a slice
    fn permutation(&self) -> &[usize];

    /// Get the permutation as a mutable slice
    fn permutation_mut(&mut self) -> &mut [usize];

    /// Create from a vector of indices
    fn from_permutation(perm: Vec<usize>) -> Result<Self, GenomeError>;

    /// Check if the genome represents a valid permutation
    fn is_valid_permutation(&self) -> bool {
        let perm = self.permutation();
        let n = perm.len();
        if n == 0 {
            return true;
        }

        let mut seen = vec![false; n];
        for &idx in perm {
            if idx >= n || seen[idx] {
                return false;
            }
            seen[idx] = true;
        }
        true
    }
}

// The trace-encoding surface (`TraceGenome`, `gene_address`, the `ChoiceValue`
// re-export) lives in `crate::genome::trace_genome` behind the `ppl` feature.

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    // Mock genome for testing the trait
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct MockGenome {
        genes: Vec<f64>,
    }

    impl EvolutionaryGenome for MockGenome {
        type Allele = f64;
        type Phenotype = Vec<f64>;

        fn decode(&self) -> Self::Phenotype {
            self.genes.clone()
        }

        fn dimension(&self) -> usize {
            self.genes.len()
        }

        fn generate<R: Rng>(rng: &mut R, bounds: &MultiBounds) -> Self {
            let genes = bounds
                .bounds
                .iter()
                .map(|b| rng.gen_range(b.min..=b.max))
                .collect();
            Self { genes }
        }

        fn as_slice(&self) -> Option<&[f64]> {
            Some(&self.genes)
        }

        fn as_mut_slice(&mut self) -> Option<&mut [f64]> {
            Some(&mut self.genes)
        }

        fn distance(&self, other: &Self) -> f64 {
            self.try_distance(other)
                .expect("distance: genomes have mismatched dimension")
        }

        fn try_distance(&self, other: &Self) -> Result<f64, GenomeError> {
            if self.genes.len() != other.genes.len() {
                return Err(GenomeError::DimensionMismatch {
                    expected: self.genes.len(),
                    actual: other.genes.len(),
                });
            }
            Ok(self
                .genes
                .iter()
                .zip(other.genes.iter())
                .map(|(a, b)| (a - b).powi(2))
                .sum::<f64>()
                .sqrt())
        }
    }

    impl RealValuedGenome for MockGenome {
        fn genes(&self) -> &[f64] {
            &self.genes
        }

        fn genes_mut(&mut self) -> &mut [f64] {
            &mut self.genes
        }

        fn from_genes(genes: Vec<f64>) -> Result<Self, GenomeError> {
            Ok(Self { genes })
        }
    }

    #[test]
    fn test_mock_genome_decode() {
        let genome = MockGenome {
            genes: vec![1.0, 2.0, 3.0],
        };
        assert_eq!(genome.decode(), vec![1.0, 2.0, 3.0]);
    }

    #[test]
    fn test_mock_genome_dimension() {
        let genome = MockGenome {
            genes: vec![1.0, 2.0, 3.0],
        };
        assert_eq!(genome.dimension(), 3);
    }

    #[test]
    fn test_mock_genome_generate() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(5.0, 3);
        let genome = MockGenome::generate(&mut rng, &bounds);
        assert_eq!(genome.dimension(), 3);
        for gene in genome.genes() {
            assert!(*gene >= -5.0 && *gene <= 5.0);
        }
    }

    #[test]
    fn test_mock_genome_distance() {
        let g1 = MockGenome {
            genes: vec![0.0, 0.0, 0.0],
        };
        let g2 = MockGenome {
            genes: vec![3.0, 4.0, 0.0],
        };
        assert_eq!(g1.distance(&g2), 5.0);
    }

    #[test]
    fn test_real_valued_genome_apply_bounds() {
        let mut genome = MockGenome {
            genes: vec![-10.0, 0.0, 10.0],
        };
        let bounds = MultiBounds::symmetric(5.0, 3);
        genome.apply_bounds(&bounds);
        assert_eq!(genome.genes, vec![-5.0, 0.0, 5.0]);
    }

    #[cfg(feature = "ppl")]
    impl crate::genome::trace_genome::TraceGenome for MockGenome {
        fn to_trace(&self) -> fugue::Trace {
            let mut trace = fugue::Trace::default();
            for (i, &gene) in self.genes.iter().enumerate() {
                trace.insert_choice(fugue::addr!("gene", i), fugue::ChoiceValue::F64(gene), 0.0);
            }
            trace
        }

        fn from_trace(trace: &fugue::Trace) -> Result<Self, GenomeError> {
            let mut genes = Vec::new();
            let mut i = 0;
            while let Some(val) = trace.get_f64(&fugue::addr!("gene", i)) {
                genes.push(val);
                i += 1;
            }
            if genes.is_empty() {
                return Err(GenomeError::InvalidStructure(
                    "No genes found in trace".to_string(),
                ));
            }
            Ok(Self { genes })
        }
    }

    #[cfg(feature = "ppl")]
    #[test]
    fn test_mock_genome_to_trace() {
        use crate::genome::trace_genome::TraceGenome;
        let genome = MockGenome {
            genes: vec![1.0, 2.0, 3.0],
        };
        let trace = genome.to_trace();

        assert_eq!(trace.get_f64(&fugue::addr!("gene", 0)), Some(1.0));
        assert_eq!(trace.get_f64(&fugue::addr!("gene", 1)), Some(2.0));
        assert_eq!(trace.get_f64(&fugue::addr!("gene", 2)), Some(3.0));
    }

    #[cfg(feature = "ppl")]
    #[test]
    fn test_mock_genome_from_trace() {
        use crate::genome::trace_genome::TraceGenome;
        let mut trace = fugue::Trace::default();
        trace.insert_choice(fugue::addr!("gene", 0), fugue::ChoiceValue::F64(1.5), 0.0);
        trace.insert_choice(fugue::addr!("gene", 1), fugue::ChoiceValue::F64(2.5), 0.0);
        trace.insert_choice(fugue::addr!("gene", 2), fugue::ChoiceValue::F64(3.5), 0.0);

        let genome = MockGenome::from_trace(&trace).unwrap();
        assert_eq!(genome.genes, vec![1.5, 2.5, 3.5]);
    }

    #[cfg(feature = "ppl")]
    #[test]
    fn test_mock_genome_trace_roundtrip() {
        use crate::genome::trace_genome::TraceGenome;
        let original = MockGenome {
            genes: vec![1.0, 2.0, 3.0, 4.0, 5.0],
        };
        let trace = original.to_trace();
        let recovered = MockGenome::from_trace(&trace).unwrap();
        assert_eq!(original, recovered);
    }

    // Mock binary genome for testing
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct MockBinaryGenome {
        bits: Vec<bool>,
    }

    impl EvolutionaryGenome for MockBinaryGenome {
        type Allele = bool;
        type Phenotype = Vec<bool>;

        fn decode(&self) -> Self::Phenotype {
            self.bits.clone()
        }

        fn dimension(&self) -> usize {
            self.bits.len()
        }

        fn generate<R: Rng>(rng: &mut R, bounds: &MultiBounds) -> Self {
            let bits = (0..bounds.dimension()).map(|_| rng.gen()).collect();
            Self { bits }
        }

        fn distance(&self, other: &Self) -> f64 {
            self.try_distance(other)
                .expect("distance: genomes have mismatched dimension")
        }

        fn try_distance(&self, other: &Self) -> Result<f64, GenomeError> {
            if self.bits.len() != other.bits.len() {
                return Err(GenomeError::DimensionMismatch {
                    expected: self.bits.len(),
                    actual: other.bits.len(),
                });
            }
            Ok(self
                .bits
                .iter()
                .zip(other.bits.iter())
                .filter(|(a, b)| a != b)
                .count() as f64)
        }
    }

    #[cfg(feature = "ppl")]
    impl crate::genome::trace_genome::TraceGenome for MockBinaryGenome {
        fn to_trace(&self) -> fugue::Trace {
            let mut trace = fugue::Trace::default();
            for (i, &bit) in self.bits.iter().enumerate() {
                trace.insert_choice(fugue::addr!("bit", i), fugue::ChoiceValue::Bool(bit), 0.0);
            }
            trace
        }

        fn from_trace(trace: &fugue::Trace) -> Result<Self, GenomeError> {
            let mut bits = Vec::new();
            let mut i = 0;
            while let Some(val) = trace.get_bool(&fugue::addr!("bit", i)) {
                bits.push(val);
                i += 1;
            }
            if bits.is_empty() {
                return Err(GenomeError::InvalidStructure(
                    "No bits found in trace".to_string(),
                ));
            }
            Ok(Self { bits })
        }

        fn trace_prefix() -> &'static str {
            "bit"
        }
    }

    impl BinaryGenome for MockBinaryGenome {
        fn bits(&self) -> &[bool] {
            &self.bits
        }

        fn bits_mut(&mut self) -> &mut [bool] {
            &mut self.bits
        }

        fn from_bits(bits: Vec<bool>) -> Result<Self, GenomeError> {
            Ok(Self { bits })
        }
    }

    #[test]
    fn test_binary_genome_count() {
        let genome = MockBinaryGenome {
            bits: vec![true, false, true, true, false],
        };
        assert_eq!(genome.count_ones(), 3);
        assert_eq!(genome.count_zeros(), 2);
    }

    #[cfg(feature = "ppl")]
    #[test]
    fn test_binary_genome_trace_roundtrip() {
        use crate::genome::trace_genome::TraceGenome;
        let original = MockBinaryGenome {
            bits: vec![true, false, true, false, true],
        };
        let trace = original.to_trace();
        let recovered = MockBinaryGenome::from_trace(&trace).unwrap();
        assert_eq!(original, recovered);
    }

    // Mock permutation genome for testing
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    struct MockPermGenome {
        perm: Vec<usize>,
    }

    impl EvolutionaryGenome for MockPermGenome {
        type Allele = usize;
        type Phenotype = Vec<usize>;

        fn decode(&self) -> Self::Phenotype {
            self.perm.clone()
        }

        fn dimension(&self) -> usize {
            self.perm.len()
        }

        fn generate<R: Rng>(rng: &mut R, bounds: &MultiBounds) -> Self {
            use rand::seq::SliceRandom;
            let n = bounds.dimension();
            let mut perm: Vec<usize> = (0..n).collect();
            perm.shuffle(rng);
            Self { perm }
        }

        fn distance(&self, other: &Self) -> f64 {
            self.try_distance(other)
                .expect("distance: genomes have mismatched dimension")
        }

        fn try_distance(&self, other: &Self) -> Result<f64, GenomeError> {
            if self.perm.len() != other.perm.len() {
                return Err(GenomeError::DimensionMismatch {
                    expected: self.perm.len(),
                    actual: other.perm.len(),
                });
            }
            // Hamming-style positional disagreement (sufficient for the mock).
            Ok(self
                .perm
                .iter()
                .zip(other.perm.iter())
                .filter(|(a, b)| a != b)
                .count() as f64)
        }
    }

    #[cfg(feature = "ppl")]
    impl crate::genome::trace_genome::TraceGenome for MockPermGenome {
        fn to_trace(&self) -> fugue::Trace {
            let mut trace = fugue::Trace::default();
            for (i, &val) in self.perm.iter().enumerate() {
                trace.insert_choice(fugue::addr!("perm", i), fugue::ChoiceValue::Usize(val), 0.0);
            }
            trace
        }

        fn from_trace(trace: &fugue::Trace) -> Result<Self, GenomeError> {
            let mut perm = Vec::new();
            let mut i = 0;
            while let Some(val) = trace.get_usize(&fugue::addr!("perm", i)) {
                perm.push(val);
                i += 1;
            }
            if perm.is_empty() {
                return Err(GenomeError::InvalidStructure(
                    "No permutation found in trace".to_string(),
                ));
            }
            Ok(Self { perm })
        }

        fn trace_prefix() -> &'static str {
            "perm"
        }
    }

    impl PermutationGenome for MockPermGenome {
        fn permutation(&self) -> &[usize] {
            &self.perm
        }

        fn permutation_mut(&mut self) -> &mut [usize] {
            &mut self.perm
        }

        fn from_permutation(perm: Vec<usize>) -> Result<Self, GenomeError> {
            Ok(Self { perm })
        }
    }

    #[test]
    fn test_permutation_genome_is_valid() {
        let valid = MockPermGenome {
            perm: vec![2, 0, 1, 3],
        };
        assert!(valid.is_valid_permutation());

        let invalid_dup = MockPermGenome {
            perm: vec![0, 1, 1, 3],
        };
        assert!(!invalid_dup.is_valid_permutation());

        let invalid_range = MockPermGenome {
            perm: vec![0, 1, 5, 3],
        };
        assert!(!invalid_range.is_valid_permutation());

        let empty = MockPermGenome { perm: vec![] };
        assert!(empty.is_valid_permutation());
    }

    #[cfg(feature = "ppl")]
    #[test]
    fn test_permutation_genome_trace_roundtrip() {
        use crate::genome::trace_genome::TraceGenome;
        let original = MockPermGenome {
            perm: vec![3, 1, 4, 0, 2],
        };
        let trace = original.to_trace();
        let recovered = MockPermGenome::from_trace(&trace).unwrap();
        assert_eq!(original, recovered);
    }
}