Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
linear_constraint.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 OR_TOOLS_SAT_LINEAR_CONSTRAINT_H_
15#define OR_TOOLS_SAT_LINEAR_CONSTRAINT_H_
16
17#include <algorithm>
18#include <cstdint>
19#include <cstring>
20#include <memory>
21#include <ostream>
22#include <string>
23#include <utility>
24#include <vector>
25
26#include "absl/base/attributes.h"
27#include "absl/log/check.h"
28#include "absl/strings/str_cat.h"
29#include "absl/types/span.h"
31#include "ortools/sat/integer.h"
33#include "ortools/sat/model.h"
37
38namespace operations_research {
39namespace sat {
40
41// One linear constraint on a set of Integer variables.
42// Important: there should be no duplicate variables.
43//
44// We also assume that we never have integer overflow when evaluating such
45// constraint at the ROOT node. This should be enforced by the checker for user
46// given constraints, and we must enforce it ourselves for the newly created
47// constraint. See ValidateLinearConstraintForOverflow().
49 IntegerValue lb;
50 IntegerValue ub;
51
52 // Rather than using two std::vector<> this class is optimized for memory
53 // consumption, given that most of our LinearConstraint are constructed once
54 // and for all.
55 //
56 // It is however up to clients to maintain the invariants that both vars
57 // and coeffs are properly allocated and of size num_terms.
58 //
59 // Also note that we did not add a copy constructor, to make sure that this is
60 // moved as often as possible. This allowed to optimize a few call site and so
61 // far we never copy this.
62 int num_terms = 0;
63 std::unique_ptr<IntegerVariable[]> vars;
64 std::unique_ptr<IntegerValue[]> coeffs;
65
66 LinearConstraint() = default;
67 LinearConstraint(IntegerValue _lb, IntegerValue _ub) : lb(_lb), ub(_ub) {}
68
69 // Resize the LinearConstraint to have space for num_terms. We always
70 // re-allocate if the size is different to always be tight in memory.
71 void resize(int size) {
72 if (size == num_terms) return;
73 IntegerVariable* tmp_vars = new IntegerVariable[size];
74 IntegerValue* tmp_coeffs = new IntegerValue[size];
75 const int to_copy = std::min(size, num_terms);
76 if (to_copy > 0) {
77 memcpy(tmp_vars, vars.get(), sizeof(IntegerVariable) * to_copy);
78 memcpy(tmp_coeffs, coeffs.get(), sizeof(IntegerValue) * to_copy);
79 }
80 num_terms = size;
81 vars.reset(tmp_vars);
82 coeffs.reset(tmp_coeffs);
83 }
84
85 std::string DebugString() const {
86 std::string result;
87 if (lb.value() > kMinIntegerValue) {
88 absl::StrAppend(&result, lb.value(), " <= ");
89 }
90 for (int i = 0; i < num_terms; ++i) {
91 absl::StrAppend(&result, i > 0 ? " " : "",
93 }
94 if (ub.value() < kMaxIntegerValue) {
95 absl::StrAppend(&result, " <= ", ub.value());
96 }
97 return result;
98 }
99
100 bool IsEqualIgnoringBounds(const LinearConstraint& other) const {
101 if (this->num_terms != other.num_terms) return false;
102 if (this->num_terms == 0) return true;
103 if (memcmp(this->vars.get(), other.vars.get(),
104 sizeof(IntegerVariable) * this->num_terms)) {
105 return false;
106 }
107 if (memcmp(this->coeffs.get(), other.coeffs.get(),
108 sizeof(IntegerValue) * this->num_terms)) {
109 return false;
110 }
111 return true;
112 }
113
114 bool operator==(const LinearConstraint& other) const {
115 if (this->lb != other.lb) return false;
116 if (this->ub != other.ub) return false;
117 return IsEqualIgnoringBounds(other);
118 }
119
120 absl::Span<const IntegerVariable> VarsAsSpan() const {
121 return absl::MakeSpan(vars.get(), num_terms);
122 }
123
124 absl::Span<const IntegerValue> CoeffsAsSpan() const {
125 return absl::MakeSpan(coeffs.get(), num_terms);
126 }
127};
128
129inline std::ostream& operator<<(std::ostream& os, const LinearConstraint& ct) {
130 os << ct.DebugString();
131 return os;
132}
133
134// Helper struct to model linear expression for lin_min/lin_max constraints. The
135// canonical expression should only contain positive coefficients.
137 std::vector<IntegerVariable> vars;
138 std::vector<IntegerValue> coeffs;
139 IntegerValue offset = IntegerValue(0);
140
141 // Return[s] the evaluation of the linear expression.
143 lp_values) const;
144
145 IntegerValue LevelZeroMin(IntegerTrail* integer_trail) const;
146
147 // Returns lower bound of linear expression using variable bounds of the
148 // variables in expression.
149 IntegerValue Min(const IntegerTrail& integer_trail) const;
150
151 // Returns upper bound of linear expression using variable bounds of the
152 // variables in expression.
153 IntegerValue Max(const IntegerTrail& integer_trail) const;
154
155 std::string DebugString() const;
156};
157
158// Returns the same expression in the canonical form (all positive
159// coefficients).
161
162// Makes sure that any of our future computation on this constraint will not
163// cause overflow. We use the level zero bounds and use the same definition as
164// in PossibleIntegerOverflow() in the cp_model.proto checker.
165//
166// Namely, the sum of positive terms, the sum of negative terms and their
167// difference shouldn't overflow. Note that we don't validate the rhs, but if
168// the bounds are properly relaxed, then this shouldn't cause any issues.
169//
170// Note(user): We should avoid doing this test too often as it can be slow. At
171// least do not do it more than once on each constraint.
173 const IntegerTrail& integer_trail);
174
175// Preserves canonicality.
177
178// Returns the same expression with positive variables.
180
181// Returns the coefficient of the variable in the expression. Works in linear
182// time.
183// Note: GetCoefficient(NegationOf(var, expr)) == -GetCoefficient(var, expr).
184IntegerValue GetCoefficient(IntegerVariable var, const LinearExpression& expr);
185IntegerValue GetCoefficientOfPositiveVar(IntegerVariable var,
186 const LinearExpression& expr);
187
188// Allow to build a LinearConstraint while making sure there is no duplicate
189// variables. Note that we do not simplify literal/variable that are currently
190// fixed here.
191//
192// All the functions manipulate a linear expression with an offset. The final
193// constraint bounds will include this offset.
194//
195// TODO(user): Rename to LinearExpressionBuilder?
197 public:
198 // We support "sticky" kMinIntegerValue for lb and kMaxIntegerValue for ub
199 // for one-sided constraints.
200 //
201 // Assumes that the 'model' has IntegerEncoder. The bounds can either be
202 // specified at construction or during the Build() call.
203 explicit LinearConstraintBuilder(const Model* model)
204 : encoder_(model->Get<IntegerEncoder>()), lb_(0), ub_(0) {}
206 : encoder_(encoder), lb_(0), ub_(0) {}
207 LinearConstraintBuilder(const Model* model, IntegerValue lb, IntegerValue ub)
208 : encoder_(model->Get<IntegerEncoder>()), lb_(lb), ub_(ub) {}
209 LinearConstraintBuilder(IntegerEncoder* encoder, IntegerValue lb,
210 IntegerValue ub)
211 : encoder_(encoder), lb_(lb), ub_(ub) {}
212
213 // Warning: this version without encoder cannot be used to add literals, so
214 // one shouldn't call AddLiteralTerm() on it. All other functions works.
215 //
216 // TODO(user): Have a subclass so we can enforce that a caller using
217 // AddLiteralTerm() must construct the Builder with an encoder.
218 LinearConstraintBuilder() : encoder_(nullptr), lb_(0), ub_(0) {}
219 LinearConstraintBuilder(IntegerValue lb, IntegerValue ub)
220 : encoder_(nullptr), lb_(lb), ub_(ub) {}
221
222 // Adds the corresponding term to the current linear expression.
223 void AddConstant(IntegerValue value);
224 void AddTerm(IntegerVariable var, IntegerValue coeff);
225 void AddTerm(AffineExpression expr, IntegerValue coeff);
226 void AddLinearExpression(const LinearExpression& expr);
227 void AddLinearExpression(const LinearExpression& expr, IntegerValue coeff);
228
229 // Add the corresponding decomposed products (obtained from
230 // TryToDecomposeProduct). The code assumes all literals to be in an
231 // exactly_one relation.
232 // It returns false if one literal does not have an integer view, as it
233 // actually calls AddLiteralTerm().
234 ABSL_MUST_USE_RESULT bool AddDecomposedProduct(
235 absl::Span<const LiteralValueValue> product);
236
237 // Add literal * coeff to the constaint. Returns false and do nothing if the
238 // given literal didn't have an integer view.
239 ABSL_MUST_USE_RESULT bool AddLiteralTerm(
240 Literal lit, IntegerValue coeff = IntegerValue(1));
241
242 // Add an under linearization of the product of two affine expressions.
243 // If at least one of them is fixed, then we add the exact product (which is
244 // linear). Otherwise, we use McCormick relaxation:
245 // left * right = (left_min + delta_left) * (right_min + delta_right) =
246 // left_min * right_min + delta_left * right_min +
247 // delta_right * left_min + delta_left * delta_right
248 // which is >= (by ignoring the quatratic term)
249 // right_min * left + left_min * right - right_min * left_min
250 //
251 // TODO(user): We could use (max - delta) instead of (min + delta) for each
252 // expression instead. This would depend on the LP value of the left and
253 // right.
255 IntegerTrail* integer_trail,
256 bool* is_quadratic = nullptr);
257
258 // Clears all added terms and constants. Keeps the original bounds.
259 void Clear() {
260 offset_ = IntegerValue(0);
261 terms_.clear();
262 }
263
264 // Reset the bounds passed at construction time.
265 void ResetBounds(IntegerValue lb, IntegerValue ub) {
266 lb_ = lb;
267 ub_ = ub;
268 }
269
270 // Builds and returns the corresponding constraint in a canonical form.
271 // All the IntegerVariable will be positive and appear in increasing index
272 // order.
273 //
274 // The bounds can be changed here or taken at construction.
275 //
276 // TODO(user): this doesn't invalidate the builder object, but if one wants
277 // to do a lot of dynamic editing to the constraint, then then underlying
278 // algorithm needs to be optimized for that.
280 LinearConstraint BuildConstraint(IntegerValue lb, IntegerValue ub);
281
282 // Similar to BuildConstraint() but make sure we don't overflow while we merge
283 // terms referring to the same variables.
284 bool BuildIntoConstraintAndCheckOverflow(IntegerValue lb, IntegerValue ub,
285 LinearConstraint* ct);
286
287 // Returns the linear expression part of the constraint only, without the
288 // bounds.
290
291 private:
292 const IntegerEncoder* encoder_;
293 IntegerValue lb_;
294 IntegerValue ub_;
295
296 IntegerValue offset_ = IntegerValue(0);
297
298 // Initially we push all AddTerm() here, and during Build() we merge terms
299 // on the same variable.
300 std::vector<std::pair<IntegerVariable, IntegerValue>> terms_;
301};
302
303// Returns the activity of the given constraint. That is the current value of
304// the linear terms.
305double ComputeActivity(
306 const LinearConstraint& constraint,
308
309// Tests for possible overflow in the given linear constraint used for the
310// linear relaxation. This is a bit relaxed compared to what we require for
311// generic linear constraint that are used in our CP propagators.
312//
313// If this check pass, our constraint should be safe to use in our simplication
314// code, our cut computation, etc...
315bool PossibleOverflow(const IntegerTrail& integer_trail,
316 const LinearConstraint& constraint);
317
318// Returns sqrt(sum square(coeff)).
319double ComputeL2Norm(const LinearConstraint& constraint);
320
321// Returns the maximum absolute value of the coefficients.
322IntegerValue ComputeInfinityNorm(const LinearConstraint& constraint);
323
324// Returns the scalar product of given constraint coefficients. This method
325// assumes that the constraint variables are in sorted order.
326double ScalarProduct(const LinearConstraint& constraint1,
327 const LinearConstraint& constraint2);
328
329// Computes the GCD of the constraint coefficient, and divide them by it. This
330// also tighten the constraint bounds assumming all the variables are integer.
331void DivideByGCD(LinearConstraint* constraint);
332
333// Removes the entries with a coefficient of zero.
334void RemoveZeroTerms(LinearConstraint* constraint);
335
336// Makes all coefficients positive by transforming a variable to its negation.
337void MakeAllCoefficientsPositive(LinearConstraint* constraint);
338
339// Makes all variables "positive" by transforming a variable to its negation.
340void MakeAllVariablesPositive(LinearConstraint* constraint);
341
342// Returns false if duplicate variables are found in ct.
343bool NoDuplicateVariable(const LinearConstraint& ct);
344
345// Sorts and merges duplicate IntegerVariable in the given "terms".
346// Fills the given LinearConstraint or LinearExpression with the result.
348 std::vector<std::pair<IntegerVariable, IntegerValue>>* terms,
349 LinearExpression* output) {
350 output->vars.clear();
351 output->coeffs.clear();
352
353 // Sort and add coeff of duplicate variables. Note that a variable and
354 // its negation will appear one after another in the natural order.
355 std::sort(terms->begin(), terms->end());
356 IntegerVariable previous_var = kNoIntegerVariable;
357 IntegerValue current_coeff(0);
358 for (const std::pair<IntegerVariable, IntegerValue>& entry : *terms) {
359 if (previous_var == entry.first) {
360 current_coeff += entry.second;
361 } else if (previous_var == NegationOf(entry.first)) {
362 current_coeff -= entry.second;
363 } else {
364 if (current_coeff != 0) {
365 output->vars.push_back(previous_var);
366 output->coeffs.push_back(current_coeff);
367 }
368 previous_var = entry.first;
369 current_coeff = entry.second;
370 }
371 }
372 if (current_coeff != 0) {
373 output->vars.push_back(previous_var);
374 output->coeffs.push_back(current_coeff);
375 }
376}
377
379 std::vector<std::pair<IntegerVariable, IntegerValue>>* terms,
380 LinearConstraint* output) {
381 // Sort and add coeff of duplicate variables. Note that a variable and
382 // its negation will appear one after another in the natural order.
383 int new_size = 0;
384 output->resize(terms->size());
385 std::sort(terms->begin(), terms->end());
386 IntegerVariable previous_var = kNoIntegerVariable;
387 IntegerValue current_coeff(0);
388 for (const std::pair<IntegerVariable, IntegerValue>& entry : *terms) {
389 if (previous_var == entry.first) {
390 current_coeff += entry.second;
391 } else if (previous_var == NegationOf(entry.first)) {
392 current_coeff -= entry.second;
393 } else {
394 if (current_coeff != 0) {
395 output->vars[new_size] = previous_var;
396 output->coeffs[new_size] = current_coeff;
397 ++new_size;
398 }
399 previous_var = entry.first;
400 current_coeff = entry.second;
401 }
402 }
403 if (current_coeff != 0) {
404 output->vars[new_size] = previous_var;
405 output->coeffs[new_size] = current_coeff;
406 ++new_size;
407 }
408 output->resize(new_size);
409}
410
412 std::vector<std::pair<IntegerVariable, IntegerValue>>* terms,
413 LinearConstraint* output) {
414 // Sort and add coeff of duplicate variables. Note that a variable and
415 // its negation will appear one after another in the natural order.
416 int new_size = 0;
417 output->resize(terms->size());
418 std::sort(terms->begin(), terms->end());
419 IntegerVariable previous_var = kNoIntegerVariable;
420 int64_t current_coeff = 0;
421 for (const std::pair<IntegerVariable, IntegerValue>& entry : *terms) {
422 DCHECK(VariableIsPositive(entry.first));
423 if (previous_var == entry.first) {
424 if (AddIntoOverflow(entry.second.value(), &current_coeff)) {
425 return false;
426 }
427 } else {
428 if (current_coeff != 0) {
429 output->vars[new_size] = previous_var;
430 output->coeffs[new_size] = current_coeff;
431 ++new_size;
432 }
433 previous_var = entry.first;
434 current_coeff = entry.second.value();
435 }
436 }
437 if (current_coeff != 0) {
438 output->vars[new_size] = previous_var;
439 output->coeffs[new_size] = current_coeff;
440 ++new_size;
441 }
442 output->resize(new_size);
443 return true;
444}
445
446} // namespace sat
447} // namespace operations_research
448
449#endif // OR_TOOLS_SAT_LINEAR_CONSTRAINT_H_
void AddQuadraticLowerBound(AffineExpression left, AffineExpression right, IntegerTrail *integer_trail, bool *is_quadratic=nullptr)
ABSL_MUST_USE_RESULT bool AddLiteralTerm(Literal lit, IntegerValue coeff=IntegerValue(1))
void ResetBounds(IntegerValue lb, IntegerValue ub)
Reset the bounds passed at construction time.
LinearConstraintBuilder(IntegerEncoder *encoder, IntegerValue lb, IntegerValue ub)
void AddTerm(IntegerVariable var, IntegerValue coeff)
void AddLinearExpression(const LinearExpression &expr)
void AddConstant(IntegerValue value)
Adds the corresponding term to the current linear expression.
void Clear()
Clears all added terms and constants. Keeps the original bounds.
LinearConstraintBuilder(const Model *model, IntegerValue lb, IntegerValue ub)
LinearConstraint BuildConstraint(IntegerValue lb, IntegerValue ub)
LinearConstraintBuilder(IntegerValue lb, IntegerValue ub)
bool BuildIntoConstraintAndCheckOverflow(IntegerValue lb, IntegerValue ub, LinearConstraint *ct)
ABSL_MUST_USE_RESULT bool AddDecomposedProduct(absl::Span< const LiteralValueValue > product)
double ComputeActivity(const LinearConstraint &constraint, const util_intops::StrongVector< IntegerVariable, double > &values)
void DivideByGCD(LinearConstraint *constraint)
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
double ComputeL2Norm(const LinearConstraint &ct)
Returns sqrt(sum square(coeff)).
void RemoveZeroTerms(LinearConstraint *constraint)
Removes the entries with a coefficient of zero.
IntegerValue ComputeInfinityNorm(const LinearConstraint &ct)
Returns the maximum absolute value of the coefficients.
std::string IntegerTermDebugString(IntegerVariable var, IntegerValue coeff)
std::vector< IntegerVariable > NegationOf(absl::Span< const IntegerVariable > vars)
Returns the vector of the negated variables.
Definition integer.cc:52
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue.value())
const IntegerVariable kNoIntegerVariable(-1)
bool PossibleOverflow(const IntegerTrail &integer_trail, const LinearConstraint &constraint)
void CleanTermsAndFillConstraint(std::vector< std::pair< IntegerVariable, IntegerValue > > *terms, LinearExpression *output)
void MakeAllCoefficientsPositive(LinearConstraint *constraint)
Makes all coefficients positive by transforming a variable to its negation.
std::ostream & operator<<(std::ostream &os, const BoolVar &var)
Definition cp_model.cc:89
LinearExpression CanonicalizeExpr(const LinearExpression &expr)
bool MergePositiveVariableTermsAndCheckForOverflow(std::vector< std::pair< IntegerVariable, IntegerValue > > *terms, LinearConstraint *output)
LinearExpression PositiveVarExpr(const LinearExpression &expr)
Returns the same expression with positive variables.
IntegerValue GetCoefficient(const IntegerVariable var, const LinearExpression &expr)
void MakeAllVariablesPositive(LinearConstraint *constraint)
Makes all variables "positive" by transforming a variable to its negation.
IntegerValue GetCoefficientOfPositiveVar(const IntegerVariable var, const LinearExpression &expr)
bool ValidateLinearConstraintForOverflow(const LinearConstraint &constraint, const IntegerTrail &integer_trail)
bool NoDuplicateVariable(const LinearConstraint &ct)
Returns false if duplicate variables are found in ct.
bool VariableIsPositive(IntegerVariable i)
double ScalarProduct(const LinearConstraint &ct1, const LinearConstraint &ct2)
In SWIG mode, we don't want anything besides these top-level includes.
bool AddIntoOverflow(int64_t x, int64_t *y)
std::unique_ptr< IntegerValue[]> coeffs
std::unique_ptr< IntegerVariable[]> vars
absl::Span< const IntegerValue > CoeffsAsSpan() const
absl::Span< const IntegerVariable > VarsAsSpan() const
bool IsEqualIgnoringBounds(const LinearConstraint &other) const
bool operator==(const LinearConstraint &other) const
LinearConstraint(IntegerValue _lb, IntegerValue _ub)
IntegerValue LevelZeroMin(IntegerTrail *integer_trail) const
IntegerValue Min(const IntegerTrail &integer_trail) const
double LpValue(const util_intops::StrongVector< IntegerVariable, double > &lp_values) const
Return[s] the evaluation of the linear expression.
IntegerValue Max(const IntegerTrail &integer_trail) const