Skip to main content

eindir_core/objectives/
rastrigin.rs

1//! N-dimensional Rastrigin: highly multimodal benchmark.
2
3use crate::{Bounds, DifferentiableObjective, FPair, Objective, gradient::Gradient};
4use ndarray::{Array1, ArrayView1};
5use std::sync::OnceLock;
6
7/// N-dimensional Rastrigin: `A * D + sum_i (x_i^2 - A * cos(2 * pi * x_i))`
8/// with `A = 10`. Domain `[-5.12, 5.12]^D`. Global minimum at the origin
9/// with value `0`.
10pub struct Rastrigin<const D: usize> {
11    bounds: Bounds<f64>,
12    min: OnceLock<FPair<f64>>,
13}
14
15impl<const D: usize> Rastrigin<D> {
16    const A: f64 = 10.0;
17
18    /// Constructs a Rastrigin objective in `D` dimensions.
19    pub fn new() -> Self {
20        Self {
21            bounds: Bounds::new(
22                Array1::from_vec(vec![-5.12; D]),
23                Array1::from_vec(vec![5.12; D]),
24                1e-9,
25            ),
26            min: OnceLock::new(),
27        }
28    }
29}
30
31impl<const D: usize> Default for Rastrigin<D> {
32    fn default() -> Self {
33        Self::new()
34    }
35}
36
37impl<const D: usize> Objective<f64> for Rastrigin<D> {
38    fn dim(&self) -> usize {
39        D
40    }
41
42    fn bounds(&self) -> &Bounds<f64> {
43        &self.bounds
44    }
45
46    fn eval(&self, x: ArrayView1<f64>) -> f64 {
47        let two_pi = 2.0 * std::f64::consts::PI;
48        let inner: f64 = x
49            .iter()
50            .map(|xi| xi.powi(2) - Self::A * (two_pi * xi).cos())
51            .sum();
52        Self::A * (D as f64) + inner
53    }
54
55    fn global_min(&self) -> Option<&FPair<f64>> {
56        Some(self.min.get_or_init(|| FPair {
57            pos: Array1::zeros(D),
58            val: 0.0,
59        }))
60    }
61}
62
63impl<const D: usize> Gradient<f64> for Rastrigin<D> {
64    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
65        // grad_i = 2 x_i + 2 π A sin(2 π x_i)
66        let two_pi = 2.0 * std::f64::consts::PI;
67        x.mapv(|xi| 2.0 * xi + 2.0 * std::f64::consts::PI * Self::A * (two_pi * xi).sin())
68    }
69    fn dim(&self) -> usize {
70        D
71    }
72}
73
74impl<const D: usize> DifferentiableObjective<f64> for Rastrigin<D> {}