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