Skip to main content

lib_jsl_optimization/
simulated_annealing.rs

1//! This file implements simulated annealing for optimization. Simulated
2//! annealing is a probabilistic optimization algorithm that is inspired by the
3//! process of annealing in metallurgy, where a material is heated and then
4//! slowly cooled to allow it to reach a state of minimum energy. In
5//! optimization, simulated annealing is used to find the minimum of an
6//! objective function by allowing for occasional uphill moves, which can help
7//! the algorithm escape local minima and explore the search space more
8//! effectively. The algorithm works by starting with an initial solution and
9//! then iteratively generating new candidate solutions by making small random
10//! changes to the current solution. The new solution is accepted with a
11//! probability that depends on the difference in objective function values
12//! between the current and new solutions, as well as a temperature parameter
13//! that controls the likelihood of accepting worse solutions. As the algorithm
14//! progresses, the temperature is gradually decreased, which reduces the
15//! probability of accepting worse solutions and allows the algorithm to
16//! converge to a minimum.
17//!
18//! In this implementation a candidate adds Gaussian noise with standard deviation equal to the
19//! current temperature to every coordinate, so the temperature sets both the acceptance
20//! probability `exp(−Δf/T)` and the step size: choose the maximum temperature (default 1) on the
21//! scale of the variables and of the changes in `f`. The temperature falls geometrically by the
22//! cooling coefficient (default 0.9) after `iterations_per_temperature` (default 100) candidates,
23//! until it reaches the minimum temperature (default 1e-5); `converged` means the schedule
24//! finished. The tolerance is not used. The best point ever evaluated is returned.
25//!
26//! Simulated annealing can be effective for optimizing
27//! complex, non-convex functions, but it can also be computationally expensive
28//! and may require careful tuning of the temperature schedule and other
29//! hyperparameters to achieve good performance.
30//!
31//! See the book entry [Stochastic global optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/stochastic.html#simulated-annealing).
32
33use crate::optimization_traits::{
34    GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction, OptimizationResult,
35};
36use lib_jsl_core::ErrorsJSL;
37use lib_jsl_random::{
38    distributions::gaussian_distribution_box_muller_vec,
39    uniform_generator::{UniformGenerator, UniformRNG},
40};
41
42pub struct SimulatedAnnealing {
43    max_iterations: Option<usize>,
44    tolerance: Option<f64>,
45    bounds: Option<Vec<(f64, f64)>>,
46    /// These are additional parameters specific to simulated annealing that can be set and get using the methods defined in this struct. The cooling coefficient controls how quickly the temperature decreases, while the minimum and maximum temperature define the range of temperatures that the algorithm will use during the optimization process.
47    cooling_coefficient: Option<f64>,
48    /// The minimum temperature is the lowest temperature that the algorithm will use during the optimization process. 
49    /// It can be set to a small positive value to ensure that the algorithm continues to explore the search space even at low temperatures, or it can be set to zero to allow for a complete cooling schedule.
50    minimum_temperature: Option<f64>,
51    /// The maximum temperature is the highest temperature that the algorithm will use during the optimization process. 
52    /// It can be set to a large value to allow for a wide exploration of the search space at the beginning of the optimization, or it can be set to a smaller value to focus the search on a narrower region of the search space.
53    maximum_temperature: Option<f64>,
54    /// Iterations per temperature is the number of iterations that the algorithm will perform at each temperature level before cooling down. It can be set to a fixed value or it can be dynamically adjusted based on the progress of the optimization.
55    iterations_per_temperature: Option<usize>,
56    /// Seed of the random number generator (default 0), so runs are reproducible.
57    seed: u64,
58}
59
60impl SimulatedAnnealing {
61    pub fn new() -> Self {
62        SimulatedAnnealing {
63            max_iterations: None,
64            tolerance: None,
65            bounds: None,
66            cooling_coefficient:None,
67            minimum_temperature: None,
68            maximum_temperature: None,
69            iterations_per_temperature: None,
70            seed: 0,
71        }
72    }
73
74    pub fn set_cooling_coefficient(&mut self, cooling_coefficient: Option<f64>) {
75        self.cooling_coefficient = cooling_coefficient;
76    }
77    pub fn get_cooling_coefficient(&self) -> Option<f64> {
78        self.cooling_coefficient
79    }
80    pub fn set_minimum_temperature(&mut self, minimum_temperature: Option<f64>) {
81        self.minimum_temperature = minimum_temperature;
82    }
83    pub fn get_minimum_temperature(&self) -> Option<f64> {
84        self.minimum_temperature
85    }
86    pub fn set_maximum_temperature(&mut self, maximum_temperature: Option<f64>) {
87        self.maximum_temperature = maximum_temperature;
88    }
89    pub fn get_maximum_temperature(&self) -> Option<f64> {
90        self.maximum_temperature
91    }
92    pub fn set_iterations_per_temperature(&mut self, iterations_per_temperature: Option<usize>) {
93        self.iterations_per_temperature = iterations_per_temperature;
94    }
95    pub fn get_iterations_per_temperature(&self) -> Option<usize> {
96        self.iterations_per_temperature
97    }
98    /// Sets the seed of the random number generator; different seeds give independent runs.
99    pub fn set_seed(&mut self, seed: u64) {
100        self.seed = seed;
101    }
102    pub fn get_seed(&self) -> u64 {
103        self.seed
104    }
105}
106
107impl Default for SimulatedAnnealing {
108    fn default() -> Self {
109        Self::new()
110    }
111}
112
113impl MinimizationControls for SimulatedAnnealing {
114    fn set_max_iterations(&mut self, max_iterations: Option<usize>) {
115        self.max_iterations = max_iterations;
116    }
117    fn get_max_iterations(&self) -> Option<usize> {
118        self.max_iterations
119    }
120    fn set_tolerance(&mut self, tolerance: Option<f64>) {
121        self.tolerance = tolerance;
122    }
123    fn get_tolerance(&self) -> Option<f64> {
124        self.tolerance
125    }
126    fn set_bounds(&mut self, bounds: Option<Vec<(f64, f64)>>) {
127        self.bounds = bounds;
128    }
129    fn get_bounds(&self) -> Option<Vec<(f64, f64)>> {
130        self.bounds.clone()
131    }
132}
133
134fn generate_candidate_solution<T>(current_parameters: &[f64], current_temperature: f64, rng: &mut T) -> Vec<f64> 
135where T: UniformGenerator{
136    let perturbations = gaussian_distribution_box_muller_vec(current_parameters.len(), rng, 0.0, current_temperature);
137    current_parameters
138        .iter()
139        .zip(perturbations.iter())
140        .map(|(&param, &perturbation)| {
141            param + perturbation
142        })
143        .collect()
144}
145
146fn project_to_bounds(parameters: &[f64], bounds: &[(f64, f64)]) -> Vec<f64> {
147    parameters
148        .iter()
149        .zip(bounds.iter())
150        .map(|(&param, &(low, high))| {
151            if param < low {
152                low
153            } else if param > high {
154                high
155            } else {
156                param
157            }
158        })
159        .collect()
160}
161
162impl<T> GradientFreeMinimizationEngine<T> for SimulatedAnnealing 
163where T: ObjectiveFunction {
164    fn gradient_free_minimize(
165        &self,
166        objective_function: &T,
167        initial_parameters: Vec<f64>,
168    ) -> Result<OptimizationResult, ErrorsJSL> {
169        if initial_parameters.is_empty() {
170            return Err(ErrorsJSL::Misconfiguration("Initial parameters must be a non-empty vector."));
171        }
172        let mut current_temperature = self.get_maximum_temperature().unwrap_or(1.0);
173        let cooling_coefficient = self.get_cooling_coefficient().unwrap_or(0.9);
174        let minimum_temperature = self.get_minimum_temperature().unwrap_or(1e-5);
175        let maximum_steps = self.get_max_iterations().unwrap_or(usize::MAX);
176        let iterations_per_temperature = self.get_iterations_per_temperature().unwrap_or(100);
177        let bounds = self.get_bounds();
178        if let Some(bounds) = bounds.as_ref() {
179            if bounds.len() != initial_parameters.len() {
180                return Err(ErrorsJSL::Misconfiguration(
181                    "Bounds length must match the number of parameters.",
182                ));
183            }            
184            if bounds.iter().any(|(lower, upper)| lower > upper) {
185                return Err(ErrorsJSL::Misconfiguration(
186                    "Lower bound must be less than or equal to upper bound.",
187                ));
188            }
189        }
190        let mut rng = UniformRNG::from_seed(self.seed);
191        let mut current_parameters = initial_parameters.clone();
192        let mut current_objective_value = objective_function.evaluate(&current_parameters);
193        let mut iteration_counter = 0;
194        let mut result = OptimizationResult {
195            parameters: current_parameters.clone(),
196            objective_value: current_objective_value,
197            iterations: iteration_counter,
198            converged: false,
199        };
200        while current_temperature > minimum_temperature && iteration_counter < maximum_steps {
201            // Here is the implementation of the simulated annealing algorithm. It assumes that the objective function is defined and that the initial parameters are a valid starting point for the optimization.
202            // The algorithm generates a new candidate solution by making a small random change to the current parameters, and then decides whether to accept the new solution based on the difference in objective function values and the current temperature. The temperature is then updated according to the cooling schedule defined by the cooling coefficient.
203            // If bounds are set, the new candidate solution is projected back into the feasible region defined by the bounds before evaluating the objective function.
204            // The algorithm continues until the temperature drops below the minimum temperature or the maximum number of iterations is reached, at which point it returns the best solution found.
205            for _ in 0..iterations_per_temperature {
206                // Generate a new candidate solution by making a small random change to the current parameters. This can be done by adding a random perturbation to each parameter, where the magnitude of the perturbation is proportional to the current temperature. The new candidate solution is then projected back into the feasible region defined by the bounds, if bounds are set.
207                // Evaluate the objective function at the new candidate solution and compare it to the current solution. If the new solution has a lower objective function value, it is accepted as the new current solution. If the new solution has a higher objective function value, it is accepted with a probability that depends on the difference in objective function values and the current temperature. This allows the algorithm to occasionally accept worse solutions, which can help it escape local minima and explore the search space more effectively.
208                // Update the temperature according to the cooling schedule defined by the cooling coefficient. This typically involves multiplying the current temperature by the cooling coefficient, which reduces the temperature over time and allows the algorithm to converge to a minimum.
209                // ANCHOR: sa_step
210                let mut candidate_parameters = generate_candidate_solution(&current_parameters, current_temperature, &mut rng);
211                if let Some(b) = bounds.as_ref() {
212                    candidate_parameters = project_to_bounds(&candidate_parameters, b); 
213                }
214                let candidate_objective_value = objective_function.evaluate(&candidate_parameters);
215                // Always keep track of the best solution found so far, even if it is not accepted as the current solution. This allows the algorithm to return the best solution found at the end of the optimization process, rather than just the last solution that was accepted.
216                if candidate_objective_value < result.objective_value {
217                    result.parameters = candidate_parameters.clone();
218                    result.objective_value = candidate_objective_value;
219                }
220                // Decide whether to accept the new candidate solution based on the difference in objective function values and the current temperature. If the new solution has a lower objective function value, it is accepted as the new current solution. If the new solution has a higher objective function value, it is accepted with a probability that depends on the difference in objective function values and the current temperature. This allows the algorithm to occasionally accept worse solutions, which can help it escape local minima and explore the search space more effectively.
221                if candidate_objective_value < current_objective_value {
222                    current_parameters = candidate_parameters;
223                    current_objective_value = candidate_objective_value;
224                } else {
225                    let delta = candidate_objective_value - current_objective_value;
226                    let acceptance_probability = (-delta / current_temperature).exp();
227                    let sample = rng.next_f64();
228                    if sample < acceptance_probability {
229                        current_parameters = candidate_parameters;
230                        current_objective_value = candidate_objective_value;
231                    }   
232                }
233                // ANCHOR_END: sa_step
234                iteration_counter+=1;
235            }
236            current_temperature *= cooling_coefficient;
237        }
238        result.converged = current_temperature <= minimum_temperature;
239        result.iterations = iteration_counter;
240        Ok(result)
241    }
242}   
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    struct TestObjectiveFunction;
248    impl ObjectiveFunction for TestObjectiveFunction {
249        fn evaluate(&self, parameters: &[f64]) -> f64 {
250            // This is a simple test objective function that has a minimum at (2.0, 3.0) with a value of 1.0. It is defined as f(x, y) = (x - 2)^2 + (y - 3)^2 + 1.
251            let x = parameters[0];
252            let y = parameters[1];
253            (x - 2.0).powi(2) + (y - 3.0).powi(2) + 1.0
254        }
255    }
256    #[test]
257    fn test_simulated_annealing() {
258        let objective_function = TestObjectiveFunction;
259        let mut optimizer = SimulatedAnnealing::new();
260        optimizer.set_cooling_coefficient(Some(0.9));
261        optimizer.set_minimum_temperature(Some(1E-16));
262        optimizer.set_maximum_temperature(Some(10.0));
263        optimizer.set_iterations_per_temperature(Some(100));            
264        optimizer.set_tolerance(Some(1e-6));
265        let initial_parameters = vec![0.0, 0.0];
266        let result = optimizer.gradient_free_minimize(&objective_function, initial_parameters).unwrap();
267        //dbg!("Result: {:?}", &result);
268        assert!(result.converged);
269        assert!((result.parameters[0] - 2.0).abs() < 1e-1);
270        assert!((result.parameters[1] - 3.0).abs() < 1e-1);
271        assert!((result.objective_value - 1.0).abs() < 1e-1);   
272    }
273}