Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cp_model_lns.cc
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
15
16#include <algorithm>
17#include <cmath>
18#include <cstdint>
19#include <deque>
20#include <functional>
21#include <limits>
22#include <memory>
23#include <random>
24#include <string>
25#include <tuple>
26#include <utility>
27#include <vector>
28
29#include "absl/algorithm/container.h"
30#include "absl/base/log_severity.h"
31#include "absl/container/flat_hash_map.h"
32#include "absl/container/flat_hash_set.h"
33#include "absl/flags/flag.h"
34#include "absl/log/check.h"
35#include "absl/log/log.h"
36#include "absl/log/vlog_is_on.h"
37#include "absl/meta/type_traits.h"
38#include "absl/random/bit_gen_ref.h"
39#include "absl/random/distributions.h"
40#include "absl/strings/str_cat.h"
41#include "absl/strings/str_join.h"
42#include "absl/synchronization/mutex.h"
43#include "absl/types/span.h"
44#include "google/protobuf/arena.h"
55#include "ortools/sat/model.h"
57#include "ortools/sat/rins.h"
61#include "ortools/sat/util.h"
63#include "ortools/util/bitset.h"
69
70namespace operations_research {
71namespace sat {
72
74 CpModelProto const* model_proto, SatParameters const* parameters,
76 ModelSharedTimeLimit* global_time_limit, SharedBoundsManager* shared_bounds)
77 : SubSolver("neighborhood_helper", HELPER),
78 parameters_(*parameters),
79 model_proto_(*model_proto),
80 shared_bounds_(shared_bounds),
81 global_time_limit_(global_time_limit),
82 shared_response_(shared_response) {
83 // Initialize proto memory.
84 local_arena_storage_.assign(Neighborhood::kDefaultArenaSizePerVariable *
85 model_proto_.variables_size(),
86 0);
87 local_arena_ = std::make_unique<google::protobuf::Arena>(
88 local_arena_storage_.data(), local_arena_storage_.size());
89 simplified_model_proto_ =
90 google::protobuf::Arena::Create<CpModelProto>(local_arena_.get());
91
92 CHECK(shared_response_ != nullptr);
93 if (shared_bounds_ != nullptr) {
94 shared_bounds_id_ = shared_bounds_->RegisterNewId();
95 }
96 *model_proto_with_only_variables_.mutable_variables() =
97 model_proto_.variables();
98 InitializeHelperData();
99 RecomputeHelperData();
100 Synchronize();
101}
102
104 if (shared_response_->ProblemIsSolved() ||
105 global_time_limit_->LimitReached()) {
106 return;
107 }
108 if (shared_bounds_ != nullptr) {
109 std::vector<int> model_variables;
110 std::vector<int64_t> new_lower_bounds;
111 std::vector<int64_t> new_upper_bounds;
112 shared_bounds_->GetChangedBounds(shared_bounds_id_, &model_variables,
113 &new_lower_bounds, &new_upper_bounds);
114
115 bool new_variables_have_been_fixed = false;
116
117 if (!model_variables.empty()) {
118 absl::MutexLock domain_lock(domain_mutex_);
119
120 for (int i = 0; i < model_variables.size(); ++i) {
121 const int var = model_variables[i];
122 const int64_t new_lb = new_lower_bounds[i];
123 const int64_t new_ub = new_upper_bounds[i];
124 if (VLOG_IS_ON(3)) {
125 const auto& domain =
126 model_proto_with_only_variables_.variables(var).domain();
127 const int64_t old_lb = domain.Get(0);
128 const int64_t old_ub = domain.Get(domain.size() - 1);
129 VLOG(3) << "Variable: " << var << " old domain: [" << old_lb << ", "
130 << old_ub << "] new domain: [" << new_lb << ", " << new_ub
131 << "]";
132 }
133 const Domain old_domain = ReadDomainFromProto(
134 model_proto_with_only_variables_.variables(var));
135 const Domain new_domain =
136 old_domain.IntersectionWith(Domain(new_lb, new_ub));
137 if (new_domain.IsEmpty()) {
138 // This can mean two things:
139 // 1/ This variable is a normal one and the problem is UNSAT or
140 // 2/ This variable is optional, and its associated literal must be
141 // set to false.
142 //
143 // Currently, we wait for any full solver to pick the crossing bounds
144 // and do the correct stuff on their own. We do not want to have empty
145 // domain in the proto as this would means INFEASIBLE. So we just
146 // ignore such bounds here.
147 //
148 // TODO(user): We could set the optional literal to false directly in
149 // the bound sharing manager. We do have to be careful that all the
150 // different solvers have the same optionality definition though.
151 continue;
152 }
154 new_domain,
155 model_proto_with_only_variables_.mutable_variables(var));
156 new_variables_have_been_fixed |= new_domain.IsFixed();
157 }
158 }
159
160 // Only trigger the computation if needed.
161 if (new_variables_have_been_fixed) {
162 RecomputeHelperData();
163 }
164 }
165}
166
167bool NeighborhoodGeneratorHelper::ObjectiveDomainIsConstraining() const {
168 if (!model_proto_.has_objective()) return false;
169 if (model_proto_.objective().domain().empty()) return false;
170
171 int64_t min_activity = 0;
172 int64_t max_activity = 0;
173 const int num_terms = model_proto_.objective().vars().size();
174 for (int i = 0; i < num_terms; ++i) {
175 const int var = PositiveRef(model_proto_.objective().vars(i));
176 const int64_t coeff = model_proto_.objective().coeffs(i);
177 const auto& var_domain =
178 model_proto_with_only_variables_.variables(var).domain();
179 const int64_t v1 = coeff * var_domain[0];
180 const int64_t v2 = coeff * var_domain[var_domain.size() - 1];
181 min_activity += std::min(v1, v2);
182 max_activity += std::max(v1, v2);
183 }
184
185 const Domain obj_domain = ReadDomainFromProto(model_proto_.objective());
186 const Domain inferred_domain =
187 Domain(min_activity, max_activity)
189 Domain(std::numeric_limits<int64_t>::min(), obj_domain.Max()));
190 return !inferred_domain.IsIncludedIn(obj_domain);
191}
192
193void NeighborhoodGeneratorHelper::InitializeHelperData() {
194 type_to_constraints_.clear();
195 const int num_constraints = model_proto_.constraints_size();
196 for (int c = 0; c < num_constraints; ++c) {
197 const int type = model_proto_.constraints(c).constraint_case();
198 if (type >= type_to_constraints_.size()) {
199 type_to_constraints_.resize(type + 1);
200 }
201 type_to_constraints_[type].push_back(c);
202 }
203
204 const int num_variables = model_proto_.variables().size();
205 is_in_objective_.resize(num_variables, false);
206 has_positive_objective_coefficient_.resize(num_variables, false);
207 if (model_proto_.has_objective()) {
208 for (int i = 0; i < model_proto_.objective().vars_size(); ++i) {
209 const int ref = model_proto_.objective().vars(i);
210 const int64_t coeff = model_proto_.objective().coeffs(i);
211 DCHECK_NE(coeff, 0);
212 is_in_objective_[PositiveRef(ref)] = true;
213 has_positive_objective_coefficient_[PositiveRef(ref)] =
214 ref == PositiveRef(ref) ? coeff > 0 : coeff < 0;
215 }
216 }
217}
218
219// Recompute all the data when new variables have been fixed. Note that this
220// shouldn't be called if there is no change as it is in O(problem size).
221void NeighborhoodGeneratorHelper::RecomputeHelperData() {
222 absl::MutexLock graph_lock(graph_mutex_);
223 absl::ReaderMutexLock domain_lock(domain_mutex_);
224
225 // Do basic presolving to have a more precise graph.
226 // Here we just remove trivially true constraints.
227 //
228 // Note(user): We do that each time a new variable is fixed. It might be too
229 // much, but on the miplib and in 1200s, we do that only about 1k time on the
230 // worst case problem.
231 //
232 // TODO(user): Change API to avoid a few copy?
233 // TODO(user): We could keep the context in the class.
234 // TODO(user): We can also start from the previous simplified model instead.
235 {
236 Model local_model;
237 CpModelProto mapping_proto;
238 // We want to replace the simplified_model_proto_ by a new one. Since
239 // deleting an object in the arena doesn't free the memory, we also delete
240 // and recreate the arena, but reusing the same storage.
241 int64_t new_size = local_arena_->SpaceUsed();
242 new_size += new_size / 2;
243 simplified_model_proto_->Clear();
244 local_arena_.reset();
245 local_arena_storage_.resize(new_size);
246 local_arena_ = std::make_unique<google::protobuf::Arena>(
247 local_arena_storage_.data(), local_arena_storage_.size());
248 simplified_model_proto_ =
249 google::protobuf::Arena::Create<CpModelProto>(local_arena_.get());
250 *simplified_model_proto_->mutable_variables() =
251 model_proto_with_only_variables_.variables();
252 PresolveContext context(&local_model, simplified_model_proto_,
253 &mapping_proto);
254 ModelCopy copier(&context);
255
256 // TODO(user): Not sure what to do if the model is UNSAT.
257 // This shouldn't matter as it should be dealt with elsewhere.
258 copier.ImportAndSimplifyConstraints(model_proto_, {});
259 }
260
261 // Compute the constraint <-> variable graph.
262 //
263 // TODO(user): Remove duplicate constraints?
264 const auto& constraints = simplified_model_proto_->constraints();
265 constraint_to_var_.clear();
266 constraint_to_var_.reserve(constraints.size());
267 for (int ct_index = 0; ct_index < constraints.size(); ++ct_index) {
268 // We remove the interval constraints since we should have an equivalent
269 // linear constraint somewhere else. This is not the case if we have a fixed
270 // size optional interval variable. But it should not matter as the
271 // intervals are replaced by their underlying variables in the scheduling
272 // constraints.
273 if (constraints[ct_index].constraint_case() == ConstraintProto::kInterval) {
274 continue;
275 }
276
277 tmp_row_.clear();
278 for (const int var : UsedVariables(constraints[ct_index])) {
279 if (IsConstant(var)) continue;
280 tmp_row_.push_back(var);
281 }
282
283 // We replace intervals by their underlying integer variables. Note that
284 // this is needed for a correct decomposition into independent part.
285 bool need_sort = false;
286 for (const int interval : UsedIntervals(constraints[ct_index])) {
287 need_sort = true;
288 for (const int var : UsedVariables(constraints[interval])) {
289 if (IsConstant(var)) continue;
290 tmp_row_.push_back(var);
291 }
292 }
293
294 // We remove constraint of size 0 and 1 since they are not useful for LNS
295 // based on this graph.
296 if (tmp_row_.size() <= 1) {
297 continue;
298 }
299
300 // Keep this constraint.
301 if (need_sort) {
303 }
304 constraint_to_var_.Add(tmp_row_);
305 }
306
307 // Initialize var to constraints, and make sure it has an entry for all
308 // variables.
309 var_to_constraint_.ResetFromTranspose(
310 constraint_to_var_,
311 /*min_transpose_size=*/model_proto_.variables().size());
312
313 // We mark as active all non-constant variables.
314 // Non-active variable will never be fixed in standard LNS fragment.
315 active_variables_.clear();
316 const int num_variables = model_proto_.variables_size();
317 active_variables_set_.assign(num_variables, false);
318 for (int i = 0; i < num_variables; ++i) {
319 if (!IsConstant(i)) {
320 active_variables_.push_back(i);
321 active_variables_set_[i] = true;
322 }
323 }
324
325 active_objective_variables_.clear();
326 for (const int var : model_proto_.objective().vars()) {
327 DCHECK(RefIsPositive(var));
328 if (active_variables_set_[var]) {
329 active_objective_variables_.push_back(var);
330 }
331 }
332
333 // Compute connected components.
334 // Note that fixed variable are just ignored.
335 DenseConnectedComponentsFinder union_find;
336 union_find.SetNumberOfNodes(num_variables);
337 for (int c = 0; c < constraint_to_var_.size(); ++c) {
338 const auto row = constraint_to_var_[c];
339 if (row.size() <= 1) continue;
340 for (int i = 1; i < row.size(); ++i) {
341 union_find.AddEdge(row[0], row[i]);
342 }
343 }
344
345 // If we have a lower bound on the objective, then this "objective constraint"
346 // might link components together.
347 if (ObjectiveDomainIsConstraining()) {
348 const auto& refs = model_proto_.objective().vars();
349 const int num_terms = refs.size();
350 for (int i = 1; i < num_terms; ++i) {
351 union_find.AddEdge(PositiveRef(refs[0]), PositiveRef(refs[i]));
352 }
353 }
354
355 // Compute all components involving non-fixed variables.
356 //
357 // TODO(user): If a component has no objective, we can fix it to any feasible
358 // solution. This will automatically be done by LNS fragment covering such
359 // component though.
360 components_.clear();
361 var_to_component_index_.assign(num_variables, -1);
362 for (int var = 0; var < num_variables; ++var) {
363 if (IsConstant(var)) continue;
364 const int root = union_find.FindRoot(var);
365 DCHECK_LT(root, var_to_component_index_.size());
366 int& index = var_to_component_index_[root];
367 if (index == -1) {
368 index = components_.size();
369 components_.push_back({});
370 }
371 var_to_component_index_[var] = index;
372 components_[index].push_back(var);
373 }
374
375 // Display information about the reduced problem.
376 //
377 // TODO(user): Exploit connected component while generating fragments.
378 // TODO(user): Do not generate fragment not touching the objective.
379 if (!shared_response_->LoggingIsEnabled()) return;
380
381 std::vector<int> component_sizes;
382 for (const std::vector<int>& component : components_) {
383 component_sizes.push_back(component.size());
384 }
385 std::sort(component_sizes.begin(), component_sizes.end(),
386 std::greater<int>());
387 std::string compo_message;
388 if (component_sizes.size() > 1) {
389 if (component_sizes.size() <= 10) {
390 compo_message =
391 absl::StrCat(" compo:", absl::StrJoin(component_sizes, ","));
392 } else {
393 component_sizes.resize(10);
394 compo_message =
395 absl::StrCat(" compo:", absl::StrJoin(component_sizes, ","), ",...");
396 }
397 }
398
399 // TODO(user): This is not ideal, as if two reductions appears in a row and
400 // nothing else is done for a while, we will never see the "latest" size
401 // in the log until it is reduced again.
402 shared_response_->LogMessageWithThrottling(
403 "Model", absl::StrCat("var:", active_variables_.size(), "/",
404 num_variables, " constraints:",
405 simplified_model_proto_->constraints().size(), "/",
406 model_proto_.constraints().size(), compo_message));
407}
408
410 return active_variables_set_[var];
411}
412
413bool NeighborhoodGeneratorHelper::IsConstant(int var) const {
414 const auto& var_proto = model_proto_with_only_variables_.variables(var);
415 return var_proto.domain_size() == 2 &&
416 var_proto.domain(0) == var_proto.domain(1);
417}
418
420 Neighborhood neighborhood;
421 neighborhood.is_reduced = false;
422 neighborhood.is_generated = true;
423 {
424 absl::ReaderMutexLock lock(domain_mutex_);
425 *neighborhood.delta.mutable_variables() =
426 model_proto_with_only_variables_.variables();
427 }
428 return neighborhood;
429}
430
432 Neighborhood neighborhood;
433 neighborhood.is_generated = false;
434 return neighborhood;
435}
436
437bool NeighborhoodGeneratorHelper::IntervalIsActive(
438 int index, const CpSolverResponse& initial_solution) const {
439 const ConstraintProto& interval_ct = ModelProto().constraints(index);
440 // We only look at intervals that are performed in the solution. The
441 // unperformed intervals should be automatically freed during the generation
442 // phase.
443 if (interval_ct.enforcement_literal().size() == 1) {
444 const int enforcement_ref = interval_ct.enforcement_literal(0);
445 const int enforcement_var = PositiveRef(enforcement_ref);
446 const int value = initial_solution.solution(enforcement_var);
447 if (RefIsPositive(enforcement_ref) == (value == 0)) return false;
448 }
449
450 for (const int v : interval_ct.interval().start().vars()) {
451 if (!IsConstant(v)) return true;
452 }
453 for (const int v : interval_ct.interval().size().vars()) {
454 if (!IsConstant(v)) return true;
455 }
456 for (const int v : interval_ct.interval().end().vars()) {
457 if (!IsConstant(v)) return true;
458 }
459 return false;
460}
461
463 absl::Span<const int> unfiltered_intervals,
464 const CpSolverResponse& initial_solution) const {
465 std::vector<int> filtered_intervals;
466 filtered_intervals.reserve(unfiltered_intervals.size());
467 absl::ReaderMutexLock lock(domain_mutex_);
468 for (const int i : unfiltered_intervals) {
469 if (IntervalIsActive(i, initial_solution)) filtered_intervals.push_back(i);
470 }
471 return filtered_intervals;
472}
473
475 const CpSolverResponse& initial_solution) const {
477 initial_solution);
478}
479
480std::vector<NeighborhoodGeneratorHelper::ActiveRectangle>
482 const CpSolverResponse& initial_solution) const {
483 const std::vector<int> active_intervals =
484 GetActiveIntervals(initial_solution);
485 const absl::flat_hash_set<int> active_intervals_set(active_intervals.begin(),
486 active_intervals.end());
487
488 absl::flat_hash_map<std::pair<int, int>, std::vector<int>> active_rectangles;
489 for (const int ct_index : TypeToConstraints(ConstraintProto::kNoOverlap2D)) {
491 model_proto_.constraints(ct_index).no_overlap_2d();
492 for (int i = 0; i < ct.x_intervals_size(); ++i) {
493 const int x_i = ct.x_intervals(i);
494 const int y_i = ct.y_intervals(i);
495 if (active_intervals_set.contains(x_i) ||
496 active_intervals_set.contains(y_i)) {
497 active_rectangles[{x_i, y_i}].push_back(ct_index);
498 }
499 }
500 }
501
502 std::vector<ActiveRectangle> results;
503 results.reserve(active_rectangles.size());
504 for (const auto& [rectangle, no_overlap_2d_constraints] : active_rectangles) {
505 ActiveRectangle& result = results.emplace_back();
506 result.x_interval = rectangle.first;
507 result.y_interval = rectangle.second;
508 result.no_overlap_2d_constraints = {no_overlap_2d_constraints.begin(),
509 no_overlap_2d_constraints.end()};
510 }
511 return results;
512}
513
514std::vector<std::vector<int>>
516 std::vector<std::vector<int>> intervals_in_constraints;
517 absl::flat_hash_set<std::vector<int>> added_intervals_sets;
518 const auto add_interval_list_only_once =
519 [&intervals_in_constraints,
520 &added_intervals_sets](const auto& intervals) {
521 std::vector<int> candidate({intervals.begin(), intervals.end()});
523 if (added_intervals_sets.insert(candidate).second) {
524 intervals_in_constraints.push_back(candidate);
525 }
526 };
527 for (const int ct_index : TypeToConstraints(ConstraintProto::kNoOverlap)) {
528 add_interval_list_only_once(
529 model_proto_.constraints(ct_index).no_overlap().intervals());
530 }
531 for (const int ct_index : TypeToConstraints(ConstraintProto::kCumulative)) {
532 add_interval_list_only_once(
533 model_proto_.constraints(ct_index).cumulative().intervals());
534 }
535 for (const int ct_index : TypeToConstraints(ConstraintProto::kNoOverlap2D)) {
536 add_interval_list_only_once(
537 model_proto_.constraints(ct_index).no_overlap_2d().x_intervals());
538 add_interval_list_only_once(
539 model_proto_.constraints(ct_index).no_overlap_2d().y_intervals());
540 }
541 return intervals_in_constraints;
542}
543
544namespace {
545
546int64_t GetLinearExpressionValue(const LinearExpressionProto& expr,
547 const CpSolverResponse& initial_solution) {
548 int64_t result = expr.offset();
549 for (int i = 0; i < expr.vars_size(); ++i) {
550 result += expr.coeffs(i) * initial_solution.solution(expr.vars(i));
551 }
552 return result;
553}
554
555void RestrictAffineExpression(const LinearExpressionProto& expr,
556 const Domain& restriction,
557 CpModelProto* mutable_proto) {
558 CHECK_LE(expr.vars().size(), 1);
559 if (expr.vars().empty()) return;
560 const Domain implied_domain = restriction.AdditionWith(Domain(-expr.offset()))
561 .InverseMultiplicationBy(expr.coeffs(0));
562 const Domain domain =
563 ReadDomainFromProto(mutable_proto->variables(expr.vars(0)))
564 .IntersectionWith(implied_domain);
565 if (!domain.IsEmpty()) {
566 FillDomainInProto(domain, mutable_proto->mutable_variables(expr.vars(0)));
567 }
568}
569
570struct StartEndIndex {
571 int64_t start;
572 int64_t end;
573 int index_in_input_vector;
574 double noise;
575 bool operator<(const StartEndIndex& o) const {
576 return std::tie(start, end, noise, index_in_input_vector) <
577 std::tie(o.start, o.end, o.noise, o.index_in_input_vector);
578 }
579};
580
581struct TimePartition {
582 std::vector<int> indices_before_selected;
583 std::vector<int> selected_indices;
584 std::vector<int> indices_after_selected;
585};
586
587// Selects all intervals in a random time window to meet the difficulty
588// requirement.
589TimePartition PartitionIndicesAroundRandomTimeWindow(
590 absl::Span<const int> intervals, const CpModelProto& model_proto,
591 const CpSolverResponse& initial_solution, double difficulty,
592 absl::BitGenRef random) {
593 std::vector<StartEndIndex> start_end_indices;
594 for (int index = 0; index < intervals.size(); ++index) {
595 const int interval = intervals[index];
596 const ConstraintProto& interval_ct = model_proto.constraints(interval);
597 const int64_t start_value = GetLinearExpressionValue(
598 interval_ct.interval().start(), initial_solution);
599 const int64_t end_value = GetLinearExpressionValue(
600 interval_ct.interval().end(), initial_solution);
601 start_end_indices.push_back(
602 {start_value, end_value, index, absl::Uniform(random, 0., 1.0)});
603 }
604
605 if (start_end_indices.empty()) return {};
606
607 std::sort(start_end_indices.begin(), start_end_indices.end());
608 const int relaxed_size = std::floor(difficulty * start_end_indices.size());
609
610 std::uniform_int_distribution<int> random_var(
611 0, start_end_indices.size() - relaxed_size - 1);
612 // TODO(user): Consider relaxing more than one time window
613 // intervals. This seems to help with Giza models.
614 const int random_start_index = random_var(random);
615
616 // We want to minimize the time window relaxed, so we now sort the interval
617 // after the first selected intervals by end value.
618 // TODO(user): We could do things differently (include all tasks <= some
619 // end). The difficulty is that the number of relaxed tasks will differ from
620 // the target. We could also tie break tasks randomly.
621 std::sort(start_end_indices.begin() + random_start_index,
622 start_end_indices.end(),
623 [](const StartEndIndex& a, const StartEndIndex& b) {
624 return std::tie(a.end, a.noise, a.index_in_input_vector) <
625 std::tie(b.end, b.noise, b.index_in_input_vector);
626 });
627 TimePartition result;
628 int i = 0;
629 for (; i < random_start_index; ++i) {
630 result.indices_before_selected.push_back(
631 start_end_indices[i].index_in_input_vector);
632 }
633 for (; i < random_start_index + relaxed_size; ++i) {
634 result.selected_indices.push_back(
635 start_end_indices[i].index_in_input_vector);
636 }
637 for (; i < start_end_indices.size(); ++i) {
638 result.indices_after_selected.push_back(
639 start_end_indices[i].index_in_input_vector);
640 }
641 return result;
642}
643
644struct Demand {
645 int interval_index;
646 int64_t start;
647 int64_t end;
648 int64_t height;
649
650 // Because of the binary splitting of the capacity in the procedure used to
651 // extract precedences out of a cumulative constraint, processing bigger
652 // heights first will decrease its probability of being split across the 2
653 // halves of the current split.
654 bool operator<(const Demand& other) const {
655 return std::tie(start, height, end) <
656 std::tie(other.start, other.height, other.end);
657 }
658
659 std::string DebugString() const {
660 return absl::StrCat("{i=", interval_index, " span=[", start, ",", end, "]",
661 " d=", height, "}");
662 }
663};
664
665void InsertPrecedencesFromSortedListOfNonOverlapingIntervals(
666 const std::vector<Demand>& demands,
667 absl::flat_hash_set<std::pair<int, int>>* precedences) {
668 for (int i = 0; i + 1 < demands.size(); ++i) {
669 DCHECK_LE(demands[i].end, demands[i + 1].start);
670 precedences->insert(
671 {demands[i].interval_index, demands[i + 1].interval_index});
672 }
673}
674
675bool IsPresent(const ConstraintProto& interval_ct,
676 const CpSolverResponse& initial_solution) {
677 if (interval_ct.enforcement_literal().size() != 1) return true;
678
679 const int enforcement_ref = interval_ct.enforcement_literal(0);
680 const int enforcement_var = PositiveRef(enforcement_ref);
681 const int64_t value = initial_solution.solution(enforcement_var);
682 return RefIsPositive(enforcement_ref) == (value == 1);
683}
684
685void InsertNoOverlapPrecedences(
686 const absl::flat_hash_set<int>& ignored_intervals,
687 const CpSolverResponse& initial_solution, const CpModelProto& model_proto,
688 int no_overlap_index,
689 absl::flat_hash_set<std::pair<int, int>>* precedences) {
690 std::vector<Demand> demands;
691 const NoOverlapConstraintProto& no_overlap =
692 model_proto.constraints(no_overlap_index).no_overlap();
693 for (const int interval_index : no_overlap.intervals()) {
694 if (ignored_intervals.contains(interval_index)) continue;
695 const ConstraintProto& interval_ct =
696 model_proto.constraints(interval_index);
697 if (!IsPresent(interval_ct, initial_solution)) continue;
698
699 const int64_t start_value = GetLinearExpressionValue(
700 interval_ct.interval().start(), initial_solution);
701 const int64_t end_value = GetLinearExpressionValue(
702 interval_ct.interval().end(), initial_solution);
703 DCHECK_LE(start_value, end_value);
704 demands.push_back({interval_index, start_value, end_value, 1});
705 }
706
707 // TODO(user): We actually only need interval_index, start.
708 // No need to fill the other fields here.
709 std::sort(demands.begin(), demands.end());
710 InsertPrecedencesFromSortedListOfNonOverlapingIntervals(demands, precedences);
711}
712
713void ProcessDemandListFromCumulativeConstraint(
714 const std::vector<Demand>& demands, int64_t capacity,
715 std::deque<std::pair<std::vector<Demand>, int64_t>>* to_process,
716 absl::BitGenRef random,
717 absl::flat_hash_set<std::pair<int, int>>* precedences) {
718 if (demands.size() <= 1) return;
719
720 // Checks if any pairs of tasks cannot overlap.
721 int64_t sum_of_min_two_capacities = 2;
722 if (capacity > 1) {
723 int64_t min1 = std::numeric_limits<int64_t>::max();
724 int64_t min2 = std::numeric_limits<int64_t>::max();
725 for (const Demand& demand : demands) {
726 if (demand.height <= min1) {
727 min2 = min1;
728 min1 = demand.height;
729 } else if (demand.height < min2) {
730 min2 = demand.height;
731 }
732 }
733 sum_of_min_two_capacities = min1 + min2;
734 }
735
736 DCHECK_GT(sum_of_min_two_capacities, 1);
737 if (sum_of_min_two_capacities > capacity) {
738 InsertPrecedencesFromSortedListOfNonOverlapingIntervals(demands,
739 precedences);
740 return;
741 }
742
743 std::vector<int64_t> unique_starts;
744 for (const Demand& demand : demands) {
745 DCHECK(unique_starts.empty() || demand.start >= unique_starts.back());
746 if (unique_starts.empty() || unique_starts.back() < demand.start) {
747 unique_starts.push_back(demand.start);
748 }
749 }
750 DCHECK(std::is_sorted(unique_starts.begin(), unique_starts.end()));
751 const int num_points = unique_starts.size();
752
753 // Split the capacity in 2 and dispatch all demands on the 2 parts.
754 const int64_t capacity1 = capacity / 2;
755 std::vector<int64_t> usage1(num_points);
756 std::vector<Demand> demands1;
757
758 const int64_t capacity2 = capacity - capacity1;
759 std::vector<int64_t> usage2(num_points);
760 std::vector<Demand> demands2;
761
762 int usage_index = 0;
763 for (const Demand& d : demands) {
764 // Since we process demand by increasing start, the usage_index only
765 // need to increase.
766 while (usage_index < num_points && unique_starts[usage_index] < d.start) {
767 usage_index++;
768 }
769 DCHECK_LT(usage_index, num_points);
770 DCHECK_EQ(unique_starts[usage_index], d.start);
771 const int64_t slack1 = capacity1 - usage1[usage_index];
772 const int64_t slack2 = capacity2 - usage2[usage_index];
773
774 // We differ from the ICAPS article. If it fits in both sub-cumulatives, We
775 // choose the smallest slack. If it fits into at most one, we choose the
776 // biggest slack. If both slacks are equal, we choose randomly.
777 const bool prefer2 =
778 slack1 == slack2
779 ? absl::Bernoulli(random, 0.5)
780 : (d.height <= std::min(slack1, slack2) ? slack2 < slack1
781 : slack2 > slack1);
782
783 auto& selected_usage = prefer2 ? usage2 : usage1;
784 auto& residual_usage = prefer2 ? usage1 : usage2;
785 std::vector<Demand>& selected_demands = prefer2 ? demands2 : demands1;
786 std::vector<Demand>& residual_demands = prefer2 ? demands1 : demands2;
787 const int64_t selected_slack = prefer2 ? slack2 : slack1;
788
789 const int64_t assigned_to_selected = std::min(selected_slack, d.height);
790 DCHECK_GT(assigned_to_selected, 0);
791 for (int i = usage_index; i < num_points; ++i) {
792 if (d.end <= unique_starts[i]) break;
793 selected_usage[i] += assigned_to_selected;
794 }
795 selected_demands.push_back(
796 {d.interval_index, d.start, d.end, assigned_to_selected});
797
798 if (d.height > selected_slack) {
799 const int64_t residual = d.height - selected_slack;
800 DCHECK_GT(residual, 0);
801 DCHECK_LE(residual, prefer2 ? slack1 : slack2);
802 for (int i = usage_index; i < num_points; ++i) {
803 if (d.end <= unique_starts[i]) break;
804 residual_usage[i] += residual;
805 }
806 residual_demands.push_back({d.interval_index, d.start, d.end, residual});
807 }
808 }
809
810 if (demands1.size() > 1) {
811 to_process->emplace_back(std::move(demands1), capacity1);
812 }
813 if (demands2.size() > 1) {
814 to_process->emplace_back(std::move(demands2), capacity2);
815 }
816}
817
818void InsertCumulativePrecedences(
819 const absl::flat_hash_set<int>& ignored_intervals,
820 const CpSolverResponse& initial_solution, const CpModelProto& model_proto,
821 int cumulative_index, absl::BitGenRef random,
822 absl::flat_hash_set<std::pair<int, int>>* precedences) {
823 const CumulativeConstraintProto& cumulative =
824 model_proto.constraints(cumulative_index).cumulative();
825
826 std::vector<Demand> demands;
827 for (int i = 0; i < cumulative.intervals().size(); ++i) {
828 const int interval_index = cumulative.intervals(i);
829 if (ignored_intervals.contains(interval_index)) continue;
830 const ConstraintProto& interval_ct =
831 model_proto.constraints(interval_index);
832 if (!IsPresent(interval_ct, initial_solution)) continue;
833
834 const int64_t start_value = GetLinearExpressionValue(
835 interval_ct.interval().start(), initial_solution);
836 const int64_t end_value = GetLinearExpressionValue(
837 interval_ct.interval().end(), initial_solution);
838 const int64_t demand_value =
839 GetLinearExpressionValue(cumulative.demands(i), initial_solution);
840 if (start_value == end_value || demand_value == 0) continue;
841
842 demands.push_back({interval_index, start_value, end_value, demand_value});
843 }
844 std::sort(demands.begin(), demands.end());
845
846 if (demands.empty()) return;
847
848 const int64_t capacity_value =
849 GetLinearExpressionValue(cumulative.capacity(), initial_solution);
850 DCHECK_GT(capacity_value, 0);
851
852 // Copying all these demands is memory intensive. Let's be careful here.
853 std::deque<std::pair<std::vector<Demand>, int64_t>> to_process;
854 to_process.emplace_back(std::move(demands), capacity_value);
855
856 while (!to_process.empty()) {
857 auto& next_task = to_process.front();
858 ProcessDemandListFromCumulativeConstraint(next_task.first,
859 /*capacity=*/next_task.second,
860 &to_process, random, precedences);
861 to_process.pop_front();
862 }
863}
864
865struct IndexedRectangle {
866 int interval_index;
867 Rectangle r;
868
869 bool operator<(const IndexedRectangle& other) const {
870 return std::tie(r.x_min, r.x_max) < std::tie(other.r.x_min, other.r.x_max);
871 }
872};
873
874void InsertRectanglePredecences(
875 absl::Span<const IndexedRectangle> rectangles,
876 absl::flat_hash_set<std::pair<int, int>>* precedences) {
877 // TODO(user): Refine set of interesting points.
878 std::vector<IntegerValue> interesting_points;
879 for (const IndexedRectangle& idx_r : rectangles) {
880 interesting_points.push_back(idx_r.r.y_max - 1);
881 }
882 gtl::STLSortAndRemoveDuplicates(&interesting_points);
883 std::vector<Demand> demands;
884 for (const IntegerValue t : interesting_points) {
885 demands.clear();
886 for (const IndexedRectangle& idx_r : rectangles) {
887 if (idx_r.r.y_min > t || idx_r.r.y_max <= t) continue;
888 demands.push_back({idx_r.interval_index, idx_r.r.x_min.value(),
889 idx_r.r.x_max.value(), 1});
890 }
891 std::sort(demands.begin(), demands.end());
892 InsertPrecedencesFromSortedListOfNonOverlapingIntervals(demands,
893 precedences);
894 }
895}
896
897void InsertNoOverlap2dPrecedences(
898 const absl::flat_hash_set<int>& ignored_intervals,
899 const CpSolverResponse& initial_solution, const CpModelProto& model_proto,
900 int no_overlap_2d_index,
901 absl::flat_hash_set<std::pair<int, int>>* precedences) {
902 std::vector<Demand> demands;
903 const NoOverlap2DConstraintProto& no_overlap_2d =
904 model_proto.constraints(no_overlap_2d_index).no_overlap_2d();
905 std::vector<IndexedRectangle> x_main;
906 std::vector<IndexedRectangle> y_main;
907 for (int i = 0; i < no_overlap_2d.x_intervals_size(); ++i) {
908 // Ignore unperformed rectangles.
909 const int x_interval_index = no_overlap_2d.x_intervals(i);
910 if (ignored_intervals.contains(x_interval_index)) continue;
911 const ConstraintProto& x_interval_ct =
912 model_proto.constraints(x_interval_index);
913 if (!IsPresent(x_interval_ct, initial_solution)) continue;
914
915 const int y_interval_index = no_overlap_2d.y_intervals(i);
916 if (ignored_intervals.contains(y_interval_index)) continue;
917 const ConstraintProto& y_interval_ct =
918 model_proto.constraints(y_interval_index);
919 if (!IsPresent(y_interval_ct, initial_solution)) continue;
920
921 const int64_t x_start_value = GetLinearExpressionValue(
922 x_interval_ct.interval().start(), initial_solution);
923 const int64_t x_end_value = GetLinearExpressionValue(
924 x_interval_ct.interval().end(), initial_solution);
925 const int64_t y_start_value = GetLinearExpressionValue(
926 y_interval_ct.interval().start(), initial_solution);
927 const int64_t y_end_value = GetLinearExpressionValue(
928 y_interval_ct.interval().end(), initial_solution);
929
930 // Ignore rectangles with zero area.
931 if (x_start_value == x_end_value || y_start_value == y_end_value) continue;
932
933 x_main.push_back({.interval_index = x_interval_index,
934 .r = {.x_min = x_start_value,
935 .x_max = x_end_value,
936 .y_min = y_start_value,
937 .y_max = y_end_value}});
938 y_main.push_back({.interval_index = y_interval_index,
939 .r = {.x_min = y_start_value,
940 .x_max = y_end_value,
941 .y_min = x_start_value,
942 .y_max = x_end_value}});
943 }
944
945 if (x_main.empty() || y_main.empty()) return;
946
947 std::sort(x_main.begin(), x_main.end());
948 InsertRectanglePredecences(x_main, precedences);
949 std::sort(y_main.begin(), y_main.end());
950 InsertRectanglePredecences(y_main, precedences);
951}
952
953} // namespace
954
955// TODO(user): We could scan for model precedences and add them to the list
956// of precedences. This could enable more simplifications in the transitive
957// reduction phase.
958std::vector<std::pair<int, int>>
960 const absl::flat_hash_set<int>& ignored_intervals,
961 const CpSolverResponse& initial_solution, absl::BitGenRef random) const {
962 absl::flat_hash_set<std::pair<int, int>> precedences;
964 InsertNoOverlapPrecedences(ignored_intervals, initial_solution,
965 ModelProto(), c, &precedences);
966 }
968 InsertCumulativePrecedences(ignored_intervals, initial_solution,
969 ModelProto(), c, random, &precedences);
970 }
972 InsertNoOverlap2dPrecedences(ignored_intervals, initial_solution,
973 ModelProto(), c, &precedences);
974 }
975
976 // TODO(user): Reduce precedence graph
977 std::vector<std::pair<int, int>> result(precedences.begin(),
978 precedences.end());
979 std::sort(result.begin(), result.end());
980 return result;
981}
982
983std::vector<std::vector<int>>
985 const CpSolverResponse& initial_solution) const {
986 struct HeadAndArcBooleanVariable {
987 int head;
988 int bool_var;
989 };
990
991 std::vector<std::vector<int>> result;
992 absl::flat_hash_map<int, HeadAndArcBooleanVariable>
993 tail_to_head_and_arc_bool_var;
994
997
998 // Collect arcs.
999 int min_node = std::numeric_limits<int>::max();
1000 tail_to_head_and_arc_bool_var.clear();
1001 for (int i = 0; i < ct.literals_size(); ++i) {
1002 const int literal = ct.literals(i);
1003 const int head = ct.heads(i);
1004 const int tail = ct.tails(i);
1005 const int bool_var = PositiveRef(literal);
1006 const int64_t value = initial_solution.solution(bool_var);
1007 // Skip unselected arcs.
1008 if (RefIsPositive(literal) == (value == 0)) continue;
1009 // Ignore self loops.
1010 if (head == tail) continue;
1011 tail_to_head_and_arc_bool_var[tail] = {head, bool_var};
1012 min_node = std::min(tail, min_node);
1013 }
1014 if (tail_to_head_and_arc_bool_var.empty()) continue;
1015
1016 // Unroll the path.
1017 int current_node = min_node;
1018 std::vector<int> path;
1019 do {
1020 auto it = tail_to_head_and_arc_bool_var.find(current_node);
1021 CHECK(it != tail_to_head_and_arc_bool_var.end());
1022 current_node = it->second.head;
1023 path.push_back(it->second.bool_var);
1024 } while (current_node != min_node);
1025 result.push_back(std::move(path));
1026 }
1027
1028 std::vector<HeadAndArcBooleanVariable> route_starts;
1029 for (const int i : TypeToConstraints(ConstraintProto::kRoutes)) {
1031 tail_to_head_and_arc_bool_var.clear();
1032 route_starts.clear();
1033
1034 // Collect route starts and arcs.
1035 for (int i = 0; i < ct.literals_size(); ++i) {
1036 const int literal = ct.literals(i);
1037 const int head = ct.heads(i);
1038 const int tail = ct.tails(i);
1039 const int bool_var = PositiveRef(literal);
1040 const int64_t value = initial_solution.solution(bool_var);
1041 // Skip unselected arcs.
1042 if (RefIsPositive(literal) == (value == 0)) continue;
1043 // Ignore self loops.
1044 if (head == tail) continue;
1045 if (tail == 0) {
1046 route_starts.push_back({head, bool_var});
1047 } else {
1048 tail_to_head_and_arc_bool_var[tail] = {head, bool_var};
1049 }
1050 }
1051
1052 // Unroll all routes.
1053 for (const HeadAndArcBooleanVariable& head_var : route_starts) {
1054 std::vector<int> path;
1055 int current_node = head_var.head;
1056 path.push_back(head_var.bool_var);
1057 do {
1058 auto it = tail_to_head_and_arc_bool_var.find(current_node);
1059 CHECK(it != tail_to_head_and_arc_bool_var.end());
1060 current_node = it->second.head;
1061 path.push_back(it->second.bool_var);
1062 } while (current_node != 0);
1063 result.push_back(std::move(path));
1064 }
1065 }
1066
1067 return result;
1068}
1069
1071 const CpSolverResponse& base_solution,
1072 const Bitset64<int>& variables_to_fix) const {
1073 const int num_variables = variables_to_fix.size();
1074 Neighborhood neighborhood(num_variables);
1075 neighborhood.delta.mutable_variables()->Reserve(num_variables);
1076
1077 // TODO(user): Maybe relax all variables in the objective when the number
1078 // is small or negligible compared to the number of variables.
1079 const int unique_objective_variable =
1080 model_proto_.has_objective() && model_proto_.objective().vars_size() == 1
1081 ? model_proto_.objective().vars(0)
1082 : -1;
1083
1084 // Fill in neighborhood.delta all variable domains.
1085 int num_fixed = 0;
1086 {
1087 absl::ReaderMutexLock domain_lock(domain_mutex_);
1088 for (int i = 0; i < num_variables; ++i) {
1089 const IntegerVariableProto& current_var =
1090 model_proto_with_only_variables_.variables(i);
1091 IntegerVariableProto* new_var = neighborhood.delta.add_variables();
1092
1093 // We only copy the name in debug mode.
1094 if (DEBUG_MODE) new_var->set_name(current_var.name());
1095
1096 if (variables_to_fix[i] && i != unique_objective_variable) {
1097 ++num_fixed;
1098
1099 // Note the use of DomainInProtoContains() instead of
1100 // ReadDomainFromProto() as the later is slower and allocate memory.
1101 const int64_t base_value = base_solution.solution(i);
1102 if (DomainInProtoContains(current_var, base_value)) {
1103 new_var->add_domain(base_value);
1104 new_var->add_domain(base_value);
1105 } else {
1106 // If under the updated domain, the base solution is no longer valid,
1107 // We should probably regenerate this neighborhood. But for now we
1108 // just do a best effort and take the closest value.
1109 const Domain domain = ReadDomainFromProto(current_var);
1110 int64_t closest_value = domain.Min();
1111 int64_t closest_dist = std::abs(closest_value - base_value);
1112 for (const ClosedInterval interval : domain) {
1113 for (const int64_t value : {interval.start, interval.end}) {
1114 const int64_t dist = std::abs(value - base_value);
1115 if (dist < closest_dist) {
1116 closest_value = value;
1117 closest_dist = dist;
1118 }
1119 }
1120 }
1121 FillDomainInProto(Domain(closest_value, closest_value), new_var);
1122 }
1123 } else {
1124 *new_var->mutable_domain() = current_var.domain();
1125 }
1126 }
1127 }
1128
1129 // Fill some statistic fields and detect if we cover a full component.
1130 //
1131 // TODO(user): If there is just one component, we can skip some computation.
1132 {
1133 absl::ReaderMutexLock graph_lock(graph_mutex_);
1134 std::vector<int> count(components_.size(), 0);
1135 const int num_variables = neighborhood.delta.variables().size();
1136 for (int var = 0; var < num_variables; ++var) {
1137 const auto& domain = neighborhood.delta.variables(var).domain();
1138 if (domain.size() != 2 || domain[0] != domain[1]) {
1139 ++neighborhood.num_relaxed_variables;
1140 if (is_in_objective_[var]) {
1142 }
1143 const int c = var_to_component_index_[var];
1144 if (c != -1) count[c]++;
1145 }
1146 }
1147
1148 for (int i = 0; i < components_.size(); ++i) {
1149 if (count[i] == components_[i].size()) {
1152 components_[i].begin(), components_[i].end());
1153 }
1154 }
1155 }
1156
1157 // If the objective domain might cut the optimal solution, we cannot exploit
1158 // the connected components. We compute this outside the mutex to avoid
1159 // any deadlock risk.
1160 //
1161 // TODO(user): We could handle some complex domain (size > 2).
1162 if (model_proto_.has_objective() &&
1163 (model_proto_.objective().domain().size() != 2 ||
1164 shared_response_->GetInnerObjectiveLowerBound() <
1165 model_proto_.objective().domain(0))) {
1167 }
1168
1169 const int num_relaxed = num_variables - num_fixed;
1170 neighborhood.delta.mutable_solution_hint()->mutable_vars()->Reserve(
1171 num_relaxed);
1172 neighborhood.delta.mutable_solution_hint()->mutable_values()->Reserve(
1173 num_relaxed);
1174 AddSolutionHinting(base_solution, &neighborhood.delta);
1175
1176 neighborhood.is_generated = true;
1177 neighborhood.is_reduced = num_fixed > 0;
1178 neighborhood.is_simple = true;
1179
1180 // TODO(user): force better objective? Note that this is already done when the
1181 // hint above is successfully loaded (i.e. if it passes the presolve
1182 // correctly) since the solver will try to find better solution than the
1183 // current one.
1184 return neighborhood;
1185}
1186
1188 const CpSolverResponse& initial_solution, CpModelProto* model_proto) const {
1189 // Set the current solution as a hint.
1190 model_proto->clear_solution_hint();
1191 const auto is_fixed = [model_proto](int var) {
1192 const IntegerVariableProto& var_proto = model_proto->variables(var);
1193 return var_proto.domain_size() == 2 &&
1194 var_proto.domain(0) == var_proto.domain(1);
1195 };
1196 for (int var = 0; var < model_proto->variables_size(); ++var) {
1197 if (is_fixed(var)) continue;
1198
1199 model_proto->mutable_solution_hint()->add_vars(var);
1200 model_proto->mutable_solution_hint()->add_values(
1201 initial_solution.solution(var));
1202 }
1203}
1204
1206 const CpSolverResponse& initial_solution,
1207 absl::Span<const int> relaxed_variables) const {
1208 Bitset64<int> fixed_variables(NumVariables());
1209 {
1210 absl::ReaderMutexLock graph_lock(graph_mutex_);
1211 for (const int i : active_variables_) {
1212 fixed_variables.Set(i);
1213 }
1214 }
1215 for (const int var : relaxed_variables) fixed_variables.Clear(var);
1216 return FixGivenVariables(initial_solution, fixed_variables);
1217}
1218
1220 const CpSolverResponse& initial_solution) const {
1221 Bitset64<int> fixed_variables(NumVariables());
1222 {
1223 absl::ReaderMutexLock graph_lock(graph_mutex_);
1224 for (const int i : active_variables_) {
1225 fixed_variables.Set(i);
1226 }
1227 }
1228 return FixGivenVariables(initial_solution, fixed_variables);
1229}
1230
1232 CpModelProto updated_model = model_proto_;
1233 {
1234 absl::MutexLock domain_lock(domain_mutex_);
1235 *updated_model.mutable_variables() =
1236 model_proto_with_only_variables_.variables();
1237 }
1238 return updated_model;
1239}
1240
1242 return helper_.shared_response().HasFeasibleSolution();
1243}
1244
1245double NeighborhoodGenerator::GetUCBScore(int64_t total_num_calls) const {
1246 absl::ReaderMutexLock mutex_lock(generator_mutex_);
1247 DCHECK_GE(total_num_calls, num_calls_);
1248 if (num_calls_ <= 10) return std::numeric_limits<double>::infinity();
1249 return current_average_ + sqrt((2 * log(total_num_calls)) / num_calls_);
1250}
1251
1252absl::Span<const double> NeighborhoodGenerator::Synchronize() {
1253 absl::MutexLock mutex_lock(generator_mutex_);
1254
1255 // To make the whole update process deterministic, we currently sort the
1256 // SolveData.
1257 std::sort(solve_data_.begin(), solve_data_.end());
1258
1259 // This will be used to update the difficulty of this neighborhood.
1260 int num_fully_solved_in_batch = 0;
1261 int num_not_fully_solved_in_batch = 0;
1262
1263 tmp_dtimes_.clear();
1264 for (const SolveData& data : solve_data_) {
1265 ++num_calls_;
1266
1267 // INFEASIBLE or OPTIMAL means that we "fully solved" the local problem.
1268 // If we didn't, then we cannot be sure that there is no improving solution
1269 // in that neighborhood.
1270 if (data.status == CpSolverStatus::INFEASIBLE ||
1271 data.status == CpSolverStatus::OPTIMAL) {
1272 ++num_fully_solved_calls_;
1273 ++num_fully_solved_in_batch;
1274 } else {
1275 ++num_not_fully_solved_in_batch;
1276 }
1277
1278 // It seems to make more sense to compare the new objective to the base
1279 // solution objective, not the best one. However this causes issue in the
1280 // logic below because on some problems the neighborhood can always lead
1281 // to a better "new objective" if the base solution wasn't the best one.
1282 //
1283 // This might not be a final solution, but it does work ok for now.
1284 const IntegerValue best_objective_improvement = IntegerValue(CapSub(
1285 data.initial_best_objective.value(), data.new_objective.value()));
1286 if (best_objective_improvement > 0) {
1287 num_consecutive_non_improving_calls_ = 0;
1288 next_time_limit_bump_ = 50;
1289 } else {
1290 ++num_consecutive_non_improving_calls_;
1291 }
1292
1293 // Confusing: this one is however comparing to the base solution objective.
1294 if (data.base_objective > data.new_objective) {
1295 ++num_improving_calls_;
1296 }
1297
1298 // TODO(user): Weight more recent data.
1299 // degrade the current average to forget old learnings.
1300 const double gain_per_time_unit =
1301 std::max(0.0, static_cast<double>(best_objective_improvement.value())) /
1302 (1.0 + data.deterministic_time);
1303 if (num_calls_ <= 100) {
1304 current_average_ += (gain_per_time_unit - current_average_) / num_calls_;
1305 } else {
1306 current_average_ = 0.9 * current_average_ + 0.1 * gain_per_time_unit;
1307 }
1308
1309 tmp_dtimes_.push_back(data.deterministic_time);
1310 }
1311
1312 // Update the difficulty.
1313 difficulty_.Update(/*num_decreases=*/num_not_fully_solved_in_batch,
1314 /*num_increases=*/num_fully_solved_in_batch);
1315
1316 // Bump the time limit if we saw no better solution in the last few calls.
1317 // This means that as the search progress, we likely spend more and more time
1318 // trying to solve individual neighborhood.
1319 //
1320 // TODO(user): experiment with resetting the time limit if a solution is
1321 // found.
1322 if (num_consecutive_non_improving_calls_ > next_time_limit_bump_) {
1323 next_time_limit_bump_ = num_consecutive_non_improving_calls_ + 50;
1324 deterministic_limit_ *= 1.02;
1325
1326 // We do not want the limit to go to high. Intuitively, the goal is to try
1327 // out a lot of neighborhoods, not just spend a lot of time on a few.
1329 }
1330
1331 solve_data_.clear();
1332 return tmp_dtimes_;
1333}
1334
1335std::vector<int>
1337 const CpSolverResponse& initial_solution) const {
1338 std::vector<int> result;
1339 absl::ReaderMutexLock lock(domain_mutex_);
1340 for (const int var : active_objective_variables_) {
1341 const auto& domain =
1342 model_proto_with_only_variables_.variables(var).domain();
1343 bool at_best_value = false;
1344 if (has_positive_objective_coefficient_[var]) {
1345 at_best_value = initial_solution.solution(var) == domain[0];
1346 } else {
1347 at_best_value =
1348 initial_solution.solution(var) == domain[domain.size() - 1];
1349 }
1350 if (!at_best_value) result.push_back(var);
1351 }
1352 return result;
1353}
1354
1355namespace {
1356
1357template <class T>
1358void GetRandomSubset(double relative_size, std::vector<T>* base,
1359 absl::BitGenRef random) {
1360 if (base->empty()) return;
1361
1362 // TODO(user): we could generate this more efficiently than using random
1363 // shuffle.
1364 std::shuffle(base->begin(), base->end(), random);
1365 const int target_size = std::round(relative_size * base->size());
1366 base->resize(target_size);
1367}
1368
1369} // namespace
1370
1372 const CpSolverResponse& initial_solution, SolveData& data,
1373 absl::BitGenRef random) {
1374 std::vector<int> fixed_variables = helper_.ActiveVariables();
1375 GetRandomSubset(1.0 - data.difficulty, &fixed_variables, random);
1376
1377 Bitset64<int> to_fix(helper_.NumVariables());
1378 for (const int var : fixed_variables) to_fix.Set(var);
1379 return helper_.FixGivenVariables(initial_solution, to_fix);
1380}
1381
1383 const CpSolverResponse& initial_solution, SolveData& data,
1384 absl::BitGenRef random) {
1385 if (helper_.DifficultyMeansFullNeighborhood(data.difficulty)) {
1386 return helper_.FullNeighborhood();
1387 }
1388
1389 std::vector<int> relaxed_variables;
1390 {
1391 absl::ReaderMutexLock graph_lock(helper_.graph_mutex_);
1392 const int num_active_constraints = helper_.ConstraintToVar().size();
1393 std::vector<int> active_constraints(num_active_constraints);
1394 for (int c = 0; c < num_active_constraints; ++c) {
1395 active_constraints[c] = c;
1396 }
1397 std::shuffle(active_constraints.begin(), active_constraints.end(), random);
1398
1399 const int num_model_vars = helper_.ModelProto().variables_size();
1400 std::vector<bool> visited_variables_set(num_model_vars, false);
1401
1402 const int num_active_vars =
1403 helper_.ActiveVariablesWhileHoldingLock().size();
1404 const int target_size = std::ceil(data.difficulty * num_active_vars);
1405 if (target_size == num_active_vars) return helper_.FullNeighborhood();
1406 // TODO(user): Clean-up when target_size == 0.
1407
1408 for (const int constraint_index : active_constraints) {
1409 // TODO(user): randomize order of variable addition when close to the
1410 // limit.
1411 for (const int var : helper_.ConstraintToVar()[constraint_index]) {
1412 if (visited_variables_set[var]) continue;
1413 visited_variables_set[var] = true;
1414 if (helper_.IsActive(var)) {
1415 relaxed_variables.push_back(var);
1416 if (relaxed_variables.size() >= target_size) break;
1417 }
1418 }
1419 if (relaxed_variables.size() >= target_size) break;
1420 }
1421 }
1422
1423 return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
1424}
1425
1426// Note that even if difficulty means full neighborhood, we go through the
1427// generation process to never get out of a connected components.
1429 const CpSolverResponse& initial_solution, SolveData& data,
1430 absl::BitGenRef random) {
1431 const int num_model_vars = helper_.ModelProto().variables_size();
1432 std::vector<bool> visited_variables_set(num_model_vars, false);
1433 std::vector<int> relaxed_variables;
1434 std::vector<int> visited_variables;
1435
1436 // It is important complexity wise to never scan a constraint twice!
1437 const int num_model_constraints = helper_.ModelProto().constraints_size();
1438 std::vector<bool> scanned_constraints(num_model_constraints, false);
1439
1440 std::vector<int> random_variables;
1441 {
1442 absl::ReaderMutexLock graph_lock(helper_.graph_mutex_);
1443
1444 std::vector<int> initial_vars =
1445 helper_.ImprovableObjectiveVariablesWhileHoldingLock(initial_solution);
1446 if (initial_vars.empty()) {
1447 initial_vars = helper_.ActiveVariablesWhileHoldingLock();
1448 }
1449 // The number of active variables can decrease asynchronously.
1450 // We read the exact number while locked.
1451 const int num_active_vars =
1452 helper_.ActiveVariablesWhileHoldingLock().size();
1453 const int target_size = std::ceil(data.difficulty * num_active_vars);
1454 if (target_size == num_active_vars) return helper_.FullNeighborhood();
1455
1456 const int first_var =
1457 initial_vars[absl::Uniform<int>(random, 0, initial_vars.size())];
1458 visited_variables_set[first_var] = true;
1459 visited_variables.push_back(first_var);
1460 relaxed_variables.push_back(first_var);
1461
1462 for (int i = 0; i < visited_variables.size(); ++i) {
1463 random_variables.clear();
1464 // Collect all the variables that appears in the same constraints as
1465 // visited_variables[i].
1466 for (const int ct : helper_.VarToConstraint()[visited_variables[i]]) {
1467 if (scanned_constraints[ct]) continue;
1468 scanned_constraints[ct] = true;
1469 for (const int var : helper_.ConstraintToVar()[ct]) {
1470 if (visited_variables_set[var]) continue;
1471 visited_variables_set[var] = true;
1472 random_variables.push_back(var);
1473 }
1474 }
1475 // We always randomize to change the partial subgraph explored
1476 // afterwards.
1477 std::shuffle(random_variables.begin(), random_variables.end(), random);
1478 for (const int var : random_variables) {
1479 if (relaxed_variables.size() < target_size) {
1480 visited_variables.push_back(var);
1481 if (helper_.IsActive(var)) {
1482 relaxed_variables.push_back(var);
1483 }
1484 } else {
1485 break;
1486 }
1487 }
1488 if (relaxed_variables.size() >= target_size) break;
1489 }
1490 }
1491
1492 return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
1493}
1494
1495// Note that even if difficulty means full neighborhood, we go through the
1496// generation process to never get out of a connected components.
1498 const CpSolverResponse& initial_solution, SolveData& data,
1499 absl::BitGenRef random) {
1500 const int num_model_vars = helper_.ModelProto().variables_size();
1501 if (num_model_vars == 0) return helper_.NoNeighborhood();
1502
1503 // We copy the full graph var <-> constraints so that we can:
1504 // - reduce it in place
1505 // - not hold the mutex too long.
1506 // TODO(user): should we compress it or use a different representation ?
1507 CompactVectorVector<int, int> vars_to_constraints;
1508 CompactVectorVector<int, int> constraints_to_vars;
1509 int num_active_vars = 0;
1510 std::vector<int> active_objective_vars;
1511 {
1512 absl::ReaderMutexLock graph_lock(helper_.graph_mutex_);
1513 num_active_vars = helper_.ActiveVariablesWhileHoldingLock().size();
1514 active_objective_vars =
1515 helper_.ImprovableObjectiveVariablesWhileHoldingLock(initial_solution);
1516 constraints_to_vars = helper_.ConstraintToVar();
1517 vars_to_constraints = helper_.VarToConstraint();
1518 }
1519
1520 const int target_size = std::ceil(data.difficulty * num_active_vars);
1521 if (target_size == 0) return helper_.NoNeighborhood();
1522
1523 // We pick a variable from the objective.
1524 const int num_objective_variables = active_objective_vars.size();
1525 if (num_objective_variables == 0) return helper_.NoNeighborhood();
1526 const int first_var = active_objective_vars[absl::Uniform<int>(
1527 random, 0, num_objective_variables)];
1528
1529 std::vector<bool> relaxed_variables_set(num_model_vars, false);
1530 std::vector<int> relaxed_variables;
1531 // Active vars are relaxed variables with some unexplored neighbors.
1532 std::vector<int> active_vars;
1533
1534 relaxed_variables_set[first_var] = true;
1535 relaxed_variables.push_back(first_var);
1536 active_vars.push_back(first_var);
1537
1538 while (relaxed_variables.size() < target_size) {
1539 if (active_vars.empty()) break; // We have exhausted our component.
1540
1541 const int tail_index = absl::Uniform<int>(random, 0, active_vars.size());
1542 const int tail_var = active_vars[tail_index];
1543 int head_var = tail_var;
1544 while (!vars_to_constraints[tail_var].empty() && head_var == tail_var) {
1545 const auto cts = vars_to_constraints[tail_var];
1546 const int pos_ct = absl::Uniform<int>(random, 0, cts.size());
1547 const int ct = cts[pos_ct];
1548 while (!constraints_to_vars[ct].empty() && head_var == tail_var) {
1549 const auto vars = constraints_to_vars[ct];
1550 const int pos_var = absl::Uniform<int>(random, 0, vars.size());
1551 const int candidate = vars[pos_var];
1552
1553 // We remove the variable as it is either already relaxed, or will be
1554 // relaxed.
1555 constraints_to_vars.RemoveBySwap(ct, pos_var);
1556 if (!relaxed_variables_set[candidate]) {
1557 head_var = candidate;
1558 }
1559 }
1560 if (constraints_to_vars[ct].empty()) {
1561 // This constraint has no more un-relaxed variables.
1562 vars_to_constraints.RemoveBySwap(tail_var, pos_ct);
1563 }
1564 }
1565
1566 // Variable is no longer active ?
1567 if (vars_to_constraints[tail_var].empty()) {
1568 std::swap(active_vars[tail_index], active_vars.back());
1569 active_vars.pop_back();
1570 }
1571
1572 if (head_var != tail_var) {
1573 relaxed_variables_set[head_var] = true;
1574 relaxed_variables.push_back(head_var);
1575 active_vars.push_back(head_var);
1576 }
1577 }
1578 return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
1579}
1580
1581// Note that even if difficulty means full neighborhood, we go through the
1582// generation process to never get out of a connected components.
1584 const CpSolverResponse& initial_solution, SolveData& data,
1585 absl::BitGenRef random) {
1586 const int num_model_constraints = helper_.ModelProto().constraints_size();
1587 if (num_model_constraints == 0) {
1588 return helper_.FullNeighborhood();
1589 }
1590
1591 const int num_model_vars = helper_.ModelProto().variables_size();
1592 std::vector<bool> visited_variables_set(num_model_vars, false);
1593 std::vector<int> relaxed_variables;
1594
1595 std::vector<bool> added_constraints(num_model_constraints, false);
1596 std::vector<int> next_constraints;
1597
1598 std::vector<int> random_variables;
1599 {
1600 absl::ReaderMutexLock graph_lock(helper_.graph_mutex_);
1601 const int num_active_vars =
1602 helper_.ActiveVariablesWhileHoldingLock().size();
1603 const int target_size = std::ceil(data.difficulty * num_active_vars);
1604 if (target_size == num_active_vars) return helper_.FullNeighborhood();
1605
1606 // Start from a random active constraint.
1607 const int num_active_constraints = helper_.ConstraintToVar().size();
1608 if (num_active_constraints == 0) return helper_.NoNeighborhood();
1609 next_constraints.push_back(
1610 absl::Uniform<int>(random, 0, num_active_constraints));
1611 added_constraints[next_constraints.back()] = true;
1612
1613 while (relaxed_variables.size() < target_size) {
1614 // Stop if we have a full connected component.
1615 if (next_constraints.empty()) break;
1616
1617 // Pick a random unprocessed constraint.
1618 const int i = absl::Uniform<int>(random, 0, next_constraints.size());
1619 const int constraint_index = next_constraints[i];
1620 std::swap(next_constraints[i], next_constraints.back());
1621 next_constraints.pop_back();
1622
1623 // Add all the variable of this constraint and increase the set of next
1624 // possible constraints.
1625 DCHECK_LT(constraint_index, num_active_constraints);
1626 random_variables.assign(
1627 helper_.ConstraintToVar()[constraint_index].begin(),
1628 helper_.ConstraintToVar()[constraint_index].end());
1629 std::shuffle(random_variables.begin(), random_variables.end(), random);
1630 for (const int var : random_variables) {
1631 if (visited_variables_set[var]) continue;
1632 visited_variables_set[var] = true;
1633 if (helper_.IsActive(var)) {
1634 relaxed_variables.push_back(var);
1635 }
1636 if (relaxed_variables.size() >= target_size) break;
1637
1638 for (const int ct : helper_.VarToConstraint()[var]) {
1639 if (added_constraints[ct]) continue;
1640 added_constraints[ct] = true;
1641 next_constraints.push_back(ct);
1642 }
1643 }
1644 }
1645 }
1646
1647 return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
1648}
1649
1651 const CpSolverResponse& initial_solution, SolveData& data,
1652 absl::BitGenRef random) {
1653 int max_width = 0;
1654 int size_at_min_width_after_100;
1655 int min_width_after_100 = std::numeric_limits<int>::max();
1656 int num_zero_score = 0;
1657 std::vector<int> relaxed_variables;
1658
1659 // Note(user): The algo is slower than the other graph generator, so we
1660 // might not want to lock the graph for so long? it is just a reader lock
1661 // though.
1662 {
1663 absl::ReaderMutexLock graph_lock(helper_.graph_mutex_);
1664
1665 const int num_active_vars =
1666 helper_.ActiveVariablesWhileHoldingLock().size();
1667 const int target_size = std::ceil(data.difficulty * num_active_vars);
1668 if (target_size == num_active_vars) return helper_.FullNeighborhood();
1669
1670 const int num_vars = helper_.VarToConstraint().size();
1671 const int num_constraints = helper_.ConstraintToVar().size();
1672 if (num_constraints == 0 || num_vars == 0) {
1673 return helper_.FullNeighborhood();
1674 }
1675
1676 // We will grow this incrementally.
1677 // Index in the graph are first variables then constraints.
1678 const int num_nodes = num_vars + num_constraints;
1679 std::vector<bool> added(num_nodes, false);
1680 std::vector<bool> added_or_connected(num_nodes, false);
1681
1682 // We will process var/constraint node by minimum "score".
1683 struct QueueElement {
1684 int Index() const { return index; }
1685 bool operator<(const QueueElement& o) const {
1686 if (score == o.score) return tie_break < o.tie_break;
1687 return score < o.score;
1688 }
1689
1690 int index;
1691 int score = 0;
1692 double tie_break = 0.0;
1693 };
1694 std::vector<QueueElement> elements(num_nodes);
1696
1697 // Initialize elements.
1698 for (int i = 0; i < num_nodes; ++i) {
1699 elements[i].index = i;
1700 elements[i].tie_break = absl::Uniform<double>(random, 0.0, 1.0);
1701 }
1702
1703 // We start from a random active variable.
1704 //
1705 // Note that while num_vars contains all variables, all the fixed variables
1706 // will have no associated constraint, so we don't want to start from a
1707 // random variable.
1708 //
1709 // TODO(user): Does starting by a constraint make sense too?
1710 const int first_index =
1711 helper_.ActiveVariablesWhileHoldingLock()[absl::Uniform<int>(
1712 random, 0, num_active_vars)];
1713 elements[first_index].score = helper_.VarToConstraint()[first_index].size();
1714 pq.Add(elements[first_index]);
1715 added_or_connected[first_index] = true;
1716
1717 // Pop max-degree from queue and update.
1718 std::vector<int> to_update;
1719 while (!pq.IsEmpty() && relaxed_variables.size() < target_size) {
1720 // Just for logging.
1721 if (relaxed_variables.size() > 100 && pq.Size() < min_width_after_100) {
1722 min_width_after_100 = pq.Size();
1723 size_at_min_width_after_100 = relaxed_variables.size();
1724 }
1725
1726 const int index = pq.Top().index;
1727 const int score = pq.Top().score;
1728 pq.Pop();
1729 added[index] = true;
1730
1731 // When the score is zero, we don't need to update anything since the
1732 // frontier does not grow.
1733 if (score == 0) {
1734 if (index < num_vars) relaxed_variables.push_back(index);
1735 ++num_zero_score;
1736 continue;
1737 }
1738
1739 // Note that while it might looks bad, the overall complexity of this is
1740 // in O(num_edge) since we scan each index once and each newly connected
1741 // vertex once.
1742 int num_added = 0;
1743 to_update.clear();
1744 if (index < num_vars) {
1745 relaxed_variables.push_back(index);
1746 for (const int c : helper_.VarToConstraint()[index]) {
1747 const int c_index = num_vars + c;
1748 if (added_or_connected[c_index]) continue;
1749 ++num_added;
1750 added_or_connected[c_index] = true;
1751 to_update.push_back(c_index);
1752 for (const int v : helper_.ConstraintToVar()[c]) {
1753 if (added[v]) continue;
1754 if (added_or_connected[v]) {
1755 to_update.push_back(v);
1756 elements[v].score--;
1757 } else {
1758 elements[c_index].score++;
1759 }
1760 }
1761 }
1762 } else {
1763 for (const int v : helper_.ConstraintToVar()[index - num_vars]) {
1764 if (added_or_connected[v]) continue;
1765 ++num_added;
1766 added_or_connected[v] = true;
1767 to_update.push_back(v);
1768 for (const int c : helper_.VarToConstraint()[v]) {
1769 if (added[num_vars + c]) continue;
1770 if (added_or_connected[num_vars + c]) {
1771 elements[num_vars + c].score--;
1772 to_update.push_back(num_vars + c);
1773 } else {
1774 elements[v].score++;
1775 }
1776 }
1777 }
1778 }
1779
1780 // The score is exactly the frontier increase in size.
1781 // This is the same as the min-degree heuristic for the elimination order.
1782 // Except we only consider connected nodes.
1783 CHECK_EQ(num_added, score);
1784
1786 for (const int index : to_update) {
1787 DCHECK(!added[index]);
1788 if (pq.Contains(index)) {
1789 pq.ChangePriority(elements[index]);
1790 } else {
1791 pq.Add(elements[index]);
1792 }
1793 }
1794
1795 max_width = std::max(max_width, pq.Size());
1796 }
1797
1798 // Just for logging.
1799 if (pq.Size() < min_width_after_100) {
1800 min_width_after_100 = pq.Size();
1801 size_at_min_width_after_100 = relaxed_variables.size();
1802 }
1803
1804 VLOG(2) << "#relaxed " << relaxed_variables.size() << " #zero_score "
1805 << num_zero_score << " max_width " << max_width
1806 << " (size,min_width)_after_100 (" << size_at_min_width_after_100
1807 << "," << min_width_after_100 << ") "
1808 << " final_width " << pq.Size();
1809 }
1810
1811 return helper_.RelaxGivenVariables(initial_solution, relaxed_variables);
1812}
1813
1814namespace {
1815
1816// Create a constraint sum (X - LB) + sum (UB - X) <= rhs.
1817ConstraintProto DistanceToBoundsSmallerThanConstraint(
1818 absl::Span<const std::pair<int, int64_t>> dist_to_lower_bound,
1819 absl::Span<const std::pair<int, int64_t>> dist_to_upper_bound,
1820 const int64_t rhs) {
1821 DCHECK_GE(rhs, 0);
1822 ConstraintProto new_constraint;
1823 LinearConstraintProto* linear = new_constraint.mutable_linear();
1824 int64_t lhs_constant_value = 0;
1825 for (const auto [var, lb] : dist_to_lower_bound) {
1826 // We add X - LB
1827 linear->add_coeffs(1);
1828 linear->add_vars(var);
1829 lhs_constant_value -= lb;
1830 }
1831 for (const auto [var, ub] : dist_to_upper_bound) {
1832 // We add UB - X
1833 lhs_constant_value += ub;
1834 linear->add_coeffs(-1);
1835 linear->add_vars(var);
1836 }
1837 linear->add_domain(std::numeric_limits<int64_t>::min());
1838 linear->add_domain(rhs - lhs_constant_value);
1839 return new_constraint;
1840}
1841
1842} // namespace
1843
1845 const CpSolverResponse& initial_solution, SolveData& data,
1846 absl::BitGenRef random) {
1847 const std::vector<int> active_variables = helper_.ActiveVariables();
1848 if (active_variables.empty()) return helper_.NoNeighborhood();
1849
1850 {
1851 // Quick corner case in case the difficulty is too high. This is mainly
1852 // useful when testing with only that kind of LNS to abort early on
1853 // super-easy problems.
1854 const int size = active_variables.size();
1855 if (static_cast<int>(std::ceil(data.difficulty * size)) == size) {
1856 return helper_.FullNeighborhood();
1857 }
1858 }
1859
1860 // These are candidate for relaxation. The score will be filled later. Active
1861 // variable not kept in candidate will be added to other_variables.
1862 std::vector<std::pair<int, double>> candidates_with_score;
1863 std::vector<int> other_variables;
1864
1865 // Our extra relaxation constraint will be: sums of distance to the respective
1866 // bound smaller than a constant that depends on the difficulty.
1867 std::vector<std::pair<int, int64_t>> dist_to_lower_bound;
1868 std::vector<std::pair<int, int64_t>> dist_to_upper_bound;
1869
1870 // For the "easy" part of the extra constraint, we either look only at the
1871 // binary variables. Or we extend that to all variables at their bound.
1872 const bool only_look_at_binary = absl::Bernoulli(random, 0.5);
1873
1874 // We copy the model early to have access to reduced domains.
1875 // TODO(user): that might not be the most efficient if we abort just below.
1876 CpModelProto local_cp_model = helper_.UpdatedModelProtoCopy();
1877
1878 // Loop over active variables.
1879 bool some_non_binary_at_bound = false;
1880 for (const int var : active_variables) {
1881 DCHECK_LT(var, initial_solution.solution().size());
1882 DCHECK_LT(var, local_cp_model.variables().size());
1883 const IntegerVariableProto& var_proto = local_cp_model.variables(var);
1884 const int64_t base_value = initial_solution.solution(var);
1885 const bool is_binary = var_proto.domain_size() == 2 &&
1886 var_proto.domain(0) == 0 && var_proto.domain(1) == 1;
1887 if (only_look_at_binary && !is_binary) {
1888 other_variables.push_back(var);
1889 continue;
1890 }
1891
1892 DCHECK(!var_proto.domain().empty());
1893 const int64_t domain_min = var_proto.domain(0);
1894 const int64_t domain_max = var_proto.domain(var_proto.domain().size() - 1);
1895 if (base_value <= domain_min) {
1896 if (!is_binary) some_non_binary_at_bound = true;
1897 candidates_with_score.push_back({var, 0.0});
1898 dist_to_lower_bound.push_back({var, domain_min});
1899 } else if (base_value >= domain_max) {
1900 if (!is_binary) some_non_binary_at_bound = true;
1901 candidates_with_score.push_back({var, 0.0});
1902 dist_to_upper_bound.push_back({var, domain_max});
1903 } else {
1904 other_variables.push_back(var);
1905 }
1906 }
1907
1908 bool use_hamming_for_others = false;
1909 if (!other_variables.empty() && absl::Bernoulli(random, 0.5)) {
1910 use_hamming_for_others = true;
1911 }
1912 if (!use_hamming_for_others && candidates_with_score.empty()) {
1913 return helper_.NoNeighborhood();
1914 }
1915
1916 // With this option, we will create a bunch of Boolean variable
1917 // and add the constraints : "bool==0 => var == value_in_base_solution".
1918 if (use_hamming_for_others) {
1919 for (const int var : other_variables) {
1920 const int indicator = local_cp_model.variables().size();
1921 auto* var_proto = local_cp_model.add_variables();
1922 var_proto->add_domain(0);
1923 var_proto->add_domain(1);
1924 auto* new_ct = local_cp_model.add_constraints();
1925 new_ct->add_enforcement_literal(NegatedRef(indicator));
1926
1927 const int64_t base_value = initial_solution.solution(var);
1928 new_ct->mutable_linear()->add_domain(base_value);
1929 new_ct->mutable_linear()->add_domain(base_value);
1930 new_ct->mutable_linear()->add_vars(var);
1931 new_ct->mutable_linear()->add_coeffs(1);
1932
1933 // Add it to the distance constraint.
1934 dist_to_lower_bound.push_back({indicator, 0});
1935 candidates_with_score.push_back({var, 0.0});
1936 }
1937
1938 // Clear other_variables so that they are not added at the end.
1939 other_variables.clear();
1940 }
1941
1942 // Constrain the distance to the bounds.
1943 const int size = dist_to_upper_bound.size() + dist_to_lower_bound.size();
1944 const int target_size = static_cast<int>(std::ceil(data.difficulty * size));
1945 DCHECK_LE(target_size, candidates_with_score.size());
1946 *local_cp_model.add_constraints() = DistanceToBoundsSmallerThanConstraint(
1947 dist_to_lower_bound, dist_to_upper_bound, target_size);
1948
1949 Model model("lb_relax_lns_lp");
1950 auto* const params = model.GetOrCreate<SatParameters>();
1951
1952 // Parameters to enable solving the LP only.
1953 params->set_num_workers(1);
1954 params->set_linearization_level(2);
1955 params->set_stop_after_root_propagation(true);
1956 params->set_add_lp_constraints_lazily(false);
1957
1958 // Parameters to attempt to speed up solve.
1959 params->set_cp_model_presolve(false);
1960 params->set_cp_model_probing_level(0);
1961
1962 // Parameters to limit time spent in the solve. The max number of iterations
1963 // is relaxed from the default since we rely more on deterministic time.
1964 params->set_root_lp_iterations(100000);
1965
1966 // TODO(user): This is a lot longer than a normal LNS, so it might cause
1967 // issue with the current round-robbin selection based on number of calls.
1968 params->set_max_deterministic_time(10);
1969 model.GetOrCreate<TimeLimit>()->ResetLimitFromParameters(*params);
1970 if (global_time_limit_ != nullptr) {
1971 global_time_limit_->UpdateLocalLimit(model.GetOrCreate<TimeLimit>());
1972 }
1973
1974 // Tricky: we want the inner_objective_lower_bound in the response to be in
1975 // term of the current problem, not the user facing one.
1976 if (local_cp_model.has_objective()) {
1977 local_cp_model.mutable_objective()->set_integer_before_offset(0);
1978 local_cp_model.mutable_objective()->set_integer_after_offset(0);
1979 local_cp_model.mutable_objective()->set_integer_scaling_factor(0);
1980 }
1981
1982 // Dump?
1983 if (absl::GetFlag(FLAGS_cp_model_dump_submodels)) {
1984 const std::string dump_name =
1985 absl::StrCat(absl::GetFlag(FLAGS_cp_model_dump_prefix),
1986 "lb_relax_lns_lp_", data.task_id, ".pb.txt");
1987 LOG(INFO) << "Dumping linear relaxed model to '" << dump_name << "'.";
1988 CHECK(WriteModelProtoToFile(local_cp_model, dump_name));
1989 }
1990
1991 // Solve.
1992 //
1993 // TODO(user): Shall we pass the objective upper bound so we have more
1994 // chance to fix variable via reduced cost fixing.
1995 //
1996 // TODO(user): Does the current solution can provide a warm-start for the
1997 // LP?
1998 auto* response_manager = model.GetOrCreate<SharedResponseManager>();
1999 {
2000 response_manager->InitializeObjective(local_cp_model);
2001 LoadCpModel(local_cp_model, &model);
2002 SolveLoadedCpModel(local_cp_model, &model);
2003 }
2004
2005 // Update dtime.
2006 data.deterministic_time +=
2007 model.GetOrCreate<TimeLimit>()->GetElapsedDeterministicTime();
2008
2009 // Analyze the status of this first "solve".
2010 //
2011 // TODO(user): If we run into this case, it also means that every other LNS
2012 // that tries to more variable than here will never be able to improve.
2013 if (local_cp_model.has_objective()) {
2014 const CpSolverResponse response = response_manager->GetResponse();
2015 if (response.status() == CpSolverStatus::INFEASIBLE) {
2017 AddSolveData(data);
2018 return helper_.NoNeighborhood();
2019 }
2020
2021 const int64_t inner_lb = response.inner_objective_lower_bound();
2022 const int64_t current_inner_obj = ComputeInnerObjective(
2023 local_cp_model.objective(), initial_solution.solution());
2024 if (inner_lb >= current_inner_obj) {
2025 // In this case, we cannot improve on the base solution.
2026 // We could try to find a different solution for diversity, but we do have
2027 // other neighborhood for that. Lets abort early.
2028 data.status = CpSolverStatus::OPTIMAL; // We cannot improve.
2029 AddSolveData(data);
2030 return helper_.NoNeighborhood();
2031 }
2032 }
2033
2034 // Compute differences between LP solution and initial solution, with a small
2035 // random noise for tie breaking.
2036 const auto var_mapping = model.GetOrCreate<CpModelMapping>();
2037 const auto lp_solution = model.GetOrCreate<ModelLpValues>();
2038 if (lp_solution->empty()) {
2039 // We likely didn't solve the LP at all, so lets not use this neighborhood.
2040 return helper_.NoNeighborhood();
2041 }
2042 for (auto& [var, score] : candidates_with_score) {
2043 const IntegerVariable integer = var_mapping->Integer(var);
2044 DCHECK_LT(integer, lp_solution->size());
2045 DCHECK_LT(var, initial_solution.solution().size());
2046 const double difference =
2047 std::abs(lp_solution->at(var_mapping->Integer(var)) -
2048 initial_solution.solution(var));
2049 score = difference + absl::Uniform<double>(random, 0.0, 1e-6);
2050 }
2051
2052 // Take the target_size variables with largest differences.
2053 absl::c_sort(candidates_with_score, [](const std::pair<int, double>& a,
2054 const std::pair<int, double>& b) {
2055 return a.second > b.second;
2056 });
2057
2058 std::vector<int> vars_to_relax;
2059 vars_to_relax.reserve(target_size);
2060 DCHECK_LE(target_size, candidates_with_score.size());
2061 for (int i = 0; i < target_size; ++i) {
2062 vars_to_relax.push_back(candidates_with_score[i].first);
2063 }
2064
2065 // We will also relax all "other variables". We assume their values are likely
2066 // tied to the other ones.
2067 vars_to_relax.insert(vars_to_relax.end(), other_variables.begin(),
2068 other_variables.end());
2069 Neighborhood result =
2070 helper_.RelaxGivenVariables(initial_solution, vars_to_relax);
2071
2072 // Lets the name reflect the type.
2073 //
2074 // TODO(user): Unfortunately like this we have a common difficulty for all
2075 // variant, we should probably fix that.
2076 result.source_info = "lb_relax_lns";
2077 absl::StrAppend(&result.source_info,
2078 some_non_binary_at_bound ? "_int" : "_bool");
2079 if (use_hamming_for_others) {
2080 absl::StrAppend(&result.source_info, "_h");
2081 }
2082
2083 return result;
2084}
2085
2086namespace {
2087
2088void AddPrecedence(const LinearExpressionProto& before,
2089 const LinearExpressionProto& after, CpModelProto* model) {
2091 linear->add_domain(std::numeric_limits<int64_t>::min());
2092 linear->add_domain(after.offset() - before.offset());
2093 for (int i = 0; i < before.vars_size(); ++i) {
2094 linear->add_vars(before.vars(i));
2095 linear->add_coeffs(before.coeffs(i));
2096 }
2097 for (int i = 0; i < after.vars_size(); ++i) {
2098 linear->add_vars(after.vars(i));
2099 linear->add_coeffs(-after.coeffs(i));
2100 }
2101}
2102
2103} // namespace
2104
2106 const absl::Span<const std::pair<int, int>> precedences,
2107 const CpSolverResponse& initial_solution,
2108 const NeighborhoodGeneratorHelper& helper) {
2109 Neighborhood neighborhood = helper.FullNeighborhood();
2110
2111 neighborhood.is_reduced = !precedences.empty();
2112 if (!neighborhood.is_reduced) { // Returns the full neighborhood.
2113 helper.AddSolutionHinting(initial_solution, &neighborhood.delta);
2114 neighborhood.is_generated = true;
2115 return neighborhood;
2116 }
2117
2118 // Collect seen intervals.
2119 absl::flat_hash_set<int> seen_intervals;
2120 for (const std::pair<int, int>& prec : precedences) {
2121 seen_intervals.insert(prec.first);
2122 seen_intervals.insert(prec.second);
2123 }
2124
2125 // Fix the presence/absence of unseen intervals.
2126 for (const int i : helper.TypeToConstraints(ConstraintProto::kInterval)) {
2127 if (seen_intervals.contains(i)) continue;
2128
2129 const ConstraintProto& interval_ct = helper.ModelProto().constraints(i);
2130 if (interval_ct.enforcement_literal().empty()) continue;
2131
2132 DCHECK_EQ(interval_ct.enforcement_literal().size(), 1);
2133 const int enforcement_ref = interval_ct.enforcement_literal(0);
2134 const int enforcement_var = PositiveRef(enforcement_ref);
2135 const int value = initial_solution.solution(enforcement_var);
2136
2137 // If the interval is not enforced, we just relax it. If it belongs to an
2138 // exactly one constraint, and the enforced interval is not relaxed, then
2139 // propagation will force this interval to stay not enforced. Otherwise,
2140 // LNS will be able to change which interval will be enforced among all
2141 // alternatives.
2142 if (RefIsPositive(enforcement_ref) == (value == 0)) continue;
2143
2144 // Fix the value.
2145 neighborhood.delta.mutable_variables(enforcement_var)->clear_domain();
2146 neighborhood.delta.mutable_variables(enforcement_var)->add_domain(value);
2147 neighborhood.delta.mutable_variables(enforcement_var)->add_domain(value);
2148 }
2149
2150 for (const std::pair<int, int>& prec : precedences) {
2151 const LinearExpressionProto& before_end =
2152 helper.ModelProto().constraints(prec.first).interval().end();
2153 const LinearExpressionProto& after_start =
2154 helper.ModelProto().constraints(prec.second).interval().start();
2155 DCHECK_LE(GetLinearExpressionValue(before_end, initial_solution),
2156 GetLinearExpressionValue(after_start, initial_solution));
2157 AddPrecedence(before_end, after_start, &neighborhood.delta);
2158 }
2159
2160 // Set the current solution as a hint.
2161 helper.AddSolutionHinting(initial_solution, &neighborhood.delta);
2162 neighborhood.is_generated = true;
2163
2164 return neighborhood;
2165}
2166
2168 absl::Span<const int> intervals_to_relax,
2169 absl::Span<const int> variables_to_fix,
2170 const CpSolverResponse& initial_solution, absl::BitGenRef random,
2171 const NeighborhoodGeneratorHelper& helper) {
2172 Neighborhood neighborhood = helper.FullNeighborhood();
2173
2174 // We will extend the set with some interval that we cannot fix.
2175 absl::flat_hash_set<int> ignored_intervals(intervals_to_relax.begin(),
2176 intervals_to_relax.end());
2177
2178 // Fix the presence/absence of non-relaxed intervals.
2179 for (const int i : helper.TypeToConstraints(ConstraintProto::kInterval)) {
2180 DCHECK_GE(i, 0);
2181 if (ignored_intervals.contains(i)) continue;
2182
2183 const ConstraintProto& interval_ct = helper.ModelProto().constraints(i);
2184 if (interval_ct.enforcement_literal().empty()) continue;
2185
2186 DCHECK_EQ(interval_ct.enforcement_literal().size(), 1);
2187 const int enforcement_ref = interval_ct.enforcement_literal(0);
2188 const int enforcement_var = PositiveRef(enforcement_ref);
2189 const int value = initial_solution.solution(enforcement_var);
2190
2191 // If the interval is not enforced, we just relax it. If it belongs to an
2192 // exactly one constraint, and the enforced interval is not relaxed, then
2193 // propagation will force this interval to stay not enforced. Otherwise,
2194 // LNS will be able to change which interval will be enforced among all
2195 // alternatives.
2196 if (RefIsPositive(enforcement_ref) == (value == 0)) {
2197 ignored_intervals.insert(i);
2198 continue;
2199 }
2200
2201 // Fix the value.
2202 neighborhood.delta.mutable_variables(enforcement_var)->clear_domain();
2203 neighborhood.delta.mutable_variables(enforcement_var)->add_domain(value);
2204 neighborhood.delta.mutable_variables(enforcement_var)->add_domain(value);
2205 }
2206
2207 if (ignored_intervals.size() >=
2209 .size()) { // Returns the full neighborhood.
2210 helper.AddSolutionHinting(initial_solution, &neighborhood.delta);
2211 neighborhood.is_generated = true;
2212 return neighborhood;
2213 }
2214
2215 neighborhood.is_reduced = true;
2216
2217 // We differ from the ICAPS05 paper as we do not consider ignored intervals
2218 // when generating the precedence graph, instead of building the full graph,
2219 // then removing intervals, and reconstructing the precedence graph
2220 // heuristically after that.
2221 const std::vector<std::pair<int, int>> precedences =
2222 helper.GetSchedulingPrecedences(ignored_intervals, initial_solution,
2223 random);
2224 for (const std::pair<int, int>& prec : precedences) {
2225 const LinearExpressionProto& before_end =
2226 helper.ModelProto().constraints(prec.first).interval().end();
2227 const LinearExpressionProto& after_start =
2228 helper.ModelProto().constraints(prec.second).interval().start();
2229 DCHECK_LE(GetLinearExpressionValue(before_end, initial_solution),
2230 GetLinearExpressionValue(after_start, initial_solution));
2231 AddPrecedence(before_end, after_start, &neighborhood.delta);
2232 }
2233
2234 // fix the extra variables passed as parameters.
2235 for (const int var : variables_to_fix) {
2236 const int value = initial_solution.solution(var);
2237 neighborhood.delta.mutable_variables(var)->clear_domain();
2238 neighborhood.delta.mutable_variables(var)->add_domain(value);
2239 neighborhood.delta.mutable_variables(var)->add_domain(value);
2240 }
2241
2242 // Set the current solution as a hint.
2243 helper.AddSolutionHinting(initial_solution, &neighborhood.delta);
2244 neighborhood.is_generated = true;
2245
2246 return neighborhood;
2247}
2248
2250 const CpSolverResponse& initial_solution, SolveData& data,
2251 absl::BitGenRef random) {
2252 std::vector<int> intervals_to_relax =
2253 helper_.GetActiveIntervals(initial_solution);
2254 GetRandomSubset(data.difficulty, &intervals_to_relax, random);
2255
2257 intervals_to_relax, {}, initial_solution, random, helper_);
2258}
2259
2261 const CpSolverResponse& initial_solution, SolveData& data,
2262 absl::BitGenRef random) {
2263 std::vector<std::pair<int, int>> precedences =
2264 helper_.GetSchedulingPrecedences({}, initial_solution, random);
2265 GetRandomSubset(1.0 - data.difficulty, &precedences, random);
2267 precedences, initial_solution, helper_);
2268}
2269
2270namespace {
2271void AppendVarsFromAllIntervalIndices(absl::Span<const int> indices,
2272 absl::Span<const int> all_intervals,
2273 const CpModelProto& model_proto,
2274 std::vector<int>* variables) {
2275 for (const int index : indices) {
2276 const std::vector<int> vars =
2277 UsedVariables(model_proto.constraints(all_intervals[index]));
2278 variables->insert(variables->end(), vars.begin(), vars.end());
2279 }
2280}
2281} // namespace
2282
2284 const CpSolverResponse& initial_solution, SolveData& data,
2285 absl::BitGenRef random) {
2286 const std::vector<int> active_intervals =
2287 helper_.GetActiveIntervals(initial_solution);
2288
2289 if (active_intervals.empty()) return helper_.FullNeighborhood();
2290
2291 const TimePartition partition = PartitionIndicesAroundRandomTimeWindow(
2292 active_intervals, helper_.ModelProto(), initial_solution, data.difficulty,
2293 random);
2294 std::vector<int> intervals_to_relax;
2295 intervals_to_relax.reserve(partition.selected_indices.size());
2296 std::vector<int> variables_to_fix;
2297 intervals_to_relax.insert(intervals_to_relax.end(),
2298 partition.selected_indices.begin(),
2299 partition.selected_indices.end());
2300
2301 if (helper_.Parameters().push_all_tasks_toward_start()) {
2302 intervals_to_relax.insert(intervals_to_relax.end(),
2303 partition.indices_before_selected.begin(),
2304 partition.indices_before_selected.end());
2305 AppendVarsFromAllIntervalIndices(partition.indices_before_selected,
2306 active_intervals, helper_.ModelProto(),
2307 &variables_to_fix);
2308 }
2309
2310 gtl::STLSortAndRemoveDuplicates(&intervals_to_relax);
2311 gtl::STLSortAndRemoveDuplicates(&variables_to_fix);
2313 intervals_to_relax, variables_to_fix, initial_solution, random, helper_);
2314}
2315
2317 const CpSolverResponse& initial_solution, SolveData& data,
2318 absl::BitGenRef random) {
2319 std::vector<int> intervals_to_relax;
2320 std::vector<int> variables_to_fix;
2321 std::vector<int> active_intervals;
2322 for (const std::vector<int>& intervals : intervals_in_constraints_) {
2323 active_intervals = helper_.KeepActiveIntervals(intervals, initial_solution);
2324 const TimePartition partition = PartitionIndicesAroundRandomTimeWindow(
2325 active_intervals, helper_.ModelProto(), initial_solution,
2326 data.difficulty, random);
2327 intervals_to_relax.insert(intervals_to_relax.end(),
2328 partition.selected_indices.begin(),
2329 partition.selected_indices.end());
2330
2331 if (helper_.Parameters().push_all_tasks_toward_start()) {
2332 intervals_to_relax.insert(intervals_to_relax.end(),
2333 partition.indices_before_selected.begin(),
2334 partition.indices_before_selected.end());
2335 AppendVarsFromAllIntervalIndices(partition.indices_before_selected,
2336 active_intervals, helper_.ModelProto(),
2337 &variables_to_fix);
2338 }
2339 }
2340
2341 if (intervals_to_relax.empty() && variables_to_fix.empty()) {
2342 return helper_.FullNeighborhood();
2343 }
2344
2345 gtl::STLSortAndRemoveDuplicates(&intervals_to_relax);
2346 gtl::STLSortAndRemoveDuplicates(&variables_to_fix);
2348 intervals_to_relax, variables_to_fix, initial_solution, random, helper_);
2349}
2350
2352 const CpSolverResponse& initial_solution, SolveData& data,
2353 absl::BitGenRef random) {
2354 std::vector<ActiveRectangle> rectangles_to_freeze =
2355 helper_.GetActiveRectangles(initial_solution);
2356 GetRandomSubset(1.0 - data.difficulty, &rectangles_to_freeze, random);
2357
2358 Bitset64<int> variables_to_freeze(helper_.NumVariables());
2359 for (const ActiveRectangle& rectangle : rectangles_to_freeze) {
2360 InsertVariablesFromInterval(helper_.ModelProto(), rectangle.x_interval,
2361 variables_to_freeze);
2362 InsertVariablesFromInterval(helper_.ModelProto(), rectangle.y_interval,
2363 variables_to_freeze);
2364 }
2365 return helper_.FixGivenVariables(initial_solution, variables_to_freeze);
2366}
2367
2369 const CpSolverResponse& initial_solution, SolveData& data,
2370 absl::BitGenRef random) {
2371 // First pick one rectangle.
2372 const std::vector<ActiveRectangle> all_active_rectangles =
2373 helper_.GetActiveRectangles(initial_solution);
2374 if (all_active_rectangles.size() <= 1) return helper_.FullNeighborhood();
2375
2376 const ActiveRectangle& base_rectangle =
2377 all_active_rectangles[absl::Uniform<int>(random, 0,
2378 all_active_rectangles.size())];
2379
2380 const auto get_rectangle = [&initial_solution, helper = &helper_](
2381 const ActiveRectangle& rectangle) {
2382 const int x_interval_idx = rectangle.x_interval;
2383 const int y_interval_idx = rectangle.y_interval;
2384 const ConstraintProto& x_interval_ct =
2385 helper->ModelProto().constraints(x_interval_idx);
2386 const ConstraintProto& y_interval_ct =
2387 helper->ModelProto().constraints(y_interval_idx);
2388 return Rectangle{.x_min = GetLinearExpressionValue(
2389 x_interval_ct.interval().start(), initial_solution),
2390 .x_max = GetLinearExpressionValue(
2391 x_interval_ct.interval().end(), initial_solution),
2392 .y_min = GetLinearExpressionValue(
2393 y_interval_ct.interval().start(), initial_solution),
2394 .y_max = GetLinearExpressionValue(
2395 y_interval_ct.interval().end(), initial_solution)};
2396 };
2397
2398 const Rectangle center_rect = get_rectangle(base_rectangle);
2399
2400 // Now compute a neighborhood around that rectangle. In this neighborhood
2401 // we prefer a "Square" region around the initial rectangle center rather than
2402 // a circle.
2403 //
2404 // Note that we only consider two rectangles as potential neighbors if they
2405 // are part of the same no_overlap_2d constraint.
2406 Bitset64<int> variables_to_freeze(helper_.NumVariables());
2407 std::vector<std::pair<int, double>> distances;
2408 distances.reserve(all_active_rectangles.size());
2409 for (int i = 0; i < all_active_rectangles.size(); ++i) {
2410 const ActiveRectangle& rectangle = all_active_rectangles[i];
2411 InsertVariablesFromInterval(helper_.ModelProto(), rectangle.x_interval,
2412 variables_to_freeze);
2413 InsertVariablesFromInterval(helper_.ModelProto(), rectangle.y_interval,
2414 variables_to_freeze);
2415
2416 const Rectangle rect = get_rectangle(rectangle);
2417 const bool same_no_overlap_as_center_rect = absl::c_any_of(
2418 base_rectangle.no_overlap_2d_constraints, [&rectangle](const int c) {
2419 return rectangle.no_overlap_2d_constraints.contains(c);
2420 });
2421 if (same_no_overlap_as_center_rect) {
2422 distances.push_back(
2423 {i, CenterToCenterLInfinityDistance(center_rect, rect)});
2424 }
2425 }
2426 std::stable_sort(
2427 distances.begin(), distances.end(),
2428 [](const auto& a, const auto& b) { return a.second < b.second; });
2429
2430 const int num_to_sample = data.difficulty * all_active_rectangles.size();
2431 const int num_to_relax = std::min<int>(distances.size(), num_to_sample);
2432 Rectangle relaxed_bounding_box = center_rect;
2433 absl::flat_hash_set<int> boxes_to_relax;
2434 for (int i = 0; i < num_to_relax; ++i) {
2435 const int rectangle_idx = distances[i].first;
2436 const ActiveRectangle& rectangle = all_active_rectangles[rectangle_idx];
2437 relaxed_bounding_box.GrowToInclude(get_rectangle(rectangle));
2438 boxes_to_relax.insert(rectangle_idx);
2439 }
2440
2441 // Heuristic: we relax a bit the bounding box in order to allow some
2442 // movements, this is needed to not have a trivial neighborhood if we relax a
2443 // single box for instance.
2444 const IntegerValue x_size = relaxed_bounding_box.SizeX();
2445 const IntegerValue y_size = relaxed_bounding_box.SizeY();
2446 relaxed_bounding_box.x_min = CapSubI(relaxed_bounding_box.x_min, x_size / 2);
2447 relaxed_bounding_box.x_max = CapAddI(relaxed_bounding_box.x_max, x_size / 2);
2448 relaxed_bounding_box.y_min = CapSubI(relaxed_bounding_box.y_min, y_size / 2);
2449 relaxed_bounding_box.y_max = CapAddI(relaxed_bounding_box.y_max, y_size / 2);
2450
2451 for (const int b : boxes_to_relax) {
2452 const ActiveRectangle& rectangle = all_active_rectangles[b];
2453 RemoveVariablesFromInterval(helper_.ModelProto(), rectangle.x_interval,
2454 variables_to_freeze);
2455 RemoveVariablesFromInterval(helper_.ModelProto(), rectangle.y_interval,
2456 variables_to_freeze);
2457 }
2458 Neighborhood neighborhood =
2459 helper_.FixGivenVariables(initial_solution, variables_to_freeze);
2460
2461 neighborhood.is_simple = false;
2462 neighborhood.is_reduced = true;
2464
2465 // The call above add the relaxed variables to the neighborhood using the
2466 // current bounds at level 0. For big problems, this might create a hard model
2467 // with a large complicated landscape of fixed boxes with a lot of potential
2468 // places to place the relaxed boxes. Therefore we update the domain so the
2469 // boxes can only stay around the area we decided to relax.
2470 for (const int b : boxes_to_relax) {
2471 {
2472 const IntervalConstraintProto& x_interval =
2473 helper_.ModelProto()
2474 .constraints(all_active_rectangles[b].x_interval)
2475 .interval();
2476 const Domain x_domain = Domain(relaxed_bounding_box.x_min.value(),
2477 relaxed_bounding_box.x_max.value());
2478 RestrictAffineExpression(x_interval.start(), x_domain,
2479 &neighborhood.delta);
2480 RestrictAffineExpression(x_interval.end(), x_domain, &neighborhood.delta);
2481 }
2482 {
2483 const IntervalConstraintProto& y_interval =
2484 helper_.ModelProto()
2485 .constraints(all_active_rectangles[b].y_interval)
2486 .interval();
2487 const Domain y_domain = Domain(relaxed_bounding_box.y_min.value(),
2488 relaxed_bounding_box.y_max.value());
2489 RestrictAffineExpression(y_interval.start(), y_domain,
2490 &neighborhood.delta);
2491 RestrictAffineExpression(y_interval.end(), y_domain, &neighborhood.delta);
2492 }
2493 }
2494 return neighborhood;
2495}
2496
2498 const CpSolverResponse& initial_solution, SolveData& data,
2499 absl::BitGenRef random) {
2500 // First pick a pair of rectangles.
2501 std::vector<ActiveRectangle> all_active_rectangles =
2502 helper_.GetActiveRectangles(initial_solution);
2503 if (all_active_rectangles.size() <= 2) return helper_.FullNeighborhood();
2504
2505 const int first_idx =
2506 absl::Uniform<int>(random, 0, all_active_rectangles.size());
2507 int second_idx =
2508 absl::Uniform<int>(random, 0, all_active_rectangles.size() - 1);
2509 if (second_idx >= first_idx) {
2510 second_idx++;
2511 }
2512
2513 const ActiveRectangle& chosen_rectangle_1 = all_active_rectangles[first_idx];
2514 const ActiveRectangle& chosen_rectangle_2 = all_active_rectangles[second_idx];
2515
2516 const auto get_rectangle = [&initial_solution, helper = &helper_](
2517 const ActiveRectangle& rectangle) {
2518 const int x_interval_idx = rectangle.x_interval;
2519 const int y_interval_idx = rectangle.y_interval;
2520 const ConstraintProto& x_interval_ct =
2521 helper->ModelProto().constraints(x_interval_idx);
2522 const ConstraintProto& y_interval_ct =
2523 helper->ModelProto().constraints(y_interval_idx);
2524 return Rectangle{.x_min = GetLinearExpressionValue(
2525 x_interval_ct.interval().start(), initial_solution),
2526 .x_max = GetLinearExpressionValue(
2527 x_interval_ct.interval().end(), initial_solution),
2528 .y_min = GetLinearExpressionValue(
2529 y_interval_ct.interval().start(), initial_solution),
2530 .y_max = GetLinearExpressionValue(
2531 y_interval_ct.interval().end(), initial_solution)};
2532 };
2533
2534 const Rectangle rect1 = get_rectangle(chosen_rectangle_1);
2535 const Rectangle rect2 = get_rectangle(chosen_rectangle_2);
2536
2537 // Now compute a neighborhood around each rectangle. Note that we only
2538 // consider two rectangles as potential neighbors if they are part of the same
2539 // no_overlap_2d constraint.
2540 //
2541 // TODO(user): This computes the distance between the center of the
2542 // rectangles. We could use the real distance between the closest points, but
2543 // not sure it is worth the extra complexity.
2544 Bitset64<int> variables_to_freeze(helper_.NumVariables());
2545 std::vector<std::pair<int, double>> distances1;
2546 std::vector<std::pair<int, double>> distances2;
2547 distances1.reserve(all_active_rectangles.size());
2548 distances2.reserve(all_active_rectangles.size());
2549 for (int i = 0; i < all_active_rectangles.size(); ++i) {
2550 const ActiveRectangle& rectangle = all_active_rectangles[i];
2551 InsertVariablesFromInterval(helper_.ModelProto(), rectangle.x_interval,
2552 variables_to_freeze);
2553 InsertVariablesFromInterval(helper_.ModelProto(), rectangle.y_interval,
2554 variables_to_freeze);
2555
2556 const Rectangle rect = get_rectangle(rectangle);
2557 const bool same_no_overlap_as_rect1 =
2558 absl::c_any_of(chosen_rectangle_1.no_overlap_2d_constraints,
2559 [&rectangle](const int c) {
2560 return rectangle.no_overlap_2d_constraints.contains(c);
2561 });
2562 const bool same_no_overlap_as_rect2 =
2563 absl::c_any_of(chosen_rectangle_2.no_overlap_2d_constraints,
2564 [&rectangle](const int c) {
2565 return rectangle.no_overlap_2d_constraints.contains(c);
2566 });
2567 if (same_no_overlap_as_rect1) {
2568 distances1.push_back({i, CenterToCenterL2Distance(rect1, rect)});
2569 }
2570 if (same_no_overlap_as_rect2) {
2571 distances2.push_back({i, CenterToCenterL2Distance(rect2, rect)});
2572 }
2573 }
2574 const int num_to_sample_each =
2575 data.difficulty * all_active_rectangles.size() / 2;
2576 std::sort(distances1.begin(), distances1.end(),
2577 [](const auto& a, const auto& b) { return a.second < b.second; });
2578 std::sort(distances2.begin(), distances2.end(),
2579 [](const auto& a, const auto& b) { return a.second < b.second; });
2580 for (auto& samples : {distances1, distances2}) {
2581 const int num_potential_samples = samples.size();
2582 for (int i = 0; i < std::min(num_potential_samples, num_to_sample_each);
2583 ++i) {
2584 const int rectangle_idx = samples[i].first;
2585 const ActiveRectangle& rectangle = all_active_rectangles[rectangle_idx];
2586 RemoveVariablesFromInterval(helper_.ModelProto(), rectangle.x_interval,
2587 variables_to_freeze);
2588 RemoveVariablesFromInterval(helper_.ModelProto(), rectangle.y_interval,
2589 variables_to_freeze);
2590 }
2591 }
2592
2593 return helper_.FixGivenVariables(initial_solution, variables_to_freeze);
2594}
2595
2597 const CpSolverResponse& initial_solution, SolveData& data,
2598 absl::BitGenRef random) {
2599 std::vector<ActiveRectangle> rectangles_to_relax =
2600 helper_.GetActiveRectangles(initial_solution);
2601 GetRandomSubset(data.difficulty, &rectangles_to_relax, random);
2602 std::vector<int> intervals_to_relax;
2603 for (const ActiveRectangle& rect : rectangles_to_relax) {
2604 intervals_to_relax.push_back(rect.x_interval);
2605 intervals_to_relax.push_back(rect.y_interval);
2606 }
2607 gtl::STLSortAndRemoveDuplicates(&intervals_to_relax);
2608
2610 intervals_to_relax, {}, initial_solution, random, helper_);
2611}
2612
2614 const CpSolverResponse& initial_solution, SolveData& data,
2615 absl::BitGenRef random) {
2616 const std::vector<ActiveRectangle> active_rectangles =
2617 helper_.GetActiveRectangles(initial_solution);
2618 const bool use_first_dimension = absl::Bernoulli(random, 0.5);
2619 std::vector<int> projected_intervals;
2620 projected_intervals.reserve(active_rectangles.size());
2621 for (const ActiveRectangle& rect : active_rectangles) {
2622 projected_intervals.push_back(use_first_dimension ? rect.x_interval
2623 : rect.y_interval);
2624 }
2625
2626 const TimePartition partition = PartitionIndicesAroundRandomTimeWindow(
2627 projected_intervals, helper_.ModelProto(), initial_solution,
2628 data.difficulty, random);
2629 std::vector<bool> indices_to_fix(active_rectangles.size(), true);
2630 for (const int index : partition.selected_indices) {
2631 indices_to_fix[index] = false;
2632 }
2633
2634 Bitset64<int> variables_to_freeze(helper_.NumVariables());
2635 for (int index = 0; index < active_rectangles.size(); ++index) {
2636 if (indices_to_fix[index]) {
2638 active_rectangles[index].x_interval,
2639 variables_to_freeze);
2641 active_rectangles[index].y_interval,
2642 variables_to_freeze);
2643 }
2644 }
2645
2646 return helper_.FixGivenVariables(initial_solution, variables_to_freeze);
2647}
2648
2650 const CpSolverResponse& initial_solution, SolveData& data,
2651 absl::BitGenRef random) {
2652 const std::vector<std::vector<int>> all_paths =
2653 helper_.GetRoutingPathBooleanVariables(initial_solution);
2654
2655 // Collect all unique variables.
2656 std::vector<int> variables_to_fix;
2657 for (const auto& path : all_paths) {
2658 variables_to_fix.insert(variables_to_fix.end(), path.begin(), path.end());
2659 }
2660 gtl::STLSortAndRemoveDuplicates(&variables_to_fix);
2661 GetRandomSubset(1.0 - data.difficulty, &variables_to_fix, random);
2662
2663 Bitset64<int> to_fix(helper_.NumVariables());
2664 for (const int var : variables_to_fix) to_fix.Set(var);
2665 return helper_.FixGivenVariables(initial_solution, to_fix);
2666}
2667
2669 const CpSolverResponse& initial_solution, SolveData& data,
2670 absl::BitGenRef random) {
2671 std::vector<std::vector<int>> all_paths =
2672 helper_.GetRoutingPathBooleanVariables(initial_solution);
2673
2674 // Remove a corner case where all paths are empty.
2675 if (all_paths.empty()) {
2676 return helper_.NoNeighborhood();
2677 }
2678
2679 // Collect all unique variables.
2680 std::vector<int> all_path_variables;
2681 int sum_of_path_sizes = 0;
2682 for (const auto& path : all_paths) {
2683 sum_of_path_sizes += path.size();
2684 }
2685 all_path_variables.reserve(sum_of_path_sizes);
2686 for (const auto& path : all_paths) {
2687 all_path_variables.insert(all_path_variables.end(), path.begin(),
2688 path.end());
2689 }
2690 gtl::STLSortAndRemoveDuplicates(&all_path_variables);
2691
2692 // Select target number of variables to relax.
2693 const int num_variables_to_relax =
2694 static_cast<int>(all_path_variables.size() * data.difficulty);
2695 absl::flat_hash_set<int> relaxed_variables;
2696
2697 while (relaxed_variables.size() < num_variables_to_relax) {
2698 DCHECK(!all_paths.empty());
2699 const int path_index = absl::Uniform<int>(random, 0, all_paths.size());
2700 std::vector<int>& path = all_paths[path_index];
2701 const int path_size = path.size();
2702 const int segment_length =
2703 std::min(path_size, absl::Uniform<int>(random, 4, 8));
2704 const int segment_start =
2705 absl::Uniform<int>(random, 0, path_size - segment_length);
2706 for (int i = segment_start; i < segment_start + segment_length; ++i) {
2707 relaxed_variables.insert(path[i]);
2708 }
2709
2710 // Remove segment and clean up empty paths.
2711 path.erase(path.begin() + segment_start,
2712 path.begin() + segment_start + segment_length);
2713 if (path.empty()) {
2714 std::swap(all_paths[path_index], all_paths.back());
2715 all_paths.pop_back();
2716 }
2717 }
2718
2719 // Compute the set of variables to fix.
2720 Bitset64<int> to_fix(helper_.NumVariables());
2721 for (const int var : all_path_variables) {
2722 if (!relaxed_variables.contains(var)) to_fix.Set(var);
2723 }
2724 return helper_.FixGivenVariables(initial_solution, to_fix);
2725}
2726
2728 const CpSolverResponse& initial_solution, SolveData& data,
2729 absl::BitGenRef random) {
2730 std::vector<std::vector<int>> all_paths =
2731 helper_.GetRoutingPathBooleanVariables(initial_solution);
2732
2733 // Remove a corner case where all paths are empty.
2734 if (all_paths.empty()) {
2735 return helper_.NoNeighborhood();
2736 }
2737
2738 // Collect all unique variables.
2739 std::vector<int> all_path_variables;
2740 int sum_of_path_sizes = 0;
2741 for (const auto& path : all_paths) {
2742 sum_of_path_sizes += path.size();
2743 }
2744 all_path_variables.reserve(sum_of_path_sizes);
2745 for (const auto& path : all_paths) {
2746 all_path_variables.insert(all_path_variables.end(), path.begin(),
2747 path.end());
2748 }
2749 gtl::STLSortAndRemoveDuplicates(&all_path_variables);
2750
2751 // Select target number of variables to relax.
2752 const int num_variables_to_relax =
2753 static_cast<int>(all_path_variables.size() * data.difficulty);
2754 absl::flat_hash_set<int> relaxed_variables;
2755
2756 // Relax the start and end of each path to ease relocation.
2757 // TODO(user): Restrict this if the difficulty is very low.
2758 for (const auto& path : all_paths) {
2759 relaxed_variables.insert(path.front());
2760 relaxed_variables.insert(path.back());
2761 }
2762
2763 // Relax all variables, if possible, of one random path.
2764 const int path_index = absl::Uniform<int>(random, 0, all_paths.size());
2765 std::shuffle(all_paths[path_index].begin(), all_paths[path_index].end(),
2766 random);
2767 while (relaxed_variables.size() < num_variables_to_relax &&
2768 !all_paths[path_index].empty()) {
2769 relaxed_variables.insert(all_paths[path_index].back());
2770 all_paths[path_index].pop_back();
2771 }
2772
2773 // Relax more variables until the target is reached.
2774 if (relaxed_variables.size() < num_variables_to_relax) {
2775 std::shuffle(all_path_variables.begin(), all_path_variables.end(), random);
2776 while (relaxed_variables.size() < num_variables_to_relax) {
2777 relaxed_variables.insert(all_path_variables.back());
2778 all_path_variables.pop_back();
2779 }
2780 }
2781
2782 // Compute the set of variables to fix.
2783 Bitset64<int> to_fix(helper_.NumVariables());
2784 for (const int var : all_path_variables) {
2785 if (!relaxed_variables.contains(var)) to_fix.Set(var);
2786 }
2787 return helper_.FixGivenVariables(initial_solution, to_fix);
2788}
2789
2791 return (incomplete_solutions_->HasSolution() ||
2792 lp_solutions_->NumSolutions() > 0);
2793}
2794
2796 const CpSolverResponse& /*initial_solution*/, SolveData& data,
2797 absl::BitGenRef random) {
2798 Neighborhood neighborhood = helper_.FullNeighborhood();
2799 neighborhood.is_generated = false;
2800
2801 const ReducedDomainNeighborhood reduced_domains =
2802 GetRinsRensNeighborhood(response_manager_, lp_solutions_,
2803 incomplete_solutions_, data.difficulty, random);
2804
2805 if (reduced_domains.fixed_vars.empty() &&
2806 reduced_domains.reduced_domain_vars.empty()) {
2807 return neighborhood;
2808 }
2809 neighborhood.source_info = reduced_domains.source_info;
2810
2811 absl::ReaderMutexLock graph_lock(helper_.graph_mutex_);
2812 // Fix the variables in the local model.
2813 for (const std::pair</*model_var*/ int, /*value*/ int64_t>& fixed_var :
2814 reduced_domains.fixed_vars) {
2815 const int var = fixed_var.first;
2816 const int64_t value = fixed_var.second;
2817 if (var >= neighborhood.delta.variables_size()) continue;
2818 if (!helper_.IsActive(var)) continue;
2819
2820 if (!DomainInProtoContains(neighborhood.delta.variables(var), value)) {
2821 // TODO(user): Instead of aborting, pick the closest point in the domain?
2822 return neighborhood;
2823 }
2824
2825 neighborhood.delta.mutable_variables(var)->clear_domain();
2826 neighborhood.delta.mutable_variables(var)->add_domain(value);
2827 neighborhood.delta.mutable_variables(var)->add_domain(value);
2828 neighborhood.is_reduced = true;
2829 }
2830
2831 for (const std::pair</*model_var*/ int,
2832 /*domain*/ std::pair<int64_t, int64_t>>& reduced_var :
2833 reduced_domains.reduced_domain_vars) {
2834 const int var = reduced_var.first;
2835 const int64_t lb = reduced_var.second.first;
2836 const int64_t ub = reduced_var.second.second;
2837 if (var >= neighborhood.delta.variables_size()) continue;
2838 if (!helper_.IsActive(var)) continue;
2839 const Domain domain =
2840 ReadDomainFromProto(neighborhood.delta.variables(var));
2841 Domain new_domain = domain.IntersectionWith(Domain(lb, ub));
2842 if (new_domain.IsEmpty()) {
2843 new_domain = Domain::FromValues(
2844 {domain.ClosestValue(lb), domain.ClosestValue(ub)});
2845 }
2846 FillDomainInProto(domain, neighborhood.delta.mutable_variables(var));
2847 neighborhood.is_reduced = true;
2848 }
2849 neighborhood.is_generated = true;
2850 return neighborhood;
2851}
2852
2853} // namespace sat
2854} // namespace operations_research
bool AddEdge(int node1, int node2)
IndexType size() const
Definition bitset.h:463
void Clear(IndexType i)
Definition bitset.h:505
void Set(IndexType i)
Definition bitset.h:543
static Domain FromValues(std::vector< int64_t > values)
Domain IntersectionWith(const Domain &domain) const
bool IsIncludedIn(const Domain &domain) const
int64_t ClosestValue(int64_t wanted) const
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
void RemoveBySwap(K key, int index)
Definition util.h:159
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
::int32_t enforcement_literal(int index) const
const ::operations_research::sat::IntervalConstraintProto & interval() const
const ::operations_research::sat::RoutesConstraintProto & routes() const
::operations_research::sat::LinearConstraintProto *PROTOBUF_NONNULL mutable_linear()
const ::operations_research::sat::CircuitConstraintProto & circuit() const
const ::operations_research::sat::IntegerVariableProto & variables(int index) const
const ::operations_research::sat::ConstraintProto & constraints(int index) const
::operations_research::sat::IntegerVariableProto *PROTOBUF_NONNULL add_variables()
::operations_research::sat::PartialVariableAssignment *PROTOBUF_NONNULL mutable_solution_hint()
::operations_research::sat::ConstraintProto *PROTOBUF_NONNULL add_constraints()
::operations_research::sat::CpObjectiveProto *PROTOBUF_NONNULL mutable_objective()
::operations_research::sat::IntegerVariableProto *PROTOBUF_NONNULL mutable_variables(int index)
const ::operations_research::sat::CpObjectiveProto & objective() const
::operations_research::sat::CpSolverStatus status() const
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
::google::protobuf::RepeatedField<::int64_t > *PROTOBUF_NONNULL mutable_domain()
void set_name(Arg_ &&arg, Args_... args)
const ::operations_research::sat::LinearExpressionProto & size() const
const ::operations_research::sat::LinearExpressionProto & end() const
const ::operations_research::sat::LinearExpressionProto & start() const
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
std::vector< int > ImprovableObjectiveVariablesWhileHoldingLock(const CpSolverResponse &initial_solution) const ABSL_LOCKS_EXCLUDED(domain_mutex_)
bool IsActive(int var) const ABSL_SHARED_LOCKS_REQUIRED(graph_mutex_)
std::vector< std::vector< int > > GetRoutingPathBooleanVariables(const CpSolverResponse &initial_solution) const
Neighborhood FixAllVariables(const CpSolverResponse &initial_solution) const
Neighborhood FixGivenVariables(const CpSolverResponse &base_solution, const Bitset64< int > &variables_to_fix) const
const SharedResponseManager & shared_response() const
Neighborhood RelaxGivenVariables(const CpSolverResponse &initial_solution, absl::Span< const int > relaxed_variables) const
std::vector< std::vector< int > > GetUniqueIntervalSets() const
std::vector< ActiveRectangle > GetActiveRectangles(const CpSolverResponse &initial_solution) const
void AddSolutionHinting(const CpSolverResponse &initial_solution, CpModelProto *model_proto) const
std::vector< int > GetActiveIntervals(const CpSolverResponse &initial_solution) const
std::vector< std::pair< int, int > > GetSchedulingPrecedences(const absl::flat_hash_set< int > &ignored_intervals, const CpSolverResponse &initial_solution, absl::BitGenRef random) const
absl::Span< const int > TypeToConstraints(ConstraintProto::ConstraintCase type) const
NeighborhoodGeneratorHelper(CpModelProto const *model_proto, SatParameters const *parameters, SharedResponseManager *shared_response, ModelSharedTimeLimit *global_time_limit, SharedBoundsManager *shared_bounds=nullptr)
std::vector< int > KeepActiveIntervals(absl::Span< const int > unfiltered_intervals, const CpSolverResponse &initial_solution) const
NeighborhoodGeneratorHelper::ActiveRectangle ActiveRectangle
double GetUCBScore(int64_t total_num_calls) const
const NeighborhoodGeneratorHelper & helper_
::google::protobuf::RepeatedField<::int64_t > *PROTOBUF_NONNULL mutable_values()
::google::protobuf::RepeatedField<::int32_t > *PROTOBUF_NONNULL mutable_vars()
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
SubSolver(absl::string_view name, SubsolverType type)
Definition subsolver.h:48
SubsolverType type() const
Definition subsolver.h:98
Neighborhood Generate(const CpSolverResponse &initial_solution, SolveData &data, absl::BitGenRef random) final
void reserve(size_type n)
void STLSortAndRemoveDuplicates(T *v, const LessFunc &less_func)
Definition stl_util.h:55
void SolveLoadedCpModel(const CpModelProto &model_proto, Model *model)
void RemoveVariablesFromInterval(const CpModelProto &model_proto, int index, Bitset64< int > &output)
int64_t ComputeInnerObjective(const CpObjectiveProto &objective, absl::Span< const int64_t > solution)
ReducedDomainNeighborhood GetRinsRensNeighborhood(const SharedResponseManager *response_manager, const SharedLPSolutionRepository *lp_solutions, SharedIncompleteSolutionManager *incomplete_solutions, double difficulty, absl::BitGenRef random)
Definition rins.cc:176
bool WriteModelProtoToFile(const M &proto, absl::string_view filename)
bool DomainInProtoContains(const ProtoWithDomain &proto, int64_t value)
Neighborhood GenerateSchedulingNeighborhoodFromIntervalPrecedences(const absl::Span< const std::pair< int, int > > precedences, const CpSolverResponse &initial_solution, const NeighborhoodGeneratorHelper &helper)
double CenterToCenterLInfinityDistance(const Rectangle &a, const Rectangle &b)
Definition diffn_util.h:144
Neighborhood GenerateSchedulingNeighborhoodFromRelaxedIntervals(absl::Span< const int > intervals_to_relax, absl::Span< const int > variables_to_fix, const CpSolverResponse &initial_solution, absl::BitGenRef random, const NeighborhoodGeneratorHelper &helper)
double CenterToCenterL2Distance(const Rectangle &a, const Rectangle &b)
Definition diffn_util.h:134
std::vector< int > UsedVariables(const ConstraintProto &ct)
std::vector< int > UsedIntervals(const ConstraintProto &ct)
void FillDomainInProto(const Domain &domain, ProtoWithDomain *proto)
IntegerValue CapAddI(IntegerValue a, IntegerValue b)
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
void LoadCpModel(const CpModelProto &model_proto, Model *model)
void InsertVariablesFromInterval(const CpModelProto &model_proto, int index, Bitset64< int > &output)
IntegerValue CapSubI(IntegerValue a, IntegerValue b)
OR-Tools root namespace.
int64_t CapSub(int64_t x, int64_t y)
ClosedInterval::Iterator end(ClosedInterval interval)
const bool DEBUG_MODE
Definition radix_sort.h:266
ClosedInterval::Iterator begin(ClosedInterval interval)
Definition model.h:50
std::vector< int > variables_that_can_be_fixed_to_local_optimum
static constexpr int kDefaultArenaSizePerVariable
void GrowToInclude(const Rectangle &other)
Definition diffn_util.h:49
std::vector< std::pair< int, std::pair< int64_t, int64_t > > > reduced_domain_vars
Definition rins.h:41
std::vector< std::pair< int, int64_t > > fixed_vars
Definition rins.h:38