Skip to content

Instantly share code, notes, and snippets.

@Nagasaki45
Created November 12, 2013 21:53
Show Gist options
  • Save Nagasaki45/7439446 to your computer and use it in GitHub Desktop.
Save Nagasaki45/7439446 to your computer and use it in GitHub Desktop.
Simplest simulated annealing algorithm.
import numpy as np
class Annealer():
def __init__(self, step_function, energy_function):
self.step_function = step_function
self.energy_function = energy_function
def run(
self, state, temperature, room_temperature, cooling_factor
):
best_state = state
energy = self.energy_function(state)
energy_curve = [energy] # tracking convergence
while temperature > room_temperature:
new_state = self.step_function(state)
new_energy = self.energy_function(new_state)
rand = np.random.rand()
if np.exp(-(energy - new_energy) / temperature) > rand:
state = new_state
energy = self.energy_function(state)
if new_energy > energy_curve[-1]:
best_state = new_state
energy_curve.append(new_energy)
temperature *= cooling_factor
return best_state, energy_curve
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment