eindir_core/objectives/
ackley.rs1use crate::{Bounds, DifferentiableObjective, FPair, Objective, gradient::Gradient};
4use ndarray::{Array1, ArrayView1};
5use std::sync::OnceLock;
6
7pub 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 pub fn new() -> Self {
20 assert!(D > 0, "Ackley requires at least one dimension");
21 Self {
22 bounds: Bounds::new(
23 Array1::from_vec(vec![-32.768; D]),
24 Array1::from_vec(vec![32.768; D]),
25 1e-9,
26 ),
27 min: OnceLock::new(),
28 }
29 }
30}
31
32impl<const D: usize> Default for Ackley<D> {
33 fn default() -> Self {
34 Self::new()
35 }
36}
37
38impl<const D: usize> Objective<f64> for Ackley<D> {
39 fn dim(&self) -> usize {
40 D
41 }
42
43 fn bounds(&self) -> &Bounds<f64> {
44 &self.bounds
45 }
46
47 fn eval(&self, x: ArrayView1<f64>) -> f64 {
48 let two_pi = 2.0 * std::f64::consts::PI;
49 let n = D as f64;
50 let sum_sq: f64 = x.iter().map(|xi| xi.powi(2)).sum();
51 let sum_cos: f64 = x.iter().map(|xi| (two_pi * xi).cos()).sum();
52 -Self::A * (-Self::B * (sum_sq / n).sqrt()).exp() - (sum_cos / n).exp()
53 + Self::A
54 + std::f64::consts::E
55 }
56
57 fn global_min(&self) -> Option<&FPair<f64>> {
58 Some(self.min.get_or_init(|| FPair {
59 pos: Array1::zeros(D),
60 val: 0.0,
61 }))
62 }
63}
64
65impl<const D: usize> Gradient<f64> for Ackley<D> {
66 fn grad(&self, x: ArrayView1<f64>) -> Array1<f64> {
67 let n = D as f64;
68 let sum_sq: f64 = x.iter().map(|xi| xi.powi(2)).sum();
69 let s = (sum_sq / n).sqrt();
70 let two_pi = 2.0 * std::f64::consts::PI;
71 let sum_cos: f64 = x.iter().map(|xi| (two_pi * xi).cos()).sum();
72 let avg_cos = sum_cos / n;
73
74 let exp_term1 = (-Self::B * s).exp();
75 let exp_term2 = avg_cos.exp();
76
77 let mut g = Array1::<f64>::zeros(D);
78 let scale1 = if s > 1e-300 {
79 Self::A * Self::B / (s * n) * exp_term1
80 } else {
81 0.0
82 };
83 let scale2 = (2.0 * std::f64::consts::PI / n) * exp_term2;
84
85 for (i, &xi) in x.iter().enumerate() {
86 g[i] = scale1 * xi + scale2 * (two_pi * xi).sin();
87 }
88 g
89 }
90 fn dim(&self) -> usize {
91 D
92 }
93}
94
95impl<const D: usize> DifferentiableObjective<f64> for Ackley<D> {}