-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulated_annealing.py
88 lines (67 loc) · 2.17 KB
/
simulated_annealing.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*-
"""simulated_annealing.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/16rdBKrPto56m1hWIYIjKmTLM7XBxZmV5
"""
import time
import random
import math
import numpy as np
import matplotlib.pyplot as plt
# Customization section
i_temp = 273 # initial temperature
cool = 10 # cooling coefficient
n_var = 2 # number of variables
u_b = [6,6] # upper bounds
l_b = [-6,-6] # lower bounds
c_time = 0.5 # computing time
def objective_function(X):
x = X[0]
y = X[1]
val = 3*(1-x)**2*math.exp(-x**2 - (y+1)**2) - 10*(x/5 - x**3 - y**5)*math.exp(-x**2 - y**2) -1/3*math.exp(-(x+1)**2 - y**2)
return val
# Simulated Annealing Algorithm
i_sol = np.zeros(n_var) # initial solution
for v in range(n_var):
i_sol[v] = random.uniform(l_b[v],u_b[v])
c_sol = i_sol # current solution
b_sol = i_sol # best solution
n = 1 # no of solutions accepted
best_f = objective_function(b_sol)
c_temp = i_temp # current temperature
start = time.time()
n_attemp = 100 # number of attempts in each level of temperature
rec_best_f = [] # record best fitness
for i in range(9999):
for j in range(n_attemp):
for k in range(n_var):
c_sol[k] = b_sol[k] + 0.1 * (random.uniform(l_b[k],u_b[k]))
c_sol[k] = max(min(c_sol[k], u_b[k]), l_b[k])
c_fit = objective_function(c_sol)
E = abs(c_fit - best_f)
if i==0 and j==0:
EA =E
if c_fit > best_f:
p = math.exp(-E/(EA*c_temp))
# make a decision to accept the worse solution or not
if random.random()<p:
accept=True
else:
accept=False
else:
accept=True
if accept==True:
b_sol = c_sol # update the best solution
best_f = objective_function(b_sol)
n = n+1 # count solutions accepted
EA = (EA * (n-1) + E) / n # update EA
print('iteration: {}, best_solution: {}, best_fitness: {}'.format(i, b_sol, best_f))
rec_best_f.append(best_f)
# Cooling the temperature
c_temp = c_temp * cool
# Stop timer
end = time.time()
if end-start >= c_time:
break
plt.plot(rec_best_f)