-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
integer.cc
2386 lines (2119 loc) · 88.9 KB
/
integer.cc
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
// Copyright 2010-2024 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/integer.h"
#include <algorithm>
#include <cstdint>
#include <deque>
#include <functional>
#include <limits>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/cleanup/cleanup.h"
#include "absl/container/btree_map.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/inlined_vector.h"
#include "absl/log/check.h"
#include "absl/meta/type_traits.h"
#include "absl/strings/str_cat.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/base/strong_vector.h"
#include "ortools/sat/model.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/sat_parameters.pb.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/util/bitset.h"
#include "ortools/util/rev.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
#include "ortools/util/strong_integers.h"
#include "ortools/util/time_limit.h"
namespace operations_research {
namespace sat {
std::vector<IntegerVariable> NegationOf(
const std::vector<IntegerVariable>& vars) {
std::vector<IntegerVariable> result(vars.size());
for (int i = 0; i < vars.size(); ++i) {
result[i] = NegationOf(vars[i]);
}
return result;
}
std::string ValueLiteralPair::DebugString() const {
return absl::StrCat("(literal = ", literal.DebugString(),
", value = ", value.value(), ")");
}
std::ostream& operator<<(std::ostream& os, const ValueLiteralPair& p) {
os << p.DebugString();
return os;
}
// TODO(user): Reserve vector index by literals? It is trickier, as we might not
// know beforehand how many we will need. Consider alternatives to not waste
// space like using dequeue.
void IntegerEncoder::ReserveSpaceForNumVariables(int num_vars) {
encoding_by_var_.reserve(num_vars);
equality_to_associated_literal_.reserve(num_vars);
equality_by_var_.reserve(num_vars);
}
void IntegerEncoder::FullyEncodeVariable(IntegerVariable var) {
if (VariableIsFullyEncoded(var)) return;
CHECK_EQ(0, sat_solver_->CurrentDecisionLevel());
var = PositiveVariable(var);
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
CHECK(!domains_[index].IsEmpty()); // UNSAT. We don't deal with that here.
CHECK_LT(domains_[index].Size(), 100000)
<< "Domain too large for full encoding.";
// TODO(user): Maybe we can optimize the literal creation order and their
// polarity as our default SAT heuristics initially depends on this.
//
// TODO(user): Currently, in some corner cases,
// GetOrCreateLiteralAssociatedToEquality() might trigger some propagation
// that update the domain of var, so we need to cache the values to not read
// garbage. Note that it is okay to call the function on values no longer
// reachable, as this will just do nothing.
tmp_values_.clear();
for (const int64_t v : domains_[index].Values()) {
tmp_values_.push_back(IntegerValue(v));
}
for (const IntegerValue v : tmp_values_) {
GetOrCreateLiteralAssociatedToEquality(var, v);
}
// Mark var and Negation(var) as fully encoded.
DCHECK_LT(GetPositiveOnlyIndex(var), is_fully_encoded_.size());
is_fully_encoded_[GetPositiveOnlyIndex(var)] = true;
}
bool IntegerEncoder::VariableIsFullyEncoded(IntegerVariable var) const {
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
if (index >= is_fully_encoded_.size()) return false;
// Once fully encoded, the status never changes.
if (is_fully_encoded_[index]) return true;
var = PositiveVariable(var);
// TODO(user): Cache result as long as equality_by_var_[index] is unchanged?
// It might not be needed since if the variable is not fully encoded, then
// PartialDomainEncoding() will filter unreachable values, and so the size
// check will be false until further value have been encoded.
const int64_t initial_domain_size = domains_[index].Size();
if (equality_by_var_[index].size() < initial_domain_size) return false;
// This cleans equality_by_var_[index] as a side effect and in particular,
// sorts it by values.
PartialDomainEncoding(var);
// TODO(user): Comparing the size might be enough, but we want to be always
// valid even if either (*domains_[var]) or PartialDomainEncoding(var) are
// not properly synced because the propagation is not finished.
const auto& ref = equality_by_var_[index];
int i = 0;
for (const int64_t v : domains_[index].Values()) {
if (i < ref.size() && v == ref[i].value) {
i++;
}
}
if (i == ref.size()) {
is_fully_encoded_[index] = true;
}
return is_fully_encoded_[index];
}
const std::vector<ValueLiteralPair>& IntegerEncoder::FullDomainEncoding(
IntegerVariable var) const {
CHECK(VariableIsFullyEncoded(var));
return PartialDomainEncoding(var);
}
const std::vector<ValueLiteralPair>& IntegerEncoder::PartialDomainEncoding(
IntegerVariable var) const {
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
if (index >= equality_by_var_.size()) {
partial_encoding_.clear();
return partial_encoding_;
}
int new_size = 0;
partial_encoding_.assign(equality_by_var_[index].begin(),
equality_by_var_[index].end());
for (int i = 0; i < partial_encoding_.size(); ++i) {
const ValueLiteralPair pair = partial_encoding_[i];
if (sat_solver_->Assignment().LiteralIsFalse(pair.literal)) continue;
if (sat_solver_->Assignment().LiteralIsTrue(pair.literal)) {
partial_encoding_.clear();
partial_encoding_.push_back(pair);
new_size = 1;
break;
}
partial_encoding_[new_size++] = pair;
}
partial_encoding_.resize(new_size);
std::sort(partial_encoding_.begin(), partial_encoding_.end(),
ValueLiteralPair::CompareByValue());
if (trail_->CurrentDecisionLevel() == 0) {
// We can cleanup the current encoding in this case.
equality_by_var_[index].assign(partial_encoding_.begin(),
partial_encoding_.end());
}
if (!VariableIsPositive(var)) {
std::reverse(partial_encoding_.begin(), partial_encoding_.end());
for (ValueLiteralPair& ref : partial_encoding_) ref.value = -ref.value;
}
return partial_encoding_;
}
// Note that by not inserting the literal in "order" we can in the worst case
// use twice as much implication (2 by literals) instead of only one between
// consecutive literals.
void IntegerEncoder::AddImplications(
const absl::btree_map<IntegerValue, Literal>& map,
absl::btree_map<IntegerValue, Literal>::const_iterator it,
Literal associated_lit) {
if (!add_implications_) return;
DCHECK_EQ(it->second, associated_lit);
// Tricky: We compute the literal first because AddClauseDuringSearch() might
// propagate at level zero and mess up the map.
LiteralIndex before_index = kNoLiteralIndex;
if (it != map.begin()) {
auto before_it = it;
--before_it;
before_index = before_it->second.Index();
}
LiteralIndex after_index = kNoLiteralIndex;
{
auto after_it = it;
++after_it;
if (after_it != map.end()) after_index = after_it->second.Index();
}
// Then we add the two implications.
if (after_index != kNoLiteralIndex) {
sat_solver_->AddClauseDuringSearch(
{Literal(after_index).Negated(), associated_lit});
}
if (before_index != kNoLiteralIndex) {
sat_solver_->AddClauseDuringSearch(
{associated_lit.Negated(), Literal(before_index)});
}
}
void IntegerEncoder::AddAllImplicationsBetweenAssociatedLiterals() {
CHECK_EQ(0, sat_solver_->CurrentDecisionLevel());
add_implications_ = true;
// This is tricky: AddBinaryClause() might trigger propagation that causes the
// encoding to be filtered. So we make a copy...
const int num_vars = encoding_by_var_.size();
for (PositiveOnlyIndex index(0); index < num_vars; ++index) {
LiteralIndex previous = kNoLiteralIndex;
const IntegerVariable var(2 * index.value());
for (const auto [unused, literal] : PartialGreaterThanEncoding(var)) {
if (previous != kNoLiteralIndex) {
// literal => previous.
sat_solver_->AddBinaryClause(literal.Negated(), Literal(previous));
}
previous = literal.Index();
}
}
}
std::pair<IntegerLiteral, IntegerLiteral> IntegerEncoder::Canonicalize(
IntegerLiteral i_lit) const {
const bool positive = VariableIsPositive(i_lit.var);
if (!positive) i_lit = i_lit.Negated();
const IntegerVariable var(i_lit.var);
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
IntegerValue after(i_lit.bound);
IntegerValue before(i_lit.bound - 1);
DCHECK_GE(before, domains_[index].Min());
DCHECK_LE(after, domains_[index].Max());
int64_t previous = std::numeric_limits<int64_t>::min();
for (const ClosedInterval& interval : domains_[index]) {
if (before > previous && before < interval.start) before = previous;
if (after > previous && after < interval.start) after = interval.start;
if (after <= interval.end) break;
previous = interval.end;
}
if (positive) {
return {IntegerLiteral::GreaterOrEqual(var, after),
IntegerLiteral::LowerOrEqual(var, before)};
} else {
return {IntegerLiteral::LowerOrEqual(var, before),
IntegerLiteral::GreaterOrEqual(var, after)};
}
}
Literal IntegerEncoder::GetOrCreateAssociatedLiteral(IntegerLiteral i_lit) {
// Remove trivial literal.
{
const PositiveOnlyIndex index = GetPositiveOnlyIndex(i_lit.var);
if (VariableIsPositive(i_lit.var)) {
if (i_lit.bound <= domains_[index].Min()) return GetTrueLiteral();
if (i_lit.bound > domains_[index].Max()) return GetFalseLiteral();
} else {
const IntegerValue bound = -i_lit.bound;
if (bound >= domains_[index].Max()) return GetTrueLiteral();
if (bound < domains_[index].Min()) return GetFalseLiteral();
}
}
// Canonicalize and see if we have an equivalent literal already.
const auto canonical_lit = Canonicalize(i_lit);
if (VariableIsPositive(i_lit.var)) {
const LiteralIndex index = GetAssociatedLiteral(canonical_lit.first);
if (index != kNoLiteralIndex) return Literal(index);
} else {
const LiteralIndex index = GetAssociatedLiteral(canonical_lit.second);
if (index != kNoLiteralIndex) return Literal(index).Negated();
}
++num_created_variables_;
const Literal literal(sat_solver_->NewBooleanVariable(), true);
AssociateToIntegerLiteral(literal, canonical_lit.first);
// TODO(user): on some problem this happens. We should probably make sure that
// we don't create extra fixed Boolean variable for no reason.
if (sat_solver_->Assignment().LiteralIsAssigned(literal)) {
VLOG(1) << "Created a fixed literal for no reason!";
}
return literal;
}
namespace {
std::pair<PositiveOnlyIndex, IntegerValue> PositiveVarKey(IntegerVariable var,
IntegerValue value) {
return std::make_pair(GetPositiveOnlyIndex(var),
VariableIsPositive(var) ? value : -value);
}
} // namespace
LiteralIndex IntegerEncoder::GetAssociatedEqualityLiteral(
IntegerVariable var, IntegerValue value) const {
const auto it =
equality_to_associated_literal_.find(PositiveVarKey(var, value));
if (it != equality_to_associated_literal_.end()) {
return it->second.Index();
}
return kNoLiteralIndex;
}
Literal IntegerEncoder::GetOrCreateLiteralAssociatedToEquality(
IntegerVariable var, IntegerValue value) {
{
const auto it =
equality_to_associated_literal_.find(PositiveVarKey(var, value));
if (it != equality_to_associated_literal_.end()) {
return it->second;
}
}
// Check for trivial true/false literal to avoid creating variable for no
// reasons.
const Domain& domain = domains_[GetPositiveOnlyIndex(var)];
if (!domain.Contains(VariableIsPositive(var) ? value.value()
: -value.value())) {
return GetFalseLiteral();
}
if (domain.IsFixed()) {
AssociateToIntegerEqualValue(GetTrueLiteral(), var, value);
return GetTrueLiteral();
}
++num_created_variables_;
const Literal literal(sat_solver_->NewBooleanVariable(), true);
AssociateToIntegerEqualValue(literal, var, value);
// TODO(user): this happens on some problem. We should probably
// make sure that we don't create extra fixed Boolean variable for no reason.
// Note that here we could detect the case before creating the literal. The
// initial domain didn't contain it, but maybe the one of (>= value) or (<=
// value) is false?
if (sat_solver_->Assignment().LiteralIsAssigned(literal)) {
VLOG(1) << "Created a fixed literal for no reason!";
}
return literal;
}
void IntegerEncoder::AssociateToIntegerLiteral(Literal literal,
IntegerLiteral i_lit) {
// Always transform to positive variable.
if (!VariableIsPositive(i_lit.var)) {
i_lit = i_lit.Negated();
literal = literal.Negated();
}
const PositiveOnlyIndex index = GetPositiveOnlyIndex(i_lit.var);
const Domain& domain = domains_[index];
const IntegerValue min(domain.Min());
const IntegerValue max(domain.Max());
if (i_lit.bound <= min) {
return (void)sat_solver_->AddUnitClause(literal);
}
if (i_lit.bound > max) {
return (void)sat_solver_->AddUnitClause(literal.Negated());
}
if (index >= encoding_by_var_.size()) {
encoding_by_var_.resize(index.value() + 1);
}
auto& var_encoding = encoding_by_var_[index];
// We just insert the part corresponding to the literal with positive
// variable.
const auto canonical_pair = Canonicalize(i_lit);
const auto [it, inserted] =
var_encoding.insert({canonical_pair.first.bound, literal});
if (!inserted) {
const Literal associated(it->second);
if (associated != literal) {
DCHECK_EQ(sat_solver_->CurrentDecisionLevel(), 0);
sat_solver_->AddClauseDuringSearch({literal, associated.Negated()});
sat_solver_->AddClauseDuringSearch({literal.Negated(), associated});
}
return;
}
AddImplications(var_encoding, it, literal);
// Corner case if adding implication cause this to be fixed.
if (sat_solver_->CurrentDecisionLevel() == 0) {
if (sat_solver_->Assignment().LiteralIsTrue(literal)) {
delayed_to_fix_->integer_literal_to_fix.push_back(canonical_pair.first);
}
if (sat_solver_->Assignment().LiteralIsFalse(literal)) {
delayed_to_fix_->integer_literal_to_fix.push_back(canonical_pair.second);
}
}
// Resize reverse encoding.
const int new_size =
1 + std::max(literal.Index().value(), literal.NegatedIndex().value());
if (new_size > reverse_encoding_.size()) {
reverse_encoding_.resize(new_size);
}
reverse_encoding_[literal].push_back(canonical_pair.first);
reverse_encoding_[literal.NegatedIndex()].push_back(canonical_pair.second);
// Detect the case >= max or <= min and properly register them. Note that
// both cases will happen at the same time if there is just two possible
// value in the domain.
if (canonical_pair.first.bound == max) {
AssociateToIntegerEqualValue(literal, i_lit.var, max);
}
if (-canonical_pair.second.bound == min) {
AssociateToIntegerEqualValue(literal.Negated(), i_lit.var, min);
}
}
void IntegerEncoder::AssociateToIntegerEqualValue(Literal literal,
IntegerVariable var,
IntegerValue value) {
// The function is symmetric and we only deal with positive variable.
if (!VariableIsPositive(var)) {
var = NegationOf(var);
value = -value;
}
// Detect literal view. Note that the same literal can be associated to more
// than one variable, and thus already have a view. We don't change it in
// this case.
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
const Domain& domain = domains_[index];
if (value == 1 && domain.Min() >= 0 && domain.Max() <= 1) {
if (literal.Index() >= literal_view_.size()) {
literal_view_.resize(literal.Index().value() + 1, kNoIntegerVariable);
literal_view_[literal] = var;
} else if (literal_view_[literal] == kNoIntegerVariable) {
literal_view_[literal] = var;
}
}
if (value == -1 && domain.Min() >= -1 && domain.Max() <= 0) {
if (literal.Index() >= literal_view_.size()) {
literal_view_.resize(literal.Index().value() + 1, kNoIntegerVariable);
literal_view_[literal] = NegationOf(var);
} else if (literal_view_[literal] == kNoIntegerVariable) {
literal_view_[literal] = NegationOf(var);
}
}
// We use the "do not insert if present" behavior of .insert() to do just one
// lookup.
const auto insert_result = equality_to_associated_literal_.insert(
{PositiveVarKey(var, value), literal});
if (!insert_result.second) {
// If this key is already associated, make the two literals equal.
const Literal representative = insert_result.first->second;
if (representative != literal) {
sat_solver_->AddClauseDuringSearch({literal, representative.Negated()});
sat_solver_->AddClauseDuringSearch({literal.Negated(), representative});
}
return;
}
// Fix literal for value outside the domain.
if (!domain.Contains(value.value())) {
return (void)sat_solver_->AddUnitClause(literal.Negated());
}
// Update equality_by_var. Note that due to the
// equality_to_associated_literal_ hash table, there should never be any
// duplicate values for a given variable.
if (index >= equality_by_var_.size()) {
equality_by_var_.resize(index.value() + 1);
is_fully_encoded_.resize(index.value() + 1);
}
equality_by_var_[index].push_back({value, literal});
// Fix literal for constant domain.
if (domain.IsFixed()) {
return (void)sat_solver_->AddUnitClause(literal);
}
const IntegerLiteral ge = IntegerLiteral::GreaterOrEqual(var, value);
const IntegerLiteral le = IntegerLiteral::LowerOrEqual(var, value);
// Special case for the first and last value.
if (value == domain.Min()) {
// Note that this will recursively call AssociateToIntegerEqualValue() but
// since equality_to_associated_literal_[] is now set, the recursion will
// stop there. When a domain has just 2 values, this allows to call just
// once AssociateToIntegerEqualValue() and also associate the other value to
// the negation of the given literal.
AssociateToIntegerLiteral(literal, le);
return;
}
if (value == domain.Max()) {
AssociateToIntegerLiteral(literal, ge);
return;
}
// (var == value) <=> (var >= value) and (var <= value).
const Literal a(GetOrCreateAssociatedLiteral(ge));
const Literal b(GetOrCreateAssociatedLiteral(le));
sat_solver_->AddClauseDuringSearch({a, literal.Negated()});
sat_solver_->AddClauseDuringSearch({b, literal.Negated()});
sat_solver_->AddClauseDuringSearch({a.Negated(), b.Negated(), literal});
// Update reverse encoding.
const int new_size = 1 + literal.Index().value();
if (new_size > reverse_equality_encoding_.size()) {
reverse_equality_encoding_.resize(new_size);
}
reverse_equality_encoding_[literal].push_back({var, value});
}
bool IntegerEncoder::IsFixedOrHasAssociatedLiteral(IntegerLiteral i_lit) const {
if (!VariableIsPositive(i_lit.var)) i_lit = i_lit.Negated();
const PositiveOnlyIndex index = GetPositiveOnlyIndex(i_lit.var);
if (i_lit.bound <= domains_[index].Min()) return true;
if (i_lit.bound > domains_[index].Max()) return true;
return GetAssociatedLiteral(i_lit) != kNoLiteralIndex;
}
// TODO(user): Canonicalization might be slow.
LiteralIndex IntegerEncoder::GetAssociatedLiteral(IntegerLiteral i_lit) const {
IntegerValue bound;
const auto canonical_pair = Canonicalize(i_lit);
const LiteralIndex result =
SearchForLiteralAtOrBefore(canonical_pair.first, &bound);
if (result != kNoLiteralIndex && bound >= i_lit.bound) {
return result;
}
return kNoLiteralIndex;
}
// Note that we assume the input literal is canonicalized and do not fall into
// a hole. Otherwise, this work but will likely return a literal before and
// not one equivalent to it (which can be after!).
LiteralIndex IntegerEncoder::SearchForLiteralAtOrBefore(
IntegerLiteral i_lit, IntegerValue* bound) const {
const PositiveOnlyIndex index = GetPositiveOnlyIndex(i_lit.var);
if (index >= encoding_by_var_.size()) return kNoLiteralIndex;
const auto& encoding = encoding_by_var_[index];
if (VariableIsPositive(i_lit.var)) {
// We need the entry at or before.
// We take the element before the upper_bound() which is either the encoding
// of i if it already exists, or the encoding just before it.
auto after_it = encoding.upper_bound(i_lit.bound);
if (after_it == encoding.begin()) return kNoLiteralIndex;
--after_it;
*bound = after_it->first;
return after_it->second.Index();
} else {
// We ask for who is implied by -var >= -bound, so we look for
// the var >= value with value > bound and take its negation.
auto after_it = encoding.upper_bound(-i_lit.bound);
if (after_it == encoding.end()) return kNoLiteralIndex;
// Compute tight bound if there are holes, we have X <= candidate.
const Domain& domain = domains_[index];
if (after_it->first <= domain.Min()) return kNoLiteralIndex;
*bound = -domain.ValueAtOrBefore(after_it->first.value() - 1);
return after_it->second.NegatedIndex();
}
}
ABSL_MUST_USE_RESULT bool IntegerEncoder::LiteralOrNegationHasView(
Literal lit, IntegerVariable* view, bool* view_is_direct) const {
const IntegerVariable direct_var = GetLiteralView(lit);
const IntegerVariable opposite_var = GetLiteralView(lit.Negated());
// If a literal has both views, we want to always keep the same
// representative: the smallest IntegerVariable.
if (direct_var != kNoIntegerVariable &&
(opposite_var == kNoIntegerVariable || direct_var <= opposite_var)) {
if (view != nullptr) *view = direct_var;
if (view_is_direct != nullptr) *view_is_direct = true;
return true;
}
if (opposite_var != kNoIntegerVariable) {
if (view != nullptr) *view = opposite_var;
if (view_is_direct != nullptr) *view_is_direct = false;
return true;
}
return false;
}
std::vector<ValueLiteralPair> IntegerEncoder::PartialGreaterThanEncoding(
IntegerVariable var) const {
std::vector<ValueLiteralPair> result;
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
if (index >= encoding_by_var_.size()) return result;
if (VariableIsPositive(var)) {
for (const auto [value, literal] : encoding_by_var_[index]) {
result.push_back({value, literal});
}
return result;
}
// Tricky: we need to account for holes.
const Domain& domain = domains_[index];
if (domain.IsEmpty()) return result;
int i = 0;
int64_t previous;
const int num_intervals = domain.NumIntervals();
for (const auto [value, literal] : encoding_by_var_[index]) {
while (value > domain[i].end) {
previous = domain[i].end;
++i;
if (i == num_intervals) break;
}
if (i == num_intervals) break;
if (value <= domain[i].start) {
if (i == 0) continue;
result.push_back({-previous, literal.Negated()});
} else {
result.push_back({-value + 1, literal.Negated()});
}
}
std::reverse(result.begin(), result.end());
return result;
}
bool IntegerEncoder::UpdateEncodingOnInitialDomainChange(IntegerVariable var,
Domain domain) {
DCHECK(VariableIsPositive(var));
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
if (index >= encoding_by_var_.size()) return true;
// Fix >= literal that can be fixed.
// We filter and canonicalize the encoding.
int i = 0;
int num_fixed = 0;
tmp_encoding_.clear();
for (const auto [value, literal] : encoding_by_var_[index]) {
while (i < domain.NumIntervals() && value > domain[i].end) ++i;
if (i == domain.NumIntervals()) {
// We are past the end, so always false.
if (trail_->Assignment().LiteralIsTrue(literal)) return false;
if (trail_->Assignment().LiteralIsFalse(literal)) continue;
++num_fixed;
trail_->EnqueueWithUnitReason(literal.Negated());
continue;
}
if (i == 0 && value <= domain[0].start) {
// We are at or before the beginning, so always true.
if (trail_->Assignment().LiteralIsTrue(literal)) continue;
if (trail_->Assignment().LiteralIsFalse(literal)) return false;
++num_fixed;
trail_->EnqueueWithUnitReason(literal);
continue;
}
// Note that we canonicalize the literal if it fall into a hole.
tmp_encoding_.push_back(
{std::max<IntegerValue>(value, domain[i].start), literal});
}
encoding_by_var_[index].clear();
for (const auto [value, literal] : tmp_encoding_) {
encoding_by_var_[index].insert({value, literal});
}
// Same for equality encoding.
// This will be lazily cleaned on the next PartialDomainEncoding() call.
i = 0;
for (const ValueLiteralPair pair : PartialDomainEncoding(var)) {
while (i < domain.NumIntervals() && pair.value > domain[i].end) ++i;
if (i == domain.NumIntervals() || pair.value < domain[i].start) {
if (trail_->Assignment().LiteralIsTrue(pair.literal)) return false;
if (trail_->Assignment().LiteralIsFalse(pair.literal)) continue;
++num_fixed;
trail_->EnqueueWithUnitReason(pair.literal.Negated());
}
}
if (num_fixed > 0) {
VLOG(1) << "Domain intersection fixed " << num_fixed
<< " encoding literals";
}
return true;
}
IntegerTrail::~IntegerTrail() {
if (parameters_.log_search_progress() && num_decisions_to_break_loop_ > 0) {
VLOG(1) << "Num decisions to break propagation loop: "
<< num_decisions_to_break_loop_;
}
}
bool IntegerTrail::Propagate(Trail* trail) {
const int level = trail->CurrentDecisionLevel();
for (ReversibleInterface* rev : reversible_classes_) rev->SetLevel(level);
// Make sure that our internal "integer_search_levels_" size matches the
// sat decision levels. At the level zero, integer_search_levels_ should
// be empty.
if (level > integer_search_levels_.size()) {
integer_search_levels_.push_back(integer_trail_.size());
lazy_reason_decision_levels_.push_back(lazy_reasons_.size());
reason_decision_levels_.push_back(literals_reason_starts_.size());
CHECK_EQ(level, integer_search_levels_.size());
}
// This is required because when loading a model it is possible that we add
// (literal <-> integer literal) associations for literals that have already
// been propagated here. This often happens when the presolve is off
// and many variables are fixed.
//
// TODO(user): refactor the interaction IntegerTrail <-> IntegerEncoder so
// that we can just push right away such literal. Unfortunately, this is is
// a big chunk of work.
if (level == 0) {
for (const IntegerLiteral i_lit : delayed_to_fix_->integer_literal_to_fix) {
// Note that we do not call Enqueue here but directly the update domain
// function so that we do not abort even if the level zero bounds were
// up to date.
const IntegerValue lb =
std::max(LevelZeroLowerBound(i_lit.var), i_lit.bound);
const IntegerValue ub = LevelZeroUpperBound(i_lit.var);
if (!UpdateInitialDomain(i_lit.var, Domain(lb.value(), ub.value()))) {
sat_solver_->NotifyThatModelIsUnsat();
return false;
}
}
delayed_to_fix_->integer_literal_to_fix.clear();
for (const Literal lit : delayed_to_fix_->literal_to_fix) {
if (trail_->Assignment().LiteralIsFalse(lit)) {
sat_solver_->NotifyThatModelIsUnsat();
return false;
}
if (trail_->Assignment().LiteralIsTrue(lit)) continue;
trail_->EnqueueWithUnitReason(lit);
}
delayed_to_fix_->literal_to_fix.clear();
}
// Process all the "associated" literals and Enqueue() the corresponding
// bounds.
while (propagation_trail_index_ < trail->Index()) {
const Literal literal = (*trail)[propagation_trail_index_++];
for (const IntegerLiteral i_lit : encoder_->GetIntegerLiterals(literal)) {
// The reason is simply the associated literal.
if (!EnqueueAssociatedIntegerLiteral(i_lit, literal)) {
return false;
}
}
}
return true;
}
void IntegerTrail::Untrail(const Trail& trail, int literal_trail_index) {
++num_untrails_;
conditional_lbs_.clear();
const int level = trail.CurrentDecisionLevel();
propagation_trail_index_ =
std::min(propagation_trail_index_, literal_trail_index);
if (level < first_level_without_full_propagation_) {
first_level_without_full_propagation_ = -1;
}
// Note that if a conflict was detected before Propagate() of this class was
// even called, it is possible that there is nothing to backtrack.
if (level >= integer_search_levels_.size()) return;
const int target = integer_search_levels_[level];
integer_search_levels_.resize(level);
CHECK_GE(target, var_lbs_.size());
CHECK_LE(target, integer_trail_.size());
for (int index = integer_trail_.size() - 1; index >= target; --index) {
const TrailEntry& entry = integer_trail_[index];
if (entry.var < 0) continue; // entry used by EnqueueLiteral().
var_trail_index_[entry.var] = entry.prev_trail_index;
var_lbs_[entry.var] = integer_trail_[entry.prev_trail_index].bound;
}
integer_trail_.resize(target);
// Resize lazy reason.
lazy_reasons_.resize(lazy_reason_decision_levels_[level]);
lazy_reason_decision_levels_.resize(level);
// Clear reason.
const int old_size = reason_decision_levels_[level];
reason_decision_levels_.resize(level);
if (old_size < literals_reason_starts_.size()) {
literals_reason_buffer_.resize(literals_reason_starts_[old_size]);
const int bound_start = bounds_reason_starts_[old_size];
bounds_reason_buffer_.resize(bound_start);
if (bound_start < trail_index_reason_buffer_.size()) {
trail_index_reason_buffer_.resize(bound_start);
}
literals_reason_starts_.resize(old_size);
bounds_reason_starts_.resize(old_size);
cached_sizes_.resize(old_size);
}
// We notify the new level once all variables have been restored to their
// old value.
for (ReversibleInterface* rev : reversible_classes_) rev->SetLevel(level);
}
void IntegerTrail::ReserveSpaceForNumVariables(int num_vars) {
// We only store the domain for the positive variable.
domains_->reserve(num_vars);
encoder_->ReserveSpaceForNumVariables(num_vars);
// Because we always create both a variable and its negation.
const int size = 2 * num_vars;
var_lbs_.reserve(size);
var_trail_index_.reserve(size);
integer_trail_.reserve(size);
var_trail_index_cache_.reserve(size);
tmp_var_to_trail_index_in_queue_.reserve(size);
var_to_trail_index_at_lower_level_.reserve(size);
}
IntegerVariable IntegerTrail::AddIntegerVariable(IntegerValue lower_bound,
IntegerValue upper_bound) {
DCHECK_GE(lower_bound, kMinIntegerValue);
DCHECK_LE(lower_bound, upper_bound);
DCHECK_LE(upper_bound, kMaxIntegerValue);
DCHECK(lower_bound >= 0 ||
lower_bound + std::numeric_limits<int64_t>::max() >= upper_bound);
DCHECK(integer_search_levels_.empty());
DCHECK_EQ(var_lbs_.size(), integer_trail_.size());
const IntegerVariable i(var_lbs_.size());
var_lbs_.push_back(lower_bound);
var_trail_index_.push_back(integer_trail_.size());
integer_trail_.push_back({lower_bound, i});
domains_->push_back(Domain(lower_bound.value(), upper_bound.value()));
CHECK_EQ(NegationOf(i).value(), var_lbs_.size());
var_lbs_.push_back(-upper_bound);
var_trail_index_.push_back(integer_trail_.size());
integer_trail_.push_back({-upper_bound, NegationOf(i)});
var_trail_index_cache_.resize(var_lbs_.size(), integer_trail_.size());
tmp_var_to_trail_index_in_queue_.resize(var_lbs_.size(), 0);
var_to_trail_index_at_lower_level_.resize(var_lbs_.size(), 0);
for (SparseBitset<IntegerVariable>* w : watchers_) {
w->Resize(NumIntegerVariables());
}
return i;
}
IntegerVariable IntegerTrail::AddIntegerVariable(const Domain& domain) {
CHECK(!domain.IsEmpty());
const IntegerVariable var = AddIntegerVariable(IntegerValue(domain.Min()),
IntegerValue(domain.Max()));
CHECK(UpdateInitialDomain(var, domain));
return var;
}
const Domain& IntegerTrail::InitialVariableDomain(IntegerVariable var) const {
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
if (VariableIsPositive(var)) return (*domains_)[index];
temp_domain_ = (*domains_)[index].Negation();
return temp_domain_;
}
// Note that we don't support optional variable here. Or at least if you set
// the domain of an optional variable to zero, the problem will be declared
// unsat.
bool IntegerTrail::UpdateInitialDomain(IntegerVariable var, Domain domain) {
CHECK_EQ(trail_->CurrentDecisionLevel(), 0);
if (!VariableIsPositive(var)) {
var = NegationOf(var);
domain = domain.Negation();
}
const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
const Domain& old_domain = (*domains_)[index];
domain = domain.IntersectionWith(old_domain);
if (old_domain == domain) return true;
if (domain.IsEmpty()) return false;
const bool lb_changed = domain.Min() > old_domain.Min();
const bool ub_changed = domain.Max() < old_domain.Max();
(*domains_)[index] = domain;
// Update directly the level zero bounds.
DCHECK(
ReasonIsValid(IntegerLiteral::LowerOrEqual(var, domain.Max()), {}, {}));
DCHECK(
ReasonIsValid(IntegerLiteral::GreaterOrEqual(var, domain.Min()), {}, {}));
DCHECK_GE(domain.Min(), LowerBound(var));
DCHECK_LE(domain.Max(), UpperBound(var));
var_lbs_[var] = domain.Min();
integer_trail_[var.value()].bound = domain.Min();
var_lbs_[NegationOf(var)] = -domain.Max();
integer_trail_[NegationOf(var).value()].bound = -domain.Max();
// Do not forget to update the watchers.
for (SparseBitset<IntegerVariable>* bitset : watchers_) {
if (lb_changed) bitset->Set(var);
if (ub_changed) bitset->Set(NegationOf(var));
}
// Update the encoding.
return encoder_->UpdateEncodingOnInitialDomainChange(var, domain);
}
IntegerVariable IntegerTrail::GetOrCreateConstantIntegerVariable(
IntegerValue value) {
auto insert = constant_map_.insert(std::make_pair(value, kNoIntegerVariable));
if (insert.second) { // new element.
const IntegerVariable new_var = AddIntegerVariable(value, value);
insert.first->second = new_var;
if (value != 0) {
// Note that this might invalidate insert.first->second.
CHECK(constant_map_.emplace(-value, NegationOf(new_var)).second);
}
return new_var;
}
return insert.first->second;
}
int IntegerTrail::NumConstantVariables() const {
// The +1 if for the special key zero (the only case when we have an odd
// number of entries).
return (constant_map_.size() + 1) / 2;
}
int IntegerTrail::FindTrailIndexOfVarBefore(IntegerVariable var,
int threshold) const {
// Optimization. We assume this is only called when computing a reason, so we
// can ignore this trail_index if we already need a more restrictive reason
// for this var.
//
// Hacky: We know this is only called with threshold == trail_index of the
// trail entry we are trying to explain. So this test can only trigger when a
// variable was shown to be already implied by the current conflict.
const int index_in_queue = tmp_var_to_trail_index_in_queue_[var];
if (threshold <= index_in_queue) {
// Disable the other optim if we might expand this literal during
// 1-UIP resolution.
const int last_decision_index =
integer_search_levels_.empty() ? 0 : integer_search_levels_.back();
if (index_in_queue >= last_decision_index) {
info_is_valid_on_subsequent_last_level_expansion_ = false;
}
return -1;
}
DCHECK_GE(threshold, var_lbs_.size());
int trail_index = var_trail_index_[var];
// Check the validity of the cached index and use it if possible.
if (trail_index > threshold) {
const int cached_index = var_trail_index_cache_[var];
if (cached_index >= threshold && cached_index < trail_index &&
integer_trail_[cached_index].var == var) {
trail_index = cached_index;
}
}
while (trail_index >= threshold) {
trail_index = integer_trail_[trail_index].prev_trail_index;
if (trail_index >= var_trail_index_cache_threshold_) {
var_trail_index_cache_[var] = trail_index;
}
}
const int num_vars = var_lbs_.size();
return trail_index < num_vars ? -1 : trail_index;
}
int IntegerTrail::FindLowestTrailIndexThatExplainBound(
IntegerLiteral i_lit) const {
DCHECK_LE(i_lit.bound, var_lbs_[i_lit.var]);
if (i_lit.bound <= LevelZeroLowerBound(i_lit.var)) return -1;
int trail_index = var_trail_index_[i_lit.var];
// Check the validity of the cached index and use it if possible. This caching
// mechanism is important in case of long chain of propagation on the same
// variable. Because during conflict resolution, we call
// FindLowestTrailIndexThatExplainBound() with lowest and lowest bound, this
// cache can transform a quadratic complexity into a linear one.