Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
drat_checker.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#ifndef ORTOOLS_SAT_DRAT_CHECKER_H_
15#define ORTOOLS_SAT_DRAT_CHECKER_H_
16
17#include <stddef.h>
18
19#include <cstddef>
20#include <cstdint>
21#include <limits>
22#include <string>
23#include <vector>
24
25#include "absl/container/flat_hash_set.h"
26#include "absl/types/span.h"
30
31namespace operations_research {
32namespace sat {
33
34// Index of a clause (>= 0).
36const ClauseIndex kNoClauseIndex(-1);
37
38// DRAT is a SAT proof format that allows a simple program to check that a
39// problem is really UNSAT. The description of the format and a checker are
40// available at http://www.cs.utexas.edu/~marijn/drat-trim/. This class checks
41// that a DRAT proof is valid.
42//
43// Note that DRAT proofs are often huge (can be GB), and can take about as much
44// time to check as it takes to find the proof in the first place!
46 public:
48 ~DratChecker() = default;
49
50 // Returns the number of Boolean variables used in the problem and inferred
51 // clauses.
52 int num_variables() const { return num_variables_; }
53
54 // Adds a clause of the problem that must be checked. The problem clauses must
55 // be added first, before any inferred clause. Must not be called after
56 // Check().
57 void AddProblemClause(absl::Span<const Literal> clause);
58
59 // Adds a clause which is inferred from the problem clauses and the previously
60 // inferred clauses (that are have not been deleted). Inferred clauses must be
61 // added after the problem clauses. Clauses with the Reverse Asymmetric
62 // Tautology (RAT) property for literal l must start with this literal. The
63 // given clause must not contain a literal and its negation. Must not be
64 // called after Check().
65 void AddInferredClause(absl::Span<const Literal> clause);
66
67 // Deletes a problem or inferred clause. The order of the literals does not
68 // matter. In particular, it can be different from the order that was used
69 // when the clause was added. Must not be called after Check().
70 void DeleteClause(absl::Span<const Literal> clause);
71
72 // Checks that the inferred clauses form a DRAT proof that the problem clauses
73 // are UNSAT. For this the last added inferred clause must be the empty clause
74 // and each inferred clause must have either the Reverse Unit Propagation
75 // (RUP) or the Reverse Asymmetric Tautology (RAT) property with respect to
76 // the problem clauses and the previously inferred clauses which are not
77 // deleted. Returns VALID if the proof is valid, INVALID if it is not, and
78 // UNKNOWN if the check timed out. WARNING: no new clause must be added or
79 // deleted after this method has been called.
85 Status Check(double max_time_in_seconds);
86
87 // Returns a subproblem of the original problem that is already UNSAT. The
88 // result is undefined if Check() was not previously called, or did not return
89 // true.
90 std::vector<std::vector<Literal>> GetUnsatSubProblem() const;
91
92 // Returns a DRAT proof that GetUnsatSubProblem() is UNSAT. The result is
93 // undefined if Check() was not previously called, or did not return true.
94 std::vector<std::vector<Literal>> GetOptimizedProof() const;
95
96 private:
97 // A problem or inferred clause. The literals are specified as a subrange of
98 // 'literals_' (namely the subrange from 'first_literal_index' to
99 // 'first_literal_index' + 'num_literals' - 1), and are sorted in increasing
100 // order *before Check() is called*.
101 struct Clause {
102 // The index of the first literal of this clause in 'literals_'.
103 size_t first_literal_index;
104 // The number of literals of this clause.
105 int num_literals;
106
107 // The clause literal to use to check the RAT property, or kNoLiteralIndex
108 // for problem clauses and empty inferred clauses.
109 LiteralIndex rat_literal_index = kNoLiteralIndex;
110
111 // The *current* number of copies of this clause. This number is incremented
112 // each time a copy of the clause is added, and decremented each time a copy
113 // is deleted. When this number reaches 0, the clause is actually marked as
114 // deleted (see 'deleted_index'). If other copies are added after this
115 // number reached 0, a new clause is added (because a Clause lifetime is a
116 // single interval of ClauseIndex values; therefore, in order to represent a
117 // lifetime made of several intervals, several Clause are used).
118 int num_copies = 1;
119
120 // The index in 'clauses_' from which this clause is deleted (inclusive).
121 // For instance, with AddProblemClause(c0), AddProblemClause(c1),
122 // DeleteClause(c0), AddProblemClause(c2), ... if c0's index is 0, then its
123 // deleted_index is 2. Meaning that when checking a clause whose index is
124 // larger than or equal to 2 (e.g. c2), c0 can be ignored.
125 ClauseIndex deleted_index = ClauseIndex(std::numeric_limits<int>::max());
126
127 // The indices of the clauses (with at least two literals) which are deleted
128 // just after this clause.
129 std::vector<ClauseIndex> deleted_clauses;
130
131 // Whether this clause is actually needed to check the DRAT proof.
132 bool is_needed_for_proof = false;
133 // Whether this clause is actually needed to check the current step (i.e. an
134 // inferred clause) of the DRAT proof. This bool is always false, except in
135 // MarkAsNeededForProof() that uses it temporarily.
136 bool tmp_is_needed_for_proof_step = false;
137
138 Clause(size_t first_literal_index, int num_literals);
139
140 // Returns true if this clause is deleted before the given clause.
141 bool IsDeleted(ClauseIndex clause_index) const;
142 };
143
144 // A literal to assign to true during boolean constraint propagation. When a
145 // literal is assigned, new literals can be found that also need to be
146 // assigned to true (via unit clauses). In this case they are pushed on a
147 // stack of LiteralToAssign values, to be processed later on (the use of this
148 // stack avoids recursive calls to the boolean constraint propagation method
149 // AssignAndPropagate()).
150 struct LiteralToAssign {
151 // The literal that must be assigned to true.
152 Literal literal;
153 // The index of the clause from which this assignment was deduced. This is
154 // kNoClauseIndex for the clause we are currently checking (whose literals
155 // are all falsified to check if a conflict can be derived). Otherwise this
156 // is the index of a unit clause with unit literal 'literal' that was found
157 // during boolean constraint propagation.
158 ClauseIndex source_clause_index;
159 };
160
161 // Hash function for clauses.
162 struct ClauseHash {
163 DratChecker* checker;
164 explicit ClauseHash(DratChecker* checker) : checker(checker) {}
165 std::size_t operator()(ClauseIndex clause_index) const;
166 };
167
168 // Equality function for clauses.
169 struct ClauseEquiv {
170 DratChecker* checker;
171 explicit ClauseEquiv(DratChecker* checker) : checker(checker) {}
172 bool operator()(ClauseIndex clause_index1, ClauseIndex clause_index2) const;
173 };
174
175 // Adds a clause and returns its index. If the clause is always true (because
176 // it contains a literal and its negation), it is not added and kNoClauseIndex
177 // is returned.
178 ClauseIndex MaybeAddClause(absl::Span<const Literal> clause);
179
180 // Removes the last clause added to 'clauses_'.
181 void RemoveLastClause();
182
183 // Returns the literals of the given clause in increasing order.
184 absl::Span<const Literal> Literals(const Clause& clause) const;
185
186 // Initializes the data structures used to check the DRAT proof.
187 void Init();
188
189 // Adds 2 watch literals for the given clause.
190 void WatchClause(ClauseIndex clause_index);
191
192 // Returns true if, by assigning all the literals of 'clause' to false, a
193 // conflict can be found with boolean constraint propagation, using the non
194 // deleted clauses whose index is strictly less than 'num_clauses'. If so,
195 // marks the clauses actually used in this process as needed to check to DRAT
196 // proof.
197 bool HasRupProperty(ClauseIndex num_clauses,
198 absl::Span<const Literal> clause);
199
200 // Assigns 'literal' to true in 'assignment_' (and pushes it to 'assigned_'),
201 // records its source clause 'source_clause_index' in 'assignment_source_',
202 // and uses the watched literals to find all the clauses (whose index is less
203 // than 'num_clauses') that become unit due to this assignment. For each unit
204 // clause found, pushes its unit literal on top of
205 // 'high_priority_literals_to_assign_' or 'low_priority_literals_to_assign_'.
206 // Returns kNoClauseIndex if no falsified clause is found, or the index of the
207 // first found falsified clause otherwise.
208 ClauseIndex AssignAndPropagate(ClauseIndex num_clauses, Literal literal,
209 ClauseIndex source_clause_index);
210
211 // Marks the given clause as needed to check the DRAT proof, as well as the
212 // other clauses which were used to check this clause (these are found from
213 // 'unit_stack_', containing the clauses that became unit in
214 // AssignAndPropagate, and from 'assignment_source_', containing for each
215 // variable the clause that caused its assignment).
216 void MarkAsNeededForProof(Clause* clause);
217
218 // Returns the clauses whose index is in [begin,end) which are needed for the
219 // proof. The result is undefined if Check() was not previously called, or did
220 // not return true.
221 std::vector<std::vector<Literal>> GetClausesNeededForProof(
222 ClauseIndex begin, ClauseIndex end) const;
223
224 void LogStatistics(int64_t duration_nanos) const;
225
226 // The index of the first inferred clause in 'clauses_', or kNoClauseIndex if
227 // there is no inferred clause.
228 ClauseIndex first_inferred_clause_index_;
229
230 // The problem clauses, followed by the inferred clauses.
231 util_intops::StrongVector<ClauseIndex, Clause> clauses_;
232
233 // A content addressable set of the non-deleted clauses in clauses_. After
234 // adding a clause to clauses_, this set can be used to find if the same
235 // clause was previously added (i.e if a find using the new clause index
236 // returns a previous index) and not yet deleted.
237 absl::flat_hash_set<ClauseIndex, ClauseHash, ClauseEquiv> clause_set_;
238
239 // All the literals used in 'clauses_'.
240 std::vector<Literal> literals_;
241
242 // The number of Boolean variables used in the clauses.
243 int num_variables_;
244
245 // ---------------------------------------------------------------------------
246 // Data initialized in Init() and used in Check() to check the DRAT proof.
247
248 // The literals that have been assigned so far (this is used to unassign them
249 // after a clause has been checked, before checking the next one).
250 std::vector<Literal> assigned_;
251
252 // The current assignment values of literals_.
253 VariablesAssignment assignment_;
254
255 // For each variable, the index of the unit clause that caused its assignment,
256 // or kNoClauseIndex if the variable is not assigned, or was assigned to
257 // falsify the clause that is currently being checked.
258 util_intops::StrongVector<BooleanVariable, ClauseIndex> assignment_source_;
259
260 // The stack of literals that remain to be assigned to true during boolean
261 // constraint propagation, with high priority (unit clauses which are already
262 // marked as needed for the proof are given higher priority than the others
263 // during boolean constraint propagation. According to 'Trimming while
264 // Checking Clausal Proofs', this heuristics reduces the final number of
265 // clauses that are marked as needed for the proof, and therefore the
266 // verification time, in a majority of cases -- but not all).
267 std::vector<LiteralToAssign> high_priority_literals_to_assign_;
268
269 // The stack of literals that remain to be assigned to true during boolean
270 // constraint propagation, with low priority (see above).
271 std::vector<LiteralToAssign> low_priority_literals_to_assign_;
272
273 // For each literal, the list of clauses in which this literal is watched.
274 // Invariant 1: the literals with indices first_watched_literal_index and
275 // second_watched_literal_index of each clause with at least two literals are
276 // watched.
277 // Invariant 2: watched literals are non-falsified if the clause is not
278 // satisfied (in more details: if a clause c is contained in
279 // 'watched_literals_[l]' for literal l, then either c is satisfied with
280 // 'assignment_', or l is unassigned or assigned to true).
281 util_intops::StrongVector<LiteralIndex, std::vector<ClauseIndex>>
282 watched_literals_;
283
284 // The list of clauses with only one literal. This is needed for boolean
285 // constraint propagation, in addition to watched literals, because watched
286 // literals can only be used with clauses having at least two literals.
287 std::vector<ClauseIndex> single_literal_clauses_;
288
289 // The stack of clauses that have become unit during boolean constraint
290 // propagation, in HasRupProperty().
291 std::vector<ClauseIndex> unit_stack_;
292
293 // A temporary assignment, always fully unassigned except in Resolve().
294 VariablesAssignment tmp_assignment_;
295
296 // ---------------------------------------------------------------------------
297 // Statistics
298
299 // The number of inferred clauses having the RAT property (but not the RUP
300 // property).
301 int num_rat_checks_;
302};
303
304// Returns true if the given clause contains the given literal. This works in
305// O(clause.size()).
306bool ContainsLiteral(absl::Span<const Literal> clause, Literal literal);
307
308// Returns true if 'complementary_literal' is the unique complementary literal
309// in the two given clauses. If so the resolvent of these clauses (i.e. their
310// union with 'complementary_literal' and its negation removed) is set in
311// 'resolvent'. 'clause' must contain 'complementary_literal', while
312// 'other_clause' must contain its negation. 'assignment' must have at least as
313// many variables as each clause, and they must all be unassigned. They are
314// still unassigned upon return.
315bool Resolve(absl::Span<const Literal> clause,
316 absl::Span<const Literal> other_clause,
317 Literal complementary_literal, VariablesAssignment* assignment,
318 std::vector<Literal>* resolvent);
319
320// Adds to the given drat checker the problem clauses from the file at the given
321// path, which must be in DIMACS format. Returns true iff the file was
322// successfully parsed.
323bool AddProblemClauses(const std::string& file_path, DratChecker* drat_checker);
324
325// Adds to the given drat checker the inferred and deleted clauses from the file
326// at the given path, which must be in DRAT format. Returns true iff the file
327// was successfully parsed.
328bool AddInferredAndDeletedClauses(const std::string& file_path,
329 DratChecker* drat_checker);
330
331// The file formats that can be used to save a list of clauses.
332enum SatFormat {
333 DIMACS,
337// Prints the given clauses in the file at the given path, using the given file
338// format. Returns true iff the file was successfully written.
339bool PrintClauses(const std::string& file_path, SatFormat format,
340 absl::Span<const std::vector<Literal>> clauses,
341 int num_variables);
342
343} // namespace sat
344} // namespace operations_research
345
346#endif // ORTOOLS_SAT_DRAT_CHECKER_H_
void AddProblemClause(absl::Span< const Literal > clause)
std::vector< std::vector< Literal > > GetUnsatSubProblem() const
Status Check(double max_time_in_seconds)
std::vector< std::vector< Literal > > GetOptimizedProof() const
void AddInferredClause(absl::Span< const Literal > clause)
void DeleteClause(absl::Span< const Literal > clause)
bool AddProblemClauses(const std::string &file_path, DratChecker *drat_checker)
const LiteralIndex kNoLiteralIndex(-1)
bool Resolve(absl::Span< const Literal > clause, absl::Span< const Literal > other_clause, Literal complementary_literal, VariablesAssignment *assignment, std::vector< Literal > *resolvent)
bool PrintClauses(const std::string &file_path, SatFormat format, absl::Span< const std::vector< Literal > > clauses, int num_variables)
bool ContainsLiteral(absl::Span< const Literal > clause, Literal literal)
bool AddInferredAndDeletedClauses(const std::string &file_path, DratChecker *drat_checker)
const ClauseIndex kNoClauseIndex(-1)
OR-Tools root namespace.
ClosedInterval::Iterator end(ClosedInterval interval)
ClosedInterval::Iterator begin(ClosedInterval interval)
#define DEFINE_STRONG_INDEX_TYPE(index_type_name)