-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulatedAnnealing.py
More file actions
58 lines (38 loc) · 1.3 KB
/
Copy pathsimulatedAnnealing.py
File metadata and controls
58 lines (38 loc) · 1.3 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
import numpy.random as rn
import math
import numpy as np
"""
The algorithm gets a problem, that must have the methon energyFunction and a range of possible inputs
"""
def simulatedAnnealing(problem, inMax, inMin, steps=50000):
interval = inMax - inMin
neightborhood = interval // 4
energy = []
states = []
temps = []
tMax = 25000
tMin = 2.5
# precalcs...
tFactor = - math.log(tMax/tMin)
# Initial state
t = tMax
currentState = rn.randint(inMin, inMax) #Initial state
for step in range(steps):
currentEnergy = problem.energyFunction(currentState)
nextState = rn.randint( currentState - neightborhood, currentState + neightborhood )
nextState = max(inMin, nextState) # Bound the nextState inside the available problem's interval
nextState = min(inMax, nextState)
#print("currentState {} nextState {}".format(currentState, nextState))
nextEnergy = problem.energyFunction(nextState)
deltaE = nextEnergy - currentEnergy
if deltaE > 0:
currentState = nextState
elif (np.exp( - deltaE / t) > rn.random()):
currentState = nextState
# Update the temp:
t = tMax * math.exp(tFactor * step / steps)
# Statistics for the algorithm
temps.append(t)
energy.append(problem.energyFunction(currentState))
states.append(currentState)
return currentState, energy, states, temps