Skip to main content

lib_jsl_optimization/
particle_swarm.rs

1//! Particle swarm optimization (Kennedy and Eberhart, with Clerc's constriction coefficients).
2//!
3//! See the book entry [Stochastic global optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/stochastic.html#particle-swarm-optimisation).
4
5use crate::differential_evolution::search_box;
6use crate::optimization_traits::{GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction, OptimizationResult};
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_random::uniform_generator::{UniformGenerator, UniformRNG};
9
10/// Global-best particle swarm optimization. Each particle moves with velocity
11/// `v ← w v + c₁ r₁ (p_best − x) + c₂ r₂ (g_best − x)` (`r` uniform per coordinate), using
12/// Clerc and Kennedy's constriction values `w = 0.7298`, `c₁ = c₂ = 1.49618` by default.
13/// Velocities are capped at the box width and positions clamped into the box (which needs
14/// finite bounds). Stops when the best value has improved by less than the tolerance (default
15/// 1e-12, relative) for `stall_iterations` iterations, or after the maximum (default 2000).
16#[derive(Debug, Clone)]
17pub struct ParticleSwarm {
18    max_iterations: Option<usize>,
19    tolerance: Option<f64>,
20    bounds: Option<Vec<(f64, f64)>>,
21    /// Number of particles; `None` uses `max(20, 10 · dimension)`.
22    pub swarm_size: Option<usize>,
23    pub inertia: f64,
24    pub cognitive: f64,
25    pub social: f64,
26    pub stall_iterations: usize,
27    pub seed: u64,
28}
29
30impl ParticleSwarm {
31    pub fn new(bounds: Vec<(f64, f64)>) -> Self {
32        ParticleSwarm {
33            max_iterations: None,
34            tolerance: None,
35            bounds: Some(bounds),
36            swarm_size: None,
37            inertia: 0.7298,
38            cognitive: 1.49618,
39            social: 1.49618,
40            stall_iterations: 100,
41            seed: 0,
42        }
43    }
44}
45
46impl MinimizationControls for ParticleSwarm {
47    fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
48        self.max_iterations = max_iterations;
49    }
50    fn get_max_iterations(&self) -> Option<usize> {
51        self.max_iterations
52    }
53    fn set_tolerance(&mut self, tolerance: Option<f64>) {
54        self.tolerance = tolerance;
55    }
56    fn get_tolerance(&self) -> Option<f64> {
57        self.tolerance
58    }
59    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
60        self.bounds = bounds;
61    }
62    fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
63        self.bounds.clone()
64    }
65}
66
67impl<T: ObjectiveFunction> GradientFreeMinimizationEngine<T> for ParticleSwarm {
68    /// `initial_parameters` seeds the first particle.
69    fn gradient_free_minimize(&self, objective: &T, initial_parameters: Vec<f64>) -> Result<OptimizationResult, ErrorsJSL> {
70        let d = initial_parameters.len();
71        let bounds = search_box(&self.bounds, d)?;
72        let n = self.swarm_size.unwrap_or((10 * d).max(20)).max(2);
73        let tol = self.tolerance.unwrap_or(1e-12);
74        let max_iterations = self.max_iterations.unwrap_or(2000);
75        let mut rng = UniformRNG::from_seed(self.seed);
76        let width: Vec<f64> = bounds.iter().map(|(lo, hi)| hi - lo).collect();
77        let mut x: Vec<Vec<f64>> = (0..n).map(|_| bounds.iter().map(|(lo, hi)| lo + rng.next_f64() * (hi - lo)).collect()).collect();
78        x[0] = initial_parameters.iter().zip(&bounds).map(|(v, (lo, hi))| v.clamp(*lo, *hi)).collect();
79        let mut v: Vec<Vec<f64>> = (0..n).map(|_| width.iter().map(|w| (2.0 * rng.next_f64() - 1.0) * 0.1 * w).collect()).collect();
80        let mut personal = x.clone();
81        let mut personal_value: Vec<f64> = x.iter().map(|p| objective.evaluate(p)).collect();
82        let mut g = (0..n).min_by(|&i, &j| personal_value[i].total_cmp(&personal_value[j])).expect("non-empty swarm");
83        let (mut best, mut best_value) = (personal[g].clone(), personal_value[g]);
84        let mut stall = 0;
85        let mut iteration = 0;
86        let mut converged = false;
87        while iteration < max_iterations {
88            iteration += 1;
89            for i in 0..n {
90                // ANCHOR: pso_update
91                for k in 0..d {
92                    let (r1, r2) = (rng.next_f64(), rng.next_f64());
93                    let vel = self.inertia * v[i][k] + self.cognitive * r1 * (personal[i][k] - x[i][k]) + self.social * r2 * (best[k] - x[i][k]);
94                    v[i][k] = vel.clamp(-width[k], width[k]);
95                    x[i][k] = (x[i][k] + v[i][k]).clamp(bounds[k].0, bounds[k].1);
96                }
97                let value = objective.evaluate(&x[i]);
98                if value < personal_value[i] {
99                    personal_value[i] = value;
100                    personal[i] = x[i].clone();
101                }
102                // ANCHOR_END: pso_update
103            }
104            g = (0..n).min_by(|&i, &j| personal_value[i].total_cmp(&personal_value[j])).expect("non-empty swarm");
105            if best_value - personal_value[g] > tol * (1.0 + best_value.abs()) {
106                stall = 0;
107            } else {
108                stall += 1;
109            }
110            if personal_value[g] < best_value {
111                best_value = personal_value[g];
112                best = personal[g].clone();
113            }
114            if stall >= self.stall_iterations {
115                converged = true;
116                break;
117            }
118        }
119        Ok(OptimizationResult { parameters: best, objective_value: best_value, iterations: iteration, converged })
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::differential_evolution::test_functions::*;
127
128    #[test]
129    fn swarm_finds_global_minima() {
130        struct Sphere;
131        impl ObjectiveFunction for Sphere {
132            fn evaluate(&self, x: &[f64]) -> f64 {
133                x.iter().map(|v| (v - 0.5).powi(2)).sum()
134            }
135        }
136        let r = ParticleSwarm::new(vec![(-10.0, 10.0); 10]).gradient_free_minimize(&Sphere, vec![9.0; 10]).unwrap();
137        assert!(r.converged && r.objective_value < 1e-10, "{r:?}");
138        let r = ParticleSwarm::new(vec![(-5.12, 5.12); 2]).gradient_free_minimize(&Rastrigin, vec![3.0, -3.0]).unwrap();
139        assert!(r.objective_value < 1e-8, "{r:?}");
140        let r = ParticleSwarm::new(vec![(-32.0, 32.0); 3]).gradient_free_minimize(&Ackley, vec![10.0; 3]).unwrap();
141        assert!(r.objective_value < 1e-6, "{r:?}");
142    }
143
144    #[test]
145    fn stays_in_bounds_and_validates() {
146        let r = ParticleSwarm::new(vec![(1.0, 2.0); 3]).gradient_free_minimize(&Rosenbrock, vec![1.5; 3]).unwrap();
147        assert!(r.parameters.iter().all(|v| (1.0..=2.0).contains(v)) && r.objective_value < 1e-6, "{r:?}");
148        let mut p = ParticleSwarm::new(vec![(0.0, 1.0)]);
149        assert!(p.gradient_free_minimize(&Rosenbrock, vec![0.5, 0.5]).is_err());
150        p.set_bounds(Some(vec![(0.0, f64::INFINITY)]));
151        assert!(p.gradient_free_minimize(&Rosenbrock, vec![0.5]).is_err());
152    }
153}