fugue-evo 0.1.0

A Probabilistic Genetic Algorithm Library 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
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
//! Bit string genome
//!
//! This module provides a fixed-length bit string genome type for combinatorial optimization,
//! with Fugue trace integration for probabilistic operations.

use fugue::{addr, ChoiceValue, Trace};
use rand::Rng;
use serde::{Deserialize, Serialize};

use crate::error::GenomeError;
use crate::genome::bounds::MultiBounds;
use crate::genome::traits::{BinaryGenome, EvolutionaryGenome};

/// Fixed-length bit string genome
///
/// This genome type represents binary optimization problems where
/// solutions are vectors of boolean values.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BitString {
    /// The bits of this genome
    bits: Vec<bool>,
}

impl BitString {
    /// Create a new bit string with the given bits
    pub fn new(bits: Vec<bool>) -> Self {
        Self { bits }
    }

    /// Create an all-zeros bit string of the given length
    pub fn zeros(length: usize) -> Self {
        Self {
            bits: vec![false; length],
        }
    }

    /// Create an all-ones bit string of the given length
    pub fn ones(length: usize) -> Self {
        Self {
            bits: vec![true; length],
        }
    }

    /// Generate a random bit string of an explicit length.
    ///
    /// This is the honest constructor for random generation: unlike
    /// [`EvolutionaryGenome::generate`],
    /// which overloads `MultiBounds` and only reads its dimension count, this
    /// takes the number of bits directly.
    pub fn generate_with_len<R: Rng>(rng: &mut R, len: usize) -> Self {
        Self {
            bits: (0..len).map(|_| rng.gen()).collect(),
        }
    }

    /// Create a bit string from a u64 with the given length
    pub fn from_u64(value: u64, length: usize) -> Self {
        assert!(length <= 64, "Length must be <= 64 for u64 conversion");
        let bits = (0..length).map(|i| (value >> i) & 1 == 1).collect();
        Self { bits }
    }

    /// Convert to a u64 (only valid for length <= 64)
    pub fn to_u64(&self) -> Option<u64> {
        if self.bits.len() > 64 {
            return None;
        }
        let mut value = 0u64;
        for (i, &bit) in self.bits.iter().enumerate() {
            if bit {
                value |= 1 << i;
            }
        }
        Some(value)
    }

    /// Get the length of the bit string
    pub fn len(&self) -> usize {
        self.bits.len()
    }

    /// Check if the bit string is empty
    pub fn is_empty(&self) -> bool {
        self.bits.is_empty()
    }

    /// Get a specific bit
    pub fn get(&self, index: usize) -> Option<bool> {
        self.bits.get(index).copied()
    }

    /// Set a specific bit
    pub fn set(&mut self, index: usize, value: bool) {
        if let Some(bit) = self.bits.get_mut(index) {
            *bit = value;
        }
    }

    /// Flip a specific bit
    pub fn flip(&mut self, index: usize) {
        if let Some(bit) = self.bits.get_mut(index) {
            *bit = !*bit;
        }
    }

    /// Flip all bits
    pub fn flip_all(&mut self) {
        for bit in &mut self.bits {
            *bit = !*bit;
        }
    }

    /// Get the complement (all bits flipped)
    pub fn complement(&self) -> Self {
        Self {
            bits: self.bits.iter().map(|b| !b).collect(),
        }
    }

    /// Hamming distance to another bit string.
    ///
    /// # Panics
    /// Panics if the two bit strings have different lengths (an invariant
    /// violation). Use [`try_hamming_distance`](Self::try_hamming_distance) for
    /// a fallible variant.
    pub fn hamming_distance(&self, other: &Self) -> usize {
        self.try_hamming_distance(other)
            .unwrap_or_else(|e| panic!("BitString::hamming_distance: {e}"))
    }

    /// Fallible Hamming distance: returns `Err(GenomeError::DimensionMismatch)`
    /// when the two bit strings differ in length instead of silently truncating
    /// to the shorter one.
    pub fn try_hamming_distance(&self, other: &Self) -> Result<usize, 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())
    }

    /// Bitwise AND with another bit string
    pub fn and(&self, other: &Self) -> Result<Self, GenomeError> {
        if self.bits.len() != other.bits.len() {
            return Err(GenomeError::DimensionMismatch {
                expected: self.bits.len(),
                actual: other.bits.len(),
            });
        }
        Ok(Self {
            bits: self
                .bits
                .iter()
                .zip(other.bits.iter())
                .map(|(a, b)| *a && *b)
                .collect(),
        })
    }

    /// Bitwise OR with another bit string
    pub fn or(&self, other: &Self) -> Result<Self, GenomeError> {
        if self.bits.len() != other.bits.len() {
            return Err(GenomeError::DimensionMismatch {
                expected: self.bits.len(),
                actual: other.bits.len(),
            });
        }
        Ok(Self {
            bits: self
                .bits
                .iter()
                .zip(other.bits.iter())
                .map(|(a, b)| *a || *b)
                .collect(),
        })
    }

    /// Bitwise XOR with another bit string
    pub fn xor(&self, other: &Self) -> Result<Self, GenomeError> {
        if self.bits.len() != other.bits.len() {
            return Err(GenomeError::DimensionMismatch {
                expected: self.bits.len(),
                actual: other.bits.len(),
            });
        }
        Ok(Self {
            bits: self
                .bits
                .iter()
                .zip(other.bits.iter())
                .map(|(a, b)| *a ^ *b)
                .collect(),
        })
    }
}

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

    /// Convert BitString to Fugue trace.
    ///
    /// Each bit is stored at address "bit#i" where i is the index.
    fn to_trace(&self) -> Trace {
        let mut trace = Trace::default();
        for (i, &bit) in self.bits.iter().enumerate() {
            trace.insert_choice(addr!("bit", i), ChoiceValue::Bool(bit), 0.0);
        }
        trace
    }

    /// Reconstruct BitString from Fugue trace.
    ///
    /// Reads bits from addresses "bit#0", "bit#1", ... until no more are found.
    /// A *missing* address terminates the scan (normal end of the sequence),
    /// but an address that is *present with the wrong value type* is a corrupt
    /// trace and yields [`GenomeError::TypeMismatch`] rather than silently
    /// truncating.
    fn from_trace(trace: &Trace) -> Result<Self, GenomeError> {
        let mut bits = Vec::new();
        let mut i = 0;
        loop {
            match trace.choices.get(&addr!("bit", i)) {
                None => break,
                Some(choice) => match choice.value.as_bool() {
                    Some(val) => {
                        bits.push(val);
                        i += 1;
                    }
                    None => {
                        return Err(GenomeError::TypeMismatch {
                            address: format!("bit#{i}"),
                            expected: "bool".to_string(),
                            actual: choice.value.type_name().to_string(),
                        });
                    }
                },
            }
        }
        if bits.is_empty() {
            return Err(GenomeError::InvalidStructure(
                "No bits found in trace".to_string(),
            ));
        }
        Ok(Self { bits })
    }

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

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

    /// Generate a random bit string.
    ///
    /// Only `bounds.dimension()` is consulted — it is the number of bits — and
    /// the per-dimension `min`/`max` values are ignored. Prefer
    /// [`BitString::generate_with_len`] to make the length explicit.
    fn generate<R: Rng>(rng: &mut R, bounds: &MultiBounds) -> Self {
        Self::generate_with_len(rng, bounds.dimension())
    }

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

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

    fn distance(&self, other: &Self) -> f64 {
        self.try_distance(other).unwrap_or_else(|e| {
            panic!("BitString::distance: {e}; use try_distance for a fallible comparison")
        })
    }

    fn try_distance(&self, other: &Self) -> Result<f64, GenomeError> {
        self.try_hamming_distance(other).map(|d| d as f64)
    }

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

impl BinaryGenome for BitString {
    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 })
    }
}

impl std::ops::Index<usize> for BitString {
    type Output = bool;

    fn index(&self, index: usize) -> &Self::Output {
        &self.bits[index]
    }
}

impl From<Vec<bool>> for BitString {
    fn from(bits: Vec<bool>) -> Self {
        Self { bits }
    }
}

impl From<BitString> for Vec<bool> {
    fn from(genome: BitString) -> Self {
        genome.bits
    }
}

impl<const N: usize> From<[bool; N]> for BitString {
    fn from(arr: [bool; N]) -> Self {
        Self { bits: arr.to_vec() }
    }
}

impl IntoIterator for BitString {
    type Item = bool;
    type IntoIter = std::vec::IntoIter<bool>;

    fn into_iter(self) -> Self::IntoIter {
        self.bits.into_iter()
    }
}

impl<'a> IntoIterator for &'a BitString {
    type Item = &'a bool;
    type IntoIter = std::slice::Iter<'a, bool>;

    fn into_iter(self) -> Self::IntoIter {
        self.bits.iter()
    }
}

impl std::fmt::Display for BitString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for bit in &self.bits {
            write!(f, "{}", if *bit { '1' } else { '0' })?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fugue::addr;

    #[test]
    fn test_bit_string_new() {
        let bs = BitString::new(vec![true, false, true]);
        assert_eq!(bs.len(), 3);
        assert_eq!(bs.bits(), &[true, false, true]);
    }

    #[test]
    fn test_bit_string_zeros() {
        let bs = BitString::zeros(5);
        assert_eq!(bs.len(), 5);
        assert!(bs.bits().iter().all(|&b| !b));
        assert_eq!(bs.count_ones(), 0);
        assert_eq!(bs.count_zeros(), 5);
    }

    #[test]
    fn test_bit_string_ones() {
        let bs = BitString::ones(5);
        assert_eq!(bs.len(), 5);
        assert!(bs.bits().iter().all(|&b| b));
        assert_eq!(bs.count_ones(), 5);
        assert_eq!(bs.count_zeros(), 0);
    }

    #[test]
    fn test_bit_string_from_u64() {
        let bs = BitString::from_u64(0b101, 4);
        assert_eq!(bs.bits(), &[true, false, true, false]);
    }

    #[test]
    fn test_bit_string_to_u64() {
        let bs = BitString::new(vec![true, false, true, false]);
        assert_eq!(bs.to_u64(), Some(0b0101));

        let long_bs = BitString::zeros(100);
        assert_eq!(long_bs.to_u64(), None);
    }

    #[test]
    fn test_bit_string_get_set() {
        let mut bs = BitString::zeros(3);
        assert_eq!(bs.get(0), Some(false));
        assert_eq!(bs.get(3), None);

        bs.set(1, true);
        assert_eq!(bs.get(1), Some(true));
    }

    #[test]
    fn test_bit_string_flip() {
        let mut bs = BitString::zeros(3);
        bs.flip(1);
        assert_eq!(bs.bits(), &[false, true, false]);
    }

    #[test]
    fn test_bit_string_flip_all() {
        let mut bs = BitString::new(vec![true, false, true]);
        bs.flip_all();
        assert_eq!(bs.bits(), &[false, true, false]);
    }

    #[test]
    fn test_bit_string_complement() {
        let bs = BitString::new(vec![true, false, true]);
        let comp = bs.complement();
        assert_eq!(comp.bits(), &[false, true, false]);
    }

    #[test]
    fn test_bit_string_hamming_distance() {
        let bs1 = BitString::new(vec![true, false, true, false]);
        let bs2 = BitString::new(vec![true, true, false, false]);
        assert_eq!(bs1.hamming_distance(&bs2), 2);
    }

    #[test]
    fn test_bit_string_and() {
        let bs1 = BitString::new(vec![true, true, false, false]);
        let bs2 = BitString::new(vec![true, false, true, false]);
        let result = bs1.and(&bs2).unwrap();
        assert_eq!(result.bits(), &[true, false, false, false]);
    }

    #[test]
    fn test_bit_string_or() {
        let bs1 = BitString::new(vec![true, true, false, false]);
        let bs2 = BitString::new(vec![true, false, true, false]);
        let result = bs1.or(&bs2).unwrap();
        assert_eq!(result.bits(), &[true, true, true, false]);
    }

    #[test]
    fn test_bit_string_xor() {
        let bs1 = BitString::new(vec![true, true, false, false]);
        let bs2 = BitString::new(vec![true, false, true, false]);
        let result = bs1.xor(&bs2).unwrap();
        assert_eq!(result.bits(), &[false, true, true, false]);
    }

    #[test]
    fn test_bit_string_dimension_mismatch() {
        let bs1 = BitString::zeros(3);
        let bs2 = BitString::zeros(4);
        assert!(bs1.and(&bs2).is_err());
        assert!(bs1.or(&bs2).is_err());
        assert!(bs1.xor(&bs2).is_err());
    }

    #[test]
    fn test_bit_string_generate() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(1.0, 10);
        let bs = BitString::generate(&mut rng, &bounds);
        assert_eq!(bs.len(), 10);
    }

    #[test]
    fn test_bit_string_distance() {
        let bs1 = BitString::new(vec![true, false, true, false]);
        let bs2 = BitString::new(vec![true, true, false, false]);
        assert_eq!(bs1.distance(&bs2), 2.0);
    }

    #[test]
    fn test_bit_string_display() {
        let bs = BitString::new(vec![true, false, true, true]);
        assert_eq!(format!("{}", bs), "1011");
    }

    #[test]
    fn test_bit_string_indexing() {
        let bs = BitString::new(vec![true, false, true]);
        assert!(bs[0]);
        assert!(!bs[1]);
        assert!(bs[2]);
    }

    #[test]
    fn test_bit_string_from_array() {
        let bs: BitString = [true, false, true].into();
        assert_eq!(bs.bits(), &[true, false, true]);
    }

    #[test]
    fn test_bit_string_serialization() {
        let bs = BitString::new(vec![true, false, true]);
        let serialized = serde_json::to_string(&bs).unwrap();
        let deserialized: BitString = serde_json::from_str(&serialized).unwrap();
        assert_eq!(bs, deserialized);
    }

    #[test]
    fn test_bit_string_decode() {
        let bs = BitString::new(vec![true, false, true]);
        let phenotype = bs.decode();
        assert_eq!(phenotype, vec![true, false, true]);
    }

    #[test]
    fn test_bit_string_to_trace() {
        let bs = BitString::new(vec![true, false, true, false]);
        let trace = bs.to_trace();

        assert_eq!(trace.get_bool(&addr!("bit", 0)), Some(true));
        assert_eq!(trace.get_bool(&addr!("bit", 1)), Some(false));
        assert_eq!(trace.get_bool(&addr!("bit", 2)), Some(true));
        assert_eq!(trace.get_bool(&addr!("bit", 3)), Some(false));
        assert_eq!(trace.get_bool(&addr!("bit", 4)), None);
    }

    #[test]
    fn test_bit_string_from_trace() {
        let mut trace = Trace::default();
        trace.insert_choice(addr!("bit", 0), ChoiceValue::Bool(true), 0.0);
        trace.insert_choice(addr!("bit", 1), ChoiceValue::Bool(false), 0.0);
        trace.insert_choice(addr!("bit", 2), ChoiceValue::Bool(true), 0.0);

        let bs = BitString::from_trace(&trace).unwrap();
        assert_eq!(bs.bits(), &[true, false, true]);
    }

    #[test]
    fn test_bit_string_trace_roundtrip() {
        let original = BitString::new(vec![true, false, true, true, false]);
        let trace = original.to_trace();
        let recovered = BitString::from_trace(&trace).unwrap();
        assert_eq!(original, recovered);
    }

    #[test]
    fn test_bit_string_from_trace_empty() {
        let trace = Trace::default();
        let result = BitString::from_trace(&trace);
        assert!(result.is_err());
    }

    #[test]
    fn test_bit_string_try_hamming_distance_mismatch() {
        // regression: EV-55 — hamming_distance previously truncated to the
        // shorter length and reported 0 despite 4 extra set bits.
        let bs1 = BitString::new(vec![true, true]);
        let bs2 = BitString::new(vec![true, true, true, true, true, true]);
        assert!(matches!(
            bs1.try_hamming_distance(&bs2),
            Err(GenomeError::DimensionMismatch {
                expected: 2,
                actual: 6
            })
        ));
        assert!(bs1.try_distance(&bs2).is_err());
    }

    #[test]
    #[should_panic(expected = "Dimension mismatch")]
    fn test_bit_string_distance_mismatch_panics() {
        // regression: EV-55 — distance() must loudly reject a length mismatch.
        let bs1 = BitString::new(vec![true, true]);
        let bs2 = BitString::new(vec![true, true, true, true, true, true]);
        let _ = bs1.distance(&bs2);
    }

    #[test]
    fn test_bit_string_from_trace_type_mismatch() {
        // regression: EV-59 — a present-but-wrong-typed choice must raise
        // TypeMismatch rather than silently truncating the bit string.
        let mut trace = Trace::default();
        trace.insert_choice(addr!("bit", 0), ChoiceValue::Bool(true), 0.0);
        trace.insert_choice(addr!("bit", 1), ChoiceValue::F64(1.0), 0.0); // wrong type
        trace.insert_choice(addr!("bit", 2), ChoiceValue::Bool(false), 0.0);

        match BitString::from_trace(&trace) {
            Err(GenomeError::TypeMismatch {
                address,
                expected,
                actual,
            }) => {
                assert_eq!(address, "bit#1");
                assert_eq!(expected, "bool");
                assert_eq!(actual, "f64");
            }
            other => panic!("expected TypeMismatch, got {other:?}"),
        }
    }

    #[test]
    fn test_bit_string_generate_with_len() {
        // EV-94: honest constructor takes an explicit length.
        let mut rng = rand::thread_rng();
        let bs = BitString::generate_with_len(&mut rng, 7);
        assert_eq!(bs.len(), 7);
    }
}