OR-Tools  9.0
optimization.cc
Go to the documentation of this file.
1 // Copyright 2010-2021 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 <cstdint>
18 #include <cstdio>
19 #include <cstdlib>
20 #include <deque>
21 #include <limits>
22 #include <map>
23 #include <memory>
24 #include <set>
25 #include <string>
26 #include <utility>
27 
28 #include "absl/random/random.h"
29 #include "absl/strings/str_cat.h"
30 #include "absl/strings/str_format.h"
31 #include "ortools/base/cleanup.h"
32 #include "ortools/base/int_type.h"
33 #include "ortools/base/logging.h"
34 #include "ortools/base/macros.h"
35 #include "ortools/base/map_util.h"
36 #include "ortools/base/stl_util.h"
37 #include "ortools/base/timer.h"
38 #if !defined(__PORTABLE_PLATFORM__) && defined(USE_SCIP)
41 #endif // __PORTABLE_PLATFORM__
42 #include "ortools/base/random.h"
45 #include "ortools/sat/encoding.h"
49 #include "ortools/sat/util.h"
51 
52 namespace operations_research {
53 namespace sat {
54 
55 namespace {
56 
57 // Used to log messages to stdout or to the normal logging framework according
58 // to the given LogBehavior value.
59 class Logger {
60  public:
61  explicit Logger(LogBehavior v) : use_stdout_(v == STDOUT_LOG) {}
62  void Log(const std::string& message) {
63  if (use_stdout_) {
64  absl::PrintF("%s\n", message);
65  } else {
66  LOG(INFO) << message;
67  }
68  }
69 
70  private:
71  bool use_stdout_;
72 };
73 
74 // Outputs the current objective value in the cnf output format.
75 // Note that this function scale the given objective.
76 std::string CnfObjectiveLine(const LinearBooleanProblem& problem,
77  Coefficient objective) {
78  const double scaled_objective =
79  AddOffsetAndScaleObjectiveValue(problem, objective);
80  return absl::StrFormat("o %d", static_cast<int64_t>(scaled_objective));
81 }
82 
83 struct LiteralWithCoreIndex {
84  LiteralWithCoreIndex(Literal l, int i) : literal(l), core_index(i) {}
85  Literal literal;
87 };
88 
89 // Deletes the given indices from a vector. The given indices must be sorted in
90 // increasing order. The order of the non-deleted entries in the vector is
91 // preserved.
92 template <typename Vector>
93 void DeleteVectorIndices(const std::vector<int>& indices, Vector* v) {
94  int new_size = 0;
95  int indices_index = 0;
96  for (int i = 0; i < v->size(); ++i) {
97  if (indices_index < indices.size() && i == indices[indices_index]) {
98  ++indices_index;
99  } else {
100  (*v)[new_size] = (*v)[i];
101  ++new_size;
102  }
103  }
104  v->resize(new_size);
105 }
106 
107 // In the Fu & Malik algorithm (or in WPM1), when two cores overlap, we
108 // artifically introduce symmetries. More precisely:
109 //
110 // The picture below shows two cores with index 0 and 1, with one blocking
111 // variable per '-' and with the variables ordered from left to right (by their
112 // assumptions index). The blocking variables will be the one added to "relax"
113 // the core for the next iteration.
114 //
115 // 1: -------------------------------
116 // 0: ------------------------------------
117 //
118 // The 2 following assignment of the blocking variables are equivalent.
119 // Remember that exactly one blocking variable per core must be assigned to 1.
120 //
121 // 1: ----------------------1--------
122 // 0: --------1---------------------------
123 //
124 // and
125 //
126 // 1: ---------------------------1---
127 // 0: ---1--------------------------------
128 //
129 // This class allows to add binary constraints excluding the second possibility.
130 // Basically, each time a new core is added, if two of its blocking variables
131 // (b1, b2) have the same assumption index of two blocking variables from
132 // another core (c1, c2), then we forbid the assignment c1 true and b2 true.
133 //
134 // Reference: C Ansótegui, ML Bonet, J Levy, "Sat-based maxsat algorithms",
135 // Artificial Intelligence, 2013 - Elsevier.
136 class FuMalikSymmetryBreaker {
137  public:
138  FuMalikSymmetryBreaker() {}
139 
140  // Must be called before a new core is processed.
141  void StartResolvingNewCore(int new_core_index) {
142  literal_by_core_.resize(new_core_index);
143  for (int i = 0; i < new_core_index; ++i) {
144  literal_by_core_[i].clear();
145  }
146  }
147 
148  // This should be called for each blocking literal b of the new core. The
149  // assumption_index identify the soft clause associated to the given blocking
150  // literal. Note that between two StartResolvingNewCore() calls,
151  // ProcessLiteral() is assumed to be called with different assumption_index.
152  //
153  // Changing the order of the calls will not change the correctness, but will
154  // change the symmetry-breaking clause produced.
155  //
156  // Returns a set of literals which can't be true at the same time as b (under
157  // symmetry breaking).
158  std::vector<Literal> ProcessLiteral(int assumption_index, Literal b) {
159  if (assumption_index >= info_by_assumption_index_.size()) {
160  info_by_assumption_index_.resize(assumption_index + 1);
161  }
162 
163  // Compute the function result.
164  // info_by_assumption_index_[assumption_index] will contain all the pairs
165  // (blocking_literal, core) of the previous resolved cores at the same
166  // assumption index as b.
167  std::vector<Literal> result;
168  for (LiteralWithCoreIndex data :
169  info_by_assumption_index_[assumption_index]) {
170  // literal_by_core_ will contain all the blocking literal of a given core
171  // with an assumption_index that was used in one of the ProcessLiteral()
172  // calls since the last StartResolvingNewCore().
173  //
174  // Note that there can be only one such literal by core, so we will not
175  // add duplicates.
176  result.insert(result.end(), literal_by_core_[data.core_index].begin(),
177  literal_by_core_[data.core_index].end());
178  }
179 
180  // Update the internal data structure.
181  for (LiteralWithCoreIndex data :
182  info_by_assumption_index_[assumption_index]) {
183  literal_by_core_[data.core_index].push_back(data.literal);
184  }
185  info_by_assumption_index_[assumption_index].push_back(
186  LiteralWithCoreIndex(b, literal_by_core_.size()));
187  return result;
188  }
189 
190  // Deletes the given assumption indices.
191  void DeleteIndices(const std::vector<int>& indices) {
192  DeleteVectorIndices(indices, &info_by_assumption_index_);
193  }
194 
195  // This is only used in WPM1 to forget all the information related to a given
196  // assumption_index.
197  void ClearInfo(int assumption_index) {
198  CHECK_LE(assumption_index, info_by_assumption_index_.size());
199  info_by_assumption_index_[assumption_index].clear();
200  }
201 
202  // This is only used in WPM1 when a new assumption_index is created.
203  void AddInfo(int assumption_index, Literal b) {
204  CHECK_GE(assumption_index, info_by_assumption_index_.size());
205  info_by_assumption_index_.resize(assumption_index + 1);
206  info_by_assumption_index_[assumption_index].push_back(
207  LiteralWithCoreIndex(b, literal_by_core_.size()));
208  }
209 
210  private:
211  std::vector<std::vector<LiteralWithCoreIndex>> info_by_assumption_index_;
212  std::vector<std::vector<Literal>> literal_by_core_;
213 
214  DISALLOW_COPY_AND_ASSIGN(FuMalikSymmetryBreaker);
215 };
216 
217 } // namespace
218 
220  std::vector<Literal>* core) {
221  if (solver->IsModelUnsat()) return;
222  std::set<LiteralIndex> moved_last;
223  std::vector<Literal> candidate(core->begin(), core->end());
224 
225  solver->Backtrack(0);
226  solver->SetAssumptionLevel(0);
227  while (!limit->LimitReached()) {
228  // We want each literal in candidate to appear last once in our propagation
229  // order. We want to do that while maximizing the reutilization of the
230  // current assignment prefix, that is minimizing the number of
231  // decision/progagation we need to perform.
232  const int target_level = MoveOneUnprocessedLiteralLast(
233  moved_last, solver->CurrentDecisionLevel(), &candidate);
234  if (target_level == -1) break;
235  solver->Backtrack(target_level);
236  while (!solver->IsModelUnsat() && !limit->LimitReached() &&
237  solver->CurrentDecisionLevel() < candidate.size()) {
238  const Literal decision = candidate[solver->CurrentDecisionLevel()];
239  if (solver->Assignment().LiteralIsTrue(decision)) {
240  candidate.erase(candidate.begin() + solver->CurrentDecisionLevel());
241  continue;
242  } else if (solver->Assignment().LiteralIsFalse(decision)) {
243  // This is a "weird" API to get the subset of decisions that caused
244  // this literal to be false with reason analysis.
245  solver->EnqueueDecisionAndBacktrackOnConflict(decision);
246  candidate = solver->GetLastIncompatibleDecisions();
247  break;
248  } else {
249  solver->EnqueueDecisionAndBackjumpOnConflict(decision);
250  }
251  }
252  if (candidate.empty() || solver->IsModelUnsat()) return;
253  moved_last.insert(candidate.back().Index());
254  }
255 
256  solver->Backtrack(0);
257  solver->SetAssumptionLevel(0);
258  if (candidate.size() < core->size()) {
259  VLOG(1) << "minimization " << core->size() << " -> " << candidate.size();
260  core->assign(candidate.begin(), candidate.end());
261  }
262 }
263 
264 // This algorithm works by exploiting the unsat core returned by the SAT solver
265 // when the problem is UNSAT. It starts by trying to solve the decision problem
266 // where all the objective variables are set to their value with minimal cost,
267 // and relax in each step some of these fixed variables until the problem
268 // becomes satisfiable.
270  const LinearBooleanProblem& problem,
271  SatSolver* solver,
272  std::vector<bool>* solution) {
273  Logger logger(log);
274  FuMalikSymmetryBreaker symmetry;
275 
276  // blocking_clauses will contains a set of clauses that are currently added to
277  // the initial problem.
278  //
279  // Initially, each clause just contains a literal associated to an objective
280  // variable with non-zero cost. Setting all these literals to true will lead
281  // to the lowest possible objective.
282  //
283  // During the algorithm, "blocking" literals will be added to each clause.
284  // Moreover each clause will contain an extra "assumption" literal stored in
285  // the separate assumptions vector (in its negated form).
286  //
287  // The meaning of a given clause will always be:
288  // If the assumption literal and all blocking literals are false, then the
289  // "objective" literal (which is the first one in the clause) must be true.
290  // When the "objective" literal is true, its variable (which have a non-zero
291  // cost) is set to the value that minimize the objective cost.
292  //
293  // ex: If a variable "x" as a cost of 3, its cost contribution is smaller when
294  // it is set to false (since it will contribute to zero instead of 3).
295  std::vector<std::vector<Literal>> blocking_clauses;
296  std::vector<Literal> assumptions;
297 
298  // Initialize blocking_clauses and assumptions.
299  const LinearObjective& objective = problem.objective();
300  CHECK_GT(objective.coefficients_size(), 0);
301  const Coefficient unique_objective_coeff(std::abs(objective.coefficients(0)));
302  for (int i = 0; i < objective.literals_size(); ++i) {
303  CHECK_EQ(std::abs(objective.coefficients(i)), unique_objective_coeff)
304  << "The basic Fu & Malik algorithm needs constant objective coeffs.";
305  const Literal literal(objective.literals(i));
306 
307  // We want to minimize the cost when this literal is true.
308  const Literal min_literal =
309  objective.coefficients(i) > 0 ? literal.Negated() : literal;
310  blocking_clauses.push_back(std::vector<Literal>(1, min_literal));
311 
312  // Note that initialy, we do not create any extra variables.
313  assumptions.push_back(min_literal);
314  }
315 
316  // Print the number of variable with a non-zero cost.
317  logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
318  assumptions.size(), problem.num_variables(),
319  problem.constraints_size()));
320 
321  // Starts the algorithm. Each loop will solve the problem under the given
322  // assumptions, and if unsat, will relax exactly one of the objective
323  // variables (from the unsat core) to be in its "costly" state. When the
324  // algorithm terminates, the number of iterations is exactly the minimal
325  // objective value.
326  for (int iter = 0;; ++iter) {
327  const SatSolver::Status result =
328  solver->ResetAndSolveWithGivenAssumptions(assumptions);
329  if (result == SatSolver::FEASIBLE) {
330  ExtractAssignment(problem, *solver, solution);
331  Coefficient objective = ComputeObjectiveValue(problem, *solution);
332  logger.Log(CnfObjectiveLine(problem, objective));
333  return SatSolver::FEASIBLE;
334  }
335  if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
336 
337  // The interesting case: we have an unsat core.
338  //
339  // We need to add new "blocking" variables b_i for all the objective
340  // variable appearing in the core. Moreover, we will only relax as little
341  // as possible (to not miss the optimal), so we will enforce that the sum
342  // of the b_i is exactly one.
343  std::vector<Literal> core = solver->GetLastIncompatibleDecisions();
344  MinimizeCore(solver, &core);
345  solver->Backtrack(0);
346 
347  // Print the search progress.
348  logger.Log(absl::StrFormat("c iter:%d core:%u", iter, core.size()));
349 
350  // Special case for a singleton core.
351  if (core.size() == 1) {
352  // Find the index of the "objective" variable that need to be fixed in
353  // its "costly" state.
354  const int index =
355  std::find(assumptions.begin(), assumptions.end(), core[0]) -
356  assumptions.begin();
357  CHECK_LT(index, assumptions.size());
358 
359  // Fix it. We also fix all the associated blocking variables if any.
360  if (!solver->AddUnitClause(core[0].Negated())) {
361  return SatSolver::INFEASIBLE;
362  }
363  for (Literal b : blocking_clauses[index]) {
364  if (!solver->AddUnitClause(b.Negated())) return SatSolver::INFEASIBLE;
365  }
366 
367  // Erase this entry from the current "objective"
368  std::vector<int> to_delete(1, index);
369  DeleteVectorIndices(to_delete, &assumptions);
370  DeleteVectorIndices(to_delete, &blocking_clauses);
371  symmetry.DeleteIndices(to_delete);
372  } else {
373  symmetry.StartResolvingNewCore(iter);
374 
375  // We will add 2 * |core.size()| variables.
376  const int old_num_variables = solver->NumVariables();
377  if (core.size() == 2) {
378  // Special case. If core.size() == 2, we can use only one blocking
379  // variable (the other one beeing its negation). This actually do happen
380  // quite often in practice, so it is worth it.
381  solver->SetNumVariables(old_num_variables + 3);
382  } else {
383  solver->SetNumVariables(old_num_variables + 2 * core.size());
384  }
385 
386  // Temporary vectors for the constraint (sum new blocking variable == 1).
387  std::vector<LiteralWithCoeff> at_most_one_constraint;
388  std::vector<Literal> at_least_one_constraint;
389 
390  // This will be set to false if the problem becomes unsat while adding a
391  // new clause. This is unlikely, but may be possible.
392  bool ok = true;
393 
394  // Loop over the core.
395  int index = 0;
396  for (int i = 0; i < core.size(); ++i) {
397  // Since the assumptions appear in order in the core, we can find the
398  // relevant "objective" variable efficiently with a simple linear scan
399  // in the assumptions vector (done with index).
400  index =
401  std::find(assumptions.begin() + index, assumptions.end(), core[i]) -
402  assumptions.begin();
403  CHECK_LT(index, assumptions.size());
404 
405  // The new blocking and assumption variables for this core entry.
406  const Literal a(BooleanVariable(old_num_variables + i), true);
407  Literal b(BooleanVariable(old_num_variables + core.size() + i), true);
408  if (core.size() == 2) {
409  b = Literal(BooleanVariable(old_num_variables + 2), true);
410  if (i == 1) b = b.Negated();
411  }
412 
413  // Symmetry breaking clauses.
414  for (Literal l : symmetry.ProcessLiteral(index, b)) {
415  ok &= solver->AddBinaryClause(l.Negated(), b.Negated());
416  }
417 
418  // Note(user): There is more than one way to encode the algorithm in
419  // SAT. Here we "delete" the old blocking clause and add a new one. In
420  // the WPM1 algorithm below, the blocking clause is decomposed into
421  // 3-SAT and we don't need to delete anything.
422 
423  // First, fix the old "assumption" variable to false, which has the
424  // effect of deleting the old clause from the solver.
425  if (assumptions[index].Variable() >= problem.num_variables()) {
426  CHECK(solver->AddUnitClause(assumptions[index].Negated()));
427  }
428 
429  // Add the new blocking variable.
430  blocking_clauses[index].push_back(b);
431 
432  // Add the new clause to the solver. Temporary including the
433  // assumption, but removing it right afterwards.
434  blocking_clauses[index].push_back(a);
435  ok &= solver->AddProblemClause(blocking_clauses[index]);
436  blocking_clauses[index].pop_back();
437 
438  // For the "== 1" constraint on the blocking literals.
439  at_most_one_constraint.push_back(LiteralWithCoeff(b, 1.0));
440  at_least_one_constraint.push_back(b);
441 
442  // The new assumption variable replace the old one.
443  assumptions[index] = a.Negated();
444  }
445 
446  // Add the "<= 1" side of the "== 1" constraint.
447  ok &= solver->AddLinearConstraint(false, Coefficient(0), true,
448  Coefficient(1.0),
449  &at_most_one_constraint);
450 
451  // TODO(user): The algorithm does not really need the >= 1 side of this
452  // constraint. Initial investigation shows that it doesn't really help,
453  // but investigate more.
454  if (/* DISABLES CODE */ (false)) {
455  ok &= solver->AddProblemClause(at_least_one_constraint);
456  }
457 
458  if (!ok) {
459  LOG(INFO) << "Infeasible while adding a clause.";
460  return SatSolver::INFEASIBLE;
461  }
462  }
463  }
464 }
465 
467  const LinearBooleanProblem& problem,
468  SatSolver* solver,
469  std::vector<bool>* solution) {
470  Logger logger(log);
471  FuMalikSymmetryBreaker symmetry;
472 
473  // The current lower_bound on the cost.
474  // It will be correct after the initialization.
475  Coefficient lower_bound(static_cast<int64_t>(problem.objective().offset()));
477 
478  // The assumption literals and their associated cost.
479  std::vector<Literal> assumptions;
480  std::vector<Coefficient> costs;
481  std::vector<Literal> reference;
482 
483  // Initialization.
484  const LinearObjective& objective = problem.objective();
485  CHECK_GT(objective.coefficients_size(), 0);
486  for (int i = 0; i < objective.literals_size(); ++i) {
487  const Literal literal(objective.literals(i));
488  const Coefficient coeff(objective.coefficients(i));
489 
490  // We want to minimize the cost when the assumption is true.
491  // Note that initially, we do not create any extra variables.
492  if (coeff > 0) {
493  assumptions.push_back(literal.Negated());
494  costs.push_back(coeff);
495  } else {
496  assumptions.push_back(literal);
497  costs.push_back(-coeff);
498  lower_bound += coeff;
499  }
500  }
501  reference = assumptions;
502 
503  // This is used by the "stratified" approach.
504  Coefficient stratified_lower_bound =
505  *std::max_element(costs.begin(), costs.end());
506 
507  // Print the number of variables with a non-zero cost.
508  logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
509  assumptions.size(), problem.num_variables(),
510  problem.constraints_size()));
511 
512  for (int iter = 0;; ++iter) {
513  // This is called "hardening" in the literature.
514  // Basically, we know that there is only hardening_threshold weight left
515  // to distribute, so any assumption with a greater cost than this can never
516  // be false. We fix it instead of treating it as an assumption.
517  solver->Backtrack(0);
518  const Coefficient hardening_threshold = upper_bound - lower_bound;
519  CHECK_GE(hardening_threshold, 0);
520  std::vector<int> to_delete;
521  int num_above_threshold = 0;
522  for (int i = 0; i < assumptions.size(); ++i) {
523  if (costs[i] > hardening_threshold) {
524  if (!solver->AddUnitClause(assumptions[i])) {
525  return SatSolver::INFEASIBLE;
526  }
527  to_delete.push_back(i);
528  ++num_above_threshold;
529  } else {
530  // This impact the stratification heuristic.
531  if (solver->Assignment().LiteralIsTrue(assumptions[i])) {
532  to_delete.push_back(i);
533  }
534  }
535  }
536  if (!to_delete.empty()) {
537  logger.Log(absl::StrFormat("c fixed %u assumptions, %d with cost > %d",
538  to_delete.size(), num_above_threshold,
539  hardening_threshold.value()));
540  DeleteVectorIndices(to_delete, &assumptions);
541  DeleteVectorIndices(to_delete, &costs);
542  DeleteVectorIndices(to_delete, &reference);
543  symmetry.DeleteIndices(to_delete);
544  }
545 
546  // This is the "stratification" part.
547  // Extract the assumptions with a cost >= stratified_lower_bound.
548  std::vector<Literal> assumptions_subset;
549  for (int i = 0; i < assumptions.size(); ++i) {
550  if (costs[i] >= stratified_lower_bound) {
551  assumptions_subset.push_back(assumptions[i]);
552  }
553  }
554 
555  const SatSolver::Status result =
556  solver->ResetAndSolveWithGivenAssumptions(assumptions_subset);
557  if (result == SatSolver::FEASIBLE) {
558  // If not all assumptions were taken, continue with a lower stratified
559  // bound. Otherwise we have an optimal solution!
560  //
561  // TODO(user): Try more advanced variant where the bound is lowered by
562  // more than this minimal amount.
563  const Coefficient old_lower_bound = stratified_lower_bound;
564  for (Coefficient cost : costs) {
565  if (cost < old_lower_bound) {
566  if (stratified_lower_bound == old_lower_bound ||
567  cost > stratified_lower_bound) {
568  stratified_lower_bound = cost;
569  }
570  }
571  }
572 
573  ExtractAssignment(problem, *solver, solution);
574  DCHECK(IsAssignmentValid(problem, *solution));
575  const Coefficient objective_offset(
576  static_cast<int64_t>(problem.objective().offset()));
577  const Coefficient objective = ComputeObjectiveValue(problem, *solution);
578  if (objective + objective_offset < upper_bound) {
579  logger.Log(CnfObjectiveLine(problem, objective));
580  upper_bound = objective + objective_offset;
581  }
582 
583  if (stratified_lower_bound < old_lower_bound) continue;
584  return SatSolver::FEASIBLE;
585  }
586  if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
587 
588  // The interesting case: we have an unsat core.
589  //
590  // We need to add new "blocking" variables b_i for all the objective
591  // variables appearing in the core. Moreover, we will only relax as little
592  // as possible (to not miss the optimal), so we will enforce that the sum
593  // of the b_i is exactly one.
594  std::vector<Literal> core = solver->GetLastIncompatibleDecisions();
595  MinimizeCore(solver, &core);
596  solver->Backtrack(0);
597 
598  // Compute the min cost of all the assertions in the core.
599  // The lower bound will be updated by that much.
600  Coefficient min_cost = kCoefficientMax;
601  {
602  int index = 0;
603  for (int i = 0; i < core.size(); ++i) {
604  index =
605  std::find(assumptions.begin() + index, assumptions.end(), core[i]) -
606  assumptions.begin();
607  CHECK_LT(index, assumptions.size());
608  min_cost = std::min(min_cost, costs[index]);
609  }
610  }
611  lower_bound += min_cost;
612 
613  // Print the search progress.
614  logger.Log(absl::StrFormat(
615  "c iter:%d core:%u lb:%d min_cost:%d strat:%d", iter, core.size(),
616  lower_bound.value(), min_cost.value(), stratified_lower_bound.value()));
617 
618  // This simple line helps a lot on the packup-wpms instances!
619  //
620  // TODO(user): That was because of a bug before in the way
621  // stratified_lower_bound was decremented, not sure it helps that much now.
622  if (min_cost > stratified_lower_bound) {
623  stratified_lower_bound = min_cost;
624  }
625 
626  // Special case for a singleton core.
627  if (core.size() == 1) {
628  // Find the index of the "objective" variable that need to be fixed in
629  // its "costly" state.
630  const int index =
631  std::find(assumptions.begin(), assumptions.end(), core[0]) -
632  assumptions.begin();
633  CHECK_LT(index, assumptions.size());
634 
635  // Fix it.
636  if (!solver->AddUnitClause(core[0].Negated())) {
637  return SatSolver::INFEASIBLE;
638  }
639 
640  // Erase this entry from the current "objective".
641  std::vector<int> to_delete(1, index);
642  DeleteVectorIndices(to_delete, &assumptions);
643  DeleteVectorIndices(to_delete, &costs);
644  DeleteVectorIndices(to_delete, &reference);
645  symmetry.DeleteIndices(to_delete);
646  } else {
647  symmetry.StartResolvingNewCore(iter);
648 
649  // We will add 2 * |core.size()| variables.
650  const int old_num_variables = solver->NumVariables();
651  if (core.size() == 2) {
652  // Special case. If core.size() == 2, we can use only one blocking
653  // variable (the other one beeing its negation). This actually do happen
654  // quite often in practice, so it is worth it.
655  solver->SetNumVariables(old_num_variables + 3);
656  } else {
657  solver->SetNumVariables(old_num_variables + 2 * core.size());
658  }
659 
660  // Temporary vectors for the constraint (sum new blocking variable == 1).
661  std::vector<LiteralWithCoeff> at_most_one_constraint;
662  std::vector<Literal> at_least_one_constraint;
663 
664  // This will be set to false if the problem becomes unsat while adding a
665  // new clause. This is unlikely, but may be possible.
666  bool ok = true;
667 
668  // Loop over the core.
669  int index = 0;
670  for (int i = 0; i < core.size(); ++i) {
671  // Since the assumptions appear in order in the core, we can find the
672  // relevant "objective" variable efficiently with a simple linear scan
673  // in the assumptions vector (done with index).
674  index =
675  std::find(assumptions.begin() + index, assumptions.end(), core[i]) -
676  assumptions.begin();
677  CHECK_LT(index, assumptions.size());
678 
679  // The new blocking and assumption variables for this core entry.
680  const Literal a(BooleanVariable(old_num_variables + i), true);
681  Literal b(BooleanVariable(old_num_variables + core.size() + i), true);
682  if (core.size() == 2) {
683  b = Literal(BooleanVariable(old_num_variables + 2), true);
684  if (i == 1) b = b.Negated();
685  }
686 
687  // a false & b false => previous assumptions (which was false).
688  const Literal old_a = assumptions[index];
689  ok &= solver->AddTernaryClause(a, b, old_a);
690 
691  // Optional. Also add the two implications a => x and b => x where x is
692  // the negation of the previous assumption variable.
693  ok &= solver->AddBinaryClause(a.Negated(), old_a.Negated());
694  ok &= solver->AddBinaryClause(b.Negated(), old_a.Negated());
695 
696  // Optional. Also add the implication a => not(b).
697  ok &= solver->AddBinaryClause(a.Negated(), b.Negated());
698 
699  // This is the difference with the Fu & Malik algorithm.
700  // If the soft clause protected by old_a has a cost greater than
701  // min_cost then:
702  // - its cost is disminished by min_cost.
703  // - an identical clause with cost min_cost is artifically added to
704  // the problem.
705  CHECK_GE(costs[index], min_cost);
706  if (costs[index] == min_cost) {
707  // The new assumption variable replaces the old one.
708  assumptions[index] = a.Negated();
709 
710  // Symmetry breaking clauses.
711  for (Literal l : symmetry.ProcessLiteral(index, b)) {
712  ok &= solver->AddBinaryClause(l.Negated(), b.Negated());
713  }
714  } else {
715  // Since the cost of the given index changes, we need to start a new
716  // "equivalence" class for the symmetry breaking algo and clear the
717  // old one.
718  symmetry.AddInfo(assumptions.size(), b);
719  symmetry.ClearInfo(index);
720 
721  // Reduce the cost of the old assumption.
722  costs[index] -= min_cost;
723 
724  // We add the new assumption with a cost of min_cost.
725  //
726  // Note(user): I think it is nice that these are added after old_a
727  // because assuming old_a will implies all the derived assumptions to
728  // true, and thus they will never appear in a core until old_a is not
729  // an assumption anymore.
730  assumptions.push_back(a.Negated());
731  costs.push_back(min_cost);
732  reference.push_back(reference[index]);
733  }
734 
735  // For the "<= 1" constraint on the blocking literals.
736  // Note(user): we don't add the ">= 1" side because it is not needed for
737  // the correctness and it doesn't seems to help.
738  at_most_one_constraint.push_back(LiteralWithCoeff(b, 1.0));
739 
740  // Because we have a core, we know that at least one of the initial
741  // problem variables must be true. This seems to help a bit.
742  //
743  // TODO(user): Experiment more.
744  at_least_one_constraint.push_back(reference[index].Negated());
745  }
746 
747  // Add the "<= 1" side of the "== 1" constraint.
748  ok &= solver->AddLinearConstraint(false, Coefficient(0), true,
749  Coefficient(1.0),
750  &at_most_one_constraint);
751 
752  // Optional. Add the ">= 1" constraint on the initial problem variables.
753  ok &= solver->AddProblemClause(at_least_one_constraint);
754 
755  if (!ok) {
756  LOG(INFO) << "Unsat while adding a clause.";
757  return SatSolver::INFEASIBLE;
758  }
759  }
760  }
761 }
762 
764  const LinearBooleanProblem& problem,
765  int num_times, SatSolver* solver,
766  std::vector<bool>* solution) {
767  Logger logger(log);
768  const SatParameters initial_parameters = solver->parameters();
769 
770  MTRandom random("A random seed.");
771  SatParameters parameters = initial_parameters;
772  TimeLimit time_limit(parameters.max_time_in_seconds());
773 
774  // We start with a low conflict limit and increase it until we are able to
775  // solve the problem at least once. After this, the limit stays the same.
776  int max_number_of_conflicts = 5;
777  parameters.set_log_search_progress(false);
778 
779  Coefficient min_seen(std::numeric_limits<int64_t>::max());
780  Coefficient max_seen(std::numeric_limits<int64_t>::min());
781  Coefficient best(min_seen);
782  for (int i = 0; i < num_times; ++i) {
783  solver->Backtrack(0);
785 
786  parameters.set_max_number_of_conflicts(max_number_of_conflicts);
787  parameters.set_max_time_in_seconds(time_limit.GetTimeLeft());
788  parameters.set_random_seed(i);
789  solver->SetParameters(parameters);
790  solver->ResetDecisionHeuristic();
791 
792  const bool use_obj = absl::Bernoulli(random, 1.0 / 4);
793  if (use_obj) UseObjectiveForSatAssignmentPreference(problem, solver);
794 
795  const SatSolver::Status result = solver->Solve();
796  if (result == SatSolver::INFEASIBLE) {
797  // If the problem is INFEASIBLE after we over-constrained the objective,
798  // then we found an optimal solution, otherwise, even the decision problem
799  // is INFEASIBLE.
800  if (best == kCoefficientMax) return SatSolver::INFEASIBLE;
801  return SatSolver::FEASIBLE;
802  }
803  if (result == SatSolver::LIMIT_REACHED) {
804  // We augment the number of conflict until we have one feasible solution.
805  if (best == kCoefficientMax) ++max_number_of_conflicts;
806  if (time_limit.LimitReached()) return SatSolver::LIMIT_REACHED;
807  continue;
808  }
809 
810  CHECK_EQ(result, SatSolver::FEASIBLE);
811  std::vector<bool> candidate;
812  ExtractAssignment(problem, *solver, &candidate);
813  CHECK(IsAssignmentValid(problem, candidate));
814  const Coefficient objective = ComputeObjectiveValue(problem, candidate);
815  if (objective < best) {
816  *solution = candidate;
817  best = objective;
818  logger.Log(CnfObjectiveLine(problem, objective));
819 
820  // Overconstrain the objective.
821  solver->Backtrack(0);
822  if (!AddObjectiveConstraint(problem, false, Coefficient(0), true,
823  objective - 1, solver)) {
824  return SatSolver::FEASIBLE;
825  }
826  }
827  min_seen = std::min(min_seen, objective);
828  max_seen = std::max(max_seen, objective);
829 
830  logger.Log(absl::StrCat(
831  "c ", objective.value(), " [", min_seen.value(), ", ", max_seen.value(),
832  "] objective_preference: ", use_obj ? "true" : "false", " ",
834  }
835 
836  // Retore the initial parameter (with an updated time limit).
837  parameters = initial_parameters;
838  parameters.set_max_time_in_seconds(time_limit.GetTimeLeft());
839  solver->SetParameters(parameters);
841 }
842 
844  const LinearBooleanProblem& problem,
845  SatSolver* solver,
846  std::vector<bool>* solution) {
847  Logger logger(log);
848 
849  // This has a big positive impact on most problems.
851 
852  Coefficient objective = kCoefficientMax;
853  if (!solution->empty()) {
854  CHECK(IsAssignmentValid(problem, *solution));
855  objective = ComputeObjectiveValue(problem, *solution);
856  }
857  while (true) {
858  if (objective != kCoefficientMax) {
859  // Over constrain the objective.
860  solver->Backtrack(0);
861  if (!AddObjectiveConstraint(problem, false, Coefficient(0), true,
862  objective - 1, solver)) {
863  return SatSolver::FEASIBLE;
864  }
865  }
866 
867  // Solve the problem.
868  const SatSolver::Status result = solver->Solve();
870  if (result == SatSolver::INFEASIBLE) {
871  if (objective == kCoefficientMax) return SatSolver::INFEASIBLE;
872  return SatSolver::FEASIBLE;
873  }
874  if (result == SatSolver::LIMIT_REACHED) {
876  }
877 
878  // Extract the new best solution.
879  CHECK_EQ(result, SatSolver::FEASIBLE);
880  ExtractAssignment(problem, *solver, solution);
881  CHECK(IsAssignmentValid(problem, *solution));
882  const Coefficient old_objective = objective;
883  objective = ComputeObjectiveValue(problem, *solution);
884  CHECK_LT(objective, old_objective);
885  logger.Log(CnfObjectiveLine(problem, objective));
886  }
887 }
888 
890  LogBehavior log, const LinearBooleanProblem& problem, SatSolver* solver,
891  std::vector<bool>* solution) {
892  Logger logger(log);
893  std::deque<EncodingNode> repository;
894 
895  // Create one initial node per variables with cost.
896  Coefficient offset(0);
897  std::vector<EncodingNode*> nodes =
898  CreateInitialEncodingNodes(problem.objective(), &offset, &repository);
899 
900  // This algorithm only work with weights of the same magnitude.
901  CHECK(!nodes.empty());
902  const Coefficient reference = nodes.front()->weight();
903  for (const EncodingNode* n : nodes) CHECK_EQ(n->weight(), reference);
904 
905  // Initialize the current objective.
906  Coefficient objective = kCoefficientMax;
907  Coefficient upper_bound = kCoefficientMax;
908  if (!solution->empty()) {
909  CHECK(IsAssignmentValid(problem, *solution));
910  objective = ComputeObjectiveValue(problem, *solution);
911  upper_bound = objective + offset;
912  }
913 
914  // Print the number of variables with a non-zero cost.
915  logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
916  nodes.size(), problem.num_variables(),
917  problem.constraints_size()));
918 
919  // Create the sorter network.
920  solver->Backtrack(0);
921  EncodingNode* root =
922  MergeAllNodesWithDeque(upper_bound, nodes, solver, &repository);
923  logger.Log(absl::StrFormat("c encoding depth:%d", root->depth()));
924 
925  while (true) {
926  if (objective != kCoefficientMax) {
927  // Over constrain the objective by fixing the variable index - 1 of the
928  // root node to 0.
929  const int index = offset.value() + objective.value();
930  if (index == 0) return SatSolver::FEASIBLE;
931  solver->Backtrack(0);
932  if (!solver->AddUnitClause(root->literal(index - 1).Negated())) {
933  return SatSolver::FEASIBLE;
934  }
935  }
936 
937  // Solve the problem.
938  const SatSolver::Status result = solver->Solve();
940  if (result == SatSolver::INFEASIBLE) {
941  if (objective == kCoefficientMax) return SatSolver::INFEASIBLE;
942  return SatSolver::FEASIBLE;
943  }
945 
946  // Extract the new best solution.
947  CHECK_EQ(result, SatSolver::FEASIBLE);
948  ExtractAssignment(problem, *solver, solution);
949  CHECK(IsAssignmentValid(problem, *solution));
950  const Coefficient old_objective = objective;
951  objective = ComputeObjectiveValue(problem, *solution);
952  CHECK_LT(objective, old_objective);
953  logger.Log(CnfObjectiveLine(problem, objective));
954  }
955 }
956 
958  LogBehavior log, const LinearBooleanProblem& problem, SatSolver* solver,
959  std::vector<bool>* solution) {
960  Logger logger(log);
961  SatParameters parameters = solver->parameters();
962 
963  // Create one initial nodes per variables with cost.
964  Coefficient offset(0);
965  std::deque<EncodingNode> repository;
966  std::vector<EncodingNode*> nodes =
967  CreateInitialEncodingNodes(problem.objective(), &offset, &repository);
968 
969  // Initialize the bounds.
970  // This is in term of number of variables not at their minimal value.
971  Coefficient lower_bound(0);
973  if (!solution->empty()) {
974  CHECK(IsAssignmentValid(problem, *solution));
975  upper_bound = ComputeObjectiveValue(problem, *solution) + offset;
976  }
977 
978  // Print the number of variables with a non-zero cost.
979  logger.Log(absl::StrFormat("c #weights:%u #vars:%d #constraints:%d",
980  nodes.size(), problem.num_variables(),
981  problem.constraints_size()));
982 
983  // This is used by the "stratified" approach.
984  Coefficient stratified_lower_bound(0);
985  if (parameters.max_sat_stratification() ==
986  SatParameters::STRATIFICATION_DESCENT) {
987  // In this case, we initialize it to the maximum assumption weights.
988  for (EncodingNode* n : nodes) {
989  stratified_lower_bound = std::max(stratified_lower_bound, n->weight());
990  }
991  }
992 
993  // Start the algorithm.
994  int max_depth = 0;
995  std::string previous_core_info = "";
996  for (int iter = 0;; ++iter) {
997  const std::vector<Literal> assumptions = ReduceNodesAndExtractAssumptions(
998  upper_bound, stratified_lower_bound, &lower_bound, &nodes, solver);
999  if (assumptions.empty()) return SatSolver::FEASIBLE;
1000 
1001  // Display the progress.
1002  const std::string gap_string =
1004  ? ""
1005  : absl::StrFormat(" gap:%d", (upper_bound - lower_bound).value());
1006  logger.Log(
1007  absl::StrFormat("c iter:%d [%s] lb:%d%s assumptions:%u depth:%d", iter,
1008  previous_core_info,
1009  lower_bound.value() - offset.value() +
1010  static_cast<int64_t>(problem.objective().offset()),
1011  gap_string, nodes.size(), max_depth));
1012 
1013  // Solve under the assumptions.
1014  const SatSolver::Status result =
1015  solver->ResetAndSolveWithGivenAssumptions(assumptions);
1016  if (result == SatSolver::FEASIBLE) {
1017  // Extract the new solution and save it if it is the best found so far.
1018  std::vector<bool> temp_solution;
1019  ExtractAssignment(problem, *solver, &temp_solution);
1020  CHECK(IsAssignmentValid(problem, temp_solution));
1021  const Coefficient obj = ComputeObjectiveValue(problem, temp_solution);
1022  if (obj + offset < upper_bound) {
1023  *solution = temp_solution;
1024  logger.Log(CnfObjectiveLine(problem, obj));
1025  upper_bound = obj + offset;
1026  }
1027 
1028  // If not all assumptions were taken, continue with a lower stratified
1029  // bound. Otherwise we have an optimal solution.
1030  stratified_lower_bound =
1031  MaxNodeWeightSmallerThan(nodes, stratified_lower_bound);
1032  if (stratified_lower_bound > 0) continue;
1033  return SatSolver::FEASIBLE;
1034  }
1035  if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
1036 
1037  // We have a new core.
1038  std::vector<Literal> core = solver->GetLastIncompatibleDecisions();
1039  if (parameters.minimize_core()) MinimizeCore(solver, &core);
1040 
1041  // Compute the min weight of all the nodes in the core.
1042  // The lower bound will be increased by that much.
1043  const Coefficient min_weight = ComputeCoreMinWeight(nodes, core);
1044  previous_core_info =
1045  absl::StrFormat("core:%u mw:%d", core.size(), min_weight.value());
1046 
1047  // Increase stratified_lower_bound according to the parameters.
1048  if (stratified_lower_bound < min_weight &&
1049  parameters.max_sat_stratification() ==
1050  SatParameters::STRATIFICATION_ASCENT) {
1051  stratified_lower_bound = min_weight;
1052  }
1053 
1054  ProcessCore(core, min_weight, &repository, &nodes, solver);
1055  max_depth = std::max(max_depth, nodes.back()->depth());
1056  }
1057 }
1058 
1060  IntegerVariable objective_var,
1061  const std::function<void()>& feasible_solution_observer, Model* model) {
1062  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1063  IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
1064  const SatParameters& parameters = *(model->GetOrCreate<SatParameters>());
1065 
1066  // Simple linear scan algorithm to find the optimal.
1067  while (true) {
1069  if (result != SatSolver::FEASIBLE) return result;
1070 
1071  // The objective is the current lower bound of the objective_var.
1072  const IntegerValue objective = integer_trail->LowerBound(objective_var);
1073 
1074  // We have a solution!
1075  if (feasible_solution_observer != nullptr) {
1076  feasible_solution_observer();
1077  }
1078  if (parameters.stop_after_first_solution()) {
1079  return SatSolver::LIMIT_REACHED;
1080  }
1081 
1082  // Restrict the objective.
1083  sat_solver->Backtrack(0);
1084  if (!integer_trail->Enqueue(
1085  IntegerLiteral::LowerOrEqual(objective_var, objective - 1), {},
1086  {})) {
1087  return SatSolver::INFEASIBLE;
1088  }
1089  }
1090 }
1091 
1093  IntegerVariable objective_var,
1094  const std::function<void()>& feasible_solution_observer, Model* model) {
1095  const SatParameters old_params = *model->GetOrCreate<SatParameters>();
1096  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1097  IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
1098  IntegerEncoder* integer_encoder = model->GetOrCreate<IntegerEncoder>();
1099 
1100  // Set the requested conflict limit.
1101  {
1102  SatParameters new_params = old_params;
1103  new_params.set_max_number_of_conflicts(
1104  old_params.binary_search_num_conflicts());
1105  *model->GetOrCreate<SatParameters>() = new_params;
1106  }
1107 
1108  // The assumption (objective <= value) for values in
1109  // [unknown_min, unknown_max] reached the conflict limit.
1110  bool loop = true;
1111  IntegerValue unknown_min = integer_trail->UpperBound(objective_var);
1112  IntegerValue unknown_max = integer_trail->LowerBound(objective_var);
1113  while (loop) {
1114  sat_solver->Backtrack(0);
1115  const IntegerValue lb = integer_trail->LowerBound(objective_var);
1116  const IntegerValue ub = integer_trail->UpperBound(objective_var);
1117  unknown_min = std::min(unknown_min, ub);
1118  unknown_max = std::max(unknown_max, lb);
1119 
1120  // We first refine the lower bound and then the upper bound.
1121  IntegerValue target;
1122  if (lb < unknown_min) {
1123  target = lb + (unknown_min - lb) / 2;
1124  } else if (unknown_max < ub) {
1125  target = ub - (ub - unknown_max) / 2;
1126  } else {
1127  VLOG(1) << "Binary-search, done.";
1128  break;
1129  }
1130  VLOG(1) << "Binary-search, objective: [" << lb << "," << ub << "]"
1131  << " tried: [" << unknown_min << "," << unknown_max << "]"
1132  << " target: obj<=" << target;
1133  SatSolver::Status result;
1134  if (target < ub) {
1135  const Literal assumption = integer_encoder->GetOrCreateAssociatedLiteral(
1136  IntegerLiteral::LowerOrEqual(objective_var, target));
1137  result = ResetAndSolveIntegerProblem({assumption}, model);
1138  } else {
1139  result = ResetAndSolveIntegerProblem({}, model);
1140  }
1141 
1142  switch (result) {
1143  case SatSolver::INFEASIBLE: {
1144  loop = false;
1145  break;
1146  }
1148  // Update the objective lower bound.
1149  sat_solver->Backtrack(0);
1150  if (!integer_trail->Enqueue(
1151  IntegerLiteral::GreaterOrEqual(objective_var, target + 1), {},
1152  {})) {
1153  loop = false;
1154  }
1155  break;
1156  }
1157  case SatSolver::FEASIBLE: {
1158  // The objective is the current lower bound of the objective_var.
1159  const IntegerValue objective = integer_trail->LowerBound(objective_var);
1160  if (feasible_solution_observer != nullptr) {
1161  feasible_solution_observer();
1162  }
1163 
1164  // We have a solution, restrict the objective upper bound to only look
1165  // for better ones now.
1166  sat_solver->Backtrack(0);
1167  if (!integer_trail->Enqueue(
1168  IntegerLiteral::LowerOrEqual(objective_var, objective - 1), {},
1169  {})) {
1170  loop = false;
1171  }
1172  break;
1173  }
1174  case SatSolver::LIMIT_REACHED: {
1175  unknown_min = std::min(target, unknown_min);
1176  unknown_max = std::max(target, unknown_max);
1177  break;
1178  }
1179  }
1180  }
1181 
1182  sat_solver->Backtrack(0);
1183  *model->GetOrCreate<SatParameters>() = old_params;
1184 }
1185 
1186 namespace {
1187 
1188 // If the given model is unsat under the given assumptions, returns one or more
1189 // non-overlapping set of assumptions, each set making the problem infeasible on
1190 // its own (the cores).
1191 //
1192 // In presence of weights, we "generalize" the notions of disjoints core using
1193 // the WCE idea describe in "Weight-Aware Core Extraction in SAT-Based MaxSAT
1194 // solving" Jeremias Berg And Matti Jarvisalo.
1195 //
1196 // The returned status can be either:
1197 // - ASSUMPTIONS_UNSAT if the set of returned core perfectly cover the given
1198 // assumptions, in this case, we don't bother trying to find a SAT solution
1199 // with no assumptions.
1200 // - FEASIBLE if after finding zero or more core we have a solution.
1201 // - LIMIT_REACHED if we reached the time-limit before one of the two status
1202 // above could be decided.
1203 //
1204 // TODO(user): There is many way to combine the WCE and stratification
1205 // heuristics. I didn't had time to properly compare the different approach. See
1206 // the WCE papers for some ideas, but there is many more ways to try to find a
1207 // lot of core at once and try to minimize the minimum weight of each of the
1208 // cores.
1209 SatSolver::Status FindCores(std::vector<Literal> assumptions,
1210  std::vector<IntegerValue> assumption_weights,
1211  IntegerValue stratified_threshold, Model* model,
1212  std::vector<std::vector<Literal>>* cores) {
1213  cores->clear();
1214  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1215  TimeLimit* limit = model->GetOrCreate<TimeLimit>();
1216  do {
1217  if (limit->LimitReached()) return SatSolver::LIMIT_REACHED;
1218 
1219  const SatSolver::Status result =
1220  ResetAndSolveIntegerProblem(assumptions, model);
1221  if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
1222  std::vector<Literal> core = sat_solver->GetLastIncompatibleDecisions();
1223  if (sat_solver->parameters().minimize_core()) {
1224  MinimizeCoreWithPropagation(limit, sat_solver, &core);
1225  }
1226  CHECK(!core.empty());
1227  cores->push_back(core);
1228  if (!sat_solver->parameters().find_multiple_cores()) break;
1229 
1230  // Recover the original indices of the assumptions that are part of the
1231  // core.
1232  std::vector<int> indices;
1233  {
1234  std::set<Literal> temp(core.begin(), core.end());
1235  for (int i = 0; i < assumptions.size(); ++i) {
1236  if (gtl::ContainsKey(temp, assumptions[i])) {
1237  indices.push_back(i);
1238  }
1239  }
1240  }
1241 
1242  // Remove min_weight from the weights of all the assumptions in the core.
1243  //
1244  // TODO(user): push right away the objective bound by that much? This should
1245  // be better in a multi-threading context as we can share more quickly the
1246  // better bound.
1247  IntegerValue min_weight = assumption_weights[indices.front()];
1248  for (const int i : indices) {
1249  min_weight = std::min(min_weight, assumption_weights[i]);
1250  }
1251  for (const int i : indices) {
1252  assumption_weights[i] -= min_weight;
1253  }
1254 
1255  // Remove from assumptions all the one with a new weight smaller than the
1256  // current stratification threshold and see if we can find another core.
1257  int new_size = 0;
1258  for (int i = 0; i < assumptions.size(); ++i) {
1259  if (assumption_weights[i] < stratified_threshold) continue;
1260  assumptions[new_size] = assumptions[i];
1261  assumption_weights[new_size] = assumption_weights[i];
1262  ++new_size;
1263  }
1264  assumptions.resize(new_size);
1265  assumption_weights.resize(new_size);
1266  } while (!assumptions.empty());
1268 }
1269 
1270 // Slightly different algo than FindCores() which aim to extract more cores, but
1271 // not necessarily non-overlaping ones.
1272 SatSolver::Status FindMultipleCoresForMaxHs(
1273  std::vector<Literal> assumptions, Model* model,
1274  std::vector<std::vector<Literal>>* cores) {
1275  cores->clear();
1276  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1277  TimeLimit* limit = model->GetOrCreate<TimeLimit>();
1278  do {
1279  if (limit->LimitReached()) return SatSolver::LIMIT_REACHED;
1280 
1281  const SatSolver::Status result =
1282  ResetAndSolveIntegerProblem(assumptions, model);
1283  if (result != SatSolver::ASSUMPTIONS_UNSAT) return result;
1284  std::vector<Literal> core = sat_solver->GetLastIncompatibleDecisions();
1285  if (sat_solver->parameters().minimize_core()) {
1286  MinimizeCoreWithPropagation(limit, sat_solver, &core);
1287  }
1288  CHECK(!core.empty());
1289  cores->push_back(core);
1290  if (!sat_solver->parameters().find_multiple_cores()) break;
1291 
1292  // Pick a random literal from the core and remove it from the set of
1293  // assumptions.
1294  CHECK(!core.empty());
1295  auto* random = model->GetOrCreate<ModelRandomGenerator>();
1296  const Literal random_literal =
1297  core[absl::Uniform<int>(*random, 0, core.size())];
1298  for (int i = 0; i < assumptions.size(); ++i) {
1299  if (assumptions[i] == random_literal) {
1300  std::swap(assumptions[i], assumptions.back());
1301  assumptions.pop_back();
1302  break;
1303  }
1304  }
1305  } while (!assumptions.empty());
1307 }
1308 
1309 } // namespace
1310 
1312  IntegerVariable objective_var,
1313  const std::vector<IntegerVariable>& variables,
1314  const std::vector<IntegerValue>& coefficients,
1315  std::function<void()> feasible_solution_observer, Model* model)
1316  : parameters_(model->GetOrCreate<SatParameters>()),
1317  sat_solver_(model->GetOrCreate<SatSolver>()),
1318  time_limit_(model->GetOrCreate<TimeLimit>()),
1319  integer_trail_(model->GetOrCreate<IntegerTrail>()),
1320  integer_encoder_(model->GetOrCreate<IntegerEncoder>()),
1321  model_(model),
1322  objective_var_(objective_var),
1323  feasible_solution_observer_(std::move(feasible_solution_observer)) {
1324  CHECK_EQ(variables.size(), coefficients.size());
1325  for (int i = 0; i < variables.size(); ++i) {
1326  if (coefficients[i] > 0) {
1327  terms_.push_back({variables[i], coefficients[i]});
1328  } else if (coefficients[i] < 0) {
1329  terms_.push_back({NegationOf(variables[i]), -coefficients[i]});
1330  } else {
1331  continue; // coefficients[i] == 0
1332  }
1333  terms_.back().depth = 0;
1334  }
1335 
1336  // This is used by the "stratified" approach. We will only consider terms with
1337  // a weight not lower than this threshold. The threshold will decrease as the
1338  // algorithm progress.
1339  stratification_threshold_ = parameters_->max_sat_stratification() ==
1340  SatParameters::STRATIFICATION_NONE
1341  ? IntegerValue(1)
1342  : kMaxIntegerValue;
1343 }
1344 
1345 bool CoreBasedOptimizer::ProcessSolution() {
1346  // We don't assume that objective_var is linked with its linear term, so
1347  // we recompute the objective here.
1348  IntegerValue objective(0);
1349  for (ObjectiveTerm& term : terms_) {
1350  const IntegerValue value = integer_trail_->LowerBound(term.var);
1351  objective += term.weight * value;
1352 
1353  // Also keep in term.cover_ub the minimum value for term.var that we have
1354  // seens amongst all the feasible solutions found so far.
1355  term.cover_ub = std::min(term.cover_ub, value);
1356  }
1357 
1358  // We use the level zero upper bound of the objective to indicate an upper
1359  // limit for the solution objective we are looking for. Again, because the
1360  // objective_var is not assumed to be linked, it could take any value in the
1361  // current solution.
1362  if (objective > integer_trail_->LevelZeroUpperBound(objective_var_)) {
1363  return true;
1364  }
1365 
1366  if (feasible_solution_observer_ != nullptr) {
1367  feasible_solution_observer_();
1368  }
1369  if (parameters_->stop_after_first_solution()) {
1370  stop_ = true;
1371  }
1372 
1373  // Constrain objective_var. This has a better result when objective_var is
1374  // used in an LP relaxation for instance.
1375  sat_solver_->Backtrack(0);
1376  sat_solver_->SetAssumptionLevel(0);
1377  return integer_trail_->Enqueue(
1378  IntegerLiteral::LowerOrEqual(objective_var_, objective - 1), {}, {});
1379 }
1380 
1381 bool CoreBasedOptimizer::PropagateObjectiveBounds() {
1382  // We assumes all terms (modulo stratification) at their lower-bound.
1383  bool some_bound_were_tightened = true;
1384  while (some_bound_were_tightened) {
1385  some_bound_were_tightened = false;
1386  if (!sat_solver_->ResetToLevelZero()) return false;
1387 
1388  // Compute implied lb.
1389  IntegerValue implied_objective_lb(0);
1390  for (ObjectiveTerm& term : terms_) {
1391  const IntegerValue var_lb = integer_trail_->LowerBound(term.var);
1392  term.old_var_lb = var_lb;
1393  implied_objective_lb += term.weight * var_lb.value();
1394  }
1395 
1396  // Update the objective lower bound with our current bound.
1397  if (implied_objective_lb > integer_trail_->LowerBound(objective_var_)) {
1398  if (!integer_trail_->Enqueue(IntegerLiteral::GreaterOrEqual(
1399  objective_var_, implied_objective_lb),
1400  {}, {})) {
1401  return false;
1402  }
1403 
1404  some_bound_were_tightened = true;
1405  }
1406 
1407  // The gap is used to propagate the upper-bound of all variable that are
1408  // in the current objective (Exactly like done in the propagation of a
1409  // linear constraint with the slack). When this fix a variable to its
1410  // lower bound, it is called "hardening" in the max-sat literature. This
1411  // has a really beneficial effect on some weighted max-sat problems like
1412  // the haplotyping-pedigrees ones.
1413  const IntegerValue gap =
1414  integer_trail_->UpperBound(objective_var_) - implied_objective_lb;
1415 
1416  for (const ObjectiveTerm& term : terms_) {
1417  if (term.weight == 0) continue;
1418  const IntegerValue var_lb = integer_trail_->LowerBound(term.var);
1419  const IntegerValue var_ub = integer_trail_->UpperBound(term.var);
1420  if (var_lb == var_ub) continue;
1421 
1422  // Hardening. This basically just propagate the implied upper bound on
1423  // term.var from the current best solution. Note that the gap is
1424  // non-negative and the weight positive here. The test is done in order
1425  // to avoid any integer overflow provided (ub - lb) do not overflow, but
1426  // this is a precondition in our cp-model.
1427  if (gap / term.weight < var_ub - var_lb) {
1428  some_bound_were_tightened = true;
1429  const IntegerValue new_ub = var_lb + gap / term.weight;
1430  CHECK_LT(new_ub, var_ub);
1431  CHECK(!integer_trail_->IsCurrentlyIgnored(term.var));
1432  if (!integer_trail_->Enqueue(
1433  IntegerLiteral::LowerOrEqual(term.var, new_ub), {}, {})) {
1434  return false;
1435  }
1436  }
1437  }
1438  }
1439  return true;
1440 }
1441 
1442 // A basic algorithm is to take the next one, or at least the next one
1443 // that invalidate the current solution. But to avoid corner cases for
1444 // problem with a lot of terms all with different objective weights (in
1445 // which case we will kind of introduce only one assumption per loop
1446 // which is little), we use an heuristic and take the 90% percentile of
1447 // the unique weights not yet included.
1448 //
1449 // TODO(user): There is many other possible heuristics here, and I
1450 // didn't have the time to properly compare them.
1451 void CoreBasedOptimizer::ComputeNextStratificationThreshold() {
1452  std::vector<IntegerValue> weights;
1453  for (ObjectiveTerm& term : terms_) {
1454  if (term.weight >= stratification_threshold_) continue;
1455  if (term.weight == 0) continue;
1456 
1457  const IntegerValue var_lb = integer_trail_->LevelZeroLowerBound(term.var);
1458  const IntegerValue var_ub = integer_trail_->LevelZeroUpperBound(term.var);
1459  if (var_lb == var_ub) continue;
1460 
1461  weights.push_back(term.weight);
1462  }
1463  if (weights.empty()) {
1464  stratification_threshold_ = IntegerValue(0);
1465  return;
1466  }
1467 
1469  stratification_threshold_ =
1470  weights[static_cast<int>(std::floor(0.9 * weights.size()))];
1471 }
1472 
1473 bool CoreBasedOptimizer::CoverOptimization() {
1474  // We set a fix deterministic time limit per all sub-solve and skip to the
1475  // next core if the sum of the subsolve is also over this limit.
1476  constexpr double max_dtime_per_core = 0.5;
1477  const double old_time_limit = parameters_->max_deterministic_time();
1478  parameters_->set_max_deterministic_time(max_dtime_per_core);
1479  auto cleanup = ::absl::MakeCleanup([old_time_limit, this]() {
1480  parameters_->set_max_deterministic_time(old_time_limit);
1481  });
1482 
1483  for (const ObjectiveTerm& term : terms_) {
1484  // We currently skip the initial objective terms as there could be many
1485  // of them. TODO(user): provide an option to cover-optimize them? I
1486  // fear that this will slow down the solver too much though.
1487  if (term.depth == 0) continue;
1488 
1489  // Find out the true lower bound of var. This is called "cover
1490  // optimization" in some of the max-SAT literature. It can helps on some
1491  // problem families and hurt on others, but the overall impact is
1492  // positive.
1493  const IntegerVariable var = term.var;
1494  IntegerValue best =
1495  std::min(term.cover_ub, integer_trail_->UpperBound(var));
1496 
1497  // Note(user): this can happen in some corner case because each time we
1498  // find a solution, we constrain the objective to be smaller than it, so
1499  // it is possible that a previous best is now infeasible.
1500  if (best <= integer_trail_->LowerBound(var)) continue;
1501 
1502  // Compute the global deterministic time for this core cover
1503  // optimization.
1504  const double deterministic_limit =
1505  time_limit_->GetElapsedDeterministicTime() + max_dtime_per_core;
1506 
1507  // Simple linear scan algorithm to find the optimal of var.
1508  SatSolver::Status result;
1509  while (best > integer_trail_->LowerBound(var)) {
1510  const Literal assumption = integer_encoder_->GetOrCreateAssociatedLiteral(
1511  IntegerLiteral::LowerOrEqual(var, best - 1));
1512  result = ResetAndSolveIntegerProblem({assumption}, model_);
1513  if (result != SatSolver::FEASIBLE) break;
1514 
1515  best = integer_trail_->LowerBound(var);
1516  VLOG(1) << "cover_opt var:" << var << " domain:["
1517  << integer_trail_->LevelZeroLowerBound(var) << "," << best << "]";
1518  if (!ProcessSolution()) return false;
1519  if (!sat_solver_->ResetToLevelZero()) return false;
1520  if (stop_ ||
1521  time_limit_->GetElapsedDeterministicTime() > deterministic_limit) {
1522  break;
1523  }
1524  }
1525  if (result == SatSolver::INFEASIBLE) return false;
1526  if (result == SatSolver::ASSUMPTIONS_UNSAT) {
1527  // TODO(user): If we improve the lower bound of var, we should check
1528  // if our global lower bound reached our current best solution in
1529  // order to abort early if the optimal is proved.
1530  if (!integer_trail_->Enqueue(IntegerLiteral::GreaterOrEqual(var, best),
1531  {}, {})) {
1532  return false;
1533  }
1534  }
1535  }
1536 
1537  if (!PropagateObjectiveBounds()) return false;
1538  return true;
1539 }
1540 
1542  // TODO(user): The core is returned in the same order as the assumptions,
1543  // so we don't really need this map, we could just do a linear scan to
1544  // recover which node are part of the core. This however needs to be properly
1545  // unit tested before usage.
1546  std::map<LiteralIndex, int> literal_to_term_index;
1547 
1548  // Start the algorithm.
1549  stop_ = false;
1550  while (true) {
1551  // TODO(user): This always resets the solver to level zero.
1552  // Because of that we don't resume a solve in "chunk" perfectly. Fix.
1553  if (!PropagateObjectiveBounds()) return SatSolver::INFEASIBLE;
1554 
1555  // Bulk cover optimization.
1556  //
1557  // TODO(user): If the search is aborted during this phase and we solve in
1558  // "chunk", we don't resume perfectly from where it was. Fix.
1559  if (parameters_->cover_optimization()) {
1560  if (!CoverOptimization()) return SatSolver::INFEASIBLE;
1561  if (stop_) return SatSolver::LIMIT_REACHED;
1562  }
1563 
1564  // We assumes all terms (modulo stratification) at their lower-bound.
1565  std::vector<int> term_indices;
1566  std::vector<IntegerLiteral> integer_assumptions;
1567  std::vector<IntegerValue> assumption_weights;
1568  IntegerValue objective_offset(0);
1569  bool some_assumptions_were_skipped = false;
1570  for (int i = 0; i < terms_.size(); ++i) {
1571  const ObjectiveTerm term = terms_[i];
1572 
1573  // TODO(user): These can be simply removed from the list.
1574  if (term.weight == 0) continue;
1575 
1576  // Skip fixed terms.
1577  // We still keep them around for a proper lower-bound computation.
1578  //
1579  // TODO(user): we could keep an objective offset instead.
1580  const IntegerValue var_lb = integer_trail_->LowerBound(term.var);
1581  const IntegerValue var_ub = integer_trail_->UpperBound(term.var);
1582  if (var_lb == var_ub) {
1583  objective_offset += term.weight * var_lb.value();
1584  continue;
1585  }
1586 
1587  // Only consider the terms above the threshold.
1588  if (term.weight >= stratification_threshold_) {
1589  integer_assumptions.push_back(
1590  IntegerLiteral::LowerOrEqual(term.var, var_lb));
1591  assumption_weights.push_back(term.weight);
1592  term_indices.push_back(i);
1593  } else {
1594  some_assumptions_were_skipped = true;
1595  }
1596  }
1597 
1598  // No assumptions with the current stratification? use the next one.
1599  if (term_indices.empty() && some_assumptions_were_skipped) {
1600  ComputeNextStratificationThreshold();
1601  continue;
1602  }
1603 
1604  // If there is only one or two assumptions left, we switch the algorithm.
1605  if (term_indices.size() <= 2 && !some_assumptions_were_skipped) {
1606  VLOG(1) << "Switching to linear scan...";
1607  if (!already_switched_to_linear_scan_) {
1608  already_switched_to_linear_scan_ = true;
1609  std::vector<IntegerVariable> constraint_vars;
1610  std::vector<int64_t> constraint_coeffs;
1611  for (const int index : term_indices) {
1612  constraint_vars.push_back(terms_[index].var);
1613  constraint_coeffs.push_back(terms_[index].weight.value());
1614  }
1615  constraint_vars.push_back(objective_var_);
1616  constraint_coeffs.push_back(-1);
1617  model_->Add(WeightedSumLowerOrEqual(constraint_vars, constraint_coeffs,
1618  -objective_offset.value()));
1619  }
1620 
1622  objective_var_, feasible_solution_observer_, model_);
1623  }
1624 
1625  // Display the progress.
1626  if (VLOG_IS_ON(1)) {
1627  int max_depth = 0;
1628  for (const ObjectiveTerm& term : terms_) {
1629  max_depth = std::max(max_depth, term.depth);
1630  }
1631  const int64_t lb = integer_trail_->LowerBound(objective_var_).value();
1632  const int64_t ub = integer_trail_->UpperBound(objective_var_).value();
1633  const int gap =
1634  lb == ub
1635  ? 0
1636  : static_cast<int>(std::ceil(
1637  100.0 * (ub - lb) / std::max(std::abs(ub), std::abs(lb))));
1638  VLOG(1) << absl::StrCat("unscaled_next_obj_range:[", lb, ",", ub,
1639  "]"
1640  " gap:",
1641  gap, "%", " assumptions:", term_indices.size(),
1642  " strat:", stratification_threshold_.value(),
1643  " depth:", max_depth);
1644  }
1645 
1646  // Convert integer_assumptions to Literals.
1647  std::vector<Literal> assumptions;
1648  literal_to_term_index.clear();
1649  for (int i = 0; i < integer_assumptions.size(); ++i) {
1650  assumptions.push_back(integer_encoder_->GetOrCreateAssociatedLiteral(
1651  integer_assumptions[i]));
1652 
1653  // Tricky: In some rare case, it is possible that the same literal
1654  // correspond to more that one assumptions. In this case, we can just
1655  // pick one of them when converting back a core to term indices.
1656  //
1657  // TODO(user): We can probably be smarter about the cost of the
1658  // assumptions though.
1659  literal_to_term_index[assumptions.back().Index()] = term_indices[i];
1660  }
1661 
1662  // Solve under the assumptions.
1663  //
1664  // TODO(user): If the "search" is interupted while computing cores, we
1665  // currently do not resume it flawlessly. We however add any cores we found
1666  // before aborting.
1667  std::vector<std::vector<Literal>> cores;
1668  const SatSolver::Status result =
1669  FindCores(assumptions, assumption_weights, stratification_threshold_,
1670  model_, &cores);
1671  if (result == SatSolver::INFEASIBLE) return SatSolver::INFEASIBLE;
1672  if (result == SatSolver::FEASIBLE) {
1673  if (!ProcessSolution()) return SatSolver::INFEASIBLE;
1674  if (stop_) return SatSolver::LIMIT_REACHED;
1675  if (cores.empty()) {
1676  ComputeNextStratificationThreshold();
1677  if (stratification_threshold_ == 0) return SatSolver::INFEASIBLE;
1678  continue;
1679  }
1680  }
1681 
1682  // Process the cores by creating new variables and transferring the minimum
1683  // weight of each core to it.
1684  if (!sat_solver_->ResetToLevelZero()) return SatSolver::INFEASIBLE;
1685  for (const std::vector<Literal>& core : cores) {
1686  // This just increase the lower-bound of the corresponding node, which
1687  // should already be done by the solver.
1688  if (core.size() == 1) continue;
1689 
1690  // Compute the min weight of all the terms in the core. The lower bound
1691  // will be increased by that much because at least one assumption in the
1692  // core must be true. This is also why we can start at 1 for new_var_lb.
1693  bool ignore_this_core = false;
1694  IntegerValue min_weight = kMaxIntegerValue;
1695  IntegerValue max_weight(0);
1696  IntegerValue new_var_lb(1);
1697  IntegerValue new_var_ub(0);
1698  int new_depth = 0;
1699  for (const Literal lit : core) {
1700  const int index = gtl::FindOrDie(literal_to_term_index, lit.Index());
1701 
1702  // When this happen, the core is now trivially "minimized" by the new
1703  // bound on this variable, so there is no point in adding it.
1704  if (terms_[index].old_var_lb <
1705  integer_trail_->LowerBound(terms_[index].var)) {
1706  ignore_this_core = true;
1707  break;
1708  }
1709 
1710  const IntegerValue weight = terms_[index].weight;
1711  min_weight = std::min(min_weight, weight);
1712  max_weight = std::max(max_weight, weight);
1713  new_depth = std::max(new_depth, terms_[index].depth + 1);
1714  new_var_lb += integer_trail_->LowerBound(terms_[index].var);
1715  new_var_ub += integer_trail_->UpperBound(terms_[index].var);
1716  }
1717  if (ignore_this_core) continue;
1718 
1719  VLOG(1) << absl::StrFormat(
1720  "core:%u weight:[%d,%d] domain:[%d,%d] depth:%d", core.size(),
1721  min_weight.value(), max_weight.value(), new_var_lb.value(),
1722  new_var_ub.value(), new_depth);
1723 
1724  // We will "transfer" min_weight from all the variables of the core
1725  // to a new variable.
1726  const IntegerVariable new_var =
1727  integer_trail_->AddIntegerVariable(new_var_lb, new_var_ub);
1728  terms_.push_back({new_var, min_weight, new_depth});
1729  terms_.back().cover_ub = new_var_ub;
1730 
1731  // Sum variables in the core <= new_var.
1732  {
1733  std::vector<IntegerVariable> constraint_vars;
1734  std::vector<int64_t> constraint_coeffs;
1735  for (const Literal lit : core) {
1736  const int index = gtl::FindOrDie(literal_to_term_index, lit.Index());
1737  terms_[index].weight -= min_weight;
1738  constraint_vars.push_back(terms_[index].var);
1739  constraint_coeffs.push_back(1);
1740  }
1741  constraint_vars.push_back(new_var);
1742  constraint_coeffs.push_back(-1);
1743  model_->Add(
1744  WeightedSumLowerOrEqual(constraint_vars, constraint_coeffs, 0));
1745  }
1746  }
1747 
1748  // Abort if we reached the time limit. Note that we still add any cores we
1749  // found in case the solve is splitted in "chunk".
1750  if (result == SatSolver::LIMIT_REACHED) return result;
1751  }
1752 }
1753 
1754 // TODO(user): take the MPModelRequest or MPModelProto directly, so that we can
1755 // have initial constraints!
1756 //
1757 // TODO(user): remove code duplication with MinimizeWithCoreAndLazyEncoding();
1759  const ObjectiveDefinition& objective_definition,
1760  const std::function<void()>& feasible_solution_observer, Model* model) {
1761 #if !defined(__PORTABLE_PLATFORM__) && defined(USE_SCIP)
1762 
1763  IntegerVariable objective_var = objective_definition.objective_var;
1764  std::vector<IntegerVariable> variables = objective_definition.vars;
1765  std::vector<IntegerValue> coefficients = objective_definition.coeffs;
1766 
1767  SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1768  IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
1769  IntegerEncoder* integer_encoder = model->GetOrCreate<IntegerEncoder>();
1770 
1771  // This will be called each time a feasible solution is found.
1772  const auto process_solution = [&]() {
1773  // We don't assume that objective_var is linked with its linear term, so
1774  // we recompute the objective here.
1775  IntegerValue objective(0);
1776  for (int i = 0; i < variables.size(); ++i) {
1777  objective +=
1778  coefficients[i] * IntegerValue(model->Get(Value(variables[i])));
1779  }
1780  if (objective > integer_trail->UpperBound(objective_var)) return true;
1781 
1782  if (feasible_solution_observer != nullptr) {
1783  feasible_solution_observer();
1784  }
1785 
1786  // Constrain objective_var. This has a better result when objective_var is
1787  // used in an LP relaxation for instance.
1788  sat_solver->Backtrack(0);
1789  sat_solver->SetAssumptionLevel(0);
1790  if (!integer_trail->Enqueue(
1791  IntegerLiteral::LowerOrEqual(objective_var, objective - 1), {},
1792  {})) {
1793  return false;
1794  }
1795  return true;
1796  };
1797 
1798  // This is the "generalized" hitting set problem we will solve. Each time
1799  // we find a core, a new constraint will be added to this problem.
1800  MPModelRequest request;
1801  request.set_solver_specific_parameters("limits/gap = 0");
1802  request.set_solver_type(MPModelRequest::SCIP_MIXED_INTEGER_PROGRAMMING);
1803 
1804  MPModelProto& hs_model = *request.mutable_model();
1805  const int num_variables_in_objective = variables.size();
1806  for (int i = 0; i < num_variables_in_objective; ++i) {
1807  if (coefficients[i] < 0) {
1808  variables[i] = NegationOf(variables[i]);
1809  coefficients[i] = -coefficients[i];
1810  }
1811  const IntegerVariable var = variables[i];
1812  MPVariableProto* var_proto = hs_model.add_variable();
1813  var_proto->set_lower_bound(integer_trail->LowerBound(var).value());
1814  var_proto->set_upper_bound(integer_trail->UpperBound(var).value());
1815  var_proto->set_objective_coefficient(coefficients[i].value());
1816  var_proto->set_is_integer(true);
1817  }
1818 
1819  MPSolutionResponse response;
1820 
1821  // This is used by the "stratified" approach. We will only consider terms with
1822  // a weight not lower than this threshold. The threshold will decrease as the
1823  // algorithm progress.
1824  IntegerValue stratified_threshold = kMaxIntegerValue;
1825 
1826  // TODO(user): The core is returned in the same order as the assumptions,
1827  // so we don't really need this map, we could just do a linear scan to
1828  // recover which node are part of the core.
1829  std::map<LiteralIndex, std::vector<int>> assumption_to_indices;
1830 
1831  // New Booleans variable in the MIP model to represent X >= cte.
1832  std::map<std::pair<int, double>, int> created_var;
1833 
1834  const SatParameters& parameters = *(model->GetOrCreate<SatParameters>());
1835 
1836  // Start the algorithm.
1837  SatSolver::Status result;
1838  for (int iter = 0;; ++iter) {
1839  // TODO(user): Even though we keep the same solver, currently the solve is
1840  // not really done incrementally. It might be hard to improve though.
1841  //
1842  // TODO(user): deal with time limit.
1845 
1846  const IntegerValue mip_objective(
1847  static_cast<int64_t>(std::round(response.objective_value())));
1848  VLOG(1) << "constraints: " << hs_model.constraint_size()
1849  << " variables: " << hs_model.variable_size() << " hs_lower_bound: "
1850  << objective_definition.ScaleIntegerObjective(mip_objective)
1851  << " strat: " << stratified_threshold;
1852 
1853  // Update the objective lower bound with our current bound.
1854  //
1855  // Note(user): This is not needed for correctness, but it might cause
1856  // more propagation and is nice to have for reporting/logging purpose.
1857  if (!integer_trail->Enqueue(
1858  IntegerLiteral::GreaterOrEqual(objective_var, mip_objective), {},
1859  {})) {
1860  result = SatSolver::INFEASIBLE;
1861  break;
1862  }
1863 
1864  sat_solver->Backtrack(0);
1865  sat_solver->SetAssumptionLevel(0);
1866  std::vector<Literal> assumptions;
1867  assumption_to_indices.clear();
1868  IntegerValue next_stratified_threshold(0);
1869  for (int i = 0; i < num_variables_in_objective; ++i) {
1870  const IntegerValue hs_value(
1871  static_cast<int64_t>(response.variable_value(i)));
1872  if (hs_value == integer_trail->UpperBound(variables[i])) continue;
1873 
1874  // Only consider the terms above the threshold.
1875  if (coefficients[i] < stratified_threshold) {
1876  next_stratified_threshold =
1877  std::max(next_stratified_threshold, coefficients[i]);
1878  } else {
1879  // It is possible that different variables have the same associated
1880  // literal. So we do need to consider this case.
1881  assumptions.push_back(integer_encoder->GetOrCreateAssociatedLiteral(
1882  IntegerLiteral::LowerOrEqual(variables[i], hs_value)));
1883  assumption_to_indices[assumptions.back().Index()].push_back(i);
1884  }
1885  }
1886 
1887  // No assumptions with the current stratified_threshold? use the new one.
1888  if (assumptions.empty() && next_stratified_threshold > 0) {
1889  CHECK_LT(next_stratified_threshold, stratified_threshold);
1890  stratified_threshold = next_stratified_threshold;
1891  --iter; // "false" iteration, the lower bound does not increase.
1892  continue;
1893  }
1894 
1895  // TODO(user): we could also randomly shuffle the assumptions to find more
1896  // cores for only one MIP solve.
1897  //
1898  // TODO(user): Use the real weights and exploit the extra cores.
1899  std::vector<std::vector<Literal>> cores;
1900  result = FindMultipleCoresForMaxHs(assumptions, model, &cores);
1901  if (result == SatSolver::FEASIBLE) {
1902  if (!process_solution()) return SatSolver::INFEASIBLE;
1903  if (parameters.stop_after_first_solution()) {
1904  return SatSolver::LIMIT_REACHED;
1905  }
1906  if (cores.empty()) {
1907  // If not all assumptions were taken, continue with a lower stratified
1908  // bound. Otherwise we have an optimal solution.
1909  stratified_threshold = next_stratified_threshold;
1910  if (stratified_threshold == 0) break;
1911  --iter; // "false" iteration, the lower bound does not increase.
1912  continue;
1913  }
1914  } else if (result != SatSolver::ASSUMPTIONS_UNSAT) {
1915  break;
1916  }
1917 
1918  sat_solver->Backtrack(0);
1919  sat_solver->SetAssumptionLevel(0);
1920  for (const std::vector<Literal>& core : cores) {
1921  if (core.size() == 1) {
1922  for (const int index :
1923  gtl::FindOrDie(assumption_to_indices, core.front().Index())) {
1924  hs_model.mutable_variable(index)->set_lower_bound(
1925  integer_trail->LowerBound(variables[index]).value());
1926  }
1927  continue;
1928  }
1929 
1930  // Add the corresponding constraint to hs_model.
1931  MPConstraintProto* ct = hs_model.add_constraint();
1932  ct->set_lower_bound(1.0);
1933  for (const Literal lit : core) {
1934  for (const int index :
1935  gtl::FindOrDie(assumption_to_indices, lit.Index())) {
1936  const double lb = integer_trail->LowerBound(variables[index]).value();
1937  const double hs_value = response.variable_value(index);
1938  if (hs_value == lb) {
1939  ct->add_var_index(index);
1940  ct->add_coefficient(1.0);
1941  ct->set_lower_bound(ct->lower_bound() + lb);
1942  } else {
1943  const std::pair<int, double> key = {index, hs_value};
1944  if (!gtl::ContainsKey(created_var, key)) {
1945  const int new_var_index = hs_model.variable_size();
1946  created_var[key] = new_var_index;
1947 
1948  MPVariableProto* new_var = hs_model.add_variable();
1949  new_var->set_lower_bound(0);
1950  new_var->set_upper_bound(1);
1951  new_var->set_is_integer(true);
1952 
1953  // (new_var == 1) => x > hs_value.
1954  // (x - lb) - (hs_value - lb + 1) * new_var >= 0.
1955  MPConstraintProto* implication = hs_model.add_constraint();
1956  implication->set_lower_bound(lb);
1957  implication->add_var_index(index);
1958  implication->add_coefficient(1.0);
1959  implication->add_var_index(new_var_index);
1960  implication->add_coefficient(lb - hs_value - 1);
1961  }
1962  ct->add_var_index(gtl::FindOrDieNoPrint(created_var, key));
1963  ct->add_coefficient(1.0);
1964  }
1965  }
1966  }
1967  }
1968  }
1969 
1970  return result;
1971 #else // !__PORTABLE_PLATFORM__ && USE_SCIP
1972  LOG(FATAL) << "Not supported.";
1973 #endif // !__PORTABLE_PLATFORM__ && USE_SCIP
1974 }
1975 
1976 } // namespace sat
1977 } // namespace operations_research
int64_t max
Definition: alldiff_cst.cc:140
int64_t min
Definition: alldiff_cst.cc:139
#define CHECK(condition)
Definition: base/logging.h:498
#define CHECK_LT(val1, val2)
Definition: base/logging.h:708
#define CHECK_EQ(val1, val2)
Definition: base/logging.h:705
#define CHECK_GE(val1, val2)
Definition: base/logging.h:709
#define CHECK_GT(val1, val2)
Definition: base/logging.h:710
#define CHECK_NE(val1, val2)
Definition: base/logging.h:706
#define LOG(severity)
Definition: base/logging.h:423
#define DCHECK(condition)
Definition: base/logging.h:892
#define CHECK_LE(val1, val2)
Definition: base/logging.h:707
#define VLOG(verboselevel)
Definition: base/logging.h:986
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response)
Solves the model encoded by a MPModelRequest protocol buffer and fills the solution encoded as a MPSo...
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
Definition: time_limit.h:105
bool LimitReached()
Returns true when the external limit is true, or the deterministic time is over the deterministic lim...
Definition: time_limit.h:532
double GetElapsedDeterministicTime() const
Returns the elapsed deterministic time since the construction of this object.
Definition: time_limit.h:260
CoreBasedOptimizer(IntegerVariable objective_var, const std::vector< IntegerVariable > &variables, const std::vector< IntegerValue > &coefficients, std::function< void()> feasible_solution_observer, Model *model)
Literal literal(int i) const
Definition: encoding.h:79
Literal GetOrCreateAssociatedLiteral(IntegerLiteral i_lit)
Definition: integer.cc:204
ABSL_MUST_USE_RESULT bool Enqueue(IntegerLiteral i_lit, absl::Span< const Literal > literal_reason, absl::Span< const IntegerLiteral > integer_reason)
Definition: integer.cc:993
bool IsCurrentlyIgnored(IntegerVariable i) const
Definition: integer.h:630
IntegerValue UpperBound(IntegerVariable i) const
Definition: integer.h:1309
IntegerValue LevelZeroUpperBound(IntegerVariable var) const
Definition: integer.h:1360
IntegerVariable AddIntegerVariable(IntegerValue lower_bound, IntegerValue upper_bound)
Definition: integer.cc:605
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
Definition: integer.h:1355
IntegerValue LowerBound(IntegerVariable i) const
Definition: integer.h:1305
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
T Add(std::function< T(Model *)> f)
This makes it possible to have a nicer API on the client side, and it allows both of these forms:
Definition: sat/model.h:81
bool AddLinearConstraint(bool use_lower_bound, Coefficient lower_bound, bool use_upper_bound, Coefficient upper_bound, std::vector< LiteralWithCoeff > *cst)
Definition: sat_solver.cc:300
void SetNumVariables(int num_variables)
Definition: sat_solver.cc:65
bool AddTernaryClause(Literal a, Literal b, Literal c)
Definition: sat_solver.cc:192
const SatParameters & parameters() const
Definition: sat_solver.cc:111
Status ResetAndSolveWithGivenAssumptions(const std::vector< Literal > &assumptions)
Definition: sat_solver.cc:948
void SetAssumptionLevel(int assumption_level)
Definition: sat_solver.cc:963
const VariablesAssignment & Assignment() const
Definition: sat_solver.h:363
int EnqueueDecisionAndBackjumpOnConflict(Literal true_literal)
Definition: sat_solver.cc:500
void SetParameters(const SatParameters &parameters)
Definition: sat_solver.cc:116
bool AddBinaryClause(Literal a, Literal b)
Definition: sat_solver.cc:181
int EnqueueDecisionAndBacktrackOnConflict(Literal true_literal)
Definition: sat_solver.cc:862
void Backtrack(int target_level)
Definition: sat_solver.cc:889
std::vector< Literal > GetLastIncompatibleDecisions()
Definition: sat_solver.cc:1273
bool AddProblemClause(absl::Span< const Literal > literals)
Definition: sat_solver.cc:204
bool AddUnitClause(Literal true_literal)
Definition: sat_solver.cc:165
bool LiteralIsTrue(Literal literal) const
Definition: sat_base.h:151
bool LiteralIsFalse(Literal literal) const
Definition: sat_base.h:148
int64_t b
int64_t a
SatParameters parameters
SharedResponseManager * response
SharedTimeLimit * time_limit
const Constraint * ct
int64_t value
IntVar * var
Definition: expr_array.cc:1874
double upper_bound
double lower_bound
absl::Span< const double > coefficients
GRBmodel * model
A C++ wrapper that provides a simple and unified interface to several linear programming and mixed in...
const int INFO
Definition: log_severity.h:31
const int FATAL
Definition: log_severity.h:32
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: macros.h:29
absl::Cleanup< absl::decay_t< Callback > > MakeCleanup(Callback &&callback)
Definition: cleanup.h:120
void STLSortAndRemoveDuplicates(T *v, const LessFunc &less_func)
Definition: stl_util.h:58
bool ContainsKey(const Collection &collection, const Key &key)
Definition: map_util.h:200
const Collection::value_type::second_type & FindOrDie(const Collection &collection, const typename Collection::value_type::first_type &key)
Definition: map_util.h:206
const Collection::value_type::second_type & FindOrDieNoPrint(const Collection &collection, const typename Collection::value_type::first_type &key)
Definition: map_util.h:216
void swap(IdMap< K, V > &a, IdMap< K, V > &b)
Definition: id_map.h:263
bool AddObjectiveConstraint(const LinearBooleanProblem &problem, bool use_lower_bound, Coefficient lower_bound, bool use_upper_bound, Coefficient upper_bound, SatSolver *solver)
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
void RestrictObjectiveDomainWithBinarySearch(IntegerVariable objective_var, const std::function< void()> &feasible_solution_observer, Model *model)
double AddOffsetAndScaleObjectiveValue(const LinearBooleanProblem &problem, Coefficient v)
SatSolver::Status ResetAndSolveIntegerProblem(const std::vector< Literal > &assumptions, Model *model)
SatSolver::Status SolveWithCardinalityEncodingAndCore(LogBehavior log, const LinearBooleanProblem &problem, SatSolver *solver, std::vector< bool > *solution)
Coefficient ComputeCoreMinWeight(const std::vector< EncodingNode * > &nodes, const std::vector< Literal > &core)
Definition: encoding.cc:419
EncodingNode * MergeAllNodesWithDeque(Coefficient upper_bound, const std::vector< EncodingNode * > &nodes, SatSolver *solver, std::deque< EncodingNode > *repository)
Definition: encoding.cc:264
int MoveOneUnprocessedLiteralLast(const std::set< LiteralIndex > &processed, int relevant_prefix_size, std::vector< Literal > *literals)
Definition: sat/util.cc:25
std::function< int64_t(const Model &)> Value(IntegerVariable v)
Definition: integer.h:1492
std::vector< Literal > ReduceNodesAndExtractAssumptions(Coefficient upper_bound, Coefficient stratified_lower_bound, Coefficient *lower_bound, std::vector< EncodingNode * > *nodes, SatSolver *solver)
Definition: encoding.cc:367
void UseObjectiveForSatAssignmentPreference(const LinearBooleanProblem &problem, SatSolver *solver)
SatSolver::Status SolveWithLinearScan(LogBehavior log, const LinearBooleanProblem &problem, SatSolver *solver, std::vector< bool > *solution)
void MinimizeCore(SatSolver *solver, std::vector< Literal > *core)
Definition: sat_solver.cc:2548
SatSolver::Status MinimizeWithHittingSetAndLazyEncoding(const ObjectiveDefinition &objective_definition, const std::function< void()> &feasible_solution_observer, Model *model)
SatSolver::Status SolveIntegerProblem(Model *model)
std::function< void(Model *)> WeightedSumLowerOrEqual(const std::vector< IntegerVariable > &vars, const VectorInt &coefficients, int64_t upper_bound)
Definition: integer_expr.h:300
SatSolver::Status SolveWithWPM1(LogBehavior log, const LinearBooleanProblem &problem, SatSolver *solver, std::vector< bool > *solution)
bool IsAssignmentValid(const LinearBooleanProblem &problem, const std::vector< bool > &assignment)
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Definition: integer.cc:29
void MinimizeCoreWithPropagation(TimeLimit *limit, SatSolver *solver, std::vector< Literal > *core)
void ProcessCore(const std::vector< Literal > &core, Coefficient min_weight, std::deque< EncodingNode > *repository, std::vector< EncodingNode * > *nodes, SatSolver *solver)
Definition: encoding.cc:446
Coefficient ComputeObjectiveValue(const LinearBooleanProblem &problem, const std::vector< bool > &assignment)
SatSolver::Status SolveWithFuMalik(LogBehavior log, const LinearBooleanProblem &problem, SatSolver *solver, std::vector< bool > *solution)
Coefficient MaxNodeWeightSmallerThan(const std::vector< EncodingNode * > &nodes, Coefficient upper_bound)
Definition: encoding.cc:434
SatSolver::Status SolveWithRandomParameters(LogBehavior log, const LinearBooleanProblem &problem, int num_times, SatSolver *solver, std::vector< bool > *solution)
std::function< int64_t(const Model &)> LowerBound(IntegerVariable v)
Definition: integer.h:1472
SatSolver::Status SolveWithCardinalityEncoding(LogBehavior log, const LinearBooleanProblem &problem, SatSolver *solver, std::vector< bool > *solution)
void ExtractAssignment(const LinearBooleanProblem &problem, const SatSolver &solver, std::vector< bool > *assignment)
std::vector< EncodingNode * > CreateInitialEncodingNodes(const std::vector< Literal > &literals, const std::vector< Coefficient > &coeffs, Coefficient *offset, std::deque< EncodingNode > *repository)
Definition: encoding.cc:303
void RandomizeDecisionHeuristic(URBG *random, SatParameters *parameters)
Definition: sat/util.h:101
const Coefficient kCoefficientMax(std::numeric_limits< Coefficient::ValueType >::max())
SatSolver::Status MinimizeIntegerVariableWithLinearScanAndLazyEncoding(IntegerVariable objective_var, const std::function< void()> &feasible_solution_observer, Model *model)
Collection of objects used to extend the Constraint Solver library.
std::string ProtobufShortDebugString(const P &message)
int core_index
Definition: optimization.cc:86
Literal literal
Definition: optimization.cc:85
int64_t weight
Definition: pack.cc:510
int index
Definition: pack.cc:509
int64_t cost
int nodes
static IntegerLiteral LowerOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1275
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
Definition: integer.h:1269
double ScaleIntegerObjective(IntegerValue value) const
std::string message
Definition: trace.cc:398
#define VLOG_IS_ON(verboselevel)
Definition: vlog_is_on.h:41