Skip to main content

evolutionary_planning/
memetic.rs

1//! Memetic search: local searchers applied to offspring, with HyGLEAM's cost-benefit
2//! adaptation of how often and how long they run (Jakob 2021, section 5; Jakob, Blume and
3//! Bretthauer 2004).
4//!
5//! A [`Memetic`] hybrid plugs into [`Ga::run_memetic`](crate::ga::Ga::run_memetic) and
6//! [`Diffusion::run_memetic`](crate::diffusion::Diffusion::run_memetic). It answers the five
7//! design questions Jakob lists:
8//!
9//! 1. which local searcher: any [`LocalSearch`] ([`HillClimb`] for any genome,
10//!    [`Rosenbrock`] for real vectors);
11//! 2. whether to write the result back: Lamarckian or Baldwinian ([`Memetic::lamarckian`]);
12//! 3. and 4. which offspring, how often: each child with a probability (the frequency);
13//! 5. how long: an evaluation cap per local search (the intensity).
14//!
15//! Frequency and intensity are either fixed ([`Schedule::Fixed`]) or adapted
16//! ([`Schedule::Adaptive`]): each is a discrete set of levels with probabilities that move
17//! towards the levels that yielded the most relative improvement per evaluation.
18//!
19//! ```
20//! use evolutionary_planning::ga::{Config, Ga, Operators};
21//! use evolutionary_planning::memetic::{Memetic, Rosenbrock};
22//! use evolutionary_planning::operators::real::{Bounds, Polynomial, Sbx};
23//! use evolutionary_planning::operators::{NoRepair, selection::Tournament};
24//! use evolutionary_planning::problems::single::rosenbrock;
25//! use evolutionary_planning::{Limits, SplitMix64};
26//!
27//! let bounds = Bounds::uniform(4, -2.0, 2.0);
28//! let mut ga = Ga::new(Config { population_size: 10, ..Config::default() }, Operators {
29//!     init: bounds.clone(),
30//!     selection: Tournament { size: 2 },
31//!     crossover: Sbx { bounds: bounds.clone(), eta: 15.0 },
32//!     mutation: Polynomial { bounds, eta: 20.0, rate: None },
33//!     repair: NoRepair,
34//! });
35//! let mut memetic = Memetic::adaptive(Rosenbrock::default());
36//! let mut objective = |x: &Vec<f64>| rosenbrock(x);
37//! let outcome = ga.run_memetic(&mut memetic, &mut objective, &mut Limits::evaluations(20_000), &mut (), &mut SplitMix64::new(1));
38//! assert!(outcome.best_cost() < 1e-6);
39//! ```
40
41use alloc::vec::Vec;
42
43use rand_core::Rng;
44
45use crate::evaluator::Evaluator;
46use crate::ga::Refine;
47use crate::operators::Mutation;
48use crate::operators::selection::{Sampling, sample};
49use crate::rng::{chance, unit_f64};
50use crate::{Budget, Individual, Objective, Observer, Stats};
51
52/// Improves a genome with a bounded number of objective evaluations.
53pub trait LocalSearch<G> {
54    /// Returns the best individual found starting from `start`, spending at most
55    /// `max_evaluations` calls of `evaluate`, which returns `None` once the global budget is
56    /// exhausted (stop then).
57    fn improve<E, R>(
58        &mut self,
59        start: Individual<G>,
60        max_evaluations: u64,
61        evaluate: &mut E,
62        rng: &mut R,
63    ) -> Individual<G>
64    where
65        G: Clone,
66        E: FnMut(&G) -> Option<f64>,
67        R: Rng + ?Sized;
68}
69
70/// Random-mutation hill climbing as a local searcher for any genome: mutate, keep if not
71/// worse.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct HillClimb<M> {
74    /// The neighbourhood move.
75    pub mutation: M,
76}
77
78impl<G, M: Mutation<G>> LocalSearch<G> for HillClimb<M> {
79    fn improve<E, R>(
80        &mut self,
81        mut current: Individual<G>,
82        max_evaluations: u64,
83        evaluate: &mut E,
84        rng: &mut R,
85    ) -> Individual<G>
86    where
87        G: Clone,
88        E: FnMut(&G) -> Option<f64>,
89        R: Rng + ?Sized,
90    {
91        for _ in 0..max_evaluations {
92            let mut candidate = current.genome.clone();
93            self.mutation.mutate(&mut candidate, rng);
94            let Some(cost) = evaluate(&candidate) else {
95                break;
96            };
97
98            if cost <= current.cost {
99                current = Individual {
100                    genome: candidate,
101                    cost,
102                };
103            }
104        }
105
106        current
107    }
108}
109
110/// Rosenbrock's rotating-coordinates method (Rosenbrock 1960), HyGLEAM's local searcher for
111/// real parameters: probe along `n` orthonormal directions, growing a step by `alpha` on
112/// success and reversing and shrinking it by `beta` on failure; once every direction has had
113/// a success and a failure, rotate the directions towards the accumulated progress
114/// (Gram-Schmidt) and start over.
115#[derive(Debug, Clone, Copy, PartialEq)]
116pub struct Rosenbrock {
117    /// The initial step along every direction.
118    pub initial_step: f64,
119    /// The expansion factor on success; `3` is Rosenbrock's.
120    pub alpha: f64,
121    /// The contraction factor on failure; `0.5` is Rosenbrock's.
122    pub beta: f64,
123    /// Stop when every step is below this.
124    pub min_step: f64,
125}
126
127impl Default for Rosenbrock {
128    fn default() -> Self {
129        Self {
130            initial_step: 0.1,
131            alpha: 3.0,
132            beta: 0.5,
133            min_step: 1e-12,
134        }
135    }
136}
137
138impl LocalSearch<Vec<f64>> for Rosenbrock {
139    fn improve<E, R>(
140        &mut self,
141        mut current: Individual<Vec<f64>>,
142        max_evaluations: u64,
143        evaluate: &mut E,
144        _rng: &mut R,
145    ) -> Individual<Vec<f64>>
146    where
147        E: FnMut(&Vec<f64>) -> Option<f64>,
148        R: Rng + ?Sized,
149    {
150        let n = current.genome.len();
151        let mut directions: Vec<Vec<f64>> = (0..n).map(|i| unit(n, i)).collect();
152        let mut steps = alloc::vec![self.initial_step; n];
153        let mut progress = alloc::vec![0.0; n];
154        let mut succeeded = alloc::vec![false; n];
155        let mut failed = alloc::vec![false; n];
156        let mut used = 0;
157        while used < max_evaluations && steps.iter().any(|s| s.abs() >= self.min_step) {
158            for i in 0..n {
159                if used >= max_evaluations {
160                    break;
161                }
162
163                let candidate: Vec<f64> = current
164                    .genome
165                    .iter()
166                    .zip(&directions[i])
167                    .map(|(x, d)| x + steps[i] * d)
168                    .collect();
169                let Some(cost) = evaluate(&candidate) else {
170                    return current;
171                };
172                used += 1;
173                if cost <= current.cost {
174                    current = Individual {
175                        genome: candidate,
176                        cost,
177                    };
178                    progress[i] += steps[i];
179                    steps[i] *= self.alpha;
180                    succeeded[i] = true;
181                } else {
182                    steps[i] *= -self.beta;
183                    failed[i] = true;
184                }
185            }
186
187            if succeeded.iter().zip(&failed).all(|(s, f)| *s && *f) {
188                directions = rotate(&directions, &progress);
189                progress.fill(0.0);
190                succeeded.fill(false);
191                failed.fill(false);
192                steps.fill(self.initial_step);
193            }
194        }
195
196        current
197    }
198}
199
200/// The `i`-th unit vector of dimension `n`.
201fn unit(n: usize, i: usize) -> Vec<f64> {
202    let mut v = alloc::vec![0.0; n];
203    v[i] = 1.0;
204
205    v
206}
207
208/// Rosenbrock's rotation: `a_i = Σ_{j ≥ i} λ_j d_j`, orthonormalised by Gram-Schmidt; a
209/// direction whose `a_i` collapses keeps its old vector (re-orthonormalised).
210fn rotate(directions: &[Vec<f64>], progress: &[f64]) -> Vec<Vec<f64>> {
211    let n = directions.len();
212    let mut basis: Vec<Vec<f64>> = Vec::with_capacity(n);
213    for i in 0..n {
214        let mut a = alloc::vec![0.0; n];
215        for j in i..n {
216            for (ak, dk) in a.iter_mut().zip(&directions[j]) {
217                *ak += progress[j] * dk;
218            }
219        }
220
221        let mut v = orthogonalised(&a, &basis);
222        if norm(&v) < 1e-12 {
223            v = orthogonalised(&directions[i], &basis);
224        }
225
226        let length = norm(&v);
227        basis.push(if length > 1e-12 {
228            v.iter().map(|x| x / length).collect()
229        } else {
230            directions[i].clone()
231        });
232    }
233
234    basis
235}
236
237/// `a` minus its projections on the orthonormal vectors of `basis`.
238fn orthogonalised(a: &[f64], basis: &[Vec<f64>]) -> Vec<f64> {
239    let mut v = a.to_vec();
240    for b in basis {
241        let dot: f64 = v.iter().zip(b).map(|(x, y)| x * y).sum();
242        v.iter_mut().zip(b).for_each(|(x, y)| *x -= dot * y);
243    }
244
245    v
246}
247
248/// The Euclidean norm.
249fn norm(v: &[f64]) -> f64 {
250    libm::sqrt(v.iter().map(|x| x * x).sum())
251}
252
253/// A discrete set of parameter levels with adapted probabilities.
254#[derive(Debug, Clone, PartialEq)]
255pub struct Levels<T> {
256    /// The level values (evaluation caps or frequencies).
257    pub values: Vec<T>,
258    /// The probability of each level; sums to one.
259    probabilities: Vec<f64>,
260    /// The accumulated benefit (relative gain per evaluation) per level since the last
261    /// adaptation.
262    benefit: Vec<f64>,
263    /// The number of uses per level since the last adaptation.
264    uses: Vec<u64>,
265}
266
267impl<T: Copy> Levels<T> {
268    /// Levels with equal initial probabilities.
269    ///
270    /// # Panics
271    ///
272    /// Panics if `values` is empty.
273    #[must_use]
274    pub fn new(values: Vec<T>) -> Self {
275        assert!(!values.is_empty(), "at least one level");
276        let k = values.len();
277        #[expect(clippy::cast_precision_loss, reason = "level counts are tiny")]
278        let p = 1.0 / k as f64;
279
280        Self {
281            values,
282            probabilities: alloc::vec![p; k],
283            benefit: alloc::vec![0.0; k],
284            uses: alloc::vec![0; k],
285        }
286    }
287
288    /// The current probabilities.
289    #[must_use]
290    pub fn probabilities(&self) -> &[f64] {
291        &self.probabilities
292    }
293
294    /// Draws a level index.
295    fn draw<R: Rng + ?Sized>(&self, rng: &mut R) -> usize {
296        let mut out = Vec::with_capacity(1);
297        sample(&self.probabilities, 1, Sampling::Roulette, rng, &mut out);
298
299        out[0]
300    }
301
302    /// Records a use of `level` with `benefit`, and adapts once every level with positive
303    /// probability has been used `window` times in total across levels.
304    fn record(&mut self, level: usize, benefit: f64, window: u64, floor: f64) {
305        self.benefit[level] += benefit;
306        self.uses[level] += 1;
307        if self.uses.iter().sum::<u64>() < window {
308            return;
309        }
310
311        // Only levels used in this window carry evidence: they share their combined
312        // probability mass in proportion to their mean benefit; unused levels keep theirs.
313        #[expect(clippy::cast_precision_loss, reason = "use counts are small")]
314        let mean: Vec<f64> = self
315            .benefit
316            .iter()
317            .zip(&self.uses)
318            .map(|(b, &u)| if u == 0 { 0.0 } else { b / u as f64 })
319            .collect();
320        let used_mass: f64 = self
321            .probabilities
322            .iter()
323            .zip(&self.uses)
324            .filter(|(_, u)| **u > 0)
325            .map(|(p, _)| p)
326            .sum();
327        let used_benefit: f64 = mean
328            .iter()
329            .zip(&self.uses)
330            .filter(|(_, u)| **u > 0)
331            .map(|(m, _)| m)
332            .sum();
333        if used_benefit > 0.0 {
334            // Half old, half new, so one noisy window cannot swing the distribution.
335            for ((p, m), &u) in self.probabilities.iter_mut().zip(&mean).zip(&self.uses) {
336                if u > 0 {
337                    *p = 0.5 * *p + 0.5 * used_mass * m / used_benefit;
338                }
339            }
340        }
341
342        let k = self.probabilities.len();
343        #[expect(clippy::cast_precision_loss, reason = "level counts are tiny")]
344        let minimum = floor / k as f64;
345        for p in &mut self.probabilities {
346            *p = p.max(minimum);
347        }
348
349        let sum: f64 = self.probabilities.iter().sum();
350        self.probabilities.iter_mut().for_each(|p| *p /= sum);
351        self.benefit.fill(0.0);
352        self.uses.fill(0);
353    }
354}
355
356/// How often and how long local search runs.
357#[derive(Debug, Clone, PartialEq)]
358pub enum Schedule {
359    /// Each child is improved with `probability`, with at most `evaluations` evaluations.
360    Fixed {
361        /// The probability of improving a child.
362        probability: f64,
363        /// The evaluation cap per local search.
364        evaluations: u64,
365    },
366    /// HyGLEAM-style cost-benefit adaptation of both.
367    Adaptive(Adaptive),
368}
369
370/// The adaptive schedule: frequency and intensity levels whose probabilities follow the
371/// relative fitness gain per evaluation they produced.
372///
373/// The gain of one local search is `(before - after) / max(|before|, 1e-12)`; its benefit
374/// is the gain divided by the evaluations spent. After `window` local searches the levels used
375/// in that window share their probability mass in proportion to their mean benefit (moving
376/// halfway there), unused levels keep theirs, and a floor of `floor / levels` keeps every
377/// level alive. The update rule is a reconstruction: Jakob (2021) describes cost-benefit
378/// adaptation without formulas.
379///
380/// Limitation: the benefit is measured per local search, so it reflects intensity directly
381/// but frequency only weakly (a frequency level is credited with the searches it triggered,
382/// not with what the skipped offspring would have cost); intensity is the parameter that
383/// really adapts.
384#[derive(Debug, Clone, PartialEq)]
385pub struct Adaptive {
386    /// The evaluation caps to choose from.
387    pub intensity: Levels<u64>,
388    /// The improvement probabilities to choose from.
389    pub frequency: Levels<f64>,
390    /// Local searches between adaptations.
391    pub window: u64,
392    /// The probability floor, spread over the levels.
393    pub floor: f64,
394}
395
396impl Default for Adaptive {
397    /// Intensities 50, 100, 200, 400, 800 evaluations; frequencies 0.1, 0.25, 0.5, 1;
398    /// adaptation every 20 searches with a 10 % floor.
399    fn default() -> Self {
400        Self {
401            intensity: Levels::new(alloc::vec![50, 100, 200, 400, 800]),
402            frequency: Levels::new(alloc::vec![0.1, 0.25, 0.5, 1.0]),
403            window: 20,
404            floor: 0.1,
405        }
406    }
407}
408
409/// A memetic hybrid: a local searcher and its schedule.
410#[derive(Debug, Clone, PartialEq)]
411pub struct Memetic<L> {
412    /// The local searcher.
413    pub local: L,
414    /// How often and how long it runs.
415    pub schedule: Schedule,
416    /// Write the improved genome back (Lamarckian); otherwise only its cost is kept
417    /// (Baldwinian).
418    pub lamarckian: bool,
419}
420
421impl<L> Memetic<L> {
422    /// A Lamarckian hybrid with the default adaptive schedule.
423    #[must_use]
424    pub fn adaptive(local: L) -> Self {
425        Self {
426            local,
427            schedule: Schedule::Adaptive(Adaptive::default()),
428            lamarckian: true,
429        }
430    }
431}
432
433impl<G, L: LocalSearch<G>> Refine<G> for Memetic<L> {
434    fn refine<O, B, Obs, R>(
435        &mut self,
436        child: Individual<G>,
437        evaluator: &mut Evaluator<'_, G, O, B, Obs>,
438        rng: &mut R,
439    ) -> Individual<G>
440    where
441        G: Clone,
442        O: Objective<G> + ?Sized,
443        B: Budget<Stats> + ?Sized,
444        Obs: Observer + ?Sized,
445        R: Rng + ?Sized,
446    {
447        let (apply, cap, levels) = match &self.schedule {
448            Schedule::Fixed {
449                probability,
450                evaluations,
451            } => (chance(rng, *probability), *evaluations, None),
452            Schedule::Adaptive(adaptive) => {
453                let f = adaptive.frequency.draw(rng);
454                let i = adaptive.intensity.draw(rng);
455                (
456                    unit_f64(rng) < adaptive.frequency.values[f],
457                    adaptive.intensity.values[i],
458                    Some((f, i)),
459                )
460            }
461        };
462        if !apply {
463            return child;
464        }
465
466        let before = child.cost;
467        let start_evaluations = evaluator.stats.evaluations;
468        let original = (!self.lamarckian).then(|| child.genome.clone());
469        let improved = self
470            .local
471            .improve(child, cap, &mut |g: &G| evaluator.evaluate(g), rng);
472        let spent = evaluator.stats.evaluations - start_evaluations;
473        if let (Schedule::Adaptive(adaptive), Some((f, i))) = (&mut self.schedule, levels) {
474            let gain = (before - improved.cost) / before.abs().max(1e-12);
475            #[expect(
476                clippy::cast_precision_loss,
477                reason = "evaluation counts far below 2^52"
478            )]
479            let benefit = if spent == 0 || !gain.is_finite() {
480                0.0
481            } else {
482                gain.max(0.0) / spent as f64
483            };
484            adaptive
485                .frequency
486                .record(f, benefit, adaptive.window, adaptive.floor);
487            adaptive
488                .intensity
489                .record(i, benefit, adaptive.window, adaptive.floor);
490        }
491
492        match original {
493            Some(genome) => Individual {
494                genome,
495                cost: improved.cost,
496            },
497            None => improved,
498        }
499    }
500}
501
502#[cfg(test)]
503mod tests {
504    use super::*;
505    use crate::ga::{Config, Ga, Operators};
506    use crate::operators::NoRepair;
507    use crate::operators::real::{Bounds, Polynomial, Sbx};
508    use crate::operators::selection::Tournament;
509    use crate::problems::single::{ellipsoid, rosenbrock};
510    use crate::{Limits, SplitMix64};
511
512    /// Rosenbrock's method alone solves a rotated, badly scaled quadratic and the Rosenbrock
513    /// function from a fixed start.
514    #[test]
515    fn rosenbrock_method_converges() {
516        let mut ls = Rosenbrock::default();
517        let mut rng = SplitMix64::new(1);
518        for (f, start) in [
519            (ellipsoid as fn(&[f64]) -> f64, alloc::vec![1.0; 4]),
520            (rosenbrock, alloc::vec![-1.2, 1.0]),
521        ] {
522            let cost = f(&start);
523            let mut evaluate = |x: &Vec<f64>| Some(f(x));
524            let result = ls.improve(
525                Individual {
526                    genome: start,
527                    cost,
528                },
529                20_000,
530                &mut evaluate,
531                &mut rng,
532            );
533            assert!(result.cost < 1e-8, "{}", result.cost);
534        }
535    }
536
537    /// The memetic GA beats the plain GA on Rosenbrock at the same budget, and the adaptive
538    /// schedule keeps valid probability distributions.
539    #[test]
540    fn memetic_beats_plain_ga() {
541        let bounds = Bounds::uniform(5, -2.0, 2.0);
542        let make = || {
543            Ga::new(
544                Config {
545                    population_size: 20,
546                    elitism: 1,
547                    ..Config::default()
548                },
549                Operators {
550                    init: bounds.clone(),
551                    selection: Tournament { size: 2 },
552                    crossover: Sbx {
553                        bounds: bounds.clone(),
554                        eta: 15.0,
555                    },
556                    mutation: Polynomial {
557                        bounds: bounds.clone(),
558                        eta: 20.0,
559                        rate: None,
560                    },
561                    repair: NoRepair,
562                },
563            )
564        };
565        let mut objective = |x: &Vec<f64>| rosenbrock(x);
566        let plain = make().run(
567            &mut objective,
568            &mut Limits::evaluations(30_000),
569            &mut (),
570            &mut SplitMix64::new(3),
571        );
572        let mut memetic = Memetic::adaptive(Rosenbrock::default());
573        let hybrid = make().run_memetic(
574            &mut memetic,
575            &mut objective,
576            &mut Limits::evaluations(30_000),
577            &mut (),
578            &mut SplitMix64::new(3),
579        );
580
581        assert_eq!(hybrid.stats.evaluations, 30_000);
582        assert!(
583            hybrid.best_cost() < plain.best_cost(),
584            "{} vs {}",
585            hybrid.best_cost(),
586            plain.best_cost()
587        );
588        assert!(hybrid.best_cost() < 1e-6, "{}", hybrid.best_cost());
589        if let Schedule::Adaptive(a) = &memetic.schedule {
590            for p in [a.intensity.probabilities(), a.frequency.probabilities()] {
591                assert!((p.iter().sum::<f64>() - 1.0).abs() < 1e-9);
592                assert!(p.iter().all(|&x| x > 0.0));
593            }
594        }
595    }
596
597    /// A Baldwinian hybrid keeps the genome but takes the improved cost.
598    #[test]
599    fn baldwinian_keeps_genome() {
600        let mut memetic = Memetic {
601            local: Rosenbrock::default(),
602            schedule: Schedule::Fixed {
603                probability: 1.0,
604                evaluations: 200,
605            },
606            lamarckian: false,
607        };
608        let mut objective = |x: &Vec<f64>| x.iter().map(|v| v * v).sum::<f64>();
609        let mut budget = Limits::unlimited();
610        let mut observer = ();
611        let mut evaluator = Evaluator::new(&mut objective, &mut budget, &mut observer);
612        let child = Individual {
613            genome: alloc::vec![1.0, 1.0],
614            cost: 2.0,
615        };
616        let refined = memetic.refine(child, &mut evaluator, &mut SplitMix64::new(1));
617
618        assert_eq!(refined.genome, [1.0, 1.0]);
619        assert!(refined.cost < 2.0);
620    }
621}