-
Notifications
You must be signed in to change notification settings - Fork 8
/
neuralAlgonometry.py
2370 lines (2079 loc) · 75.3 KB
/
neuralAlgonometry.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
# path to latex2sympy. Converts a latex equation to sympy format
sys.path.append('/home/ubuntu/math-knowledge-base/Codes/latex2sympy')
import json
from sympy import *
import pprint
#from process_latex import process_sympy
import re
#from prover import parseEquation
import copy
from itertools import count
import random
import compiler
from collections import deque
import mxnet as mx
import numpy as np
# from nnTreeUtils import nnTree, BucketEqIterator
from nnTreeMain import lstmTreeInpOutMSE, BucketEqIteratorInpOut
import gspread
from oauth2client.service_account import ServiceAccountCredentials
################################################################################
# global recDepth
# global globalCtr
# global maxDepth
functionOneInp = ['sin', 'cos', 'csc', 'sec', 'tan', 'cot',
'asin', 'acos', 'acsc', 'asec', 'atan', 'acot',
'sinh', 'cosh', 'csch', 'sech', 'tanh', 'coth',
'asinh', 'acosh', 'acsch', 'asech', 'atanh', 'acoth',
'exp', 'NumberDecoder']# , 'IdentityFunction', 'root', 'sqrt'
functionOneInpSet = set(functionOneInp)
functionTwoInp = ['Equality', 'Add', 'Mul', 'Pow', 'log']#'Min', 'Max','atan2', 'Div'
functionTwoInpSet = set(functionTwoInp)
functionBothSides = ['Add', 'Mul', 'Pow'] # Anything else?, 'log'
functionBothSidesSet = set(functionBothSides)
variables = ['Symbol']
variablesSet = set(variables)
consts = ['NegativeOne', 'Pi', 'One',
'Half', 'Integer', 'Rational', 'Float']#, 'Float', 'NaN', 'Exp1','Infinity'
constsSet = set(consts)
nums = ['Number']
numsSet = set(nums)
# intList = [0, 2, 3, 4, 10]#, -2, -3]
intList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -2, -3]
intSet = set(intList)
ratList = ['2/5']#, -1/2, 0]
ratSet = set(ratList)
floatList = [0.7]
floatSet = set(floatList)
################################################################################
functionVocab = []
tmp = []
functionVocab.extend(functionOneInp)
functionVocab.extend(functionTwoInp)
functionVocab.extend(functionBothSides)
tmp.extend(functionVocab)
tmp.extend(variables)
tmp.extend(consts)
functionDictionary = {}
ctr = 1
for f in tmp:
functionDictionary[f] = ctr
ctr+=1
################################################################################
# equation functions: #
def saveResults(path, args, tMetrics, vMetrics=[]):
res = {}
if vMetrics==[]:
#we have test only
for met in tMetrics:
# print "met:", met
# print "met0:", met[0]
# print "met1:", met[1]
res[met[0]+'_test'] = met[1]
else:
for tMet, vMet in zip(tMetrics, vMetrics):
res[tMet[0][0]+'_train_final'] = tMet[-1][1]
res[tMet[0][0]+'_dev_final'] = vMet[-1][0]
res[tMet[0][0]+'_train'] = [tm[1] for tm in tMet]
res[vMet[0][0]+'_dev'] = [vm[1] for vm in vMet]
try:
res['args'] = vars(args)
except TypeError:
# print 'there is a TypeError'
res['args'] = 'no args'
with open(path, 'w') as outfile:
json.dump(res, outfile, indent=4)
def dumpParams(args):
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
if args.sheetName != None:
sheet = client.open(args.sheetName).sheet1
else:
raise ValueError("enter sheet name. If you are calling the script just once, uncomment below")
# sheet = client.create("resultsSheet")
# sheet.share('[email protected]', perm_type='user', role='owner')
# args.sheetName = "resultsSheet"
argDict = vars(args)
cellPref = args.cell_prefix
if cellPref == 0:
cell_list = sheet.range(1,2*cellPref+1,len(argDict),2*cellPref+1)
for key, cellP in zip(argDict.keys(), cell_list):
cellP.value = key
sheet.update_cells(cell_list)
cell_list = sheet.range(1,2*cellPref+2,len(argDict),2*cellPref+2)
for key, cellP in zip(argDict.keys(), cell_list):
cellP.value = argDict[key]
sheet.update_cells(cell_list)
else:
cell_list = sheet.range(1,cellPref+2,len(argDict),cellPref+2)
for key, cellP in zip(argDict.keys(), cell_list):
cellP.value = argDict[key]
sheet.update_cells(cell_list)
def updateWorksheet(args, tMetrics, vMetrics=[]):
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
client = gspread.authorize(creds)
sheet = client.open(args.sheetName).sheet1
cellPref = args.cell_prefix
argLen = len(vars(args))
tmLen = len(tMetrics)
if vMetrics != []:
vmLen = len(vMetrics)
#Storing final training results:
if cellPref == 0:
cell_list = sheet.range(argLen+1 , 2*cellPref+1, \
argLen+tmLen , 2*cellPref+1)
for tm, cellP in zip(tMetrics, cell_list):
cellP.value = 'train_'+tm[0][0]
sheet.update_cells(cell_list)
cell_list = sheet.range(argLen+1 , 2*cellPref+2, \
argLen+tmLen , 2*cellPref+2)
for tm, cellP in zip(tMetrics, cell_list):
cellP.value = tm[-1][1]
sheet.update_cells(cell_list)
cell_list = sheet.range(argLen+tmLen+1 , 2*cellPref+1, \
argLen+tmLen+vmLen , 2*cellPref+1)
for vm, cellP in zip(vMetrics, cell_list):
cellP.value = 'val_'+vm[0][0]
sheet.update_cells(cell_list)
cell_list = sheet.range(argLen+tmLen+1 , 2*cellPref+2, \
argLen+tmLen+vmLen , 2*cellPref+2)
for vm, cellP in zip(vMetrics, cell_list):
cellP.value = vm[-1][1]
sheet.update_cells(cell_list)
else:
cell_list = sheet.range(argLen+1 , cellPref+2, \
argLen+tmLen , cellPref+2)
for tm, cellP in zip(tMetrics, cell_list):
cellP.value = tm[-1][1]
sheet.update_cells(cell_list)
cell_list = sheet.range(argLen+tmLen+1 , cellPref+2, \
argLen+tmLen+vmLen , cellPref+2)
for vm, cellP in zip(vMetrics, cell_list):
cellP.value = vm[-1][1]
sheet.update_cells(cell_list)
else:
if cellPref == 0:
cell_list = sheet.range(argLen+2*tmLen+1 , 2*cellPref+1, \
argLen+3*tmLen , 2*cellPref+1)
for tm, cellP in zip(tMetrics, cell_list):
cellP.value = 'test_'+tm[0]
sheet.update_cells(cell_list)
cell_list = sheet.range(argLen+2*tmLen+1 , 2*cellPref+2, \
argLen+3*tmLen , 2*cellPref+2)
for tm, cellP in zip(tMetrics, cell_list):
cellP.value = tm[1]
sheet.update_cells(cell_list)
else:
cell_list = sheet.range(argLen+2*tmLen+1 , cellPref+2, \
argLen+3*tmLen , cellPref+2)
for tm, cellP in zip(tMetrics, cell_list):
cellP.value = tm[1]
sheet.update_cells(cell_list)
def catJsons(inpPaths, outPath, maxDepth):
data = [[] for _ in range(maxDepth+1)]
for path in inpPaths:
with open(path) as data_file:
datain = json.load(data_file)
for i, dat in enumerate(datain):
data[i].extend(dat)
with open(outPath, 'w') as outfile:
json.dump(data, outfile, indent=4)
def catJsonsDepthLimit(inpPaths, outPath, maxDepth):
data = [[] for _ in range(maxDepth+1)]
for path in inpPaths:
with open(path) as data_file:
datain = json.load(data_file)
for i, dat in enumerate(datain):
if i <= maxDepth:
data[i].extend(dat)
with open(outPath, 'w') as outfile:
json.dump(data, outfile, indent=4)
def readJson(path, equations, ranges, jsonAtts):
with open(path) as data_file:
data = json.load(data_file)
for i in range(0,len(data)):
eq = data[i]["equation"]
# print "eq before:", eq
while len(eq)>0 and (eq[-1]=='.' or eq[-1]==',' or eq[-1]=='!' or eq[-1]=='\\'):
# print "here"
eq = eq[:-1]
eq = str(eq.encode("utf-8"))
# print "eq after:", eq
equations.append(eq)
# ranges.append(data[i]["range"])
def writeJson(path, equations, ranges, variables, labels, maxDepth):
data = [[] for _ in range(maxDepth+1)]
for i, eq in enumerate(equations):
depth = eq.depth
d = {}
p = preOrder(eq)
d['equation'] = {'func' : p[0][:-1],
'vars' : p[1][:-1],
'nodeNum' : p[2][:-1],
'depth' : p[3][:-1],
'numNodes' : str(eq.numNodes),
'variables' : variables[i]}
# d['vars'] = p[1][:-1]
# d['nodeNum'] = p[2][:-1]
d['label'] = str(int(labels[i].asnumpy()[0]))
# d['ranges'] = preOrder(ranges[i])
if i==0 and eq.depth>maxDepth:
data[0].append(d)
else:
data[depth].append(d)
# a = [len(data[buck]) for buck in range(len(data))]
# return a
with open(path, 'w') as outfile:
json.dump(data, outfile, indent=4)
def readJsonEquations(path):
equations = []
variables = []
ranges = []
labels = []
with open(path) as data_file:
data = json.load(data_file)
for j in range(len(data)):
dat = data[j]
for i in range(len(dat)):
d = dat[i]
currFunc = d['equation']['func'].split(',')
currVarname = d['equation']['vars'].split(',')
currNumber = d['equation']['nodeNum'].split(',')
currDepth = d['equation']['depth'].split(',')
currVariables = d['equation']['variables']
currNumNodes = int(d['equation']['numNodes'])
currLabel = mx.nd.array([int(d['label'])], dtype='float32')
# currRange = d['range'].split(',')
currEq = makeEqTree(currFunc, currVarname, currNumber, currDepth, currNumNodes)
equations.append(currEq)
# ranges.append(rangeTree)
labels.append(currLabel)
variables.append(currVariables)
return [equations, variables, ranges, labels]
def readAllJsonEquations(path):
with open(path) as data_file:
data = json.load(data_file)
equations = [[] for _ in range(len(data))]
variables = [[] for _ in range(len(data))]
ranges = [[] for _ in range(len(data))]
labels = [[] for _ in range(len(data))]
for j in range(len(data)):
dat = data[j]
for i in range(len(dat)):
d = dat[i]
currFunc = d['equation']['func'].split(',')
currVarname = d['equation']['vars'].split(',')
currNumber = d['equation']['nodeNum'].split(',')
currDepth = d['equation']['depth'].split(',')
currVariables = d['equation']['variables']
currNumNodes = int(d['equation']['numNodes'])
currLabel = mx.nd.array([int(d['label'])], dtype='float32')
# currRange = d['range'].split(',')
currEq = makeEqTree(currFunc, currVarname, currNumber, currDepth, currNumNodes)
equations[j].append(currEq)
# ranges.append(rangeTree)
labels[j].append(currLabel)
variables[j].append(currVariables)
return [equations, variables, ranges, labels]
def readBlockJsonEquations(path, trainDepth=None, testDepth=None, excludeFunc='', splitRatio=0.8, devSplit=0.9, containsNumeric=False):
random.seed(1)
equations = []
variables = []
ranges = []
labels = []
teEquations = []
teVariables = []
teRanges = []
teLabels = []
with open(path) as data_file:
data = json.load(data_file)
if trainDepth!=None:
ind = [0]
ind.extend(trainDepth)
teIn = [0]
teIn.extend(testDepth)
if excludeFunc != '':
#TODO
pass
if trainDepth == testDepth:
trainData = [data[i] for i in ind]
testData = []
elif testDepth not in trainDepth:
trainData = [data[i] for i in ind]
testData = [data[i] for i in teIn]
else:
raise ValueError("unknown input experiment pattern. trainDepth %s, testDepth %s"\
%(str(trainData), str(testDepth)))
else:
trainData = data
testData = []
for j in range(len(trainData)):
dat = trainData[j]
for i in range(len(dat)):
d = dat[i]
currFunc = d['equation']['func'].split(',')
currVarname = d['equation']['vars'].split(',')
currNumber = d['equation']['nodeNum'].split(',')
currDepth = d['equation']['depth'].split(',')
currVariables = d['equation']['variables']
currNumNodes = int(d['equation']['numNodes'])
currLabel = mx.nd.array([int(d['label'])], dtype='float32')
# currRange = d['range'].split(',')
currEq = makeEqTree(currFunc, currVarname, currNumber, currDepth, currNumNodes)
if currEq.isUnique(numList=[]) == False:
# TODO check why this is happening
currEq.enumerize_queue()
if containsNumeric == True:
if j==0:
eqToChange = copy.deepcopy(currEq)
origNode = copy.deepcopy(eqToChange.findNode(106))
child1 = EquationTree(func='Number', varname='1.1')
rootNode = EquationTree(func='Add', args=[child1, origNode])
changedEq = putNodeInTree(eqToChange, rootNode, 106)
changedEq.enumerize_queue()
currEq = copy.deepcopy(changedEq)
equations.append(currEq)
# ranges.append(rangeTree)
labels.append(currLabel)
variables.append(currVariables)
for j in range(len(testData)):
teDat = testData[j]
for i in range(len(teDat)):
d = teDat[i]
currFunc = d['equation']['func'].split(',')
currVarname = d['equation']['vars'].split(',')
currNumber = d['equation']['nodeNum'].split(',')
currDepth = d['equation']['depth'].split(',')
currVariables = d['equation']['variables']
currNumNodes = int(d['equation']['numNodes'])
currLabel = mx.nd.array([int(d['label'])], dtype='float32')
currEq = makeEqTree(currFunc, currVarname, currNumber, currDepth, currNumNodes)
if currEq.isUnique(numList=[]) == False:
# TODO check why this is happening
currEq.enumerize_queue()
if containsNumeric == True:
if j==0:
eqToChange = copy.deepcopy(currEq)
origNode = copy.deepcopy(eqToChange.findNode(106))
child1 = EquationTree(func='Number', varname='1.1')
rootNode = EquationTree(func='Add', args=[child1, origNode])
changedEq = putNodeInTree(eqToChange, rootNode, 106)
changedEq.enumerize_queue()
currEq = copy.deepcopy(changedEq)
teEquations.append(currEq)
# teRanges.append(rangeTree)
teLabels.append(currLabel)
teVariables.append(currVariables)
indices = range(1,len(equations))
random.shuffle(indices)
iind = [0]
iind.extend(indices)
indices = iind
if testData==[]:
"it means that train and test data are random shuffles of input, splitted"
splitInd = int(splitRatio * len(equations))
trInd = indices[:splitInd]
teInd = [0]
teInd.extend(indices[splitInd:])
trainEquations = [equations[i] for i in trInd]
testEquations = [equations[i] for i in teInd]
trainLabels = [labels[i] for i in trInd]
testLabels = [labels[i] for i in teInd]
trainVars = [variables[i] for i in trInd]
testVars = [variables[i] for i in teInd]
# trainRanges = [ranges[i] for i in trInd]
# testRanges = [ranges[i] for i in teInd]
else:
trInd = indices
teInd = range(1,len(teEquations))
random.shuffle(teInd)
iind = [0]
iind.extend(teInd)
teInd = iind
trainEquations = [equations[i] for i in trInd]
testEquations = [teEquations[i] for i in teInd]
trainLabels = [labels[i] for i in trInd]
testLabels = [teLabels[i] for i in teInd]
trainVars = [variables[i] for i in trInd]
testVars = [teVariables[i] for i in teInd]
# trainRanges = [ranges[i] for i in trInd]
# testRanges = [teRanges[i] for i in teInd]
indices = range(1,len(trainEquations))
random.shuffle(indices)
iind = [0]
iind.extend(indices)
indices = iind
splitInd = int(devSplit * len(trainEquations))
trInd = indices[:splitInd]
devInd = [0]
devInd.extend(indices[splitInd:])
trEquations = [trainEquations[i] for i in trInd]
devEquations = [trainEquations[i] for i in devInd]
trLabels = [trainLabels[i] for i in trInd]
devLabels = [trainLabels[i] for i in devInd]
trVars = [trainVars[i] for i in trInd]
devVars = [trainVars[i] for i in devInd]
return [trEquations, trVars, ranges, trLabels,
devEquations, devVars, ranges, devLabels,
testEquations, testVars, ranges, testLabels]
def makeEqTree(func, varname, number, depth, numNodes=-1):
if len(func) == 0:
return
if func[0] != '#':
eq = EquationTree(func=func[0], varname=varname[0], number=int(number[0]), depth=int(depth[0]), args=[])
if numNodes != -1:
eq.numNodes = numNodes
del func[0]
del varname[0]
del number[0]
del depth[0]
eq.args.append(makeEqTree(func, varname, number, depth))
eq.args.append(makeEqTree(func, varname, number, depth))
if eq.args[1] == None:
del eq.args[1]
if eq.args[0] == None:
del eq.args[0]
return eq
else:
del func[0]
del varname[0]
del number[0]
del depth[0]
return
def readAxioms(path, axioms, axiomVariables):
f = open(path, 'r')
for axiom in f:
axiomTree = compiler.parse(axiom)
for i in range(0,3):
# print axiomTree
axiomTree = axiomTree.getChildNodes()[0]
axioms.append(axiomTree)
#extracting variables: Pi will also be a variable resolve this later
extractedVars = re.findall("Name\(.*?\)", str(axiomTree))
var = []
for v in extractedVars:
vsplit = v.split('\'')
var.append(vsplit[1])
# removing repetitions:
var = set(var)
if 'Half' in var:
var.remove('Half')
elif 'Pi' in var:
var.remove('Pi')
var = list(var)
varDict = {'%s'%(e):i for i, e in enumerate(var)}
axiomVariables.append(varDict)
def parseEquation(equations, parsedEquations, variabs):
for ctr in range(len(equations)):
# eq = sympify(equations[ctr], evaluate=False)
eq = process_sympy(equations[ctr])
# print equations[ctr]
# eq = sympify(equations[ctr], evaluate=False)
# eq = sympify(equations[ctr])
var = eq.free_symbols
varDict = {'%s'%(e):i for i, e in enumerate(var)}
parsedEquations.append(eq)
# print variables
variabs.append(varDict)
def parseRange(ranges, parsedRanges, variabs):
for i, rng in enumerate(ranges):
d = {}
for key, val in rng.iteritems():
if key not in variabs[i]:
raise AssertionError('unknown variable %s. Not in the variable dictionary %s' %(key, variabs))
val = val.split(',')
assert len(val) <= 2, 'cannot have more than two inputs to range'
val = [compiler.parse(val[n]) for n in range(len(val))]
for j in range(len(val)):
for k in range(0,3):
val[j] = val[j].getChildNodes()[0]
d[key] = val
parsedRanges.append(d)
def preOrder(equation):
funcStr = equation.func + ','
varStr = equation.varname + ','
numStr = str(equation.number) + ','
depthStr = str(equation.depth) + ','
if len(equation.args) == 0:
funcStr = funcStr + '#,#,'
varStr = varStr + '#,#,'
numStr = numStr + '#,#,'
depthStr = depthStr + '#,#,'
elif len(equation.args) == 1:
p = preOrder(equation.args[0])
funcStr = funcStr + p[0] + '#,'
varStr = varStr + p[1] + '#,'
numStr = numStr + p[2] + '#,'
depthStr = depthStr + p[3] + '#,'
elif len(equation.args) == 2:
p0 = preOrder(equation.args[0])
p1 = preOrder(equation.args[1])
funcStr = funcStr + p0[0] + p1[0]
varStr = varStr + p0[1] + p1[1]
numStr = numStr + p0[2] + p1[2]
depthStr = depthStr + p0[3] + p1[3]
return [funcStr, varStr, numStr, depthStr]
def buildEq(parsedEquation, variables):
# enforces the tree to be binary regardless of the input equation's structure. This
# allows us to do weight sharing as well as incorporating for commutative or associative
# propoerties of addition and multiplication
def expand(parent, children):
# always exapnds in the same order. Does not consider commutativity or associativity
if len(children) > 2:
par = EquationTree(func=parent, args=[buildEq(children[0], variables), expand(parent=parent, children=children[1:])])
else:
par = EquationTree(func=parent, args=[buildEq(arg, variables) for arg in children])
return par
# extracting the function name from the sympy parse
func = str(parsedEquation.func)
func = func.split('.')[-1]
while func[-1]=='\'' or func[-1]=='>':
func = func[:-1]
# pre-order tree generation
# main traversal:
if len(parsedEquation.args) > 2:
root = EquationTree(func=func, args=[buildEq(parsedEquation.args[0], variables), expand(parent=func, children=parsedEquation.args[1:])])
else:
root = EquationTree(func=func, args=[buildEq(arg, variables) for arg in parsedEquation.args])
# base case: leaf
if len(parsedEquation.args)==0:
key = '%s'%(parsedEquation)
# print key
if key in variables:
if key == 'pi' or key == 'Pi':
root.func = 'Pi'
root.varname = 'pi'
else:
root.varname = 'var_%d' %(variables[key])
else:
# note: if we do not do str, it will return the sympy class in the varname
# This could come in handy anyways. I might need to add a node attribute that carries this information.
# also note: for pi, we might want to handle it with hard coding for now.
root.varname = str(parsedEquation)
return root
def buildAxiom(axiomTree, variables):
# pre-processing function to be compatible with the sympy terminology
# This is a temporary hack. Might need to come back to this and make it smarter
# too much hand coding already :/
negOneFlag = 0
func = str(axiomTree)
func = func.split('(')[0]
if func == 'Power':
func = 'Pow'
elif func == 'Const' and axiomTree.getChildren()[0] == 1:
# print "here: functionality is One"
func = 'One'
elif func == 'Const' and axiomTree.getChildren()[0] == -1:
func = 'NegativeOne'
elif func == 'Const':
func = 'Integer'
elif func == 'Name':
if str(axiomTree.getChildren()[0]) == 'Half':
func = 'Half'
elif str(axiomTree.getChildren()[0]) == 'Pi' or str(axiomTree.getChildren()[0]) == 'pi':
func = 'Pi'
else: func = 'Symbol'
elif func == 'UnarySub':
child = axiomTree.getChildren()[0]
childFunc = str(child)
childFunc = childFunc.split('(')[0]
if childFunc == 'Const':
childFunc = 'Integer'
elif childFunc == 'Name':
childFunc = 'Symbol'
if child.getChildren()[0] == 1:
func = 'NegativeOne'
negOneFlag = 1
axiomTree = axiomTree.getChildren()[0]
else:
func = 'Mul'
return EquationTree(func=func,
args=[EquationTree(func='NegativeOne', args=[], varname=str(-1)),
EquationTree(func=childFunc, args=[], varname=str(child.getChildren()[0]))])
# else:
# print "I have found an undefined category:", func, axiomTree.getChildren()[0]
children = axiomTree.getChildren()
if len(children) == 1 and (isinstance(children[0], int) or isinstance(children[0], str)):
# print "in leaf"
if (func not in functionOneInpSet) and (func not in functionTwoInpSet) and (func not in variablesSet) and (func not in constsSet):
raise AssertionError("found an undefined category", func)
root = EquationTree(func=func, args=[])
key = children[0]
if key == 'Half':
root.varname = '1/2'
elif key == 'Pi' or key=='pi':
root.varname = 'pi'
elif key in variables:
root.varname = 'var_%d' %(variables[key])
elif negOneFlag:
root.varname = str(-1)
else:
root.varname = str(key)
return root
if func == 'Compare' and children[1] == '==':
func = 'Equality'
root = EquationTree(func=func, args =[buildAxiom(children[0], variables), buildAxiom(children[2], variables)])
elif func == 'Sub':
func = 'Add'
childchild1 = EquationTree(func='NegativeOne', args=[], varname=str(-1))
child1 = EquationTree(func='Mul', args=[childchild1, buildAxiom(children[1], variables)])
root = EquationTree(func=func, args=[buildAxiom(children[0], variables), child1])
elif func == 'Compare' and children[1] != '==':
func = 'Equality'
raise AssertionError('comparison other than equality is not currently supported')
else:
root = EquationTree(func=func, args =[buildAxiom(arg, variables) for arg in children])
if (func not in functionOneInpSet) and (func not in functionTwoInpSet) and (func not in variablesSet) and (func not in constsSet):
raise AssertionError("found an undefined category", func)
return root
# TODO: take this inside matchSubTree:
def matchLeaves(eqTree, subTree):
# boolean function
# indicates if two leaves match
# a leaf can only match a leaf
eqTreeCopy = copy.deepcopy(eqTree)
subTreeCopy = copy.deepcopy(subTree)
if subTreeCopy.isLeaf() == False:
return False
elif eqTreeCopy.func in variablesSet:
# TODO: if the equation is a variable we can replace it with any leaf node as long as we
# replace all the instances of that variable with the same symbol and then do the new node
# replacement in the tree
# right now it only matches to a symbol
if subTreeCopy.func == eqTreeCopy.func:
return True
else:
return False
elif eqTreeCopy.func in constsSet:
if (subTreeCopy.func == eqTreeCopy.func) and (subTreeCopy.varname == eqTreeCopy.varname):
return True
else:
return False
else:
# print "eqTreeCopy functionality: ", eqTreeCopy.func
# print "subTreeCopy functionality: ", subTreeCopy.func
raise AssertionError("we cannot end up here")
def mapLeaveVars(eqTree, subTree):
lMapping={}
eqTreeCopy = copy.deepcopy(eqTree)
subTreeCopy = copy.deepcopy(subTree)
# Note if the symbol on the rhs and lhs of the equation
# were non-matching this will not work and we might want to do the varname
# lookup
if eqTreeCopy.func in variablesSet:
lMapping[subTreeCopy] = copy.deepcopy(eqTreeCopy)
# print "lMapping:"
# for k, v in lMapping.iteritems():
# print "k:", k, ": v:", v
return lMapping
# TODO: take this inside matchSubTree:
def matchTrees(eqTree, subTree):
# boolean function
# indicate if subTree is a sub tree of the equation tree
# TODO: if there are several instances of the same variable in the subTree,
# it should make sure that the eqTree also has these shared
# simple test case for this situation is the RHS of:
# (x + y) * z == (x * z) + (y * z)
eqTreeCopy = copy.deepcopy(eqTree)
subTreeCopy = copy.deepcopy(subTree)
if subTreeCopy.isLeaf():
if subTreeCopy.func in variablesSet:
# be careful with this. Yes this is matching (x + y) to (x + x) :|
return True
elif subTreeCopy.func in constsSet:
if subTreeCopy.func == eqTreeCopy.func and subTreeCopy.varname == eqTreeCopy.varname:
# print "subTreeCopy True: ", subTreeCopy.varname, "eqTreeCopy True: ", eqTreeCopy.varname
return True
# elif subTreeCopy.func == eqTreeCopy.func:
# print "subTreeCopy False: ", subTreeCopy.varname, "eqTreeCopy False: ", eqTreeCopy.varname
# raise AssertionError(
# "something weird is going on, constants have the same functionality but",
# "different values. This could be because we have an integer. check ")
# return False
else: return False
else:
raise AssertionError("undefined functionality in the leaf:", subTreeCopy.func)
# print len(eqTreeCopy.args)
# print subTreeCopy.func
# print eqTreeCopy.func
if eqTreeCopy.func == subTreeCopy.func:
assert len(eqTreeCopy.args) == len(subTreeCopy.args), "same functions cannot have different no of args"
match = True
for i in range(0, len(eqTreeCopy.args)):
match = match and matchTrees(eqTreeCopy.args[i], subTreeCopy.args[i])
if match == True:
# corner case for when the children are the same
# (x + x) == 2 * x should not match to (x + y)
if len(eqTreeCopy.args) == 2 and \
str(subTreeCopy.args[0]) == str(subTreeCopy.args[1]):
if str(eqTreeCopy.args[0]) != str(eqTreeCopy.args[1]):
match = False
elif len(eqTreeCopy.args) == 2 and \
str(eqTreeCopy.args[0]) == str(eqTreeCopy.args[1]):
if str(subTreeCopy.args[0]) != str(subTreeCopy.args[1]):
match = False
else:
match = False
return match
def mapTreeVars(eqTree, subTree, tMapping):
# Note if the symbol on the rhs and lhs of the equation
# were non-matching this will not work and we might want to do the varname
# lookup
eqTreeCopy = copy.deepcopy(eqTree)
subTreeCopy = copy.deepcopy(subTree)
if len(subTreeCopy.args)==0:
tMapping[subTreeCopy] = eqTreeCopy
# tMapping[subTree.varname] = copy.deepcopy(eqTree)
return tMapping
assert len(eqTreeCopy.args)==len(subTreeCopy.args), "reported match is incorrect"
for i in range(0, len(subTreeCopy.args)):
tMapping = mapTreeVars(eqTreeCopy.args[i], subTreeCopy.args[i], tMapping)
# print "tMapping:"
# for k, v in tMapping.iteritems():
# print "k:", k, ": v:", v
return tMapping
def matchSubTree(eqTree, mathDictionary):
# Call on subtree to find a match in the dictionary
eqTreeCopy = copy.deepcopy(eqTree)
matches = {}
varMap = {}
leafFlag = eqTreeCopy.isLeaf()
for key, value in mathDictionary.iteritems():
if leafFlag:
if matchLeaves(eqTreeCopy, key):
matches[key] = copy.deepcopy(value)
varMap[key] = copy.deepcopy(mapLeaveVars(eqTreeCopy, key))
else:
if eqTreeCopy.func != key.func:
continue
elif matchTrees(eqTreeCopy, key):
matches[key] = copy.deepcopy(value)
varMap[key] = copy.deepcopy(mapTreeVars(eqTreeCopy, key, tMapping={}))
return matches, varMap
def putNodeInTree(eqTree, newNode, nodeNum):
newNodeCopy = copy.deepcopy(newNode)
if len(eqTree.args) == 0:
#base case: leaf
if eqTree.number == nodeNum:
newRoot = newNodeCopy
else:
newRoot = copy.deepcopy(eqTree)
else:
newRoot = copy.deepcopy(eqTree)
newRoot.args = []
for arg in eqTree.args:
if arg.number==nodeNum:
newRoot.args.append(newNodeCopy)
else:
newRoot.args.append(putNodeInTree(arg, newNodeCopy, nodeNum))
return newRoot
def putSubtreeInTree(eqTree, node, pattern, sub, nodeNum, mapping):
# This code replaces the 'eqTree's 'node' numbered 'nodeNum', whose pattern is 'pattern',
# with 'sub'. 'mapping' is the mapping from the sub variables to the eqTree variables
subCCopy = copy.deepcopy(sub)
def correctSub(sub, mapping):
sebCopy = copy.deepcopy(sub)
if len(sebCopy.args) == 0:
# print "sebCopy:", sebCopy, isinstance(sebCopy, EquationTree)
# print "mapping:", mapping
for k, v in mapping.iteritems():
if sebCopy == k:
return copy.deepcopy(mapping[k])
# print "var:", k, isinstance(k, EquationTree)
# print "are they equal?:", sebCopy == k
return sebCopy
else:
newSub = copy.deepcopy(sebCopy)
newSub.args = []
for arg in sebCopy.args:
newSub.args.append(correctSub(arg, mapping))
return newSub
if mapping == {}:
newSub = subCCopy
else:
newSub = correctSub(subCCopy, mapping)
newRoot = putNodeInTree(eqTree, newSub, nodeNum)
return newRoot
def genPosEquation(eqTree, mathDictionary, eqVars):
eq = copy.deepcopy(eqTree)
#randomly choose a node to change:
# print "equation:", eq
# print "number of nodes:", eq.numNodes
nodeNum = random.randrange(0, eq.numNodes)
dummy = EquationTree(args=[eq])
# alter the node:
node = dummy.findNode(nodeNum)
if node == None:
print "node number to look for:", nodeNum
print "node is none. Traversing the equation:"
eq.preOrder()
print "also traversing the original equation:"
eqTree.preOrder()
raise AssertionError, "node should not be none. There is a problem with numbering"
# print "node functionality: ", node.func
# print "equation:", eqTree
if nodeNum == 0:
"grow sides"
newEq = node.growBothSides(eqVars)
if not isinstance(newEq, EquationTree):
raise AssertionError("newNode is not of type EquationTree")
else:
# print "found node:", node
# print "nodeNumber:", nodeNum
matches, varMatchMap = matchSubTree(node, mathDictionary)
while matches == {}:
nodeNum = random.randrange(1, eq.numNodes)
node = dummy.findNode(nodeNum)
if node == None:
print "In inner loop: node number to look for:", nodeNum
print "node is none. Traversing the equation:"
eq.preOrder()
print "also traversing the original equation:"
eqTree.preOrder()
raise AssertionError, "node should not be none. There is a problem with numbering"
matches, varMatchMap = matchSubTree(node, mathDictionary)
# for key, value in matches.iteritems():
# vard = varMatchMap[key]
# print "key:", key, ": value :", value
# print "varKey:", key
# for k, v in vard.iteritems():
# print "k", k, ": v", v
# print "another printing method just to check:"
# for key, value in varMatchMap.iteritems():
# print "key:", key
# print "val:", value
# choose a match randomly:
match, sub = random.choice(list(matches.items()))
varMapFinal = varMatchMap[match]
# print "match:", match
# print "sub:", sub
# for k, v in varMapFinal.iteritems():
# print "key:", k, "value:", v
# replace the match into the tree
newEq = putSubtreeInTree(eq, node, match, sub, nodeNum, varMapFinal)
return newEq
def genNegEquation(eqTree, eqTreeVariables):
# global recDepth
eq = copy.deepcopy(eqTree)
#randomly choose a node to change:
nodeNum = random.randrange(1, eq.numNodes) # we don't want to choose the root
# find the node:
dummy = EquationTree(args=[eq])
# alter the node:
node = dummy.findNode(nodeNum)
if node == None:
print "node number to look for:", nodeNum
print "node is none. Traversing the equation:"
eq.preOrder()
raise AssertionError, "node should not be none. There is a problem with numbering"
# if nodeNum == 0:
# newEq = node.growBothSides()
# if not isinstance(newEq, EquationTree):
# raise AssertionError("newNode is not of type EquationTree")
# else:
# recDepth = count()
newNode = node.changeNode(eqTreeVariables)
# traverse and replace the new node:
newEq = putNodeInTree(eq, newNode, nodeNum)
if not isinstance(newNode, EquationTree):
# print newNode
raise AssertionError("newNode is not of type EquationTree")
# after insertion of the new nodes numberings have changed
globarCtr = count()
newEq.enumerize()
return newEq