Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cp_model_search.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 <cstddef>
18#include <cstdint>
19#include <functional>
20#include <limits>
21#include <string>
22#include <utility>
23#include <vector>
24
25#include "absl/algorithm/container.h"
26#include "absl/container/flat_hash_map.h"
27#include "absl/container/flat_hash_set.h"
28#include "absl/log/check.h"
29#include "absl/random/distributions.h"
30#include "absl/strings/str_cat.h"
31#include "absl/strings/string_view.h"
32#include "absl/types/span.h"
37#include "ortools/sat/integer.h"
41#include "ortools/sat/model.h"
44#include "ortools/sat/util.h"
46
47namespace operations_research {
48namespace sat {
49
51 : mapping_(*model->GetOrCreate<CpModelMapping>()),
52 boolean_assignment_(model->GetOrCreate<Trail>()->Assignment()),
53 integer_trail_(*model->GetOrCreate<IntegerTrail>()),
54 integer_encoder_(*model->GetOrCreate<IntegerEncoder>()),
55 random_(*model->GetOrCreate<ModelRandomGenerator>()) {}
56
57int CpModelView::NumVariables() const { return mapping_.NumProtoVariables(); }
58
59bool CpModelView::IsFixed(int var) const {
60 if (mapping_.IsBoolean(var)) {
61 return boolean_assignment_.VariableIsAssigned(
62 mapping_.Literal(var).Variable());
63 } else if (mapping_.IsInteger(var)) {
64 return integer_trail_.IsFixed(mapping_.Integer(var));
65 }
66 return true; // Default.
67}
68
69int64_t CpModelView::Min(int var) const {
70 if (mapping_.IsBoolean(var)) {
71 const Literal l = mapping_.Literal(var);
72 return boolean_assignment_.LiteralIsTrue(l) ? 1 : 0;
73 } else if (mapping_.IsInteger(var)) {
74 return integer_trail_.LowerBound(mapping_.Integer(var)).value();
75 }
76 return 0; // Default.
77}
78
79int64_t CpModelView::Max(int var) const {
80 if (mapping_.IsBoolean(var)) {
81 const Literal l = mapping_.Literal(var);
82 return boolean_assignment_.LiteralIsFalse(l) ? 0 : 1;
83 } else if (mapping_.IsInteger(var)) {
84 return integer_trail_.UpperBound(mapping_.Integer(var)).value();
85 }
86 return 0; // Default.
87}
88
90 int64_t value) const {
91 DCHECK(!IsFixed(var));
93 if (mapping_.IsBoolean(var)) {
94 DCHECK(value == 0 || value == 1);
95 if (value == 1) {
96 result.boolean_literal_index = mapping_.Literal(var).Index();
97 }
98 } else if (mapping_.IsInteger(var)) {
100 mapping_.Integer(var), IntegerValue(value));
101 }
102 return result;
103}
104
106 int64_t value) const {
107 DCHECK(!IsFixed(var));
109 if (mapping_.IsBoolean(var)) {
110 DCHECK(value == 0 || value == 1);
111 if (value == 0) {
112 result.boolean_literal_index = mapping_.Literal(var).NegatedIndex();
113 }
114 } else if (mapping_.IsInteger(var)) {
115 result.integer_literal = IntegerLiteral::LowerOrEqual(mapping_.Integer(var),
116 IntegerValue(value));
117 }
118 return result;
119}
120
122 DCHECK(!IsFixed(var));
124 if (mapping_.IsBoolean(var)) {
125 result.boolean_literal_index = mapping_.Literal(var).NegatedIndex();
126 } else if (mapping_.IsInteger(var)) {
127 const IntegerVariable variable = mapping_.Integer(var);
128 const std::vector<ValueLiteralPair> encoding =
129 integer_encoder_.FullDomainEncoding(variable);
130
131 // 5 values -> returns the second.
132 // 4 values -> returns the second too.
133 // Array is 0 based.
134 const int target = (static_cast<int>(encoding.size()) + 1) / 2 - 1;
135 result.boolean_literal_index = encoding[target].literal.Index();
136 }
137 return result;
138}
139
141 int64_t ub) const {
142 DCHECK(!IsFixed(var));
144 if (mapping_.IsBoolean(var)) {
145 if (absl::Bernoulli(random_, 0.5)) {
146 result.boolean_literal_index = mapping_.Literal(var).Index();
147 } else {
148 result.boolean_literal_index = mapping_.Literal(var).NegatedIndex();
149 }
150 } else if (mapping_.IsInteger(var)) {
151 if (absl::Bernoulli(random_, 0.5)) {
153 mapping_.Integer(var), IntegerValue(lb + (ub - lb) / 2));
154 } else {
156 mapping_.Integer(var), IntegerValue(ub - (ub - lb) / 2));
157 }
158 }
159 return result;
160}
161
162// Stores one variable and its strategy value.
163struct VarValue {
164 int ref;
165 int64_t value;
166};
167
168namespace {
169
170// TODO(user): Save this somewhere instead of recomputing it.
171bool ModelHasSchedulingConstraints(const CpModelProto& cp_model_proto) {
172 for (const ConstraintProto& ct : cp_model_proto.constraints()) {
173 if (ct.constraint_case() == ConstraintProto::kNoOverlap) return true;
174 if (ct.constraint_case() == ConstraintProto::kCumulative) return true;
175 }
176 return false;
177}
178
179void AddExtraSchedulingPropagators(SatParameters& new_params) {
180 new_params.set_exploit_all_precedences(true);
181 new_params.set_use_hard_precedences_in_cumulative(true);
182 new_params.set_use_overload_checker_in_cumulative(true);
183 new_params.set_use_strong_propagation_in_disjunctive(true);
184 new_params.set_use_timetable_edge_finding_in_cumulative(true);
185 new_params.set_use_conservative_scale_overload_checker(true);
186 new_params.set_max_pairs_pairwise_reasoning_in_no_overlap_2d(5000);
187 new_params.set_use_timetabling_in_no_overlap_2d(true);
188 new_params.set_use_energetic_reasoning_in_no_overlap_2d(true);
189 new_params.set_use_area_energetic_reasoning_in_no_overlap_2d(true);
190 new_params.set_use_try_edge_reasoning_in_no_overlap_2d(true);
191 new_params.set_no_overlap_2d_boolean_relations_limit(100);
192}
193
194// We want a random tie breaking among variables with equivalent values.
195struct NoisyInteger {
196 int64_t value;
197 double noise;
198
199 bool operator<=(const NoisyInteger& other) const {
200 return value < other.value ||
201 (value == other.value && noise <= other.noise);
202 }
203 bool operator>(const NoisyInteger& other) const {
204 return value > other.value || (value == other.value && noise > other.noise);
205 }
206};
207
208} // namespace
209
211 const CpModelProto& cp_model_proto, Model* model) {
212 if (cp_model_proto.search_strategy().empty()) return nullptr;
213
214 std::vector<DecisionStrategyProto> strategies;
215 for (const DecisionStrategyProto& proto : cp_model_proto.search_strategy()) {
216 strategies.push_back(proto);
217 }
218 const auto& view = *model->GetOrCreate<CpModelView>();
219 const auto& parameters = *model->GetOrCreate<SatParameters>();
220 auto* random = model->GetOrCreate<ModelRandomGenerator>();
221
222 // Note that we copy strategies to keep the return function validity
223 // independently of the life of the passed vector.
224 return [&view, &parameters, random, strategies]() {
225 for (const DecisionStrategyProto& strategy : strategies) {
226 int candidate_ref = -1;
227 int64_t candidate_value = std::numeric_limits<int64_t>::max();
228
229 // TODO(user): Improve the complexity if this becomes an issue which
230 // may be the case if we do a fixed_search.
231
232 // To store equivalent variables in randomized search.
233 const bool randomize_decision =
234 parameters.search_random_variable_pool_size() > 1;
235 TopN<int, NoisyInteger> top_variables(
236 randomize_decision ? parameters.search_random_variable_pool_size()
237 : 1);
238
239 for (const LinearExpressionProto& expr : strategy.exprs()) {
240 const int var = expr.vars(0);
241 if (view.IsFixed(var)) continue;
242
243 int64_t coeff = expr.coeffs(0);
244 int64_t offset = expr.offset();
245 int64_t lb = view.Min(var);
246 int64_t ub = view.Max(var);
247 int ref = var;
248 if (coeff < 0) {
249 lb = -view.Max(var);
250 ub = -view.Min(var);
251 coeff = -coeff;
252 ref = NegatedRef(var);
253 }
254
255 int64_t value(0);
256 switch (strategy.variable_selection_strategy()) {
258 break;
260 value = coeff * lb + offset;
261 break;
263 value = -(coeff * ub + offset);
264 break;
266 // The size of the domain is not multiplied by the coeff.
267 value = ub - lb + 1;
268 break;
270 // The size of the domain is not multiplied by the coeff.
271 value = -(ub - lb + 1);
272 break;
273 default:
274 LOG(FATAL) << "Unknown VariableSelectionStrategy "
275 << strategy.variable_selection_strategy();
276 }
277
278 if (randomize_decision) {
279 // We need to use -value as we want the minimum valued variables.
280 // We add a random noise to get improve the entropy.
281 const double noise = absl::Uniform(*random, 0., 1.0);
282 top_variables.Add(ref, {-value, noise});
283 candidate_value = std::min(candidate_value, value);
284 } else if (value < candidate_value) {
285 candidate_ref = ref;
286 candidate_value = value;
287 }
288
289 // We can stop scanning if the variable selection strategy is to use the
290 // first unbound variable and no randomization is needed.
291 if (strategy.variable_selection_strategy() ==
293 !randomize_decision) {
294 break;
295 }
296 }
297
298 // Check if one active variable has been found.
299 if (candidate_value == std::numeric_limits<int64_t>::max()) continue;
300
301 // Pick the winner when decisions are randomized.
302 if (randomize_decision) {
303 const std::vector<int>& candidates = top_variables.UnorderedElements();
304 candidate_ref = candidates[absl::Uniform(
305 *random, 0, static_cast<int>(candidates.size()))];
306 }
307
309 strategy.domain_reduction_strategy();
310 if (!RefIsPositive(candidate_ref)) {
311 switch (selection) {
314 break;
317 break;
320 break;
323 break;
324 default:
325 break;
326 }
327 }
328
329 const int var = PositiveRef(candidate_ref);
330 const int64_t lb = view.Min(var);
331 const int64_t ub = view.Max(var);
332 switch (selection) {
334 return view.LowerOrEqual(var, lb);
336 return view.GreaterOrEqual(var, ub);
338 return view.LowerOrEqual(var, lb + (ub - lb) / 2);
340 return view.GreaterOrEqual(var, ub - (ub - lb) / 2);
342 return view.MedianValue(var);
344 return view.RandomSplit(var, lb, ub);
345 default:
346 LOG(FATAL) << "Unknown DomainReductionStrategy "
347 << strategy.domain_reduction_strategy();
348 }
349 }
351 };
352}
353
354// TODO(user): Implement a routing search.
356 const CpModelProto& cp_model_proto, Model* model) {
357 if (ModelHasSchedulingConstraints(cp_model_proto)) {
358 std::vector<std::function<BooleanOrIntegerLiteral()>> heuristics;
359 const auto& params = *model->GetOrCreate<SatParameters>();
360 bool possible_new_constraints = false;
361 if (params.use_dynamic_precedence_in_disjunctive()) {
362 possible_new_constraints = true;
363 heuristics.push_back(DisjunctivePrecedenceSearchHeuristic(model));
364 }
365 if (params.use_dynamic_precedence_in_cumulative()) {
366 possible_new_constraints = true;
367 heuristics.push_back(CumulativePrecedenceSearchHeuristic(model));
368 }
369
370 // Tricky: we need to create this at level zero in case there are no linear
371 // constraint in the model at the beginning.
372 //
373 // TODO(user): Alternatively, support creation of SatPropagator at positive
374 // level.
375 if (possible_new_constraints && params.new_linear_propagation()) {
377 }
378
379 heuristics.push_back(SchedulingSearchHeuristic(model));
380 return SequentialSearch(std::move(heuristics));
381 }
382 return PseudoCost(model);
383}
384
385std::function<BooleanOrIntegerLiteral()>
387 absl::Span<const IntegerVariable> variable_mapping,
388 IntegerVariable objective_var, Model* model) {
389 const auto& params = *model->GetOrCreate<SatParameters>();
390 if (!params.instantiate_all_variables()) {
391 return []() { return BooleanOrIntegerLiteral(); };
392 }
393
394 std::vector<IntegerVariable> decisions;
395 for (const IntegerVariable var : variable_mapping) {
396 if (var == kNoIntegerVariable) continue;
397
398 // Make sure we try to fix the objective to its lowest value first.
399 // TODO(user): we could also fix terms of the objective in the right
400 // direction.
401 if (var == NegationOf(objective_var)) {
402 decisions.push_back(objective_var);
403 } else {
404 decisions.push_back(var);
405 }
406 }
407 return FirstUnassignedVarAtItsMinHeuristic(decisions, model);
408}
409
410// Constructs a search strategy that follow the hint from the model.
412 const CpModelProto& cp_model_proto, CpModelMapping* mapping, Model* model) {
413 std::vector<BooleanOrIntegerVariable> vars;
414 std::vector<IntegerValue> values;
415 for (int i = 0; i < cp_model_proto.solution_hint().vars_size(); ++i) {
416 const int ref = cp_model_proto.solution_hint().vars(i);
417 CHECK(RefIsPositive(ref));
419 if (mapping->IsBoolean(ref)) {
420 var.bool_var = mapping->Literal(ref).Variable();
421 } else {
422 var.int_var = mapping->Integer(ref);
423 }
424 vars.push_back(var);
425 values.push_back(IntegerValue(cp_model_proto.solution_hint().values(i)));
426 }
427 return FollowHint(vars, values, model);
428}
429
431 std::function<BooleanOrIntegerLiteral()> user_search,
432 std::function<BooleanOrIntegerLiteral()> heuristic_search,
433 std::function<BooleanOrIntegerLiteral()> integer_completion) {
434 // We start by the user specified heuristic.
435 std::vector<std::function<BooleanOrIntegerLiteral()>> heuristics;
436 if (user_search != nullptr) {
437 heuristics.push_back(user_search);
438 }
439 if (heuristic_search != nullptr) {
440 heuristics.push_back(heuristic_search);
441 }
442 if (integer_completion != nullptr) {
443 heuristics.push_back(integer_completion);
444 }
445
446 return SequentialSearch(heuristics);
447}
448
450 const CpModelProto& cp_model_proto,
451 absl::Span<const IntegerVariable> variable_mapping,
452 std::function<BooleanOrIntegerLiteral()> instrumented_strategy,
453 Model* model) {
454 std::vector<int> ref_to_display;
455 for (int i = 0; i < cp_model_proto.variables_size(); ++i) {
456 if (variable_mapping[i] == kNoIntegerVariable) continue;
457 if (cp_model_proto.variables(i).name().empty()) continue;
458 ref_to_display.push_back(i);
459 }
460 std::sort(ref_to_display.begin(), ref_to_display.end(), [&](int i, int j) {
461 return cp_model_proto.variables(i).name() <
462 cp_model_proto.variables(j).name();
463 });
464
465 std::vector<std::pair<int64_t, int64_t>> old_domains(variable_mapping.size());
466 return [instrumented_strategy, model, variable_mapping, &cp_model_proto,
467 old_domains, ref_to_display]() mutable {
468 const BooleanOrIntegerLiteral decision = instrumented_strategy();
469 if (!decision.HasValue()) return decision;
470
471 if (decision.boolean_literal_index != kNoLiteralIndex) {
472 const Literal l = Literal(decision.boolean_literal_index);
473 LOG(INFO) << "Boolean decision " << l;
474 const auto& encoder = model->Get<IntegerEncoder>();
475 for (const IntegerLiteral i_lit : encoder->GetIntegerLiterals(l)) {
476 LOG(INFO) << " - associated with " << i_lit;
477 }
478 for (const auto [var, value] : encoder->GetEqualityLiterals(l)) {
479 LOG(INFO) << " - associated with " << var << " == " << value;
480 }
481 } else {
482 LOG(INFO) << "Integer decision " << decision.integer_literal;
483 }
484 const int level = model->Get<Trail>()->CurrentDecisionLevel();
485 std::string to_display =
486 absl::StrCat("Diff since last call, level=", level, "\n");
487 IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
488 for (const int ref : ref_to_display) {
489 const IntegerVariable var = variable_mapping[ref];
490 const std::pair<int64_t, int64_t> new_domain(
491 integer_trail->LowerBound(var).value(),
492 integer_trail->UpperBound(var).value());
493 if (new_domain != old_domains[ref]) {
494 absl::StrAppend(&to_display, cp_model_proto.variables(ref).name(), " [",
495 old_domains[ref].first, ",", old_domains[ref].second,
496 "] -> [", new_domain.first, ",", new_domain.second,
497 "]\n");
498 old_domains[ref] = new_domain;
499 }
500 }
501 LOG(INFO) << to_display;
502 return decision;
503 };
504}
505
506absl::flat_hash_map<std::string, SatParameters> GetNamedParameters(
507 SatParameters base_params) {
508 absl::flat_hash_map<std::string, SatParameters> strategies;
509
510 // By default we disable the logging when we generate a set of parameter. It
511 // is possible to force it by setting it in the corresponding named parameter
512 // via the subsolver_params field.
513 base_params.set_log_search_progress(false);
514
515 // The "default" name can be used for the base_params unchanged.
516 strategies["default"] = base_params;
517
518 // Lp variations only.
519 {
520 SatParameters new_params = base_params;
521 new_params.set_linearization_level(0);
522 strategies["no_lp"] = new_params;
523 new_params.set_linearization_level(1);
524 strategies["default_lp"] = new_params;
525 new_params.set_linearization_level(2);
526 new_params.set_add_lp_constraints_lazily(false);
527 strategies["max_lp"] = new_params;
528 new_params.set_use_symmetry_in_lp(true);
529 strategies["max_lp_sym"] = new_params;
530 }
531
532 // Core. Note that we disable the lp here because it is faster on the minizinc
533 // benchmark.
534 //
535 // TODO(user): Do more experiments, the LP with core could be useful, but we
536 // probably need to incorporate the newly created integer variables from the
537 // core algorithm into the LP.
538 {
539 SatParameters new_params = base_params;
541 new_params.set_optimize_with_core(true);
542 new_params.set_linearization_level(0);
543 strategies["core"] = new_params;
544 }
545
546 // It can be interesting to try core and lp.
547 {
548 SatParameters new_params = base_params;
550 new_params.set_optimize_with_core(true);
551 new_params.set_linearization_level(1);
552 strategies["core_default_lp"] = new_params;
553 }
554
555 {
556 SatParameters new_params = base_params;
558 new_params.set_optimize_with_core(true);
559 new_params.set_linearization_level(2);
560 strategies["core_max_lp"] = new_params;
561 }
562
563 {
564 SatParameters new_params = base_params;
566 new_params.set_optimize_with_core(true);
567 new_params.set_optimize_with_max_hs(true);
568 strategies["max_hs"] = new_params;
569 }
570
571 {
572 SatParameters new_params = base_params;
573 new_params.set_optimize_with_lb_tree_search(true);
574 // We do not want to change the objective_var lb from outside as it gives
575 // better result to only use locally derived reason in that algo.
576 new_params.set_share_objective_bounds(false);
577
578 new_params.set_linearization_level(0);
579 strategies["lb_tree_search_no_lp"] = new_params;
580
581 new_params.set_linearization_level(2);
582 if (base_params.use_dual_scheduling_heuristics()) {
583 AddExtraSchedulingPropagators(new_params);
584 }
585 // We want to spend more time on the LP here.
586 new_params.set_add_lp_constraints_lazily(false);
587 new_params.set_root_lp_iterations(100'000);
588 strategies["lb_tree_search"] = new_params;
589 }
590
591 {
592 SatParameters new_params = base_params;
593 new_params.set_use_objective_lb_search(true);
594
595 new_params.set_linearization_level(0);
596 strategies["objective_lb_search_no_lp"] = new_params;
597
598 new_params.set_linearization_level(1);
599 strategies["objective_lb_search"] = new_params;
600
601 if (base_params.use_dual_scheduling_heuristics()) {
602 AddExtraSchedulingPropagators(new_params);
603 }
604 new_params.set_linearization_level(2);
605 strategies["objective_lb_search_max_lp"] = new_params;
606 }
607
608 {
609 SatParameters new_params = base_params;
610 new_params.set_use_objective_shaving_search(true);
611 new_params.set_cp_model_presolve(true);
612 new_params.set_cp_model_probing_level(0);
613 new_params.set_symmetry_level(0);
614 if (base_params.use_dual_scheduling_heuristics()) {
615 AddExtraSchedulingPropagators(new_params);
616 }
617
618 strategies["objective_shaving"] = new_params;
619
620 new_params.set_linearization_level(0);
621 strategies["objective_shaving_no_lp"] = new_params;
622
623 new_params.set_linearization_level(2);
624 strategies["objective_shaving_max_lp"] = new_params;
625 }
626
627 {
628 SatParameters new_params = base_params;
629 new_params.set_cp_model_presolve(true);
630 new_params.set_cp_model_probing_level(0);
631 new_params.set_symmetry_level(0);
632 new_params.set_share_objective_bounds(false);
633 new_params.set_share_level_zero_bounds(false);
635
636 strategies["variables_shaving"] = new_params;
637
638 new_params.set_linearization_level(0);
639 strategies["variables_shaving_no_lp"] = new_params;
640
641 if (base_params.use_dual_scheduling_heuristics()) {
642 AddExtraSchedulingPropagators(new_params);
643 }
644 new_params.set_linearization_level(2);
645 strategies["variables_shaving_max_lp"] = new_params;
646 }
647
648 {
649 SatParameters new_params = base_params;
651 new_params.set_use_probing_search(true);
653 // Use a small deterministic time to avoid spending too much time on
654 // shaving by default. The probing workers will increase it as needed.
656 if (base_params.use_dual_scheduling_heuristics()) {
657 AddExtraSchedulingPropagators(new_params);
658 }
659 strategies["probing"] = new_params;
660
661 new_params.set_linearization_level(0);
662 strategies["probing_no_lp"] = new_params;
663
664 // We want to spend more time on the LP here.
665 new_params.set_linearization_level(2);
666 new_params.set_add_lp_constraints_lazily(false);
667 new_params.set_root_lp_iterations(100'000);
668 strategies["probing_max_lp"] = new_params;
669 }
670
671 // Search variation.
672 {
673 SatParameters new_params = base_params;
675 strategies["auto"] = new_params;
676
680 strategies["fixed"] = new_params;
681 }
682
683 // Quick restart.
684 {
685 // TODO(user): Experiment with search_random_variable_pool_size.
686 SatParameters new_params = base_params;
687 new_params.set_search_branching(
689 strategies["quick_restart"] = new_params;
690
691 new_params.set_linearization_level(0);
692 strategies["quick_restart_no_lp"] = new_params;
693
694 new_params.set_linearization_level(2);
695 strategies["quick_restart_max_lp"] = new_params;
696 }
697
698 {
699 SatParameters new_params = base_params;
700 new_params.set_linearization_level(2);
702 if (base_params.use_dual_scheduling_heuristics()) {
703 AddExtraSchedulingPropagators(new_params);
704 }
705 strategies["reduced_costs"] = new_params;
706 }
707
708 {
709 // Note: no dual scheduling heuristics.
710 SatParameters new_params = base_params;
711 new_params.set_linearization_level(2);
713 new_params.set_exploit_best_solution(true);
714 strategies["pseudo_costs"] = new_params;
715 }
716
717 // Less encoding.
718 {
719 SatParameters new_params = base_params;
720 new_params.set_boolean_encoding_level(0);
721 strategies["less_encoding"] = new_params;
722 }
723
724 // Base parameters for shared tree worker.
725 {
726 SatParameters new_params = base_params;
727 new_params.set_use_shared_tree_search(true);
729 new_params.set_linearization_level(0);
730
731 // These settings don't make sense with shared tree search, turn them off as
732 // they can break things.
733 new_params.set_optimize_with_core(false);
734 new_params.set_optimize_with_lb_tree_search(false);
735 new_params.set_optimize_with_max_hs(false);
736
737 // Given that each workers work on a different part of the subtree, it might
738 // not be a good idea to try to work on a global shared solution.
739 //
740 // TODO(user): Experiments more here, in particular we could follow it if
741 // it falls into the current subtree.
742 new_params.set_polarity_exploit_ls_hints(false);
743
744 strategies["shared_tree"] = new_params;
745 }
746
747 // Base parameters for LNS worker.
748 {
749 SatParameters lns_params = base_params;
750 lns_params.set_stop_after_first_solution(false);
751 lns_params.set_cp_model_presolve(true);
752
753 // We disable costly presolve/inprocessing.
754 lns_params.set_use_sat_inprocessing(false);
755 lns_params.set_cp_model_probing_level(0);
756 lns_params.set_symmetry_level(0);
757 lns_params.set_find_big_linear_overlap(false);
758
759 lns_params.set_log_search_progress(false);
760 lns_params.set_debug_crash_on_bad_hint(false); // Can happen in lns.
761 lns_params.set_solution_pool_size(1); // Keep the best solution found.
762 strategies["lns"] = lns_params;
763
764 // Note that we only do this for the derived parameters. The strategy "lns"
765 // will be handled along with the other ones.
766 auto it = absl::c_find_if(
767 base_params.subsolver_params(),
768 [](const SatParameters& params) { return params.name() == "lns"; });
769 if (it != base_params.subsolver_params().end()) {
770 lns_params.MergeFrom(*it);
771 }
772
773 SatParameters lns_params_base = lns_params;
774 lns_params_base.set_linearization_level(0);
776 strategies["lns_base"] = lns_params_base;
777
778 SatParameters lns_params_stalling = lns_params;
780 lns_params_stalling.set_search_random_variable_pool_size(5);
781 strategies["lns_stalling"] = lns_params_stalling;
782
783 // For routing, the LP relaxation seems pretty important, so we prefer an
784 // high linearization level to solve LNS subproblems.
785 SatParameters lns_params_routing = lns_params;
786 lns_params_routing.set_linearization_level(2);
788 strategies["lns_routing"] = lns_params_routing;
789 }
790
791 // Add user defined ones.
792 // Note that this might be merged to our default ones.
793 for (const SatParameters& params : base_params.subsolver_params()) {
794 auto it = strategies.find(params.name());
795 if (it != strategies.end()) {
796 it->second.MergeFrom(params);
797 } else {
798 // Merge the named parameters with the base parameters to create the new
799 // parameters.
800 SatParameters new_params = base_params;
801 new_params.MergeFrom(params);
802 strategies[params.name()] = new_params;
803 }
804 }
805
806 // Fix names (we don't set them above).
807 for (auto& [name, params] : strategies) {
808 params.set_name(name);
809 }
810
811 return strategies;
812}
813
814// Note: in flatzinc setting, we know we always have a fixed search defined.
815//
816// Things to try:
817// - Specialize for purely boolean problems
818// - Disable linearization_level options for non linear problems
819// - Fast restart in randomized search
820// - Different propatation levels for scheduling constraints
821std::vector<SatParameters> GetFullWorkerParameters(
822 const SatParameters& base_params, const CpModelProto& cp_model,
823 int num_already_present, SubsolverNameFilter* filter) {
824 // Defines a set of named strategies so it is easier to read in one place
825 // the one that are used. See below.
826 const auto strategies = GetNamedParameters(base_params);
827
828 // We only use a "fixed search" worker if some strategy is specified or
829 // if we have a scheduling model.
830 //
831 // TODO(user): For scheduling, this is important to find good first solution
832 // but afterwards it is not really great and should probably be replaced by a
833 // LNS worker.
834 const bool use_fixed_strategy = !cp_model.search_strategy().empty() ||
835 ModelHasSchedulingConstraints(cp_model);
836
837 // Our current set of strategies
838 //
839 // TODO(user): Avoid launching two strategies if they are the same,
840 // like if there is no lp, or everything is already linearized at level 1.
841 std::vector<std::string> names;
842
843 // Starts by adding user specified ones.
844 for (const std::string& name : base_params.extra_subsolvers()) {
845 names.push_back(name);
846 }
847
848 // We use the default if empty.
849 if (base_params.subsolvers().empty()) {
850 // Note that the order is important as the list can be truncated.
851 names.push_back("default_lp");
852 names.push_back("fixed");
853 names.push_back("core");
854 names.push_back("no_lp");
855 if (cp_model.has_symmetry()) {
856 names.push_back("max_lp_sym");
857 } else {
858 // If there is no symmetry, max_lp_sym and max_lp are the same, but
859 // we prefer the less confusing name.
860 names.push_back("max_lp");
861 }
862 names.push_back("quick_restart");
863 names.push_back("reduced_costs");
864 names.push_back("quick_restart_no_lp");
865 names.push_back("pseudo_costs");
866 names.push_back("lb_tree_search");
867 names.push_back("probing");
868 names.push_back("objective_lb_search");
869 names.push_back("objective_shaving_no_lp");
870 names.push_back("objective_shaving_max_lp");
871 names.push_back("probing_max_lp");
872 names.push_back("probing_no_lp");
873 names.push_back("objective_lb_search_no_lp");
874 names.push_back("objective_lb_search_max_lp");
875 if (cp_model.has_symmetry()) {
876 names.push_back("max_lp");
877 }
878 } else {
879 for (const std::string& name : base_params.subsolvers()) {
880 // Hack for flatzinc. At the time of parameter setting, the objective is
881 // not expanded. So we do not know if core is applicable or not.
882 if (name == "core_or_no_lp") {
883 if (!cp_model.has_objective() ||
884 cp_model.objective().vars_size() <= 1) {
885 names.push_back("no_lp");
886 } else {
887 names.push_back("core");
888 }
889 } else {
890 names.push_back(name);
891 }
892 }
893 }
894
895 // Remove the names that should be ignored.
896 int new_size = 0;
897 for (const std::string& name : names) {
898 if (filter->Keep(name)) {
899 names[new_size++] = name;
900 }
901 }
902 names.resize(new_size);
903
904 // Creates the diverse set of parameters with names and seed.
905 std::vector<SatParameters> result;
906 for (const std::string& name : names) {
907 SatParameters params = strategies.at(name);
908
909 // Do some filtering.
910 if (!use_fixed_strategy &&
912 continue;
913 }
914
915 // TODO(user): Enable probing_search in deterministic mode.
916 // Currently it timeouts on small problems as the deterministic time limit
917 // never hits the sharding limit.
918 if (params.use_probing_search() && params.interleave_search()) continue;
919
920 // TODO(user): Enable shaving search in interleave mode.
921 // Currently it do not respect ^C, and has no per chunk time limit.
922 if ((params.use_objective_shaving_search()) && params.interleave_search()) {
923 continue;
924 }
925
926 // In the corner case of empty variable, lets not schedule the probing as
927 // it currently just loop forever instead of returning right away.
928 if (params.use_probing_search() && cp_model.variables().empty()) continue;
929
930 if (cp_model.has_objective() && !cp_model.objective().vars().empty()) {
931 // Disable core search if there is only 1 term in the objective.
932 if (cp_model.objective().vars().size() == 1 &&
933 params.optimize_with_core()) {
934 continue;
935 }
936
937 if (name == "less_encoding") continue;
938
939 // Disable subsolvers that do not implement the deterministic mode.
940 //
941 // TODO(user): Enable lb_tree_search in deterministic mode.
942 if (params.interleave_search() &&
944 params.use_objective_lb_search())) {
945 continue;
946 }
947 } else {
948 // Remove subsolvers that require an objective.
949 if (params.optimize_with_lb_tree_search()) continue;
950 if (params.optimize_with_core()) continue;
951 if (params.use_objective_lb_search()) continue;
952 if (params.use_objective_shaving_search()) continue;
953 if (params.search_branching() == SatParameters::LP_SEARCH) continue;
955 continue;
956 }
957 }
958
959 // Add this strategy.
960 params.set_name(name);
962 base_params.random_seed(), static_cast<int64_t>(result.size()) + 1));
963 result.push_back(params);
964 }
965
966 // In interleaved mode, we run all of them.
967 //
968 // TODO(user): Actually make sure the gap num_workers <-> num_heuristics is
969 // contained.
970 if (base_params.interleave_search()) return result;
971
972 // Apply the logic for how many we keep.
973 int num_to_keep = base_params.num_full_subsolvers();
974 if (num_to_keep == 0) {
975 // Derive some automatic number to leave room for LS/LNS and other
976 // strategies not taken into account here.
977 const int num_available =
978 std::max(0, base_params.num_workers() - num_already_present);
979
980 const auto heuristic_num_workers = [](int num_workers) {
981 DCHECK_GE(num_workers, 0);
982 if (num_workers == 1) return 1;
983 if (num_workers <= 4) return num_workers - 1;
984 if (num_workers <= 8) return num_workers - 2;
985 if (num_workers <= 16) return num_workers - (num_workers / 4 + 1);
986 return num_workers - (num_workers / 2 - 3);
987 };
988
989 num_to_keep = heuristic_num_workers(num_available);
990 }
991
992 if (result.size() > num_to_keep) {
993 result.resize(std::max(0, num_to_keep));
994 }
995 return result;
996}
997
998std::vector<SatParameters> GetFirstSolutionBaseParams(
999 const SatParameters& base_params) {
1000 std::vector<SatParameters> result;
1001
1002 const auto get_base = [&result, &base_params](bool fj) {
1003 SatParameters new_params = base_params;
1004 new_params.set_log_search_progress(false);
1005 new_params.set_use_feasibility_jump(fj);
1006
1007 const int base_seed = base_params.random_seed();
1008 new_params.set_random_seed(CombineSeed(base_seed, result.size()));
1009 return new_params;
1010 };
1011
1012 // Add one feasibility jump.
1013 if (base_params.use_feasibility_jump()) {
1014 SatParameters new_params = get_base(true);
1015 new_params.set_name("fj");
1017 result.push_back(new_params);
1018 }
1019
1020 // Random search.
1021 for (int i = 0; i < 2; ++i) {
1022 SatParameters new_params = get_base(false);
1025 if (i % 2 == 0) {
1026 new_params.set_name("fs_random_no_lp");
1027 new_params.set_linearization_level(0);
1028 } else {
1029 new_params.set_name("fs_random");
1030 }
1031 result.push_back(new_params);
1032 }
1033
1034 // Add a second feasibility jump.
1035 if (base_params.use_feasibility_jump()) {
1036 SatParameters new_params = get_base(true);
1037 new_params.set_name("fj");
1039 result.push_back(new_params);
1040 }
1041
1042 // Random quick restart.
1043 for (int i = 0; i < 2; ++i) {
1044 SatParameters new_params = get_base(false);
1046 new_params.set_search_branching(
1048 if (i % 2 == 0) {
1049 new_params.set_name("fs_random_quick_restart_no_lp");
1050 new_params.set_linearization_level(0);
1051 } else {
1052 new_params.set_name("fs_random_quick_restart");
1053 }
1054 result.push_back(new_params);
1055 }
1056
1057 // Add a linear feasibility jump.
1058 // This one seems to perform worse, so we add only 1 for 2 normal LS, and we
1059 // add this late.
1060 if (base_params.use_feasibility_jump()) {
1061 SatParameters new_params = get_base(true);
1062 new_params.set_name("fj_lin");
1064 result.push_back(new_params);
1065 }
1066
1067 return result;
1068}
1069
1070std::vector<SatParameters> RepeatParameters(
1071 absl::Span<const SatParameters> base_params, int num_params_to_generate) {
1072 // Return if we are done.
1073 std::vector<SatParameters> result;
1074 result.assign(base_params.begin(), base_params.end());
1075 if (result.empty()) return result;
1076 if (result.size() >= num_params_to_generate) {
1077 result.resize(num_params_to_generate);
1078 return result;
1079 }
1080
1081 // Repeat parameters until we have enough.
1082 int i = 0;
1083 const int base_size = result.size();
1084 while (result.size() < num_params_to_generate) {
1085 result.push_back(result[i % base_size]);
1086 result.back().set_random_seed(CombineSeed(result.back().random_seed(), i));
1087 ++i;
1088 }
1089 return result;
1090}
1091
1093 for (const auto& pattern : params.filter_subsolvers()) {
1094 filter_patterns_.push_back(pattern);
1095 }
1096 for (const auto& pattern : params.ignore_subsolvers()) {
1097 ignore_patterns_.push_back(pattern);
1098 }
1099
1100 // Hack for backward compatibility and easy of use.
1101 if (params.use_ls_only()) {
1102 filter_patterns_.push_back("ls*");
1103 filter_patterns_.push_back("fj*");
1104 }
1105
1106 if (params.use_lns_only()) {
1107 // Still add first solution solvers.
1108 filter_patterns_.push_back("fj*");
1109 filter_patterns_.push_back("fs*");
1110 filter_patterns_.push_back("*lns");
1111 }
1112}
1113
1114bool SubsolverNameFilter::Keep(absl::string_view name) {
1115 last_name_ = name;
1116 if (!filter_patterns_.empty()) {
1117 bool keep = false;
1118 for (const absl::string_view pattern : filter_patterns_) {
1119 if (FNMatch(pattern, name)) {
1120 keep = true;
1121 break;
1122 }
1123 }
1124 if (!keep) {
1125 ignored_.emplace_back(name);
1126 return false;
1127 }
1128 }
1129 for (const absl::string_view pattern : ignore_patterns_) {
1130 if (FNMatch(pattern, name)) {
1131 ignored_.emplace_back(name);
1132 return false;
1133 }
1134 }
1135 return true;
1136}
1137
1138bool SubsolverNameFilter::FNMatch(absl::string_view pattern,
1139 absl::string_view str) {
1140 bool in_wildcard_match = false;
1141 while (true) {
1142 if (pattern.empty()) {
1143 return in_wildcard_match || str.empty();
1144 }
1145 if (str.empty()) {
1146 return pattern.find_first_not_of('*') == pattern.npos;
1147 }
1148 switch (pattern.front()) {
1149 case '*':
1150 pattern.remove_prefix(1);
1151 in_wildcard_match = true;
1152 break;
1153 case '?':
1154 pattern.remove_prefix(1);
1155 str.remove_prefix(1);
1156 break;
1157 default:
1158 if (in_wildcard_match) {
1159 absl::string_view fixed_portion = pattern;
1160 const size_t end = fixed_portion.find_first_of("*?");
1161 if (end != fixed_portion.npos) {
1162 fixed_portion = fixed_portion.substr(0, end);
1163 }
1164 const size_t match = str.find(fixed_portion);
1165 if (match == str.npos) {
1166 return false;
1167 }
1168 pattern.remove_prefix(fixed_portion.size());
1169 str.remove_prefix(match + fixed_portion.size());
1170 in_wildcard_match = false;
1171 } else {
1172 if (pattern.front() != str.front()) {
1173 return false;
1174 }
1175 pattern.remove_prefix(1);
1176 str.remove_prefix(1);
1177 }
1178 break;
1179 }
1180 }
1181}
1182
1183} // namespace sat
1184} // namespace operations_research
IntegerVariable Integer(int ref) const
bool has_symmetry() const
.operations_research.sat.SymmetryProto symmetry = 8;
const ::operations_research::sat::IntegerVariableProto & variables(int index) const
const ::operations_research::sat::ConstraintProto & constraints(int index) const
bool has_objective() const
.operations_research.sat.CpObjectiveProto objective = 4;
const ::operations_research::sat::DecisionStrategyProto & search_strategy(int index) const
int variables_size() const
repeated .operations_research.sat.IntegerVariableProto variables = 2;
const ::operations_research::sat::PartialVariableAssignment & solution_hint() const
const ::operations_research::sat::CpObjectiveProto & objective() const
BooleanOrIntegerLiteral GreaterOrEqual(int var, int64_t value) const
Helpers to generate a decision.
BooleanOrIntegerLiteral LowerOrEqual(int var, int64_t value) const
BooleanOrIntegerLiteral MedianValue(int var) const
int NumVariables() const
The valid indices for the calls below are in [0, num_variables).
bool IsFixed(int var) const
Getters about the current domain of the given variable.
BooleanOrIntegerLiteral RandomSplit(int var, int64_t lb, int64_t ub) const
int vars_size() const
repeated int32 vars = 1;
static constexpr DomainReductionStrategy SELECT_MAX_VALUE
static constexpr DomainReductionStrategy SELECT_MIN_VALUE
DecisionStrategyProto_DomainReductionStrategy DomainReductionStrategy
static constexpr VariableSelectionStrategy CHOOSE_HIGHEST_MAX
static constexpr VariableSelectionStrategy CHOOSE_FIRST
static constexpr DomainReductionStrategy SELECT_MEDIAN_VALUE
static constexpr DomainReductionStrategy SELECT_UPPER_HALF
static constexpr VariableSelectionStrategy CHOOSE_LOWEST_MIN
static constexpr VariableSelectionStrategy CHOOSE_MAX_DOMAIN_SIZE
static constexpr VariableSelectionStrategy CHOOSE_MIN_DOMAIN_SIZE
static constexpr DomainReductionStrategy SELECT_LOWER_HALF
static constexpr DomainReductionStrategy SELECT_RANDOM_HALF
IntegerValue LowerBound(IntegerVariable i) const
Returns the current lower/upper bound of the given integer variable.
Definition integer.h:1317
IntegerValue UpperBound(IntegerVariable i) const
Definition integer.h:1321
BooleanVariable Variable() const
Definition sat_base.h:87
T Get(std::function< T(const Model &)> f) const
Similar to Add() but this is const.
Definition model.h:93
const ::std::string & ignore_subsolvers(int index) const
const ::operations_research::sat::SatParameters & subsolver_params(int index) const
void set_search_branching(::operations_research::sat::SatParameters_SearchBranching value)
static constexpr SearchBranching PORTFOLIO_SEARCH
const ::std::string & extra_subsolvers(int index) const
static constexpr SearchBranching AUTOMATIC_SEARCH
static constexpr SearchBranching RANDOMIZED_SEARCH
void set_feasibility_jump_linearization_level(::int32_t value)
static constexpr SearchBranching FIXED_SEARCH
const ::std::string & subsolvers(int index) const
static constexpr SearchBranching PSEUDO_COST_SEARCH
void set_at_most_one_max_expansion_size(::int32_t value)
const ::std::string & filter_subsolvers(int index) const
::operations_research::sat::SatParameters_SearchBranching search_branching() const
void set_name(Arg_ &&arg, Args_... args)
static constexpr SearchBranching PORTFOLIO_WITH_QUICK_RESTART_SEARCH
void set_no_overlap_2d_boolean_relations_limit(::int32_t value)
static constexpr SearchBranching LP_SEARCH
void MergeFrom(const SatParameters &from)
void set_search_random_variable_pool_size(::int64_t value)
Simple class used to filter executed subsolver names.
SubsolverNameFilter(const SatParameters &params)
Warning, params must outlive the class and be constant.
bool Keep(absl::string_view name)
Shall we keep a parameter with given name?
void Add(Element e, Score score)
Definition util.h:690
const std::vector< Element > & UnorderedElements() const
Definition util.h:713
std::function< BooleanOrIntegerLiteral()> FirstUnassignedVarAtItsMinHeuristic(absl::Span< const IntegerVariable > vars, Model *model)
std::vector< SatParameters > GetFullWorkerParameters(const SatParameters &base_params, const CpModelProto &cp_model, int num_already_present, SubsolverNameFilter *filter)
const LiteralIndex kNoLiteralIndex(-1)
std::function< BooleanOrIntegerLiteral()> DisjunctivePrecedenceSearchHeuristic(Model *model)
std::function< BooleanOrIntegerLiteral()> ConstructIntegerCompletionSearchStrategy(absl::Span< const IntegerVariable > variable_mapping, IntegerVariable objective_var, Model *model)
Constructs an integer completion search strategy.
std::vector< IntegerVariable > NegationOf(absl::Span< const IntegerVariable > vars)
Returns the vector of the negated variables.
Definition integer.cc:52
int CombineSeed(int base_seed, int64_t delta)
We assume delta >= 0 and we only use the low bit of delta.
std::function< BooleanOrIntegerLiteral()> ConstructFixedSearchStrategy(std::function< BooleanOrIntegerLiteral()> user_search, std::function< BooleanOrIntegerLiteral()> heuristic_search, std::function< BooleanOrIntegerLiteral()> integer_completion)
std::function< BooleanOrIntegerLiteral()> ConstructHintSearchStrategy(const CpModelProto &cp_model_proto, CpModelMapping *mapping, Model *model)
Constructs a search strategy that follow the hint from the model.
const IntegerVariable kNoIntegerVariable(-1)
std::function< BooleanOrIntegerLiteral()> PseudoCost(Model *model)
std::function< BooleanOrIntegerLiteral()> ConstructHeuristicSearchStrategy(const CpModelProto &cp_model_proto, Model *model)
Constructs a search strategy tailored for the current model.
std::function< BooleanOrIntegerLiteral()> SchedulingSearchHeuristic(Model *model)
A simple heuristic for scheduling models.
std::vector< SatParameters > GetFirstSolutionBaseParams(const SatParameters &base_params)
std::vector< SatParameters > RepeatParameters(absl::Span< const SatParameters > base_params, int num_params_to_generate)
std::function< BooleanOrIntegerLiteral()> ConstructUserSearchStrategy(const CpModelProto &cp_model_proto, Model *model)
Constructs the search strategy specified in the given CpModelProto.
std::function< BooleanOrIntegerLiteral()> FollowHint(absl::Span< const BooleanOrIntegerVariable > vars, absl::Span< const IntegerValue > values, Model *model)
int NegatedRef(int ref)
Small utility functions to deal with negative variable/literal references.
absl::flat_hash_map< std::string, SatParameters > GetNamedParameters(SatParameters base_params)
std::function< BooleanOrIntegerLiteral()> InstrumentSearchStrategy(const CpModelProto &cp_model_proto, absl::Span< const IntegerVariable > variable_mapping, std::function< BooleanOrIntegerLiteral()> instrumented_strategy, Model *model)
std::function< BooleanOrIntegerLiteral()> CumulativePrecedenceSearchHeuristic(Model *model)
std::function< BooleanOrIntegerLiteral()> SequentialSearch(std::vector< std::function< BooleanOrIntegerLiteral()> > heuristics)
In SWIG mode, we don't want anything besides these top-level includes.
LinearRange operator<=(const LinearExpr &lhs, const LinearExpr &rhs)
ClosedInterval::Iterator end(ClosedInterval interval)
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)
Stores one variable and its strategy value.