-
Notifications
You must be signed in to change notification settings - Fork 2
/
ising_model.py
1494 lines (1182 loc) · 62.1 KB
/
ising_model.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
from __future__ import division
import numpy as np
import maxflow
import matplotlib
matplotlib.use('Agg') #prevent error running remotely
import matplotlib.pyplot as plt
import time
from pgmpy.models import MarkovModel
from pgmpy.inference import BeliefPropagation
from pgmpy.factors.discrete import DiscreteFactor
from itertools import product
################## Create a graph with integer capacities.
#################g = maxflow.Graph[int](2, 2)
################## Add two (non-terminal) nodes. Get the index to the first one.
#################nodes = g.add_nodes(2)
################## Create two edges (forwards and backwards) with the given capacities.
################## The indices of the nodes are always consecutive.
#################g.add_edge(nodes[0], nodes[1], 1, 2)
################## Set the capacities of the terminal edges...
################## ...for the first node.
#################g.add_tedge(nodes[0], -2, -5)
################## ...for the second node.
#################g.add_tedge(nodes[1], -9, 4)
#################
#################
#################flow = g.maxflow()
#################print "Maximum flow:", flow
#################
#################print "Segment of the node 0:", g.get_segment(nodes[0])
#################print "Segment of the node 1:", g.get_segment(nodes[1])
#################
#################sleep(4)
class SG_model:
def __init__(self, N, f, c, all_weights_1=False):
'''
Sample local field parameters and coupling parameters to define a spin glass model
Inputs:
- N: int, the model will be a grid with shape (NxN)
- f: float, local field parameters (theta_i) will be drawn uniformly at random
from [-f, f] for each node in the grid
- c: float, coupling parameters (theta_ij) will be drawn uniformly at random from
[0, c) (gumbel paper uses [0,c], but this shouldn't matter) for each edge in
the grid
- all_weights_1: bool, if true return a model with all weights = 1 so Z=2^(N^2)
if false return randomly sampled model
Values defining the spin glass model:
- lcl_fld_params: array with dimensions (NxN), local field parameters (theta_i)
that we sampled for each node in the grid
- cpl_params_h: array with dimensions (N x N-1), coupling parameters (theta_ij)
for each horizontal edge in the grid. cpl_params_h[k,l] corresponds to
theta_ij where i is the node indexed by (k,l) and j is the node indexed by
(k,l+1)
- cpl_params_v: array with dimensions (N-1 x N), coupling parameters (theta_ij)
for each vertical edge in the grid. cpl_params_h[k,l] corresponds to
theta_ij where i is the node indexed by (k,l) and j is the node indexed by
(k+1,l)
'''
self.N = N
if all_weights_1: #make all weights 1
#sample local field parameters (theta_i) for each node
self.lcl_fld_params = np.zeros((N,N))
#sample horizontal coupling parameters (theta_ij) for each horizontal edge
self.cpl_params_h = np.zeros((N,N-1))
#sample vertical coupling parameters (theta_ij) for each vertical edge
self.cpl_params_v = np.zeros((N-1,N))
else: #randomly sample weights
#sample local field parameters (theta_i) for each node
self.lcl_fld_params = np.random.uniform(low=-f, high=f, size=(N,N))
#sample horizontal coupling parameters (theta_ij) for each horizontal edge
self.cpl_params_h = np.random.uniform(low=0.0, high=c, size=(N,N-1))
#sample vertical coupling parameters (theta_ij) for each vertical edge
self.cpl_params_v = np.random.uniform(low=0.0, high=c, size=(N-1,N))
def spin_glass_perturbed_MAP_state(sg_model, perturb_ones, perturb_zeros):
'''
Find the MAP state of a perturbed spin glass model using a min-cut/max-flow
solver. This method is faster than a MAP solver for a general MRF, but can
only be used for special cases of MRF's.
For info about what models can be used see:
http://www.cs.cornell.edu/~rdz/Papers/KZ-PAMI04.pdf
For info about transforming the MAP problem into a min-cut problem see:
https://www.classes.cs.uchicago.edu/archive/2006/fall/35040-1/gps.pdf
(N is an implicit parameter, the glass spin model has shape (NxN))
Inputs:
- sg_model: type SG_model, specifies the spin glass model
- perturb_ones: array with dimensions (NxN), specifies a perturbation of each
node's potential when the node takes the value 1
- perturb_zeros: array with dimensions (NxN), specifies a perturbation of each
node's potential when the node takes the value 0
Outputs:
- map_state: binary array with dimensions (NxN), the state in the spin glass model
with the largest energy. map_state[i,j] = 0 means node (i,j) is zero in the
map state and map_state[i,j] = 1 means node (i,j) is one in the map state
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
g = maxflow.GraphFloat()
#Create (NxN) grid of nodes nodes
nodes = g.add_nodes(N**2)
#Add single node potentials
for r in range(N):
for c in range(N):
# assert(np.abs(sg_model.lcl_fld_params[r,c]) + sg_model.lcl_fld_params[r,c] +\
# np.abs(perturb_ones[r,c] - perturb_zeros[r,c]) >= 0)
# assert(np.abs(sg_model.lcl_fld_params[r,c]) - sg_model.lcl_fld_params[r,c] +\
# np.abs(perturb_ones[r,c] - perturb_zeros[r,c]) +\
# perturb_ones[r,c] - perturb_zeros[r,c] >= 0), (np.abs(sg_model.lcl_fld_params[r,c]) - sg_model.lcl_fld_params[r,c] +\
# np.abs(perturb_ones[r,c] - perturb_zeros[r,c]) +\
# perturb_ones[r,c] - perturb_zeros[r,c])
#
# perturbed_0_potential =2+ np.abs(sg_model.lcl_fld_params[r,c]) + sg_model.lcl_fld_params[r,c] +\
# np.abs(perturb_ones[r,c] - perturb_zeros[r,c])
# perturbed_1_potential =2+ np.abs(sg_model.lcl_fld_params[r,c]) - sg_model.lcl_fld_params[r,c] +\
# np.abs(perturb_ones[r,c] - perturb_zeros[r,c]) +\
# perturb_ones[r,c] - perturb_zeros[r,c]
lamda_i = (sg_model.lcl_fld_params[r,c] + perturb_ones[r,c]) \
- (-sg_model.lcl_fld_params[r,c] + perturb_zeros[r,c])
perturbed_0_potential = np.max((0, lamda_i))
perturbed_1_potential = np.max((0, -lamda_i))
# g.add_tedge(nodes[r*N + c], perturbed_0_potential, perturbed_1_potential)
g.add_tedge(nodes[r*N + c], perturbed_1_potential, perturbed_0_potential)
#Add two node potentials
edge_count = 0
for r in range(N):
for c in range(N):
#add a horizontal edge
if c < N-1:
g.add_edge(nodes[r*N + c], nodes[r*N + c+1], 2*sg_model.cpl_params_h[r,c], 2*sg_model.cpl_params_h[r,c])
edge_count += 1
#add a vertical edge
if r < N-1:
g.add_edge(nodes[r*N + c], nodes[(r+1)*N + c], 2*sg_model.cpl_params_v[r,c], 2*sg_model.cpl_params_v[r,c])
edge_count += 1
assert(edge_count == 2*N*(N-1))
#find the maximum flow
flow = g.maxflow()
#read out node partitioning for max-flow
map_state = np.zeros((N,N))
for r in range(N):
for c in range(N):
map_state[r,c] = g.get_segment(nodes[r*N + c])
assert(map_state[r,c] == 0 or map_state[r,c] == 1)
return map_state
def calc_perturbed_energy(sg_model, perturb_ones, perturb_zeros, state):
'''
Compute the perturbed energy of the given state in a spin glass model
(N is an implicit parameter, the glass spin model has shape (NxN))
Inputs:
- sg_model: type SG_model, specifies the spin glass model
- perturb_ones: array with dimensions (NxN), specifies a perturbation of each
node's potential when the node takes the value 1
- perturb_zeros: array with dimensions (NxN), specifies a perturbation of each
node's potential when the node takes the value 0 (really -1)
- state: binary (0,1) array with dimensions (NxN), we are finding the perturbed
energy of this particular state. state[i,j] = 0 means node ij takes the value -1,
state[i,j] = 1 means node ij takes the value 1
Outputs:
- perturbed_energy: float, the perturbed energy of the specified state in the
specified spin glass model
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
perturbed_energy = 0.0
#Add single node potential and perturbation contributions
for r in range(N):
for c in range(N):
if state[r,c] == 1:
perturbed_energy += sg_model.lcl_fld_params[r,c]
perturbed_energy += perturb_ones[r,c]
else:
assert(state[r,c] == 0)
perturbed_energy -= sg_model.lcl_fld_params[r,c]
perturbed_energy += perturb_zeros[r,c]
#Add two node potential contributions
edge_count = 0
for r in range(N):
for c in range(N):
#from horizontal edge
if c < N-1:
perturbed_energy += sg_model.cpl_params_h[r,c]*(2*state[r,c]-1)*(2*state[r,c+1]-1)
edge_count += 1
#from vertical edge
if r < N-1:
perturbed_energy += sg_model.cpl_params_v[r,c]*(2*state[r,c]-1)*(2*state[r+1,c]-1)
edge_count += 1
assert(edge_count == 2*N*(N-1))
return perturbed_energy
def upper_bound_Z_gumbel(sg_model, num_trials):
'''
Upper bound the partition function of the specified spin glass model using
an empircal estimate of the expected maximum energy perturbed with
Gumbel noise
Inputs:
- sg_model: type SG_model, specifies the spin glass model
- num_trials: int, estimate the expected perturbed maximum energy as
the mean over num_trials perturbed maximum energies
Outputs:
- upper_bound: type float, upper bound on ln(partition function)
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
upper_bound = 0.0
for i in range(num_trials):
perturb_ones = np.random.gumbel(loc=0.0, scale=1.0, size=(N,N))
perturb_zeros = np.random.gumbel(loc=0.0, scale=1.0, size=(N,N))
map_state = spin_glass_perturbed_MAP_state(sg_model, perturb_ones, perturb_zeros)
cur_perturbed_energy = calc_perturbed_energy(sg_model, perturb_ones, perturb_zeros, map_state)
##### ########### DEBUGGING ###########
##### (delta_exp, map_state_debug) = find_MAP_spin_glass(sg_model, perturb_ones, perturb_zeros)
##### check_delta = np.log(delta_exp)
###### if cur_perturbed_energy != check_delta:
###### print "local field params:"
###### print sg_model.lcl_fld_params
###### print "cpl_params_h"
###### print sg_model.cpl_params_h
###### print "cpl_params_v"
###### print sg_model.cpl_params_v
######
###### print "perturb 1s"
###### print perturb_ones
######
###### print "perturb 0s"
###### print perturb_zeros
#####
##### assert(np.abs(cur_perturbed_energy - check_delta) < .0001), (cur_perturbed_energy, check_delta, map_state, map_state_debug)
##### cur_perturbed_energy = check_delta
##### ########### END DEBUGGING ###########
upper_bound += cur_perturbed_energy
# upper_bound = upper_bound/num_trials
upper_bound = upper_bound/num_trials - .5772*N**2
return upper_bound
def estimate_Z_iid_gumbel(sg_model, num_trials):
'''
For debugging, generate iid gumbel for every state in the spin glass model
to estimate the partition function and also compute log(Z) exactly
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
all_states = [[0, 1] for i in range(N**2)]
energies = np.zeros(2**(N**2))
#- state: binary (0,1) array with dimensions (NxN), we are finding the perturbed
#energy of this particular state. state[i,j] = 0 means node ij takes the value -1,
#state[i,j] = 1 means node ij takes the value 1
idx = 0
print sg_model.lcl_fld_params
for cur_state in product(*all_states):
cur_state_array = np.zeros((N,N))
for r in range(N):
for c in range(N):
cur_state_array[r,c] = cur_state[r*N + c]
cur_energy = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), cur_state_array)
energies[idx] = cur_energy
# print '-'*30
# print "idx =", idx
# print "cur_energy", cur_energy
# print "energies", energies
idx += 1
assert(idx == 2**(N**2))
exact_log_Z = 0.0
for cur_energy in energies:
# print "cur_energy", cur_energy
exact_log_Z += np.exp(cur_energy)
exact_log_Z = np.log(exact_log_Z)
# print exact_log_Z
lfp = sg_model.lcl_fld_params[0]
# assert(exact_log_Z == np.log(np.exp(lfp) + np.exp(-lfp))), (exact_log_Z, np.log(np.exp(lfp) + np.exp(-lfp)))
# assert(exact_log_Z < 1.127 and exact_log_Z > .693), (exact_log_Z, sg_model.lcl_fld_params)
log_Z_estimates = []
for itr in range(num_trials):
cur_gumbel_perturbations = np.random.gumbel(loc=0.0, scale=1.0, size=2**(N**2))
cur_log_Z_est = np.max(energies+cur_gumbel_perturbations) - 0.5772
log_Z_estimates.append(cur_log_Z_est)
return (np.mean(log_Z_estimates), exact_log_Z)
def expanded_spin_glass_perturbed_MAP_state(sg_model, copy_factor, perturb_ones, perturb_zeros):
'''
Find the MAP state of an expanded perturbed spin glass model using a min-cut/max-flow
solver for the Gumbel lower bound on Z. This method is faster than a MAP solver for a general
MRF, but can only be used for special cases of MRF's.
For info about what models can be used see:
http://www.cs.cornell.edu/~rdz/Papers/KZ-PAMI04.pdf
For info about transforming the MAP problem into a min-cut problem see:
https://www.classes.cs.uchicago.edu/archive/2006/fall/35040-1/gps.pdf
(N is an implicit parameter, the glass spin model has shape (NxN))
Inputs:
- sg_model: type SG_model, specifies the (original, unexpanded) spin glass model
- copy_factor: int, specifies the number of copies of each variable in the
expanded model. We will take the original (N x N) spin glass model and expand it
to a model with dimensions (copy_factor*N x copy_factor*N), creating copy_factor^2
copies of each variable
- perturb_ones: array with dimensions (copy_factor*N x copy_factor*N), specifies a perturbation of each
node's potential when the node takes the value 1
- perturb_zeros: array with dimensions (copy_factor*N x copy_factor*N), specifies a perturbation of each
node's potential when the node takes the value 0
Outputs:
- map_state: binary array with dimensions (copy_factor*N x copy_factor*N), the state in the
expanded spin glass model with the largest energy. map_state[i,j] = 0 means node (i,j)
is zero in the map state and map_state[i,j] = 1 means node (i,j) is one in the map state
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
g = maxflow.GraphFloat()
#Create (NxN) grid of nodes nodes
nodes = g.add_nodes((copy_factor*N)**2)
t0 = time.time()
#Add single node potentials
for r in range(N):
for c in range(N):
for cpy_idx_r in range(copy_factor):
for cpy_idx_c in range(copy_factor):
lamda_i = (sg_model.lcl_fld_params[r,c] + perturb_ones[cpy_idx_r*N+r, cpy_idx_c*N+c]) \
- (-sg_model.lcl_fld_params[r,c] + perturb_zeros[cpy_idx_r*N+r, cpy_idx_c*N+c])
perturbed_0_potential = np.max((0, lamda_i))
perturbed_1_potential = np.max((0, -lamda_i))
# g.add_tedge(nodes[r*N + c], perturbed_0_potential, perturbed_1_potential)
g.add_tedge(nodes[(cpy_idx_r*N+r)*copy_factor*N + cpy_idx_c*N+c], perturbed_1_potential, perturbed_0_potential)
t1 = time.time()
print "adding single node potentials took:", t1-t0
#DOUBLE CHECK INDEXING HERE!!
#Add two node potentials
edge_count = 0
for r in range(N):
for c in range(N):
for cpy_idx_from_r in range(copy_factor):
for cpy_idx_from_c in range(copy_factor):
for cpy_idx_to_r in range(copy_factor):
for cpy_idx_to_c in range(copy_factor):
#add a horizontal edge
if c < N-1:
g.add_edge(nodes[(cpy_idx_from_r*N + r)*copy_factor*N + cpy_idx_from_c*N + c],
nodes[(cpy_idx_to_r*N + r)*copy_factor*N + cpy_idx_to_c*N + c+1], 2*sg_model.cpl_params_h[r,c], 2*sg_model.cpl_params_h[r,c])
edge_count += 1
#add a vertical edge
if r < N-1:
g.add_edge(nodes[(cpy_idx_from_r*N + r)*copy_factor*N + cpy_idx_from_c*N + c],
nodes[(cpy_idx_to_r*N + r+1)*copy_factor*N + cpy_idx_to_c*N + c], 2*sg_model.cpl_params_v[r,c], 2*sg_model.cpl_params_v[r,c])
edge_count += 1
assert(edge_count == 2*N*(N-1)*copy_factor**4), (edge_count, 2*N*(N-1)*copy_factor**4)
t2 = time.time()
print "adding double node potentials took:", t2-t1
#find the maximum flow
flow = g.maxflow()
t3 = time.time()
print "computing min cut took:", t3-t2
#read out node partitioning for max-flow
map_state = np.zeros((copy_factor*N,copy_factor*N))
for r in range(copy_factor*N):
for c in range(copy_factor*N):
map_state[r,c] = g.get_segment(nodes[r*copy_factor*N + c])
assert(map_state[r,c] == 0 or map_state[r,c] == 1)
return map_state
def calc_expanded_perturbed_energy(sg_model, copy_factor, perturb_ones, perturb_zeros, state):
'''
Compute the perturbed energy of the given state in an expanded spin glass model
(N is an implicit parameter, the glass spin model has shape (NxN))
Inputs:
- sg_model: type SG_model, specifies the spin glass model
- copy_factor: int, specifies the number of copies of each variable in the
expanded model. The original (N x N) spin glass model has been expanded
to a model with dimensions (copy_factor*N x copy_factor*N), with copy_factor^2
copies of each variable
- perturb_ones: array with dimensions (copy_factor*N x copy_factor*N), specifies a perturbation of each
node's potential when the node takes the value 1
- perturb_zeros: array with dimensions (copy_factor*N x copy_factor*N), specifies a perturbation of each
node's potential when the node takes the value 0 (really -1)
- state: binary (0,1) array with dimensions (copy_factor*N x copy_factor*N), we are finding the perturbed
energy of this particular state. state[i,j] = 0 means node ij takes the value -1,
state[i,j] = 1 means node ij takes the value 1
Outputs:
- perturbed_energy: float, the perturbed energy of the specified state in the
specified spin glass model
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
single_node_energy_contribution = 0.0
#Add single node potential and perturbation contributions
for r in range(N):
for c in range(N):
for cpy_idx_r in range(copy_factor):
for cpy_idx_c in range(copy_factor):
if state[r,c] == 1:
single_node_energy_contribution += sg_model.lcl_fld_params[r,c]
single_node_energy_contribution += perturb_ones[cpy_idx_r*N+r, cpy_idx_c*N+c]
else:
assert(state[r,c] == 0)
single_node_energy_contribution -= sg_model.lcl_fld_params[r,c]
single_node_energy_contribution += perturb_zeros[cpy_idx_r*N+r, cpy_idx_c*N+c]
single_node_energy_contribution/=copy_factor**2
#Add two node potential contributions
edge_count = 0
two_node_energy_contribution = 0.0
for r in range(N):
for c in range(N):
for cpy_idx_from_r in range(copy_factor):
for cpy_idx_from_c in range(copy_factor):
for cpy_idx_to_r in range(copy_factor):
for cpy_idx_to_c in range(copy_factor):
#from horizontal edge
if c < N-1:
# g.add_edge(nodes[(cpy_idx_from_r*N + r)*copy_factor*N + cpy_idx_from_c*N + c],
# nodes[(cpy_idx_to_r*N + r)*copy_factor*N + cpy_idx_to_c*N + c+1], 2*sg_model.cpl_params_h[r,c], 2*sg_model.cpl_params_h[r,c])
two_node_energy_contribution += sg_model.cpl_params_h[r,c]\
*(2*state[cpy_idx_from_r*N + r, cpy_idx_from_c*N + c]-1)\
*(2*state[cpy_idx_to_r*N + r,cpy_idx_to_c*N + c +1]-1)
edge_count += 1
#from vertical edge
if r < N-1:
# g.add_edge(nodes[(cpy_idx_from_r*N + r)*copy_factor*N + cpy_idx_from_c*N + c],
# nodes[(cpy_idx_to_r*N + r+1)*copy_factor*N + cpy_idx_to_c*N + c], 2*sg_model.cpl_params_v[r,c], 2*sg_model.cpl_params_v[r,c])
two_node_energy_contribution += sg_model.cpl_params_v[r,c]\
*(2*state[cpy_idx_from_r*N + r, cpy_idx_from_c*N + c]-1)\
*(2*state[cpy_idx_to_r*N + r+1, cpy_idx_to_c*N + c]-1)
edge_count += 1
two_node_energy_contribution/=copy_factor**4
assert(edge_count == 2*N*(N-1)*copy_factor**4)
################ #divide by product_{i=1}^n M_i
################ #where M_i = copy_factor^2 and n = N^2
################ print perturbed_energy
################ perturbed_energy /= (copy_factor**2)**(N**2)
################ print perturbed_energy
perturbed_energy = single_node_energy_contribution + two_node_energy_contribution
return perturbed_energy
def lower_bound_Z_gumbel(sg_model, copy_factor):
'''
Upper bound the partition function of the specified spin glass model using
an empircal estimate of the expected maximum energy perturbed with
Gumbel noise
Inputs:
- sg_model: type SG_model, specifies the spin glass model
- copy_factor: int, specifies the number of copies of each variable in the
expanded model. The original (N x N) spin glass model has been expanded
to a model with dimensions (copy_factor*N x copy_factor*N), with copy_factor^2
copies of each variable
Outputs:
- lower_bound: type float, lower bound on ln(partition function)
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
perturb_ones = np.random.gumbel(loc=-.5772, scale=1.0, size=(copy_factor*N, copy_factor*N))
perturb_zeros = np.random.gumbel(loc=-.5772, scale=1.0, size=(copy_factor*N, copy_factor*N))
expanded_map_state = expanded_spin_glass_perturbed_MAP_state(sg_model, copy_factor, perturb_ones, perturb_zeros)
lower_bound = calc_expanded_perturbed_energy(sg_model, copy_factor, perturb_ones, perturb_zeros, expanded_map_state)
return lower_bound
def enumerate_wishful_term_rademacher_LB(sg_model, lamda):
'''
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
list_all_log_S_1 = []
max_energies = []
all_c_s = [[-1, 1] for i in range(N**2)]
for cur_c in product(*all_c_s):
cur_c_array = np.zeros((N,N))
for r in range(N):
for c in range(N):
cur_c_array[r,c] = cur_c[r*N + c]
perturb_ones = cur_c_array
perturb_zeros = -1*cur_c_array
all_states = [[0, 1] for i in range(N**2)]
energies = np.zeros(2**(N**2))
#- state: binary (0,1) array with dimensions (NxN), we are finding the perturbed
#energy of this particular state. state[i,j] = 0 means node ij takes the value -1,
#state[i,j] = 1 means node ij takes the value 1
idx = 0
# print sg_model.lcl_fld_params
for cur_state in product(*all_states):
cur_state_array = np.zeros((N,N))
for r in range(N):
for c in range(N):
cur_state_array[r,c] = cur_state[r*N + c]
cur_energy = calc_perturbed_energy(sg_model, perturb_ones, perturb_zeros, cur_state_array)
energies[idx] = cur_energy
# print '-'*30
# print "idx =", idx
# print "cur_energy", cur_energy
# print "energies", energies
idx += 1
assert(idx == 2**(N**2))
S_1 = 0.0
for cur_energy in energies:
# print "cur_energy", cur_energy
S_1 += np.exp(lamda*cur_energy)
list_all_log_S_1.append(np.log(S_1))
max_energies.append(np.max(energies))
assert(len(list_all_log_S_1) == 2**(N**2))
expected_log_S_1 = np.mean(list_all_log_S_1)
expected_log_s1_minus_s2 = lamda*np.mean(max_energies)
assert(expected_log_s1_minus_s2 < expected_log_S_1), (expected_log_s1_minus_s2, expected_log_S_1)
return (expected_log_s1_minus_s2 - expected_log_S_1)
def bound_Z_barvinok_wishful(sg_model, k_2):
'''
Test unproven bounds to get an optimistic idea of how bounds
might compare with gumbel
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
#we will take the mean of k_2 solutions to independently perturbed optimization
#problems to tighten the slack term between max and expected max
deltas = []
for i in range(k_2):
random_vec = np.random.rand(N,N)
for r in range(N):
for c in range(N):
if random_vec[r,c] < .5:
random_vec[r,c] = -1
else:
random_vec[r,c] = 1
perturb_ones = random_vec
perturb_zeros = -1*random_vec
map_state = spin_glass_perturbed_MAP_state(sg_model, perturb_ones, perturb_zeros)
cur_delta = calc_perturbed_energy(sg_model, perturb_ones, perturb_zeros, map_state)
deltas.append(cur_delta)
delta_bar = np.mean(deltas)
############# ########### DEBUGGING ###########
############# (delta_exp, map_state_debug) = find_MAP_spin_glass(sg_model, perturb_ones, perturb_zeros)
############# check_delta = np.log(delta_exp)
############# assert(np.abs(check_delta - delta_bar) < .0001)
#############
############# #assert(cur_perturbed_energy == check_delta), (cur_perturbed_energy, check_delta)
############# delta_bar = check_delta
############# ########### END DEBUGGING ###########
total_num_random_vals = N**2
## #option 1 for upper bound on log(permanent)
## total_num_random_vals = N**2
## upper_bound1 = delta_bar + np.sqrt(6*total_num_random_vals/k_2) + total_num_random_vals*np.log(1+1/np.e)
##
wishful_LB = ((delta_bar - np.sqrt(6*total_num_random_vals/k_2))**2)/(2*total_num_random_vals)
#corrected rademacher lower bound
#check optimize beta
unperturbed_map_state = spin_glass_perturbed_MAP_state(sg_model, np.zeros((N,N)), np.zeros((N,N)))
log_w_max = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), unperturbed_map_state)
(w_min, w_min_state) = find_w_min_spin_glass(sg_model)
log_w_min = np.log(w_min)
lambda_prime_w_max = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_max)/total_num_random_vals
lambda_prime_w_min = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)/total_num_random_vals
print "lambda_prime_w_max =", lambda_prime_w_max
print "lambda_prime_w_min =", lambda_prime_w_min
#check whether can we use w_max?
if lambda_prime_w_max >= 1:
print ":) :) we can use w_max for corrected rademacher!!"
print "lambda =", lambda_prime_w_max
wishful_corrected_rademacher_LB = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_max)**2/(2*total_num_random_vals) + log_w_max
extra_expectation = enumerate_wishful_term_rademacher_LB(sg_model, lambda_prime_w_max)
# perturbed_MAP_state = spin_glass_perturbed_MAP_state(sg_model, np.zeros((N,N)), np.zeros((N,N)))
# perturbed_log_w_max = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), perturbed_MAP_state)
# s_1_minus_s_2 = np.exp(lambda_prime_w_max*perturbed_log_w_max)
wishful_corrected_rademacher_LB -= extra_expectation
#check whether can we use w_min?
elif lambda_prime_w_min <= 1:
print ":) we can use w_min for corrected rademacher!!"
print "lambda =", lambda_prime_w_min
print "delta_bar - np.sqrt(6*total_num_random_vals/k_2) =", delta_bar - np.sqrt(6*total_num_random_vals/k_2)
print "log_w_min =", log_w_min
print "2*total_num_random_vals =", 2*total_num_random_vals
print "(delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)**2/(2*total_num_random_vals) =", (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)**2/(2*total_num_random_vals)
wishful_corrected_rademacher_LB = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)**2/(2*total_num_random_vals) + log_w_min
extra_expectation = enumerate_wishful_term_rademacher_LB(sg_model, lambda_prime_w_min)
# perturbed_MAP_state = spin_glass_perturbed_MAP_state(sg_model, np.zeros((N,N)), np.zeros((N,N)))
# perturbed_log_w_max = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), perturbed_MAP_state)
# s_1_minus_s_2 = np.exp(lambda_prime_w_min*perturbed_log_w_max)
wishful_corrected_rademacher_LB -= extra_expectation
else:
print ":( we can't use w_min or w_max for corrected rademacher"
wishful_corrected_rademacher_LB = delta_bar - np.sqrt(6*total_num_random_vals/k_2) - total_num_random_vals/2
extra_expectation = enumerate_wishful_term_rademacher_LB(sg_model, 1.0)
# perturbed_MAP_state = spin_glass_perturbed_MAP_state(sg_model, np.zeros((N,N)), np.zeros((N,N)))
# perturbed_log_w_max = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), perturbed_MAP_state)
# s_1_minus_s_2 = np.exp(1.0*perturbed_log_w_max)
wishful_corrected_rademacher_LB -= extra_expectation
return (wishful_corrected_rademacher_LB, 0.0)
# return (wishful_LB, 0.0)
def upper_bound_Z_barvinok_k2(sg_model, k_2, TEST_PWR_2_BOUND=False):
'''
Upper bound the partition function of the specified spin glass model using
vector perturbations (uniform random in {-1,1}^n) inspired by Barvinok
Inputs:
- sg_model: type SG_model, specifies the spin glass model
- k_2: int, take the mean of k_2 solutions to independently perturbed optimization
problems to tighten the slack term between max and expected max
Outputs:
- upper_bound: type float, upper bound on ln(partition function)
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
#we will take the mean of k_2 solutions to independently perturbed optimization
#problems to tighten the slack term between max and expected max
deltas = []
for i in range(k_2):
random_vec = np.random.rand(N,N)
for r in range(N):
for c in range(N):
if random_vec[r,c] < .5:
random_vec[r,c] = -1
else:
random_vec[r,c] = 1
perturb_ones = random_vec
perturb_zeros = -1*random_vec
map_state = spin_glass_perturbed_MAP_state(sg_model, perturb_ones, perturb_zeros)
cur_delta = calc_perturbed_energy(sg_model, perturb_ones, perturb_zeros, map_state)
deltas.append(cur_delta)
delta_bar = np.mean(deltas)
############# ########### DEBUGGING ###########
############# (delta_exp, map_state_debug) = find_MAP_spin_glass(sg_model, perturb_ones, perturb_zeros)
############# check_delta = np.log(delta_exp)
############# assert(np.abs(check_delta - delta_bar) < .0001)
#############
############# #assert(cur_perturbed_energy == check_delta), (cur_perturbed_energy, check_delta)
############# delta_bar = check_delta
############# ########### END DEBUGGING ###########
#option 1 for upper bound on log(permanent)
total_num_random_vals = N**2
upper_bound1 = delta_bar + np.sqrt(6*total_num_random_vals/k_2) + total_num_random_vals*np.log(1+1/np.e)
#check optimize beta
unperturbed_map_state = spin_glass_perturbed_MAP_state(sg_model, np.zeros((N,N)), np.zeros((N,N)))
log_w_max = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), unperturbed_map_state)
a_min = delta_bar + np.sqrt(6*total_num_random_vals/k_2) - log_w_max
(w_min, w_min_state) = find_w_min_spin_glass(sg_model)
log_w_min = np.log(w_min)
a_max = delta_bar + np.sqrt(6*total_num_random_vals/k_2) - log_w_min
def upper_bound_Z(delta_bar, n, log_w, log_w_type, k_2):
'''
Inputs:
- delta_bar: float, our estimator of the log of the permanent
- n: int, the total number of random values (c is in {-1,1}^n)
- log_w: float, either log_w_min or log_w_max (log of the smallest or largest weight)
- log_w_type: string, either "min" or "max" meaning we are upper bounding using
either the largest or smallest weight
- k_2: int, take the mean of k_2 solutions to independently perturbed optimization
problems to tighten the slack term between max and expected max
Ouputs:
- log_Z_upper_bound: float, upper bound on log(Z)
- beta: float, the optimized value of beta (see our writeup, ratio used in rules)
'''
assert(log_w_type in ["min", "max"])
a = delta_bar + np.sqrt(6*n/k_2) - log_w
if log_w_type == "max":
if a/n > .5:
beta = .5
# if a/n > 1:
# beta = 1
elif a/n < 1/(1+np.e):
beta = 1/(1+np.e)
else:
beta = a/n
elif log_w_type == "min":
if a/n > 1/(1+np.e):
beta = 1/(1+np.e)
elif a/n < 0:
beta = 0
else:
beta = a/n
PRINT_DEBUG = True
if PRINT_DEBUG:
print "beta =", beta
log_Z_upper_bound = np.log((1-beta)/beta)*a - n*np.log(1-beta) + log_w
return log_Z_upper_bound, beta
(upper_bound_w_min, beta_w_min) = upper_bound_Z(delta_bar, total_num_random_vals, log_w_min, "min", k_2)
(upper_bound_w_max, beta_w_max) = upper_bound_Z(delta_bar, total_num_random_vals, log_w_max, "max", k_2)
if np.isnan(upper_bound_w_min):
upper_bound_w_min = np.PINF
if np.isnan(upper_bound_w_max):
upper_bound_w_max = np.PINF
upper_bound_opt_beta = min([upper_bound_w_min, upper_bound_w_max, upper_bound1])
############ upper_bound_opt_beta = upper_bound1
############ upper_bound_opt_beta = min([upper_bound_w_max, upper_bound1])
# if (delta_bar + np.sqrt(6*total_num_random_vals/k_2) - log_w_max)/total_num_random_vals >= .5 or \
# (delta_bar + np.sqrt(6*total_num_random_vals/k_2) - log_w_max)/total_num_random_vals <= 1/(1+np.e) or \
# (delta_bar + np.sqrt(6*total_num_random_vals/k_2) - log_w_min)/total_num_random_vals >= 1/(1+np.e) or \
# (delta_bar + np.sqrt(6*total_num_random_vals/k_2) - log_w_min)/total_num_random_vals <= 0:
# assert(upper_bound_opt_beta == upper_bound1), (upper_bound_opt_beta, [upper_bound_w_min, upper_bound_w_max, upper_bound1])
# else:
# assert(upper_bound_opt_beta == upper_bound_w_max or upper_bound_opt_beta == upper_bound_w_min)
#
#corrected rademacher lower bound
lambda_prime_w_max = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_max)/total_num_random_vals
lambda_prime_w_min = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)/total_num_random_vals
print "lambda_prime_w_max =", lambda_prime_w_max
print "lambda_prime_w_min =", lambda_prime_w_min
#check whether can we use w_max?
if lambda_prime_w_max >= 1:
print ":) :) we can use w_max for corrected rademacher!!"
print "lambda =", lambda_prime_w_max
corrected_rademacher_LB = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_max)**2/(2*total_num_random_vals) + log_w_max
#check whether can we use w_min?
elif lambda_prime_w_min <= 1:
print ":) we can use w_min for corrected rademacher!!"
print "lambda =", lambda_prime_w_min
print "delta_bar - np.sqrt(6*total_num_random_vals/k_2) =", delta_bar - np.sqrt(6*total_num_random_vals/k_2)
print "log_w_min =", log_w_min
print "2*total_num_random_vals =", 2*total_num_random_vals
print "(delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)**2/(2*total_num_random_vals) =", (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)**2/(2*total_num_random_vals)
corrected_rademacher_LB = (delta_bar - np.sqrt(6*total_num_random_vals/k_2) - log_w_min)**2/(2*total_num_random_vals) + log_w_min
else:
print ":( we can't use w_min or w_max for corrected rademacher"
corrected_rademacher_LB = delta_bar - np.sqrt(6*total_num_random_vals/k_2) - total_num_random_vals/2
#testing lower bound that should be easy to show for weights that are powers of two
if TEST_PWR_2_BOUND:
all_states = [[0, 1] for i in range(N**2)]
energies = np.zeros(2**(N**2))
#- state: binary (0,1) array with dimensions (NxN), we are finding the perturbed
#energy of this particular state. state[i,j] = 0 means node ij takes the value -1,
#state[i,j] = 1 means node ij takes the value 1
idx = 0
print sg_model.lcl_fld_params
for cur_state in product(*all_states):
cur_state_array = np.zeros((N,N))
for r in range(N):
for c in range(N):
cur_state_array[r,c] = cur_state[r*N + c]
cur_energy = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), cur_state_array)
energies[idx] = cur_energy
# print '-'*30
# print "idx =", idx
# print "cur_energy", cur_energy
# print "energies", energies
idx += 1
assert(idx == 2**(N**2))
avg_log_weight = np.mean(energies)
# pwr_2_LB = (delta_bar/np.sqrt(total_num_random_vals) - 7/np.sqrt(k_2))**2/16
n_prime = total_num_random_vals + log_w_max - log_w_min
pwr_2_LB = ((delta_bar - log_w_min - (avg_log_weight-log_w_min))**2)/(2*total_num_random_vals/k_2) - 3/k_2 + log_w_min
print '@'*80
print "check power2:"
print "take2, ((delta_bar - log_w_min - avg_log_weight)**2)/(2*total_num_random_vals/k_2) - 3/k_2 + log_w_min =", ((delta_bar - log_w_min- (avg_log_weight-log_w_min))**2)/(2*total_num_random_vals/k_2) - 3/k_2 + log_w_min
print "log_w_min =", log_w_min
print "log_w_max =", log_w_max
print "avg_log_weight =", avg_log_weight
print "n_prime =", n_prime
print "(delta_bar/np.sqrt(total_num_random_vals) - 7/np.sqrt(k_2))**2/16", (delta_bar/np.sqrt(total_num_random_vals) - 7/np.sqrt(k_2))**2/16
print "(delta_bar/np.sqrt(total_num_random_vals) - 7/np.sqrt(k_2))**2", (delta_bar/np.sqrt(total_num_random_vals) - 7/np.sqrt(k_2))**2
print "(delta_bar/np.sqrt(total_num_random_vals) - 7/np.sqrt(k_2))", (delta_bar/np.sqrt(total_num_random_vals) - 7/np.sqrt(k_2))
print "delta_bar/np.sqrt(total_num_random_vals)", delta_bar/np.sqrt(total_num_random_vals)
print "delta_bar", delta_bar, "np.sqrt(total_num_random_vals) =", np.sqrt(total_num_random_vals)
if TEST_PWR_2_BOUND:
return (corrected_rademacher_LB, pwr_2_LB, upper_bound_opt_beta)
else:
return (corrected_rademacher_LB, upper_bound_opt_beta, delta_bar)
############ return(upper_bound1, upper_bound_w_max, upper_bound_opt_beta)
def upper_bound_Z_barvinok(sg_model):
'''
Upper bound the partition function of the specified spin glass model using
vector perturbations (uniform random in {-1,1}^n) inspired by Barvinok
Inputs:
- sg_model: type SG_model, specifies the spin glass model
Outputs:
- upper_bound: type float, upper bound on ln(partition function)
'''
N = sg_model.lcl_fld_params.shape[0]
assert(N == sg_model.lcl_fld_params.shape[1])
random_vec = np.random.rand(N,N)
for r in range(N):
for c in range(N):
if random_vec[r,c] < .5:
random_vec[r,c] = -1
else:
random_vec[r,c] = 1
perturb_ones = random_vec
perturb_zeros = -1*random_vec
map_state = spin_glass_perturbed_MAP_state(sg_model, perturb_ones, perturb_zeros)
delta = calc_perturbed_energy(sg_model, perturb_ones, perturb_zeros, map_state)
############# ########### DEBUGGING ###########
############# (delta_exp, map_state_debug) = find_MAP_spin_glass(sg_model, perturb_ones, perturb_zeros)
############# check_delta = np.log(delta_exp)
############# assert(np.abs(check_delta - delta) < .0001)
#############
############# #assert(cur_perturbed_energy == check_delta), (cur_perturbed_energy, check_delta)
############# delta = check_delta
############# ########### END DEBUGGING ###########
#option 1 for upper bound on log(permanent)
total_num_random_vals = N**2
upper_bound1 = delta + np.sqrt(6*total_num_random_vals) + total_num_random_vals*np.log(1+1/np.e)
#check optimize beta
unperturbed_map_state = spin_glass_perturbed_MAP_state(sg_model, np.zeros((N,N)), np.zeros((N,N)))
log_w_max = calc_perturbed_energy(sg_model, np.zeros((N,N)), np.zeros((N,N)), unperturbed_map_state)
a_min = delta + np.sqrt(6*total_num_random_vals) - log_w_max
############ a_max = delta + np.sqrt(6*total_num_random_vals) - log_w_min
def upper_bound_Z(delta, n, log_w, log_w_type):
'''
Inputs:
- delta: float, our estimator of the log of the permanent
- n: int, the total number of random values (c is in {-1,1}^n)
- log_w: float, either log_w_min or log_w_max (log of the smallest or largest weight)
- log_w_type: string, either "min" or "max" meaning we are upper bounding using
either the largest or smallest weight
Ouputs: