OR-Tools  8.0
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.
29  CHECK_NE(var, kNoIntegerVariable);
30  CHECK_GT(coeff, 0);
33 }
34 
35 // var * coeff + constant <= bound.
37  CHECK_NE(var, kNoIntegerVariable);
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 {
122  CHECK(VariableIsFullyEncoded(var));
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  const int level = trail->CurrentDecisionLevel();
490  for (ReversibleInterface* rev : reversible_classes_) rev->SetLevel(level);
491 
492  // Make sure that our internal "integer_search_levels_" size matches the
493  // sat decision levels. At the level zero, integer_search_levels_ should
494  // be empty.
495  if (level > integer_search_levels_.size()) {
496  integer_search_levels_.push_back(integer_trail_.size());
497  reason_decision_levels_.push_back(literals_reason_starts_.size());
498  CHECK_EQ(trail->CurrentDecisionLevel(), integer_search_levels_.size());
499  }
500 
501  // This is used to map any integer literal out of the initial variable domain
502  // into one that use one of the domain value.
503  var_to_current_lb_interval_index_.SetLevel(level);
504 
505  // This is required because when loading a model it is possible that we add
506  // (literal <-> integer literal) associations for literals that have already
507  // been propagated here. This often happens when the presolve is off
508  // and many variables are fixed.
509  //
510  // TODO(user): refactor the interaction IntegerTrail <-> IntegerEncoder so
511  // that we can just push right away such literal. Unfortunately, this is is
512  // a big chunck of work.
513  if (level == 0) {
514  for (const IntegerLiteral i_lit : encoder_->NewlyFixedIntegerLiterals()) {
515  if (IsCurrentlyIgnored(i_lit.var)) continue;
516  if (!Enqueue(i_lit, {}, {})) return false;
517  }
518  encoder_->ClearNewlyFixedIntegerLiterals();
519  }
520 
521  // Process all the "associated" literals and Enqueue() the corresponding
522  // bounds.
523  while (propagation_trail_index_ < trail->Index()) {
524  const Literal literal = (*trail)[propagation_trail_index_++];
525  for (const IntegerLiteral i_lit : encoder_->GetIntegerLiterals(literal)) {
526  if (IsCurrentlyIgnored(i_lit.var)) continue;
527 
528  // The reason is simply the associated literal.
529  if (!EnqueueAssociatedIntegerLiteral(i_lit, literal)) {
530  return false;
531  }
532  }
533  }
534 
535  return true;
536 }
537 
538 void IntegerTrail::Untrail(const Trail& trail, int literal_trail_index) {
539  ++num_untrails_;
540  const int level = trail.CurrentDecisionLevel();
541  for (ReversibleInterface* rev : reversible_classes_) rev->SetLevel(level);
542  var_to_current_lb_interval_index_.SetLevel(level);
544  std::min(propagation_trail_index_, literal_trail_index);
545 
546  // Note that if a conflict was detected before Propagate() of this class was
547  // even called, it is possible that there is nothing to backtrack.
548  if (level >= integer_search_levels_.size()) return;
549  const int target = integer_search_levels_[level];
550  integer_search_levels_.resize(level);
551  CHECK_GE(target, vars_.size());
552  CHECK_LE(target, integer_trail_.size());
553 
554  for (int index = integer_trail_.size() - 1; index >= target; --index) {
555  const TrailEntry& entry = integer_trail_[index];
556  if (entry.var < 0) continue; // entry used by EnqueueLiteral().
557  vars_[entry.var].current_trail_index = entry.prev_trail_index;
558  vars_[entry.var].current_bound =
559  integer_trail_[entry.prev_trail_index].bound;
560  }
561  integer_trail_.resize(target);
562 
563  // Clear reason.
564  const int old_size = reason_decision_levels_[level];
565  reason_decision_levels_.resize(level);
566  if (old_size < literals_reason_starts_.size()) {
567  literals_reason_buffer_.resize(literals_reason_starts_[old_size]);
568 
569  const int bound_start = bounds_reason_starts_[old_size];
570  bounds_reason_buffer_.resize(bound_start);
571  if (bound_start < trail_index_reason_buffer_.size()) {
572  trail_index_reason_buffer_.resize(bound_start);
573  }
574 
575  literals_reason_starts_.resize(old_size);
576  bounds_reason_starts_.resize(old_size);
577  }
578 }
579 
581  // Because we always create both a variable and its negation.
582  const int size = 2 * num_vars;
583  vars_.reserve(size);
584  is_ignored_literals_.reserve(size);
585  integer_trail_.reserve(size);
586  domains_->reserve(size);
587  var_trail_index_cache_.reserve(size);
588  tmp_var_to_trail_index_in_queue_.reserve(size);
589 }
590 
591 IntegerVariable IntegerTrail::AddIntegerVariable(IntegerValue lower_bound,
592  IntegerValue upper_bound) {
593  DCHECK_GE(lower_bound, kMinIntegerValue);
594  DCHECK_LE(lower_bound, kMaxIntegerValue);
595  DCHECK_GE(upper_bound, kMinIntegerValue);
596  DCHECK_LE(upper_bound, kMaxIntegerValue);
597  DCHECK(integer_search_levels_.empty());
598  DCHECK_EQ(vars_.size(), integer_trail_.size());
599 
600  const IntegerVariable i(vars_.size());
601  is_ignored_literals_.push_back(kNoLiteralIndex);
602  vars_.push_back({lower_bound, static_cast<int>(integer_trail_.size())});
603  integer_trail_.push_back({lower_bound, i});
604  domains_->push_back(Domain(lower_bound.value(), upper_bound.value()));
605 
606  // TODO(user): the is_ignored_literals_ Booleans are currently always the same
607  // for a variable and its negation. So it may be better not to store it twice
608  // so that we don't have to be careful when setting them.
609  CHECK_EQ(NegationOf(i).value(), vars_.size());
610  is_ignored_literals_.push_back(kNoLiteralIndex);
611  vars_.push_back({-upper_bound, static_cast<int>(integer_trail_.size())});
612  integer_trail_.push_back({-upper_bound, NegationOf(i)});
613  domains_->push_back(Domain(-upper_bound.value(), -lower_bound.value()));
614 
615  var_trail_index_cache_.resize(vars_.size(), integer_trail_.size());
616  tmp_var_to_trail_index_in_queue_.resize(vars_.size(), 0);
617 
618  for (SparseBitset<IntegerVariable>* w : watchers_) {
619  w->Resize(NumIntegerVariables());
620  }
621  return i;
622 }
623 
624 IntegerVariable IntegerTrail::AddIntegerVariable(const Domain& domain) {
625  CHECK(!domain.IsEmpty());
626  const IntegerVariable var = AddIntegerVariable(IntegerValue(domain.Min()),
627  IntegerValue(domain.Max()));
628  CHECK(UpdateInitialDomain(var, domain));
629  return var;
630 }
631 
632 const Domain& IntegerTrail::InitialVariableDomain(IntegerVariable var) const {
633  return (*domains_)[var];
634 }
635 
636 bool IntegerTrail::UpdateInitialDomain(IntegerVariable var, Domain domain) {
637  CHECK_EQ(trail_->CurrentDecisionLevel(), 0);
638 
639  const Domain& old_domain = InitialVariableDomain(var);
640  domain = domain.IntersectionWith(old_domain);
641  if (old_domain == domain) return true;
642 
643  if (domain.IsEmpty()) return false;
644  (*domains_)[var] = domain;
645  (*domains_)[NegationOf(var)] = domain.Negation();
646  if (domain.NumIntervals() > 1) {
647  var_to_current_lb_interval_index_.Set(var, 0);
648  var_to_current_lb_interval_index_.Set(NegationOf(var), 0);
649  }
650 
651  // TODO(user): That works, but it might be better to simply update the
652  // bounds here directly. This is because these function might call again
653  // UpdateInitialDomain(), and we will abort after realizing that the domain
654  // didn't change this time.
655  CHECK(Enqueue(IntegerLiteral::GreaterOrEqual(var, IntegerValue(domain.Min())),
656  {}, {}));
657  CHECK(Enqueue(IntegerLiteral::LowerOrEqual(var, IntegerValue(domain.Max())),
658  {}, {}));
659 
660  // Set to false excluded literals.
661  int i = 0;
662  int num_fixed = 0;
663  for (const IntegerEncoder::ValueLiteralPair pair :
664  encoder_->PartialDomainEncoding(var)) {
665  while (i < domain.NumIntervals() && pair.value > domain[i].end) ++i;
666  if (i == domain.NumIntervals() || pair.value < domain[i].start) {
667  ++num_fixed;
668  if (trail_->Assignment().LiteralIsTrue(pair.literal)) return false;
669  if (!trail_->Assignment().LiteralIsFalse(pair.literal)) {
670  trail_->EnqueueWithUnitReason(pair.literal.Negated());
671  }
672  }
673  }
674  if (num_fixed > 0) {
675  VLOG(1)
676  << "Domain intersection fixed " << num_fixed
677  << " equality literal corresponding to values outside the new domain.";
678  }
679 
680  return true;
681 }
682 
684  IntegerValue value) {
685  auto insert = constant_map_.insert(std::make_pair(value, kNoIntegerVariable));
686  if (insert.second) { // new element.
687  const IntegerVariable new_var = AddIntegerVariable(value, value);
688  insert.first->second = new_var;
689  if (value != 0) {
690  // Note that this might invalidate insert.first->second.
691  gtl::InsertOrDie(&constant_map_, -value, NegationOf(new_var));
692  }
693  return new_var;
694  }
695  return insert.first->second;
696 }
697 
699  // The +1 if for the special key zero (the only case when we have an odd
700  // number of entries).
701  return (constant_map_.size() + 1) / 2;
702 }
703 
705  int threshold) const {
706  // Optimization. We assume this is only called when computing a reason, so we
707  // can ignore this trail_index if we already need a more restrictive reason
708  // for this var.
709  const int index_in_queue = tmp_var_to_trail_index_in_queue_[var];
710  if (threshold <= index_in_queue) {
711  if (index_in_queue != kint32max) has_dependency_ = true;
712  return -1;
713  }
714 
715  DCHECK_GE(threshold, vars_.size());
716  int trail_index = vars_[var].current_trail_index;
717 
718  // Check the validity of the cached index and use it if possible.
719  if (trail_index > threshold) {
720  const int cached_index = var_trail_index_cache_[var];
721  if (cached_index >= threshold && cached_index < trail_index &&
722  integer_trail_[cached_index].var == var) {
723  trail_index = cached_index;
724  }
725  }
726 
727  while (trail_index >= threshold) {
728  trail_index = integer_trail_[trail_index].prev_trail_index;
729  if (trail_index >= var_trail_index_cache_threshold_) {
730  var_trail_index_cache_[var] = trail_index;
731  }
732  }
733 
734  const int num_vars = vars_.size();
735  return trail_index < num_vars ? -1 : trail_index;
736 }
737 
738 int IntegerTrail::FindLowestTrailIndexThatExplainBound(
739  IntegerLiteral i_lit) const {
740  DCHECK_LE(i_lit.bound, vars_[i_lit.var].current_bound);
741  if (i_lit.bound <= LevelZeroLowerBound(i_lit.var)) return -1;
742  int trail_index = vars_[i_lit.var].current_trail_index;
743 
744  // Check the validity of the cached index and use it if possible. This caching
745  // mechanism is important in case of long chain of propagation on the same
746  // variable. Because during conflict resolution, we call
747  // FindLowestTrailIndexThatExplainBound() with lowest and lowest bound, this
748  // cache can transform a quadratic complexity into a linear one.
749  {
750  const int cached_index = var_trail_index_cache_[i_lit.var];
751  if (cached_index < trail_index) {
752  const TrailEntry& entry = integer_trail_[cached_index];
753  if (entry.var == i_lit.var && entry.bound >= i_lit.bound) {
754  trail_index = cached_index;
755  }
756  }
757  }
758 
759  int prev_trail_index = trail_index;
760  while (true) {
761  if (trail_index >= var_trail_index_cache_threshold_) {
762  var_trail_index_cache_[i_lit.var] = trail_index;
763  }
764  const TrailEntry& entry = integer_trail_[trail_index];
765  if (entry.bound == i_lit.bound) return trail_index;
766  if (entry.bound < i_lit.bound) return prev_trail_index;
767  prev_trail_index = trail_index;
768  trail_index = entry.prev_trail_index;
769  }
770 }
771 
772 // TODO(user): Get rid of this function and only keep the trail index one?
774  IntegerValue slack, absl::Span<const IntegerValue> coeffs,
775  std::vector<IntegerLiteral>* reason) const {
776  CHECK_GE(slack, 0);
777  if (slack == 0) return;
778  const int size = reason->size();
779  tmp_indices_.resize(size);
780  for (int i = 0; i < size; ++i) {
781  CHECK_EQ((*reason)[i].bound, LowerBound((*reason)[i].var));
782  CHECK_GE(coeffs[i], 0);
783  tmp_indices_[i] = vars_[(*reason)[i].var].current_trail_index;
784  }
785 
786  RelaxLinearReason(slack, coeffs, &tmp_indices_);
787 
788  reason->clear();
789  for (const int i : tmp_indices_) {
790  reason->push_back(IntegerLiteral::GreaterOrEqual(integer_trail_[i].var,
791  integer_trail_[i].bound));
792  }
793 }
794 
796  IntegerValue slack, absl::Span<const IntegerValue> coeffs,
797  absl::Span<const IntegerVariable> vars,
798  std::vector<IntegerLiteral>* reason) const {
799  tmp_indices_.clear();
800  for (const IntegerVariable var : vars) {
801  tmp_indices_.push_back(vars_[var].current_trail_index);
802  }
803  if (slack > 0) RelaxLinearReason(slack, coeffs, &tmp_indices_);
804  for (const int i : tmp_indices_) {
805  reason->push_back(IntegerLiteral::GreaterOrEqual(integer_trail_[i].var,
806  integer_trail_[i].bound));
807  }
808 }
809 
810 // TODO(user): When this is called during a reason computation, we can use
811 // the term already part of the reason we are constructed to optimize this
812 // further.
813 void IntegerTrail::RelaxLinearReason(IntegerValue slack,
814  absl::Span<const IntegerValue> coeffs,
815  std::vector<int>* trail_indices) const {
816  DCHECK_GT(slack, 0);
817  DCHECK(relax_heap_.empty());
818 
819  // We start by filtering *trail_indices:
820  // - remove all level zero entries.
821  // - keep the one that cannot be relaxed.
822  // - move the other one to the relax_heap_ (and creating the heap).
823  int new_size = 0;
824  const int size = coeffs.size();
825  const int num_vars = vars_.size();
826  for (int i = 0; i < size; ++i) {
827  const int index = (*trail_indices)[i];
828 
829  // We ignore level zero entries.
830  if (index < num_vars) continue;
831 
832  // If the coeff is too large, we cannot relax this entry.
833  const IntegerValue coeff = coeffs[i];
834  if (coeff > slack) {
835  (*trail_indices)[new_size++] = index;
836  continue;
837  }
838 
839  // Note that both terms of the product are positive.
840  const TrailEntry& entry = integer_trail_[index];
841  const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
842  const int64 diff =
843  CapProd(coeff.value(), (entry.bound - previous_entry.bound).value());
844  if (diff > slack) {
845  (*trail_indices)[new_size++] = index;
846  continue;
847  }
848 
849  relax_heap_.push_back({index, coeff, diff});
850  }
851  trail_indices->resize(new_size);
852  std::make_heap(relax_heap_.begin(), relax_heap_.end());
853 
854  while (slack > 0 && !relax_heap_.empty()) {
855  const RelaxHeapEntry heap_entry = relax_heap_.front();
856  std::pop_heap(relax_heap_.begin(), relax_heap_.end());
857  relax_heap_.pop_back();
858 
859  // The slack might have changed since the entry was added.
860  if (heap_entry.diff > slack) {
861  trail_indices->push_back(heap_entry.index);
862  continue;
863  }
864 
865  // Relax, and decide what to do with the new value of index.
866  slack -= heap_entry.diff;
867  const int index = integer_trail_[heap_entry.index].prev_trail_index;
868 
869  // Same code as in the first block.
870  if (index < num_vars) continue;
871  if (heap_entry.coeff > slack) {
872  trail_indices->push_back(index);
873  continue;
874  }
875  const TrailEntry& entry = integer_trail_[index];
876  const TrailEntry& previous_entry = integer_trail_[entry.prev_trail_index];
877  const int64 diff = CapProd(heap_entry.coeff.value(),
878  (entry.bound - previous_entry.bound).value());
879  if (diff > slack) {
880  trail_indices->push_back(index);
881  continue;
882  }
883  relax_heap_.push_back({index, heap_entry.coeff, diff});
884  std::push_heap(relax_heap_.begin(), relax_heap_.end());
885  }
886 
887  // If we aborted early because of the slack, we need to push all remaining
888  // indices back into the reason.
889  for (const RelaxHeapEntry& entry : relax_heap_) {
890  trail_indices->push_back(entry.index);
891  }
892  relax_heap_.clear();
893 }
894 
896  std::vector<IntegerLiteral>* reason) const {
897  int new_size = 0;
898  for (const IntegerLiteral literal : *reason) {
899  if (literal.bound <= LevelZeroLowerBound(literal.var)) continue;
900  (*reason)[new_size++] = literal;
901  }
902  reason->resize(new_size);
903 }
904 
905 std::vector<Literal>* IntegerTrail::InitializeConflict(
906  IntegerLiteral integer_literal, const LazyReasonFunction& lazy_reason,
907  absl::Span<const Literal> literals_reason,
908  absl::Span<const IntegerLiteral> bounds_reason) {
909  DCHECK(tmp_queue_.empty());
910  std::vector<Literal>* conflict = trail_->MutableConflict();
911  if (lazy_reason == nullptr) {
912  conflict->assign(literals_reason.begin(), literals_reason.end());
913  const int num_vars = vars_.size();
914  for (const IntegerLiteral& literal : bounds_reason) {
915  const int trail_index = FindLowestTrailIndexThatExplainBound(literal);
916  if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
917  }
918  } else {
919  // We use the current trail index here.
920  conflict->clear();
921  lazy_reason(integer_literal, integer_trail_.size(), conflict, &tmp_queue_);
922  }
923  return conflict;
924 }
925 
926 namespace {
927 
928 std::string ReasonDebugString(absl::Span<const Literal> literal_reason,
929  absl::Span<const IntegerLiteral> integer_reason) {
930  std::string result = "literals:{";
931  for (const Literal l : literal_reason) {
932  if (result.back() != '{') result += ",";
933  result += l.DebugString();
934  }
935  result += "} bounds:{";
936  for (const IntegerLiteral l : integer_reason) {
937  if (result.back() != '{') result += ",";
938  result += l.DebugString();
939  }
940  result += "}";
941  return result;
942 }
943 
944 } // namespace
945 
946 std::string IntegerTrail::DebugString() {
947  std::string result = "trail:{";
948  const int num_vars = vars_.size();
949  const int limit =
950  std::min(num_vars + 30, static_cast<int>(integer_trail_.size()));
951  for (int i = num_vars; i < limit; ++i) {
952  if (result.back() != '{') result += ",";
953  result +=
954  IntegerLiteral::GreaterOrEqual(IntegerVariable(integer_trail_[i].var),
955  integer_trail_[i].bound)
956  .DebugString();
957  }
958  if (limit < integer_trail_.size()) {
959  result += ", ...";
960  }
961  result += "}";
962  return result;
963 }
964 
966  absl::Span<const Literal> literal_reason,
967  absl::Span<const IntegerLiteral> integer_reason) {
968  return EnqueueInternal(i_lit, nullptr, literal_reason, integer_reason,
969  integer_trail_.size());
970 }
971 
973  absl::Span<const Literal> literal_reason,
974  absl::Span<const IntegerLiteral> integer_reason,
975  int trail_index_with_same_reason) {
976  return EnqueueInternal(i_lit, nullptr, literal_reason, integer_reason,
977  trail_index_with_same_reason);
978 }
979 
981  LazyReasonFunction lazy_reason) {
982  return EnqueueInternal(i_lit, lazy_reason, {}, {}, integer_trail_.size());
983 }
984 
985 bool IntegerTrail::ReasonIsValid(
986  absl::Span<const Literal> literal_reason,
987  absl::Span<const IntegerLiteral> integer_reason) {
988  const VariablesAssignment& assignment = trail_->Assignment();
989  for (const Literal lit : literal_reason) {
990  if (!assignment.LiteralIsFalse(lit)) return false;
991  }
992  for (const IntegerLiteral i_lit : integer_reason) {
993  if (i_lit.bound > vars_[i_lit.var].current_bound) {
994  if (IsOptional(i_lit.var)) {
995  const Literal is_ignored = IsIgnoredLiteral(i_lit.var);
996  LOG(INFO) << "Reason " << i_lit << " is not true!"
997  << " optional variable:" << i_lit.var
998  << " present:" << assignment.LiteralIsFalse(is_ignored)
999  << " absent:" << assignment.LiteralIsTrue(is_ignored)
1000  << " current_lb:" << vars_[i_lit.var].current_bound;
1001  } else {
1002  LOG(INFO) << "Reason " << i_lit << " is not true!"
1003  << " non-optional variable:" << i_lit.var
1004  << " current_lb:" << vars_[i_lit.var].current_bound;
1005  }
1006  return false;
1007  }
1008  }
1009 
1010  // This may not indicate an incorectness, but just some propagators that
1011  // didn't reach a fixed-point at level zero.
1012  if (!integer_search_levels_.empty()) {
1013  int num_literal_assigned_after_root_node = 0;
1014  for (const Literal lit : literal_reason) {
1015  if (trail_->Info(lit.Variable()).level > 0) {
1016  num_literal_assigned_after_root_node++;
1017  }
1018  }
1019  for (const IntegerLiteral i_lit : integer_reason) {
1020  if (LevelZeroLowerBound(i_lit.var) < i_lit.bound) {
1021  num_literal_assigned_after_root_node++;
1022  }
1023  }
1024  DLOG_IF(INFO, num_literal_assigned_after_root_node == 0)
1025  << "Propagating a literal with no reason at a positive level!\n"
1026  << "level:" << integer_search_levels_.size() << " "
1027  << ReasonDebugString(literal_reason, integer_reason) << "\n"
1028  << DebugString();
1029  }
1030 
1031  return true;
1032 }
1033 
1035  Literal literal, absl::Span<const Literal> literal_reason,
1036  absl::Span<const IntegerLiteral> integer_reason) {
1037  EnqueueLiteralInternal(literal, nullptr, literal_reason, integer_reason);
1038 }
1039 
1040 void IntegerTrail::EnqueueLiteralInternal(
1041  Literal literal, LazyReasonFunction lazy_reason,
1042  absl::Span<const Literal> literal_reason,
1043  absl::Span<const IntegerLiteral> integer_reason) {
1044  DCHECK(!trail_->Assignment().LiteralIsAssigned(literal));
1045  DCHECK(lazy_reason != nullptr ||
1046  ReasonIsValid(literal_reason, integer_reason));
1047  if (integer_search_levels_.empty()) {
1048  // Level zero. We don't keep any reason.
1049  trail_->EnqueueWithUnitReason(literal);
1050  return;
1051  }
1052 
1053  const int trail_index = trail_->Index();
1054  if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1055  boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1056  }
1057  boolean_trail_index_to_integer_one_[trail_index] = integer_trail_.size();
1058 
1059  int reason_index = literals_reason_starts_.size();
1060  if (lazy_reason != nullptr) {
1061  if (integer_trail_.size() >= lazy_reasons_.size()) {
1062  lazy_reasons_.resize(integer_trail_.size() + 1, nullptr);
1063  }
1064  lazy_reasons_[integer_trail_.size()] = lazy_reason;
1065  reason_index = -1;
1066  } else {
1067  // Copy the reason.
1068  literals_reason_starts_.push_back(literals_reason_buffer_.size());
1069  literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1070  literal_reason.begin(),
1071  literal_reason.end());
1072  bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1073  bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1074  integer_reason.begin(), integer_reason.end());
1075  }
1076 
1077  integer_trail_.push_back({/*bound=*/IntegerValue(0),
1078  /*var=*/kNoIntegerVariable,
1079  /*prev_trail_index=*/-1,
1080  /*reason_index=*/reason_index});
1081 
1082  trail_->Enqueue(literal, propagator_id_);
1083 }
1084 
1085 bool IntegerTrail::EnqueueInternal(
1086  IntegerLiteral i_lit, LazyReasonFunction lazy_reason,
1087  absl::Span<const Literal> literal_reason,
1088  absl::Span<const IntegerLiteral> integer_reason,
1089  int trail_index_with_same_reason) {
1090  DCHECK(lazy_reason != nullptr ||
1091  ReasonIsValid(literal_reason, integer_reason));
1092 
1093  const IntegerVariable var(i_lit.var);
1094 
1095  // No point doing work if the variable is already ignored.
1096  if (IsCurrentlyIgnored(var)) return true;
1097 
1098  // Nothing to do if the bound is not better than the current one.
1099  // TODO(user): Change this to a CHECK? propagator shouldn't try to push such
1100  // bound and waste time explaining it.
1101  if (i_lit.bound <= vars_[var].current_bound) return true;
1102  ++num_enqueues_;
1103 
1104  // If the domain of var is not a single intervals and i_lit.bound fall into a
1105  // "hole", we increase it to the next possible value. This ensure that we
1106  // never Enqueue() non-canonical literals. See also Canonicalize().
1107  //
1108  // Note: The literals in the reason are not necessarily canonical, but then
1109  // we always map these to enqueued literals during conflict resolution.
1110  if ((*domains_)[var].NumIntervals() > 1) {
1111  const auto& domain = (*domains_)[var];
1112  int index = var_to_current_lb_interval_index_.FindOrDie(var);
1113  const int size = domain.NumIntervals();
1114  while (index < size && i_lit.bound > domain[index].end) {
1115  ++index;
1116  }
1117  if (index == size) {
1118  return ReportConflict(literal_reason, integer_reason);
1119  } else {
1120  var_to_current_lb_interval_index_.Set(var, index);
1121  i_lit.bound = std::max(i_lit.bound, IntegerValue(domain[index].start));
1122  }
1123  }
1124 
1125  // Check if the integer variable has an empty domain.
1126  if (i_lit.bound > UpperBound(var)) {
1127  // We relax the upper bound as much as possible to still have a conflict.
1128  const auto ub_reason = IntegerLiteral::LowerOrEqual(var, i_lit.bound - 1);
1129 
1130  if (!IsOptional(var) || trail_->Assignment().LiteralIsFalse(
1131  Literal(is_ignored_literals_[var]))) {
1132  // Note that we want only one call to MergeReasonIntoInternal() for
1133  // efficiency and a potential smaller reason.
1134  auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1135  integer_reason);
1136  if (IsOptional(var)) {
1137  conflict->push_back(Literal(is_ignored_literals_[var]));
1138  }
1139  {
1140  const int trail_index = FindLowestTrailIndexThatExplainBound(ub_reason);
1141  const int num_vars = vars_.size(); // must be signed.
1142  if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1143  }
1144  MergeReasonIntoInternal(conflict);
1145  return false;
1146  } else {
1147  // Note(user): We never make the bound of an optional literal cross. We
1148  // used to have a bug where we propagated these bounds and their
1149  // associated literals, and we were reaching a conflict while propagating
1150  // the associated literal instead of setting is_ignored below to false.
1151  const Literal is_ignored = Literal(is_ignored_literals_[var]);
1152  if (integer_search_levels_.empty()) {
1153  trail_->EnqueueWithUnitReason(is_ignored);
1154  } else {
1155  // Here we currently expand any lazy reason because we need to add
1156  // to it the reason for the upper bound.
1157  // TODO(user): A possible solution would be to support the two types
1158  // of reason (lazy and not) at the same time and use the union of both?
1159  if (lazy_reason != nullptr) {
1160  lazy_reason(i_lit, integer_trail_.size(), &lazy_reason_literals_,
1161  &lazy_reason_trail_indices_);
1162  std::vector<IntegerLiteral> temp;
1163  for (const int trail_index : lazy_reason_trail_indices_) {
1164  const TrailEntry& entry = integer_trail_[trail_index];
1165  temp.push_back(IntegerLiteral(entry.var, entry.bound));
1166  }
1167  EnqueueLiteral(is_ignored, lazy_reason_literals_, temp);
1168  } else {
1169  EnqueueLiteral(is_ignored, literal_reason, integer_reason);
1170  }
1171 
1172  // Hack, we add the upper bound reason here.
1173  bounds_reason_buffer_.push_back(ub_reason);
1174  }
1175  return true;
1176  }
1177  }
1178 
1179  // Notify the watchers.
1180  for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1181  bitset->Set(i_lit.var);
1182  }
1183 
1184  // Enqueue the strongest associated Boolean literal implied by this one.
1185  // Because we linked all such literal with implications, all the one before
1186  // will be propagated by the SAT solver.
1187  //
1188  // Important: It is possible that such literal or even stronger ones are
1189  // already true! This is because we might push stuff while Propagate() haven't
1190  // been called yet. Maybe we should call it?
1191  //
1192  // TODO(user): It might be simply better and more efficient to simply enqueue
1193  // all of them here. We have also more liberty to choose the explanation we
1194  // want. A drawback might be that the implications might not be used in the
1195  // binary conflict minimization algo.
1196  IntegerValue bound;
1197  const LiteralIndex literal_index =
1198  encoder_->SearchForLiteralAtOrBefore(i_lit, &bound);
1199  if (literal_index != kNoLiteralIndex) {
1200  const Literal to_enqueue = Literal(literal_index);
1201  if (trail_->Assignment().LiteralIsFalse(to_enqueue)) {
1202  auto* conflict = InitializeConflict(i_lit, lazy_reason, literal_reason,
1203  integer_reason);
1204  conflict->push_back(to_enqueue);
1205  MergeReasonIntoInternal(conflict);
1206  return false;
1207  }
1208 
1209  // If the associated literal exactly correspond to i_lit, then we push
1210  // it first, and then we use it as a reason for i_lit. We do that so that
1211  // MergeReasonIntoInternal() will not unecessarily expand further the reason
1212  // for i_lit.
1213  if (IntegerLiteral::GreaterOrEqual(i_lit.var, bound) == i_lit) {
1214  if (!trail_->Assignment().LiteralIsTrue(to_enqueue)) {
1215  EnqueueLiteralInternal(to_enqueue, lazy_reason, literal_reason,
1216  integer_reason);
1217  }
1218  return EnqueueAssociatedIntegerLiteral(i_lit, to_enqueue);
1219  }
1220 
1221  if (!trail_->Assignment().LiteralIsTrue(to_enqueue)) {
1222  if (integer_search_levels_.empty()) {
1223  trail_->EnqueueWithUnitReason(to_enqueue);
1224  } else {
1225  // Subtle: the reason is the same as i_lit, that we will enqueue if no
1226  // conflict occur at position integer_trail_.size(), so we just refer to
1227  // this index here.
1228  const int trail_index = trail_->Index();
1229  if (trail_index >= boolean_trail_index_to_integer_one_.size()) {
1230  boolean_trail_index_to_integer_one_.resize(trail_index + 1);
1231  }
1232  boolean_trail_index_to_integer_one_[trail_index] =
1233  trail_index_with_same_reason;
1234  trail_->Enqueue(to_enqueue, propagator_id_);
1235  }
1236  }
1237  }
1238 
1239  // Special case for level zero.
1240  if (integer_search_levels_.empty()) {
1241  ++num_level_zero_enqueues_;
1242  vars_[i_lit.var].current_bound = i_lit.bound;
1243  integer_trail_[i_lit.var.value()].bound = i_lit.bound;
1244 
1245  // We also update the initial domain. If this fail, since we are at level
1246  // zero, we don't care about the reason.
1247  trail_->MutableConflict()->clear();
1248  return UpdateInitialDomain(
1249  i_lit.var,
1250  Domain(LowerBound(i_lit.var).value(), UpperBound(i_lit.var).value()));
1251  }
1252  DCHECK_GT(trail_->CurrentDecisionLevel(), 0);
1253 
1254  int reason_index = literals_reason_starts_.size();
1255  if (lazy_reason != nullptr) {
1256  if (integer_trail_.size() >= lazy_reasons_.size()) {
1257  lazy_reasons_.resize(integer_trail_.size() + 1, nullptr);
1258  }
1259  lazy_reasons_[integer_trail_.size()] = lazy_reason;
1260  reason_index = -1;
1261  } else if (trail_index_with_same_reason >= integer_trail_.size()) {
1262  // Save the reason into our internal buffers.
1263  literals_reason_starts_.push_back(literals_reason_buffer_.size());
1264  if (!literal_reason.empty()) {
1265  literals_reason_buffer_.insert(literals_reason_buffer_.end(),
1266  literal_reason.begin(),
1267  literal_reason.end());
1268  }
1269  bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1270  if (!integer_reason.empty()) {
1271  bounds_reason_buffer_.insert(bounds_reason_buffer_.end(),
1272  integer_reason.begin(),
1273  integer_reason.end());
1274  }
1275  } else {
1276  reason_index = integer_trail_[trail_index_with_same_reason].reason_index;
1277  }
1278 
1279  const int prev_trail_index = vars_[i_lit.var].current_trail_index;
1280  integer_trail_.push_back({/*bound=*/i_lit.bound,
1281  /*var=*/i_lit.var,
1282  /*prev_trail_index=*/prev_trail_index,
1283  /*reason_index=*/reason_index});
1284 
1285  vars_[i_lit.var].current_bound = i_lit.bound;
1286  vars_[i_lit.var].current_trail_index = integer_trail_.size() - 1;
1287  return true;
1288 }
1289 
1290 bool IntegerTrail::EnqueueAssociatedIntegerLiteral(IntegerLiteral i_lit,
1291  Literal literal_reason) {
1292  DCHECK(ReasonIsValid({literal_reason.Negated()}, {}));
1293  DCHECK(!IsCurrentlyIgnored(i_lit.var));
1294 
1295  // Nothing to do if the bound is not better than the current one.
1296  if (i_lit.bound <= vars_[i_lit.var].current_bound) return true;
1297  ++num_enqueues_;
1298 
1299  // Check if the integer variable has an empty domain. Note that this should
1300  // happen really rarely since in most situation, pushing the upper bound would
1301  // have resulted in this literal beeing false. Because of this we revert to
1302  // the "generic" Enqueue() to avoid some code duplication.
1303  if (i_lit.bound > UpperBound(i_lit.var)) {
1304  return Enqueue(i_lit, {literal_reason.Negated()}, {});
1305  }
1306 
1307  // Notify the watchers.
1308  for (SparseBitset<IntegerVariable>* bitset : watchers_) {
1309  bitset->Set(i_lit.var);
1310  }
1311 
1312  // Special case for level zero.
1313  if (integer_search_levels_.empty()) {
1314  vars_[i_lit.var].current_bound = i_lit.bound;
1315  integer_trail_[i_lit.var.value()].bound = i_lit.bound;
1316 
1317  // We also update the initial domain. If this fail, since we are at level
1318  // zero, we don't care about the reason.
1319  trail_->MutableConflict()->clear();
1320  return UpdateInitialDomain(
1321  i_lit.var,
1322  Domain(LowerBound(i_lit.var).value(), UpperBound(i_lit.var).value()));
1323  }
1324  DCHECK_GT(trail_->CurrentDecisionLevel(), 0);
1325 
1326  const int reason_index = literals_reason_starts_.size();
1327  CHECK_EQ(reason_index, bounds_reason_starts_.size());
1328  literals_reason_starts_.push_back(literals_reason_buffer_.size());
1329  bounds_reason_starts_.push_back(bounds_reason_buffer_.size());
1330  literals_reason_buffer_.push_back(literal_reason.Negated());
1331 
1332  const int prev_trail_index = vars_[i_lit.var].current_trail_index;
1333  integer_trail_.push_back({/*bound=*/i_lit.bound,
1334  /*var=*/i_lit.var,
1335  /*prev_trail_index=*/prev_trail_index,
1336  /*reason_index=*/reason_index});
1337 
1338  vars_[i_lit.var].current_bound = i_lit.bound;
1339  vars_[i_lit.var].current_trail_index = integer_trail_.size() - 1;
1340  return true;
1341 }
1342 
1343 void IntegerTrail::ComputeLazyReasonIfNeeded(int trail_index) const {
1344  const int reason_index = integer_trail_[trail_index].reason_index;
1345  if (reason_index == -1) {
1346  const TrailEntry& entry = integer_trail_[trail_index];
1347  const IntegerLiteral literal(entry.var, entry.bound);
1348  lazy_reasons_[trail_index](literal, trail_index, &lazy_reason_literals_,
1349  &lazy_reason_trail_indices_);
1350  }
1351 }
1352 
1353 absl::Span<const int> IntegerTrail::Dependencies(int trail_index) const {
1354  const int reason_index = integer_trail_[trail_index].reason_index;
1355  if (reason_index == -1) {
1356  return absl::Span<const int>(lazy_reason_trail_indices_);
1357  }
1358 
1359  const int start = bounds_reason_starts_[reason_index];
1360  const int end = reason_index + 1 < bounds_reason_starts_.size()
1361  ? bounds_reason_starts_[reason_index + 1]
1362  : bounds_reason_buffer_.size();
1363  if (start == end) return {};
1364 
1365  // Cache the result if not already computed. Remark, if the result was never
1366  // computed then the span trail_index_reason_buffer_[start, end) will either
1367  // be non-existent or full of -1.
1368  //
1369  // TODO(user): For empty reason, we will always recompute them.
1370  if (end > trail_index_reason_buffer_.size()) {
1371  trail_index_reason_buffer_.resize(end, -1);
1372  }
1373  if (trail_index_reason_buffer_[start] == -1) {
1374  int new_end = start;
1375  const int num_vars = vars_.size();
1376  for (int i = start; i < end; ++i) {
1377  const int dep =
1378  FindLowestTrailIndexThatExplainBound(bounds_reason_buffer_[i]);
1379  if (dep >= num_vars) {
1380  trail_index_reason_buffer_[new_end++] = dep;
1381  }
1382  }
1383  return absl::Span<const int>(&trail_index_reason_buffer_[start],
1384  new_end - start);
1385  } else {
1386  // TODO(user): We didn't store new_end in a previous call, so end might be
1387  // larger. That is a bit annoying since we have to test for -1 while
1388  // iterating.
1389  return absl::Span<const int>(&trail_index_reason_buffer_[start],
1390  end - start);
1391  }
1392 }
1393 
1394 void IntegerTrail::AppendLiteralsReason(int trail_index,
1395  std::vector<Literal>* output) const {
1396  CHECK_GE(trail_index, vars_.size());
1397  const int reason_index = integer_trail_[trail_index].reason_index;
1398  if (reason_index == -1) {
1399  for (const Literal l : lazy_reason_literals_) {
1400  if (!added_variables_[l.Variable()]) {
1401  added_variables_.Set(l.Variable());
1402  output->push_back(l);
1403  }
1404  }
1405  return;
1406  }
1407 
1408  const int start = literals_reason_starts_[reason_index];
1409  const int end = reason_index + 1 < literals_reason_starts_.size()
1410  ? literals_reason_starts_[reason_index + 1]
1411  : literals_reason_buffer_.size();
1412  for (int i = start; i < end; ++i) {
1413  const Literal l = literals_reason_buffer_[i];
1414  if (!added_variables_[l.Variable()]) {
1415  added_variables_.Set(l.Variable());
1416  output->push_back(l);
1417  }
1418  }
1419 }
1420 
1421 std::vector<Literal> IntegerTrail::ReasonFor(IntegerLiteral literal) const {
1422  std::vector<Literal> reason;
1423  MergeReasonInto({literal}, &reason);
1424  return reason;
1425 }
1426 
1427 // TODO(user): If this is called many time on the same variables, it could be
1428 // made faster by using some caching mecanism.
1429 void IntegerTrail::MergeReasonInto(absl::Span<const IntegerLiteral> literals,
1430  std::vector<Literal>* output) const {
1431  DCHECK(tmp_queue_.empty());
1432  const int num_vars = vars_.size();
1433  for (const IntegerLiteral& literal : literals) {
1434  const int trail_index = FindLowestTrailIndexThatExplainBound(literal);
1435 
1436  // Any indices lower than that means that there is no reason needed.
1437  // Note that it is important for size to be signed because of -1 indices.
1438  if (trail_index >= num_vars) tmp_queue_.push_back(trail_index);
1439  }
1440  return MergeReasonIntoInternal(output);
1441 }
1442 
1443 // This will expand the reason of the IntegerLiteral already in tmp_queue_ until
1444 // everything is explained in term of Literal.
1445 void IntegerTrail::MergeReasonIntoInternal(std::vector<Literal>* output) const {
1446  // All relevant trail indices will be >= vars_.size(), so we can safely use
1447  // zero to means that no literal refering to this variable is in the queue.
1448  DCHECK(std::all_of(tmp_var_to_trail_index_in_queue_.begin(),
1449  tmp_var_to_trail_index_in_queue_.end(),
1450  [](int v) { return v == 0; }));
1451 
1452  added_variables_.ClearAndResize(BooleanVariable(trail_->NumVariables()));
1453  for (const Literal l : *output) {
1454  added_variables_.Set(l.Variable());
1455  }
1456 
1457  // During the algorithm execution, all the queue entries that do not match the
1458  // content of tmp_var_to_trail_index_in_queue_[] will be ignored.
1459  for (const int trail_index : tmp_queue_) {
1460  DCHECK_GE(trail_index, vars_.size());
1461  DCHECK_LT(trail_index, integer_trail_.size());
1462  const TrailEntry& entry = integer_trail_[trail_index];
1463  tmp_var_to_trail_index_in_queue_[entry.var] =
1464  std::max(tmp_var_to_trail_index_in_queue_[entry.var], trail_index);
1465  }
1466 
1467  // We manage our heap by hand so that we can range iterate over it above, and
1468  // this initial heapify is faster.
1469  std::make_heap(tmp_queue_.begin(), tmp_queue_.end());
1470 
1471  // We process the entries by highest trail_index first. The content of the
1472  // queue will always be a valid reason for the literals we already added to
1473  // the output.
1474  tmp_to_clear_.clear();
1475  while (!tmp_queue_.empty()) {
1476  const int trail_index = tmp_queue_.front();
1477  const TrailEntry& entry = integer_trail_[trail_index];
1478  std::pop_heap(tmp_queue_.begin(), tmp_queue_.end());
1479  tmp_queue_.pop_back();
1480 
1481  // Skip any stale queue entry. Amongst all the entry refering to a given
1482  // variable, only the latest added to the queue is valid and we detect it
1483  // using its trail index.
1484  if (tmp_var_to_trail_index_in_queue_[entry.var] != trail_index) {
1485  continue;
1486  }
1487 
1488  // Set the cache threshold. Since we process trail indices in decreasing
1489  // order and we only have single linked list, we only want to advance the
1490  // "cache" up to this threshold.
1491  var_trail_index_cache_threshold_ = trail_index;
1492 
1493  // If this entry has an associated literal, then it should always be the
1494  // one we used for the reason. This code DCHECK that.
1495  if (DEBUG_MODE) {
1496  const LiteralIndex associated_lit =
1498  IntegerVariable(entry.var), entry.bound));
1499  if (associated_lit != kNoLiteralIndex) {
1500  // We check that the reason is the same!
1501  const int reason_index = integer_trail_[trail_index].reason_index;
1502  CHECK_NE(reason_index, -1);
1503  {
1504  const int start = literals_reason_starts_[reason_index];
1505  const int end = reason_index + 1 < literals_reason_starts_.size()
1506  ? literals_reason_starts_[reason_index + 1]
1507  : literals_reason_buffer_.size();
1508  CHECK_EQ(start + 1, end);
1509  CHECK_EQ(literals_reason_buffer_[start],
1510  Literal(associated_lit).Negated());
1511  }
1512  {
1513  const int start = bounds_reason_starts_[reason_index];
1514  const int end = reason_index + 1 < bounds_reason_starts_.size()
1515  ? bounds_reason_starts_[reason_index + 1]
1516  : bounds_reason_buffer_.size();
1517  CHECK_EQ(start, end);
1518  }
1519  }
1520  }
1521 
1522  // Process this entry. Note that if any of the next expansion include the
1523  // variable entry.var in their reason, we must process it again because we
1524  // cannot easily detect if it was needed to infer the current entry.
1525  //
1526  // Important: the queue might already contains entries refering to the same
1527  // variable. The code act like if we deleted all of them at this point, we
1528  // just do that lazily. tmp_var_to_trail_index_in_queue_[var] will
1529  // only refer to newly added entries.
1530  tmp_var_to_trail_index_in_queue_[entry.var] = 0;
1531  has_dependency_ = false;
1532 
1533  ComputeLazyReasonIfNeeded(trail_index);
1534  AppendLiteralsReason(trail_index, output);
1535  for (const int next_trail_index : Dependencies(trail_index)) {
1536  if (next_trail_index < 0) break;
1537  DCHECK_LT(next_trail_index, trail_index);
1538  const TrailEntry& next_entry = integer_trail_[next_trail_index];
1539 
1540  // Only add literals that are not "implied" by the ones already present.
1541  // For instance, do not add (x >= 4) if we already have (x >= 7). This
1542  // translate into only adding a trail index if it is larger than the one
1543  // in the queue refering to the same variable.
1544  const int index_in_queue =
1545  tmp_var_to_trail_index_in_queue_[next_entry.var];
1546  if (index_in_queue != kint32max) has_dependency_ = true;
1547  if (next_trail_index > index_in_queue) {
1548  tmp_var_to_trail_index_in_queue_[next_entry.var] = next_trail_index;
1549  tmp_queue_.push_back(next_trail_index);
1550  std::push_heap(tmp_queue_.begin(), tmp_queue_.end());
1551  }
1552  }
1553 
1554  // Special case for a "leaf", we will never need this variable again.
1555  if (!has_dependency_) {
1556  tmp_to_clear_.push_back(entry.var);
1557  tmp_var_to_trail_index_in_queue_[entry.var] = kint32max;
1558  }
1559  }
1560 
1561  // clean-up.
1562  for (const IntegerVariable var : tmp_to_clear_) {
1563  tmp_var_to_trail_index_in_queue_[var] = 0;
1564  }
1565 }
1566 
1567 absl::Span<const Literal> IntegerTrail::Reason(const Trail& trail,
1568  int trail_index) const {
1569  const int index = boolean_trail_index_to_integer_one_[trail_index];
1570  std::vector<Literal>* reason = trail.GetEmptyVectorToStoreReason(trail_index);
1571  added_variables_.ClearAndResize(BooleanVariable(trail_->NumVariables()));
1572 
1573  ComputeLazyReasonIfNeeded(index);
1574  AppendLiteralsReason(index, reason);
1575  DCHECK(tmp_queue_.empty());
1576  for (const int prev_trail_index : Dependencies(index)) {
1577  if (prev_trail_index < 0) break;
1578  DCHECK_GE(prev_trail_index, vars_.size());
1579  tmp_queue_.push_back(prev_trail_index);
1580  }
1581  MergeReasonIntoInternal(reason);
1582  return *reason;
1583 }
1584 
1585 // TODO(user): Implement a dense version if there is more trail entries
1586 // than variables!
1587 void IntegerTrail::AppendNewBounds(std::vector<IntegerLiteral>* output) const {
1588  tmp_marked_.ClearAndResize(IntegerVariable(vars_.size()));
1589 
1590  // In order to push the best bound for each variable, we loop backward.
1591  const int end = vars_.size();
1592  for (int i = integer_trail_.size(); --i >= end;) {
1593  const TrailEntry& entry = integer_trail_[i];
1594  if (entry.var == kNoIntegerVariable) continue;
1595  if (tmp_marked_[entry.var]) continue;
1596 
1597  tmp_marked_.Set(entry.var);
1598  output->push_back(IntegerLiteral::GreaterOrEqual(entry.var, entry.bound));
1599  }
1600 }
1601 
1603  : SatPropagator("GenericLiteralWatcher"),
1604  time_limit_(model->GetOrCreate<TimeLimit>()),
1605  integer_trail_(model->GetOrCreate<IntegerTrail>()),
1606  rev_int_repository_(model->GetOrCreate<RevIntRepository>()) {
1607  // TODO(user): This propagator currently needs to be last because it is the
1608  // only one enforcing that a fix-point is reached on the integer variables.
1609  // Figure out a better interaction between the sat propagation loop and
1610  // this one.
1611  model->GetOrCreate<SatSolver>()->AddLastPropagator(this);
1612 
1613  integer_trail_->RegisterReversibleClass(
1614  &id_to_greatest_common_level_since_last_call_);
1615  integer_trail_->RegisterWatcher(&modified_vars_);
1616  queue_by_priority_.resize(2); // Because default priority is 1.
1617 }
1618 
1619 void GenericLiteralWatcher::UpdateCallingNeeds(Trail* trail) {
1620  // Process any new Literal on the trail.
1621  while (propagation_trail_index_ < trail->Index()) {
1622  const Literal literal = (*trail)[propagation_trail_index_++];
1623  if (literal.Index() >= literal_to_watcher_.size()) continue;
1624  for (const auto entry : literal_to_watcher_[literal.Index()]) {
1625  if (!in_queue_[entry.id]) {
1626  in_queue_[entry.id] = true;
1627  queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1628  }
1629  if (entry.watch_index >= 0) {
1630  id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1631  }
1632  }
1633  }
1634 
1635  // Process the newly changed variables lower bounds.
1636  for (const IntegerVariable var : modified_vars_.PositionsSetAtLeastOnce()) {
1637  if (var.value() >= var_to_watcher_.size()) continue;
1638  for (const auto entry : var_to_watcher_[var]) {
1639  if (!in_queue_[entry.id]) {
1640  in_queue_[entry.id] = true;
1641  queue_by_priority_[id_to_priority_[entry.id]].push_back(entry.id);
1642  }
1643  if (entry.watch_index >= 0) {
1644  id_to_watch_indices_[entry.id].push_back(entry.watch_index);
1645  }
1646  }
1647  }
1648 
1649  if (trail->CurrentDecisionLevel() == 0) {
1650  const std::vector<IntegerVariable>& modified_vars =
1651  modified_vars_.PositionsSetAtLeastOnce();
1652  for (const auto& callback : level_zero_modified_variable_callback_) {
1653  callback(modified_vars);
1654  }
1655  }
1656 
1657  modified_vars_.ClearAndResize(integer_trail_->NumIntegerVariables());
1658 }
1659 
1661  // Only once per call to Propagate(), if we are at level zero, we might want
1662  // to call propagators even if the bounds didn't change.
1663  const int level = trail->CurrentDecisionLevel();
1664  if (level == 0) {
1665  for (const int id : propagator_ids_to_call_at_level_zero_) {
1666  if (in_queue_[id]) continue;
1667  in_queue_[id] = true;
1668  queue_by_priority_[id_to_priority_[id]].push_back(id);
1669  }
1670  }
1671 
1672  UpdateCallingNeeds(trail);
1673 
1674  // Note that the priority may be set to -1 inside the loop in order to restart
1675  // at zero.
1676  int test_limit = 0;
1677  for (int priority = 0; priority < queue_by_priority_.size(); ++priority) {
1678  // We test the time limit from time to time. This is in order to return in
1679  // case of slow propagation.
1680  //
1681  // TODO(user): The queue will not be emptied, but I am not sure the solver
1682  // will be left in an usable state. Fix if it become needed to resume
1683  // the solve from the last time it was interupted.
1684  if (test_limit > 100) {
1685  test_limit = 0;
1686  if (time_limit_->LimitReached()) break;
1687  }
1688 
1689  std::deque<int>& queue = queue_by_priority_[priority];
1690  while (!queue.empty()) {
1691  const int id = queue.front();
1692  current_id_ = id;
1693  queue.pop_front();
1694 
1695  // Before we propagate, make sure any reversible structure are up to date.
1696  // Note that we never do anything expensive more than once per level.
1697  {
1698  const int low =
1699  id_to_greatest_common_level_since_last_call_[IdType(id)];
1700  const int high = id_to_level_at_last_call_[id];
1701  if (low < high || level > low) { // Equivalent to not all equal.
1702  id_to_level_at_last_call_[id] = level;
1703  id_to_greatest_common_level_since_last_call_.MutableRef(IdType(id)) =
1704  level;
1705  for (ReversibleInterface* rev : id_to_reversible_classes_[id]) {
1706  if (low < high) rev->SetLevel(low);
1707  if (level > low) rev->SetLevel(level);
1708  }
1709  for (int* rev_int : id_to_reversible_ints_[id]) {
1710  rev_int_repository_->SaveState(rev_int);
1711  }
1712  }
1713  }
1714 
1715  // This is needed to detect if the propagator propagated anything or not.
1716  const int64 old_integer_timestamp = integer_trail_->num_enqueues();
1717  const int64 old_boolean_timestamp = trail->Index();
1718 
1719  // TODO(user): Maybe just provide one function Propagate(watch_indices) ?
1720  std::vector<int>& watch_indices_ref = id_to_watch_indices_[id];
1721  const bool result =
1722  watch_indices_ref.empty()
1723  ? watchers_[id]->Propagate()
1724  : watchers_[id]->IncrementalPropagate(watch_indices_ref);
1725  if (!result) {
1726  watch_indices_ref.clear();
1727  in_queue_[id] = false;
1728  return false;
1729  }
1730 
1731  // Update the propagation queue. At this point, the propagator has been
1732  // removed from the queue but in_queue_ is still true.
1733  if (id_to_idempotence_[id]) {
1734  // If the propagator is assumed to be idempotent, then we set in_queue_
1735  // to false after UpdateCallingNeeds() so this later function will never
1736  // add it back.
1737  UpdateCallingNeeds(trail);
1738  watch_indices_ref.clear();
1739  in_queue_[id] = false;
1740  } else {
1741  // Otherwise, we set in_queue_ to false first so that
1742  // UpdateCallingNeeds() may add it back if the propagator modified any
1743  // of its watched variables.
1744  watch_indices_ref.clear();
1745  in_queue_[id] = false;
1746  UpdateCallingNeeds(trail);
1747  }
1748 
1749  // If the propagator pushed a literal, we exit in order to rerun all SAT
1750  // only propagators first. Note that since a literal was pushed we are
1751  // guaranteed to be called again, and we will resume from priority 0.
1752  if (trail->Index() > old_boolean_timestamp) {
1753  // Important: for now we need to re-run the clauses propagator each time
1754  // we push a new literal because some propagator like the arc consistent
1755  // all diff relies on this.
1756  //
1757  // TODO(user): However, on some problem, it seems to work better to not
1758  // do that. One possible reason is that the reason of a "natural"
1759  // propagation might be better than one we learned.
1760  return true;
1761  }
1762 
1763  // If the propagator pushed an integer bound, we revert to priority = 0.
1764  if (integer_trail_->num_enqueues() > old_integer_timestamp) {
1765  ++test_limit;
1766  priority = -1; // Because of the ++priority in the for loop.
1767  break;
1768  }
1769  }
1770  }
1771  return true;
1772 }
1773 
1774 void GenericLiteralWatcher::Untrail(const Trail& trail, int trail_index) {
1775  if (propagation_trail_index_ <= trail_index) {
1776  // Nothing to do since we found a conflict before Propagate() was called.
1777  CHECK_EQ(propagation_trail_index_, trail_index);
1778  return;
1779  }
1780 
1781  // We need to clear the watch indices on untrail.
1782  for (std::deque<int>& queue : queue_by_priority_) {
1783  for (const int id : queue) {
1784  id_to_watch_indices_[id].clear();
1785  }
1786  queue.clear();
1787  }
1788 
1789  // This means that we already propagated all there is to propagate
1790  // at the level trail_index, so we can safely clear modified_vars_ in case
1791  // it wasn't already done.
1792  propagation_trail_index_ = trail_index;
1793  modified_vars_.ClearAndResize(integer_trail_->NumIntegerVariables());
1794  in_queue_.assign(watchers_.size(), false);
1795 }
1796 
1797 // Registers a propagator and returns its unique ids.
1799  const int id = watchers_.size();
1800  watchers_.push_back(propagator);
1801  id_to_level_at_last_call_.push_back(0);
1802  id_to_greatest_common_level_since_last_call_.GrowByOne();
1803  id_to_reversible_classes_.push_back(std::vector<ReversibleInterface*>());
1804  id_to_reversible_ints_.push_back(std::vector<int*>());
1805  id_to_watch_indices_.push_back(std::vector<int>());
1806  id_to_priority_.push_back(1);
1807  id_to_idempotence_.push_back(true);
1808 
1809  // Call this propagator at least once the next time Propagate() is called.
1810  //
1811  // TODO(user): This initial propagation does not respect any later priority
1812  // settings. Fix this. Maybe we should force users to pass the priority at
1813  // registration. For now I didn't want to change the interface because there
1814  // are plans to implement a kind of "dynamic" priority, and if it works we may
1815  // want to get rid of this altogether.
1816  in_queue_.push_back(true);
1817  queue_by_priority_[1].push_back(id);
1818  return id;
1819 }
1820 
1822  id_to_priority_[id] = priority;
1823  if (priority >= queue_by_priority_.size()) {
1824  queue_by_priority_.resize(priority + 1);
1825  }
1826 }
1827 
1829  int id) {
1830  id_to_idempotence_[id] = false;
1831 }
1832 
1834  propagator_ids_to_call_at_level_zero_.push_back(id);
1835 }
1836 
1838  ReversibleInterface* rev) {
1839  id_to_reversible_classes_[id].push_back(rev);
1840 }
1841 
1843  id_to_reversible_ints_[id].push_back(rev);
1844 }
1845 
1846 // This is really close to ExcludeCurrentSolutionAndBacktrack().
1847 std::function<void(Model*)>
1849  return [=](Model* model) {
1850  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1851  IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
1852  IntegerEncoder* encoder = model->GetOrCreate<IntegerEncoder>();
1853 
1854  const int current_level = sat_solver->CurrentDecisionLevel();
1855  std::vector<Literal> clause_to_exclude_solution;
1856  clause_to_exclude_solution.reserve(current_level);
1857  for (int i = 0; i < current_level; ++i) {
1858  bool include_decision = true;
1859  const Literal decision = sat_solver->Decisions()[i].literal;
1860 
1861  // Tests if this decision is associated to a bound of an ignored variable
1862  // in the current assignment.
1863  const InlinedIntegerLiteralVector& associated_literals =
1864  encoder->GetIntegerLiterals(decision);
1865  for (const IntegerLiteral bound : associated_literals) {
1866  if (integer_trail->IsCurrentlyIgnored(bound.var)) {
1867  // In this case we replace the decision (which is a bound on an
1868  // ignored variable) with the fact that the integer variable was
1869  // ignored. This works because the only impact a bound of an ignored
1870  // variable can have on the rest of the model is through the
1871  // is_ignored literal.
1872  clause_to_exclude_solution.push_back(
1873  integer_trail->IsIgnoredLiteral(bound.var).Negated());
1874  include_decision = false;
1875  }
1876  }
1877 
1878  if (include_decision) {
1879  clause_to_exclude_solution.push_back(decision.Negated());
1880  }
1881  }
1882 
1883  // Note that it is okay to add duplicates literals in ClauseConstraint(),
1884  // the clause will be preprocessed correctly.
1885  sat_solver->Backtrack(0);
1886  model->Add(ClauseConstraint(clause_to_exclude_solution));
1887  };
1888 }
1889 
1890 } // namespace sat
1891 } // namespace operations_research
operations_research::sat::Trail
Definition: sat_base.h:233
var
IntVar * var
Definition: expr_array.cc:1858
operations_research::sat::VariablesAssignment::LiteralIsTrue
bool LiteralIsTrue(Literal literal) const
Definition: sat_base.h:150
operations_research::sat::Trail::Enqueue
void Enqueue(Literal true_literal, int propagator_id)
Definition: sat_base.h:250
operations_research::sat::IntegerEncoder::FullDomainEncoding
std::vector< ValueLiteralPair > FullDomainEncoding(IntegerVariable var) const
Definition: integer.cc:121
operations_research::sat::IntegerLiteral
Definition: integer.h:164
operations_research::SparseBitset::ClearAndResize
void ClearAndResize(IntegerType size)
Definition: bitset.h:780
operations_research::sat::SatSolver::AddClauseDuringSearch
bool AddClauseDuringSearch(absl::Span< const Literal > literals)
Definition: sat_solver.cc:132
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:795
min
int64 min
Definition: alldiff_cst.cc:138
operations_research::sat::IntegerTrail::Index
int Index() const
Definition: integer.h:811
operations_research::sat::IntegerLiteral::GreaterOrEqual
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1197
operations_research::sat::kNoIntegerVariable
const IntegerVariable kNoIntegerVariable(-1)
operations_research::sat::FloorRatio
IntegerValue FloorRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition: integer.h:101
operations_research::sat::VariableIsPositive
bool VariableIsPositive(IntegerVariable i)
Definition: integer.h:141
max
int64 max
Definition: alldiff_cst.cc:139
time_limit.h
gtl::ITIVector::begin
iterator begin()
Definition: int_type_indexed_vector.h:137
gtl::ITIVector::end
iterator end()
Definition: int_type_indexed_vector.h:139
operations_research::sat::IntegerTrail::IsIgnoredLiteral
Literal IsIgnoredLiteral(IntegerVariable i) const
Definition: integer.h:617
operations_research::sat::IntegerTrail::IsOptional
bool IsOptional(IntegerVariable i) const
Definition: integer.h:609
bound
int64 bound
Definition: routing_search.cc:972
operations_research::sat::IntegerLiteral::var
IntegerVariable var
Definition: integer.h:198
operations_research::CapProd
int64 CapProd(int64 x, int64 y)
Definition: saturated_arithmetic.h:231
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::kNoLiteralIndex
const LiteralIndex kNoLiteralIndex(-1)
operations_research::sat::CeilRatio
IntegerValue CeilRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition: integer.h:92
operations_research::sat::IntegerTrail::Reason
absl::Span< const Literal > Reason(const Trail &trail, int trail_index) const final
Definition: integer.cc:1567
operations_research::SparseBitset::Set
void Set(IntegerType index)
Definition: bitset.h:805
operations_research::sat::IntegerTrail::UpperBound
IntegerValue UpperBound(IntegerVariable i) const
Definition: integer.h:1221
operations_research::sat::GetPositiveOnlyIndex
PositiveOnlyIndex GetPositiveOnlyIndex(IntegerVariable var)
Definition: integer.h:151
operations_research::sat::GenericLiteralWatcher::Propagate
bool Propagate(Trail *trail) final
Definition: integer.cc:1660
operations_research::sat::IntegerTrail::LevelZeroLowerBound
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
Definition: integer.h:1267
operations_research::sat::AssignmentInfo::level
uint32 level
Definition: sat_base.h:199
operations_research::sat::PropagatorInterface
Definition: integer.h:1008
operations_research::sat::GenericLiteralWatcher::GenericLiteralWatcher
GenericLiteralWatcher(Model *model)
Definition: integer.cc:1602
operations_research::RevVector::MutableRef
T & MutableRef(IndexType index)
Definition: rev.h:95
operations_research::sat::VariablesAssignment
Definition: sat_base.h:122
operations_research::sat::SatSolver::NewBooleanVariable
BooleanVariable NewBooleanVariable()
Definition: sat_solver.h:84
operations_research::sat::AffineExpression::coeff
IntegerValue coeff
Definition: integer.h:237
operations_research::sat::IntegerTrail::RegisterWatcher
void RegisterWatcher(SparseBitset< IntegerVariable > *p)
Definition: integer.h:777
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:743
operations_research::sat::RevIntRepository
Definition: integer.h:1039
value
int64 value
Definition: demon_profiler.cc:43
operations_research::Domain::end
absl::InlinedVector< ClosedInterval, 1 >::const_iterator end() const
Definition: sorted_interval_list.h:343
operations_research::sat::IntegerTrail::num_enqueues
int64 num_enqueues() const
Definition: integer.h:768
operations_research::sat::IntegerEncoder::NewlyFixedIntegerLiterals
const std::vector< IntegerLiteral > NewlyFixedIntegerLiterals() const
Definition: integer.h:411
operations_research::sat::IntegerLiteral::DebugString
std::string DebugString() const
Definition: integer.h:191
gtl::ITIVector::resize
void resize(size_type new_size)
Definition: int_type_indexed_vector.h:149
operations_research::sat::IntegerTrail::AddIntegerVariable
IntegerVariable AddIntegerVariable()
Definition: integer.h:600
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::Trail::Index
int Index() const
Definition: sat_base.h:378
operations_research::sat::NegationOf
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Definition: integer.cc:42
gtl::ITIVector::reserve
void reserve(size_type n)
Definition: int_type_indexed_vector.h:156
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:965
operations_research::sat::IntegerTrail::IsCurrentlyIgnored
bool IsCurrentlyIgnored(IntegerVariable i) const
Definition: integer.h:612
operations_research::sat::IntegerEncoder::ValueLiteralPair
Definition: integer.h:318
operations_research::sat::IntegerEncoder::ValueLiteralPair::literal
Literal literal
Definition: integer.h:327
operations_research::RevMap::Set
void Set(key_type key, mapped_type value)
Definition: rev.h:238
operations_research::sat::IntegerEncoder::GetTrueLiteral
Literal GetTrueLiteral()
Definition: integer.h:439
kint64min
static const int64 kint64min
Definition: integral_types.h:60
operations_research::ClosedInterval
Represents a closed interval [start, end].
Definition: sorted_interval_list.h:33
operations_research::sat::GenericLiteralWatcher::Register
int Register(PropagatorInterface *propagator)
Definition: integer.cc:1798
operations_research::sat::IntegerTrail
Definition: integer.h:534
operations_research::sat::GenericLiteralWatcher::NotifyThatPropagatorMayNotReachFixedPointInOnePass
void NotifyThatPropagatorMayNotReachFixedPointInOnePass(int id)
Definition: integer.cc:1828
operations_research::sat::SatSolver::AddBinaryClause
bool AddBinaryClause(Literal a, Literal b)
Definition: sat_solver.cc:178
operations_research::sat::PositiveVariable
IntegerVariable PositiveVariable(IntegerVariable i)
Definition: integer.h:145
int64
int64_t int64
Definition: integral_types.h:34
gtl::ITIVector::size
size_type size() const
Definition: int_type_indexed_vector.h:146
operations_research::sat::IntegerEncoder::GetOrCreateAssociatedLiteral
Literal GetOrCreateAssociatedLiteral(IntegerLiteral i_lit)
Definition: integer.cc:217
operations_research::Domain
We call domain any subset of Int64 = [kint64min, kint64max].
Definition: sorted_interval_list.h:81
operations_research::sat::GenericLiteralWatcher::RegisterReversibleClass
void RegisterReversibleClass(int id, ReversibleInterface *rev)
Definition: integer.cc:1837
operations_research::sat::Model
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
index
int index
Definition: pack.cc:508
operations_research::sat::IntegerEncoder::PartialDomainEncoding
std::vector< ValueLiteralPair > PartialDomainEncoding(IntegerVariable var) const
Definition: integer.cc:127
operations_research::sat::IntegerEncoder::AssociateToIntegerEqualValue
void AssociateToIntegerEqualValue(Literal literal, IntegerVariable var, IntegerValue value)
Definition: integer.cc:323
operations_research::sat::IntegerEncoder::Canonicalize
std::pair< IntegerLiteral, IntegerLiteral > Canonicalize(IntegerLiteral i_lit) const
Definition: integer.cc:199
operations_research::sat::SatSolver
Definition: sat_solver.h:58
operations_research::sat::Trail::GetEmptyVectorToStoreReason
std::vector< Literal > * GetEmptyVectorToStoreReason(int trail_index) const
Definition: sat_base.h:320
operations_research::sat::Trail::CurrentDecisionLevel
int CurrentDecisionLevel() const
Definition: sat_base.h:355
operations_research::sat::IntegerTrail::RegisterReversibleClass
void RegisterReversibleClass(ReversibleInterface *rev)
Definition: integer.h:807
operations_research::sat::IntegerTrail::Untrail
void Untrail(const Trail &trail, int literal_trail_index) final
Definition: integer.cc:538
operations_research::sat::IntegerTrail::InitialVariableDomain
const Domain & InitialVariableDomain(IntegerVariable var) const
Definition: integer.cc:632
operations_research::sat::Literal
Definition: sat_base.h:64
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::sat::IntegerEncoder::SearchForLiteralAtOrBefore
LiteralIndex SearchForLiteralAtOrBefore(IntegerLiteral i, IntegerValue *bound) const
Definition: integer.cc:475
operations_research::RevRepository::SaveState
void SaveState(T *object)
Definition: rev.h:61
DEBUG_MODE
const bool DEBUG_MODE
Definition: macros.h:24
a
int64 a
Definition: constraint_solver/table.cc:42
operations_research::Domain::IsEmpty
bool IsEmpty() const
Returns true if this is the empty set.
Definition: sorted_interval_list.cc:190
operations_research::sat::IntegerEncoder
Definition: integer.h:278
operations_research::sat::Literal::Negated
Literal Negated() const
Definition: sat_base.h:91
operations_research::sat::IntegerTrail::Propagate
bool Propagate(Trail *trail) final
Definition: integer.cc:488
operations_research::sat::IntegerTrail::NumConstantVariables
int NumConstantVariables() const
Definition: integer.cc:698
kint32max
static const int32 kint32max
Definition: integral_types.h:59
operations_research::sat::IntegerEncoder::GetOrCreateLiteralAssociatedToEquality
Literal GetOrCreateLiteralAssociatedToEquality(IntegerVariable var, IntegerValue value)
Definition: integer.cc:263
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::SatPropagator::propagation_trail_index_
int propagation_trail_index_
Definition: sat_base.h:506
operations_research::RevMap::SetLevel
void SetLevel(int level) final
Definition: rev.h:206
operations_research::sat::kMaxIntegerValue
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
operations_research::sat::IntegerLiteral::bound
IntegerValue bound
Definition: integer.h:199
operations_research::sat::IntegerTrail::RelaxLinearReason
void RelaxLinearReason(IntegerValue slack, absl::Span< const IntegerValue > coeffs, std::vector< IntegerLiteral > *reason) const
Definition: integer.cc:773
operations_research::sat::SatPropagator::propagator_id_
int propagator_id_
Definition: sat_base.h:505
operations_research::sat::IntegerTrail::AppendNewBounds
void AppendNewBounds(std::vector< IntegerLiteral > *output) const
Definition: integer.cc:1587
representative
ColIndex representative
Definition: preprocessor.cc:424
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::ReversibleInterface
Definition: rev.h:29
operations_research::sat::Trail::Assignment
const VariablesAssignment & Assignment() const
Definition: sat_base.h:380
operations_research::sat::IntegerTrail::NumIntegerVariables
IntegerVariable NumIntegerVariables() const
Definition: integer.h:558
operations_research::sat::IntegerEncoder::ClearNewlyFixedIntegerLiterals
void ClearNewlyFixedIntegerLiterals()
Definition: integer.h:414
operations_research::sat::Trail::EnqueueWithUnitReason
void EnqueueWithUnitReason(Literal true_literal)
Definition: sat_base.h:265
operations_research::SparseBitset::PositionsSetAtLeastOnce
const std::vector< IntegerType > & PositionsSetAtLeastOnce() const
Definition: bitset.h:815
operations_research::sat::IntegerTrail::ReserveSpaceForNumVariables
void ReserveSpaceForNumVariables(int num_vars)
Definition: integer.cc:580
operations_research::sat::IntegerTrail::ReportConflict
bool ReportConflict(absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.h:784
operations_research::sat::IntegerTrail::ReasonFor
std::vector< Literal > ReasonFor(IntegerLiteral literal) const
Definition: integer.cc:1421
operations_research::sat::Trail::Info
const AssignmentInfo & Info(BooleanVariable var) const
Definition: sat_base.h:381
operations_research::sat::SatSolver::Assignment
const VariablesAssignment & Assignment() const
Definition: sat_solver.h:363
operations_research::sat::ExcludeCurrentSolutionWithoutIgnoredVariableAndBacktrack
std::function< void(Model *)> ExcludeCurrentSolutionWithoutIgnoredVariableAndBacktrack()
Definition: integer.cc:1848
operations_research::sat::Trail::MutableConflict
std::vector< Literal > * MutableConflict()
Definition: sat_base.h:361
operations_research::sat::Trail::NumVariables
int NumVariables() const
Definition: sat_base.h:376
operations_research::sat::ClauseConstraint
std::function< void(Model *)> ClauseConstraint(absl::Span< const Literal > literals)
Definition: sat_solver.h:884
callback
MPCallback * callback
Definition: gurobi_interface.cc:440
model
GRBmodel * model
Definition: gurobi_interface.cc:195
operations_research::sat::SatSolver::CurrentDecisionLevel
int CurrentDecisionLevel() const
Definition: sat_solver.h:361
operations_research::sat::IntegerTrail::MergeReasonInto
void MergeReasonInto(absl::Span< const IntegerLiteral > literals, std::vector< Literal > *output) const
Definition: integer.cc:1429
operations_research::sat::SatPropagator
Definition: sat_base.h:444
operations_research::sat::GenericLiteralWatcher::SetPropagatorPriority
void SetPropagatorPriority(int id, int priority)
Definition: integer.cc:1821
operations_research::sat::SatSolver::Decisions
const std::vector< Decision > & Decisions() const
Definition: sat_solver.h:360
operations_research::sat::SatSolver::AddUnitClause
bool AddUnitClause(Literal true_literal)
Definition: sat_solver.cc:162
operations_research::sat::IntegerTrail::LowerBound
IntegerValue LowerBound(IntegerVariable i) const
Definition: integer.h:1217
operations_research::sat::IntegerTrail::UpdateInitialDomain
bool UpdateInitialDomain(IntegerVariable var, Domain domain)
Definition: integer.cc:636
operations_research::sat::kMinIntegerValue
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
operations_research::sat::IntegerEncoder::FullyEncodeVariable
void FullyEncodeVariable(IntegerVariable var)
Definition: integer.cc:51
stl_util.h
gtl::InsertOrDie
void InsertOrDie(Collection *const collection, const typename Collection::value_type &value)
Definition: map_util.h:135
operations_research::sat::IntegerEncoder::GetFalseLiteral
Literal GetFalseLiteral()
Definition: integer.h:449
operations_research::sat::SatSolver::Backtrack
void Backtrack(int target_level)
Definition: sat_solver.cc:886
operations_research::Domain::Negation
Domain Negation() const
Returns {x ∈ Int64, ∃ e ∈ D, x = -e}.
Definition: sorted_interval_list.cc:261
iterator_adaptors.h
operations_research::RevMap::FindOrDie
const mapped_type & FindOrDie(key_type key) const
Definition: rev.h:172
operations_research::sat::VariablesAssignment::LiteralIsFalse
bool LiteralIsFalse(Literal literal) const
Definition: sat_base.h:147
operations_research::sat::AffineExpression::var
IntegerVariable var
Definition: integer.h:236
operations_research::sat::AffineExpression::constant
IntegerValue constant
Definition: integer.h:238
operations_research::sat::AffineExpression::GreaterOrEqual
IntegerLiteral GreaterOrEqual(IntegerValue bound) const
Definition: integer.cc:28
operations_research::sat::IntegerLiteral::LowerOrEqual
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1203
operations_research::sat::IntegerTrail::EnqueueLiteral
void EnqueueLiteral(Literal literal, absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.cc:1034
b
int64 b
Definition: constraint_solver/table.cc:43
operations_research::sat::GenericLiteralWatcher::AlwaysCallAtLevelZero
void AlwaysCallAtLevelZero(int id)
Definition: integer.cc:1833
operations_research::sat::IntegerEncoder::GetIntegerLiterals
const InlinedIntegerLiteralVector & GetIntegerLiterals(Literal lit) const
Definition: integer.h:392
operations_research::RevVector::GrowByOne
void GrowByOne()
Definition: rev.h:108
interval
IntervalVar * interval
Definition: resource.cc:98
operations_research::sat::IntegerEncoder::GetAssociatedEqualityLiteral
LiteralIndex GetAssociatedEqualityLiteral(IntegerVariable var, IntegerValue value) const
Definition: integer.cc:253
operations_research::glop::Index
int32 Index
Definition: lp_types.h:37
operations_research::sat::AffineExpression::LowerOrEqual
IntegerLiteral LowerOrEqual(IntegerValue bound) const
Definition: integer.cc:36
gtl::ITIVector::push_back
void push_back(const value_type &x)
Definition: int_type_indexed_vector.h:157
operations_research::sat::IntegerEncoder::VariableIsFullyEncoded
bool VariableIsFullyEncoded(IntegerVariable var) const
Definition: integer.cc:83
operations_research::sat::IntegerEncoder::AssociateToIntegerLiteral
void AssociateToIntegerLiteral(Literal literal, IntegerLiteral i_lit)
Definition: integer.cc:297
operations_research::Domain::Max
int64 Max() const
Returns the max value of the domain.
Definition: sorted_interval_list.cc:211
operations_research::Domain::Min
int64 Min() const
Returns the min value of the domain.
Definition: sorted_interval_list.cc:206
operations_research::SparseBitset< IntegerVariable >
literal
Literal literal
Definition: optimization.cc:84
operations_research::sat::IntegerEncoder::LiteralIsAssociated
bool LiteralIsAssociated(IntegerLiteral i_lit) const
Definition: integer.cc:461
operations_research::sat::IntegerEncoder::GetAssociatedLiteral
LiteralIndex GetAssociatedLiteral(IntegerLiteral i_lit) const
Definition: integer.cc:467
operations_research::sat::IntegerTrail::GetOrCreateConstantIntegerVariable
IntegerVariable GetOrCreateConstantIntegerVariable(IntegerValue value)
Definition: integer.cc:683
operations_research::sat::VariablesAssignment::LiteralIsAssigned
bool LiteralIsAssigned(Literal literal) const
Definition: sat_base.h:153
operations_research::sat::IntegerTrail::RemoveLevelZeroBounds
void RemoveLevelZeroBounds(std::vector< IntegerLiteral > *reason) const
Definition: integer.cc:895
operations_research::sat::IntegerEncoder::AddAllImplicationsBetweenAssociatedLiterals
void AddAllImplicationsBetweenAssociatedLiterals()
Definition: integer.cc:183
operations_research::sat::Literal::Index
LiteralIndex Index() const
Definition: sat_base.h:84
operations_research::sat::GenericLiteralWatcher::Untrail
void Untrail(const Trail &trail, int literal_trail_index) final
Definition: integer.cc:1774
operations_research::sat::InlinedIntegerLiteralVector
absl::InlinedVector< IntegerLiteral, 2 > InlinedIntegerLiteralVector
Definition: integer.h:207
integer.h
operations_research::sat::IntegerTrail::FindTrailIndexOfVarBefore
int FindTrailIndexOfVarBefore(IntegerVariable var, int threshold) const
Definition: integer.cc:704
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::GenericLiteralWatcher::RegisterReversibleInt
void RegisterReversibleInt(int id, int *rev)
Definition: integer.cc:1842