Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
linear_constraint.cc
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
15
16#include <algorithm>
17#include <cmath>
18#include <cstddef>
19#include <cstdint>
20#include <limits>
21#include <string>
22#include <utility>
23#include <vector>
24
25#include "absl/base/attributes.h"
26#include "absl/container/flat_hash_set.h"
27#include "absl/log/check.h"
28#include "absl/strings/str_cat.h"
29#include "absl/types/span.h"
32#include "ortools/sat/integer.h"
37
38namespace operations_research {
39namespace sat {
40
41void LinearConstraintBuilder::AddTerm(IntegerVariable var, IntegerValue coeff) {
42 if (coeff == 0) return;
43 // We can either add var or NegationOf(var), and we always choose the
44 // positive one.
45 if (VariableIsPositive(var)) {
46 terms_.push_back({var, coeff});
47 } else {
48 terms_.push_back({NegationOf(var), -coeff});
49 }
50}
51
53 IntegerValue coeff) {
54 if (coeff == 0) return;
55 // We can either add var or NegationOf(var), and we always choose the
56 // positive one.
57 if (expr.var != kNoIntegerVariable) {
58 if (VariableIsPositive(expr.var)) {
59 terms_.push_back({expr.var, coeff * expr.coeff});
60 } else {
61 terms_.push_back({NegationOf(expr.var), -coeff * expr.coeff});
62 }
63 }
64 DCHECK(!ProdOverflow(coeff, expr.constant));
65 offset_ += coeff * expr.constant;
66}
67
69 const LinearExpression& expr) {
70 AddLinearExpression(expr, IntegerValue(1));
71}
72
74 IntegerValue coeff) {
75 for (int i = 0; i < expr.vars.size(); ++i) {
76 // We must use positive variables.
77 if (VariableIsPositive(expr.vars[i])) {
78 terms_.push_back({expr.vars[i], expr.coeffs[i] * coeff});
79 } else {
80 terms_.push_back({NegationOf(expr.vars[i]), -expr.coeffs[i] * coeff});
81 }
82 }
83 offset_ += expr.offset * coeff;
84}
85
87 absl::Span<const LiteralValueValue> product) {
88 if (product.empty()) return true;
89
90 IntegerValue product_min = kMaxIntegerValue;
91 // TODO(user): Checks the value of literals.
92 for (const LiteralValueValue& term : product) {
93 product_min = std::min(product_min, term.left_value * term.right_value);
94 }
95
96 for (const LiteralValueValue& term : product) {
97 IntegerValue coeff = term.left_value * term.right_value - product_min;
98 if (coeff == 0) continue;
99 if (!AddLiteralTerm(term.literal, coeff)) {
100 return false;
101 }
102 }
103 AddConstant(product_min);
104 return true;
105}
106
108 AffineExpression left, AffineExpression right, IntegerTrail* integer_trail,
109 bool* is_quadratic) {
110 if (integer_trail->IsFixed(left)) {
111 AddTerm(right, integer_trail->FixedValue(left));
112 } else if (integer_trail->IsFixed(right)) {
113 AddTerm(left, integer_trail->FixedValue(right));
114 } else {
115 const IntegerValue left_min = integer_trail->LowerBound(left);
116 const IntegerValue right_min = integer_trail->LowerBound(right);
117 AddTerm(left, right_min);
118 AddTerm(right, left_min);
119 // Substract the energy counted twice.
120 AddConstant(-left_min * right_min);
121 if (is_quadratic != nullptr) *is_quadratic = true;
122 }
123}
124
125void LinearConstraintBuilder::AddConstant(IntegerValue value) {
126 offset_ += value;
127}
128
130 Literal lit, IntegerValue coeff) {
131 DCHECK(encoder_ != nullptr);
132 IntegerVariable var = kNoIntegerVariable;
133 bool view_is_direct = true;
134 if (!encoder_->LiteralOrNegationHasView(lit, &var, &view_is_direct)) {
135 return false;
136 }
137
138 if (view_is_direct) {
139 AddTerm(var, coeff);
140 } else {
141 AddTerm(var, -coeff);
142 offset_ += coeff;
143 }
144 return true;
145}
146
150
152 IntegerValue ub) {
153 LinearConstraint result;
154 result.lb = lb > kMinIntegerValue ? lb - offset_ : lb;
155 result.ub = ub < kMaxIntegerValue ? ub - offset_ : ub;
156 CleanTermsAndFillConstraint(&terms_, &result);
157 return result;
158}
159
161 IntegerValue lb, IntegerValue ub, LinearConstraint* ct) {
162 ct->lb = lb > kMinIntegerValue ? lb - offset_ : lb;
163 ct->ub = ub < kMaxIntegerValue ? ub - offset_ : ub;
165}
166
168 LinearExpression result;
169 CleanTermsAndFillConstraint(&terms_, &result);
170 result.offset = offset_;
171 return result;
172}
173
176 const double activity = ComputeActivity(*this, lp_values);
177 const double violation =
178 std::max(activity - ToDouble(ub), ToDouble(lb) - activity);
179 if (violation <= 0.0) return 0.0;
180
181 const double l2_norm = ComputeL2Norm(*this);
182 return violation / l2_norm;
183}
184
186 const LinearConstraint& constraint,
188 int i = 0;
189 const int size = constraint.num_terms;
190 const int shifted_size = size - 3;
191 double a0 = 0.0;
192 double a1 = 0.0;
193 double a2 = 0.0;
194 double a3 = 0.0;
195 const double* view = values.data();
196 for (; i < shifted_size; i += 4) {
197 a0 += static_cast<double>(constraint.coeffs[i].value()) *
198 view[constraint.vars[i].value()];
199 a1 += static_cast<double>(constraint.coeffs[i + 1].value()) *
200 view[constraint.vars[i + 1].value()];
201 a2 += static_cast<double>(constraint.coeffs[i + 2].value()) *
202 view[constraint.vars[i + 2].value()];
203 a3 += static_cast<double>(constraint.coeffs[i + 3].value()) *
204 view[constraint.vars[i + 3].value()];
205 }
206 double activity = a0 + a1 + a2 + a3;
207 if (i < size) {
208 activity += static_cast<double>(constraint.coeffs[i].value()) *
209 view[constraint.vars[i].value()];
210 if (i + 1 < size) {
211 activity += static_cast<double>(constraint.coeffs[i + 1].value()) *
212 view[constraint.vars[i + 1].value()];
213 if (i + 2 < size) {
214 activity += static_cast<double>(constraint.coeffs[i + 2].value()) *
215 view[constraint.vars[i + 2].value()];
216 }
217 }
218 }
219 return activity;
220}
221
223 double sum = 0.0;
224 for (int i = 0; i < ct.num_terms; ++i) {
225 sum += ToDouble(ct.coeffs[i]) * ToDouble(ct.coeffs[i]);
226 }
227 return std::sqrt(sum);
228}
229
230IntegerValue ComputeInfinityNorm(const LinearConstraint& ct) {
231 IntegerValue result(0);
232 for (int i = 0; i < ct.num_terms; ++i) {
233 result = std::max(result, IntTypeAbs(ct.coeffs[i]));
234 }
235 return result;
236}
237
238double ScalarProduct(const LinearConstraint& ct1, const LinearConstraint& ct2) {
239 if (ct1.num_terms == 0 || ct2.num_terms == 0) return 0.0;
240 DCHECK(std::is_sorted(ct1.vars.get(), ct1.vars.get() + ct1.num_terms));
241 DCHECK(std::is_sorted(ct2.vars.get(), ct2.vars.get() + ct2.num_terms));
242 double scalar_product = 0.0;
243 int index_1 = 0;
244 int index_2 = 0;
245 IntegerVariable var1 = ct1.vars[index_1];
246 IntegerVariable var2 = ct2.vars[index_2];
247 while (true) {
248 if (var1 == var2) {
249 scalar_product += static_cast<double>(ct1.coeffs[index_1].value()) *
250 static_cast<double>(ct2.coeffs[index_2].value());
251 if (++index_1 == ct1.num_terms) break;
252 if (++index_2 == ct2.num_terms) break;
253 var1 = ct1.vars[index_1];
254 var2 = ct2.vars[index_2];
255 } else if (var1 > var2) {
256 if (++index_2 == ct2.num_terms) break;
257 var2 = ct2.vars[index_2];
258 } else {
259 if (++index_1 == ct1.num_terms) break;
260 var1 = ct1.vars[index_1];
261 }
262 }
263 return scalar_product;
264}
265
266namespace {
267
268// TODO(user): Template for any integer type and expose this?
269IntegerValue ComputeGcd(absl::Span<const IntegerValue> values) {
270 if (values.empty()) return IntegerValue(1);
271 int64_t gcd = 0;
272 for (const IntegerValue value : values) {
273 gcd = MathUtil::GCD64(gcd, std::abs(value.value()));
274 if (gcd == 1) break;
275 }
276 if (gcd < 0) return IntegerValue(1); // Can happen with kint64min.
277 return IntegerValue(gcd);
278}
279
280} // namespace
281
282void DivideByGCD(LinearConstraint* constraint) {
283 if (constraint->num_terms == 0) return;
284 const IntegerValue gcd = ComputeGcd(
285 {constraint->coeffs.get(), static_cast<size_t>(constraint->num_terms)});
286 if (gcd == 1) return;
287
288 if (constraint->lb > kMinIntegerValue) {
289 constraint->lb = CeilRatio(constraint->lb, gcd);
290 }
291 if (constraint->ub < kMaxIntegerValue) {
292 constraint->ub = FloorRatio(constraint->ub, gcd);
293 }
294 for (int i = 0; i < constraint->num_terms; ++i) {
295 constraint->coeffs[i] /= gcd;
296 }
297}
298
300 const int size = constraint->num_terms;
301 for (int i = 0; i < size; ++i) {
302 const IntegerVariable var = constraint->vars[i];
303 if (!VariableIsPositive(var)) {
304 constraint->coeffs[i] = -constraint->coeffs[i];
305 constraint->vars[i] = NegationOf(var);
306 }
307 }
308}
309
312 double result = ToDouble(offset);
313 for (int i = 0; i < vars.size(); ++i) {
314 result += ToDouble(coeffs[i]) * lp_values[vars[i]];
315 }
316 return result;
317}
318
319IntegerValue LinearExpression::LevelZeroMin(IntegerTrail* integer_trail) const {
320 IntegerValue result = offset;
321 for (int i = 0; i < vars.size(); ++i) {
322 DCHECK_GE(coeffs[i], 0);
323 result += coeffs[i] * integer_trail->LevelZeroLowerBound(vars[i]);
324 }
325 return result;
326}
327
328IntegerValue LinearExpression::Min(const IntegerTrail& integer_trail) const {
329 IntegerValue result = offset;
330 for (int i = 0; i < vars.size(); ++i) {
331 if (coeffs[i] > 0) {
332 result += coeffs[i] * integer_trail.LowerBound(vars[i]);
333 } else {
334 result += coeffs[i] * integer_trail.UpperBound(vars[i]);
335 }
336 }
337 return result;
338}
339
340IntegerValue LinearExpression::Max(const IntegerTrail& integer_trail) const {
341 IntegerValue result = offset;
342 for (int i = 0; i < vars.size(); ++i) {
343 if (coeffs[i] > 0) {
344 result += coeffs[i] * integer_trail.UpperBound(vars[i]);
345 } else {
346 result += coeffs[i] * integer_trail.LowerBound(vars[i]);
347 }
348 }
349 return result;
350}
351
352std::string LinearExpression::DebugString() const {
353 if (vars.empty()) return absl::StrCat(offset.value());
354 std::string result;
355 for (int i = 0; i < vars.size(); ++i) {
356 absl::StrAppend(&result, i > 0 ? " " : "",
358 }
359 if (offset != 0) {
360 absl::StrAppend(&result, " + ", offset.value());
361 }
362 return result;
363}
364
366 absl::flat_hash_set<IntegerVariable> seen_variables;
367 const int size = ct.num_terms;
368 for (int i = 0; i < size; ++i) {
369 if (VariableIsPositive(ct.vars[i])) {
370 if (!seen_variables.insert(ct.vars[i]).second) return false;
371 } else {
372 if (!seen_variables.insert(NegationOf(ct.vars[i])).second) return false;
373 }
374 }
375 return true;
376}
377
379 LinearExpression canonical_expr;
380 canonical_expr.offset = expr.offset;
381 for (int i = 0; i < expr.vars.size(); ++i) {
382 if (expr.coeffs[i] < 0) {
383 canonical_expr.vars.push_back(NegationOf(expr.vars[i]));
384 canonical_expr.coeffs.push_back(-expr.coeffs[i]);
385 } else {
386 canonical_expr.vars.push_back(expr.vars[i]);
387 canonical_expr.coeffs.push_back(expr.coeffs[i]);
388 }
389 }
390 return canonical_expr;
391}
392
393// TODO(user): Avoid duplication with PossibleIntegerOverflow() in the checker?
394// At least make sure the code is the same.
396 const IntegerTrail& integer_trail) {
397 int64_t positive_sum(0);
398 int64_t negative_sum(0);
399 for (int i = 0; i < constraint.num_terms; ++i) {
400 const IntegerVariable var = constraint.vars[i];
401 const IntegerValue coeff = constraint.coeffs[i];
402 const IntegerValue lb = integer_trail.LevelZeroLowerBound(var);
403 const IntegerValue ub = integer_trail.LevelZeroUpperBound(var);
404
405 int64_t min_prod = CapProd(coeff.value(), lb.value());
406 int64_t max_prod = CapProd(coeff.value(), ub.value());
407 if (min_prod > max_prod) std::swap(min_prod, max_prod);
408
409 positive_sum = CapAdd(positive_sum, std::max(int64_t{0}, max_prod));
410 negative_sum = CapAdd(negative_sum, std::min(int64_t{0}, min_prod));
411 }
412
413 const int64_t limit = std::numeric_limits<int64_t>::max();
414 if (positive_sum >= limit) return false;
415 if (negative_sum <= -limit) return false;
416 if (CapSub(positive_sum, negative_sum) >= limit) return false;
417
418 return true;
419}
420
422 LinearExpression result;
423 result.vars = NegationOf(expr.vars);
424 result.coeffs = expr.coeffs;
425 result.offset = -expr.offset;
426 return result;
427}
428
430 LinearExpression result;
431 result.offset = expr.offset;
432 for (int i = 0; i < expr.vars.size(); ++i) {
433 if (VariableIsPositive(expr.vars[i])) {
434 result.vars.push_back(expr.vars[i]);
435 result.coeffs.push_back(expr.coeffs[i]);
436 } else {
437 result.vars.push_back(NegationOf(expr.vars[i]));
438 result.coeffs.push_back(-expr.coeffs[i]);
439 }
440 }
441 return result;
442}
443
444IntegerValue GetCoefficient(const IntegerVariable var,
445 const LinearExpression& expr) {
446 for (int i = 0; i < expr.vars.size(); ++i) {
447 if (expr.vars[i] == var) {
448 return expr.coeffs[i];
449 } else if (expr.vars[i] == NegationOf(var)) {
450 return -expr.coeffs[i];
451 }
452 }
453 return IntegerValue(0);
454}
455
456IntegerValue GetCoefficientOfPositiveVar(const IntegerVariable var,
457 const LinearExpression& expr) {
458 CHECK(VariableIsPositive(var));
459 for (int i = 0; i < expr.vars.size(); ++i) {
460 if (expr.vars[i] == var) {
461 return expr.coeffs[i];
462 }
463 }
464 return IntegerValue(0);
465}
466
467bool PossibleOverflow(const IntegerTrail& integer_trail,
468 const LinearConstraint& constraint) {
469 IntegerValue min_activity(0);
470 IntegerValue max_activity(0);
471 const int size = constraint.num_terms;
472 for (int i = 0; i < size; ++i) {
473 const IntegerVariable var = constraint.vars[i];
474 const IntegerValue coeff = constraint.coeffs[i];
475 CHECK_NE(coeff, 0);
476 const IntegerValue lb = integer_trail.LevelZeroLowerBound(var);
477 const IntegerValue ub = integer_trail.LevelZeroUpperBound(var);
478 if (coeff > 0) {
479 if (!AddProductTo(lb, coeff, &min_activity)) return true;
480 if (!AddProductTo(ub, coeff, &max_activity)) return true;
481 } else {
482 if (!AddProductTo(ub, coeff, &min_activity)) return true;
483 if (!AddProductTo(lb, coeff, &max_activity)) return true;
484 }
485 }
486 return AtMinOrMaxInt64(CapSub(max_activity.value(), min_activity.value()));
487}
488
489} // namespace sat
490} // namespace operations_research
static int64_t GCD64(int64_t x, int64_t y)
Definition mathutil.h:107
IntegerValue LowerBound(IntegerVariable i) const
Definition integer.h:1537
IntegerValue UpperBound(IntegerVariable i) const
Definition integer.h:1541
IntegerValue FixedValue(IntegerVariable i) const
Definition integer.h:1549
bool IsFixed(IntegerVariable i) const
Definition integer.h:1545
IntegerValue LevelZeroUpperBound(IntegerVariable var) const
Definition integer.h:1657
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
Definition integer.h:1650
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 AddTerm(IntegerVariable var, IntegerValue coeff)
void AddLinearExpression(const LinearExpression &expr)
LinearConstraint BuildConstraint(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)
IntegerValue FloorRatio(IntegerValue dividend, IntegerValue positive_divisor)
bool AddProductTo(IntegerValue a, IntegerValue b, IntegerValue *result)
void DivideByGCD(LinearConstraint *constraint)
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
IntType IntTypeAbs(IntType t)
IntegerValue CeilRatio(IntegerValue dividend, IntegerValue positive_divisor)
bool ProdOverflow(IntegerValue t, IntegerValue value)
std::string IntegerTermDebugString(IntegerVariable var, IntegerValue coeff)
std::vector< IntegerVariable > NegationOf(absl::Span< const IntegerVariable > vars)
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)
LinearExpression CanonicalizeExpr(const LinearExpression &expr)
bool MergePositiveVariableTermsAndCheckForOverflow(std::vector< std::pair< IntegerVariable, IntegerValue > > *terms, LinearConstraint *output)
IntegerValue ComputeInfinityNorm(const LinearConstraint &ct)
LinearExpression PositiveVarExpr(const LinearExpression &expr)
double ComputeL2Norm(const LinearConstraint &ct)
IntegerValue GetCoefficient(const IntegerVariable var, const LinearExpression &expr)
void MakeAllVariablesPositive(LinearConstraint *constraint)
IntegerValue GetCoefficientOfPositiveVar(const IntegerVariable var, const LinearExpression &expr)
bool ValidateLinearConstraintForOverflow(const LinearConstraint &constraint, const IntegerTrail &integer_trail)
bool NoDuplicateVariable(const LinearConstraint &ct)
bool VariableIsPositive(IntegerVariable i)
double ToDouble(IntegerValue value)
double ScalarProduct(const LinearConstraint &ct1, const LinearConstraint &ct2)
OR-Tools root namespace.
bool AtMinOrMaxInt64(int64_t x)
int64_t CapAdd(int64_t x, int64_t y)
int64_t CapSub(int64_t x, int64_t y)
int64_t CapProd(int64_t x, int64_t y)
std::unique_ptr< IntegerValue[]> coeffs
std::unique_ptr< IntegerVariable[]> vars
double NormalizedViolation(const util_intops::StrongVector< IntegerVariable, double > &lp_values) const
IntegerValue LevelZeroMin(IntegerTrail *integer_trail) const
IntegerValue Min(const IntegerTrail &integer_trail) const
double LpValue(const util_intops::StrongVector< IntegerVariable, double > &lp_values) const
IntegerValue Max(const IntegerTrail &integer_trail) const