-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMLHeuristic.py
217 lines (180 loc) · 5.74 KB
/
MLHeuristic.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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import sys
import time
from heapq import *
import AST
import numpy as np
import multiprocessing as m
import json
from parser import Parser
def depthH(node, target):
return abs(node.depth() - target.depth())
targetOpDict = None
def numOpsH(node, target):
global targetOpDict
if targetOpDict == None:
targetOpDict = target.numOps()
nodeOpDict = node.numOps()
commonKeys = set(targetOpDict.keys()) | set(nodeOpDict.keys())
total = 0
for key in commonKeys:
keyCount = 0
if key in nodeOpDict:
keyCount = nodeOpDict[key]
if key in targetOpDict:
keyCount = abs(targetOpDict[key] - keyCount)
total += keyCount
return total
def countConsts(node):
if isinstance(node, AST.Const):
return 1
if isinstance(node, AST.BinaryOp):
return countConsts(node.getFirstChild()) + countConsts(node.getSecondChild())
return countConsts(node.getChild())
def constH(node, target):
return abs(countConsts(target) - countConsts(node))
def heur(s, t, h, w):
v = np.array([hi(s, t) for hi in h])
return np.matrix.dot(v, w)
def search(start, target, heurs, weights, pr=True):
heap = []
score = heur(start, target, heurs, weights)
heappush(heap, (score, [start, None]))
found = False
visited = {}
last = None
if start == target:
found = True
last = [target, None]
startDepth = start.depth()
targetDepth = target.depth()
maxDepth = max(startDepth, targetDepth) + np.sqrt(startDepth + targetDepth)
while (not found) and len(heap)>0:
node = heappop(heap)
node = node[1]
allNeigh = node[0].getNeighbors()
neigh = list(filter(lambda x: x.depth() < maxDepth, allNeigh))
for n in neigh:
if n==target:
found = True
last = [target, node]
break
elif str(n) not in visited:
visited[str(n)] = True
score = heur(n, target, heurs, weights)
item = (score, [n, node])
heappush(heap, item)
if last==None:
if pr:
print('The expressions are not logically equivalent.')
return found
else:
if pr:
print('Path found! The expressions are logically equivalent!')
AST.printPath(last)
return found
# def printPath(node):
# if node[1]==None:
# print(node[0])
# else:
# printPath(node[1])
# print(node[0])
def newPop(population, scores):
choose = []
for i in range(5):
choose.append(heappop(scores)[1].array)
pop = [c for c in choose]
for i in range(40):
old = np.random.choice(range(len(choose)))
old = choose[old]
mute = np.multiply(np.random.choice([-1, 1], size=3), 3)
pop.append(np.add(old, mute))
for i in range(5):
pop.append(np.random.rand(1, 3)[0])
return pop
class StupidArray:
def __init__(self, a):
self.array = a
def __lt__(self, other):
return 0
def __str__(self):
return str(self.array)
def __repr__(self):
return str(self.array)
def train():
training = [
('(avb)vc', 'av(bvc)'),
('~(p->q)', 'p^~q'),
('~(pv(~p^q))', '~p^~q'),
('(p^q)->(pvq)', 'T'),
('(pvq)^((~pvr)->(pvq))', 'T')
]
results = {}
par = Parser()
train = [(par.parse(t[0]), par.parse(t[1])) for t in training]
population = np.random.rand(50, 3)*10 #3 is number of heuristics
best = []
searchTimeout = 10 # In seconds
for i in range(20):
best = []
for p in population:
score = 0
for t in train:
start = t[0]
target = t[1]
searchProcess = m.Process(target=search, args=(start, target, [depthH, numOpsH, constH], p, False))
s = time.time()
searchProcess.start()
searchProcess.join(searchTimeout)
# res = search(start, target, [depthH, numOpsH, constH], p, False)
e = time.time()
if searchProcess.is_alive():
searchProcess.terminate()
score += 100
print("search did not terminate in time")
else:
score += e-s
print(score)
heappush(best, (score, StupidArray(p)))
smallest = nsmallest(45, best)
smallest = [i[0] for i in smallest]
results[i] = smallest
population = newPop(population, best)
print(nsmallest(1, best))
print("%s done" % i)
times = []
for t in train:
s = time.time()
res = search(t[0], t[1], [depthH, numOpsH, constH], best[0][1].array)
e = time.time()
times.append(e-s)
print("Avg time: %s" % np.mean(times))
print("Weights: %s" % best[0][1].array)
with open('mL_res.json', 'w') as file:
file.write(json.dumps(results))
#[ 0.90416266 0.60873807 -0.97709181]
#[ 15.33613225 22.53582815 -19.79393251]
def runWeightedSearch(start, end, weights):
'''
#Test result:
cases = [
('(avb)vc', 'av(bvc)'),
('~(p->q)', 'p^~q'),
('~(pv(~p^q))', '~p^~q'),
('(p^q)->(pvq)', 'T'),
('(pvq)^((~pvr)->(pvq))', 'T')
]
'''
p = Parser()
startp = p.parse(start)
targetp = p.parse(end)
s = time.time()
res = search(startp, targetp, [depthH, numOpsH, constH], weights)
e = time.time()
if __name__ == '__main__':
if len(sys.argv) == 1:
train()
elif len(sys.argv) == 6:
weights = [float(w) for w in sys.argv[3:]]
runWeightedSearch(sys.argv[1], sys.argv[2], weights)
else:
print("Invalid number of arguments")