forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 9
/
clause.cc
2678 lines (2386 loc) · 95.8 KB
/
clause.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/clause.h"
#include <stddef.h>
#include <algorithm>
#include <cstdint>
#include <deque>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/container/inlined_vector.h"
#include "absl/log/check.h"
#include "absl/random/bit_gen_ref.h"
#include "absl/random/distributions.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/strong_vector.h"
#include "ortools/base/timer.h"
#include "ortools/graph/strongly_connected_components.h"
#include "ortools/sat/drat_proof_handler.h"
#include "ortools/sat/inclusion.h"
#include "ortools/sat/model.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/util.h"
#include "ortools/util/bitset.h"
#include "ortools/util/stats.h"
#include "ortools/util/strong_integers.h"
#include "ortools/util/time_limit.h"
namespace operations_research {
namespace sat {
namespace {
// Returns true if the given watcher list contains the given clause.
template <typename Watcher>
bool WatcherListContains(const std::vector<Watcher>& list,
const SatClause& candidate) {
for (const Watcher& watcher : list) {
if (watcher.clause == &candidate) return true;
}
return false;
}
// A simple wrapper to simplify the erase(std::remove_if()) pattern.
template <typename Container, typename Predicate>
void RemoveIf(Container c, Predicate p) {
c->erase(std::remove_if(c->begin(), c->end(), p), c->end());
}
} // namespace
// ----- ClauseManager -----
ClauseManager::ClauseManager(Model* model)
: SatPropagator("ClauseManager"),
implication_graph_(model->GetOrCreate<BinaryImplicationGraph>()),
trail_(model->GetOrCreate<Trail>()),
num_inspected_clauses_(0),
num_inspected_clause_literals_(0),
num_watched_clauses_(0),
stats_("ClauseManager") {
trail_->RegisterPropagator(this);
}
ClauseManager::~ClauseManager() {
gtl::STLDeleteElements(&clauses_);
IF_STATS_ENABLED(LOG(INFO) << stats_.StatString());
}
void ClauseManager::Resize(int num_variables) {
DCHECK(is_clean_);
watchers_on_false_.resize(num_variables << 1);
reasons_.resize(num_variables);
needs_cleaning_.Resize(LiteralIndex(num_variables << 1));
}
// Note that this is the only place where we add Watcher so the DCHECK
// guarantees that there are no duplicates.
void ClauseManager::AttachOnFalse(Literal literal, Literal blocking_literal,
SatClause* clause) {
SCOPED_TIME_STAT(&stats_);
DCHECK(is_clean_);
DCHECK(!WatcherListContains(watchers_on_false_[literal], *clause));
watchers_on_false_[literal].push_back(Watcher(clause, blocking_literal));
}
bool ClauseManager::PropagateOnFalse(Literal false_literal, Trail* trail) {
SCOPED_TIME_STAT(&stats_);
DCHECK(is_clean_);
std::vector<Watcher>& watchers = watchers_on_false_[false_literal];
const auto assignment = AssignmentView(trail->Assignment());
// Note(user): It sounds better to inspect the list in order, this is because
// small clauses like binary or ternary clauses will often propagate and thus
// stay at the beginning of the list.
auto new_it = watchers.begin();
const auto end = watchers.end();
while (new_it != end && assignment.LiteralIsTrue(new_it->blocking_literal)) {
++new_it;
}
for (auto it = new_it; it != end; ++it) {
// Don't even look at the clause memory if the blocking literal is true.
if (assignment.LiteralIsTrue(it->blocking_literal)) {
*new_it++ = *it;
continue;
}
++num_inspected_clauses_;
// If the other watched literal is true, just change the blocking literal.
// Note that we use the fact that the first two literals of the clause are
// the ones currently watched.
Literal* literals = it->clause->literals();
const Literal other_watched_literal(
LiteralIndex(literals[0].Index().value() ^ literals[1].Index().value() ^
false_literal.Index().value()));
if (assignment.LiteralIsTrue(other_watched_literal)) {
*new_it = *it;
new_it->blocking_literal = other_watched_literal;
++new_it;
++num_inspected_clause_literals_;
continue;
}
// Look for another literal to watch. We go through the list in a cyclic
// fashion from start. The first two literals can be ignored as they are the
// watched ones.
{
const int start = it->start_index;
const int size = it->clause->size();
DCHECK_GE(start, 2);
int i = start;
while (i < size && assignment.LiteralIsFalse(literals[i])) ++i;
num_inspected_clause_literals_ += i - start + 2;
if (i >= size) {
i = 2;
while (i < start && assignment.LiteralIsFalse(literals[i])) ++i;
num_inspected_clause_literals_ += i - 2;
if (i >= start) i = size;
}
if (i < size) {
// literal[i] is unassigned or true, it's now the new literal to watch.
// Note that by convention, we always keep the two watched literals at
// the beginning of the clause.
literals[0] = other_watched_literal;
literals[1] = literals[i];
literals[i] = false_literal;
watchers_on_false_[literals[1]].emplace_back(
it->clause, other_watched_literal, i + 1);
continue;
}
}
// At this point other_watched_literal is either false or unassigned, all
// other literals are false.
if (assignment.LiteralIsFalse(other_watched_literal)) {
// Conflict: All literals of it->clause are false.
//
// Note(user): we could avoid a copy here, but the conflict analysis
// complexity will be a lot higher than this anyway.
trail->MutableConflict()->assign(it->clause->begin(), it->clause->end());
trail->SetFailingSatClause(it->clause);
num_inspected_clause_literals_ += it - watchers.begin() + 1;
watchers.erase(new_it, it);
return false;
} else {
// Propagation: other_watched_literal is unassigned, set it to true and
// put it at position 0. Note that the position 0 is important because
// we will need later to recover the literal that was propagated from the
// clause using this convention.
literals[0] = other_watched_literal;
literals[1] = false_literal;
reasons_[trail->Index()] = it->clause;
trail->Enqueue(other_watched_literal, propagator_id_);
*new_it++ = *it;
}
}
num_inspected_clause_literals_ += watchers.size(); // The blocking ones.
watchers.erase(new_it, end);
return true;
}
bool ClauseManager::Propagate(Trail* trail) {
const int old_index = trail->Index();
while (trail->Index() == old_index && propagation_trail_index_ < old_index) {
const Literal literal = (*trail)[propagation_trail_index_++];
if (!PropagateOnFalse(literal.Negated(), trail)) return false;
}
return true;
}
absl::Span<const Literal> ClauseManager::Reason(const Trail& /*trail*/,
int trail_index,
int64_t /*conflict_id*/) const {
return reasons_[trail_index]->PropagationReason();
}
SatClause* ClauseManager::ReasonClause(int trail_index) const {
return reasons_[trail_index];
}
bool ClauseManager::AddClause(absl::Span<const Literal> literals) {
return AddClause(literals, trail_, -1);
}
bool ClauseManager::AddClause(absl::Span<const Literal> literals, Trail* trail,
int lbd) {
SatClause* clause = SatClause::Create(literals);
clauses_.push_back(clause);
if (add_clause_callback_ != nullptr) add_clause_callback_(lbd, literals);
return AttachAndPropagate(clause, trail);
}
SatClause* ClauseManager::AddRemovableClause(absl::Span<const Literal> literals,
Trail* trail, int lbd) {
SatClause* clause = SatClause::Create(literals);
clauses_.push_back(clause);
if (add_clause_callback_ != nullptr) add_clause_callback_(lbd, literals);
CHECK(AttachAndPropagate(clause, trail));
return clause;
}
// Sets up the 2-watchers data structure. It selects two non-false literals
// and attaches the clause to the event: one of the watched literals become
// false. It returns false if the clause only contains literals assigned to
// false. If only one literals is not false, it propagates it to true if it
// is not already assigned.
bool ClauseManager::AttachAndPropagate(SatClause* clause, Trail* trail) {
SCOPED_TIME_STAT(&stats_);
const int size = clause->size();
Literal* literals = clause->literals();
// Select the first two literals that are not assigned to false and put them
// on position 0 and 1.
int num_literal_not_false = 0;
for (int i = 0; i < size; ++i) {
if (!trail->Assignment().LiteralIsFalse(literals[i])) {
std::swap(literals[i], literals[num_literal_not_false]);
++num_literal_not_false;
if (num_literal_not_false == 2) {
break;
}
}
}
// Returns false if all the literals were false.
// This should only happen on an UNSAT problem, and there is no need to attach
// the clause in this case.
if (num_literal_not_false == 0) return false;
if (num_literal_not_false == 1) {
// To maintain the validity of the 2-watcher algorithm, we need to watch
// the false literal with the highest decision level.
int max_level = trail->Info(literals[1].Variable()).level;
for (int i = 2; i < size; ++i) {
const int level = trail->Info(literals[i].Variable()).level;
if (level > max_level) {
max_level = level;
std::swap(literals[1], literals[i]);
}
}
// Propagates literals[0] if it is unassigned.
if (!trail->Assignment().LiteralIsTrue(literals[0])) {
reasons_[trail->Index()] = clause;
trail->Enqueue(literals[0], propagator_id_);
}
}
++num_watched_clauses_;
AttachOnFalse(literals[0], literals[1], clause);
AttachOnFalse(literals[1], literals[0], clause);
return true;
}
void ClauseManager::Attach(SatClause* clause, Trail* trail) {
Literal* literals = clause->literals();
DCHECK(!trail->Assignment().LiteralIsAssigned(literals[0]));
DCHECK(!trail->Assignment().LiteralIsAssigned(literals[1]));
++num_watched_clauses_;
AttachOnFalse(literals[0], literals[1], clause);
AttachOnFalse(literals[1], literals[0], clause);
}
void ClauseManager::InternalDetach(SatClause* clause) {
--num_watched_clauses_;
const size_t size = clause->size();
if (drat_proof_handler_ != nullptr && size > 2) {
drat_proof_handler_->DeleteClause({clause->begin(), size});
}
clauses_info_.erase(clause);
clause->Clear();
}
void ClauseManager::LazyDetach(SatClause* clause) {
InternalDetach(clause);
is_clean_ = false;
needs_cleaning_.Set(clause->FirstLiteral());
needs_cleaning_.Set(clause->SecondLiteral());
}
void ClauseManager::Detach(SatClause* clause) {
InternalDetach(clause);
for (const Literal l : {clause->FirstLiteral(), clause->SecondLiteral()}) {
needs_cleaning_.Clear(l);
RemoveIf(&(watchers_on_false_[l]), [](const Watcher& watcher) {
return watcher.clause->IsRemoved();
});
}
}
void ClauseManager::DetachAllClauses() {
if (!all_clauses_are_attached_) return;
all_clauses_are_attached_ = false;
// This is easy, and this allows to reset memory if some watcher lists where
// really long at some point.
is_clean_ = true;
num_watched_clauses_ = 0;
watchers_on_false_.clear();
}
void ClauseManager::AttachAllClauses() {
if (all_clauses_are_attached_) return;
all_clauses_are_attached_ = true;
needs_cleaning_.ClearAll(); // This doesn't resize it.
watchers_on_false_.resize(needs_cleaning_.size().value());
DeleteRemovedClauses();
for (SatClause* clause : clauses_) {
++num_watched_clauses_;
DCHECK_GE(clause->size(), 2);
AttachOnFalse(clause->FirstLiteral(), clause->SecondLiteral(), clause);
AttachOnFalse(clause->SecondLiteral(), clause->FirstLiteral(), clause);
}
}
// This one do not need the clause to be detached.
bool ClauseManager::InprocessingFixLiteral(Literal true_literal) {
DCHECK_EQ(trail_->CurrentDecisionLevel(), 0);
if (drat_proof_handler_ != nullptr) {
drat_proof_handler_->AddClause({true_literal});
}
// TODO(user): remove the test when the DRAT issue with fixed literal is
// resolved.
if (!trail_->Assignment().LiteralIsTrue(true_literal)) {
trail_->EnqueueWithUnitReason(true_literal);
// Even when all clauses are detached, we can propagate the implication
// graph and we do that right away.
return implication_graph_->Propagate(trail_);
}
return true;
}
// TODO(user): We could do something slower if the clauses are attached like
// we do for InprocessingRewriteClause().
void ClauseManager::InprocessingRemoveClause(SatClause* clause) {
DCHECK(!all_clauses_are_attached_);
if (drat_proof_handler_ != nullptr) {
drat_proof_handler_->DeleteClause(clause->AsSpan());
}
clauses_info_.erase(clause);
clause->Clear();
}
bool ClauseManager::InprocessingRewriteClause(
SatClause* clause, absl::Span<const Literal> new_clause) {
if (new_clause.empty()) return false; // UNSAT.
if (DEBUG_MODE) {
for (const Literal l : new_clause) {
DCHECK(!trail_->Assignment().LiteralIsAssigned(l));
}
}
if (new_clause.size() == 1) {
if (!InprocessingFixLiteral(new_clause[0])) return false;
InprocessingRemoveClause(clause);
return true;
}
if (new_clause.size() == 2) {
CHECK(implication_graph_->AddBinaryClause(new_clause[0], new_clause[1]));
InprocessingRemoveClause(clause);
return true;
}
if (drat_proof_handler_ != nullptr) {
// We must write the new clause before we delete the old one.
drat_proof_handler_->AddClause(new_clause);
drat_proof_handler_->DeleteClause(clause->AsSpan());
}
if (all_clauses_are_attached_) {
// We can still rewrite the clause, but it is inefficient. We first
// detach it in a non-lazy way.
--num_watched_clauses_;
clause->Clear();
for (const Literal l : {clause->FirstLiteral(), clause->SecondLiteral()}) {
needs_cleaning_.Clear(l);
RemoveIf(&(watchers_on_false_[l]), [](const Watcher& watcher) {
return watcher.clause->IsRemoved();
});
}
}
clause->Rewrite(new_clause);
// And we reattach it.
if (all_clauses_are_attached_) Attach(clause, trail_);
return true;
}
SatClause* ClauseManager::InprocessingAddClause(
absl::Span<const Literal> new_clause) {
DCHECK(!new_clause.empty());
DCHECK(!all_clauses_are_attached_);
if (DEBUG_MODE) {
for (const Literal l : new_clause) {
DCHECK(!trail_->Assignment().LiteralIsAssigned(l));
}
}
if (new_clause.size() == 1) {
// TODO(user): We should return false...
if (!InprocessingFixLiteral(new_clause[0])) return nullptr;
return nullptr;
}
if (new_clause.size() == 2) {
implication_graph_->AddBinaryClause(new_clause[0], new_clause[1]);
return nullptr;
}
SatClause* clause = SatClause::Create(new_clause);
clauses_.push_back(clause);
return clause;
}
void ClauseManager::CleanUpWatchers() {
SCOPED_TIME_STAT(&stats_);
for (const LiteralIndex index : needs_cleaning_.PositionsSetAtLeastOnce()) {
DCHECK(needs_cleaning_[index]);
RemoveIf(&(watchers_on_false_[index]), [](const Watcher& watcher) {
return watcher.clause->IsRemoved();
});
needs_cleaning_.Clear(index);
}
needs_cleaning_.NotifyAllClear();
is_clean_ = true;
}
// We also update to_minimize_index_/to_probe_index_ correctly.
//
// TODO(user): If more indices are needed, generalize the code to a vector of
// indices.
void ClauseManager::DeleteRemovedClauses() {
DCHECK(is_clean_);
int new_size = 0;
const int old_size = clauses_.size();
for (int i = 0; i < old_size; ++i) {
if (i == to_minimize_index_) to_minimize_index_ = new_size;
if (i == to_first_minimize_index_) to_first_minimize_index_ = new_size;
if (i == to_probe_index_) to_probe_index_ = new_size;
if (clauses_[i]->IsRemoved()) {
delete clauses_[i];
} else {
clauses_[new_size++] = clauses_[i];
}
}
clauses_.resize(new_size);
if (to_minimize_index_ > new_size) to_minimize_index_ = new_size;
if (to_first_minimize_index_ > new_size) to_first_minimize_index_ = new_size;
if (to_probe_index_ > new_size) to_probe_index_ = new_size;
}
SatClause* ClauseManager::NextNewClauseToMinimize() {
for (; to_first_minimize_index_ < clauses_.size();
++to_first_minimize_index_) {
if (clauses_[to_first_minimize_index_]->IsRemoved()) continue;
if (!IsRemovable(clauses_[to_first_minimize_index_])) {
// If the round-robin is in-sync with the new clauses, we may as well
// count this minimization as part of the round-robin and advance both
// indexes.
if (to_minimize_index_ == to_first_minimize_index_) {
++to_minimize_index_;
}
return clauses_[to_first_minimize_index_++];
}
}
return nullptr;
}
SatClause* ClauseManager::NextClauseToMinimize() {
for (; to_minimize_index_ < clauses_.size(); ++to_minimize_index_) {
if (clauses_[to_minimize_index_]->IsRemoved()) continue;
if (!IsRemovable(clauses_[to_minimize_index_])) {
return clauses_[to_minimize_index_++];
}
}
return nullptr;
}
SatClause* ClauseManager::NextClauseToProbe() {
for (; to_probe_index_ < clauses_.size(); ++to_probe_index_) {
if (clauses_[to_probe_index_]->IsRemoved()) continue;
return clauses_[to_probe_index_++];
}
return nullptr;
}
// ----- BinaryImplicationGraph -----
void BinaryImplicationGraph::Resize(int num_variables) {
SCOPED_TIME_STAT(&stats_);
bfs_stack_.resize(num_variables << 1);
implications_.resize(num_variables << 1);
implies_something_.resize(num_variables << 1);
might_have_dups_.resize(num_variables << 1);
is_redundant_.resize(implications_.size());
is_removed_.resize(implications_.size(), false);
estimated_sizes_.resize(implications_.size(), 0);
in_direct_implications_.resize(implications_.size(), false);
reasons_.resize(num_variables);
}
void BinaryImplicationGraph::NotifyPossibleDuplicate(Literal a) {
if (might_have_dups_[a.Index()]) return;
might_have_dups_[a.Index()] = true;
to_clean_.push_back(a);
}
void BinaryImplicationGraph::RemoveDuplicates() {
for (const Literal l : to_clean_) {
might_have_dups_[l.Index()] = false;
gtl::STLSortAndRemoveDuplicates(&implications_[l.Index()]);
}
to_clean_.clear();
}
// TODO(user): Not all of the solver knows about representative literal, do
// use them here to maintains invariant? Explore this when we start cleaning our
// clauses using equivalence during search. We can easily do it for every
// conflict we learn instead of here.
bool BinaryImplicationGraph::AddBinaryClause(Literal a, Literal b) {
SCOPED_TIME_STAT(&stats_);
// Tricky: If this is the first clause, the propagator will be added and
// assumed to be in a "propagated" state. This makes sure this is the case.
if (IsEmpty()) propagation_trail_index_ = trail_->Index();
if (drat_proof_handler_ != nullptr) {
// TODO(user): Like this we will duplicate all binary clause from the
// problem. However this leads to a simpler API (since we don't need to
// special case the loading of the original clauses) and we mainly use drat
// proof for testing anyway.
drat_proof_handler_->AddClause({a, b});
}
if (is_redundant_[a.Index()]) a = Literal(representative_of_[a.Index()]);
if (is_redundant_[b.Index()]) b = Literal(representative_of_[b.Index()]);
if (a == b.Negated()) return true;
if (a == b) return FixLiteral(a);
DCHECK(!is_removed_[a]);
DCHECK(!is_removed_[b]);
estimated_sizes_[a.NegatedIndex()]++;
estimated_sizes_[b.NegatedIndex()]++;
implications_[a.NegatedIndex()].push_back(b);
implications_[b.NegatedIndex()].push_back(a);
implies_something_.Set(a.NegatedIndex());
implies_something_.Set(b.NegatedIndex());
NotifyPossibleDuplicate(a);
NotifyPossibleDuplicate(b);
is_dag_ = false;
num_implications_ += 2;
if (enable_sharing_ && add_binary_callback_ != nullptr) {
add_binary_callback_(a, b);
}
const auto& assignment = trail_->Assignment();
if (trail_->CurrentDecisionLevel() == 0) {
DCHECK(!assignment.LiteralIsAssigned(a));
DCHECK(!assignment.LiteralIsAssigned(b));
} else {
if (assignment.LiteralIsFalse(a)) {
if (assignment.LiteralIsAssigned(b)) {
if (assignment.LiteralIsFalse(b)) return false;
} else {
reasons_[trail_->Index()] = a;
trail_->Enqueue(b, propagator_id_);
}
} else if (assignment.LiteralIsFalse(b)) {
if (!assignment.LiteralIsAssigned(a)) {
reasons_[trail_->Index()] = b;
trail_->Enqueue(a, propagator_id_);
}
}
}
return true;
}
bool BinaryImplicationGraph::AddAtMostOne(
absl::Span<const Literal> at_most_one) {
DCHECK_EQ(trail_->CurrentDecisionLevel(), 0);
if (at_most_one.size() <= 1) return true;
// Temporarily copy the at_most_one constraint at the end of
// at_most_one_buffer_. It will be cleaned up and added by
// CleanUpAndAddAtMostOnes().
const int base_index = at_most_one_buffer_.size();
at_most_one_buffer_.push_back(Literal(LiteralIndex(at_most_one.size())));
at_most_one_buffer_.insert(at_most_one_buffer_.end(), at_most_one.begin(),
at_most_one.end());
is_dag_ = false;
return CleanUpAndAddAtMostOnes(base_index);
}
// TODO(user): remove dupl with ClauseManager::InprocessingFixLiteral().
//
// Note that we currently do not support calling this at a positive level since
// we might loose the fixing on backtrack otherwise.
bool BinaryImplicationGraph::FixLiteral(Literal true_literal) {
CHECK_EQ(trail_->CurrentDecisionLevel(), 0);
if (trail_->Assignment().LiteralIsTrue(true_literal)) return true;
if (trail_->Assignment().LiteralIsFalse(true_literal)) return false;
if (drat_proof_handler_ != nullptr) {
drat_proof_handler_->AddClause({true_literal});
}
trail_->EnqueueWithUnitReason(true_literal);
return Propagate(trail_);
}
// This works by doing a linear scan on the at_most_one_buffer_ and
// cleaning/copying the at most ones on the fly to the beginning of the same
// buffer.
bool BinaryImplicationGraph::CleanUpAndAddAtMostOnes(int base_index) {
const VariablesAssignment& assignment = trail_->Assignment();
int local_end = base_index;
const int buffer_size = at_most_one_buffer_.size();
for (int i = base_index; i < buffer_size;) {
// Process a new at most one.
// It will be copied into buffer[local_start + 1, local_end].
// With its size at buffer[local_start].
const int local_start = local_end;
// Update the iterator now. Even if the current at_most_one is reduced away,
// local_start will still point to the next one, or to the end of the
// buffer.
if (i == at_most_one_iterator_) {
at_most_one_iterator_ = local_start;
}
// We have an at_most_one starting at i, and we increment i to the next one.
const absl::Span<const Literal> initial_amo = AtMostOne(i);
i += initial_amo.size() + 1;
// Reserve space for size.
local_end++;
bool set_all_left_to_false = false;
for (const Literal l : initial_amo) {
if (assignment.LiteralIsFalse(l)) continue;
if (is_removed_[l]) continue;
if (!set_all_left_to_false && assignment.LiteralIsTrue(l)) {
set_all_left_to_false = true;
continue;
}
at_most_one_buffer_[local_end++] = RepresentativeOf(l);
}
at_most_one_buffer_[local_start] =
Literal(LiteralIndex(local_end - local_start - 1));
// Deal with duplicates.
// Any duplicate in an "at most one" must be false.
bool some_duplicates = false;
if (!set_all_left_to_false) {
// Sort the copied amo.
// We only want to expose a const AtMostOne() so we sort directly here.
Literal* pt = &at_most_one_buffer_[local_start + 1];
std::sort(pt, pt + AtMostOne(local_start).size());
LiteralIndex previous = kNoLiteralIndex;
bool remove_previous = false;
int new_local_end = local_start + 1;
for (const Literal l : AtMostOne(local_start)) {
if (l.Index() == previous) {
if (assignment.LiteralIsTrue(l)) return false;
if (!assignment.LiteralIsFalse(l)) {
if (!FixLiteral(l.Negated())) return false;
}
remove_previous = true;
some_duplicates = true;
continue;
}
// We need to pay attention to triplet or more of equal elements, so
// it is why we need this boolean and can't just remove it right away.
if (remove_previous) {
--new_local_end;
remove_previous = false;
}
previous = l.Index();
at_most_one_buffer_[new_local_end++] = l;
}
if (remove_previous) --new_local_end;
// Update local end and the amo size.
local_end = new_local_end;
at_most_one_buffer_[local_start] =
Literal(LiteralIndex(local_end - local_start - 1));
}
// If there was some duplicates, we need to rescan to see if a literal
// didn't become true because its negation was appearing twice!
if (some_duplicates) {
int new_local_end = local_start + 1;
for (const Literal l : AtMostOne(local_start)) {
if (assignment.LiteralIsFalse(l)) continue;
if (!set_all_left_to_false && assignment.LiteralIsTrue(l)) {
set_all_left_to_false = true;
continue;
}
at_most_one_buffer_[new_local_end++] = l;
}
// Update local end and the amo size.
local_end = new_local_end;
at_most_one_buffer_[local_start] =
Literal(LiteralIndex(local_end - local_start - 1));
}
// Deal with all false.
if (set_all_left_to_false) {
for (const Literal l : AtMostOne(local_start)) {
if (assignment.LiteralIsFalse(l)) continue;
if (assignment.LiteralIsTrue(l)) return false;
if (!FixLiteral(l.Negated())) return false;
}
// Erase this at_most_one.
local_end = local_start;
continue;
}
// Create a Span<> to simplify the code below.
const absl::Span<const Literal> at_most_one = AtMostOne(local_start);
// We expand small sizes into implications.
// TODO(user): Investigate what the best threshold is.
if (at_most_one.size() <= std::max(2, at_most_one_max_expansion_size_)) {
for (const Literal a : at_most_one) {
for (const Literal b : at_most_one) {
if (a == b) continue;
implications_[a].push_back(b.Negated());
implies_something_.Set(a);
NotifyPossibleDuplicate(a);
}
}
num_implications_ += at_most_one.size() * (at_most_one.size() - 1);
// This will erase the at_most_one from the buffer.
local_end = local_start;
continue;
}
// Index the new at most one.
for (const Literal l : at_most_one) {
if (l.Index() >= at_most_ones_.size()) {
at_most_ones_.resize(l.Index().value() + 1);
}
DCHECK(!is_redundant_[l]);
at_most_ones_[l].push_back(local_start);
implies_something_.Set(l);
}
}
at_most_one_buffer_.resize(local_end);
return true;
}
bool BinaryImplicationGraph::PropagateOnTrue(Literal true_literal,
Trail* trail) {
SCOPED_TIME_STAT(&stats_);
const auto assignment = AssignmentView(trail->Assignment());
DCHECK(assignment.LiteralIsTrue(true_literal));
// Note(user): This update is not exactly correct because in case of conflict
// we don't inspect that much clauses. But doing ++num_inspections_ inside the
// loop does slow down the code by a few percent.
num_inspections_ += implications_[true_literal].size();
for (const Literal literal : implications_[true_literal]) {
if (assignment.LiteralIsTrue(literal)) {
// Note(user): I tried to update the reason here if the literal was
// enqueued after the true_literal on the trail. This property is
// important for ComputeFirstUIPConflict() to work since it needs the
// trail order to be a topological order for the deduction graph.
// But the performance was not too good...
continue;
}
++num_propagations_;
if (assignment.LiteralIsFalse(literal)) {
// Conflict.
*(trail->MutableConflict()) = {true_literal.Negated(), literal};
return false;
} else {
// Propagation.
reasons_[trail->Index()] = true_literal.Negated();
trail->FastEnqueue(literal);
}
}
// Propagate the at_most_one constraints.
if (true_literal.Index() < at_most_ones_.size()) {
for (const int start : at_most_ones_[true_literal]) {
bool seen = false;
for (const Literal literal : AtMostOne(start)) {
++num_inspections_;
if (literal == true_literal) {
if (DEBUG_MODE) {
DCHECK(!seen);
seen = true;
}
continue;
}
if (assignment.LiteralIsFalse(literal)) continue;
++num_propagations_;
if (assignment.LiteralIsTrue(literal)) {
// Conflict.
*(trail->MutableConflict()) = {true_literal.Negated(),
literal.Negated()};
return false;
} else {
// Propagation.
reasons_[trail->Index()] = true_literal.Negated();
trail->FastEnqueue(literal.Negated());
}
}
}
}
return true;
}
bool BinaryImplicationGraph::Propagate(Trail* trail) {
if (IsEmpty()) {
propagation_trail_index_ = trail->Index();
return true;
}
trail->SetCurrentPropagatorId(propagator_id_);
while (propagation_trail_index_ < trail->Index()) {
const Literal literal = (*trail)[propagation_trail_index_++];
if (!PropagateOnTrue(literal, trail)) return false;
}
return true;
}
absl::Span<const Literal> BinaryImplicationGraph::Reason(
const Trail& /*trail*/, int trail_index, int64_t /*conflict_id*/) const {
return {&reasons_[trail_index], 1};
}
// Here, we remove all the literal whose negation are implied by the negation of
// the 1-UIP literal (which always appear first in the given conflict). Note
// that this algorithm is "optimal" in the sense that it leads to a minimized
// conflict with a backjump level as low as possible. However, not all possible
// literals are removed.
//
// TODO(user): Also consider at most one?
void BinaryImplicationGraph::MinimizeConflictWithReachability(
std::vector<Literal>* conflict) {
SCOPED_TIME_STAT(&stats_);
dfs_stack_.clear();
// Compute the reachability from the literal "not(conflict->front())" using
// an iterative dfs.
const LiteralIndex root_literal_index = conflict->front().NegatedIndex();
is_marked_.ClearAndResize(LiteralIndex(implications_.size()));
is_marked_.Set(root_literal_index);
// TODO(user): This sounds like a good idea, but somehow it seems better not
// to do that even though it is almost for free. Investigate more.
//
// The idea here is that since we already compute the reachability from the
// root literal, we can use this computation to remove any implication
// root_literal => b if there is already root_literal => a and b is reachable
// from a.
const bool also_prune_direct_implication_list = false;
// We treat the direct implications differently so we can also remove the
// redundant implications from this list at the same time.
auto& direct_implications = implications_[root_literal_index];
for (const Literal l : direct_implications) {
if (is_marked_[l]) continue;
dfs_stack_.push_back(l);
while (!dfs_stack_.empty()) {
const LiteralIndex index = dfs_stack_.back().Index();
dfs_stack_.pop_back();
if (!is_marked_[index]) {
is_marked_.Set(index);
for (const Literal implied : implications_[index]) {
if (!is_marked_[implied]) dfs_stack_.push_back(implied);
}
}
}
// The "trick" is to unmark 'l'. This way, if we explore it twice, it means
// that this l is reachable from some other 'l' from the direct implication
// list. Remarks:
// - We don't loose too much complexity when this happen since a literal
// can be unmarked only once, so in the worst case we loop twice over its
// children. Moreover, this literal will be pruned for later calls.
// - This is correct, i.e. we can't prune too many literals because of a
// strongly connected component. Proof by contradiction: If we take the
// first (in direct_implications) literal from a removed SCC, it must
// have marked all the others. But because they are marked, they will not
// be explored again and so can't mark the first literal.
if (also_prune_direct_implication_list) {
is_marked_.Clear(l);
}
}
// Now we can prune the direct implications list and make sure are the
// literals there are marked.
if (also_prune_direct_implication_list) {
int new_size = 0;
for (const Literal l : direct_implications) {
if (!is_marked_[l]) {
is_marked_.Set(l);
direct_implications[new_size] = l;
++new_size;
}
}
if (new_size < direct_implications.size()) {
num_redundant_implications_ += direct_implications.size() - new_size;
direct_implications.resize(new_size);
}
}
RemoveRedundantLiterals(conflict);
}
// Same as MinimizeConflictWithReachability() but also mark (in the given
// SparseBitset) the reachable literal already assigned to false. These literals
// will be implied if the 1-UIP literal is assigned to false, and the classic
// minimization algorithm can take advantage of that.
void BinaryImplicationGraph::MinimizeConflictFirst(
const Trail& trail, std::vector<Literal>* conflict,
SparseBitset<BooleanVariable>* marked) {
SCOPED_TIME_STAT(&stats_);
DCHECK(!conflict->empty());
is_marked_.ClearAndResize(LiteralIndex(implications_.size()));
MarkDescendants(conflict->front().Negated());
for (const LiteralIndex i : is_marked_.PositionsSetAtLeastOnce()) {
// TODO(user): if this is false, then we actually have a conflict of size 2.
// This can only happen if the binary clause was not propagated properly
// if for instance we do chronological bactracking without re-enqueuing the
// consequence of a binary clause.
if (trail.Assignment().LiteralIsTrue(Literal(i))) {
marked->Set(Literal(i).Variable());
}
}
RemoveRedundantLiterals(conflict);
}
// Same as MinimizeConflictFirst() but take advantage of this reachability
// computation to remove redundant implication in the implication list of the
// first UIP conflict.