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