-
Notifications
You must be signed in to change notification settings - Fork 2
/
nestingUB_gumbel_sample_permanent.py
4129 lines (3512 loc) · 288 KB
/
nestingUB_gumbel_sample_permanent.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
from munkres import Munkres, print_matrix
import sys
import itertools
import math
from operator import itemgetter
from permanent import permanent as rysers_permanent
from scipy.optimize import linear_sum_assignment, minimize, LinearConstraint
from pymatgen.optimization import linear_assignment
import matplotlib
matplotlib.use('Agg') #prevent error running remotely
import matplotlib.pyplot as plt
from collections import defaultdict
import heapq
import time
from profilehooks import profile
import pickle
import numba as nb
import scipy
import scipy.stats
import scipy.io
import copy
import os
import networkx as nx
# import ot
# from libc.stdlib cimport malloc, free
# from libc.math cimport pow
# sys.path.insert(0, '/Users/jkuck/research/atlas_AAAI_2017/refactored_multi_model/')
# from permanent_model import compute_gumbel_upper_bound, approx_permanent3
# from boundZ import calculate_gumbel_slack
sys.path.insert(0, '/atlas/u/jkuck/rbpf_fireworks/mht_helpers')
# from k_best_assignment import k_best_assignments
#'pymatgen' should be fastest, significantly
#pick from ['munkres', 'scipy', 'pymatgen'],
ASSIGNMENT_SOLVER = 'pymatgen'
# random.seed(0)
SEED=2
np.random.seed(SEED)
PICK_PARTITION_ORDER = False
USE_1_GUMBEL = True
DEBUG = False
DEBUG1 = False
FIRST_GUMBEL_LARGER = []
BEST_ROW_CACHE={}
matrix_permanent_UBs = {}
COMPARE_WAI = False
#
#
#References:
# [1] K. G. Murty, "Letter to the Editor--An Algorithm for Ranking all the Assignments in Order of
# Increasing Cost," Oper. Res., vol. 16, no. May 2016, pp. 682-687, 1968.
#
# [2] I. J. Cox and M. L. Miller, "On finding ranked assignments with application to multitarget
# tracking and motion correspondence," IEEE Trans. Aerosp. Electron. Syst., vol. 31, no. 1, pp.
# 486-489, Jan. 1995.
# @profile
def sample_log_permanent_with_gumbels(matrix, clear_caches_new_matrix):
'''
Inputs:
- matrix: (numpy array) all entries should be non-negative
Output:
- sampled_association: a list of pairs where each pair represents an association
in the assignment (1's in assignment matrix)
- sample_of_logZ: (float), a sample from a Gumbel variable with location=ln(Z) and scale=1
'''
# key: tuple of (required_cells, submatrix), where
# required_cells: tuple of ((row, col), (row, col), ...)
# submatrix: tuple of ((a, b, c, ...), (d, e, f, ...), ...)
# value: (int) upper bound on the permanent
# print "-"*80
# print "sample_log_permanent_with_gumbels just called"
# print "exact_permanent =", calc_permanent_rysers(matrix)
# print "matrix:", matrix
# BEST_ROW_CACHE = {}
global matrix_permanent_UBs
global BEST_ROW_CACHE
if clear_caches_new_matrix:
matrix_permanent_UBs = {}
BEST_ROW_CACHE = {}
N = matrix.shape[0]
assert(N == matrix.shape[1])
global ORIGINAL_MATRIX
ORIGINAL_MATRIX = matrix
#convert 2d array to tuple of tuples
hashable_matrix = tuple([tuple(row) for row in matrix])
no_required_cells = ()
complete_matrix_permanent_UB = (minc_extended_UB2(matrix)) #add a little for potential computational error, would be nice to make this cleaner
matrix_permanent_UBs[no_required_cells] = complete_matrix_permanent_UB
gumbel_truncation = np.inf
sampled_association = None
first_sample = True
while(True):
#sample a gumbel that is the max of log(floor(matrix_permanent_UBs[no_required_cells])) gumbels
cur_sampled_gumbel = compare_truncated_gumbel(n_vals=[matrix_permanent_UBs[no_required_cells]], truncation=gumbel_truncation)[0]
global_row_indices = range(N)
global_col_indices = range(N)
sampled_association, sub_tree_slack = sample_association_01matrix_plusSlack(matrix, matrix_permanent_UBs[no_required_cells], \
matrix_permanent_UBs, prv_required_cells=[], depth=1, \
global_row_indices=global_row_indices, global_col_indices=global_col_indices, first_sample=first_sample)
if sampled_association is None: #we sampled a weight 0 association from proposal
# print "subtracting sub_tree_slack", sub_tree_slack, "from no_required_cells:", no_required_cells
# check_bounds_add_up(matrix, no_required_cells, global_row_indices, global_col_indices)
gumbel_truncation = cur_sampled_gumbel
# print "matrix_permanent_UBs before 99", matrix_permanent_UBs
# print "matrix_permanent_UBs before 99", matrix_permanent_UBs
# print "matrix_permanent_UBs[no_required_cells]:", matrix_permanent_UBs[no_required_cells]
else: #we sampled a weight 1 association and are done
break
first_sample = False
sample_of_logZ = cur_sampled_gumbel - np.euler_gamma#weight is 1, so ln(weight) = ln(1) = 0
# sampled_association = correct_sampled_association_indices(sampled_association)
cur_permanentUB = matrix_permanent_UBs[no_required_cells]
print_sampled_association_weight = True
if print_sampled_association_weight:
sampled_association_weight = 1.0
for row, col in sampled_association:
sampled_association_weight *= matrix[row, col]
print "sampled_association_weight:", sampled_association_weight
return (sampled_association, sample_of_logZ, cur_permanentUB)
def correct_sampled_association_indices(incorrect_sampled_association):
used_cols = defaultdict(int)
corrected_row = 0
correct_sampled_association = []
print "incorrect_sampled_association:", incorrect_sampled_association
for cur_assoc in incorrect_sampled_association:
cur_incorrect_col = cur_assoc[1]
cur_corrected_col = cur_incorrect_col
for col, col_count in used_cols.iteritems():
if cur_incorrect_col >= col:
cur_corrected_col += col_count
used_cols[cur_incorrect_col] += 1
correct_sampled_association.append((corrected_row, cur_corrected_col))
corrected_row += 1
print "correct_sampled_association:", correct_sampled_association
print
print
return correct_sampled_association
def check_bounds_add_up_simple(original_matrix, prv_required_cells):
return
total_UB = matrix_permanent_UBs[tuple(prv_required_cells)]
sum_of_sub_UBs = 0.0
for cur_req_cells, sub_matrix_UB in matrix_permanent_UBs.items():
if len(cur_req_cells) == len(prv_required_cells) + 1 and\
cur_req_cells == prv_required_cells[:len(cur_req_cells)]:
sum_of_sub_UBs += sub_matrix_UB*original_matrix[cur_req_cells[-1]]
print "sub_matrix_UB*original_matrix[cur_req_cells[-1]]:", sub_matrix_UB*original_matrix[cur_req_cells[-1]]
if sum_of_sub_UBs <= total_UB + .000001:
pass
# print "Correct!", sum_of_sub_UBs, "<", total_UB
else:
pass
# print "incorrect!", sum_of_sub_UBs, ">", total_UB
assert (sum_of_sub_UBs <= total_UB + .000001), (sum_of_sub_UBs - total_UB, sum_of_sub_UBs, total_UB, prv_required_cells)
def check_bounds_add_up(matrix, prv_required_cells, global_row_indices, global_col_indices):
print "check_bounds_add_up called on:"
print "matrix:", matrix
print "prv_required_cells:", prv_required_cells
global_best_row_to_partition = find_best_row_to_partition_matrix(matrix, prv_required_cells, first_sample=False, verbose=False)
#get local index
best_row_to_partition = global_best_row_to_partition
# best_row_to_partition = list(global_row_indices).index(global_best_row_to_partition)
print "global_row_indices[best_row_to_partition]:", global_row_indices[best_row_to_partition]
print "matrix_permanent_UBs:", matrix_permanent_UBs
matrix_UB = matrix_permanent_UBs[tuple(prv_required_cells)]
proposal_distribution = []
N = matrix.shape[0]
assert(N == matrix.shape[1])
fixed_column_options = list(itertools.permutations(range(N), 1))
for fixed_columns in (fixed_column_options):
cur_submatrix = np.delete(matrix, fixed_columns, 1) #delete columns
cur_submatrix = np.delete(cur_submatrix, [best_row_to_partition], 0) #delete rows
print "global_row_indices:", global_row_indices
print "best_row_to_partition:", best_row_to_partition
print "global_col_indices:", global_col_indices
print "fixed_columns:", fixed_columns
print "best_row_to_partition:", best_row_to_partition
print "N:", N
required_cells = tuple(prv_required_cells + [(global_row_indices[best_row_to_partition], global_col_indices[fixed_columns[0]])])
submatrix_permanent_UB = matrix_permanent_UBs[tuple(required_cells)]
# submatrix_permanent_UB = (minc_extended_UB2(cur_submatrix)) #add a little for potential computational error, would be nice to make this cleaner
upper_bound_submatrix_count = submatrix_permanent_UB
upper_bound_submatrix_count *= matrix[best_row_to_partition, fixed_columns[0]]
proposal_distribution.append(upper_bound_submatrix_count)
cur_partitioned_UB = np.sum(proposal_distribution)
assert(np.abs(cur_partitioned_UB - matrix_UB) < .001), (cur_partitioned_UB, matrix_UB)
def sinkhorn_scale(matrix, debug=False):
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
cols_scaling = np.ones(N)
rows_scaling = np.ones(N)
original_matrix = copy.copy(matrix)
iters = 0
while(True):
col_sums = np.sum(matrix, axis=0)
col_normalized_matrix = matrix / col_sums
row_sums = np.sum(col_normalized_matrix, axis=1)
double_stochastic_matrix = col_normalized_matrix/row_sums[:,None]
cols_scaling /= col_sums
rows_scaling /= row_sums
if np.allclose(matrix, double_stochastic_matrix):
break
else:
matrix = double_stochastic_matrix
if debug:
iters += 1
print "iters:", iters
assert(np.allclose(original_matrix*cols_scaling*rows_scaling[:,None], double_stochastic_matrix))
assert(np.allclose(np.sum(double_stochastic_matrix, axis=0), np.ones(N)))
assert(np.allclose(np.sum(double_stochastic_matrix, axis=1), np.ones(N)))
return double_stochastic_matrix, cols_scaling, rows_scaling
def sinkhorn_scale_fast(matrix, lam=1):
M = -np.log(matrix)/lam
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
a = np.ones(N)
b = np.ones(N)
results = ot.sinkhorn(a,b,M,1,method='sinkhorn',numItermax=10000000000,log=True)
print("results:", results)
double_stochastic_matrix = results[0]
cols_scaling = results[1]['v']
rows_scaling = results[1]['u']
check_scaled_matrix = cols_scaling*np.expand_dims(rows_scaling, axis=1)*matrix
print("check_scaled_matrix:", check_scaled_matrix)
print(np.sum(check_scaled_matrix, axis=0))
print(np.sum(check_scaled_matrix, axis=1))
# print("cols_scaling:", cols_scaling)
# print("rows_scaling:", rows_scaling)
# print("double_stochastic_matrix:", double_stochastic_matrix)
return cols_scaling, rows_scaling, double_stochastic_matrix
def conjectured_optimal_bound(matrix):
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
double_stochastic_matrix, cols_scaling, rows_scaling = sinkhorn_scale(matrix)
one_minus_matrix = 1 - double_stochastic_matrix
permanent_UB = 2**(N/2) * np.prod(np.power(one_minus_matrix, one_minus_matrix)) / (np.prod(cols_scaling)*np.prod(rows_scaling))
# permanent_UB = 2**(N) * np.prod(np.power(one_minus_matrix, one_minus_matrix)) / (np.prod(cols_scaling)*np.prod(rows_scaling))
return permanent_UB
# @profile
def minc_extended_UB2_excludeRowCol(matrix, excluded_row, excluded_col):
#another bound
#https://ac-els-cdn-com.stanford.idm.oclc.org/S002437950400299X/1-s2.0-S002437950400299X-main.pdf?_tid=fa4d00ee-39a5-4030-b7c1-28bb5fbc76c0&acdnat=1534454814_a7411b3006e0e092622de35cbf015275
# equation (6), U^M(A)
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
minc_extended_upper_bound2 = 1.0
for row in range(N):
if row == excluded_row:
continue
sorted_row = sorted(zip(matrix[row], range(N)), reverse=True)
row_sum = 0
delta_idx = 0
for col in range(N):
if sorted_row[col][1] == excluded_col:
continue
row_sum += sorted_row[col][0] * delta(delta_idx+1)
delta_idx += 1
# row_sum += sorted_row[col][0] * numba_delta(col+1)
minc_extended_upper_bound2 *= row_sum
return minc_extended_upper_bound2
# @profile
def find_best_row_to_partition_matrix_faster(matrix, prv_required_cells, first_sample, permanentUB, verbose=False):
if COMPARE_WAI:
return 0
N = matrix.shape[0]
assert(N == matrix.shape[1])
global BEST_ROW_CACHE
# print "BEST_ROW_CACHE:"
# print BEST_ROW_CACHE
if first_sample and len(prv_required_cells) == 0:
pass
# BEST_ROW_CACHE = {} #clear the cache, new matrix
# print "cache cleared!!"
else:
assert(len(BEST_ROW_CACHE)>0), (first_sample, len(prv_required_cells), BEST_ROW_CACHE) #the cache should contain something
if tuple(prv_required_cells) in BEST_ROW_CACHE:
if verbose:
print "returning cached result"
# print "smallest_partitioned_upper_bound =", BEST_ROW_CACHE[tuple(prv_required_cells)]
return BEST_ROW_CACHE[tuple(prv_required_cells)]
#check if first row is valid
proposal_distribution = []
for col in range(N):
submatrix_permanent_UB = minc_extended_UB2_excludeRowCol(matrix, excluded_row=0, excluded_col=col)
# print row, col, submatrix_permanent_UB
upper_bound_submatrix_count = submatrix_permanent_UB
upper_bound_submatrix_count *= matrix[0, col]
proposal_distribution.append(upper_bound_submatrix_count)
first_row_partitioned_UB = np.sum(proposal_distribution)
if first_row_partitioned_UB < permanentUB:
BEST_ROW_CACHE[tuple(prv_required_cells)] = 0
return 0
# permanentUB = (minc_extended_UB2(matrix))
if verbose:
print "find_best_row_to_partition_matrix_fast", '*'*80
print "permanentUB:", permanentUB
row_with_smallest_partitioned_UB = None
smallest_partitioned_upper_bound = None
for row in range(N):
proposal_distribution = []
for col in range(N):
submatrix_permanent_UB = minc_extended_UB2_excludeRowCol(matrix, excluded_row=row, excluded_col=col)
# print row, col, submatrix_permanent_UB
upper_bound_submatrix_count = submatrix_permanent_UB
upper_bound_submatrix_count *= matrix[row, col]
proposal_distribution.append(upper_bound_submatrix_count)
cur_partitioned_UB = np.sum(proposal_distribution)
if smallest_partitioned_upper_bound is None or cur_partitioned_UB < smallest_partitioned_upper_bound:
smallest_partitioned_upper_bound = cur_partitioned_UB
row_with_smallest_partitioned_UB = row
if verbose:
print "partitioned UB:", np.sum(proposal_distribution)
print "(partitioned UB)/permanentUB:", np.sum(proposal_distribution)/permanentUB
# assert(np.sum(proposal_distribution)/permanentUB < 1), (np.sum(proposal_distribution), permanentUB, matrix)
if verbose:
print "returning new result"
print "smallest_partitioned_upper_bound =", smallest_partitioned_upper_bound, "permanentUB =", permanentUB
if verbose:
print "smallest_partitioned_upper_bound =", smallest_partitioned_upper_bound, "permanentUB =", permanentUB
assert(smallest_partitioned_upper_bound <= permanentUB + .000001), (smallest_partitioned_upper_bound, permanentUB)
BEST_ROW_CACHE[tuple(prv_required_cells)] = row_with_smallest_partitioned_UB
# print "BEST_ROW_CACHE:"
# print BEST_ROW_CACHE
return row_with_smallest_partitioned_UB
# @profile
def find_best_row_to_partition_matrix(matrix, prv_required_cells, first_sample, verbose=False):
if COMPARE_WAI:
return 0
global BEST_ROW_CACHE
# print "BEST_ROW_CACHE:"
# print BEST_ROW_CACHE
if first_sample and len(prv_required_cells) == 0:
pass
# BEST_ROW_CACHE = {} #clear the cache, new matrix
# print "cache cleared!!"
else:
assert(len(BEST_ROW_CACHE)>0), (first_sample, len(prv_required_cells), BEST_ROW_CACHE) #the cache should contain something
if tuple(prv_required_cells) in BEST_ROW_CACHE:
if verbose:
print "returning cached result"
# print "smallest_partitioned_upper_bound =", BEST_ROW_CACHE[tuple(prv_required_cells)]
return BEST_ROW_CACHE[tuple(prv_required_cells)]
N = matrix.shape[0]
assert(N == matrix.shape[1])
fixed_column_options = list(itertools.permutations(range(N), 1))
matrix_UB = (minc_extended_UB2(matrix))
if verbose:
print "find_best_row_to_partition_matrix", '*'*80
print "matrix_UB:", matrix_UB
deltas = np.array([delta(i + 1) for i in range(N - 1)])
row_sum = np.empty_like(matrix, dtype=float)
for col in range(N):
matrix_sorted = np.sort(np.delete(matrix, col, 1), axis=1)[:, ::-1]
row_sum[:, col] = (matrix_sorted * deltas).sum(axis=1)
# Can't use this trick to multiply all the rows and then divide, as we might get 0 / 0
# upper_bounds_excluding_row_col = row_sum.prod(axis=0) / row_sum
upper_bounds_excluding_row_col = np.empty_like(matrix, dtype=float)
for row in range(N):
upper_bounds_excluding_row_col[row] = np.delete(row_sum, row, 0).prod(axis=0)
# The (i, j)-element is the upper bound of the submatrix after deleting the i-th row and j-th column
partitioned_UB = (upper_bounds_excluding_row_col * matrix).sum(axis=1)
row_with_smallest_partitioned_UB = np.argmin(partitioned_UB)
smallest_partitioned_upper_bound = partitioned_UB[row_with_smallest_partitioned_UB]
if verbose:
print "returning new result"
print "smallest_partitioned_upper_bound =", smallest_partitioned_upper_bound, "matrix_UB =", matrix_UB
if verbose:
print "smallest_partitioned_upper_bound =", smallest_partitioned_upper_bound, "matrix_UB =", matrix_UB
assert(smallest_partitioned_upper_bound < matrix_UB or np.allclose(smallest_partitioned_upper_bound, matrix_UB)), (smallest_partitioned_upper_bound, matrix_UB, matrix.shape, matrix)
BEST_ROW_CACHE[tuple(prv_required_cells)] = row_with_smallest_partitioned_UB
# print "BEST_ROW_CACHE:"
# print BEST_ROW_CACHE
return row_with_smallest_partitioned_UB
def find_best_row_to_partition_matrix_not_vectorized(matrix, prv_required_cells, first_sample, verbose=False):
# return 0
global BEST_ROW_CACHE
# print "BEST_ROW_CACHE:"
# print BEST_ROW_CACHE
if first_sample and len(prv_required_cells) == 0:
pass
# BEST_ROW_CACHE = {} #clear the cache, new matrix
# print "cache cleared!!"
else:
assert(len(BEST_ROW_CACHE)>0), (first_sample, len(prv_required_cells), BEST_ROW_CACHE) #the cache should contain something
if tuple(prv_required_cells) in BEST_ROW_CACHE:
if verbose:
print "returning cached result"
# print "smallest_partitioned_upper_bound =", BEST_ROW_CACHE[tuple(prv_required_cells)]
return BEST_ROW_CACHE[tuple(prv_required_cells)]
N = matrix.shape[0]
assert(N == matrix.shape[1])
fixed_column_options = list(itertools.permutations(range(N), 1))
matrix_UB = (minc_extended_UB2(matrix))
if verbose:
print "find_best_row_to_partition_matrix", '*'*80
print "matrix_UB:", matrix_UB
row_with_smallest_partitioned_UB = None
smallest_partitioned_upper_bound = None
for row in range(N):
proposal_distribution = []
for fixed_columns in (fixed_column_options):
cur_submatrix = np.delete(matrix, fixed_columns, 1) #delete columns
cur_submatrix = np.delete(cur_submatrix, [row], 0) #delete rows
submatrix_permanent_UB = (minc_extended_UB2(cur_submatrix)) #add a little for potential computational error, would be nice to make this cleaner
# print row, fixed_columns, submatrix_permanent_UB
upper_bound_submatrix_count = submatrix_permanent_UB
upper_bound_submatrix_count *= matrix[row, fixed_columns[0]]
proposal_distribution.append(upper_bound_submatrix_count)
cur_partitioned_UB = np.sum(proposal_distribution)
if smallest_partitioned_upper_bound is None or cur_partitioned_UB < smallest_partitioned_upper_bound:
smallest_partitioned_upper_bound = cur_partitioned_UB
row_with_smallest_partitioned_UB = row
if verbose:
print "partitioned UB:", np.sum(proposal_distribution)
print "(partitioned UB)/matrix_UB:", np.sum(proposal_distribution)/matrix_UB
# assert(np.sum(proposal_distribution)/matrix_UB < 1), (np.sum(proposal_distribution), matrix_UB, matrix)
if verbose:
print "returning new result"
print "smallest_partitioned_upper_bound =", smallest_partitioned_upper_bound, "matrix_UB =", matrix_UB
if verbose:
print "smallest_partitioned_upper_bound =", smallest_partitioned_upper_bound, "matrix_UB =", matrix_UB
assert(smallest_partitioned_upper_bound < matrix_UB or np.allclose(smallest_partitioned_upper_bound, matrix_UB)), (smallest_partitioned_upper_bound, matrix_UB)
BEST_ROW_CACHE[tuple(prv_required_cells)] = row_with_smallest_partitioned_UB
# print "BEST_ROW_CACHE:"
# print BEST_ROW_CACHE
return row_with_smallest_partitioned_UB
def sample_association_01matrix_plusSlack(matrix, permanentUB, matrix_permanent_UBs, prv_required_cells, depth, \
global_row_indices, global_col_indices, first_sample=False):
'''
Inputs:
- matrix: (np.array of shap NxN)
- prv_required_cells: (list of tuples), [(row, col), ...]
Outputs: list of length N of tuples representing (row, col) associations
'''
# print "depth =", depth
if DEBUG1:
print "matrix_permanent_UBs:", matrix_permanent_UBs
local_matrix = np.copy(matrix)
N = local_matrix.shape[0]
assert(N == local_matrix.shape[1])
# Get all permutations of length depth of numbers 0 through N-1
fixed_column_options = list(itertools.permutations(range(N), depth))
prv_required_cells_copy = copy.copy(prv_required_cells)
best_row_to_partition = find_best_row_to_partition_matrix(local_matrix, prv_required_cells_copy, first_sample)
# best_row_to_partition = find_best_row_to_partition_matrix_faster(local_matrix, prv_required_cells_copy, first_sample, permanentUB)
#swap rows
# temp_row = np.copy(local_matrix[0])
# local_matrix[0] = local_matrix[best_row_to_partition]
# local_matrix[best_row_to_partition] = temp_row
local_matrix[[0,best_row_to_partition]] = local_matrix[[best_row_to_partition,0]]
#swap global indices
if DEBUG1:
print "about to swap global_row_indices"
print "prv_required_cells:", prv_required_cells, "best_row_to_partition:", best_row_to_partition, "global_row_indices:", global_row_indices
temp_idx = global_row_indices[0]
global_row_indices[0] = global_row_indices[best_row_to_partition]
global_row_indices[best_row_to_partition] = temp_idx
if DEBUG1:
print "after swap global_row_indices"
print "prv_required_cells:", prv_required_cells, "best_row_to_partition:", best_row_to_partition, "global_row_indices:", global_row_indices
proposal_distribution = []
if DEBUG1:
print "submatrix upper bounds:"
for fixed_columns in (fixed_column_options):
cur_submatrix = np.delete(local_matrix, fixed_columns, 1) #delete columns
cur_submatrix = np.delete(cur_submatrix, range(depth), 0) #delete rows
hashable_matrix = tuple([tuple(row) for row in cur_submatrix])
required_cells = tuple(prv_required_cells_copy + [(global_row_indices[row], global_col_indices[fixed_columns[row]]) for row in range(depth)])
if required_cells in matrix_permanent_UBs:
submatrix_permanent_UB = matrix_permanent_UBs[required_cells]
else:
submatrix_permanent_UB = (minc_extended_UB2(cur_submatrix)) #add a little for potential computational error, would be nice to make this cleaner
assert(submatrix_permanent_UB > -.000000001)
if submatrix_permanent_UB < 0:
submatrix_permanent_UB = 0
matrix_permanent_UBs[required_cells] = submatrix_permanent_UB
# print submatrix_permanent_UB
upper_bound_submatrix_count = submatrix_permanent_UB
for row in range(depth):
upper_bound_submatrix_count *= local_matrix[row, fixed_columns[row]]
assert(submatrix_permanent_UB >= 0), submatrix_permanent_UB
proposal_distribution.append(upper_bound_submatrix_count)
if DEBUG1:
print upper_bound_submatrix_count,
if DEBUG1:
print
sum_of_submatrix_UBs = np.sum(proposal_distribution)
if DEBUG1:
print "prv_required_cells_copy:", prv_required_cells_copy
print "local_matrix:", local_matrix
print "sum_of_submatrix_UBs:", sum_of_submatrix_UBs
print "permanentUB:", permanentUB
EPSILON = 0.0001
# if sum_of_submatrix_UBs <= permanentUB+EPSILON:
# if (sum_of_submatrix_UBs-permanentUB)/permanentUB <= EPSILON:
if sum_of_submatrix_UBs <= permanentUB or np.allclose(sum_of_submatrix_UBs, permanentUB):
# print "sum_of_submatrix_UBs <= permanentUB :):):)"
cur_level_slack = permanentUB - sum_of_submatrix_UBs
check_bounds_add_up_simple(ORIGINAL_MATRIX, prv_required_cells_copy)
if cur_level_slack < 0.0:
cur_level_slack = 0.0
if DEBUG1:
print "cur_level_slack =", cur_level_slack
print "sum_of_submatrix_UBs =", sum_of_submatrix_UBs
print "permanentUB =", permanentUB
proposal_distribution.append(cur_level_slack)
# print "un-normalized proposal_distribution:", proposal_distribution
proposal_distribution /= np.sum(proposal_distribution)
# print "proposal_distribution:", proposal_distribution
# print
sampled_association_idx = np.random.choice(len(proposal_distribution), p=proposal_distribution)
# print "proposal distribution:", proposal_distribution
if sampled_association_idx == len(proposal_distribution) - 1:
# print "we sampled the junk bin"
sampled_association = None #we sampled a weight 0 association
# hashable_matrix = tuple([tuple(row) for row in local_matrix])
# required_cells = tuple(prv_required_cells_copy)
# print "calling 179 with required_cells:", required_cells
# print "matrix_permanent_UBs before 179", matrix_permanent_UBs
# matrix_permanent_UBs[required_cells] -= 1
# print "matrix_permanent_UBs after 179", matrix_permanent_UBs
# print
check_bounds_add_up_simple(ORIGINAL_MATRIX, prv_required_cells)
matrix_permanent_UBs[tuple(prv_required_cells)] -= cur_level_slack #+ sub_tree_slack*local_matrix[0, sampled_fixed_columns[0]]#sub_tree_slack
assert(matrix_permanent_UBs[tuple(prv_required_cells)] > -.000000001)
if matrix_permanent_UBs[tuple(prv_required_cells)] < 0:
matrix_permanent_UBs[tuple(prv_required_cells)] = 0
check_bounds_add_up_simple(ORIGINAL_MATRIX, prv_required_cells)
return sampled_association, cur_level_slack
else:
sampled_fixed_columns = fixed_column_options[sampled_association_idx]
sampled_submatrix = np.delete(local_matrix, sampled_fixed_columns, 1) #delete columns
sampled_submatrix = np.delete(sampled_submatrix, range(depth), 0) #delete rows
sampled_association = [(row, sampled_fixed_columns[row]) for row in range(depth)]
sampled_association_global_indices = [(global_row_indices[local_row], global_col_indices[local_col]) for (local_row, local_col) in sampled_association]
hashable_matrix = tuple([tuple(row) for row in sampled_submatrix])
required_cells = tuple(prv_required_cells_copy + sampled_association_global_indices)
sampled_submatrix_permanent_UB = matrix_permanent_UBs[required_cells]
# print "sampled_submatrix:", sampled_submatrix
if sampled_submatrix.shape[0] == 0:
matrix_permanent_UBs[tuple(prv_required_cells)] -= cur_level_slack
assert(matrix_permanent_UBs[tuple(prv_required_cells)] > -.000000001)
if matrix_permanent_UBs[tuple(prv_required_cells)] < 0:
matrix_permanent_UBs[tuple(prv_required_cells)] = 0
return sampled_association_global_indices, cur_level_slack
prv_required_cells_copy.extend(sampled_association_global_indices)
global_row_indices = np.delete(global_row_indices, range(depth))
global_col_indices = np.delete(global_col_indices, sampled_fixed_columns)
if DEBUG1:
print "required_cells before calling sample_association_01matrix_plusSlack:", required_cells
remaining_sampled_associations, sub_tree_slack = sample_association_01matrix_plusSlack(sampled_submatrix, sampled_submatrix_permanent_UB, matrix_permanent_UBs, prv_required_cells_copy, depth=1, global_row_indices=global_row_indices, global_col_indices=global_col_indices)
if DEBUG1:
print "required_cells after calling sample_association_01matrix_plusSlack:", required_cells
print "subtracting sub_tree_slack", sub_tree_slack, "from required_cells:", required_cells
#begin debug
if DEBUG1:
if DEBUG1:
print '-'*80
print "before subtracting slack from ", required_cells
print matrix_permanent_UBs
print "submatrix upper bounds"
partitioned_ubs = []
for cur_col in range(len(global_col_indices)):
cur_required_cells = tuple(list(required_cells) + [(global_row_indices[0], global_col_indices[cur_col])])
submatrix_permanent_UB = matrix_permanent_UBs[cur_required_cells]
# submatrix_permanent_UB = (minc_extended_UB2(cur_submatrix)) #add a little for potential computational error, would be nice to make this cleaner
upper_bound_submatrix_count = submatrix_permanent_UB
upper_bound_submatrix_count *= local_matrix[0, cur_col]
partitioned_ubs.append(upper_bound_submatrix_count)
if DEBUG1:
print upper_bound_submatrix_count,
if DEBUG1:
print
print "np.sum(partitioned_ubs) =", np.sum(partitioned_ubs)
print "non partitioned UB =", matrix_permanent_UBs[required_cells]
#end debug
# print "associated with valid subtree, subtracting cur_level_slack + sub_tree_slack*local_matrix[0, sampled_fixed_columns[0]] =", cur_level_slack + sub_tree_slack*local_matrix[0, sampled_fixed_columns[0]]
# print "prv_required_cells:", prv_required_cells
check_bounds_add_up_simple(ORIGINAL_MATRIX, prv_required_cells)
matrix_permanent_UBs[tuple(prv_required_cells)] -= cur_level_slack + sub_tree_slack*local_matrix[0, sampled_fixed_columns[0]]#sub_tree_slack
assert(matrix_permanent_UBs[tuple(prv_required_cells)] > -.000000001)
if matrix_permanent_UBs[tuple(prv_required_cells)] < 0:
matrix_permanent_UBs[tuple(prv_required_cells)] = 0
check_bounds_add_up_simple(ORIGINAL_MATRIX, prv_required_cells)
#begin debug
if DEBUG1:
partitioned_ubs = []
for cur_col in range(len(global_col_indices)):
cur_required_cells = tuple(list(required_cells) + [(global_row_indices[0], global_col_indices[cur_col])])
submatrix_permanent_UB = matrix_permanent_UBs[cur_required_cells]
# submatrix_permanent_UB = (minc_extended_UB2(cur_submatrix)) #add a little for potential computational error, would be nice to make this cleaner
upper_bound_submatrix_count = submatrix_permanent_UB
upper_bound_submatrix_count *= local_matrix[0, cur_col]
partitioned_ubs.append(upper_bound_submatrix_count)
#end debug
# check_bounds_add_up(sampled_submatrix, prv_required_cells_copy, global_row_indices, global_col_indices)
if remaining_sampled_associations is None: #we sampled some slack
sampled_association_global_indices = None
# print "calling 203 with required_cells:", required_cells
# print "matrix_permanent_UBs before 203", matrix_permanent_UBs
# print "matrix_permanent_UBs after 203", matrix_permanent_UBs
# print
return sampled_association_global_indices, cur_level_slack + sub_tree_slack*local_matrix[0, sampled_fixed_columns[0]]
else:
sampled_association_global_indices.extend(remaining_sampled_associations)
return sampled_association_global_indices, cur_level_slack + sub_tree_slack*local_matrix[0, sampled_fixed_columns[0]]
else:
print "sum_of_submatrix_UBs > permanentUB :(:(:("
print "sum_of_submatrix_UBs-permanentUB: ", sum_of_submatrix_UBs-permanentUB
print "(sum_of_submatrix_UBs-permanentUB)/permanentUB: ", (sum_of_submatrix_UBs-permanentUB)/permanentUB
print "np.log(sum_of_submatrix_UBs)-np.log(permanentUB): ", np.log(sum_of_submatrix_UBs)-np.log(permanentUB)
print "sum_of_submatrix_UBs: ", sum_of_submatrix_UBs
print "permanentUB: ", permanentUB
print "try other partitionings"
assert(False), "not expecting this! also fix find_best_row_to_partition_matrix and caching there, etc."
find_best_row_to_partition_matrix(local_matrix, prv_required_cells_copy, first_sample)
print
sampled_association_global_indices = sample_association_01matrix_plusSlack(local_matrix, permanentUB, matrix_permanent_UBs, prv_required_cells_copy, depth=depth+1, global_row_indices=global_row_indices, global_col_indices=global_col_indices)
return sampled_association_global_indices
# return sampled_association_global_indices
MINC_UB_BEST = []
EXTENDEND_MINC_UB_BEST = []
FULLY_INDECOMPOSABLE_UB_BEST = []
FULLY_INDECOMPOSABLE_UB_INVALID = []
def mu_func(m, x):
'''
Calculate the geometric mean of m equally spaced numbers from 1 to x
'''
if m == 1:
return (x+1)/2 #CHECK ME!!
geom_mean = 1.0
for k in range(1, m+1):
geom_mean *= ((k-1)*x + m - k)/(m-1)
geom_mean = geom_mean ** (1/m)
return geom_mean
LOOKUP_TABLE = np.array([
1, 1, 2, 6, 24, 120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600,
6227020800, 87178291200, 1307674368000,
20922789888000, 355687428096000, 6402373705728000,
121645100408832000, 2432902008176640000], dtype='int64')
@nb.jit
def fast_factorial(n):
if n > 20:
raise ValueError
return LOOKUP_TABLE[n]
gamma_cache = {}
def gamma(k):
if k == 0:
return 0
else:
assert(k >= 1)
if k in gamma_cache:
return gamma_cache[k]
else:
return_val = (math.factorial(k))**(1/k)
# return_val = (fast_factorial(k))**(1/k)
gamma_cache[k] = return_val
return return_val
delta_cache = {}
def delta(k):
if k in delta_cache:
return delta_cache[k]
else:
return_val = gamma(k) - gamma(k-1)
delta_cache[k] = return_val
return return_val
NUMBA_GAMMA_CACHE = np.zeros(100, dtype=np.float64)
@nb.jit(["float64(int32, float64[:])"], "(),(n)->()")
# @nb.jit(nb.float64(nb.int32,), nopython=True)
# @nb.vectorize(nb.float64(nb.int32,))
def numba_gamma(k, numba_gamma_cache=NUMBA_GAMMA_CACHE):
if k == 0:
return 0
else:
assert(k >= 1)
if numba_gamma_cache[0] == 0:
for cur_k in range(100):
return_val = (fast_factorial(cur_k-1))**(1/cur_k-1)
numba_gamma_cache[cur_k-1] = return_val
return numba_gamma_cache[k-1]
NUMBA_DELTA_CACHE = np.zeros(100, dtype=np.float64)
@nb.jit(["float64(int32, float64[:])"], "(),(n)->()")
# @nb.jit((nb.int32,))
# @nb.vectorize(nb.float64(nb.int32,))
def numba_delta(k, numba_delta_cache=NUMBA_DELTA_CACHE):
assert(k < 100)
if numba_delta_cache[0]: #compute cache
for cur_k in range(100):
return_val = numba_gamma(cur_k, numba_gamma_cache=NUMBA_GAMMA_CACHE) - numba_gamma(cur_k-1, numba_gamma_cache=NUMBA_GAMMA_CACHE)
numba_delta_cache[cur_k-1] = return_val
return numba_delta_cache[k-1]
def minc_extended_UB2(matrix, require_square_matrix=False):
if COMPARE_WAI:
return immediate_nesting_extended_bregman(matrix)
if require_square_matrix: #testing generalization to non-square matrices
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[1]
deltas = np.array([delta(i + 1) for i in range(N)])
matrix_sorted = np.sort(matrix, axis=1)[:, ::-1]
return (matrix_sorted * deltas).sum(axis=1).prod()
# @profile
# @nb.jit
# @nb.guvectorize(["float64(float64[:,:])"], "(n,n)->()")
def minc_extended_UB2_not_vectorized(matrix):
#another bound
#https://ac-els-cdn-com.stanford.idm.oclc.org/S002437950400299X/1-s2.0-S002437950400299X-main.pdf?_tid=fa4d00ee-39a5-4030-b7c1-28bb5fbc76c0&acdnat=1534454814_a7411b3006e0e092622de35cbf015275
# equation (6), U^M(A)
if COMPARE_WAI:
return immediate_nesting_extended_bregman(matrix)
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
minc_extended_upper_bound2 = 1.0
for row in range(N):
sorted_row = sorted(matrix[row], reverse=True)
row_sum = 0
for col in range(N):
row_sum += sorted_row[col] * delta(col+1)
# row_sum += sorted_row[col] * numba_delta(col+1)
minc_extended_upper_bound2 *= row_sum
return minc_extended_upper_bound2
def minc_extended_UB2_scaled(matrix, col_scale):
#another bound
#https://ac-els-cdn-com.stanford.idm.oclc.org/S002437950400299X/1-s2.0-S002437950400299X-main.pdf?_tid=fa4d00ee-39a5-4030-b7c1-28bb5fbc76c0&acdnat=1534454814_a7411b3006e0e092622de35cbf015275
# equation (6), U^M(A), with column scaling
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
assert(len(col_scale) == N)
minc_extended_upper_bound2 = 1.0
for scale in col_scale:
minc_extended_upper_bound2 /= scale
for row in range(N):
assert(matrix[row].shape == col_scale.shape)
scaled_row = np.multiply(matrix[row], col_scale) #elmentwise multiplication
sorted_row = sorted(scaled_row, reverse=True)
row_sum = 0
for col in range(N):
row_sum += sorted_row[col] * delta(col+1)
minc_extended_upper_bound2 *= row_sum
return minc_extended_upper_bound2
def get_func_of_scale_minc_extended_UB2_scaled(matrix):
#get the upper bound as a function of a column scaling for a particular matrix
#another bound
#https://ac-els-cdn-com.stanford.idm.oclc.org/S002437950400299X/1-s2.0-S002437950400299X-main.pdf?_tid=fa4d00ee-39a5-4030-b7c1-28bb5fbc76c0&acdnat=1534454814_a7411b3006e0e092622de35cbf015275
# equation (6), U^M(A), with column scaling
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
def func_of_column_scale(col_scale):
assert(len(col_scale) == N)
minc_extended_upper_bound2 = 1.0
for scale in col_scale:
minc_extended_upper_bound2 /= scale
for row in range(N):
assert(matrix[row].shape == col_scale.shape)
scaled_row = np.multiply(matrix[row], col_scale) #elmentwise multiplication
sorted_row = sorted(scaled_row, reverse=True)
row_sum = 0
for col in range(N):
row_sum += sorted_row[col] * delta(col+1)
minc_extended_upper_bound2 *= row_sum
return minc_extended_upper_bound2
return func_of_column_scale
def optimized_minc_extened_UB2(matrix):
#https://ac-els-cdn-com.stanford.idm.oclc.org/S002437950400299X/1-s2.0-S002437950400299X-main.pdf?_tid=fa4d00ee-39a5-4030-b7c1-28bb5fbc76c0&acdnat=1534454814_a7411b3006e0e092622de35cbf015275
# optimize equation (6), U^M(A) according to equation (9) (that is, rescaling columns)
assert(matrix.shape[0] == matrix.shape[1])
N = matrix.shape[0]
# # rescale by positive numbers, SHOULD BE GREATER THAN 0, NOT >=, is this a probelm??
x0 = np.ones(N)
function = get_func_of_scale_minc_extended_UB2_scaled(matrix)
result = minimize(fun=function, x0=x0, bounds=[(0, np.inf) for i in range(N)])
optimzed_upper_bound = function(result.x)
assert((result.x>0).all()), (result.x, optimzed_upper_bound)
print ("result.x =", result.x, "optimzed_upper_bound =", optimzed_upper_bound)
return optimzed_upper_bound
# @profile
def immediate_nesting_extended_bregman(matrix):
#https://dukespace.lib.duke.edu/dspace/bitstream/handle/10161/1054/D_Law_Wai_a_200904.pdf?sequence=1&isAllowed=y
assert((matrix <= 1).all())
assert((matrix >= 0).all())
N = matrix.shape[0]
assert(N == matrix.shape[1])
col_sum = matrix.sum(axis=0)
h_func = np.where(col_sum >= 1, col_sum + 0.5 * np.log(col_sum) + np.e - 1, 1 + (np.e - 1) * col_sum) / np.e
return h_func.prod()
def h_func(r):
if r >= 1:
return r + .5*math.log(r) + np.e - 1
else:
return 1 + (np.e - 1)*r
# @profile
def immediate_nesting_extended_bregman_not_vectorized(matrix):
#https://dukespace.lib.duke.edu/dspace/bitstream/handle/10161/1054/D_Law_Wai_a_200904.pdf?sequence=1&isAllowed=y
assert((matrix <= 1).all())
assert((matrix >= 0).all())
N = matrix.shape[0]
assert(N == matrix.shape[1])
bregman_extended_upper_bound = 1
for col in range(N):
col_sum = 0
for row in range(N):
col_sum += matrix[row][col]
bregman_extended_upper_bound *= h_func(col_sum)/np.e
return bregman_extended_upper_bound
class Node:
# @profile
def __init__(self, orig_cost_matrix, required_cells, excluded_cells, orig_cost_matrix_index, gumbel_truncation):
'''
Following the terminology used by [1], a node is defined to be a nonempty subset of possible
assignments to a cost matrix. Every assignment in node N is required to contain
required_cells and exclude excluded_cells.
Inputs:
- orig_cost_matrix: (2d numpy array) the original cost matrix
- required_cells: (list of pairs) where each pair represents a (zero indexed) location
in the assignment matrix that must be a 1
- excluded_cells: (list of pairs) where each pair represents a (zero indexed) location
in the assignment matrix that must be a 0
- orig_cost_matrix_index: index of the cost matrix this Node is descended from, used when
when finding the k lowest cost assignments among a group of assignment matrices
(k_best_assign_mult_cost_matrices)
- gumbel_truncation: (float) truncate gumbels for this Node to this value (https://cmaddis.github.io/)
'''
self.orig_cost_matrix = np.array(orig_cost_matrix, copy=True)
self.required_cells = required_cells[:]
self.excluded_cells = excluded_cells[:]
self.gumbel_truncation = gumbel_truncation
rows_containing_excluded_cells = set()
cols_containing_excluded_cells = set()
for row, col in self.excluded_cells:
rows_containing_excluded_cells.add(row)
cols_containing_excluded_cells.add(col)
for row, col in self.required_cells:
if row in rows_containing_excluded_cells:
rows_containing_excluded_cells.remove(row)
if col in cols_containing_excluded_cells:
cols_containing_excluded_cells.remove(col)
# if len(rows_containing_excluded_cells) > 1 and len(cols_containing_excluded_cells) > 1:
if len(rows_containing_excluded_cells) > 1:
# print( "more than 1 col and more than 1 row contain excluded cells!!!")
print( "more than 1 row contain excluded cells!!!")
print( "self.excluded_cells:", self.excluded_cells)
print( "self.required_cells:", self.required_cells)
print( "rows_containing_excluded_cells:", rows_containing_excluded_cells)
print( "cols_containing_excluded_cells:", cols_containing_excluded_cells)