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