OR-Tools  8.0
presolve_context.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 
15 
16 #include "ortools/base/map_util.h"
17 #include "ortools/base/mathutil.h"
19 
20 namespace operations_research {
21 namespace sat {
22 
24  return context->GetLiteralRepresentative(ref_);
25 }
26 
28  return context->GetVariableRepresentative(ref_);
29 }
30 
32 
33 int PresolveContext::NewIntVar(const Domain& domain) {
34  IntegerVariableProto* const var = working_model->add_variables();
35  FillDomainInProto(domain, var);
37  return working_model->variables_size() - 1;
38 }
39 
41 
43  if (!gtl::ContainsKey(constant_to_ref_, cst)) {
44  constant_to_ref_[cst] = SavedVariable(working_model->variables_size());
45  IntegerVariableProto* const var_proto = working_model->add_variables();
46  var_proto->add_domain(cst);
47  var_proto->add_domain(cst);
49  }
50  return constant_to_ref_[cst].Get(this);
51 }
52 
53 // a => b.
55  ConstraintProto* const ct = working_model->add_constraints();
56  ct->add_enforcement_literal(a);
57  ct->mutable_bool_and()->add_literals(b);
58 }
59 
60 // b => x in [lb, ub].
61 void PresolveContext::AddImplyInDomain(int b, int x, const Domain& domain) {
62  ConstraintProto* const imply = working_model->add_constraints();
63 
64  // Doing it like this seems to use slightly less memory.
65  // TODO(user): Find the best way to create such small proto.
66  imply->mutable_enforcement_literal()->Resize(1, b);
67  LinearConstraintProto* mutable_linear = imply->mutable_linear();
68  mutable_linear->mutable_vars()->Resize(1, x);
69  mutable_linear->mutable_coeffs()->Resize(1, 1);
70  FillDomainInProto(domain, mutable_linear);
71 }
72 
73 bool PresolveContext::DomainIsEmpty(int ref) const {
74  return domains[PositiveRef(ref)].IsEmpty();
75 }
76 
77 bool PresolveContext::IsFixed(int ref) const {
78  DCHECK_LT(PositiveRef(ref), domains.size());
79  DCHECK(!DomainIsEmpty(ref));
80  return domains[PositiveRef(ref)].IsFixed();
81 }
82 
84  const int var = PositiveRef(ref);
85  return domains[var].Min() >= 0 && domains[var].Max() <= 1;
86 }
87 
88 bool PresolveContext::LiteralIsTrue(int lit) const {
89  DCHECK(CanBeUsedAsLiteral(lit));
90  if (RefIsPositive(lit)) {
91  return domains[lit].Min() == 1;
92  } else {
93  return domains[PositiveRef(lit)].Max() == 0;
94  }
95 }
96 
97 bool PresolveContext::LiteralIsFalse(int lit) const {
98  DCHECK(CanBeUsedAsLiteral(lit));
99  if (RefIsPositive(lit)) {
100  return domains[lit].Max() == 0;
101  } else {
102  return domains[PositiveRef(lit)].Min() == 1;
103  }
104 }
105 
107  DCHECK(!DomainIsEmpty(ref));
108  return RefIsPositive(ref) ? domains[PositiveRef(ref)].Min()
109  : -domains[PositiveRef(ref)].Max();
110 }
111 
113  DCHECK(!DomainIsEmpty(ref));
114  return RefIsPositive(ref) ? domains[PositiveRef(ref)].Max()
115  : -domains[PositiveRef(ref)].Min();
116 }
117 
118 int64 PresolveContext::MinOf(const LinearExpressionProto& expr) const {
119  int64 result = expr.offset();
120  for (int i = 0; i < expr.vars_size(); ++i) {
121  const int64 coeff = expr.coeffs(i);
122  if (coeff > 0) {
123  result += coeff * MinOf(expr.vars(i));
124  } else {
125  result += coeff * MaxOf(expr.vars(i));
126  }
127  }
128  return result;
129 }
130 
131 int64 PresolveContext::MaxOf(const LinearExpressionProto& expr) const {
132  int64 result = expr.offset();
133  for (int i = 0; i < expr.vars_size(); ++i) {
134  const int64 coeff = expr.coeffs(i);
135  if (coeff > 0) {
136  result += coeff * MaxOf(expr.vars(i));
137  } else {
138  result += coeff * MinOf(expr.vars(i));
139  }
140  }
141  return result;
142 }
143 
144 // Important: To be sure a variable can be removed, we need it to not be a
145 // representative of both affine and equivalence relation.
146 bool PresolveContext::VariableIsNotRepresentativeOfEquivalenceClass(
147  int var) const {
148  DCHECK(RefIsPositive(var));
149  if (affine_relations_.ClassSize(var) > 1 &&
150  affine_relations_.Get(var).representative == var) {
151  return false;
152  }
153  if (var_equiv_relations_.ClassSize(var) > 1 &&
154  var_equiv_relations_.Get(var).representative == var) {
155  return false;
156  }
157  return true;
158 }
159 
160 // Tricky: If this variable is equivalent to another one (but not the
161 // representative) and appear in just one constraint, then this constraint must
162 // be the affine defining one. And in this case the code using this function
163 // should do the proper stuff.
165  if (!ConstraintVariableGraphIsUpToDate()) return false;
166  const int var = PositiveRef(ref);
167  return var_to_constraints_[var].size() == 1 &&
168  VariableIsNotRepresentativeOfEquivalenceClass(var) &&
170 }
171 
172 // Tricky: Same remark as for VariableIsUniqueAndRemovable().
174  if (!ConstraintVariableGraphIsUpToDate()) return false;
175  const int var = PositiveRef(ref);
176  return !keep_all_feasible_solutions &&
177  var_to_constraints_[var].contains(kObjectiveConstraint) &&
178  var_to_constraints_[var].size() == 2 &&
179  VariableIsNotRepresentativeOfEquivalenceClass(var);
180 }
181 
182 // Here, even if the variable is equivalent to others, if its affine defining
183 // constraints where removed, then it is not needed anymore.
185  if (!ConstraintVariableGraphIsUpToDate()) return false;
186  return var_to_constraints_[PositiveRef(ref)].empty();
187 }
188 
190  removed_variables_.insert(PositiveRef(ref));
191 }
192 
193 // Note(user): I added an indirection and a function for this to be able to
194 // display debug information when this return false. This should actually never
195 // return false in the cases where it is used.
197  // It is okay to reuse removed fixed variable.
198  if (IsFixed(ref)) return false;
199  if (!removed_variables_.contains(PositiveRef(ref))) return false;
200  if (!var_to_constraints_[PositiveRef(ref)].empty()) {
202  LOG(INFO) << "Variable " << PositiveRef(ref)
203  << " was removed, yet it appears in some constraints!";
204  LOG(INFO) << "affine relation = " << r.coeff << " * X" << r.representative
205  << " + " << r.offset;
206  for (const int c : var_to_constraints_[PositiveRef(ref)]) {
207  LOG(INFO) << "constraint #" << c << " : "
208  << (c >= 0 ? working_model->constraints(c).ShortDebugString()
209  : "");
210  }
211  }
212  return true;
213 }
214 
216  if (!ConstraintVariableGraphIsUpToDate()) return false;
217  const int var = PositiveRef(ref);
218  return var_to_num_linear1_[var] == var_to_constraints_[var].size();
219 }
220 
222  Domain result;
223  if (RefIsPositive(ref)) {
224  result = domains[ref];
225  } else {
226  result = domains[PositiveRef(ref)].Negation();
227  }
228  return result;
229 }
230 
232  if (!RefIsPositive(ref)) {
233  return domains[PositiveRef(ref)].Contains(-value);
234  }
235  return domains[ref].Contains(value);
236 }
237 
238 ABSL_MUST_USE_RESULT bool PresolveContext::IntersectDomainWith(
239  int ref, const Domain& domain, bool* domain_modified) {
240  DCHECK(!DomainIsEmpty(ref));
241  const int var = PositiveRef(ref);
242 
243  if (RefIsPositive(ref)) {
244  if (domains[var].IsIncludedIn(domain)) {
245  return true;
246  }
247  domains[var] = domains[var].IntersectionWith(domain);
248  } else {
249  const Domain temp = domain.Negation();
250  if (domains[var].IsIncludedIn(temp)) {
251  return true;
252  }
253  domains[var] = domains[var].IntersectionWith(temp);
254  }
255 
256  if (domain_modified != nullptr) {
257  *domain_modified = true;
258  }
260  if (domains[var].IsEmpty()) {
261  is_unsat = true;
262  return false;
263  }
264 
265  // Propagate the domain of the representative right away.
266  // Note that the recursive call should only by one level deep.
268  if (r.representative == var) return true;
270  DomainOf(var)
271  .AdditionWith(Domain(-r.offset))
273 }
274 
275 ABSL_MUST_USE_RESULT bool PresolveContext::SetLiteralToFalse(int lit) {
276  const int var = PositiveRef(lit);
277  const int64 value = RefIsPositive(lit) ? 0 : 1;
279 }
280 
281 ABSL_MUST_USE_RESULT bool PresolveContext::SetLiteralToTrue(int lit) {
282  return SetLiteralToFalse(NegatedRef(lit));
283 }
284 
285 void PresolveContext::UpdateRuleStats(const std::string& name) {
286  if (enable_stats) {
287  VLOG(1) << num_presolve_operations << " : " << name;
289  }
291 }
292 
293 void PresolveContext::UpdateLinear1Usage(const ConstraintProto& ct, int c) {
294  const int old_var = constraint_to_linear1_var_[c];
295  if (old_var >= 0) {
296  var_to_num_linear1_[old_var]--;
297  }
298  if (ct.constraint_case() == ConstraintProto::ConstraintCase::kLinear &&
299  ct.linear().vars().size() == 1) {
300  const int var = PositiveRef(ct.linear().vars(0));
301  constraint_to_linear1_var_[c] = var;
302  var_to_num_linear1_[var]++;
303  }
304 }
305 
306 void PresolveContext::AddVariableUsage(int c) {
307  const ConstraintProto& ct = working_model->constraints(c);
308  constraint_to_vars_[c] = UsedVariables(ct);
309  constraint_to_intervals_[c] = UsedIntervals(ct);
310  for (const int v : constraint_to_vars_[c]) {
311  DCHECK(!VariableWasRemoved(v));
312  var_to_constraints_[v].insert(c);
313  }
314  for (const int i : constraint_to_intervals_[c]) interval_usage_[i]++;
315  UpdateLinear1Usage(ct, c);
316 }
317 
319  if (is_unsat) return;
320  DCHECK_EQ(constraint_to_vars_.size(), working_model->constraints_size());
321  const ConstraintProto& ct = working_model->constraints(c);
322 
323  // We don't optimize the interval usage as this is not super frequent.
324  for (const int i : constraint_to_intervals_[c]) interval_usage_[i]--;
325  constraint_to_intervals_[c] = UsedIntervals(ct);
326  for (const int i : constraint_to_intervals_[c]) interval_usage_[i]++;
327 
328  // For the variables, we avoid an erase() followed by an insert() for the
329  // variables that didn't change.
330  tmp_new_usage_ = UsedVariables(ct);
331  const std::vector<int>& old_usage = constraint_to_vars_[c];
332  const int old_size = old_usage.size();
333  int i = 0;
334  for (const int var : tmp_new_usage_) {
335  DCHECK(!VariableWasRemoved(var));
336  while (i < old_size && old_usage[i] < var) {
337  var_to_constraints_[old_usage[i]].erase(c);
338  ++i;
339  }
340  if (i < old_size && old_usage[i] == var) {
341  ++i;
342  } else {
343  var_to_constraints_[var].insert(c);
344  }
345  }
346  for (; i < old_size; ++i) var_to_constraints_[old_usage[i]].erase(c);
347  constraint_to_vars_[c] = tmp_new_usage_;
348 
349  UpdateLinear1Usage(ct, c);
350 }
351 
353  return constraint_to_vars_.size() == working_model->constraints_size();
354 }
355 
357  if (is_unsat) return;
358  const int old_size = constraint_to_vars_.size();
359  const int new_size = working_model->constraints_size();
360  CHECK_LE(old_size, new_size);
361  constraint_to_vars_.resize(new_size);
362  constraint_to_linear1_var_.resize(new_size, -1);
363  constraint_to_intervals_.resize(new_size);
364  interval_usage_.resize(new_size);
365  for (int c = old_size; c < new_size; ++c) {
366  AddVariableUsage(c);
367  }
368 }
369 
370 // TODO(user): Also test var_to_constraints_ !!
372  if (is_unsat) return true; // We do not care in this case.
373  if (constraint_to_vars_.size() != working_model->constraints_size()) {
374  LOG(INFO) << "Wrong constraint_to_vars size!";
375  return false;
376  }
377  for (int c = 0; c < constraint_to_vars_.size(); ++c) {
378  if (constraint_to_vars_[c] !=
379  UsedVariables(working_model->constraints(c))) {
380  LOG(INFO) << "Wrong variables usage for constraint: \n"
381  << ProtobufDebugString(working_model->constraints(c))
382  << "old_size: " << constraint_to_vars_[c].size();
383  return false;
384  }
385  }
386  int num_in_objective = 0;
387  for (int v = 0; v < var_to_constraints_.size(); ++v) {
388  if (var_to_constraints_[v].contains(kObjectiveConstraint)) {
389  ++num_in_objective;
390  if (!objective_map.contains(v)) {
391  LOG(INFO) << "Variable " << v
392  << " is marked as part of the objective but isn't.";
393  return false;
394  }
395  }
396  }
397  if (num_in_objective != objective_map.size()) {
398  LOG(INFO) << "Not all variables are marked as part of the objective";
399  return false;
400  }
401 
402  return true;
403 }
404 
405 // If a Boolean variable (one with domain [0, 1]) appear in this affine
406 // equivalence class, then we want its representative to be Boolean. Note that
407 // this is always possible because a Boolean variable can never be equal to a
408 // multiple of another if std::abs(coeff) is greater than 1 and if it is not
409 // fixed to zero. This is important because it allows to simply use the same
410 // representative for any referenced literals.
411 //
412 // Note(user): When both domain contains [0,1] and later the wrong variable
413 // become usable as boolean, then we have a bug. Because of that, the code
414 // for GetLiteralRepresentative() is not as simple as it should be.
415 bool PresolveContext::AddRelation(int x, int y, int64 c, int64 o,
416  AffineRelation* repo) {
417  // When the coefficient is larger than one, then if later one variable becomes
418  // Boolean, it must be the representative.
419  if (std::abs(c) != 1) return repo->TryAdd(x, y, c, o);
420 
421  CHECK(!VariableWasRemoved(x));
422  CHECK(!VariableWasRemoved(y));
423 
424  // To avoid integer overflow, we always want to use the representative with
425  // the smallest domain magnitude. Otherwise we might express a variable in say
426  // [0, 3] as ([x, x + 3] - x) for an arbitrary large x, and substituting
427  // something like this in a linear expression could break our overflow
428  // precondition.
429  //
430  // Note that if either rep_x or rep_y can be used as a literal, then it will
431  // also be the variable with the smallest domain magnitude (1 or 0 if fixed).
432  const int rep_x = repo->Get(x).representative;
433  const int rep_y = repo->Get(y).representative;
434  const int64 m_x = std::max(std::abs(MinOf(rep_x)), std::abs(MaxOf(rep_x)));
435  const int64 m_y = std::max(std::abs(MinOf(rep_y)), std::abs(MaxOf(rep_y)));
436  bool allow_rep_x = m_x < m_y;
437  bool allow_rep_y = m_y < m_x;
438  if (m_x == m_y) {
439  // If both magnitude are the same, we prefer a positive domain.
440  // This is important so we don't use [-1, 0] as a representative for [0, 1].
441  allow_rep_x = MinOf(rep_x) >= MinOf(rep_y);
442  allow_rep_y = MinOf(rep_y) >= MinOf(rep_x);
443  }
444  return repo->TryAdd(x, y, c, o, allow_rep_x, allow_rep_y);
445 }
446 
448  CHECK(RefIsPositive(var));
449  CHECK(IsFixed(var));
450  const int min = MinOf(var);
451  if (gtl::ContainsKey(constant_to_ref_, min)) {
452  const int rep = constant_to_ref_[min].Get(this);
453  if (RefIsPositive(rep)) {
454  if (rep != var) {
455  AddRelation(var, rep, 1, 0, &affine_relations_);
456  AddRelation(var, rep, 1, 0, &var_equiv_relations_);
457  }
458  } else {
459  if (PositiveRef(rep) == var) {
460  CHECK_EQ(min, 0);
461  } else {
462  AddRelation(var, PositiveRef(rep), -1, 0, &affine_relations_);
463  AddRelation(var, PositiveRef(rep), -1, 0, &var_equiv_relations_);
464  }
465  }
466  } else {
467  constant_to_ref_[min] = SavedVariable(var);
468  }
469 }
470 
472  const int var = PositiveRef(ref);
474  if (r.representative == var) return true;
475 
476  // Propagate domains both ways.
477  // var = coeff * rep + offset
479  DomainOf(var)
480  .AdditionWith(Domain(-r.offset))
482  return false;
483  }
486  .AdditionWith(Domain(r.offset)))) {
487  return false;
488  }
489 
490  return true;
491 }
492 
494  for (auto& ref_map : var_to_constraints_) {
495  ref_map.erase(kAffineRelationConstraint);
496  }
497 }
498 
499 // We only call that for a non representative variable that is only used in
500 // the kAffineRelationConstraint. Such variable can be ignored and should never
501 // be seen again in the presolve.
503  const int rep = GetAffineRelation(var).representative;
504 
505  CHECK(RefIsPositive(var));
506  CHECK_NE(var, rep);
507  CHECK_EQ(var_to_constraints_[var].size(), 1);
508  CHECK(var_to_constraints_[var].contains(kAffineRelationConstraint));
509  CHECK(var_to_constraints_[rep].contains(kAffineRelationConstraint));
510 
511  // We shouldn't reuse this variable again!
513 
514  var_to_constraints_[var].erase(kAffineRelationConstraint);
515  affine_relations_.IgnoreFromClassSize(var);
516  var_equiv_relations_.IgnoreFromClassSize(var);
517 
518  // If the representative is left alone, we can remove it from the special
519  // affine relation constraint too.
520  if (affine_relations_.ClassSize(rep) == 1 &&
521  var_equiv_relations_.ClassSize(rep) == 1) {
522  var_to_constraints_[rep].erase(kAffineRelationConstraint);
523  }
524 
525  if (VLOG_IS_ON(2)) {
526  const auto r = GetAffineRelation(var);
527  LOG(INFO) << "Removing affine relation for " << var << " : "
528  << DomainOf(var) << " = " << r.coeff << " * "
529  << DomainOf(r.representative) << " + " << r.offset
530  << " ( rep : " << rep << ").";
531  }
532 }
533 
534 bool PresolveContext::StoreAffineRelation(int ref_x, int ref_y, int64 coeff,
535  int64 offset) {
536  CHECK_NE(coeff, 0);
537  if (is_unsat) return false;
538 
539  // TODO(user): I am not 100% sure why, but sometimes the representative is
540  // fixed but that is not propagated to ref_x or ref_y and this causes issues.
541  if (!PropagateAffineRelation(ref_x)) return true;
542  if (!PropagateAffineRelation(ref_y)) return true;
543 
544  if (IsFixed(ref_x)) {
545  const int64 lhs = DomainOf(ref_x).Min() - offset;
546  if (lhs % std::abs(coeff) != 0) {
547  is_unsat = true;
548  return true;
549  }
550  static_cast<void>(IntersectDomainWith(ref_y, Domain(lhs / coeff)));
551  UpdateRuleStats("affine: fixed");
552  return true;
553  }
554 
555  if (IsFixed(ref_y)) {
556  const int64 value_x = DomainOf(ref_y).Min() * coeff + offset;
557  static_cast<void>(IntersectDomainWith(ref_x, Domain(value_x)));
558  UpdateRuleStats("affine: fixed");
559  return true;
560  }
561 
562  // If both are already in the same class, we need to make sure the relations
563  // are compatible.
566  if (rx.representative == ry.representative) {
567  // x = rx.coeff * rep + rx.offset;
568  // y = ry.coeff * rep + ry.offset_y;
569  // And x == coeff * ry.coeff * rep + (coeff * ry.offset + offset).
570  //
571  // So we get the relation a * rep == b with a and b defined here:
572  const int64 a = coeff * ry.coeff - rx.coeff;
573  const int64 b = coeff * ry.offset + offset - rx.offset;
574  if (a == 0) {
575  if (b != 0) is_unsat = true;
576  return true;
577  }
578  if (b % a != 0) {
579  is_unsat = true;
580  return true;
581  }
582  UpdateRuleStats("affine: unique solution");
583  const int64 unique_value = -b / a;
584  if (!IntersectDomainWith(rx.representative, Domain(unique_value))) {
585  return true;
586  }
587  if (!IntersectDomainWith(ref_x,
588  Domain(unique_value * rx.coeff + rx.offset))) {
589  return true;
590  }
591  if (!IntersectDomainWith(ref_y,
592  Domain(unique_value * ry.coeff + ry.offset))) {
593  return true;
594  }
595  return true;
596  }
597 
598  const int x = PositiveRef(ref_x);
599  const int y = PositiveRef(ref_y);
600  const int64 c = RefIsPositive(ref_x) == RefIsPositive(ref_y) ? coeff : -coeff;
601  const int64 o = RefIsPositive(ref_x) ? offset : -offset;
602 
603  // TODO(user): can we force the rep and remove GetAffineRelation()?
604  bool added = AddRelation(x, y, c, o, &affine_relations_);
605  if ((c == 1 || c == -1) && o == 0) {
606  added |= AddRelation(x, y, c, o, &var_equiv_relations_);
607  }
608  if (added) {
609  UpdateRuleStats("affine: new relation");
610 
611  // Lets propagate again the new relation. We might as well do it as early
612  // as possible and not all call site do it.
613  if (!PropagateAffineRelation(ref_x)) return true;
614  if (!PropagateAffineRelation(ref_y)) return true;
615 
616  // These maps should only contains representative, so only need to remap
617  // either x or y.
618  const int rep = GetAffineRelation(x).representative;
619  if (x != rep) encoding_remap_queue_.push_back(x);
620  if (y != rep) encoding_remap_queue_.push_back(y);
621 
622  // The domain didn't change, but this notification allows to re-process any
623  // constraint containing these variables. Note that we do not need to
624  // retrigger a propagation of the constraint containing a variable whose
625  // representative didn't change.
626  if (x != rep) modified_domains.Set(x);
627  if (y != rep) modified_domains.Set(y);
628 
629  var_to_constraints_[x].insert(kAffineRelationConstraint);
630  var_to_constraints_[y].insert(kAffineRelationConstraint);
631  return true;
632  }
633 
634  UpdateRuleStats("affine: incompatible relation");
635  if (VLOG_IS_ON(1)) {
636  LOG(INFO) << "Cannot add relation " << DomainOf(ref_x) << " = " << coeff
637  << " * " << DomainOf(ref_y) << " + " << offset
638  << " because of incompatibilities with existing relation: ";
639  for (const int ref : {ref_x, ref_y}) {
640  const auto r = GetAffineRelation(ref);
641  LOG(INFO) << DomainOf(ref) << " = " << r.coeff << " * "
642  << DomainOf(r.representative) << " + " << r.offset;
643  }
644  }
645 
646  return false;
647 }
648 
650  if (is_unsat) return;
651 
652  CHECK(!VariableWasRemoved(ref_a));
653  CHECK(!VariableWasRemoved(ref_b));
654  CHECK(!DomainOf(ref_a).IsEmpty());
655  CHECK(!DomainOf(ref_b).IsEmpty());
656  CHECK(CanBeUsedAsLiteral(ref_a));
657  CHECK(CanBeUsedAsLiteral(ref_b));
658 
659  if (ref_a == ref_b) return;
660  if (ref_a == NegatedRef(ref_b)) {
661  is_unsat = true;
662  return;
663  }
664  const int var_a = PositiveRef(ref_a);
665  const int var_b = PositiveRef(ref_b);
666  if (RefIsPositive(ref_a) == RefIsPositive(ref_b)) {
667  // a = b
668  CHECK(StoreAffineRelation(var_a, var_b, /*coeff=*/1, /*offset=*/0));
669  } else {
670  // a = 1 - b
671  CHECK(StoreAffineRelation(var_a, var_b, /*coeff=*/-1, /*offset=*/1));
672  }
673 }
674 
675 bool PresolveContext::StoreAbsRelation(int target_ref, int ref) {
676  const auto insert_status = abs_relations_.insert(
677  std::make_pair(target_ref, SavedVariable(PositiveRef(ref))));
678  if (!insert_status.second) {
679  // Tricky: overwrite if the old value refer to a now unused variable.
680  const int candidate = insert_status.first->second.Get(this);
681  if (removed_variables_.contains(candidate)) {
682  insert_status.first->second = SavedVariable(PositiveRef(ref));
683  return true;
684  }
685  return false;
686  }
687  return true;
688 }
689 
690 bool PresolveContext::GetAbsRelation(int target_ref, int* ref) {
691  auto it = abs_relations_.find(target_ref);
692  if (it == abs_relations_.end()) return false;
693 
694  // Tricky: In some rare case the stored relation can refer to a deleted
695  // variable, so we need to ignore it.
696  //
697  // TODO(user): Incorporate this as part of SavedVariable/SavedLiteral so we
698  // make sure we never forget about this.
699  const int candidate = it->second.Get(this);
700  if (removed_variables_.contains(candidate)) {
701  abs_relations_.erase(it);
702  return false;
703  }
704  *ref = candidate;
705  return true;
706 }
707 
710 
711  CHECK(CanBeUsedAsLiteral(ref));
713  // Note(user): This can happen is some corner cases where the affine
714  // relation where added before the variable became usable as Boolean. When
715  // this is the case, the domain will be of the form [x, x + 1] and should be
716  // later remapped to a Boolean variable.
717  return ref;
718  }
719 
720  // We made sure that the affine representative can always be used as a
721  // literal. However, if some variable are fixed, we might not have only
722  // (coeff=1 offset=0) or (coeff=-1 offset=1) and we might have something like
723  // (coeff=8 offset=0) which is only valid for both variable at zero...
724  //
725  // What is sure is that depending on the value, only one mapping can be valid
726  // because r.coeff can never be zero.
727  const bool positive_possible = (r.offset == 0 || r.coeff + r.offset == 1);
728  const bool negative_possible = (r.offset == 1 || r.coeff + r.offset == 0);
729  DCHECK_NE(positive_possible, negative_possible);
730  if (RefIsPositive(ref)) {
731  return positive_possible ? r.representative : NegatedRef(r.representative);
732  } else {
733  return positive_possible ? NegatedRef(r.representative) : r.representative;
734  }
735 }
736 
738  const AffineRelation::Relation r = var_equiv_relations_.Get(PositiveRef(ref));
739  CHECK_EQ(std::abs(r.coeff), 1);
740  CHECK_EQ(r.offset, 0);
741  return RefIsPositive(ref) == (r.coeff == 1) ? r.representative
743 }
744 
745 // This makes sure that the affine relation only uses one of the
746 // representative from the var_equiv_relations_.
748  AffineRelation::Relation r = affine_relations_.Get(PositiveRef(ref));
749  AffineRelation::Relation o = var_equiv_relations_.Get(r.representative);
751  if (o.coeff == -1) r.coeff = -r.coeff;
752  if (!RefIsPositive(ref)) {
753  r.coeff *= -1;
754  r.offset *= -1;
755  }
756  return r;
757 }
758 
759 // Create the internal structure for any new variables in working_model.
761  for (int i = domains.size(); i < working_model->variables_size(); ++i) {
762  domains.emplace_back(ReadDomainFromProto(working_model->variables(i)));
763  if (domains.back().IsEmpty()) {
764  is_unsat = true;
765  return;
766  }
767  if (IsFixed(i)) ExploitFixedDomain(i);
768  }
769  modified_domains.Resize(domains.size());
770  var_to_constraints_.resize(domains.size());
771  var_to_num_linear1_.resize(domains.size());
772  var_to_ub_only_constraints.resize(domains.size());
773  var_to_lb_only_constraints.resize(domains.size());
774 }
775 
776 bool PresolveContext::RemapEncodingMaps() {
777  // TODO(user): for now, while the code works most of the time, it triggers
778  // weird side effect that causes some issues in some LNS presolve...
779  // We should continue the investigation before activating it.
780  //
781  // Note also that because all our encoding constraints are present in the
782  // model, they will be remapped, and the new mapping re-added again. So while
783  // the current code might not be efficient, it should eventually reach the
784  // same effect.
785  encoding_remap_queue_.clear();
786 
787  // Note that InsertVarValueEncodingInternal() will potentially add new entry
788  // to the encoding_ map, but for a different variables. So this code relies on
789  // the fact that the var_map shouldn't change content nor address of the
790  // "var_map" below while we iterate on them.
791  for (const int var : encoding_remap_queue_) {
792  CHECK(RefIsPositive(var));
794  if (r.representative == var) return true;
795  int num_remapping = 0;
796 
797  // Encoding.
798  {
799  const absl::flat_hash_map<int64, SavedLiteral>& var_map = encoding_[var];
800  for (const auto& entry : var_map) {
801  const int lit = entry.second.Get(this);
802  if (removed_variables_.contains(PositiveRef(lit))) continue;
803  if ((entry.first - r.offset) % r.coeff != 0) continue;
804  const int64 rep_value = (entry.first - r.offset) / r.coeff;
805  ++num_remapping;
806  InsertVarValueEncodingInternal(lit, r.representative, rep_value,
807  /*add_constraints=*/false);
808  if (is_unsat) return false;
809  }
810  encoding_.erase(var);
811  }
812 
813  // Eq half encoding.
814  {
815  const absl::flat_hash_map<int64, absl::flat_hash_set<int>>& var_map =
816  eq_half_encoding_[var];
817  for (const auto& entry : var_map) {
818  if ((entry.first - r.offset) % r.coeff != 0) continue;
819  const int64 rep_value = (entry.first - r.offset) / r.coeff;
820  for (int literal : entry.second) {
821  ++num_remapping;
822  InsertHalfVarValueEncoding(GetLiteralRepresentative(literal),
823  r.representative, rep_value,
824  /*imply_eq=*/true);
825  if (is_unsat) return false;
826  }
827  }
828  eq_half_encoding_.erase(var);
829  }
830 
831  // Neq half encoding.
832  {
833  const absl::flat_hash_map<int64, absl::flat_hash_set<int>>& var_map =
834  neq_half_encoding_[var];
835  for (const auto& entry : var_map) {
836  if ((entry.first - r.offset) % r.coeff != 0) continue;
837  const int64 rep_value = (entry.first - r.offset) / r.coeff;
838  for (int literal : entry.second) {
839  ++num_remapping;
840  InsertHalfVarValueEncoding(GetLiteralRepresentative(literal),
841  r.representative, rep_value,
842  /*imply_eq=*/false);
843  if (is_unsat) return false;
844  }
845  }
846  neq_half_encoding_.erase(var);
847  }
848 
849  if (num_remapping > 0) {
850  VLOG(1) << "Remapped " << num_remapping << " encodings due to " << var
851  << " -> " << r.representative << ".";
852  }
853  }
854  encoding_remap_queue_.clear();
855  return !is_unsat;
856 }
857 
859  CHECK(RefIsPositive(var));
860  CHECK_EQ(DomainOf(var).Size(), 2);
861  const int64 var_min = MinOf(var);
862  const int64 var_max = MaxOf(var);
863 
864  if (is_unsat) return;
865 
866  absl::flat_hash_map<int64, SavedLiteral>& var_map = encoding_[var];
867 
868  // Find encoding for min if present.
869  auto min_it = var_map.find(var_min);
870  if (min_it != var_map.end()) {
871  const int old_var = PositiveRef(min_it->second.Get(this));
872  if (removed_variables_.contains(old_var)) {
873  var_map.erase(min_it);
874  min_it = var_map.end();
875  }
876  }
877 
878  // Find encoding for max if present.
879  auto max_it = var_map.find(var_max);
880  if (max_it != var_map.end()) {
881  const int old_var = PositiveRef(max_it->second.Get(this));
882  if (removed_variables_.contains(old_var)) {
883  var_map.erase(max_it);
884  max_it = var_map.end();
885  }
886  }
887 
888  // Insert missing encoding.
889  int min_literal;
890  int max_literal;
891  if (min_it != var_map.end() && max_it != var_map.end()) {
892  min_literal = min_it->second.Get(this);
893  max_literal = max_it->second.Get(this);
894  if (min_literal != NegatedRef(max_literal)) {
895  UpdateRuleStats("variables with 2 values: merge encoding literals");
896  StoreBooleanEqualityRelation(min_literal, NegatedRef(max_literal));
897  if (is_unsat) return;
898  }
899  min_literal = GetLiteralRepresentative(min_literal);
900  max_literal = GetLiteralRepresentative(max_literal);
901  if (!IsFixed(min_literal)) CHECK_EQ(min_literal, NegatedRef(max_literal));
902  } else if (min_it != var_map.end() && max_it == var_map.end()) {
903  UpdateRuleStats("variables with 2 values: register other encoding");
904  min_literal = min_it->second.Get(this);
905  max_literal = NegatedRef(min_literal);
906  var_map[var_max] = SavedLiteral(max_literal);
907  } else if (min_it == var_map.end() && max_it != var_map.end()) {
908  UpdateRuleStats("variables with 2 values: register other encoding");
909  max_literal = max_it->second.Get(this);
910  min_literal = NegatedRef(max_literal);
911  var_map[var_min] = SavedLiteral(min_literal);
912  } else {
913  UpdateRuleStats("variables with 2 values: create encoding literal");
914  max_literal = NewBoolVar();
915  min_literal = NegatedRef(max_literal);
916  var_map[var_min] = SavedLiteral(min_literal);
917  var_map[var_max] = SavedLiteral(max_literal);
918  }
919 
920  if (IsFixed(min_literal) || IsFixed(max_literal)) {
921  CHECK(IsFixed(min_literal));
922  CHECK(IsFixed(max_literal));
923  UpdateRuleStats("variables with 2 values: fixed encoding");
924  if (LiteralIsTrue(min_literal)) {
925  return static_cast<void>(IntersectDomainWith(var, Domain(var_min)));
926  } else {
927  return static_cast<void>(IntersectDomainWith(var, Domain(var_max)));
928  }
929  }
930 
931  // Add affine relation.
932  if (GetAffineRelation(var).representative != PositiveRef(min_literal)) {
933  UpdateRuleStats("variables with 2 values: new affine relation");
934  if (RefIsPositive(max_literal)) {
935  CHECK(StoreAffineRelation(var, PositiveRef(max_literal),
936  var_max - var_min, var_min));
937  } else {
938  CHECK(StoreAffineRelation(var, PositiveRef(max_literal),
939  var_min - var_max, var_max));
940  }
941  }
942 }
943 
944 void PresolveContext::InsertVarValueEncodingInternal(int literal, int var,
945  int64 value,
946  bool add_constraints) {
947  CHECK(!VariableWasRemoved(literal));
948  CHECK(!VariableWasRemoved(var));
949  absl::flat_hash_map<int64, SavedLiteral>& var_map = encoding_[var];
950 
951  // Ticky and rare: I have only observed this on the LNS of
952  // radiation_m18_12_05_sat.fzn. The value was encoded, but maybe we never
953  // used the involved variables / constraints, so it was removed (with the
954  // encoding constraints) from the model already! We have to be careful.
955  const auto it = var_map.find(value);
956  if (it != var_map.end()) {
957  const int old_var = PositiveRef(it->second.Get(this));
958  if (removed_variables_.contains(old_var)) {
959  var_map.erase(it);
960  }
961  }
962 
963  const auto insert =
964  var_map.insert(std::make_pair(value, SavedLiteral(literal)));
965 
966  // If an encoding already exist, make the two Boolean equals.
967  if (!insert.second) {
968  UpdateRuleStats("variables: merge equivalent var value encoding literals");
969  const int previous_literal = insert.first->second.Get(this);
970  CHECK(!VariableWasRemoved(previous_literal));
971  if (literal != previous_literal) {
972  StoreBooleanEqualityRelation(literal, previous_literal);
973  }
974  return;
975  }
976 
977  if (DomainOf(var).Size() == 2) {
979  } else {
980  VLOG(2) << "Insert lit(" << literal << ") <=> var(" << var
981  << ") == " << value;
982  // eq_half_encoding_[var][value].insert(literal);
983  // neq_half_encoding_[var][value].insert(NegatedRef(literal));
984  if (add_constraints) {
985  UpdateRuleStats("variables: add encoding constraint");
986  AddImplyInDomain(literal, var, Domain(value));
987  AddImplyInDomain(NegatedRef(literal), var, Domain(value).Complement());
988  }
989  }
990 }
991 
992 bool PresolveContext::InsertHalfVarValueEncoding(int literal, int var,
993  int64 value, bool imply_eq) {
994  if (is_unsat) return false;
995  CHECK(RefIsPositive(var));
996 
997  // Creates the linking sets on demand.
998  // Insert the enforcement literal in the half encoding map.
999  auto& direct_set =
1000  imply_eq ? eq_half_encoding_[var][value] : neq_half_encoding_[var][value];
1001  if (!direct_set.insert(literal).second) return false; // Already there.
1002 
1003  VLOG(2) << "Collect lit(" << literal << ") implies var(" << var
1004  << (imply_eq ? ") == " : ") != ") << value;
1005  UpdateRuleStats("variables: detect half reified value encoding");
1006 
1007  // Note(user): We don't expect a lot of literals in these sets, so doing
1008  // a scan should be okay.
1009  auto& other_set =
1010  imply_eq ? neq_half_encoding_[var][value] : eq_half_encoding_[var][value];
1011  for (const int other : other_set) {
1012  if (GetLiteralRepresentative(other) != NegatedRef(literal)) continue;
1013 
1014  UpdateRuleStats("variables: detect fully reified value encoding");
1015  const int imply_eq_literal = imply_eq ? literal : NegatedRef(literal);
1016  InsertVarValueEncodingInternal(imply_eq_literal, var, value,
1017  /*add_constraints=*/false);
1018  break;
1019  }
1020 
1021  return true;
1022 }
1023 
1024 bool PresolveContext::CanonicalizeEncoding(int* ref, int64* value) {
1025  const AffineRelation::Relation r = GetAffineRelation(*ref);
1026  if ((*value - r.offset) % r.coeff != 0) return false;
1027  *ref = r.representative;
1028  *value = (*value - r.offset) / r.coeff;
1029  return true;
1030 }
1031 
1033  int64 value) {
1034  if (!RemapEncodingMaps()) return;
1035  if (!CanonicalizeEncoding(&ref, &value)) return;
1037  InsertVarValueEncodingInternal(literal, ref, value, /*add_constraints=*/true);
1038 }
1039 
1041  int64 value) {
1042  if (!RemapEncodingMaps()) return false;
1043  if (!CanonicalizeEncoding(&var, &value)) return false;
1045  return InsertHalfVarValueEncoding(literal, var, value, /*imply_eq=*/true);
1046 }
1047 
1049  int64 value) {
1050  if (!RemapEncodingMaps()) return false;
1051  if (!CanonicalizeEncoding(&var, &value)) return false;
1053  return InsertHalfVarValueEncoding(literal, var, value, /*imply_eq=*/false);
1054 }
1055 
1057  if (!RemapEncodingMaps()) return false;
1058  if (!CanonicalizeEncoding(&ref, &value)) return false;
1059  const absl::flat_hash_map<int64, SavedLiteral>& var_map = encoding_[ref];
1060  const auto it = var_map.find(value);
1061  if (it != var_map.end()) {
1062  if (literal != nullptr) {
1063  *literal = it->second.Get(this);
1064  }
1065  return true;
1066  }
1067  return false;
1068 }
1069 
1071  if (!RemapEncodingMaps()) return GetOrCreateConstantVar(0);
1072  if (!CanonicalizeEncoding(&ref, &value)) return GetOrCreateConstantVar(0);
1073 
1074  // Positive after CanonicalizeEncoding().
1075  const int var = ref;
1076 
1077  // Returns the false literal if the value is not in the domain.
1078  if (!domains[var].Contains(value)) {
1079  return GetOrCreateConstantVar(0);
1080  }
1081 
1082  // Returns the associated literal if already present.
1083  absl::flat_hash_map<int64, SavedLiteral>& var_map = encoding_[var];
1084  auto it = var_map.find(value);
1085  if (it != var_map.end()) {
1086  return it->second.Get(this);
1087  }
1088 
1089  // Special case for fixed domains.
1090  if (domains[var].Size() == 1) {
1091  const int true_literal = GetOrCreateConstantVar(1);
1092  var_map[value] = SavedLiteral(true_literal);
1093  return true_literal;
1094  }
1095 
1096  // Special case for domains of size 2.
1097  const int64 var_min = MinOf(var);
1098  const int64 var_max = MaxOf(var);
1099  if (domains[var].Size() == 2) {
1100  // Checks if the other value is already encoded.
1101  const int64 other_value = value == var_min ? var_max : var_min;
1102  auto other_it = var_map.find(other_value);
1103  if (other_it != var_map.end()) {
1104  // Update the encoding map. The domain could have been reduced to size
1105  // two after the creation of the first literal.
1106  const int literal = NegatedRef(other_it->second.Get(this));
1107  var_map[value] = SavedLiteral(literal);
1108  return literal;
1109  }
1110 
1111  if (var_min == 0 && var_max == 1) {
1113  var_map[1] = SavedLiteral(representative);
1114  var_map[0] = SavedLiteral(NegatedRef(representative));
1115  return value == 1 ? representative : NegatedRef(representative);
1116  } else {
1117  const int literal = NewBoolVar();
1118  InsertVarValueEncoding(literal, var, var_max);
1120  return value == var_max ? representative : NegatedRef(representative);
1121  }
1122  }
1123 
1124  const int literal = NewBoolVar();
1127 }
1128 
1130  const CpObjectiveProto& obj = working_model->objective();
1131 
1132  objective_offset = obj.offset();
1133  objective_scaling_factor = obj.scaling_factor();
1134  if (objective_scaling_factor == 0.0) {
1135  objective_scaling_factor = 1.0;
1136  }
1137  if (!obj.domain().empty()) {
1138  // We might relax this in CanonicalizeObjective() when we will compute
1139  // the possible objective domain from the domains of the variables.
1140  objective_domain_is_constraining = true;
1141  objective_domain = ReadDomainFromProto(obj);
1142  } else {
1143  objective_domain_is_constraining = false;
1144  objective_domain = Domain::AllValues();
1145  }
1146 
1147  objective_map.clear();
1148  for (int i = 0; i < obj.vars_size(); ++i) {
1149  const int ref = obj.vars(i);
1150  int64 coeff = obj.coeffs(i);
1151  if (!RefIsPositive(ref)) coeff = -coeff;
1152  int var = PositiveRef(ref);
1153 
1154  objective_map[var] += coeff;
1155  if (objective_map[var] == 0) {
1156  objective_map.erase(var);
1157  var_to_constraints_[var].erase(kObjectiveConstraint);
1158  } else {
1159  var_to_constraints_[var].insert(kObjectiveConstraint);
1160  }
1161  }
1162 }
1163 
1165  int64 offset_change = 0;
1166 
1167  // We replace each entry by its affine representative.
1168  // Note that the non-deterministic loop is fine, but because we iterate
1169  // one the map while modifying it, it is safer to do a copy rather than to
1170  // try to handle that in one pass.
1171  tmp_entries.clear();
1172  for (const auto& entry : objective_map) {
1173  tmp_entries.push_back(entry);
1174  }
1175 
1176  // TODO(user): This is a bit duplicated with the presolve linear code.
1177  // We also do not propagate back any domain restriction from the objective to
1178  // the variables if any.
1179  for (const auto& entry : tmp_entries) {
1180  const int var = entry.first;
1181  const auto it = objective_map.find(var);
1182  if (it == objective_map.end()) continue;
1183  const int64 coeff = it->second;
1184 
1185  // If a variable only appear in objective, we can fix it!
1186  // Note that we don't care if it was in affine relation, because if none
1187  // of the relations are left, then we can still fix it.
1188  if (!keep_all_feasible_solutions && !objective_domain_is_constraining &&
1190  var_to_constraints_[var].size() == 1 &&
1191  var_to_constraints_[var].contains(kObjectiveConstraint)) {
1192  UpdateRuleStats("objective: variable not used elsewhere");
1193  if (coeff > 0) {
1194  if (!IntersectDomainWith(var, Domain(MinOf(var)))) {
1195  return false;
1196  }
1197  } else {
1198  if (!IntersectDomainWith(var, Domain(MaxOf(var)))) {
1199  return false;
1200  }
1201  }
1202  }
1203 
1204  if (IsFixed(var)) {
1205  offset_change += coeff * MinOf(var);
1206  var_to_constraints_[var].erase(kObjectiveConstraint);
1207  objective_map.erase(var);
1208  continue;
1209  }
1210 
1212  if (r.representative == var) continue;
1213 
1214  objective_map.erase(var);
1215  var_to_constraints_[var].erase(kObjectiveConstraint);
1216 
1217  // Do the substitution.
1218  offset_change += coeff * r.offset;
1219  const int64 new_coeff = objective_map[r.representative] += coeff * r.coeff;
1220 
1221  // Process new term.
1222  if (new_coeff == 0) {
1223  objective_map.erase(r.representative);
1224  var_to_constraints_[r.representative].erase(kObjectiveConstraint);
1225  } else {
1226  var_to_constraints_[r.representative].insert(kObjectiveConstraint);
1227  if (IsFixed(r.representative)) {
1228  offset_change += new_coeff * MinOf(r.representative);
1229  var_to_constraints_[r.representative].erase(kObjectiveConstraint);
1230  objective_map.erase(r.representative);
1231  }
1232  }
1233  }
1234 
1235  Domain implied_domain(0);
1236  int64 gcd(0);
1237 
1238  // We need to sort the entries to be deterministic.
1239  tmp_entries.clear();
1240  for (const auto& entry : objective_map) {
1241  tmp_entries.push_back(entry);
1242  }
1243  std::sort(tmp_entries.begin(), tmp_entries.end());
1244  for (const auto& entry : tmp_entries) {
1245  const int var = entry.first;
1246  const int64 coeff = entry.second;
1247  gcd = MathUtil::GCD64(gcd, std::abs(coeff));
1248  implied_domain =
1249  implied_domain.AdditionWith(DomainOf(var).MultiplicationBy(coeff))
1250  .RelaxIfTooComplex();
1251  }
1252 
1253  // This is the new domain.
1254  // Note that the domain never include the offset.
1255  objective_domain = objective_domain.AdditionWith(Domain(-offset_change))
1256  .IntersectionWith(implied_domain);
1257  objective_domain =
1258  objective_domain.SimplifyUsingImpliedDomain(implied_domain);
1259 
1260  // Updat the offset.
1261  objective_offset += offset_change;
1262 
1263  // Maybe divide by GCD.
1264  if (gcd > 1) {
1265  for (auto& entry : objective_map) {
1266  entry.second /= gcd;
1267  }
1268  objective_domain = objective_domain.InverseMultiplicationBy(gcd);
1269  objective_offset /= static_cast<double>(gcd);
1270  objective_scaling_factor *= static_cast<double>(gcd);
1271  }
1272 
1273  if (objective_domain.IsEmpty()) return false;
1274 
1275  // Detect if the objective domain do not limit the "optimal" objective value.
1276  // If this is true, then we can apply any reduction that reduce the objective
1277  // value without any issues.
1278  objective_domain_is_constraining =
1279  !implied_domain
1280  .IntersectionWith(Domain(kint64min, objective_domain.Max()))
1281  .IsIncludedIn(objective_domain);
1282  return true;
1283 }
1284 
1286  int var_in_equality, int64 coeff_in_equality,
1287  const ConstraintProto& equality, std::vector<int>* new_vars_in_objective) {
1288  CHECK(equality.enforcement_literal().empty());
1289  CHECK(RefIsPositive(var_in_equality));
1290 
1291  if (new_vars_in_objective != nullptr) new_vars_in_objective->clear();
1292 
1293  // We can only "easily" substitute if the objective coefficient is a multiple
1294  // of the one in the constraint.
1295  const int64 coeff_in_objective =
1296  gtl::FindOrDie(objective_map, var_in_equality);
1297  CHECK_NE(coeff_in_equality, 0);
1298  CHECK_EQ(coeff_in_objective % coeff_in_equality, 0);
1299  const int64 multiplier = coeff_in_objective / coeff_in_equality;
1300 
1301  for (int i = 0; i < equality.linear().vars().size(); ++i) {
1302  int var = equality.linear().vars(i);
1303  int64 coeff = equality.linear().coeffs(i);
1304  if (!RefIsPositive(var)) {
1305  var = NegatedRef(var);
1306  coeff = -coeff;
1307  }
1308  if (var == var_in_equality) continue;
1309 
1310  int64& map_ref = objective_map[var];
1311  if (map_ref == 0 && new_vars_in_objective != nullptr) {
1312  new_vars_in_objective->push_back(var);
1313  }
1314  map_ref -= coeff * multiplier;
1315 
1316  if (map_ref == 0) {
1317  objective_map.erase(var);
1318  var_to_constraints_[var].erase(kObjectiveConstraint);
1319  } else {
1320  var_to_constraints_[var].insert(kObjectiveConstraint);
1321  }
1322  }
1323 
1324  objective_map.erase(var_in_equality);
1325  var_to_constraints_[var_in_equality].erase(kObjectiveConstraint);
1326 
1327  // Deal with the offset.
1328  Domain offset = ReadDomainFromProto(equality.linear());
1329  DCHECK_EQ(offset.Min(), offset.Max());
1330  bool exact = true;
1331  offset = offset.MultiplicationBy(multiplier, &exact);
1332  CHECK(exact);
1333 
1334  // Tricky: The objective domain is without the offset, so we need to shift it.
1335  objective_offset += static_cast<double>(offset.Min());
1336  objective_domain = objective_domain.AdditionWith(Domain(-offset.Min()));
1337 
1338  // Because we can assume that the constraint we used was constraining
1339  // (otherwise it would have been removed), the objective domain should be now
1340  // constraining.
1341  objective_domain_is_constraining = true;
1342 }
1343 
1345  if (objective_domain.IsEmpty()) {
1346  return (void)NotifyThatModelIsUnsat();
1347  }
1348 
1349  // We need to sort the entries to be deterministic.
1350  std::vector<std::pair<int, int64>> entries;
1351  for (const auto& entry : objective_map) {
1352  entries.push_back(entry);
1353  }
1354  std::sort(entries.begin(), entries.end());
1355 
1356  CpObjectiveProto* mutable_obj = working_model->mutable_objective();
1357  mutable_obj->set_offset(objective_offset);
1358  mutable_obj->set_scaling_factor(objective_scaling_factor);
1359  FillDomainInProto(objective_domain, mutable_obj);
1360  mutable_obj->clear_vars();
1361  mutable_obj->clear_coeffs();
1362  for (const auto& entry : entries) {
1363  mutable_obj->add_vars(entry.first);
1364  mutable_obj->add_coeffs(entry.second);
1365  }
1366 }
1367 
1368 } // namespace sat
1369 } // namespace operations_research
operations_research::sat::PresolveContext::AddImplyInDomain
void AddImplyInDomain(int b, int x, const Domain &domain)
Definition: presolve_context.cc:61
operations_research::sat::PresolveContext::UpdateRuleStats
void UpdateRuleStats(const std::string &name)
Definition: presolve_context.cc:285
var
IntVar * var
Definition: expr_array.cc:1858
operations_research::sat::PresolveContext::NewBoolVar
int NewBoolVar()
Definition: presolve_context.cc:40
operations_research::sat::PresolveContext::SetLiteralToFalse
ABSL_MUST_USE_RESULT bool SetLiteralToFalse(int lit)
Definition: presolve_context.cc:275
operations_research::sat::PresolveContext::GetOrCreateVarValueEncoding
int GetOrCreateVarValueEncoding(int ref, int64 value)
Definition: presolve_context.cc:1070
operations_research::sat::PresolveContext::ReadObjectiveFromProto
void ReadObjectiveFromProto()
Definition: presolve_context.cc:1129
min
int64 min
Definition: alldiff_cst.cc:138
map_util.h
max
int64 max
Definition: alldiff_cst.cc:139
operations_research::sat::PresolveContext::IntersectDomainWith
ABSL_MUST_USE_RESULT bool IntersectDomainWith(int ref, const Domain &domain, bool *domain_modified=nullptr)
Definition: presolve_context.cc:238
operations_research::sat::PresolveContext::PropagateAffineRelation
bool PropagateAffineRelation(int ref)
Definition: presolve_context.cc:471
operations_research::AffineRelation::TryAdd
bool TryAdd(int x, int y, int64 coeff, int64 offset)
Definition: affine_relation.h:164
operations_research::sat::PresolveContext::LiteralIsFalse
bool LiteralIsFalse(int lit) const
Definition: presolve_context.cc:97
operations_research::Domain::MultiplicationBy
Domain MultiplicationBy(int64 coeff, bool *exact=nullptr) const
Returns {x ∈ Int64, ∃ e ∈ D, x = e * coeff}.
Definition: sorted_interval_list.cc:361
operations_research::sat::PresolveContext::keep_all_feasible_solutions
bool keep_all_feasible_solutions
Definition: presolve_context.h:352
operations_research::sat::PresolveContext::modified_domains
SparseBitset< int64 > modified_domains
Definition: presolve_context.h:375
operations_research::SparseBitset::Set
void Set(IntegerType index)
Definition: bitset.h:805
operations_research::sat::PresolveContext::NewIntVar
int NewIntVar(const Domain &domain)
Definition: presolve_context.cc:33
proto_utils.h
presolve_context.h
operations_research::sat::UsedVariables
std::vector< int > UsedVariables(const ConstraintProto &ct)
Definition: cp_model_utils.cc:441
operations_research::sat::PresolveContext::VariableIsOnlyUsedInEncoding
bool VariableIsOnlyUsedInEncoding(int ref) const
Definition: presolve_context.cc:215
operations_research::sat::PresolveContext::VariableWithCostIsUniqueAndRemovable
bool VariableWithCostIsUniqueAndRemovable(int ref) const
Definition: presolve_context.cc:173
value
int64 value
Definition: demon_profiler.cc:43
operations_research::AffineRelation::ClassSize
int ClassSize(int x) const
Definition: affine_relation.h:107
operations_research::sat::PresolveContext::UpdateNewConstraintsVariableUsage
void UpdateNewConstraintsVariableUsage()
Definition: presolve_context.cc:356
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::AffineRelation::Relation
Definition: affine_relation.h:76
kint64min
static const int64 kint64min
Definition: integral_types.h:60
operations_research::sat::PresolveContext::num_presolve_operations
int64 num_presolve_operations
Definition: presolve_context.h:366
operations_research::sat::PresolveContext::CanBeUsedAsLiteral
bool CanBeUsedAsLiteral(int ref) const
Definition: presolve_context.cc:83
operations_research::Domain::AdditionWith
Domain AdditionWith(const Domain &domain) const
Returns {x ∈ Int64, ∃ a ∈ D, ∃ b ∈ domain, x = a + b}.
Definition: sorted_interval_list.cc:332
operations_research::sat::PresolveContext::MarkVariableAsRemoved
void MarkVariableAsRemoved(int ref)
Definition: presolve_context.cc:189
int64
int64_t int64
Definition: integral_types.h:34
operations_research::AffineRelation::IgnoreFromClassSize
void IgnoreFromClassSize(int x)
Definition: affine_relation.h:93
operations_research::sat::PresolveContext::StoreAbsRelation
bool StoreAbsRelation(int target_ref, int ref)
Definition: presolve_context.cc:675
operations_research::sat::PresolveContext::LiteralIsTrue
bool LiteralIsTrue(int lit) const
Definition: presolve_context.cc:88
operations_research::Domain
We call domain any subset of Int64 = [kint64min, kint64max].
Definition: sorted_interval_list.h:81
operations_research::sat::PresolveContext::RemoveAllVariablesFromAffineRelationConstraint
void RemoveAllVariablesFromAffineRelationConstraint()
Definition: presolve_context.cc:493
context
GurobiMPCallbackContext * context
Definition: gurobi_interface.cc:439
operations_research::AffineRelation::Relation::representative
int representative
Definition: affine_relation.h:77
operations_research::sat::PresolveContext::ClearStats
void ClearStats()
Definition: presolve_context.cc:31
operations_research::sat::PresolveContext::VariableIsNotUsedAnymore
bool VariableIsNotUsedAnymore(int ref) const
Definition: presolve_context.cc:184
operations_research::AffineRelation::Relation::offset
int64 offset
Definition: affine_relation.h:79
operations_research::sat::SavedVariable::Get
int Get(PresolveContext *context) const
Definition: presolve_context.cc:27
gtl::FindOrDie
const Collection::value_type::second_type & FindOrDie(const Collection &collection, const typename Collection::value_type::first_type &key)
Definition: map_util.h:176
operations_research::sat::UsedIntervals
std::vector< int > UsedIntervals(const ConstraintProto &ct)
Definition: cp_model_utils.cc:456
operations_research::ProtobufDebugString
std::string ProtobufDebugString(const P &message)
Definition: port/proto_utils.h:53
operations_research::sat::PresolveContext::DomainContains
bool DomainContains(int ref, int64 value) const
Definition: presolve_context.cc:231
operations_research::sat::PresolveContext::IsFixed
bool IsFixed(int ref) const
Definition: presolve_context.cc:77
operations_research::sat::PresolveContext::UpdateConstraintVariableUsage
void UpdateConstraintVariableUsage(int c)
Definition: presolve_context.cc:318
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::PositiveRef
int PositiveRef(int ref)
Definition: cp_model_utils.h:33
operations_research::sat::PresolveContext::GetVariableRepresentative
int GetVariableRepresentative(int ref) const
Definition: presolve_context.cc:737
operations_research::sat::PresolveContext::StoreLiteralImpliesVarNEqValue
bool StoreLiteralImpliesVarNEqValue(int literal, int var, int64 value)
Definition: presolve_context.cc:1048
a
int64 a
Definition: constraint_solver/table.cc:42
operations_research::sat::PresolveContext::GetLiteralRepresentative
int GetLiteralRepresentative(int ref) const
Definition: presolve_context.cc:708
operations_research::sat::PresolveContext::GetOrCreateConstantVar
int GetOrCreateConstantVar(int64 cst)
Definition: presolve_context.cc:42
operations_research::AffineRelation
Definition: affine_relation.h:36
operations_research::Domain::IsEmpty
bool IsEmpty() const
Returns true if this is the empty set.
Definition: sorted_interval_list.cc:190
operations_research::Domain::AllValues
static Domain AllValues()
Returns the full domain Int64.
Definition: sorted_interval_list.cc:135
operations_research::SparseBitset::Resize
void Resize(IntegerType size)
Definition: bitset.h:791
operations_research::sat::PresolveContext::stats_by_rule_name
absl::flat_hash_map< std::string, int > stats_by_rule_name
Definition: presolve_context.h:359
operations_research::sat::PresolveContext::AddImplication
void AddImplication(int a, int b)
Definition: presolve_context.cc:54
operations_research::Domain::RelaxIfTooComplex
Domain RelaxIfTooComplex() const
If NumIntervals() is too large, this return a superset of the domain.
Definition: sorted_interval_list.cc:353
operations_research::Domain::SimplifyUsingImpliedDomain
Domain SimplifyUsingImpliedDomain(const Domain &implied_domain) const
Advanced usage.
Definition: sorted_interval_list.cc:461
operations_research::sat::PresolveContext::SetLiteralToTrue
ABSL_MUST_USE_RESULT bool SetLiteralToTrue(int lit)
Definition: presolve_context.cc:281
operations_research::sat::PresolveContext::StoreAffineRelation
bool StoreAffineRelation(int ref_x, int ref_y, int64 coeff, int64 offset)
Definition: presolve_context.cc:534
mathutil.h
representative
ColIndex representative
Definition: preprocessor.cc:424
operations_research::sat::PresolveContext::var_to_lb_only_constraints
std::vector< absl::flat_hash_set< int > > var_to_lb_only_constraints
Definition: presolve_context.h:342
operations_research::sat::PresolveContext::CanonicalizeDomainOfSizeTwo
void CanonicalizeDomainOfSizeTwo(int var)
Definition: presolve_context.cc:858
ct
const Constraint * ct
Definition: demon_profiler.cc:42
operations_research::MathUtil::GCD64
static int64 GCD64(int64 x, int64 y)
Definition: mathutil.h:107
operations_research::sat::PresolveContext::RemoveVariableFromAffineRelation
void RemoveVariableFromAffineRelation(int var)
Definition: presolve_context.cc:502
operations_research::sat::NegatedRef
int NegatedRef(int ref)
Definition: cp_model_utils.h:32
operations_research::sat::PresolveContext::CanonicalizeObjective
ABSL_MUST_USE_RESULT bool CanonicalizeObjective()
Definition: presolve_context.cc:1164
operations_research::sat::PresolveContext::DomainOf
Domain DomainOf(int ref) const
Definition: presolve_context.cc:221
operations_research::sat::PresolveContext::HasVarValueEncoding
bool HasVarValueEncoding(int ref, int64 value, int *literal=nullptr)
Definition: presolve_context.cc:1056
operations_research::sat::PresolveContext::ExploitFixedDomain
void ExploitFixedDomain(int var)
Definition: presolve_context.cc:447
operations_research::sat::PresolveContext::enable_stats
bool enable_stats
Definition: presolve_context.h:356
operations_research::sat::PresolveContext::NotifyThatModelIsUnsat
ABSL_MUST_USE_RESULT bool NotifyThatModelIsUnsat(const std::string &message="")
Definition: presolve_context.h:142
operations_research::Domain::InverseMultiplicationBy
Domain InverseMultiplicationBy(const int64 coeff) const
Returns {x ∈ Int64, ∃ e ∈ D, x * coeff = e}.
Definition: sorted_interval_list.cc:433
operations_research::sat::PresolveContext::working_model
CpModelProto * working_model
Definition: presolve_context.h:344
operations_research::sat::PresolveContext::GetAbsRelation
bool GetAbsRelation(int target_ref, int *ref)
Definition: presolve_context.cc:690
operations_research::sat::PresolveContext::var_to_ub_only_constraints
std::vector< absl::flat_hash_set< int > > var_to_ub_only_constraints
Definition: presolve_context.h:341
operations_research::sat::FillDomainInProto
void FillDomainInProto(const Domain &domain, ProtoWithDomain *proto)
Definition: cp_model_utils.h:91
operations_research::sat::RefIsPositive
bool RefIsPositive(int ref)
Definition: cp_model_utils.h:34
operations_research::sat::PresolveContext::ConstraintVariableUsageIsConsistent
bool ConstraintVariableUsageIsConsistent()
Definition: presolve_context.cc:371
operations_research::Domain::Negation
Domain Negation() const
Returns {x ∈ Int64, ∃ e ∈ D, x = -e}.
Definition: sorted_interval_list.cc:261
operations_research::sat::PresolveContext::ConstraintVariableGraphIsUpToDate
bool ConstraintVariableGraphIsUpToDate() const
Definition: presolve_context.cc:352
operations_research::sat::PresolveContext::InsertVarValueEncoding
void InsertVarValueEncoding(int literal, int ref, int64 value)
Definition: presolve_context.cc:1032
operations_research::sat::SavedVariable
Definition: presolve_context.h:60
b
int64 b
Definition: constraint_solver/table.cc:43
operations_research::sat::PresolveContext::InitializeNewDomains
void InitializeNewDomains()
Definition: presolve_context.cc:760
operations_research::sat::PresolveContext::GetAffineRelation
AffineRelation::Relation GetAffineRelation(int ref) const
Definition: presolve_context.cc:747
operations_research::AffineRelation::Get
Relation Get(int x) const
Definition: affine_relation.h:210
operations_research::sat::PresolveContext::StoreLiteralImpliesVarEqValue
bool StoreLiteralImpliesVarEqValue(int literal, int var, int64 value)
Definition: presolve_context.cc:1040
operations_research::sat::kObjectiveConstraint
constexpr int kObjectiveConstraint
Definition: presolve_context.h:33
operations_research::Domain::Max
int64 Max() const
Returns the max value of the domain.
Definition: sorted_interval_list.cc:211
operations_research::sat::SavedLiteral
Definition: presolve_context.h:49
operations_research::sat::PresolveContext::VariableWasRemoved
bool VariableWasRemoved(int ref) const
Definition: presolve_context.cc:196
operations_research::Domain::Min
int64 Min() const
Returns the min value of the domain.
Definition: sorted_interval_list.cc:206
literal
Literal literal
Definition: optimization.cc:84
operations_research::sat::PresolveContext::SubstituteVariableInObjective
void SubstituteVariableInObjective(int var_in_equality, int64 coeff_in_equality, const ConstraintProto &equality, std::vector< int > *new_vars_in_objective=nullptr)
Definition: presolve_context.cc:1285
operations_research::Domain::IsIncludedIn
bool IsIncludedIn(const Domain &domain) const
Returns true iff D is included in the given domain.
Definition: sorted_interval_list.cc:232
operations_research::sat::ReadDomainFromProto
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
Definition: cp_model_utils.h:102
operations_research::sat::PresolveContext::WriteObjectiveToProto
void WriteObjectiveToProto()
Definition: presolve_context.cc:1344
operations_research::sat::PresolveContext
Definition: presolve_context.h:72
name
const std::string name
Definition: default_search.cc:807
operations_research::sat::SavedLiteral::Get
int Get(PresolveContext *context) const
Definition: presolve_context.cc:23
operations_research::sat::PresolveContext::StoreBooleanEqualityRelation
void StoreBooleanEqualityRelation(int ref_a, int ref_b)
Definition: presolve_context.cc:649
operations_research::sat::kAffineRelationConstraint
constexpr int kAffineRelationConstraint
Definition: presolve_context.h:34
operations_research::AffineRelation::Relation::coeff
int64 coeff
Definition: affine_relation.h:78
operations_research::sat::PresolveContext::DomainIsEmpty
bool DomainIsEmpty(int ref) const
Definition: presolve_context.cc:73
operations_research::sat::PresolveContext::VariableIsUniqueAndRemovable
bool VariableIsUniqueAndRemovable(int ref) const
Definition: presolve_context.cc:164
operations_research::sat::PresolveContext::MaxOf
int64 MaxOf(int ref) const
Definition: presolve_context.cc:112
gtl::ContainsKey
bool ContainsKey(const Collection &collection, const Key &key)
Definition: map_util.h:170
operations_research::sat::PresolveContext::MinOf
int64 MinOf(int ref) const
Definition: presolve_context.cc:106