OR-Tools  9.0
linear_programming_constraint.cc
Go to the documentation of this file.
1 // Copyright 2010-2021 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 <algorithm>
17 #include <cmath>
18 #include <cstdint>
19 #include <iterator>
20 #include <limits>
21 #include <string>
22 #include <utility>
23 #include <vector>
24 
25 #include "absl/container/flat_hash_map.h"
26 #include "absl/numeric/int128.h"
29 #include "ortools/base/logging.h"
30 #include "ortools/base/map_util.h"
31 #include "ortools/base/mathutil.h"
32 #include "ortools/base/stl_util.h"
36 #include "ortools/glop/status.h"
40 #include "ortools/sat/integer.h"
43 
44 namespace operations_research {
45 namespace sat {
46 
47 using glop::ColIndex;
48 using glop::Fractional;
49 using glop::RowIndex;
50 
52  if (is_sparse_) {
53  for (const glop::ColIndex col : non_zeros_) {
54  dense_vector_[col] = IntegerValue(0);
55  }
56  dense_vector_.resize(size, IntegerValue(0));
57  } else {
58  dense_vector_.assign(size, IntegerValue(0));
59  }
60  for (const glop::ColIndex col : non_zeros_) {
61  is_zeros_[col] = true;
62  }
63  is_zeros_.resize(size, true);
64  non_zeros_.clear();
65  is_sparse_ = true;
66 }
67 
68 bool ScatteredIntegerVector::Add(glop::ColIndex col, IntegerValue value) {
69  const int64_t add = CapAdd(value.value(), dense_vector_[col].value());
70  if (add == std::numeric_limits<int64_t>::min() ||
72  return false;
73  dense_vector_[col] = IntegerValue(add);
74  if (is_sparse_ && is_zeros_[col]) {
75  is_zeros_[col] = false;
76  non_zeros_.push_back(col);
77  }
78  return true;
79 }
80 
82  IntegerValue multiplier,
83  const std::vector<std::pair<glop::ColIndex, IntegerValue>>& terms) {
84  const double threshold = 0.1 * static_cast<double>(dense_vector_.size());
85  if (is_sparse_ && static_cast<double>(terms.size()) < threshold) {
86  for (const std::pair<glop::ColIndex, IntegerValue> term : terms) {
87  if (is_zeros_[term.first]) {
88  is_zeros_[term.first] = false;
89  non_zeros_.push_back(term.first);
90  }
91  if (!AddProductTo(multiplier, term.second, &dense_vector_[term.first])) {
92  return false;
93  }
94  }
95  if (static_cast<double>(non_zeros_.size()) < threshold) {
96  is_sparse_ = false;
97  }
98  } else {
99  is_sparse_ = false;
100  for (const std::pair<glop::ColIndex, IntegerValue> term : terms) {
101  if (!AddProductTo(multiplier, term.second, &dense_vector_[term.first])) {
102  return false;
103  }
104  }
105  }
106  return true;
107 }
108 
110  const std::vector<IntegerVariable>& integer_variables,
111  IntegerValue upper_bound, LinearConstraint* result) {
112  result->vars.clear();
113  result->coeffs.clear();
114  if (is_sparse_) {
115  std::sort(non_zeros_.begin(), non_zeros_.end());
116  for (const glop::ColIndex col : non_zeros_) {
117  const IntegerValue coeff = dense_vector_[col];
118  if (coeff == 0) continue;
119  result->vars.push_back(integer_variables[col.value()]);
120  result->coeffs.push_back(coeff);
121  }
122  } else {
123  const int size = dense_vector_.size();
124  for (glop::ColIndex col(0); col < size; ++col) {
125  const IntegerValue coeff = dense_vector_[col];
126  if (coeff == 0) continue;
127  result->vars.push_back(integer_variables[col.value()]);
128  result->coeffs.push_back(coeff);
129  }
130  }
131  result->lb = kMinIntegerValue;
132  result->ub = upper_bound;
133 }
134 
135 std::vector<std::pair<glop::ColIndex, IntegerValue>>
137  std::vector<std::pair<glop::ColIndex, IntegerValue>> result;
138  if (is_sparse_) {
139  std::sort(non_zeros_.begin(), non_zeros_.end());
140  for (const glop::ColIndex col : non_zeros_) {
141  const IntegerValue coeff = dense_vector_[col];
142  if (coeff != 0) result.push_back({col, coeff});
143  }
144  } else {
145  const int size = dense_vector_.size();
146  for (glop::ColIndex col(0); col < size; ++col) {
147  const IntegerValue coeff = dense_vector_[col];
148  if (coeff != 0) result.push_back({col, coeff});
149  }
150  }
151  return result;
152 }
153 
154 // TODO(user): make SatParameters singleton too, otherwise changing them after
155 // a constraint was added will have no effect on this class.
157  : constraint_manager_(model),
158  sat_parameters_(*(model->GetOrCreate<SatParameters>())),
159  model_(model),
160  time_limit_(model->GetOrCreate<TimeLimit>()),
161  integer_trail_(model->GetOrCreate<IntegerTrail>()),
162  trail_(model->GetOrCreate<Trail>()),
163  integer_encoder_(model->GetOrCreate<IntegerEncoder>()),
164  random_(model->GetOrCreate<ModelRandomGenerator>()),
165  implied_bounds_processor_({}, integer_trail_,
166  model->GetOrCreate<ImpliedBounds>()),
167  dispatcher_(model->GetOrCreate<LinearProgrammingDispatcher>()),
168  expanded_lp_solution_(
169  *model->GetOrCreate<LinearProgrammingConstraintLpSolution>()) {
170  // Tweak the default parameters to make the solve incremental.
171  glop::GlopParameters parameters;
172  parameters.set_use_dual_simplex(true);
173  simplex_.SetParameters(parameters);
174  if (sat_parameters_.use_branching_in_lp() ||
175  sat_parameters_.search_branching() == SatParameters::LP_SEARCH) {
176  compute_reduced_cost_averages_ = true;
177  }
178 
179  // Register our local rev int repository.
180  integer_trail_->RegisterReversibleClass(&rc_rev_int_repository_);
181 }
182 
184  VLOG(1) << "Total number of simplex iterations: "
185  << total_num_simplex_iterations_;
186  for (int i = 0; i < num_solves_by_status_.size(); ++i) {
187  if (num_solves_by_status_[i] == 0) continue;
188  VLOG(1) << "#" << glop::ProblemStatus(i) << " : "
189  << num_solves_by_status_[i];
190  }
191 }
192 
194  const LinearConstraint& ct) {
195  DCHECK(!lp_constraint_is_registered_);
196  constraint_manager_.Add(ct);
197 
198  // We still create the mirror variable right away though.
199  //
200  // TODO(user): clean this up? Note that it is important that the variable
201  // in lp_data_ never changes though, so we can restart from the current
202  // lp solution and be incremental (even if the constraints changed).
203  for (const IntegerVariable var : ct.vars) {
204  GetOrCreateMirrorVariable(PositiveVariable(var));
205  }
206 }
207 
208 glop::ColIndex LinearProgrammingConstraint::GetOrCreateMirrorVariable(
209  IntegerVariable positive_variable) {
210  DCHECK(VariableIsPositive(positive_variable));
211  const auto it = mirror_lp_variable_.find(positive_variable);
212  if (it == mirror_lp_variable_.end()) {
213  const glop::ColIndex col(integer_variables_.size());
214  implied_bounds_processor_.AddLpVariable(positive_variable);
215  mirror_lp_variable_[positive_variable] = col;
216  integer_variables_.push_back(positive_variable);
217  lp_solution_.push_back(std::numeric_limits<double>::infinity());
218  lp_reduced_cost_.push_back(0.0);
219  (*dispatcher_)[positive_variable] = this;
220 
221  const int index = std::max(positive_variable.value(),
222  NegationOf(positive_variable).value());
223  if (index >= expanded_lp_solution_.size()) {
224  expanded_lp_solution_.resize(index + 1, 0.0);
225  }
226  return col;
227  }
228  return it->second;
229 }
230 
232  IntegerValue coeff) {
233  CHECK(!lp_constraint_is_registered_);
234  objective_is_defined_ = true;
235  IntegerVariable pos_var = VariableIsPositive(ivar) ? ivar : NegationOf(ivar);
236  if (ivar != pos_var) coeff = -coeff;
237 
238  constraint_manager_.SetObjectiveCoefficient(pos_var, coeff);
239  const glop::ColIndex col = GetOrCreateMirrorVariable(pos_var);
240  integer_objective_.push_back({col, coeff});
241  objective_infinity_norm_ =
242  std::max(objective_infinity_norm_, IntTypeAbs(coeff));
243 }
244 
245 // TODO(user): As the search progress, some variables might get fixed. Exploit
246 // this to reduce the number of variables in the LP and in the
247 // ConstraintManager? We might also detect during the search that two variable
248 // are equivalent.
249 //
250 // TODO(user): On TSP/VRP with a lot of cuts, this can take 20% of the overall
251 // running time. We should be able to almost remove most of this from the
252 // profile by being more incremental (modulo LP scaling).
253 //
254 // TODO(user): A longer term idea for LP with a lot of variables is to not
255 // add all variables to each LP solve and do some "sifting". That can be useful
256 // for TSP for instance where the number of edges is large, but only a small
257 // fraction will be used in the optimal solution.
258 bool LinearProgrammingConstraint::CreateLpFromConstraintManager() {
259  // Fill integer_lp_.
260  integer_lp_.clear();
261  infinity_norms_.clear();
262  const auto& all_constraints = constraint_manager_.AllConstraints();
263  for (const auto index : constraint_manager_.LpConstraints()) {
264  const LinearConstraint& ct = all_constraints[index].constraint;
265 
266  integer_lp_.push_back(LinearConstraintInternal());
267  LinearConstraintInternal& new_ct = integer_lp_.back();
268  new_ct.lb = ct.lb;
269  new_ct.ub = ct.ub;
270  const int size = ct.vars.size();
271  IntegerValue infinity_norm(0);
272  if (ct.lb > ct.ub) {
273  VLOG(1) << "Trivial infeasible bound in an LP constraint";
274  return false;
275  }
276  if (ct.lb > kMinIntegerValue) {
277  infinity_norm = std::max(infinity_norm, IntTypeAbs(ct.lb));
278  }
279  if (ct.ub < kMaxIntegerValue) {
280  infinity_norm = std::max(infinity_norm, IntTypeAbs(ct.ub));
281  }
282  for (int i = 0; i < size; ++i) {
283  // We only use positive variable inside this class.
284  IntegerVariable var = ct.vars[i];
285  IntegerValue coeff = ct.coeffs[i];
286  if (!VariableIsPositive(var)) {
287  var = NegationOf(var);
288  coeff = -coeff;
289  }
290  infinity_norm = std::max(infinity_norm, IntTypeAbs(coeff));
291  new_ct.terms.push_back({GetOrCreateMirrorVariable(var), coeff});
292  }
293  infinity_norms_.push_back(infinity_norm);
294 
295  // Important to keep lp_data_ "clean".
296  std::sort(new_ct.terms.begin(), new_ct.terms.end());
297  }
298 
299  // Copy the integer_lp_ into lp_data_.
300  lp_data_.Clear();
301  for (int i = 0; i < integer_variables_.size(); ++i) {
302  CHECK_EQ(glop::ColIndex(i), lp_data_.CreateNewVariable());
303  }
304 
305  // We remove fixed variables from the objective. This should help the LP
306  // scaling, but also our integer reason computation.
307  int new_size = 0;
308  objective_infinity_norm_ = 0;
309  for (const auto entry : integer_objective_) {
310  const IntegerVariable var = integer_variables_[entry.first.value()];
311  if (integer_trail_->IsFixedAtLevelZero(var)) {
312  integer_objective_offset_ +=
313  entry.second * integer_trail_->LevelZeroLowerBound(var);
314  continue;
315  }
316  objective_infinity_norm_ =
317  std::max(objective_infinity_norm_, IntTypeAbs(entry.second));
318  integer_objective_[new_size++] = entry;
319  lp_data_.SetObjectiveCoefficient(entry.first, ToDouble(entry.second));
320  }
321  objective_infinity_norm_ =
322  std::max(objective_infinity_norm_, IntTypeAbs(integer_objective_offset_));
323  integer_objective_.resize(new_size);
324  lp_data_.SetObjectiveOffset(ToDouble(integer_objective_offset_));
325 
326  for (const LinearConstraintInternal& ct : integer_lp_) {
327  const ConstraintIndex row = lp_data_.CreateNewConstraint();
328  lp_data_.SetConstraintBounds(row, ToDouble(ct.lb), ToDouble(ct.ub));
329  for (const auto& term : ct.terms) {
330  lp_data_.SetCoefficient(row, term.first, ToDouble(term.second));
331  }
332  }
333  lp_data_.NotifyThatColumnsAreClean();
334 
335  // We scale the LP using the level zero bounds that we later override
336  // with the current ones.
337  //
338  // TODO(user): As part of the scaling, we may also want to shift the initial
339  // variable bounds so that each variable contain the value zero in their
340  // domain. Maybe just once and for all at the beginning.
341  const int num_vars = integer_variables_.size();
342  for (int i = 0; i < num_vars; i++) {
343  const IntegerVariable cp_var = integer_variables_[i];
344  const double lb = ToDouble(integer_trail_->LevelZeroLowerBound(cp_var));
345  const double ub = ToDouble(integer_trail_->LevelZeroUpperBound(cp_var));
346  lp_data_.SetVariableBounds(glop::ColIndex(i), lb, ub);
347  }
348 
349  // TODO(user): As we have an idea of the LP optimal after the first solves,
350  // maybe we can adapt the scaling accordingly.
351  glop::GlopParameters params;
352  params.set_cost_scaling(glop::GlopParameters::MEAN_COST_SCALING);
353  scaler_.Scale(params, &lp_data_);
354  UpdateBoundsOfLpVariables();
355 
356  // Set the information for the step to polish the LP basis. All our variables
357  // are integer, but for now, we just try to minimize the fractionality of the
358  // binary variables.
359  if (sat_parameters_.polish_lp_solution()) {
360  simplex_.ClearIntegralityScales();
361  for (int i = 0; i < num_vars; ++i) {
362  const IntegerVariable cp_var = integer_variables_[i];
363  const IntegerValue lb = integer_trail_->LevelZeroLowerBound(cp_var);
364  const IntegerValue ub = integer_trail_->LevelZeroUpperBound(cp_var);
365  if (lb != 0 || ub != 1) continue;
366  simplex_.SetIntegralityScale(
367  glop::ColIndex(i),
368  1.0 / scaler_.VariableScalingFactor(glop::ColIndex(i)));
369  }
370  }
371 
372  lp_data_.NotifyThatColumnsAreClean();
373  lp_data_.AddSlackVariablesWhereNecessary(false);
374  VLOG(1) << "LP relaxation: " << lp_data_.GetDimensionString() << ". "
375  << constraint_manager_.AllConstraints().size()
376  << " Managed constraints.";
377  return true;
378 }
379 
380 LPSolveInfo LinearProgrammingConstraint::SolveLpForBranching() {
381  LPSolveInfo info;
382  glop::BasisState basis_state = simplex_.GetState();
383 
384  const glop::Status status = simplex_.Solve(lp_data_, time_limit_);
385  total_num_simplex_iterations_ += simplex_.GetNumberOfIterations();
386  simplex_.LoadStateForNextSolve(basis_state);
387  if (!status.ok()) {
388  VLOG(1) << "The LP solver encountered an error: " << status.error_message();
389  info.status = glop::ProblemStatus::ABNORMAL;
390  return info;
391  }
392  info.status = simplex_.GetProblemStatus();
393  if (info.status == glop::ProblemStatus::OPTIMAL ||
394  info.status == glop::ProblemStatus::DUAL_FEASIBLE) {
395  // Record the objective bound.
396  info.lp_objective = simplex_.GetObjectiveValue();
397  info.new_obj_bound = IntegerValue(
398  static_cast<int64_t>(std::ceil(info.lp_objective - kCpEpsilon)));
399  }
400  return info;
401 }
402 
403 void LinearProgrammingConstraint::FillReducedCostReasonIn(
404  const glop::DenseRow& reduced_costs,
405  std::vector<IntegerLiteral>* integer_reason) {
406  integer_reason->clear();
407  const int num_vars = integer_variables_.size();
408  for (int i = 0; i < num_vars; i++) {
409  const double rc = reduced_costs[glop::ColIndex(i)];
410  if (rc > kLpEpsilon) {
411  integer_reason->push_back(
412  integer_trail_->LowerBoundAsLiteral(integer_variables_[i]));
413  } else if (rc < -kLpEpsilon) {
414  integer_reason->push_back(
415  integer_trail_->UpperBoundAsLiteral(integer_variables_[i]));
416  }
417  }
418 
419  integer_trail_->RemoveLevelZeroBounds(integer_reason);
420 }
421 
422 bool LinearProgrammingConstraint::BranchOnVar(IntegerVariable positive_var) {
423  // From the current LP solution, branch on the given var if fractional.
424  DCHECK(lp_solution_is_set_);
425  const double current_value = GetSolutionValue(positive_var);
426  DCHECK_GT(std::abs(current_value - std::round(current_value)), kCpEpsilon);
427 
428  // Used as empty reason in this method.
429  integer_reason_.clear();
430 
431  bool deductions_were_made = false;
432 
433  UpdateBoundsOfLpVariables();
434 
435  const IntegerValue current_obj_lb = integer_trail_->LowerBound(objective_cp_);
436  // This will try to branch in both direction around the LP value of the
437  // given variable and push any deduction done this way.
438 
439  const glop::ColIndex lp_var = GetOrCreateMirrorVariable(positive_var);
440  const double current_lb = ToDouble(integer_trail_->LowerBound(positive_var));
441  const double current_ub = ToDouble(integer_trail_->UpperBound(positive_var));
442  const double factor = scaler_.VariableScalingFactor(lp_var);
443  if (current_value < current_lb || current_value > current_ub) {
444  return false;
445  }
446 
447  // Form LP1 var <= floor(current_value)
448  const double new_ub = std::floor(current_value);
449  lp_data_.SetVariableBounds(lp_var, current_lb * factor, new_ub * factor);
450 
451  LPSolveInfo lower_branch_info = SolveLpForBranching();
452  if (lower_branch_info.status != glop::ProblemStatus::OPTIMAL &&
453  lower_branch_info.status != glop::ProblemStatus::DUAL_FEASIBLE &&
454  lower_branch_info.status != glop::ProblemStatus::DUAL_UNBOUNDED) {
455  return false;
456  }
457 
458  if (lower_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
459  // Push the other branch.
460  const IntegerLiteral deduction = IntegerLiteral::GreaterOrEqual(
461  positive_var, IntegerValue(std::ceil(current_value)));
462  if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
463  return false;
464  }
465  deductions_were_made = true;
466  } else if (lower_branch_info.new_obj_bound <= current_obj_lb) {
467  return false;
468  }
469 
470  // Form LP2 var >= ceil(current_value)
471  const double new_lb = std::ceil(current_value);
472  lp_data_.SetVariableBounds(lp_var, new_lb * factor, current_ub * factor);
473 
474  LPSolveInfo upper_branch_info = SolveLpForBranching();
475  if (upper_branch_info.status != glop::ProblemStatus::OPTIMAL &&
476  upper_branch_info.status != glop::ProblemStatus::DUAL_FEASIBLE &&
477  upper_branch_info.status != glop::ProblemStatus::DUAL_UNBOUNDED) {
478  return deductions_were_made;
479  }
480 
481  if (upper_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
482  // Push the other branch if not infeasible.
483  if (lower_branch_info.status != glop::ProblemStatus::DUAL_UNBOUNDED) {
484  const IntegerLiteral deduction = IntegerLiteral::LowerOrEqual(
485  positive_var, IntegerValue(std::floor(current_value)));
486  if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
487  return deductions_were_made;
488  }
489  deductions_were_made = true;
490  }
491  } else if (upper_branch_info.new_obj_bound <= current_obj_lb) {
492  return deductions_were_made;
493  }
494 
495  IntegerValue approximate_obj_lb = kMinIntegerValue;
496 
497  if (lower_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED &&
498  upper_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
499  return integer_trail_->ReportConflict(integer_reason_);
500  } else if (lower_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
501  approximate_obj_lb = upper_branch_info.new_obj_bound;
502  } else if (upper_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
503  approximate_obj_lb = lower_branch_info.new_obj_bound;
504  } else {
505  approximate_obj_lb = std::min(lower_branch_info.new_obj_bound,
506  upper_branch_info.new_obj_bound);
507  }
508 
509  // NOTE: On some problems, the approximate_obj_lb could be inexact which add
510  // some tolerance to CP-SAT where currently there is none.
511  if (approximate_obj_lb <= current_obj_lb) return deductions_were_made;
512 
513  // Push the bound to the trail.
514  const IntegerLiteral deduction =
515  IntegerLiteral::GreaterOrEqual(objective_cp_, approximate_obj_lb);
516  if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
517  return deductions_were_made;
518  }
519 
520  return true;
521 }
522 
524  DCHECK(!lp_constraint_is_registered_);
525  lp_constraint_is_registered_ = true;
526  model->GetOrCreate<LinearProgrammingConstraintCollection>()->push_back(this);
527 
528  // Note fdid, this is not really needed by should lead to better cache
529  // locality.
530  std::sort(integer_objective_.begin(), integer_objective_.end());
531 
532  // Set the LP to its initial content.
533  if (!sat_parameters_.add_lp_constraints_lazily()) {
534  constraint_manager_.AddAllConstraintsToLp();
535  }
536  if (!CreateLpFromConstraintManager()) {
537  model->GetOrCreate<SatSolver>()->NotifyThatModelIsUnsat();
538  return;
539  }
540 
541  GenericLiteralWatcher* watcher = model->GetOrCreate<GenericLiteralWatcher>();
542  const int watcher_id = watcher->Register(this);
543  const int num_vars = integer_variables_.size();
544  for (int i = 0; i < num_vars; i++) {
545  watcher->WatchIntegerVariable(integer_variables_[i], watcher_id, i);
546  }
547  if (objective_is_defined_) {
548  watcher->WatchUpperBound(objective_cp_, watcher_id);
549  }
550  watcher->SetPropagatorPriority(watcher_id, 2);
551  watcher->AlwaysCallAtLevelZero(watcher_id);
552 
553  // Registering it with the trail make sure this class is always in sync when
554  // it is used in the decision heuristics.
555  integer_trail_->RegisterReversibleClass(this);
556  watcher->RegisterReversibleInt(watcher_id, &rev_optimal_constraints_size_);
557 }
558 
560  optimal_constraints_.resize(rev_optimal_constraints_size_);
561  if (lp_solution_is_set_ && level < lp_solution_level_) {
562  lp_solution_is_set_ = false;
563  }
564 
565  // Special case for level zero, we "reload" any previously known optimal
566  // solution from that level.
567  //
568  // TODO(user): Keep all optimal solution in the current branch?
569  // TODO(user): Still try to add cuts/constraints though!
570  if (level == 0 && !level_zero_lp_solution_.empty()) {
571  lp_solution_is_set_ = true;
572  lp_solution_ = level_zero_lp_solution_;
573  lp_solution_level_ = 0;
574  for (int i = 0; i < lp_solution_.size(); i++) {
575  expanded_lp_solution_[integer_variables_[i]] = lp_solution_[i];
576  expanded_lp_solution_[NegationOf(integer_variables_[i])] =
577  -lp_solution_[i];
578  }
579  }
580 }
581 
583  for (const IntegerVariable var : generator.vars) {
584  GetOrCreateMirrorVariable(VariableIsPositive(var) ? var : NegationOf(var));
585  }
586  cut_generators_.push_back(std::move(generator));
587 }
588 
590  const std::vector<int>& watch_indices) {
591  if (!lp_solution_is_set_) return Propagate();
592 
593  // At level zero, if there is still a chance to add cuts or lazy constraints,
594  // we re-run the LP.
595  if (trail_->CurrentDecisionLevel() == 0 && !lp_at_level_zero_is_final_) {
596  return Propagate();
597  }
598 
599  // Check whether the change breaks the current LP solution. If it does, call
600  // Propagate() on the current LP.
601  for (const int index : watch_indices) {
602  const double lb =
603  ToDouble(integer_trail_->LowerBound(integer_variables_[index]));
604  const double ub =
605  ToDouble(integer_trail_->UpperBound(integer_variables_[index]));
606  const double value = lp_solution_[index];
607  if (value < lb - kCpEpsilon || value > ub + kCpEpsilon) return Propagate();
608  }
609 
610  // TODO(user): The saved lp solution is still valid given the current variable
611  // bounds, so the LP optimal didn't change. However we might still want to add
612  // new cuts or new lazy constraints?
613  //
614  // TODO(user): Propagate the last optimal_constraint? Note that we need
615  // to be careful since the reversible int in IntegerSumLE are not registered.
616  // However, because we delete "optimalconstraints" on backtrack, we might not
617  // care.
618  return true;
619 }
620 
621 glop::Fractional LinearProgrammingConstraint::GetVariableValueAtCpScale(
622  glop::ColIndex var) {
623  return scaler_.UnscaleVariableValue(var, simplex_.GetVariableValue(var));
624 }
625 
627  IntegerVariable variable) const {
628  return lp_solution_[gtl::FindOrDie(mirror_lp_variable_, variable).value()];
629 }
630 
632  IntegerVariable variable) const {
633  return lp_reduced_cost_[gtl::FindOrDie(mirror_lp_variable_, variable)
634  .value()];
635 }
636 
637 void LinearProgrammingConstraint::UpdateBoundsOfLpVariables() {
638  const int num_vars = integer_variables_.size();
639  for (int i = 0; i < num_vars; i++) {
640  const IntegerVariable cp_var = integer_variables_[i];
641  const double lb = ToDouble(integer_trail_->LowerBound(cp_var));
642  const double ub = ToDouble(integer_trail_->UpperBound(cp_var));
643  const double factor = scaler_.VariableScalingFactor(glop::ColIndex(i));
644  lp_data_.SetVariableBounds(glop::ColIndex(i), lb * factor, ub * factor);
645  }
646 }
647 
648 bool LinearProgrammingConstraint::SolveLp() {
649  if (trail_->CurrentDecisionLevel() == 0) {
650  lp_at_level_zero_is_final_ = false;
651  }
652 
653  const auto status = simplex_.Solve(lp_data_, time_limit_);
654  total_num_simplex_iterations_ += simplex_.GetNumberOfIterations();
655  if (!status.ok()) {
656  VLOG(1) << "The LP solver encountered an error: " << status.error_message();
657  simplex_.ClearStateForNextSolve();
658  return false;
659  }
660  average_degeneracy_.AddData(CalculateDegeneracy());
661  if (average_degeneracy_.CurrentAverage() >= 1000.0) {
662  VLOG(2) << "High average degeneracy: "
663  << average_degeneracy_.CurrentAverage();
664  }
665 
666  const int status_as_int = static_cast<int>(simplex_.GetProblemStatus());
667  if (status_as_int >= num_solves_by_status_.size()) {
668  num_solves_by_status_.resize(status_as_int + 1);
669  }
670  num_solves_by_status_[status_as_int]++;
671  VLOG(2) << "lvl:" << trail_->CurrentDecisionLevel() << " "
672  << simplex_.GetProblemStatus()
673  << " iter:" << simplex_.GetNumberOfIterations()
674  << " obj:" << simplex_.GetObjectiveValue();
675 
677  lp_solution_is_set_ = true;
678  lp_solution_level_ = trail_->CurrentDecisionLevel();
679  const int num_vars = integer_variables_.size();
680  for (int i = 0; i < num_vars; i++) {
681  const glop::Fractional value =
682  GetVariableValueAtCpScale(glop::ColIndex(i));
683  lp_solution_[i] = value;
684  expanded_lp_solution_[integer_variables_[i]] = value;
685  expanded_lp_solution_[NegationOf(integer_variables_[i])] = -value;
686  }
687 
688  if (lp_solution_level_ == 0) {
689  level_zero_lp_solution_ = lp_solution_;
690  }
691  }
692  return true;
693 }
694 
695 bool LinearProgrammingConstraint::AddCutFromConstraints(
696  const std::string& name,
697  const std::vector<std::pair<RowIndex, IntegerValue>>& integer_multipliers) {
698  // This is initialized to a valid linear constraint (by taking linear
699  // combination of the LP rows) and will be transformed into a cut if
700  // possible.
701  //
702  // TODO(user): For CG cuts, Ideally this linear combination should have only
703  // one fractional variable (basis_col). But because of imprecision, we get a
704  // bunch of fractional entry with small coefficient (relative to the one of
705  // basis_col). We try to handle that in IntegerRoundingCut(), but it might be
706  // better to add small multiple of the involved rows to get rid of them.
707  IntegerValue cut_ub;
708  if (!ComputeNewLinearConstraint(integer_multipliers, &tmp_scattered_vector_,
709  &cut_ub)) {
710  VLOG(1) << "Issue, overflow!";
711  return false;
712  }
713 
714  // Important: because we use integer_multipliers below, we cannot just
715  // divide by GCD or call PreventOverflow() here.
716  //
717  // TODO(user): the conversion col_index -> IntegerVariable is slow and could
718  // in principle be removed. Easy for cuts, but not so much for
719  // implied_bounds_processor_. Note that in theory this could allow us to
720  // use Literal directly without the need to have an IntegerVariable for them.
721  tmp_scattered_vector_.ConvertToLinearConstraint(integer_variables_, cut_ub,
722  &cut_);
723 
724  // Note that the base constraint we use are currently always tight.
725  // It is not a requirement though.
726  if (DEBUG_MODE) {
727  const double norm = ToDouble(ComputeInfinityNorm(cut_));
728  const double activity = ComputeActivity(cut_, expanded_lp_solution_);
729  if (std::abs(activity - ToDouble(cut_.ub)) / norm > 1e-4) {
730  VLOG(1) << "Cut not tight " << activity << " <= " << ToDouble(cut_.ub);
731  return false;
732  }
733  }
734  CHECK(constraint_manager_.DebugCheckConstraint(cut_));
735 
736  // We will create "artificial" variables after this index that will be
737  // substitued back into LP variables afterwards. Also not that we only use
738  // positive variable indices for these new variables, so that algorithm that
739  // take their negation will not mess up the indexing.
740  const IntegerVariable first_new_var(expanded_lp_solution_.size());
741  CHECK_EQ(first_new_var.value() % 2, 0);
742 
743  LinearConstraint copy_in_debug;
744  if (DEBUG_MODE) {
745  copy_in_debug = cut_;
746  }
747 
748  // Unlike for the knapsack cuts, it might not be always beneficial to
749  // process the implied bounds even though it seems to be better in average.
750  //
751  // TODO(user): Perform more experiments, in particular with which bound we use
752  // and if we complement or not before the MIR rounding. Other solvers seems
753  // to try different complementation strategies in a "potprocessing" and we
754  // don't. Try this too.
755  std::vector<ImpliedBoundsProcessor::SlackInfo> ib_slack_infos;
756  implied_bounds_processor_.ProcessUpperBoundedConstraintWithSlackCreation(
757  /*substitute_only_inner_variables=*/false, first_new_var,
758  expanded_lp_solution_, &cut_, &ib_slack_infos);
759  DCHECK(implied_bounds_processor_.DebugSlack(first_new_var, copy_in_debug,
760  cut_, ib_slack_infos));
761 
762  // Fills data for IntegerRoundingCut().
763  //
764  // Note(user): we use the current bound here, so the reasonement will only
765  // produce locally valid cut if we call this at a non-root node. We could
766  // use the level zero bounds if we wanted to generate a globally valid cut
767  // at another level. For now this is only called at level zero anyway.
768  tmp_lp_values_.clear();
769  tmp_var_lbs_.clear();
770  tmp_var_ubs_.clear();
771  for (const IntegerVariable var : cut_.vars) {
772  if (var >= first_new_var) {
774  const auto& info =
775  ib_slack_infos[(var.value() - first_new_var.value()) / 2];
776  tmp_lp_values_.push_back(info.lp_value);
777  tmp_var_lbs_.push_back(info.lb);
778  tmp_var_ubs_.push_back(info.ub);
779  } else {
780  tmp_lp_values_.push_back(expanded_lp_solution_[var]);
781  tmp_var_lbs_.push_back(integer_trail_->LevelZeroLowerBound(var));
782  tmp_var_ubs_.push_back(integer_trail_->LevelZeroUpperBound(var));
783  }
784  }
785 
786  // Add slack.
787  // definition: integer_lp_[row] + slack_row == bound;
788  const IntegerVariable first_slack(first_new_var +
789  IntegerVariable(2 * ib_slack_infos.size()));
790  tmp_slack_rows_.clear();
791  tmp_slack_bounds_.clear();
792  for (const auto pair : integer_multipliers) {
793  const RowIndex row = pair.first;
794  const IntegerValue coeff = pair.second;
795  const auto status = simplex_.GetConstraintStatus(row);
796  if (status == glop::ConstraintStatus::FIXED_VALUE) continue;
797 
798  tmp_lp_values_.push_back(0.0);
799  cut_.vars.push_back(first_slack +
800  2 * IntegerVariable(tmp_slack_rows_.size()));
801  tmp_slack_rows_.push_back(row);
802  cut_.coeffs.push_back(coeff);
803 
804  const IntegerValue diff(
805  CapSub(integer_lp_[row].ub.value(), integer_lp_[row].lb.value()));
806  if (coeff > 0) {
807  tmp_slack_bounds_.push_back(integer_lp_[row].ub);
808  tmp_var_lbs_.push_back(IntegerValue(0));
809  tmp_var_ubs_.push_back(diff);
810  } else {
811  tmp_slack_bounds_.push_back(integer_lp_[row].lb);
812  tmp_var_lbs_.push_back(-diff);
813  tmp_var_ubs_.push_back(IntegerValue(0));
814  }
815  }
816 
817  bool at_least_one_added = false;
818 
819  // Try cover appraoch to find cut.
820  {
821  if (cover_cut_helper_.TrySimpleKnapsack(cut_, tmp_lp_values_, tmp_var_lbs_,
822  tmp_var_ubs_)) {
823  at_least_one_added |= PostprocessAndAddCut(
824  absl::StrCat(name, "_K"), cover_cut_helper_.Info(), first_new_var,
825  first_slack, ib_slack_infos, cover_cut_helper_.mutable_cut());
826  }
827  }
828 
829  // Try integer rounding heuristic to find cut.
830  {
831  RoundingOptions options;
832  options.max_scaling = sat_parameters_.max_integer_rounding_scaling();
833  integer_rounding_cut_helper_.ComputeCut(options, tmp_lp_values_,
834  tmp_var_lbs_, tmp_var_ubs_,
835  &implied_bounds_processor_, &cut_);
836  at_least_one_added |= PostprocessAndAddCut(
837  name,
838  absl::StrCat("num_lifted_booleans=",
839  integer_rounding_cut_helper_.NumLiftedBooleans()),
840  first_new_var, first_slack, ib_slack_infos, &cut_);
841  }
842  return at_least_one_added;
843 }
844 
845 bool LinearProgrammingConstraint::PostprocessAndAddCut(
846  const std::string& name, const std::string& info,
847  IntegerVariable first_new_var, IntegerVariable first_slack,
848  const std::vector<ImpliedBoundsProcessor::SlackInfo>& ib_slack_infos,
849  LinearConstraint* cut) {
850  // Compute the activity. Warning: the cut no longer have the same size so we
851  // cannot use tmp_lp_values_. Note that the substitution below shouldn't
852  // change the activity by definition.
853  double activity = 0.0;
854  for (int i = 0; i < cut->vars.size(); ++i) {
855  if (cut->vars[i] < first_new_var) {
856  activity +=
857  ToDouble(cut->coeffs[i]) * expanded_lp_solution_[cut->vars[i]];
858  }
859  }
860  const double kMinViolation = 1e-4;
861  const double violation = activity - ToDouble(cut->ub);
862  if (violation < kMinViolation) {
863  VLOG(3) << "Bad cut " << activity << " <= " << ToDouble(cut->ub);
864  return false;
865  }
866 
867  // Substitute any slack left.
868  {
869  int num_slack = 0;
870  tmp_scattered_vector_.ClearAndResize(integer_variables_.size());
871  IntegerValue cut_ub = cut->ub;
872  bool overflow = false;
873  for (int i = 0; i < cut->vars.size(); ++i) {
874  const IntegerVariable var = cut->vars[i];
875 
876  // Simple copy for non-slack variables.
877  if (var < first_new_var) {
878  const glop::ColIndex col =
879  gtl::FindOrDie(mirror_lp_variable_, PositiveVariable(var));
880  if (VariableIsPositive(var)) {
881  tmp_scattered_vector_.Add(col, cut->coeffs[i]);
882  } else {
883  tmp_scattered_vector_.Add(col, -cut->coeffs[i]);
884  }
885  continue;
886  }
887 
888  // Replace slack from bound substitution.
889  if (var < first_slack) {
890  const IntegerValue multiplier = cut->coeffs[i];
891  const int index = (var.value() - first_new_var.value()) / 2;
892  CHECK_LT(index, ib_slack_infos.size());
893 
894  std::vector<std::pair<ColIndex, IntegerValue>> terms;
895  for (const std::pair<IntegerVariable, IntegerValue>& term :
896  ib_slack_infos[index].terms) {
897  terms.push_back(
898  {gtl::FindOrDie(mirror_lp_variable_,
899  PositiveVariable(term.first)),
900  VariableIsPositive(term.first) ? term.second : -term.second});
901  }
902  if (!tmp_scattered_vector_.AddLinearExpressionMultiple(multiplier,
903  terms)) {
904  overflow = true;
905  break;
906  }
907  if (!AddProductTo(multiplier, -ib_slack_infos[index].offset, &cut_ub)) {
908  overflow = true;
909  break;
910  }
911  continue;
912  }
913 
914  // Replace slack from LP constraints.
915  ++num_slack;
916  const int slack_index = (var.value() - first_slack.value()) / 2;
917  const glop::RowIndex row = tmp_slack_rows_[slack_index];
918  const IntegerValue multiplier = -cut->coeffs[i];
919  if (!tmp_scattered_vector_.AddLinearExpressionMultiple(
920  multiplier, integer_lp_[row].terms)) {
921  overflow = true;
922  break;
923  }
924 
925  // Update rhs.
926  if (!AddProductTo(multiplier, tmp_slack_bounds_[slack_index], &cut_ub)) {
927  overflow = true;
928  break;
929  }
930  }
931 
932  if (overflow) {
933  VLOG(1) << "Overflow in slack removal.";
934  return false;
935  }
936 
937  VLOG(3) << " num_slack: " << num_slack;
938  tmp_scattered_vector_.ConvertToLinearConstraint(integer_variables_, cut_ub,
939  cut);
940  }
941 
942  // Display some stats used for investigation of cut generation.
943  const std::string extra_info =
944  absl::StrCat(info, " num_ib_substitutions=", ib_slack_infos.size());
945 
946  const double new_violation =
947  ComputeActivity(*cut, expanded_lp_solution_) - ToDouble(cut_.ub);
948  if (std::abs(violation - new_violation) >= 1e-4) {
949  VLOG(1) << "Violation discrepancy after slack removal. "
950  << " before = " << violation << " after = " << new_violation;
951  }
952 
953  DivideByGCD(cut);
954  return constraint_manager_.AddCut(*cut, name, expanded_lp_solution_,
955  extra_info);
956 }
957 
958 // TODO(user): This can be still too slow on some problems like
959 // 30_70_45_05_100.mps.gz. Not this actual function, but the set of computation
960 // it triggers. We should add heuristics to abort earlier if a cut is not
961 // promising. Or only test a few positions and not all rows.
962 void LinearProgrammingConstraint::AddCGCuts() {
963  const RowIndex num_rows = lp_data_.num_constraints();
964  std::vector<std::pair<RowIndex, double>> lp_multipliers;
965  std::vector<std::pair<RowIndex, IntegerValue>> integer_multipliers;
966  for (RowIndex row(0); row < num_rows; ++row) {
967  ColIndex basis_col = simplex_.GetBasis(row);
968  const Fractional lp_value = GetVariableValueAtCpScale(basis_col);
969 
970  // Only consider fractional basis element. We ignore element that are close
971  // to an integer to reduce the amount of positions we try.
972  //
973  // TODO(user): We could just look at the diff with std::floor() in the hope
974  // that when we are just under an integer, the exact computation below will
975  // also be just under it.
976  if (std::abs(lp_value - std::round(lp_value)) < 0.01) continue;
977 
978  // If this variable is a slack, we ignore it. This is because the
979  // corresponding row is not tight under the given lp values.
980  if (basis_col >= integer_variables_.size()) continue;
981 
982  if (time_limit_->LimitReached()) break;
983 
984  // TODO(user): Avoid code duplication between the sparse/dense path.
985  double magnitude = 0.0;
986  lp_multipliers.clear();
987  const glop::ScatteredRow& lambda = simplex_.GetUnitRowLeftInverse(row);
988  if (lambda.non_zeros.empty()) {
989  for (RowIndex row(0); row < num_rows; ++row) {
990  const double value = lambda.values[glop::RowToColIndex(row)];
991  if (std::abs(value) < kZeroTolerance) continue;
992 
993  // There should be no BASIC status, but they could be imprecision
994  // in the GetUnitRowLeftInverse() code? not sure, so better be safe.
995  const auto status = simplex_.GetConstraintStatus(row);
996  if (status == glop::ConstraintStatus::BASIC) {
997  VLOG(1) << "BASIC row not expected! " << value;
998  continue;
999  }
1000 
1001  magnitude = std::max(magnitude, std::abs(value));
1002  lp_multipliers.push_back({row, value});
1003  }
1004  } else {
1005  for (const ColIndex col : lambda.non_zeros) {
1006  const RowIndex row = glop::ColToRowIndex(col);
1007  const double value = lambda.values[col];
1008  if (std::abs(value) < kZeroTolerance) continue;
1009 
1010  const auto status = simplex_.GetConstraintStatus(row);
1011  if (status == glop::ConstraintStatus::BASIC) {
1012  VLOG(1) << "BASIC row not expected! " << value;
1013  continue;
1014  }
1015 
1016  magnitude = std::max(magnitude, std::abs(value));
1017  lp_multipliers.push_back({row, value});
1018  }
1019  }
1020  if (lp_multipliers.empty()) continue;
1021 
1022  Fractional scaling;
1023  for (int i = 0; i < 2; ++i) {
1024  if (i == 1) {
1025  // Try other sign.
1026  //
1027  // TODO(user): Maybe add an heuristic to know beforehand which sign to
1028  // use?
1029  for (std::pair<RowIndex, double>& p : lp_multipliers) {
1030  p.second = -p.second;
1031  }
1032  }
1033 
1034  // TODO(user): We use a lower value here otherwise we might run into
1035  // overflow while computing the cut. This should be fixable.
1036  integer_multipliers =
1037  ScaleLpMultiplier(/*take_objective_into_account=*/false,
1038  lp_multipliers, &scaling, /*max_pow=*/52);
1039  AddCutFromConstraints("CG", integer_multipliers);
1040  }
1041  }
1042 }
1043 
1044 namespace {
1045 
1046 // For each element of a, adds a random one in b and append the pair to output.
1047 void RandomPick(const std::vector<RowIndex>& a, const std::vector<RowIndex>& b,
1048  ModelRandomGenerator* random,
1049  std::vector<std::pair<RowIndex, RowIndex>>* output) {
1050  if (a.empty() || b.empty()) return;
1051  for (const RowIndex row : a) {
1052  const RowIndex other = b[absl::Uniform<int>(*random, 0, b.size())];
1053  if (other != row) {
1054  output->push_back({row, other});
1055  }
1056  }
1057 }
1058 
1059 template <class ListOfTerms>
1060 IntegerValue GetCoeff(ColIndex col, const ListOfTerms& terms) {
1061  for (const auto& term : terms) {
1062  if (term.first == col) return term.second;
1063  }
1064  return IntegerValue(0);
1065 }
1066 
1067 } // namespace
1068 
1069 void LinearProgrammingConstraint::AddMirCuts() {
1070  // Heuristic to generate MIR_n cuts by combining a small number of rows. This
1071  // works greedily and follow more or less the MIR cut description in the
1072  // literature. We have a current cut, and we add one more row to it while
1073  // eliminating a variable of the current cut whose LP value is far from its
1074  // bound.
1075  //
1076  // A notable difference is that we randomize the variable we eliminate and
1077  // the row we use to do so. We still have weights to indicate our preferred
1078  // choices. This allows to generate different cuts when called again and
1079  // again.
1080  //
1081  // TODO(user): We could combine n rows to make sure we eliminate n variables
1082  // far away from their bounds by solving exactly in integer small linear
1083  // system.
1085  integer_variables_.size(), IntegerValue(0));
1086  SparseBitset<ColIndex> non_zeros_(ColIndex(integer_variables_.size()));
1087 
1088  // We compute all the rows that are tight, these will be used as the base row
1089  // for the MIR_n procedure below.
1090  const RowIndex num_rows = lp_data_.num_constraints();
1091  std::vector<std::pair<RowIndex, IntegerValue>> base_rows;
1092  absl::StrongVector<RowIndex, double> row_weights(num_rows.value(), 0.0);
1093  for (RowIndex row(0); row < num_rows; ++row) {
1094  const auto status = simplex_.GetConstraintStatus(row);
1095  if (status == glop::ConstraintStatus::BASIC) continue;
1096  if (status == glop::ConstraintStatus::FREE) continue;
1097 
1100  base_rows.push_back({row, IntegerValue(1)});
1101  }
1104  base_rows.push_back({row, IntegerValue(-1)});
1105  }
1106 
1107  // For now, we use the dual values for the row "weights".
1108  //
1109  // Note that we use the dual at LP scale so that it make more sense when we
1110  // compare different rows since the LP has been scaled.
1111  //
1112  // TODO(user): In Kati Wolter PhD "Implementation of Cutting Plane
1113  // Separators for Mixed Integer Programs" which describe SCIP's MIR cuts
1114  // implementation (or at least an early version of it), a more complex score
1115  // is used.
1116  //
1117  // Note(user): Because we only consider tight rows under the current lp
1118  // solution (i.e. non-basic rows), most should have a non-zero dual values.
1119  // But there is some degenerate problem where these rows have a really low
1120  // weight (or even zero), and having only weight of exactly zero in
1121  // std::discrete_distribution will result in a crash.
1122  row_weights[row] = std::max(1e-8, std::abs(simplex_.GetDualValue(row)));
1123  }
1124 
1125  std::vector<double> weights;
1127  std::vector<std::pair<RowIndex, IntegerValue>> integer_multipliers;
1128  for (const std::pair<RowIndex, IntegerValue>& entry : base_rows) {
1129  if (time_limit_->LimitReached()) break;
1130 
1131  // First try to generate a cut directly from this base row (MIR1).
1132  //
1133  // Note(user): We abort on success like it seems to be done in the
1134  // literature. Note that we don't succeed that often in generating an
1135  // efficient cut, so I am not sure aborting will make a big difference
1136  // speedwise. We might generate similar cuts though, but hopefully the cut
1137  // management can deal with that.
1138  integer_multipliers = {entry};
1139  if (AddCutFromConstraints("MIR_1", integer_multipliers)) {
1140  continue;
1141  }
1142 
1143  // Cleanup.
1144  for (const ColIndex col : non_zeros_.PositionsSetAtLeastOnce()) {
1145  dense_cut[col] = IntegerValue(0);
1146  }
1147  non_zeros_.SparseClearAll();
1148 
1149  // Copy cut.
1150  const IntegerValue multiplier = entry.second;
1151  for (const std::pair<ColIndex, IntegerValue> term :
1152  integer_lp_[entry.first].terms) {
1153  const ColIndex col = term.first;
1154  const IntegerValue coeff = term.second;
1155  non_zeros_.Set(col);
1156  dense_cut[col] += coeff * multiplier;
1157  }
1158 
1159  used_rows.assign(num_rows.value(), false);
1160  used_rows[entry.first] = true;
1161 
1162  // We will aggregate at most kMaxAggregation more rows.
1163  //
1164  // TODO(user): optim + tune.
1165  const int kMaxAggregation = 5;
1166  for (int i = 0; i < kMaxAggregation; ++i) {
1167  // First pick a variable to eliminate. We currently pick a random one with
1168  // a weight that depend on how far it is from its closest bound.
1169  IntegerValue max_magnitude(0);
1170  weights.clear();
1171  std::vector<ColIndex> col_candidates;
1172  for (const ColIndex col : non_zeros_.PositionsSetAtLeastOnce()) {
1173  if (dense_cut[col] == 0) continue;
1174 
1175  max_magnitude = std::max(max_magnitude, IntTypeAbs(dense_cut[col]));
1176  const int col_degree =
1177  lp_data_.GetSparseColumn(col).num_entries().value();
1178  if (col_degree <= 1) continue;
1180  continue;
1181  }
1182 
1183  const IntegerVariable var = integer_variables_[col.value()];
1184  const double lp_value = expanded_lp_solution_[var];
1185  const double lb = ToDouble(integer_trail_->LevelZeroLowerBound(var));
1186  const double ub = ToDouble(integer_trail_->LevelZeroUpperBound(var));
1187  const double bound_distance = std::min(ub - lp_value, lp_value - lb);
1188  if (bound_distance > 1e-2) {
1189  weights.push_back(bound_distance);
1190  col_candidates.push_back(col);
1191  }
1192  }
1193  if (col_candidates.empty()) break;
1194 
1195  const ColIndex var_to_eliminate =
1196  col_candidates[std::discrete_distribution<>(weights.begin(),
1197  weights.end())(*random_)];
1198 
1199  // What rows can we add to eliminate var_to_eliminate?
1200  std::vector<RowIndex> possible_rows;
1201  weights.clear();
1202  for (const auto entry : lp_data_.GetSparseColumn(var_to_eliminate)) {
1203  const RowIndex row = entry.row();
1204  const auto status = simplex_.GetConstraintStatus(row);
1205  if (status == glop::ConstraintStatus::BASIC) continue;
1206  if (status == glop::ConstraintStatus::FREE) continue;
1207 
1208  // We disallow all the rows that contain a variable that we already
1209  // eliminated (or are about to). This mean that we choose rows that
1210  // form a "triangular" matrix on the position we choose to eliminate.
1211  if (used_rows[row]) continue;
1212  used_rows[row] = true;
1213 
1214  // TODO(user): Instead of using FIXED_VALUE consider also both direction
1215  // when we almost have an equality? that is if the LP constraints bounds
1216  // are close from each others (<1e-6 ?). Initial experiments shows it
1217  // doesn't change much, so I kept this version for now. Note that it
1218  // might just be better to use the side that constrain the current lp
1219  // optimal solution (that we get from the status).
1220  bool add_row = false;
1221  if (status == glop::ConstraintStatus::FIXED_VALUE ||
1223  if (entry.coefficient() > 0.0) {
1224  if (dense_cut[var_to_eliminate] < 0) add_row = true;
1225  } else {
1226  if (dense_cut[var_to_eliminate] > 0) add_row = true;
1227  }
1228  }
1229  if (status == glop::ConstraintStatus::FIXED_VALUE ||
1231  if (entry.coefficient() > 0.0) {
1232  if (dense_cut[var_to_eliminate] > 0) add_row = true;
1233  } else {
1234  if (dense_cut[var_to_eliminate] < 0) add_row = true;
1235  }
1236  }
1237  if (add_row) {
1238  possible_rows.push_back(row);
1239  weights.push_back(row_weights[row]);
1240  }
1241  }
1242  if (possible_rows.empty()) break;
1243 
1244  const RowIndex row_to_combine =
1245  possible_rows[std::discrete_distribution<>(weights.begin(),
1246  weights.end())(*random_)];
1247  const IntegerValue to_combine_coeff =
1248  GetCoeff(var_to_eliminate, integer_lp_[row_to_combine].terms);
1249  CHECK_NE(to_combine_coeff, 0);
1250 
1251  IntegerValue mult1 = -to_combine_coeff;
1252  IntegerValue mult2 = dense_cut[var_to_eliminate];
1253  CHECK_NE(mult2, 0);
1254  if (mult1 < 0) {
1255  mult1 = -mult1;
1256  mult2 = -mult2;
1257  }
1258 
1259  const IntegerValue gcd = IntegerValue(
1260  MathUtil::GCD64(std::abs(mult1.value()), std::abs(mult2.value())));
1261  CHECK_NE(gcd, 0);
1262  mult1 /= gcd;
1263  mult2 /= gcd;
1264 
1265  // Overflow detection.
1266  //
1267  // TODO(user): do that in the possible_rows selection? only problem is
1268  // that we do not have the integer coefficient there...
1269  for (std::pair<RowIndex, IntegerValue>& entry : integer_multipliers) {
1270  max_magnitude = std::max(max_magnitude, entry.second);
1271  }
1272  if (CapAdd(CapProd(max_magnitude.value(), std::abs(mult1.value())),
1273  CapProd(infinity_norms_[row_to_combine].value(),
1274  std::abs(mult2.value()))) ==
1276  break;
1277  }
1278 
1279  for (std::pair<RowIndex, IntegerValue>& entry : integer_multipliers) {
1280  entry.second *= mult1;
1281  }
1282  integer_multipliers.push_back({row_to_combine, mult2});
1283 
1284  // TODO(user): Not supper efficient to recombine the rows.
1285  if (AddCutFromConstraints(absl::StrCat("MIR_", i + 2),
1286  integer_multipliers)) {
1287  break;
1288  }
1289 
1290  // Minor optim: the computation below is only needed if we do one more
1291  // iteration.
1292  if (i + 1 == kMaxAggregation) break;
1293 
1294  for (ColIndex col : non_zeros_.PositionsSetAtLeastOnce()) {
1295  dense_cut[col] *= mult1;
1296  }
1297  for (const std::pair<ColIndex, IntegerValue> term :
1298  integer_lp_[row_to_combine].terms) {
1299  const ColIndex col = term.first;
1300  const IntegerValue coeff = term.second;
1301  non_zeros_.Set(col);
1302  dense_cut[col] += coeff * mult2;
1303  }
1304  }
1305  }
1306 }
1307 
1308 void LinearProgrammingConstraint::AddZeroHalfCuts() {
1309  if (time_limit_->LimitReached()) return;
1310 
1311  tmp_lp_values_.clear();
1312  tmp_var_lbs_.clear();
1313  tmp_var_ubs_.clear();
1314  for (const IntegerVariable var : integer_variables_) {
1315  tmp_lp_values_.push_back(expanded_lp_solution_[var]);
1316  tmp_var_lbs_.push_back(integer_trail_->LevelZeroLowerBound(var));
1317  tmp_var_ubs_.push_back(integer_trail_->LevelZeroUpperBound(var));
1318  }
1319 
1320  // TODO(user): See if it make sense to try to use implied bounds there.
1321  zero_half_cut_helper_.ProcessVariables(tmp_lp_values_, tmp_var_lbs_,
1322  tmp_var_ubs_);
1323  for (glop::RowIndex row(0); row < integer_lp_.size(); ++row) {
1324  // Even though we could use non-tight row, for now we prefer to use tight
1325  // ones.
1326  const auto status = simplex_.GetConstraintStatus(row);
1327  if (status == glop::ConstraintStatus::BASIC) continue;
1328  if (status == glop::ConstraintStatus::FREE) continue;
1329 
1330  zero_half_cut_helper_.AddOneConstraint(
1331  row, integer_lp_[row].terms, integer_lp_[row].lb, integer_lp_[row].ub);
1332  }
1333  for (const std::vector<std::pair<RowIndex, IntegerValue>>& multipliers :
1334  zero_half_cut_helper_.InterestingCandidates(random_)) {
1335  if (time_limit_->LimitReached()) break;
1336 
1337  // TODO(user): Make sure that if the resulting linear coefficients are not
1338  // too high, we do try a "divisor" of two and thus try a true zero-half cut
1339  // instead of just using our best MIR heuristic (which might still be better
1340  // though).
1341  AddCutFromConstraints("ZERO_HALF", multipliers);
1342  }
1343 }
1344 
1345 void LinearProgrammingConstraint::UpdateSimplexIterationLimit(
1346  const int64_t min_iter, const int64_t max_iter) {
1347  if (sat_parameters_.linearization_level() < 2) return;
1348  const int64_t num_degenerate_columns = CalculateDegeneracy();
1349  const int64_t num_cols = simplex_.GetProblemNumCols().value();
1350  if (num_cols <= 0) {
1351  return;
1352  }
1353  CHECK_GT(num_cols, 0);
1354  const int64_t decrease_factor = (10 * num_degenerate_columns) / num_cols;
1356  // We reached here probably because we predicted wrong. We use this as a
1357  // signal to increase the iterations or punish less for degeneracy compare
1358  // to the other part.
1359  if (is_degenerate_) {
1360  next_simplex_iter_ /= std::max(int64_t{1}, decrease_factor);
1361  } else {
1362  next_simplex_iter_ *= 2;
1363  }
1364  } else if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
1365  if (is_degenerate_) {
1366  next_simplex_iter_ /= std::max(int64_t{1}, 2 * decrease_factor);
1367  } else {
1368  // This is the most common case. We use the size of the problem to
1369  // determine the limit and ignore the previous limit.
1370  next_simplex_iter_ = num_cols / 40;
1371  }
1372  }
1373  next_simplex_iter_ =
1374  std::max(min_iter, std::min(max_iter, next_simplex_iter_));
1375 }
1376 
1378  UpdateBoundsOfLpVariables();
1379 
1380  // TODO(user): It seems the time we loose by not stopping early might be worth
1381  // it because we end up with a better explanation at optimality.
1382  glop::GlopParameters parameters = simplex_.GetParameters();
1383  if (/* DISABLES CODE */ (false) && objective_is_defined_) {
1384  // We put a limit on the dual objective since there is no point increasing
1385  // it past our current objective upper-bound (we will already fail as soon
1386  // as we pass it). Note that this limit is properly transformed using the
1387  // objective scaling factor and offset stored in lp_data_.
1388  //
1389  // Note that we use a bigger epsilon here to be sure that if we abort
1390  // because of this, we will report a conflict.
1391  parameters.set_objective_upper_limit(
1392  static_cast<double>(integer_trail_->UpperBound(objective_cp_).value() +
1393  100.0 * kCpEpsilon));
1394  }
1395 
1396  // Put an iteration limit on the work we do in the simplex for this call. Note
1397  // that because we are "incremental", even if we don't solve it this time we
1398  // will make progress towards a solve in the lower node of the tree search.
1399  if (trail_->CurrentDecisionLevel() == 0) {
1400  // TODO(user): Dynamically change the iteration limit for root node as
1401  // well.
1402  parameters.set_max_number_of_iterations(2000);
1403  } else {
1404  parameters.set_max_number_of_iterations(next_simplex_iter_);
1405  }
1406  if (sat_parameters_.use_exact_lp_reason()) {
1407  parameters.set_change_status_to_imprecise(false);
1408  parameters.set_primal_feasibility_tolerance(1e-7);
1409  parameters.set_dual_feasibility_tolerance(1e-7);
1410  }
1411 
1412  simplex_.SetParameters(parameters);
1414  if (!SolveLp()) return true;
1415 
1416  // Add new constraints to the LP and resolve?
1417  const int max_cuts_rounds =
1418  trail_->CurrentDecisionLevel() == 0
1419  ? sat_parameters_.max_cut_rounds_at_level_zero()
1420  : 1;
1421  int cuts_round = 0;
1422  while (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL &&
1423  cuts_round < max_cuts_rounds) {
1424  // We wait for the first batch of problem constraints to be added before we
1425  // begin to generate cuts.
1426  cuts_round++;
1427  if (!integer_lp_.empty()) {
1428  implied_bounds_processor_.ClearCache();
1429  implied_bounds_processor_.SeparateSomeImpliedBoundCuts(
1430  expanded_lp_solution_);
1431 
1432  // The "generic" cuts are currently part of this class as they are using
1433  // data from the current LP.
1434  //
1435  // TODO(user): Refactor so that they are just normal cut generators?
1436  if (trail_->CurrentDecisionLevel() == 0) {
1437  if (sat_parameters_.add_mir_cuts()) AddMirCuts();
1438  if (sat_parameters_.add_cg_cuts()) AddCGCuts();
1439  if (sat_parameters_.add_zero_half_cuts()) AddZeroHalfCuts();
1440  }
1441 
1442  // Try to add cuts.
1443  if (!cut_generators_.empty() &&
1444  (trail_->CurrentDecisionLevel() == 0 ||
1445  !sat_parameters_.only_add_cuts_at_level_zero())) {
1446  for (const CutGenerator& generator : cut_generators_) {
1447  generator.generate_cuts(expanded_lp_solution_, &constraint_manager_);
1448  }
1449  }
1450 
1451  implied_bounds_processor_.IbCutPool().TransferToManager(
1452  expanded_lp_solution_, &constraint_manager_);
1453  }
1454 
1455  glop::BasisState state = simplex_.GetState();
1456  if (constraint_manager_.ChangeLp(expanded_lp_solution_, &state)) {
1457  simplex_.LoadStateForNextSolve(state);
1458  if (!CreateLpFromConstraintManager()) {
1459  return integer_trail_->ReportConflict({});
1460  }
1461  const double old_obj = simplex_.GetObjectiveValue();
1462  if (!SolveLp()) return true;
1463  if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
1464  VLOG(1) << "Relaxation improvement " << old_obj << " -> "
1465  << simplex_.GetObjectiveValue()
1466  << " diff: " << simplex_.GetObjectiveValue() - old_obj
1467  << " level: " << trail_->CurrentDecisionLevel();
1468  }
1469  } else {
1470  if (trail_->CurrentDecisionLevel() == 0) {
1471  lp_at_level_zero_is_final_ = true;
1472  }
1473  break;
1474  }
1475  }
1476 
1477  // A dual-unbounded problem is infeasible. We use the dual ray reason.
1479  if (sat_parameters_.use_exact_lp_reason()) {
1480  if (!FillExactDualRayReason()) return true;
1481  } else {
1482  FillReducedCostReasonIn(simplex_.GetDualRayRowCombination(),
1483  &integer_reason_);
1484  }
1485  return integer_trail_->ReportConflict(integer_reason_);
1486  }
1487 
1488  // TODO(user): Update limits for DUAL_UNBOUNDED status as well.
1489  UpdateSimplexIterationLimit(/*min_iter=*/10, /*max_iter=*/1000);
1490 
1491  // Optimality deductions if problem has an objective.
1492  if (objective_is_defined_ &&
1495  // Try to filter optimal objective value. Note that GetObjectiveValue()
1496  // already take care of the scaling so that it returns an objective in the
1497  // CP world.
1498  const double relaxed_optimal_objective = simplex_.GetObjectiveValue();
1499  const IntegerValue approximate_new_lb(static_cast<int64_t>(
1500  std::ceil(relaxed_optimal_objective - kCpEpsilon)));
1501 
1502  // TODO(user): Maybe do a bit less computation when we cannot propagate
1503  // anything.
1504  if (sat_parameters_.use_exact_lp_reason()) {
1505  if (!ExactLpReasonning()) return false;
1506 
1507  // Display when the inexact bound would have propagated more.
1508  const IntegerValue propagated_lb =
1509  integer_trail_->LowerBound(objective_cp_);
1510  if (approximate_new_lb > propagated_lb) {
1511  VLOG(2) << "LP objective [ " << ToDouble(propagated_lb) << ", "
1512  << ToDouble(integer_trail_->UpperBound(objective_cp_))
1513  << " ] approx_lb += "
1514  << ToDouble(approximate_new_lb - propagated_lb) << " gap: "
1515  << integer_trail_->UpperBound(objective_cp_) - propagated_lb;
1516  }
1517  } else {
1518  FillReducedCostReasonIn(simplex_.GetReducedCosts(), &integer_reason_);
1519  const double objective_cp_ub =
1520  ToDouble(integer_trail_->UpperBound(objective_cp_));
1521  ReducedCostStrengtheningDeductions(objective_cp_ub -
1522  relaxed_optimal_objective);
1523  if (!deductions_.empty()) {
1524  deductions_reason_ = integer_reason_;
1525  deductions_reason_.push_back(
1526  integer_trail_->UpperBoundAsLiteral(objective_cp_));
1527  }
1528 
1529  // Push new objective lb.
1530  if (approximate_new_lb > integer_trail_->LowerBound(objective_cp_)) {
1531  const IntegerLiteral deduction =
1532  IntegerLiteral::GreaterOrEqual(objective_cp_, approximate_new_lb);
1533  if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
1534  return false;
1535  }
1536  }
1537 
1538  // Push reduced cost strengthening bounds.
1539  if (!deductions_.empty()) {
1540  const int trail_index_with_same_reason = integer_trail_->Index();
1541  for (const IntegerLiteral deduction : deductions_) {
1542  if (!integer_trail_->Enqueue(deduction, {}, deductions_reason_,
1543  trail_index_with_same_reason)) {
1544  return false;
1545  }
1546  }
1547  }
1548  }
1549  }
1550 
1551  // Copy more info about the current solution.
1552  if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
1553  CHECK(lp_solution_is_set_);
1554 
1555  lp_objective_ = simplex_.GetObjectiveValue();
1556  lp_solution_is_integer_ = true;
1557  const int num_vars = integer_variables_.size();
1558  for (int i = 0; i < num_vars; i++) {
1559  lp_reduced_cost_[i] = scaler_.UnscaleReducedCost(
1560  glop::ColIndex(i), simplex_.GetReducedCost(glop::ColIndex(i)));
1561  if (std::abs(lp_solution_[i] - std::round(lp_solution_[i])) >
1562  kCpEpsilon) {
1563  lp_solution_is_integer_ = false;
1564  }
1565  }
1566 
1567  if (compute_reduced_cost_averages_) {
1568  UpdateAverageReducedCosts();
1569  }
1570  }
1571 
1572  if (sat_parameters_.use_branching_in_lp() && objective_is_defined_ &&
1573  trail_->CurrentDecisionLevel() == 0 && !is_degenerate_ &&
1574  lp_solution_is_set_ && !lp_solution_is_integer_ &&
1575  sat_parameters_.linearization_level() >= 2 &&
1576  compute_reduced_cost_averages_ &&
1578  count_since_last_branching_++;
1579  if (count_since_last_branching_ < branching_frequency_) {
1580  return true;
1581  }
1582  count_since_last_branching_ = 0;
1583  bool branching_successful = false;
1584 
1585  // Strong branching on top max_num_branches variable.
1586  const int max_num_branches = 3;
1587  const int num_vars = integer_variables_.size();
1588  std::vector<std::pair<double, IntegerVariable>> branching_vars;
1589  for (int i = 0; i < num_vars; ++i) {
1590  const IntegerVariable var = integer_variables_[i];
1591  const IntegerVariable positive_var = PositiveVariable(var);
1592 
1593  // Skip non fractional variables.
1594  const double current_value = GetSolutionValue(positive_var);
1595  if (std::abs(current_value - std::round(current_value)) <= kCpEpsilon) {
1596  continue;
1597  }
1598 
1599  // Skip ignored variables.
1600  if (integer_trail_->IsCurrentlyIgnored(var)) continue;
1601 
1602  // We can use any metric to select a variable to branch on. Reduced cost
1603  // average is one of the most promissing metric. It captures the history
1604  // of the objective bound improvement in LP due to changes in the given
1605  // variable bounds.
1606  //
1607  // NOTE: We also experimented using PseudoCosts and most recent reduced
1608  // cost as metrics but it doesn't give better results on benchmarks.
1609  const double cost_i = rc_scores_[i];
1610  std::pair<double, IntegerVariable> branching_var =
1611  std::make_pair(-cost_i, positive_var);
1612  auto iterator = std::lower_bound(branching_vars.begin(),
1613  branching_vars.end(), branching_var);
1614 
1615  branching_vars.insert(iterator, branching_var);
1616  if (branching_vars.size() > max_num_branches) {
1617  branching_vars.resize(max_num_branches);
1618  }
1619  }
1620 
1621  for (const std::pair<double, IntegerVariable>& branching_var :
1622  branching_vars) {
1623  const IntegerVariable positive_var = branching_var.second;
1624  VLOG(2) << "Branching on: " << positive_var;
1625  if (BranchOnVar(positive_var)) {
1626  VLOG(2) << "Branching successful.";
1627  branching_successful = true;
1628  } else {
1629  break;
1630  }
1631  }
1632  if (!branching_successful) {
1633  branching_frequency_ *= 2;
1634  }
1635  }
1636  return true;
1637 }
1638 
1639 // Returns kMinIntegerValue in case of overflow.
1640 //
1641 // TODO(user): Because of PreventOverflow(), this should actually never happen.
1642 IntegerValue LinearProgrammingConstraint::GetImpliedLowerBound(
1643  const LinearConstraint& terms) const {
1644  IntegerValue lower_bound(0);
1645  const int size = terms.vars.size();
1646  for (int i = 0; i < size; ++i) {
1647  const IntegerVariable var = terms.vars[i];
1648  const IntegerValue coeff = terms.coeffs[i];
1649  CHECK_NE(coeff, 0);
1650  const IntegerValue bound = coeff > 0 ? integer_trail_->LowerBound(var)
1651  : integer_trail_->UpperBound(var);
1652  if (!AddProductTo(bound, coeff, &lower_bound)) return kMinIntegerValue;
1653  }
1654  return lower_bound;
1655 }
1656 
1657 bool LinearProgrammingConstraint::PossibleOverflow(
1658  const LinearConstraint& constraint) {
1659  IntegerValue lower_bound(0);
1660  const int size = constraint.vars.size();
1661  for (int i = 0; i < size; ++i) {
1662  const IntegerVariable var = constraint.vars[i];
1663  const IntegerValue coeff = constraint.coeffs[i];
1664  CHECK_NE(coeff, 0);
1665  const IntegerValue bound = coeff > 0
1666  ? integer_trail_->LevelZeroLowerBound(var)
1667  : integer_trail_->LevelZeroUpperBound(var);
1668  if (!AddProductTo(bound, coeff, &lower_bound)) {
1669  return true;
1670  }
1671  }
1672  const int64_t slack = CapAdd(lower_bound.value(), -constraint.ub.value());
1673  if (slack == std::numeric_limits<int64_t>::min() ||
1674  slack == std::numeric_limits<int64_t>::max()) {
1675  return true;
1676  }
1677  return false;
1678 }
1679 
1680 namespace {
1681 
1682 absl::int128 FloorRatio128(absl::int128 x, IntegerValue positive_div) {
1683  absl::int128 div128(positive_div.value());
1684  absl::int128 result = x / div128;
1685  if (result * div128 > x) return result - 1;
1686  return result;
1687 }
1688 
1689 } // namespace
1690 
1691 void LinearProgrammingConstraint::PreventOverflow(LinearConstraint* constraint,
1692  int max_pow) {
1693  // Compute the min/max possible partial sum. Note that we need to use the
1694  // level zero bounds here since we might use this cut after backtrack.
1695  double sum_min = std::min(0.0, ToDouble(-constraint->ub));
1696  double sum_max = std::max(0.0, ToDouble(-constraint->ub));
1697  const int size = constraint->vars.size();
1698  for (int i = 0; i < size; ++i) {
1699  const IntegerVariable var = constraint->vars[i];
1700  const double coeff = ToDouble(constraint->coeffs[i]);
1701  const double prod1 =
1702  coeff * ToDouble(integer_trail_->LevelZeroLowerBound(var));
1703  const double prod2 =
1704  coeff * ToDouble(integer_trail_->LevelZeroUpperBound(var));
1705  sum_min += std::min(0.0, std::min(prod1, prod2));
1706  sum_max += std::max(0.0, std::max(prod1, prod2));
1707  }
1708  const double max_value = std::max({sum_max, -sum_min, sum_max - sum_min});
1709 
1710  const IntegerValue divisor(std::ceil(std::ldexp(max_value, -max_pow)));
1711  if (divisor <= 1) return;
1712 
1713  // To be correct, we need to shift all variable so that they are positive.
1714  //
1715  // Important: One might be tempted to think that using the current variable
1716  // bounds is okay here since we only use this to derive cut/constraint that
1717  // only needs to be locally valid. However, in some corner cases (like when
1718  // one term become zero), we might loose the fact that we used one of the
1719  // variable bound to derive the new constraint, so we will miss it in the
1720  // explanation !!
1721  //
1722  // TODO(user): This code is tricky and similar to the one to generate cuts.
1723  // Test and may reduce the duplication? note however that here we use int128
1724  // to deal with potential overflow.
1725  int new_size = 0;
1726  absl::int128 adjust = 0;
1727  for (int i = 0; i < size; ++i) {
1728  const IntegerValue old_coeff = constraint->coeffs[i];
1729  const IntegerValue new_coeff = FloorRatio(old_coeff, divisor);
1730 
1731  // Compute the rhs adjustement.
1732  const absl::int128 remainder =
1733  absl::int128(old_coeff.value()) -
1734  absl::int128(new_coeff.value()) * absl::int128(divisor.value());
1735  adjust +=
1736  remainder *
1737  absl::int128(
1738  integer_trail_->LevelZeroLowerBound(constraint->vars[i]).value());
1739 
1740  if (new_coeff == 0) continue;
1741  constraint->vars[new_size] = constraint->vars[i];
1742  constraint->coeffs[new_size] = new_coeff;
1743  ++new_size;
1744  }
1745  constraint->vars.resize(new_size);
1746  constraint->coeffs.resize(new_size);
1747 
1748  constraint->ub = IntegerValue(static_cast<int64_t>(
1749  FloorRatio128(absl::int128(constraint->ub.value()) - adjust, divisor)));
1750 }
1751 
1752 // TODO(user): combine this with RelaxLinearReason() to avoid the extra
1753 // magnitude vector and the weird precondition of RelaxLinearReason().
1754 void LinearProgrammingConstraint::SetImpliedLowerBoundReason(
1755  const LinearConstraint& terms, IntegerValue slack) {
1756  integer_reason_.clear();
1757  std::vector<IntegerValue> magnitudes;
1758  const int size = terms.vars.size();
1759  for (int i = 0; i < size; ++i) {
1760  const IntegerVariable var = terms.vars[i];
1761  const IntegerValue coeff = terms.coeffs[i];
1762  CHECK_NE(coeff, 0);
1763  if (coeff > 0) {
1764  magnitudes.push_back(coeff);
1765  integer_reason_.push_back(integer_trail_->LowerBoundAsLiteral(var));
1766  } else {
1767  magnitudes.push_back(-coeff);
1768  integer_reason_.push_back(integer_trail_->UpperBoundAsLiteral(var));
1769  }
1770  }
1771  CHECK_GE(slack, 0);
1772  if (slack > 0) {
1773  integer_trail_->RelaxLinearReason(slack, magnitudes, &integer_reason_);
1774  }
1775  integer_trail_->RemoveLevelZeroBounds(&integer_reason_);
1776 }
1777 
1778 std::vector<std::pair<RowIndex, IntegerValue>>
1779 LinearProgrammingConstraint::ScaleLpMultiplier(
1780  bool take_objective_into_account,
1781  const std::vector<std::pair<RowIndex, double>>& lp_multipliers,
1782  Fractional* scaling, int max_pow) const {
1783  double max_sum = 0.0;
1784  tmp_cp_multipliers_.clear();
1785  for (const std::pair<RowIndex, double>& p : lp_multipliers) {
1786  const RowIndex row = p.first;
1787  const Fractional lp_multi = p.second;
1788 
1789  // We ignore small values since these are likely errors and will not
1790  // contribute much to the new lp constraint anyway.
1791  if (std::abs(lp_multi) < kZeroTolerance) continue;
1792 
1793  // Remove trivial bad cases.
1794  //
1795  // TODO(user): It might be better (when possible) to use the OPTIMAL row
1796  // status since in most situation we do want the constraint we add to be
1797  // tight under the current LP solution. Only for infeasible problem we might
1798  // not have access to the status.
1799  if (lp_multi > 0.0 && integer_lp_[row].ub >= kMaxIntegerValue) {
1800  continue;
1801  }
1802  if (lp_multi < 0.0 && integer_lp_[row].lb <= kMinIntegerValue) {
1803  continue;
1804  }
1805 
1806  const Fractional cp_multi = scaler_.UnscaleDualValue(row, lp_multi);
1807  tmp_cp_multipliers_.push_back({row, cp_multi});
1808  max_sum += ToDouble(infinity_norms_[row]) * std::abs(cp_multi);
1809  }
1810 
1811  // This behave exactly like if we had another "objective" constraint with
1812  // an lp_multi of 1.0 and a cp_multi of 1.0.
1813  if (take_objective_into_account) {
1814  max_sum += ToDouble(objective_infinity_norm_);
1815  }
1816 
1817  *scaling = 1.0;
1818  std::vector<std::pair<RowIndex, IntegerValue>> integer_multipliers;
1819  if (max_sum == 0.0) {
1820  // Empty linear combinaison.
1821  return integer_multipliers;
1822  }
1823 
1824  // We want max_sum * scaling to be <= 2 ^ max_pow and fit on an int64_t.
1825  // We use a power of 2 as this seems to work better.
1826  const double threshold = std::ldexp(1, max_pow) / max_sum;
1827  if (threshold < 1.0) {
1828  // TODO(user): we currently do not support scaling down, so we just abort
1829  // in this case.
1830  return integer_multipliers;
1831  }
1832  while (2 * *scaling <= threshold) *scaling *= 2;
1833 
1834  // Scale the multipliers by *scaling.
1835  //
1836  // TODO(user): Maybe use int128 to avoid overflow?
1837  for (const auto entry : tmp_cp_multipliers_) {
1838  const IntegerValue coeff(std::round(entry.second * (*scaling)));
1839  if (coeff != 0) integer_multipliers.push_back({entry.first, coeff});
1840  }
1841  return integer_multipliers;
1842 }
1843 
1844 bool LinearProgrammingConstraint::ComputeNewLinearConstraint(
1845  const std::vector<std::pair<RowIndex, IntegerValue>>& integer_multipliers,
1846  ScatteredIntegerVector* scattered_vector, IntegerValue* upper_bound) const {
1847  // Initialize the new constraint.
1848  *upper_bound = 0;
1849  scattered_vector->ClearAndResize(integer_variables_.size());
1850 
1851  // Compute the new constraint by taking the linear combination given by
1852  // integer_multipliers of the integer constraints in integer_lp_.
1853  for (const std::pair<RowIndex, IntegerValue> term : integer_multipliers) {
1854  const RowIndex row = term.first;
1855  const IntegerValue multiplier = term.second;
1856  CHECK_LT(row, integer_lp_.size());
1857 
1858  // Update the constraint.
1859  if (!scattered_vector->AddLinearExpressionMultiple(
1860  multiplier, integer_lp_[row].terms)) {
1861  return false;
1862  }
1863 
1864  // Update the upper bound.
1865  const IntegerValue bound =
1866  multiplier > 0 ? integer_lp_[row].ub : integer_lp_[row].lb;
1867  if (!AddProductTo(multiplier, bound, upper_bound)) return false;
1868  }
1869 
1870  return true;
1871 }
1872 
1873 // TODO(user): no need to update the multipliers.
1874 void LinearProgrammingConstraint::AdjustNewLinearConstraint(
1875  std::vector<std::pair<glop::RowIndex, IntegerValue>>* integer_multipliers,
1876  ScatteredIntegerVector* scattered_vector, IntegerValue* upper_bound) const {
1877  const IntegerValue kMaxWantedCoeff(1e18);
1878  for (std::pair<RowIndex, IntegerValue>& term : *integer_multipliers) {
1879  const RowIndex row = term.first;
1880  const IntegerValue multiplier = term.second;
1881  if (multiplier == 0) continue;
1882 
1883  // We will only allow change of the form "multiplier += to_add" with to_add
1884  // in [-negative_limit, positive_limit].
1885  IntegerValue negative_limit = kMaxWantedCoeff;
1886  IntegerValue positive_limit = kMaxWantedCoeff;
1887 
1888  // Make sure we never change the sign of the multiplier, except if the
1889  // row is an equality in which case we don't care.
1890  if (integer_lp_[row].ub != integer_lp_[row].lb) {
1891  if (multiplier > 0) {
1892  negative_limit = std::min(negative_limit, multiplier);
1893  } else {
1894  positive_limit = std::min(positive_limit, -multiplier);
1895  }
1896  }
1897 
1898  // Make sure upper_bound + to_add * row_bound never overflow.
1899  const IntegerValue row_bound =
1900  multiplier > 0 ? integer_lp_[row].ub : integer_lp_[row].lb;
1901  if (row_bound != 0) {
1902  const IntegerValue limit1 = FloorRatio(
1903  std::max(IntegerValue(0), kMaxWantedCoeff - IntTypeAbs(*upper_bound)),
1904  IntTypeAbs(row_bound));
1905  const IntegerValue limit2 =
1906  FloorRatio(kMaxWantedCoeff, IntTypeAbs(row_bound));
1907  if ((*upper_bound > 0) == (row_bound > 0)) { // Same sign.
1908  positive_limit = std::min(positive_limit, limit1);
1909  negative_limit = std::min(negative_limit, limit2);
1910  } else {
1911  negative_limit = std::min(negative_limit, limit1);
1912  positive_limit = std::min(positive_limit, limit2);
1913  }
1914  }
1915 
1916  // If we add the row to the scattered_vector, diff will indicate by how much
1917  // |upper_bound - ImpliedLB(scattered_vector)| will change. That correspond
1918  // to increasing the multiplier by 1.
1919  //
1920  // At this stage, we are not sure computing sum coeff * bound will not
1921  // overflow, so we use floating point numbers. It is fine to do so since
1922  // this is not directly involved in the actual exact constraint generation:
1923  // these variables are just used in an heuristic.
1924  double positive_diff = ToDouble(row_bound);
1925  double negative_diff = ToDouble(row_bound);
1926 
1927  // TODO(user): we could relax a bit some of the condition and allow a sign
1928  // change. It is just trickier to compute the diff when we allow such
1929  // changes.
1930  for (const auto entry : integer_lp_[row].terms) {
1931  const ColIndex col = entry.first;
1932  const IntegerValue coeff = entry.second;
1933  const IntegerValue abs_coef = IntTypeAbs(coeff);
1934  CHECK_NE(coeff, 0);
1935 
1936  const IntegerVariable var = integer_variables_[col.value()];
1937  const IntegerValue lb = integer_trail_->LowerBound(var);
1938  const IntegerValue ub = integer_trail_->UpperBound(var);
1939 
1940  // Moving a variable away from zero seems to improve the bound even
1941  // if it reduces the number of non-zero. Note that this is because of
1942  // this that positive_diff and negative_diff are not the same.
1943  const IntegerValue current = (*scattered_vector)[col];
1944  if (current == 0) {
1945  const IntegerValue overflow_limit(
1946  FloorRatio(kMaxWantedCoeff, abs_coef));
1947  positive_limit = std::min(positive_limit, overflow_limit);
1948  negative_limit = std::min(negative_limit, overflow_limit);
1949  if (coeff > 0) {
1950  positive_diff -= ToDouble(coeff) * ToDouble(lb);
1951  negative_diff -= ToDouble(coeff) * ToDouble(ub);
1952  } else {
1953  positive_diff -= ToDouble(coeff) * ToDouble(ub);
1954  negative_diff -= ToDouble(coeff) * ToDouble(lb);
1955  }
1956  continue;
1957  }
1958 
1959  // We don't want to change the sign of current (except if the variable is
1960  // fixed) or to have an overflow.
1961  //
1962  // Corner case:
1963  // - IntTypeAbs(current) can be larger than kMaxWantedCoeff!
1964  // - The code assumes that 2 * kMaxWantedCoeff do not overflow.
1965  const IntegerValue current_magnitude = IntTypeAbs(current);
1966  const IntegerValue other_direction_limit = FloorRatio(
1967  lb == ub
1968  ? kMaxWantedCoeff + std::min(current_magnitude,
1969  kMaxIntegerValue - kMaxWantedCoeff)
1970  : current_magnitude,
1971  abs_coef);
1972  const IntegerValue same_direction_limit(FloorRatio(
1973  std::max(IntegerValue(0), kMaxWantedCoeff - current_magnitude),
1974  abs_coef));
1975  if ((current > 0) == (coeff > 0)) { // Same sign.
1976  negative_limit = std::min(negative_limit, other_direction_limit);
1977  positive_limit = std::min(positive_limit, same_direction_limit);
1978  } else {
1979  negative_limit = std::min(negative_limit, same_direction_limit);
1980  positive_limit = std::min(positive_limit, other_direction_limit);
1981  }
1982 
1983  // This is how diff change.
1984  const IntegerValue implied = current > 0 ? lb : ub;
1985  if (implied != 0) {
1986  positive_diff -= ToDouble(coeff) * ToDouble(implied);
1987  negative_diff -= ToDouble(coeff) * ToDouble(implied);
1988  }
1989  }
1990 
1991  // Only add a multiple of this row if it tighten the final constraint.
1992  // The positive_diff/negative_diff are supposed to be integer modulo the
1993  // double precision, so we only add a multiple if they seems far away from
1994  // zero.
1995  IntegerValue to_add(0);
1996  if (positive_diff <= -1.0 && positive_limit > 0) {
1997  to_add = positive_limit;
1998  }
1999  if (negative_diff >= 1.0 && negative_limit > 0) {
2000  // Pick this if it is better than the positive sign.
2001  if (to_add == 0 ||
2002  std::abs(ToDouble(negative_limit) * negative_diff) >
2003  std::abs(ToDouble(positive_limit) * positive_diff)) {
2004  to_add = -negative_limit;
2005  }
2006  }
2007  if (to_add != 0) {
2008  term.second += to_add;
2009  *upper_bound += to_add * row_bound;
2010 
2011  // TODO(user): we could avoid checking overflow here, but this is likely
2012  // not in the hot loop.
2013  CHECK(scattered_vector->AddLinearExpressionMultiple(
2014  to_add, integer_lp_[row].terms));
2015  }
2016  }
2017 }
2018 
2019 // The "exact" computation go as follow:
2020 //
2021 // Given any INTEGER linear combination of the LP constraints, we can create a
2022 // new integer constraint that is valid (its computation must not overflow
2023 // though). Lets call this "linear_combination <= ub". We can then always add to
2024 // it the inequality "objective_terms <= objective_var", so we get:
2025 // ImpliedLB(objective_terms + linear_combination) - ub <= objective_var.
2026 // where ImpliedLB() is computed from the variable current bounds.
2027 //
2028 // Now, if we use for the linear combination and approximation of the optimal
2029 // negated dual LP values (by scaling them and rounding them to integer), we
2030 // will get an EXACT objective lower bound that is more or less the same as the
2031 // inexact bound given by the LP relaxation. This allows to derive exact reasons
2032 // for any propagation done by this constraint.
2033 bool LinearProgrammingConstraint::ExactLpReasonning() {
2034  // Clear old reason and deductions.
2035  integer_reason_.clear();
2036  deductions_.clear();
2037  deductions_reason_.clear();
2038 
2039  // The row multipliers will be the negation of the LP duals.
2040  //
2041  // TODO(user): Provide and use a sparse API in Glop to get the duals.
2042  const RowIndex num_rows = simplex_.GetProblemNumRows();
2043  std::vector<std::pair<RowIndex, double>> lp_multipliers;
2044  for (RowIndex row(0); row < num_rows; ++row) {
2045  const double value = -simplex_.GetDualValue(row);
2046  if (std::abs(value) < kZeroTolerance) continue;
2047  lp_multipliers.push_back({row, value});
2048  }
2049 
2050  Fractional scaling;
2051  std::vector<std::pair<RowIndex, IntegerValue>> integer_multipliers =
2052  ScaleLpMultiplier(/*take_objective_into_account=*/true, lp_multipliers,
2053  &scaling);
2054 
2055  IntegerValue rc_ub;
2056  if (!ComputeNewLinearConstraint(integer_multipliers, &tmp_scattered_vector_,
2057  &rc_ub)) {
2058  VLOG(1) << "Issue while computing the exact LP reason. Aborting.";
2059  return true;
2060  }
2061 
2062  // The "objective constraint" behave like if the unscaled cp multiplier was
2063  // 1.0, so we will multiply it by this number and add it to reduced_costs.
2064  const IntegerValue obj_scale(std::round(scaling));
2065  if (obj_scale == 0) {
2066  VLOG(1) << "Overflow during exact LP reasoning. scaling=" << scaling;
2067  return true;
2068  }
2069  CHECK(tmp_scattered_vector_.AddLinearExpressionMultiple(obj_scale,
2070  integer_objective_));
2071  CHECK(AddProductTo(-obj_scale, integer_objective_offset_, &rc_ub));
2072  AdjustNewLinearConstraint(&integer_multipliers, &tmp_scattered_vector_,
2073  &rc_ub);
2074 
2075  // Create the IntegerSumLE that will allow to propagate the objective and more
2076  // generally do the reduced cost fixing.
2077  LinearConstraint new_constraint;
2078  tmp_scattered_vector_.ConvertToLinearConstraint(integer_variables_, rc_ub,
2079  &new_constraint);
2080  new_constraint.vars.push_back(objective_cp_);
2081  new_constraint.coeffs.push_back(-obj_scale);
2082  DivideByGCD(&new_constraint);
2083  PreventOverflow(&new_constraint);
2084  DCHECK(!PossibleOverflow(new_constraint));
2085  DCHECK(constraint_manager_.DebugCheckConstraint(new_constraint));
2086 
2087  IntegerSumLE* cp_constraint =
2088  new IntegerSumLE({}, new_constraint.vars, new_constraint.coeffs,
2089  new_constraint.ub, model_);
2090  if (trail_->CurrentDecisionLevel() == 0) {
2091  // Since we will never ask the reason for a constraint at level 0, we just
2092  // keep the last one.
2093  optimal_constraints_.clear();
2094  }
2095  optimal_constraints_.emplace_back(cp_constraint);
2096  rev_optimal_constraints_size_ = optimal_constraints_.size();
2097  if (!cp_constraint->PropagateAtLevelZero()) return false;
2098  return cp_constraint->Propagate();
2099 }
2100 
2101 bool LinearProgrammingConstraint::FillExactDualRayReason() {
2102  Fractional scaling;
2103  const glop::DenseColumn ray = simplex_.GetDualRay();
2104  std::vector<std::pair<RowIndex, double>> lp_multipliers;
2105  for (RowIndex row(0); row < ray.size(); ++row) {
2106  const double value = ray[row];
2107  if (std::abs(value) < kZeroTolerance) continue;
2108  lp_multipliers.push_back({row, value});
2109  }
2110  std::vector<std::pair<RowIndex, IntegerValue>> integer_multipliers =
2111  ScaleLpMultiplier(/*take_objective_into_account=*/false, lp_multipliers,
2112  &scaling);
2113 
2114  IntegerValue new_constraint_ub;
2115  if (!ComputeNewLinearConstraint(integer_multipliers, &tmp_scattered_vector_,
2116  &new_constraint_ub)) {
2117  VLOG(1) << "Isse while computing the exact dual ray reason. Aborting.";
2118  return false;
2119  }
2120 
2121  AdjustNewLinearConstraint(&integer_multipliers, &tmp_scattered_vector_,
2122  &new_constraint_ub);
2123 
2124  LinearConstraint new_constraint;
2125  tmp_scattered_vector_.ConvertToLinearConstraint(
2126  integer_variables_, new_constraint_ub, &new_constraint);
2127  DivideByGCD(&new_constraint);
2128  PreventOverflow(&new_constraint);
2129  DCHECK(!PossibleOverflow(new_constraint));
2130  DCHECK(constraint_manager_.DebugCheckConstraint(new_constraint));
2131 
2132  const IntegerValue implied_lb = GetImpliedLowerBound(new_constraint);
2133  if (implied_lb <= new_constraint.ub) {
2134  VLOG(1) << "LP exact dual ray not infeasible,"
2135  << " implied_lb: " << implied_lb.value() / scaling
2136  << " ub: " << new_constraint.ub.value() / scaling;
2137  return false;
2138  }
2139  const IntegerValue slack = (implied_lb - new_constraint.ub) - 1;
2140  SetImpliedLowerBoundReason(new_constraint, slack);
2141  return true;
2142 }
2143 
2144 int64_t LinearProgrammingConstraint::CalculateDegeneracy() {
2145  const glop::ColIndex num_vars = simplex_.GetProblemNumCols();
2146  int num_non_basic_with_zero_rc = 0;
2147  for (glop::ColIndex i(0); i < num_vars; ++i) {
2148  const double rc = simplex_.GetReducedCost(i);
2149  if (rc != 0.0) continue;
2150  if (simplex_.GetVariableStatus(i) == glop::VariableStatus::BASIC) {
2151  continue;
2152  }
2153  num_non_basic_with_zero_rc++;
2154  }
2155  const int64_t num_cols = simplex_.GetProblemNumCols().value();
2156  is_degenerate_ = num_non_basic_with_zero_rc >= 0.3 * num_cols;
2157  return num_non_basic_with_zero_rc;
2158 }
2159 
2160 void LinearProgrammingConstraint::ReducedCostStrengtheningDeductions(
2161  double cp_objective_delta) {
2162  deductions_.clear();
2163 
2164  // TRICKY: while simplex_.GetObjectiveValue() use the objective scaling factor
2165  // stored in the lp_data_, all the other functions like GetReducedCost() or
2166  // GetVariableValue() do not.
2167  const double lp_objective_delta =
2168  cp_objective_delta / lp_data_.objective_scaling_factor();
2169  const int num_vars = integer_variables_.size();
2170  for (int i = 0; i < num_vars; i++) {
2171  const IntegerVariable cp_var = integer_variables_[i];
2172  const glop::ColIndex lp_var = glop::ColIndex(i);
2173  const double rc = simplex_.GetReducedCost(lp_var);
2174  const double value = simplex_.GetVariableValue(lp_var);
2175 
2176  if (rc == 0.0) continue;
2177  const double lp_other_bound = value + lp_objective_delta / rc;
2178  const double cp_other_bound =
2179  scaler_.UnscaleVariableValue(lp_var, lp_other_bound);
2180 
2181  if (rc > kLpEpsilon) {
2182  const double ub = ToDouble(integer_trail_->UpperBound(cp_var));
2183  const double new_ub = std::floor(cp_other_bound + kCpEpsilon);
2184  if (new_ub < ub) {
2185  // TODO(user): Because rc > kLpEpsilon, the lower_bound of cp_var
2186  // will be part of the reason returned by FillReducedCostsReason(), but
2187  // we actually do not need it here. Same below.
2188  const IntegerValue new_ub_int(static_cast<IntegerValue>(new_ub));
2189  deductions_.push_back(IntegerLiteral::LowerOrEqual(cp_var, new_ub_int));
2190  }
2191  } else if (rc < -kLpEpsilon) {
2192  const double lb = ToDouble(integer_trail_->LowerBound(cp_var));
2193  const double new_lb = std::ceil(cp_other_bound - kCpEpsilon);
2194  if (new_lb > lb) {
2195  const IntegerValue new_lb_int(static_cast<IntegerValue>(new_lb));
2196  deductions_.push_back(
2197  IntegerLiteral::GreaterOrEqual(cp_var, new_lb_int));
2198  }
2199  }
2200  }
2201 }
2202 
2203 namespace {
2204 
2205 // Add a cut of the form Sum_{outgoing arcs from S} lp >= rhs_lower_bound.
2206 //
2207 // Note that we used to also add the same cut for the incoming arcs, but because
2208 // of flow conservation on these problems, the outgoing flow is always the same
2209 // as the incoming flow, so adding this extra cut doesn't seem relevant.
2210 void AddOutgoingCut(
2211  int num_nodes, int subset_size, const std::vector<bool>& in_subset,
2212  const std::vector<int>& tails, const std::vector<int>& heads,
2213  const std::vector<Literal>& literals,
2214  const std::vector<double>& literal_lp_values, int64_t rhs_lower_bound,
2216  LinearConstraintManager* manager, Model* model) {
2217  // A node is said to be optional if it can be excluded from the subcircuit,
2218  // in which case there is a self-loop on that node.
2219  // If there are optional nodes, use extended formula:
2220  // sum(cut) >= 1 - optional_loop_in - optional_loop_out
2221  // where optional_loop_in's node is in subset, optional_loop_out's is out.
2222  // TODO(user): Favor optional loops fixed to zero at root.
2223  int num_optional_nodes_in = 0;
2224  int num_optional_nodes_out = 0;
2225  int optional_loop_in = -1;
2226  int optional_loop_out = -1;
2227  for (int i = 0; i < tails.size(); ++i) {
2228  if (tails[i] != heads[i]) continue;
2229  if (in_subset[tails[i]]) {
2230  num_optional_nodes_in++;
2231  if (optional_loop_in == -1 ||
2232  literal_lp_values[i] < literal_lp_values[optional_loop_in]) {
2233  optional_loop_in = i;
2234  }
2235  } else {
2236  num_optional_nodes_out++;
2237  if (optional_loop_out == -1 ||
2238  literal_lp_values[i] < literal_lp_values[optional_loop_out]) {
2239  optional_loop_out = i;
2240  }
2241  }
2242  }
2243 
2244  // TODO(user): The lower bound for CVRP is computed assuming all nodes must be
2245  // served, if it is > 1 we lower it to one in the presence of optional nodes.
2246  if (num_optional_nodes_in + num_optional_nodes_out > 0) {
2247  CHECK_GE(rhs_lower_bound, 1);
2248  rhs_lower_bound = 1;
2249  }
2250 
2251  LinearConstraintBuilder outgoing(model, IntegerValue(rhs_lower_bound),
2253  double sum_outgoing = 0.0;
2254 
2255  // Add outgoing arcs, compute outgoing flow.
2256  for (int i = 0; i < tails.size(); ++i) {
2257  if (in_subset[tails[i]] && !in_subset[heads[i]]) {
2258  sum_outgoing += literal_lp_values[i];
2259  CHECK(outgoing.AddLiteralTerm(literals[i], IntegerValue(1)));
2260  }
2261  }
2262 
2263  // Support optional nodes if any.
2264  if (num_optional_nodes_in + num_optional_nodes_out > 0) {
2265  // When all optionals of one side are excluded in lp solution, no cut.
2266  if (num_optional_nodes_in == subset_size &&
2267  (optional_loop_in == -1 ||
2268  literal_lp_values[optional_loop_in] > 1.0 - 1e-6)) {
2269  return;
2270  }
2271  if (num_optional_nodes_out == num_nodes - subset_size &&
2272  (optional_loop_out == -1 ||
2273  literal_lp_values[optional_loop_out] > 1.0 - 1e-6)) {
2274  return;
2275  }
2276 
2277  // There is no mandatory node in subset, add optional_loop_in.
2278  if (num_optional_nodes_in == subset_size) {
2279  CHECK(
2280  outgoing.AddLiteralTerm(literals[optional_loop_in], IntegerValue(1)));
2281  sum_outgoing += literal_lp_values[optional_loop_in];
2282  }
2283 
2284  // There is no mandatory node out of subset, add optional_loop_out.
2285  if (num_optional_nodes_out == num_nodes - subset_size) {
2286  CHECK(outgoing.AddLiteralTerm(literals[optional_loop_out],
2287  IntegerValue(1)));
2288  sum_outgoing += literal_lp_values[optional_loop_out];
2289  }
2290  }
2291 
2292  if (sum_outgoing < rhs_lower_bound - 1e-6) {
2293  manager->AddCut(outgoing.Build(), "Circuit", lp_values);
2294  }
2295 }
2296 
2297 } // namespace
2298 
2299 // We roughly follow the algorithm described in section 6 of "The Traveling
2300 // Salesman Problem, A computational Study", David L. Applegate, Robert E.
2301 // Bixby, Vasek Chvatal, William J. Cook.
2302 //
2303 // Note that this is mainly a "symmetric" case algo, but it does still work for
2304 // the asymmetric case.
2306  int num_nodes, const std::vector<int>& tails, const std::vector<int>& heads,
2307  const std::vector<Literal>& literals,
2309  absl::Span<const int64_t> demands, int64_t capacity,
2310  LinearConstraintManager* manager, Model* model) {
2311  if (num_nodes <= 2) return;
2312 
2313  // We will collect only the arcs with a positive lp_values to speed up some
2314  // computation below.
2315  struct Arc {
2316  int tail;
2317  int head;
2318  double lp_value;
2319  };
2320  std::vector<Arc> relevant_arcs;
2321 
2322  // Sort the arcs by non-increasing lp_values.
2323  std::vector<double> literal_lp_values(literals.size());
2324  std::vector<std::pair<double, int>> arc_by_decreasing_lp_values;
2325  auto* encoder = model->GetOrCreate<IntegerEncoder>();
2326  for (int i = 0; i < literals.size(); ++i) {
2327  double lp_value;
2328  const IntegerVariable direct_view = encoder->GetLiteralView(literals[i]);
2329  if (direct_view != kNoIntegerVariable) {
2330  lp_value = lp_values[direct_view];
2331  } else {
2332  lp_value =
2333  1.0 - lp_values[encoder->GetLiteralView(literals[i].Negated())];
2334  }
2335  literal_lp_values[i] = lp_value;
2336 
2337  if (lp_value < 1e-6) continue;
2338  relevant_arcs.push_back({tails[i], heads[i], lp_value});
2339  arc_by_decreasing_lp_values.push_back({lp_value, i});
2340  }
2341  std::sort(arc_by_decreasing_lp_values.begin(),
2342  arc_by_decreasing_lp_values.end(),
2343  std::greater<std::pair<double, int>>());
2344 
2345  // We will do a union-find by adding one by one the arc of the lp solution
2346  // in the order above. Every intermediate set during this construction will
2347  // be a candidate for a cut.
2348  //
2349  // In parallel to the union-find, to efficiently reconstruct these sets (at
2350  // most num_nodes), we construct a "decomposition forest" of the different
2351  // connected components. Note that we don't exploit any asymmetric nature of
2352  // the graph here. This is exactly the algo 6.3 in the book above.
2353  int num_components = num_nodes;
2354  std::vector<int> parent(num_nodes);
2355  std::vector<int> root(num_nodes);
2356  for (int i = 0; i < num_nodes; ++i) {
2357  parent[i] = i;
2358  root[i] = i;
2359  }
2360  auto get_root_and_compress_path = [&root](int node) {
2361  int r = node;
2362  while (root[r] != r) r = root[r];
2363  while (root[node] != r) {
2364  const int next = root[node];
2365  root[node] = r;
2366  node = next;
2367  }
2368  return r;
2369  };
2370  for (const auto pair : arc_by_decreasing_lp_values) {
2371  if (num_components == 2) break;
2372  const int tail = get_root_and_compress_path(tails[pair.second]);
2373  const int head = get_root_and_compress_path(heads[pair.second]);
2374  if (tail != head) {
2375  // Update the decomposition forest, note that the number of nodes is
2376  // growing.
2377  const int new_node = parent.size();
2378  parent.push_back(new_node);
2379  parent[head] = new_node;
2380  parent[tail] = new_node;
2381  --num_components;
2382 
2383  // It is important that the union-find representative is the same node.
2384  root.push_back(new_node);
2385  root[head] = new_node;
2386  root[tail] = new_node;
2387  }
2388  }
2389 
2390  // For each node in the decomposition forest, try to add a cut for the set
2391  // formed by the nodes and its children. To do that efficiently, we first
2392  // order the nodes so that for each node in a tree, the set of children forms
2393  // a consecutive span in the pre_order vector. This vector just lists the
2394  // nodes in the "pre-order" graph traversal order. The Spans will point inside
2395  // the pre_order vector, it is why we initialize it once and for all.
2396  int new_size = 0;
2397  std::vector<int> pre_order(num_nodes);
2398  std::vector<absl::Span<const int>> subsets;
2399  {
2400  std::vector<absl::InlinedVector<int, 2>> graph(parent.size());
2401  for (int i = 0; i < parent.size(); ++i) {
2402  if (parent[i] != i) graph[parent[i]].push_back(i);
2403  }
2404  std::vector<int> queue;
2405  std::vector<bool> seen(graph.size(), false);
2406  std::vector<int> start_index(parent.size());
2407  for (int i = num_nodes; i < parent.size(); ++i) {
2408  // Note that because of the way we constructed 'parent', the graph is a
2409  // binary tree. This is not required for the correctness of the algorithm
2410  // here though.
2411  CHECK(graph[i].empty() || graph[i].size() == 2);
2412  if (parent[i] != i) continue;
2413 
2414  // Explore the subtree rooted at node i.
2415  CHECK(!seen[i]);
2416  queue.push_back(i);
2417  while (!queue.empty()) {
2418  const int node = queue.back();
2419  if (seen[node]) {
2420  queue.pop_back();
2421  // All the children of node are in the span [start, end) of the
2422  // pre_order vector.
2423  const int start = start_index[node];
2424  if (new_size - start > 1) {
2425  subsets.emplace_back(&pre_order[start], new_size - start);
2426  }
2427  continue;
2428  }
2429  seen[node] = true;
2430  start_index[node] = new_size;
2431  if (node < num_nodes) pre_order[new_size++] = node;
2432  for (const int child : graph[node]) {
2433  if (!seen[child]) queue.push_back(child);
2434  }
2435  }
2436  }
2437  }
2438 
2439  // Compute the total demands in order to know the minimum incoming/outgoing
2440  // flow.
2441  int64_t total_demands = 0;
2442  if (!demands.empty()) {
2443  for (const int64_t demand : demands) total_demands += demand;
2444  }
2445 
2446  // Process each subsets and add any violated cut.
2447  CHECK_EQ(pre_order.size(), num_nodes);
2448  std::vector<bool> in_subset(num_nodes, false);
2449  for (const absl::Span<const int> subset : subsets) {
2450  CHECK_GT(subset.size(), 1);
2451  CHECK_LT(subset.size(), num_nodes);
2452 
2453  // These fields will be left untouched if demands.empty().
2454  bool contain_depot = false;
2455  int64_t subset_demand = 0;
2456 
2457  // Initialize "in_subset" and the subset demands.
2458  for (const int n : subset) {
2459  in_subset[n] = true;
2460  if (!demands.empty()) {
2461  if (n == 0) contain_depot = true;
2462  subset_demand += demands[n];
2463  }
2464  }
2465 
2466  // Compute a lower bound on the outgoing flow.
2467  //
2468  // TODO(user): This lower bound assume all nodes in subset must be served,
2469  // which is not the case. For TSP we do the correct thing in
2470  // AddOutgoingCut() but not for CVRP... Fix!!
2471  //
2472  // TODO(user): It could be very interesting to see if this "min outgoing
2473  // flow" cannot be automatically infered from the constraint in the
2474  // precedence graph. This might work if we assume that any kind of path
2475  // cumul constraint is encoded with constraints:
2476  // [edge => value_head >= value_tail + edge_weight].
2477  // We could take the minimum incoming edge weight per node in the set, and
2478  // use the cumul variable domain to infer some capacity.
2479  int64_t min_outgoing_flow = 1;
2480  if (!demands.empty()) {
2481  min_outgoing_flow =
2482  contain_depot
2483  ? (total_demands - subset_demand + capacity - 1) / capacity
2484  : (subset_demand + capacity - 1) / capacity;
2485  }
2486 
2487  // We still need to serve nodes with a demand of zero, and in the corner
2488  // case where all node in subset have a zero demand, the formula above
2489  // result in a min_outgoing_flow of zero.
2490  min_outgoing_flow = std::max(min_outgoing_flow, int64_t{1});
2491 
2492  // Compute the current outgoing flow out of the subset.
2493  //
2494  // This can take a significant portion of the running time, it is why it is
2495  // faster to do it only on arcs with non-zero lp values which should be in
2496  // linear number rather than the total number of arc which can be quadratic.
2497  //
2498  // TODO(user): For the symmetric case there is an even faster algo. See if
2499  // it can be generalized to the asymmetric one if become needed.
2500  // Reference is algo 6.4 of the "The Traveling Salesman Problem" book
2501  // mentionned above.
2502  double outgoing_flow = 0.0;
2503  for (const auto arc : relevant_arcs) {
2504  if (in_subset[arc.tail] && !in_subset[arc.head]) {
2505  outgoing_flow += arc.lp_value;
2506  }
2507  }
2508 
2509  // Add a cut if the current outgoing flow is not enough.
2510  if (outgoing_flow < min_outgoing_flow - 1e-6) {
2511  AddOutgoingCut(num_nodes, subset.size(), in_subset, tails, heads,
2512  literals, literal_lp_values,
2513  /*rhs_lower_bound=*/min_outgoing_flow, lp_values, manager,
2514  model);
2515  }
2516 
2517  // Sparse clean up.
2518  for (const int n : subset) in_subset[n] = false;
2519  }
2520 }
2521 
2522 namespace {
2523 
2524 // Returns for each literal its integer view, or the view of its negation.
2525 std::vector<IntegerVariable> GetAssociatedVariables(
2526  const std::vector<Literal>& literals, Model* model) {
2527  auto* encoder = model->GetOrCreate<IntegerEncoder>();
2528  std::vector<IntegerVariable> result;
2529  for (const Literal l : literals) {
2530  const IntegerVariable direct_view = encoder->GetLiteralView(l);
2531  if (direct_view != kNoIntegerVariable) {
2532  result.push_back(direct_view);
2533  } else {
2534  result.push_back(encoder->GetLiteralView(l.Negated()));
2535  DCHECK_NE(result.back(), kNoIntegerVariable);
2536  }
2537  }
2538  return result;
2539 }
2540 
2541 } // namespace
2542 
2543 // We use a basic algorithm to detect components that are not connected to the
2544 // rest of the graph in the LP solution, and add cuts to force some arcs to
2545 // enter and leave this component from outside.
2547  int num_nodes, const std::vector<int>& tails, const std::vector<int>& heads,
2548  const std::vector<Literal>& literals, Model* model) {
2549  CutGenerator result;
2550  result.vars = GetAssociatedVariables(literals, model);
2551  result.generate_cuts =
2552  [num_nodes, tails, heads, literals, model](
2554  LinearConstraintManager* manager) {
2556  num_nodes, tails, heads, literals, lp_values,
2557  /*demands=*/{}, /*capacity=*/0, manager, model);
2558  };
2559  return result;
2560 }
2561 
2563  const std::vector<int>& tails,
2564  const std::vector<int>& heads,
2565  const std::vector<Literal>& literals,
2566  const std::vector<int64_t>& demands,
2567  int64_t capacity, Model* model) {
2568  CutGenerator result;
2569  result.vars = GetAssociatedVariables(literals, model);
2570  result.generate_cuts =
2571  [num_nodes, tails, heads, demands, capacity, literals, model](
2573  LinearConstraintManager* manager) {
2574  SeparateSubtourInequalities(num_nodes, tails, heads, literals,
2575  lp_values, demands, capacity, manager,
2576  model);
2577  };
2578  return result;
2579 }
2580 
2581 std::function<IntegerLiteral()>
2583  // Gather all 0-1 variables that appear in this LP.
2584  std::vector<IntegerVariable> variables;
2585  for (IntegerVariable var : integer_variables_) {
2586  if (integer_trail_->LowerBound(var) == 0 &&
2587  integer_trail_->UpperBound(var) == 1) {
2588  variables.push_back(var);
2589  }
2590  }
2591  VLOG(1) << "HeuristicLPMostInfeasibleBinary has " << variables.size()
2592  << " variables.";
2593 
2594  return [this, variables]() {
2595  const double kEpsilon = 1e-6;
2596  // Find most fractional value.
2597  IntegerVariable fractional_var = kNoIntegerVariable;
2598  double fractional_distance_best = -1.0;
2599  for (const IntegerVariable var : variables) {
2600  // Skip ignored and fixed variables.
2601  if (integer_trail_->IsCurrentlyIgnored(var)) continue;
2602  const IntegerValue lb = integer_trail_->LowerBound(var);
2603  const IntegerValue ub = integer_trail_->UpperBound(var);
2604  if (lb == ub) continue;
2605 
2606  // Check variable's support is fractional.
2607  const double lp_value = this->GetSolutionValue(var);
2608  const double fractional_distance =
2609  std::min(std::ceil(lp_value - kEpsilon) - lp_value,
2610  lp_value - std::floor(lp_value + kEpsilon));
2611  if (fractional_distance < kEpsilon) continue;
2612 
2613  // Keep variable if it is farther from integrality than the previous.
2614  if (fractional_distance > fractional_distance_best) {
2615  fractional_var = var;
2616  fractional_distance_best = fractional_distance;
2617  }
2618  }
2619 
2620  if (fractional_var != kNoIntegerVariable) {
2621  IntegerLiteral::GreaterOrEqual(fractional_var, IntegerValue(1));
2622  }
2623  return IntegerLiteral();
2624  };
2625 }
2626 
2627 std::function<IntegerLiteral()>
2629  // Gather all 0-1 variables that appear in this LP.
2630  std::vector<IntegerVariable> variables;
2631  for (IntegerVariable var : integer_variables_) {
2632  if (integer_trail_->LowerBound(var) == 0 &&
2633  integer_trail_->UpperBound(var) == 1) {
2634  variables.push_back(var);
2635  }
2636  }
2637  VLOG(1) << "HeuristicLpReducedCostBinary has " << variables.size()
2638  << " variables.";
2639 
2640  // Store average of reduced cost from 1 to 0. The best heuristic only sets
2641  // variables to one and cares about cost to zero, even though classic
2642  // pseudocost will use max_var min(cost_to_one[var], cost_to_zero[var]).
2643  const int num_vars = variables.size();
2644  std::vector<double> cost_to_zero(num_vars, 0.0);
2645  std::vector<int> num_cost_to_zero(num_vars);
2646  int num_calls = 0;
2647 
2648  return [=]() mutable {
2649  const double kEpsilon = 1e-6;
2650 
2651  // Every 10000 calls, decay pseudocosts.
2652  num_calls++;
2653  if (num_calls == 10000) {
2654  for (int i = 0; i < num_vars; i++) {
2655  cost_to_zero[i] /= 2;
2656  num_cost_to_zero[i] /= 2;
2657  }
2658  num_calls = 0;
2659  }
2660 
2661  // Accumulate pseudo-costs of all unassigned variables.
2662  for (int i = 0; i < num_vars; i++) {
2663  const IntegerVariable var = variables[i];
2664  // Skip ignored and fixed variables.
2665  if (integer_trail_->IsCurrentlyIgnored(var)) continue;
2666  const IntegerValue lb = integer_trail_->LowerBound(var);
2667  const IntegerValue ub = integer_trail_->UpperBound(var);
2668  if (lb == ub) continue;
2669 
2670  const double rc = this->GetSolutionReducedCost(var);
2671  // Skip reduced costs that are nonzero because of numerical issues.
2672  if (std::abs(rc) < kEpsilon) continue;
2673 
2674  const double value = std::round(this->GetSolutionValue(var));
2675  if (value == 1.0 && rc < 0.0) {
2676  cost_to_zero[i] -= rc;
2677  num_cost_to_zero[i]++;
2678  }
2679  }
2680 
2681  // Select noninstantiated variable with highest pseudo-cost.
2682  int selected_index = -1;
2683  double best_cost = 0.0;
2684  for (int i = 0; i < num_vars; i++) {
2685  const IntegerVariable var = variables[i];
2686  // Skip ignored and fixed variables.
2687  if (integer_trail_->IsCurrentlyIgnored(var)) continue;
2688  if (integer_trail_->IsFixed(var)) continue;
2689 
2690  if (num_cost_to_zero[i] > 0 &&
2691  best_cost < cost_to_zero[i] / num_cost_to_zero[i]) {
2692  best_cost = cost_to_zero[i] / num_cost_to_zero[i];
2693  selected_index = i;
2694  }
2695  }
2696 
2697  if (selected_index >= 0) {
2698  return IntegerLiteral::GreaterOrEqual(variables[selected_index],
2699  IntegerValue(1));
2700  }
2701  return IntegerLiteral();
2702  };
2703 }
2704 
2705 void LinearProgrammingConstraint::UpdateAverageReducedCosts() {
2706  const int num_vars = integer_variables_.size();
2707  if (sum_cost_down_.size() < num_vars) {
2708  sum_cost_down_.resize(num_vars, 0.0);
2709  num_cost_down_.resize(num_vars, 0);
2710  sum_cost_up_.resize(num_vars, 0.0);
2711  num_cost_up_.resize(num_vars, 0);
2712  rc_scores_.resize(num_vars, 0.0);
2713  }
2714 
2715  // Decay averages.
2716  num_calls_since_reduced_cost_averages_reset_++;
2717  if (num_calls_since_reduced_cost_averages_reset_ == 10000) {
2718  for (int i = 0; i < num_vars; i++) {
2719  sum_cost_up_[i] /= 2;
2720  num_cost_up_[i] /= 2;
2721  sum_cost_down_[i] /= 2;
2722  num_cost_down_[i] /= 2;
2723  }
2724  num_calls_since_reduced_cost_averages_reset_ = 0;
2725  }
2726 
2727  // Accumulate reduced costs of all unassigned variables.
2728  for (int i = 0; i < num_vars; i++) {
2729  const IntegerVariable var = integer_variables_[i];
2730 
2731  // Skip ignored and fixed variables.
2732  if (integer_trail_->IsCurrentlyIgnored(var)) continue;
2733  if (integer_trail_->IsFixed(var)) continue;
2734 
2735  // Skip reduced costs that are zero or close.
2736  const double rc = lp_reduced_cost_[i];
2737  if (std::abs(rc) < kCpEpsilon) continue;
2738 
2739  if (rc < 0.0) {
2740  sum_cost_down_[i] -= rc;
2741  num_cost_down_[i]++;
2742  } else {
2743  sum_cost_up_[i] += rc;
2744  num_cost_up_[i]++;
2745  }
2746  }
2747 
2748  // Tricky, we artificially reset the rc_rev_int_repository_ to level zero
2749  // so that the rev_rc_start_ is zero.
2750  rc_rev_int_repository_.SetLevel(0);
2751  rc_rev_int_repository_.SetLevel(trail_->CurrentDecisionLevel());
2752  rev_rc_start_ = 0;
2753 
2754  // Cache the new score (higher is better) using the average reduced costs
2755  // as a signal.
2756  positions_by_decreasing_rc_score_.clear();
2757  for (int i = 0; i < num_vars; i++) {
2758  // If only one direction exist, we takes its value divided by 2, so that
2759  // such variable should have a smaller cost than the min of the two side
2760  // except if one direction have a really high reduced costs.
2761  const double a_up =
2762  num_cost_up_[i] > 0 ? sum_cost_up_[i] / num_cost_up_[i] : 0.0;
2763  const double a_down =
2764  num_cost_down_[i] > 0 ? sum_cost_down_[i] / num_cost_down_[i] : 0.0;
2765  if (num_cost_down_[i] > 0 && num_cost_up_[i] > 0) {
2766  rc_scores_[i] = std::min(a_up, a_down);
2767  } else {
2768  rc_scores_[i] = 0.5 * (a_down + a_up);
2769  }
2770 
2771  // We ignore scores of zero (i.e. no data) and will follow the default
2772  // search heuristic if all variables are like this.
2773  if (rc_scores_[i] > 0.0) {
2774  positions_by_decreasing_rc_score_.push_back({-rc_scores_[i], i});
2775  }
2776  }
2777  std::sort(positions_by_decreasing_rc_score_.begin(),
2778  positions_by_decreasing_rc_score_.end());
2779 }
2780 
2781 // TODO(user): Remove duplication with HeuristicLpReducedCostBinary().
2782 std::function<IntegerLiteral()>
2784  return [this]() { return this->LPReducedCostAverageDecision(); };
2785 }
2786 
2787 IntegerLiteral LinearProgrammingConstraint::LPReducedCostAverageDecision() {
2788  // Select noninstantiated variable with highest positive average reduced cost.
2789  int selected_index = -1;
2790  const int size = positions_by_decreasing_rc_score_.size();
2791  rc_rev_int_repository_.SaveState(&rev_rc_start_);
2792  for (int i = rev_rc_start_; i < size; ++i) {
2793  const int index = positions_by_decreasing_rc_score_[i].second;
2794  const IntegerVariable var = integer_variables_[index];
2795  if (integer_trail_->IsCurrentlyIgnored(var)) continue;
2796  if (integer_trail_->IsFixed(var)) continue;
2797  selected_index = index;
2798  rev_rc_start_ = i;
2799  break;
2800  }
2801 
2802  if (selected_index == -1) return IntegerLiteral();
2803  const IntegerVariable var = integer_variables_[selected_index];
2804 
2805  // If ceil(value) is current upper bound, try var == upper bound first.
2806  // Guarding with >= prevents numerical problems.
2807  // With 0/1 variables, this will tend to try setting to 1 first,
2808  // which produces more shallow trees.
2809  const IntegerValue ub = integer_trail_->UpperBound(var);
2810  const IntegerValue value_ceil(
2811  std::ceil(this->GetSolutionValue(var) - kCpEpsilon));
2812  if (value_ceil >= ub) {
2813  return IntegerLiteral::GreaterOrEqual(var, ub);
2814  }
2815 
2816  // If floor(value) is current lower bound, try var == lower bound first.
2817  // Guarding with <= prevents numerical problems.
2818  const IntegerValue lb = integer_trail_->LowerBound(var);
2819  const IntegerValue value_floor(
2820  std::floor(this->GetSolutionValue(var) + kCpEpsilon));
2821  if (value_floor <= lb) {
2822  return IntegerLiteral::LowerOrEqual(var, lb);
2823  }
2824 
2825  // Here lb < value_floor <= value_ceil < ub.
2826  // Try the most promising split between var <= floor or var >= ceil.
2827  const double a_up =
2828  num_cost_up_[selected_index] > 0
2829  ? sum_cost_up_[selected_index] / num_cost_up_[selected_index]
2830  : 0.0;
2831  const double a_down =
2832  num_cost_down_[selected_index] > 0
2833  ? sum_cost_down_[selected_index] / num_cost_down_[selected_index]
2834  : 0.0;
2835  if (a_down < a_up) {
2836  return IntegerLiteral::LowerOrEqual(var, value_floor);
2837  } else {
2838  return IntegerLiteral::GreaterOrEqual(var, value_ceil);
2839  }
2840 }
2841 
2842 } // namespace sat
2843 } // namespace operations_research
int64_t max
Definition: alldiff_cst.cc:140
int64_t min
Definition: alldiff_cst.cc:139
#define CHECK(condition)
Definition: base/logging.h:498
#define DCHECK_NE(val1, val2)
Definition: base/logging.h:894
#define CHECK_LT(val1, val2)
Definition: base/logging.h:708
#define CHECK_EQ(val1, val2)
Definition: base/logging.h:705
#define CHECK_GE(val1, val2)
Definition: base/logging.h:709
#define CHECK_GT(val1, val2)
Definition: base/logging.h:710
#define CHECK_NE(val1, val2)
Definition: base/logging.h:706
#define DCHECK_GT(val1, val2)
Definition: base/logging.h:898
#define DCHECK(condition)
Definition: base/logging.h:892
#define VLOG(verboselevel)
Definition: base/logging.h:986
void assign(size_type n, const value_type &val)
void resize(size_type new_size)
size_type size() const
void push_back(const value_type &x)
static int64_t GCD64(int64_t x, int64_t y)
Definition: mathutil.h:107
void SetLevel(int level) final
Definition: rev.h:134
void SaveState(T *object)
Definition: rev.h:61
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
Definition: time_limit.h:105
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
Definition: time_limit.h:532
void SetVariableBounds(ColIndex col, Fractional lower_bound, Fractional upper_bound)
Definition: lp_data.cc:249
void SetObjectiveOffset(Fractional objective_offset)
Definition: lp_data.cc:331
void SetCoefficient(RowIndex row, ColIndex col, Fractional value)
Definition: lp_data.cc:317
void SetConstraintBounds(RowIndex row, Fractional lower_bound, Fractional upper_bound)
Definition: lp_data.cc:309
void AddSlackVariablesWhereNecessary(bool detect_integer_constraints)
Definition: lp_data.cc:697
void SetObjectiveCoefficient(ColIndex col, Fractional value)
Definition: lp_data.cc:326
std::string GetDimensionString() const
Definition: lp_data.cc:425
Fractional objective_scaling_factor() const
Definition: lp_data.h:261
const SparseColumn & GetSparseColumn(ColIndex col) const
Definition: lp_data.cc:409
Fractional VariableScalingFactor(ColIndex col) const
Fractional UnscaleVariableValue(ColIndex col, Fractional value) const
Fractional UnscaleReducedCost(ColIndex col, Fractional value) const
Fractional UnscaleDualValue(RowIndex row, Fractional value) const
const GlopParameters & GetParameters() const
const DenseRow & GetDualRayRowCombination() const
Fractional GetVariableValue(ColIndex col) const
void SetIntegralityScale(ColIndex col, Fractional scale)
VariableStatus GetVariableStatus(ColIndex col) const
Fractional GetReducedCost(ColIndex col) const
const DenseColumn & GetDualRay() const
ABSL_MUST_USE_RESULT Status Solve(const LinearProgram &lp, TimeLimit *time_limit)
Fractional GetDualValue(RowIndex row) const
ConstraintStatus GetConstraintStatus(RowIndex row) const
void LoadStateForNextSolve(const BasisState &state)
ColIndex GetBasis(RowIndex row) const
void SetParameters(const GlopParameters &parameters)
const ScatteredRow & GetUnitRowLeftInverse(RowIndex row)
LinearConstraint * mutable_cut()
Definition: cuts.h:251
bool TrySimpleKnapsack(const LinearConstraint base_ct, const std::vector< double > &lp_values, const std::vector< IntegerValue > &lower_bounds, const std::vector< IntegerValue > &upper_bounds)
Definition: cuts.cc:1159
void WatchIntegerVariable(IntegerVariable i, int id, int watch_index=-1)
Definition: integer.h:1402
void WatchUpperBound(IntegerVariable var, int id, int watch_index=-1)
Definition: integer.h:1396
void SetPropagatorPriority(int id, int priority)
Definition: integer.cc:1968
int Register(PropagatorInterface *propagator)
Definition: integer.cc:1945
void AddLpVariable(IntegerVariable var)
Definition: cuts.h:108
void ProcessUpperBoundedConstraintWithSlackCreation(bool substitute_only_inner_variables, IntegerVariable first_slack, const absl::StrongVector< IntegerVariable, double > &lp_values, LinearConstraint *cut, std::vector< SlackInfo > *slack_infos)
Definition: cuts.cc:1588
bool DebugSlack(IntegerVariable first_slack, const LinearConstraint &initial_cut, const LinearConstraint &cut, const std::vector< SlackInfo > &info)
Definition: cuts.cc:1729
void SeparateSomeImpliedBoundCuts(const absl::StrongVector< IntegerVariable, double > &lp_values)
Definition: cuts.cc:1579
const IntegerVariable GetLiteralView(Literal lit) const
Definition: integer.h:425
void ComputeCut(RoundingOptions options, const std::vector< double > &lp_values, const std::vector< IntegerValue > &lower_bounds, const std::vector< IntegerValue > &upper_bounds, ImpliedBoundsProcessor *ib_processor, LinearConstraint *cut)
Definition: cuts.cc:710
ABSL_MUST_USE_RESULT bool Enqueue(IntegerLiteral i_lit, absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.cc:993
bool IsCurrentlyIgnored(IntegerVariable i) const
Definition: integer.h:630
bool IsFixed(IntegerVariable i) const
Definition: integer.h:1313
IntegerLiteral LowerBoundAsLiteral(IntegerVariable i) const
Definition: integer.h:1335
bool ReportConflict(absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.h:815
IntegerValue UpperBound(IntegerVariable i) const
Definition: integer.h:1309
IntegerValue LevelZeroUpperBound(IntegerVariable var) const
Definition: integer.h:1360
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
Definition: integer.h:1355
void RelaxLinearReason(IntegerValue slack, absl::Span< const IntegerValue > coeffs, std::vector< IntegerLiteral > *reason) const
Definition: integer.cc:789
IntegerValue LowerBound(IntegerVariable i) const
Definition: integer.h:1305
IntegerLiteral UpperBoundAsLiteral(IntegerVariable i) const
Definition: integer.h:1340
bool IsFixedAtLevelZero(IntegerVariable var) const
Definition: integer.h:1365
void RemoveLevelZeroBounds(std::vector< IntegerLiteral > *reason) const
Definition: integer.cc:923
void RegisterReversibleClass(ReversibleInterface *rev)
Definition: integer.h:838
bool ChangeLp(const absl::StrongVector< IntegerVariable, double > &lp_solution, glop::BasisState *solution_state)
void SetObjectiveCoefficient(IntegerVariable var, IntegerValue coeff)
ConstraintIndex Add(LinearConstraint ct, bool *added=nullptr)
const absl::StrongVector< ConstraintIndex, ConstraintInfo > & AllConstraints() const
const std::vector< ConstraintIndex > & LpConstraints() const
bool AddCut(LinearConstraint ct, std::string type_name, const absl::StrongVector< IntegerVariable, double > &lp_solution, std::string extra_info="")
std::function< IntegerLiteral()> HeuristicLpReducedCostBinary(Model *model)
bool IncrementalPropagate(const std::vector< int > &watch_indices) override
std::function< IntegerLiteral()> HeuristicLpMostInfeasibleBinary(Model *model)
void SetObjectiveCoefficient(IntegerVariable ivar, IntegerValue coeff)
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
void ConvertToLinearConstraint(const std::vector< IntegerVariable > &integer_variables, IntegerValue upper_bound, LinearConstraint *result)
bool Add(glop::ColIndex col, IntegerValue value)
std::vector< std::pair< glop::ColIndex, IntegerValue > > GetTerms()
bool AddLinearExpressionMultiple(IntegerValue multiplier, const std::vector< std::pair< glop::ColIndex, IntegerValue >> &terms)
void TransferToManager(const absl::StrongVector< IntegerVariable, double > &lp_solution, LinearConstraintManager *manager)
void ProcessVariables(const std::vector< double > &lp_values, const std::vector< IntegerValue > &lower_bounds, const std::vector< IntegerValue > &upper_bounds)
std::vector< std::vector< std::pair< glop::RowIndex, IntegerValue > > > InterestingCandidates(ModelRandomGenerator *random)
void AddOneConstraint(glop::RowIndex, const std::vector< std::pair< glop::ColIndex, IntegerValue >> &terms, IntegerValue lb, IntegerValue ub)
int64_t b
int64_t a
Block * next
SatParameters parameters
const std::string name
const Constraint * ct
int64_t value
IntVar * var
Definition: expr_array.cc:1874
double upper_bound
double lower_bound
GRBmodel * model
const bool DEBUG_MODE
Definition: macros.h:24
ColIndex col
Definition: markowitz.cc:183
RowIndex row
Definition: markowitz.cc:182
const Collection::value_type::second_type & FindOrDie(const Collection &collection, const typename Collection::value_type::first_type &key)
Definition: map_util.h:206
StrictITIVector< ColIndex, Fractional > DenseRow
Definition: lp_types.h:300
ColIndex RowToColIndex(RowIndex row)
Definition: lp_types.h:49
RowIndex ColToRowIndex(ColIndex col)
Definition: lp_types.h:52
const double kEpsilon
Definition: lp_types.h:87
StrictITIVector< RowIndex, Fractional > DenseColumn
Definition: lp_types.h:329
IntegerValue FloorRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition: integer.h:91
CutGenerator CreateCVRPCutGenerator(int num_nodes, const std::vector< int > &tails, const std::vector< int > &heads, const std::vector< Literal > &literals, const std::vector< int64_t > &demands, int64_t capacity, Model *model)
bool AddProductTo(IntegerValue a, IntegerValue b, IntegerValue *result)
Definition: integer.h:111
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
IntType IntTypeAbs(IntType t)
Definition: integer.h:78
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
const IntegerVariable kNoIntegerVariable(-1)
IntegerVariable PositiveVariable(IntegerVariable i)
Definition: integer.h:139
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Definition: integer.cc:29
IntegerValue ComputeInfinityNorm(const LinearConstraint &constraint)
void SeparateSubtourInequalities(int num_nodes, const std::vector< int > &tails, const std::vector< int > &heads, const std::vector< Literal > &literals, const absl::StrongVector< IntegerVariable, double > &lp_values, absl::Span< const int64_t > demands, int64_t capacity, LinearConstraintManager *manager, Model *model)
bool VariableIsPositive(IntegerVariable i)
Definition: integer.h:135
void DivideByGCD(LinearConstraint *constraint)
CutGenerator CreateStronglyConnectedGraphCutGenerator(int num_nodes, const std::vector< int > &tails, const std::vector< int > &heads, const std::vector< Literal > &literals, Model *model)
double ComputeActivity(const LinearConstraint &constraint, const absl::StrongVector< IntegerVariable, double > &values)
double ToDouble(IntegerValue value)
Definition: integer.h:70
Collection of objects used to extend the Constraint Solver library.
int64_t CapAdd(int64_t x, int64_t y)
int64_t CapSub(int64_t x, int64_t y)
std::pair< int64_t, int64_t > Arc
Definition: search.cc:3383
int64_t CapProd(int64_t x, int64_t y)
int index
Definition: pack.cc:509
int64_t demand
Definition: resource.cc:125
int64_t bound
int64_t capacity
int64_t tail
int64_t head
std::vector< IntegerVariable > vars
Definition: cuts.h:42
std::function< void(const absl::StrongVector< IntegerVariable, double > &lp_values, LinearConstraintManager *manager)> generate_cuts
Definition: cuts.h:46
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1275
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1269