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
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Permutation genome
//!
//! This module provides a permutation genome type for ordering problems
//! (e.g., TSP, scheduling) with Fugue trace integration.

#[cfg(feature = "ppl")]
use fugue::{addr, ChoiceValue, Trace};
use rand::seq::SliceRandom;
use rand::Rng;
use serde::{Deserialize, Serialize};

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

/// Permutation genome for ordering problems
///
/// Represents a permutation of indices 0..n, commonly used for:
/// - Traveling Salesman Problem (TSP)
/// - Job Shop Scheduling
/// - Vehicle Routing Problems
/// - Any problem where the solution is an ordering of elements
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Permutation {
    /// The permutation (indices 0..n in some order)
    perm: Vec<usize>,
}

impl Permutation {
    /// Create a new permutation from a vector of indices
    ///
    /// # Panics
    /// Panics if the input is not a valid permutation of 0..n
    pub fn new(perm: Vec<usize>) -> Self {
        let result = Self { perm };
        assert!(
            result.is_valid_permutation(),
            "Input must be a valid permutation of 0..n"
        );
        result
    }

    /// Create a permutation from a vector **without** validating it.
    ///
    /// # Invariants
    /// The caller must guarantee that `perm` is a valid permutation of
    /// `0..perm.len()` — every index in that range appears exactly once.
    /// Violating this invariant does not fail here, but corrupts downstream
    /// operations that assume it:
    /// - [`inverse`](Self::inverse) panics with an out-of-bounds index for an
    ///   out-of-range value, or silently produces a meaningless result for
    ///   in-range duplicates.
    /// - [`compose`](Self::compose) panics on out-of-range indices.
    ///
    /// Prefer [`try_new`](Self::try_new) (or [`new`](Self::new)) unless validity
    /// has already been established elsewhere and you need to skip the O(n)
    /// re-check. In debug builds this constructor still asserts validity to
    /// catch contract violations early.
    pub fn from_vec_unchecked(perm: Vec<usize>) -> Self {
        let result = Self { perm };
        debug_assert!(
            result.is_valid_permutation(),
            "from_vec_unchecked called with a vector that is not a valid permutation of 0..n"
        );
        result
    }

    /// Try to create a permutation, returning an error if invalid
    pub fn try_new(perm: Vec<usize>) -> Result<Self, GenomeError> {
        let result = Self { perm };
        if result.is_valid_permutation() {
            Ok(result)
        } else {
            Err(GenomeError::InvalidStructure(
                "Input is not a valid permutation of 0..n".to_string(),
            ))
        }
    }

    /// Create the identity permutation [0, 1, 2, ..., n-1]
    pub fn identity(n: usize) -> Self {
        Self {
            perm: (0..n).collect(),
        }
    }

    /// Create a random permutation of size n
    pub fn random<R: Rng>(n: usize, rng: &mut R) -> Self {
        let mut perm: Vec<usize> = (0..n).collect();
        perm.shuffle(rng);
        Self { perm }
    }

    /// Generate a random permutation 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 permutation length directly. Equivalent to [`random`](Self::random).
    pub fn generate_with_len<R: Rng>(rng: &mut R, len: usize) -> Self {
        Self::random(len, rng)
    }

    /// Get the length of the permutation
    pub fn len(&self) -> usize {
        self.perm.len()
    }

    /// Check if the permutation is empty
    pub fn is_empty(&self) -> bool {
        self.perm.is_empty()
    }

    /// Get the element at index i
    pub fn get(&self, i: usize) -> Option<usize> {
        self.perm.get(i).copied()
    }

    /// Get the inverse permutation
    ///
    /// If `perm[i] = j`, then `inverse[j] = i`
    pub fn inverse(&self) -> Self {
        let n = self.perm.len();
        let mut inv = vec![0; n];
        for (i, &j) in self.perm.iter().enumerate() {
            inv[j] = i;
        }
        Self { perm: inv }
    }

    /// Compose this permutation with another
    ///
    /// Returns a permutation where `result[i] = other[self[i]]`
    pub fn compose(&self, other: &Self) -> Result<Self, GenomeError> {
        if self.perm.len() != other.perm.len() {
            return Err(GenomeError::DimensionMismatch {
                expected: self.perm.len(),
                actual: other.perm.len(),
            });
        }
        let composed: Vec<usize> = self.perm.iter().map(|&i| other.perm[i]).collect();
        Ok(Self { perm: composed })
    }

    /// Swap two elements at positions i and j
    pub fn swap(&mut self, i: usize, j: usize) {
        self.perm.swap(i, j);
    }

    /// Reverse a segment from start to end (inclusive)
    pub fn reverse_segment(&mut self, start: usize, end: usize) {
        if start < end && end < self.perm.len() {
            self.perm[start..=end].reverse();
        }
    }

    /// Insert element at position `from` to position `to`
    pub fn insert(&mut self, from: usize, to: usize) {
        if from == to || from >= self.perm.len() || to >= self.perm.len() {
            return;
        }
        let elem = self.perm.remove(from);
        self.perm.insert(to, elem);
    }

    /// Calculate the number of inversions (disorder measure)
    ///
    /// An inversion is a pair (i, j) where i < j but `perm[i] > perm[j]`.
    /// Returns a value in `[0, n*(n-1)/2]` where 0 means sorted.
    pub fn inversions(&self) -> usize {
        let n = self.perm.len();
        let mut count = 0;
        for i in 0..n {
            for j in (i + 1)..n {
                if self.perm[i] > self.perm[j] {
                    count += 1;
                }
            }
        }
        count
    }

    /// Calculate Kendall tau distance to another permutation
    ///
    /// Counts the number of pairwise disagreements (i.e., pairs that are
    /// in different order in the two permutations).
    pub fn kendall_tau_distance(&self, other: &Self) -> Result<usize, GenomeError> {
        if self.perm.len() != other.perm.len() {
            return Err(GenomeError::DimensionMismatch {
                expected: self.perm.len(),
                actual: other.perm.len(),
            });
        }

        // Compose with inverse of other to get relative order
        let other_inv = other.inverse();
        let composed = self.compose(&other_inv)?;

        // Count inversions in the composed permutation
        Ok(composed.inversions())
    }

    /// Check if this is a cyclic permutation (single cycle)
    pub fn is_cyclic(&self) -> bool {
        if self.perm.is_empty() {
            return true;
        }

        let n = self.perm.len();
        let mut visited = vec![false; n];
        let mut current = 0;
        let mut cycle_len = 0;

        while !visited[current] {
            visited[current] = true;
            current = self.perm[current];
            cycle_len += 1;
        }

        cycle_len == n && current == 0
    }

    /// Get the underlying vector
    pub fn into_inner(self) -> Vec<usize> {
        self.perm
    }

    /// Get a reference to the underlying slice
    pub fn as_slice(&self) -> &[usize] {
        &self.perm
    }
}

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

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

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

    /// Generate a random permutation.
    ///
    /// Only `bounds.dimension()` is consulted — it is the permutation length —
    /// and the per-dimension `min`/`max` values are ignored. Prefer
    /// [`Permutation::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 distance(&self, other: &Self) -> f64 {
        self.try_distance(other).unwrap_or_else(|e| {
            panic!("Permutation::distance: {e}; use try_distance for a fallible comparison")
        })
    }

    fn try_distance(&self, other: &Self) -> Result<f64, GenomeError> {
        // kendall_tau_distance already errors on a length mismatch; propagate it
        // instead of collapsing it to 0.0 (which meant "identical").
        self.kendall_tau_distance(other).map(|d| d as f64)
    }
}

#[cfg(feature = "ppl")]
impl crate::genome::trace_genome::TraceGenome for Permutation {
    /// Convert Permutation to Fugue trace using the **Lehmer-code (rank)**
    /// encoding: position `i` stores the rank of `perm[i]` among the values
    /// not yet used at positions `< i` (a `Usize` in `0..n-i`).
    ///
    /// This encoding (rather than storing raw values) is what makes the trace
    /// *generative*: any in-range assignment of ranks decodes to a valid
    /// permutation, so a single-site change of one rank is a valid move — the
    /// value encoding would make every single-site change a duplicate. It
    /// coincides site-for-site with the sequential categorical prior model in
    /// [`crate::inference::prior::PermutationPrior`].
    fn to_trace(&self) -> Trace {
        let n = self.perm.len();
        let mut available: Vec<usize> = (0..n).collect();
        let mut trace = Trace::default();
        for (i, &val) in self.perm.iter().enumerate() {
            let rank = available
                .iter()
                .position(|&v| v == val)
                .expect("Permutation invariant guarantees the value is available");
            available.remove(rank);
            trace.insert_choice(addr!("perm", i), ChoiceValue::Usize(rank), 0.0);
        }
        trace
    }

    /// Reconstruct Permutation from Fugue trace.
    ///
    /// Reads values from addresses "perm#0", "perm#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 — which for a permutation is especially dangerous,
    /// since a truncated prefix can itself pass the validity check.
    fn from_trace(trace: &Trace) -> Result<Self, GenomeError> {
        // First pass: read the rank sequence (Lehmer code).
        let mut ranks = Vec::new();
        let mut i = 0;
        loop {
            match trace.choices.get(&addr!("perm", i)) {
                None => break,
                Some(choice) => match choice.value.as_usize() {
                    Some(rank) => {
                        ranks.push(rank);
                        i += 1;
                    }
                    None => {
                        return Err(GenomeError::TypeMismatch {
                            address: format!("perm#{i}"),
                            expected: "usize".to_string(),
                            actual: choice.value.type_name().to_string(),
                        });
                    }
                },
            }
        }
        if ranks.is_empty() {
            return Err(GenomeError::InvalidStructure(
                "No permutation found in trace".to_string(),
            ));
        }
        // Second pass: decode ranks against the shrinking available list.
        let n = ranks.len();
        let mut available: Vec<usize> = (0..n).collect();
        let mut perm = Vec::with_capacity(n);
        for (i, &rank) in ranks.iter().enumerate() {
            if rank >= available.len() {
                return Err(GenomeError::InvalidStructure(format!(
                    "Lehmer rank {rank} at perm#{i} out of range 0..{}",
                    available.len()
                )));
            }
            perm.push(available.remove(rank));
        }
        Self::try_new(perm)
    }

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

impl PermutationGenome for Permutation {
    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> {
        Self::try_new(perm)
    }
}

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

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

impl From<Vec<usize>> for Permutation {
    fn from(perm: Vec<usize>) -> Self {
        Self::new(perm)
    }
}

impl From<Permutation> for Vec<usize> {
    fn from(p: Permutation) -> Self {
        p.perm
    }
}

impl IntoIterator for Permutation {
    type Item = usize;
    type IntoIter = std::vec::IntoIter<usize>;

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

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::genome::traits::PermutationGenome;

    #[test]
    fn test_permutation_new() {
        let p = Permutation::new(vec![2, 0, 1, 3]);
        assert_eq!(p.len(), 4);
        assert_eq!(p[0], 2);
        assert_eq!(p[1], 0);
    }

    #[test]
    #[should_panic(expected = "valid permutation")]
    fn test_permutation_new_invalid_duplicate() {
        Permutation::new(vec![0, 1, 1, 3]);
    }

    #[test]
    #[should_panic(expected = "valid permutation")]
    fn test_permutation_new_invalid_out_of_range() {
        Permutation::new(vec![0, 1, 5, 3]);
    }

    #[test]
    fn test_permutation_try_new() {
        assert!(Permutation::try_new(vec![2, 0, 1, 3]).is_ok());
        assert!(Permutation::try_new(vec![0, 1, 1, 3]).is_err());
    }

    #[test]
    fn test_permutation_identity() {
        let p = Permutation::identity(5);
        assert_eq!(p.as_slice(), &[0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_permutation_random() {
        let mut rng = rand::thread_rng();
        let p = Permutation::random(10, &mut rng);
        assert!(p.is_valid_permutation());
        assert_eq!(p.len(), 10);
    }

    #[test]
    fn test_permutation_inverse() {
        let p = Permutation::new(vec![2, 0, 3, 1]);
        let inv = p.inverse();
        // If p[i] = j, then inv[j] = i
        // p[0]=2 -> inv[2]=0, p[1]=0 -> inv[0]=1, p[2]=3 -> inv[3]=2, p[3]=1 -> inv[1]=3
        assert_eq!(inv.as_slice(), &[1, 3, 0, 2]);

        // Composing with inverse should give identity
        let composed = p.compose(&inv).unwrap();
        assert_eq!(composed.as_slice(), &[0, 1, 2, 3]);
    }

    #[test]
    fn test_permutation_compose() {
        let p1 = Permutation::new(vec![1, 2, 0]);
        let p2 = Permutation::new(vec![2, 0, 1]);
        let composed = p1.compose(&p2).unwrap();
        // composed[i] = p2[p1[i]]
        // composed[0] = p2[1] = 0, composed[1] = p2[2] = 1, composed[2] = p2[0] = 2
        assert_eq!(composed.as_slice(), &[0, 1, 2]);
    }

    #[test]
    fn test_permutation_swap() {
        let mut p = Permutation::new(vec![0, 1, 2, 3]);
        p.swap(0, 3);
        assert_eq!(p.as_slice(), &[3, 1, 2, 0]);
    }

    #[test]
    fn test_permutation_reverse_segment() {
        let mut p = Permutation::new(vec![0, 1, 2, 3, 4]);
        p.reverse_segment(1, 3);
        assert_eq!(p.as_slice(), &[0, 3, 2, 1, 4]);
    }

    #[test]
    fn test_permutation_insert() {
        let mut p = Permutation::new(vec![0, 1, 2, 3, 4]);
        p.insert(1, 4);
        assert_eq!(p.as_slice(), &[0, 2, 3, 4, 1]);
    }

    #[test]
    fn test_permutation_inversions() {
        // Sorted: 0 inversions
        let p1 = Permutation::identity(5);
        assert_eq!(p1.inversions(), 0);

        // Reversed: n*(n-1)/2 inversions
        let p2 = Permutation::new(vec![4, 3, 2, 1, 0]);
        assert_eq!(p2.inversions(), 10); // 5*4/2 = 10

        // Single swap: 1 inversion
        let p3 = Permutation::new(vec![1, 0, 2, 3, 4]);
        assert_eq!(p3.inversions(), 1);
    }

    #[test]
    fn test_permutation_kendall_tau() {
        let p1 = Permutation::new(vec![0, 1, 2, 3]);
        let p2 = Permutation::new(vec![0, 1, 2, 3]);
        assert_eq!(p1.kendall_tau_distance(&p2).unwrap(), 0);

        let p3 = Permutation::new(vec![0, 1, 3, 2]);
        assert_eq!(p1.kendall_tau_distance(&p3).unwrap(), 1);

        let p4 = Permutation::new(vec![3, 2, 1, 0]);
        assert_eq!(p1.kendall_tau_distance(&p4).unwrap(), 6);
    }

    #[test]
    fn test_permutation_is_cyclic() {
        // Single cycle (3 -> 1 -> 2 -> 0 -> 3)
        let cyclic = Permutation::new(vec![3, 2, 0, 1]);
        // Let's trace: 0 -> 3 -> 1 -> 2 -> 0, that's 4 elements in one cycle
        assert!(cyclic.is_cyclic());

        // Not a single cycle: identity has n fixed points (1-cycles)
        let identity = Permutation::identity(4);
        assert!(!identity.is_cyclic()); // Each element maps to itself

        // Empty is trivially cyclic
        let empty = Permutation::identity(0);
        assert!(empty.is_cyclic());
    }

    #[test]
    fn test_permutation_decode() {
        let p = Permutation::new(vec![2, 0, 1]);
        assert_eq!(p.decode(), vec![2, 0, 1]);
    }

    #[test]
    fn test_permutation_dimension() {
        let p = Permutation::new(vec![2, 0, 1, 3, 4]);
        assert_eq!(p.dimension(), 5);
    }

    #[test]
    fn test_permutation_generate() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(1.0, 10);
        let p = Permutation::generate(&mut rng, &bounds);
        assert_eq!(p.dimension(), 10);
        assert!(p.is_valid_permutation());
    }

    #[test]
    fn test_permutation_distance() {
        let p1 = Permutation::new(vec![0, 1, 2, 3]);
        let p2 = Permutation::new(vec![3, 2, 1, 0]);
        assert_eq!(p1.distance(&p2), 6.0);
    }

    #[test]
    #[cfg(feature = "ppl")]
    fn test_permutation_to_trace() {
        use crate::genome::trace_genome::TraceGenome;
        let p = Permutation::new(vec![2, 0, 1]);
        let trace = p.to_trace();

        // Lehmer-code (rank) encoding: [2,0,1] -> ranks (2, 0, 0).
        assert_eq!(trace.get_usize(&addr!("perm", 0)), Some(2));
        assert_eq!(trace.get_usize(&addr!("perm", 1)), Some(0));
        assert_eq!(trace.get_usize(&addr!("perm", 2)), Some(0));
        assert_eq!(trace.get_usize(&addr!("perm", 3)), None);
    }

    #[test]
    #[cfg(feature = "ppl")]
    fn test_permutation_from_trace() {
        use crate::genome::trace_genome::TraceGenome;
        let mut trace = Trace::default();
        // Lehmer ranks (1, 1, 0): available [0,1,2] -> 1; [0,2] -> 2; [0] -> 0.
        trace.insert_choice(addr!("perm", 0), ChoiceValue::Usize(1), 0.0);
        trace.insert_choice(addr!("perm", 1), ChoiceValue::Usize(1), 0.0);
        trace.insert_choice(addr!("perm", 2), ChoiceValue::Usize(0), 0.0);

        let p = Permutation::from_trace(&trace).unwrap();
        assert_eq!(p.as_slice(), &[1, 2, 0]);
    }

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

    #[test]
    #[cfg(feature = "ppl")]
    fn test_permutation_from_trace_invalid() {
        use crate::genome::trace_genome::TraceGenome;
        let mut trace = Trace::default();
        trace.insert_choice(addr!("perm", 0), ChoiceValue::Usize(0), 0.0);
        trace.insert_choice(addr!("perm", 1), ChoiceValue::Usize(5), 0.0); // rank out of range

        let result = Permutation::from_trace(&trace);
        assert!(result.is_err());
    }

    #[test]
    #[cfg(feature = "ppl")]
    fn test_permutation_from_trace_empty() {
        use crate::genome::trace_genome::TraceGenome;
        let trace = Trace::default();
        let result = Permutation::from_trace(&trace);
        assert!(result.is_err());
    }

    #[test]
    fn test_permutation_serialization() {
        let p = Permutation::new(vec![2, 0, 1, 3]);
        let serialized = serde_json::to_string(&p).unwrap();
        let deserialized: Permutation = serde_json::from_str(&serialized).unwrap();
        assert_eq!(p, deserialized);
    }

    #[test]
    fn test_permutation_iteration() {
        let p = Permutation::new(vec![2, 0, 1]);
        let collected: Vec<usize> = p.into_iter().collect();
        assert_eq!(collected, vec![2, 0, 1]);
    }

    #[test]
    fn test_permutation_ref_iteration() {
        let p = Permutation::new(vec![2, 0, 1]);
        let sum: usize = p.into_iter().sum();
        assert_eq!(sum, 3);
    }

    #[test]
    fn test_permutation_into_inner() {
        let p = Permutation::new(vec![2, 0, 1]);
        let v: Vec<usize> = p.into_inner();
        assert_eq!(v, vec![2, 0, 1]);
    }

    #[test]
    fn test_permutation_from_vec() {
        let p: Permutation = vec![1, 0, 2].into();
        assert_eq!(p.as_slice(), &[1, 0, 2]);
    }

    #[test]
    fn test_permutation_try_distance_length_mismatch() {
        // regression: EV-19 — distance previously swallowed the length-mismatch
        // Err via unwrap_or(0) and reported 0.0 ("identical") for different sizes.
        let p1 = Permutation::identity(3);
        let p2 = Permutation::identity(5);
        assert!(matches!(
            p1.try_distance(&p2),
            Err(GenomeError::DimensionMismatch {
                expected: 3,
                actual: 5
            })
        ));
    }

    #[test]
    #[should_panic(expected = "Dimension mismatch")]
    fn test_permutation_distance_length_mismatch_panics() {
        // regression: EV-19 — distance() must loudly reject a length mismatch
        // rather than returning 0.0 as if the permutations were identical.
        let p1 = Permutation::identity(3);
        let p2 = Permutation::identity(5);
        let _ = p1.distance(&p2);
    }

    #[test]
    #[cfg(feature = "ppl")]
    fn test_permutation_from_trace_type_mismatch() {
        // regression: EV-59 — a present-but-wrong-typed choice must raise
        // TypeMismatch. This is especially important for permutations, since a
        // silently truncated prefix can itself be a "valid" shorter permutation.
        use crate::genome::trace_genome::TraceGenome;
        let mut trace = Trace::default();
        trace.insert_choice(addr!("perm", 0), ChoiceValue::Usize(2), 0.0);
        trace.insert_choice(addr!("perm", 1), ChoiceValue::Bool(true), 0.0); // wrong type
        trace.insert_choice(addr!("perm", 2), ChoiceValue::Usize(0), 0.0);

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

    #[test]
    fn test_permutation_from_vec_unchecked_debug_asserts() {
        // regression: EV-92 — the unchecked constructor now debug-asserts the
        // invariant. In debug builds an invalid vector triggers the assertion.
        let p = Permutation::from_vec_unchecked(vec![2, 0, 1]);
        assert!(p.is_valid_permutation());
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "not a valid permutation")]
    fn test_permutation_from_vec_unchecked_rejects_invalid_in_debug() {
        // regression: EV-92 — in-range duplicates are a contract violation.
        let _ = Permutation::from_vec_unchecked(vec![0, 0, 2]);
    }

    #[test]
    fn test_permutation_generate_with_len() {
        // EV-94: honest constructor takes an explicit length.
        let mut rng = rand::thread_rng();
        let p = Permutation::generate_with_len(&mut rng, 8);
        assert_eq!(p.len(), 8);
        assert!(p.is_valid_permutation());
    }
}