1use 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
52pub trait LocalSearch<G> {
54 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct HillClimb<M> {
74 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#[derive(Debug, Clone, Copy, PartialEq)]
116pub struct Rosenbrock {
117 pub initial_step: f64,
119 pub alpha: f64,
121 pub beta: f64,
123 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
200fn 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
208fn 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
237fn 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
248fn norm(v: &[f64]) -> f64 {
250 libm::sqrt(v.iter().map(|x| x * x).sum())
251}
252
253#[derive(Debug, Clone, PartialEq)]
255pub struct Levels<T> {
256 pub values: Vec<T>,
258 probabilities: Vec<f64>,
260 benefit: Vec<f64>,
263 uses: Vec<u64>,
265}
266
267impl<T: Copy> Levels<T> {
268 #[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 #[must_use]
290 pub fn probabilities(&self) -> &[f64] {
291 &self.probabilities
292 }
293
294 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 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 #[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 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#[derive(Debug, Clone, PartialEq)]
358pub enum Schedule {
359 Fixed {
361 probability: f64,
363 evaluations: u64,
365 },
366 Adaptive(Adaptive),
368}
369
370#[derive(Debug, Clone, PartialEq)]
385pub struct Adaptive {
386 pub intensity: Levels<u64>,
388 pub frequency: Levels<f64>,
390 pub window: u64,
392 pub floor: f64,
394}
395
396impl Default for Adaptive {
397 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#[derive(Debug, Clone, PartialEq)]
411pub struct Memetic<L> {
412 pub local: L,
414 pub schedule: Schedule,
416 pub lamarckian: bool,
419}
420
421impl<L> Memetic<L> {
422 #[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 #[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 #[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 #[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}