-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulatedAnnealing.py
More file actions
89 lines (67 loc) · 2.25 KB
/
SimulatedAnnealing.py
File metadata and controls
89 lines (67 loc) · 2.25 KB
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
84
import random
import math
import numpy as np
class SimulatedAnnealing :
def __init__(self, problem):
self.problem = problem
self.visited = 0
self.extend = 0
self.bestAns = []
self.value = 0
def randomNeighbor(self,currentSol):
"""
:param currentSol: current state
:return: a random neighbor for current state
"""
neighbor = self.problem.neighbors(currentSol)
self.visited= self.visited + 1
return neighbor[0]
def acceptance_probability (self,oldCost,newCost,T) :
"""
:param oldCost: old solution cost
:param newCost: new solution cost
:param T: temerature
:return: a value that decrease depends on time and solution
if the new solution is worse than the old solution it decreases
"""
return (math.exp((newCost - oldCost) / T))
def SimulatedAnnealingAlgorithm (self,start) :
"""
:param start: start state
:return: path to goal state
"""
path = []
sol =[]
oldCost = self.problem.value(start)
T = 1.0
T_min = 0.0001
# alpha = 0.9
alpha = 0.001
# alpha = 20
currentSol = start[:]
iterateNumber = 0
while iterateNumber < 1000 and T > T_min :
iterateNumber = iterateNumber + 1
path.append([currentSol,oldCost])
newSol = self.randomNeighbor(currentSol)[:]
# print("hereeeee",newSol)
newCost = self.problem.value(newSol)
p = self.acceptance_probability(oldCost,newCost,T)
r = random.random()
# print(p,r,newCost,oldCost,newSol)
# print()
if p > r :
# if( newCost > oldCost ) :
print(newSol,'value :' , newCost)
sol.append([newSol,newCost])
self.extend = self.extend + 1
currentSol = newSol[:]
oldCost = newCost
# decrease T by passing time in every iterate
T = T - alpha
# T = T * alpha
max = -1
finalSol = []
self.bestAns = currentSol
self.value = self.problem.value(currentSol)
return finalSol