OR-Tools  9.2
sat_solver.h
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
14// This file implements a SAT solver.
15// see http://en.wikipedia.org/wiki/Boolean_satisfiability_problem
16// for more detail.
17// TODO(user): Expand.
18
19#ifndef OR_TOOLS_SAT_SAT_SOLVER_H_
20#define OR_TOOLS_SAT_SAT_SOLVER_H_
21
22#include <cstdint>
23#include <functional>
24#include <limits>
25#include <memory>
26#include <string>
27#include <utility>
28#include <vector>
29
30#include "absl/container/flat_hash_map.h"
31#include "absl/types/span.h"
32#include "ortools/base/hash.h"
36#include "ortools/base/macros.h"
37#include "ortools/base/timer.h"
38#include "ortools/sat/clause.h"
40#include "ortools/sat/model.h"
42#include "ortools/sat/restart.h"
46#include "ortools/util/stats.h"
48
49namespace operations_research {
50namespace sat {
51
52// A constant used by the EnqueueDecision*() API.
53const int kUnsatTrailIndex = -1;
54
55// The main SAT solver.
56// It currently implements the CDCL algorithm. See
57// http://en.wikipedia.org/wiki/Conflict_Driven_Clause_Learning
58class SatSolver {
59 public:
60 SatSolver();
61 explicit SatSolver(Model* model);
62 ~SatSolver();
63
64 // TODO(user): Remove. This is temporary for accessing the model deep within
65 // some old code that didn't use the Model object.
66 Model* model() { return model_; }
67
68 // Parameters management. Note that calling SetParameters() will reset the
69 // value of many heuristics. For instance:
70 // - The restart strategy will be reinitialized.
71 // - The random seed and random generator will be reset to the value given in
72 // parameters.
73 // - The global TimeLimit singleton will be reset and time will be
74 // counted from this call.
76 const SatParameters& parameters() const;
77
78 // Increases the number of variables of the current problem.
79 //
80 // TODO(user): Rename to IncreaseNumVariablesTo() until we support removing
81 // variables...
82 void SetNumVariables(int num_variables);
83 int NumVariables() const { return num_variables_.value(); }
84 BooleanVariable NewBooleanVariable() {
85 const int num_vars = NumVariables();
86
87 // We need to be able to encode the variable as a literal.
89 SetNumVariables(num_vars + 1);
90 return BooleanVariable(num_vars);
91 }
92
93 // Fixes a variable so that the given literal is true. This can be used to
94 // solve a subproblem where some variables are fixed. Note that it is more
95 // efficient to add such unit clause before all the others.
96 // Returns false if the problem is detected to be UNSAT.
97 bool AddUnitClause(Literal true_literal);
98
99 // Same as AddProblemClause() below, but for small clauses.
100 //
101 // TODO(user): Remove this and AddUnitClause() when initializer lists can be
102 // used in the open-source code like in AddClause({a, b}).
105
106 // Adds a clause to the problem. Returns false if the problem is detected to
107 // be UNSAT.
108 //
109 // TODO(user): Rename this to AddClause().
110 bool AddProblemClause(absl::Span<const Literal> literals);
111
112 // Adds a pseudo-Boolean constraint to the problem. Returns false if the
113 // problem is detected to be UNSAT. If the constraint is always true, this
114 // detects it and does nothing.
115 //
116 // Note(user): There is an optimization if the same constraint is added
117 // consecutively (even if the bounds are different). This is particularly
118 // useful for an optimization problem when we want to constrain the objective
119 // of the problem more and more. Just re-adding such constraint is relatively
120 // efficient.
121 //
122 // OVERFLOW: The sum of the absolute value of all the coefficients
123 // in the constraint must not overflow. This is currently CHECKed().
124 // TODO(user): Instead of failing, implement an error handling code.
125 bool AddLinearConstraint(bool use_lower_bound, Coefficient lower_bound,
126 bool use_upper_bound, Coefficient upper_bound,
127 std::vector<LiteralWithCoeff>* cst);
128
129 // Returns true if the model is UNSAT. Note that currently the status is
130 // "sticky" and once this happen, nothing else can be done with the solver.
131 //
132 // Thanks to this function, a client can safely ignore the return value of any
133 // Add*() functions. If one of them return false, then IsModelUnsat() will
134 // return true.
135 //
136 // TODO(user): Rename to ModelIsUnsat().
137 bool IsModelUnsat() const { return model_is_unsat_; }
138
139 // Adds and registers the given propagator with the sat solver. Note that
140 // during propagation, they will be called in the order they were added.
141 void AddPropagator(SatPropagator* propagator);
142 void AddLastPropagator(SatPropagator* propagator);
143 void TakePropagatorOwnership(std::unique_ptr<SatPropagator> propagator) {
144 owned_propagators_.push_back(std::move(propagator));
145 }
146
147 // Wrapper around the same functions in SatDecisionPolicy.
148 //
149 // TODO(user): Clean this up by making clients directly talk to
150 // SatDecisionPolicy.
152 decision_policy_->SetAssignmentPreference(literal, weight);
153 }
154 std::vector<std::pair<Literal, double>> AllPreferences() const {
155 return decision_policy_->AllPreferences();
156 }
158 return decision_policy_->ResetDecisionHeuristic();
159 }
161 const std::vector<std::pair<Literal, double>>& prefs) {
162 decision_policy_->ResetDecisionHeuristic();
163 for (const std::pair<Literal, double> p : prefs) {
164 decision_policy_->SetAssignmentPreference(p.first, p.second);
165 }
166 }
167
168 // Solves the problem and returns its status.
169 // An empty problem is considered to be SAT.
170 //
171 // Note that the conflict limit applies only to this function and starts
172 // counting from the time it is called.
173 //
174 // This will restart from the current solver configuration. If a previous call
175 // to Solve() was interrupted by a conflict or time limit, calling this again
176 // will resume the search exactly as it would have continued.
177 //
178 // Note that this will use the TimeLimit singleton, so the time limit
179 // will be counted since the last time TimeLimit was reset, not from
180 // the start of this function.
181 enum Status {
186 };
187 Status Solve();
188
189 // Same as Solve(), but with a given time limit. Note that this will not
190 // update the TimeLimit singleton, but only the passed object instead.
192
193 // Simple interface to solve a problem under the given assumptions. This
194 // simply ask the solver to solve a problem given a set of variables fixed to
195 // a given value (the assumptions). Compared to simply calling AddUnitClause()
196 // and fixing the variables once and for all, this allow to backtrack over the
197 // assumptions and thus exploit the incrementally between subsequent solves.
198 //
199 // This function backtrack over all the current decision, tries to enqueue the
200 // given assumptions, sets the assumption level accordingly and finally calls
201 // Solve().
202 //
203 // If, given these assumptions, the model is UNSAT, this returns the
204 // ASSUMPTIONS_UNSAT status. INFEASIBLE is reserved for the case where the
205 // model is proven to be unsat without any assumptions.
206 //
207 // If ASSUMPTIONS_UNSAT is returned, it is possible to get a "core" of unsat
208 // assumptions by calling GetLastIncompatibleDecisions().
210 const std::vector<Literal>& assumptions);
211
212 // Changes the assumption level. All the decisions below this level will be
213 // treated as assumptions by the next Solve(). Note that this may impact some
214 // heuristics, like the LBD value of a clause.
215 void SetAssumptionLevel(int assumption_level);
216
217 // Returns the current assumption level. Note that if a solve was done since
218 // the last SetAssumptionLevel(), then the returned level may be lower than
219 // the one that was set. This is because some assumptions may now be
220 // consequences of others before them due to the newly learned clauses.
221 int AssumptionLevel() const { return assumption_level_; }
222
223 // This can be called just after SolveWithAssumptions() returned
224 // ASSUMPTION_UNSAT or after EnqueueDecisionAndBacktrackOnConflict() leaded
225 // to a conflict. It returns a subsequence (in the correct order) of the
226 // previously enqueued decisions that cannot be taken together without making
227 // the problem UNSAT.
228 std::vector<Literal> GetLastIncompatibleDecisions();
229
230 // Advanced usage. The next 3 functions allow to drive the search from outside
231 // the solver.
232
233 // Takes a new decision (the given true_literal must be unassigned) and
234 // propagates it. Returns the trail index of the first newly propagated
235 // literal. If there is a conflict and the problem is detected to be UNSAT,
236 // returns kUnsatTrailIndex.
237 //
238 // A client can determine if there is a conflict by checking if the
239 // CurrentDecisionLevel() was increased by 1 or not.
240 //
241 // If there is a conflict, the given decision is not applied and:
242 // - The conflict is learned.
243 // - The decisions are potentially backtracked to the first decision that
244 // propagates more variables because of the newly learned conflict.
245 // - The returned value is equal to trail_->Index() after this backtracking
246 // and just before the new propagation (due to the conflict) which is also
247 // performed by this function.
249
250 // This function starts by calling EnqueueDecisionAndBackjumpOnConflict(). If
251 // there is no conflict, it stops there. Otherwise, it tries to reapply all
252 // the decisions that were backjumped over until the first one that can't be
253 // taken because it is incompatible. Note that during this process, more
254 // conflicts may happen and the trail may be backtracked even further.
255 //
256 // In any case, the new decisions stack will be the largest valid "prefix"
257 // of the old stack. Note that decisions that are now consequence of the ones
258 // before them will no longer be decisions.
259 //
260 // Note(user): This function can be called with an already assigned literal.
262
263 // Tries to enqueue the given decision and performs the propagation.
264 // Returns true if no conflict occurred. Otherwise, returns false and restores
265 // the solver to the state just before this was called.
266 //
267 // Note(user): With this function, the solver doesn't learn anything.
268 bool EnqueueDecisionIfNotConflicting(Literal true_literal);
269
270 // Restores the state to the given target decision level. The decision at that
271 // level and all its propagation will not be undone. But all the trail after
272 // this will be cleared. Calling this with 0 will revert all the decisions and
273 // only the fixed variables will be left on the trail.
274 void Backtrack(int target_level);
275
276 // Advanced usage. This is meant to restore the solver to a "proper" state
277 // after a solve was interupted due to a limit reached.
278 //
279 // Without assumption (i.e. if AssumptionLevel() is 0), this will revert all
280 // decisions and make sure that all the fixed literals are propagated. In
281 // presence of assumptions, this will either backtrack to the assumption level
282 // or re-enqueue any assumptions that may have been backtracked over due to
283 // conflits resolution. In both cases, the propagation is finished.
284 //
285 // Note that this may prove the model to be UNSAT or ASSUMPTION_UNSAT in which
286 // case it will return false.
288
289 // Advanced usage. Finish the progation if it was interupted. Note that this
290 // might run into conflict and will propagate again until a fixed point is
291 // reached or the model was proven UNSAT. Returns IsModelUnsat().
292 bool FinishPropagation();
293
294 // Like Backtrack(0) but make sure the propagation is finished and return
295 // false if unsat was detected. This also removes any assumptions level.
296 bool ResetToLevelZero();
297
298 // Changes the assumptions level and the current solver assumptions. Returns
299 // false if the model is UNSAT or ASSUMPTION_UNSAT, true otherwise.
300 bool ResetWithGivenAssumptions(const std::vector<Literal>& assumptions);
301
302 // Advanced usage. If the decision level is smaller than the assumption level,
303 // this will try to reapply all assumptions. Returns true if this was doable,
304 // otherwise returns false in which case the model is either UNSAT or
305 // ASSUMPTION_UNSAT.
307
308 // Helper functions to get the correct status when one of the functions above
309 // returns false.
312 }
313
314 // Extract the current problem clauses. The Output type must support the two
315 // functions:
316 // - void AddBinaryClause(Literal a, Literal b);
317 // - void AddClause(absl::Span<const Literal> clause);
318 //
319 // TODO(user): also copy the removable clauses?
320 template <typename Output>
321 void ExtractClauses(Output* out) {
323 Backtrack(0);
324 if (!FinishPropagation()) return;
325
326 // It is important to process the newly fixed variables, so they are not
327 // present in the clauses we export.
328 if (num_processed_fixed_variables_ < trail_->Index()) {
330 }
331 clauses_propagator_->DeleteRemovedClauses();
332
333 // Note(user): Putting the binary clauses first help because the presolver
334 // currently process the clauses in order.
335 out->SetNumVariables(NumVariables());
336 binary_implication_graph_->ExtractAllBinaryClauses(out);
337 for (SatClause* clause : clauses_propagator_->AllClausesInCreationOrder()) {
338 if (!clauses_propagator_->IsRemovable(clause)) {
339 out->AddClause(clause->AsSpan());
340 }
341 }
342 }
343
344 // Functions to manage the set of learned binary clauses.
345 // Only clauses added/learned when TrackBinaryClause() is true are managed.
346 void TrackBinaryClauses(bool value) { track_binary_clauses_ = value; }
347 bool AddBinaryClauses(const std::vector<BinaryClause>& clauses);
348 const std::vector<BinaryClause>& NewlyAddedBinaryClauses();
350
351 struct Decision {
353 Decision(int i, Literal l) : trail_index(i), literal(l) {}
354 int trail_index = 0;
356 };
357
358 // Note that the Decisions() vector is always of size NumVariables(), and that
359 // only the first CurrentDecisionLevel() entries have a meaning.
360 const std::vector<Decision>& Decisions() const { return decisions_; }
361 int CurrentDecisionLevel() const { return current_decision_level_; }
362 const Trail& LiteralTrail() const { return *trail_; }
363 const VariablesAssignment& Assignment() const { return trail_->Assignment(); }
364
365 // Some statistics since the creation of the solver.
366 int64_t num_branches() const;
367 int64_t num_failures() const;
368 int64_t num_propagations() const;
369
370 // Note that we count the number of backtrack to level zero from a positive
371 // level. Those can corresponds to actual restarts, or conflicts that learn
372 // unit clauses or any other reason that trigger such backtrack.
373 int64_t num_restarts() const;
374
375 // A deterministic number that should be correlated with the time spent in
376 // the Solve() function. The order of magnitude should be close to the time
377 // in seconds.
378 double deterministic_time() const;
379
380 // Only used for debugging. Save the current assignment in debug_assignment_.
381 // The idea is that if we know that a given assignment is satisfiable, then
382 // all the learned clauses or PB constraints must be satisfiable by it. In
383 // debug mode, and after this is called, all the learned clauses are tested to
384 // satisfy this saved assignement.
385 void SaveDebugAssignment();
386
387 // Returns true iff the loaded problem only contains clauses.
388 bool ProblemIsPureSat() const { return problem_is_pure_sat_; }
389
390 void SetDratProofHandler(DratProofHandler* drat_proof_handler) {
391 drat_proof_handler_ = drat_proof_handler;
392 clauses_propagator_->SetDratProofHandler(drat_proof_handler_);
393 binary_implication_graph_->SetDratProofHandler(drat_proof_handler_);
394 }
395
396 // This function is here to deal with the case where a SAT/CP model is found
397 // to be trivially UNSAT while the user is constructing the model. Instead of
398 // having to test the status of all the lines adding a constraint, one can
399 // just check if the solver is not UNSAT once the model is constructed. Note
400 // that we usually log a warning on the first constraint that caused a
401 // "trival" unsatisfiability.
402 void NotifyThatModelIsUnsat() { model_is_unsat_ = true; }
403
404 // Adds a clause at any level of the tree and propagate any new deductions.
405 // Returns false if the model becomes UNSAT. Important: We currently do not
406 // support adding a clause that is already falsified at a positive decision
407 // level. Doing that will cause a check fail.
408 //
409 // TODO(user): Backjump and propagate on a falsified clause? this is currently
410 // not needed.
411 bool AddClauseDuringSearch(absl::Span<const Literal> literals);
412
413 // Performs propagation of the recently enqueued elements.
414 // Mainly visible for testing.
415 bool Propagate();
416
417 // This must be called at level zero. It will spend the given num decision and
418 // use propagation to try to minimize some clauses from the database.
419 void MinimizeSomeClauses(int decisions_budget);
420
421 // Advance the given time limit with all the deterministic time that was
422 // elapsed since last call.
424 const double current = deterministic_time();
426 current - deterministic_time_at_last_advanced_time_limit_);
427 deterministic_time_at_last_advanced_time_limit_ = current;
428 }
429
430 // Simplifies the problem when new variables are assigned at level 0.
432
433 int64_t NumFixedVariables() const {
434 if (!decisions_.empty()) return decisions_[0].trail_index;
436 return trail_->Index();
437 }
438
439 private:
440 // Calls Propagate() and returns true if no conflict occurred. Otherwise,
441 // learns the conflict, backtracks, enqueues the consequence of the learned
442 // conflict and returns false.
443 bool PropagateAndStopAfterOneConflictResolution();
444
445 // All Solve() functions end up calling this one.
446 Status SolveInternal(TimeLimit* time_limit);
447
448 // Adds a binary clause to the BinaryImplicationGraph and to the
449 // BinaryClauseManager when track_binary_clauses_ is true.
450 void AddBinaryClauseInternal(Literal a, Literal b);
451
452 // See SaveDebugAssignment(). Note that these functions only consider the
453 // variables at the time the debug_assignment_ was saved. If new variables
454 // were added since that time, they will be considered unassigned.
455 bool ClauseIsValidUnderDebugAssignement(
456 const std::vector<Literal>& clause) const;
457 bool PBConstraintIsValidUnderDebugAssignment(
458 const std::vector<LiteralWithCoeff>& cst, const Coefficient rhs) const;
459
460 // Logs the given status if parameters_.log_search_progress() is true.
461 // Also returns it.
462 Status StatusWithLog(Status status);
463
464 // Main function called from SolveWithAssumptions() or from Solve() with an
465 // assumption_level of 0 (meaning no assumptions).
466 Status SolveInternal(int assumption_level);
467
468 // Applies the previous decisions (which are still on decisions_), in order,
469 // starting from the one at the current decision level. Stops at the one at
470 // decisions_[level] or on the first decision already propagated to "false"
471 // and thus incompatible.
472 //
473 // Note that during this process, conflicts may arise which will lead to
474 // backjumps. In this case, we will simply keep reapplying decisions from the
475 // last one backtracked over and so on.
476 //
477 // Returns FEASIBLE if no conflict occurred, INFEASIBLE if the model was
478 // proven unsat and ASSUMPTION_UNSAT otherwise. In the last case the first non
479 // taken old decision will be propagated to false by the ones before.
480 //
481 // first_propagation_index will be filled with the trail index of the first
482 // newly propagated literal, or with -1 if INFEASIBLE is returned.
483 Status ReapplyDecisionsUpTo(int level, int* first_propagation_index);
484
485 // Returns false if the thread memory is over the limit.
486 bool IsMemoryLimitReached() const;
487
488 // Sets model_is_unsat_ to true and return false.
489 bool SetModelUnsat();
490
491 // Returns the decision level of a given variable.
492 int DecisionLevel(BooleanVariable var) const {
493 return trail_->Info(var).level;
494 }
495
496 // Returns the relevant pointer if the given variable was propagated by the
497 // constraint in question. This is used to bump the activity of the learned
498 // clauses or pb constraints.
499 SatClause* ReasonClauseOrNull(BooleanVariable var) const;
500 UpperBoundedLinearConstraint* ReasonPbConstraintOrNull(
501 BooleanVariable var) const;
502
503 // This does one step of a pseudo-Boolean resolution:
504 // - The variable var has been assigned to l at a given trail_index.
505 // - The reason for var propagates it to l.
506 // - The conflict propagates it to not(l)
507 // The goal of the operation is to combine the two constraints in order to
508 // have a new conflict at a lower trail_index.
509 //
510 // Returns true if the reason for var was a normal clause. In this case,
511 // the *slack is updated to its new value.
512 bool ResolvePBConflict(BooleanVariable var,
513 MutableUpperBoundedLinearConstraint* conflict,
514 Coefficient* slack);
515
516 // Returns true iff the clause is the reason for an assigned variable.
517 //
518 // TODO(user): With our current data structures, we could also return true
519 // for clauses that were just used as a reason (like just before an untrail).
520 // This may be beneficial, but should properly be defined so that we can
521 // have the same behavior if we change the implementation.
522 bool ClauseIsUsedAsReason(SatClause* clause) const {
523 const BooleanVariable var = clause->PropagatedLiteral().Variable();
524 return trail_->Info(var).trail_index < trail_->Index() &&
525 (*trail_)[trail_->Info(var).trail_index].Variable() == var &&
526 ReasonClauseOrNull(var) == clause;
527 }
528
529 // Add a problem clause. The clause is assumed to be "cleaned", that is no
530 // duplicate variables (not strictly required) and not empty.
531 bool AddProblemClauseInternal(absl::Span<const Literal> literals);
532
533 // This is used by all the Add*LinearConstraint() functions. It detects
534 // infeasible/trivial constraints or clause constraints and takes the proper
535 // action.
536 bool AddLinearConstraintInternal(const std::vector<LiteralWithCoeff>& cst,
537 Coefficient rhs, Coefficient max_value);
538
539 // Adds a learned clause to the problem. This should be called after
540 // Backtrack(). The backtrack is such that after it is applied, all the
541 // literals of the learned close except one will be false. Thus the last one
542 // will be implied True. This function also Enqueue() the implied literal.
543 //
544 // Returns the LBD of the clause.
545 int AddLearnedClauseAndEnqueueUnitPropagation(
546 const std::vector<Literal>& literals, bool is_redundant);
547
548 // Creates a new decision which corresponds to setting the given literal to
549 // True and Enqueue() this change.
550 void EnqueueNewDecision(Literal literal);
551
552 // Returns true if everything has been propagated.
553 //
554 // TODO(user): This test is fast but not exhaustive, especially regarding the
555 // integer propagators. Fix.
556 bool PropagationIsDone() const;
557
558 // Update the propagators_ list with the relevant propagators.
559 void InitializePropagators();
560
561 // Unrolls the trail until a given point. This unassign the assigned variables
562 // and add them to the priority queue with the correct weight.
563 void Untrail(int target_trail_index);
564
565 // Output to the DRAT proof handler any newly fixed variables.
566 void ProcessNewlyFixedVariablesForDratProof();
567
568 // Returns the maximum trail_index of the literals in the given clause.
569 // All the literals must be assigned. Returns -1 if the clause is empty.
570 int ComputeMaxTrailIndex(absl::Span<const Literal> clause) const;
571
572 // Computes what is known as the first UIP (Unique implication point) conflict
573 // clause starting from the failing clause. For a definition of UIP and a
574 // comparison of the different possible conflict clause computation, see the
575 // reference below.
576 //
577 // The conflict will have only one literal at the highest decision level, and
578 // this literal will always be the first in the conflict vector.
579 //
580 // L Zhang, CF Madigan, MH Moskewicz, S Malik, "Efficient conflict driven
581 // learning in a boolean satisfiability solver" Proceedings of the 2001
582 // IEEE/ACM international conference on Computer-aided design, Pages 279-285.
583 // http://www.cs.tau.ac.il/~msagiv/courses/ATP/iccad2001_final.pdf
584 void ComputeFirstUIPConflict(
585 int max_trail_index, std::vector<Literal>* conflict,
586 std::vector<Literal>* reason_used_to_infer_the_conflict,
587 std::vector<SatClause*>* subsumed_clauses);
588
589 // Fills literals with all the literals in the reasons of the literals in the
590 // given input. The output vector will have no duplicates and will not contain
591 // the literals already present in the input.
592 void ComputeUnionOfReasons(const std::vector<Literal>& input,
593 std::vector<Literal>* literals);
594
595 // Given an assumption (i.e. literal) currently assigned to false, this will
596 // returns the set of all assumptions that caused this particular assignment.
597 //
598 // This is useful to get a small set of assumptions that can't be all
599 // satisfied together.
600 void FillUnsatAssumptions(Literal false_assumption,
601 std::vector<Literal>* unsat_assumptions);
602
603 // Do the full pseudo-Boolean constraint analysis. This calls multiple
604 // time ResolvePBConflict() on the current conflict until we have a conflict
605 // that allow us to propagate more at a lower decision level. This level
606 // is the one returned in backjump_level.
607 void ComputePBConflict(int max_trail_index, Coefficient initial_slack,
608 MutableUpperBoundedLinearConstraint* conflict,
609 int* backjump_level);
610
611 // Applies some heuristics to a conflict in order to minimize its size and/or
612 // replace literals by other literals from lower decision levels. The first
613 // function choose which one of the other functions to call depending on the
614 // parameters.
615 //
616 // Precondidtion: is_marked_ should be set to true for all the variables of
617 // the conflict. It can also contains false non-conflict variables that
618 // are implied by the negation of the 1-UIP conflict literal.
619 void MinimizeConflict(
620 std::vector<Literal>* conflict,
621 std::vector<Literal>* reason_used_to_infer_the_conflict);
622 void MinimizeConflictExperimental(std::vector<Literal>* conflict);
623 void MinimizeConflictSimple(std::vector<Literal>* conflict);
624 void MinimizeConflictRecursively(std::vector<Literal>* conflict);
625
626 // Utility function used by MinimizeConflictRecursively().
627 bool CanBeInferedFromConflictVariables(BooleanVariable variable);
628
629 // To be used in DCHECK(). Verifies some property of the conflict clause:
630 // - There is an unique literal with the highest decision level.
631 // - This literal appears in the first position.
632 // - All the other literals are of smaller decision level.
633 // - Ther is no literal with a decision level of zero.
634 bool IsConflictValid(const std::vector<Literal>& literals);
635
636 // Given the learned clause after a conflict, this computes the correct
637 // backtrack level to call Backtrack() with.
638 int ComputeBacktrackLevel(const std::vector<Literal>& literals);
639
640 // The LBD (Literal Blocks Distance) is the number of different decision
641 // levels at which the literals of the clause were assigned. Note that we
642 // ignore the decision level 0 whereas the definition in the paper below
643 // doesn't:
644 //
645 // G. Audemard, L. Simon, "Predicting Learnt Clauses Quality in Modern SAT
646 // Solver" in Twenty-first International Joint Conference on Artificial
647 // Intelligence (IJCAI'09), july 2009.
648 // http://www.ijcai.org/papers09/Papers/IJCAI09-074.pdf
649 //
650 // IMPORTANT: All the literals of the clause must be assigned, and the first
651 // literal must be of the highest decision level. This will be the case for
652 // all the reason clauses.
653 template <typename LiteralList>
654 int ComputeLbd(const LiteralList& literals);
655
656 // Checks if we need to reduce the number of learned clauses and do
657 // it if needed. Also updates the learned clause limit for the next cleanup.
658 void CleanClauseDatabaseIfNeeded();
659
660 // Activity management for clauses. This work the same way at the ones for
661 // variables, but with different parameters.
662 void BumpReasonActivities(const std::vector<Literal>& literals);
663 void BumpClauseActivity(SatClause* clause);
664 void RescaleClauseActivities(double scaling_factor);
665 void UpdateClauseActivityIncrement();
666
667 std::string DebugString(const SatClause& clause) const;
668 std::string StatusString(Status status) const;
669 std::string RunningStatisticsString() const;
670
671 // Marks as "non-deletable" all clauses that were used to infer the given
672 // variable. The variable must be currently assigned.
673 void KeepAllClauseUsedToInfer(BooleanVariable variable);
674
675 // Use propagation to try to minimize the given clause. This is really similar
676 // to MinimizeCoreWithPropagation(). It must be called when the current
677 // decision level is zero. Note that because this do a small tree search, it
678 // will impact the variable/clauses activities and may add new conflicts.
679 void TryToMinimizeClause(SatClause* clause);
680
681 // This is used by the old non-model constructor.
682 Model* model_;
683 std::unique_ptr<Model> owned_model_;
684
685 BooleanVariable num_variables_ = BooleanVariable(0);
686
687 // Internal propagators. We keep them here because we need more than the
688 // SatPropagator interface for them.
689 BinaryImplicationGraph* binary_implication_graph_;
690 LiteralWatchers* clauses_propagator_;
691 PbConstraints* pb_constraints_;
692
693 // Ordered list of propagators used by Propagate()/Untrail().
694 std::vector<SatPropagator*> propagators_;
695
696 // Ordered list of propagators added with AddPropagator().
697 std::vector<SatPropagator*> external_propagators_;
698 SatPropagator* last_propagator_ = nullptr;
699
700 // For the old, non-model interface.
701 std::vector<std::unique_ptr<SatPropagator>> owned_propagators_;
702
703 // Keep track of all binary clauses so they can be exported.
704 bool track_binary_clauses_;
705 BinaryClauseManager binary_clauses_;
706
707 // Pointers to singleton Model objects.
708 Trail* trail_;
709 TimeLimit* time_limit_;
710 SatParameters* parameters_;
711 RestartPolicy* restart_;
712 SatDecisionPolicy* decision_policy_;
713
714 // Used for debugging only. See SaveDebugAssignment().
715 VariablesAssignment debug_assignment_;
716
717 // The stack of decisions taken by the solver. They are stored in [0,
718 // current_decision_level_). The vector is of size num_variables_ so it can
719 // store all the decisions. This is done this way because in some situation we
720 // need to remember the previously taken decisions after a backtrack.
721 int current_decision_level_ = 0;
722 std::vector<Decision> decisions_;
723
724 // The trail index after the last Backtrack() call or before the last
725 // EnqueueNewDecision() call.
726 int last_decision_or_backtrack_trail_index_ = 0;
727
728 // The assumption level. See SolveWithAssumptions().
729 int assumption_level_ = 0;
730
731 // The size of the trail when ProcessNewlyFixedVariables() was last called.
732 // Note that the trail contains only fixed literals (that is literals of
733 // decision levels 0) before this point.
734 int num_processed_fixed_variables_ = 0;
735 double deterministic_time_of_last_fixed_variables_cleanup_ = 0.0;
736
737 // Used in ProcessNewlyFixedVariablesForDratProof().
738 int drat_num_processed_fixed_variables_ = 0;
739
740 // Tracks various information about the solver progress.
741 struct Counters {
742 int64_t num_branches = 0;
743 int64_t num_failures = 0;
744 int64_t num_restarts = 0;
745
746 // Minimization stats.
747 int64_t num_minimizations = 0;
748 int64_t num_literals_removed = 0;
749
750 // PB constraints.
751 int64_t num_learned_pb_literals = 0;
752
753 // Clause learning /deletion stats.
754 int64_t num_literals_learned = 0;
755 int64_t num_literals_forgotten = 0;
756 int64_t num_subsumed_clauses = 0;
757
758 // TryToMinimizeClause() stats.
759 int64_t minimization_num_clauses = 0;
760 int64_t minimization_num_decisions = 0;
761 int64_t minimization_num_true = 0;
762 int64_t minimization_num_subsumed = 0;
763 int64_t minimization_num_removed_literals = 0;
764 };
765 Counters counters_;
766
767 // Solver information.
768 WallTimer timer_;
769
770 // This is set to true if the model is found to be UNSAT when adding new
771 // constraints.
772 bool model_is_unsat_ = false;
773
774 // Increment used to bump the variable activities.
775 double clause_activity_increment_;
776
777 // This counter is decremented each time we learn a clause that can be
778 // deleted. When it reaches zero, a clause cleanup is triggered.
779 int num_learned_clause_before_cleanup_ = 0;
780
781 // Temporary members used during conflict analysis.
782 SparseBitset<BooleanVariable> is_marked_;
783 SparseBitset<BooleanVariable> is_independent_;
784 SparseBitset<BooleanVariable> tmp_mark_;
785 std::vector<int> min_trail_index_per_level_;
786
787 // Temporary members used by CanBeInferedFromConflictVariables().
788 std::vector<BooleanVariable> dfs_stack_;
789 std::vector<BooleanVariable> variable_to_process_;
790
791 // Temporary member used by AddLinearConstraintInternal().
792 std::vector<Literal> literals_scratchpad_;
793
794 // A boolean vector used to temporarily mark decision levels.
795 DEFINE_INT_TYPE(SatDecisionLevel, int);
796 SparseBitset<SatDecisionLevel> is_level_marked_;
797
798 // Temporary vectors used by EnqueueDecisionAndBackjumpOnConflict().
799 std::vector<Literal> learned_conflict_;
800 std::vector<Literal> reason_used_to_infer_the_conflict_;
801 std::vector<Literal> extra_reason_literals_;
802 std::vector<SatClause*> subsumed_clauses_;
803
804 // When true, temporarily disable the deletion of clauses that are not needed
805 // anymore. This is a hack for TryToMinimizeClause() because we use
806 // propagation in this function which might trigger a clause database
807 // deletion, but we still want the pointer to the clause we wants to minimize
808 // to be valid until the end of that function.
809 bool block_clause_deletion_ = false;
810
811 // "cache" to avoid inspecting many times the same reason during conflict
812 // analysis.
813 VariableWithSameReasonIdentifier same_reason_identifier_;
814
815 // Temporary vector used by AddProblemClause().
816 std::vector<LiteralWithCoeff> tmp_pb_constraint_;
817
818 // Boolean used to include/exclude constraints from the core computation.
819 bool is_relevant_for_core_computation_;
820
821 // The current pseudo-Boolean conflict used in PB conflict analysis.
822 MutableUpperBoundedLinearConstraint pb_conflict_;
823
824 // The deterministic time when the time limit was updated.
825 // As the deterministic time in the time limit has to be advanced manually,
826 // it is necessary to keep track of the last time the time was advanced.
827 double deterministic_time_at_last_advanced_time_limit_ = 0;
828
829 // This is true iff the loaded problem only contains clauses.
830 bool problem_is_pure_sat_;
831
832 DratProofHandler* drat_proof_handler_;
833
834 mutable StatsGroup stats_;
835 DISALLOW_COPY_AND_ASSIGN(SatSolver);
836};
837
838// Tries to minimize the given UNSAT core with a really simple heuristic.
839// The idea is to remove literals that are consequences of others in the core.
840// We already know that in the initial order, no literal is propagated by the
841// one before it, so we just look for propagation in the reverse order.
842//
843// Important: The given SatSolver must be the one that just produced the given
844// core.
845void MinimizeCore(SatSolver* solver, std::vector<Literal>* core);
846
847// ============================================================================
848// Model based functions.
849//
850// TODO(user): move them in another file, and unit-test them.
851// ============================================================================
852
853inline std::function<void(Model*)> BooleanLinearConstraint(
854 int64_t lower_bound, int64_t upper_bound,
855 std::vector<LiteralWithCoeff>* cst) {
856 return [=](Model* model) {
857 model->GetOrCreate<SatSolver>()->AddLinearConstraint(
858 /*use_lower_bound=*/true, Coefficient(lower_bound),
859 /*use_upper_bound=*/true, Coefficient(upper_bound), cst);
860 };
861}
862
863inline std::function<void(Model*)> CardinalityConstraint(
864 int64_t lower_bound, int64_t upper_bound,
865 const std::vector<Literal>& literals) {
866 return [=](Model* model) {
867 std::vector<LiteralWithCoeff> cst;
868 cst.reserve(literals.size());
869 for (int i = 0; i < literals.size(); ++i) {
870 cst.emplace_back(literals[i], 1);
871 }
872 model->GetOrCreate<SatSolver>()->AddLinearConstraint(
873 /*use_lower_bound=*/true, Coefficient(lower_bound),
874 /*use_upper_bound=*/true, Coefficient(upper_bound), &cst);
875 };
876}
877
878inline std::function<void(Model*)> ExactlyOneConstraint(
879 const std::vector<Literal>& literals) {
880 return [=](Model* model) {
881 std::vector<LiteralWithCoeff> cst;
882 cst.reserve(literals.size());
883 for (const Literal l : literals) {
884 cst.emplace_back(l, Coefficient(1));
885 }
886 model->GetOrCreate<SatSolver>()->AddLinearConstraint(
887 /*use_lower_bound=*/true, Coefficient(1),
888 /*use_upper_bound=*/true, Coefficient(1), &cst);
889 };
890}
891
892inline std::function<void(Model*)> AtMostOneConstraint(
893 const std::vector<Literal>& literals) {
894 return [=](Model* model) {
895 std::vector<LiteralWithCoeff> cst;
896 cst.reserve(literals.size());
897 for (const Literal l : literals) {
898 cst.emplace_back(l, Coefficient(1));
899 }
900 model->GetOrCreate<SatSolver>()->AddLinearConstraint(
901 /*use_lower_bound=*/false, Coefficient(0),
902 /*use_upper_bound=*/true, Coefficient(1), &cst);
903 };
904}
905
906inline std::function<void(Model*)> ClauseConstraint(
907 absl::Span<const Literal> literals) {
908 return [=](Model* model) {
909 std::vector<LiteralWithCoeff> cst;
910 cst.reserve(literals.size());
911 for (const Literal l : literals) {
912 cst.emplace_back(l, Coefficient(1));
913 }
914 model->GetOrCreate<SatSolver>()->AddLinearConstraint(
915 /*use_lower_bound=*/true, Coefficient(1),
916 /*use_upper_bound=*/false, Coefficient(1), &cst);
917 };
918}
919
920// a => b.
921inline std::function<void(Model*)> Implication(Literal a, Literal b) {
922 return [=](Model* model) {
923 model->GetOrCreate<SatSolver>()->AddBinaryClause(a.Negated(), b);
924 };
925}
926
927// a == b.
928inline std::function<void(Model*)> Equality(Literal a, Literal b) {
929 return [=](Model* model) {
930 model->GetOrCreate<SatSolver>()->AddBinaryClause(a.Negated(), b);
931 model->GetOrCreate<SatSolver>()->AddBinaryClause(a, b.Negated());
932 };
933}
934
935// r <=> (at least one literal is true). This is a reified clause.
936inline std::function<void(Model*)> ReifiedBoolOr(
937 const std::vector<Literal>& literals, Literal r) {
938 return [=](Model* model) {
939 std::vector<Literal> clause;
940 for (const Literal l : literals) {
941 model->Add(Implication(l, r)); // l => r.
942 clause.push_back(l);
943 }
944
945 // All false => r false.
946 clause.push_back(r.Negated());
947 model->Add(ClauseConstraint(clause));
948 };
949}
950
951// enforcement_literals => clause.
952inline std::function<void(Model*)> EnforcedClause(
953 absl::Span<const Literal> enforcement_literals,
954 absl::Span<const Literal> clause) {
955 return [=](Model* model) {
956 std::vector<Literal> tmp;
957 for (const Literal l : enforcement_literals) {
958 tmp.push_back(l.Negated());
959 }
960 for (const Literal l : clause) {
961 tmp.push_back(l);
962 }
963 model->Add(ClauseConstraint(tmp));
964 };
965}
966
967// r <=> (all literals are true).
968//
969// Note(user): we could have called ReifiedBoolOr() with everything negated.
970inline std::function<void(Model*)> ReifiedBoolAnd(
971 const std::vector<Literal>& literals, Literal r) {
972 return [=](Model* model) {
973 std::vector<Literal> clause;
974 for (const Literal l : literals) {
975 model->Add(Implication(r, l)); // r => l.
976 clause.push_back(l.Negated());
977 }
978
979 // All true => r true.
980 clause.push_back(r);
981 model->Add(ClauseConstraint(clause));
982 };
983}
984
985// r <=> (a <= b).
986inline std::function<void(Model*)> ReifiedBoolLe(Literal a, Literal b,
987 Literal r) {
988 return [=](Model* model) {
989 // r <=> (a <= b) is the same as r <=> not(a=1 and b=0).
990 // So r <=> a=0 OR b=1.
991 model->Add(ReifiedBoolOr({a.Negated(), b}, r));
992 };
993}
994
995// This checks that the variable is fixed.
996inline std::function<int64_t(const Model&)> Value(Literal l) {
997 return [=](const Model& model) {
998 const Trail* trail = model.Get<Trail>();
1000 return trail->Assignment().LiteralIsTrue(l);
1001 };
1002}
1003
1004// This checks that the variable is fixed.
1005inline std::function<int64_t(const Model&)> Value(BooleanVariable b) {
1006 return [=](const Model& model) {
1007 const Trail* trail = model.Get<Trail>();
1009 return trail->Assignment().LiteralIsTrue(Literal(b, true));
1010 };
1011}
1012
1013// This can be used to enumerate all the solutions. After each SAT call to
1014// Solve(), calling this will reset the solver and exclude the current solution
1015// so that the next call to Solve() will give a new solution or UNSAT is there
1016// is no more new solutions.
1017inline std::function<void(Model*)> ExcludeCurrentSolutionAndBacktrack() {
1018 return [=](Model* model) {
1019 SatSolver* sat_solver = model->GetOrCreate<SatSolver>();
1020
1021 // Note that we only exclude the current decisions, which is an efficient
1022 // way to not get the same SAT assignment.
1023 const int current_level = sat_solver->CurrentDecisionLevel();
1024 std::vector<Literal> clause_to_exclude_solution;
1025 clause_to_exclude_solution.reserve(current_level);
1026 for (int i = 0; i < current_level; ++i) {
1027 clause_to_exclude_solution.push_back(
1028 sat_solver->Decisions()[i].literal.Negated());
1029 }
1030 sat_solver->Backtrack(0);
1031 model->Add(ClauseConstraint(clause_to_exclude_solution));
1032 };
1033}
1034
1035// Returns a string representation of a SatSolver::Status.
1037inline std::ostream& operator<<(std::ostream& os, SatSolver::Status status) {
1038 os << SatStatusString(status);
1039 return os;
1040}
1041
1042} // namespace sat
1043} // namespace operations_research
1044
1045#endif // OR_TOOLS_SAT_SAT_SOLVER_H_
int64_t max
Definition: alldiff_cst.cc:140
#define CHECK(condition)
Definition: base/logging.h:495
#define CHECK_LT(val1, val2)
Definition: base/logging.h:705
#define CHECK_EQ(val1, val2)
Definition: base/logging.h:702
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
Definition: time_limit.h:106
void AdvanceDeterministicTime(double deterministic_duration)
Advances the deterministic time.
Definition: time_limit.h:227
void ExtractAllBinaryClauses(Output *out) const
Definition: clause.h:648
void SetDratProofHandler(DratProofHandler *drat_proof_handler)
Definition: clause.h:669
BooleanVariable Variable() const
Definition: sat_base.h:82
void SetDratProofHandler(DratProofHandler *drat_proof_handler)
Definition: clause.h:240
bool IsRemovable(SatClause *const clause) const
Definition: clause.h:220
const std::vector< SatClause * > & AllClausesInCreationOrder() const
Definition: clause.h:212
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
std::vector< std::pair< Literal, double > > AllPreferences() const
void SetAssignmentPreference(Literal literal, double weight)
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
bool EnqueueDecisionIfNotConflicting(Literal true_literal)
Definition: sat_solver.cc:874
void SetNumVariables(int num_variables)
Definition: sat_solver.cc:65
std::vector< std::pair< Literal, double > > AllPreferences() const
Definition: sat_solver.h:154
bool AddTernaryClause(Literal a, Literal b, Literal c)
Definition: sat_solver.cc:192
void AddLastPropagator(SatPropagator *propagator)
Definition: sat_solver.cc:414
const SatParameters & parameters() const
Definition: sat_solver.cc:111
bool AddClauseDuringSearch(absl::Span< const Literal > literals)
Definition: sat_solver.cc:135
Status SolveWithTimeLimit(TimeLimit *time_limit)
Definition: sat_solver.cc:969
Status ResetAndSolveWithGivenAssumptions(const std::vector< Literal > &assumptions)
Definition: sat_solver.cc:948
void AddPropagator(SatPropagator *propagator)
Definition: sat_solver.cc:406
BooleanVariable NewBooleanVariable()
Definition: sat_solver.h:84
const VariablesAssignment & Assignment() const
Definition: sat_solver.h:363
const std::vector< BinaryClause > & NewlyAddedBinaryClauses()
Definition: sat_solver.cc:933
const std::vector< Decision > & Decisions() const
Definition: sat_solver.h:360
bool AddBinaryClauses(const std::vector< BinaryClause > &clauses)
Definition: sat_solver.cc:919
const Trail & LiteralTrail() const
Definition: sat_solver.h:362
void SetAssumptionLevel(int assumption_level)
Definition: sat_solver.cc:963
void AdvanceDeterministicTime(TimeLimit *limit)
Definition: sat_solver.h:423
void SetDratProofHandler(DratProofHandler *drat_proof_handler)
Definition: sat_solver.h:390
void MinimizeSomeClauses(int decisions_budget)
Definition: sat_solver.cc:1248
void SetAssignmentPreference(Literal literal, double weight)
Definition: sat_solver.h:151
void ResetDecisionHeuristicAndSetAllPreferences(const std::vector< std::pair< Literal, double > > &prefs)
Definition: sat_solver.h:160
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
void TakePropagatorOwnership(std::unique_ptr< SatPropagator > propagator)
Definition: sat_solver.h:143
bool ResetWithGivenAssumptions(const std::vector< Literal > &assumptions)
Definition: sat_solver.cc:537
bool AddProblemClause(absl::Span< const Literal > literals)
Definition: sat_solver.cc:204
bool AddUnitClause(Literal true_literal)
Definition: sat_solver.cc:165
const VariablesAssignment & Assignment() const
Definition: sat_base.h:382
const AssignmentInfo & Info(BooleanVariable var) const
Definition: sat_base.h:383
bool VariableIsAssigned(BooleanVariable var) const
Definition: sat_base.h:160
bool LiteralIsTrue(Literal literal) const
Definition: sat_base.h:152
int64_t b
int64_t a
ModelSharedTimeLimit * time_limit
int64_t value
IntVar * var
Definition: expr_array.cc:1874
absl::Status status
Definition: g_gurobi.cc:35
double upper_bound
double lower_bound
GRBmodel * model
std::tuple< int64_t, int64_t, const double > Coefficient
std::function< void(Model *)> Equality(IntegerVariable v, int64_t value)
Definition: integer.h:1711
std::ostream & operator<<(std::ostream &os, const BoolVar &var)
Definition: cp_model.cc:86
std::function< void(Model *)> ReifiedBoolOr(const std::vector< Literal > &literals, Literal r)
Definition: sat_solver.h:936
std::function< void(Model *)> ClauseConstraint(absl::Span< const Literal > literals)
Definition: sat_solver.h:906
std::function< void(Model *)> EnforcedClause(absl::Span< const Literal > enforcement_literals, absl::Span< const Literal > clause)
Definition: sat_solver.h:952
std::function< void(Model *)> ReifiedBoolLe(Literal a, Literal b, Literal r)
Definition: sat_solver.h:986
std::function< void(Model *)> Implication(const std::vector< Literal > &enforcement_literals, IntegerLiteral i)
Definition: integer.h:1724
void MinimizeCore(SatSolver *solver, std::vector< Literal > *core)
Definition: sat_solver.cc:2553
std::string SatStatusString(SatSolver::Status status)
Definition: sat_solver.cc:2536
std::function< void(Model *)> AtMostOneConstraint(const std::vector< Literal > &literals)
Definition: sat_solver.h:892
std::function< int64_t(const Model &)> Value(IntegerVariable v)
Definition: integer.h:1673
std::function< void(Model *)> ReifiedBoolAnd(const std::vector< Literal > &literals, Literal r)
Definition: sat_solver.h:970
std::function< void(Model *)> CardinalityConstraint(int64_t lower_bound, int64_t upper_bound, const std::vector< Literal > &literals)
Definition: sat_solver.h:863
std::function< void(Model *)> BooleanLinearConstraint(int64_t lower_bound, int64_t upper_bound, std::vector< LiteralWithCoeff > *cst)
Definition: sat_solver.h:853
std::function< void(Model *)> ExactlyOneConstraint(const std::vector< Literal > &literals)
Definition: sat_solver.h:878
std::function< void(Model *)> ExcludeCurrentSolutionAndBacktrack()
Definition: sat_solver.h:1017
const int kUnsatTrailIndex
Definition: sat_solver.h:53
Collection of objects used to extend the Constraint Solver library.
Literal literal
Definition: optimization.cc:85
int64_t weight
Definition: pack.cc:510
static int input(yyscan_t yyscanner)