robertness
6/27/2014 - 2:04 PM

R implementation of Simulated Annealing

R implementation of Simulated Annealing

simulatedAnnealing <- function(s0, kMax, eMax, getNeighbor, getEnergy, getAcceptanceProb){
  #s0: initial state
  #kMax: Max desired number of iterations
  #eMax: Max desired energy
  #getNeighbor, getEnergy, getAcceptanceProb: neighborhood, energy, and acceptance prob functions, respectively
  #Returns a list with the best state, the number of iterations reached before annealing stopped, and the lowest energy when stopped.
  s <- s0
  e <- getEnergy(s)
  sBest <- s
  eBest <- e
  k <- 1
  while(k <= kMax && e > eMax){
    temp <- getTemp(k / kMax)
    sNew <- getNeighbor(s)
    eNew <- getEnergy(snew)
    prob <- getAcceptanceProb(e, eNew, temp)
    if(prob > runif(1)){
      s <- sNew
      e <- eNew
    }
    if(enew < ebest){
      sBest <- sNew
      eBest <- eNew 
    }
    k <- k + 1
  }
  list(state = sBest, iterations = k, final.energy = eMax)
}