OR-Tools  8.2
cp_model_lns.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 <limits>
17 #include <numeric>
18 #include <vector>
19 
23 #include "ortools/sat/integer.h"
25 #include "ortools/sat/rins.h"
28 
29 namespace operations_research {
30 namespace sat {
31 
33  CpModelProto const* model_proto, SatParameters const* parameters,
34  SharedResponseManager* shared_response, SharedTimeLimit* shared_time_limit,
35  SharedBoundsManager* shared_bounds)
36  : SubSolver(""),
37  parameters_(*parameters),
38  model_proto_(*model_proto),
39  shared_time_limit_(shared_time_limit),
40  shared_bounds_(shared_bounds),
41  shared_response_(shared_response) {
42  CHECK(shared_response_ != nullptr);
43  if (shared_bounds_ != nullptr) {
44  shared_bounds_id_ = shared_bounds_->RegisterNewId();
45  }
46  *model_proto_with_only_variables_.mutable_variables() =
47  model_proto_.variables();
48  RecomputeHelperData();
49  Synchronize();
50 }
51 
53  absl::MutexLock mutex_lock(&mutex_);
54  if (shared_bounds_ != nullptr) {
55  std::vector<int> model_variables;
56  std::vector<int64> new_lower_bounds;
57  std::vector<int64> new_upper_bounds;
58  shared_bounds_->GetChangedBounds(shared_bounds_id_, &model_variables,
59  &new_lower_bounds, &new_upper_bounds);
60 
61  for (int i = 0; i < model_variables.size(); ++i) {
62  const int var = model_variables[i];
63  const int64 new_lb = new_lower_bounds[i];
64  const int64 new_ub = new_upper_bounds[i];
65  if (VLOG_IS_ON(3)) {
66  const auto& domain =
67  model_proto_with_only_variables_.variables(var).domain();
68  const int64 old_lb = domain.Get(0);
69  const int64 old_ub = domain.Get(domain.size() - 1);
70  VLOG(3) << "Variable: " << var << " old domain: [" << old_lb << ", "
71  << old_ub << "] new domain: [" << new_lb << ", " << new_ub
72  << "]";
73  }
74  const Domain old_domain =
75  ReadDomainFromProto(model_proto_with_only_variables_.variables(var));
76  const Domain new_domain =
77  old_domain.IntersectionWith(Domain(new_lb, new_ub));
78  if (new_domain.IsEmpty()) {
79  // This can mean two things:
80  // 1/ This variable is a normal one and the problem is UNSAT or
81  // 2/ This variable is optional, and its associated literal must be
82  // set to false.
83  //
84  // Currently, we wait for any full solver to pick the crossing bounds
85  // and do the correct stuff on their own. We do not want to have empty
86  // domain in the proto as this would means INFEASIBLE. So we just ignore
87  // such bounds here.
88  //
89  // TODO(user): We could set the optional literal to false directly in
90  // the bound sharing manager. We do have to be careful that all the
91  // different solvers have the same optionality definition though.
92  continue;
93  }
95  new_domain, model_proto_with_only_variables_.mutable_variables(var));
96  }
97 
98  // Only trigger the computation if needed.
99  if (!model_variables.empty()) {
100  RecomputeHelperData();
101  }
102  }
103 }
104 
105 void NeighborhoodGeneratorHelper::RecomputeHelperData() {
106  // Recompute all the data in case new variables have been fixed.
107  //
108  // TODO(user): Ideally we should ignore trivially true/false constraint, but
109  // this will duplicate already existing code :-( we should probably still do
110  // at least enforcement literal and clauses? We could maybe run a light
111  // presolve?
112  var_to_constraint_.assign(model_proto_.variables_size(), {});
113  constraint_to_var_.assign(model_proto_.constraints_size(), {});
114  for (int ct_index = 0; ct_index < model_proto_.constraints_size();
115  ++ct_index) {
116  for (const int var : UsedVariables(model_proto_.constraints(ct_index))) {
117  if (IsConstant(var)) continue;
118  var_to_constraint_[var].push_back(ct_index);
119  constraint_to_var_[ct_index].push_back(var);
120  CHECK_GE(var, 0);
121  CHECK_LT(var, model_proto_.variables_size());
122  }
123  }
124 
125  type_to_constraints_.clear();
126  const int num_constraints = model_proto_.constraints_size();
127  for (int c = 0; c < num_constraints; ++c) {
128  const int type = model_proto_.constraints(c).constraint_case();
129  if (type >= type_to_constraints_.size()) {
130  type_to_constraints_.resize(type + 1);
131  }
132  type_to_constraints_[type].push_back(c);
133  }
134 
135  active_variables_.clear();
136  active_variables_set_.assign(model_proto_.variables_size(), false);
137 
138  if (parameters_.lns_focus_on_decision_variables()) {
139  for (const auto& search_strategy : model_proto_.search_strategy()) {
140  for (const int var : search_strategy.variables()) {
141  const int pos_var = PositiveRef(var);
142  if (!active_variables_set_[pos_var] && !IsConstant(pos_var)) {
143  active_variables_set_[pos_var] = true;
144  active_variables_.push_back(pos_var);
145  }
146  }
147  }
148 
149  // Revert to no focus if active_variables_ is empty().
150  if (!active_variables_.empty()) return;
151  }
152 
153  // Add all non-constant variables.
154  for (int i = 0; i < model_proto_.variables_size(); ++i) {
155  if (!IsConstant(i)) {
156  active_variables_.push_back(i);
157  active_variables_set_[i] = true;
158  }
159  }
160 }
161 
163  return active_variables_set_[var];
164 }
165 
166 bool NeighborhoodGeneratorHelper::IsConstant(int var) const {
167  return model_proto_with_only_variables_.variables(var).domain_size() == 2 &&
168  model_proto_with_only_variables_.variables(var).domain(0) ==
169  model_proto_with_only_variables_.variables(var).domain(1);
170 }
171 
173  Neighborhood neighborhood;
174  neighborhood.is_reduced = false;
175  neighborhood.is_generated = true;
176  neighborhood.cp_model = model_proto_;
177  *neighborhood.cp_model.mutable_variables() =
178  model_proto_with_only_variables_.variables();
179  return neighborhood;
180 }
181 
183  const CpSolverResponse& initial_solution,
184  const std::vector<int>& variables_to_fix) const {
185  // TODO(user,user): Do not include constraint with all fixed variables to
186  // save memory and speed-up LNS presolving.
187  Neighborhood neighborhood = FullNeighborhood();
188 
189  // Set the current solution as a hint.
190  neighborhood.cp_model.clear_solution_hint();
191  for (int var = 0; var < neighborhood.cp_model.variables_size(); ++var) {
192  neighborhood.cp_model.mutable_solution_hint()->add_vars(var);
193  neighborhood.cp_model.mutable_solution_hint()->add_values(
194  initial_solution.solution(var));
195  }
196 
197  neighborhood.is_reduced = !variables_to_fix.empty();
198  if (!neighborhood.is_reduced) return neighborhood;
199  CHECK_EQ(initial_solution.solution_size(),
200  neighborhood.cp_model.variables_size());
201  for (const int var : variables_to_fix) {
202  neighborhood.cp_model.mutable_variables(var)->clear_domain();
203  neighborhood.cp_model.mutable_variables(var)->add_domain(
204  initial_solution.solution(var));
205  neighborhood.cp_model.mutable_variables(var)->add_domain(
206  initial_solution.solution(var));
207  }
208 
209  // TODO(user): force better objective? Note that this is already done when the
210  // hint above is successfully loaded (i.e. if it passes the presolve
211  // correctly) since the solver will try to find better solution than the
212  // current one.
213  return neighborhood;
214 }
215 
217  const std::vector<int>& constraints_to_remove) const {
218  // TODO(user,user): Do not include constraint with all fixed variables to
219  // save memory and speed-up LNS presolving.
220  Neighborhood neighborhood = FullNeighborhood();
221 
222  if (constraints_to_remove.empty()) return neighborhood;
223  neighborhood.is_reduced = false;
224  for (const int constraint : constraints_to_remove) {
225  neighborhood.cp_model.mutable_constraints(constraint)->Clear();
226  }
227 
228  return neighborhood;
229 }
230 
232  const CpSolverResponse& initial_solution,
233  const std::vector<int>& relaxed_variables) const {
234  std::vector<bool> relaxed_variables_set(model_proto_.variables_size(), false);
235  for (const int var : relaxed_variables) relaxed_variables_set[var] = true;
236  std::vector<int> fixed_variables;
237  for (const int i : active_variables_) {
238  if (!relaxed_variables_set[i]) {
239  fixed_variables.push_back(i);
240  }
241  }
242  return FixGivenVariables(initial_solution, fixed_variables);
243 }
244 
246  const CpSolverResponse& initial_solution) const {
247  std::vector<int> fixed_variables;
248  for (const int i : active_variables_) {
249  fixed_variables.push_back(i);
250  }
251  return FixGivenVariables(initial_solution, fixed_variables);
252 }
253 
256 }
257 
258 double NeighborhoodGenerator::GetUCBScore(int64 total_num_calls) const {
259  absl::MutexLock mutex_lock(&mutex_);
260  DCHECK_GE(total_num_calls, num_calls_);
261  if (num_calls_ <= 10) return std::numeric_limits<double>::infinity();
262  return current_average_ + sqrt((2 * log(total_num_calls)) / num_calls_);
263 }
264 
266  absl::MutexLock mutex_lock(&mutex_);
267 
268  // To make the whole update process deterministic, we currently sort the
269  // SolveData.
270  std::sort(solve_data_.begin(), solve_data_.end());
271 
272  // This will be used to update the difficulty of this neighborhood.
273  int num_fully_solved_in_batch = 0;
274  int num_not_fully_solved_in_batch = 0;
275 
276  for (const SolveData& data : solve_data_) {
278  ++num_calls_;
279 
280  // INFEASIBLE or OPTIMAL means that we "fully solved" the local problem.
281  // If we didn't, then we cannot be sure that there is no improving solution
282  // in that neighborhood.
283  if (data.status == CpSolverStatus::INFEASIBLE ||
284  data.status == CpSolverStatus::OPTIMAL) {
285  ++num_fully_solved_calls_;
286  ++num_fully_solved_in_batch;
287  } else {
288  ++num_not_fully_solved_in_batch;
289  }
290 
291  // It seems to make more sense to compare the new objective to the base
292  // solution objective, not the best one. However this causes issue in the
293  // logic below because on some problems the neighborhood can always lead
294  // to a better "new objective" if the base solution wasn't the best one.
295  //
296  // This might not be a final solution, but it does work ok for now.
297  const IntegerValue best_objective_improvement =
299  ? IntegerValue(CapSub(data.new_objective_bound.value(),
300  data.initial_best_objective_bound.value()))
301  : IntegerValue(CapSub(data.initial_best_objective.value(),
302  data.new_objective.value()));
303  if (best_objective_improvement > 0) {
304  num_consecutive_non_improving_calls_ = 0;
305  } else {
306  ++num_consecutive_non_improving_calls_;
307  }
308 
309  // TODO(user): Weight more recent data.
310  // degrade the current average to forget old learnings.
311  const double gain_per_time_unit =
312  std::max(0.0, static_cast<double>(best_objective_improvement.value())) /
313  (1.0 + data.deterministic_time);
314  if (num_calls_ <= 100) {
315  current_average_ += (gain_per_time_unit - current_average_) / num_calls_;
316  } else {
317  current_average_ = 0.9 * current_average_ + 0.1 * gain_per_time_unit;
318  }
319 
320  deterministic_time_ += data.deterministic_time;
321  }
322 
323  // Update the difficulty.
324  difficulty_.Update(/*num_decreases=*/num_not_fully_solved_in_batch,
325  /*num_increases=*/num_fully_solved_in_batch);
326 
327  // Bump the time limit if we saw no better solution in the last few calls.
328  // This means that as the search progress, we likely spend more and more time
329  // trying to solve individual neighborhood.
330  //
331  // TODO(user): experiment with resetting the time limit if a solution is
332  // found.
333  if (num_consecutive_non_improving_calls_ > 50) {
334  num_consecutive_non_improving_calls_ = 0;
335  deterministic_limit_ *= 1.02;
336 
337  // We do not want the limit to go to high. Intuitively, the goal is to try
338  // out a lot of neighborhoods, not just spend a lot of time on a few.
339  deterministic_limit_ = std::min(60.0, deterministic_limit_);
340  }
341 
342  solve_data_.clear();
343 }
344 
345 namespace {
346 
347 void GetRandomSubset(double relative_size, std::vector<int>* base,
348  absl::BitGenRef random) {
349  // TODO(user): we could generate this more efficiently than using random
350  // shuffle.
351  std::shuffle(base->begin(), base->end(), random);
352  const int target_size = std::round(relative_size * base->size());
353  base->resize(target_size);
354 }
355 
356 } // namespace
357 
359  const CpSolverResponse& initial_solution, double difficulty,
360  absl::BitGenRef random) {
361  std::vector<int> fixed_variables = helper_.ActiveVariables();
362  GetRandomSubset(1.0 - difficulty, &fixed_variables, random);
363  return helper_.FixGivenVariables(initial_solution, fixed_variables);
364 }
365 
367  const CpSolverResponse& initial_solution, double difficulty,
368  absl::BitGenRef random) {
369  const int num_active_vars = helper_.ActiveVariables().size();
370  const int num_model_vars = helper_.ModelProto().variables_size();
371  const int target_size = std::ceil(difficulty * num_active_vars);
372  if (target_size == num_active_vars) {
373  return helper_.FullNeighborhood();
374  }
375  CHECK_GT(target_size, 0) << difficulty << " " << num_active_vars;
376 
377  std::vector<bool> visited_variables_set(num_model_vars, false);
378  std::vector<int> relaxed_variables;
379  std::vector<int> visited_variables;
380 
381  const int first_var =
382  helper_.ActiveVariables()[absl::Uniform<int>(random, 0, num_active_vars)];
383  visited_variables_set[first_var] = true;
384  visited_variables.push_back(first_var);
385  relaxed_variables.push_back(first_var);
386 
387  std::vector<int> random_variables;
388  for (int i = 0; i < visited_variables.size(); ++i) {
389  random_variables.clear();
390  // Collect all the variables that appears in the same constraints as
391  // visited_variables[i].
392  for (const int ct : helper_.VarToConstraint()[visited_variables[i]]) {
393  for (const int var : helper_.ConstraintToVar()[ct]) {
394  if (visited_variables_set[var]) continue;
395  visited_variables_set[var] = true;
396  random_variables.push_back(var);
397  }
398  }
399  // We always randomize to change the partial subgraph explored afterwards.
400  std::shuffle(random_variables.begin(), random_variables.end(), random);
401  for (const int var : random_variables) {
402  if (relaxed_variables.size() < target_size) {
403  visited_variables.push_back(var);
404  if (helper_.IsActive(var)) {
405  relaxed_variables.push_back(var);
406  }
407  } else {
408  break;
409  }
410  }
411  if (relaxed_variables.size() >= target_size) break;
412  }
413 
414  return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
415 }
416 
418  const CpSolverResponse& initial_solution, double difficulty,
419  absl::BitGenRef random) {
420  const int num_active_vars = helper_.ActiveVariables().size();
421  const int num_model_vars = helper_.ModelProto().variables_size();
422  const int target_size = std::ceil(difficulty * num_active_vars);
423  const int num_constraints = helper_.ConstraintToVar().size();
424  if (num_constraints == 0 || target_size == num_active_vars) {
425  return helper_.FullNeighborhood();
426  }
427  CHECK_GT(target_size, 0);
428 
429  std::vector<bool> visited_variables_set(num_model_vars, false);
430  std::vector<int> relaxed_variables;
431  std::vector<bool> added_constraints(num_constraints, false);
432  std::vector<int> next_constraints;
433 
434  // Start by a random constraint.
435  next_constraints.push_back(absl::Uniform<int>(random, 0, num_constraints));
436  added_constraints[next_constraints.back()] = true;
437 
438  std::vector<int> random_variables;
439  while (relaxed_variables.size() < target_size) {
440  // Stop if we have a full connected component.
441  if (next_constraints.empty()) break;
442 
443  // Pick a random unprocessed constraint.
444  const int i = absl::Uniform<int>(random, 0, next_constraints.size());
445  const int contraint_index = next_constraints[i];
446  std::swap(next_constraints[i], next_constraints.back());
447  next_constraints.pop_back();
448 
449  // Add all the variable of this constraint and increase the set of next
450  // possible constraints.
451  CHECK_LT(contraint_index, num_constraints);
452  random_variables = helper_.ConstraintToVar()[contraint_index];
453  std::shuffle(random_variables.begin(), random_variables.end(), random);
454  for (const int var : random_variables) {
455  if (visited_variables_set[var]) continue;
456  visited_variables_set[var] = true;
457  if (helper_.IsActive(var)) {
458  relaxed_variables.push_back(var);
459  }
460  if (relaxed_variables.size() == target_size) break;
461 
462  for (const int ct : helper_.VarToConstraint()[var]) {
463  if (added_constraints[ct]) continue;
464  added_constraints[ct] = true;
465  next_constraints.push_back(ct);
466  }
467  }
468  }
469  return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
470 }
471 
473  const absl::Span<const int> intervals_to_relax,
474  const CpSolverResponse& initial_solution,
475  const NeighborhoodGeneratorHelper& helper) {
476  Neighborhood neighborhood = helper.FullNeighborhood();
477  neighborhood.is_reduced =
478  (intervals_to_relax.size() <
479  helper.TypeToConstraints(ConstraintProto::kInterval).size());
480 
481  // We will extend the set with some interval that we cannot fix.
482  std::set<int> ignored_intervals(intervals_to_relax.begin(),
483  intervals_to_relax.end());
484 
485  // Fix the presence/absence of non-relaxed intervals.
486  for (const int i : helper.TypeToConstraints(ConstraintProto::kInterval)) {
487  if (ignored_intervals.count(i)) continue;
488 
489  const ConstraintProto& interval_ct = neighborhood.cp_model.constraints(i);
490  if (interval_ct.enforcement_literal().empty()) continue;
491 
492  CHECK_EQ(interval_ct.enforcement_literal().size(), 1);
493  const int enforcement_ref = interval_ct.enforcement_literal(0);
494  const int enforcement_var = PositiveRef(enforcement_ref);
495  const int value = initial_solution.solution(enforcement_var);
496 
497  // Fix the value.
498  neighborhood.cp_model.mutable_variables(enforcement_var)->clear_domain();
499  neighborhood.cp_model.mutable_variables(enforcement_var)->add_domain(value);
500  neighborhood.cp_model.mutable_variables(enforcement_var)->add_domain(value);
501 
502  // If the interval is ignored, skip for the loop below as there is no
503  // point adding precedence on it.
504  if (RefIsPositive(enforcement_ref) == (value == 0)) {
505  ignored_intervals.insert(i);
506  }
507  }
508 
509  for (const int c : helper.TypeToConstraints(ConstraintProto::kNoOverlap)) {
510  // Sort all non-relaxed intervals of this constraint by current start time.
511  std::vector<std::pair<int64, int>> start_interval_pairs;
512  for (const int i :
513  neighborhood.cp_model.constraints(c).no_overlap().intervals()) {
514  if (ignored_intervals.count(i)) continue;
515  const ConstraintProto& interval_ct = neighborhood.cp_model.constraints(i);
516 
517  // TODO(user): we ignore size zero for now.
518  const int size_var = interval_ct.interval().size();
519  if (initial_solution.solution(size_var) == 0) continue;
520 
521  const int start_var = interval_ct.interval().start();
522  const int64 start_value = initial_solution.solution(start_var);
523  start_interval_pairs.push_back({start_value, i});
524  }
525  std::sort(start_interval_pairs.begin(), start_interval_pairs.end());
526 
527  // Add precedence between the remaining intervals, forcing their order.
528  for (int i = 0; i + 1 < start_interval_pairs.size(); ++i) {
529  const int before_var =
530  neighborhood.cp_model.constraints(start_interval_pairs[i].second)
531  .interval()
532  .end();
533  const int after_var =
534  neighborhood.cp_model.constraints(start_interval_pairs[i + 1].second)
535  .interval()
536  .start();
537  CHECK_LE(initial_solution.solution(before_var),
538  initial_solution.solution(after_var));
539 
540  LinearConstraintProto* linear =
541  neighborhood.cp_model.add_constraints()->mutable_linear();
542  linear->add_domain(kint64min);
543  linear->add_domain(0);
544  linear->add_vars(before_var);
545  linear->add_coeffs(1);
546  linear->add_vars(after_var);
547  linear->add_coeffs(-1);
548  }
549  }
550 
551  // Set the current solution as a hint.
552  //
553  // TODO(user): Move to common function?
554  neighborhood.cp_model.clear_solution_hint();
555  for (int var = 0; var < neighborhood.cp_model.variables_size(); ++var) {
556  neighborhood.cp_model.mutable_solution_hint()->add_vars(var);
557  neighborhood.cp_model.mutable_solution_hint()->add_values(
558  initial_solution.solution(var));
559  }
560  neighborhood.is_generated = true;
561 
562  return neighborhood;
563 }
564 
566  const CpSolverResponse& initial_solution, double difficulty,
567  absl::BitGenRef random) {
568  const auto span = helper_.TypeToConstraints(ConstraintProto::kInterval);
569  std::vector<int> intervals_to_relax(span.begin(), span.end());
570  GetRandomSubset(difficulty, &intervals_to_relax, random);
571 
572  return GenerateSchedulingNeighborhoodForRelaxation(intervals_to_relax,
573  initial_solution, helper_);
574 }
575 
577  const CpSolverResponse& initial_solution, double difficulty,
578  absl::BitGenRef random) {
579  std::vector<std::pair<int64, int>> start_interval_pairs;
580  for (const int i : helper_.TypeToConstraints(ConstraintProto::kInterval)) {
581  const ConstraintProto& interval_ct = helper_.ModelProto().constraints(i);
582 
583  const int start_var = interval_ct.interval().start();
584  const int64 start_value = initial_solution.solution(start_var);
585  start_interval_pairs.push_back({start_value, i});
586  }
587  std::sort(start_interval_pairs.begin(), start_interval_pairs.end());
588  const int relaxed_size = std::floor(difficulty * start_interval_pairs.size());
589 
590  std::uniform_int_distribution<int> random_var(
591  0, start_interval_pairs.size() - relaxed_size - 1);
592  const int random_start_index = random_var(random);
593  std::vector<int> intervals_to_relax;
594  // TODO(user,user): Consider relaxing more than one time window intervals.
595  // This seems to help with Giza models.
596  for (int i = random_start_index; i < relaxed_size; ++i) {
597  intervals_to_relax.push_back(start_interval_pairs[i].second);
598  }
599  return GenerateSchedulingNeighborhoodForRelaxation(intervals_to_relax,
600  initial_solution, helper_);
601 }
602 
604  if (incomplete_solutions_ != nullptr) {
605  return incomplete_solutions_->HasNewSolution();
606  }
607 
608  if (response_manager_ != nullptr) {
609  if (response_manager_->SolutionsRepository().NumSolutions() == 0) {
610  return false;
611  }
612  }
613 
614  // At least one relaxation solution should be available to generate a
615  // neighborhood.
616  if (lp_solutions_ != nullptr && lp_solutions_->NumSolutions() > 0) {
617  return true;
618  }
619 
620  if (relaxation_solutions_ != nullptr &&
621  relaxation_solutions_->NumSolutions() > 0) {
622  return true;
623  }
624  return false;
625 }
626 
628  const CpSolverResponse& initial_solution, double difficulty,
629  absl::BitGenRef random) {
630  Neighborhood neighborhood = helper_.FullNeighborhood();
631  neighborhood.is_generated = false;
632 
633  const bool lp_solution_available =
634  (lp_solutions_ != nullptr && lp_solutions_->NumSolutions() > 0);
635 
636  const bool relaxation_solution_available =
637  (relaxation_solutions_ != nullptr &&
638  relaxation_solutions_->NumSolutions() > 0);
639 
640  const bool incomplete_solution_available =
641  (incomplete_solutions_ != nullptr &&
642  incomplete_solutions_->HasNewSolution());
643 
644  if (!lp_solution_available && !relaxation_solution_available &&
645  !incomplete_solution_available) {
646  return neighborhood;
647  }
648 
649  RINSNeighborhood rins_neighborhood;
650  // Randomly select the type of relaxation if both lp and relaxation solutions
651  // are available.
652  // TODO(user): Tune the probability value for this.
653  std::bernoulli_distribution random_bool(0.5);
654  const bool use_lp_relaxation =
655  (lp_solution_available && relaxation_solution_available)
656  ? random_bool(random)
657  : lp_solution_available;
658  if (use_lp_relaxation) {
659  rins_neighborhood =
660  GetRINSNeighborhood(response_manager_,
661  /*relaxation_solutions=*/nullptr, lp_solutions_,
662  incomplete_solutions_, random);
663  neighborhood.source_info =
664  incomplete_solution_available ? "incomplete" : "lp";
665  } else {
666  CHECK(relaxation_solution_available || incomplete_solution_available);
667  rins_neighborhood = GetRINSNeighborhood(
668  response_manager_, relaxation_solutions_,
669  /*lp_solutions=*/nullptr, incomplete_solutions_, random);
670  neighborhood.source_info =
671  incomplete_solution_available ? "incomplete" : "relaxation";
672  }
673 
674  if (rins_neighborhood.fixed_vars.empty() &&
675  rins_neighborhood.reduced_domain_vars.empty()) {
676  return neighborhood;
677  }
678 
679  // Fix the variables in the local model.
680  for (const std::pair</*model_var*/ int, /*value*/ int64> fixed_var :
681  rins_neighborhood.fixed_vars) {
682  const int var = fixed_var.first;
683  const int64 value = fixed_var.second;
684  if (var >= neighborhood.cp_model.variables_size()) continue;
685  if (!helper_.IsActive(var)) continue;
686 
687  const Domain domain =
688  ReadDomainFromProto(neighborhood.cp_model.variables(var));
689  if (!domain.Contains(value)) {
690  // TODO(user): Instead of aborting, pick the closest point in the domain?
691  return neighborhood;
692  }
693 
694  neighborhood.cp_model.mutable_variables(var)->clear_domain();
695  neighborhood.cp_model.mutable_variables(var)->add_domain(value);
696  neighborhood.cp_model.mutable_variables(var)->add_domain(value);
697  neighborhood.is_reduced = true;
698  }
699 
700  for (const std::pair</*model_var*/ int, /*domain*/ std::pair<int64, int64>>
701  reduced_var : rins_neighborhood.reduced_domain_vars) {
702  const int var = reduced_var.first;
703  const int64 lb = reduced_var.second.first;
704  const int64 ub = reduced_var.second.second;
705  if (var >= neighborhood.cp_model.variables_size()) continue;
706  if (!helper_.IsActive(var)) continue;
707  Domain domain = ReadDomainFromProto(neighborhood.cp_model.variables(var));
708  domain = domain.IntersectionWith(Domain(lb, ub));
709  if (domain.IsEmpty()) {
710  // TODO(user): Instead of aborting, pick the closest point in the domain?
711  return neighborhood;
712  }
713  FillDomainInProto(domain, neighborhood.cp_model.mutable_variables(var));
714  neighborhood.is_reduced = true;
715  }
716  neighborhood.is_generated = true;
717  return neighborhood;
718 }
719 
721  const CpSolverResponse& initial_solution, double difficulty,
722  absl::BitGenRef random) {
723  std::vector<int> removable_constraints;
724  const int num_constraints = helper_.ModelProto().constraints_size();
725  removable_constraints.reserve(num_constraints);
726  for (int c = 0; c < num_constraints; ++c) {
727  // Removing intervals is not easy because other constraint might require
728  // them, so for now, we don't remove them.
729  if (helper_.ModelProto().constraints(c).constraint_case() ==
730  ConstraintProto::kInterval) {
731  continue;
732  }
733  removable_constraints.push_back(c);
734  }
735 
736  const int target_size =
737  std::round((1.0 - difficulty) * removable_constraints.size());
738 
739  const int random_start_index =
740  absl::Uniform<int>(random, 0, removable_constraints.size());
741  std::vector<int> removed_constraints;
742  removed_constraints.reserve(target_size);
743  int c = random_start_index;
744  while (removed_constraints.size() < target_size) {
745  removed_constraints.push_back(removable_constraints[c]);
746  ++c;
747  if (c == removable_constraints.size()) {
748  c = 0;
749  }
750  }
751 
752  return helper_.RemoveMarkedConstraints(removed_constraints);
753 }
754 
757  NeighborhoodGeneratorHelper const* helper, const std::string& name)
758  : NeighborhoodGenerator(name, helper) {
759  std::vector<int> removable_constraints;
760  const int num_constraints = helper_.ModelProto().constraints_size();
761  constraint_weights_.reserve(num_constraints);
762  // TODO(user): Experiment with different starting weights.
763  for (int c = 0; c < num_constraints; ++c) {
764  switch (helper_.ModelProto().constraints(c).constraint_case()) {
765  case ConstraintProto::kCumulative:
766  case ConstraintProto::kAllDiff:
767  case ConstraintProto::kElement:
768  case ConstraintProto::kRoutes:
769  case ConstraintProto::kCircuit:
770  constraint_weights_.push_back(3.0);
771  num_removable_constraints_++;
772  break;
773  case ConstraintProto::kBoolOr:
774  case ConstraintProto::kBoolAnd:
775  case ConstraintProto::kBoolXor:
776  case ConstraintProto::kIntProd:
777  case ConstraintProto::kIntDiv:
778  case ConstraintProto::kIntMod:
779  case ConstraintProto::kIntMax:
780  case ConstraintProto::kLinMax:
781  case ConstraintProto::kIntMin:
782  case ConstraintProto::kLinMin:
783  case ConstraintProto::kNoOverlap:
784  case ConstraintProto::kNoOverlap2D:
785  constraint_weights_.push_back(2.0);
786  num_removable_constraints_++;
787  break;
788  case ConstraintProto::kLinear:
789  case ConstraintProto::kTable:
790  case ConstraintProto::kAutomaton:
791  case ConstraintProto::kInverse:
792  case ConstraintProto::kReservoir:
793  case ConstraintProto::kAtMostOne:
794  case ConstraintProto::kExactlyOne:
795  constraint_weights_.push_back(1.0);
796  num_removable_constraints_++;
797  break;
798  case ConstraintProto::CONSTRAINT_NOT_SET:
799  case ConstraintProto::kInterval:
800  // Removing intervals is not easy because other constraint might require
801  // them, so for now, we don't remove them.
802  constraint_weights_.push_back(0.0);
803  break;
804  }
805  }
806 }
807 
808 void WeightedRandomRelaxationNeighborhoodGenerator::
809  AdditionalProcessingOnSynchronize(const SolveData& solve_data) {
810  const IntegerValue best_objective_improvement =
811  solve_data.new_objective_bound - solve_data.initial_best_objective_bound;
812 
813  const std::vector<int>& removed_constraints =
814  removed_constraints_[solve_data.neighborhood_id];
815 
816  // Heuristic: We change the weights of the removed constraints if the
817  // neighborhood is solved (status is OPTIMAL or INFEASIBLE) or we observe an
818  // improvement in objective bounds. Otherwise we assume that the
819  // difficulty/time wasn't right for us to record feedbacks.
820  //
821  // If the objective bounds are improved, we bump up the weights. If the
822  // objective bounds are worse and the problem status is OPTIMAL, we bump down
823  // the weights. Otherwise if the new objective bounds are same as current
824  // bounds (which happens a lot on some instances), we do not update the
825  // weights as we do not have a clear signal whether the constraints removed
826  // were good choices or not.
827  // TODO(user): We can improve this heuristic with more experiments.
828  if (best_objective_improvement > 0) {
829  // Bump up the weights of all removed constraints.
830  for (int c : removed_constraints) {
831  if (constraint_weights_[c] <= 90.0) {
832  constraint_weights_[c] += 10.0;
833  } else {
834  constraint_weights_[c] = 100.0;
835  }
836  }
837  } else if (solve_data.status == CpSolverStatus::OPTIMAL &&
838  best_objective_improvement < 0) {
839  // Bump down the weights of all removed constraints.
840  for (int c : removed_constraints) {
841  if (constraint_weights_[c] > 0.5) {
842  constraint_weights_[c] -= 0.5;
843  }
844  }
845  }
846  removed_constraints_.erase(solve_data.neighborhood_id);
847 }
848 
850  const CpSolverResponse& initial_solution, double difficulty,
851  absl::BitGenRef random) {
852  const int target_size =
853  std::round((1.0 - difficulty) * num_removable_constraints_);
854 
855  std::vector<int> removed_constraints;
856 
857  // Generate a random number between (0,1) = u[i] and use score[i] =
858  // u[i]^(1/w[i]) and then select top k items with largest scores.
859  // Reference: https://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf
860  std::vector<std::pair<double, int>> constraint_removal_scores;
861  std::uniform_real_distribution<double> random_var(0.0, 1.0);
862  for (int c = 0; c < constraint_weights_.size(); ++c) {
863  if (constraint_weights_[c] <= 0) continue;
864  const double u = random_var(random);
865  const double score = std::pow(u, (1 / constraint_weights_[c]));
866  constraint_removal_scores.push_back({score, c});
867  }
868  std::sort(constraint_removal_scores.rbegin(),
869  constraint_removal_scores.rend());
870  for (int i = 0; i < target_size; ++i) {
871  removed_constraints.push_back(constraint_removal_scores[i].second);
872  }
873 
874  Neighborhood result = helper_.RemoveMarkedConstraints(removed_constraints);
875  absl::MutexLock mutex_lock(&mutex_);
876  result.id = next_available_id_;
877  next_available_id_++;
878  removed_constraints_.insert({result.id, removed_constraints});
879  return result;
880 }
881 
882 } // namespace sat
883 } // namespace operations_research
int64 min
Definition: alldiff_cst.cc:138
int64 max
Definition: alldiff_cst.cc:139
#define CHECK(condition)
Definition: base/logging.h:495
#define CHECK_LT(val1, val2)
Definition: base/logging.h:700
#define CHECK_EQ(val1, val2)
Definition: base/logging.h:697
#define CHECK_GE(val1, val2)
Definition: base/logging.h:701
#define CHECK_GT(val1, val2)
Definition: base/logging.h:702
#define DCHECK_GE(val1, val2)
Definition: base/logging.h:889
#define CHECK_LE(val1, val2)
Definition: base/logging.h:699
#define VLOG(verboselevel)
Definition: base/logging.h:978
void Update(int num_decreases, int num_increases)
We call domain any subset of Int64 = [kint64min, kint64max].
Domain IntersectionWith(const Domain &domain) const
Returns the intersection of D and domain.
bool IsEmpty() const
Returns true if this is the empty set.
bool Contains(int64 value) const
Returns true iff value is in Domain.
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
NeighborhoodGeneratorHelper(CpModelProto const *model_proto, SatParameters const *parameters, SharedResponseManager *shared_response, SharedTimeLimit *shared_time_limit=nullptr, SharedBoundsManager *shared_bounds=nullptr)
Definition: cp_model_lns.cc:32
const SharedResponseManager & shared_response() const
Definition: cp_model_lns.h:137
const std::vector< std::vector< int > > & VarToConstraint() const
Definition: cp_model_lns.h:113
Neighborhood FixAllVariables(const CpSolverResponse &initial_solution) const
Neighborhood FixGivenVariables(const CpSolverResponse &initial_solution, const std::vector< int > &variables_to_fix) const
const absl::Span< const int > TypeToConstraints(ConstraintProto::ConstraintCase type) const
Definition: cp_model_lns.h:118
Neighborhood RelaxGivenVariables(const CpSolverResponse &initial_solution, const std::vector< int > &relaxed_variables) const
const std::vector< int > & ActiveVariables() const
Definition: cp_model_lns.h:106
Neighborhood RemoveMarkedConstraints(const std::vector< int > &constraints_to_remove) const
const std::vector< std::vector< int > > & ConstraintToVar() const
Definition: cp_model_lns.h:110
double GetUCBScore(int64 total_num_calls) const
virtual void AdditionalProcessingOnSynchronize(const SolveData &solve_data)
Definition: cp_model_lns.h:318
const NeighborhoodGeneratorHelper & helper_
Definition: cp_model_lns.h:321
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
void GetChangedBounds(int id, std::vector< int > *variables, std::vector< int64 > *new_lower_bounds, std::vector< int64 > *new_upper_bounds)
const SharedSolutionRepository< int64 > & SolutionsRepository() const
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
WeightedRandomRelaxationNeighborhoodGenerator(NeighborhoodGeneratorHelper const *helper, const std::string &name)
Neighborhood Generate(const CpSolverResponse &initial_solution, double difficulty, absl::BitGenRef random) final
SatParameters parameters
CpModelProto const * model_proto
const std::string name
const Constraint * ct
int64 value
IntVar * var
Definition: expr_array.cc:1858
int64_t int64
static const int64 kint64min
std::vector< int > UsedVariables(const ConstraintProto &ct)
bool RefIsPositive(int ref)
void FillDomainInProto(const Domain &domain, ProtoWithDomain *proto)
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
Neighborhood GenerateSchedulingNeighborhoodForRelaxation(const absl::Span< const int > intervals_to_relax, const CpSolverResponse &initial_solution, const NeighborhoodGeneratorHelper &helper)
RINSNeighborhood GetRINSNeighborhood(const SharedResponseManager *response_manager, const SharedRelaxationSolutionRepository *relaxation_solutions, const SharedLPSolutionRepository *lp_solutions, SharedIncompleteSolutionManager *incomplete_solutions, absl::BitGenRef random)
Definition: rins.cc:99
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...
int64 CapSub(int64 x, int64 y)
std::vector< std::pair< int, std::pair< int64, int64 > > > reduced_domain_vars
Definition: rins.h:60
std::vector< std::pair< int, int64 > > fixed_vars
Definition: rins.h:58
#define VLOG_IS_ON(verboselevel)
Definition: vlog_is_on.h:41