lib_jsl_optimization/
differential_evolution.rs1use crate::optimization_traits::{GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction, OptimizationResult};
6use lib_jsl_core::ErrorsJSL;
7use lib_jsl_random::uniform_generator::{UniformGenerator, UniformRNG};
8
9#[derive(Debug, Clone)]
16pub struct DifferentialEvolution {
17 max_iterations: Option<usize>,
18 tolerance: Option<f64>,
19 bounds: Option<Vec<(f64, f64)>>,
20 pub population_size: Option<usize>,
22 pub differential_weight: f64,
24 pub crossover_probability: f64,
26 pub seed: u64,
27}
28
29impl DifferentialEvolution {
30 pub fn new(bounds: Vec<(f64, f64)>) -> Self {
31 DifferentialEvolution {
32 max_iterations: None,
33 tolerance: None,
34 bounds: Some(bounds),
35 population_size: None,
36 differential_weight: 0.8,
37 crossover_probability: 0.9,
38 seed: 0,
39 }
40 }
41}
42
43impl MinimizationControls for DifferentialEvolution {
44 fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
45 self.max_iterations = max_iterations;
46 }
47 fn get_max_iterations(&self) -> Option<usize> {
48 self.max_iterations
49 }
50 fn set_tolerance(&mut self, tolerance: Option<f64>) {
51 self.tolerance = tolerance;
52 }
53 fn get_tolerance(&self) -> Option<f64> {
54 self.tolerance
55 }
56 fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
57 self.bounds = bounds;
58 }
59 fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
60 self.bounds.clone()
61 }
62}
63
64pub(crate) fn search_box(bounds: &Option<Vec<(f64, f64)>>, dimension: usize) -> Result<Vec<(f64, f64)>, ErrorsJSL> {
66 let b = bounds.clone().ok_or(ErrorsJSL::Misconfiguration("Population methods need finite bounds."))?;
67 if b.len() != dimension || dimension == 0 {
68 return Err(ErrorsJSL::Misconfiguration("Bounds length must match the number of parameters."));
69 }
70 if b.iter().any(|(lo, hi)| !lo.is_finite() || !hi.is_finite() || lo > hi) {
71 return Err(ErrorsJSL::Misconfiguration("Bounds must be finite with lower <= upper."));
72 }
73 Ok(b)
74}
75
76impl<T: ObjectiveFunction> GradientFreeMinimizationEngine<T> for DifferentialEvolution {
77 fn gradient_free_minimize(&self, objective: &T, initial_parameters: Vec<f64>) -> Result<OptimizationResult, ErrorsJSL> {
79 let d = initial_parameters.len();
80 let bounds = search_box(&self.bounds, d)?;
81 let np = self.population_size.unwrap_or((10 * d).max(15)).max(4);
82 let tol = self.tolerance.unwrap_or(1e-12);
83 let generations = self.max_iterations.unwrap_or(1000);
84 let mut rng = UniformRNG::from_seed(self.seed);
85 let mut population: Vec<Vec<f64>> = (0..np).map(|_| bounds.iter().map(|(lo, hi)| lo + rng.next_f64() * (hi - lo)).collect()).collect();
86 population[0] = initial_parameters.iter().zip(&bounds).map(|(v, (lo, hi))| v.clamp(*lo, *hi)).collect();
87 let mut values: Vec<f64> = population.iter().map(|p| objective.evaluate(p)).collect();
88 let pick = |rng: &mut UniformRNG, exclude: &[usize]| loop {
89 let k = (rng.next_f64() * np as f64) as usize % np;
90 if !exclude.contains(&k) {
91 break k;
92 }
93 };
94 let mut generation = 0;
95 let mut converged = false;
96 while generation < generations {
97 generation += 1;
98 for i in 0..np {
99 let a = pick(&mut rng, &[i]);
101 let b = pick(&mut rng, &[i, a]);
102 let c = pick(&mut rng, &[i, a, b]);
103 let forced = (rng.next_f64() * d as f64) as usize % d;
104 let trial: Vec<f64> = (0..d)
105 .map(|j| {
106 if j == forced || rng.next_f64() < self.crossover_probability {
107 let v = population[a][j] + self.differential_weight * (population[b][j] - population[c][j]);
108 let (lo, hi) = bounds[j];
109 if v < lo {
111 lo + rng.next_f64() * (population[i][j] - lo)
112 } else if v > hi {
113 hi - rng.next_f64() * (hi - population[i][j])
114 } else {
115 v
116 }
117 } else {
118 population[i][j]
119 }
120 })
121 .collect();
122 let value = objective.evaluate(&trial);
123 if value <= values[i] {
124 population[i] = trial;
125 values[i] = value;
126 }
127 }
129 let (best, worst) = values.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &v| (lo.min(v), hi.max(v)));
130 if worst - best <= tol * (1.0 + best.abs()) {
131 converged = true;
132 break;
133 }
134 }
135 let best = (0..np).min_by(|&i, &j| values[i].total_cmp(&values[j])).expect("non-empty population");
136 Ok(OptimizationResult { parameters: population[best].clone(), objective_value: values[best], iterations: generation, converged })
137 }
138}
139
140#[cfg(test)]
141pub(crate) mod test_functions {
142 use crate::optimization_traits::ObjectiveFunction;
143 use std::f64::consts::PI;
144
145 pub struct Rastrigin;
147 impl ObjectiveFunction for Rastrigin {
148 fn evaluate(&self, x: &[f64]) -> f64 {
149 10.0 * x.len() as f64 + x.iter().map(|v| v * v - 10.0 * (2.0 * PI * v).cos()).sum::<f64>()
150 }
151 }
152
153 pub struct Ackley;
155 impl ObjectiveFunction for Ackley {
156 fn evaluate(&self, x: &[f64]) -> f64 {
157 let n = x.len() as f64;
158 let s1 = x.iter().map(|v| v * v).sum::<f64>() / n;
159 let s2 = x.iter().map(|v| (2.0 * PI * v).cos()).sum::<f64>() / n;
160 -20.0 * (-0.2 * s1.sqrt()).exp() - s2.exp() + 20.0 + std::f64::consts::E
161 }
162 }
163
164 pub struct Rosenbrock;
165 impl ObjectiveFunction for Rosenbrock {
166 fn evaluate(&self, p: &[f64]) -> f64 {
167 p.windows(2).map(|w| 100.0 * (w[1] - w[0] * w[0]).powi(2) + (1.0 - w[0]).powi(2)).sum()
168 }
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::test_functions::*;
175 use super::*;
176
177 #[test]
178 fn finds_global_minima_of_multimodal_functions() {
179 let de = DifferentialEvolution::new(vec![(-5.12, 5.12); 5]);
180 let r = de.gradient_free_minimize(&Rastrigin, vec![4.0; 5]).unwrap();
181 assert!(r.objective_value < 1e-8 && r.parameters.iter().all(|v| v.abs() < 1e-4), "{r:?}");
182 let de = DifferentialEvolution::new(vec![(-32.0, 32.0); 3]);
183 let r = de.gradient_free_minimize(&Ackley, vec![20.0; 3]).unwrap();
184 assert!(r.objective_value < 1e-6, "{r:?}");
185 let mut de = DifferentialEvolution::new(vec![(-2.0, 2.0); 4]);
186 de.set_max_iterations(Some(3000));
187 let r = de.gradient_free_minimize(&Rosenbrock, vec![0.0; 4]).unwrap();
188 assert!(r.parameters.iter().all(|v| (v - 1.0).abs() < 1e-3), "{r:?}");
189 }
190
191 #[test]
192 fn respects_bounds_and_validates() {
193 struct Shifted;
195 impl ObjectiveFunction for Shifted {
196 fn evaluate(&self, x: &[f64]) -> f64 {
197 (x[0] - 3.0).powi(2) + x[1] * x[1]
198 }
199 }
200 let de = DifferentialEvolution::new(vec![(-1.0, 1.0), (-1.0, 1.0)]);
201 let r = de.gradient_free_minimize(&Shifted, vec![0.0, 0.0]).unwrap();
202 assert!((r.parameters[0] - 1.0).abs() < 1e-6 && r.parameters.iter().all(|v| (-1.0..=1.0).contains(v)));
203 let mut bad = DifferentialEvolution::new(vec![(0.0, 1.0)]);
204 assert!(bad.gradient_free_minimize(&Shifted, vec![0.0, 0.0]).is_err());
205 bad.set_bounds(None);
206 assert!(bad.gradient_free_minimize(&Shifted, vec![0.0]).is_err());
207 }
208}