Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
optimization.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 <functional>
20#include <string>
21#include <utility>
22#include <vector>
23
24#include "absl/cleanup/cleanup.h"
25#include "absl/container/btree_map.h"
26#include "absl/container/btree_set.h"
27#include "absl/container/flat_hash_set.h"
28#include "absl/log/check.h"
29#include "absl/log/log.h"
30#include "absl/log/vlog_is_on.h"
31#include "absl/strings/str_cat.h"
32#include "absl/strings/str_format.h"
33#include "absl/types/span.h"
38#include "ortools/sat/clause.h"
40#include "ortools/sat/integer.h"
44#include "ortools/sat/model.h"
50#include "ortools/sat/util.h"
54
55namespace operations_research {
56namespace sat {
57
59 std::vector<Literal>* core) {
60 if (solver->ModelIsUnsat()) return;
61 absl::btree_set<LiteralIndex> moved_last;
62 std::vector<Literal> candidate(core->begin(), core->end());
63
64 solver->Backtrack(0);
65 solver->SetAssumptionLevel(0);
66 if (!solver->FinishPropagation()) return;
67 while (!limit->LimitReached()) {
68 // We want each literal in candidate to appear last once in our propagation
69 // order. We want to do that while maximizing the reutilization of the
70 // current assignment prefix, that is minimizing the number of
71 // decision/progagation we need to perform.
72 const int target_level = MoveOneUnprocessedLiteralLast(
73 moved_last, solver->CurrentDecisionLevel(), &candidate);
74 if (target_level == -1) break;
75 solver->Backtrack(target_level);
76 while (!solver->ModelIsUnsat() && !limit->LimitReached() &&
77 solver->CurrentDecisionLevel() < candidate.size()) {
78 const Literal decision = candidate[solver->CurrentDecisionLevel()];
79 if (solver->Assignment().LiteralIsTrue(decision)) {
80 candidate.erase(candidate.begin() + solver->CurrentDecisionLevel());
81 continue;
82 } else if (solver->Assignment().LiteralIsFalse(decision)) {
83 // This is a "weird" API to get the subset of decisions that caused
84 // this literal to be false with reason analysis.
86 candidate = solver->GetLastIncompatibleDecisions();
87 break;
88 } else {
90 }
91 }
92 if (candidate.empty() || solver->ModelIsUnsat()) return;
93 moved_last.insert(candidate.back().Index());
94 }
95
96 solver->Backtrack(0);
97 solver->SetAssumptionLevel(0);
98 if (candidate.size() < core->size()) {
99 VLOG(1) << "minimization with propag " << core->size() << " -> "
100 << candidate.size();
101
102 // We want to preserve the order of literal in the response.
103 absl::flat_hash_set<LiteralIndex> set;
104 for (const Literal l : candidate) set.insert(l.Index());
105 int new_size = 0;
106 for (const Literal l : *core) {
107 if (set.contains(l.Index())) {
108 (*core)[new_size++] = l;
109 }
110 }
111 core->resize(new_size);
112 }
113}
114
116 std::vector<Literal>* core) {
117 if (solver->ModelIsUnsat()) return;
118
119 // TODO(user): tune.
120 if (core->size() > 100 || core->size() == 1) return;
121
122 const bool old_log_state = solver->mutable_logger()->LoggingIsEnabled();
123 solver->mutable_logger()->EnableLogging(false);
124
125 const int old_size = core->size();
126 std::vector<Literal> assumptions;
127 absl::flat_hash_set<LiteralIndex> removed_once;
128 while (true) {
129 if (limit->LimitReached()) break;
130
131 // Find a not yet removed literal to remove.
132 // We prefer to remove high indices since these are more likely to be of
133 // high depth.
134 //
135 // TODO(user): Properly use the node depth instead.
136 int to_remove = -1;
137 for (int i = core->size(); --i >= 0;) {
138 const Literal l = (*core)[i];
139 const auto [_, inserted] = removed_once.insert(l.Index());
140 if (inserted) {
141 to_remove = i;
142 break;
143 }
144 }
145 if (to_remove == -1) break;
146
147 assumptions.clear();
148 for (int i = 0; i < core->size(); ++i) {
149 if (i == to_remove) continue;
150 assumptions.push_back((*core)[i]);
151 }
152
153 const auto status = solver->ResetAndSolveWithGivenAssumptions(
154 assumptions, /*max_number_of_conflicts=*/1000);
155 if (status == SatSolver::ASSUMPTIONS_UNSAT) {
156 *core = solver->GetLastIncompatibleDecisions();
157 }
158 }
159
160 if (core->size() < old_size) {
161 VLOG(1) << "minimization with search " << old_size << " -> "
162 << core->size();
163 }
164
165 (void)solver->ResetToLevelZero();
166 solver->mutable_logger()->EnableLogging(old_log_state);
167}
168
169bool ProbeLiteral(Literal assumption, SatSolver* solver) {
170 if (solver->ModelIsUnsat()) return false;
171
172 const bool old_log_state = solver->mutable_logger()->LoggingIsEnabled();
173 solver->mutable_logger()->EnableLogging(false);
174
175 // Note that since we only care about Booleans here, even if we have a
176 // feasible solution, it might not be feasible for the full cp_model.
177 //
178 // TODO(user): Still use it if the problem is Boolean only.
179 const auto status = solver->ResetAndSolveWithGivenAssumptions(
180 {assumption}, /*max_number_of_conflicts=*/1'000);
181 if (!solver->ResetToLevelZero()) return false;
182 if (status == SatSolver::ASSUMPTIONS_UNSAT) {
183 if (!solver->AddUnitClause(assumption.Negated())) {
184 return false;
185 }
186 if (!solver->Propagate()) {
187 solver->NotifyThatModelIsUnsat();
188 return false;
189 }
190 }
191
192 solver->mutable_logger()->EnableLogging(old_log_state);
193 return solver->Assignment().LiteralIsAssigned(assumption);
194}
195
196// A core cannot be all true.
198 std::vector<Literal>* core) {
199 int new_size = 0;
200 for (const Literal lit : *core) {
201 if (assignment.LiteralIsTrue(lit)) continue;
202 if (assignment.LiteralIsFalse(lit)) {
203 (*core)[0] = lit;
204 core->resize(1);
205 return;
206 }
207 (*core)[new_size++] = lit;
208 }
209 core->resize(new_size);
210}
211
213 IntegerVariable objective_var,
214 const std::function<void()>& feasible_solution_observer, Model* model) {
215 auto* sat_solver = model->GetOrCreate<SatSolver>();
216 auto* integer_trail = model->GetOrCreate<IntegerTrail>();
217 auto* search = model->GetOrCreate<IntegerSearchHelper>();
218 const SatParameters& parameters = *(model->GetOrCreate<SatParameters>());
219
220 // Simple linear scan algorithm to find the optimal.
221 if (!sat_solver->ResetToLevelZero()) return SatSolver::INFEASIBLE;
222 while (true) {
223 const SatSolver::Status result = search->SolveIntegerProblem();
224 if (result != SatSolver::FEASIBLE) return result;
225
226 // The objective is the current lower bound of the objective_var.
227 const IntegerValue objective = integer_trail->LowerBound(objective_var);
228
229 // We have a solution!
230 if (feasible_solution_observer != nullptr) {
231 feasible_solution_observer();
232 }
233 if (parameters.stop_after_first_solution()) {
235 }
236
237 // Restrict the objective.
238 sat_solver->Backtrack(0);
239 if (!integer_trail->Enqueue(
240 IntegerLiteral::LowerOrEqual(objective_var, objective - 1), {},
241 {})) {
243 }
244 }
245}
246
248 IntegerVariable objective_var,
249 const std::function<void()>& feasible_solution_observer, Model* model) {
250 const SatParameters old_params = *model->GetOrCreate<SatParameters>();
251 SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
252 IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
253 IntegerEncoder* integer_encoder = model->GetOrCreate<IntegerEncoder>();
254
255 // Set the requested conflict limit.
256 {
257 SatParameters new_params = old_params;
259 old_params.binary_search_num_conflicts());
260 *model->GetOrCreate<SatParameters>() = new_params;
261 }
262
263 // The assumption (objective <= value) for values in
264 // [unknown_min, unknown_max] reached the conflict limit.
265 bool loop = true;
266 IntegerValue unknown_min = integer_trail->UpperBound(objective_var);
267 IntegerValue unknown_max = integer_trail->LowerBound(objective_var);
268 while (loop) {
269 sat_solver->Backtrack(0);
270 const IntegerValue lb = integer_trail->LowerBound(objective_var);
271 const IntegerValue ub = integer_trail->UpperBound(objective_var);
272 unknown_min = std::min(unknown_min, ub);
273 unknown_max = std::max(unknown_max, lb);
274
275 // We first refine the lower bound and then the upper bound.
276 IntegerValue target;
277 if (lb < unknown_min) {
278 target = lb + (unknown_min - lb) / 2;
279 } else if (unknown_max < ub) {
280 target = ub - (ub - unknown_max) / 2;
281 } else {
282 VLOG(1) << "Binary-search, done.";
283 break;
284 }
285 VLOG(1) << "Binary-search, objective: [" << lb << "," << ub << "]"
286 << " tried: [" << unknown_min << "," << unknown_max << "]"
287 << " target: obj<=" << target;
288 SatSolver::Status result;
289 if (target < ub) {
290 const Literal assumption = integer_encoder->GetOrCreateAssociatedLiteral(
291 IntegerLiteral::LowerOrEqual(objective_var, target));
292 result = ResetAndSolveIntegerProblem({assumption}, model);
293 } else {
294 result = ResetAndSolveIntegerProblem({}, model);
295 }
296
297 switch (result) {
299 loop = false;
300 break;
301 }
303 // Update the objective lower bound.
304 sat_solver->Backtrack(0);
305 if (!integer_trail->Enqueue(
306 IntegerLiteral::GreaterOrEqual(objective_var, target + 1), {},
307 {})) {
308 loop = false;
309 }
310 break;
311 }
312 case SatSolver::FEASIBLE: {
313 // The objective is the current lower bound of the objective_var.
314 const IntegerValue objective = integer_trail->LowerBound(objective_var);
315 if (feasible_solution_observer != nullptr) {
316 feasible_solution_observer();
317 }
318
319 // We have a solution, restrict the objective upper bound to only look
320 // for better ones now.
321 sat_solver->Backtrack(0);
322 if (!integer_trail->Enqueue(
323 IntegerLiteral::LowerOrEqual(objective_var, objective - 1), {},
324 {})) {
325 loop = false;
326 }
327 break;
328 }
330 unknown_min = std::min(target, unknown_min);
331 unknown_max = std::max(target, unknown_max);
332 break;
333 }
334 }
335 }
336
337 sat_solver->Backtrack(0);
338 *model->GetOrCreate<SatParameters>() = old_params;
339}
340
341namespace {
342
343// If the given model is unsat under the given assumptions, returns one or more
344// non-overlapping set of assumptions, each set making the problem infeasible on
345// its own (the cores).
346//
347// In presence of weights, we "generalize" the notions of disjoints core using
348// the WCE idea describe in "Weight-Aware Core Extraction in SAT-Based MaxSAT
349// solving" Jeremias Berg And Matti Jarvisalo.
350//
351// The returned status can be either:
352// - ASSUMPTIONS_UNSAT if the set of returned core perfectly cover the given
353// assumptions, in this case, we don't bother trying to find a SAT solution
354// with no assumptions.
355// - FEASIBLE if after finding zero or more core we have a solution.
356// - LIMIT_REACHED if we reached the time-limit before one of the two status
357// above could be decided.
358//
359// TODO(user): There is many way to combine the WCE and stratification
360// heuristics. I didn't had time to properly compare the different approach. See
361// the WCE papers for some ideas, but there is many more ways to try to find a
362// lot of core at once and try to minimize the minimum weight of each of the
363// cores.
364SatSolver::Status FindCores(std::vector<Literal> assumptions,
365 std::vector<IntegerValue> assumption_weights,
366 IntegerValue stratified_threshold, Model* model,
367 std::vector<std::vector<Literal>>* cores) {
368 cores->clear();
369 SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
370 TimeLimit* limit = model->GetOrCreate<TimeLimit>();
371 do {
372 if (limit->LimitReached()) return SatSolver::LIMIT_REACHED;
373
374 const SatSolver::Status result =
375 ResetAndSolveIntegerProblem(assumptions, model);
376 if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
377 std::vector<Literal> core = sat_solver->GetLastIncompatibleDecisions();
378 if (sat_solver->parameters().core_minimization_level() > 0) {
379 MinimizeCoreWithPropagation(limit, sat_solver, &core);
380 }
381 if (core.size() == 1) {
382 if (!sat_solver->AddUnitClause(core[0].Negated())) {
384 }
385 }
386 if (core.empty()) return sat_solver->UnsatStatus();
387 cores->push_back(core);
388 if (!sat_solver->parameters().find_multiple_cores()) break;
389
390 // Recover the original indices of the assumptions that are part of the
391 // core.
392 std::vector<int> indices;
393 {
394 absl::btree_set<Literal> temp(core.begin(), core.end());
395 for (int i = 0; i < assumptions.size(); ++i) {
396 if (temp.contains(assumptions[i])) {
397 indices.push_back(i);
398 }
399 }
400 }
401
402 // Remove min_weight from the weights of all the assumptions in the core.
403 //
404 // TODO(user): push right away the objective bound by that much? This should
405 // be better in a multi-threading context as we can share more quickly the
406 // better bound.
407 IntegerValue min_weight = assumption_weights[indices.front()];
408 for (const int i : indices) {
409 min_weight = std::min(min_weight, assumption_weights[i]);
410 }
411 for (const int i : indices) {
412 assumption_weights[i] -= min_weight;
413 }
414
415 // Remove from assumptions all the one with a new weight smaller than the
416 // current stratification threshold and see if we can find another core.
417 int new_size = 0;
418 for (int i = 0; i < assumptions.size(); ++i) {
419 if (assumption_weights[i] < stratified_threshold) continue;
420 assumptions[new_size] = assumptions[i];
421 assumption_weights[new_size] = assumption_weights[i];
422 ++new_size;
423 }
424 assumptions.resize(new_size);
425 assumption_weights.resize(new_size);
426 } while (!assumptions.empty());
428}
429
430} // namespace
431
433 IntegerVariable objective_var, absl::Span<const IntegerVariable> variables,
434 absl::Span<const IntegerValue> coefficients,
435 std::function<void()> feasible_solution_observer, Model* model)
436 : parameters_(model->GetOrCreate<SatParameters>()),
437 sat_solver_(model->GetOrCreate<SatSolver>()),
438 clauses_(model->GetOrCreate<ClauseManager>()),
439 time_limit_(model->GetOrCreate<TimeLimit>()),
440 implications_(model->GetOrCreate<BinaryImplicationGraph>()),
441 integer_trail_(model->GetOrCreate<IntegerTrail>()),
442 integer_encoder_(model->GetOrCreate<IntegerEncoder>()),
443 model_(model),
444 objective_var_(objective_var),
445 feasible_solution_observer_(std::move(feasible_solution_observer)) {
446 CHECK_EQ(variables.size(), coefficients.size());
447 for (int i = 0; i < variables.size(); ++i) {
448 if (coefficients[i] > 0) {
449 terms_.push_back({variables[i], coefficients[i]});
450 } else if (coefficients[i] < 0) {
451 terms_.push_back({NegationOf(variables[i]), -coefficients[i]});
452 } else {
453 continue; // coefficients[i] == 0
454 }
455 terms_.back().depth = 0;
456 }
457
458 // This is used by the "stratified" approach. We will only consider terms with
459 // a weight not lower than this threshold. The threshold will decrease as the
460 // algorithm progress.
461 stratification_threshold_ = parameters_->max_sat_stratification() ==
463 ? IntegerValue(1)
465}
466
467bool CoreBasedOptimizer::ProcessSolution() {
468 // We don't assume that objective_var is linked with its linear term, so
469 // we recompute the objective here.
470 IntegerValue objective(0);
471 for (ObjectiveTerm& term : terms_) {
472 const IntegerValue value = integer_trail_->LowerBound(term.var);
473 objective += term.weight * value;
474
475 // Also keep in term.cover_ub the minimum value for term.var that we have
476 // seens amongst all the feasible solutions found so far.
477 term.cover_ub = std::min(term.cover_ub, value);
478 }
479
480 // Test that the current objective value fall in the requested objective
481 // domain, which could potentially have holes.
482 if (!integer_trail_->InitialVariableDomain(objective_var_)
483 .Contains(objective.value())) {
484 return true;
485 }
486
487 if (feasible_solution_observer_ != nullptr) {
488 feasible_solution_observer_();
489 }
490 if (parameters_->stop_after_first_solution()) {
491 stop_ = true;
492 }
493
494 // Constrain objective_var. This has a better result when objective_var is
495 // used in an LP relaxation for instance.
496 sat_solver_->Backtrack(0);
497 sat_solver_->SetAssumptionLevel(0);
498 return integer_trail_->Enqueue(
499 IntegerLiteral::LowerOrEqual(objective_var_, objective - 1), {}, {});
500}
501
502bool CoreBasedOptimizer::PropagateObjectiveBounds() {
503 // We assumes all terms (modulo stratification) at their lower-bound.
504 bool some_bound_were_tightened = true;
505 while (some_bound_were_tightened) {
506 some_bound_were_tightened = false;
507 if (!sat_solver_->ResetToLevelZero()) return false;
508 if (time_limit_->LimitReached()) return true;
509
510 // Compute implied lb.
511 IntegerValue implied_objective_lb(0);
512 for (ObjectiveTerm& term : terms_) {
513 const IntegerValue var_lb = integer_trail_->LowerBound(term.var);
514 term.old_var_lb = var_lb;
515 implied_objective_lb += term.weight * var_lb.value();
516 }
517
518 // Update the objective lower bound with our current bound.
519 if (implied_objective_lb > integer_trail_->LowerBound(objective_var_)) {
520 if (!integer_trail_->Enqueue(IntegerLiteral::GreaterOrEqual(
521 objective_var_, implied_objective_lb),
522 {}, {})) {
523 return false;
524 }
525
526 some_bound_were_tightened = true;
527 }
528
529 // The gap is used to propagate the upper-bound of all variable that are
530 // in the current objective (Exactly like done in the propagation of a
531 // linear constraint with the slack). When this fix a variable to its
532 // lower bound, it is called "hardening" in the max-sat literature. This
533 // has a really beneficial effect on some weighted max-sat problems like
534 // the haplotyping-pedigrees ones.
535 const IntegerValue gap =
536 integer_trail_->UpperBound(objective_var_) - implied_objective_lb;
537
538 for (const ObjectiveTerm& term : terms_) {
539 if (term.weight == 0) continue;
540 const IntegerValue var_lb = integer_trail_->LowerBound(term.var);
541 const IntegerValue var_ub = integer_trail_->UpperBound(term.var);
542 if (var_lb == var_ub) continue;
543
544 // Hardening. This basically just propagate the implied upper bound on
545 // term.var from the current best solution. Note that the gap is
546 // non-negative and the weight positive here. The test is done in order
547 // to avoid any integer overflow provided (ub - lb) do not overflow, but
548 // this is a precondition in our cp-model.
549 if (gap / term.weight < var_ub - var_lb) {
550 some_bound_were_tightened = true;
551 const IntegerValue new_ub = var_lb + gap / term.weight;
552 DCHECK_LT(new_ub, var_ub);
553 if (!integer_trail_->Enqueue(
554 IntegerLiteral::LowerOrEqual(term.var, new_ub), {}, {})) {
555 return false;
556 }
557 }
558 }
559 }
560 return true;
561}
562
563// A basic algorithm is to take the next one, or at least the next one
564// that invalidate the current solution. But to avoid corner cases for
565// problem with a lot of terms all with different objective weights (in
566// which case we will kind of introduce only one assumption per loop
567// which is little), we use an heuristic and take the 90% percentile of
568// the unique weights not yet included.
569//
570// TODO(user): There is many other possible heuristics here, and I
571// didn't have the time to properly compare them.
572void CoreBasedOptimizer::ComputeNextStratificationThreshold() {
573 std::vector<IntegerValue> weights;
574 for (ObjectiveTerm& term : terms_) {
575 if (term.weight >= stratification_threshold_) continue;
576 if (term.weight == 0) continue;
577
578 const IntegerValue var_lb = integer_trail_->LevelZeroLowerBound(term.var);
579 const IntegerValue var_ub = integer_trail_->LevelZeroUpperBound(term.var);
580 if (var_lb == var_ub) continue;
581
582 weights.push_back(term.weight);
583 }
584 if (weights.empty()) {
585 stratification_threshold_ = IntegerValue(0);
586 return;
587 }
588
590 stratification_threshold_ =
591 weights[static_cast<int>(std::floor(0.9 * weights.size()))];
592}
593
594bool CoreBasedOptimizer::CoverOptimization() {
595 if (!sat_solver_->ResetToLevelZero()) return false;
596
597 // We set a fix deterministic time limit per all sub-solves and skip to the
598 // next core if the sum of the sub-solves is also over this limit.
599 constexpr double max_dtime_per_core = 0.5;
600 const double old_time_limit = parameters_->max_deterministic_time();
601 parameters_->set_max_deterministic_time(max_dtime_per_core);
602 auto cleanup = ::absl::MakeCleanup([old_time_limit, this]() {
603 parameters_->set_max_deterministic_time(old_time_limit);
604 });
605
606 for (const ObjectiveTerm& term : terms_) {
607 // We currently skip the initial objective terms as there could be many
608 // of them. TODO(user): provide an option to cover-optimize them? I
609 // fear that this will slow down the solver too much though.
610 if (term.depth == 0) continue;
611
612 // Find out the true lower bound of var. This is called "cover
613 // optimization" in some of the max-SAT literature. It can helps on some
614 // problem families and hurt on others, but the overall impact is
615 // positive.
616 const IntegerVariable var = term.var;
617 IntegerValue best =
618 std::min(term.cover_ub, integer_trail_->UpperBound(var));
619
620 // Note(user): this can happen in some corner case because each time we
621 // find a solution, we constrain the objective to be smaller than it, so
622 // it is possible that a previous best is now infeasible.
623 if (best <= integer_trail_->LowerBound(var)) continue;
624
625 // Compute the global deterministic time for this core cover
626 // optimization.
627 const double deterministic_limit =
628 time_limit_->GetElapsedDeterministicTime() + max_dtime_per_core;
629
630 // Simple linear scan algorithm to find the optimal of var.
631 SatSolver::Status result;
632 while (best > integer_trail_->LowerBound(var)) {
633 const Literal assumption = integer_encoder_->GetOrCreateAssociatedLiteral(
634 IntegerLiteral::LowerOrEqual(var, best - 1));
635 result = ResetAndSolveIntegerProblem({assumption}, model_);
636 if (result != SatSolver::FEASIBLE) break;
637
638 best = integer_trail_->LowerBound(var);
639 VLOG(1) << "cover_opt var:" << var << " domain:["
640 << integer_trail_->LevelZeroLowerBound(var) << "," << best << "]";
641 if (!ProcessSolution()) return false;
642 if (!sat_solver_->ResetToLevelZero()) return false;
643 if (stop_ ||
644 time_limit_->GetElapsedDeterministicTime() > deterministic_limit) {
645 break;
646 }
647 }
648 if (result == SatSolver::INFEASIBLE) return false;
649 if (result == SatSolver::ASSUMPTIONS_UNSAT) {
650 if (!sat_solver_->ResetToLevelZero()) return false;
651
652 // TODO(user): If we improve the lower bound of var, we should check
653 // if our global lower bound reached our current best solution in
654 // order to abort early if the optimal is proved.
655 if (!integer_trail_->Enqueue(IntegerLiteral::GreaterOrEqual(var, best),
656 {}, {})) {
657 return false;
658 }
659 }
660 }
661
662 return PropagateObjectiveBounds();
663}
664
666 absl::Span<const Literal> literals, absl::Span<const IntegerVariable> vars,
667 absl::Span<const Coefficient> coefficients, Coefficient offset) {
668 // Create one initial nodes per variables with cost.
669 // TODO(user): We could create EncodingNode out of IntegerVariable.
670 //
671 // Note that the nodes order and assumptions extracted from it will be stable.
672 // In particular, new nodes will be appended at the end, which make the solver
673 // more likely to find core involving only the first assumptions. This is
674 // important at the beginning so the solver as a chance to find a lot of
675 // non-overlapping small cores without the need to have dedicated
676 // non-overlapping core finder.
677 // TODO(user): It could still be beneficial to add one. Experiments.
678 ObjectiveEncoder encoder(model_);
679 if (vars.empty()) {
680 // All Booleans.
681 for (int i = 0; i < literals.size(); ++i) {
682 CHECK_GT(coefficients[i], 0);
683 encoder.AddBaseNode(
684 EncodingNode::LiteralNode(literals[i], coefficients[i]));
685 }
686 } else {
687 // Use integer encoding.
688 CHECK_EQ(vars.size(), coefficients.size());
689 for (int i = 0; i < vars.size(); ++i) {
690 CHECK_GT(coefficients[i], 0);
691 const IntegerVariable var = vars[i];
692 const IntegerValue var_lb = integer_trail_->LowerBound(var);
693 const IntegerValue var_ub = integer_trail_->UpperBound(var);
694 if (var_ub - var_lb == 1) {
695 const Literal lit = integer_encoder_->GetOrCreateAssociatedLiteral(
696 IntegerLiteral::GreaterOrEqual(var, var_ub));
697 encoder.AddBaseNode(EncodingNode::LiteralNode(lit, coefficients[i]));
698 } else {
699 // TODO(user): This might not be ideal if there are holes in the domain.
700 // It should work by adding duplicates literal, but we should be able to
701 // be more efficient.
702 const int lb = 0;
703 const int ub = static_cast<int>(var_ub.value() - var_lb.value());
705 lb, ub,
706 [var, var_lb, this](int x) {
707 return integer_encoder_->GetOrCreateAssociatedLiteral(
709 var_lb + IntegerValue(x + 1)));
710 },
711 coefficients[i]));
712 }
713 }
714 }
715
716 // Initialize the bounds.
717 // This is in term of number of variables not at their minimal value.
718 Coefficient lower_bound(0);
719
720 // This is used by the "stratified" approach.
721 Coefficient stratified_lower_bound(0);
722 if (parameters_->max_sat_stratification() !=
724 for (EncodingNode* n : encoder.nodes()) {
725 stratified_lower_bound = std::max(stratified_lower_bound, n->weight());
726 }
727 }
728
729 // Start the algorithm.
730 int max_depth = 0;
731 std::string previous_core_info = "";
732 for (int iter = 0;;) {
733 if (time_limit_->LimitReached()) return SatSolver::LIMIT_REACHED;
734 if (!sat_solver_->ResetToLevelZero()) return SatSolver::INFEASIBLE;
735
736 // Note that the objective_var_ upper bound is the one from the "improving"
737 // problem, so if we have a feasible solution, it will be the best solution
738 // objective value - 1.
739 const Coefficient upper_bound(
740 integer_trail_->UpperBound(objective_var_).value() - offset.value());
741 ReduceNodes(upper_bound, &lower_bound, encoder.mutable_nodes(),
742 sat_solver_);
743 const IntegerValue new_obj_lb(lower_bound.value() + offset.value());
744 if (new_obj_lb > integer_trail_->LowerBound(objective_var_)) {
745 if (!integer_trail_->Enqueue(
746 IntegerLiteral::GreaterOrEqual(objective_var_, new_obj_lb), {},
747 {})) {
749 }
750
751 // Report the improvement.
752 // Note that we have a callback that will do the same, but doing it
753 // earlier allow us to add more information.
754 const int num_bools = sat_solver_->NumVariables();
755 const int num_fixed = sat_solver_->NumFixedVariables();
756 model_->GetOrCreate<SharedResponseManager>()->UpdateInnerObjectiveBounds(
757 absl::StrFormat("bool_%s (num_cores=%d [%s] a=%u d=%d "
758 "fixed=%d/%d clauses=%s)",
759 model_->Name(), iter, previous_core_info,
760 encoder.nodes().size(), max_depth, num_fixed,
761 num_bools, FormatCounter(clauses_->num_clauses())),
762 new_obj_lb, integer_trail_->LevelZeroUpperBound(objective_var_));
763 }
764
765 if (parameters_->cover_optimization() && encoder.nodes().size() > 1) {
766 if (ProbeLiteral(
767 encoder.mutable_nodes()->back()->GetAssumption(sat_solver_),
768 sat_solver_)) {
769 previous_core_info = "cover";
770 continue;
771 }
772 }
773
774 // We adapt the stratified lower bound when the gap is small. All literals
775 // with such weight will be in an at_most_one relationship, which will lead
776 // to a nice encoding if we find a core.
777 const Coefficient gap = upper_bound - lower_bound;
778 if (stratified_lower_bound > (gap + 2) / 2) {
779 stratified_lower_bound = (gap + 2) / 2;
780 }
781 std::vector<Literal> assumptions;
782 while (true) {
783 assumptions = ExtractAssumptions(stratified_lower_bound, encoder.nodes(),
784 sat_solver_);
785 if (!assumptions.empty()) break;
786
787 stratified_lower_bound =
788 MaxNodeWeightSmallerThan(encoder.nodes(), stratified_lower_bound);
789 if (stratified_lower_bound > 0) continue;
790
791 // We do not have any assumptions anymore, but we still need to see
792 // if the problem is feasible or not!
793 break;
794 }
795 VLOG(2) << "[Core] #nodes " << encoder.nodes().size()
796 << " #assumptions:" << assumptions.size()
797 << " stratification:" << stratified_lower_bound << " gap:" << gap;
798
799 // Solve under the assumptions.
800 //
801 // TODO(user): Find multiple core like in the "main" algorithm. This is just
802 // trying to solve with assumptions not involving the newly found core.
803 //
804 // TODO(user): With stratification, sometime we just spend too much time
805 // trying to find a feasible solution/prove infeasibility and we could
806 // instead just use stratification=0 to find easty core and improve lower
807 // bound.
808 const SatSolver::Status result =
809 ResetAndSolveIntegerProblem(assumptions, model_);
810 if (result == SatSolver::FEASIBLE) {
811 if (!ProcessSolution()) return SatSolver::INFEASIBLE;
812 if (stop_) return SatSolver::LIMIT_REACHED;
813
814 // If not all assumptions were taken, continue with a lower stratified
815 // bound. Otherwise we have an optimal solution.
816 stratified_lower_bound =
817 MaxNodeWeightSmallerThan(encoder.nodes(), stratified_lower_bound);
818 if (stratified_lower_bound > 0) continue;
820 }
821 if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
822
823 // We have a new core.
824 std::vector<Literal> core = sat_solver_->GetLastIncompatibleDecisions();
825 if (parameters_->core_minimization_level() > 0) {
826 MinimizeCoreWithPropagation(time_limit_, sat_solver_, &core);
827 }
828 if (parameters_->core_minimization_level() > 1) {
829 MinimizeCoreWithSearch(time_limit_, sat_solver_, &core);
830 }
831 if (!sat_solver_->ResetToLevelZero()) return SatSolver::INFEASIBLE;
832 FilterAssignedLiteral(sat_solver_->Assignment(), &core);
833 if (core.empty()) return SatSolver::INFEASIBLE;
834
835 // Compute the min weight of all the nodes in the core.
836 // The lower bound will be increased by that much.
837 const Coefficient min_weight = ComputeCoreMinWeight(encoder.nodes(), core);
838 previous_core_info =
839 absl::StrFormat("size:%u mw:%d", core.size(), min_weight.value());
840
841 // We only count an iter when we found a core.
842 ++iter;
843 if (!encoder.ProcessCore(core, min_weight, gap, &previous_core_info)) {
845 }
846 max_depth = std::max(max_depth, encoder.nodes().back()->depth());
847 }
848
849 return SatSolver::FEASIBLE; // shouldn't reach here.
850}
851
852void PresolveBooleanLinearExpression(std::vector<Literal>* literals,
853 std::vector<Coefficient>* coefficients,
854 Coefficient* offset) {
855 // Sorting by literal index regroup duplicate or negated literal together.
856 std::vector<std::pair<LiteralIndex, Coefficient>> pairs;
857 const int size = literals->size();
858 for (int i = 0; i < size; ++i) {
859 pairs.push_back({(*literals)[i].Index(), (*coefficients)[i]});
860 }
861 std::sort(pairs.begin(), pairs.end());
862
863 // Merge terms if needed.
864 int new_size = 0;
865 for (const auto& [index, coeff] : pairs) {
866 if (new_size > 0) {
867 if (pairs[new_size - 1].first == index) {
868 pairs[new_size - 1].second += coeff;
869 continue;
870 } else if (pairs[new_size - 1].first == Literal(index).NegatedIndex()) {
871 // The term is coeff *( 1 - X).
872 pairs[new_size - 1].second -= coeff;
873 *offset += coeff;
874 continue;
875 }
876 }
877 pairs[new_size++] = {index, coeff};
878 }
879 pairs.resize(new_size);
880
881 // Rebuild with positive coeff.
882 literals->clear();
883 coefficients->clear();
884 for (const auto& [index, coeff] : pairs) {
885 if (coeff > 0) {
886 literals->push_back(Literal(index));
887 coefficients->push_back(coeff);
888 } else if (coeff < 0) {
889 // coeff * X = coeff - coeff * (1 - X).
890 *offset += coeff;
891 literals->push_back(Literal(index).Negated());
892 coefficients->push_back(-coeff);
893 }
894 }
895}
896
897void CoreBasedOptimizer::PresolveObjectiveWithAtMostOne(
898 std::vector<Literal>* literals, std::vector<Coefficient>* coefficients,
899 Coefficient* offset) {
900 // This contains non-negative value. If a literal has negative weight, then
901 // we just put a positive weight on its negation and update the offset.
902 const int num_literals = implications_->literal_size();
904 util_intops::StrongVector<LiteralIndex, bool> is_candidate(num_literals);
905
906 // For now, we do not use weight. Note that finding the at most on in the
907 // creation order of the variable make a HUGE difference on the max-sat frb
908 // family.
909 //
910 // TODO(user): We can assign preferences to literals to favor certain at most
911 // one instead of other. For now we don't, so ExpandAtMostOneWithWeight() will
912 // kind of randomize the expansion amongst possible choices.
914
915 // Collect all literals with "negative weights", we will try to find at most
916 // one between them.
917 std::vector<Literal> candidates;
918 const int num_terms = literals->size();
919 for (int i = 0; i < num_terms; ++i) {
920 const Literal lit = (*literals)[i];
921 const Coefficient coeff = (*coefficients)[i];
922
923 // For now we know the input only has positive weight, but it is easy to
924 // adapt if needed.
925 CHECK_GT(coeff, 0);
926 weights[lit] = coeff;
927
928 candidates.push_back(lit.Negated());
929 is_candidate[lit.NegatedIndex()] = true;
930 }
931
932 int num_at_most_ones = 0;
933 Coefficient overall_lb_increase(0);
934
935 std::vector<Literal> at_most_one;
936 std::vector<std::pair<Literal, Coefficient>> new_obj_terms;
937 implications_->ResetWorkDone();
938 for (const Literal root : candidates) {
939 if (weights[root.NegatedIndex()] == 0) continue;
940 if (implications_->WorkDone() > 1e8) continue;
941
942 // We never put weight on both a literal and its negation.
943 CHECK_EQ(weights[root], 0);
944
945 // Note that for this to be as exhaustive as possible, the probing needs
946 // to have added binary clauses corresponding to lvl0 propagation.
947 at_most_one =
948 implications_->ExpandAtMostOneWithWeight</*use_weight=*/false>(
949 {root}, is_candidate, preferences);
950 if (at_most_one.size() <= 1) continue;
951 ++num_at_most_ones;
952
953 // Change the objective weights. Note that all the literal in the at most
954 // one will not be processed again since the weight of their negation will
955 // be zero after this step.
956 Coefficient max_coeff(0);
957 Coefficient lb_increase(0);
958 for (const Literal lit : at_most_one) {
959 const Coefficient coeff = weights[lit.NegatedIndex()];
960 lb_increase += coeff;
961 max_coeff = std::max(max_coeff, coeff);
962 }
963 lb_increase -= max_coeff;
964
965 *offset += lb_increase;
966 overall_lb_increase += lb_increase;
967
968 for (const Literal lit : at_most_one) {
969 is_candidate[lit] = false;
970 const Coefficient new_weight = max_coeff - weights[lit.NegatedIndex()];
971 CHECK_EQ(weights[lit], 0);
972 weights[lit] = new_weight;
973 weights[lit.NegatedIndex()] = 0;
974 if (new_weight > 0) {
975 // TODO(user): While we autorize this to be in future at most one, it
976 // will not appear in the "literal" list. We might also want to continue
977 // until we reached the fix point.
978 is_candidate[lit.NegatedIndex()] = true;
979 }
980 }
981
982 // Create a new Boolean with weight max_coeff.
983 const Literal new_lit(sat_solver_->NewBooleanVariable(), true);
984 new_obj_terms.push_back({new_lit, max_coeff});
985
986 // The new boolean is true only if all the one in the at most one are false.
987 at_most_one.push_back(new_lit);
988 sat_solver_->AddProblemClause(at_most_one);
989 is_candidate.resize(implications_->literal_size(), false);
990 preferences.resize(implications_->literal_size(), 1.0);
991 }
992
993 if (overall_lb_increase > 0) {
994 // Report new bounds right away with extra information.
995 model_->GetOrCreate<SharedResponseManager>()->UpdateInnerObjectiveBounds(
996 absl::StrFormat("am1_presolve (num_literals=%d num_am1=%d "
997 "increase=%lld work_done=%lld)",
998 (int)candidates.size(), num_at_most_ones,
999 overall_lb_increase.value(), implications_->WorkDone()),
1000 IntegerValue(offset->value()),
1001 integer_trail_->LevelZeroUpperBound(objective_var_));
1002 }
1003
1004 // Reconstruct the objective.
1005 literals->clear();
1006 coefficients->clear();
1007 for (const Literal root : candidates) {
1008 if (weights[root] > 0) {
1009 CHECK_EQ(weights[root.NegatedIndex()], 0);
1010 literals->push_back(root);
1011 coefficients->push_back(weights[root]);
1012 }
1013 if (weights[root.NegatedIndex()] > 0) {
1014 CHECK_EQ(weights[root], 0);
1015 literals->push_back(root.Negated());
1016 coefficients->push_back(weights[root.NegatedIndex()]);
1017 }
1018 }
1019 for (const auto& [lit, coeff] : new_obj_terms) {
1020 literals->push_back(lit);
1021 coefficients->push_back(coeff);
1022 }
1023}
1024
1026 // Hack: If the objective is fully Boolean, we use the
1027 // OptimizeWithSatEncoding() version as it seems to be better.
1028 //
1029 // TODO(user): Try to understand exactly why and merge both code path.
1030 if (!parameters_->interleave_search()) {
1031 Coefficient offset(0);
1032 std::vector<Literal> literals;
1033 std::vector<IntegerVariable> vars;
1034 std::vector<Coefficient> coefficients;
1035 bool all_booleans = true;
1036 IntegerValue range(0);
1037 for (const ObjectiveTerm& term : terms_) {
1038 const IntegerVariable var = term.var;
1039 const IntegerValue coeff = term.weight;
1040 const IntegerValue lb = integer_trail_->LowerBound(var);
1041 const IntegerValue ub = integer_trail_->UpperBound(var);
1042 offset += Coefficient((lb * coeff).value());
1043 if (lb == ub) continue;
1044
1045 vars.push_back(var);
1046 coefficients.push_back(Coefficient(coeff.value()));
1047 if (ub - lb == 1) {
1048 literals.push_back(integer_encoder_->GetOrCreateAssociatedLiteral(
1050 } else {
1051 all_booleans = false;
1052 range += ub - lb;
1053 }
1054 }
1055 if (all_booleans) {
1056 // In some corner case, it is possible the GetOrCreateAssociatedLiteral()
1057 // returns identical or negated literal of another term. We don't support
1058 // this below, so we need to make sure this is not the case.
1059 PresolveBooleanLinearExpression(&literals, &coefficients, &offset);
1060
1061 // TODO(user): It might be interesting to redo this kind of presolving
1062 // once high cost booleans have been fixed as we might have more at most
1063 // one between literal in the objective by then.
1064 //
1065 // Or alternatively, we could try this or something like it on the
1066 // literals from the cores as they are found. We should probably make
1067 // sure that if it exist, a core of size two is always added. And for
1068 // such core, we can always try to see if the "at most one" can be
1069 // extended.
1070 PresolveObjectiveWithAtMostOne(&literals, &coefficients, &offset);
1071 return OptimizeWithSatEncoding(literals, {}, coefficients, offset);
1072 }
1073 if (range < 1e8) {
1074 return OptimizeWithSatEncoding({}, vars, coefficients, offset);
1075 }
1076 }
1077
1078 // TODO(user): The core is returned in the same order as the assumptions,
1079 // so we don't really need this map, we could just do a linear scan to
1080 // recover which node are part of the core. This however needs to be properly
1081 // unit tested before usage.
1082 absl::btree_map<LiteralIndex, int> literal_to_term_index;
1083
1084 // Start the algorithm.
1085 stop_ = false;
1086 while (true) {
1087 // TODO(user): This always resets the solver to level zero.
1088 // Because of that we don't resume a solve in "chunk" perfectly. Fix.
1089 if (!PropagateObjectiveBounds()) return SatSolver::INFEASIBLE;
1090 if (time_limit_->LimitReached()) return SatSolver::LIMIT_REACHED;
1091
1092 // Bulk cover optimization.
1093 //
1094 // TODO(user): If the search is aborted during this phase and we solve in
1095 // "chunk", we don't resume perfectly from where it was. Fix.
1096 if (parameters_->cover_optimization()) {
1097 if (!CoverOptimization()) return SatSolver::INFEASIBLE;
1098 if (stop_) return SatSolver::LIMIT_REACHED;
1099 }
1100
1101 // We assumes all terms (modulo stratification) at their lower-bound.
1102 std::vector<int> term_indices;
1103 std::vector<IntegerLiteral> integer_assumptions;
1104 std::vector<IntegerValue> assumption_weights;
1105 IntegerValue objective_offset(0);
1106 bool some_assumptions_were_skipped = false;
1107 for (int i = 0; i < terms_.size(); ++i) {
1108 const ObjectiveTerm term = terms_[i];
1109
1110 // TODO(user): These can be simply removed from the list.
1111 if (term.weight == 0) continue;
1112
1113 // Skip fixed terms.
1114 // We still keep them around for a proper lower-bound computation.
1115 //
1116 // TODO(user): we could keep an objective offset instead.
1117 const IntegerValue var_lb = integer_trail_->LowerBound(term.var);
1118 const IntegerValue var_ub = integer_trail_->UpperBound(term.var);
1119 if (var_lb == var_ub) {
1120 objective_offset += term.weight * var_lb.value();
1121 continue;
1122 }
1123
1124 // Only consider the terms above the threshold.
1125 if (term.weight >= stratification_threshold_) {
1126 integer_assumptions.push_back(
1127 IntegerLiteral::LowerOrEqual(term.var, var_lb));
1128 assumption_weights.push_back(term.weight);
1129 term_indices.push_back(i);
1130 } else {
1131 some_assumptions_were_skipped = true;
1132 }
1133 }
1134
1135 // No assumptions with the current stratification? use the next one.
1136 if (term_indices.empty() && some_assumptions_were_skipped) {
1137 ComputeNextStratificationThreshold();
1138 continue;
1139 }
1140
1141 // If there is only one or two assumptions left, we switch the algorithm.
1142 if (term_indices.size() <= 2 && !some_assumptions_were_skipped) {
1143 VLOG(1) << "Switching to linear scan...";
1144 if (!already_switched_to_linear_scan_) {
1145 already_switched_to_linear_scan_ = true;
1146 std::vector<IntegerVariable> constraint_vars;
1147 std::vector<int64_t> constraint_coeffs;
1148 for (const int index : term_indices) {
1149 constraint_vars.push_back(terms_[index].var);
1150 constraint_coeffs.push_back(terms_[index].weight.value());
1151 }
1152 constraint_vars.push_back(objective_var_);
1153 constraint_coeffs.push_back(-1);
1154 model_->Add(WeightedSumLowerOrEqual(constraint_vars, constraint_coeffs,
1155 -objective_offset.value()));
1156 }
1157
1159 objective_var_, feasible_solution_observer_, model_);
1160 }
1161
1162 // Display the progress.
1163 if (VLOG_IS_ON(1)) {
1164 int max_depth = 0;
1165 for (const ObjectiveTerm& term : terms_) {
1166 max_depth = std::max(max_depth, term.depth);
1167 }
1168 const int64_t lb = integer_trail_->LowerBound(objective_var_).value();
1169 const int64_t ub = integer_trail_->UpperBound(objective_var_).value();
1170 const int gap =
1171 lb == ub
1172 ? 0
1173 : static_cast<int>(std::ceil(
1174 100.0 * (ub - lb) / std::max(std::abs(ub), std::abs(lb))));
1175 VLOG(1) << absl::StrCat("unscaled_next_obj_range:[", lb, ",", ub,
1176 "]"
1177 " gap:",
1178 gap, "%", " assumptions:", term_indices.size(),
1179 " strat:", stratification_threshold_.value(),
1180 " depth:", max_depth,
1181 " bool: ", sat_solver_->NumVariables());
1182 }
1183
1184 // Convert integer_assumptions to Literals.
1185 std::vector<Literal> assumptions;
1186 literal_to_term_index.clear();
1187 for (int i = 0; i < integer_assumptions.size(); ++i) {
1188 assumptions.push_back(integer_encoder_->GetOrCreateAssociatedLiteral(
1189 integer_assumptions[i]));
1190
1191 // Tricky: In some rare case, it is possible that the same literal
1192 // correspond to more that one assumptions. In this case, we can just
1193 // pick one of them when converting back a core to term indices.
1194 //
1195 // TODO(user): We can probably be smarter about the cost of the
1196 // assumptions though.
1197 literal_to_term_index[assumptions.back()] = term_indices[i];
1198 }
1199
1200 // Solve under the assumptions.
1201 //
1202 // TODO(user): If the "search" is interrupted while computing cores, we
1203 // currently do not resume it flawlessly. We however add any cores we found
1204 // before aborting.
1205 std::vector<std::vector<Literal>> cores;
1206 const SatSolver::Status result =
1207 FindCores(assumptions, assumption_weights, stratification_threshold_,
1208 model_, &cores);
1209 if (result == SatSolver::INFEASIBLE) return SatSolver::INFEASIBLE;
1210 if (result == SatSolver::FEASIBLE) {
1211 if (!ProcessSolution()) return SatSolver::INFEASIBLE;
1212 if (stop_) return SatSolver::LIMIT_REACHED;
1213 if (cores.empty()) {
1214 ComputeNextStratificationThreshold();
1215 if (stratification_threshold_ == 0) return SatSolver::INFEASIBLE;
1216 continue;
1217 }
1218 }
1219
1220 // Process the cores by creating new variables and transferring the minimum
1221 // weight of each core to it.
1222 if (!sat_solver_->ResetToLevelZero()) return SatSolver::INFEASIBLE;
1223 for (const std::vector<Literal>& core : cores) {
1224 // This just increase the lower-bound of the corresponding node.
1225 // TODO(user): Maybe the solver should do it right away.
1226 if (core.size() == 1) {
1227 if (!sat_solver_->AddUnitClause(core[0].Negated())) {
1228 return SatSolver::INFEASIBLE;
1229 }
1230 continue;
1231 }
1232
1233 // Compute the min weight of all the terms in the core. The lower bound
1234 // will be increased by that much because at least one assumption in the
1235 // core must be true. This is also why we can start at 1 for new_var_lb.
1236 bool ignore_this_core = false;
1237 IntegerValue min_weight = kMaxIntegerValue;
1238 IntegerValue max_weight(0);
1239 IntegerValue new_var_lb(1);
1240 IntegerValue new_var_ub(0);
1241 int new_depth = 0;
1242 for (const Literal lit : core) {
1243 const int index = literal_to_term_index.at(lit.Index());
1244
1245 // When this happen, the core is now trivially "minimized" by the new
1246 // bound on this variable, so there is no point in adding it.
1247 if (terms_[index].old_var_lb <
1248 integer_trail_->LowerBound(terms_[index].var)) {
1249 ignore_this_core = true;
1250 break;
1251 }
1252
1253 const IntegerValue weight = terms_[index].weight;
1254 min_weight = std::min(min_weight, weight);
1255 max_weight = std::max(max_weight, weight);
1256 new_depth = std::max(new_depth, terms_[index].depth + 1);
1257 new_var_lb += integer_trail_->LowerBound(terms_[index].var);
1258 new_var_ub += integer_trail_->UpperBound(terms_[index].var);
1259 }
1260 if (ignore_this_core) continue;
1261
1262 VLOG(1) << absl::StrFormat(
1263 "core:%u weight:[%d,%d] domain:[%d,%d] depth:%d", core.size(),
1264 min_weight.value(), max_weight.value(), new_var_lb.value(),
1265 new_var_ub.value(), new_depth);
1266
1267 // We will "transfer" min_weight from all the variables of the core
1268 // to a new variable.
1269 const IntegerVariable new_var =
1270 integer_trail_->AddIntegerVariable(new_var_lb, new_var_ub);
1271 terms_.push_back({new_var, min_weight, new_depth});
1272 terms_.back().cover_ub = new_var_ub;
1273
1274 // Sum variables in the core <= new_var.
1275 {
1276 std::vector<IntegerVariable> constraint_vars;
1277 std::vector<int64_t> constraint_coeffs;
1278 for (const Literal lit : core) {
1279 const int index = literal_to_term_index.at(lit.Index());
1280 terms_[index].weight -= min_weight;
1281 constraint_vars.push_back(terms_[index].var);
1282 constraint_coeffs.push_back(1);
1283 }
1284 constraint_vars.push_back(new_var);
1285 constraint_coeffs.push_back(-1);
1286 model_->Add(
1287 WeightedSumLowerOrEqual(constraint_vars, constraint_coeffs, 0));
1288 }
1289 }
1290
1291 // Abort if we reached the time limit. Note that we still add any cores we
1292 // found in case the solve is split in "chunk".
1293 if (result == SatSolver::LIMIT_REACHED) return result;
1294 }
1295}
1296
1297} // namespace sat
1298} // namespace operations_research
Definition model.h:341
bool Contains(int64_t value) const
void EnableLogging(bool enable)
Definition logging.h:47
bool LoggingIsEnabled() const
Returns true iff logging is enabled.
Definition logging.h:50
std::vector< Literal > ExpandAtMostOneWithWeight(absl::Span< const Literal > at_most_one, const util_intops::StrongVector< LiteralIndex, bool > &can_be_included, const util_intops::StrongVector< LiteralIndex, double > &expanded_lp_values)
Same as ExpandAtMostOne() but try to maximize the weight in the clique.
Definition clause.cc:2016
SatSolver::Status OptimizeWithSatEncoding(absl::Span< const Literal > literals, absl::Span< const IntegerVariable > vars, absl::Span< const Coefficient > coefficients, Coefficient offset)
CoreBasedOptimizer(IntegerVariable objective_var, absl::Span< const IntegerVariable > variables, absl::Span< const IntegerValue > coefficients, std::function< void()> feasible_solution_observer, Model *model)
static EncodingNode GenericNode(int lb, int ub, std::function< Literal(int x)> create_lit, Coefficient weight)
Definition encoding.cc:63
static EncodingNode LiteralNode(Literal l, Coefficient weight)
Definition encoding.cc:52
An helper class to share the code used by the different kind of search.
IntegerValue LowerBound(IntegerVariable i) const
Returns the current lower/upper bound of the given integer variable.
Definition integer.h:1317
const Domain & InitialVariableDomain(IntegerVariable var) const
Definition integer.cc:869
LiteralIndex Index() const
Definition sat_base.h:91
std::vector< EncodingNode * > * mutable_nodes()
Definition encoding.h:252
void AddBaseNode(EncodingNode node)
Definition encoding.h:245
const std::vector< EncodingNode * > & nodes() const
Definition encoding.h:251
bool ProcessCore(absl::Span< const Literal > core, Coefficient min_weight, Coefficient gap, std::string *info)
Definition encoding.cc:588
static constexpr MaxSatStratificationAlgorithm STRATIFICATION_NONE
Status EnqueueDecisionAndBacktrackOnConflict(Literal true_literal, int *first_propagation_index=nullptr)
SolverLogger * mutable_logger()
Hack to allow to temporarily disable logging if it is enabled.
Definition sat_solver.h:495
std::vector< Literal > GetLastIncompatibleDecisions()
int EnqueueDecisionAndBackjumpOnConflict(Literal true_literal)
void Backtrack(int target_level)
ABSL_MUST_USE_RESULT bool Propagate()
void SetAssumptionLevel(int assumption_level)
ABSL_MUST_USE_RESULT bool AddUnitClause(Literal true_literal)
Status ResetAndSolveWithGivenAssumptions(const std::vector< Literal > &assumptions, int64_t max_number_of_conflicts=-1)
const VariablesAssignment & Assignment() const
Definition sat_solver.h:390
ABSL_MUST_USE_RESULT bool ResetToLevelZero()
ABSL_MUST_USE_RESULT bool FinishPropagation()
bool LiteralIsAssigned(Literal literal) const
Definition sat_base.h:191
bool LiteralIsFalse(Literal literal) const
Definition sat_base.h:185
bool LiteralIsTrue(Literal literal) const
Definition sat_base.h:188
void resize(size_type new_size)
void STLSortAndRemoveDuplicates(T *v, const LessFunc &less_func)
Definition stl_util.h:55
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
std::vector< Literal > ExtractAssumptions(Coefficient stratified_lower_bound, const std::vector< EncodingNode * > &nodes, SatSolver *solver)
Definition encoding.cc:549
std::function< int64_t(const Model &)> LowerBound(IntegerVariable v)
Definition integer.h:1581
std::vector< IntegerVariable > NegationOf(absl::Span< const IntegerVariable > vars)
Returns the vector of the negated variables.
Definition integer.cc:52
void ReduceNodes(Coefficient upper_bound, Coefficient *lower_bound, std::vector< EncodingNode * > *nodes, SatSolver *solver)
Definition encoding.cc:503
void MinimizeCoreWithPropagation(TimeLimit *limit, SatSolver *solver, std::vector< Literal > *core)
void FilterAssignedLiteral(const VariablesAssignment &assignment, std::vector< Literal > *core)
A core cannot be all true.
Coefficient ComputeCoreMinWeight(const std::vector< EncodingNode * > &nodes, absl::Span< const Literal > core)
Definition encoding.cc:562
void MinimizeCoreWithSearch(TimeLimit *limit, SatSolver *solver, std::vector< Literal > *core)
void PresolveBooleanLinearExpression(std::vector< Literal > *literals, std::vector< Coefficient > *coefficients, Coefficient *offset)
std::string FormatCounter(int64_t num)
Prints a positive number with separators for easier reading (ex: 1'348'065).
Definition util.cc:44
bool ProbeLiteral(Literal assumption, SatSolver *solver)
SatSolver::Status MinimizeIntegerVariableWithLinearScanAndLazyEncoding(IntegerVariable objective_var, const std::function< void()> &feasible_solution_observer, Model *model)
int MoveOneUnprocessedLiteralLast(const absl::btree_set< LiteralIndex > &processed, int relevant_prefix_size, std::vector< Literal > *literals)
Definition util.cc:388
SatSolver::Status ResetAndSolveIntegerProblem(const std::vector< Literal > &assumptions, Model *model)
void RestrictObjectiveDomainWithBinarySearch(IntegerVariable objective_var, const std::function< void()> &feasible_solution_observer, Model *model)
Coefficient MaxNodeWeightSmallerThan(const std::vector< EncodingNode * > &nodes, Coefficient upper_bound)
Definition encoding.cc:576
std::function< void(Model *)> WeightedSumLowerOrEqual(absl::Span< const IntegerVariable > vars, const VectorInt &coefficients, int64_t upper_bound)
Weighted sum <= constant.
In SWIG mode, we don't want anything besides these top-level includes.
STL namespace.
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)