OR-Tools  8.0
linear_constraint.h
Go to the documentation of this file.
1 // Copyright 2010-2018 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 <vector>
18 
19 #include "ortools/sat/integer.h"
20 #include "ortools/sat/model.h"
21 
22 namespace operations_research {
23 namespace sat {
24 
25 // One linear constraint on a set of Integer variables.
26 // Important: there should be no duplicate variables.
27 //
28 // We also assume that we never have integer overflow when evaluating such
29 // constraint. This should be enforced by the checker for user given
30 // constraints, and we must enforce it ourselves for the newly created
31 // constraint. We requires:
32 // - sum_i max(0, max(c_i * lb_i, c_i * ub_i)) < kMaxIntegerValue.
33 // - sum_i min(0, min(c_i * lb_i, c_i * ub_i)) > kMinIntegerValue
34 // so that in whichever order we compute the sum, we have no overflow. Note
35 // that this condition invoves the bounds of the variables.
36 //
37 // TODO(user): Add DCHECKs for the no-overflow property? but we need access
38 // to the variable bounds.
40  IntegerValue lb;
41  IntegerValue ub;
42  std::vector<IntegerVariable> vars;
43  std::vector<IntegerValue> coeffs;
44 
46  LinearConstraint(IntegerValue _lb, IntegerValue _ub) : lb(_lb), ub(_ub) {}
47 
48  void AddTerm(IntegerVariable var, IntegerValue coeff) {
49  vars.push_back(var);
50  coeffs.push_back(coeff);
51  }
52 
53  std::string DebugString() const {
54  std::string result;
55  if (lb.value() > kMinIntegerValue) {
56  absl::StrAppend(&result, lb.value(), " <= ");
57  }
58  for (int i = 0; i < vars.size(); ++i) {
59  const IntegerValue coeff =
60  VariableIsPositive(vars[i]) ? coeffs[i] : -coeffs[i];
61  absl::StrAppend(&result, i > 0 ? " " : "", coeff.value(), "*X",
62  vars[i].value() / 2);
63  }
64  if (ub.value() < kMaxIntegerValue) {
65  absl::StrAppend(&result, " <= ", ub.value());
66  }
67  return result;
68  }
69 
70  bool operator==(const LinearConstraint other) const {
71  if (this->lb != other.lb) return false;
72  if (this->ub != other.ub) return false;
73  if (this->vars != other.vars) return false;
74  if (this->coeffs != other.coeffs) return false;
75  return true;
76  }
77 };
78 
79 // Allow to build a LinearConstraint while making sure there is no duplicate
80 // variables. Note that we do not simplify literal/variable that are currently
81 // fixed here.
83  public:
84  // We support "sticky" kMinIntegerValue for lb and kMaxIntegerValue for ub
85  // for one-sided constraints.
86  //
87  // Assumes that the 'model' has IntegerEncoder.
88  LinearConstraintBuilder(const Model* model, IntegerValue lb, IntegerValue ub)
89  : encoder_(*model->Get<IntegerEncoder>()), lb_(lb), ub_(ub) {}
90 
91  // Adds var * coeff to the constraint.
92  void AddTerm(IntegerVariable var, IntegerValue coeff);
93  void AddTerm(AffineExpression expr, IntegerValue coeff);
94 
95  // Add literal * coeff to the constaint. Returns false and do nothing if the
96  // given literal didn't have an integer view.
97  ABSL_MUST_USE_RESULT bool AddLiteralTerm(Literal lit, IntegerValue coeff);
98 
99  // Builds and return the corresponding constraint in a canonical form.
100  // All the IntegerVariable will be positive and appear in increasing index
101  // order.
102  //
103  // TODO(user): this doesn't invalidate the builder object, but if one wants
104  // to do a lot of dynamic editing to the constraint, then then underlying
105  // algorithm needs to be optimized of that.
107 
108  private:
109  const IntegerEncoder& encoder_;
110  IntegerValue lb_;
111  IntegerValue ub_;
112  IntegerValue offset_;
113 
114  // Initially we push all AddTerm() here, and during Build() we merge terms
115  // on the same variable.
116  std::vector<std::pair<IntegerVariable, IntegerValue>> terms_;
117 };
118 
119 // Returns the activity of the given constraint. That is the current value of
120 // the linear terms.
121 double ComputeActivity(const LinearConstraint& constraint,
123 
124 // Returns sqrt(sum square(coeff)).
125 double ComputeL2Norm(const LinearConstraint& constraint);
126 
127 // Returns the maximum absolute value of the coefficients.
128 IntegerValue ComputeInfinityNorm(const LinearConstraint& constraint);
129 
130 // Returns the scalar product of given constraint coefficients. This method
131 // assumes that the constraint variables are in sorted order.
132 double ScalarProduct(const LinearConstraint& constraint1,
133  const LinearConstraint& constraint2);
134 
135 // Computes the GCD of the constraint coefficient, and divide them by it. This
136 // also tighten the constraint bounds assumming all the variables are integer.
137 void DivideByGCD(LinearConstraint* constraint);
138 
139 // Removes the entries with a coefficient of zero.
140 void RemoveZeroTerms(LinearConstraint* constraint);
141 
142 // Makes all coefficients positive by transforming a variable to its negation.
143 void MakeAllCoefficientsPositive(LinearConstraint* constraint);
144 
145 // Makes all variables "positive" by transforming a variable to its negation.
146 void MakeAllVariablesPositive(LinearConstraint* constraint);
147 
148 // Sorts and merges duplicate IntegerVariable in the given "terms".
149 // Fills the given LinearConstraint with the result.
151  std::vector<std::pair<IntegerVariable, IntegerValue>>* terms,
152  LinearConstraint* constraint);
153 
154 // Sorts the terms and makes all IntegerVariable positive. This assumes that a
155 // variable or its negation only appear once.
156 //
157 // Note that currently this allocates some temporary memory.
158 void CanonicalizeConstraint(LinearConstraint* ct);
159 
160 // Returns false if duplicate variables are found in ct.
161 bool NoDuplicateVariable(const LinearConstraint& ct);
162 
163 // Helper struct to model linear expression for lin_min/lin_max constraints. The
164 // canonical expression should only contain positive coefficients.
166  std::vector<IntegerVariable> vars;
167  std::vector<IntegerValue> coeffs;
168  IntegerValue offset = IntegerValue(0);
169 };
170 
171 // Returns the same expression in the canonical form (all positive
172 // coefficients).
174 
175 // Returns lower bound of linear expression using variable bounds of the
176 // variables in expression. Assumes Canonical expression (all positive
177 // coefficients).
178 IntegerValue LinExprLowerBound(const LinearExpression& expr,
179  const IntegerTrail& integer_trail);
180 
181 // Returns upper bound of linear expression using variable bounds of the
182 // variables in expression. Assumes Canonical expression (all positive
183 // coefficients).
184 IntegerValue LinExprUpperBound(const LinearExpression& expr,
185  const IntegerTrail& integer_trail);
186 
187 // Preserves canonicality.
189 
190 // Returns the same expression with positive variables.
192 
193 // Returns the coefficient of the variable in the expression. Works in linear
194 // time.
195 // Note: GetCoefficient(NegationOf(var, expr)) == -GetCoefficient(var, expr).
196 IntegerValue GetCoefficient(const IntegerVariable var,
197  const LinearExpression& expr);
198 IntegerValue GetCoefficientOfPositiveVar(const IntegerVariable var,
199  const LinearExpression& expr);
200 
201 } // namespace sat
202 } // namespace operations_research
203 
204 #endif // OR_TOOLS_SAT_LINEAR_CONSTRAINT_H_
var
IntVar * var
Definition: expr_array.cc:1858
operations_research::sat::LinearExpression::vars
std::vector< IntegerVariable > vars
Definition: linear_constraint.h:166
operations_research::sat::LinearConstraint::ub
IntegerValue ub
Definition: linear_constraint.h:41
operations_research::sat::CleanTermsAndFillConstraint
void CleanTermsAndFillConstraint(std::vector< std::pair< IntegerVariable, IntegerValue >> *terms, LinearConstraint *constraint)
Definition: linear_constraint.cc:77
operations_research::sat::ScalarProduct
double ScalarProduct(const LinearConstraint &constraint1, const LinearConstraint &constraint2)
Definition: linear_constraint.cc:143
operations_research::sat::VariableIsPositive
bool VariableIsPositive(IntegerVariable i)
Definition: integer.h:141
operations_research::sat::LinearConstraint::DebugString
std::string DebugString() const
Definition: linear_constraint.h:53
operations_research::sat::NoDuplicateVariable
bool NoDuplicateVariable(const LinearConstraint &ct)
Definition: linear_constraint.cc:258
operations_research::sat::LinearExpression
Definition: linear_constraint.h:165
operations_research::sat::LinExprUpperBound
IntegerValue LinExprUpperBound(const LinearExpression &expr, const IntegerTrail &integer_trail)
Definition: linear_constraint.cc:296
model.h
operations_research::sat::LinearConstraint::lb
IntegerValue lb
Definition: linear_constraint.h:40
operations_research
The vehicle routing library lets one model and solve generic vehicle routing problems ranging from th...
Definition: dense_doubly_linked_list.h:21
operations_research::sat::NegationOf
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Definition: integer.cc:42
operations_research::sat::IntegerTrail
Definition: integer.h:534
operations_research::sat::LinearExpression::coeffs
std::vector< IntegerValue > coeffs
Definition: linear_constraint.h:167
operations_research::sat::LinearConstraintBuilder::LinearConstraintBuilder
LinearConstraintBuilder(const Model *model, IntegerValue lb, IntegerValue ub)
Definition: linear_constraint.h:88
operations_research::sat::Model
Class that owns everything related to a particular optimization model.
Definition: sat/model.h:38
operations_research::sat::GetCoefficient
IntegerValue GetCoefficient(const IntegerVariable var, const LinearExpression &expr)
Definition: linear_constraint.cc:329
operations_research::sat::Literal
Definition: sat_base.h:64
operations_research::sat::LinearConstraint::operator==
bool operator==(const LinearConstraint other) const
Definition: linear_constraint.h:70
operations_research::sat::LinearConstraint
Definition: linear_constraint.h:39
operations_research::sat::LinearConstraintBuilder::AddTerm
void AddTerm(IntegerVariable var, IntegerValue coeff)
Definition: linear_constraint.cc:22
operations_research::sat::IntegerEncoder
Definition: integer.h:278
operations_research::sat::AffineExpression
Definition: integer.h:214
operations_research::sat::kMaxIntegerValue
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
operations_research::sat::CanonicalizeExpr
LinearExpression CanonicalizeExpr(const LinearExpression &expr)
Definition: linear_constraint.cc:271
ct
const Constraint * ct
Definition: demon_profiler.cc:42
operations_research::sat::PositiveVarExpr
LinearExpression PositiveVarExpr(const LinearExpression &expr)
Definition: linear_constraint.cc:314
operations_research::sat::LinearConstraint::AddTerm
void AddTerm(IntegerVariable var, IntegerValue coeff)
Definition: linear_constraint.h:48
operations_research::sat::LinExprLowerBound
IntegerValue LinExprLowerBound(const LinearExpression &expr, const IntegerTrail &integer_trail)
Definition: linear_constraint.cc:286
operations_research::sat::MakeAllCoefficientsPositive
void MakeAllCoefficientsPositive(LinearConstraint *constraint)
Definition: linear_constraint.cc:209
operations_research::sat::GetCoefficientOfPositiveVar
IntegerValue GetCoefficientOfPositiveVar(const IntegerVariable var, const LinearExpression &expr)
Definition: linear_constraint.cc:341
operations_research::sat::ComputeL2Norm
double ComputeL2Norm(const LinearConstraint &constraint)
Definition: linear_constraint.cc:127
model
GRBmodel * model
Definition: gurobi_interface.cc:195
operations_research::sat::RemoveZeroTerms
void RemoveZeroTerms(LinearConstraint *constraint)
Definition: linear_constraint.cc:196
operations_research::sat::LinearExpression::offset
IntegerValue offset
Definition: linear_constraint.h:168
operations_research::sat::LinearConstraint::LinearConstraint
LinearConstraint(IntegerValue _lb, IntegerValue _ub)
Definition: linear_constraint.h:46
operations_research::sat::LinearConstraint::LinearConstraint
LinearConstraint()
Definition: linear_constraint.h:45
operations_research::sat::kMinIntegerValue
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
operations_research::sat::LinearConstraintBuilder
Definition: linear_constraint.h:82
operations_research::sat::MakeAllVariablesPositive
void MakeAllVariablesPositive(LinearConstraint *constraint)
Definition: linear_constraint.cc:220
operations_research::sat::ComputeActivity
double ComputeActivity(const LinearConstraint &constraint, const gtl::ITIVector< IntegerVariable, double > &values)
Definition: linear_constraint.cc:116
operations_research::sat::LinearConstraint::vars
std::vector< IntegerVariable > vars
Definition: linear_constraint.h:42
operations_research::sat::LinearConstraintBuilder::Build
LinearConstraint Build()
Definition: linear_constraint.cc:108
gtl::ITIVector< IntegerVariable, double >
operations_research::sat::ComputeInfinityNorm
IntegerValue ComputeInfinityNorm(const LinearConstraint &constraint)
Definition: linear_constraint.cc:135
operations_research::sat::DivideByGCD
void DivideByGCD(LinearConstraint *constraint)
Definition: linear_constraint.cc:182
operations_research::sat::LinearConstraintBuilder::AddLiteralTerm
ABSL_MUST_USE_RESULT bool AddLiteralTerm(Literal lit, IntegerValue coeff)
Definition: linear_constraint.cc:47
operations_research::sat::CanonicalizeConstraint
void CanonicalizeConstraint(LinearConstraint *ct)
Definition: linear_constraint.cc:237
integer.h
operations_research::sat::LinearConstraint::coeffs
std::vector< IntegerValue > coeffs
Definition: linear_constraint.h:43