25#include "absl/container/btree_map.h"
26#include "absl/container/flat_hash_map.h"
27#include "absl/meta/type_traits.h"
28#include "absl/strings/str_cat.h"
29#include "absl/types/span.h"
35#include "ortools/sat/sat_parameters.pb.h"
48 const std::vector<IntegerVariable>& vars) {
49 std::vector<IntegerVariable> result(vars.size());
50 for (
int i = 0; i < vars.size(); ++i) {
58 ", value = ",
value.value(),
")");
72 <<
"Domain too large for full encoding.";
83 for (
const int64_t v : (*domains_)[
var].Values()) {
84 tmp_values_.push_back(IntegerValue(v));
86 for (
const IntegerValue v : tmp_values_) {
98 if (
index >= is_fully_encoded_.
size())
return false;
101 if (is_fully_encoded_[
index])
return true;
108 const int64_t initial_domain_size = (*domains_)[
var].Size();
109 if (equality_by_var_[
index].size() < initial_domain_size)
return false;
118 const auto& ref = equality_by_var_[
index];
120 for (
const int64_t v : (*domains_)[
var].Values()) {
121 if (i < ref.size() && v == ref[i].value) {
125 if (i == ref.size()) {
126 is_fully_encoded_[
index] =
true;
128 return is_fully_encoded_[
index];
132 IntegerVariable
var)
const {
138 IntegerVariable
var)
const {
141 if (
index >= equality_by_var_.size())
return {};
144 std::vector<ValueLiteralPair>& ref = equality_by_var_[
index];
145 for (
int i = 0; i < ref.size(); ++i) {
154 ref[new_size++] = pair;
156 ref.resize(new_size);
159 std::vector<ValueLiteralPair> result = ref;
161 std::reverse(result.begin(), result.end());
168 IntegerVariable
var)
const {
171 if (
index >= equality_by_var_.size())
return {};
173 return equality_by_var_[
index];
179void IntegerEncoder::AddImplications(
180 const absl::btree_map<IntegerValue, Literal>& map,
181 absl::btree_map<IntegerValue, Literal>::const_iterator it,
183 if (!add_implications_)
return;
189 if (after_it != map.end()) {
191 {after_it->second.Negated(), associated_lit});
195 if (it != map.begin()) {
199 {associated_lit.
Negated(), before_it->second});
205 add_implications_ =
true;
206 for (
const absl::btree_map<IntegerValue, Literal>& encoding :
209 for (
const auto value_literal : encoding) {
210 const Literal lit = value_literal.second;
215 previous = lit.
Index();
222 const IntegerVariable
var(i_lit.
var);
223 IntegerValue after(i_lit.
bound);
224 IntegerValue before(i_lit.
bound - 1);
229 if (before > previous && before <
interval.start) before = previous;
239 if (i_lit.
bound <= (*domains_)[i_lit.
var].Min()) {
242 if (i_lit.
bound > (*domains_)[i_lit.
var].Max()) {
254 ++num_created_variables_;
261 VLOG(1) <<
"Created a fixed literal for no reason!";
267std::pair<PositiveOnlyIndex, IntegerValue> PositiveVarKey(IntegerVariable
var,
268 IntegerValue
value) {
275 IntegerVariable
var, IntegerValue
value)
const {
277 equality_to_associated_literal_.find(PositiveVarKey(
var,
value));
278 if (it != equality_to_associated_literal_.end()) {
279 return it->second.Index();
285 IntegerVariable
var, IntegerValue
value) {
288 equality_to_associated_literal_.find(PositiveVarKey(
var,
value));
289 if (it != equality_to_associated_literal_.end()) {
303 ++num_created_variables_;
313 VLOG(1) <<
"Created a fixed literal for no reason!";
320 const auto& domain = (*domains_)[i_lit.
var];
321 const IntegerValue
min(domain.Min());
322 const IntegerValue
max(domain.Max());
329 HalfAssociateGivenLiteral(pair.first,
literal);
330 HalfAssociateGivenLiteral(pair.second,
literal.Negated());
335 if (pair.first.bound ==
max) {
338 if (-pair.second.bound ==
min) {
346 IntegerValue
value) {
351 if (
value == 1 && domain.
Min() >= 0 && domain.
Max() <= 1) {
359 if (
value == -1 && domain.
Min() >= -1 && domain.
Max() <= 0) {
370 const auto insert_result = equality_to_associated_literal_.insert(
372 if (!insert_result.second) {
393 if (
index >= equality_by_var_.size()) {
394 equality_by_var_.resize(
index.value() + 1);
397 equality_by_var_[
index].push_back(
432 const int new_size = 1 +
literal.Index().value();
433 if (new_size > full_reverse_encoding_.
size()) {
434 full_reverse_encoding_.
resize(new_size);
444void IntegerEncoder::HalfAssociateGivenLiteral(
IntegerLiteral i_lit,
447 const int new_size = 1 +
literal.Index().value();
448 if (new_size > reverse_encoding_.
size()) {
449 reverse_encoding_.
resize(new_size);
451 if (new_size > full_reverse_encoding_.
size()) {
452 full_reverse_encoding_.
resize(new_size);
456 if (i_lit.
var >= encoding_by_var_.size()) {
457 encoding_by_var_.resize(i_lit.
var.value() + 1);
459 auto& var_encoding = encoding_by_var_[i_lit.
var];
460 auto insert_result = var_encoding.insert({i_lit.
bound,
literal});
461 if (insert_result.second) {
462 AddImplications(var_encoding, insert_result.first,
literal);
465 newly_fixed_integer_literals_.push_back(i_lit);
473 const Literal associated(insert_result.first->second);
483 if (i.
var >= encoding_by_var_.size())
return false;
484 const absl::btree_map<IntegerValue, Literal>& encoding =
485 encoding_by_var_[i.
var];
486 return encoding.find(i.
bound) != encoding.end();
491 const absl::btree_map<IntegerValue, Literal>& encoding =
492 encoding_by_var_[i.
var];
493 const auto result = encoding.find(i.
bound);
495 return result->second.Index();
503 const absl::btree_map<IntegerValue, Literal>& encoding =
504 encoding_by_var_[i.
var];
505 auto after_it = encoding.upper_bound(i.
bound);
508 *
bound = after_it->first;
509 return after_it->second.Index();
513 if (parameters_.log_search_progress() && num_decisions_to_break_loop_ > 0) {
514 VLOG(1) <<
"Num decisions to break propagation loop: "
515 << num_decisions_to_break_loop_;
526 if (level > integer_search_levels_.size()) {
527 integer_search_levels_.push_back(integer_trail_.size());
528 reason_decision_levels_.push_back(literals_reason_starts_.size());
534 var_to_current_lb_interval_index_.
SetLevel(level);
547 if (!
Enqueue(i_lit, {}, {}))
return false;
553 if (!
Enqueue(i_lit, {}, {}))
return false;
555 integer_literal_to_fix_.clear();
557 for (
const Literal lit : literal_to_fix_) {
562 literal_to_fix_.clear();
567 while (propagation_trail_index_ < trail->
Index()) {
573 if (!EnqueueAssociatedIntegerLiteral(i_lit,
literal)) {
584 conditional_lbs_.clear();
586 var_to_current_lb_interval_index_.
SetLevel(level);
590 if (level < first_level_without_full_propagation_) {
591 first_level_without_full_propagation_ = -1;
596 if (level >= integer_search_levels_.size())
return;
597 const int target = integer_search_levels_[level];
598 integer_search_levels_.resize(level);
600 CHECK_LE(target, integer_trail_.size());
602 for (
int index = integer_trail_.size() - 1;
index >= target; --
index) {
603 const TrailEntry& entry = integer_trail_[
index];
604 if (entry.var < 0)
continue;
605 vars_[entry.var].current_trail_index = entry.prev_trail_index;
606 vars_[entry.var].current_bound =
607 integer_trail_[entry.prev_trail_index].bound;
609 integer_trail_.resize(target);
612 const int old_size = reason_decision_levels_[level];
613 reason_decision_levels_.resize(level);
614 if (old_size < literals_reason_starts_.size()) {
615 literals_reason_buffer_.resize(literals_reason_starts_[old_size]);
617 const int bound_start = bounds_reason_starts_[old_size];
618 bounds_reason_buffer_.resize(bound_start);
619 if (bound_start < trail_index_reason_buffer_.size()) {
620 trail_index_reason_buffer_.resize(bound_start);
623 literals_reason_starts_.resize(old_size);
624 bounds_reason_starts_.resize(old_size);
634 const int size = 2 * num_vars;
636 is_ignored_literals_.
reserve(size);
637 integer_trail_.reserve(size);
639 var_trail_index_cache_.
reserve(size);
640 tmp_var_to_trail_index_in_queue_.
reserve(size);
650 DCHECK(integer_search_levels_.empty());
653 const IntegerVariable i(vars_.
size());
668 var_trail_index_cache_.
resize(vars_.
size(), integer_trail_.size());
669 tmp_var_to_trail_index_in_queue_.
resize(vars_.
size(), 0);
680 IntegerValue(domain.
Max()));
686 return (*domains_)[
var];
694 if (old_domain == domain)
return true;
696 if (domain.
IsEmpty())
return false;
697 (*domains_)[
var] = domain;
700 var_to_current_lb_interval_index_.
Set(
var, 0);
718 if (i == domain.
NumIntervals() || pair.value < domain[i].start) {
728 <<
"Domain intersection fixed " << num_fixed
729 <<
" equality literal corresponding to values outside the new domain.";
736 IntegerValue
value) {
740 insert.first->second = new_var;
747 return insert.first->second;
753 return (constant_map_.size() + 1) / 2;
757 int threshold)
const {
761 const int index_in_queue = tmp_var_to_trail_index_in_queue_[
var];
762 if (threshold <= index_in_queue) {
764 has_dependency_ =
true;
769 int trail_index = vars_[
var].current_trail_index;
772 if (trail_index > threshold) {
773 const int cached_index = var_trail_index_cache_[
var];
774 if (cached_index >= threshold && cached_index < trail_index &&
775 integer_trail_[cached_index].
var ==
var) {
776 trail_index = cached_index;
780 while (trail_index >= threshold) {
781 trail_index = integer_trail_[trail_index].prev_trail_index;
782 if (trail_index >= var_trail_index_cache_threshold_) {
783 var_trail_index_cache_[
var] = trail_index;
787 const int num_vars = vars_.
size();
788 return trail_index < num_vars ? -1 : trail_index;
791int IntegerTrail::FindLowestTrailIndexThatExplainBound(
795 int trail_index = vars_[i_lit.
var].current_trail_index;
803 const int cached_index = var_trail_index_cache_[i_lit.
var];
804 if (cached_index < trail_index) {
805 const TrailEntry& entry = integer_trail_[cached_index];
806 if (entry.var == i_lit.
var && entry.bound >= i_lit.
bound) {
807 trail_index = cached_index;
812 int prev_trail_index = trail_index;
814 if (trail_index >= var_trail_index_cache_threshold_) {
815 var_trail_index_cache_[i_lit.
var] = trail_index;
817 const TrailEntry& entry = integer_trail_[trail_index];
818 if (entry.bound == i_lit.
bound)
return trail_index;
819 if (entry.bound < i_lit.
bound)
return prev_trail_index;
820 prev_trail_index = trail_index;
821 trail_index = entry.prev_trail_index;
827 IntegerValue slack, absl::Span<const IntegerValue> coeffs,
828 std::vector<IntegerLiteral>* reason)
const {
830 if (slack == 0)
return;
831 const int size = reason->size();
832 tmp_indices_.resize(size);
833 for (
int i = 0; i < size; ++i) {
836 tmp_indices_[i] = vars_[(*reason)[i].var].current_trail_index;
842 for (
const int i : tmp_indices_) {
844 integer_trail_[i].
bound));
849 IntegerValue slack, absl::Span<const IntegerValue> coeffs,
850 absl::Span<const IntegerVariable> vars,
851 std::vector<IntegerLiteral>* reason)
const {
852 tmp_indices_.clear();
853 for (
const IntegerVariable
var : vars) {
854 tmp_indices_.push_back(vars_[
var].current_trail_index);
857 for (
const int i : tmp_indices_) {
859 integer_trail_[i].
bound));
864 absl::Span<const IntegerValue> coeffs,
865 std::vector<int>* trail_indices)
const {
867 DCHECK(relax_heap_.empty());
874 const int size = coeffs.size();
875 const int num_vars = vars_.
size();
876 for (
int i = 0; i < size; ++i) {
877 const int index = (*trail_indices)[i];
880 if (
index < num_vars)
continue;
883 const IntegerValue
coeff = coeffs[i];
885 (*trail_indices)[new_size++] =
index;
892 const TrailEntry& entry = integer_trail_[
index];
894 index <= tmp_var_to_trail_index_in_queue_[entry.var]) {
895 (*trail_indices)[new_size++] =
index;
900 const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
902 CapProd(
coeff.value(), (entry.bound - previous_entry.bound).value());
904 (*trail_indices)[new_size++] =
index;
910 trail_indices->resize(new_size);
911 std::make_heap(relax_heap_.begin(), relax_heap_.end());
913 while (slack > 0 && !relax_heap_.empty()) {
914 const RelaxHeapEntry heap_entry = relax_heap_.front();
915 std::pop_heap(relax_heap_.begin(), relax_heap_.end());
916 relax_heap_.pop_back();
919 if (heap_entry.diff > slack) {
920 trail_indices->push_back(heap_entry.index);
925 slack -= heap_entry.diff;
926 const int index = integer_trail_[heap_entry.index].prev_trail_index;
929 if (
index < num_vars)
continue;
930 if (heap_entry.coeff > slack) {
931 trail_indices->push_back(
index);
934 const TrailEntry& entry = integer_trail_[
index];
936 index <= tmp_var_to_trail_index_in_queue_[entry.var]) {
937 trail_indices->push_back(
index);
941 const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
942 const int64_t diff =
CapProd(heap_entry.coeff.value(),
943 (entry.bound - previous_entry.bound).value());
945 trail_indices->push_back(
index);
948 relax_heap_.push_back({
index, heap_entry.coeff, diff});
949 std::push_heap(relax_heap_.begin(), relax_heap_.end());
954 for (
const RelaxHeapEntry& entry : relax_heap_) {
955 trail_indices->push_back(entry.index);
961 std::vector<IntegerLiteral>* reason)
const {
965 (*reason)[new_size++] =
literal;
967 reason->resize(new_size);
970std::vector<Literal>* IntegerTrail::InitializeConflict(
971 IntegerLiteral integer_literal,
const LazyReasonFunction& lazy_reason,
972 absl::Span<const Literal> literals_reason,
973 absl::Span<const IntegerLiteral> bounds_reason) {
974 DCHECK(tmp_queue_.empty());
976 if (lazy_reason ==
nullptr) {
977 conflict->assign(literals_reason.begin(), literals_reason.end());
978 const int num_vars = vars_.
size();
980 const int trail_index = FindLowestTrailIndexThatExplainBound(
literal);
981 if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
986 lazy_reason(integer_literal, integer_trail_.size(), conflict, &tmp_queue_);
993std::string ReasonDebugString(absl::Span<const Literal> literal_reason,
994 absl::Span<const IntegerLiteral> integer_reason) {
995 std::string result =
"literals:{";
996 for (
const Literal l : literal_reason) {
997 if (result.back() !=
'{') result +=
",";
998 result += l.DebugString();
1000 result +=
"} bounds:{";
1001 for (
const IntegerLiteral l : integer_reason) {
1002 if (result.back() !=
'{') result +=
",";
1003 result += l.DebugString();
1011std::string IntegerTrail::DebugString() {
1012 std::string result =
"trail:{";
1013 const int num_vars = vars_.
size();
1015 std::min(num_vars + 30,
static_cast<int>(integer_trail_.size()));
1016 for (
int i = num_vars; i < limit; ++i) {
1017 if (result.back() !=
'{') result +=
",";
1020 integer_trail_[i].
bound)
1023 if (limit < integer_trail_.size()) {
1031 IntegerLiteral i_lit, absl::Span<const IntegerLiteral> integer_reason) {
1034 std::vector<IntegerLiteral> cleaned_reason;
1036 DCHECK(!lit.IsFalseLiteral());
1037 if (lit.IsTrueLiteral())
continue;
1038 cleaned_reason.push_back(lit);
1044 return Enqueue(i_lit, {}, cleaned_reason);
1049 absl::Span<const Literal> literal_reason,
1050 absl::Span<const IntegerLiteral> integer_reason) {
1051 return EnqueueInternal(i_lit,
nullptr, literal_reason, integer_reason,
1052 integer_trail_.size());
1057 std::vector<IntegerLiteral>* integer_reason) {
1065 return Enqueue(i_lit, *literal_reason, *integer_reason);
1069 literal_reason->push_back(lit.
Negated());
1070 return Enqueue(i_lit, *literal_reason, *integer_reason);
1074 integer_reason->push_back(
1090 const auto [it, inserted] =
1091 conditional_lbs_.insert({{lit.
Index(), i_lit.
var}, i_lit.
bound});
1100 absl::Span<const Literal> literal_reason,
1101 absl::Span<const IntegerLiteral> integer_reason,
1102 int trail_index_with_same_reason) {
1103 return EnqueueInternal(i_lit,
nullptr, literal_reason, integer_reason,
1104 trail_index_with_same_reason);
1109 return EnqueueInternal(i_lit, lazy_reason, {}, {}, integer_trail_.size());
1112bool IntegerTrail::ReasonIsValid(
1113 absl::Span<const Literal> literal_reason,
1114 absl::Span<const IntegerLiteral> integer_reason) {
1116 for (
const Literal lit : literal_reason) {
1119 for (
const IntegerLiteral i_lit : integer_reason) {
1120 if (i_lit.
bound > vars_[i_lit.
var].current_bound) {
1123 LOG(
INFO) <<
"Reason " << i_lit <<
" is not true!"
1124 <<
" optional variable:" << i_lit.
var
1127 <<
" current_lb:" << vars_[i_lit.
var].current_bound;
1129 LOG(
INFO) <<
"Reason " << i_lit <<
" is not true!"
1130 <<
" non-optional variable:" << i_lit.
var
1131 <<
" current_lb:" << vars_[i_lit.
var].current_bound;
1139 if (!integer_search_levels_.empty()) {
1140 int num_literal_assigned_after_root_node = 0;
1141 for (
const Literal lit : literal_reason) {
1142 if (trail_->
Info(lit.Variable()).
level > 0) {
1143 num_literal_assigned_after_root_node++;
1146 for (
const IntegerLiteral i_lit : integer_reason) {
1148 num_literal_assigned_after_root_node++;
1151 if (num_literal_assigned_after_root_node == 0) {
1152 VLOG(2) <<
"Propagating a literal with no reason at a positive level!\n"
1153 <<
"level:" << integer_search_levels_.size() <<
" "
1154 << ReasonDebugString(literal_reason, integer_reason) <<
"\n"
1164 absl::Span<const IntegerLiteral> integer_reason) {
1165 EnqueueLiteralInternal(
literal,
nullptr, literal_reason, integer_reason);
1168void IntegerTrail::EnqueueLiteralInternal(
1170 absl::Span<const Literal> literal_reason,
1171 absl::Span<const IntegerLiteral> integer_reason) {
1173 DCHECK(lazy_reason !=
nullptr ||
1174 ReasonIsValid(literal_reason, integer_reason));
1175 if (integer_search_levels_.empty()) {
1182 if (!integer_search_levels_.empty() && integer_reason.empty() &&
1183 literal_reason.empty() && lazy_reason ==
nullptr) {
1184 literal_to_fix_.push_back(
literal);
1187 const int trail_index = trail_->
Index();
1188 if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1189 boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1191 boolean_trail_index_to_integer_one_[trail_index] = integer_trail_.size();
1193 int reason_index = literals_reason_starts_.size();
1194 if (lazy_reason !=
nullptr) {
1195 if (integer_trail_.size() >= lazy_reasons_.size()) {
1196 lazy_reasons_.resize(integer_trail_.size() + 1,
nullptr);
1198 lazy_reasons_[integer_trail_.size()] = lazy_reason;
1202 literals_reason_starts_.push_back(literals_reason_buffer_.size());
1203 literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1204 literal_reason.begin(),
1205 literal_reason.end());
1206 bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1207 bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1208 integer_reason.begin(), integer_reason.end());
1211 integer_trail_.push_back({IntegerValue(0),
1223 const int num_vars = vars_.
size();
1224 return (!integer_search_levels_.empty() &&
1225 integer_trail_.size() - integer_search_levels_.back() >
1227 parameters_.search_branching() != SatParameters::FIXED_SEARCH);
1234 ++num_decisions_to_break_loop_;
1235 std::vector<IntegerVariable> vars;
1236 for (
int i = integer_search_levels_.back(); i < integer_trail_.size(); ++i) {
1237 const IntegerVariable
var = integer_trail_[i].var;
1240 vars.push_back(
var);
1243 std::sort(vars.begin(), vars.end());
1244 IntegerVariable best_var = vars[0];
1247 for (
int i = 1; i < vars.size(); ++i) {
1248 if (vars[i] != vars[i - 1]) {
1252 if (count > best_count) {
1262 return first_level_without_full_propagation_ != -1;
1266 for (IntegerVariable
var(0);
var < vars_.
size();
var += 2) {
1273bool IntegerTrail::EnqueueInternal(
1275 absl::Span<const Literal> literal_reason,
1276 absl::Span<const IntegerLiteral> integer_reason,
1277 int trail_index_with_same_reason) {
1278 DCHECK(lazy_reason !=
nullptr ||
1279 ReasonIsValid(literal_reason, integer_reason));
1281 const IntegerVariable
var(i_lit.
var);
1289 if (i_lit.
bound <= vars_[
var].current_bound)
return true;
1298 if ((*domains_)[
var].NumIntervals() > 1) {
1299 const auto& domain = (*domains_)[
var];
1301 const int size = domain.NumIntervals();
1302 while (index < size && i_lit.bound > domain[
index].
end) {
1305 if (
index == size) {
1308 var_to_current_lb_interval_index_.
Set(
var,
index);
1319 Literal(is_ignored_literals_[
var]))) {
1322 auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1325 conflict->push_back(Literal(is_ignored_literals_[
var]));
1328 const int trail_index = FindLowestTrailIndexThatExplainBound(ub_reason);
1329 const int num_vars = vars_.
size();
1330 if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1332 MergeReasonIntoInternal(conflict);
1339 const Literal is_ignored = Literal(is_ignored_literals_[
var]);
1340 if (integer_search_levels_.empty()) {
1347 if (lazy_reason !=
nullptr) {
1348 lazy_reason(i_lit, integer_trail_.size(), &lazy_reason_literals_,
1349 &lazy_reason_trail_indices_);
1350 std::vector<IntegerLiteral> temp;
1351 for (
const int trail_index : lazy_reason_trail_indices_) {
1352 const TrailEntry& entry = integer_trail_[trail_index];
1353 temp.push_back(IntegerLiteral(entry.var, entry.bound));
1361 bounds_reason_buffer_.push_back(ub_reason);
1381 if (i_lit.
bound - lb < (ub - lb) / 2) {
1382 if (first_level_without_full_propagation_ == -1) {
1390 for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1391 bitset->Set(i_lit.
var);
1394 if (!integer_search_levels_.empty() && integer_reason.empty() &&
1395 literal_reason.empty() && lazy_reason ==
nullptr &&
1396 trail_index_with_same_reason >= integer_trail_.size()) {
1397 integer_literal_to_fix_.push_back(i_lit);
1413 const LiteralIndex literal_index =
1416 const Literal to_enqueue = Literal(literal_index);
1418 auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1420 conflict->push_back(to_enqueue);
1421 MergeReasonIntoInternal(conflict);
1431 EnqueueLiteralInternal(to_enqueue, lazy_reason, literal_reason,
1434 return EnqueueAssociatedIntegerLiteral(i_lit, to_enqueue);
1438 if (integer_search_levels_.empty()) {
1444 const int trail_index = trail_->
Index();
1445 if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1446 boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1448 boolean_trail_index_to_integer_one_[trail_index] =
1449 trail_index_with_same_reason;
1456 if (integer_search_levels_.empty()) {
1457 ++num_level_zero_enqueues_;
1458 vars_[i_lit.
var].current_bound = i_lit.
bound;
1459 integer_trail_[i_lit.
var.value()].bound = i_lit.
bound;
1470 int reason_index = literals_reason_starts_.size();
1471 if (lazy_reason !=
nullptr) {
1472 if (integer_trail_.size() >= lazy_reasons_.size()) {
1473 lazy_reasons_.resize(integer_trail_.size() + 1,
nullptr);
1475 lazy_reasons_[integer_trail_.size()] = lazy_reason;
1477 }
else if (trail_index_with_same_reason >= integer_trail_.size()) {
1479 literals_reason_starts_.push_back(literals_reason_buffer_.size());
1480 if (!literal_reason.empty()) {
1481 literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1482 literal_reason.begin(),
1483 literal_reason.end());
1485 bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1486 if (!integer_reason.empty()) {
1487 bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1488 integer_reason.begin(),
1489 integer_reason.end());
1492 reason_index = integer_trail_[trail_index_with_same_reason].reason_index;
1495 const int prev_trail_index = vars_[i_lit.
var].current_trail_index;
1496 integer_trail_.push_back({i_lit.
bound,
1501 vars_[i_lit.
var].current_bound = i_lit.
bound;
1502 vars_[i_lit.
var].current_trail_index = integer_trail_.size() - 1;
1506bool IntegerTrail::EnqueueAssociatedIntegerLiteral(IntegerLiteral i_lit,
1507 Literal literal_reason) {
1508 DCHECK(ReasonIsValid({literal_reason.Negated()}, {}));
1512 if (i_lit.bound <= vars_[i_lit.var].current_bound)
return true;
1520 return Enqueue(i_lit, {literal_reason.Negated()}, {});
1524 for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1525 bitset->Set(i_lit.var);
1529 if (integer_search_levels_.empty()) {
1530 vars_[i_lit.var].current_bound = i_lit.bound;
1531 integer_trail_[i_lit.var.value()].bound = i_lit.bound;
1542 const int reason_index = literals_reason_starts_.size();
1543 CHECK_EQ(reason_index, bounds_reason_starts_.size());
1544 literals_reason_starts_.push_back(literals_reason_buffer_.size());
1545 bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1546 literals_reason_buffer_.push_back(literal_reason.Negated());
1548 const int prev_trail_index = vars_[i_lit.var].current_trail_index;
1549 integer_trail_.push_back({i_lit.bound,
1554 vars_[i_lit.var].current_bound = i_lit.bound;
1555 vars_[i_lit.var].current_trail_index = integer_trail_.size() - 1;
1559void IntegerTrail::ComputeLazyReasonIfNeeded(
int trail_index)
const {
1560 const int reason_index = integer_trail_[trail_index].reason_index;
1561 if (reason_index == -1) {
1562 const TrailEntry& entry = integer_trail_[trail_index];
1563 const IntegerLiteral
literal(entry.var, entry.bound);
1564 lazy_reasons_[trail_index](
literal, trail_index, &lazy_reason_literals_,
1565 &lazy_reason_trail_indices_);
1569absl::Span<const int> IntegerTrail::Dependencies(
int trail_index)
const {
1570 const int reason_index = integer_trail_[trail_index].reason_index;
1571 if (reason_index == -1) {
1572 return absl::Span<const int>(lazy_reason_trail_indices_);
1575 const int start = bounds_reason_starts_[reason_index];
1576 const int end = reason_index + 1 < bounds_reason_starts_.size()
1577 ? bounds_reason_starts_[reason_index + 1]
1578 : bounds_reason_buffer_.size();
1586 if (
end > trail_index_reason_buffer_.size()) {
1587 trail_index_reason_buffer_.resize(
end, -1);
1589 if (trail_index_reason_buffer_[
start] == -1) {
1590 int new_end =
start;
1591 const int num_vars = vars_.
size();
1592 for (
int i =
start; i <
end; ++i) {
1594 FindLowestTrailIndexThatExplainBound(bounds_reason_buffer_[i]);
1595 if (dep >= num_vars) {
1596 trail_index_reason_buffer_[new_end++] = dep;
1599 return absl::Span<const int>(&trail_index_reason_buffer_[
start],
1605 return absl::Span<const int>(&trail_index_reason_buffer_[
start],
1610void IntegerTrail::AppendLiteralsReason(
int trail_index,
1611 std::vector<Literal>* output)
const {
1613 const int reason_index = integer_trail_[trail_index].reason_index;
1614 if (reason_index == -1) {
1615 for (
const Literal l : lazy_reason_literals_) {
1616 if (!added_variables_[l.Variable()]) {
1617 added_variables_.
Set(l.Variable());
1618 output->push_back(l);
1624 const int start = literals_reason_starts_[reason_index];
1625 const int end = reason_index + 1 < literals_reason_starts_.size()
1626 ? literals_reason_starts_[reason_index + 1]
1627 : literals_reason_buffer_.size();
1628 for (
int i =
start; i <
end; ++i) {
1629 const Literal l = literals_reason_buffer_[i];
1630 if (!added_variables_[l.Variable()]) {
1631 added_variables_.
Set(l.Variable());
1632 output->push_back(l);
1638 std::vector<Literal> reason;
1646 std::vector<Literal>* output)
const {
1647 DCHECK(tmp_queue_.empty());
1648 const int num_vars = vars_.
size();
1650 const int trail_index = FindLowestTrailIndexThatExplainBound(
literal);
1654 if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1656 return MergeReasonIntoInternal(output);
1661void IntegerTrail::MergeReasonIntoInternal(std::vector<Literal>* output)
const {
1664 DCHECK(std::all_of(tmp_var_to_trail_index_in_queue_.
begin(),
1665 tmp_var_to_trail_index_in_queue_.
end(),
1666 [](
int v) { return v == 0; }));
1669 for (
const Literal l : *output) {
1670 added_variables_.
Set(l.Variable());
1675 for (
const int trail_index : tmp_queue_) {
1677 DCHECK_LT(trail_index, integer_trail_.size());
1678 const TrailEntry& entry = integer_trail_[trail_index];
1679 tmp_var_to_trail_index_in_queue_[entry.var] =
1680 std::max(tmp_var_to_trail_index_in_queue_[entry.var], trail_index);
1685 std::make_heap(tmp_queue_.begin(), tmp_queue_.end());
1690 tmp_to_clear_.clear();
1691 while (!tmp_queue_.empty()) {
1692 const int trail_index = tmp_queue_.front();
1693 const TrailEntry& entry = integer_trail_[trail_index];
1694 std::pop_heap(tmp_queue_.begin(), tmp_queue_.end());
1695 tmp_queue_.pop_back();
1700 if (tmp_var_to_trail_index_in_queue_[entry.var] != trail_index) {
1707 var_trail_index_cache_threshold_ = trail_index;
1712 const LiteralIndex associated_lit =
1714 IntegerVariable(entry.var), entry.bound));
1717 const int reason_index = integer_trail_[trail_index].reason_index;
1720 const int start = literals_reason_starts_[reason_index];
1721 const int end = reason_index + 1 < literals_reason_starts_.size()
1722 ? literals_reason_starts_[reason_index + 1]
1723 : literals_reason_buffer_.size();
1726 Literal(associated_lit).Negated());
1729 const int start = bounds_reason_starts_[reason_index];
1730 const int end = reason_index + 1 < bounds_reason_starts_.size()
1731 ? bounds_reason_starts_[reason_index + 1]
1732 : bounds_reason_buffer_.size();
1746 tmp_var_to_trail_index_in_queue_[entry.var] = 0;
1747 has_dependency_ =
false;
1749 ComputeLazyReasonIfNeeded(trail_index);
1750 AppendLiteralsReason(trail_index, output);
1751 for (
const int next_trail_index : Dependencies(trail_index)) {
1752 if (next_trail_index < 0)
break;
1753 DCHECK_LT(next_trail_index, trail_index);
1754 const TrailEntry& next_entry = integer_trail_[next_trail_index];
1760 const int index_in_queue =
1761 tmp_var_to_trail_index_in_queue_[next_entry.var];
1763 has_dependency_ =
true;
1764 if (next_trail_index > index_in_queue) {
1765 tmp_var_to_trail_index_in_queue_[next_entry.var] = next_trail_index;
1767 std::push_heap(tmp_queue_.begin(), tmp_queue_.end());
1772 if (!has_dependency_) {
1773 tmp_to_clear_.push_back(entry.var);
1774 tmp_var_to_trail_index_in_queue_[entry.var] =
1780 for (
const IntegerVariable
var : tmp_to_clear_) {
1781 tmp_var_to_trail_index_in_queue_[
var] = 0;
1786 int trail_index)
const {
1787 const int index = boolean_trail_index_to_integer_one_[trail_index];
1791 ComputeLazyReasonIfNeeded(
index);
1792 AppendLiteralsReason(
index, reason);
1793 DCHECK(tmp_queue_.empty());
1794 for (
const int prev_trail_index : Dependencies(
index)) {
1795 if (prev_trail_index < 0)
break;
1797 tmp_queue_.push_back(prev_trail_index);
1799 MergeReasonIntoInternal(reason);
1810 for (
int i = integer_trail_.size(); --i >=
end;) {
1811 const TrailEntry& entry = integer_trail_[i];
1813 if (tmp_marked_[entry.var])
continue;
1815 tmp_marked_.
Set(entry.var);
1832 &id_to_greatest_common_level_since_last_call_);
1834 queue_by_priority_.resize(2);
1837void GenericLiteralWatcher::UpdateCallingNeeds(
Trail* trail) {
1839 while (propagation_trail_index_ < trail->
Index()) {
1841 if (
literal.Index() >= literal_to_watcher_.
size())
continue;
1842 for (
const auto entry : literal_to_watcher_[
literal.Index()]) {
1843 if (!in_queue_[entry.id]) {
1844 in_queue_[entry.id] =
true;
1845 queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1847 if (entry.watch_index >= 0) {
1848 id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1855 if (
var.value() >= var_to_watcher_.
size())
continue;
1856 for (
const auto entry : var_to_watcher_[
var]) {
1857 if (!in_queue_[entry.id]) {
1858 in_queue_[entry.id] =
true;
1859 queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1861 if (entry.watch_index >= 0) {
1862 id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1868 !level_zero_modified_variable_callback_.empty()) {
1869 modified_vars_for_callback_.
Resize(modified_vars_.
size());
1871 modified_vars_for_callback_.
Set(
var);
1883 for (
const int id : propagator_ids_to_call_at_level_zero_) {
1884 if (in_queue_[
id])
continue;
1885 in_queue_[id] =
true;
1886 queue_by_priority_[id_to_priority_[id]].push_back(
id);
1890 UpdateCallingNeeds(trail);
1895 for (
int priority = 0; priority < queue_by_priority_.size(); ++priority) {
1902 if (test_limit > 100) {
1907 std::deque<int>& queue = queue_by_priority_[priority];
1908 while (!queue.empty()) {
1909 const int id = queue.front();
1917 id_to_greatest_common_level_since_last_call_[IdType(
id)];
1918 const int high = id_to_level_at_last_call_[id];
1919 if (low < high || level > low) {
1920 id_to_level_at_last_call_[id] = level;
1921 id_to_greatest_common_level_since_last_call_.
MutableRef(IdType(
id)) =
1924 if (low < high) rev->SetLevel(low);
1925 if (level > low) rev->SetLevel(level);
1927 for (
int* rev_int : id_to_reversible_ints_[
id]) {
1928 rev_int_repository_->
SaveState(rev_int);
1934 const int64_t old_integer_timestamp = integer_trail_->
num_enqueues();
1935 const int64_t old_boolean_timestamp = trail->
Index();
1938 std::vector<int>& watch_indices_ref = id_to_watch_indices_[id];
1940 watch_indices_ref.empty()
1941 ? watchers_[id]->Propagate()
1942 : watchers_[id]->IncrementalPropagate(watch_indices_ref);
1944 watch_indices_ref.clear();
1945 in_queue_[id] =
false;
1951 if (id_to_idempotence_[
id]) {
1955 UpdateCallingNeeds(trail);
1956 watch_indices_ref.clear();
1957 in_queue_[id] =
false;
1962 watch_indices_ref.clear();
1963 in_queue_[id] =
false;
1964 UpdateCallingNeeds(trail);
1970 if (trail->
Index() > old_boolean_timestamp) {
1982 if (integer_trail_->
num_enqueues() > old_integer_timestamp) {
1992 const std::vector<IntegerVariable>& modified_vars =
1994 for (
const auto&
callback : level_zero_modified_variable_callback_) {
2012 for (std::deque<int>& queue : queue_by_priority_) {
2013 for (
const int id : queue) {
2014 id_to_watch_indices_[id].clear();
2024 in_queue_.assign(watchers_.size(),
false);
2029 const int id = watchers_.size();
2030 watchers_.push_back(propagator);
2031 id_to_level_at_last_call_.push_back(0);
2032 id_to_greatest_common_level_since_last_call_.
GrowByOne();
2033 id_to_reversible_classes_.push_back(std::vector<ReversibleInterface*>());
2034 id_to_reversible_ints_.push_back(std::vector<int*>());
2035 id_to_watch_indices_.push_back(std::vector<int>());
2036 id_to_priority_.push_back(1);
2037 id_to_idempotence_.push_back(
true);
2046 in_queue_.push_back(
true);
2047 queue_by_priority_[1].push_back(
id);
2052 id_to_priority_[id] = priority;
2053 if (priority >= queue_by_priority_.size()) {
2054 queue_by_priority_.resize(priority + 1);
2060 id_to_idempotence_[id] =
false;
2064 propagator_ids_to_call_at_level_zero_.push_back(
id);
2069 id_to_reversible_classes_[id].push_back(rev);
2073 id_to_reversible_ints_[id].push_back(rev);
2077std::function<void(
Model*)>
2085 std::vector<Literal> clause_to_exclude_solution;
2086 clause_to_exclude_solution.reserve(current_level);
2087 for (
int i = 0; i < current_level; ++i) {
2088 bool include_decision =
true;
2094 encoder->GetIntegerLiterals(decision);
2096 if (integer_trail->IsCurrentlyIgnored(
bound.var)) {
2102 clause_to_exclude_solution.push_back(
2103 integer_trail->IsIgnoredLiteral(
bound.var).Negated());
2104 include_decision =
false;
2108 if (include_decision) {
2109 clause_to_exclude_solution.push_back(decision.
Negated());
#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.
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.
absl::InlinedVector< ClosedInterval, 1 >::const_iterator end() const
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)
void Set(IntegerType index)
const std::vector< IntegerType > & PositionsSetAtLeastOnce() const
void Resize(IntegerType size)
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
const std::vector< IntegerLiteral > NewlyFixedIntegerLiterals() const
LiteralIndex GetAssociatedLiteral(IntegerLiteral i_lit) const
void FullyEncodeVariable(IntegerVariable var)
Literal GetFalseLiteral()
std::pair< IntegerLiteral, IntegerLiteral > Canonicalize(IntegerLiteral i_lit) const
void ClearNewlyFixedIntegerLiterals()
void AssociateToIntegerEqualValue(Literal literal, IntegerVariable var, IntegerValue value)
std::vector< ValueLiteralPair > PartialDomainEncoding(IntegerVariable var) const
bool LiteralIsAssociated(IntegerLiteral i_lit) const
std::vector< ValueLiteralPair > FullDomainEncoding(IntegerVariable var) const
void AddAllImplicationsBetweenAssociatedLiterals()
bool VariableIsFullyEncoded(IntegerVariable var) const
const InlinedIntegerLiteralVector & GetIntegerLiterals(Literal lit) const
std::vector< ValueLiteralPair > RawDomainEncoding(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
ABSL_MUST_USE_RESULT bool SafeEnqueue(IntegerLiteral i_lit, absl::Span< const IntegerLiteral > integer_reason)
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
std::string DebugString() 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
const std::vector< Decision > & Decisions() const
bool AddBinaryClause(Literal a, Literal b)
void Backtrack(int target_level)
int CurrentDecisionLevel() const
bool AddUnitClause(Literal true_literal)
void Enqueue(Literal true_literal, int propagator_id)
std::vector< Literal > * GetEmptyVectorToStoreReason(int trail_index) const
const VariablesAssignment & Assignment() const
std::vector< Literal > * MutableConflict()
const AssignmentInfo & Info(BooleanVariable var) 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::ostream & operator<<(std::ostream &os, const BoolVar &var)
const LiteralIndex kNoLiteralIndex(-1)
std::function< void(Model *)> ClauseConstraint(absl::Span< const Literal > literals)
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue.value())
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)
std::optional< int64_t > end
Represents a closed interval [start, end].
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
std::string DebugString() const
bool IsTrueLiteral() const
bool IsFalseLiteral() const
std::string DebugString() const