Created
January 8, 2014 16:52
-
-
Save derrickturk/8320041 to your computer and use it in GitHub Desktop.
A simple generic simulated annealing solver, and basic implementations of the "standard" acceptance probability function and exponential-decay temperature schedules.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import Random | |
import math | |
def anneal(initial, energyfn, candidatefn, acceptancefn, temperaturefn, tmax): | |
rand = Random() | |
t = 0 | |
solution = initial | |
s_best = initial | |
e_best = energyfn(initial) | |
while (t <= tmax): | |
temp = temperaturefn(float(t) / tmax) | |
candidate = candidatefn(solution) | |
e_cur = energyfn(solution) | |
e_cand = energyfn(candidatefn) | |
p_accept = acceptancefn(e_cur, e_cand, temp) | |
if rand.random() <= p_accept: | |
solution = candidate | |
if e_cand < e_best: | |
s_best = candidate | |
e_best = e_cand | |
t += 1 | |
return s_best | |
def standard_accept(e_cur, e_cand, temp): | |
if e_cand <= e_cur: | |
return 1 | |
if temp <= 0: | |
return 0 | |
return math.exp(-(e_cand - e_cur)/temp) | |
def exp_decay(initial, decay_const=5, zero_threshold=0.95): | |
def f(t_frac): | |
if t_frac >= zero_threshold: | |
return 0.0 | |
return initial * math.exp(-decay_const * t_frac) | |
return f |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment