Skip to main content

eindir_core/objectives/
ackley.rs

1//! N-dimensional Ackley: nearly flat outer region with a deep central well.
2
3use crate::{Bounds, FPair, Objective, gradient::Gradient};
4use ndarray::{Array1, ArrayView1};
5use std::sync::OnceLock;
6
7/// N-dimensional Ackley: a multi-modal benchmark with a sharp central well.
8/// Domain `[-32.768, 32.768]^D`. Global minimum at the origin with value `0`.
9pub struct Ackley<const D: usize> {
10    bounds: Bounds<f64>,
11    min: OnceLock<FPair<f64>>,
12}
13
14impl<const D: usize> Ackley<D> {
15    const A: f64 = 20.0;
16    const B: f64 = 0.2;
17
18    /// Constructs an Ackley objective in `D` dimensions.
19    pub fn new() -> Self {
20        Self {
21            bounds: Bounds::new(
22                Array1::from_vec(vec![-32.768; D]),
23                Array1::from_vec(vec![32.768; D]),
24                1e-9,
25            ),
26            min: OnceLock::new(),
27        }
28    }
29}
30
31impl<const D: usize> Default for Ackley<D> {
32    fn default() -> Self {
33        Self::new()
34    }
35}
36
37impl<const D: usize> Objective<f64> for Ackley<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 n = D as f64;
49        let sum_sq: f64 = x.iter().map(|xi| xi.powi(2)).sum();
50        let sum_cos: f64 = x.iter().map(|xi| (two_pi * xi).cos()).sum();
51        -Self::A * (-Self::B * (sum_sq / n).sqrt()).exp() - (sum_cos / n).exp()
52            + Self::A
53            + std::f64::consts::E
54    }
55
56    fn global_min(&self) -> Option<&FPair<f64>> {
57        Some(self.min.get_or_init(|| FPair {
58            pos: Array1::zeros(D),
59            val: 0.0,
60        }))
61    }
62}
63
64impl<const D: usize> Gradient<f64> for Ackley<D> {
65    fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
66        let n = D as f64;
67        let sum_sq: f64 = x.iter().map(|xi| xi.powi(2)).sum();
68        let s = (sum_sq / n).sqrt();
69        let two_pi = 2.0 * std::f64::consts::PI;
70        let sum_cos: f64 = x.iter().map(|xi| (two_pi * xi).cos()).sum();
71        let avg_cos = sum_cos / n;
72
73        let exp_term1 = (-Self::B * s).exp();
74        let exp_term2 = avg_cos.exp();
75
76        let mut g = Array1::<f64>::zeros(D);
77        let scale1 = if s > 1e-300 {
78            Self::A * Self::B / (s * n) * exp_term1
79        } else {
80            0.0
81        };
82        let scale2 = (2.0 * std::f64::consts::PI / n) * exp_term2;
83
84        for (i, &xi) in x.iter().enumerate() {
85            g[i] = scale1 * xi + scale2 * (two_pi * xi).sin();
86        }
87        g
88    }
89    fn dim(&self) -> usize {
90        D
91    }
92}