20 #include <type_traits>
30 const std::vector<IntegerVariable>& vars) {
31 std::vector<IntegerVariable> result(vars.size());
32 for (
int i = 0; i < vars.size(); ++i) {
44 <<
"Domain too large for full encoding.";
57 tmp_values_.push_back(v);
60 for (
const IntegerValue v : tmp_values_) {
72 if (
index >= is_fully_encoded_.
size())
return false;
75 if (is_fully_encoded_[
index])
return true;
82 const int64_t initial_domain_size = (*domains_)[
var].Size();
83 if (equality_by_var_[
index].size() < initial_domain_size)
return false;
92 const auto& ref = equality_by_var_[
index];
96 if (i < ref.size() && v == ref[i].value) {
101 if (i == ref.size()) {
102 is_fully_encoded_[
index] =
true;
104 return is_fully_encoded_[
index];
107 std::vector<IntegerEncoder::ValueLiteralPair>
113 std::vector<IntegerEncoder::ValueLiteralPair>
117 if (
index >= equality_by_var_.size())
return {};
120 std::vector<ValueLiteralPair>& ref = equality_by_var_[
index];
121 for (
int i = 0; i < ref.size(); ++i) {
130 ref[new_size++] = pair;
132 ref.resize(new_size);
133 std::sort(ref.begin(), ref.end());
135 std::vector<IntegerEncoder::ValueLiteralPair> result = ref;
137 std::reverse(result.begin(), result.end());
146 void IntegerEncoder::AddImplications(
147 const std::map<IntegerValue, Literal>& map,
148 std::map<IntegerValue, Literal>::const_iterator it,
150 if (!add_implications_)
return;
156 if (after_it != map.end()) {
158 {after_it->second.Negated(), associated_lit});
162 if (it != map.begin()) {
166 {associated_lit.
Negated(), before_it->second});
172 add_implications_ =
true;
173 for (
const std::map<IntegerValue, Literal>& encoding : encoding_by_var_) {
175 for (
const auto value_literal : encoding) {
176 const Literal lit = value_literal.second;
181 previous = lit.
Index();
188 const IntegerVariable
var(i_lit.
var);
189 IntegerValue after(i_lit.
bound);
190 IntegerValue before(i_lit.
bound - 1);
195 if (before > previous && before <
interval.start) before = previous;
205 if (i_lit.
bound <= (*domains_)[i_lit.
var].Min()) {
208 if (i_lit.
bound > (*domains_)[i_lit.
var].Max()) {
220 ++num_created_variables_;
227 VLOG(1) <<
"Created a fixed literal for no reason!";
233 std::pair<PositiveOnlyIndex, IntegerValue> PositiveVarKey(IntegerVariable
var,
234 IntegerValue
value) {
241 IntegerVariable
var, IntegerValue
value)
const {
243 equality_to_associated_literal_.find(PositiveVarKey(
var,
value));
244 if (it != equality_to_associated_literal_.end()) {
245 return it->second.Index();
251 IntegerVariable
var, IntegerValue
value) {
254 equality_to_associated_literal_.find(PositiveVarKey(
var,
value));
255 if (it != equality_to_associated_literal_.end()) {
269 ++num_created_variables_;
279 VLOG(1) <<
"Created a fixed literal for no reason!";
286 const auto& domain = (*domains_)[i_lit.
var];
287 const IntegerValue
min(domain.Min());
288 const IntegerValue
max(domain.Max());
295 HalfAssociateGivenLiteral(pair.first,
literal);
296 HalfAssociateGivenLiteral(pair.second,
literal.Negated());
301 if (pair.first.bound ==
max) {
304 if (-pair.second.bound ==
min) {
312 IntegerValue
value) {
317 if (
value == 1 && domain.
Min() >= 0 && domain.
Max() <= 1) {
325 if (
value == -1 && domain.
Min() >= -1 && domain.
Max() <= 0) {
336 const auto insert_result = equality_to_associated_literal_.insert(
338 if (!insert_result.second) {
359 if (
index >= equality_by_var_.size()) {
360 equality_by_var_.resize(
index.value() + 1);
363 equality_by_var_[
index].push_back(
398 const int new_size = 1 +
literal.Index().value();
399 if (new_size > full_reverse_encoding_.
size()) {
400 full_reverse_encoding_.
resize(new_size);
410 void IntegerEncoder::HalfAssociateGivenLiteral(
IntegerLiteral i_lit,
413 const int new_size = 1 +
literal.Index().value();
414 if (new_size > reverse_encoding_.
size()) {
415 reverse_encoding_.
resize(new_size);
417 if (new_size > full_reverse_encoding_.
size()) {
418 full_reverse_encoding_.
resize(new_size);
422 if (i_lit.
var >= encoding_by_var_.size()) {
423 encoding_by_var_.resize(i_lit.
var.value() + 1);
425 auto& var_encoding = encoding_by_var_[i_lit.
var];
426 auto insert_result = var_encoding.insert({i_lit.
bound,
literal});
427 if (insert_result.second) {
428 AddImplications(var_encoding, insert_result.first,
literal);
431 newly_fixed_integer_literals_.push_back(i_lit);
439 const Literal associated(insert_result.first->second);
449 if (i.
var >= encoding_by_var_.size())
return false;
450 const std::map<IntegerValue, Literal>& encoding = encoding_by_var_[i.
var];
451 return encoding.find(i.
bound) != encoding.end();
456 const std::map<IntegerValue, Literal>& encoding = encoding_by_var_[i.
var];
457 const auto result = encoding.find(i.
bound);
459 return result->second.Index();
467 const std::map<IntegerValue, Literal>& encoding = encoding_by_var_[i.
var];
468 auto after_it = encoding.upper_bound(i.
bound);
471 *
bound = after_it->first;
472 return after_it->second.Index();
476 if (parameters_.log_search_progress() && num_decisions_to_break_loop_ > 0) {
477 LOG(
INFO) <<
"Num decisions to break propagation loop: "
478 << num_decisions_to_break_loop_;
489 if (level > integer_search_levels_.size()) {
490 integer_search_levels_.push_back(integer_trail_.size());
491 reason_decision_levels_.push_back(literals_reason_starts_.size());
497 var_to_current_lb_interval_index_.
SetLevel(level);
510 if (!
Enqueue(i_lit, {}, {}))
return false;
516 if (!
Enqueue(i_lit, {}, {}))
return false;
518 integer_literal_to_fix_.clear();
520 for (
const Literal lit : literal_to_fix_) {
525 literal_to_fix_.clear();
530 while (propagation_trail_index_ < trail->
Index()) {
536 if (!EnqueueAssociatedIntegerLiteral(i_lit,
literal)) {
548 var_to_current_lb_interval_index_.
SetLevel(level);
552 if (level < first_level_without_full_propagation_) {
553 first_level_without_full_propagation_ = -1;
558 if (level >= integer_search_levels_.size())
return;
559 const int target = integer_search_levels_[level];
560 integer_search_levels_.resize(level);
562 CHECK_LE(target, integer_trail_.size());
564 for (
int index = integer_trail_.size() - 1;
index >= target; --
index) {
565 const TrailEntry& entry = integer_trail_[
index];
566 if (entry.var < 0)
continue;
567 vars_[entry.var].current_trail_index = entry.prev_trail_index;
568 vars_[entry.var].current_bound =
569 integer_trail_[entry.prev_trail_index].bound;
571 integer_trail_.resize(target);
574 const int old_size = reason_decision_levels_[level];
575 reason_decision_levels_.resize(level);
576 if (old_size < literals_reason_starts_.size()) {
577 literals_reason_buffer_.resize(literals_reason_starts_[old_size]);
579 const int bound_start = bounds_reason_starts_[old_size];
580 bounds_reason_buffer_.resize(bound_start);
581 if (bound_start < trail_index_reason_buffer_.size()) {
582 trail_index_reason_buffer_.resize(bound_start);
585 literals_reason_starts_.resize(old_size);
586 bounds_reason_starts_.resize(old_size);
596 const int size = 2 * num_vars;
598 is_ignored_literals_.
reserve(size);
599 integer_trail_.reserve(size);
601 var_trail_index_cache_.
reserve(size);
602 tmp_var_to_trail_index_in_queue_.
reserve(size);
612 DCHECK(integer_search_levels_.empty());
615 const IntegerVariable i(vars_.
size());
630 var_trail_index_cache_.
resize(vars_.
size(), integer_trail_.size());
631 tmp_var_to_trail_index_in_queue_.
resize(vars_.
size(), 0);
642 IntegerValue(domain.
Max()));
648 return (*domains_)[
var];
656 if (old_domain == domain)
return true;
658 if (domain.
IsEmpty())
return false;
659 (*domains_)[
var] = domain;
662 var_to_current_lb_interval_index_.
Set(
var, 0);
681 if (i == domain.
NumIntervals() || pair.value < domain[i].start) {
691 <<
"Domain intersection fixed " << num_fixed
692 <<
" equality literal corresponding to values outside the new domain.";
699 IntegerValue
value) {
703 insert.first->second = new_var;
710 return insert.first->second;
716 return (constant_map_.size() + 1) / 2;
720 int threshold)
const {
724 const int index_in_queue = tmp_var_to_trail_index_in_queue_[
var];
725 if (threshold <= index_in_queue) {
727 has_dependency_ =
true;
732 int trail_index = vars_[
var].current_trail_index;
735 if (trail_index > threshold) {
736 const int cached_index = var_trail_index_cache_[
var];
737 if (cached_index >= threshold && cached_index < trail_index &&
738 integer_trail_[cached_index].
var ==
var) {
739 trail_index = cached_index;
743 while (trail_index >= threshold) {
744 trail_index = integer_trail_[trail_index].prev_trail_index;
745 if (trail_index >= var_trail_index_cache_threshold_) {
746 var_trail_index_cache_[
var] = trail_index;
750 const int num_vars = vars_.
size();
751 return trail_index < num_vars ? -1 : trail_index;
754 int IntegerTrail::FindLowestTrailIndexThatExplainBound(
758 int trail_index = vars_[i_lit.
var].current_trail_index;
766 const int cached_index = var_trail_index_cache_[i_lit.
var];
767 if (cached_index < trail_index) {
768 const TrailEntry& entry = integer_trail_[cached_index];
769 if (entry.var == i_lit.
var && entry.bound >= i_lit.
bound) {
770 trail_index = cached_index;
775 int prev_trail_index = trail_index;
777 if (trail_index >= var_trail_index_cache_threshold_) {
778 var_trail_index_cache_[i_lit.
var] = trail_index;
780 const TrailEntry& entry = integer_trail_[trail_index];
781 if (entry.bound == i_lit.
bound)
return trail_index;
782 if (entry.bound < i_lit.
bound)
return prev_trail_index;
783 prev_trail_index = trail_index;
784 trail_index = entry.prev_trail_index;
790 IntegerValue slack, absl::Span<const IntegerValue> coeffs,
791 std::vector<IntegerLiteral>* reason)
const {
793 if (slack == 0)
return;
794 const int size = reason->size();
795 tmp_indices_.resize(size);
796 for (
int i = 0; i < size; ++i) {
799 tmp_indices_[i] = vars_[(*reason)[i].var].current_trail_index;
805 for (
const int i : tmp_indices_) {
807 integer_trail_[i].
bound));
812 IntegerValue slack, absl::Span<const IntegerValue> coeffs,
813 absl::Span<const IntegerVariable> vars,
814 std::vector<IntegerLiteral>* reason)
const {
815 tmp_indices_.clear();
816 for (
const IntegerVariable
var : vars) {
817 tmp_indices_.push_back(vars_[
var].current_trail_index);
820 for (
const int i : tmp_indices_) {
822 integer_trail_[i].
bound));
827 absl::Span<const IntegerValue> coeffs,
828 std::vector<int>* trail_indices)
const {
830 DCHECK(relax_heap_.empty());
837 const int size = coeffs.size();
838 const int num_vars = vars_.
size();
839 for (
int i = 0; i < size; ++i) {
840 const int index = (*trail_indices)[i];
843 if (
index < num_vars)
continue;
846 const IntegerValue coeff = coeffs[i];
848 (*trail_indices)[new_size++] =
index;
855 const TrailEntry& entry = integer_trail_[
index];
857 index <= tmp_var_to_trail_index_in_queue_[entry.var]) {
858 (*trail_indices)[new_size++] =
index;
863 const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
865 CapProd(coeff.value(), (entry.bound - previous_entry.bound).value());
867 (*trail_indices)[new_size++] =
index;
871 relax_heap_.push_back({
index, coeff, diff});
873 trail_indices->resize(new_size);
874 std::make_heap(relax_heap_.begin(), relax_heap_.end());
876 while (slack > 0 && !relax_heap_.empty()) {
877 const RelaxHeapEntry heap_entry = relax_heap_.front();
878 std::pop_heap(relax_heap_.begin(), relax_heap_.end());
879 relax_heap_.pop_back();
882 if (heap_entry.diff > slack) {
883 trail_indices->push_back(heap_entry.index);
888 slack -= heap_entry.diff;
889 const int index = integer_trail_[heap_entry.index].prev_trail_index;
892 if (
index < num_vars)
continue;
893 if (heap_entry.coeff > slack) {
894 trail_indices->push_back(
index);
897 const TrailEntry& entry = integer_trail_[
index];
899 index <= tmp_var_to_trail_index_in_queue_[entry.var]) {
900 trail_indices->push_back(
index);
904 const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
905 const int64_t diff =
CapProd(heap_entry.coeff.value(),
906 (entry.bound - previous_entry.bound).value());
908 trail_indices->push_back(
index);
911 relax_heap_.push_back({
index, heap_entry.coeff, diff});
912 std::push_heap(relax_heap_.begin(), relax_heap_.end());
917 for (
const RelaxHeapEntry& entry : relax_heap_) {
918 trail_indices->push_back(entry.index);
924 std::vector<IntegerLiteral>* reason)
const {
928 (*reason)[new_size++] =
literal;
930 reason->resize(new_size);
933 std::vector<Literal>* IntegerTrail::InitializeConflict(
934 IntegerLiteral integer_literal,
const LazyReasonFunction& lazy_reason,
935 absl::Span<const Literal> literals_reason,
936 absl::Span<const IntegerLiteral> bounds_reason) {
937 DCHECK(tmp_queue_.empty());
939 if (lazy_reason ==
nullptr) {
940 conflict->assign(literals_reason.begin(), literals_reason.end());
941 const int num_vars = vars_.
size();
943 const int trail_index = FindLowestTrailIndexThatExplainBound(
literal);
944 if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
949 lazy_reason(integer_literal, integer_trail_.size(), conflict, &tmp_queue_);
956 std::string ReasonDebugString(absl::Span<const Literal> literal_reason,
957 absl::Span<const IntegerLiteral> integer_reason) {
958 std::string result =
"literals:{";
959 for (
const Literal l : literal_reason) {
960 if (result.back() !=
'{') result +=
",";
961 result += l.DebugString();
963 result +=
"} bounds:{";
964 for (
const IntegerLiteral l : integer_reason) {
965 if (result.back() !=
'{') result +=
",";
966 result += l.DebugString();
974 std::string IntegerTrail::DebugString() {
975 std::string result =
"trail:{";
976 const int num_vars = vars_.
size();
978 std::min(num_vars + 30,
static_cast<int>(integer_trail_.size()));
979 for (
int i = num_vars; i < limit; ++i) {
980 if (result.back() !=
'{') result +=
",";
983 integer_trail_[i].
bound)
986 if (limit < integer_trail_.size()) {
994 absl::Span<const Literal> literal_reason,
995 absl::Span<const IntegerLiteral> integer_reason) {
996 return EnqueueInternal(i_lit,
nullptr, literal_reason, integer_reason,
997 integer_trail_.size());
1002 std::vector<IntegerLiteral>* integer_reason) {
1010 return Enqueue(i_lit, *literal_reason, *integer_reason);
1014 literal_reason->push_back(lit.
Negated());
1015 return Enqueue(i_lit, *literal_reason, *integer_reason);
1019 integer_reason->push_back(
1030 absl::Span<const Literal> literal_reason,
1031 absl::Span<const IntegerLiteral> integer_reason,
1032 int trail_index_with_same_reason) {
1033 return EnqueueInternal(i_lit,
nullptr, literal_reason, integer_reason,
1034 trail_index_with_same_reason);
1039 return EnqueueInternal(i_lit, lazy_reason, {}, {}, integer_trail_.size());
1042 bool IntegerTrail::ReasonIsValid(
1043 absl::Span<const Literal> literal_reason,
1044 absl::Span<const IntegerLiteral> integer_reason) {
1046 for (
const Literal lit : literal_reason) {
1049 for (
const IntegerLiteral i_lit : integer_reason) {
1050 if (i_lit.
bound > vars_[i_lit.
var].current_bound) {
1053 LOG(
INFO) <<
"Reason " << i_lit <<
" is not true!"
1054 <<
" optional variable:" << i_lit.
var
1057 <<
" current_lb:" << vars_[i_lit.
var].current_bound;
1059 LOG(
INFO) <<
"Reason " << i_lit <<
" is not true!"
1060 <<
" non-optional variable:" << i_lit.
var
1061 <<
" current_lb:" << vars_[i_lit.
var].current_bound;
1069 if (!integer_search_levels_.empty()) {
1070 int num_literal_assigned_after_root_node = 0;
1071 for (
const Literal lit : literal_reason) {
1072 if (trail_->
Info(lit.Variable()).
level > 0) {
1073 num_literal_assigned_after_root_node++;
1076 for (
const IntegerLiteral i_lit : integer_reason) {
1078 num_literal_assigned_after_root_node++;
1081 DLOG_IF(
INFO, num_literal_assigned_after_root_node == 0)
1082 <<
"Propagating a literal with no reason at a positive level!\n"
1083 <<
"level:" << integer_search_levels_.size() <<
" "
1084 << ReasonDebugString(literal_reason, integer_reason) <<
"\n"
1093 absl::Span<const IntegerLiteral> integer_reason) {
1094 EnqueueLiteralInternal(
literal,
nullptr, literal_reason, integer_reason);
1097 void IntegerTrail::EnqueueLiteralInternal(
1099 absl::Span<const Literal> literal_reason,
1100 absl::Span<const IntegerLiteral> integer_reason) {
1102 DCHECK(lazy_reason !=
nullptr ||
1103 ReasonIsValid(literal_reason, integer_reason));
1104 if (integer_search_levels_.empty()) {
1111 if (!integer_search_levels_.empty() && integer_reason.empty() &&
1112 literal_reason.empty() && lazy_reason ==
nullptr) {
1113 literal_to_fix_.push_back(
literal);
1116 const int trail_index = trail_->
Index();
1117 if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1118 boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1120 boolean_trail_index_to_integer_one_[trail_index] = integer_trail_.size();
1122 int reason_index = literals_reason_starts_.size();
1123 if (lazy_reason !=
nullptr) {
1124 if (integer_trail_.size() >= lazy_reasons_.size()) {
1125 lazy_reasons_.resize(integer_trail_.size() + 1,
nullptr);
1127 lazy_reasons_[integer_trail_.size()] = lazy_reason;
1131 literals_reason_starts_.push_back(literals_reason_buffer_.size());
1132 literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1133 literal_reason.begin(),
1134 literal_reason.end());
1135 bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1136 bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1137 integer_reason.begin(), integer_reason.end());
1140 integer_trail_.push_back({IntegerValue(0),
1152 const int num_vars = vars_.
size();
1153 return (!integer_search_levels_.empty() &&
1154 integer_trail_.size() - integer_search_levels_.back() >
1156 parameters_.search_branching() != SatParameters::FIXED_SEARCH);
1163 ++num_decisions_to_break_loop_;
1164 std::vector<IntegerVariable> vars;
1165 for (
int i = integer_search_levels_.back(); i < integer_trail_.size(); ++i) {
1166 const IntegerVariable
var = integer_trail_[i].var;
1169 vars.push_back(
var);
1172 std::sort(vars.begin(), vars.end());
1173 IntegerVariable best_var = vars[0];
1176 for (
int i = 1; i < vars.size(); ++i) {
1177 if (vars[i] != vars[i - 1]) {
1181 if (count > best_count) {
1191 return first_level_without_full_propagation_ != -1;
1195 for (IntegerVariable
var(0);
var < vars_.
size();
var += 2) {
1202 bool IntegerTrail::EnqueueInternal(
1204 absl::Span<const Literal> literal_reason,
1205 absl::Span<const IntegerLiteral> integer_reason,
1206 int trail_index_with_same_reason) {
1207 DCHECK(lazy_reason !=
nullptr ||
1208 ReasonIsValid(literal_reason, integer_reason));
1210 const IntegerVariable
var(i_lit.
var);
1218 if (i_lit.
bound <= vars_[
var].current_bound)
return true;
1227 if ((*domains_)[
var].NumIntervals() > 1) {
1228 const auto& domain = (*domains_)[
var];
1230 const int size = domain.NumIntervals();
1231 while (index < size && i_lit.bound > domain[
index].end) {
1234 if (
index == size) {
1237 var_to_current_lb_interval_index_.
Set(
var,
index);
1248 Literal(is_ignored_literals_[
var]))) {
1251 auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1254 conflict->push_back(Literal(is_ignored_literals_[
var]));
1257 const int trail_index = FindLowestTrailIndexThatExplainBound(ub_reason);
1258 const int num_vars = vars_.
size();
1259 if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1261 MergeReasonIntoInternal(conflict);
1268 const Literal is_ignored = Literal(is_ignored_literals_[
var]);
1269 if (integer_search_levels_.empty()) {
1276 if (lazy_reason !=
nullptr) {
1277 lazy_reason(i_lit, integer_trail_.size(), &lazy_reason_literals_,
1278 &lazy_reason_trail_indices_);
1279 std::vector<IntegerLiteral> temp;
1280 for (
const int trail_index : lazy_reason_trail_indices_) {
1281 const TrailEntry& entry = integer_trail_[trail_index];
1282 temp.push_back(IntegerLiteral(entry.var, entry.bound));
1290 bounds_reason_buffer_.push_back(ub_reason);
1310 if (i_lit.
bound - lb < (ub - lb) / 2) {
1311 if (first_level_without_full_propagation_ == -1) {
1319 for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1320 bitset->Set(i_lit.
var);
1323 if (!integer_search_levels_.empty() && integer_reason.empty() &&
1324 literal_reason.empty() && lazy_reason ==
nullptr &&
1325 trail_index_with_same_reason >= integer_trail_.size()) {
1326 integer_literal_to_fix_.push_back(i_lit);
1342 const LiteralIndex literal_index =
1345 const Literal to_enqueue = Literal(literal_index);
1347 auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1349 conflict->push_back(to_enqueue);
1350 MergeReasonIntoInternal(conflict);
1360 EnqueueLiteralInternal(to_enqueue, lazy_reason, literal_reason,
1363 return EnqueueAssociatedIntegerLiteral(i_lit, to_enqueue);
1367 if (integer_search_levels_.empty()) {
1373 const int trail_index = trail_->
Index();
1374 if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1375 boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1377 boolean_trail_index_to_integer_one_[trail_index] =
1378 trail_index_with_same_reason;
1385 if (integer_search_levels_.empty()) {
1386 ++num_level_zero_enqueues_;
1387 vars_[i_lit.
var].current_bound = i_lit.
bound;
1388 integer_trail_[i_lit.
var.value()].bound = i_lit.
bound;
1399 int reason_index = literals_reason_starts_.size();
1400 if (lazy_reason !=
nullptr) {
1401 if (integer_trail_.size() >= lazy_reasons_.size()) {
1402 lazy_reasons_.resize(integer_trail_.size() + 1,
nullptr);
1404 lazy_reasons_[integer_trail_.size()] = lazy_reason;
1406 }
else if (trail_index_with_same_reason >= integer_trail_.size()) {
1408 literals_reason_starts_.push_back(literals_reason_buffer_.size());
1409 if (!literal_reason.empty()) {
1410 literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1411 literal_reason.begin(),
1412 literal_reason.end());
1414 bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1415 if (!integer_reason.empty()) {
1416 bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1417 integer_reason.begin(),
1418 integer_reason.end());
1421 reason_index = integer_trail_[trail_index_with_same_reason].reason_index;
1424 const int prev_trail_index = vars_[i_lit.
var].current_trail_index;
1425 integer_trail_.push_back({i_lit.
bound,
1430 vars_[i_lit.
var].current_bound = i_lit.
bound;
1431 vars_[i_lit.
var].current_trail_index = integer_trail_.size() - 1;
1435 bool IntegerTrail::EnqueueAssociatedIntegerLiteral(IntegerLiteral i_lit,
1436 Literal literal_reason) {
1437 DCHECK(ReasonIsValid({literal_reason.Negated()}, {}));
1441 if (i_lit.bound <= vars_[i_lit.var].current_bound)
return true;
1449 return Enqueue(i_lit, {literal_reason.Negated()}, {});
1453 for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1454 bitset->Set(i_lit.var);
1458 if (integer_search_levels_.empty()) {
1459 vars_[i_lit.var].current_bound = i_lit.bound;
1460 integer_trail_[i_lit.var.value()].bound = i_lit.bound;
1471 const int reason_index = literals_reason_starts_.size();
1472 CHECK_EQ(reason_index, bounds_reason_starts_.size());
1473 literals_reason_starts_.push_back(literals_reason_buffer_.size());
1474 bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1475 literals_reason_buffer_.push_back(literal_reason.Negated());
1477 const int prev_trail_index = vars_[i_lit.var].current_trail_index;
1478 integer_trail_.push_back({i_lit.bound,
1483 vars_[i_lit.var].current_bound = i_lit.bound;
1484 vars_[i_lit.var].current_trail_index = integer_trail_.size() - 1;
1488 void IntegerTrail::ComputeLazyReasonIfNeeded(
int trail_index)
const {
1489 const int reason_index = integer_trail_[trail_index].reason_index;
1490 if (reason_index == -1) {
1491 const TrailEntry& entry = integer_trail_[trail_index];
1492 const IntegerLiteral
literal(entry.var, entry.bound);
1493 lazy_reasons_[trail_index](
literal, trail_index, &lazy_reason_literals_,
1494 &lazy_reason_trail_indices_);
1498 absl::Span<const int> IntegerTrail::Dependencies(
int trail_index)
const {
1499 const int reason_index = integer_trail_[trail_index].reason_index;
1500 if (reason_index == -1) {
1501 return absl::Span<const int>(lazy_reason_trail_indices_);
1504 const int start = bounds_reason_starts_[reason_index];
1505 const int end = reason_index + 1 < bounds_reason_starts_.size()
1506 ? bounds_reason_starts_[reason_index + 1]
1507 : bounds_reason_buffer_.size();
1508 if (start == end)
return {};
1515 if (end > trail_index_reason_buffer_.size()) {
1516 trail_index_reason_buffer_.resize(end, -1);
1518 if (trail_index_reason_buffer_[start] == -1) {
1519 int new_end = start;
1520 const int num_vars = vars_.
size();
1521 for (
int i = start; i < end; ++i) {
1523 FindLowestTrailIndexThatExplainBound(bounds_reason_buffer_[i]);
1524 if (dep >= num_vars) {
1525 trail_index_reason_buffer_[new_end++] = dep;
1528 return absl::Span<const int>(&trail_index_reason_buffer_[start],
1534 return absl::Span<const int>(&trail_index_reason_buffer_[start],
1539 void IntegerTrail::AppendLiteralsReason(
int trail_index,
1540 std::vector<Literal>* output)
const {
1542 const int reason_index = integer_trail_[trail_index].reason_index;
1543 if (reason_index == -1) {
1544 for (
const Literal l : lazy_reason_literals_) {
1545 if (!added_variables_[l.Variable()]) {
1546 added_variables_.
Set(l.Variable());
1547 output->push_back(l);
1553 const int start = literals_reason_starts_[reason_index];
1554 const int end = reason_index + 1 < literals_reason_starts_.size()
1555 ? literals_reason_starts_[reason_index + 1]
1556 : literals_reason_buffer_.size();
1557 for (
int i = start; i < end; ++i) {
1558 const Literal l = literals_reason_buffer_[i];
1559 if (!added_variables_[l.Variable()]) {
1560 added_variables_.
Set(l.Variable());
1561 output->push_back(l);
1567 std::vector<Literal> reason;
1575 std::vector<Literal>* output)
const {
1576 DCHECK(tmp_queue_.empty());
1577 const int num_vars = vars_.
size();
1579 const int trail_index = FindLowestTrailIndexThatExplainBound(
literal);
1583 if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1585 return MergeReasonIntoInternal(output);
1590 void IntegerTrail::MergeReasonIntoInternal(std::vector<Literal>* output)
const {
1593 DCHECK(std::all_of(tmp_var_to_trail_index_in_queue_.
begin(),
1594 tmp_var_to_trail_index_in_queue_.
end(),
1595 [](
int v) { return v == 0; }));
1598 for (
const Literal l : *output) {
1599 added_variables_.
Set(l.Variable());
1604 for (
const int trail_index : tmp_queue_) {
1606 DCHECK_LT(trail_index, integer_trail_.size());
1607 const TrailEntry& entry = integer_trail_[trail_index];
1608 tmp_var_to_trail_index_in_queue_[entry.var] =
1609 std::max(tmp_var_to_trail_index_in_queue_[entry.var], trail_index);
1614 std::make_heap(tmp_queue_.begin(), tmp_queue_.end());
1619 tmp_to_clear_.clear();
1620 while (!tmp_queue_.empty()) {
1621 const int trail_index = tmp_queue_.front();
1622 const TrailEntry& entry = integer_trail_[trail_index];
1623 std::pop_heap(tmp_queue_.begin(), tmp_queue_.end());
1624 tmp_queue_.pop_back();
1629 if (tmp_var_to_trail_index_in_queue_[entry.var] != trail_index) {
1636 var_trail_index_cache_threshold_ = trail_index;
1641 const LiteralIndex associated_lit =
1643 IntegerVariable(entry.var), entry.bound));
1646 const int reason_index = integer_trail_[trail_index].reason_index;
1649 const int start = literals_reason_starts_[reason_index];
1650 const int end = reason_index + 1 < literals_reason_starts_.size()
1651 ? literals_reason_starts_[reason_index + 1]
1652 : literals_reason_buffer_.size();
1654 CHECK_EQ(literals_reason_buffer_[start],
1655 Literal(associated_lit).Negated());
1658 const int start = bounds_reason_starts_[reason_index];
1659 const int end = reason_index + 1 < bounds_reason_starts_.size()
1660 ? bounds_reason_starts_[reason_index + 1]
1661 : bounds_reason_buffer_.size();
1675 tmp_var_to_trail_index_in_queue_[entry.var] = 0;
1676 has_dependency_ =
false;
1678 ComputeLazyReasonIfNeeded(trail_index);
1679 AppendLiteralsReason(trail_index, output);
1680 for (
const int next_trail_index : Dependencies(trail_index)) {
1681 if (next_trail_index < 0)
break;
1682 DCHECK_LT(next_trail_index, trail_index);
1683 const TrailEntry& next_entry = integer_trail_[next_trail_index];
1689 const int index_in_queue =
1690 tmp_var_to_trail_index_in_queue_[next_entry.var];
1692 has_dependency_ =
true;
1693 if (next_trail_index > index_in_queue) {
1694 tmp_var_to_trail_index_in_queue_[next_entry.var] = next_trail_index;
1696 std::push_heap(tmp_queue_.begin(), tmp_queue_.end());
1701 if (!has_dependency_) {
1702 tmp_to_clear_.push_back(entry.var);
1703 tmp_var_to_trail_index_in_queue_[entry.var] =
1709 for (
const IntegerVariable
var : tmp_to_clear_) {
1710 tmp_var_to_trail_index_in_queue_[
var] = 0;
1715 int trail_index)
const {
1716 const int index = boolean_trail_index_to_integer_one_[trail_index];
1720 ComputeLazyReasonIfNeeded(
index);
1721 AppendLiteralsReason(
index, reason);
1722 DCHECK(tmp_queue_.empty());
1723 for (
const int prev_trail_index : Dependencies(
index)) {
1724 if (prev_trail_index < 0)
break;
1726 tmp_queue_.push_back(prev_trail_index);
1728 MergeReasonIntoInternal(reason);
1738 const int end = vars_.
size();
1739 for (
int i = integer_trail_.size(); --i >= end;) {
1740 const TrailEntry& entry = integer_trail_[i];
1742 if (tmp_marked_[entry.var])
continue;
1744 tmp_marked_.
Set(entry.var);
1761 &id_to_greatest_common_level_since_last_call_);
1763 queue_by_priority_.resize(2);
1766 void GenericLiteralWatcher::UpdateCallingNeeds(
Trail* trail) {
1768 while (propagation_trail_index_ < trail->
Index()) {
1770 if (
literal.Index() >= literal_to_watcher_.
size())
continue;
1771 for (
const auto entry : literal_to_watcher_[
literal.Index()]) {
1772 if (!in_queue_[entry.id]) {
1773 in_queue_[entry.id] =
true;
1774 queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1776 if (entry.watch_index >= 0) {
1777 id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1784 if (
var.value() >= var_to_watcher_.
size())
continue;
1785 for (
const auto entry : var_to_watcher_[
var]) {
1786 if (!in_queue_[entry.id]) {
1787 in_queue_[entry.id] =
true;
1788 queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1790 if (entry.watch_index >= 0) {
1791 id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1797 const std::vector<IntegerVariable>& modified_vars =
1799 for (
const auto&
callback : level_zero_modified_variable_callback_) {
1812 for (
const int id : propagator_ids_to_call_at_level_zero_) {
1813 if (in_queue_[
id])
continue;
1814 in_queue_[id] =
true;
1815 queue_by_priority_[id_to_priority_[id]].push_back(
id);
1819 UpdateCallingNeeds(trail);
1824 for (
int priority = 0; priority < queue_by_priority_.size(); ++priority) {
1831 if (test_limit > 100) {
1836 std::deque<int>& queue = queue_by_priority_[priority];
1837 while (!queue.empty()) {
1838 const int id = queue.front();
1846 id_to_greatest_common_level_since_last_call_[IdType(
id)];
1847 const int high = id_to_level_at_last_call_[id];
1848 if (low < high || level > low) {
1849 id_to_level_at_last_call_[id] = level;
1850 id_to_greatest_common_level_since_last_call_.
MutableRef(IdType(
id)) =
1853 if (low < high) rev->SetLevel(low);
1854 if (level > low) rev->SetLevel(level);
1856 for (
int* rev_int : id_to_reversible_ints_[
id]) {
1857 rev_int_repository_->
SaveState(rev_int);
1863 const int64_t old_integer_timestamp = integer_trail_->
num_enqueues();
1864 const int64_t old_boolean_timestamp = trail->
Index();
1867 std::vector<int>& watch_indices_ref = id_to_watch_indices_[id];
1869 watch_indices_ref.empty()
1870 ? watchers_[id]->Propagate()
1871 : watchers_[id]->IncrementalPropagate(watch_indices_ref);
1873 watch_indices_ref.clear();
1874 in_queue_[id] =
false;
1880 if (id_to_idempotence_[
id]) {
1884 UpdateCallingNeeds(trail);
1885 watch_indices_ref.clear();
1886 in_queue_[id] =
false;
1891 watch_indices_ref.clear();
1892 in_queue_[id] =
false;
1893 UpdateCallingNeeds(trail);
1899 if (trail->
Index() > old_boolean_timestamp) {
1911 if (integer_trail_->
num_enqueues() > old_integer_timestamp) {
1929 for (std::deque<int>& queue : queue_by_priority_) {
1930 for (
const int id : queue) {
1931 id_to_watch_indices_[id].clear();
1941 in_queue_.assign(watchers_.size(),
false);
1946 const int id = watchers_.size();
1947 watchers_.push_back(propagator);
1948 id_to_level_at_last_call_.push_back(0);
1949 id_to_greatest_common_level_since_last_call_.
GrowByOne();
1950 id_to_reversible_classes_.push_back(std::vector<ReversibleInterface*>());
1951 id_to_reversible_ints_.push_back(std::vector<int*>());
1952 id_to_watch_indices_.push_back(std::vector<int>());
1953 id_to_priority_.push_back(1);
1954 id_to_idempotence_.push_back(
true);
1963 in_queue_.push_back(
true);
1964 queue_by_priority_[1].push_back(
id);
1969 id_to_priority_[id] = priority;
1970 if (priority >= queue_by_priority_.size()) {
1971 queue_by_priority_.resize(priority + 1);
1977 id_to_idempotence_[id] =
false;
1981 propagator_ids_to_call_at_level_zero_.push_back(
id);
1986 id_to_reversible_classes_[id].push_back(rev);
1990 id_to_reversible_ints_[id].push_back(rev);
1994 std::function<void(
Model*)>
2002 std::vector<Literal> clause_to_exclude_solution;
2003 clause_to_exclude_solution.reserve(current_level);
2004 for (
int i = 0; i < current_level; ++i) {
2005 bool include_decision =
true;
2011 encoder->GetIntegerLiterals(decision);
2013 if (integer_trail->IsCurrentlyIgnored(
bound.var)) {
2019 clause_to_exclude_solution.push_back(
2020 integer_trail->IsIgnoredLiteral(
bound.var).Negated());
2021 include_decision =
false;
2025 if (include_decision) {
2026 clause_to_exclude_solution.push_back(decision.
Negated());
#define DLOG_IF(severity, condition)
#define DCHECK_LE(val1, val2)
#define CHECK_LT(val1, val2)
#define CHECK_EQ(val1, val2)
#define CHECK_GE(val1, val2)
#define DCHECK_GE(val1, val2)
#define CHECK_NE(val1, val2)
#define DCHECK_GT(val1, val2)
#define DCHECK_LT(val1, val2)
#define DCHECK(condition)
#define CHECK_LE(val1, val2)
#define DCHECK_EQ(val1, val2)
#define VLOG(verboselevel)
void resize(size_type new_size)
void reserve(size_type n)
void push_back(const value_type &x)
We call domain any subset of Int64 = [kint64min, kint64max].
Domain Negation() const
Returns {x ∈ Int64, ∃ e ∈ D, x = -e}.
bool Contains(int64_t value) const
Returns true iff value is in Domain.
absl::InlinedVector< ClosedInterval, 1 >::const_iterator end() const
int NumIntervals() const
Basic read-only std::vector<> wrapping to view a Domain as a sorted list of non-adjacent intervals.
Domain IntersectionWith(const Domain &domain) const
Returns the intersection of D and domain.
int64_t Min() const
Returns the min value of the domain.
bool IsEmpty() const
Returns true if this is the empty set.
int64_t Max() const
Returns the max value of the domain.
void Set(key_type key, mapped_type value)
void SetLevel(int level) final
const mapped_type & FindOrDie(key_type key) const
void SaveState(T *object)
T & MutableRef(IndexType index)
const std::vector< IntegerType > & PositionsSetAtLeastOnce() const
void Set(IntegerType index)
void ClearAndResize(IntegerType size)
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
bool Propagate(Trail *trail) final
void AlwaysCallAtLevelZero(int id)
void RegisterReversibleInt(int id, int *rev)
void RegisterReversibleClass(int id, ReversibleInterface *rev)
GenericLiteralWatcher(Model *model)
void SetPropagatorPriority(int id, int priority)
int Register(PropagatorInterface *propagator)
void NotifyThatPropagatorMayNotReachFixedPointInOnePass(int id)
void Untrail(const Trail &trail, int literal_trail_index) final
Literal GetOrCreateLiteralAssociatedToEquality(IntegerVariable var, IntegerValue value)
LiteralIndex SearchForLiteralAtOrBefore(IntegerLiteral i, IntegerValue *bound) const
LiteralIndex GetAssociatedLiteral(IntegerLiteral i_lit) const
void FullyEncodeVariable(IntegerVariable var)
Literal GetFalseLiteral()
std::pair< IntegerLiteral, IntegerLiteral > Canonicalize(IntegerLiteral i_lit) const
void ClearNewlyFixedIntegerLiterals()
const std::vector< IntegerLiteral > NewlyFixedIntegerLiterals() const
void AssociateToIntegerEqualValue(Literal literal, IntegerVariable var, IntegerValue value)
const InlinedIntegerLiteralVector & GetIntegerLiterals(Literal lit) const
bool LiteralIsAssociated(IntegerLiteral i_lit) const
std::vector< ValueLiteralPair > FullDomainEncoding(IntegerVariable var) const
std::vector< ValueLiteralPair > PartialDomainEncoding(IntegerVariable var) const
void AddAllImplicationsBetweenAssociatedLiterals()
bool VariableIsFullyEncoded(IntegerVariable var) const
LiteralIndex GetAssociatedEqualityLiteral(IntegerVariable var, IntegerValue value) const
void AssociateToIntegerLiteral(Literal literal, IntegerLiteral i_lit)
Literal GetOrCreateAssociatedLiteral(IntegerLiteral i_lit)
IntegerVariable FirstUnassignedVariable() const
ABSL_MUST_USE_RESULT bool Enqueue(IntegerLiteral i_lit, absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
IntegerVariable GetOrCreateConstantIntegerVariable(IntegerValue value)
int64_t num_enqueues() const
void RegisterWatcher(SparseBitset< IntegerVariable > *p)
bool Propagate(Trail *trail) final
void ReserveSpaceForNumVariables(int num_vars)
int FindTrailIndexOfVarBefore(IntegerVariable var, int threshold) const
bool IsCurrentlyIgnored(IntegerVariable i) const
std::vector< Literal > ReasonFor(IntegerLiteral literal) const
std::function< void(IntegerLiteral literal_to_explain, int trail_index_of_literal, std::vector< Literal > *literals, std::vector< int > *dependencies)> LazyReasonFunction
bool IsFixed(IntegerVariable i) const
LiteralIndex OptionalLiteralIndex(IntegerVariable i) const
absl::Span< const Literal > Reason(const Trail &trail, int trail_index) const final
bool CurrentBranchHadAnIncompletePropagation()
bool InPropagationLoop() const
bool ReportConflict(absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
void EnqueueLiteral(Literal literal, absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
IntegerVariable NextVariableToBranchOnInPropagationLoop() const
IntegerValue UpperBound(IntegerVariable i) const
void AppendRelaxedLinearReason(IntegerValue slack, absl::Span< const IntegerValue > coeffs, absl::Span< const IntegerVariable > vars, std::vector< IntegerLiteral > *reason) const
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
void RelaxLinearReason(IntegerValue slack, absl::Span< const IntegerValue > coeffs, std::vector< IntegerLiteral > *reason) const
void AppendNewBounds(std::vector< IntegerLiteral > *output) const
IntegerValue LowerBound(IntegerVariable i) const
int NumConstantVariables() const
void MergeReasonInto(absl::Span< const IntegerLiteral > literals, std::vector< Literal > *output) const
Literal IsIgnoredLiteral(IntegerVariable i) const
bool IsOptional(IntegerVariable i) const
ABSL_MUST_USE_RESULT bool ConditionalEnqueue(Literal lit, IntegerLiteral i_lit, std::vector< Literal > *literal_reason, std::vector< IntegerLiteral > *integer_reason)
bool IntegerLiteralIsFalse(IntegerLiteral l) const
void RemoveLevelZeroBounds(std::vector< IntegerLiteral > *reason) const
IntegerVariable AddIntegerVariable()
void RegisterReversibleClass(ReversibleInterface *rev)
const Domain & InitialVariableDomain(IntegerVariable var) const
void Untrail(const Trail &trail, int literal_trail_index) final
IntegerVariable NumIntegerVariables() const
bool UpdateInitialDomain(IntegerVariable var, Domain domain)
LiteralIndex Index() const
Class that owns everything related to a particular optimization model.
int propagation_trail_index_
bool AddClauseDuringSearch(absl::Span< const Literal > literals)
BooleanVariable NewBooleanVariable()
const VariablesAssignment & Assignment() const
bool AddBinaryClause(Literal a, Literal b)
void Backtrack(int target_level)
int CurrentDecisionLevel() const
const std::vector< Decision > & Decisions() const
bool AddUnitClause(Literal true_literal)
void Enqueue(Literal true_literal, int propagator_id)
const AssignmentInfo & Info(BooleanVariable var) const
std::vector< Literal > * GetEmptyVectorToStoreReason(int trail_index) const
std::vector< Literal > * MutableConflict()
const VariablesAssignment & Assignment() const
int CurrentDecisionLevel() const
void EnqueueWithUnitReason(Literal true_literal)
bool LiteralIsAssigned(Literal literal) const
bool LiteralIsTrue(Literal literal) const
bool LiteralIsFalse(Literal literal) const
void InsertOrDie(Collection *const collection, const typename Collection::value_type &value)
absl::InlinedVector< IntegerLiteral, 2 > InlinedIntegerLiteralVector
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
std::function< void(Model *)> ClauseConstraint(absl::Span< const Literal > literals)
const LiteralIndex kNoLiteralIndex(-1)
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
const IntegerVariable kNoIntegerVariable(-1)
IntegerVariable PositiveVariable(IntegerVariable i)
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
std::function< void(Model *)> ExcludeCurrentSolutionWithoutIgnoredVariableAndBacktrack()
PositiveOnlyIndex GetPositiveOnlyIndex(IntegerVariable var)
bool VariableIsPositive(IntegerVariable i)
Collection of objects used to extend the Constraint Solver library.
int64_t CapProd(int64_t x, int64_t y)
Represents a closed interval [start, end].
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
std::string DebugString() const