Google OR-Tools v9.9
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
linear_expr_util.cc
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
15
16#include <utility>
17#include <vector>
18
19#include "absl/algorithm/container.h"
21
23namespace {
24
25double ComputeBound(const LinearExpression& linear_expression,
26 bool is_upper_bound) {
27 // The algorithm used is as follows:
28 // (1) Make a list of the terms to add up, e.g.
29 // [offset, x1.lb()*c1, x3.ub()*c3]
30 // (2) Sort the list by {abs(x), x} lexicographically
31 // (3) Sum up the values from the smallest absolute value to largest.
32 // The result will give deterministic output with reasonable precision.
33 std::vector<double> terms_to_add;
34 terms_to_add.reserve(linear_expression.terms().size() + 1);
35 terms_to_add.push_back(linear_expression.offset());
36 for (const auto [var, coef] : linear_expression.terms()) {
37 const bool use_ub =
38 (is_upper_bound && coef > 0) || (!is_upper_bound && coef < 0);
39 const double val =
40 use_ub ? var.upper_bound() * coef : var.lower_bound() * coef;
41 terms_to_add.push_back(val);
42 }
43 // all values in terms_to_add are finite.
44 absl::c_sort(terms_to_add, [](const double left, const double right) {
45 return std::pair(std::abs(left), left) < std::pair(std::abs(right), right);
46 });
47 return absl::c_accumulate(terms_to_add, 0.0);
48}
49
50} // namespace
51
52double LowerBound(const LinearExpression& linear_expression) {
53 return ComputeBound(linear_expression, /*is_upper_bound=*/false);
54}
55
56double UpperBound(const LinearExpression& linear_expression) {
57 return ComputeBound(linear_expression, /*is_upper_bound=*/true);
58}
59
60} // namespace operations_research::math_opt
IntVar * var
int64_t coef
An object oriented wrapper for quadratic constraints in ModelStorage.
Definition gurobi_isv.cc:28
double LowerBound(const LinearExpression &linear_expression)
double UpperBound(const LinearExpression &linear_expression)