Skip to main content

evolutionary_planning/operators/
chain.rs

1//! GLEAM action chains (Blume and Jakob; Jakob 2021): variable-length chromosomes of typed,
2//! parameterised actions, with gene-level and chain-level mutations and crossovers that
3//! accept parents of different lengths.
4//!
5//! Two layers:
6//!
7//! - **Chain level**, generic over any `Vec<T>`: shifting a gene or a segment, inverting a
8//!   segment, inserting, deleting, duplicating or replacing genes and segments, and
9//!   cut-and-splice, n-point and segment-exchange crossover. A new gene comes from any
10//!   [`Initializer<T>`], so a SAS+ plan `Vec<OpId>` uses these unchanged.
11//! - **Gene level**, on [`Action`]s described by an [`ActionModel`]: each action type has its
12//!   own integer or real parameters with bounds that the mutations respect (Jakob's rule
13//!   that explicit restrictions belong in the operators).
14//!
15//! GLEAM applies one operator per offspring, drawn from a weighted operator mix; build such a
16//! mix with [`mix`](super::mix).
17//!
18//! ```
19//! use evolutionary_planning::operators::chain::{Action, ActionKind, ActionModel, ParamSpec, RandomChain};
20//! use evolutionary_planning::operators::Initializer;
21//! use evolutionary_planning::SplitMix64;
22//!
23//! // Two action types: "move" with a real distance and "turn" with an integer angle.
24//! let model = ActionModel::new(vec![
25//!     ActionKind::new(vec![ParamSpec::real(0.0, 10.0)]),
26//!     ActionKind::new(vec![ParamSpec::integer(-180.0, 180.0)]),
27//! ]);
28//! let mut init = RandomChain { genes: model.clone(), min_len: 2, max_len: 6 };
29//! let chain: Vec<Action> = init.initialize(&mut SplitMix64::new(1));
30//! assert!((2..=6).contains(&chain.len()));
31//! assert!(chain.iter().all(|action| model.is_valid(action)));
32//! ```
33
34use alloc::vec::Vec;
35
36use rand_core::Rng;
37
38use super::{Crossover, Initializer, Mutation};
39use crate::operators::sequence::splice;
40use crate::rng::{below, uniform, unit_f64};
41
42/// The bounds and kind of one action parameter.
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub struct ParamSpec {
45    /// The smallest value, finite.
46    pub low: f64,
47    /// The largest value, finite, `>= low`.
48    pub high: f64,
49    /// Whether the parameter takes integer values only (stored as whole `f64`s).
50    pub integer: bool,
51}
52
53impl ParamSpec {
54    /// A real parameter in `[low, high]`.
55    #[must_use]
56    pub const fn real(low: f64, high: f64) -> Self {
57        Self {
58            low,
59            high,
60            integer: false,
61        }
62    }
63
64    /// An integer parameter in `[low, high]` (both rounded towards the inside).
65    #[must_use]
66    pub const fn integer(low: f64, high: f64) -> Self {
67        Self {
68            low,
69            high,
70            integer: true,
71        }
72    }
73
74    /// Draws a uniform value; integers uniformly among the whole numbers in range.
75    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
76        if self.integer {
77            let low = libm::ceil(self.low);
78            let high = libm::floor(self.high);
79            #[expect(
80                clippy::cast_possible_truncation,
81                clippy::cast_sign_loss,
82                reason = "the count of whole numbers in a finite parameter range"
83            )]
84            let count = (high - low) as usize + 1;
85            #[expect(
86                clippy::cast_precision_loss,
87                reason = "parameter ranges are far below 2^52"
88            )]
89            let offset = below(rng, count.max(1)) as f64;
90            low + offset
91        } else {
92            uniform(rng, self.low, self.high).min(self.high)
93        }
94    }
95
96    /// Clamps and, for integers, rounds `value` into range.
97    fn fit(&self, value: f64) -> f64 {
98        if self.integer {
99            libm::round(value).clamp(libm::ceil(self.low), libm::floor(self.high))
100        } else {
101            value.clamp(self.low, self.high)
102        }
103    }
104
105    /// Returns `true` if `value` is in range (and whole, for integers).
106    fn admits(&self, value: f64) -> bool {
107        (self.low..=self.high).contains(&value)
108            && (!self.integer || libm::round(value).total_cmp(&value).is_eq())
109    }
110}
111
112/// One action type: its parameter list.
113#[derive(Debug, Clone, PartialEq)]
114pub struct ActionKind {
115    /// The parameters every action of this type carries, in order.
116    pub params: Vec<ParamSpec>,
117}
118
119impl ActionKind {
120    /// An action type with the given parameters.
121    #[must_use]
122    pub fn new(params: Vec<ParamSpec>) -> Self {
123        Self { params }
124    }
125}
126
127/// One gene of a GLEAM chain: an action type and its parameter values.
128#[derive(Debug, Clone, PartialEq)]
129pub struct Action {
130    /// Index into [`ActionModel::kinds`].
131    pub kind: usize,
132    /// One value per parameter of the kind, within its [`ParamSpec`].
133    pub params: Vec<f64>,
134}
135
136/// The action types a chain may contain. Implements [`Initializer<Action>`]: a uniform kind
137/// with uniform parameters.
138#[derive(Debug, Clone, PartialEq)]
139pub struct ActionModel {
140    /// The action types; never empty.
141    kinds: Vec<ActionKind>,
142}
143
144impl ActionModel {
145    /// Creates a model.
146    ///
147    /// # Panics
148    ///
149    /// Panics if `kinds` is empty or a parameter range is empty or not finite.
150    #[must_use]
151    pub fn new(kinds: Vec<ActionKind>) -> Self {
152        assert!(
153            !kinds.is_empty(),
154            "an action model needs at least one action type"
155        );
156        for spec in kinds.iter().flat_map(|k| &k.params) {
157            assert!(
158                spec.low.is_finite() && spec.high.is_finite() && spec.low <= spec.high,
159                "invalid parameter range [{}, {}]",
160                spec.low,
161                spec.high
162            );
163        }
164
165        Self { kinds }
166    }
167
168    /// The action types.
169    #[must_use]
170    pub fn kinds(&self) -> &[ActionKind] {
171        &self.kinds
172    }
173
174    /// Returns `true` if `action` has a known kind and admissible parameters.
175    #[must_use]
176    pub fn is_valid(&self, action: &Action) -> bool {
177        self.kinds.get(action.kind).is_some_and(|kind| {
178            kind.params.len() == action.params.len()
179                && kind
180                    .params
181                    .iter()
182                    .zip(&action.params)
183                    .all(|(spec, &v)| spec.admits(v))
184        })
185    }
186
187    /// Draws new parameters for an action of type `kind`.
188    fn sample_params<R: Rng + ?Sized>(&self, kind: usize, rng: &mut R) -> Vec<f64> {
189        self.kinds[kind]
190            .params
191            .iter()
192            .map(|spec| spec.sample(rng))
193            .collect()
194    }
195}
196
197impl Initializer<Action> for ActionModel {
198    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Action {
199        let kind = below(rng, self.kinds.len());
200        let params = self.sample_params(kind, rng);
201
202        Action { kind, params }
203    }
204}
205
206/// Random chains of uniform length in `min_len..=max_len`, genes from `genes`.
207#[derive(Debug, Clone, PartialEq)]
208pub struct RandomChain<S> {
209    /// The gene sampler, for example an [`ActionModel`].
210    pub genes: S,
211    /// The shortest chain.
212    pub min_len: usize,
213    /// The longest chain, `>= min_len`.
214    pub max_len: usize,
215}
216
217impl<T, S: Initializer<T>> Initializer<Vec<T>> for RandomChain<S> {
218    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<T> {
219        let span = self.max_len.saturating_sub(self.min_len);
220        let len = self.min_len + below(rng, span + 1);
221
222        (0..len).map(|_| self.genes.initialize(rng)).collect()
223    }
224}
225
226/// Picks a random segment `[i, j)` of a chain of length `n >= 1`, at most `max_len` long
227/// (`None`: unbounded).
228fn segment<R: Rng + ?Sized>(rng: &mut R, n: usize, max_len: Option<usize>) -> (usize, usize) {
229    let start = below(rng, n);
230    let longest = (n - start).min(max_len.unwrap_or(usize::MAX)).max(1);
231    let len = 1 + below(rng, longest);
232
233    (start, start + len)
234}
235
236/// Moves one gene to another position (GLEAM "gene shift").
237#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
238pub struct GeneShift;
239
240impl<T> Mutation<Vec<T>> for GeneShift {
241    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
242        super::permutation::Insertion.mutate(genome, rng);
243    }
244}
245
246/// Moves a random segment to another position (GLEAM "segment shift").
247#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
248pub struct SegmentShift {
249    /// The longest segment moved; `None` means unbounded.
250    pub max_segment: Option<usize>,
251}
252
253impl<T> Mutation<Vec<T>> for SegmentShift {
254    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
255        if genome.len() < 2 {
256            return;
257        }
258
259        let (start, end) = segment(rng, genome.len(), self.max_segment);
260        let moved: Vec<T> = genome.drain(start..end).collect();
261        let at = below(rng, genome.len() + 1);
262        let tail = genome.split_off(at);
263        genome.extend(moved);
264        genome.extend(tail);
265    }
266}
267
268/// Reverses a random segment (GLEAM "segment inversion").
269#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
270pub struct SegmentInversion {
271    /// The longest segment reversed; `None` means unbounded.
272    pub max_segment: Option<usize>,
273}
274
275impl<T> Mutation<Vec<T>> for SegmentInversion {
276    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
277        if genome.len() >= 2 {
278            let (start, end) = segment(rng, genome.len(), self.max_segment);
279            genome[start..end].reverse();
280        }
281    }
282}
283
284/// Inserts one new random gene at a random position, unless the chain has `max_len` genes.
285#[derive(Debug, Clone, PartialEq)]
286pub struct InsertGene<S> {
287    /// The gene sampler.
288    pub genes: S,
289    /// The longest chain allowed.
290    pub max_len: usize,
291}
292
293impl<T, S: Initializer<T>> Mutation<Vec<T>> for InsertGene<S> {
294    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
295        if genome.len() < self.max_len {
296            let at = below(rng, genome.len() + 1);
297            genome.insert(at, self.genes.initialize(rng));
298        }
299    }
300}
301
302/// Inserts a segment of new random genes (length `1..=max_segment`), within `max_len`.
303#[derive(Debug, Clone, PartialEq)]
304pub struct InsertSegment<S> {
305    /// The gene sampler.
306    pub genes: S,
307    /// The longest segment inserted, at least `1`.
308    pub max_segment: usize,
309    /// The longest chain allowed.
310    pub max_len: usize,
311}
312
313impl<T, S: Initializer<T>> Mutation<Vec<T>> for InsertSegment<S> {
314    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
315        let room = self
316            .max_len
317            .saturating_sub(genome.len())
318            .min(self.max_segment.max(1));
319        if room == 0 {
320            return;
321        }
322
323        let len = 1 + below(rng, room);
324        let at = below(rng, genome.len() + 1);
325        let tail = genome.split_off(at);
326        for _ in 0..len {
327            genome.push(self.genes.initialize(rng));
328        }
329
330        genome.extend(tail);
331    }
332}
333
334/// Deletes one random gene, unless the chain has only `min_len` genes.
335#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
336pub struct DeleteGene {
337    /// The shortest chain allowed.
338    pub min_len: usize,
339}
340
341impl<T> Mutation<Vec<T>> for DeleteGene {
342    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
343        if genome.len() > self.min_len && !genome.is_empty() {
344            let at = below(rng, genome.len());
345            genome.remove(at);
346        }
347    }
348}
349
350/// Deletes a random segment, keeping at least `min_len` genes.
351#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
352pub struct DeleteSegment {
353    /// The shortest chain allowed.
354    pub min_len: usize,
355    /// The longest segment deleted; `None` means unbounded.
356    pub max_segment: Option<usize>,
357}
358
359impl<T> Mutation<Vec<T>> for DeleteSegment {
360    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
361        let removable = genome.len().saturating_sub(self.min_len);
362        if removable == 0 {
363            return;
364        }
365
366        let cap = Some(self.max_segment.unwrap_or(usize::MAX).min(removable));
367        let (start, end) = segment(rng, genome.len(), cap);
368        genome.drain(start..end);
369    }
370}
371
372/// Duplicates one random gene in place (the copy follows the original), within `max_len`.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub struct DuplicateGene {
375    /// The longest chain allowed.
376    pub max_len: usize,
377}
378
379impl<T: Clone> Mutation<Vec<T>> for DuplicateGene {
380    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
381        if !genome.is_empty() && genome.len() < self.max_len {
382            let at = below(rng, genome.len());
383            genome.insert(at + 1, genome[at].clone());
384        }
385    }
386}
387
388/// Replaces one random gene by a new random gene (GLEAM "new action").
389#[derive(Debug, Clone, PartialEq)]
390pub struct ReplaceGene<S> {
391    /// The gene sampler.
392    pub genes: S,
393}
394
395impl<T, S: Initializer<T>> Mutation<Vec<T>> for ReplaceGene<S> {
396    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<T>, rng: &mut R) {
397        if !genome.is_empty() {
398            let at = below(rng, genome.len());
399            genome[at] = self.genes.initialize(rng);
400        }
401    }
402}
403
404/// Picks a random parameter of a random gene that has parameters: `(gene, parameter)`.
405fn random_parameter<R: Rng + ?Sized>(genome: &[Action], rng: &mut R) -> Option<(usize, usize)> {
406    let with_params: Vec<usize> = (0..genome.len())
407        .filter(|&g| !genome[g].params.is_empty())
408        .collect();
409    if with_params.is_empty() {
410        return None;
411    }
412
413    let gene = with_params[below(rng, with_params.len())];
414
415    Some((gene, below(rng, genome[gene].params.len())))
416}
417
418/// Gives one parameter of one gene a new uniform value within its bounds (GLEAM "parameter
419/// new value").
420#[derive(Debug, Clone, PartialEq)]
421pub struct ParamNewValue {
422    /// The action model holding the parameter bounds.
423    pub model: ActionModel,
424}
425
426impl Mutation<Vec<Action>> for ParamNewValue {
427    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Action>, rng: &mut R) {
428        if let Some((gene, param)) = random_parameter(genome, rng) {
429            let spec = self.model.kinds[genome[gene].kind].params[param];
430            genome[gene].params[param] = spec.sample(rng);
431        }
432    }
433}
434
435/// Changes one parameter of one gene by a small amount (GLEAM "parameter shift").
436///
437/// The step is `±width · 10^(-3u)` with `u ~ U(0, 1)`: log-uniform between the whole range
438/// and a thousandth of it, so small changes are as likely per decade as large ones (a
439/// reconstruction of GLEAM's ten change classes, which the guide does not spell out). Integer
440/// parameters move by at least one; the result is clamped to the bounds.
441#[derive(Debug, Clone, PartialEq)]
442pub struct ParamShift {
443    /// The action model holding the parameter bounds.
444    pub model: ActionModel,
445}
446
447impl Mutation<Vec<Action>> for ParamShift {
448    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Action>, rng: &mut R) {
449        let Some((gene, param)) = random_parameter(genome, rng) else {
450            return;
451        };
452
453        let spec = self.model.kinds[genome[gene].kind].params[param];
454        let mut step = (spec.high - spec.low) * libm::pow(10.0, -3.0 * unit_f64(rng));
455        if spec.integer {
456            step = step.max(1.0);
457        }
458
459        let sign = if rng.next_u32() & 1 == 0 { -1.0 } else { 1.0 };
460        let value = &mut genome[gene].params[param];
461        *value = spec.fit(*value + sign * step);
462    }
463}
464
465/// Gives every parameter of one gene new uniform values (GLEAM "action new parameters").
466#[derive(Debug, Clone, PartialEq)]
467pub struct ActionNewParams {
468    /// The action model holding the parameter bounds.
469    pub model: ActionModel,
470}
471
472impl Mutation<Vec<Action>> for ActionNewParams {
473    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<Action>, rng: &mut R) {
474        if !genome.is_empty() {
475            let gene = below(rng, genome.len());
476            genome[gene].params = self.model.sample_params(genome[gene].kind, rng);
477        }
478    }
479}
480
481/// Cut-and-splice crossover: independent cut points in each parent, tails exchanged. Children
482/// lengths vary, which lets chain length evolve.
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub struct CutAndSplice {
485    /// Children longer than this are truncated.
486    pub max_len: usize,
487}
488
489impl<T: Clone> Crossover<Vec<T>> for CutAndSplice {
490    fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
491        let cut_a = below(rng, a.len() + 1);
492        let cut_b = below(rng, b.len() + 1);
493        let mut c1 = splice(a, b, cut_a, cut_b);
494        let mut c2 = splice(b, a, cut_b, cut_a);
495        c1.truncate(self.max_len);
496        c2.truncate(self.max_len);
497
498        [c1, c2]
499    }
500}
501
502/// GLEAM n-point crossover on chains of different lengths: `points` cut fractions are drawn
503/// once and mapped to each parent's length, and the children alternate parents segment by
504/// segment, so corresponding regions of the parents are exchanged.
505#[derive(Debug, Clone, Copy, PartialEq, Eq)]
506pub struct NPoint {
507    /// The number of cut points, at least `1`.
508    pub points: usize,
509}
510
511impl<T: Clone> Crossover<Vec<T>> for NPoint {
512    fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
513        let mut fractions: Vec<f64> = (0..self.points.max(1)).map(|_| unit_f64(rng)).collect();
514        fractions.sort_by(f64::total_cmp);
515        let cuts_a = scaled_cuts(&fractions, a.len());
516        let cuts_b = scaled_cuts(&fractions, b.len());
517
518        [
519            alternate(a, b, &cuts_a, &cuts_b),
520            alternate(b, a, &cuts_b, &cuts_a),
521        ]
522    }
523}
524
525/// Maps sorted fractions to cut positions `0..=len`, keeping the sentinels `0` and `len`.
526fn scaled_cuts(fractions: &[f64], len: usize) -> Vec<usize> {
527    let mut cuts = Vec::with_capacity(fractions.len() + 2);
528    cuts.push(0);
529    #[expect(
530        clippy::cast_possible_truncation,
531        clippy::cast_sign_loss,
532        clippy::cast_precision_loss,
533        reason = "a fraction in [0, 1) of a chain length"
534    )]
535    cuts.extend(
536        fractions
537            .iter()
538            .map(|f| libm::round(f * len as f64) as usize),
539    );
540    cuts.push(len);
541
542    cuts
543}
544
545/// Concatenates segment `k` of `first` for even `k` and of `second` for odd `k`.
546fn alternate<T: Clone>(
547    first: &[T],
548    second: &[T],
549    cuts_first: &[usize],
550    cuts_second: &[usize],
551) -> Vec<T> {
552    let mut child = Vec::with_capacity(first.len().max(second.len()));
553    for k in 0..cuts_first.len() - 1 {
554        if k % 2 == 0 {
555            child.extend_from_slice(&first[cuts_first[k]..cuts_first[k + 1]]);
556        } else {
557            child.extend_from_slice(&second[cuts_second[k]..cuts_second[k + 1]]);
558        }
559    }
560
561    child
562}
563
564/// Exchanges one random segment of each parent; the segments may differ in length and
565/// position (GLEAM segment recombination).
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567pub struct SegmentExchange {
568    /// Children longer than this are truncated.
569    pub max_len: usize,
570}
571
572impl<T: Clone> Crossover<Vec<T>> for SegmentExchange {
573    fn crossover<R: Rng + ?Sized>(&mut self, a: &Vec<T>, b: &Vec<T>, rng: &mut R) -> [Vec<T>; 2] {
574        if a.is_empty() || b.is_empty() {
575            return [a.clone(), b.clone()];
576        }
577
578        let (ia, ja) = segment(rng, a.len(), None);
579        let (ib, jb) = segment(rng, b.len(), None);
580        let build = |x: &[T], (i, j): (usize, usize), y: &[T], (k, l): (usize, usize)| {
581            let mut child = Vec::with_capacity(x.len() - (j - i) + (l - k));
582            child.extend_from_slice(&x[..i]);
583            child.extend_from_slice(&y[k..l]);
584            child.extend_from_slice(&x[j..]);
585            child.truncate(self.max_len);
586            child
587        };
588
589        [
590            build(a, (ia, ja), b, (ib, jb)),
591            build(b, (ib, jb), a, (ia, ja)),
592        ]
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use alloc::vec;
599
600    use proptest::prelude::*;
601
602    use super::*;
603    use crate::SplitMix64;
604
605    /// A model with a real, an integer and a parameterless action.
606    fn model() -> ActionModel {
607        ActionModel::new(vec![
608            ActionKind::new(vec![
609                ParamSpec::real(-1.0, 1.0),
610                ParamSpec::integer(0.0, 5.0),
611            ]),
612            ActionKind::new(vec![ParamSpec::integer(-3.0, 3.0)]),
613            ActionKind::new(vec![]),
614        ])
615    }
616
617    proptest! {
618        /// Gene-level mutations keep every action valid; chain mutations respect length limits.
619        #[test]
620        fn chain_operators_keep_validity(seed in any::<u64>()) {
621            let mut rng = SplitMix64::new(seed);
622            let m = model();
623            let mut init = RandomChain { genes: m.clone(), min_len: 1, max_len: 8 };
624            let mut chain = init.initialize(&mut rng);
625            let mut ops = mix(
626                mix(ParamShift { model: m.clone() }, 1.0, ParamNewValue { model: m.clone() }, 1.0),
627                1.0,
628                mix(
629                    mix(InsertSegment { genes: m.clone(), max_segment: 3, max_len: 12 }, 1.0, DeleteSegment { min_len: 1, max_segment: Some(3) }, 1.0),
630                    1.0,
631                    mix(SegmentShift::default(), 1.0, mix(DuplicateGene { max_len: 12 }, 1.0, ActionNewParams { model: m.clone() }, 1.0), 1.0),
632                    1.0,
633                ),
634                1.0,
635            );
636            for _ in 0..50 {
637                ops.mutate(&mut chain, &mut rng);
638                prop_assert!((1..=12).contains(&chain.len()));
639                prop_assert!(chain.iter().all(|a| m.is_valid(a)));
640            }
641        }
642
643        /// Crossovers only rearrange the parents' genes.
644        #[test]
645        fn crossovers_reuse_parent_genes(seed in any::<u64>(), la in 0u32..10, lb in 0u32..10) {
646            let mut rng = SplitMix64::new(seed);
647            let a: Vec<u32> = (0..la).collect();
648            let b: Vec<u32> = (100..100 + lb).collect();
649            for [c1, c2] in [
650                CutAndSplice { max_len: 100 }.crossover(&a, &b, &mut rng),
651                NPoint { points: 3 }.crossover(&a, &b, &mut rng),
652                SegmentExchange { max_len: 100 }.crossover(&a, &b, &mut rng),
653            ] {
654                let mut all: Vec<u32> = c1.iter().chain(&c2).copied().collect();
655                all.sort_unstable();
656                let mut parents: Vec<u32> = a.iter().chain(&b).copied().collect();
657                parents.sort_unstable();
658                prop_assert_eq!(all, parents);
659            }
660        }
661    }
662
663    use crate::operators::mix;
664
665    /// Segment shift keeps the multiset of genes.
666    #[test]
667    fn segment_shift_permutes() {
668        let mut rng = SplitMix64::new(4);
669        let mut chain: Vec<u32> = (0..20).collect();
670        for _ in 0..100 {
671            SegmentShift {
672                max_segment: Some(5),
673            }
674            .mutate(&mut chain, &mut rng);
675            SegmentInversion::default().mutate(&mut chain, &mut rng);
676        }
677
678        let mut sorted = chain.clone();
679        sorted.sort_unstable();
680        assert_eq!(sorted, (0..20).collect::<Vec<_>>());
681    }
682}