-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulatedAnnealing.py
69 lines (53 loc) · 1.65 KB
/
SimulatedAnnealing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
""" Implements simulated annealing to find out a string """
import random
import string
import math
all_chars = string.lowercase + string.digits + string.punctuation
rand_str = lambda n: ''.join([random.choice(all_chars) for i in xrange(n)])
objective = rand_str(500)
solution = rand_str(len(objective))
def cost(s):
cost = 0
for i, j in enumerate(s):
if objective[i] != j:
cost += 1
return cost
def fitness(s):
fitness = 0
for i, j in enumerate(s):
if objective[i] == j:
fitness += 1
return fitness
def generate_neighbor(s):
index = random.randint(0, len(s)-1)
# s = s.replace(s[index], random.choice(string.lowercase), 1)
if len(s) == index -1:
s = s[:index] + random.choice(all_chars)
else:
s = s[:index] + random.choice(all_chars) + s[index+1:]
return s
"""def acceptance_prob(c_old, c_new, T): # is using cost, not fitness
return math.e * (c_old-c_new) / T"""
def acceptance_prob(f_new, f_old, T):
return math.e * (f_new-f_old) / T
def anneal(solution):
old_fitness = fitness(solution)
T = 1.0
T_min = 1e-5
alpha = 0.99
iters = 0
while T > T_min:
for i in xrange(250):
new_solution = generate_neighbor(solution)
new_fitness = fitness(new_solution)
a_p = acceptance_prob(new_fitness, old_fitness, T)
if a_p > random.random():
solution, old_fitness = new_solution, new_fitness
i += 1
T *= alpha
iters += 1
if iters % 50 == 0:
print cost(solution)
return solution
solution = anneal(solution)
print cost(solution)