-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimulatedannealing.py
More file actions
84 lines (74 loc) · 2.77 KB
/
simulatedannealing.py
File metadata and controls
84 lines (74 loc) · 2.77 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
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: William
#
# Created: 15/10/2012
# Copyright: (c) William 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import random, framework, math, os, time
class model:
def __init__(self, problem, coolingRate=0.9, maxSwaps = 40, maxSuccessSwaps = 30, initTemp=100.0):
self.problem = problem
self.coolingRate=coolingRate
self.maxSwaps = maxSwaps
self.maxSuccessSwaps = maxSuccessSwaps
self.initTemp = initTemp
def run(self):
startTimeReal = time.time()
startTimeUser = os.times()[0]
startTimeSys = os.times()[1]
self.longdata = ""
self.T = self.initTemp
self.iternum = 0
self.state = framework.timetable(self.problem)
self.state.setupRandom()
self.state.objective()
self.startState = self.state.obj
self.bestvalue = 100000
self.bestcount = 0
while True:
self.bestcount += 1
self.iteration()
if self.T > 1:
self.bestcount = 0
if self.bestcount > 10:
return self.bestvalue, time.time() - startTimeReal, (os.times()[0] - startTimeUser) + (os.times()[1] - startTimeSys), self.iternum, self.longdata, self.startState, self.best.printMatrix()
def iteration(self):
swaps = 0
successSwaps = 0
while swaps < self.maxSwaps and successSwaps < self.maxSuccessSwaps:
newstate = framework.timetable(self.problem)
newstate.matrix = [x[:] for x in self.state.matrix]
newstate.mutate()
newstate.objective()
if newstate.obj <= self.state.obj:
self.state = newstate
successSwaps += 1
elif random.random() < math.exp(-(newstate.obj-self.state.obj) / self.T):
self.state = newstate
successSwaps += 1
swaps += 1
print "T=" + str(self.T)
print "SuccessSwaps: " + str(successSwaps)
print "Swaps: " + str(swaps)
print self.state.obj
self.longdata += str(self.state.obj) + ","
if self.state.obj < self.bestvalue:
self.bestvalue = self.state.obj
self.best = self.state
self.bestcount = 0
self.iternum += 1
self.cool()
def cool(self):
self.T *= self.coolingRate
def main():
prob = framework.timetableProblem()
prob.setupXML("samplesets/12.xml")
m = model(prob)
print m.run()
if __name__ == '__main__':
main()