OR-Tools  8.1
integer.cc
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 #include "ortools/sat/integer.h"
15 
16 #include <algorithm>
17 #include <queue>
18 #include <type_traits>
19 
21 #include "ortools/base/stl_util.h"
23 
24 namespace operations_research {
25 namespace sat {
26 
27 // var * coeff + constant >= bound.
30  CHECK_GT(coeff, 0);
33 }
34 
35 // var * coeff + constant <= bound.
38  CHECK_GT(coeff, 0);
40 }
41 
42 std::vector<IntegerVariable> NegationOf(
43  const std::vector<IntegerVariable>& vars) {
44  std::vector<IntegerVariable> result(vars.size());
45  for (int i = 0; i < vars.size(); ++i) {
46  result[i] = NegationOf(vars[i]);
47  }
48  return result;
49 }
50 
52  if (VariableIsFullyEncoded(var)) return;
53 
54  CHECK_EQ(0, sat_solver_->CurrentDecisionLevel());
55  CHECK(!(*domains_)[var].IsEmpty()); // UNSAT. We don't deal with that here.
56  CHECK_LT((*domains_)[var].Size(), 100000)
57  << "Domain too large for full encoding.";
58 
59  // TODO(user): Maybe we can optimize the literal creation order and their
60  // polarity as our default SAT heuristics initially depends on this.
61  //
62  // TODO(user): Currently, in some corner cases,
63  // GetOrCreateLiteralAssociatedToEquality() might trigger some propagation
64  // that update the domain of var, so we need to cache the values to not read
65  // garbage. Note that it is okay to call the function on values no longer
66  // reachable, as this will just do nothing.
67  tmp_values_.clear();
68  for (const ClosedInterval interval : (*domains_)[var]) {
69  for (IntegerValue v(interval.start); v <= interval.end; ++v) {
70  tmp_values_.push_back(v);
71  }
72  }
73  for (const IntegerValue v : tmp_values_) {
75  }
76 
77  // Mark var and Negation(var) as fully encoded.
78  CHECK_LT(GetPositiveOnlyIndex(var), is_fully_encoded_.size());
79  CHECK(!equality_by_var_[GetPositiveOnlyIndex(var)].empty());
80  is_fully_encoded_[GetPositiveOnlyIndex(var)] = true;
81 }
82 
83 bool IntegerEncoder::VariableIsFullyEncoded(IntegerVariable var) const {
84  const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
85  if (index >= is_fully_encoded_.size()) return false;
86 
87  // Once fully encoded, the status never changes.
88  if (is_fully_encoded_[index]) return true;
90 
91  // TODO(user): Cache result as long as equality_by_var_[index] is unchanged?
92  // It might not be needed since if the variable is not fully encoded, then
93  // PartialDomainEncoding() will filter unreachable values, and so the size
94  // check will be false until further value have been encoded.
95  const int64 initial_domain_size = (*domains_)[var].Size();
96  if (equality_by_var_[index].size() < initial_domain_size) return false;
97 
98  // This cleans equality_by_var_[index] as a side effect and in particular,
99  // sorts it by values.
101 
102  // TODO(user): Comparing the size might be enough, but we want to be always
103  // valid even if either (*domains_[var]) or PartialDomainEncoding(var) are
104  // not properly synced because the propagation is not finished.
105  const auto& ref = equality_by_var_[index];
106  int i = 0;
107  for (const ClosedInterval interval : (*domains_)[var]) {
108  for (int64 v = interval.start; v <= interval.end; ++v) {
109  if (i < ref.size() && v == ref[i].value) {
110  i++;
111  }
112  }
113  }
114  if (i == ref.size()) {
115  is_fully_encoded_[index] = true;
116  }
117  return is_fully_encoded_[index];
118 }
119 
120 std::vector<IntegerEncoder::ValueLiteralPair>
121 IntegerEncoder::FullDomainEncoding(IntegerVariable var) const {
123  return PartialDomainEncoding(var);
124 }
125 
126 std::vector<IntegerEncoder::ValueLiteralPair>
128  CHECK_EQ(sat_solver_->CurrentDecisionLevel(), 0);
129  const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
130  if (index >= equality_by_var_.size()) return {};
131 
132  int new_size = 0;
133  std::vector<ValueLiteralPair>& ref = equality_by_var_[index];
134  for (int i = 0; i < ref.size(); ++i) {
135  const ValueLiteralPair pair = ref[i];
136  if (sat_solver_->Assignment().LiteralIsFalse(pair.literal)) continue;
137  if (sat_solver_->Assignment().LiteralIsTrue(pair.literal)) {
138  ref.clear();
139  ref.push_back(pair);
140  new_size = 1;
141  break;
142  }
143  ref[new_size++] = pair;
144  }
145  ref.resize(new_size);
146  std::sort(ref.begin(), ref.end());
147 
148  std::vector<IntegerEncoder::ValueLiteralPair> result = ref;
149  if (!VariableIsPositive(var)) {
150  std::reverse(result.begin(), result.end());
151  for (ValueLiteralPair& ref : result) ref.value = -ref.value;
152  }
153  return result;
154 }
155 
156 // Note that by not inserting the literal in "order" we can in the worst case
157 // use twice as much implication (2 by literals) instead of only one between
158 // consecutive literals.
159 void IntegerEncoder::AddImplications(
160  const std::map<IntegerValue, Literal>& map,
161  std::map<IntegerValue, Literal>::const_iterator it,
162  Literal associated_lit) {
163  if (!add_implications_) return;
164  DCHECK_EQ(it->second, associated_lit);
165 
166  // Literal(after) => associated_lit
167  auto after_it = it;
168  ++after_it;
169  if (after_it != map.end()) {
170  sat_solver_->AddClauseDuringSearch(
171  {after_it->second.Negated(), associated_lit});
172  }
173 
174  // associated_lit => Literal(before)
175  if (it != map.begin()) {
176  auto before_it = it;
177  --before_it;
178  sat_solver_->AddClauseDuringSearch(
179  {associated_lit.Negated(), before_it->second});
180  }
181 }
182 
184  CHECK_EQ(0, sat_solver_->CurrentDecisionLevel());
185  add_implications_ = true;
186  for (const std::map<IntegerValue, Literal>& encoding : encoding_by_var_) {
187  LiteralIndex previous = kNoLiteralIndex;
188  for (const auto value_literal : encoding) {
189  const Literal lit = value_literal.second;
190  if (previous != kNoLiteralIndex) {
191  // lit => previous.
192  sat_solver_->AddBinaryClause(lit.Negated(), Literal(previous));
193  }
194  previous = lit.Index();
195  }
196  }
197 }
198 
199 std::pair<IntegerLiteral, IntegerLiteral> IntegerEncoder::Canonicalize(
200  IntegerLiteral i_lit) const {
201  const IntegerVariable var(i_lit.var);
202  IntegerValue after(i_lit.bound);
203  IntegerValue before(i_lit.bound - 1);
204  CHECK_GE(before, (*domains_)[var].Min());
205  CHECK_LE(after, (*domains_)[var].Max());
206  int64 previous = kint64min;
207  for (const ClosedInterval& interval : (*domains_)[var]) {
208  if (before > previous && before < interval.start) before = previous;
209  if (after > previous && after < interval.start) after = interval.start;
210  if (after <= interval.end) break;
211  previous = interval.end;
212  }
213  return {IntegerLiteral::GreaterOrEqual(var, after),
215 }
216 
218  if (i_lit.bound <= (*domains_)[i_lit.var].Min()) {
219  return GetTrueLiteral();
220  }
221  if (i_lit.bound > (*domains_)[i_lit.var].Max()) {
222  return GetFalseLiteral();
223  }
224 
225  const auto canonicalization = Canonicalize(i_lit);
226  const IntegerLiteral new_lit = canonicalization.first;
227 
228  const LiteralIndex index = GetAssociatedLiteral(new_lit);
229  if (index != kNoLiteralIndex) return Literal(index);
230  const LiteralIndex n_index = GetAssociatedLiteral(canonicalization.second);
231  if (n_index != kNoLiteralIndex) return Literal(n_index).Negated();
232 
233  ++num_created_variables_;
234  const Literal literal(sat_solver_->NewBooleanVariable(), true);
236 
237  // TODO(user): on some problem this happens. We should probably make sure that
238  // we don't create extra fixed Boolean variable for no reason.
239  if (sat_solver_->Assignment().LiteralIsAssigned(literal)) {
240  VLOG(1) << "Created a fixed literal for no reason!";
241  }
242  return literal;
243 }
244 
245 namespace {
246 std::pair<PositiveOnlyIndex, IntegerValue> PositiveVarKey(IntegerVariable var,
247  IntegerValue value) {
248  return std::make_pair(GetPositiveOnlyIndex(var),
250 }
251 } // namespace
252 
254  IntegerVariable var, IntegerValue value) const {
255  const auto it =
256  equality_to_associated_literal_.find(PositiveVarKey(var, value));
257  if (it != equality_to_associated_literal_.end()) {
258  return it->second.Index();
259  }
260  return kNoLiteralIndex;
261 }
262 
264  IntegerVariable var, IntegerValue value) {
265  {
266  const auto it =
267  equality_to_associated_literal_.find(PositiveVarKey(var, value));
268  if (it != equality_to_associated_literal_.end()) {
269  return it->second;
270  }
271  }
272 
273  // Check for trivial true/false literal to avoid creating variable for no
274  // reasons.
275  const Domain& domain = (*domains_)[var];
276  if (!domain.Contains(value.value())) return GetFalseLiteral();
277  if (value == domain.Min() && value == domain.Max()) {
279  return GetTrueLiteral();
280  }
281 
282  ++num_created_variables_;
283  const Literal literal(sat_solver_->NewBooleanVariable(), true);
285 
286  // TODO(user): this happens on some problem. We should probably
287  // make sure that we don't create extra fixed Boolean variable for no reason.
288  // Note that here we could detect the case before creating the literal. The
289  // initial domain didn't contain it, but maybe the one of (>= value) or (<=
290  // value) is false?
291  if (sat_solver_->Assignment().LiteralIsAssigned(literal)) {
292  VLOG(1) << "Created a fixed literal for no reason!";
293  }
294  return literal;
295 }
296 
298  IntegerLiteral i_lit) {
299  const auto& domain = (*domains_)[i_lit.var];
300  const IntegerValue min(domain.Min());
301  const IntegerValue max(domain.Max());
302  if (i_lit.bound <= min) {
303  sat_solver_->AddUnitClause(literal);
304  } else if (i_lit.bound > max) {
305  sat_solver_->AddUnitClause(literal.Negated());
306  } else {
307  const auto pair = Canonicalize(i_lit);
308  HalfAssociateGivenLiteral(pair.first, literal);
309  HalfAssociateGivenLiteral(pair.second, literal.Negated());
310 
311  // Detect the case >= max or <= min and properly register them. Note that
312  // both cases will happen at the same time if there is just two possible
313  // value in the domain.
314  if (pair.first.bound == max) {
316  }
317  if (-pair.second.bound == min) {
318  AssociateToIntegerEqualValue(literal.Negated(), i_lit.var, min);
319  }
320  }
321 }
322 
324  IntegerVariable var,
325  IntegerValue value) {
326  // Detect literal view. Note that the same literal can be associated to more
327  // than one variable, and thus already have a view. We don't change it in
328  // this case.
329  const Domain& domain = (*domains_)[var];
330  if (value == 1 && domain.Min() >= 0 && domain.Max() <= 1) {
331  if (literal.Index() >= literal_view_.size()) {
332  literal_view_.resize(literal.Index().value() + 1, kNoIntegerVariable);
333  literal_view_[literal.Index()] = var;
334  } else if (literal_view_[literal.Index()] == kNoIntegerVariable) {
335  literal_view_[literal.Index()] = var;
336  }
337  }
338  if (value == -1 && domain.Min() >= -1 && domain.Max() <= 0) {
339  if (literal.Index() >= literal_view_.size()) {
340  literal_view_.resize(literal.Index().value() + 1, kNoIntegerVariable);
341  literal_view_[literal.Index()] = NegationOf(var);
342  } else if (literal_view_[literal.Index()] == kNoIntegerVariable) {
343  literal_view_[literal.Index()] = NegationOf(var);
344  }
345  }
346 
347  // We use the "do not insert if present" behavior of .insert() to do just one
348  // lookup.
349  const auto insert_result = equality_to_associated_literal_.insert(
350  {PositiveVarKey(var, value), literal});
351  if (!insert_result.second) {
352  // If this key is already associated, make the two literals equal.
353  const Literal representative = insert_result.first->second;
354  if (representative != literal) {
355  DCHECK_EQ(sat_solver_->CurrentDecisionLevel(), 0);
356  sat_solver_->AddClauseDuringSearch({literal, representative.Negated()});
357  sat_solver_->AddClauseDuringSearch({literal.Negated(), representative});
358  }
359  return;
360  }
361 
362  // Fix literal for value outside the domain.
363  if (!domain.Contains(value.value())) {
364  sat_solver_->AddUnitClause(literal.Negated());
365  return;
366  }
367 
368  // Update equality_by_var. Note that due to the
369  // equality_to_associated_literal_ hash table, there should never be any
370  // duplicate values for a given variable.
371  const PositiveOnlyIndex index = GetPositiveOnlyIndex(var);
372  if (index >= equality_by_var_.size()) {
373  equality_by_var_.resize(index.value() + 1);
374  is_fully_encoded_.resize(index.value() + 1);
375  }
376  equality_by_var_[index].push_back(
378 
379  // Fix literal for constant domain.
380  if (value == domain.Min() && value == domain.Max()) {
381  sat_solver_->AddUnitClause(literal);
382  return;
383  }
384 
387 
388  // Special case for the first and last value.
389  if (value == domain.Min()) {
390  // Note that this will recursively call AssociateToIntegerEqualValue() but
391  // since equality_to_associated_literal_[] is now set, the recursion will
392  // stop there. When a domain has just 2 values, this allows to call just
393  // once AssociateToIntegerEqualValue() and also associate the other value to
394  // the negation of the given literal.
396  return;
397  }
398  if (value == domain.Max()) {
400  return;
401  }
402 
403  // (var == value) <=> (var >= value) and (var <= value).
406  sat_solver_->AddClauseDuringSearch({a, literal.Negated()});
407  sat_solver_->AddClauseDuringSearch({b, literal.Negated()});
408  sat_solver_->AddClauseDuringSearch({a.Negated(), b.Negated(), literal});
409 
410  // Update reverse encoding.
411  const int new_size = 1 + literal.Index().value();
412  if (new_size > full_reverse_encoding_.size()) {
413  full_reverse_encoding_.resize(new_size);
414  }
415  full_reverse_encoding_[literal.Index()].push_back(le);
416  full_reverse_encoding_[literal.Index()].push_back(ge);
417 }
418 
419 // TODO(user): The hard constraints we add between associated literals seems to
420 // work for optional variables, but I am not 100% sure why!! I think it works
421 // because these literals can only appear in a conflict if the presence literal
422 // of the optional variables is true.
423 void IntegerEncoder::HalfAssociateGivenLiteral(IntegerLiteral i_lit,
424  Literal literal) {
425  // Resize reverse encoding.
426  const int new_size = 1 + literal.Index().value();
427  if (new_size > reverse_encoding_.size()) {
428  reverse_encoding_.resize(new_size);
429  }
430  if (new_size > full_reverse_encoding_.size()) {
431  full_reverse_encoding_.resize(new_size);
432  }
433 
434  // Associate the new literal to i_lit.
435  if (i_lit.var >= encoding_by_var_.size()) {
436  encoding_by_var_.resize(i_lit.var.value() + 1);
437  }
438  auto& var_encoding = encoding_by_var_[i_lit.var];
439  auto insert_result = var_encoding.insert({i_lit.bound, literal});
440  if (insert_result.second) { // New item.
441  AddImplications(var_encoding, insert_result.first, literal);
442  if (sat_solver_->Assignment().LiteralIsTrue(literal)) {
443  if (sat_solver_->CurrentDecisionLevel() == 0) {
444  newly_fixed_integer_literals_.push_back(i_lit);
445  }
446  }
447 
448  // TODO(user): do that for the other branch too?
449  reverse_encoding_[literal.Index()].push_back(i_lit);
450  full_reverse_encoding_[literal.Index()].push_back(i_lit);
451  } else {
452  const Literal associated(insert_result.first->second);
453  if (associated != literal) {
454  DCHECK_EQ(sat_solver_->CurrentDecisionLevel(), 0);
455  sat_solver_->AddClauseDuringSearch({literal, associated.Negated()});
456  sat_solver_->AddClauseDuringSearch({literal.Negated(), associated});
457  }
458  }
459 }
460 
462  if (i.var >= encoding_by_var_.size()) return false;
463  const std::map<IntegerValue, Literal>& encoding = encoding_by_var_[i.var];
464  return encoding.find(i.bound) != encoding.end();
465 }
466 
468  if (i.var >= encoding_by_var_.size()) return kNoLiteralIndex;
469  const std::map<IntegerValue, Literal>& encoding = encoding_by_var_[i.var];
470  const auto result = encoding.find(i.bound);
471  if (result == encoding.end()) return kNoLiteralIndex;
472  return result->second.Index();
473 }
474 
476  IntegerLiteral i, IntegerValue* bound) const {
477  // We take the element before the upper_bound() which is either the encoding
478  // of i if it already exists, or the encoding just before it.
479  if (i.var >= encoding_by_var_.size()) return kNoLiteralIndex;
480  const std::map<IntegerValue, Literal>& encoding = encoding_by_var_[i.var];
481  auto after_it = encoding.upper_bound(i.bound);
482  if (after_it == encoding.begin()) return kNoLiteralIndex;
483  --after_it;
484  *bound = after_it->first;
485  return after_it->second.Index();
486 }
487 
489  if (parameters_.log_search_progress() && num_decisions_to_break_loop_ > 0) {
490  LOG(INFO) << "Num decisions to break propagation loop: "
491  << num_decisions_to_break_loop_;
492  }
493 }
494 
496  const int level = trail->CurrentDecisionLevel();
497  for (ReversibleInterface* rev : reversible_classes_) rev->SetLevel(level);
498 
499  // Make sure that our internal "integer_search_levels_" size matches the
500  // sat decision levels. At the level zero, integer_search_levels_ should
501  // be empty.
502  if (level > integer_search_levels_.size()) {
503  integer_search_levels_.push_back(integer_trail_.size());
504  reason_decision_levels_.push_back(literals_reason_starts_.size());
505  CHECK_EQ(trail->CurrentDecisionLevel(), integer_search_levels_.size());
506  }
507 
508  // This is used to map any integer literal out of the initial variable domain
509  // into one that use one of the domain value.
510  var_to_current_lb_interval_index_.SetLevel(level);
511 
512  // This is required because when loading a model it is possible that we add
513  // (literal <-> integer literal) associations for literals that have already
514  // been propagated here. This often happens when the presolve is off
515  // and many variables are fixed.
516  //
517  // TODO(user): refactor the interaction IntegerTrail <-> IntegerEncoder so
518  // that we can just push right away such literal. Unfortunately, this is is
519  // a big chunck of work.
520  if (level == 0) {
521  for (const IntegerLiteral i_lit : encoder_->NewlyFixedIntegerLiterals()) {
522  if (IsCurrentlyIgnored(i_lit.var)) continue;
523  if (!Enqueue(i_lit, {}, {})) return false;
524  }
525  encoder_->ClearNewlyFixedIntegerLiterals();
526 
527  for (const IntegerLiteral i_lit : integer_literal_to_fix_) {
528  if (IsCurrentlyIgnored(i_lit.var)) continue;
529  if (!Enqueue(i_lit, {}, {})) return false;
530  }
531  integer_literal_to_fix_.clear();
532 
533  for (const Literal lit : literal_to_fix_) {
534  if (trail_->Assignment().LiteralIsFalse(lit)) return false;
535  if (trail_->Assignment().LiteralIsTrue(lit)) continue;
536  trail_->EnqueueWithUnitReason(lit);
537  }
538  literal_to_fix_.clear();
539  }
540 
541  // Process all the "associated" literals and Enqueue() the corresponding
542  // bounds.
543  while (propagation_trail_index_ < trail->Index()) {
544  const Literal literal = (*trail)[propagation_trail_index_++];
545  for (const IntegerLiteral i_lit : encoder_->GetIntegerLiterals(literal)) {
546  if (IsCurrentlyIgnored(i_lit.var)) continue;
547 
548  // The reason is simply the associated literal.
549  if (!EnqueueAssociatedIntegerLiteral(i_lit, literal)) {
550  return false;
551  }
552  }
553  }
554 
555  return true;
556 }
557 
558 void IntegerTrail::Untrail(const Trail& trail, int literal_trail_index) {
559  ++num_untrails_;
560  const int level = trail.CurrentDecisionLevel();
561  for (ReversibleInterface* rev : reversible_classes_) rev->SetLevel(level);
562  var_to_current_lb_interval_index_.SetLevel(level);
564  std::min(propagation_trail_index_, literal_trail_index);
565 
566  if (level < first_level_without_full_propagation_) {
567  first_level_without_full_propagation_ = -1;
568  }
569 
570  // Note that if a conflict was detected before Propagate() of this class was
571  // even called, it is possible that there is nothing to backtrack.
572  if (level >= integer_search_levels_.size()) return;
573  const int target = integer_search_levels_[level];
574  integer_search_levels_.resize(level);
575  CHECK_GE(target, vars_.size());
576  CHECK_LE(target, integer_trail_.size());
577 
578  for (int index = integer_trail_.size() - 1; index >= target; --index) {
579  const TrailEntry& entry = integer_trail_[index];
580  if (entry.var < 0) continue; // entry used by EnqueueLiteral().
581  vars_[entry.var].current_trail_index = entry.prev_trail_index;
582  vars_[entry.var].current_bound =
583  integer_trail_[entry.prev_trail_index].bound;
584  }
585  integer_trail_.resize(target);
586 
587  // Clear reason.
588  const int old_size = reason_decision_levels_[level];
589  reason_decision_levels_.resize(level);
590  if (old_size < literals_reason_starts_.size()) {
591  literals_reason_buffer_.resize(literals_reason_starts_[old_size]);
592 
593  const int bound_start = bounds_reason_starts_[old_size];
594  bounds_reason_buffer_.resize(bound_start);
595  if (bound_start < trail_index_reason_buffer_.size()) {
596  trail_index_reason_buffer_.resize(bound_start);
597  }
598 
599  literals_reason_starts_.resize(old_size);
600  bounds_reason_starts_.resize(old_size);
601  }
602 }
603 
605  // Because we always create both a variable and its negation.
606  const int size = 2 * num_vars;
607  vars_.reserve(size);
608  is_ignored_literals_.reserve(size);
609  integer_trail_.reserve(size);
610  domains_->reserve(size);
611  var_trail_index_cache_.reserve(size);
612  tmp_var_to_trail_index_in_queue_.reserve(size);
613 }
614 
615 IntegerVariable IntegerTrail::AddIntegerVariable(IntegerValue lower_bound,
616  IntegerValue upper_bound) {
617  DCHECK_GE(lower_bound, kMinIntegerValue);
618  DCHECK_LE(lower_bound, upper_bound);
619  DCHECK_LE(upper_bound, kMaxIntegerValue);
620  DCHECK(lower_bound >= 0 || lower_bound + kint64max >= upper_bound);
621  DCHECK(integer_search_levels_.empty());
622  DCHECK_EQ(vars_.size(), integer_trail_.size());
623 
624  const IntegerVariable i(vars_.size());
625  is_ignored_literals_.push_back(kNoLiteralIndex);
626  vars_.push_back({lower_bound, static_cast<int>(integer_trail_.size())});
627  integer_trail_.push_back({lower_bound, i});
628  domains_->push_back(Domain(lower_bound.value(), upper_bound.value()));
629 
630  // TODO(user): the is_ignored_literals_ Booleans are currently always the same
631  // for a variable and its negation. So it may be better not to store it twice
632  // so that we don't have to be careful when setting them.
633  CHECK_EQ(NegationOf(i).value(), vars_.size());
634  is_ignored_literals_.push_back(kNoLiteralIndex);
635  vars_.push_back({-upper_bound, static_cast<int>(integer_trail_.size())});
636  integer_trail_.push_back({-upper_bound, NegationOf(i)});
637  domains_->push_back(Domain(-upper_bound.value(), -lower_bound.value()));
638 
639  var_trail_index_cache_.resize(vars_.size(), integer_trail_.size());
640  tmp_var_to_trail_index_in_queue_.resize(vars_.size(), 0);
641 
642  for (SparseBitset<IntegerVariable>* w : watchers_) {
643  w->Resize(NumIntegerVariables());
644  }
645  return i;
646 }
647 
648 IntegerVariable IntegerTrail::AddIntegerVariable(const Domain& domain) {
649  CHECK(!domain.IsEmpty());
650  const IntegerVariable var = AddIntegerVariable(IntegerValue(domain.Min()),
651  IntegerValue(domain.Max()));
652  CHECK(UpdateInitialDomain(var, domain));
653  return var;
654 }
655 
656 const Domain& IntegerTrail::InitialVariableDomain(IntegerVariable var) const {
657  return (*domains_)[var];
658 }
659 
660 bool IntegerTrail::UpdateInitialDomain(IntegerVariable var, Domain domain) {
661  CHECK_EQ(trail_->CurrentDecisionLevel(), 0);
662 
663  const Domain& old_domain = InitialVariableDomain(var);
664  domain = domain.IntersectionWith(old_domain);
665  if (old_domain == domain) return true;
666 
667  if (domain.IsEmpty()) return false;
668  (*domains_)[var] = domain;
669  (*domains_)[NegationOf(var)] = domain.Negation();
670  if (domain.NumIntervals() > 1) {
671  var_to_current_lb_interval_index_.Set(var, 0);
672  var_to_current_lb_interval_index_.Set(NegationOf(var), 0);
673  }
674 
675  // TODO(user): That works, but it might be better to simply update the
676  // bounds here directly. This is because these function might call again
677  // UpdateInitialDomain(), and we will abort after realizing that the domain
678  // didn't change this time.
679  CHECK(Enqueue(IntegerLiteral::GreaterOrEqual(var, IntegerValue(domain.Min())),
680  {}, {}));
681  CHECK(Enqueue(IntegerLiteral::LowerOrEqual(var, IntegerValue(domain.Max())),
682  {}, {}));
683 
684  // Set to false excluded literals.
685  int i = 0;
686  int num_fixed = 0;
687  for (const IntegerEncoder::ValueLiteralPair pair :
688  encoder_->PartialDomainEncoding(var)) {
689  while (i < domain.NumIntervals() && pair.value > domain[i].end) ++i;
690  if (i == domain.NumIntervals() || pair.value < domain[i].start) {
691  ++num_fixed;
692  if (trail_->Assignment().LiteralIsTrue(pair.literal)) return false;
693  if (!trail_->Assignment().LiteralIsFalse(pair.literal)) {
694  trail_->EnqueueWithUnitReason(pair.literal.Negated());
695  }
696  }
697  }
698  if (num_fixed > 0) {
699  VLOG(1)
700  << "Domain intersection fixed " << num_fixed
701  << " equality literal corresponding to values outside the new domain.";
702  }
703 
704  return true;
705 }
706 
708  IntegerValue value) {
709  auto insert = constant_map_.insert(std::make_pair(value, kNoIntegerVariable));
710  if (insert.second) { // new element.
711  const IntegerVariable new_var = AddIntegerVariable(value, value);
712  insert.first->second = new_var;
713  if (value != 0) {
714  // Note that this might invalidate insert.first->second.
715  gtl::InsertOrDie(&constant_map_, -value, NegationOf(new_var));
716  }
717  return new_var;
718  }
719  return insert.first->second;
720 }
721 
723  // The +1 if for the special key zero (the only case when we have an odd
724  // number of entries).
725  return (constant_map_.size() + 1) / 2;
726 }
727 
729  int threshold) const {
730  // Optimization. We assume this is only called when computing a reason, so we
731  // can ignore this trail_index if we already need a more restrictive reason
732  // for this var.
733  const int index_in_queue = tmp_var_to_trail_index_in_queue_[var];
734  if (threshold <= index_in_queue) {
735  if (index_in_queue != kint32max) has_dependency_ = true;
736  return -1;
737  }
738 
739  DCHECK_GE(threshold, vars_.size());
740  int trail_index = vars_[var].current_trail_index;
741 
742  // Check the validity of the cached index and use it if possible.
743  if (trail_index > threshold) {
744  const int cached_index = var_trail_index_cache_[var];
745  if (cached_index >= threshold && cached_index < trail_index &&
746  integer_trail_[cached_index].var == var) {
747  trail_index = cached_index;
748  }
749  }
750 
751  while (trail_index >= threshold) {
752  trail_index = integer_trail_[trail_index].prev_trail_index;
753  if (trail_index >= var_trail_index_cache_threshold_) {
754  var_trail_index_cache_[var] = trail_index;
755  }
756  }
757 
758  const int num_vars = vars_.size();
759  return trail_index < num_vars ? -1 : trail_index;
760 }
761 
762 int IntegerTrail::FindLowestTrailIndexThatExplainBound(
763  IntegerLiteral i_lit) const {
764  DCHECK_LE(i_lit.bound, vars_[i_lit.var].current_bound);
765  if (i_lit.bound <= LevelZeroLowerBound(i_lit.var)) return -1;
766  int trail_index = vars_[i_lit.var].current_trail_index;
767 
768  // Check the validity of the cached index and use it if possible. This caching
769  // mechanism is important in case of long chain of propagation on the same
770  // variable. Because during conflict resolution, we call
771  // FindLowestTrailIndexThatExplainBound() with lowest and lowest bound, this
772  // cache can transform a quadratic complexity into a linear one.
773  {
774  const int cached_index = var_trail_index_cache_[i_lit.var];
775  if (cached_index < trail_index) {
776  const TrailEntry& entry = integer_trail_[cached_index];
777  if (entry.var == i_lit.var && entry.bound >= i_lit.bound) {
778  trail_index = cached_index;
779  }
780  }
781  }
782 
783  int prev_trail_index = trail_index;
784  while (true) {
785  if (trail_index >= var_trail_index_cache_threshold_) {
786  var_trail_index_cache_[i_lit.var] = trail_index;
787  }
788  const TrailEntry& entry = integer_trail_[trail_index];
789  if (entry.bound == i_lit.bound) return trail_index;
790  if (entry.bound < i_lit.bound) return prev_trail_index;
791  prev_trail_index = trail_index;
792  trail_index = entry.prev_trail_index;
793  }
794 }
795 
796 // TODO(user): Get rid of this function and only keep the trail index one?
798  IntegerValue slack, absl::Span<const IntegerValue> coeffs,
799  std::vector<IntegerLiteral>* reason) const {
800  CHECK_GE(slack, 0);
801  if (slack == 0) return;
802  const int size = reason->size();
803  tmp_indices_.resize(size);
804  for (int i = 0; i < size; ++i) {
805  CHECK_EQ((*reason)[i].bound, LowerBound((*reason)[i].var));
806  CHECK_GE(coeffs[i], 0);
807  tmp_indices_[i] = vars_[(*reason)[i].var].current_trail_index;
808  }
809 
810  RelaxLinearReason(slack, coeffs, &tmp_indices_);
811 
812  reason->clear();
813  for (const int i : tmp_indices_) {
814  reason->push_back(IntegerLiteral::GreaterOrEqual(integer_trail_[i].var,
815  integer_trail_[i].bound));
816  }
817 }
818 
820  IntegerValue slack, absl::Span<const IntegerValue> coeffs,
821  absl::Span<const IntegerVariable> vars,
822  std::vector<IntegerLiteral>* reason) const {
823  tmp_indices_.clear();
824  for (const IntegerVariable var : vars) {
825  tmp_indices_.push_back(vars_[var].current_trail_index);
826  }
827  if (slack > 0) RelaxLinearReason(slack, coeffs, &tmp_indices_);
828  for (const int i : tmp_indices_) {
829  reason->push_back(IntegerLiteral::GreaterOrEqual(integer_trail_[i].var,
830  integer_trail_[i].bound));
831  }
832 }
833 
834 void IntegerTrail::RelaxLinearReason(IntegerValue slack,
835  absl::Span<const IntegerValue> coeffs,
836  std::vector<int>* trail_indices) const {
837  DCHECK_GT(slack, 0);
838  DCHECK(relax_heap_.empty());
839 
840  // We start by filtering *trail_indices:
841  // - remove all level zero entries.
842  // - keep the one that cannot be relaxed.
843  // - move the other one to the relax_heap_ (and creating the heap).
844  int new_size = 0;
845  const int size = coeffs.size();
846  const int num_vars = vars_.size();
847  for (int i = 0; i < size; ++i) {
848  const int index = (*trail_indices)[i];
849 
850  // We ignore level zero entries.
851  if (index < num_vars) continue;
852 
853  // If the coeff is too large, we cannot relax this entry.
854  const IntegerValue coeff = coeffs[i];
855  if (coeff > slack) {
856  (*trail_indices)[new_size++] = index;
857  continue;
858  }
859 
860  // This is a bit hacky, but when it is used from MergeReasonIntoInternal(),
861  // we never relax a reason that will not be expanded because it is already
862  // part of the current conflict.
863  const TrailEntry& entry = integer_trail_[index];
864  if (entry.var != kNoIntegerVariable &&
865  index <= tmp_var_to_trail_index_in_queue_[entry.var]) {
866  (*trail_indices)[new_size++] = index;
867  continue;
868  }
869 
870  // Note that both terms of the product are positive.
871  const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
872  const int64 diff =
873  CapProd(coeff.value(), (entry.bound - previous_entry.bound).value());
874  if (diff > slack) {
875  (*trail_indices)[new_size++] = index;
876  continue;
877  }
878 
879  relax_heap_.push_back({index, coeff, diff});
880  }
881  trail_indices->resize(new_size);
882  std::make_heap(relax_heap_.begin(), relax_heap_.end());
883 
884  while (slack > 0 && !relax_heap_.empty()) {
885  const RelaxHeapEntry heap_entry = relax_heap_.front();
886  std::pop_heap(relax_heap_.begin(), relax_heap_.end());
887  relax_heap_.pop_back();
888 
889  // The slack might have changed since the entry was added.
890  if (heap_entry.diff > slack) {
891  trail_indices->push_back(heap_entry.index);
892  continue;
893  }
894 
895  // Relax, and decide what to do with the new value of index.
896  slack -= heap_entry.diff;
897  const int index = integer_trail_[heap_entry.index].prev_trail_index;
898 
899  // Same code as in the first block.
900  if (index < num_vars) continue;
901  if (heap_entry.coeff > slack) {
902  trail_indices->push_back(index);
903  continue;
904  }
905  const TrailEntry& entry = integer_trail_[index];
906  if (entry.var != kNoIntegerVariable &&
907  index <= tmp_var_to_trail_index_in_queue_[entry.var]) {
908  trail_indices->push_back(index);
909  continue;
910  }
911 
912  const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
913  const int64 diff = CapProd(heap_entry.coeff.value(),
914  (entry.bound - previous_entry.bound).value());
915  if (diff > slack) {
916  trail_indices->push_back(index);
917  continue;
918  }
919  relax_heap_.push_back({index, heap_entry.coeff, diff});
920  std::push_heap(relax_heap_.begin(), relax_heap_.end());
921  }
922 
923  // If we aborted early because of the slack, we need to push all remaining
924  // indices back into the reason.
925  for (const RelaxHeapEntry& entry : relax_heap_) {
926  trail_indices->push_back(entry.index);
927  }
928  relax_heap_.clear();
929 }
930 
932  std::vector<IntegerLiteral>* reason) const {
933  int new_size = 0;
934  for (const IntegerLiteral literal : *reason) {
935  if (literal.bound <= LevelZeroLowerBound(literal.var)) continue;
936  (*reason)[new_size++] = literal;
937  }
938  reason->resize(new_size);
939 }
940 
941 std::vector<Literal>* IntegerTrail::InitializeConflict(
942  IntegerLiteral integer_literal, const LazyReasonFunction& lazy_reason,
943  absl::Span<const Literal> literals_reason,
944  absl::Span<const IntegerLiteral> bounds_reason) {
945  DCHECK(tmp_queue_.empty());
946  std::vector<Literal>* conflict = trail_->MutableConflict();
947  if (lazy_reason == nullptr) {
948  conflict->assign(literals_reason.begin(), literals_reason.end());
949  const int num_vars = vars_.size();
950  for (const IntegerLiteral& literal : bounds_reason) {
951  const int trail_index = FindLowestTrailIndexThatExplainBound(literal);
952  if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
953  }
954  } else {
955  // We use the current trail index here.
956  conflict->clear();
957  lazy_reason(integer_literal, integer_trail_.size(), conflict, &tmp_queue_);
958  }
959  return conflict;
960 }
961 
962 namespace {
963 
964 std::string ReasonDebugString(absl::Span<const Literal> literal_reason,
965  absl::Span<const IntegerLiteral> integer_reason) {
966  std::string result = "literals:{";
967  for (const Literal l : literal_reason) {
968  if (result.back() != '{') result += ",";
969  result += l.DebugString();
970  }
971  result += "} bounds:{";
972  for (const IntegerLiteral l : integer_reason) {
973  if (result.back() != '{') result += ",";
974  result += l.DebugString();
975  }
976  result += "}";
977  return result;
978 }
979 
980 } // namespace
981 
982 std::string IntegerTrail::DebugString() {
983  std::string result = "trail:{";
984  const int num_vars = vars_.size();
985  const int limit =
986  std::min(num_vars + 30, static_cast<int>(integer_trail_.size()));
987  for (int i = num_vars; i < limit; ++i) {
988  if (result.back() != '{') result += ",";
989  result +=
990  IntegerLiteral::GreaterOrEqual(IntegerVariable(integer_trail_[i].var),
991  integer_trail_[i].bound)
992  .DebugString();
993  }
994  if (limit < integer_trail_.size()) {
995  result += ", ...";
996  }
997  result += "}";
998  return result;
999 }
1000 
1002  absl::Span<const Literal> literal_reason,
1003  absl::Span<const IntegerLiteral> integer_reason) {
1004  return EnqueueInternal(i_lit, nullptr, literal_reason, integer_reason,
1005  integer_trail_.size());
1006 }
1007 
1009  absl::Span<const Literal> literal_reason,
1010  absl::Span<const IntegerLiteral> integer_reason,
1011  int trail_index_with_same_reason) {
1012  return EnqueueInternal(i_lit, nullptr, literal_reason, integer_reason,
1013  trail_index_with_same_reason);
1014 }
1015 
1017  LazyReasonFunction lazy_reason) {
1018  return EnqueueInternal(i_lit, lazy_reason, {}, {}, integer_trail_.size());
1019 }
1020 
1021 bool IntegerTrail::ReasonIsValid(
1022  absl::Span<const Literal> literal_reason,
1023  absl::Span<const IntegerLiteral> integer_reason) {
1024  const VariablesAssignment& assignment = trail_->Assignment();
1025  for (const Literal lit : literal_reason) {
1026  if (!assignment.LiteralIsFalse(lit)) return false;
1027  }
1028  for (const IntegerLiteral i_lit : integer_reason) {
1029  if (i_lit.bound > vars_[i_lit.var].current_bound) {
1030  if (IsOptional(i_lit.var)) {
1031  const Literal is_ignored = IsIgnoredLiteral(i_lit.var);
1032  LOG(INFO) << "Reason " << i_lit << " is not true!"
1033  << " optional variable:" << i_lit.var
1034  << " present:" << assignment.LiteralIsFalse(is_ignored)
1035  << " absent:" << assignment.LiteralIsTrue(is_ignored)
1036  << " current_lb:" << vars_[i_lit.var].current_bound;
1037  } else {
1038  LOG(INFO) << "Reason " << i_lit << " is not true!"
1039  << " non-optional variable:" << i_lit.var
1040  << " current_lb:" << vars_[i_lit.var].current_bound;
1041  }
1042  return false;
1043  }
1044  }
1045 
1046  // This may not indicate an incorectness, but just some propagators that
1047  // didn't reach a fixed-point at level zero.
1048  if (!integer_search_levels_.empty()) {
1049  int num_literal_assigned_after_root_node = 0;
1050  for (const Literal lit : literal_reason) {
1051  if (trail_->Info(lit.Variable()).level > 0) {
1052  num_literal_assigned_after_root_node++;
1053  }
1054  }
1055  for (const IntegerLiteral i_lit : integer_reason) {
1056  if (LevelZeroLowerBound(i_lit.var) < i_lit.bound) {
1057  num_literal_assigned_after_root_node++;
1058  }
1059  }
1060  DLOG_IF(INFO, num_literal_assigned_after_root_node == 0)
1061  << "Propagating a literal with no reason at a positive level!\n"
1062  << "level:" << integer_search_levels_.size() << " "
1063  << ReasonDebugString(literal_reason, integer_reason) << "\n"
1064  << DebugString();
1065  }
1066 
1067  return true;
1068 }
1069 
1071  Literal literal, absl::Span<const Literal> literal_reason,
1072  absl::Span<const IntegerLiteral> integer_reason) {
1073  EnqueueLiteralInternal(literal, nullptr, literal_reason, integer_reason);
1074 }
1075 
1076 void IntegerTrail::EnqueueLiteralInternal(
1077  Literal literal, LazyReasonFunction lazy_reason,
1078  absl::Span<const Literal> literal_reason,
1079  absl::Span<const IntegerLiteral> integer_reason) {
1081  DCHECK(lazy_reason != nullptr ||
1082  ReasonIsValid(literal_reason, integer_reason));
1083  if (integer_search_levels_.empty()) {
1084  // Level zero. We don't keep any reason.
1085  trail_->EnqueueWithUnitReason(literal);
1086  return;
1087  }
1088 
1089  // If we are fixing something at a positive level, remember it.
1090  if (!integer_search_levels_.empty() && integer_reason.empty() &&
1091  literal_reason.empty() && lazy_reason == nullptr) {
1092  literal_to_fix_.push_back(literal);
1093  }
1094 
1095  const int trail_index = trail_->Index();
1096  if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1097  boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1098  }
1099  boolean_trail_index_to_integer_one_[trail_index] = integer_trail_.size();
1100 
1101  int reason_index = literals_reason_starts_.size();
1102  if (lazy_reason != nullptr) {
1103  if (integer_trail_.size() >= lazy_reasons_.size()) {
1104  lazy_reasons_.resize(integer_trail_.size() + 1, nullptr);
1105  }
1106  lazy_reasons_[integer_trail_.size()] = lazy_reason;
1107  reason_index = -1;
1108  } else {
1109  // Copy the reason.
1110  literals_reason_starts_.push_back(literals_reason_buffer_.size());
1111  literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1112  literal_reason.begin(),
1113  literal_reason.end());
1114  bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1115  bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1116  integer_reason.begin(), integer_reason.end());
1117  }
1118 
1119  integer_trail_.push_back({/*bound=*/IntegerValue(0),
1120  /*var=*/kNoIntegerVariable,
1121  /*prev_trail_index=*/-1,
1122  /*reason_index=*/reason_index});
1123 
1124  trail_->Enqueue(literal, propagator_id_);
1125 }
1126 
1127 // We count the number of propagation at the current level, and returns true
1128 // if it seems really large. Note that we disable this if we are in fixed
1129 // search.
1131  const int num_vars = vars_.size();
1132  return (!integer_search_levels_.empty() &&
1133  integer_trail_.size() - integer_search_levels_.back() >
1134  std::max(10000, num_vars) &&
1135  parameters_.search_branching() != SatParameters::FIXED_SEARCH);
1136 }
1137 
1138 // We try to select a variable with a large domain that was propagated a lot
1139 // already.
1142  ++num_decisions_to_break_loop_;
1143  std::vector<IntegerVariable> vars;
1144  for (int i = integer_search_levels_.back(); i < integer_trail_.size(); ++i) {
1145  const IntegerVariable var = integer_trail_[i].var;
1146  if (var == kNoIntegerVariable) continue;
1147  if (UpperBound(var) - LowerBound(var) <= 100) continue;
1148  vars.push_back(var);
1149  }
1150  if (vars.empty()) return kNoIntegerVariable;
1151  std::sort(vars.begin(), vars.end());
1152  IntegerVariable best_var = vars[0];
1153  int best_count = 1;
1154  int count = 1;
1155  for (int i = 1; i < vars.size(); ++i) {
1156  if (vars[i] != vars[i - 1]) {
1157  count = 1;
1158  } else {
1159  ++count;
1160  if (count > best_count) {
1161  best_count = count;
1162  best_var = vars[i];
1163  }
1164  }
1165  }
1166  return best_var;
1167 }
1168 
1170  return first_level_without_full_propagation_ != -1;
1171 }
1172 
1173 IntegerVariable IntegerTrail::FirstUnassignedVariable() const {
1174  for (IntegerVariable var(0); var < vars_.size(); var += 2) {
1175  if (IsCurrentlyIgnored(var)) continue;
1176  if (!IsFixed(var)) return var;
1177  }
1178  return kNoIntegerVariable;
1179 }
1180 
1181 bool IntegerTrail::EnqueueInternal(
1182  IntegerLiteral i_lit, LazyReasonFunction lazy_reason,
1183  absl::Span<const Literal> literal_reason,
1184  absl::Span<const IntegerLiteral> integer_reason,
1185  int trail_index_with_same_reason) {
1186  DCHECK(lazy_reason != nullptr ||
1187  ReasonIsValid(literal_reason, integer_reason));
1188 
1189  const IntegerVariable var(i_lit.var);
1190 
1191  // No point doing work if the variable is already ignored.
1192  if (IsCurrentlyIgnored(var)) return true;
1193 
1194  // Nothing to do if the bound is not better than the current one.
1195  // TODO(user): Change this to a CHECK? propagator shouldn't try to push such
1196  // bound and waste time explaining it.
1197  if (i_lit.bound <= vars_[var].current_bound) return true;
1198  ++num_enqueues_;
1199 
1200  // If the domain of var is not a single intervals and i_lit.bound fall into a
1201  // "hole", we increase it to the next possible value. This ensure that we
1202  // never Enqueue() non-canonical literals. See also Canonicalize().
1203  //
1204  // Note: The literals in the reason are not necessarily canonical, but then
1205  // we always map these to enqueued literals during conflict resolution.
1206  if ((*domains_)[var].NumIntervals() > 1) {
1207  const auto& domain = (*domains_)[var];
1208  int index = var_to_current_lb_interval_index_.FindOrDie(var);
1209  const int size = domain.NumIntervals();
1210  while (index < size && i_lit.bound > domain[index].end) {
1211  ++index;
1212  }
1213  if (index == size) {
1214  return ReportConflict(literal_reason, integer_reason);
1215  } else {
1216  var_to_current_lb_interval_index_.Set(var, index);
1217  i_lit.bound = std::max(i_lit.bound, IntegerValue(domain[index].start));
1218  }
1219  }
1220 
1221  // Check if the integer variable has an empty domain.
1222  if (i_lit.bound > UpperBound(var)) {
1223  // We relax the upper bound as much as possible to still have a conflict.
1224  const auto ub_reason = IntegerLiteral::LowerOrEqual(var, i_lit.bound - 1);
1225 
1226  if (!IsOptional(var) || trail_->Assignment().LiteralIsFalse(
1227  Literal(is_ignored_literals_[var]))) {
1228  // Note that we want only one call to MergeReasonIntoInternal() for
1229  // efficiency and a potential smaller reason.
1230  auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1231  integer_reason);
1232  if (IsOptional(var)) {
1233  conflict->push_back(Literal(is_ignored_literals_[var]));
1234  }
1235  {
1236  const int trail_index = FindLowestTrailIndexThatExplainBound(ub_reason);
1237  const int num_vars = vars_.size(); // must be signed.
1238  if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1239  }
1240  MergeReasonIntoInternal(conflict);
1241  return false;
1242  } else {
1243  // Note(user): We never make the bound of an optional literal cross. We
1244  // used to have a bug where we propagated these bounds and their
1245  // associated literals, and we were reaching a conflict while propagating
1246  // the associated literal instead of setting is_ignored below to false.
1247  const Literal is_ignored = Literal(is_ignored_literals_[var]);
1248  if (integer_search_levels_.empty()) {
1249  trail_->EnqueueWithUnitReason(is_ignored);
1250  } else {
1251  // Here we currently expand any lazy reason because we need to add
1252  // to it the reason for the upper bound.
1253  // TODO(user): A possible solution would be to support the two types
1254  // of reason (lazy and not) at the same time and use the union of both?
1255  if (lazy_reason != nullptr) {
1256  lazy_reason(i_lit, integer_trail_.size(), &lazy_reason_literals_,
1257  &lazy_reason_trail_indices_);
1258  std::vector<IntegerLiteral> temp;
1259  for (const int trail_index : lazy_reason_trail_indices_) {
1260  const TrailEntry& entry = integer_trail_[trail_index];
1261  temp.push_back(IntegerLiteral(entry.var, entry.bound));
1262  }
1263  EnqueueLiteral(is_ignored, lazy_reason_literals_, temp);
1264  } else {
1265  EnqueueLiteral(is_ignored, literal_reason, integer_reason);
1266  }
1267 
1268  // Hack, we add the upper bound reason here.
1269  bounds_reason_buffer_.push_back(ub_reason);
1270  }
1271  return true;
1272  }
1273  }
1274 
1275  // Stop propagating if we detect a propagation loop. The search heuristic will
1276  // then take an appropriate next decision. Note that we do that after checking
1277  // for a potential conflict if the two bounds of a variable cross. This is
1278  // important, so that in the corner case where all variables are actually
1279  // fixed, we still make sure no propagator detect a conflict.
1280  //
1281  // TODO(user): Some propagation code have CHECKS in place and not like when
1282  // something they just pushed is not reflected right away. They must be aware
1283  // of that, which is a bit tricky.
1284  if (InPropagationLoop()) {
1285  // Note that we still propagate "big" push as it seems better to do that
1286  // now rather than to delay to the next decision.
1287  const IntegerValue lb = LowerBound(i_lit.var);
1288  const IntegerValue ub = UpperBound(i_lit.var);
1289  if (i_lit.bound - lb < (ub - lb) / 2) {
1290  if (first_level_without_full_propagation_ == -1) {
1291  first_level_without_full_propagation_ = trail_->CurrentDecisionLevel();
1292  }
1293  return true;
1294  }
1295  }
1296 
1297  // Notify the watchers.
1298  for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1299  bitset->Set(i_lit.var);
1300  }
1301 
1302  if (!integer_search_levels_.empty() && integer_reason.empty() &&
1303  literal_reason.empty() && lazy_reason == nullptr &&
1304  trail_index_with_same_reason >= integer_trail_.size()) {
1305  integer_literal_to_fix_.push_back(i_lit);
1306  }
1307 
1308  // Enqueue the strongest associated Boolean literal implied by this one.
1309  // Because we linked all such literal with implications, all the one before
1310  // will be propagated by the SAT solver.
1311  //
1312  // Important: It is possible that such literal or even stronger ones are
1313  // already true! This is because we might push stuff while Propagate() haven't
1314  // been called yet. Maybe we should call it?
1315  //
1316  // TODO(user): It might be simply better and more efficient to simply enqueue
1317  // all of them here. We have also more liberty to choose the explanation we
1318  // want. A drawback might be that the implications might not be used in the
1319  // binary conflict minimization algo.
1320  IntegerValue bound;
1321  const LiteralIndex literal_index =
1322  encoder_->SearchForLiteralAtOrBefore(i_lit, &bound);
1323  if (literal_index != kNoLiteralIndex) {
1324  const Literal to_enqueue = Literal(literal_index);
1325  if (trail_->Assignment().LiteralIsFalse(to_enqueue)) {
1326  auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1327  integer_reason);
1328  conflict->push_back(to_enqueue);
1329  MergeReasonIntoInternal(conflict);
1330  return false;
1331  }
1332 
1333  // If the associated literal exactly correspond to i_lit, then we push
1334  // it first, and then we use it as a reason for i_lit. We do that so that
1335  // MergeReasonIntoInternal() will not unecessarily expand further the reason
1336  // for i_lit.
1337  if (IntegerLiteral::GreaterOrEqual(i_lit.var, bound) == i_lit) {
1338  if (!trail_->Assignment().LiteralIsTrue(to_enqueue)) {
1339  EnqueueLiteralInternal(to_enqueue, lazy_reason, literal_reason,
1340  integer_reason);
1341  }
1342  return EnqueueAssociatedIntegerLiteral(i_lit, to_enqueue);
1343  }
1344 
1345  if (!trail_->Assignment().LiteralIsTrue(to_enqueue)) {
1346  if (integer_search_levels_.empty()) {
1347  trail_->EnqueueWithUnitReason(to_enqueue);
1348  } else {
1349  // Subtle: the reason is the same as i_lit, that we will enqueue if no
1350  // conflict occur at position integer_trail_.size(), so we just refer to
1351  // this index here.
1352  const int trail_index = trail_->Index();
1353  if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1354  boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1355  }
1356  boolean_trail_index_to_integer_one_[trail_index] =
1357  trail_index_with_same_reason;
1358  trail_->Enqueue(to_enqueue, propagator_id_);
1359  }
1360  }
1361  }
1362 
1363  // Special case for level zero.
1364  if (integer_search_levels_.empty()) {
1365  ++num_level_zero_enqueues_;
1366  vars_[i_lit.var].current_bound = i_lit.bound;
1367  integer_trail_[i_lit.var.value()].bound = i_lit.bound;
1368 
1369  // We also update the initial domain. If this fail, since we are at level
1370  // zero, we don't care about the reason.
1371  trail_->MutableConflict()->clear();
1372  return UpdateInitialDomain(
1373  i_lit.var,
1374  Domain(LowerBound(i_lit.var).value(), UpperBound(i_lit.var).value()));
1375  }
1376  DCHECK_GT(trail_->CurrentDecisionLevel(), 0);
1377 
1378  int reason_index = literals_reason_starts_.size();
1379  if (lazy_reason != nullptr) {
1380  if (integer_trail_.size() >= lazy_reasons_.size()) {
1381  lazy_reasons_.resize(integer_trail_.size() + 1, nullptr);
1382  }
1383  lazy_reasons_[integer_trail_.size()] = lazy_reason;
1384  reason_index = -1;
1385  } else if (trail_index_with_same_reason >= integer_trail_.size()) {
1386  // Save the reason into our internal buffers.
1387  literals_reason_starts_.push_back(literals_reason_buffer_.size());
1388  if (!literal_reason.empty()) {
1389  literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1390  literal_reason.begin(),
1391  literal_reason.end());
1392  }
1393  bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1394  if (!integer_reason.empty()) {
1395  bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1396  integer_reason.begin(),
1397  integer_reason.end());
1398  }
1399  } else {
1400  reason_index = integer_trail_[trail_index_with_same_reason].reason_index;
1401  }
1402 
1403  const int prev_trail_index = vars_[i_lit.var].current_trail_index;
1404  integer_trail_.push_back({/*bound=*/i_lit.bound,
1405  /*var=*/i_lit.var,
1406  /*prev_trail_index=*/prev_trail_index,
1407  /*reason_index=*/reason_index});
1408 
1409  vars_[i_lit.var].current_bound = i_lit.bound;
1410  vars_[i_lit.var].current_trail_index = integer_trail_.size() - 1;
1411  return true;
1412 }
1413 
1414 bool IntegerTrail::EnqueueAssociatedIntegerLiteral(IntegerLiteral i_lit,
1415  Literal literal_reason) {
1416  DCHECK(ReasonIsValid({literal_reason.Negated()}, {}));
1417  DCHECK(!IsCurrentlyIgnored(i_lit.var));
1418 
1419  // Nothing to do if the bound is not better than the current one.
1420  if (i_lit.bound <= vars_[i_lit.var].current_bound) return true;
1421  ++num_enqueues_;
1422 
1423  // Check if the integer variable has an empty domain. Note that this should
1424  // happen really rarely since in most situation, pushing the upper bound would
1425  // have resulted in this literal beeing false. Because of this we revert to
1426  // the "generic" Enqueue() to avoid some code duplication.
1427  if (i_lit.bound > UpperBound(i_lit.var)) {
1428  return Enqueue(i_lit, {literal_reason.Negated()}, {});
1429  }
1430 
1431  // Notify the watchers.
1432  for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1433  bitset->Set(i_lit.var);
1434  }
1435 
1436  // Special case for level zero.
1437  if (integer_search_levels_.empty()) {
1438  vars_[i_lit.var].current_bound = i_lit.bound;
1439  integer_trail_[i_lit.var.value()].bound = i_lit.bound;
1440 
1441  // We also update the initial domain. If this fail, since we are at level
1442  // zero, we don't care about the reason.
1443  trail_->MutableConflict()->clear();
1444  return UpdateInitialDomain(
1445  i_lit.var,
1446  Domain(LowerBound(i_lit.var).value(), UpperBound(i_lit.var).value()));
1447  }
1448  DCHECK_GT(trail_->CurrentDecisionLevel(), 0);
1449 
1450  const int reason_index = literals_reason_starts_.size();
1451  CHECK_EQ(reason_index, bounds_reason_starts_.size());
1452  literals_reason_starts_.push_back(literals_reason_buffer_.size());
1453  bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1454  literals_reason_buffer_.push_back(literal_reason.Negated());
1455 
1456  const int prev_trail_index = vars_[i_lit.var].current_trail_index;
1457  integer_trail_.push_back({/*bound=*/i_lit.bound,
1458  /*var=*/i_lit.var,
1459  /*prev_trail_index=*/prev_trail_index,
1460  /*reason_index=*/reason_index});
1461 
1462  vars_[i_lit.var].current_bound = i_lit.bound;
1463  vars_[i_lit.var].current_trail_index = integer_trail_.size() - 1;
1464  return true;
1465 }
1466 
1467 void IntegerTrail::ComputeLazyReasonIfNeeded(int trail_index) const {
1468  const int reason_index = integer_trail_[trail_index].reason_index;
1469  if (reason_index == -1) {
1470  const TrailEntry& entry = integer_trail_[trail_index];
1471  const IntegerLiteral literal(entry.var, entry.bound);
1472  lazy_reasons_[trail_index](literal, trail_index, &lazy_reason_literals_,
1473  &lazy_reason_trail_indices_);
1474  }
1475 }
1476 
1477 absl::Span<const int> IntegerTrail::Dependencies(int trail_index) const {
1478  const int reason_index = integer_trail_[trail_index].reason_index;
1479  if (reason_index == -1) {
1480  return absl::Span<const int>(lazy_reason_trail_indices_);
1481  }
1482 
1483  const int start = bounds_reason_starts_[reason_index];
1484  const int end = reason_index + 1 < bounds_reason_starts_.size()
1485  ? bounds_reason_starts_[reason_index + 1]
1486  : bounds_reason_buffer_.size();
1487  if (start == end) return {};
1488 
1489  // Cache the result if not already computed. Remark, if the result was never
1490  // computed then the span trail_index_reason_buffer_[start, end) will either
1491  // be non-existent or full of -1.
1492  //
1493  // TODO(user): For empty reason, we will always recompute them.
1494  if (end > trail_index_reason_buffer_.size()) {
1495  trail_index_reason_buffer_.resize(end, -1);
1496  }
1497  if (trail_index_reason_buffer_[start] == -1) {
1498  int new_end = start;
1499  const int num_vars = vars_.size();
1500  for (int i = start; i < end; ++i) {
1501  const int dep =
1502  FindLowestTrailIndexThatExplainBound(bounds_reason_buffer_[i]);
1503  if (dep >= num_vars) {
1504  trail_index_reason_buffer_[new_end++] = dep;
1505  }
1506  }
1507  return absl::Span<const int>(&trail_index_reason_buffer_[start],
1508  new_end - start);
1509  } else {
1510  // TODO(user): We didn't store new_end in a previous call, so end might be
1511  // larger. That is a bit annoying since we have to test for -1 while
1512  // iterating.
1513  return absl::Span<const int>(&trail_index_reason_buffer_[start],
1514  end - start);
1515  }
1516 }
1517 
1518 void IntegerTrail::AppendLiteralsReason(int trail_index,
1519  std::vector<Literal>* output) const {
1520  CHECK_GE(trail_index, vars_.size());
1521  const int reason_index = integer_trail_[trail_index].reason_index;
1522  if (reason_index == -1) {
1523  for (const Literal l : lazy_reason_literals_) {
1524  if (!added_variables_[l.Variable()]) {
1525  added_variables_.Set(l.Variable());
1526  output->push_back(l);
1527  }
1528  }
1529  return;
1530  }
1531 
1532  const int start = literals_reason_starts_[reason_index];
1533  const int end = reason_index + 1 < literals_reason_starts_.size()
1534  ? literals_reason_starts_[reason_index + 1]
1535  : literals_reason_buffer_.size();
1536  for (int i = start; i < end; ++i) {
1537  const Literal l = literals_reason_buffer_[i];
1538  if (!added_variables_[l.Variable()]) {
1539  added_variables_.Set(l.Variable());
1540  output->push_back(l);
1541  }
1542  }
1543 }
1544 
1545 std::vector<Literal> IntegerTrail::ReasonFor(IntegerLiteral literal) const {
1546  std::vector<Literal> reason;
1547  MergeReasonInto({literal}, &reason);
1548  return reason;
1549 }
1550 
1551 // TODO(user): If this is called many time on the same variables, it could be
1552 // made faster by using some caching mecanism.
1553 void IntegerTrail::MergeReasonInto(absl::Span<const IntegerLiteral> literals,
1554  std::vector<Literal>* output) const {
1555  DCHECK(tmp_queue_.empty());
1556  const int num_vars = vars_.size();
1557  for (const IntegerLiteral& literal : literals) {
1558  const int trail_index = FindLowestTrailIndexThatExplainBound(literal);
1559 
1560  // Any indices lower than that means that there is no reason needed.
1561  // Note that it is important for size to be signed because of -1 indices.
1562  if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1563  }
1564  return MergeReasonIntoInternal(output);
1565 }
1566 
1567 // This will expand the reason of the IntegerLiteral already in tmp_queue_ until
1568 // everything is explained in term of Literal.
1569 void IntegerTrail::MergeReasonIntoInternal(std::vector<Literal>* output) const {
1570  // All relevant trail indices will be >= vars_.size(), so we can safely use
1571  // zero to means that no literal refering to this variable is in the queue.
1572  DCHECK(std::all_of(tmp_var_to_trail_index_in_queue_.begin(),
1573  tmp_var_to_trail_index_in_queue_.end(),
1574  [](int v) { return v == 0; }));
1575 
1576  added_variables_.ClearAndResize(BooleanVariable(trail_->NumVariables()));
1577  for (const Literal l : *output) {
1578  added_variables_.Set(l.Variable());
1579  }
1580 
1581  // During the algorithm execution, all the queue entries that do not match the
1582  // content of tmp_var_to_trail_index_in_queue_[] will be ignored.
1583  for (const int trail_index : tmp_queue_) {
1584  DCHECK_GE(trail_index, vars_.size());
1585  DCHECK_LT(trail_index, integer_trail_.size());
1586  const TrailEntry& entry = integer_trail_[trail_index];
1587  tmp_var_to_trail_index_in_queue_[entry.var] =
1588  std::max(tmp_var_to_trail_index_in_queue_[entry.var], trail_index);
1589  }
1590 
1591  // We manage our heap by hand so that we can range iterate over it above, and
1592  // this initial heapify is faster.
1593  std::make_heap(tmp_queue_.begin(), tmp_queue_.end());
1594 
1595  // We process the entries by highest trail_index first. The content of the
1596  // queue will always be a valid reason for the literals we already added to
1597  // the output.
1598  tmp_to_clear_.clear();
1599  while (!tmp_queue_.empty()) {
1600  const int trail_index = tmp_queue_.front();
1601  const TrailEntry& entry = integer_trail_[trail_index];
1602  std::pop_heap(tmp_queue_.begin(), tmp_queue_.end());
1603  tmp_queue_.pop_back();
1604 
1605  // Skip any stale queue entry. Amongst all the entry refering to a given
1606  // variable, only the latest added to the queue is valid and we detect it
1607  // using its trail index.
1608  if (tmp_var_to_trail_index_in_queue_[entry.var] != trail_index) {
1609  continue;
1610  }
1611 
1612  // Set the cache threshold. Since we process trail indices in decreasing
1613  // order and we only have single linked list, we only want to advance the
1614  // "cache" up to this threshold.
1615  var_trail_index_cache_threshold_ = trail_index;
1616 
1617  // If this entry has an associated literal, then it should always be the
1618  // one we used for the reason. This code DCHECK that.
1619  if (DEBUG_MODE) {
1620  const LiteralIndex associated_lit =
1622  IntegerVariable(entry.var), entry.bound));
1623  if (associated_lit != kNoLiteralIndex) {
1624  // We check that the reason is the same!
1625  const int reason_index = integer_trail_[trail_index].reason_index;
1626  CHECK_NE(reason_index, -1);
1627  {
1628  const int start = literals_reason_starts_[reason_index];
1629  const int end = reason_index + 1 < literals_reason_starts_.size()
1630  ? literals_reason_starts_[reason_index + 1]
1631  : literals_reason_buffer_.size();
1632  CHECK_EQ(start + 1, end);
1633  CHECK_EQ(literals_reason_buffer_[start],
1634  Literal(associated_lit).Negated());
1635  }
1636  {
1637  const int start = bounds_reason_starts_[reason_index];
1638  const int end = reason_index + 1 < bounds_reason_starts_.size()
1639  ? bounds_reason_starts_[reason_index + 1]
1640  : bounds_reason_buffer_.size();
1641  CHECK_EQ(start, end);
1642  }
1643  }
1644  }
1645 
1646  // Process this entry. Note that if any of the next expansion include the
1647  // variable entry.var in their reason, we must process it again because we
1648  // cannot easily detect if it was needed to infer the current entry.
1649  //
1650  // Important: the queue might already contains entries refering to the same
1651  // variable. The code act like if we deleted all of them at this point, we
1652  // just do that lazily. tmp_var_to_trail_index_in_queue_[var] will
1653  // only refer to newly added entries.
1654  tmp_var_to_trail_index_in_queue_[entry.var] = 0;
1655  has_dependency_ = false;
1656 
1657  ComputeLazyReasonIfNeeded(trail_index);
1658  AppendLiteralsReason(trail_index, output);
1659  for (const int next_trail_index : Dependencies(trail_index)) {
1660  if (next_trail_index < 0) break;
1661  DCHECK_LT(next_trail_index, trail_index);
1662  const TrailEntry& next_entry = integer_trail_[next_trail_index];
1663 
1664  // Only add literals that are not "implied" by the ones already present.
1665  // For instance, do not add (x >= 4) if we already have (x >= 7). This
1666  // translate into only adding a trail index if it is larger than the one
1667  // in the queue refering to the same variable.
1668  const int index_in_queue =
1669  tmp_var_to_trail_index_in_queue_[next_entry.var];
1670  if (index_in_queue != kint32max) has_dependency_ = true;
1671  if (next_trail_index > index_in_queue) {
1672  tmp_var_to_trail_index_in_queue_[next_entry.var] = next_trail_index;
1673  tmp_queue_.push_back(next_trail_index);
1674  std::push_heap(tmp_queue_.begin(), tmp_queue_.end());
1675  }
1676  }
1677 
1678  // Special case for a "leaf", we will never need this variable again.
1679  if (!has_dependency_) {
1680  tmp_to_clear_.push_back(entry.var);
1681  tmp_var_to_trail_index_in_queue_[entry.var] = kint32max;
1682  }
1683  }
1684 
1685  // clean-up.
1686  for (const IntegerVariable var : tmp_to_clear_) {
1687  tmp_var_to_trail_index_in_queue_[var] = 0;
1688  }
1689 }
1690 
1691 absl::Span<const Literal> IntegerTrail::Reason(const Trail& trail,
1692  int trail_index) const {
1693  const int index = boolean_trail_index_to_integer_one_[trail_index];
1694  std::vector<Literal>* reason = trail.GetEmptyVectorToStoreReason(trail_index);
1695  added_variables_.ClearAndResize(BooleanVariable(trail_->NumVariables()));
1696 
1697  ComputeLazyReasonIfNeeded(index);
1698  AppendLiteralsReason(index, reason);
1699  DCHECK(tmp_queue_.empty());
1700  for (const int prev_trail_index : Dependencies(index)) {
1701  if (prev_trail_index < 0) break;
1702  DCHECK_GE(prev_trail_index, vars_.size());
1703  tmp_queue_.push_back(prev_trail_index);
1704  }
1705  MergeReasonIntoInternal(reason);
1706  return *reason;
1707 }
1708 
1709 // TODO(user): Implement a dense version if there is more trail entries
1710 // than variables!
1711 void IntegerTrail::AppendNewBounds(std::vector<IntegerLiteral>* output) const {
1712  tmp_marked_.ClearAndResize(IntegerVariable(vars_.size()));
1713 
1714  // In order to push the best bound for each variable, we loop backward.
1715  const int end = vars_.size();
1716  for (int i = integer_trail_.size(); --i >= end;) {
1717  const TrailEntry& entry = integer_trail_[i];
1718  if (entry.var == kNoIntegerVariable) continue;
1719  if (tmp_marked_[entry.var]) continue;
1720 
1721  tmp_marked_.Set(entry.var);
1722  output->push_back(IntegerLiteral::GreaterOrEqual(entry.var, entry.bound));
1723  }
1724 }
1725 
1727  : SatPropagator("GenericLiteralWatcher"),
1728  time_limit_(model->GetOrCreate<TimeLimit>()),
1729  integer_trail_(model->GetOrCreate<IntegerTrail>()),
1730  rev_int_repository_(model->GetOrCreate<RevIntRepository>()) {
1731  // TODO(user): This propagator currently needs to be last because it is the
1732  // only one enforcing that a fix-point is reached on the integer variables.
1733  // Figure out a better interaction between the sat propagation loop and
1734  // this one.
1735  model->GetOrCreate<SatSolver>()->AddLastPropagator(this);
1736 
1737  integer_trail_->RegisterReversibleClass(
1738  &id_to_greatest_common_level_since_last_call_);
1739  integer_trail_->RegisterWatcher(&modified_vars_);
1740  queue_by_priority_.resize(2); // Because default priority is 1.
1741 }
1742 
1743 void GenericLiteralWatcher::UpdateCallingNeeds(Trail* trail) {
1744  // Process any new Literal on the trail.
1745  while (propagation_trail_index_ < trail->Index()) {
1746  const Literal literal = (*trail)[propagation_trail_index_++];
1747  if (literal.Index() >= literal_to_watcher_.size()) continue;
1748  for (const auto entry : literal_to_watcher_[literal.Index()]) {
1749  if (!in_queue_[entry.id]) {
1750  in_queue_[entry.id] = true;
1751  queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1752  }
1753  if (entry.watch_index >= 0) {
1754  id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1755  }
1756  }
1757  }
1758 
1759  // Process the newly changed variables lower bounds.
1760  for (const IntegerVariable var : modified_vars_.PositionsSetAtLeastOnce()) {
1761  if (var.value() >= var_to_watcher_.size()) continue;
1762  for (const auto entry : var_to_watcher_[var]) {
1763  if (!in_queue_[entry.id]) {
1764  in_queue_[entry.id] = true;
1765  queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1766  }
1767  if (entry.watch_index >= 0) {
1768  id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1769  }
1770  }
1771  }
1772 
1773  if (trail->CurrentDecisionLevel() == 0) {
1774  const std::vector<IntegerVariable>& modified_vars =
1775  modified_vars_.PositionsSetAtLeastOnce();
1776  for (const auto& callback : level_zero_modified_variable_callback_) {
1777  callback(modified_vars);
1778  }
1779  }
1780 
1781  modified_vars_.ClearAndResize(integer_trail_->NumIntegerVariables());
1782 }
1783 
1785  // Only once per call to Propagate(), if we are at level zero, we might want
1786  // to call propagators even if the bounds didn't change.
1787  const int level = trail->CurrentDecisionLevel();
1788  if (level == 0) {
1789  for (const int id : propagator_ids_to_call_at_level_zero_) {
1790  if (in_queue_[id]) continue;
1791  in_queue_[id] = true;
1792  queue_by_priority_[id_to_priority_[id]].push_back(id);
1793  }
1794  }
1795 
1796  UpdateCallingNeeds(trail);
1797 
1798  // Note that the priority may be set to -1 inside the loop in order to restart
1799  // at zero.
1800  int test_limit = 0;
1801  for (int priority = 0; priority < queue_by_priority_.size(); ++priority) {
1802  // We test the time limit from time to time. This is in order to return in
1803  // case of slow propagation.
1804  //
1805  // TODO(user): The queue will not be emptied, but I am not sure the solver
1806  // will be left in an usable state. Fix if it become needed to resume
1807  // the solve from the last time it was interupted.
1808  if (test_limit > 100) {
1809  test_limit = 0;
1810  if (time_limit_->LimitReached()) break;
1811  }
1812 
1813  std::deque<int>& queue = queue_by_priority_[priority];
1814  while (!queue.empty()) {
1815  const int id = queue.front();
1816  current_id_ = id;
1817  queue.pop_front();
1818 
1819  // Before we propagate, make sure any reversible structure are up to date.
1820  // Note that we never do anything expensive more than once per level.
1821  {
1822  const int low =
1823  id_to_greatest_common_level_since_last_call_[IdType(id)];
1824  const int high = id_to_level_at_last_call_[id];
1825  if (low < high || level > low) { // Equivalent to not all equal.
1826  id_to_level_at_last_call_[id] = level;
1827  id_to_greatest_common_level_since_last_call_.MutableRef(IdType(id)) =
1828  level;
1829  for (ReversibleInterface* rev : id_to_reversible_classes_[id]) {
1830  if (low < high) rev->SetLevel(low);
1831  if (level > low) rev->SetLevel(level);
1832  }
1833  for (int* rev_int : id_to_reversible_ints_[id]) {
1834  rev_int_repository_->SaveState(rev_int);
1835  }
1836  }
1837  }
1838 
1839  // This is needed to detect if the propagator propagated anything or not.
1840  const int64 old_integer_timestamp = integer_trail_->num_enqueues();
1841  const int64 old_boolean_timestamp = trail->Index();
1842 
1843  // TODO(user): Maybe just provide one function Propagate(watch_indices) ?
1844  std::vector<int>& watch_indices_ref = id_to_watch_indices_[id];
1845  const bool result =
1846  watch_indices_ref.empty()
1847  ? watchers_[id]->Propagate()
1848  : watchers_[id]->IncrementalPropagate(watch_indices_ref);
1849  if (!result) {
1850  watch_indices_ref.clear();
1851  in_queue_[id] = false;
1852  return false;
1853  }
1854 
1855  // Update the propagation queue. At this point, the propagator has been
1856  // removed from the queue but in_queue_ is still true.
1857  if (id_to_idempotence_[id]) {
1858  // If the propagator is assumed to be idempotent, then we set in_queue_
1859  // to false after UpdateCallingNeeds() so this later function will never
1860  // add it back.
1861  UpdateCallingNeeds(trail);
1862  watch_indices_ref.clear();
1863  in_queue_[id] = false;
1864  } else {
1865  // Otherwise, we set in_queue_ to false first so that
1866  // UpdateCallingNeeds() may add it back if the propagator modified any
1867  // of its watched variables.
1868  watch_indices_ref.clear();
1869  in_queue_[id] = false;
1870  UpdateCallingNeeds(trail);
1871  }
1872 
1873  // If the propagator pushed a literal, we exit in order to rerun all SAT
1874  // only propagators first. Note that since a literal was pushed we are
1875  // guaranteed to be called again, and we will resume from priority 0.
1876  if (trail->Index() > old_boolean_timestamp) {
1877  // Important: for now we need to re-run the clauses propagator each time
1878  // we push a new literal because some propagator like the arc consistent
1879  // all diff relies on this.
1880  //
1881  // TODO(user): However, on some problem, it seems to work better to not
1882  // do that. One possible reason is that the reason of a "natural"
1883  // propagation might be better than one we learned.
1884  return true;
1885  }
1886 
1887  // If the propagator pushed an integer bound, we revert to priority = 0.
1888  if (integer_trail_->num_enqueues() > old_integer_timestamp) {
1889  ++test_limit;
1890  priority = -1; // Because of the ++priority in the for loop.
1891  break;
1892  }
1893  }
1894  }
1895  return true;
1896 }
1897 
1898 void GenericLiteralWatcher::Untrail(const Trail& trail, int trail_index) {
1899  if (propagation_trail_index_ <= trail_index) {
1900  // Nothing to do since we found a conflict before Propagate() was called.
1901  CHECK_EQ(propagation_trail_index_, trail_index);
1902  return;
1903  }
1904 
1905  // We need to clear the watch indices on untrail.
1906  for (std::deque<int>& queue : queue_by_priority_) {
1907  for (const int id : queue) {
1908  id_to_watch_indices_[id].clear();
1909  }
1910  queue.clear();
1911  }
1912 
1913  // This means that we already propagated all there is to propagate
1914  // at the level trail_index, so we can safely clear modified_vars_ in case
1915  // it wasn't already done.
1916  propagation_trail_index_ = trail_index;
1917  modified_vars_.ClearAndResize(integer_trail_->NumIntegerVariables());
1918  in_queue_.assign(watchers_.size(), false);
1919 }
1920 
1921 // Registers a propagator and returns its unique ids.
1923  const int id = watchers_.size();
1924  watchers_.push_back(propagator);
1925  id_to_level_at_last_call_.push_back(0);
1926  id_to_greatest_common_level_since_last_call_.GrowByOne();
1927  id_to_reversible_classes_.push_back(std::vector<ReversibleInterface*>());
1928  id_to_reversible_ints_.push_back(std::vector<int*>());
1929  id_to_watch_indices_.push_back(std::vector<int>());
1930  id_to_priority_.push_back(1);
1931  id_to_idempotence_.push_back(true);
1932 
1933  // Call this propagator at least once the next time Propagate() is called.
1934  //
1935  // TODO(user): This initial propagation does not respect any later priority
1936  // settings. Fix this. Maybe we should force users to pass the priority at
1937  // registration. For now I didn't want to change the interface because there
1938  // are plans to implement a kind of "dynamic" priority, and if it works we may
1939  // want to get rid of this altogether.
1940  in_queue_.push_back(true);
1941  queue_by_priority_[1].push_back(id);
1942  return id;
1943 }
1944 
1946  id_to_priority_[id] = priority;
1947  if (priority >= queue_by_priority_.size()) {
1948  queue_by_priority_.resize(priority + 1);
1949  }
1950 }
1951 
1953  int id) {
1954  id_to_idempotence_[id] = false;
1955 }
1956 
1958  propagator_ids_to_call_at_level_zero_.push_back(id);
1959 }
1960 
1962  ReversibleInterface* rev) {
1963  id_to_reversible_classes_[id].push_back(rev);
1964 }
1965 
1967  id_to_reversible_ints_[id].push_back(rev);
1968 }
1969 
1970 // This is really close to ExcludeCurrentSolutionAndBacktrack().
1971 std::function<void(Model*)>
1973  return [=](Model* model) {
1974  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1975  IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
1976  IntegerEncoder* encoder = model->GetOrCreate<IntegerEncoder>();
1977 
1978  const int current_level = sat_solver->CurrentDecisionLevel();
1979  std::vector<Literal> clause_to_exclude_solution;
1980  clause_to_exclude_solution.reserve(current_level);
1981  for (int i = 0; i < current_level; ++i) {
1982  bool include_decision = true;
1983  const Literal decision = sat_solver->Decisions()[i].literal;
1984 
1985  // Tests if this decision is associated to a bound of an ignored variable
1986  // in the current assignment.
1987  const InlinedIntegerLiteralVector& associated_literals =
1988  encoder->GetIntegerLiterals(decision);
1989  for (const IntegerLiteral bound : associated_literals) {
1990  if (integer_trail->IsCurrentlyIgnored(bound.var)) {
1991  // In this case we replace the decision (which is a bound on an
1992  // ignored variable) with the fact that the integer variable was
1993  // ignored. This works because the only impact a bound of an ignored
1994  // variable can have on the rest of the model is through the
1995  // is_ignored literal.
1996  clause_to_exclude_solution.push_back(
1997  integer_trail->IsIgnoredLiteral(bound.var).Negated());
1998  include_decision = false;
1999  }
2000  }
2001 
2002  if (include_decision) {
2003  clause_to_exclude_solution.push_back(decision.Negated());
2004  }
2005  }
2006 
2007  // Note that it is okay to add duplicates literals in ClauseConstraint(),
2008  // the clause will be preprocessed correctly.
2009  sat_solver->Backtrack(0);
2010  model->Add(ClauseConstraint(clause_to_exclude_solution));
2011  };
2012 }
2013 
2014 } // namespace sat
2015 } // namespace operations_research
var
IntVar * var
Definition: expr_array.cc:1858
operations_research::sat::IntegerEncoder::ValueLiteralPair::literal
Literal literal
Definition: integer.h:311
operations_research::sat::IntegerEncoder::GetOrCreateAssociatedLiteral
Literal GetOrCreateAssociatedLiteral(IntegerLiteral i_lit)
Definition: integer.cc:217
operations_research::sat::IntegerLiteral::DebugString
std::string DebugString() const
Definition: integer.h:182
INFO
const int INFO
Definition: log_severity.h:31
operations_research::sat::AffineExpression::constant
IntegerValue constant
Definition: integer.h:229
operations_research::sat::GenericLiteralWatcher::Register
int Register(PropagatorInterface *propagator)
Definition: integer.cc:1922
min
int64 min
Definition: alldiff_cst.cc:138
operations_research::sat::IntegerEncoder::PartialDomainEncoding
std::vector< ValueLiteralPair > PartialDomainEncoding(IntegerVariable var) const
Definition: integer.cc:127
operations_research::sat::IntegerTrail::AppendNewBounds
void AppendNewBounds(std::vector< IntegerLiteral > *output) const
Definition: integer.cc:1711
DCHECK_LT
#define DCHECK_LT(val1, val2)
Definition: base/logging.h:888
operations_research::sat::Trail::EnqueueWithUnitReason
void EnqueueWithUnitReason(Literal true_literal)
Definition: sat_base.h:265
operations_research::sat::IntegerTrail::~IntegerTrail
~IntegerTrail() final
Definition: integer.cc:488
operations_research::sat::IntegerTrail
Definition: integer.h:518
VLOG
#define VLOG(verboselevel)
Definition: base/logging.h:978
operations_research::sat::kNoIntegerVariable
const IntegerVariable kNoIntegerVariable(-1)
operations_research::sat::FloorRatio
IntegerValue FloorRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition: integer.h:90
operations_research::sat::VariableIsPositive
bool VariableIsPositive(IntegerVariable i)
Definition: integer.h:130
max
int64 max
Definition: alldiff_cst.cc:139
time_limit.h
operations_research::SparseBitset::ClearAndResize
void ClearAndResize(IntegerType size)
Definition: bitset.h:780
bound
int64 bound
Definition: routing_search.cc:969
operations_research::sat::IntegerEncoder::GetIntegerLiterals
const InlinedIntegerLiteralVector & GetIntegerLiterals(Literal lit) const
Definition: integer.h:376
LOG
#define LOG(severity)
Definition: base/logging.h:420
operations_research::CapProd
int64 CapProd(int64 x, int64 y)
Definition: saturated_arithmetic.h:231
operations_research::Domain::Contains
bool Contains(int64 value) const
Returns true iff value is in Domain.
Definition: sorted_interval_list.cc:221
operations_research::sat::SatSolver::Assignment
const VariablesAssignment & Assignment() const
Definition: sat_solver.h:363
operations_research::sat::kNoLiteralIndex
const LiteralIndex kNoLiteralIndex(-1)
operations_research::sat::CeilRatio
IntegerValue CeilRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition: integer.h:81
operations_research::sat::SatSolver::AddBinaryClause
bool AddBinaryClause(Literal a, Literal b)
Definition: sat_solver.cc:180
operations_research::sat::GetPositiveOnlyIndex
PositiveOnlyIndex GetPositiveOnlyIndex(IntegerVariable var)
Definition: integer.h:140
operations_research::sat::GenericLiteralWatcher::RegisterReversibleClass
void RegisterReversibleClass(int id, ReversibleInterface *rev)
Definition: integer.cc:1961
operations_research::sat::RevIntRepository
Definition: integer.h:1058
operations_research::sat::IntegerTrail::LevelZeroLowerBound
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
Definition: integer.h:1286
CHECK_GE
#define CHECK_GE(val1, val2)
Definition: base/logging.h:701
operations_research::sat::Trail::Info
const AssignmentInfo & Info(BooleanVariable var) const
Definition: sat_base.h:381
operations_research::sat::PropagatorInterface
Definition: integer.h:1027
gtl::ITIVector::push_back
void push_back(const value_type &x)
Definition: int_type_indexed_vector.h:157
operations_research::sat::SatSolver
Definition: sat_solver.h:58
operations_research::sat::IntegerEncoder::ClearNewlyFixedIntegerLiterals
void ClearNewlyFixedIntegerLiterals()
Definition: integer.h:398
operations_research::RevVector::GrowByOne
void GrowByOne()
Definition: rev.h:108
operations_research::Domain::IsEmpty
bool IsEmpty() const
Returns true if this is the empty set.
Definition: sorted_interval_list.cc:190
operations_research::sat::GenericLiteralWatcher::RegisterReversibleInt
void RegisterReversibleInt(int id, int *rev)
Definition: integer.cc:1966
DCHECK_GT
#define DCHECK_GT(val1, val2)
Definition: base/logging.h:890
operations_research::sat::AffineExpression::coeff
IntegerValue coeff
Definition: integer.h:228
value
int64 value
Definition: demon_profiler.cc:43
operations_research::sat::IntegerTrail::Propagate
bool Propagate(Trail *trail) final
Definition: integer.cc:495
CHECK_GT
#define CHECK_GT(val1, val2)
Definition: base/logging.h:702
gtl::ITIVector::begin
iterator begin()
Definition: int_type_indexed_vector.h:137
CHECK_LT
#define CHECK_LT(val1, val2)
Definition: base/logging.h:700
operations_research::sat::SatSolver::Decisions
const std::vector< Decision > & Decisions() const
Definition: sat_solver.h:360
operations_research::sat::SatSolver::AddClauseDuringSearch
bool AddClauseDuringSearch(absl::Span< const Literal > literals)
Definition: sat_solver.cc:134
operations_research
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...
Definition: dense_doubly_linked_list.h:21
operations_research::sat::IntegerTrail::EnqueueLiteral
void EnqueueLiteral(Literal literal, absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.cc:1070
operations_research::sat::NegationOf
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Definition: integer.cc:42
operations_research::sat::VariablesAssignment::LiteralIsTrue
bool LiteralIsTrue(Literal literal) const
Definition: sat_base.h:150
operations_research::sat::IntegerTrail::InPropagationLoop
bool InPropagationLoop() const
Definition: integer.cc:1130
operations_research::RevVector::MutableRef
T & MutableRef(IndexType index)
Definition: rev.h:95
kint64min
static const int64 kint64min
Definition: integral_types.h:60
operations_research::sat::IntegerLiteral::GreaterOrEqual
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1216
operations_research::sat::IntegerTrail::FirstUnassignedVariable
IntegerVariable FirstUnassignedVariable() const
Definition: integer.cc:1173
operations_research::sat::SatPropagator::propagation_trail_index_
int propagation_trail_index_
Definition: sat_base.h:506
operations_research::Domain
We call domain any subset of Int64 = [kint64min, kint64max].
Definition: sorted_interval_list.h:81
operations_research::sat::PositiveVariable
IntegerVariable PositiveVariable(IntegerVariable i)
Definition: integer.h:134
int64
int64_t int64
Definition: integral_types.h:34
operations_research::sat::Literal::Negated
Literal Negated() const
Definition: sat_base.h:91
operations_research::Domain::IntersectionWith
Domain IntersectionWith(const Domain &domain) const
Returns the intersection of D and domain.
Definition: sorted_interval_list.cc:282
operations_research::TimeLimit
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
Definition: time_limit.h:105
operations_research::sat::IntegerTrail::Reason
absl::Span< const Literal > Reason(const Trail &trail, int trail_index) const final
Definition: integer.cc:1691
operations_research::Domain::end
absl::InlinedVector< ClosedInterval, 1 >::const_iterator end() const
Definition: sorted_interval_list.h:343
index
int index
Definition: pack.cc:508
operations_research::sat::SatPropagator::propagator_id_
int propagator_id_
Definition: sat_base.h:505
operations_research::sat::IntegerTrail::UpdateInitialDomain
bool UpdateInitialDomain(IntegerVariable var, Domain domain)
Definition: integer.cc:660
operations_research::sat::GenericLiteralWatcher::GenericLiteralWatcher
GenericLiteralWatcher(Model *model)
Definition: integer.cc:1726
operations_research::sat::IntegerEncoder::AddAllImplicationsBetweenAssociatedLiterals
void AddAllImplicationsBetweenAssociatedLiterals()
Definition: integer.cc:183
operations_research::sat::Trail::Index
int Index() const
Definition: sat_base.h:378
operations_research::sat::IntegerTrail::NumIntegerVariables
IntegerVariable NumIntegerVariables() const
Definition: integer.h:543
operations_research::sat::IntegerEncoder::AssociateToIntegerLiteral
void AssociateToIntegerLiteral(Literal literal, IntegerLiteral i_lit)
Definition: integer.cc:297
operations_research::SparseBitset::Set
void Set(IntegerType index)
Definition: bitset.h:805
operations_research::ClosedInterval
Represents a closed interval [start, end].
Definition: sorted_interval_list.h:33
operations_research::sat::IntegerLiteral::var
IntegerVariable var
Definition: integer.h:189
operations_research::sat::SatSolver::CurrentDecisionLevel
int CurrentDecisionLevel() const
Definition: sat_solver.h:361
DEBUG_MODE
const bool DEBUG_MODE
Definition: macros.h:24
gtl::ITIVector::end
iterator end()
Definition: int_type_indexed_vector.h:139
a
int64 a
Definition: constraint_solver/table.cc:42
operations_research::sat::SatSolver::AddUnitClause
bool AddUnitClause(Literal true_literal)
Definition: sat_solver.cc:164
operations_research::sat::IntegerTrail::AppendRelaxedLinearReason
void AppendRelaxedLinearReason(IntegerValue slack, absl::Span< const IntegerValue > coeffs, absl::Span< const IntegerVariable > vars, std::vector< IntegerLiteral > *reason) const
Definition: integer.cc:819
operations_research::SparseBitset< IntegerVariable >
operations_research::sat::IntegerEncoder::FullDomainEncoding
std::vector< ValueLiteralPair > FullDomainEncoding(IntegerVariable var) const
Definition: integer.cc:121
kint32max
static const int32 kint32max
Definition: integral_types.h:59
operations_research::sat::GenericLiteralWatcher::SetPropagatorPriority
void SetPropagatorPriority(int id, int priority)
Definition: integer.cc:1945
operations_research::sat::IntegerTrail::RegisterWatcher
void RegisterWatcher(SparseBitset< IntegerVariable > *p)
Definition: integer.h:771
operations_research::sat::IntegerTrail::UpperBound
IntegerValue UpperBound(IntegerVariable i) const
Definition: integer.h:1240
operations_research::sat::IntegerTrail::Enqueue
ABSL_MUST_USE_RESULT bool Enqueue(IntegerLiteral i_lit, absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.cc:1001
operations_research::sat::IntegerEncoder::GetOrCreateLiteralAssociatedToEquality
Literal GetOrCreateLiteralAssociatedToEquality(IntegerVariable var, IntegerValue value)
Definition: integer.cc:263
operations_research::sat::GenericLiteralWatcher::NotifyThatPropagatorMayNotReachFixedPointInOnePass
void NotifyThatPropagatorMayNotReachFixedPointInOnePass(int id)
Definition: integer.cc:1952
operations_research::sat::IntegerTrail::InitialVariableDomain
const Domain & InitialVariableDomain(IntegerVariable var) const
Definition: integer.cc:656
operations_research::sat::kMaxIntegerValue
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
operations_research::sat::IntegerEncoder::Canonicalize
std::pair< IntegerLiteral, IntegerLiteral > Canonicalize(IntegerLiteral i_lit) const
Definition: integer.cc:199
operations_research::sat::Trail::Assignment
const VariablesAssignment & Assignment() const
Definition: sat_base.h:380
operations_research::sat::IntegerTrail::IsIgnoredLiteral
Literal IsIgnoredLiteral(IntegerVariable i) const
Definition: integer.h:608
CHECK_EQ
#define CHECK_EQ(val1, val2)
Definition: base/logging.h:697
representative
ColIndex representative
Definition: preprocessor.cc:424
operations_research::SparseBitset::PositionsSetAtLeastOnce
const std::vector< IntegerType > & PositionsSetAtLeastOnce() const
Definition: bitset.h:815
operations_research::sat::IntegerEncoder::AssociateToIntegerEqualValue
void AssociateToIntegerEqualValue(Literal literal, IntegerVariable var, IntegerValue value)
Definition: integer.cc:323
operations_research::RevMap::FindOrDie
const mapped_type & FindOrDie(key_type key) const
Definition: rev.h:172
operations_research::sat::Literal::Index
LiteralIndex Index() const
Definition: sat_base.h:84
operations_research::sat::IntegerTrail::RegisterReversibleClass
void RegisterReversibleClass(ReversibleInterface *rev)
Definition: integer.h:801
operations_research::sat::Model
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
operations_research::sat::IntegerEncoder::GetAssociatedEqualityLiteral
LiteralIndex GetAssociatedEqualityLiteral(IntegerVariable var, IntegerValue value) const
Definition: integer.cc:253
operations_research::sat::IntegerLiteral::bound
IntegerValue bound
Definition: integer.h:190
operations_research::sat::IntegerTrail::ReserveSpaceForNumVariables
void ReserveSpaceForNumVariables(int num_vars)
Definition: integer.cc:604
operations_research::sat::IntegerTrail::ReasonFor
std::vector< Literal > ReasonFor(IntegerLiteral literal) const
Definition: integer.cc:1545
operations_research::sat::IntegerEncoder::SearchForLiteralAtOrBefore
LiteralIndex SearchForLiteralAtOrBefore(IntegerLiteral i, IntegerValue *bound) const
Definition: integer.cc:475
operations_research::sat::AffineExpression::GreaterOrEqual
IntegerLiteral GreaterOrEqual(IntegerValue bound) const
Definition: integer.cc:28
operations_research::sat::IntegerLiteral
Definition: integer.h:153
DCHECK
#define DCHECK(condition)
Definition: base/logging.h:884
operations_research::sat::AffineExpression::LowerOrEqual
IntegerLiteral LowerOrEqual(IntegerValue bound) const
Definition: integer.cc:36
operations_research::sat::IntegerLiteral::LowerOrEqual
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1222
CHECK_LE
#define CHECK_LE(val1, val2)
Definition: base/logging.h:699
operations_research::Domain::Min
int64 Min() const
Returns the min value of the domain.
Definition: sorted_interval_list.cc:206
operations_research::sat::ExcludeCurrentSolutionWithoutIgnoredVariableAndBacktrack
std::function< void(Model *)> ExcludeCurrentSolutionWithoutIgnoredVariableAndBacktrack()
Definition: integer.cc:1972
operations_research::sat::Trail::MutableConflict
std::vector< Literal > * MutableConflict()
Definition: sat_base.h:361
operations_research::sat::IntegerTrail::Index
int Index() const
Definition: integer.h:805
gtl::ITIVector::size
size_type size() const
Definition: int_type_indexed_vector.h:146
operations_research::sat::ClauseConstraint
std::function< void(Model *)> ClauseConstraint(absl::Span< const Literal > literals)
Definition: sat_solver.h:899
callback
MPCallback * callback
Definition: gurobi_interface.cc:510
DCHECK_GE
#define DCHECK_GE(val1, val2)
Definition: base/logging.h:889
model
GRBmodel * model
Definition: gurobi_interface.cc:269
gtl::ITIVector::reserve
void reserve(size_type n)
Definition: int_type_indexed_vector.h:156
operations_research::sat::Trail::CurrentDecisionLevel
int CurrentDecisionLevel() const
Definition: sat_base.h:355
operations_research::sat::Literal
Definition: sat_base.h:64
operations_research::sat::IntegerTrail::NumConstantVariables
int NumConstantVariables() const
Definition: integer.cc:722
operations_research::sat::IntegerTrail::RemoveLevelZeroBounds
void RemoveLevelZeroBounds(std::vector< IntegerLiteral > *reason) const
Definition: integer.cc:931
operations_research::sat::AssignmentInfo::level
uint32 level
Definition: sat_base.h:199
operations_research::sat::IntegerTrail::NextVariableToBranchOnInPropagationLoop
IntegerVariable NextVariableToBranchOnInPropagationLoop() const
Definition: integer.cc:1140
operations_research::sat::IntegerEncoder::GetTrueLiteral
Literal GetTrueLiteral()
Definition: integer.h:423
operations_research::sat::IntegerEncoder::ValueLiteralPair
Definition: integer.h:302
operations_research::sat::IntegerTrail::ReportConflict
bool ReportConflict(absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.h:778
operations_research::ReversibleInterface
Definition: rev.h:29
operations_research::sat::kMinIntegerValue
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
stl_util.h
gtl::InsertOrDie
void InsertOrDie(Collection *const collection, const typename Collection::value_type &value)
Definition: map_util.h:135
iterator_adaptors.h
operations_research::sat::IntegerTrail::Untrail
void Untrail(const Trail &trail, int literal_trail_index) final
Definition: integer.cc:558
operations_research::sat::IntegerTrail::RelaxLinearReason
void RelaxLinearReason(IntegerValue slack, absl::Span< const IntegerValue > coeffs, std::vector< IntegerLiteral > *reason) const
Definition: integer.cc:797
operations_research::sat::IntegerEncoder::LiteralIsAssociated
bool LiteralIsAssociated(IntegerLiteral i_lit) const
Definition: integer.cc:461
operations_research::sat::SatSolver::Backtrack
void Backtrack(int target_level)
Definition: sat_solver.cc:888
operations_research::sat::Trail::Enqueue
void Enqueue(Literal true_literal, int propagator_id)
Definition: sat_base.h:250
DCHECK_EQ
#define DCHECK_EQ(val1, val2)
Definition: base/logging.h:885
operations_research::sat::GenericLiteralWatcher::Untrail
void Untrail(const Trail &trail, int literal_trail_index) final
Definition: integer.cc:1898
operations_research::sat::IntegerTrail::FindTrailIndexOfVarBefore
int FindTrailIndexOfVarBefore(IntegerVariable var, int threshold) const
Definition: integer.cc:728
operations_research::sat::IntegerTrail::GetOrCreateConstantIntegerVariable
IntegerVariable GetOrCreateConstantIntegerVariable(IntegerValue value)
Definition: integer.cc:707
operations_research::sat::IntegerTrail::IsFixed
bool IsFixed(IntegerVariable i) const
Definition: integer.h:1244
b
int64 b
Definition: constraint_solver/table.cc:43
operations_research::sat::GenericLiteralWatcher::AlwaysCallAtLevelZero
void AlwaysCallAtLevelZero(int id)
Definition: integer.cc:1957
operations_research::sat::IntegerTrail::MergeReasonInto
void MergeReasonInto(absl::Span< const IntegerLiteral > literals, std::vector< Literal > *output) const
Definition: integer.cc:1553
operations_research::RevMap::SetLevel
void SetLevel(int level) final
Definition: rev.h:206
gtl::ITIVector::resize
void resize(size_type new_size)
Definition: int_type_indexed_vector.h:149
operations_research::Domain::Negation
Domain Negation() const
Returns {x ∈ Int64, ∃ e ∈ D, x = -e}.
Definition: sorted_interval_list.cc:261
operations_research::sat::AffineExpression::var
IntegerVariable var
Definition: integer.h:227
interval
IntervalVar * interval
Definition: resource.cc:98
operations_research::sat::IntegerTrail::LowerBound
IntegerValue LowerBound(IntegerVariable i) const
Definition: integer.h:1236
operations_research::sat::IntegerEncoder::GetAssociatedLiteral
LiteralIndex GetAssociatedLiteral(IntegerLiteral i_lit) const
Definition: integer.cc:467
operations_research::sat::IntegerTrail::LazyReasonFunction
std::function< void(IntegerLiteral literal_to_explain, int trail_index_of_literal, std::vector< Literal > *literals, std::vector< int > *dependencies)> LazyReasonFunction
Definition: integer.h:737
DLOG_IF
#define DLOG_IF(severity, condition)
Definition: base/logging.h:877
operations_research::glop::Index
int32 Index
Definition: lp_types.h:37
CHECK_NE
#define CHECK_NE(val1, val2)
Definition: base/logging.h:698
operations_research::sat::IntegerTrail::num_enqueues
int64 num_enqueues() const
Definition: integer.h:762
operations_research::sat::IntegerTrail::IsCurrentlyIgnored
bool IsCurrentlyIgnored(IntegerVariable i) const
Definition: integer.h:603
literal
Literal literal
Definition: optimization.cc:84
operations_research::sat::VariablesAssignment
Definition: sat_base.h:122
operations_research::sat::GenericLiteralWatcher::Propagate
bool Propagate(Trail *trail) final
Definition: integer.cc:1784
DCHECK_LE
#define DCHECK_LE(val1, val2)
Definition: base/logging.h:887
operations_research::sat::IntegerEncoder::GetFalseLiteral
Literal GetFalseLiteral()
Definition: integer.h:433
operations_research::TimeLimit::LimitReached
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
Definition: time_limit.h:532
operations_research::Domain::Max
int64 Max() const
Returns the max value of the domain.
Definition: sorted_interval_list.cc:211
operations_research::sat::IntegerEncoder::NewlyFixedIntegerLiterals
const std::vector< IntegerLiteral > NewlyFixedIntegerLiterals() const
Definition: integer.h:395
operations_research::sat::Trail::NumVariables
int NumVariables() const
Definition: sat_base.h:376
operations_research::sat::IntegerTrail::IsOptional
bool IsOptional(IntegerVariable i) const
Definition: integer.h:600
operations_research::sat::SatSolver::NewBooleanVariable
BooleanVariable NewBooleanVariable()
Definition: sat_solver.h:84
operations_research::RevRepository::SaveState
void SaveState(T *object)
Definition: rev.h:61
CHECK
#define CHECK(condition)
Definition: base/logging.h:495
operations_research::sat::SatPropagator
Definition: sat_base.h:444
operations_research::sat::InlinedIntegerLiteralVector
absl::InlinedVector< IntegerLiteral, 2 > InlinedIntegerLiteralVector
Definition: integer.h:198
operations_research::sat::IntegerEncoder
Definition: integer.h:262
operations_research::sat::VariablesAssignment::LiteralIsAssigned
bool LiteralIsAssigned(Literal literal) const
Definition: sat_base.h:153
integer.h
operations_research::sat::VariablesAssignment::LiteralIsFalse
bool LiteralIsFalse(Literal literal) const
Definition: sat_base.h:147
operations_research::sat::IntegerTrail::AddIntegerVariable
IntegerVariable AddIntegerVariable()
Definition: integer.h:591
operations_research::RevMap::Set
void Set(key_type key, mapped_type value)
Definition: rev.h:238
operations_research::sat::Trail
Definition: sat_base.h:233
operations_research::sat::IntegerEncoder::FullyEncodeVariable
void FullyEncodeVariable(IntegerVariable var)
Definition: integer.cc:51
operations_research::sat::IntegerEncoder::VariableIsFullyEncoded
bool VariableIsFullyEncoded(IntegerVariable var) const
Definition: integer.cc:83
kint64max
static const int64 kint64max
Definition: integral_types.h:62
operations_research::Domain::NumIntervals
int NumIntervals() const
Basic read-only std::vector<> wrapping to view a Domain as a sorted list of non-adjacent intervals.
Definition: sorted_interval_list.h:336
operations_research::sat::IntegerTrail::CurrentBranchHadAnIncompletePropagation
bool CurrentBranchHadAnIncompletePropagation()
Definition: integer.cc:1169
operations_research::sat::Trail::GetEmptyVectorToStoreReason
std::vector< Literal > * GetEmptyVectorToStoreReason(int trail_index) const
Definition: sat_base.h:320