Skip to main content

evolutionary_planning/operators/
real.rs

1//! Operators for real vectors `Vec<f64>`: box [`Bounds`], uniform and Latin hypercube
2//! initialisation, Gaussian, polynomial and uniform-reset mutation, SBX, BLX-α and arithmetic
3//! crossover, and clamping or reflecting repair.
4//!
5//! Following Jakob's rule that explicit bounds belong in the operators, every bounded operator
6//! keeps its children inside the box; Gaussian mutation is unbounded and pairs with
7//! [`Clamp`] or [`Reflect`].
8
9use alloc::vec::Vec;
10
11use rand_core::Rng;
12
13use super::{Crossover, Initializer, Mutation, Repair};
14use crate::rng::{below, chance, shuffle, standard_normal, uniform, unit_f64};
15
16/// An axis-aligned box `[lower_i, upper_i]` per coordinate.
17///
18/// ```
19/// use evolutionary_planning::operators::{Initializer, real::Bounds};
20/// use evolutionary_planning::SplitMix64;
21///
22/// let bounds = Bounds::uniform(3, -5.0, 5.0);
23/// let x = bounds.clone().initialize(&mut SplitMix64::new(1));
24/// assert!(bounds.contains(&x));
25/// ```
26#[derive(Debug, Clone, PartialEq)]
27pub struct Bounds {
28    /// Lower bounds, one per coordinate; finite, `lower[i] <= upper[i]`.
29    lower: Vec<f64>,
30    /// Upper bounds, one per coordinate; finite.
31    upper: Vec<f64>,
32}
33
34impl Bounds {
35    /// Creates a box from per-coordinate bounds.
36    ///
37    /// # Panics
38    ///
39    /// Panics if the lengths differ, a bound is not finite, or `lower[i] > upper[i]`.
40    #[must_use]
41    pub fn new(lower: Vec<f64>, upper: Vec<f64>) -> Self {
42        assert_eq!(lower.len(), upper.len(), "bounds of different dimension");
43        for (lo, hi) in lower.iter().zip(&upper) {
44            assert!(
45                lo.is_finite() && hi.is_finite() && lo <= hi,
46                "invalid bound [{lo}, {hi}]"
47            );
48        }
49
50        Self { lower, upper }
51    }
52
53    /// The box `[low, high]^dimension`.
54    ///
55    /// # Panics
56    ///
57    /// Panics if `low > high` or either is not finite.
58    #[must_use]
59    pub fn uniform(dimension: usize, low: f64, high: f64) -> Self {
60        Self::new(alloc::vec![low; dimension], alloc::vec![high; dimension])
61    }
62
63    /// The number of coordinates.
64    #[must_use]
65    pub fn dimension(&self) -> usize {
66        self.lower.len()
67    }
68
69    /// The lower bounds.
70    #[must_use]
71    pub fn lower(&self) -> &[f64] {
72        &self.lower
73    }
74
75    /// The upper bounds.
76    #[must_use]
77    pub fn upper(&self) -> &[f64] {
78        &self.upper
79    }
80
81    /// The width `upper[i] - lower[i]` of coordinate `i`.
82    #[must_use]
83    pub fn width(&self, i: usize) -> f64 {
84        self.upper[i] - self.lower[i]
85    }
86
87    /// Returns `true` if `x` has the right dimension and lies inside the box.
88    #[must_use]
89    pub fn contains(&self, x: &[f64]) -> bool {
90        x.len() == self.dimension()
91            && x.iter()
92                .enumerate()
93                .all(|(i, v)| (self.lower[i]..=self.upper[i]).contains(v))
94    }
95
96    /// Clamps `x` into the box coordinate by coordinate.
97    pub fn clamp(&self, x: &mut [f64]) {
98        for (i, v) in x.iter_mut().enumerate() {
99            *v = v.clamp(self.lower[i], self.upper[i]);
100        }
101    }
102
103    /// The centre of the box.
104    #[must_use]
105    pub fn center(&self) -> Vec<f64> {
106        self.lower
107            .iter()
108            .zip(&self.upper)
109            .map(|(lo, hi)| 0.5 * (lo + hi))
110            .collect()
111    }
112}
113
114/// Uniform random points in the box.
115impl Initializer<Vec<f64>> for Bounds {
116    fn initialize<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Vec<f64> {
117        (0..self.dimension())
118            .map(|i| uniform(rng, self.lower[i], self.upper[i]))
119            .collect()
120    }
121}
122
123/// Returns `count` points of a Latin hypercube sample of `bounds`: every coordinate's range is
124/// split into `count` equal strata, each stratum holds exactly one point per coordinate, and
125/// the strata are permuted independently per coordinate (McKay, Beckman and Conover 1979).
126///
127/// Yue et al. (2023) initialise DE this way for more uniform coverage with few points.
128///
129/// ```
130/// use evolutionary_planning::operators::real::{Bounds, latin_hypercube};
131/// use evolutionary_planning::SplitMix64;
132///
133/// let points = latin_hypercube(&Bounds::uniform(2, 0.0, 1.0), 4, &mut SplitMix64::new(1));
134/// let mut strata: Vec<usize> = points.iter().map(|p| (p[0] * 4.0) as usize).collect();
135/// strata.sort();
136/// assert_eq!(strata, [0, 1, 2, 3]);
137/// ```
138pub fn latin_hypercube<R: Rng + ?Sized>(
139    bounds: &Bounds,
140    count: usize,
141    rng: &mut R,
142) -> Vec<Vec<f64>> {
143    let mut points = alloc::vec![alloc::vec![0.0; bounds.dimension()]; count];
144    let mut strata: Vec<usize> = (0..count).collect();
145    #[expect(
146        clippy::cast_precision_loss,
147        reason = "sample counts are far below 2^52"
148    )]
149    let n = count as f64;
150    for i in 0..bounds.dimension() {
151        shuffle(rng, &mut strata);
152        for (point, &stratum) in points.iter_mut().zip(&strata) {
153            #[expect(
154                clippy::cast_precision_loss,
155                reason = "sample counts are far below 2^52"
156            )]
157            let offset = (stratum as f64 + unit_f64(rng)) / n;
158            point[i] = (bounds.lower[i] + offset * bounds.width(i)).min(bounds.upper[i]);
159        }
160    }
161
162    points
163}
164
165/// Returns the per-gene mutation probability: `rate`, or `1 / n` if `None`.
166fn gene_rate(rate: Option<f64>, n: usize) -> f64 {
167    #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
168    let default = 1.0 / n.max(1) as f64;
169
170    rate.unwrap_or(default)
171}
172
173/// Adds `N(0, sigma^2)` to each coordinate with probability `rate` (default `1/n`); at least
174/// one coordinate changes. Unbounded; combine with [`Clamp`] or [`Reflect`] if needed.
175#[derive(Debug, Clone, Copy, PartialEq)]
176pub struct Gaussian {
177    /// The standard deviation, in the units of the coordinates.
178    pub sigma: f64,
179    /// The per-coordinate probability; `None` means `1/n`.
180    pub rate: Option<f64>,
181}
182
183impl Mutation<Vec<f64>> for Gaussian {
184    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, rng: &mut R) {
185        let rate = gene_rate(self.rate, genome.len());
186        for_some_genes(genome.len(), rate, rng, |i, rng| {
187            genome[i] += self.sigma * standard_normal(rng);
188        });
189    }
190}
191
192/// Calls `f` for each index with probability `rate`, and for one uniform index if no other was
193/// chosen, so a mutation never silently returns its input unchanged.
194fn for_some_genes<R: Rng + ?Sized>(
195    n: usize,
196    rate: f64,
197    rng: &mut R,
198    mut f: impl FnMut(usize, &mut R),
199) {
200    if n == 0 {
201        return;
202    }
203
204    let mut any = false;
205    for i in 0..n {
206        if chance(rng, rate) {
207            f(i, rng);
208            any = true;
209        }
210    }
211
212    if !any {
213        let i = below(rng, n);
214        f(i, rng);
215    }
216}
217
218/// Deb's bounded polynomial mutation with distribution index `eta` (Deb and Goyal 1996, in
219/// the form of the NSGA-II reference code); each coordinate mutates with probability `rate`
220/// (default `1/n`), at least one does.
221#[derive(Debug, Clone, PartialEq)]
222pub struct Polynomial {
223    /// The box the children stay in.
224    pub bounds: Bounds,
225    /// The distribution index; larger values give smaller steps. `20` is customary.
226    pub eta: f64,
227    /// The per-coordinate probability; `None` means `1/n`.
228    pub rate: Option<f64>,
229}
230
231impl Mutation<Vec<f64>> for Polynomial {
232    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, rng: &mut R) {
233        let rate = gene_rate(self.rate, genome.len());
234        let bounds = &self.bounds;
235        let eta = self.eta;
236        for_some_genes(genome.len(), rate, rng, |i, rng| {
237            genome[i] = polynomial_step(
238                genome[i],
239                bounds.lower[i],
240                bounds.upper[i],
241                eta,
242                unit_f64(rng),
243            );
244        });
245    }
246}
247
248/// One polynomial-mutation step of `y` in `[low, high]` for the uniform draw `u`.
249fn polynomial_step(y: f64, low: f64, high: f64, eta: f64, u: f64) -> f64 {
250    let width = high - low;
251    if width <= 0.0 {
252        return low;
253    }
254
255    let power = 1.0 / (eta + 1.0);
256    let delta_q = if u <= 0.5 {
257        let xy = 1.0 - (y - low) / width;
258        let value = 2.0 * u + (1.0 - 2.0 * u) * libm::pow(xy, eta + 1.0);
259        libm::pow(value, power) - 1.0
260    } else {
261        let xy = 1.0 - (high - y) / width;
262        let value = 2.0 * (1.0 - u) + 2.0 * (u - 0.5) * libm::pow(xy, eta + 1.0);
263        1.0 - libm::pow(value, power)
264    };
265
266    (y + delta_q * width).clamp(low, high)
267}
268
269/// Replaces each coordinate with probability `rate` (default `1/n`) by a uniform value in its
270/// bounds; at least one coordinate changes.
271#[derive(Debug, Clone, PartialEq)]
272pub struct UniformReset {
273    /// The box new values are drawn from.
274    pub bounds: Bounds,
275    /// The per-coordinate probability; `None` means `1/n`.
276    pub rate: Option<f64>,
277}
278
279impl Mutation<Vec<f64>> for UniformReset {
280    fn mutate<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, rng: &mut R) {
281        let rate = gene_rate(self.rate, genome.len());
282        let bounds = &self.bounds;
283        for_some_genes(genome.len(), rate, rng, |i, rng| {
284            genome[i] = uniform(rng, bounds.lower[i], bounds.upper[i]);
285        });
286    }
287}
288
289/// Simulated binary crossover (Deb and Agrawal 1995), bounded form of the NSGA-II reference
290/// code: each coordinate is recombined with probability `1/2`, the children's spread follows
291/// the distribution index `eta`, and the children are swapped per coordinate with probability
292/// `1/2`.
293#[derive(Debug, Clone, PartialEq)]
294pub struct Sbx {
295    /// The box the children stay in.
296    pub bounds: Bounds,
297    /// The distribution index; larger values keep children closer to the parents. `15`–`20`
298    /// is customary.
299    pub eta: f64,
300}
301
302impl Crossover<Vec<f64>> for Sbx {
303    fn crossover<R: Rng + ?Sized>(
304        &mut self,
305        a: &Vec<f64>,
306        b: &Vec<f64>,
307        rng: &mut R,
308    ) -> [Vec<f64>; 2] {
309        let mut c1 = a.clone();
310        let mut c2 = b.clone();
311        for i in 0..a.len().min(b.len()) {
312            if unit_f64(rng) > 0.5 || (a[i] - b[i]).abs() <= 1e-14 {
313                continue;
314            }
315
316            let (low, high) = (self.bounds.lower[i], self.bounds.upper[i]);
317            let (y1, y2) = if a[i] < b[i] {
318                (a[i], b[i])
319            } else {
320                (b[i], a[i])
321            };
322            let u = unit_f64(rng);
323            let lower_child = sbx_child(
324                y1,
325                y2,
326                1.0 + 2.0 * (y1 - low) / (y2 - y1),
327                self.eta,
328                u,
329                -1.0,
330            );
331            let upper_child = sbx_child(
332                y1,
333                y2,
334                1.0 + 2.0 * (high - y2) / (y2 - y1),
335                self.eta,
336                u,
337                1.0,
338            );
339            let (x1, x2) = (lower_child.clamp(low, high), upper_child.clamp(low, high));
340            if unit_f64(rng) < 0.5 {
341                c1[i] = x2;
342                c2[i] = x1;
343            } else {
344                c1[i] = x1;
345                c2[i] = x2;
346            }
347        }
348
349        [c1, c2]
350    }
351}
352
353/// One SBX child of the sorted parents `y1 < y2` given the bound ratio `beta`, the uniform draw
354/// `u`, and `sign` (`-1` towards the lower bound, `+1` towards the upper).
355fn sbx_child(y1: f64, y2: f64, beta: f64, eta: f64, u: f64, sign: f64) -> f64 {
356    let alpha = 2.0 - libm::pow(beta, -(eta + 1.0));
357    let beta_q = if u <= 1.0 / alpha {
358        libm::pow(u * alpha, 1.0 / (eta + 1.0))
359    } else {
360        libm::pow(1.0 / (2.0 - u * alpha), 1.0 / (eta + 1.0))
361    };
362
363    0.5 * ((y1 + y2) + sign * beta_q * (y2 - y1))
364}
365
366/// Blend crossover BLX-α (Eshelman and Schaffer 1993): each child coordinate is uniform in
367/// the parents' interval widened by `alpha` times its length on both sides, clamped to the
368/// bounds.
369#[derive(Debug, Clone, PartialEq)]
370pub struct Blx {
371    /// The box the children stay in.
372    pub bounds: Bounds,
373    /// The widening factor; `0.5` is customary.
374    pub alpha: f64,
375}
376
377impl Crossover<Vec<f64>> for Blx {
378    fn crossover<R: Rng + ?Sized>(
379        &mut self,
380        a: &Vec<f64>,
381        b: &Vec<f64>,
382        rng: &mut R,
383    ) -> [Vec<f64>; 2] {
384        let mut children = [a.clone(), b.clone()];
385        for child in &mut children {
386            for i in 0..a.len().min(b.len()) {
387                let (lo, hi) = (a[i].min(b[i]), a[i].max(b[i]));
388                let spread = self.alpha * (hi - lo);
389                let value = uniform(rng, lo - spread, hi + spread);
390                child[i] = value.clamp(self.bounds.lower[i], self.bounds.upper[i]);
391            }
392        }
393
394        children
395    }
396}
397
398/// Whole arithmetic crossover: `λa + (1-λ)b` and `(1-λ)a + λb` with one uniform `λ`. Children
399/// stay in the parents' bounding box, hence in any convex feasible set containing both.
400#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
401pub struct Arithmetic;
402
403impl Crossover<Vec<f64>> for Arithmetic {
404    fn crossover<R: Rng + ?Sized>(
405        &mut self,
406        a: &Vec<f64>,
407        b: &Vec<f64>,
408        rng: &mut R,
409    ) -> [Vec<f64>; 2] {
410        let lambda = unit_f64(rng);
411        let blend = |x: f64, y: f64, l: f64| l * x + (1.0 - l) * y;
412
413        [
414            a.iter()
415                .zip(b)
416                .map(|(&x, &y)| blend(x, y, lambda))
417                .collect(),
418            a.iter()
419                .zip(b)
420                .map(|(&x, &y)| blend(x, y, 1.0 - lambda))
421                .collect(),
422        ]
423    }
424}
425
426/// Iso+line variation (Vassiliades and Mouret 2018), the directional crossover of
427/// MAP-Elites: `a + σ_iso N(0, I) + σ_line N(0, 1) (b - a)`, and symmetrically for the second
428/// child. Unbounded; combine with [`Clamp`] or [`Reflect`].
429#[derive(Debug, Clone, Copy, PartialEq)]
430pub struct IsoLineDd {
431    /// The isotropic Gaussian spread `σ_iso`.
432    pub sigma_iso: f64,
433    /// The spread `σ_line` along the line between the parents.
434    pub sigma_line: f64,
435}
436
437impl Crossover<Vec<f64>> for IsoLineDd {
438    fn crossover<R: Rng + ?Sized>(
439        &mut self,
440        a: &Vec<f64>,
441        b: &Vec<f64>,
442        rng: &mut R,
443    ) -> [Vec<f64>; 2] {
444        let child = |x: &[f64], y: &[f64], rng: &mut R| {
445            let line = self.sigma_line * standard_normal(rng);
446            x.iter()
447                .zip(y)
448                .map(|(p, q)| p + self.sigma_iso * standard_normal(rng) + line * (q - p))
449                .collect()
450        };
451
452        [child(a, b, rng), child(b, a, rng)]
453    }
454}
455
456/// Clamps every coordinate into the bounds.
457#[derive(Debug, Clone, PartialEq)]
458pub struct Clamp(pub Bounds);
459
460impl Repair<Vec<f64>> for Clamp {
461    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, _rng: &mut R) {
462        self.0.clamp(genome);
463    }
464}
465
466/// Reflects coordinates that left the box back in at the violated bound (mirror boundary),
467/// which, unlike clamping, does not pile up probability mass on the boundary.
468#[derive(Debug, Clone, PartialEq)]
469pub struct Reflect(pub Bounds);
470
471impl Repair<Vec<f64>> for Reflect {
472    fn repair<R: Rng + ?Sized>(&mut self, genome: &mut Vec<f64>, _rng: &mut R) {
473        for (i, value) in genome.iter_mut().enumerate() {
474            *value = reflect(*value, self.0.lower[i], self.0.upper[i]);
475        }
476    }
477}
478
479/// Folds `x` into `[low, high]` by repeated mirroring at the bounds.
480fn reflect(x: f64, low: f64, high: f64) -> f64 {
481    let width = high - low;
482    if width <= 0.0 || !x.is_finite() {
483        return x.clamp(low, high);
484    }
485
486    let period = 2.0 * width;
487    let mut offset = (x - low) % period;
488    if offset < 0.0 {
489        offset += period;
490    }
491
492    if offset <= width {
493        low + offset
494    } else {
495        high - (offset - width)
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use alloc::vec;
502
503    use super::*;
504    use crate::SplitMix64;
505
506    /// Bounded operators keep their children in the box.
507    #[test]
508    fn bounded_operators_stay_inside() {
509        let bounds = Bounds::uniform(5, -1.0, 2.0);
510        let mut rng = SplitMix64::new(7);
511        let mut init = bounds.clone();
512        let mut sbx = Sbx {
513            bounds: bounds.clone(),
514            eta: 15.0,
515        };
516        let mut blx = Blx {
517            bounds: bounds.clone(),
518            alpha: 0.5,
519        };
520        let mut poly = Polynomial {
521            bounds: bounds.clone(),
522            eta: 20.0,
523            rate: Some(1.0),
524        };
525        for _ in 0..500 {
526            let a = init.initialize(&mut rng);
527            let b = init.initialize(&mut rng);
528            for mut child in sbx
529                .crossover(&a, &b, &mut rng)
530                .into_iter()
531                .chain(blx.crossover(&a, &b, &mut rng))
532            {
533                assert!(bounds.contains(&child), "{child:?}");
534                poly.mutate(&mut child, &mut rng);
535                assert!(bounds.contains(&child), "{child:?}");
536            }
537        }
538    }
539
540    /// Reflection folds values back and is the identity inside.
541    #[test]
542    fn reflection_folds() {
543        assert!((reflect(2.5, 0.0, 2.0) - 1.5).abs() < 1e-12);
544        assert!((reflect(-0.5, 0.0, 2.0) - 0.5).abs() < 1e-12);
545        assert!((reflect(5.0, 0.0, 2.0) - 1.0).abs() < 1e-12);
546        assert!((reflect(1.25, 0.0, 2.0) - 1.25).abs() < 1e-12);
547    }
548
549    /// Identical SBX parents give identical children.
550    #[test]
551    fn sbx_of_equal_parents_is_identity() {
552        let mut sbx = Sbx {
553            bounds: Bounds::uniform(3, 0.0, 1.0),
554            eta: 15.0,
555        };
556        let p = vec![0.2, 0.5, 0.9];
557
558        assert_eq!(
559            sbx.crossover(&p, &p, &mut SplitMix64::new(1)),
560            [p.clone(), p]
561        );
562    }
563
564    /// Latin hypercube samples hit every stratum of every coordinate exactly once.
565    #[test]
566    fn latin_hypercube_stratifies() {
567        let bounds = Bounds::uniform(3, -2.0, 2.0);
568        let points = latin_hypercube(&bounds, 10, &mut SplitMix64::new(3));
569        for i in 0..3 {
570            let mut strata: Vec<usize> = points
571                .iter()
572                .map(|p| {
573                    #[expect(
574                        clippy::cast_possible_truncation,
575                        clippy::cast_sign_loss,
576                        reason = "test"
577                    )]
578                    let s = ((p[i] + 2.0) / 4.0 * 10.0) as usize;
579                    s
580                })
581                .collect();
582            strata.sort_unstable();
583            assert_eq!(strata, (0..10).collect::<Vec<_>>());
584        }
585    }
586}