Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Stochastic global optimisation: simulated annealing, differential evolution and particle swarms

ProblemFind the global minimum of a function with many local minima, using only its values, within a bounded region
Devised bySimulated annealing: Scott Kirkpatrick, Daniel Gelatt and Mario Vecchi (1983), and Vlado Černý (1985), after the Metropolis algorithm (1953). Differential evolution: Rainer Storn and Kenneth Price (1995). Particle swarm optimisation: James Kennedy and Russell Eberhart (1995); constriction coefficients: Maurice Clerc and Kennedy (2002)
AccuracyNo guarantee in finite time; success is measured statistically over runs. Population methods typically locate the global minimum of moderately rugged functions in a few dimensions
CostThousands to hundreds of thousands of evaluations; little work besides evaluating
Read firstBackground: what a minimum looks like, Markov chain Monte Carlo
APISimulatedAnnealing, DifferentialEvolution, ParticleSwarm

Overview

The local methods of this chapter descend into the nearest valley. When has many valleys (an energy landscape of a molecule, the error of a model with many interacting parameters, a design space with competing effects), the nearest minimum is rarely the best. Global methods explore the space more widely, using randomness to escape local minima.

Simulated annealing imitates the slow cooling of a metal: it walks randomly, always accepting downhill moves and sometimes uphill ones, with a willingness to climb that falls as a “temperature” is lowered. Differential evolution and particle swarm optimisation move a whole population of candidate points, combining information between them: differential evolution by adding scaled differences of members, the swarm by pulling each particle towards its own best point and the best point found by any. None is guaranteed to succeed in finite time, and the no free lunch theorems (Wolpert and Macready, 1997) show that no method is best on all problems, but on many practical problems these methods work remarkably well.

Where it is used

Stochastic methods search when the landscape is rugged.

  • Engineering design. Differential evolution and particle swarms tune antennas, controllers, filter coefficients and aerodynamic shapes with many local optima.
  • Scheduling and routing. Simulated annealing is a classic method for the travelling salesman and for placing components on a chip.
  • Physics. The annealing analogy comes from the statistical mechanics of cooling metals.
  • Black-box functions. All of these need only function values.

History

The Metropolis algorithm (Nicholas Metropolis, Arianna and Marshall Rosenbluth, Augusta and Edward Teller, 1953) samples the states of a physical system at a temperature by accepting a proposed change in energy with probability . Scott Kirkpatrick, Daniel Gelatt and Mario Vecchi at IBM (1983), and independently Vlado Černý (1985), turned it into an optimiser by lowering slowly, as in the annealing of metals, and applied it to the travelling salesman problem and chip layout. Stuart and Donald Geman (1984) proved that a logarithmically slow cooling finds the global minimum with probability one, though far too slowly to be practical.

Rainer Storn and Kenneth Price devised differential evolution in 1995 while fitting Chebyshev polynomials, and it did well in the first international contest on evolutionary optimisation in 1996. James Kennedy, a social psychologist, and Russell Eberhart, an electrical engineer, developed particle swarm optimisation the same year from simulations of bird flocking; Maurice Clerc and Kennedy (2002) analysed its dynamics and derived the “constriction” parameters that keep the swarm stable.

The idea

Simulated annealing

A local method only ever moves downhill, so it is trapped by the first valley it enters. Simulated annealing escapes by sometimes accepting a move uphill. From the current point , propose a random neighbour , and let .

  • If the neighbour is better: move there.
  • Otherwise move there anyway with probability .

The parameter is called the temperature, by analogy with the slow cooling (annealing) of a metal, in which atoms jostled by heat find their way to a low-energy crystal. It sets how tolerant the walk is. An uphill move of is accepted with probability at , but with probability at . At high almost every move is accepted and the walk explores the whole landscape freely. As falls, uphill moves become rare, first the large ones and then the small ones, and the walk settles into a deep valley and finally behaves like a local search.

Two details of the library’s version: the neighbour is formed by adding Gaussian noise with standard deviation to every coordinate, so the temperature also sets the step size; and the temperature is multiplied by a fixed cooling factor after each batch of proposals (geometric cooling). Since the walk may leave a good point, the best point ever seen is recorded and returned.

Differential evolution

Differential evolution keeps not one point but a population of points (by default ), initially spread uniformly over the search box. In each generation, every member is challenged by a new candidate built from other members.

  1. Mutation. Pick three other distinct members at random and form the mutant , with . The mutant is a random member displaced by a scaled difference of two others.
  2. Crossover. Build the trial point by taking each coordinate from with probability and otherwise from . At least one coordinate always comes from , so the trial differs from .
  3. Selection. If the trial is no worse than , it replaces it; otherwise survives.

The clever part is the mutation. The method has no step-size parameter to tune, because the differences between members supply the steps. While the population is scattered over the whole box, the differences are large and the search is global. As the population gathers in a valley, the differences shrink, and they also line up with the shape of the valley, so the search becomes local and adapted to the function. This variant is known as DE/rand/1/bin: a random base member, one difference, binomial crossover.

Particle swarm optimisation

A particle swarm is also a population, but its members move continuously and share information. Each particle has a position and a velocity , and remembers the best position it has visited. The swarm as a whole remembers the best position any particle has visited. Each step updates

where are vectors of random numbers, uniform in and drawn afresh for each coordinate, and multiplies vectors coordinate by coordinate. The new velocity is a sum of three tendencies.

  • The inertia term keeps the particle moving in its current direction, which carries it across small bumps.
  • The cognitive term pulls it back towards the best place it has itself seen.
  • The social term pulls it towards the best place anyone has seen.

The random factors keep the particles from all following the same path. The balance of the coefficients matters: with too much inertia the velocities grow without bound, and with too little the swarm collapses at once onto its first good point. Clerc and Kennedy’s analysis gives the values , , which make the swarm converge without exploding.

Comparison

On the Rastrigin function (a bowl covered with a lattice of about local minima) and the Ackley function (a nearly flat plateau with a deep central hole), over 20 runs each from random starting points:

Table 5.12. Global optimisers on multimodal functions.

functionmethodruns reaching median best median evaluations
Rastrigin, Nelder-Mead, random start0 / 201.7e171
Rastrigin, simulated annealing15 / 202.5e-840201
Rastrigin, differential evolution20 / 201.1e-142250
Rastrigin, particle swarm19 / 200.0e05050
Rastrigin, Nelder-Mead, random start0 / 204.6e1314
Rastrigin, simulated annealing0 / 203.0e0100501
Rastrigin, differential evolution20 / 207.1e-1439750
Rastrigin, particle swarm12 / 200.0e020950
Ackley, Nelder-Mead, random start1 / 202.0e172
Ackley, simulated annealing20 / 209.2e-640201
Ackley, differential evolution20 / 201.1e-133040
Ackley, particle swarm20 / 204.4e-167340
Ackley, Nelder-Mead, random start0 / 202.0e1258
Ackley, simulated annealing10 / 201.0e-4100501
Ackley, differential evolution20 / 204.3e-1327325
Ackley, particle swarm20 / 204.0e-1522225

Figure 5.12. Progress on the Rastrigin function.

  • Nelder-Mead, a local method, stops in the first valley it finds, cheaply but almost never at the global minimum.
  • Differential evolution succeeded in every run here, at the cost of tens of thousands of evaluations in five dimensions.
  • The particle swarm is faster but less reliable on Rastrigin in five dimensions, where the swarm sometimes collapses onto a local minimum.
  • Simulated annealing, with the settings shown, does well in two dimensions and poorly in five: its results depend strongly on the temperature schedule, which must be matched to the problem.

Algorithm

Simulated annealing. Input: , a starting point, the temperatures and , a cooling factor below 1 and a number of proposals per temperature.

  1. Set , and record the starting point as the best so far.
  2. Repeat iterations_per_temperature times: propose a neighbour by adding Gaussian noise of standard deviation to each coordinate; accept it if it is better, or otherwise with probability ; if the accepted point is the best seen, record it.
  3. Multiply by the cooling factor. If , go to 2.
  4. Return the best point recorded.

The number of evaluations is fixed in advance by the schedule.

Differential evolution. Input: and a box of bounds.

  1. Draw the population uniformly in the box (the starting point is one member) and evaluate every member.
  2. For each member in turn, build a trial point by mutation and crossover, evaluate it, and let it replace the member if it is no worse.
  3. Stop if the function values of the population agree to within the tolerance, or the limit on generations is reached; otherwise go to 2.
  4. Return the best member.

Each generation costs evaluations.

Particle swarm. Input: and a box of bounds.

  1. Draw positions uniformly in the box, give each particle an initial velocity, evaluate every particle, and record each particle’s best position and the swarm’s best.
  2. For each particle: update its velocity by the formula above, limiting each component to the width of the box; update its position, moving any coordinate that leaves the box back to the boundary; evaluate; update its own best and the swarm’s best.
  3. Stop if the swarm’s best has not improved for stall_iterations iterations, or the iteration limit is reached; otherwise go to 2.
  4. Return the swarm’s best position.

Implementation

                let mut candidate_parameters = generate_candidate_solution(&current_parameters, current_temperature, &mut rng);
                if let Some(b) = bounds.as_ref() {
                    candidate_parameters = project_to_bounds(&candidate_parameters, b); 
                }
                let candidate_objective_value = objective_function.evaluate(&candidate_parameters);
                // 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.
                if candidate_objective_value < result.objective_value {
                    result.parameters = candidate_parameters.clone();
                    result.objective_value = candidate_objective_value;
                }
                // 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.
                if candidate_objective_value < current_objective_value {
                    current_parameters = candidate_parameters;
                    current_objective_value = candidate_objective_value;
                } else {
                    let delta = candidate_objective_value - current_objective_value;
                    let acceptance_probability = (-delta / current_temperature).exp();
                    let sample = rng.next_f64();
                    if sample < acceptance_probability {
                        current_parameters = candidate_parameters;
                        current_objective_value = candidate_objective_value;
                    }   
                }
                let a = pick(&mut rng, &[i]);
                let b = pick(&mut rng, &[i, a]);
                let c = pick(&mut rng, &[i, a, b]);
                let forced = (rng.next_f64() * d as f64) as usize % d;
                let trial: Vec<f64> = (0..d)
                    .map(|j| {
                        if j == forced || rng.next_f64() < self.crossover_probability {
                            let v = population[a][j] + self.differential_weight * (population[b][j] - population[c][j]);
                            let (lo, hi) = bounds[j];
                            // Out of the box: move to a random point between the parent and the bound.
                            if v < lo {
                                lo + rng.next_f64() * (population[i][j] - lo)
                            } else if v > hi {
                                hi - rng.next_f64() * (hi - population[i][j])
                            } else {
                                v
                            }
                        } else {
                            population[i][j]
                        }
                    })
                    .collect();
                let value = objective.evaluate(&trial);
                if value <= values[i] {
                    population[i] = trial;
                    values[i] = value;
                }
                for k in 0..d {
                    let (r1, r2) = (rng.next_f64(), rng.next_f64());
                    let vel = self.inertia * v[i][k] + self.cognitive * r1 * (personal[i][k] - x[i][k]) + self.social * r2 * (best[k] - x[i][k]);
                    v[i][k] = vel.clamp(-width[k], width[k]);
                    x[i][k] = (x[i][k] + v[i][k]).clamp(bounds[k].0, bounds[k].1);
                }
                let value = objective.evaluate(&x[i]);
                if value < personal_value[i] {
                    personal_value[i] = value;
                    personal[i] = x[i].clone();
                }
  • All three are deterministic given a seed: set_seed for simulated annealing (once fixed at 0, with no way to change it), and the seed field for the population methods. Different seeds give independent runs.
  • Differential evolution and particle swarms need finite bounds, given to their constructors; the starting point joins the initial population.
  • Simulated annealing ignores the tolerance; converged means its temperature schedule finished.

In practice

//! Global minimisation of a function with many local minima.
//!
//! Run with `cargo run -p lib_jsl_optimization --example optimization_global`.

use lib_jsl_optimization::differential_evolution::DifferentialEvolution;
use lib_jsl_optimization::nelder_mead_method::NelderMeadMethod;
use lib_jsl_optimization::optimization_traits::{GradientFreeMinimizationEngine, MinimizationControls, ObjectiveFunction};
use lib_jsl_optimization::particle_swarm::ParticleSwarm;
use lib_jsl_optimization::simulated_annealing::SimulatedAnnealing;

/// The Rastrigin function: a bowl covered in ripples, global minimum 0 at the origin and a
/// local minimum near every point of the integer lattice.
struct Rastrigin;
impl ObjectiveFunction for Rastrigin {
    fn evaluate(&self, x: &[f64]) -> f64 {
        10.0 * x.len() as f64 + x.iter().map(|v| v * v - 10.0 * (2.0 * std::f64::consts::PI * v).cos()).sum::<f64>()
    }
}

fn main() {
    let bounds = vec![(-5.12, 5.12); 3];
    let start = vec![3.3, -2.1, 4.4];
    let local = NelderMeadMethod::new().gradient_free_minimize(&Rastrigin, start.clone()).unwrap();
    println!("Nelder-Mead (local): f = {:.4} at {:.3?}", local.objective_value, local.parameters);

    let mut sa = SimulatedAnnealing::new();
    sa.set_bounds(Some(bounds.clone()));
    sa.set_maximum_temperature(Some(3.0));
    sa.set_cooling_coefficient(Some(0.95));
    let r = sa.gradient_free_minimize(&Rastrigin, start.clone()).unwrap();
    println!("simulated annealing: f = {:.2e}", r.objective_value);

    let r = DifferentialEvolution::new(bounds.clone()).gradient_free_minimize(&Rastrigin, start.clone()).unwrap();
    println!("differential evolution: f = {:.2e} after {} generations", r.objective_value, r.iterations);

    let r = ParticleSwarm::new(bounds).gradient_free_minimize(&Rastrigin, start).unwrap();
    println!("particle swarm: f = {:.2e} after {} iterations", r.objective_value, r.iterations);
}

Strengths

  • No derivatives, smoothness or good starting point needed.
  • Can escape local minima; population methods are easily parallelised.

Weaknesses

  • Many evaluations, and no guarantee or certificate of global optimality.
  • Parameters (temperature schedule, population size, , , swarm coefficients) affect success.
  • They are slow to reach high accuracy: polishing the best point with a local method is common.

Exercises

  1. Show that at a fixed temperature the Metropolis acceptance rule leaves the Boltzmann distribution invariant (detailed balance).
  2. Run simulated annealing on the Rastrigin function in five dimensions with cooling factors 0.8, 0.95 and 0.99 and maximum temperatures 1, 3 and 10. Which settings succeed most often?
  3. Vary the differential evolution parameters and on the Rastrigin function and plot the success rate.
  4. Hybridise: run differential evolution for a few generations, then polish the best point with BFGS. Compare evaluations and accuracy with differential evolution alone.
  5. Replace the global best in the particle swarm with the best of each particle’s two neighbours on a ring. How does reliability change?
Hints and answers
  1. With a symmetric proposal, the Metropolis acceptance probability is . Then (both equal ), which is detailed balance and implies invariance.
  2. Slower cooling (0.99) and higher starting temperatures cost more evaluations and typically succeed more often on Rastrigin’s many local minima; count successes over many seeds before comparing, since single runs are noisy.
  3. Tabulate the success rate against both parameters over many seeds. Moderate and a high are common good choices, but the best region depends on the problem and the population size.
  4. Differential evolution finds the right basin cheaply; BFGS then converges to full precision in a few dozen evaluations, so the hybrid usually reaches much higher accuracy for a similar or smaller budget.
  5. A ring topology spreads information slowly, which slows convergence but reduces premature convergence to a poor local minimum, so reliability usually improves on multimodal functions.

Further reading

  • S. Kirkpatrick, C. D. Gelatt and M. P. Vecchi, “Optimization by simulated annealing”, Science 220 (1983) 671–680.
  • R. Storn and K. Price, “Differential evolution: a simple and efficient heuristic for global optimization over continuous spaces”, Journal of Global Optimization 11 (1997) 341–359.
  • J. Kennedy and R. Eberhart, “Particle swarm optimization”, Proceedings of the IEEE International Conference on Neural Networks (1995) 1942–1948.
  • M. Clerc and J. Kennedy, “The particle swarm: explosion, stability, and convergence in a multidimensional complex space”, IEEE Transactions on Evolutionary Computation 6 (2002) 58–73.
  • D. H. Wolpert and W. G. Macready, “No free lunch theorems for optimization”, IEEE Transactions on Evolutionary Computation 1 (1997) 67–82.