OR-Tools  9.3
simplification.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// Implementation of a pure SAT presolver. This roughly follows the paper:
15//
16// "Effective Preprocessing in SAT through Variable and Clause Elimination",
17// Niklas Een and Armin Biere, published in the SAT 2005 proceedings.
18
19#ifndef OR_TOOLS_SAT_SIMPLIFICATION_H_
20#define OR_TOOLS_SAT_SIMPLIFICATION_H_
21
22#include <cstdint>
23#include <deque>
24#include <memory>
25#include <utility>
26#include <vector>
27
28#include "absl/container/btree_set.h"
29#include "absl/types/span.h"
32#include "ortools/base/macros.h"
36#include "ortools/sat/sat_parameters.pb.h"
41
42namespace operations_research {
43namespace sat {
44
45// A simple sat postsolver.
46//
47// The idea is that any presolve algorithm can just update this class, and at
48// the end, this class will recover a solution of the initial problem from a
49// solution of the presolved problem.
51 public:
52 explicit SatPostsolver(int num_variables);
53
54 // The postsolver will process the Add() calls in reverse order. If the given
55 // clause has all its literals at false, it simply sets the literal x to true.
56 // Note that x must be a literal of the given clause.
57 void Add(Literal x, const absl::Span<const Literal> clause);
58
59 // Tells the postsolver that the given literal must be true in any solution.
60 // We currently check that the variable is not already fixed.
61 //
62 // TODO(user): this as almost the same effect as adding an unit clause, and we
63 // should probably remove this to simplify the code.
64 void FixVariable(Literal x);
65
66 // This assumes that the given variable mapping has been applied to the
67 // problem. All the subsequent Add() and FixVariable() will refer to the new
68 // problem. During postsolve, the initial solution must also correspond to
69 // this new problem. Note that if mapping[v] == -1, then the literal v is
70 // assumed to be deleted.
71 //
72 // This can be called more than once. But each call must refer to the current
73 // variables set (after all the previous mapping have been applied).
74 void ApplyMapping(
76
77 // Extracts the current assignment of the given solver and postsolve it.
78 //
79 // Node(fdid): This can currently be called only once (but this is easy to
80 // change since only some CHECK will fail).
81 std::vector<bool> ExtractAndPostsolveSolution(const SatSolver& solver);
82 std::vector<bool> PostsolveSolution(const std::vector<bool>& solution);
83
84 // Getters to the clauses managed by this class.
85 // Important: This will always put the associated literal first.
86 int NumClauses() const { return clauses_start_.size(); }
87 std::vector<Literal> Clause(int i) const {
88 // TODO(user): we could avoid the copy here, but because clauses_literals_
89 // is a deque, we do need a special return class and cannot juste use
90 // absl::Span<Literal> for instance.
91 const int begin = clauses_start_[i];
92 const int end = i + 1 < clauses_start_.size() ? clauses_start_[i + 1]
93 : clauses_literals_.size();
94 std::vector<Literal> result(clauses_literals_.begin() + begin,
95 clauses_literals_.begin() + end);
96 for (int j = 0; j < result.size(); ++j) {
97 if (result[j] == associated_literal_[i]) {
98 std::swap(result[0], result[j]);
99 break;
100 }
101 }
102 return result;
103 }
104
105 private:
106 Literal ApplyReverseMapping(Literal l);
107 void Postsolve(VariablesAssignment* assignment) const;
108
109 // The presolve can add new variables, so we need to store the number of
110 // original variables in order to return a solution with the correct number
111 // of variables.
112 const int initial_num_variables_;
113 int num_variables_;
114
115 // Stores the arguments of the Add() calls: clauses_start_[i] is the index of
116 // the first literal of the clause #i in the clauses_literals_ deque.
117 std::vector<int> clauses_start_;
118 std::deque<Literal> clauses_literals_;
119 std::vector<Literal> associated_literal_;
120
121 // All the added clauses will be mapped back to the initial variables using
122 // this reverse mapping. This way, clauses_ and associated_literal_ are only
123 // in term of the initial problem.
125
126 // This will stores the fixed variables value and later the postsolved
127 // assignment.
128 VariablesAssignment assignment_;
129
130 DISALLOW_COPY_AND_ASSIGN(SatPostsolver);
131};
132
133// This class holds a SAT problem (i.e. a set of clauses) and the logic to
134// presolve it by a series of subsumption, self-subsuming resolution, and
135// variable elimination by clause distribution.
136//
137// Note that this does propagate unit-clauses, but probably much
138// less efficiently than the propagation code in the SAT solver. So it is better
139// to use a SAT solver to fix variables before using this class.
140//
141// TODO(user): Interact more with a SAT solver to reuse its propagation logic.
142//
143// TODO(user): Forbid the removal of some variables. This way we can presolve
144// only the clause part of a general Boolean problem by not removing variables
145// appearing in pseudo-Boolean constraints.
147 public:
148 // TODO(user): use IntType!
149 typedef int32_t ClauseIndex;
150
151 explicit SatPresolver(SatPostsolver* postsolver, SolverLogger* logger)
152 : postsolver_(postsolver),
153 num_trivial_clauses_(0),
154 drat_proof_handler_(nullptr),
155 logger_(logger) {}
156
157 void SetParameters(const SatParameters& params) { parameters_ = params; }
158 void SetTimeLimit(TimeLimit* time_limit) { time_limit_ = time_limit; }
159
160 // Registers a mapping to encode equivalent literals.
161 // See ProbeAndFindEquivalentLiteral().
164 equiv_mapping_ = mapping;
165 }
166
167 // Adds new clause to the SatPresolver.
168 void SetNumVariables(int num_variables);
170 void AddClause(absl::Span<const Literal> clause);
171
172 // Presolves the problem currently loaded. Returns false if the model is
173 // proven to be UNSAT during the presolving.
174 //
175 // TODO(user): Add support for a time limit and some kind of iterations limit
176 // so that this can never take too much time.
177 bool Presolve();
178
179 // Same as Presolve() but only allow to remove BooleanVariable whose index
180 // is set to true in the given vector.
181 bool Presolve(const std::vector<bool>& var_that_can_be_removed);
182
183 // All the clauses managed by this class.
184 // Note that deleted clauses keep their indices (they are just empty).
185 int NumClauses() const { return clauses_.size(); }
186 const std::vector<Literal>& Clause(ClauseIndex ci) const {
187 return clauses_[ci];
188 }
189
190 // The number of variables. This is computed automatically from the clauses
191 // added to the SatPresolver.
192 int NumVariables() const { return literal_to_clause_sizes_.size() / 2; }
193
194 // After presolving, Some variables in [0, NumVariables()) have no longer any
195 // clause pointing to them. This return a mapping that maps this interval to
196 // [0, new_size) such that now all variables are used. The unused variable
197 // will be mapped to BooleanVariable(-1).
199
200 // Loads the current presolved problem in to the given sat solver.
201 // Note that the variables will be re-indexed according to the mapping given
202 // by GetMapping() so that they form a dense set.
203 //
204 // IMPORTANT: This is not const because it deletes the presolver clauses as
205 // they are added to the SatSolver in order to save memory. After this is
206 // called, only VariableMapping() will still works.
208
209 // Visible for Testing. Takes a given clause index and looks for clause that
210 // can be subsumed or strengthened using this clause. Returns false if the
211 // model is proven to be unsat.
213
214 // Visible for testing. Tries to eliminate x by clause distribution.
215 // This is also known as bounded variable elimination.
216 //
217 // It is always possible to remove x by resolving each clause containing x
218 // with all the clauses containing not(x). Hence the cross-product name. Note
219 // that this function only do that if the number of clauses is reduced.
220 bool CrossProduct(Literal x);
221
222 // Visible for testing. Just applies the BVA step of the presolve.
223 void PresolveWithBva();
224
225 void SetDratProofHandler(DratProofHandler* drat_proof_handler) {
226 drat_proof_handler_ = drat_proof_handler;
227 }
228
229 private:
230 // Internal function used by ProcessClauseToSimplifyOthers().
231 bool ProcessClauseToSimplifyOthersUsingLiteral(ClauseIndex clause_index,
232 Literal lit);
233
234 // Internal function to add clauses generated during the presolve. The clause
235 // must already be sorted with the default Literal order and will be cleared
236 // after this call.
237 void AddClauseInternal(std::vector<Literal>* clause);
238
239 // Clause removal function.
240 void Remove(ClauseIndex ci);
241 void RemoveAndRegisterForPostsolve(ClauseIndex ci, Literal x);
242 void RemoveAndRegisterForPostsolveAllClauseContaining(Literal x);
243
244 // Call ProcessClauseToSimplifyOthers() on all the clauses in
245 // clause_to_process_ and empty the list afterwards. Note that while some
246 // clauses are processed, new ones may be added to the list. Returns false if
247 // the problem is shown to be UNSAT.
248 bool ProcessAllClauses();
249
250 // Finds the literal from the clause that occur the less in the clause
251 // database.
252 Literal FindLiteralWithShortestOccurrenceList(
253 const std::vector<Literal>& clause);
254 LiteralIndex FindLiteralWithShortestOccurrenceListExcluding(
255 const std::vector<Literal>& clause, Literal to_exclude);
256
257 // Tests and maybe perform a Simple Bounded Variable addition starting from
258 // the given literal as described in the paper: "Automated Reencoding of
259 // Boolean Formulas", Norbert Manthey, Marijn J. H. Heule, and Armin Biere,
260 // Volume 7857 of the series Lecture Notes in Computer Science pp 102-117,
261 // 2013.
262 // https://www.research.ibm.com/haifa/conferences/hvc2012/papers/paper16.pdf
263 //
264 // This seems to have a mostly positive effect, except on the crafted problem
265 // familly mugrauer_balint--GI.crafted_nxx_d6_cx_numxx where the reduction
266 // is big, but apparently the problem is harder to prove UNSAT for the solver.
267 void SimpleBva(LiteralIndex l);
268
269 // Display some statistics on the current clause database.
270 void DisplayStats(double elapsed_seconds);
271
272 // Returns a hash of the given clause variables (not literal) in such a way
273 // that hash1 & not(hash2) == 0 iff the set of variable of clause 1 is a
274 // subset of the one of clause2.
275 uint64_t ComputeSignatureOfClauseVariables(ClauseIndex ci);
276
277 // The "active" variables on which we want to call CrossProduct() are kept
278 // in a priority queue so that we process first the ones that occur the least
279 // often in the clause database.
280 void InitializePriorityQueue();
281 void UpdatePriorityQueue(BooleanVariable var);
282 struct PQElement {
283 PQElement() : heap_index(-1), variable(-1), weight(0.0) {}
284
285 // Interface for the AdjustablePriorityQueue.
286 void SetHeapIndex(int h) { heap_index = h; }
287 int GetHeapIndex() const { return heap_index; }
288
289 // Priority order. The AdjustablePriorityQueue returns the largest element
290 // first, but our weight goes this other way around (smaller is better).
291 bool operator<(const PQElement& other) const {
292 return weight > other.weight;
293 }
294
295 int heap_index;
296 BooleanVariable variable;
297 double weight;
298 };
301
302 // Literal priority queue for BVA. The literals are ordered by descending
303 // number of occurrences in clauses.
304 void InitializeBvaPriorityQueue();
305 void UpdateBvaPriorityQueue(LiteralIndex lit);
306 void AddToBvaPriorityQueue(LiteralIndex lit);
307 struct BvaPqElement {
308 BvaPqElement() : heap_index(-1), literal(-1), weight(0.0) {}
309
310 // Interface for the AdjustablePriorityQueue.
311 void SetHeapIndex(int h) { heap_index = h; }
312 int GetHeapIndex() const { return heap_index; }
313
314 // Priority order.
315 // The AdjustablePriorityQueue returns the largest element first.
316 bool operator<(const BvaPqElement& other) const {
317 return weight < other.weight;
318 }
319
320 int heap_index;
321 LiteralIndex literal;
322 double weight;
323 };
324 std::deque<BvaPqElement> bva_pq_elements_; // deque because we add variables.
326
327 // Temporary data for SimpleBva().
328 absl::btree_set<LiteralIndex> m_lit_;
329 std::vector<ClauseIndex> m_cls_;
330 absl::StrongVector<LiteralIndex, int> literal_to_p_size_;
331 std::vector<std::pair<LiteralIndex, ClauseIndex>> flattened_p_;
332 std::vector<Literal> tmp_new_clause_;
333
334 // List of clauses on which we need to call ProcessClauseToSimplifyOthers().
335 // See ProcessAllClauses().
336 std::vector<bool> in_clause_to_process_;
337 std::deque<ClauseIndex> clause_to_process_;
338
339 // The set of all clauses.
340 // An empty clause means that it has been removed.
341 std::vector<std::vector<Literal>> clauses_; // Indexed by ClauseIndex
342
343 // The cached value of ComputeSignatureOfClauseVariables() for each clause.
344 std::vector<uint64_t> signatures_; // Indexed by ClauseIndex
345 int64_t num_inspected_signatures_ = 0;
346 int64_t num_inspected_literals_ = 0;
347
348 // Occurrence list. For each literal, contains the ClauseIndex of the clause
349 // that contains it (ordered by clause index).
351 literal_to_clauses_;
352
353 // Because we only lazily clean the occurrence list after clause deletions,
354 // we keep the size of the occurrence list (without the deleted clause) here.
355 absl::StrongVector<LiteralIndex, int> literal_to_clause_sizes_;
356
357 // Used for postsolve.
358 SatPostsolver* postsolver_;
359
360 // Equivalent literal mapping.
362
363 int num_trivial_clauses_;
364 SatParameters parameters_;
365 DratProofHandler* drat_proof_handler_;
366 TimeLimit* time_limit_ = nullptr;
367 SolverLogger* logger_;
368
369 DISALLOW_COPY_AND_ASSIGN(SatPresolver);
370};
371
372// Visible for testing. Returns true iff:
373// - a subsume b (subsumption): the clause a is a subset of b, in which case
374// opposite_literal is set to -1.
375// - b is strengthened by self-subsumption using a (self-subsuming resolution):
376// the clause a with one of its literal negated is a subset of b, in which
377// case opposite_literal is set to this negated literal index. Moreover, this
378// opposite_literal is then removed from b.
379//
380// If num_inspected_literals_ is not nullptr, the "complexity" of this function
381// will be added to it in order to track the amount of work done.
382//
383// TODO(user): when a.size() << b.size(), we should use binary search instead
384// of scanning b linearly.
385bool SimplifyClause(const std::vector<Literal>& a, std::vector<Literal>* b,
386 LiteralIndex* opposite_literal,
387 int64_t* num_inspected_literals = nullptr);
388
389// Visible for testing. Returns kNoLiteralIndex except if:
390// - a and b differ in only one literal.
391// - For a it is the given literal l.
392// In which case, returns the LiteralIndex of the literal in b that is not in a.
393LiteralIndex DifferAtGivenLiteral(const std::vector<Literal>& a,
394 const std::vector<Literal>& b, Literal l);
395
396// Visible for testing. Computes the resolvant of 'a' and 'b' obtained by
397// performing the resolution on 'x'. If the resolvant is trivially true this
398// returns false, otherwise it returns true and fill 'out' with the resolvant.
399//
400// Note that the resolvant is just 'a' union 'b' with the literals 'x' and
401// not(x) removed. The two clauses are assumed to be sorted, and the computed
402// resolvant will also be sorted.
403//
404// This is the basic operation when a variable is eliminated by clause
405// distribution.
406bool ComputeResolvant(Literal x, const std::vector<Literal>& a,
407 const std::vector<Literal>& b, std::vector<Literal>* out);
408
409// Same as ComputeResolvant() but just returns the resolvant size.
410// Returns -1 when ComputeResolvant() returns false.
411int ComputeResolvantSize(Literal x, const std::vector<Literal>& a,
412 const std::vector<Literal>& b);
413
414// Presolver that does literals probing and finds equivalent literals by
415// computing the strongly connected components of the graph:
416// literal l -> literals propagated by l.
417//
418// Clears the mapping if there are no equivalent literals. Otherwise, mapping[l]
419// is the representative of the equivalent class of l. Note that mapping[l] may
420// be equal to l.
421//
422// The postsolver will be updated so it can recover a solution of the mapped
423// problem. Note that this works on any problem the SatSolver can handle, not
424// only pure SAT problem, but the returned mapping do need to be applied to all
425// constraints.
427 SatSolver* solver, SatPostsolver* postsolver,
428 DratProofHandler* drat_proof_handler,
430
431// Given a 'solver' with a problem already loaded, this will try to simplify the
432// problem (i.e. presolve it) before calling solver->Solve(). In the process,
433// because of the way the presolve is implemented, the underlying SatSolver may
434// change (it is why we use this unique_ptr interface). In particular, the final
435// variables and 'solver' state may have nothing to do with the problem
436// originaly present in the solver. That said, if the problem is shown to be
437// SAT, then the returned solution will be in term of the original variables.
438//
439// Note that the full presolve is only executed if the problem is a pure SAT
440// problem with only clauses.
442 std::unique_ptr<SatSolver>* solver, TimeLimit* time_limit,
443 std::vector<bool>* solution /* only filled if SAT */,
444 DratProofHandler* drat_proof_handler /* can be nullptr */,
445 SolverLogger* logger);
446
447} // namespace sat
448} // namespace operations_research
449
450#endif // OR_TOOLS_SAT_SIMPLIFICATION_H_
size_type size() const
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 Add(Literal x, const absl::Span< const Literal > clause)
void ApplyMapping(const absl::StrongVector< BooleanVariable, BooleanVariable > &mapping)
std::vector< bool > PostsolveSolution(const std::vector< bool > &solution)
std::vector< Literal > Clause(int i) const
std::vector< bool > ExtractAndPostsolveSolution(const SatSolver &solver)
void SetNumVariables(int num_variables)
const std::vector< Literal > & Clause(ClauseIndex ci) const
void LoadProblemIntoSatSolver(SatSolver *solver)
void AddBinaryClause(Literal a, Literal b)
SatPresolver(SatPostsolver *postsolver, SolverLogger *logger)
void SetEquivalentLiteralMapping(const absl::StrongVector< LiteralIndex, LiteralIndex > &mapping)
void SetParameters(const SatParameters &params)
absl::StrongVector< BooleanVariable, BooleanVariable > VariableMapping() const
void SetDratProofHandler(DratProofHandler *drat_proof_handler)
void AddClause(absl::Span< const Literal > clause)
bool ProcessClauseToSimplifyOthers(ClauseIndex clause_index)
void SetTimeLimit(TimeLimit *time_limit)
int64_t b
int64_t a
ModelSharedTimeLimit * time_limit
IntVar * var
Definition: expr_array.cc:1874
void swap(IdMap< K, V > &a, IdMap< K, V > &b)
Definition: id_map.h:262
int ComputeResolvantSize(Literal x, const std::vector< Literal > &a, const std::vector< Literal > &b)
LiteralIndex DifferAtGivenLiteral(const std::vector< Literal > &a, const std::vector< Literal > &b, Literal l)
bool SimplifyClause(const std::vector< Literal > &a, std::vector< Literal > *b, LiteralIndex *opposite_literal, int64_t *num_inspected_literals)
bool ComputeResolvant(Literal x, const std::vector< Literal > &a, const std::vector< Literal > &b, std::vector< Literal > *out)
SatSolver::Status SolveWithPresolve(std::unique_ptr< SatSolver > *solver, TimeLimit *time_limit, std::vector< bool > *solution, DratProofHandler *drat_proof_handler, SolverLogger *logger)
void ProbeAndFindEquivalentLiteral(SatSolver *solver, SatPostsolver *postsolver, DratProofHandler *drat_proof_handler, absl::StrongVector< LiteralIndex, LiteralIndex > *mapping)
Collection of objects used to extend the Constraint Solver library.
Literal literal
Definition: optimization.cc:89
int64_t weight
Definition: pack.cc:510
std::optional< int64_t > end