-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKLEE_SearchMC.py
1642 lines (1491 loc) · 68.4 KB
/
KLEE_SearchMC.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
#!/usr/bin/env python3
import os
import math
import subprocess
import argparse
import random
import z3
import time
import pyparma
from scipy.optimize import minimize
from fractions import Fraction
import numpy as np
import cvxpy as cp
all_var_names = set()
total_solving_time = 0
############################Get model counts##########################
define_text = ""
def calculate_domain_size_ABC(directory, bit_size):
global define_text
max_num_var = 0
for root,_,files in os.walk(directory):
for file in files:
if file[-4:] == "smt2":
abs_path = os.path.abspath(os.path.join(root, file))
f = open(abs_path, "r")
cons = f.read();
f.close()
cons = cons.split("----")[0]
num_var = cons.count("declare-fun")
print(num_var)
if num_var > max_num_var:
max_num_var = num_var
define_text = cons.split("(assert ")[0].split("\n")[1]
print("define text: " + define_text)
print(max_num_var)
return (2 ** bit_size) ** max_num_var
def add_unexplored_path(directory):
declarations = set()
assertions = set()
unnegated_assertions = set()
for root,_,files in os.walk(directory):
for file in files:
if file[-4:] == "smt2" and file != "unexplored.smt2":
abs_path = os.path.abspath(os.path.join(root, file))
f = open(abs_path, "r")
cons = f.read()
f.close()
if "Int" not in cons:
lines = cons.split('\n')
assertion = ""
for line in lines:
if line.startswith("(declare-fun"):
declarations.add(line)
elif line.startswith("(assert"):
if assertion == "":
assertion = line[len("(assert ") : -1]
else:
assertion = "(and {} {})".format(assertion, line[len("(assert ") : -1])
assertions.add(assertion)
else:
i = cons.find("declare-fun")
while i != -1:
left_paren_index = i - 1
paren_counter = 1
right_paren_index = i
while paren_counter > 0 :
if cons[right_paren_index] == '(':
paren_counter += 1
right_paren_index += 1
elif cons[right_paren_index] == ')':
paren_counter -= 1
if paren_counter == 0:
break
right_paren_index += 1
else:
right_paren_index += 1
declarations.add(cons[left_paren_index : right_paren_index + 1])
i = cons.find("declare-fun", right_paren_index)
i = cons.find("assert")
assertion = ""
while i != -1:
left_paren_index = i - 1
paren_counter = 1
right_paren_index = i
while paren_counter > 0 :
if cons[right_paren_index] == '(':
paren_counter += 1
right_paren_index += 1
elif cons[right_paren_index] == ')':
paren_counter -= 1
if paren_counter == 0:
break
right_paren_index += 1
else:
right_paren_index += 1
curr_assertion = cons[left_paren_index : right_paren_index + 1]
#print(curr_assertion)
if "127" in curr_assertion or "128" in curr_assertion: #temp fix
unnegated_assertions.add(curr_assertion)
else:
curr_assertion = curr_assertion[len("(assert ") : -1]
if assertion == "":
assertion = curr_assertion
else:
assertion = "(and {} {})".format(assertion, curr_assertion)
i = cons.find("assert", right_paren_index)
assertions.add(assertion)
unexplored = ""
unexplored += ";1000000\n"
if "Int" not in cons:
unexplored += "(set-logic QF_AUFBV)\n"
for declaration in declarations:
unexplored += declaration
unexplored += "\n"
unexplored_cons = ""
for assertion in assertions:
if unexplored_cons == "":
unexplored_cons = assertion
else :
unexplored_cons = "(or {} {})".format(unexplored_cons, assertion)
unexplored_cons = "(assert (not {}))".format(unexplored_cons)
unexplored_cons += "".join(unnegated_assertions)
unexplored += unexplored_cons
unexplored += "\n"
#if domain_size == 256:
# unexplored += "\n(let ( (?B1 (concat (select x (_ bv3 32) ) (concat (select x (_ bv2 32) ) (concat (select x (_ bv1 32) ) (select x (_ bv0 32) ) ) ) ) ) )"
# unexplored += "(and (bvsle (_ bv0 32) ?B1 ) (bvslt ?B1 (_ bv256 32) ) ) (bvsle (_ bv16 32) ?B1 ) )\n"
# For pinchecker binary
# unexplored += "(assert (let ( (?B1 ((_ sign_extend 24) (select h (_ bv2 32) ) ) ) (?B2 ((_ sign_extend 24) (select l (_ bv2 32) ) ) ) (?B3 ((_ sign_extend 24) (select h (_ bv0 32) ) ) ) (?B4 ((_ sign_extend 24) (select l (_ bv0 32) ) ) ) (?B5 ((_ sign_extend 24) (select l (_ bv1 32) ) ) ) (?B6 ((_ sign_extend 24) (select h (_ bv1 32) ) ) ) (?B7 ((_ sign_extend 24) (select l (_ bv5 32) ) ) ) (?B8 ((_ sign_extend 24) (select h (_ bv5 32) ) ) ) (?B9 ((_ sign_extend 24) (select l (_ bv3 32) ) ) ) (?B10 ((_ sign_extend 24) (select l (_ bv4 32) ) ) ) (?B11 ((_ sign_extend 24) (select h (_ bv4 32) ) ) ) (?B12 ((_ sign_extend 24) (select h (_ bv9 32) ) ) ) (?B13 ((_ sign_extend 24) (select h (_ bv3 32) ) ) ) (?B14 ((_ sign_extend 24) (select l (_ bv9 32) ) ) ) (?B15 ((_ sign_extend 24) (select h (_ bv7 32) ) ) ) (?B16 ((_ sign_extend 24) (select h (_ bv6 32) ) ) ) (?B17 ((_ sign_extend 24) (select l (_ bv7 32) ) ) ) (?B18 ((_ sign_extend 24) (select l (_ bv8 32) ) ) ) (?B19 ((_ sign_extend 24) (select h (_ bv8 32) ) ) ) (?B20 ((_ sign_extend 24) (select l (_ bv6 32) ) ) ) (?B21 ((_ sign_extend 24) (select l (_ bv10 32) ) ) ) (?B22 ((_ sign_extend 24) (select h (_ bv12 32) ) ) ) (?B23 ((_ sign_extend 24) (select l (_ bv12 32) ) ) ) (?B24 ((_ sign_extend 24) (select l (_ bv11 32) ) ) ) (?B25 ((_ sign_extend 24) (select h (_ bv11 32) ) ) ) (?B26 ((_ sign_extend 24) (select h (_ bv10 32) ) ) ) (?B27 ((_ sign_extend 24) (select h (_ bv14 32) ) ) ) (?B28 ((_ sign_extend 24) (select l (_ bv14 32) ) ) ) (?B29 ((_ sign_extend 24) (select l (_ bv15 32) ) ) ) (?B30 ((_ sign_extend 24) (select h (_ bv15 32) ) ) ) (?B31 ((_ sign_extend 24) (select h (_ bv13 32) ) ) ) (?B32 ((_ sign_extend 24) (select l (_ bv13 32) ) ) ) (?B33 ((_ sign_extend 24) (select h (_ bv18 32) ) ) ) (?B34 ((_ sign_extend 24) (select l (_ bv18 32) ) ) ) (?B35 ((_ sign_extend 24) (select h (_ bv16 32) ) ) ) (?B36 ((_ sign_extend 24) (select l (_ bv16 32) ) ) ) (?B37 ((_ sign_extend 24) (select h (_ bv17 32) ) ) ) (?B38 ((_ sign_extend 24) (select l (_ bv17 32) ) ) ) (?B39 ((_ sign_extend 24) (select h (_ bv21 32) ) ) ) (?B40 ((_ sign_extend 24) (select h (_ bv22 32) ) ) ) (?B41 ((_ sign_extend 24) (select l (_ bv22 32) ) ) ) (?B42 ((_ sign_extend 24) (select l (_ bv19 32) ) ) ) (?B43 ((_ sign_extend 24) (select h (_ bv19 32) ) ) ) (?B44 ((_ sign_extend 24) (select l (_ bv20 32) ) ) ) (?B45 ((_ sign_extend 24) (select l (_ bv21 32) ) ) ) (?B46 ((_ sign_extend 24) (select h (_ bv20 32) ) ) ) (?B47 ((_ sign_extend 24) (select l (_ bv24 32) ) ) ) (?B48 ((_ sign_extend 24) (select h (_ bv24 32) ) ) ) (?B49 ((_ sign_extend 24) (select l (_ bv25 32) ) ) ) (?B50 ((_ sign_extend 24) (select h (_ bv25 32) ) ) ) (?B51 ((_ sign_extend 24) (select h (_ bv23 32) ) ) ) (?B52 ((_ sign_extend 24) (select l (_ bv23 32) ) ) ) (?B53 ((_ sign_extend 24) (select h (_ bv28 32) ) ) ) (?B54 ((_ sign_extend 24) (select l (_ bv28 32) ) ) ) (?B55 ((_ sign_extend 24) (select h (_ bv27 32) ) ) ) (?B56 ((_ sign_extend 24) (select l (_ bv27 32) ) ) ) (?B57 ((_ sign_extend 24) (select l (_ bv26 32) ) ) ) (?B58 ((_ sign_extend 24) (select h (_ bv26 32) ) ) ) (?B59 ((_ sign_extend 24) (select l (_ bv30 32) ) ) ) (?B60 ((_ sign_extend 24) (select h (_ bv30 32) ) ) ) (?B61 ((_ sign_extend 24) (select h (_ bv31 32) ) ) ) (?B62 ((_ sign_extend 24) (select l (_ bv31 32) ) ) ) (?B63 ((_ sign_extend 24) (select h (_ bv29 32) ) ) ) (?B64 ((_ sign_extend 24) (select l (_ bv29 32) ) ) ) ) (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (and (bvsle (_ bv0 32) ?B3 ) (bvsle ?B3 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B4 ) ) (bvsle ?B4 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B6 ) ) (bvsle ?B6 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B5 ) ) (bvsle ?B5 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B1 ) ) (bvsle ?B1 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B2 ) ) (bvsle ?B2 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B13 ) ) (bvsle ?B13 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B9 ) ) (bvsle ?B9 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B11 ) ) (bvsle ?B11 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B10 ) ) (bvsle ?B10 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B8 ) ) (bvsle ?B8 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B7 ) ) (bvsle ?B7 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B16 ) ) (bvsle ?B16 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B20 ) ) (bvsle ?B20 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B15 ) ) (bvsle ?B15 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B17 ) ) (bvsle ?B17 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B19 ) ) (bvsle ?B19 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B18 ) ) (bvsle ?B18 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B12 ) ) (bvsle ?B12 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B14 ) ) (bvsle ?B14 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B26 ) ) (bvsle ?B26 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B21 ) ) (bvsle ?B21 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B25 ) ) (bvsle ?B25 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B24 ) ) (bvsle ?B24 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B22 ) ) (bvsle ?B22 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B23 ) ) (bvsle ?B23 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B31 ) ) (bvsle ?B31 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B32 ) ) (bvsle ?B32 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B27 ) ) (bvsle ?B27 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B28 ) ) (bvsle ?B28 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B30 ) ) (bvsle ?B30 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B29 ) ) (bvsle ?B29 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B35 ) ) (bvsle ?B35 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B36 ) ) (bvsle ?B36 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B37 ) ) (bvsle ?B37 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B38 ) ) (bvsle ?B38 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B33 ) ) (bvsle ?B33 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B34 ) ) (bvsle ?B34 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B43 ) ) (bvsle ?B43 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B42 ) ) (bvsle ?B42 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B46 ) ) (bvsle ?B46 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B44 ) ) (bvsle ?B44 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B39 ) ) (bvsle ?B39 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B45 ) ) (bvsle ?B45 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B40 ) ) (bvsle ?B40 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B41 ) ) (bvsle ?B41 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B51 ) ) (bvsle ?B51 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B52 ) ) (bvsle ?B52 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B48 ) ) (bvsle ?B48 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B47 ) ) (bvsle ?B47 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B50 ) ) (bvsle ?B50 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B49 ) ) (bvsle ?B49 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B58 ) ) (bvsle ?B58 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B57 ) ) (bvsle ?B57 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B55 ) ) (bvsle ?B55 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B56 ) ) (bvsle ?B56 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B53 ) ) (bvsle ?B53 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B54 ) ) (bvsle ?B54 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B63 ) ) (bvsle ?B63 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B64 ) ) (bvsle ?B64 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B60 ) ) (bvsle ?B60 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B59 ) ) (bvsle ?B59 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B61 ) ) (bvsle ?B61 (_ bv1 32) ) ) (bvsle (_ bv0 32) ?B62 ) ) (bvsle ?B62 (_ bv1 32) ) ) ) )\n"
# For GPT14
# unexplored += "(assert (let ( (?B1 (concat (select b (_ bv3 32) ) (concat (select b (_ bv2 32) ) (concat (select b (_ bv1 32) ) (select b (_ bv0 32) ) ) ) ) ) (?B2 (concat (select c (_ bv3 32) ) (concat (select c (_ bv2 32) ) (concat (select c (_ bv1 32) ) (select c (_ bv0 32) ) ) ) ) ) (?B3 (concat (select a (_ bv3 32) ) (concat (select a (_ bv2 32) ) (concat (select a (_ bv1 32) ) (select a (_ bv0 32) ) ) ) ) ) ) (and (and (and (and (and (bvsle (_ bv0 32) ?B3 ) (bvslt ?B3 (_ bv16 32) ) ) (bvsle (_ bv0 32) ?B1 ) ) (bvslt ?B1 (_ bv16 32) ) ) (bvsle (_ bv0 32) ?B2 ) ) (bvslt ?B2 (_ bv4 32) ) ) ) )\n"
# For modpow2unsafe
# unexplored += "(assert (let ( (?B1 (concat (select b (_ bv3 32) ) (concat (select b (_ bv2 32) ) (concat (select b (_ bv1 32) ) (select b (_ bv0 32) ) ) ) ) ) (?B2 (concat (select c (_ bv3 32) ) (concat (select c (_ bv2 32) ) (concat (select c (_ bv1 32) ) (select c (_ bv0 32) ) ) ) ) ) (?B3 (concat (select a (_ bv3 32) ) (concat (select a (_ bv2 32) ) (concat (select a (_ bv1 32) ) (select a (_ bv0 32) ) ) ) ) ) ) (and (and (and (and (and (bvsle (_ bv0 32) ?B3 ) (bvslt ?B3 (_ bv256 32) ) ) (bvsle (_ bv0 32) ?B1 ) ) (bvslt ?B1 (_ bv256 32) ) ) (bvsle (_ bv0 32) ?B2 ) ) (bvslt ?B2 (_ bv256 32) ) ) ) )\n"
unexplored += "(check-sat)\n"
unexplored += "(exit)\n"
abs_path = os.path.join(directory, "unexplored.smt2")
f = open(abs_path, 'w')
f.write(unexplored)
f.close()
def model_count_ABC_exact(file, domain_size, bit_size, sign):
global define_text
global all_var_names
global total_solving_time
upper_bound = 0
f = open(file, "r")
bound_cons = f.read();
f.close()
bound_cons_arr = bound_cons.split("----")
upper_bound_cons = bound_cons_arr[0]
#temp = upper_bound_cons.split("(assert ")[0].split("\n")[1]
#print("temp: " + temp)
#print("define_text: " + define_text)
#upper_bound_cons = upper_bound_cons.replace(temp, define_text)
if bit_size == 1:
upper_bound_cons = upper_bound_cons.replace("(- 128)", "0");
upper_bound_cons = upper_bound_cons.replace("127", "1");
#print("Updated constraint: " + upper_bound_cons)
f = open("temp_upper_bound_cons.smt2","w")
f.write(upper_bound_cons)
f.close()
#upper_bound
if sign == 0:
process = subprocess.Popen(["abc", "-i", "temp_upper_bound_cons.smt2", "-bi", str(bit_size), "-v", "0", "--use-unsigned"], stdout = subprocess.PIPE)
else:
process = subprocess.Popen(["abc", "-i", "temp_upper_bound_cons.smt2", "-bi", str(bit_size), "-v", "0"], stdout = subprocess.PIPE)
result = process.communicate()[0].decode('utf-8')
process.terminate()
#print(result)
lines = result.split('\n');
print(lines)
if lines[0] == "sat":
upper_bound = int(lines[1])
print("Model count upper bound: ", upper_bound)
return(0, upper_bound)
def model_count_ABC(file, domain_size, bit_size):
global all_var_names
global total_solving_time
lower_bound = 0
upper_bound = 0
f = open(file, "r")
bound_cons = f.read();
f.close()
bound_cons_arr = bound_cons.split("----")
upper_bound_cons = bound_cons_arr[0]
lower_bound_cons = bound_cons_arr[1]
f = open("temp_lower_bound_cons.smt2","w")
f.write(lower_bound_cons)
f.close()
f = open("temp_upper_bound_cons.smt2","w")
f.write(upper_bound_cons)
f.close()
#upper_bound
process = subprocess.Popen(["abc", "-i", "temp_upper_bound_cons.smt2", "-bi", str(bit_size), "-v", "0", "--disable-equivalence", "--precise"], stdout = subprocess.PIPE)
result = process.communicate()[0].decode('utf-8')
process.terminate()
#print(result)
lines = result.split('\n');
print(lines)
if lines[0] == "sat":
upper_bound = int(lines[1])
print("Model count upper bound: ", upper_bound)
#lower_bound
process = subprocess.Popen(["abc", "-i", "temp_lower_bound_cons.smt2", "-bi", str(bit_size), "-v", "0", "--disable-equivalence", "--precise"], stdout = subprocess.PIPE)
result = process.communicate()[0].decode('utf-8')
process.terminate()
#print(result)
lines = result.split('\n');
if lines[0] == "sat":
count = int(lines[1])
lower_bound = domain_size - count
print(count)
print(domain_size)
print("Model count lower bound: ", lower_bound)
#os.remove("temp_lower_bound_cons.smt2")
#os.remove("temp_upper_bound_cons.smt2")
return(lower_bound, upper_bound)
def collect_variables(directory):
all_var_names = set()
for root,_,files in os.walk(directory):
for file in files:
if file[-4:] == "smt2":
abs_path = os.path.abspath(os.path.join(root, file))
#print(abs_path)
var_names = set()
process = subprocess.Popen(["./stp-2.1.2", "-p", "--disable-simplifications", "--disable-cbitp", "--disable-equality" ,"-a", "-w", "--output-CNF", "--minisat", abs_path], stdout = subprocess.PIPE)
result = process.communicate()[0].decode('utf-8')
process.terminate()
lines = result.split('\n');
for line in lines:
words = line.split()
if len(words) > 0 and words[0] == "ASSERT(":
all_var_names.add(words[1])
return all_var_names
def get_obs_SearchMC(file):
process = subprocess.Popen(["./stp-2.1.2", "-p", "--disable-simplifications", "--disable-cbitp", "--disable-equality" ,"-a", "-w", "--output-CNF", "--minisat", file], stdout = subprocess.PIPE)
result = process.communicate()[0].decode('utf-8')
process.terminate()
print(result)
lines = result.split('\n');
for line in lines:
if "ASSERT" in line and "a[0x00000000]" in line and " = " in line and " )" in line:
return line.split(" = ")[1].split(" )")[0]
return ""
def model_count_SearchMC(file, domain_size, bit_size):
global all_var_names
global total_solving_time
#f = open(file, "r")
#cost = f.readline()
#og_constraint = f.read()
#f.close()
#constraint_lines = og_constraint.split('\n')
#new_constraint_lines = []
#for i in range(len(constraint_lines)):
#print(constraint_lines[i])
# new_constraint_lines.append(constraint_lines[i])
# if constraint_lines[i].startswith("(declare-fun") and not constraint_lines[i + 1].startswith("(declare-fun") and "pad" not in constraint_lines[1]:
# new_constraint_lines.append("(declare-fun pad () (_ BitVec 8) )")
# elif constraint_lines[i].startswith("(assert") and not constraint_lines[i + 1].startswith("(assert") and "pad" not in constraint_lines[1]:
# new_constraint_lines.append("(assert ( = (_ bv0 8) pad ) ) ")
#new_constraint = "\n".join(new_constraint_lines)
#f = open(file, "w")
#f.write(new_constraint)
#f.close()
if bit_size == 1:
f = open(file, "r")
bound_cons = f.read();
f.close()
bound_cons = bound_cons.replace("(Array (_ BitVec 32) (_ BitVec 8) )", "(Array (_ BitVec 32) (_ BitVec 1) )");
f = open("temp_bv_cons.smt2","w")
f.write(bound_cons)
f.close()
file = "temp_bv_cons.smt2"
var_names = set()
assert_var_names = set()
process = subprocess.Popen(["./stp-2.1.2", "-p", "--disable-simplifications", "--disable-cbitp", "--disable-equality" ,"-a", "--minisat", file], stdout = subprocess.PIPE)
result = process.communicate()[0].decode('utf-8')
process.terminate()
#print(result)
lines = result.split('\n');
for line in lines:
words = line.split()
if len(words) > 0 and words[0] == "VarDump:" and not words[1].startswith("STP__IndexVariables_"):
var_names.add(words[1])
output_names = " "
for var_name in var_names:
output_names += "-output_name=" + var_name + " "
print(output_names)
print(file)
process = subprocess.Popen(["./SearchMC.pl", "-input_type=smt", "-cl=0.95" ,"-thres=0.5", "-term_cond=1"] + output_names.split() + [file], stdout = subprocess.PIPE)
result = process.communicate()[0].decode('utf-8')
process.terminate()
lines = result.split('\n')
#f = open(file, "w")
#f.write(og_constraint)
#f.close()
upper_bound = 0
lower_bound = 0
for line in lines:
l = line.split();
if len(l) > 0:
if l[1] == "Sound" and l[2] == "Upper":
upper_bound = l[-3]
upper_bound = int(2**float(upper_bound))
if l[1] == "Sound" and l[2] == "Lower":
lower_bound = l[-3]
lower_bound = int(2**float(lower_bound))
elif l[1] == "Exact":
lower_bound = int(l[-1])
upper_bound = int(l[-1])
elif l[1] == "Running":
runtime = float(l[-1])
total_solving_time += runtime
#print(og_constraint)
#print(var_names)
#if "pad" in var_names:
# var_names.remove("pad")
print(len(all_var_names))
print(len(var_names))
print(lower_bound)
print(upper_bound)
return (lower_bound * ((2 ** bit_size) ** (len(all_var_names) - len(var_names))), upper_bound * ((2 ** bit_size) ** (len(all_var_names) - len(var_names))))
def get_observation_constraints(directory, tool, domain_size, bit_size, sign):
observationConstraints = {}
for root,_,files in os.walk(directory):
for file in files:
if file[-4:] == "smt2" and "domain" not in file:
abs_path = os.path.abspath(os.path.join(root, file))
f = open(abs_path, "r")
cost = f.readline()
actual_constraint = f.read()
f.close()
cost = int(cost[1:])
print(cost)
#print(abs_path)
#c = get_obs_SearchMC(abs_path)
#if c != "":
# cost = int(c, 16)
#else:
# cost = 0
if tool == "searchMC":
count = model_count_SearchMC(abs_path, domain_size, bit_size)
elif tool == "abc-exact":
count = model_count_ABC_exact(abs_path, domain_size, bit_size, sign)
else:
count = model_count_ABC(abs_path, domain_size, bit_size)
#print(all_var_names)
print("Count:", count)
if cost in observationConstraints:
observationConstraints[cost].append((actual_constraint, count))
else:
observationConstraints[cost] = [(actual_constraint, count)]
#print("Number of observations: ", len(observationConstraints))
if not bool(observationConstraints):
print("No leakage")
else:
threshold = 6
costs = sorted(observationConstraints.keys())
currentInterval = list(costs)[0]
pathConditions = observationConstraints[currentInterval]
for currentCost in sorted(observationConstraints.copy().keys()):
#print("current cost: ", currentCost)
#print("current interval: ", currentInterval)
if currentCost > currentInterval and currentCost < currentInterval + threshold:
pathConditions += observationConstraints[currentCost]
observationConstraints.pop(currentCost)
observationConstraints[currentInterval] = pathConditions
#print("merged")
else:
currentInterval = currentCost
pathConditions = observationConstraints[currentInterval]
return observationConstraints
def get_upper_lower_bounds(observationConstraints):
upper_lower_bounds = dict()
for cost in observationConstraints:
lower_bound = 0
upper_bound = 0
for (constraint, count) in observationConstraints[cost]:
lower_bound += count[0]
upper_bound += count[1]
upper_lower_bounds[cost] = [lower_bound, upper_bound]
return upper_lower_bounds
#############################Calculate entropy#######################################
############Standard deviation method##############
def get_max_entropy_standard_deviation(upper_lower_bounds, domain_size):
print("Domain Size: ", domain_size)
counts = {}
avg = domain_size//len(upper_lower_bounds)
sum_counts = 0
max_entropy = 0
#print("Length: ", len(upper_lower_bounds))
for cost in upper_lower_bounds:
#print(cost)
lower_bound = upper_lower_bounds[cost][0]
upper_bound = upper_lower_bounds[cost][1]
if avg >= lower_bound and avg <= upper_bound:
counts[cost] = avg
sum_counts += avg
elif avg < lower_bound:
counts[cost] = lower_bound
sum_counts += lower_bound
elif avg > upper_bound:
counts[cost] = upper_bound
sum_counts += upper_bound
#print("Upper and lower bounds: ",upper_lower_bounds)
diff = sum_counts - domain_size
if diff == 0:
for cost in counts:
prob = counts[cost]/domain_size
max_entropy += -1 * prob * math.log(prob,2)
return (counts, max_entropy)
elif diff > 0: # need to decrease
while diff != 0:
l = []
min_diff_between_count_and_avg = -1
second_min_diff_between_count_and_avg = -1
min_room_to_decrease = 0
for cost in counts:
if counts[cost] > upper_lower_bounds[cost][0] and avg - counts[cost] >= 0:
if min_diff_between_count_and_avg == -1:
# First encounter of count that both is less than avg and has room to decrease
min_diff_between_count_and_avg = avg - counts[cost]
l = [cost]
min_room_to_decrease = counts[cost] - upper_lower_bounds[cost][0]
elif avg-counts[cost] < min_diff_between_count_and_avg:
# Find a count that is closer to avg
# Need to update previous closest count
second_min_diff_between_count_and_avg = min_diff_between_count_and_avg
min_diff_between_count_and_avg = avg - counts[cost]
l = [cost]
min_room_to_decrease = counts[cost] - upper_lower_bounds[cost][0]
elif avg-counts[cost] == min_diff_between_count_and_avg:
# Find a count that is equally close to avg
# No need to update previous closest count
# May need to update min_room_to_decrease
l.append(cost)
if counts[cost] - upper_lower_bounds[cost][0] < min_room_to_decrease:
min_room_to_decrease = counts[cost] - upper_lower_bounds[cost][0]
else:
if second_min_diff_between_count_and_avg == -1:
second_min_diff_between_count_and_avg = avg - counts[cost]
else:
if avg - counts[cost] < second_min_diff_between_count_and_avg:
second_min_diff_between_count_and_avg = avg - counts[cost]
if len(l) == 0:
print("Incorrect counts given by model counter:",upper_lower_bounds)
avg_diff = int(diff/len(l))
if second_min_diff_between_count_and_avg != -1:
diff_min_second = second_min_diff_between_count_and_avg - min_diff_between_count_and_avg
else:
diff_min_second = min_diff_between_count_and_avg
if avg_diff == 0:
for cost in l:
counts[cost] -= 1
diff -= 1
if diff == 0:
break
elif second_min_diff_between_count_and_avg == -1:
# All counts that are smaller than avg are equal
for cost in l:
counts[cost] -= min(min_room_to_decrease, avg_diff)
diff -= min(min_room_to_decrease, avg_diff)
else:
for cost in l:
counts[cost] -= min(min_room_to_decrease, avg_diff, diff_min_second)
diff -= min(min_room_to_decrease, avg_diff, diff_min_second)
else: # need to increase
diff = abs(diff)
while diff != 0:
l = []
min_diff_between_count_and_avg = -1
second_min_diff_between_count_and_avg = -1
min_room_to_increase = 0
for cost in counts:
if counts[cost] < upper_lower_bounds[cost][1] and counts[cost] - avg >= 0:
if min_diff_between_count_and_avg == -1:
# First encounter of count that both is greater than avg and has room to increase
min_diff_between_count_and_avg = counts[cost] - avg
l = [cost]
min_room_to_increase = upper_lower_bounds[cost][1] - counts[cost]
elif counts[cost] - avg < min_diff_between_count_and_avg:
# Find a count that is closer to avg
# Need to update previous closest count
second_min_diff_between_count_and_avg = min_diff_between_count_and_avg
min_diff_between_count_and_avg = counts[cost] - avg
l = [cost]
min_room_to_increase = upper_lower_bounds[cost][1] - counts[cost]
elif counts[cost] - avg == min_diff_between_count_and_avg:
# Find a count that is equally close to avg
# No need to update previous closest count
# May need to update min_room_to_decrease
l.append(cost)
if upper_lower_bounds[cost][1] - counts[cost] < min_room_to_increase:
min_room_to_increase = upper_lower_bounds[cost][1] - counts[cost]
else:
if second_min_diff_between_count_and_avg == -1:
second_min_diff_between_count_and_avg = counts[cost] - avg
else:
if counts[cost] - avg < second_min_diff_between_count_and_avg:
second_min_diff_between_count_and_avg = counts[cost] - avg
if len(l) == 0:
print("Incorrect counts given by SearchMC:",upper_lower_bounds)
avg_diff = int(diff/len(l))
if second_min_diff_between_count_and_avg != -1:
diff_min_second = second_min_diff_between_count_and_avg - min_diff_between_count_and_avg
else:
diff_min_second = min_diff_between_count_and_avg
if avg_diff == 0:
for cost in l:
counts[cost] += 1
diff -= 1
if diff == 0:
break
elif second_min_diff_between_count_and_avg == -1:
# All counts that are greater than avg are equal
for cost in l:
counts[cost] += min(min_room_to_increase, avg_diff)
diff -= min(min_room_to_increase, avg_diff)
else:
for cost in l:
counts[cost] += min(min_room_to_increase, avg_diff, diff_min_second)
diff -= min(min_room_to_increase, avg_diff, diff_min_second)
for cost in counts:
#print(cost,":", counts[cost], domain_size)
prob = counts[cost]/domain_size
#print(cost,":", counts[cost], domain_size, -1 * prob * math.log(prob,2))
max_entropy += -1 * prob * math.log(prob,2)
#print("res: ",max_entropy)
#print("Standard deviation method end point:", counts)
return (counts, max_entropy)
def get_min_entropy_standard_deviation(upper_lower_bounds, domain_size):
counts = {}
avg = domain_size//len(upper_lower_bounds)
sum_counts = 0
min_entropy = 0
for cost in upper_lower_bounds:
lower_bound = upper_lower_bounds[cost][0]
upper_bound = upper_lower_bounds[cost][1]
if avg >= lower_bound and avg <= upper_bound:
if abs(avg - lower_bound) > abs(avg - upper_bound):
counts[cost] = lower_bound
sum_counts += lower_bound
else:
counts[cost] = upper_bound
sum_counts += upper_bound
elif avg < lower_bound:
counts[cost] = upper_bound
sum_counts += upper_bound
elif avg > upper_bound:
counts[cost] = lower_bound
sum_counts += lower_bound
#print("Initial counts:", upper_lower_bound)
diff = sum_counts - domain_size
if diff == 0:
for cost in counts:
prob = counts[cost]/domain_size
min_entropy += -1 * prob * math.log(prob,2)
elif diff > 0: # need to decrease
while diff != 0:
l = []
min_diff_between_count_and_avg = -1
second_min_diff_between_count_and_avg = -1
min_room_to_decrease = 0
for cost in counts:
if counts[cost] > upper_lower_bounds[cost][0]:
if min_diff_between_count_and_avg == -1:
# First encounter of count that has room to decrease
min_diff_between_count_and_avg = abs(avg - counts[cost])
l = [cost]
min_room_to_decrease = counts[cost] - upper_lower_bounds[cost][0]
elif abs(avg - counts[cost]) < min_diff_between_count_and_avg:
# Find a count that is closer to avg
# Need to update previous closest count
second_min_diff_between_count_and_avg = min_diff_between_count_and_avg
min_diff_between_count_and_avg = abs(avg - counts[cost])
l = [cost]
min_room_to_decrease = counts[cost] - upper_lower_bounds[cost][0]
elif abs(avg - counts[cost]) == min_diff_between_count_and_avg:
# Find a count that is equally close to avg
# No need to update previous closest count
# May need to update min_room_to_decrease
l.append(cost)
if counts[cost] - upper_lower_bounds[cost][0] < min_room_to_decrease:
min_room_to_decrease = counts[cost] - upper_lower_bounds[cost][0]
else:
if second_min_diff_between_count_and_avg == -1:
second_min_diff_between_count_and_avg = abs(avg - counts[cost])
else:
if abs(avg - counts[cost]) < second_min_diff_between_count_and_avg:
second_min_diff_between_count_and_avg = abs(avg - counts[cost])
if len(l) == 0:
print("Incorrect counts given by SearchMC:", upper_lower_bounds)
avg_diff = diff//len(l)
if second_min_diff_between_count_and_avg != -1:
diff_min_second = second_min_diff_between_count_and_avg - min_diff_between_count_and_avg
else:
diff_min_second = min_diff_between_count_and_avg
if avg_diff == 0:
for cost in l:
counts[cost] -= 1
diff -= 1
if diff == 0:
break
elif second_min_diff_between_count_and_avg == -1:
# All counts that are smaller than avg are equal
for cost in l:
counts[cost] -= min(min_room_to_decrease, avg_diff)
diff -= min(min_room_to_decrease, avg_diff)
else:
for cost in l:
counts[cost] -= min(min_room_to_decrease, avg_diff, diff_min_second)
diff -= min(min_room_to_decrease, avg_diff, diff_min_second)
else: # need to increase
diff = abs(diff)
while diff != 0:
l = []
min_diff_between_count_and_avg = -1
second_min_diff_between_count_and_avg = -1
min_room_to_increase = 0
for cost in counts:
if counts[cost] < upper_lower_bounds[cost][1]:
if min_diff_between_count_and_avg == -1:
# First encounter of count that has room to increase
min_diff_between_count_and_avg = abs(counts[cost] - avg)
l = [cost]
min_room_to_increase = upper_lower_bounds[cost][1] - counts[cost]
elif abs(counts[cost] - avg) < min_diff_between_count_and_avg:
# Find a count that is closer to avg
# Need to update previous closest count
second_min_diff_between_count_and_avg = min_diff_between_count_and_avg
min_diff_between_count_and_avg = abs(counts[cost] - avg)
l = [cost]
min_room_to_increase = upper_lower_bounds[cost][1] - counts[cost]
elif abs(counts[cost] - avg) == min_diff_between_count_and_avg:
# Find a count that is equally close to avg
# No need to update previous closest count
# May need to update min_room_to_decrease
l.append(cost)
if upper_lower_bounds[cost][1] - counts[cost] < min_room_to_increase:
min_room_to_increase = upper_lower_bounds[cost][1] - counts[cost]
else:
if second_min_diff_between_count_and_avg == -1:
second_min_diff_between_count_and_avg = abs(counts[cost] - avg)
else:
if abs(counts[cost] - avg) < second_min_diff_between_count_and_avg:
second_min_diff_between_count_and_avg = abs(counts[cost] - avg)
if len(l) == 0:
print("Incorrect counts given by SearchMC:",upper_lower_bounds)
avg_diff = diff//len(l)
if second_min_diff_between_count_and_avg != -1:
diff_min_second = second_min_diff_between_count_and_avg - min_diff_between_count_and_avg
else:
diff_min_second = min_diff_between_count_and_avg
if avg_diff == 0:
for cost in l:
counts[cost] += 1
diff -= 1
if diff == 0:
break
elif second_min_diff_between_count_and_avg == -1:
# All counts that are greater than avg are equal
for cost in l:
counts[cost] += min(min_room_to_increase, avg_diff)
diff -= min(min_room_to_increase, avg_diff)
else:
for cost in l:
counts[cost] += min(min_room_to_increase, avg_diff, diff_min_second)
diff -= min(min_room_to_increase, avg_diff, diff_min_second)
for cost in counts:
#print(cost,":",upper_lower_bound[cost],counts[cost])
prob = counts[cost]/domain_size
min_entropy += -1 * prob * math.log(prob,2)
#print("Standard deviation method end point:", counts)
return (counts, min_entropy)
#################Hill climbing method (deterministic)#####################
def get_next_neighbor_max_deterministic(current_counts, upper_lower_bounds, domain_size, current_entropy, uup):
max_neighbor_entropy = current_entropy
max_neighbor = current_counts.copy()
for i in range(len(current_counts)):
neighbor = current_counts.copy()
cost = current_counts[i][0]
count = current_counts[i][1]
if count > upper_lower_bounds[cost][0]:
dec_count = count - 1
for j in range(i + 1, len(current_counts)):
neighbor_cost = current_counts[j][0]
neighbor_count = current_counts[j][1]
if neighbor_count < upper_lower_bounds[neighbor_cost][1]:
inc_neighbor_count = neighbor_count + 1
neighbor[i] = (cost, dec_count)
neighbor[j] = (neighbor_cost, inc_neighbor_count)
entropy = 0
if uup == 0:
for k in range(len(neighbor)):
entropy += -1 * neighbor[k][1]/domain_size * math.log(neighbor[k][1]/domain_size, 2)
else:
for k in range(len(neighbor)):
if neighbor[k][0] != 1000000:
entropy += -1 * neighbor[k][1]/domain_size * math.log(neighbor[k][1]/domain_size, 2)
else:
entropy += -1 * neighbor[k][1]/domain_size * math.log(1/domain_size, 2)
if entropy > max_neighbor_entropy:
#print("A BETTER NEIGHBOR IS FOUND")
max_neighbor_entropy = entropy
max_neighbor = neighbor.copy()
#return (max_neighbor, max_neighbor_entropy)
neighbor = current_counts.copy()
if count < upper_lower_bounds[cost][1]:
inc_count = count + 1
for j in range(i + 1, len(current_counts)):
neighbor_cost = current_counts[j][0]
neighbor_count = current_counts[j][1]
if neighbor_count > upper_lower_bounds[neighbor_cost][0]:
dec_neighbor_count = neighbor_count - 1
neighbor[i] = (cost, inc_count)
neighbor[j] = (neighbor_cost, dec_neighbor_count)
entropy = 0
if uup == 0:
for k in range(len(neighbor)):
entropy += -1 * neighbor[k][1]/domain_size * math.log(neighbor[k][1]/domain_size, 2)
else:
for k in range(len(neighbor)):
if neighbor[k][0] != 1000000:
entropy += -1 * neighbor[k][1]/domain_size * math.log(neighbor[k][1]/domain_size, 2)
else:
entropy += -1 * neighbor[k][1]/domain_size * math.log(1/domain_size, 2)
if entropy > max_neighbor_entropy:
#print("A BETTER NEIGHBOR IS FOUND")
max_neighbor_entropy = entropy
max_neighbor = neighbor.copy()
#return (max_neighbor, max_neighbor_entropy)
neighbor = current_counts.copy()
#print(max_neighbor)
return (max_neighbor, max_neighbor_entropy)
def get_max_entropy_hill_climbing_deterministic(upper_lower_bounds, domain_size, uup):
if uup == 0:
current_counts_dict, current_entropy = get_max_entropy_standard_deviation(upper_lower_bounds, domain_size)
else:
current_counts_dict, current_entropy = get_max_entropy_with_unexplored_SLSQP(upper_lower_bounds, domain_size)
current_counts = []
for cost in current_counts_dict:
current_counts.append((cost, current_counts_dict[cost]))
while True:
#print("current_counts:", current_counts)
neighbor = get_next_neighbor_max_deterministic(current_counts, upper_lower_bounds, domain_size, current_entropy, uup)
if neighbor[1] <= current_entropy:
max_entropy = current_entropy
break
current_counts = neighbor[0]
current_entropy = neighbor[1]
#print("Hill climbing end point:", current_counts)
curr_counts_dict = {}
for cost, counts in current_counts:
current_counts_dict[cost] = counts
return (current_counts_dict, max_entropy)
def get_next_neighbor_min_deterministic(current_counts, upper_lower_bounds, domain_size, current_entropy):
min_neighbor_entropy = current_entropy
min_neighbor = current_counts.copy()
for i in range(len(current_counts)):
neighbor = current_counts.copy()
cost = current_counts[i][0]
count = current_counts[i][1]
if count > upper_lower_bounds[cost][0]:
dec_count = count - 1
for j in range(i + 1, len(current_counts)):
neighbor_cost = current_counts[j][0]
neighbor_count = current_counts[j][1]
if neighbor_count < upper_lower_bounds[neighbor_cost][1]:
inc_neighbor_count = neighbor_count + 1
neighbor[i] = (cost, dec_count)
neighbor[j] = (neighbor_cost, inc_neighbor_count)
entropy = 0
for k in range(len(neighbor)):
entropy += -1 * neighbor[k][1]/domain_size * math.log(neighbor[k][1]/domain_size, 2)
if entropy < min_neighbor_entropy:
min_neighbor_entropy = entropy
min_neighbor = neighbor.copy()
neighbor = current_counts.copy()
if count < upper_lower_bounds[cost][1]:
inc_count = count + 1
for j in range(i + 1, len(current_counts)):
neighbor_cost = current_counts[j][0]
neighbor_count = current_counts[j][1]
if neighbor_count > upper_lower_bounds[neighbor_cost][0]:
dec_neighbor_count = neighbor_count - 1
neighbor[i] = (cost, inc_count)
entropy = 0
neighbor[j] = (neighbor_cost, dec_neighbor_count)
for k in range(len(neighbor)):
entropy += -1 * neighbor[k][1]/domain_size * math.log(neighbor[k][1]/domain_size, 2)
if entropy < min_neighbor_entropy:
min_neighbor_entropy = entropy
min_neighbor = neighbor.copy()
neighbor = current_counts.copy()
return (min_neighbor, min_neighbor_entropy)
def get_min_entropy_hill_climbing_deterministic(upper_lower_bound, domain_size):
current_counts_dict, current_entropy = get_max_entropy_standard_deviation(upper_lower_bounds, domain_size)
current_counts = []
for cost in current_counts_dict:
current_counts.append((cost, current_counts_dict[cost]))
while True:
#print("current_counts:", current_counts)
neighbor = get_next_neighbor_min_deterministic(current_counts, upper_lower_bound, domain_size, current_entropy)
if neighbor[1] >= current_entropy:
min_entropy = current_entropy
break
current_counts = neighbor[0]
current_entropy = neighbor[1]
#print("Hill climbing end point:", current_counts)
curr_counts_dict = {}
for cost, counts in current_counts:
current_counts_dict[cost] = counts
return (current_counts_dict, min_entropy)
'''
#################Hill climbing method (random)#####################
def get_next_neighbor_max_random(current_counts, upper_lower_bounds, domain_size, current_entropy):
max_neighbor_entropy = current_entropy
max_neighbor = current_counts.copy()
for i in range(40):
diff = 0
neighbor = current_counts.copy()
max_upper_room = 0
max_lower_room = 0
for j in range(len(current_counts)):
cost = neighbor[j][0]
count = neighbor[j][1]
max_upper_room += upper_lower_bounds[cost][1] - count
max_lower_room += upper_lower_bounds[cost][0] - count
for j in range(len(current_counts)):
cost = neighbor[j][0]
count = neighbor[j][1]
upper_room = upper_lower_bounds[cost][1] - count
lower_room = upper_lower_bounds[cost][0] - count
if j != len(current_counts) - 1:
change = random.randint(max(lower_room, upper_room - max_upper_room - diff), min(upper_room, lower_room - max_lower_room - diff))
max_upper_room -= upper_room
max_lower_room -= lower_room
diff += change # Make sure that diff can be changed to 0
count += change
neighbor[j] = (cost, count)
else:
change = -1 * diff
if change > upper_room or change < lower_room:
raise ValueError
max_upper_room -= upper_room
max_lower_room -= lower_room
diff += change # Make sure that diff can be changed to 0
count += change
neighbor[j] = (cost, count)
assert diff == 0
entropy = 0
for j in range(len(neighbor)):
entropy += -1 * neighbor[j][1]/domain_size * math.log(neighbor[j][1]/domain_size, 2)
if entropy > max_neighbor_entropy:
max_neighbor_entropy = entropy
max_neighbor = neighbor.copy()
return (max_neighbor, max_neighbor_entropy)
def get_next_neighbor_min_random(current_counts, upper_lower_bounds, domain_size, current_entropy):
max_neighbor_entropy = current_entropy
max_neighbor = current_counts.copy()
for i in range(40):
diff = 0
neighbor = current_counts.copy()
max_upper_room = 0
max_lower_room = 0
for j in range(len(current_counts)):
cost = neighbor[j][0]
count = neighbor[j][1]
max_upper_room += upper_lower_bounds[cost][1] - count
max_lower_room += upper_lower_bounds[cost][0] - count
for j in range(len(current_counts)):
cost = neighbor[j][0]
count = neighbor[j][1]
upper_room = upper_lower_bounds[cost][1] - count
lower_room = upper_lower_bounds[cost][0] - count
if j != len(current_counts) - 1:
change = random.randint(max(lower_room, upper_room - max_upper_room - diff), min(upper_room, lower_room - max_lower_room - diff))
max_upper_room -= upper_room
max_lower_room -= lower_room
diff += change # Make sure that diff can be changed to 0
count += change
neighbor[j] = (cost, count)
else:
change = -1 * diff
if change > upper_room or change < lower_room:
#print(neighbor)
raise ValueError
max_upper_room -= upper_room
max_lower_room -= lower_room
diff += change # Make sure that diff can be changed to 0
count += change
neighbor[j] = (cost, count)
entropy = 0
for j in range(len(neighbor)):
entropy += -1 * neighbor[j][1]/domain_size * math.log(neighbor[j][1]/domain_size, 2)
if entropy < max_neighbor_entropy:
max_neighbor_entropy = entropy
max_neighbor = neighbor.copy()
return (max_neighbor, max_neighbor_entropy)
def get_max_entropy_hill_climbing_random(upper_lower_bounds, domain_size):
counts = {}
sum_counts = 0
max_entropy = 0
sum_var = 0;
s = z3.Solver()
var_list = {}
for cost in upper_lower_bounds:
temp = z3.Int("c" + str(cost))
lower_bound = upper_lower_bounds[cost][0]
upper_bound = upper_lower_bounds[cost][1]
s.add(temp >= lower_bound)
s.add(temp <= upper_bound)
sum_var += temp;
var_list[cost] = temp;
s.add(sum_var == domain_size)
s.check()
m = s.model();
for cost in upper_lower_bounds: