-
Notifications
You must be signed in to change notification settings - Fork 0
/
sa.py
54 lines (36 loc) · 1.15 KB
/
sa.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
import numpy as np
import random
import math
from initialization import initial_cnf
from cnf_functions import cnf_eval
def schedule(t, alpha):
"""
manipulate the tempature in a linear manner
"""
return t - alpha
def child_generator(parent):
index = random.randint(0, len(parent) - 1)
parent[index] *= -1
return parent
def simulated_anealing(root, cnf):
t = 400
current = root
alpha = 2
while t > alpha:
current_evaluation = cnf_eval(cnf, current)
if current_evaluation[0]:
return current
t = schedule(t, alpha)
child = child_generator(root)
child_evaluation = cnf_eval(cnf, child)
delta_e = child_evaluation[1] - current_evaluation[1]
if delta_e > 0 or random.random() < math.exp((-1 * abs(delta_e)) / t):
print(child_evaluation[1])
current = child
return current
def run():
cnf, (m, n) = initial_cnf()
root = np.ones(100)
solution = simulated_anealing(root, cnf)
print("final solituon : ",solution)
print("count : ", cnf_eval(cnf, solution)[1])