Skip to content
Snippets Groups Projects
Commit 6c9aef3e authored by Tong's avatar Tong
Browse files

Test

parent 07ff4ea6
No related branches found
No related tags found
1 merge request!1Test
from pylab import *
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.axes3d import Axes3D
from numpy import asarray
from numpy import exp
from numpy.random import randn
from numpy.random import rand
from numpy.random import seed
xlist=[]
ylist=[]
zlist=[]
xrange = np.linspace(1.1, 5, 100)
yrange = np.linspace(1.1, 5, 100)
X,Y = np.meshgrid(xrange, yrange)
# objective function
def objective(x1,x2):
return x1+x2**2/(x1*x2-1)
Z = objective(X, Y)
# simulated annealing algorithm
def simulated_annealing(objective, bounds, n_iterations, step_size, temp):
# generate an initial point
x_cb = bounds[:, 0] + rand(len(bounds)) * (bounds[:, 1] - bounds[:, 0])
x_cb=[5,5]
# evaluate the initial point
Jx_cb = objective(x_cb[0],x_cb[1])
# current working solution
current, Jcurrent = x_cb, Jx_cb
scores = list()
# run the algorithm
for i in range(n_iterations):
# calculate temperature for current epoch
t = temp / float(i + 1)
# perturb x
x_per = current + randn(len(bounds)) * step_size
# evaluate x_per
Jx_per = objective(x_per[0],x_per[1])
# check for new x_cb solution
if Jx_per < Jx_cb:
# store new x_cb point
x_cb, Jx_cb = x_per, Jx_per
# keep track of scores
scores.append(Jx_cb)
xlist.append(x_cb[0])
ylist.append(x_cb[1])
zlist.append(Jx_cb)
# report progress
print('>%d f(%s) = %.5f' % (i, x_cb, Jx_cb))
# difference between x_per and current point evaluation
diff = Jx_per - Jcurrent
# check if we should keep the new point
if diff < 0 or rand() < exp(-diff / t):
# store the new current point
current, Jcurrent = x_per, Jx_per
return [x_cb, Jx_cb, scores]
# define range for input
bounds = asarray([[1.1, 5.0],[1.1,5.0]])
# define the total iterations
n_iterations = 1000
# define the maximum step size
step_size = 0.1
# initial temperature
temp = 000
# perform the simulated annealing search
x_cb, score, scores = simulated_annealing(objective, bounds, n_iterations, step_size, temp)
print('Done!')
print('f(%s) = %f' % (x_cb, score))
# line plot of x_cb scores
pyplot.plot(scores, '.-')
pyplot.xlabel('Improvement')
pyplot.ylabel('J(x)')
pyplot.show()
fig = plt.figure(figsize=(26,6))
# surface_plot with color grading and color bar
ax = fig.add_subplot(1, 2, 1, projection='3d')
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0, antialiased=False, zorder=0)
ax.plot3D(xlist, ylist,zlist, color="k", marker='o', zorder=10)
ax.view_init(80,30)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment