Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
pb_constraint.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#ifndef OR_TOOLS_SAT_PB_CONSTRAINT_H_
15#define OR_TOOLS_SAT_PB_CONSTRAINT_H_
16
17#include <algorithm>
18#include <cstdint>
19#include <limits>
20#include <memory>
21#include <ostream>
22#include <string>
23#include <vector>
24
25#include "absl/container/flat_hash_map.h"
26#include "absl/log/check.h"
27#include "absl/strings/string_view.h"
28#include "absl/types/span.h"
31#include "ortools/base/types.h"
32#include "ortools/sat/model.h"
34#include "ortools/sat/sat_parameters.pb.h"
35#include "ortools/util/bitset.h"
36#include "ortools/util/stats.h"
38
39namespace operations_research {
40namespace sat {
41
42// The type of the integer coefficients in a pseudo-Boolean constraint.
43// This is also used for the current value of a constraint or its bounds.
45
46// IMPORTANT: We can't use numeric_limits<Coefficient>::max() which will compile
47// but just returns zero!!
48const Coefficient kCoefficientMax(
49 std::numeric_limits<Coefficient::ValueType>::max());
50
51// Represents a term in a pseudo-Boolean formula.
53 LiteralWithCoeff() = default;
54 LiteralWithCoeff(Literal l, Coefficient c) : literal(l), coefficient(c) {}
55 LiteralWithCoeff(Literal l, int64_t c) : literal(l), coefficient(c) {}
57 Coefficient coefficient;
58 bool operator==(const LiteralWithCoeff& other) const {
59 return literal.Index() == other.literal.Index() &&
60 coefficient == other.coefficient;
61 }
62};
63
64template <typename H>
65H AbslHashValue(H h, const LiteralWithCoeff& term) {
66 return H::combine(std::move(h), term.literal.Index(),
67 term.coefficient.value());
68}
69
70inline std::ostream& operator<<(std::ostream& os, LiteralWithCoeff term) {
71 os << term.coefficient << "[" << term.literal.DebugString() << "]";
72 return os;
73}
74
75// Puts the given Boolean linear expression in canonical form:
76// - Merge all the literal corresponding to the same variable.
77// - Remove zero coefficients.
78// - Make all the coefficients positive.
79// - Sort the terms by increasing coefficient values.
80//
81// This function also computes:
82// - max_value: the maximum possible value of the formula.
83// - bound_shift: which allows to updates initial bounds. That is, if an
84// initial pseudo-Boolean constraint was
85// lhs < initial_pb_formula < rhs
86// then the new one is:
87// lhs + bound_shift < canonical_form < rhs + bound_shift
88//
89// Finally, this will return false, if some integer overflow or underflow
90// occurred during the reduction to the canonical form.
92 std::vector<LiteralWithCoeff>* cst, Coefficient* bound_shift,
93 Coefficient* max_value);
94
95// Maps all the literals of the given constraint using the given mapping. The
96// mapping may map a literal index to kTrueLiteralIndex or kFalseLiteralIndex in
97// which case the literal will be considered fixed to the appropriate value.
98//
99// Note that this function also canonicalizes the constraint and updates
100// bound_shift and max_value like ComputeBooleanLinearExpressionCanonicalForm()
101// does.
102//
103// Finally, this will return false if some integer overflow or underflow
104// occurred during the constraint simplification.
107 std::vector<LiteralWithCoeff>* cst, Coefficient* bound_shift,
108 Coefficient* max_value);
109
110// From a constraint 'expr <= ub' and the result (bound_shift, max_value) of
111// calling ComputeBooleanLinearExpressionCanonicalForm() on 'expr', this returns
112// a new rhs such that 'canonical expression <= rhs' is an equivalent
113// constraint. This function deals with all the possible overflow corner cases.
114//
115// The result will be in [-1, max_value] where -1 means unsatisfiable and
116// max_value means trivialy satisfiable.
117Coefficient ComputeCanonicalRhs(Coefficient upper_bound,
118 Coefficient bound_shift, Coefficient max_value);
119
120// Same as ComputeCanonicalRhs(), but uses the initial constraint lower bound
121// instead. From a constraint 'lb <= expression', this returns a rhs such that
122// 'canonical expression with literals negated <= rhs'.
123//
124// Note that the range is also [-1, max_value] with the same meaning.
125Coefficient ComputeNegatedCanonicalRhs(Coefficient lower_bound,
126 Coefficient bound_shift,
127 Coefficient max_value);
128
129// Returns true iff the Boolean linear expression is in canonical form.
130bool BooleanLinearExpressionIsCanonical(absl::Span<const LiteralWithCoeff> cst);
131
132// Given a Boolean linear constraint in canonical form, simplify its
133// coefficients using simple heuristics.
135 std::vector<LiteralWithCoeff>* cst, Coefficient* rhs);
136
137// Holds a set of boolean linear constraints in canonical form:
138// - The constraint is a linear sum of LiteralWithCoeff <= rhs.
139// - The linear sum satisfies the properties described in
140// ComputeBooleanLinearExpressionCanonicalForm().
141//
142// TODO(user): Simplify further the constraints.
143//
144// TODO(user): Remove the duplication between this and what the sat solver
145// is doing in AddLinearConstraint() which is basically the same.
146//
147// TODO(user): Remove duplicate constraints? some problems have them, and
148// this is not ideal for the symmetry computation since it leads to a lot of
149// symmetries of the associated graph that are not useful.
151 public:
153
154 // This type is neither copyable nor movable.
157 const CanonicalBooleanLinearProblem&) = delete;
158
159 // Adds a new constraint to the problem. The bounds are inclusive.
160 // Returns false in case of a possible overflow or if the constraint is
161 // never satisfiable.
162 //
163 // TODO(user): Use a return status to distinguish errors if needed.
164 bool AddLinearConstraint(bool use_lower_bound, Coefficient lower_bound,
165 bool use_upper_bound, Coefficient upper_bound,
166 std::vector<LiteralWithCoeff>* cst);
167
168 // Getters. All the constraints are guaranteed to be in canonical form.
169 int NumConstraints() const { return constraints_.size(); }
170 Coefficient Rhs(int i) const { return rhs_[i]; }
171 const std::vector<LiteralWithCoeff>& Constraint(int i) const {
172 return constraints_[i];
173 }
174
175 private:
176 bool AddConstraint(absl::Span<const LiteralWithCoeff> cst,
177 Coefficient max_value, Coefficient rhs);
178
179 std::vector<Coefficient> rhs_;
180 std::vector<std::vector<LiteralWithCoeff>> constraints_;
181};
182
183// Encode a constraint sum term <= rhs, where each term is a positive
184// Coefficient times a literal. This class allows efficient modification of the
185// constraint and is used during pseudo-Boolean resolution.
187 public:
188 // This must be called before any other functions is used with an higher
189 // variable index.
190 void ClearAndResize(int num_variables);
191
192 // Reset the constraint to 0 <= 0.
193 // Note that the constraint size stays the same.
194 void ClearAll();
195
196 // Returns the coefficient (>= 0) of the given variable.
197 Coefficient GetCoefficient(BooleanVariable var) const {
198 return AbsCoefficient(terms_[var]);
199 }
200
201 // Returns the literal under which the given variable appear in the
202 // constraint. Note that if GetCoefficient(var) == 0 this just returns
203 // Literal(var, true).
204 Literal GetLiteral(BooleanVariable var) const {
205 return Literal(var, terms_[var] > 0);
206 }
207
208 // If we have a lower bounded constraint sum terms >= rhs, then it is trivial
209 // to see that the coefficient of any term can be reduced to rhs if it is
210 // bigger. This does exactly this operation, but on the upper bounded
211 // representation.
212 //
213 // If we take a constraint sum ci.xi <= rhs, take its negation and add max_sum
214 // on both side, we have sum ci.(1 - xi) >= max_sum - rhs
215 // So every ci > (max_sum - rhs) can be replacend by (max_sum - rhs).
216 // Not that this operation also change the original rhs of the constraint.
217 void ReduceCoefficients();
218
219 // Same as ReduceCoefficients() but only consider the coefficient of the given
220 // variable.
221 void ReduceGivenCoefficient(BooleanVariable var) {
222 const Coefficient bound = max_sum_ - rhs_;
223 const Coefficient diff = GetCoefficient(var) - bound;
224 if (diff > 0) {
225 rhs_ -= diff;
226 max_sum_ -= diff;
227 terms_[var] = (terms_[var] > 0) ? bound : -bound;
228 }
229 }
230
231 // Compute the constraint slack assuming that only the variables with index <
232 // trail_index are assigned.
233 Coefficient ComputeSlackForTrailPrefix(const Trail& trail,
234 int trail_index) const;
235
236 // Same as ReduceCoefficients() followed by ComputeSlackForTrailPrefix(). It
237 // allows to loop only once over all the terms of the constraint instead of
238 // doing it twice. This helps since doing that can be the main bottleneck.
239 //
240 // Note that this function assumes that the returned slack will be negative.
241 // This allow to DCHECK some assumptions on what coefficients can be reduced
242 // or not.
243 //
244 // TODO(user): Ideally the slack should be maitainable incrementally.
246 const Trail& trail, int trail_index);
247
248 // Relaxes the constraint so that:
249 // - ComputeSlackForTrailPrefix(trail, trail_index) == target;
250 // - All the variables that were propagated given the assignment < trail_index
251 // are still propagated.
252 //
253 // As a precondition, ComputeSlackForTrailPrefix(trail, trail_index) >= target
254 // Note that nothing happen if the slack is already equals to target.
255 //
256 // Algorithm: Let diff = slack - target (>= 0). We will split the constraint
257 // linear expression in 3 parts:
258 // - P1: the true variables (only the one assigned < trail_index).
259 // - P2: the other variables with a coeff > diff.
260 // Note that all these variables were the propagated ones.
261 // - P3: the other variables with a coeff <= diff.
262 // We can then transform P1 + P2 + P3 <= rhs_ into P1 + P2' <= rhs_ - diff
263 // Where P2' is the same sum as P2 with all the coefficient reduced by diff.
264 //
265 // Proof: Given the old constraint, we want to show that the relaxed one is
266 // always true. If all the variable in P2' are false, then
267 // P1 <= rhs_ - slack <= rhs_ - diff is always true. If at least one of the
268 // P2' variable is true, then P2 >= P2' + diff and we have
269 // P1 + P2' + diff <= P1 + P2 <= rhs_.
270 void ReduceSlackTo(const Trail& trail, int trail_index,
271 Coefficient initial_slack, Coefficient target);
272
273 // Copies this constraint into a vector<LiteralWithCoeff> representation.
274 void CopyIntoVector(std::vector<LiteralWithCoeff>* output);
275
276 // Adds a non-negative value to this constraint Rhs().
277 void AddToRhs(Coefficient value) {
278 CHECK_GE(value, 0);
279 rhs_ += value;
280 }
281 Coefficient Rhs() const { return rhs_; }
282 Coefficient MaxSum() const { return max_sum_; }
283
284 // Adds a term to this constraint. This is in the .h for efficiency.
285 // The encoding used internally is described below in the terms_ comment.
286 void AddTerm(Literal literal, Coefficient coeff) {
287 CHECK_GT(coeff, 0);
288 const BooleanVariable var = literal.Variable();
289 const Coefficient term_encoding = literal.IsPositive() ? coeff : -coeff;
290 if (literal != GetLiteral(var)) {
291 // The two terms are of opposite sign, a "cancelation" happens.
292 // We need to change the encoding of the lower magnitude term.
293 // - If term > 0, term . x -> term . (x - 1) + term
294 // - If term < 0, term . (x - 1) -> term . x - term
295 // In both cases, rhs -= abs(term).
296 rhs_ -= std::min(coeff, AbsCoefficient(terms_[var]));
297 max_sum_ += AbsCoefficient(term_encoding + terms_[var]) -
298 AbsCoefficient(terms_[var]);
299 } else {
300 // Both terms are of the same sign (or terms_[var] is zero).
301 max_sum_ += coeff;
302 }
303 CHECK_GE(max_sum_, 0) << "Overflow";
304 terms_[var] += term_encoding;
305 non_zeros_.Set(var);
306 }
307
308 // Returns the "cancelation" amount of AddTerm(literal, coeff).
309 Coefficient CancelationAmount(Literal literal, Coefficient coeff) const {
310 DCHECK_GT(coeff, 0);
311 const BooleanVariable var = literal.Variable();
312 if (literal == GetLiteral(var)) return Coefficient(0);
313 return std::min(coeff, AbsCoefficient(terms_[var]));
314 }
315
316 // Returns a set of positions that contains all the non-zeros terms of the
317 // constraint. Note that this set can also contains some zero terms.
318 const std::vector<BooleanVariable>& PossibleNonZeros() const {
319 return non_zeros_.PositionsSetAtLeastOnce();
320 }
321
322 // Returns a string representation of the constraint.
323 std::string DebugString();
324
325 private:
326 Coefficient AbsCoefficient(Coefficient a) const { return a > 0 ? a : -a; }
327
328 // Only used for DCHECK_EQ(max_sum_, ComputeMaxSum());
329 Coefficient ComputeMaxSum() const;
330
331 // The encoding is special:
332 // - If terms_[x] > 0, then the associated term is 'terms_[x] . x'
333 // - If terms_[x] < 0, then the associated term is 'terms_[x] . (x - 1)'
335
336 // The right hand side of the constraint (sum terms <= rhs_).
337 Coefficient rhs_;
338
339 // The constraint maximum sum (i.e. sum of the absolute term coefficients).
340 // Note that checking the integer overflow on this sum is enough.
341 Coefficient max_sum_;
342
343 // Contains the possibly non-zeros terms_ value.
345};
346
347// A simple "helper" class to enqueue a propagated literal on the trail and
348// keep the information needed to explain it when requested.
349class UpperBoundedLinearConstraint;
350
352 void Enqueue(Literal l, int source_trail_index,
354 reasons[trail->Index()] = {source_trail_index, ct};
355 trail->Enqueue(l, propagator_id);
356 }
357
358 // The propagator id of PbConstraints.
360
361 // A temporary vector to store the last conflict.
362 std::vector<Literal> conflict;
363
364 // Information needed to recover the reason of an Enqueue().
365 // Indexed by trail_index.
370 std::vector<ReasonInfo> reasons;
371};
372
373// This class contains half the propagation logic for a constraint of the form
374//
375// sum ci * li <= rhs, ci positive coefficients, li literals.
376//
377// The other half is implemented by the PbConstraints class below which takes
378// care of updating the 'threshold' value of this constraint:
379// - 'slack' is rhs minus all the ci of the variables xi assigned to
380// true. Note that it is not updated as soon as xi is assigned, but only
381// later when this assignment is "processed" by the PbConstraints class.
382// - 'threshold' is the distance from 'slack' to the largest coefficient ci
383// smaller or equal to slack. By definition, all the literals with
384// even larger coefficients that are yet 'processed' must be false for the
385// constraint to be satisfiable.
387 public:
388 // Takes a pseudo-Boolean formula in canonical form.
390 const std::vector<LiteralWithCoeff>& cst);
391
392 // Returns true if the given terms are the same as the one in this constraint.
393 bool HasIdenticalTerms(absl::Span<const LiteralWithCoeff> cst);
394 Coefficient Rhs() const { return rhs_; }
395
396 // Sets the rhs of this constraint. Compute the initial threshold value using
397 // only the literal with a trail index smaller than the given one. Enqueues on
398 // the trail any propagated literals.
399 //
400 // Returns false if the preconditions described in
401 // PbConstraints::AddConstraint() are not meet.
402 bool InitializeRhs(Coefficient rhs, int trail_index, Coefficient* threshold,
403 Trail* trail, PbConstraintsEnqueueHelper* helper);
404
405 // Tests for propagation and enqueues propagated literals on the trail.
406 // Returns false if a conflict was detected, in which case conflict is filled.
407 //
408 // Preconditions:
409 // - For each "processed" literal, the given threshold value must have been
410 // decreased by its associated coefficient in the constraint. It must now
411 // be stricly negative.
412 // - The given trail_index is the index of a true literal in the trail which
413 // just caused threshold to become stricly negative. All literals with
414 // smaller index must have been "processed". All assigned literals with
415 // greater trail index are not yet "processed".
416 //
417 // The threshold is updated to its new value.
418 bool Propagate(int trail_index, Coefficient* threshold, Trail* trail,
420
421 // Updates the given threshold and the internal state. This is the opposite of
422 // Propagate(). Each time a literal in unassigned, the threshold value must
423 // have been increased by its coefficient. This update the threshold to its
424 // new value.
425 void Untrail(Coefficient* threshold, int trail_index);
426
427 // Provided that the literal with given source_trail_index was the one that
428 // propagated the conflict or the literal we wants to explain, then this will
429 // compute the reason.
430 //
431 // Some properties of the reason:
432 // - Literals of level 0 are removed.
433 // - It will always contain the literal with given source_trail_index (except
434 // if it is of level 0).
435 // - We make the reason more compact by greedily removing terms with small
436 // coefficients that would not have changed the propagation.
437 //
438 // TODO(user): Maybe it is possible to derive a better reason by using more
439 // information. For instance one could use the mask of literals that are
440 // better to use during conflict minimization (namely the one already in the
441 // 1-UIP conflict).
442 void FillReason(const Trail& trail, int source_trail_index,
443 BooleanVariable propagated_variable,
444 std::vector<Literal>* reason);
445
446 // Same operation as SatSolver::ResolvePBConflict(), the only difference is
447 // that here the reason for var is *this.
448 void ResolvePBConflict(const Trail& trail, BooleanVariable var,
450 Coefficient* conflict_slack);
451
452 // Adds this pb constraint into the given mutable one.
453 //
454 // TODO(user): Provides instead an easy to use iterator over an
455 // UpperBoundedLinearConstraint and move this function to
456 // MutableUpperBoundedLinearConstraint.
458
459 // Compute the sum of the "cancelation" in AddTerm() if *this is added to
460 // the given conflict. The sum doesn't take into account literal assigned with
461 // a trail index smaller than the given one.
462 //
463 // Note(user): Currently, this is only used in DCHECKs.
464 Coefficient ComputeCancelation(
465 const Trail& trail, int trail_index,
467
468 // API to mark a constraint for deletion before actually deleting it.
469 void MarkForDeletion() { is_marked_for_deletion_ = true; }
470 bool is_marked_for_deletion() const { return is_marked_for_deletion_; }
471
472 // Only learned constraints are considered for deletion during the constraint
473 // cleanup phase. We also can't delete variables used as a reason.
474 void set_is_learned(bool is_learned) { is_learned_ = is_learned; }
475 bool is_learned() const { return is_learned_; }
476 bool is_used_as_a_reason() const { return first_reason_trail_index_ != -1; }
477
478 // Activity of the constraint. Only low activity constraint will be deleted
479 // during the constraint cleanup phase.
480 void set_activity(double activity) { activity_ = activity; }
481 double activity() const { return activity_; }
482
483 // Returns a fingerprint of the constraint linear expression (without rhs).
484 // This is used for duplicate detection.
485 uint64_t hash() const { return hash_; }
486
487 // This is used to get statistics of the number of literals inspected by
488 // a Propagate() call.
489 int already_propagated_end() const { return already_propagated_end_; }
490
491 private:
492 Coefficient GetSlackFromThreshold(Coefficient threshold) {
493 return (index_ < 0) ? threshold : coeffs_[index_] + threshold;
494 }
495 void Update(Coefficient slack, Coefficient* threshold) {
496 *threshold = (index_ < 0) ? slack : slack - coeffs_[index_];
497 already_propagated_end_ = starts_[index_ + 1];
498 }
499
500 // Constraint management fields.
501 // TODO(user): Rearrange and specify bit size to minimize memory usage.
502 bool is_marked_for_deletion_;
503 bool is_learned_;
504 int first_reason_trail_index_;
505 double activity_;
506
507 // Constraint propagation fields.
508 int index_;
509 int already_propagated_end_;
510
511 // In the internal representation, we merge the terms with the same
512 // coefficient.
513 // - literals_ contains all the literal of the constraint sorted by
514 // increasing coefficients.
515 // - coeffs_ contains unique increasing coefficients.
516 // - starts_[i] is the index in literals_ of the first literal with
517 // coefficient coeffs_[i].
518 std::vector<Coefficient> coeffs_;
519 std::vector<int> starts_;
520 std::vector<Literal> literals_;
521 Coefficient rhs_;
522
523 uint64_t hash_;
524};
525
526// Class responsible for managing a set of pseudo-Boolean constraints and their
527// propagation.
529 public:
531 : SatPropagator("PbConstraints"),
532 conflicting_constraint_index_(-1),
533 num_learned_constraint_before_cleanup_(0),
534 constraint_activity_increment_(1.0),
535 parameters_(model->GetOrCreate<SatParameters>()),
536 stats_("PbConstraints"),
537 num_constraint_lookups_(0),
538 num_inspected_constraint_literals_(0),
539 num_threshold_updates_(0) {
540 model->GetOrCreate<Trail>()->RegisterPropagator(this);
541 }
542
543 // This type is neither copyable nor movable.
544 PbConstraints(const PbConstraints&) = delete;
546 ~PbConstraints() override {
548 LOG(INFO) << stats_.StatString();
549 LOG(INFO) << "num_constraint_lookups_: " << num_constraint_lookups_;
550 LOG(INFO) << "num_threshold_updates_: " << num_threshold_updates_;
551 });
552 }
553
554 bool Propagate(Trail* trail) final;
555 void Untrail(const Trail& trail, int trail_index) final;
556 absl::Span<const Literal> Reason(const Trail& trail, int trail_index,
557 int64_t conflict_id) const final;
558
559 // Changes the number of variables.
560 void Resize(int num_variables) {
561 // Note that we avoid using up memory in the common case where there are no
562 // pb constraints at all. If there is 10 million variables, this vector
563 // alone will take 480 MB!
564 if (!constraints_.empty()) {
565 to_update_.resize(num_variables << 1);
566 enqueue_helper_.reasons.resize(num_variables);
567 }
568 }
569
570 // Adds a constraint in canonical form to the set of managed constraints. Note
571 // that this detects constraints with exactly the same terms. In this case,
572 // the constraint rhs is updated if the new one is lower or nothing is done
573 // otherwise.
574 //
575 // There are some preconditions, and the function will return false if they
576 // are not met. The constraint can be added when the trail is not empty,
577 // however given the current propagated assignment:
578 // - The constraint cannot be conflicting.
579 // - The constraint cannot have propagated at an earlier decision level.
580 bool AddConstraint(const std::vector<LiteralWithCoeff>& cst, Coefficient rhs,
581 Trail* trail);
582
583 // Same as AddConstraint(), but also marks the added constraint as learned
584 // so that it can be deleted during the constraint cleanup phase.
585 bool AddLearnedConstraint(const std::vector<LiteralWithCoeff>& cst,
586 Coefficient rhs, Trail* trail);
587
588 // Returns the number of constraints managed by this class.
589 int NumberOfConstraints() const { return constraints_.size(); }
590 bool IsEmpty() const final { return constraints_.empty(); }
591
592 // ConflictingConstraint() returns the last PB constraint that caused a
593 // conflict. Calling ClearConflictingConstraint() reset this to nullptr.
594 //
595 // TODO(user): This is a hack to get the PB conflict, because the rest of
596 // the solver API assume only clause conflict. Find a cleaner way?
597 void ClearConflictingConstraint() { conflicting_constraint_index_ = -1; }
599 if (conflicting_constraint_index_ == -1) return nullptr;
600 return constraints_[conflicting_constraint_index_.value()].get();
601 }
602
603 // Returns the underlying UpperBoundedLinearConstraint responsible for
604 // assigning the literal at given trail index.
605 UpperBoundedLinearConstraint* ReasonPbConstraint(int trail_index) const;
606
607 // Activity update functions.
608 // TODO(user): Remove duplication with other activity update functions.
610 void RescaleActivities(double scaling_factor);
612
613 // Only used for testing.
615 constraints_[index]->MarkForDeletion();
616 DeleteConstraintMarkedForDeletion();
617 }
618
619 // Some statistics.
620 int64_t num_constraint_lookups() const { return num_constraint_lookups_; }
622 return num_inspected_constraint_literals_;
623 }
624 int64_t num_threshold_updates() const { return num_threshold_updates_; }
625
626 private:
627 bool PropagateNext(Trail* trail);
628
629 // Same function as the clause related one is SatSolver().
630 // TODO(user): Remove duplication.
631 void ComputeNewLearnedConstraintLimit();
632 void DeleteSomeLearnedConstraintIfNeeded();
633
634 // Deletes all the UpperBoundedLinearConstraint for which
635 // is_marked_for_deletion() is true. This is relatively slow in O(number of
636 // terms in all constraints).
637 void DeleteConstraintMarkedForDeletion();
638
639 // Each constraint managed by this class is associated with an index.
640 // The set of indices is always [0, num_constraints_).
641 //
642 // Note(user): this complicate things during deletion, but the propagation is
643 // about two times faster with this implementation than one with direct
644 // pointer to an UpperBoundedLinearConstraint. The main reason for this is
645 // probably that the thresholds_ vector is a lot more efficient cache-wise.
646 DEFINE_STRONG_INDEX_TYPE(ConstraintIndex);
647 struct ConstraintIndexWithCoeff {
648 ConstraintIndexWithCoeff() = default; // Needed for vector.resize()
649 ConstraintIndexWithCoeff(bool n, ConstraintIndex i, Coefficient c)
650 : need_untrail_inspection(n), index(i), coefficient(c) {}
651 bool need_untrail_inspection;
652 ConstraintIndex index;
653 Coefficient coefficient;
654 };
655
656 // The set of all pseudo-boolean constraint managed by this class.
657 std::vector<std::unique_ptr<UpperBoundedLinearConstraint>> constraints_;
658
659 // The current value of the threshold for each constraints.
661
662 // For each literal, the list of all the constraints that contains it together
663 // with the literal coefficient in these constraints.
665 to_update_;
666
667 // Bitset used to optimize the Untrail() function.
668 SparseBitset<ConstraintIndex> to_untrail_;
669
670 // Pointers to the constraints grouped by their hash.
671 // This is used to find duplicate constraints by AddConstraint().
672 absl::flat_hash_map<int64_t, std::vector<UpperBoundedLinearConstraint*>>
673 possible_duplicates_;
674
675 // Helper to enqueue propagated literals on the trail and store their reasons.
676 PbConstraintsEnqueueHelper enqueue_helper_;
677
678 // Last conflicting PB constraint index. This is reset to -1 when
679 // ClearConflictingConstraint() is called.
680 ConstraintIndex conflicting_constraint_index_;
681
682 // Used for the constraint cleaning policy.
683 int target_number_of_learned_constraint_;
684 int num_learned_constraint_before_cleanup_;
685 double constraint_activity_increment_;
686
687 // Algorithm parameters.
688 SatParameters* parameters_;
689
690 // Some statistics.
691 mutable StatsGroup stats_;
692 int64_t num_constraint_lookups_;
693 int64_t num_inspected_constraint_literals_;
694 int64_t num_threshold_updates_;
695};
696
697// Boolean linear constraints can propagate a lot of literals at the same time.
698// As a result, all these literals will have exactly the same reason. It is
699// important to take advantage of that during the conflict
700// computation/minimization. On some problem, this can have a huge impact.
701//
702// TODO(user): With the new SAME_REASON_AS mechanism, this is more general so
703// move out of pb_constraint.
705 public:
707 : trail_(trail) {}
708
709 // This type is neither copyable nor movable.
711 delete;
713 const VariableWithSameReasonIdentifier&) = delete;
714
715 void Resize(int num_variables) {
716 first_variable_.resize(num_variables);
717 seen_.ClearAndResize(BooleanVariable(num_variables));
718 }
719
720 // Clears the cache. Call this before each conflict analysis.
721 void Clear() { seen_.ClearAll(); }
722
723 // Returns the first variable with exactly the same reason as 'var' on which
724 // this function was called since the last Clear(). Note that if no variable
725 // had the same reason, then var is returned.
726 BooleanVariable FirstVariableWithSameReason(BooleanVariable var) {
727 if (seen_[var]) return first_variable_[var];
728 const BooleanVariable reference_var =
730 if (reference_var == var) return var;
731 if (seen_[reference_var]) return first_variable_[reference_var];
732 seen_.Set(reference_var);
733 first_variable_[reference_var] = var;
734 return var;
735 }
736
737 private:
738 const Trail& trail_;
741};
742
743} // namespace sat
744} // namespace operations_research
745
746#endif // OR_TOOLS_SAT_PB_CONSTRAINT_H_
void ClearAndResize(IntegerType size)
Definition bitset.h:839
const std::vector< IntegerType > & PositionsSetAtLeastOnce() const
Definition bitset.h:878
void Set(IntegerType index)
Definition bitset.h:864
std::string StatString() const
Definition stats.cc:77
int NumConstraints() const
Getters. All the constraints are guaranteed to be in canonical form.
CanonicalBooleanLinearProblem & operator=(const CanonicalBooleanLinearProblem &)=delete
const std::vector< LiteralWithCoeff > & Constraint(int i) const
CanonicalBooleanLinearProblem(const CanonicalBooleanLinearProblem &)=delete
This type is neither copyable nor movable.
bool AddLinearConstraint(bool use_lower_bound, Coefficient lower_bound, bool use_upper_bound, Coefficient upper_bound, std::vector< LiteralWithCoeff > *cst)
std::string DebugString() const
Definition sat_base.h:100
LiteralIndex Index() const
Definition sat_base.h:91
std::string DebugString()
Returns a string representation of the constraint.
Coefficient ReduceCoefficientsAndComputeSlackForTrailPrefix(const Trail &trail, int trail_index)
Coefficient CancelationAmount(Literal literal, Coefficient coeff) const
Returns the "cancelation" amount of AddTerm(literal, coeff).
Coefficient GetCoefficient(BooleanVariable var) const
Returns the coefficient (>= 0) of the given variable.
Coefficient ComputeSlackForTrailPrefix(const Trail &trail, int trail_index) const
void AddToRhs(Coefficient value)
Adds a non-negative value to this constraint Rhs().
void CopyIntoVector(std::vector< LiteralWithCoeff > *output)
Copies this constraint into a vector<LiteralWithCoeff> representation.
const std::vector< BooleanVariable > & PossibleNonZeros() const
void ReduceSlackTo(const Trail &trail, int trail_index, Coefficient initial_slack, Coefficient target)
bool AddConstraint(const std::vector< LiteralWithCoeff > &cst, Coefficient rhs, Trail *trail)
PbConstraints & operator=(const PbConstraints &)=delete
int64_t num_constraint_lookups() const
Some statistics.
void Resize(int num_variables)
Changes the number of variables.
PbConstraints(const PbConstraints &)=delete
This type is neither copyable nor movable.
int NumberOfConstraints() const
Returns the number of constraints managed by this class.
UpperBoundedLinearConstraint * ReasonPbConstraint(int trail_index) const
absl::Span< const Literal > Reason(const Trail &trail, int trail_index, int64_t conflict_id) const final
void BumpActivity(UpperBoundedLinearConstraint *constraint)
bool AddLearnedConstraint(const std::vector< LiteralWithCoeff > &cst, Coefficient rhs, Trail *trail)
void RescaleActivities(double scaling_factor)
void DeleteConstraint(int index)
Only used for testing.
UpperBoundedLinearConstraint * ConflictingConstraint()
void Untrail(const Trail &trail, int trail_index) final
Base class for all the SAT constraints.
Definition sat_base.h:533
BooleanVariable ReferenceVarWithSameReason(BooleanVariable var) const
Definition sat_base.h:659
void Enqueue(Literal true_literal, int propagator_id)
Definition sat_base.h:317
void RegisterPropagator(SatPropagator *propagator)
Definition sat_base.h:650
void MarkForDeletion()
API to mark a constraint for deletion before actually deleting it.
void ResolvePBConflict(const Trail &trail, BooleanVariable var, MutableUpperBoundedLinearConstraint *conflict, Coefficient *conflict_slack)
UpperBoundedLinearConstraint(const std::vector< LiteralWithCoeff > &cst)
Takes a pseudo-Boolean formula in canonical form.
Coefficient ComputeCancelation(const Trail &trail, int trail_index, const MutableUpperBoundedLinearConstraint &conflict)
bool Propagate(int trail_index, Coefficient *threshold, Trail *trail, PbConstraintsEnqueueHelper *helper)
void AddToConflict(MutableUpperBoundedLinearConstraint *conflict)
void FillReason(const Trail &trail, int source_trail_index, BooleanVariable propagated_variable, std::vector< Literal > *reason)
void Untrail(Coefficient *threshold, int trail_index)
bool HasIdenticalTerms(absl::Span< const LiteralWithCoeff > cst)
Returns true if the given terms are the same as the one in this constraint.
bool InitializeRhs(Coefficient rhs, int trail_index, Coefficient *threshold, Trail *trail, PbConstraintsEnqueueHelper *helper)
BooleanVariable FirstVariableWithSameReason(BooleanVariable var)
VariableWithSameReasonIdentifier(const VariableWithSameReasonIdentifier &)=delete
This type is neither copyable nor movable.
VariableWithSameReasonIdentifier & operator=(const VariableWithSameReasonIdentifier &)=delete
void Clear()
Clears the cache. Call this before each conflict analysis.
void resize(size_type new_size)
int64_t a
Definition table.cc:44
const Constraint * ct
int64_t value
IntVar * var
double upper_bound
double lower_bound
GRBmodel * model
int literal
int index
void SimplifyCanonicalBooleanLinearConstraint(std::vector< LiteralWithCoeff > *cst, Coefficient *rhs)
bool ApplyLiteralMapping(const util_intops::StrongVector< LiteralIndex, LiteralIndex > &mapping, std::vector< LiteralWithCoeff > *cst, Coefficient *bound_shift, Coefficient *max_value)
Coefficient ComputeNegatedCanonicalRhs(Coefficient lower_bound, Coefficient bound_shift, Coefficient max_value)
std::ostream & operator<<(std::ostream &os, const BoolVar &var)
Definition cp_model.cc:89
bool BooleanLinearExpressionIsCanonical(absl::Span< const LiteralWithCoeff > cst)
Returns true iff the Boolean linear expression is in canonical form.
Coefficient ComputeCanonicalRhs(Coefficient upper_bound, Coefficient bound_shift, Coefficient max_value)
H AbslHashValue(H h, const IntVar &i)
– ABSL HASHING SUPPORT --------------------------------------------------—
Definition cp_model.h:515
const Coefficient kCoefficientMax(std::numeric_limits< Coefficient::ValueType >::max())
bool ComputeBooleanLinearExpressionCanonicalForm(std::vector< LiteralWithCoeff > *cst, Coefficient *bound_shift, Coefficient *max_value)
In SWIG mode, we don't want anything besides these top-level includes.
int64_t bound
#define IF_STATS_ENABLED(instructions)
Definition stats.h:417
#define DEFINE_STRONG_INT64_TYPE(integer_type_name)
#define DEFINE_STRONG_INDEX_TYPE(index_type_name)
Represents a term in a pseudo-Boolean formula.
LiteralWithCoeff(Literal l, Coefficient c)
bool operator==(const LiteralWithCoeff &other) const
void Enqueue(Literal l, int source_trail_index, UpperBoundedLinearConstraint *ct, Trail *trail)
int propagator_id
The propagator id of PbConstraints.
std::vector< Literal > conflict
A temporary vector to store the last conflict.