forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_constraint.cc
353 lines (319 loc) · 11.2 KB
/
linear_constraint.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright 2010-2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/linear_constraint.h"
#include "ortools/base/mathutil.h"
#include "ortools/sat/integer.h"
namespace operations_research {
namespace sat {
void LinearConstraintBuilder::AddTerm(IntegerVariable var, IntegerValue coeff) {
// We can either add var or NegationOf(var), and we always choose the
// positive one.
if (VariableIsPositive(var)) {
terms_.push_back({var, coeff});
} else {
terms_.push_back({NegationOf(var), -coeff});
}
}
void LinearConstraintBuilder::AddTerm(AffineExpression expr,
IntegerValue coeff) {
// We can either add var or NegationOf(var), and we always choose the
// positive one.
if (expr.var != kNoIntegerVariable) {
if (VariableIsPositive(expr.var)) {
terms_.push_back({expr.var, coeff * expr.coeff});
} else {
terms_.push_back({NegationOf(expr.var), -coeff * expr.coeff});
}
}
if (lb_ > kMinIntegerValue) lb_ -= coeff * expr.constant;
if (ub_ < kMaxIntegerValue) ub_ -= coeff * expr.constant;
}
ABSL_MUST_USE_RESULT bool LinearConstraintBuilder::AddLiteralTerm(
Literal lit, IntegerValue coeff) {
bool has_direct_view = encoder_.GetLiteralView(lit) != kNoIntegerVariable;
bool has_opposite_view =
encoder_.GetLiteralView(lit.Negated()) != kNoIntegerVariable;
// If a literal has both views, we want to always keep the same
// representative: the smallest IntegerVariable. Note that AddTerm() will
// also make sure to use the associated positive variable.
if (has_direct_view && has_opposite_view) {
if (encoder_.GetLiteralView(lit) <=
encoder_.GetLiteralView(lit.Negated())) {
has_opposite_view = false;
} else {
has_direct_view = false;
}
}
if (has_direct_view) {
AddTerm(encoder_.GetLiteralView(lit), coeff);
return true;
}
if (has_opposite_view) {
AddTerm(encoder_.GetLiteralView(lit.Negated()), -coeff);
if (lb_ > kMinIntegerValue) lb_ -= coeff;
if (ub_ < kMaxIntegerValue) ub_ -= coeff;
return true;
}
return false;
}
void CleanTermsAndFillConstraint(
std::vector<std::pair<IntegerVariable, IntegerValue>>* terms,
LinearConstraint* constraint) {
constraint->vars.clear();
constraint->coeffs.clear();
// Sort and add coeff of duplicate variables. Note that a variable and
// its negation will appear one after another in the natural order.
std::sort(terms->begin(), terms->end());
IntegerVariable previous_var = kNoIntegerVariable;
IntegerValue current_coeff(0);
for (const std::pair<IntegerVariable, IntegerValue> entry : *terms) {
if (previous_var == entry.first) {
current_coeff += entry.second;
} else if (previous_var == NegationOf(entry.first)) {
current_coeff -= entry.second;
} else {
if (current_coeff != 0) {
constraint->vars.push_back(previous_var);
constraint->coeffs.push_back(current_coeff);
}
previous_var = entry.first;
current_coeff = entry.second;
}
}
if (current_coeff != 0) {
constraint->vars.push_back(previous_var);
constraint->coeffs.push_back(current_coeff);
}
}
LinearConstraint LinearConstraintBuilder::Build() {
LinearConstraint result;
result.lb = lb_;
result.ub = ub_;
CleanTermsAndFillConstraint(&terms_, &result);
return result;
}
double ComputeActivity(const LinearConstraint& constraint,
const gtl::ITIVector<IntegerVariable, double>& values) {
double activity = 0;
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
const IntegerValue coeff = constraint.coeffs[i];
activity += coeff.value() * values[var];
}
return activity;
}
double ComputeL2Norm(const LinearConstraint& constraint) {
double sum = 0.0;
for (const IntegerValue coeff : constraint.coeffs) {
sum += ToDouble(coeff) * ToDouble(coeff);
}
return std::sqrt(sum);
}
IntegerValue ComputeInfinityNorm(const LinearConstraint& constraint) {
IntegerValue result(0);
for (const IntegerValue coeff : constraint.coeffs) {
result = std::max(result, IntTypeAbs(coeff));
}
return result;
}
double ScalarProduct(const LinearConstraint& constraint1,
const LinearConstraint& constraint2) {
DCHECK(std::is_sorted(constraint1.vars.begin(), constraint1.vars.end()));
DCHECK(std::is_sorted(constraint2.vars.begin(), constraint2.vars.end()));
double scalar_product = 0.0;
int index_1 = 0;
int index_2 = 0;
while (index_1 < constraint1.vars.size() &&
index_2 < constraint2.vars.size()) {
if (constraint1.vars[index_1] == constraint2.vars[index_2]) {
scalar_product += ToDouble(constraint1.coeffs[index_1]) *
ToDouble(constraint2.coeffs[index_2]);
index_1++;
index_2++;
} else if (constraint1.vars[index_1] > constraint2.vars[index_2]) {
index_2++;
} else {
index_1++;
}
}
return scalar_product;
}
namespace {
// TODO(user): Template for any integer type and expose this?
IntegerValue ComputeGcd(const std::vector<IntegerValue>& values) {
if (values.empty()) return IntegerValue(1);
int64 gcd = 0;
for (const IntegerValue value : values) {
gcd = MathUtil::GCD64(gcd, std::abs(value.value()));
if (gcd == 1) break;
}
if (gcd < 0) return IntegerValue(1); // Can happen with kint64min.
return IntegerValue(gcd);
}
} // namespace
void DivideByGCD(LinearConstraint* constraint) {
if (constraint->coeffs.empty()) return;
const IntegerValue gcd = ComputeGcd(constraint->coeffs);
if (gcd == 1) return;
if (constraint->lb > kMinIntegerValue) {
constraint->lb = CeilRatio(constraint->lb, gcd);
}
if (constraint->ub < kMaxIntegerValue) {
constraint->ub = FloorRatio(constraint->ub, gcd);
}
for (IntegerValue& coeff : constraint->coeffs) coeff /= gcd;
}
void RemoveZeroTerms(LinearConstraint* constraint) {
int new_size = 0;
const int size = constraint->vars.size();
for (int i = 0; i < size; ++i) {
if (constraint->coeffs[i] == 0) continue;
constraint->vars[new_size] = constraint->vars[i];
constraint->coeffs[new_size] = constraint->coeffs[i];
++new_size;
}
constraint->vars.resize(new_size);
constraint->coeffs.resize(new_size);
}
void MakeAllCoefficientsPositive(LinearConstraint* constraint) {
const int size = constraint->vars.size();
for (int i = 0; i < size; ++i) {
const IntegerValue coeff = constraint->coeffs[i];
if (coeff < 0) {
constraint->coeffs[i] = -coeff;
constraint->vars[i] = NegationOf(constraint->vars[i]);
}
}
}
void MakeAllVariablesPositive(LinearConstraint* constraint) {
const int size = constraint->vars.size();
for (int i = 0; i < size; ++i) {
const IntegerVariable var = constraint->vars[i];
if (!VariableIsPositive(var)) {
constraint->coeffs[i] = -constraint->coeffs[i];
constraint->vars[i] = NegationOf(var);
}
}
}
// TODO(user): it would be better if LinearConstraint natively supported
// term and not two separated vectors. Fix?
//
// TODO(user): This is really similar to CleanTermsAndFillConstraint(), maybe
// we should just make the later switch negative variable to positive ones to
// avoid an extra linear scan on each new cuts.
void CanonicalizeConstraint(LinearConstraint* ct) {
std::vector<std::pair<IntegerVariable, IntegerValue>> terms;
const int size = ct->vars.size();
for (int i = 0; i < size; ++i) {
if (VariableIsPositive(ct->vars[i])) {
terms.push_back({ct->vars[i], ct->coeffs[i]});
} else {
terms.push_back({NegationOf(ct->vars[i]), -ct->coeffs[i]});
}
}
std::sort(terms.begin(), terms.end());
ct->vars.clear();
ct->coeffs.clear();
for (const auto& term : terms) {
ct->vars.push_back(term.first);
ct->coeffs.push_back(term.second);
}
}
bool NoDuplicateVariable(const LinearConstraint& ct) {
absl::flat_hash_set<IntegerVariable> seen_variables;
const int size = ct.vars.size();
for (int i = 0; i < size; ++i) {
if (VariableIsPositive(ct.vars[i])) {
if (!seen_variables.insert(ct.vars[i]).second) return false;
} else {
if (!seen_variables.insert(NegationOf(ct.vars[i])).second) return false;
}
}
return true;
}
LinearExpression CanonicalizeExpr(const LinearExpression& expr) {
LinearExpression canonical_expr;
canonical_expr.offset = expr.offset;
for (int i = 0; i < expr.vars.size(); ++i) {
if (expr.coeffs[i] < 0) {
canonical_expr.vars.push_back(NegationOf(expr.vars[i]));
canonical_expr.coeffs.push_back(-expr.coeffs[i]);
} else {
canonical_expr.vars.push_back(expr.vars[i]);
canonical_expr.coeffs.push_back(expr.coeffs[i]);
}
}
return canonical_expr;
}
IntegerValue LinExprLowerBound(const LinearExpression& expr,
const IntegerTrail& integer_trail) {
IntegerValue lower_bound = expr.offset;
for (int i = 0; i < expr.vars.size(); ++i) {
DCHECK_GE(expr.coeffs[i], 0) << "The expression is not canonicalized";
lower_bound += expr.coeffs[i] * integer_trail.LowerBound(expr.vars[i]);
}
return lower_bound;
}
IntegerValue LinExprUpperBound(const LinearExpression& expr,
const IntegerTrail& integer_trail) {
IntegerValue upper_bound = expr.offset;
for (int i = 0; i < expr.vars.size(); ++i) {
DCHECK_GE(expr.coeffs[i], 0) << "The expression is not canonicalized";
upper_bound += expr.coeffs[i] * integer_trail.UpperBound(expr.vars[i]);
}
return upper_bound;
}
LinearExpression NegationOf(const LinearExpression& expr) {
LinearExpression result;
result.vars = NegationOf(expr.vars);
result.coeffs = expr.coeffs;
result.offset = -expr.offset;
return result;
}
LinearExpression PositiveVarExpr(const LinearExpression& expr) {
LinearExpression result;
result.offset = expr.offset;
for (int i = 0; i < expr.vars.size(); ++i) {
if (VariableIsPositive(expr.vars[i])) {
result.vars.push_back(expr.vars[i]);
result.coeffs.push_back(expr.coeffs[i]);
} else {
result.vars.push_back(NegationOf(expr.vars[i]));
result.coeffs.push_back(-expr.coeffs[i]);
}
}
return result;
}
IntegerValue GetCoefficient(const IntegerVariable var,
const LinearExpression& expr) {
for (int i = 0; i < expr.vars.size(); ++i) {
if (expr.vars[i] == var) {
return expr.coeffs[i];
} else if (expr.vars[i] == NegationOf(var)) {
return -expr.coeffs[i];
}
}
return IntegerValue(0);
}
IntegerValue GetCoefficientOfPositiveVar(const IntegerVariable var,
const LinearExpression& expr) {
CHECK(VariableIsPositive(var));
for (int i = 0; i < expr.vars.size(); ++i) {
if (expr.vars[i] == var) {
return expr.coeffs[i];
}
}
return IntegerValue(0);
}
} // namespace sat
} // namespace operations_research