OR-Tools  8.0
linear_constraint_manager.cc
Go to the documentation of this file.
1 // Copyright 2010-2018 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
15 
16 #include <algorithm>
17 #include <cmath>
18 #include <limits>
19 #include <utility>
20 
21 #include "absl/container/flat_hash_set.h"
22 #include "ortools/sat/integer.h"
24 
25 namespace operations_research {
26 namespace sat {
27 
28 namespace {
29 
30 const LinearConstraintManager::ConstraintIndex kInvalidConstraintIndex(-1);
31 
32 size_t ComputeHashOfTerms(const LinearConstraint& ct) {
33  DCHECK(std::is_sorted(ct.vars.begin(), ct.vars.end()));
34  size_t hash = 0;
35  const int num_terms = ct.vars.size();
36  for (int i = 0; i < num_terms; ++i) {
37  hash = util_hash::Hash(ct.vars[i].value(), hash);
38  hash = util_hash::Hash(ct.coeffs[i].value(), hash);
39  }
40  return hash;
41 }
42 
43 } // namespace
44 
46  if (num_merged_constraints_ > 0) {
47  VLOG(2) << "num_merged_constraints: " << num_merged_constraints_;
48  }
49  if (num_shortened_constraints_ > 0) {
50  VLOG(2) << "num_shortened_constraints: " << num_shortened_constraints_;
51  }
52  if (num_splitted_constraints_ > 0) {
53  VLOG(2) << "num_splitted_constraints: " << num_splitted_constraints_;
54  }
55  if (num_coeff_strenghtening_ > 0) {
56  VLOG(2) << "num_coeff_strenghtening: " << num_coeff_strenghtening_;
57  }
58  if (sat_parameters_.log_search_progress() && num_cuts_ > 0) {
59  LOG(INFO) << "Total cuts added: " << num_cuts_ << " (out of "
60  << num_add_cut_calls_ << " calls) worker: '" << model_->Name()
61  << "'";
62  LOG(INFO) << "Num simplifications: " << num_simplifications_;
63  for (const auto& entry : type_to_num_cuts_) {
64  LOG(INFO) << "Added " << entry.second << " cuts of type '" << entry.first
65  << "'.";
66  }
67  }
68 }
69 
70 void LinearConstraintManager::RescaleActiveCounts(const double scaling_factor) {
71  for (ConstraintIndex i(0); i < constraint_infos_.size(); ++i) {
72  constraint_infos_[i].active_count *= scaling_factor;
73  }
74  constraint_active_count_increase_ *= scaling_factor;
75  VLOG(2) << "Rescaled active counts by " << scaling_factor;
76 }
77 
78 bool LinearConstraintManager::MaybeRemoveSomeInactiveConstraints(
79  glop::BasisState* solution_state) {
80  if (solution_state->IsEmpty()) return false; // Mainly to simplify tests.
81  const glop::RowIndex num_rows(lp_constraints_.size());
82  const glop::ColIndex num_cols =
83  solution_state->statuses.size() - RowToColIndex(num_rows);
84  int new_size = 0;
85  for (int i = 0; i < num_rows; ++i) {
86  const ConstraintIndex constraint_index = lp_constraints_[i];
87 
88  // Constraints that are not tight in the current solution have a basic
89  // status. We remove the ones that have been inactive in the last recent
90  // solves.
91  //
92  // TODO(user): More advanced heuristics might perform better, I didn't do
93  // a lot of tuning experiments yet.
94  const glop::VariableStatus row_status =
95  solution_state->statuses[num_cols + glop::ColIndex(i)];
96  if (row_status == glop::VariableStatus::BASIC) {
97  constraint_infos_[constraint_index].inactive_count++;
98  if (constraint_infos_[constraint_index].inactive_count >
99  sat_parameters_.max_consecutive_inactive_count()) {
100  constraint_infos_[constraint_index].is_in_lp = false;
101  continue; // Remove it.
102  }
103  } else {
104  // Only count consecutive inactivities.
105  constraint_infos_[constraint_index].inactive_count = 0;
106  }
107 
108  lp_constraints_[new_size] = constraint_index;
109  solution_state->statuses[num_cols + glop::ColIndex(new_size)] = row_status;
110  new_size++;
111  }
112  const int num_removed_constraints = lp_constraints_.size() - new_size;
113  lp_constraints_.resize(new_size);
114  solution_state->statuses.resize(num_cols + glop::ColIndex(new_size));
115  if (num_removed_constraints > 0) {
116  VLOG(2) << "Removed " << num_removed_constraints << " constraints";
117  }
118  return num_removed_constraints > 0;
119 }
120 
121 // Because sometimes we split a == constraint in two (>= and <=), it makes sense
122 // to detect duplicate constraints and merge bounds. This is also relevant if
123 // we regenerate identical cuts for some reason.
124 LinearConstraintManager::ConstraintIndex LinearConstraintManager::Add(
125  LinearConstraint ct, bool* added) {
126  CHECK(!ct.vars.empty());
127  DCHECK(NoDuplicateVariable(ct));
128  SimplifyConstraint(&ct);
129  DivideByGCD(&ct);
131  DCHECK(DebugCheckConstraint(ct));
132 
133  // If an identical constraint exists, only updates its bound.
134  const size_t key = ComputeHashOfTerms(ct);
135  if (gtl::ContainsKey(equiv_constraints_, key)) {
136  const ConstraintIndex ct_index = equiv_constraints_[key];
137  if (constraint_infos_[ct_index].constraint.vars == ct.vars &&
138  constraint_infos_[ct_index].constraint.coeffs == ct.coeffs) {
139  if (added != nullptr) *added = false;
140  if (ct.lb > constraint_infos_[ct_index].constraint.lb) {
141  if (constraint_infos_[ct_index].is_in_lp) current_lp_is_changed_ = true;
142  constraint_infos_[ct_index].constraint.lb = ct.lb;
143  if (added != nullptr) *added = true;
144  }
145  if (ct.ub < constraint_infos_[ct_index].constraint.ub) {
146  if (constraint_infos_[ct_index].is_in_lp) current_lp_is_changed_ = true;
147  constraint_infos_[ct_index].constraint.ub = ct.ub;
148  if (added != nullptr) *added = true;
149  }
150  ++num_merged_constraints_;
151  return ct_index;
152  }
153  }
154 
155  if (added != nullptr) *added = true;
156  const ConstraintIndex ct_index(constraint_infos_.size());
157  ConstraintInfo ct_info;
158  ct_info.constraint = std::move(ct);
159  ct_info.l2_norm = ComputeL2Norm(ct_info.constraint);
160  ct_info.hash = key;
161  equiv_constraints_[key] = ct_index;
162  ct_info.active_count = constraint_active_count_increase_;
163  constraint_infos_.push_back(std::move(ct_info));
164  return ct_index;
165 }
166 
167 void LinearConstraintManager::ComputeObjectiveParallelism(
168  const ConstraintIndex ct_index) {
169  CHECK(objective_is_defined_);
170  // lazy computation of objective norm.
171  if (!objective_norm_computed_) {
172  double sum = 0.0;
173  for (const double coeff : dense_objective_coeffs_) {
174  sum += coeff * coeff;
175  }
176  objective_l2_norm_ = std::sqrt(sum);
177  objective_norm_computed_ = true;
178  }
179  CHECK_GT(objective_l2_norm_, 0.0);
180 
181  constraint_infos_[ct_index].objective_parallelism_computed = true;
182  if (constraint_infos_[ct_index].l2_norm == 0.0) {
183  constraint_infos_[ct_index].objective_parallelism = 0.0;
184  return;
185  }
186 
187  const LinearConstraint& lc = constraint_infos_[ct_index].constraint;
188  double unscaled_objective_parallelism = 0.0;
189  for (int i = 0; i < lc.vars.size(); ++i) {
190  const IntegerVariable var = lc.vars[i];
191  DCHECK(VariableIsPositive(var));
192  if (var < dense_objective_coeffs_.size()) {
193  unscaled_objective_parallelism +=
194  ToDouble(lc.coeffs[i]) * dense_objective_coeffs_[var];
195  }
196  }
197  const double objective_parallelism =
198  unscaled_objective_parallelism /
199  (constraint_infos_[ct_index].l2_norm * objective_l2_norm_);
200  constraint_infos_[ct_index].objective_parallelism =
201  std::abs(objective_parallelism);
202 }
203 
204 // Same as Add(), but logs some information about the newly added constraint.
205 // Cuts are also handled slightly differently than normal constraints.
207  LinearConstraint ct, std::string type_name,
208  const gtl::ITIVector<IntegerVariable, double>& lp_solution,
209  std::string extra_info) {
210  ++num_add_cut_calls_;
211  if (ct.vars.empty()) return false;
212 
213  const double activity = ComputeActivity(ct, lp_solution);
214  const double violation =
215  std::max(activity - ToDouble(ct.ub), ToDouble(ct.lb) - activity);
216  const double l2_norm = ComputeL2Norm(ct);
217 
218  // Only add cut with sufficient efficacy.
219  if (violation / l2_norm < 1e-5) return false;
220 
221  bool added = false;
222  const ConstraintIndex ct_index = Add(std::move(ct), &added);
223 
224  // We only mark the constraint as a cut if it is not an update of an already
225  // existing one.
226  if (!added) return false;
227 
228  // TODO(user): Use better heuristic here for detecting good cuts and mark
229  // them undeletable.
230  constraint_infos_[ct_index].is_deletable = true;
231 
232  VLOG(1) << "Cut '" << type_name << "'"
233  << " size=" << constraint_infos_[ct_index].constraint.vars.size()
234  << " max_magnitude="
235  << ComputeInfinityNorm(constraint_infos_[ct_index].constraint)
236  << " norm=" << l2_norm << " violation=" << violation
237  << " eff=" << violation / l2_norm << " " << extra_info;
238 
239  num_cuts_++;
240  num_deletable_constraints_++;
241  type_to_num_cuts_[type_name]++;
242  return true;
243 }
244 
245 void LinearConstraintManager::PermanentlyRemoveSomeConstraints() {
246  std::vector<double> deletable_constraint_counts;
247  for (ConstraintIndex i(0); i < constraint_infos_.size(); ++i) {
248  if (constraint_infos_[i].is_deletable && !constraint_infos_[i].is_in_lp) {
249  deletable_constraint_counts.push_back(constraint_infos_[i].active_count);
250  }
251  }
252  if (deletable_constraint_counts.empty()) return;
253  std::sort(deletable_constraint_counts.begin(),
254  deletable_constraint_counts.end());
255 
256  // We will delete the oldest (in the order they where added) cleanup target
257  // constraints with a count lower or equal to this.
258  double active_count_threshold = std::numeric_limits<double>::infinity();
259  if (sat_parameters_.cut_cleanup_target() <
260  deletable_constraint_counts.size()) {
261  active_count_threshold =
262  deletable_constraint_counts[sat_parameters_.cut_cleanup_target()];
263  }
264 
265  ConstraintIndex new_size(0);
266  equiv_constraints_.clear();
268  constraint_infos_.size());
269  int num_deleted_constraints = 0;
270  for (ConstraintIndex i(0); i < constraint_infos_.size(); ++i) {
271  if (constraint_infos_[i].is_deletable && !constraint_infos_[i].is_in_lp &&
272  constraint_infos_[i].active_count <= active_count_threshold &&
273  num_deleted_constraints < sat_parameters_.cut_cleanup_target()) {
274  ++num_deleted_constraints;
275  continue;
276  }
277 
278  if (i != new_size) {
279  constraint_infos_[new_size] = std::move(constraint_infos_[i]);
280  }
281  index_mapping[i] = new_size;
282 
283  // Make sure we recompute the hash_map of identical constraints.
284  equiv_constraints_[constraint_infos_[new_size].hash] = new_size;
285  new_size++;
286  }
287  constraint_infos_.resize(new_size.value());
288 
289  // Also update lp_constraints_
290  for (int i = 0; i < lp_constraints_.size(); ++i) {
291  lp_constraints_[i] = index_mapping[lp_constraints_[i]];
292  }
293 
294  if (num_deleted_constraints > 0) {
295  VLOG(1) << "Constraint manager cleanup: #deleted:"
296  << num_deleted_constraints;
297  }
298  num_deletable_constraints_ -= num_deleted_constraints;
299 }
300 
302  IntegerValue coeff) {
303  if (coeff == IntegerValue(0)) return;
304  objective_is_defined_ = true;
305  if (!VariableIsPositive(var)) {
306  var = NegationOf(var);
307  coeff = -coeff;
308  }
309  if (var.value() >= dense_objective_coeffs_.size()) {
310  dense_objective_coeffs_.resize(var.value() + 1, 0.0);
311  }
312  dense_objective_coeffs_[var] = ToDouble(coeff);
313 }
314 
315 bool LinearConstraintManager::SimplifyConstraint(LinearConstraint* ct) {
316  bool term_changed = false;
317 
318  IntegerValue min_sum(0);
319  IntegerValue max_sum(0);
320  IntegerValue max_magnitude(0);
321  int new_size = 0;
322  const int num_terms = ct->vars.size();
323  for (int i = 0; i < num_terms; ++i) {
324  const IntegerVariable var = ct->vars[i];
325  const IntegerValue coeff = ct->coeffs[i];
326  const IntegerValue lb = integer_trail_.LevelZeroLowerBound(var);
327  const IntegerValue ub = integer_trail_.LevelZeroUpperBound(var);
328 
329  // For now we do not change ct, but just compute its new_size if we where
330  // to remove a fixed term.
331  if (lb == ub) continue;
332  ++new_size;
333 
334  max_magnitude = std::max(max_magnitude, IntTypeAbs(coeff));
335  if (coeff > 0.0) {
336  min_sum += coeff * lb;
337  max_sum += coeff * ub;
338  } else {
339  min_sum += coeff * ub;
340  max_sum += coeff * lb;
341  }
342  }
343 
344  // Shorten the constraint if needed.
345  if (new_size < num_terms) {
346  term_changed = true;
347  ++num_shortened_constraints_;
348  new_size = 0;
349  for (int i = 0; i < num_terms; ++i) {
350  const IntegerVariable var = ct->vars[i];
351  const IntegerValue coeff = ct->coeffs[i];
352  const IntegerValue lb = integer_trail_.LevelZeroLowerBound(var);
353  const IntegerValue ub = integer_trail_.LevelZeroUpperBound(var);
354  if (lb == ub) {
355  const IntegerValue rhs_adjust = lb * coeff;
356  if (ct->lb > kMinIntegerValue) ct->lb -= rhs_adjust;
357  if (ct->ub < kMaxIntegerValue) ct->ub -= rhs_adjust;
358  continue;
359  }
360  ct->vars[new_size] = var;
361  ct->coeffs[new_size] = coeff;
362  ++new_size;
363  }
364  ct->vars.resize(new_size);
365  ct->coeffs.resize(new_size);
366  }
367 
368  // Relax the bound if needed, note that this doesn't require a change to
369  // the equiv map.
370  if (min_sum >= ct->lb) ct->lb = kMinIntegerValue;
371  if (max_sum <= ct->ub) ct->ub = kMaxIntegerValue;
372 
373  // Clear constraints that are always true.
374  // We rely on the deletion code to remove them eventually.
375  if (ct->lb == kMinIntegerValue && ct->ub == kMaxIntegerValue) {
376  ct->vars.clear();
377  ct->coeffs.clear();
378  return true;
379  }
380 
381  // TODO(user): Split constraint in two if it is boxed and there is possible
382  // reduction?
383  //
384  // TODO(user): Make sure there cannot be any overflow. They shouldn't, but
385  // I am not sure all the generated cuts are safe regarding min/max sum
386  // computation. We should check this.
387  if (ct->ub != kMaxIntegerValue && max_magnitude > max_sum - ct->ub) {
388  if (ct->lb != kMinIntegerValue) {
389  ++num_splitted_constraints_;
390  } else {
391  term_changed = true;
392  ++num_coeff_strenghtening_;
393  const int num_terms = ct->vars.size();
394  const IntegerValue target = max_sum - ct->ub;
395  for (int i = 0; i < num_terms; ++i) {
396  const IntegerValue coeff = ct->coeffs[i];
397  if (coeff > target) {
398  const IntegerVariable var = ct->vars[i];
399  const IntegerValue ub = integer_trail_.LevelZeroUpperBound(var);
400  ct->coeffs[i] = target;
401  ct->ub -= (coeff - target) * ub;
402  } else if (coeff < -target) {
403  const IntegerVariable var = ct->vars[i];
404  const IntegerValue lb = integer_trail_.LevelZeroLowerBound(var);
405  ct->coeffs[i] = -target;
406  ct->ub += (-target - coeff) * lb;
407  }
408  }
409  }
410  }
411 
412  if (ct->lb != kMinIntegerValue && max_magnitude > ct->lb - min_sum) {
413  if (ct->ub != kMaxIntegerValue) {
414  ++num_splitted_constraints_;
415  } else {
416  term_changed = true;
417  ++num_coeff_strenghtening_;
418  const int num_terms = ct->vars.size();
419  const IntegerValue target = ct->lb - min_sum;
420  for (int i = 0; i < num_terms; ++i) {
421  const IntegerValue coeff = ct->coeffs[i];
422  if (coeff > target) {
423  const IntegerVariable var = ct->vars[i];
424  const IntegerValue lb = integer_trail_.LevelZeroLowerBound(var);
425  ct->coeffs[i] = target;
426  ct->lb -= (coeff - target) * lb;
427  } else if (coeff < -target) {
428  const IntegerVariable var = ct->vars[i];
429  const IntegerValue ub = integer_trail_.LevelZeroUpperBound(var);
430  ct->coeffs[i] = -target;
431  ct->lb += (-target - coeff) * ub;
432  }
433  }
434  }
435  }
436 
437  return term_changed;
438 }
439 
441  const gtl::ITIVector<IntegerVariable, double>& lp_solution,
442  glop::BasisState* solution_state) {
443  VLOG(3) << "Enter ChangeLP, scan " << constraint_infos_.size()
444  << " constraints";
445  const double saved_dtime = dtime_;
446  std::vector<ConstraintIndex> new_constraints;
447  std::vector<double> new_constraints_efficacies;
448  std::vector<double> new_constraints_orthogonalities;
449 
450  const bool simplify_constraints =
451  integer_trail_.num_level_zero_enqueues() > last_simplification_timestamp_;
452  last_simplification_timestamp_ = integer_trail_.num_level_zero_enqueues();
453 
454  // We keep any constraints that is already present, and otherwise, we add the
455  // ones that are currently not satisfied by at least "tolerance" to the set
456  // of potential new constraints.
457  bool rescale_active_count = false;
458  const double tolerance = 1e-6;
459  for (ConstraintIndex i(0); i < constraint_infos_.size(); ++i) {
460  // Inprocessing of the constraint.
461  if (simplify_constraints &&
462  SimplifyConstraint(&constraint_infos_[i].constraint)) {
463  ++num_simplifications_;
464 
465  // Note that the canonicalization shouldn't be needed since the order
466  // of the variable is not changed by the simplification, and we only
467  // reduce the coefficients at both end of the spectrum.
468  DivideByGCD(&constraint_infos_[i].constraint);
469  DCHECK(DebugCheckConstraint(constraint_infos_[i].constraint));
470 
471  constraint_infos_[i].objective_parallelism_computed = false;
472  constraint_infos_[i].l2_norm =
473  ComputeL2Norm(constraint_infos_[i].constraint);
474 
475  if (constraint_infos_[i].is_in_lp) current_lp_is_changed_ = true;
476  equiv_constraints_.erase(constraint_infos_[i].hash);
477  constraint_infos_[i].hash =
478  ComputeHashOfTerms(constraint_infos_[i].constraint);
479 
480  // TODO(user): Because we simplified this constraint, it is possible that
481  // it is now a duplicate of another one. Merge them.
482  equiv_constraints_[constraint_infos_[i].hash] = i;
483  }
484 
485  if (constraint_infos_[i].is_in_lp) continue;
486 
487  // ComputeActivity() often represent the bulk of the time spent in
488  // ChangeLP().
489  dtime_ += 1.7e-9 *
490  static_cast<double>(constraint_infos_[i].constraint.vars.size());
491  const double activity =
492  ComputeActivity(constraint_infos_[i].constraint, lp_solution);
493  const double lb_violation =
494  ToDouble(constraint_infos_[i].constraint.lb) - activity;
495  const double ub_violation =
496  activity - ToDouble(constraint_infos_[i].constraint.ub);
497  const double violation = std::max(lb_violation, ub_violation);
498  if (violation >= tolerance) {
499  constraint_infos_[i].inactive_count = 0;
500  new_constraints.push_back(i);
501  new_constraints_efficacies.push_back(violation /
502  constraint_infos_[i].l2_norm);
503  new_constraints_orthogonalities.push_back(1.0);
504 
505  if (objective_is_defined_ &&
506  !constraint_infos_[i].objective_parallelism_computed) {
507  ComputeObjectiveParallelism(i);
508  } else if (!objective_is_defined_) {
509  constraint_infos_[i].objective_parallelism = 0.0;
510  }
511 
512  constraint_infos_[i].current_score =
513  new_constraints_efficacies.back() +
514  constraint_infos_[i].objective_parallelism;
515 
516  if (constraint_infos_[i].is_deletable) {
517  constraint_infos_[i].active_count += constraint_active_count_increase_;
518  if (constraint_infos_[i].active_count >
519  sat_parameters_.cut_max_active_count_value()) {
520  rescale_active_count = true;
521  }
522  }
523  }
524  }
525 
526  // Bump activities of active constraints in LP.
527  if (solution_state != nullptr) {
528  const glop::RowIndex num_rows(lp_constraints_.size());
529  const glop::ColIndex num_cols =
530  solution_state->statuses.size() - RowToColIndex(num_rows);
531 
532  for (int i = 0; i < num_rows; ++i) {
533  const ConstraintIndex constraint_index = lp_constraints_[i];
534  const glop::VariableStatus row_status =
535  solution_state->statuses[num_cols + glop::ColIndex(i)];
536  if (row_status != glop::VariableStatus::BASIC &&
537  constraint_infos_[constraint_index].is_deletable) {
538  constraint_infos_[constraint_index].active_count +=
539  constraint_active_count_increase_;
540  if (constraint_infos_[constraint_index].active_count >
541  sat_parameters_.cut_max_active_count_value()) {
542  rescale_active_count = true;
543  }
544  }
545  }
546  }
547 
548  if (rescale_active_count) {
549  CHECK_GT(sat_parameters_.cut_max_active_count_value(), 0.0);
550  RescaleActiveCounts(1.0 / sat_parameters_.cut_max_active_count_value());
551  }
552 
553  // Update the increment counter.
554  constraint_active_count_increase_ *=
555  1.0 / sat_parameters_.cut_active_count_decay();
556 
557  // Remove constraints from the current LP that have been inactive for a while.
558  // We do that after we computed new_constraints so we do not need to iterate
559  // over the just deleted constraints.
560  if (MaybeRemoveSomeInactiveConstraints(solution_state)) {
561  current_lp_is_changed_ = true;
562  }
563 
564  // Note that the algo below is in O(limit * new_constraint). In order to
565  // limit spending too much time on this, we first sort all the constraints
566  // with an imprecise score (no orthogonality), then limit the size of the
567  // vector of constraints to precisely score, then we do the actual scoring.
568  //
569  // On problem crossword_opt_grid-19.05_dict-80_sat with linearization_level=2,
570  // new_constraint.size() > 1.5M.
571  //
572  // TODO(user): This blowup factor could be adaptative w.r.t. the constraint
573  // limit.
574  const int kBlowupFactor = 4;
575  int constraint_limit = std::min(sat_parameters_.new_constraints_batch_size(),
576  static_cast<int>(new_constraints.size()));
577  if (lp_constraints_.empty()) {
578  constraint_limit = std::min(1000, static_cast<int>(new_constraints.size()));
579  }
580  VLOG(3) << " - size = " << new_constraints.size()
581  << ", limit = " << constraint_limit;
582 
583  std::stable_sort(new_constraints.begin(), new_constraints.end(),
584  [&](ConstraintIndex a, ConstraintIndex b) {
585  return constraint_infos_[a].current_score >
586  constraint_infos_[b].current_score;
587  });
588  if (new_constraints.size() > kBlowupFactor * constraint_limit) {
589  VLOG(3) << "Resize candidate constraints from " << new_constraints.size()
590  << " down to " << kBlowupFactor * constraint_limit;
591  new_constraints.resize(kBlowupFactor * constraint_limit);
592  }
593 
594  int num_added = 0;
595  int num_skipped_checks = 0;
596  const int kCheckFrequency = 100;
597  ConstraintIndex last_added_candidate = kInvalidConstraintIndex;
598  for (int i = 0; i < constraint_limit; ++i) {
599  // Iterate through all new constraints and select the one with the best
600  // score.
601  double best_score = 0.0;
602  ConstraintIndex best_candidate = kInvalidConstraintIndex;
603  for (int j = 0; j < new_constraints.size(); ++j) {
604  // Checks the time limit, and returns if the lp has changed.
605  if (++num_skipped_checks >= kCheckFrequency) {
606  if (time_limit_->LimitReached()) return current_lp_is_changed_;
607  num_skipped_checks = 0;
608  }
609 
610  const ConstraintIndex new_constraint = new_constraints[j];
611  if (constraint_infos_[new_constraint].is_in_lp) continue;
612 
613  if (last_added_candidate != kInvalidConstraintIndex) {
614  const double current_orthogonality =
615  1.0 - (std::abs(ScalarProduct(
616  constraint_infos_[last_added_candidate].constraint,
617  constraint_infos_[new_constraint].constraint)) /
618  (constraint_infos_[last_added_candidate].l2_norm *
619  constraint_infos_[new_constraint].l2_norm));
620  new_constraints_orthogonalities[j] =
621  std::min(new_constraints_orthogonalities[j], current_orthogonality);
622  }
623 
624  // NOTE(user): It is safe to not add this constraint as the constraint
625  // that is almost parallel to this constraint is present in the LP or is
626  // inactive for a long time and is removed from the LP. In either case,
627  // this constraint is not adding significant value and is only making the
628  // LP larger.
629  if (new_constraints_orthogonalities[j] <
630  sat_parameters_.min_orthogonality_for_lp_constraints()) {
631  continue;
632  }
633 
634  // TODO(user): Experiment with different weights or different
635  // functions for computing score.
636  const double score = new_constraints_orthogonalities[j] +
637  constraint_infos_[new_constraint].current_score;
638  CHECK_GE(score, 0.0);
639  if (score > best_score || best_candidate == kInvalidConstraintIndex) {
640  best_score = score;
641  best_candidate = new_constraint;
642  }
643  }
644 
645  if (best_candidate != kInvalidConstraintIndex) {
646  // Add the best constraint in the LP.
647  constraint_infos_[best_candidate].is_in_lp = true;
648  // Note that it is important for LP incremental solving that the old
649  // constraints stays at the same position in this list (and thus in the
650  // returned GetLp()).
651  ++num_added;
652  current_lp_is_changed_ = true;
653  lp_constraints_.push_back(best_candidate);
654  last_added_candidate = best_candidate;
655  }
656  }
657 
658  if (num_added > 0) {
659  // We update the solution sate to match the new LP size.
660  VLOG(2) << "Added " << num_added << " constraints.";
661  solution_state->statuses.resize(solution_state->statuses.size() + num_added,
663  }
664 
665  // TODO(user): Instead of comparing num_deletable_constraints with cut
666  // limit, compare number of deletable constraints not in lp against the limit.
667  if (num_deletable_constraints_ > sat_parameters_.max_num_cuts()) {
668  PermanentlyRemoveSomeConstraints();
669  }
670 
671  time_limit_->AdvanceDeterministicTime(dtime_ - saved_dtime);
672 
673  // The LP changed only if we added new constraints or if some constraints
674  // already inside changed (simplification or tighter bounds).
675  if (current_lp_is_changed_) {
676  current_lp_is_changed_ = false;
677  return true;
678  }
679  return false;
680 }
681 
683  for (ConstraintIndex i(0); i < constraint_infos_.size(); ++i) {
684  if (constraint_infos_[i].is_in_lp) continue;
685  constraint_infos_[i].is_in_lp = true;
686  lp_constraints_.push_back(i);
687  }
688 }
689 
691  const LinearConstraint& cut) {
692  if (model_->Get<DebugSolution>() == nullptr) return true;
693  const auto& debug_solution = *(model_->Get<DebugSolution>());
694  if (debug_solution.empty()) return true;
695 
696  IntegerValue activity(0);
697  for (int i = 0; i < cut.vars.size(); ++i) {
698  const IntegerVariable var = cut.vars[i];
699  const IntegerValue coeff = cut.coeffs[i];
700  activity += coeff * debug_solution[var];
701  }
702  if (activity > cut.ub || activity < cut.lb) {
703  LOG(INFO) << "activity " << activity << " not in [" << cut.lb << ","
704  << cut.ub << "]";
705  return false;
706  }
707  return true;
708 }
709 
711  LinearConstraint ct, const std::string& name,
712  const gtl::ITIVector<IntegerVariable, double>& lp_solution) {
713  if (ct.vars.empty()) return;
714  const double activity = ComputeActivity(ct, lp_solution);
715  const double violation =
716  std::max(activity - ToDouble(ct.ub), ToDouble(ct.lb) - activity);
717  const double l2_norm = ComputeL2Norm(ct);
718  cuts_.Add({name, ct}, violation / l2_norm);
719 }
720 
722  const gtl::ITIVector<IntegerVariable, double>& lp_solution,
723  LinearConstraintManager* manager) {
724  for (const CutCandidate& candidate : cuts_.UnorderedElements()) {
725  manager->AddCut(candidate.cut, candidate.name, lp_solution);
726  }
727  cuts_.Clear();
728 }
729 
730 } // namespace sat
731 } // namespace operations_research
operations_research::sat::LinearConstraintManager::ChangeLp
bool ChangeLp(const gtl::ITIVector< IntegerVariable, double > &lp_solution, glop::BasisState *solution_state)
Definition: linear_constraint_manager.cc:440
var
IntVar * var
Definition: expr_array.cc:1858
operations_research::glop::StrictITIVector::resize
void resize(IntType size)
Definition: lp_types.h:269
min
int64 min
Definition: alldiff_cst.cc:138
operations_research::glop::VariableStatus::BASIC
@ BASIC
operations_research::sat::ScalarProduct
double ScalarProduct(const LinearConstraint &constraint1, const LinearConstraint &constraint2)
Definition: linear_constraint.cc:148
operations_research::sat::VariableIsPositive
bool VariableIsPositive(IntegerVariable i)
Definition: integer.h:130
max
int64 max
Definition: alldiff_cst.cc:139
operations_research::sat::LinearConstraint::vars
std::vector< IntegerVariable > vars
Definition: linear_constraint.h:42
operations_research::sat::LinearConstraintManager::ConstraintInfo::hash
size_t hash
Definition: linear_constraint_manager.h:49
operations_research::sat::LinearConstraintManager::ConstraintInfo::constraint
LinearConstraint constraint
Definition: linear_constraint_manager.h:43
operations_research::sat::LinearConstraintManager::ConstraintInfo::active_count
double active_count
Definition: linear_constraint_manager.h:55
operations_research::sat::TopN::Clear
void Clear()
Definition: linear_constraint_manager.h:230
linear_constraint.h
operations_research::sat::IntegerTrail::LevelZeroUpperBound
IntegerValue LevelZeroUpperBound(IntegerVariable var) const
Definition: integer.h:1283
operations_research::sat::IntegerTrail::LevelZeroLowerBound
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
Definition: integer.h:1278
gtl::ITIVector< IntegerVariable, double >
hash
int64 hash
Definition: matrix_utils.cc:60
operations_research::sat::NoDuplicateVariable
bool NoDuplicateVariable(const LinearConstraint &ct)
Definition: linear_constraint.cc:263
operations_research::glop::StrictITIVector::size
IntType size() const
Definition: lp_types.h:276
operations_research
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...
Definition: dense_doubly_linked_list.h:21
operations_research::sat::NegationOf
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Definition: integer.cc:42
operations_research::sat::LinearConstraintManager
Definition: linear_constraint_manager.h:40
operations_research::glop::RowToColIndex
ColIndex RowToColIndex(RowIndex row)
Definition: lp_types.h:48
a
int64 a
Definition: constraint_solver/table.cc:42
operations_research::sat::LinearConstraint
Definition: linear_constraint.h:39
operations_research::sat::IntTypeAbs
IntType IntTypeAbs(IntType t)
Definition: integer.h:77
operations_research::glop::BasisState
Definition: revised_simplex.h:132
operations_research::sat::kMaxIntegerValue
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
operations_research::sat::LinearConstraintManager::Add
ConstraintIndex Add(LinearConstraint ct, bool *added=nullptr)
Definition: linear_constraint_manager.cc:124
operations_research::sat::LinearConstraint::lb
IntegerValue lb
Definition: linear_constraint.h:40
ct
const Constraint * ct
Definition: demon_profiler.cc:42
operations_research::sat::LinearConstraintManager::SetObjectiveCoefficient
void SetObjectiveCoefficient(IntegerVariable var, IntegerValue coeff)
Definition: linear_constraint_manager.cc:301
operations_research::sat::LinearConstraintManager::AddCut
bool AddCut(LinearConstraint ct, std::string type_name, const gtl::ITIVector< IntegerVariable, double > &lp_solution, std::string extra_info="")
Definition: linear_constraint_manager.cc:206
operations_research::sat::IntegerTrail::num_level_zero_enqueues
int64 num_level_zero_enqueues() const
Definition: integer.h:771
gtl::ITIVector::size
size_type size() const
Definition: int_type_indexed_vector.h:146
operations_research::sat::ComputeL2Norm
double ComputeL2Norm(const LinearConstraint &constraint)
Definition: linear_constraint.cc:132
operations_research::sat::TopN::Add
void Add(Element e, double score)
Definition: linear_constraint_manager.h:235
operations_research::TimeLimit::AdvanceDeterministicTime
void AdvanceDeterministicTime(double deterministic_duration)
Advances the deterministic time.
Definition: time_limit.h:226
operations_research::sat::ToDouble
double ToDouble(IntegerValue value)
Definition: integer.h:69
operations_research::sat::kMinIntegerValue
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
linear_constraint_manager.h
operations_research::sat::ComputeActivity
double ComputeActivity(const LinearConstraint &constraint, const gtl::ITIVector< IntegerVariable, double > &values)
Definition: linear_constraint.cc:121
operations_research::sat::DebugSolution
Definition: integer.h:238
operations_research::sat::LinearConstraintManager::~LinearConstraintManager
~LinearConstraintManager()
Definition: linear_constraint_manager.cc:45
b
int64 b
Definition: constraint_solver/table.cc:43
operations_research::sat::TopN::UnorderedElements
const std::vector< Element > & UnorderedElements() const
Definition: linear_constraint_manager.h:256
gtl::ITIVector::resize
void resize(size_type new_size)
Definition: int_type_indexed_vector.h:149
operations_research::sat::ComputeInfinityNorm
IntegerValue ComputeInfinityNorm(const LinearConstraint &constraint)
Definition: linear_constraint.cc:140
operations_research::glop::VariableStatus
VariableStatus
Definition: lp_types.h:196
operations_research::sat::LinearConstraint::coeffs
std::vector< IntegerValue > coeffs
Definition: linear_constraint.h:43
operations_research::sat::LinearConstraintManager::ConstraintInfo
Definition: linear_constraint_manager.h:42
operations_research::sat::DivideByGCD
void DivideByGCD(LinearConstraint *constraint)
Definition: linear_constraint.cc:187
operations_research::sat::TopNCuts::TransferToManager
void TransferToManager(const gtl::ITIVector< IntegerVariable, double > &lp_solution, LinearConstraintManager *manager)
Definition: linear_constraint_manager.cc:721
operations_research::TimeLimit::LimitReached
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
Definition: time_limit.h:532
operations_research::sat::Model::Name
const std::string & Name() const
Definition: sat/model.h:175
operations_research::glop::BasisState::statuses
VariableStatusRow statuses
Definition: revised_simplex.h:140
operations_research::sat::LinearConstraint::ub
IntegerValue ub
Definition: linear_constraint.h:41
operations_research::sat::LinearConstraintManager::AddAllConstraintsToLp
void AddAllConstraintsToLp()
Definition: linear_constraint_manager.cc:682
operations_research::sat::LinearConstraintManager::DebugCheckConstraint
bool DebugCheckConstraint(const LinearConstraint &cut)
Definition: linear_constraint_manager.cc:690
operations_research::sat::CanonicalizeConstraint
void CanonicalizeConstraint(LinearConstraint *ct)
Definition: linear_constraint.cc:242
operations_research::sat::TopNCuts::AddCut
void AddCut(LinearConstraint ct, const std::string &name, const gtl::ITIVector< IntegerVariable, double > &lp_solution)
Definition: linear_constraint_manager.cc:710
util_hash::Hash
uint64 Hash(uint64 num, uint64 c)
Definition: hash.h:150
integer.h
name
const std::string name
Definition: default_search.cc:807
operations_research::sat::Model::Get
T Get(std::function< T(const Model &)> f) const
Similar to Add() but this is const.
Definition: sat/model.h:87
operations_research::sat::LinearConstraintManager::ConstraintInfo::l2_norm
double l2_norm
Definition: linear_constraint_manager.h:44
gtl::ContainsKey
bool ContainsKey(const Collection &collection, const Key &key)
Definition: map_util.h:170