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