Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cuts.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
14#include "ortools/sat/cuts.h"
15
16#include <algorithm>
17#include <array>
18#include <cmath>
19#include <cstdint>
20#include <functional>
21#include <limits>
22#include <string>
23#include <tuple>
24#include <utility>
25#include <vector>
26
27#include "absl/base/attributes.h"
28#include "absl/container/btree_map.h"
29#include "absl/container/btree_set.h"
30#include "absl/container/flat_hash_map.h"
31#include "absl/container/flat_hash_set.h"
32#include "absl/log/check.h"
33#include "absl/log/log.h"
34#include "absl/log/vlog_is_on.h"
35#include "absl/meta/type_traits.h"
36#include "absl/numeric/int128.h"
37#include "absl/strings/str_cat.h"
38#include "absl/strings/string_view.h"
39#include "absl/types/span.h"
44#include "ortools/sat/clause.h"
46#include "ortools/sat/integer.h"
50#include "ortools/sat/model.h"
56
57namespace operations_research {
58namespace sat {
59
60namespace {
61
62// TODO(user): the function ToDouble() does some testing for min/max integer
63// value and we don't need that here.
64double AsDouble(IntegerValue v) { return static_cast<double>(v.value()); }
65
66} // namespace
67
68std::string CutTerm::DebugString() const {
69 return absl::StrCat("coeff=", coeff.value(), " lp=", lp_value,
70 " range=", bound_diff.value(), " expr=[",
71 expr_coeffs[0].value(), ",", expr_coeffs[1].value(), "]",
72 " * [V", expr_vars[0].value(), ",V", expr_vars[1].value(),
73 "]", " + ", expr_offset.value());
74}
75
76std::string CutData::DebugString() const {
77 std::string result = absl::StrCat("CutData rhs=", rhs, "\n");
78 for (const CutTerm& term : terms) {
79 absl::StrAppend(&result, term.DebugString(), "\n");
80 }
81 return result;
82}
83
84void CutTerm::Complement(absl::int128* rhs) {
85 // We replace coeff * X by coeff * (X - bound_diff + bound_diff)
86 // which gives -coeff * complement(X) + coeff * bound_diff;
87 *rhs -= absl::int128(coeff.value()) * absl::int128(bound_diff.value());
88
89 // We keep the same expression variable.
90 for (int i = 0; i < 2; ++i) {
92 }
94
95 // Note that this is not involutive because of floating point error. Fix?
96 lp_value = static_cast<double>(bound_diff.value()) - lp_value;
97 coeff = -coeff;
98
99 // Swap the implied bound info.
101}
102
103void CutTerm::ReplaceExpressionByLiteral(IntegerVariable var) {
104 CHECK_EQ(bound_diff, 1);
105 expr_coeffs[1] = 0;
106 if (VariableIsPositive(var)) {
107 expr_vars[0] = var;
108 expr_coeffs[0] = 1;
109 expr_offset = 0;
110 } else {
111 expr_vars[0] = PositiveVariable(var);
112 expr_coeffs[0] = -1;
113 expr_offset = 1;
114 }
115}
116
117IntegerVariable CutTerm::GetUnderlyingLiteralOrNone() const {
118 if (expr_coeffs[1] != 0) return kNoIntegerVariable;
119 if (bound_diff != 1) return kNoIntegerVariable;
120
121 if (expr_coeffs[0] > 0) {
122 if (expr_coeffs[0] != 1) return kNoIntegerVariable;
123 if (expr_offset != 0) return kNoIntegerVariable;
124 CHECK(VariableIsPositive(expr_vars[0]));
125 return expr_vars[0];
126 }
127
128 if (expr_coeffs[0] != -1) return kNoIntegerVariable;
129 if (expr_offset != 1) return kNoIntegerVariable;
130 CHECK(VariableIsPositive(expr_vars[0]));
131 return NegationOf(expr_vars[0]);
132}
133
134// To try to minimize the risk of overflow, we switch to the bound closer
135// to the lp_value. Since most of our base constraint for cut are tight,
136// hopefully this is not too bad.
137bool CutData::AppendOneTerm(IntegerVariable var, IntegerValue coeff,
138 double lp_value, IntegerValue lb, IntegerValue ub) {
139 if (coeff == 0) return true;
140 const IntegerValue bound_diff = ub - lb;
141
142 // Complement the variable so that it is has a positive coefficient.
143 const bool complement = coeff < 0;
144
145 // See formula below, the constant term is either coeff * lb or coeff * ub.
146 rhs -= absl::int128(coeff.value()) *
147 absl::int128(complement ? ub.value() : lb.value());
148
149 // Deal with fixed variable, no need to shift back in this case, we can
150 // just remove the term.
151 if (bound_diff == 0) return true;
152
153 CutTerm entry;
154 entry.expr_vars[0] = var;
155 entry.expr_coeffs[1] = 0;
156 entry.bound_diff = bound_diff;
157 if (complement) {
158 // X = -(UB - X) + UB
159 entry.expr_coeffs[0] = -IntegerValue(1);
160 entry.expr_offset = ub;
161 entry.coeff = -coeff;
162 entry.lp_value = static_cast<double>(ub.value()) - lp_value;
163 } else {
164 // C = (X - LB) + LB
165 entry.expr_coeffs[0] = IntegerValue(1);
166 entry.expr_offset = -lb;
167 entry.coeff = coeff;
168 entry.lp_value = lp_value - static_cast<double>(lb.value());
169 }
170 terms.push_back(entry);
171 return true;
172}
173
175 const LinearConstraint& base_ct,
177 IntegerTrail* integer_trail) {
178 rhs = absl::int128(base_ct.ub.value());
179 terms.clear();
180 const int num_terms = base_ct.num_terms;
181 for (int i = 0; i < num_terms; ++i) {
182 const IntegerVariable var = base_ct.vars[i];
183 if (!AppendOneTerm(var, base_ct.coeffs[i], lp_values[base_ct.vars[i]],
184 integer_trail->LevelZeroLowerBound(var),
185 integer_trail->LevelZeroUpperBound(var))) {
186 return false;
187 }
188 }
189 return true;
190}
191
193 IntegerValue ub, absl::Span<const IntegerVariable> vars,
194 absl::Span<const IntegerValue> coeffs, absl::Span<const double> lp_values,
195 absl::Span<const IntegerValue> lower_bounds,
196 absl::Span<const IntegerValue> upper_bounds) {
197 rhs = absl::int128(ub.value());
198 terms.clear();
199
200 const int size = lp_values.size();
201 if (size == 0) return true;
202
203 CHECK_EQ(vars.size(), size);
204 CHECK_EQ(coeffs.size(), size);
205 CHECK_EQ(lower_bounds.size(), size);
206 CHECK_EQ(upper_bounds.size(), size);
207
208 for (int i = 0; i < size; ++i) {
209 if (!AppendOneTerm(vars[i], coeffs[i], lp_values[i], lower_bounds[i],
210 upper_bounds[i])) {
211 return false;
212 }
213 }
214
215 return true;
216}
217
219 for (CutTerm& term : terms) {
220 if (term.coeff >= 0) continue;
221 term.Complement(&rhs);
222 }
223}
224
226 for (CutTerm& term : terms) {
227 if (term.lp_value <= term.LpDistToMaxValue()) continue;
228 term.Complement(&rhs);
229 }
230}
231
233 for (const CutTerm& term : terms) {
234 if (term.coeff < 0) return false;
235 }
236 return true;
237}
238
241 max_magnitude = 0;
242 for (CutTerm& entry : terms) {
243 max_magnitude = std::max(max_magnitude, IntTypeAbs(entry.coeff));
244 if (entry.HasRelevantLpValue()) {
245 std::swap(terms[num_relevant_entries], entry);
247 }
248 }
249
250 // Sort by larger lp_value first.
251 std::sort(terms.begin(), terms.begin() + num_relevant_entries,
252 [](const CutTerm& a, const CutTerm& b) {
253 return a.lp_value > b.lp_value;
254 });
255}
256
258 double violation = -static_cast<double>(rhs);
259 for (const CutTerm& term : terms) {
260 violation += term.lp_value * static_cast<double>(term.coeff.value());
261 }
262 return violation;
263}
264
266 double violation = -static_cast<double>(rhs);
267 double norm = 0.0;
268 for (const CutTerm& term : terms) {
269 const double coeff = static_cast<double>(term.coeff.value());
270 violation += term.lp_value * coeff;
271 norm += coeff * coeff;
272 }
273 return violation / std::sqrt(norm);
274}
275
276// We can only merge the term if term.coeff + old_coeff do not overflow and
277// if t * new_coeff do not overflow.
278//
279// If we cannot merge the term, we will keep them separate. The produced cut
280// will be less strong, but can still be used.
281bool CutDataBuilder::MergeIfPossible(IntegerValue t, CutTerm& to_add,
282 CutTerm& target) {
283 DCHECK_EQ(to_add.expr_vars[0], target.expr_vars[0]);
284 DCHECK_EQ(to_add.expr_coeffs[0], target.expr_coeffs[0]);
285
286 const IntegerValue new_coeff = CapAddI(to_add.coeff, target.coeff);
287 if (AtMinOrMaxInt64I(new_coeff) || ProdOverflow(t, new_coeff)) {
288 return false;
289 }
290
291 to_add.coeff = 0; // Clear since we merge it.
292 target.coeff = new_coeff;
293 return true;
294}
295
296// We only deal with coeff * Bool or coeff * (1 - Bool)
297//
298// TODO(user): Because of merges, we might have entry with a coefficient of
299// zero than are not useful. Remove them?
300int CutDataBuilder::AddOrMergeBooleanTerms(absl::Span<CutTerm> new_terms,
301 IntegerValue t, CutData* cut) {
302 if (new_terms.empty()) return 0;
303
304 bool_index_.clear();
305 secondary_bool_index_.clear();
306 int num_merges = 0;
307
308 // Fill the maps.
309 int i = 0;
310 for (CutTerm& term : new_terms) {
311 const IntegerVariable var = term.expr_vars[0];
312 auto& map = term.expr_coeffs[0] > 0 ? bool_index_ : secondary_bool_index_;
313 const auto [it, inserted] = map.insert({var, i});
314 if (!inserted) {
315 if (MergeIfPossible(t, term, new_terms[it->second])) {
316 ++num_merges;
317 }
318 }
319 ++i;
320 }
321
322 // Loop over the cut now. Note that we loop with indices as we might add new
323 // terms in the middle of the loop.
324 for (CutTerm& term : cut->terms) {
325 if (term.bound_diff != 1) continue;
326 if (!term.IsSimple()) continue;
327
328 const IntegerVariable var = term.expr_vars[0];
329 auto& map = term.expr_coeffs[0] > 0 ? bool_index_ : secondary_bool_index_;
330 auto it = map.find(var);
331 if (it == map.end()) continue;
332
333 // We found a match, try to merge the map entry into the cut.
334 // Note that we don't waste time erasing this entry from the map since
335 // we should have no duplicates in the original cut.
336 if (MergeIfPossible(t, new_terms[it->second], term)) {
337 ++num_merges;
338 }
339 }
340
341 // Finally add the terms we couldn't merge.
342 for (const CutTerm& term : new_terms) {
343 if (term.coeff == 0) continue;
344 cut->terms.push_back(term);
345 }
346
347 return num_merges;
348}
349
350// TODO(user): Divide by gcd first to avoid possible overflow in the
351// conversion? it is however unlikely given that our coeffs should be small.
352ABSL_DEPRECATED("Only used in tests, this will be removed.")
354 LinearConstraint* output) {
355 tmp_map_.clear();
356 if (cut.rhs > absl::int128(std::numeric_limits<int64_t>::max()) ||
357 cut.rhs < absl::int128(std::numeric_limits<int64_t>::min())) {
358 return false;
359 }
360 IntegerValue new_rhs = static_cast<int64_t>(cut.rhs);
361 for (const CutTerm& term : cut.terms) {
362 for (int i = 0; i < 2; ++i) {
363 if (term.expr_coeffs[i] == 0) continue;
364 if (!AddProductTo(term.coeff, term.expr_coeffs[i],
365 &tmp_map_[term.expr_vars[i]])) {
366 return false;
367 }
368 }
369 if (!AddProductTo(-term.coeff, term.expr_offset, &new_rhs)) {
370 return false;
371 }
372 }
373
374 output->lb = kMinIntegerValue;
375 output->ub = new_rhs;
376 output->resize(tmp_map_.size());
377 int new_size = 0;
378 for (const auto [var, coeff] : tmp_map_) {
379 if (coeff == 0) continue;
380 output->vars[new_size] = var;
381 output->coeffs[new_size] = coeff;
382 ++new_size;
383 }
384 output->resize(new_size);
385 DivideByGCD(output);
386 return true;
387}
388
389namespace {
390
391// Minimum amount of violation of the cut constraint by the solution. This
392// is needed to avoid numerical issues and adding cuts with minor effect.
393const double kMinCutViolation = 1e-4;
394
395IntegerValue PositiveRemainder(absl::int128 dividend,
396 IntegerValue positive_divisor) {
397 DCHECK_GT(positive_divisor, 0);
398 const IntegerValue m =
399 static_cast<int64_t>(dividend % absl::int128(positive_divisor.value()));
400 return m < 0 ? m + positive_divisor : m;
401}
402
403// We use the fact that f(k * divisor + rest) = k * f(divisor) + f(rest)
404absl::int128 ApplyToInt128(const std::function<IntegerValue(IntegerValue)>& f,
405 IntegerValue divisor, absl::int128 value) {
406 const IntegerValue rest = PositiveRemainder(value, divisor);
407 const absl::int128 k =
408 (value - absl::int128(rest.value())) / absl::int128(divisor.value());
409 const absl::int128 result =
410 k * absl::int128(f(divisor).value()) + absl::int128(f(rest).value());
411 return result;
412}
413
414// Apply f() to the cut with a potential improvement for one Boolean:
415//
416// If we have a Boolean X, and a cut: terms + a * X <= b;
417// By setting X to true or false, we have two inequalities:
418// terms <= b if X == 0
419// terms <= b - a if X == 1
420// We can apply f to both inequalities and recombine:
421// f(terms) <= f(b) * (1 - X) + f(b - a) * X
422// Which change the final coeff of X from f(a) to [f(b) - f(b - a)].
423// This can only improve the cut since f(b) >= f(b - a) + f(a)
424int ApplyWithPotentialBump(const std::function<IntegerValue(IntegerValue)>& f,
425 const IntegerValue divisor, CutData* cut) {
426 int bump_index = -1;
427 double bump_score = -1.0;
428 IntegerValue bump_coeff;
429 const IntegerValue remainder = PositiveRemainder(cut->rhs, divisor);
430 const IntegerValue f_remainder = f(remainder);
431 cut->rhs = ApplyToInt128(f, divisor, cut->rhs);
432 for (int i = 0; i < cut->terms.size(); ++i) {
433 CutTerm& entry = cut->terms[i];
434 const IntegerValue f_coeff = f(entry.coeff);
435 if (entry.bound_diff == 1) {
436 // TODO(user): we probably don't need int128 here, but we need
437 // t * (remainder - entry.coeff) not to overflow, and we can't really be
438 // sure.
439 const IntegerValue alternative =
440 entry.coeff > 0
441 ? f_remainder - f(remainder - entry.coeff)
442 : f_remainder - IntegerValue(static_cast<int64_t>(ApplyToInt128(
443 f, divisor,
444 absl::int128(remainder.value()) -
445 absl::int128(entry.coeff.value()))));
446 DCHECK_GE(alternative, f_coeff);
447 if (alternative > f_coeff) {
448 const double score = ToDouble(alternative - f_coeff) * entry.lp_value;
449 if (score > bump_score) {
450 bump_index = i;
451 bump_score = score;
452 bump_coeff = alternative;
453 }
454 }
455 }
456 entry.coeff = f_coeff;
457 }
458 if (bump_index >= 0) {
459 cut->terms[bump_index].coeff = bump_coeff;
460 return 1;
461 }
462 return 0;
463}
464
465} // namespace
466
467// Compute the larger t <= max_t such that t * rhs_remainder >= divisor / 2.
468//
469// This is just a separate function as it is slightly faster to compute the
470// result only once.
471IntegerValue GetFactorT(IntegerValue rhs_remainder, IntegerValue divisor,
472 IntegerValue max_magnitude) {
473 // Make sure that when we multiply the rhs or the coefficient by a factor t,
474 // we do not have an integer overflow. Note that the rhs should be counted
475 // in max_magnitude since we will apply f() on it.
476 IntegerValue max_t(std::numeric_limits<int64_t>::max());
477 if (max_magnitude != 0) {
478 max_t = max_t / max_magnitude;
479 }
480 return rhs_remainder == 0
481 ? max_t
482 : std::min(max_t, CeilRatio(divisor / 2, rhs_remainder));
483}
484
485std::function<IntegerValue(IntegerValue)> GetSuperAdditiveRoundingFunction(
486 IntegerValue rhs_remainder, IntegerValue divisor, IntegerValue t,
487 IntegerValue max_scaling) {
488 DCHECK_GE(max_scaling, 1);
489 DCHECK_GE(t, 1);
490
491 // Adjust after the multiplication by t.
492 rhs_remainder *= t;
493 DCHECK_LT(rhs_remainder, divisor);
494
495 // Make sure we don't have an integer overflow below. Note that we assume that
496 // divisor and the maximum coeff magnitude are not too different (maybe a
497 // factor 1000 at most) so that the final result will never overflow.
498 max_scaling =
499 std::min(max_scaling, std::numeric_limits<int64_t>::max() / divisor);
500
501 const IntegerValue size = divisor - rhs_remainder;
502 if (max_scaling == 1 || size == 1) {
503 // TODO(user): Use everywhere a two step computation to avoid overflow?
504 // First divide by divisor, then multiply by t. For now, we limit t so that
505 // we never have an overflow instead.
506 return [t, divisor](IntegerValue coeff) {
507 return FloorRatio(t * coeff, divisor);
508 };
509 } else if (size <= max_scaling) {
510 return [size, rhs_remainder, t, divisor](IntegerValue coeff) {
511 const IntegerValue t_coeff = t * coeff;
512 const IntegerValue ratio = FloorRatio(t_coeff, divisor);
513 const IntegerValue remainder = PositiveRemainder(t_coeff, divisor);
514 const IntegerValue diff = remainder - rhs_remainder;
515 return size * ratio + std::max(IntegerValue(0), diff);
516 };
517 } else if (max_scaling.value() * rhs_remainder.value() < divisor) {
518 // Because of our max_t limitation, the rhs_remainder might stay small.
519 //
520 // If it is "too small" we cannot use the code below because it will not be
521 // valid. So we just divide divisor into max_scaling bucket. The
522 // rhs_remainder will be in the bucket 0.
523 //
524 // Note(user): This seems the same as just increasing t, modulo integer
525 // overflows. Maybe we should just always do the computation like this so
526 // that we can use larger t even if coeff is close to kint64max.
527 return [t, divisor, max_scaling](IntegerValue coeff) {
528 const IntegerValue t_coeff = t * coeff;
529 const IntegerValue ratio = FloorRatio(t_coeff, divisor);
530 const IntegerValue remainder = PositiveRemainder(t_coeff, divisor);
531 const IntegerValue bucket = FloorRatio(remainder * max_scaling, divisor);
532 return max_scaling * ratio + bucket;
533 };
534 } else {
535 // We divide (size = divisor - rhs_remainder) into (max_scaling - 1) buckets
536 // and increase the function by 1 / max_scaling for each of them.
537 //
538 // Note that for different values of max_scaling, we get a family of
539 // functions that do not dominate each others. So potentially, a max scaling
540 // as low as 2 could lead to the better cut (this is exactly the Letchford &
541 // Lodi function).
542 //
543 // Another interesting fact, is that if we want to compute the maximum alpha
544 // for a constraint with 2 terms like:
545 // divisor * Y + (ratio * divisor + remainder) * X
546 // <= rhs_ratio * divisor + rhs_remainder
547 // so that we have the cut:
548 // Y + (ratio + alpha) * X <= rhs_ratio
549 // This is the same as computing the maximum alpha such that for all integer
550 // X > 0 we have CeilRatio(alpha * divisor * X, divisor)
551 // <= CeilRatio(remainder * X - rhs_remainder, divisor).
552 // We can prove that this alpha is of the form (n - 1) / n, and it will
553 // be reached by such function for a max_scaling of n.
554 //
555 // TODO(user): This function is not always maximal when
556 // size % (max_scaling - 1) == 0. Improve?
557 return [size, rhs_remainder, t, divisor, max_scaling](IntegerValue coeff) {
558 const IntegerValue t_coeff = t * coeff;
559 const IntegerValue ratio = FloorRatio(t_coeff, divisor);
560 const IntegerValue remainder = PositiveRemainder(t_coeff, divisor);
561 const IntegerValue diff = remainder - rhs_remainder;
562 const IntegerValue bucket =
563 diff > 0 ? CeilRatio(diff * (max_scaling - 1), size)
564 : IntegerValue(0);
565 return max_scaling * ratio + bucket;
566 };
567 }
568}
569
570std::function<IntegerValue(IntegerValue)> GetSuperAdditiveStrengtheningFunction(
571 IntegerValue positive_rhs, IntegerValue min_magnitude) {
572 CHECK_GT(positive_rhs, 0);
573 CHECK_GT(min_magnitude, 0);
574
575 if (min_magnitude >= CeilRatio(positive_rhs, 2)) {
576 return [positive_rhs](IntegerValue v) {
577 if (v >= 0) return IntegerValue(0);
578 if (v > -positive_rhs) return IntegerValue(-1);
579 return IntegerValue(-2);
580 };
581 }
582
583 // The transformation only work if 2 * second_threshold >= positive_rhs.
584 //
585 // TODO(user): Limit the number of value used with scaling like above.
586 min_magnitude = std::min(min_magnitude, FloorRatio(positive_rhs, 2));
587 const IntegerValue second_threshold = positive_rhs - min_magnitude;
588 return [positive_rhs, min_magnitude, second_threshold](IntegerValue v) {
589 if (v >= 0) return IntegerValue(0);
590 if (v <= -positive_rhs) return -positive_rhs;
591 if (v <= -second_threshold) return -second_threshold;
592
593 // This should actually never happen by the definition of min_magnitude.
594 // But with it, the function is supper-additive even if min_magnitude is not
595 // correct.
596 if (v >= -min_magnitude) return -min_magnitude;
597
598 // TODO(user): we might want to intoduce some step to reduce the final
599 // magnitude of the cut.
600 return v;
601 };
602}
603
604std::function<IntegerValue(IntegerValue)>
606 IntegerValue scaling) {
607 if (scaling >= positive_rhs) {
608 // Simple case, no scaling required.
609 return [positive_rhs](IntegerValue v) {
610 if (v >= 0) return IntegerValue(0);
611 if (v <= -positive_rhs) return -positive_rhs;
612 return v;
613 };
614 }
615
616 // We need to scale.
617 scaling =
618 std::min(scaling, IntegerValue(std::numeric_limits<int64_t>::max()) /
619 positive_rhs);
620 if (scaling == 1) {
621 return [](IntegerValue v) {
622 if (v >= 0) return IntegerValue(0);
623 return IntegerValue(-1);
624 };
625 }
626
627 // We divide [-positive_rhs + 1, 0] into (scaling - 1) bucket.
628 return [positive_rhs, scaling](IntegerValue v) {
629 if (v >= 0) return IntegerValue(0);
630 if (v <= -positive_rhs) return -scaling;
631 return FloorRatio(v * (scaling - 1), (positive_rhs - 1));
632 };
633}
634
636 if (!VLOG_IS_ON(1)) return;
637 if (shared_stats_ == nullptr) return;
638 std::vector<std::pair<std::string, int64_t>> stats;
639 stats.push_back({"rounding_cut/num_initial_ibs_", total_num_initial_ibs_});
640 stats.push_back(
641 {"rounding_cut/num_initial_merges_", total_num_initial_merges_});
642 stats.push_back({"rounding_cut/num_pos_lifts", total_num_pos_lifts_});
643 stats.push_back({"rounding_cut/num_neg_lifts", total_num_neg_lifts_});
644 stats.push_back(
645 {"rounding_cut/num_post_complements", total_num_post_complements_});
646 stats.push_back({"rounding_cut/num_overflows", total_num_overflow_abort_});
647 stats.push_back({"rounding_cut/num_adjusts", total_num_coeff_adjust_});
648 stats.push_back({"rounding_cut/num_merges", total_num_merges_});
649 stats.push_back({"rounding_cut/num_bumps", total_num_bumps_});
650 stats.push_back(
651 {"rounding_cut/num_final_complements", total_num_final_complements_});
652 stats.push_back({"rounding_cut/num_dominating_f", total_num_dominating_f_});
653 shared_stats_->AddStats(stats);
654}
655
656double IntegerRoundingCutHelper::GetScaledViolation(
657 IntegerValue divisor, IntegerValue max_scaling,
658 IntegerValue remainder_threshold, const CutData& cut) {
659 absl::int128 rhs = cut.rhs;
660 IntegerValue max_magnitude = cut.max_magnitude;
661 const IntegerValue initial_rhs_remainder = PositiveRemainder(rhs, divisor);
662 if (initial_rhs_remainder < remainder_threshold) return 0.0;
663
664 // We will adjust coefficient that are just under an exact multiple of
665 // divisor to an exact multiple. This is meant to get rid of small errors
666 // that appears due to rounding error in our exact computation of the
667 // initial constraint given to this class.
668 //
669 // Each adjustement will cause the initial_rhs_remainder to increase, and we
670 // do not want to increase it above divisor. Our threshold below guarantees
671 // this. Note that the higher the rhs_remainder becomes, the more the
672 // function f() has a chance to reduce the violation, so it is not always a
673 // good idea to use all the slack we have between initial_rhs_remainder and
674 // divisor.
675 //
676 // TODO(user): We could see if for a fixed function f, the increase is
677 // interesting?
678 // before: f(rhs) - f(coeff) * lp_value
679 // after: f(rhs + increase * bound_diff) - f(coeff + increase) * lp_value.
680 adjusted_coeffs_.clear();
681 const IntegerValue adjust_threshold =
682 (divisor - initial_rhs_remainder - 1) /
683 IntegerValue(std::max(1000, cut.num_relevant_entries));
684 if (adjust_threshold > 0) {
685 // Even before we finish the adjust, we can have a lower bound on the
686 // activily loss using this divisor, and so we can abort early. This is
687 // similar to what is done below.
688 double max_violation = static_cast<double>(initial_rhs_remainder.value());
689 for (int i = 0; i < cut.num_relevant_entries; ++i) {
690 const CutTerm& entry = cut.terms[i];
691 const IntegerValue remainder = PositiveRemainder(entry.coeff, divisor);
692 if (remainder == 0) continue;
693 if (remainder <= initial_rhs_remainder) {
694 // We do not know exactly f() yet, but it will always round to the
695 // floor of the division by divisor in this case.
696 max_violation -=
697 static_cast<double>(remainder.value()) * entry.lp_value;
698 if (max_violation <= 1e-3) return 0.0;
699 continue;
700 }
701
702 // Adjust coeff of the form k * divisor - epsilon.
703 const IntegerValue adjust = divisor - remainder;
704 const IntegerValue prod = CapProdI(adjust, entry.bound_diff);
705 if (prod <= adjust_threshold) {
706 rhs += absl::int128(prod.value());
707 const IntegerValue new_coeff = entry.coeff + adjust;
708 adjusted_coeffs_.push_back({i, new_coeff});
709 max_magnitude = std::max(max_magnitude, IntTypeAbs(new_coeff));
710 }
711 }
712 }
713
714 const IntegerValue rhs_remainder = PositiveRemainder(rhs, divisor);
715 const IntegerValue t = GetFactorT(rhs_remainder, divisor, max_magnitude);
716 const auto f =
717 GetSuperAdditiveRoundingFunction(rhs_remainder, divisor, t, max_scaling);
718
719 // As we round coefficients, we will compute the loss compared to the
720 // current scaled constraint activity. As soon as this loss crosses the
721 // slack, then we known that there is no violation and we can abort early.
722 //
723 // TODO(user): modulo the scaling, we could compute the exact threshold
724 // using our current best cut. Note that we also have to account the change
725 // in slack due to the adjust code above.
726 const double scaling = ToDouble(f(divisor)) / ToDouble(divisor);
727 double max_violation = scaling * ToDouble(rhs_remainder);
728
729 // Apply f() to the cut and compute the cut violation. Note that it is
730 // okay to just look at the relevant indices since the other have a lp
731 // value which is almost zero. Doing it like this is faster, and even if
732 // the max_magnitude might be off it should still be relevant enough.
733 double violation = -static_cast<double>(ApplyToInt128(f, divisor, rhs));
734 double l2_norm = 0.0;
735 int adjusted_coeffs_index = 0;
736 for (int i = 0; i < cut.num_relevant_entries; ++i) {
737 const CutTerm& entry = cut.terms[i];
738
739 // Adjust coeff according to our previous computation if needed.
740 IntegerValue coeff = entry.coeff;
741 if (adjusted_coeffs_index < adjusted_coeffs_.size() &&
742 adjusted_coeffs_[adjusted_coeffs_index].first == i) {
743 coeff = adjusted_coeffs_[adjusted_coeffs_index].second;
744 adjusted_coeffs_index++;
745 }
746
747 if (coeff == 0) continue;
748 const IntegerValue new_coeff = f(coeff);
749 const double new_coeff_double = ToDouble(new_coeff);
750 const double lp_value = entry.lp_value;
751
752 // TODO(user): Shall we compute the norm after slack are substituted back?
753 // it might be widely different. Another reason why this might not be
754 // the best measure.
755 l2_norm += new_coeff_double * new_coeff_double;
756 violation += new_coeff_double * lp_value;
757 max_violation -= (scaling * ToDouble(coeff) - new_coeff_double) * lp_value;
758 if (max_violation <= 1e-3) return 0.0;
759 }
760 if (l2_norm == 0.0) return 0.0;
761
762 // Here we scale by the L2 norm over the "relevant" positions. This seems
763 // to work slighly better in practice.
764 //
765 // Note(user): The non-relevant position have an LP value of zero. If their
766 // coefficient is positive, it seems good not to take it into account in the
767 // norm since the larger this coeff is, the stronger the cut. If the coeff
768 // is negative though, a large coeff means a small increase from zero of the
769 // lp value will make the cut satisfied, so we might want to look at them.
770 return violation / sqrt(l2_norm);
771}
772
773// TODO(user): This is slow, 50% of run time on a2c1s1.pb.gz. Optimize!
775 RoundingOptions options, const CutData& base_ct,
776 ImpliedBoundsProcessor* ib_processor) {
777 // Try IB before heuristic?
778 // This should be better except it can mess up the norm and the divisors.
779 cut_ = base_ct;
780 if (options.use_ib_before_heuristic && ib_processor != nullptr) {
781 std::vector<CutTerm>* new_bool_terms =
782 ib_processor->ClearedMutableTempTerms();
783 for (CutTerm& term : cut_.terms) {
784 if (term.bound_diff <= 1) continue;
785 if (!term.HasRelevantLpValue()) continue;
786
787 if (options.prefer_positive_ib && term.coeff < 0) {
788 // We complement the term before trying the implied bound.
789 term.Complement(&cut_.rhs);
790 if (ib_processor->TryToExpandWithLowerImpliedbound(
791 IntegerValue(1),
792 /*complement=*/true, &term, &cut_.rhs, new_bool_terms)) {
793 ++total_num_initial_ibs_;
794 continue;
795 }
796 term.Complement(&cut_.rhs);
797 }
798
799 if (ib_processor->TryToExpandWithLowerImpliedbound(
800 IntegerValue(1),
801 /*complement=*/true, &term, &cut_.rhs, new_bool_terms)) {
802 ++total_num_initial_ibs_;
803 }
804 }
805
806 // TODO(user): We assume that this is called with and without the option
807 // use_ib_before_heuristic, so that we can abort if no IB has been applied
808 // since then we will redo the computation. This is not really clean.
809 if (new_bool_terms->empty()) return false;
810 total_num_initial_merges_ +=
812 absl::MakeSpan(*new_bool_terms), IntegerValue(1), &cut_);
813 }
814
815 // Our heuristic will try to generate a few different cuts, and we will keep
816 // the most violated one scaled by the l2 norm of the relevant position.
817 //
818 // TODO(user): Experiment for the best value of this initial violation
819 // threshold. Note also that we use the l2 norm on the restricted position
820 // here. Maybe we should change that? On that note, the L2 norm usage seems
821 // a bit weird to me since it grows with the number of term in the cut. And
822 // often, we already have a good cut, and we make it stronger by adding
823 // extra terms that do not change its activity.
824 //
825 // The discussion above only concern the best_scaled_violation initial
826 // value. The remainder_threshold allows to not consider cuts for which the
827 // final efficacity is clearly lower than 1e-3 (it is a bound, so we could
828 // generate cuts with a lower efficacity than this).
829 //
830 // TODO(user): If the rhs is small and close to zero, we might want to
831 // consider different way of complementing the variables.
832 cut_.SortRelevantEntries();
833 const IntegerValue remainder_threshold(
834 std::max(IntegerValue(1), cut_.max_magnitude / 1000));
835 if (cut_.rhs >= 0 && cut_.rhs < remainder_threshold.value()) {
836 return false;
837 }
838
839 // There is no point trying twice the same divisor or a divisor that is too
840 // small. Note that we use a higher threshold than the remainder_threshold
841 // because we can boost the remainder thanks to our adjusting heuristic
842 // below and also because this allows to have cuts with a small range of
843 // coefficients.
844 divisors_.clear();
845 for (const CutTerm& entry : cut_.terms) {
846 // Note that because of the slacks, initial coeff are here too.
847 const IntegerValue magnitude = IntTypeAbs(entry.coeff);
848 if (magnitude <= remainder_threshold) continue;
849 divisors_.push_back(magnitude);
850
851 // If we have too many divisor to try, restrict to the first ones which
852 // should correspond to the highest lp values.
853 if (divisors_.size() > 50) break;
854 }
855 if (divisors_.empty()) return false;
856 gtl::STLSortAndRemoveDuplicates(&divisors_, std::greater<IntegerValue>());
857
858 // Note that most of the time is spend here since we call this function on
859 // many linear equation, and just a few of them have a good enough scaled
860 // violation. We can spend more time afterwards to tune the cut.
861 //
862 // TODO(user): Avoid quadratic algorithm? Note that we are quadratic in
863 // relevant positions not the full cut size, but this is still too much on
864 // some problems.
865 IntegerValue best_divisor(0);
866 double best_scaled_violation = 1e-3;
867 for (const IntegerValue divisor : divisors_) {
868 // Note that the function will abort right away if PositiveRemainder() is
869 // not good enough, so it is quick for bad divisor.
870 const double violation = GetScaledViolation(divisor, options.max_scaling,
871 remainder_threshold, cut_);
872 if (violation > best_scaled_violation) {
873 best_scaled_violation = violation;
874 best_adjusted_coeffs_ = adjusted_coeffs_;
875 best_divisor = divisor;
876 }
877 }
878 if (best_divisor == 0) return false;
879
880 // Try best_divisor divided by small number.
881 for (int div = 2; div < 9; ++div) {
882 const IntegerValue divisor = best_divisor / IntegerValue(div);
883 if (divisor <= 1) continue;
884 const double violation = GetScaledViolation(divisor, options.max_scaling,
885 remainder_threshold, cut_);
886 if (violation > best_scaled_violation) {
887 best_scaled_violation = violation;
888 best_adjusted_coeffs_ = adjusted_coeffs_;
889 best_divisor = divisor;
890 }
891 }
892
893 // Re try complementation on the transformed cut.
894 // TODO(user): This can be quadratic! we don't want to try too much of them.
895 // Or optimize the algo, we should be able to be more incremental here.
896 // see on g200x740.pb.gz for instance.
897 for (CutTerm& entry : cut_.terms) {
898 if (!entry.HasRelevantLpValue()) break;
899 if (entry.coeff % best_divisor == 0) continue;
900
901 // Temporary complement this variable.
902 entry.Complement(&cut_.rhs);
903
904 const double violation = GetScaledViolation(
905 best_divisor, options.max_scaling, remainder_threshold, cut_);
906 if (violation > best_scaled_violation) {
907 // keep the change.
908 ++total_num_post_complements_;
909 best_scaled_violation = violation;
910 best_adjusted_coeffs_ = adjusted_coeffs_;
911 } else {
912 // Restore.
913 entry.Complement(&cut_.rhs);
914 }
915 }
916
917 // Adjust coefficients as computed by the best GetScaledViolation().
918 for (const auto [index, new_coeff] : best_adjusted_coeffs_) {
919 ++total_num_coeff_adjust_;
920 CutTerm& entry = cut_.terms[index];
921 const IntegerValue remainder = new_coeff - entry.coeff;
922 CHECK_GT(remainder, 0);
923 entry.coeff = new_coeff;
924 cut_.rhs += absl::int128(remainder.value()) *
925 absl::int128(entry.bound_diff.value());
926 cut_.max_magnitude = std::max(cut_.max_magnitude, IntTypeAbs(new_coeff));
927 }
928
929 // Create the base super-additive function f().
930 const IntegerValue rhs_remainder = PositiveRemainder(cut_.rhs, best_divisor);
931 IntegerValue factor_t =
932 GetFactorT(rhs_remainder, best_divisor, cut_.max_magnitude);
933 auto f = GetSuperAdditiveRoundingFunction(rhs_remainder, best_divisor,
934 factor_t, options.max_scaling);
935
936 // Look amongst all our possible function f() for one that dominate greedily
937 // our current best one. Note that we prefer lower scaling factor since that
938 // result in a cut with lower coefficients.
939 //
940 // We only look at relevant position and ignore the other. Not sure this is
941 // the best approach.
942 remainders_.clear();
943 for (const CutTerm& entry : cut_.terms) {
944 if (!entry.HasRelevantLpValue()) break;
945 const IntegerValue coeff = entry.coeff;
946 const IntegerValue r = PositiveRemainder(coeff, best_divisor);
947 if (r > rhs_remainder) remainders_.push_back(r);
948 }
950 if (remainders_.size() <= 100) {
951 best_rs_.clear();
952 for (const IntegerValue r : remainders_) {
953 best_rs_.push_back(f(r));
954 }
955 IntegerValue best_d = f(best_divisor);
956
957 // Note that the complexity seems high 100 * 2 * options.max_scaling, but
958 // this only run on cuts that are already efficient and the inner loop tend
959 // to abort quickly. I didn't see this code in the cpu profile so far.
960 for (const IntegerValue t :
961 {IntegerValue(1),
962 GetFactorT(rhs_remainder, best_divisor, cut_.max_magnitude)}) {
963 for (IntegerValue s(2); s <= options.max_scaling; ++s) {
964 const auto g =
965 GetSuperAdditiveRoundingFunction(rhs_remainder, best_divisor, t, s);
966 int num_strictly_better = 0;
967 rs_.clear();
968 const IntegerValue d = g(best_divisor);
969 for (int i = 0; i < best_rs_.size(); ++i) {
970 const IntegerValue temp = g(remainders_[i]);
971 if (temp * best_d < best_rs_[i] * d) break;
972 if (temp * best_d > best_rs_[i] * d) num_strictly_better++;
973 rs_.push_back(temp);
974 }
975 if (rs_.size() == best_rs_.size() && num_strictly_better > 0) {
976 ++total_num_dominating_f_;
977 f = g;
978 factor_t = t;
979 best_rs_ = rs_;
980 best_d = d;
981 }
982 }
983 }
984 }
985
986 // Use implied bounds to "lift" Booleans into the cut.
987 // This should lead to stronger cuts even if the norms might be worse.
988 num_ib_used_ = 0;
989 if (ib_processor != nullptr) {
990 const auto [num_lb, num_ub, num_merges] =
991 ib_processor->PostprocessWithImpliedBound(f, factor_t, &cut_);
992 total_num_pos_lifts_ += num_lb;
993 total_num_neg_lifts_ += num_ub;
994 total_num_merges_ += num_merges;
995 num_ib_used_ = num_lb + num_ub;
996 }
997
998 // More complementation, but for the same f.
999 // If we can do that, it probably means our heuristics above are not great.
1000 for (int i = 0; i < 3; ++i) {
1001 const int64_t saved = total_num_final_complements_;
1002 for (CutTerm& entry : cut_.terms) {
1003 // Complementing an entry gives:
1004 // [a * X <= b] -> [-a * (diff - X) <= b - a * diff]
1005 //
1006 // We will compare what happen when we apply f:
1007 // [f(b) - f(a) * lp(X)] -> [f(b - a * diff) - f(-a) * (diff - lp(X))].
1008 //
1009 // If lp(X) is zero, then the transformation is always worse.
1010 // Because f(b - a * diff) >= f(b) + f(-a) * diff by super-additivity.
1011 //
1012 // However the larger is X, the better it gets since at diff, we have
1013 // f(b) >= f(b - a * diff) + f(a * diff) >= f(b - a * diff) + f(a) * diff.
1014 //
1015 // TODO(user): It is still unclear if we have a * X + b * (1 - X) <= rhs
1016 // for a Boolean X, what is the best way to apply f and if we should merge
1017 // the terms. If there is no other terms, best is probably
1018 // f(rhs - a) * X + f(rhs - b) * (1 - X).
1019 if (entry.coeff % best_divisor == 0) continue;
1020 if (!entry.HasRelevantLpValue()) continue;
1021
1022 // Avoid potential overflow here.
1023 const IntegerValue prod(CapProdI(entry.bound_diff, entry.coeff));
1024 const IntegerValue remainder = PositiveRemainder(cut_.rhs, best_divisor);
1025 if (ProdOverflow(factor_t, prod)) continue;
1026 if (ProdOverflow(factor_t, CapSubI(remainder, prod))) continue;
1027
1028 const double lp1 =
1029 ToDouble(f(remainder)) - ToDouble(f(entry.coeff)) * entry.lp_value;
1030 const double lp2 = ToDouble(f(remainder - prod)) -
1031 ToDouble(f(-entry.coeff)) *
1032 (ToDouble(entry.bound_diff) - entry.lp_value);
1033 if (lp2 + 1e-2 < lp1) {
1034 entry.Complement(&cut_.rhs);
1035 ++total_num_final_complements_;
1036 }
1037 }
1038 if (total_num_final_complements_ == saved) break;
1039 }
1040
1041 total_num_bumps_ += ApplyWithPotentialBump(f, best_divisor, &cut_);
1042 return true;
1043}
1044
1046 if (!VLOG_IS_ON(1)) return;
1047 if (shared_stats_ == nullptr) return;
1048
1049 std::vector<std::pair<std::string, int64_t>> stats;
1050 const auto add_stats = [&stats](absl::string_view name, const CutStats& s) {
1051 stats.push_back(
1052 {absl::StrCat(name, "num_overflows"), s.num_overflow_aborts});
1053 stats.push_back({absl::StrCat(name, "num_lifting"), s.num_lifting});
1054 stats.push_back({absl::StrCat(name, "num_initial_ib"), s.num_initial_ibs});
1055 stats.push_back({absl::StrCat(name, "num_implied_lb"), s.num_lb_ibs});
1056 stats.push_back({absl::StrCat(name, "num_implied_ub"), s.num_ub_ibs});
1057 stats.push_back({absl::StrCat(name, "num_bumps"), s.num_bumps});
1058 stats.push_back({absl::StrCat(name, "num_cuts"), s.num_cuts});
1059 stats.push_back({absl::StrCat(name, "num_merges"), s.num_merges});
1060 };
1061 add_stats("cover_cut/", cover_stats_);
1062 add_stats("flow_cut/", flow_stats_);
1063 add_stats("ls_cut/", ls_stats_);
1064 shared_stats_->AddStats(stats);
1065}
1066
1067namespace {
1068
1069struct LargeCoeffFirst {
1070 bool operator()(const CutTerm& a, const CutTerm& b) const {
1071 if (a.coeff == b.coeff) {
1072 return a.LpDistToMaxValue() > b.LpDistToMaxValue();
1073 }
1074 return a.coeff > b.coeff;
1075 }
1076};
1077
1078struct SmallContribFirst {
1079 bool operator()(const CutTerm& a, const CutTerm& b) const {
1080 const double contrib_a = a.lp_value * static_cast<double>(a.coeff.value());
1081 const double contrib_b = b.lp_value * static_cast<double>(b.coeff.value());
1082 return contrib_a < contrib_b;
1083 }
1084};
1085
1086struct LargeContribFirst {
1087 bool operator()(const CutTerm& a, const CutTerm& b) const {
1088 const double contrib_a = a.lp_value * static_cast<double>(a.coeff.value());
1089 const double contrib_b = b.lp_value * static_cast<double>(b.coeff.value());
1090 return contrib_a > contrib_b;
1091 }
1092};
1093
1094struct LargeLpValueFirst {
1095 bool operator()(const CutTerm& a, const CutTerm& b) const {
1096 if (a.lp_value == b.lp_value) {
1097 // Prefer high coefficients if the distance is the same.
1098 // We have more chance to get a cover this way.
1099 return a.coeff > b.coeff;
1100 }
1101 return a.lp_value > b.lp_value;
1102 }
1103};
1104
1105// When minimizing a cover we want to remove bad score (large dist) divided by
1106// item size. Note that here we assume item are "boolean" fully taken or not.
1107// for general int we use (lp_dist / bound_diff) / (coeff * bound_diff) which
1108// lead to the same formula as for Booleans.
1109struct KnapsackAdd {
1110 bool operator()(const CutTerm& a, const CutTerm& b) const {
1111 const double contrib_a =
1112 a.LpDistToMaxValue() / static_cast<double>(a.coeff.value());
1113 const double contrib_b =
1114 b.LpDistToMaxValue() / static_cast<double>(b.coeff.value());
1115 return contrib_a < contrib_b;
1116 }
1117};
1118struct KnapsackRemove {
1119 bool operator()(const CutTerm& a, const CutTerm& b) const {
1120 const double contrib_a =
1121 a.LpDistToMaxValue() / static_cast<double>(a.coeff.value());
1122 const double contrib_b =
1123 b.LpDistToMaxValue() / static_cast<double>(b.coeff.value());
1124 return contrib_a > contrib_b;
1125 }
1126};
1127
1128} // namespace.
1129
1130// Transform to a minimal cover. We want to greedily remove the largest coeff
1131// first, so we have more chance for the "lifting" below which can increase
1132// the cut violation. If the coeff are the same, we prefer to remove high
1133// distance from upper bound first.
1134template <class Compare>
1135int CoverCutHelper::MinimizeCover(int cover_size, absl::int128 slack) {
1136 CHECK_GT(slack, 0);
1137 absl::Span<CutTerm> terms = absl::MakeSpan(cut_.terms);
1138 std::sort(terms.begin(), terms.begin() + cover_size, Compare());
1139 for (int i = 0; i < cover_size;) {
1140 const CutTerm& t = terms[i];
1141 const absl::int128 contrib =
1142 absl::int128(t.bound_diff.value()) * absl::int128(t.coeff.value());
1143 if (contrib < slack) {
1144 slack -= contrib;
1145 std::swap(terms[i], terms[--cover_size]);
1146 } else {
1147 ++i;
1148 }
1149 }
1150 DCHECK_GT(cover_size, 0);
1151 return cover_size;
1152}
1153
1154template <class CompareAdd, class CompareRemove>
1155int CoverCutHelper::GetCoverSize(int relevant_size) {
1156 if (relevant_size == 0) return 0;
1157 absl::Span<CutTerm> terms = absl::MakeSpan(cut_.terms);
1158
1159 // Take first all at variable at upper bound, and ignore the one at lower
1160 // bound.
1161 int part1 = 0;
1162 for (int i = 0; i < relevant_size;) {
1163 CutTerm& term = terms[i];
1164 const double dist = term.LpDistToMaxValue();
1165 if (dist < 1e-6) {
1166 // Move to part 1.
1167 std::swap(term, terms[part1]);
1168 ++i;
1169 ++part1;
1170 } else if (term.lp_value > 1e-6) {
1171 // Keep in part 2.
1172 ++i;
1173 } else {
1174 // Exclude entirely (part 3).
1175 --relevant_size;
1176 std::swap(term, terms[relevant_size]);
1177 }
1178 }
1179 std::sort(terms.begin() + part1, terms.begin() + relevant_size, CompareAdd());
1180
1181 // We substract the initial rhs to avoid overflow.
1182 DCHECK_GE(cut_.rhs, 0);
1183 absl::int128 max_shifted_activity = -cut_.rhs;
1184 absl::int128 shifted_round_up = -cut_.rhs;
1185 int cover_size = 0;
1186 for (; cover_size < relevant_size; ++cover_size) {
1187 if (max_shifted_activity > 0) break;
1188 const CutTerm& term = terms[cover_size];
1189 max_shifted_activity += absl::int128(term.coeff.value()) *
1190 absl::int128(term.bound_diff.value());
1191 shifted_round_up += absl::int128(term.coeff.value()) *
1192 std::min(absl::int128(term.bound_diff.value()),
1193 absl::int128(std::ceil(term.lp_value - 1e-6)));
1194 }
1195
1196 DCHECK_GE(cover_size, 0);
1197 if (shifted_round_up <= 0) {
1198 return 0;
1199 }
1200 return MinimizeCover<CompareRemove>(cover_size, max_shifted_activity);
1201}
1202
1203// Try a simple cover heuristic.
1204// Look for violated CUT of the form: sum (UB - X) or (X - LB) >= 1.
1205int CoverCutHelper::GetCoverSizeForBooleans() {
1206 absl::Span<CutTerm> terms = absl::MakeSpan(cut_.terms);
1207
1208 // Sorting can be slow, so we start by splitting the vector in 3 parts
1209 // - Can always be in cover
1210 // - Candidates that needs sorting
1211 // - At most one can be in cover (we keep the max).
1212 int part1 = 0;
1213 int relevant_size = terms.size();
1214 int best_in_part3 = -1;
1215 const double threshold = 1.0 - 1.0 / static_cast<double>(terms.size());
1216 for (int i = 0; i < relevant_size;) {
1217 const double lp_value = terms[i].lp_value;
1218
1219 // Exclude non-Boolean.
1220 if (terms[i].bound_diff > 1) {
1221 --relevant_size;
1222 std::swap(terms[i], terms[relevant_size]);
1223 continue;
1224 }
1225
1226 if (lp_value >= threshold) {
1227 // Move to part 1.
1228 std::swap(terms[i], terms[part1]);
1229 ++i;
1230 ++part1;
1231 } else if (lp_value > 0.5) {
1232 // Keep in part 2.
1233 ++i;
1234 } else {
1235 // Only keep the max (part 3).
1236 --relevant_size;
1237 std::swap(terms[i], terms[relevant_size]);
1238
1239 if (best_in_part3 == -1 ||
1240 LargeLpValueFirst()(terms[relevant_size], terms[best_in_part3])) {
1241 best_in_part3 = relevant_size;
1242 }
1243 }
1244 }
1245
1246 if (best_in_part3 != -1) {
1247 std::swap(terms[relevant_size], terms[best_in_part3]);
1248 ++relevant_size;
1249 }
1250
1251 // Sort by decreasing Lp value.
1252 std::sort(terms.begin() + part1, terms.begin() + relevant_size,
1253 LargeLpValueFirst());
1254
1255 double activity = 0.0;
1256 int cover_size = relevant_size;
1257 absl::int128 slack = -cut_.rhs;
1258 for (int i = 0; i < relevant_size; ++i) {
1259 const CutTerm& term = terms[i];
1260 activity += term.LpDistToMaxValue();
1261
1262 // As an heuristic we select all the term so that the sum of distance
1263 // to the upper bound is <= 1.0. If the corresponding slack is positive,
1264 // then we will have a cut of violation at least 0.0. Note that this
1265 // violation can be improved by the lifting.
1266 //
1267 // TODO(user): experiment with different threshold (even greater than one).
1268 // Or come up with an algo that incorporate the lifting into the heuristic.
1269 if (activity > 0.9999) {
1270 cover_size = i; // before this entry.
1271 break;
1272 }
1273
1274 // TODO(user): Stop if we overflow int128 max! Note that because we scale
1275 // things so that the max coeff is 2^52, this is unlikely.
1276 slack += absl::int128(term.coeff.value()) *
1277 absl::int128(term.bound_diff.value());
1278 }
1279
1280 // If the rhs is now negative, we have a cut.
1281 //
1282 // Note(user): past this point, now that a given "base" cover has been chosen,
1283 // we basically compute the cut (of the form sum X <= bound) with the maximum
1284 // possible violation. Note also that we lift as much as possible, so we don't
1285 // necessarily optimize for the cut efficacity though. But we do get a
1286 // stronger cut.
1287 if (slack <= 0) {
1288 return 0;
1289 }
1290 if (cover_size == 0) return 0;
1291 return MinimizeCover<LargeCoeffFirst>(cover_size, slack);
1292}
1293
1294void CoverCutHelper::InitializeCut(const CutData& input_ct) {
1295 num_lifting_ = 0;
1296 cut_ = input_ct;
1297
1298 // We should have dealt with an infeasible constraint before.
1299 // Note that because of our scaling, it is unlikely we will overflow int128.
1300 CHECK_GE(cut_.rhs, 0);
1301 DCHECK(cut_.AllCoefficientsArePositive());
1302}
1303
1305 ImpliedBoundsProcessor* ib_processor) {
1306 InitializeCut(input_ct);
1307
1308 // Tricky: This only work because the cut absl128 rhs is not changed by these
1309 // operations.
1310 if (ib_processor != nullptr) {
1311 std::vector<CutTerm>* new_bool_terms =
1312 ib_processor->ClearedMutableTempTerms();
1313 for (CutTerm& term : cut_.terms) {
1314 // We only look at non-Boolean with an lp value not close to the upper
1315 // bound.
1316 if (term.bound_diff <= 1) continue;
1317 if (term.lp_value + 1e-4 > AsDouble(term.bound_diff)) continue;
1318
1319 if (ib_processor->TryToExpandWithLowerImpliedbound(
1320 IntegerValue(1),
1321 /*complement=*/false, &term, &cut_.rhs, new_bool_terms)) {
1322 ++cover_stats_.num_initial_ibs;
1323 }
1324 }
1325
1327 absl::MakeSpan(*new_bool_terms), IntegerValue(1), &cut_);
1328 }
1329
1330 bool has_relevant_int = false;
1331 for (const CutTerm& term : cut_.terms) {
1332 if (term.HasRelevantLpValue() && term.bound_diff > 1) {
1333 has_relevant_int = true;
1334 break;
1335 }
1336 }
1337
1338 const int base_size = static_cast<int>(cut_.terms.size());
1339 const int cover_size =
1340 has_relevant_int
1341 ? GetCoverSize<LargeContribFirst, LargeCoeffFirst>(base_size)
1342 : GetCoverSizeForBooleans();
1343 if (!has_relevant_int && ib_processor == nullptr) {
1344 // If some implied bound substitution are possible, we do not cache anything
1345 // currently because the logic is currently sighlty different between the
1346 // two code. Fix?
1347 has_bool_base_ct_ = true;
1348 bool_cover_size_ = cover_size;
1349 if (cover_size == 0) return false;
1350 bool_base_ct_ = cut_;
1351 }
1352 if (cover_size == 0) return false;
1353
1354 // The cut is just obtained by complementing the variable in the cover and
1355 // applying the MIR super additive function.
1356 //
1357 // Note that since all coeff in the cover will now be negative. If we do no
1358 // scaling, and if we use max_coeff_in_cover to construct f(), they will be
1359 // mapped by f() to -1 and we get the classical cover inequality. With scaling
1360 // we can get a strictly dominating cut though.
1361 //
1362 // TODO(user): we don't have to pick max_coeff_in_cover and could use the
1363 // coefficient of the most fractional variable. Or like in the MIR code try
1364 // a few of them. Currently, the cut in the test is worse if we don't take
1365 // the max_coeff_in_cover though, so we need more understanding.
1366 //
1367 // TODO(user): It seems we could use a more advanced lifting function
1368 // described later in the paper. Investigate.
1369 IntegerValue best_coeff = 0;
1370 double best_score = -1.0;
1371 IntegerValue max_coeff_in_cover(0);
1372 for (int i = 0; i < cover_size; ++i) {
1373 CutTerm& term = cut_.terms[i];
1374 max_coeff_in_cover = std::max(max_coeff_in_cover, term.coeff);
1375 const double score =
1376 std::abs(term.lp_value - std::floor(term.lp_value + 1e-6)) *
1377 ToDouble(term.coeff);
1378 if (score > best_score) {
1379 best_score = score;
1380 best_coeff = term.coeff;
1381 }
1382 term.Complement(&cut_.rhs);
1383 }
1384 CHECK_LT(cut_.rhs, 0); // Because we complemented a cover.
1385
1386 // TODO(user): Experiment without this line that basically disable scoring.
1387 best_coeff = max_coeff_in_cover;
1388
1389 // TODO(user): experiment with different value of scaling and param t.
1390 std::function<IntegerValue(IntegerValue)> f;
1391 {
1392 IntegerValue max_magnitude = 0;
1393 for (const CutTerm& term : cut_.terms) {
1394 max_magnitude = std::max(max_magnitude, IntTypeAbs(term.coeff));
1395 }
1396 const IntegerValue max_scaling(std::min(
1397 IntegerValue(6000), FloorRatio(kMaxIntegerValue, max_magnitude)));
1398 const IntegerValue remainder = PositiveRemainder(cut_.rhs, best_coeff);
1399 f = GetSuperAdditiveRoundingFunction(remainder, best_coeff, IntegerValue(1),
1400 max_scaling);
1401 }
1402
1403 if (ib_processor != nullptr) {
1404 const auto [num_lb, num_ub, num_merges] =
1405 ib_processor->PostprocessWithImpliedBound(f, /*factor_t=*/1, &cut_);
1406 cover_stats_.num_lb_ibs += num_lb;
1407 cover_stats_.num_ub_ibs += num_ub;
1408 cover_stats_.num_merges += num_merges;
1409 }
1410
1411 cover_stats_.num_bumps += ApplyWithPotentialBump(f, best_coeff, &cut_);
1412
1413 // Update counters.
1414 for (int i = cover_size; i < cut_.terms.size(); ++i) {
1415 if (cut_.terms[i].coeff != 0) ++num_lifting_;
1416 }
1417 cover_stats_.num_lifting += num_lifting_;
1418 ++cover_stats_.num_cuts;
1419 return true;
1420}
1421
1423 ImpliedBoundsProcessor* ib_processor) {
1424 InitializeCut(input_ct);
1425
1426 // TODO(user): Change the heuristic to depends on the lp_value of the implied
1427 // bounds. This way we can exactly match what happen in the old
1428 // FlowCoverCutHelper.
1429 const int base_size = static_cast<int>(cut_.terms.size());
1430 const int cover_size = GetCoverSize<KnapsackAdd, KnapsackRemove>(base_size);
1431 if (cover_size == 0) return false;
1432
1433 // After complementing the term in the cover, we have
1434 // sum -ci.X + other_terms <= -slack;
1435 for (int i = 0; i < cover_size; ++i) {
1436 cut_.terms[i].Complement(&cut_.rhs);
1437
1438 // We do not support complex terms, but we shouldn't get any.
1439 if (cut_.terms[i].expr_coeffs[1] != 0) return false;
1440 }
1441
1442 // The algorithm goes as follow:
1443 // - Compute heuristically a minimal cover.
1444 // - We have sum_cover ci.Xi >= slack where Xi is distance to upper bound.
1445 // - Apply coefficient strenghtening if ci > slack.
1446 //
1447 // Using implied bound we have two cases (all coeffs positive):
1448 // 1/ ci.Xi = ci.fi.Bi + ci.Si : always good.
1449 // 2/ ci.Xi = ci.di.Bi - ci.Si <= di.Bi: good if Si lp_value is zero.
1450 //
1451 // Note that if everything is Boolean, we just get a normal cover and coeff
1452 // strengthening just result in all coeff at 1, so worse than our cover
1453 // heuristic.
1454 CHECK_LT(cut_.rhs, 0);
1455 if (cut_.rhs <= absl::int128(std::numeric_limits<int64_t>::min())) {
1456 return false;
1457 }
1458
1459 bool has_large_coeff = false;
1460 for (const CutTerm& term : cut_.terms) {
1461 if (IntTypeAbs(term.coeff) > 1'000'000) {
1462 has_large_coeff = true;
1463 break;
1464 }
1465 }
1466
1467 // TODO(user): Shouldn't we just use rounding f() with maximum coeff to allows
1468 // lift of all other terms? but then except for the heuristic the cut is
1469 // really similar to the cover cut.
1470 const IntegerValue positive_rhs = -static_cast<int64_t>(cut_.rhs);
1471 IntegerValue min_magnitude = kMaxIntegerValue;
1472 for (int i = 0; i < cover_size; ++i) {
1473 const IntegerValue magnitude = IntTypeAbs(cut_.terms[i].coeff);
1474 min_magnitude = std::min(min_magnitude, magnitude);
1475 }
1476 const bool use_scaling =
1477 has_large_coeff || min_magnitude == 1 || min_magnitude >= positive_rhs;
1478 auto f = use_scaling ? GetSuperAdditiveStrengtheningMirFunction(
1479 positive_rhs, /*scaling=*/6000)
1481 min_magnitude);
1482
1483 if (ib_processor != nullptr) {
1484 const auto [num_lb, num_ub, num_merges] =
1485 ib_processor->PostprocessWithImpliedBound(f, /*factor_t=*/1, &cut_);
1486 flow_stats_.num_lb_ibs += num_lb;
1487 flow_stats_.num_ub_ibs += num_ub;
1488 flow_stats_.num_merges += num_merges;
1489 }
1490
1491 // Lifting.
1492 {
1493 IntegerValue period = positive_rhs;
1494 for (const CutTerm& term : cut_.terms) {
1495 if (term.coeff > 0) continue;
1496 period = std::max(period, -term.coeff);
1497 }
1498
1499 // Compute good period.
1500 // We don't want to extend it in the simpler case where f(x)=-1 if x < 0.
1501 //
1502 // TODO(user): If the Mir*() function is used, we don't need to extend that
1503 // much the period. Fix.
1504 if (f(-period + FloorRatio(period, 2)) != f(-period)) {
1505 // TODO(user): do exact binary search to find highest x in
1506 // [-max_neg_magnitude, 0] such that f(x) == f(-max_neg_magnitude) ? not
1507 // really needed though since we know that we have this equality:
1508 CHECK_EQ(f(-period), f(-positive_rhs));
1509 period = std::max(period, CapProdI(2, positive_rhs) - 1);
1510 }
1511
1512 f = ExtendNegativeFunction(f, period);
1513 }
1514
1515 // Generate the cut.
1516 cut_.rhs = absl::int128(f(-positive_rhs).value());
1517 for (CutTerm& term : cut_.terms) {
1518 const IntegerValue old_coeff = term.coeff;
1519 term.coeff = f(term.coeff);
1520 if (old_coeff > 0 && term.coeff != 0) ++flow_stats_.num_lifting;
1521 }
1522 ++flow_stats_.num_cuts;
1523 return true;
1524}
1525
1527 const CutData& input_ct, ImpliedBoundsProcessor* ib_processor) {
1528 int cover_size;
1529 if (has_bool_base_ct_) {
1530 // We already called GetCoverSizeForBooleans() and ib_processor was nullptr,
1531 // so reuse that info.
1532 CHECK(ib_processor == nullptr);
1533 cover_size = bool_cover_size_;
1534 if (cover_size == 0) return false;
1535 InitializeCut(bool_base_ct_);
1536 } else {
1537 InitializeCut(input_ct);
1538
1539 // Perform IB expansion with no restriction, all coeff should still be
1540 // positive.
1541 //
1542 // TODO(user): Merge Boolean terms that are complement of each other.
1543 if (ib_processor != nullptr) {
1544 std::vector<CutTerm>* new_bool_terms =
1545 ib_processor->ClearedMutableTempTerms();
1546 for (CutTerm& term : cut_.terms) {
1547 if (term.bound_diff <= 1) continue;
1548 if (ib_processor->TryToExpandWithLowerImpliedbound(
1549 IntegerValue(1),
1550 /*complement=*/false, &term, &cut_.rhs, new_bool_terms)) {
1551 ++ls_stats_.num_initial_ibs;
1552 }
1553 }
1554
1556 absl::MakeSpan(*new_bool_terms), IntegerValue(1), &cut_);
1557 }
1558
1559 // TODO(user): we currently only deal with Boolean in the cover. Fix.
1560 cover_size = GetCoverSizeForBooleans();
1561 }
1562 if (cover_size == 0) return false;
1563
1564 // We don't support big rhs here.
1565 // Note however than since this only deal with Booleans, it is less likely.
1566 if (cut_.rhs > absl::int128(std::numeric_limits<int64_t>::max())) {
1567 ++ls_stats_.num_overflow_aborts;
1568 return false;
1569 }
1570 const IntegerValue rhs = static_cast<int64_t>(cut_.rhs);
1571
1572 // Collect the weight in the cover.
1573 IntegerValue sum(0);
1574 std::vector<IntegerValue> cover_weights;
1575 for (int i = 0; i < cover_size; ++i) {
1576 CHECK_EQ(cut_.terms[i].bound_diff, 1);
1577 CHECK_GT(cut_.terms[i].coeff, 0);
1578 cover_weights.push_back(cut_.terms[i].coeff);
1579 sum = CapAddI(sum, cut_.terms[i].coeff);
1580 }
1581 if (AtMinOrMaxInt64(sum.value())) {
1582 ++ls_stats_.num_overflow_aborts;
1583 return false;
1584 }
1585 CHECK_GT(sum, rhs);
1586
1587 // Compute the correct threshold so that if we round down larger weights to
1588 // p/q. We have sum of the weight in cover == base_rhs.
1589 IntegerValue p(0);
1590 IntegerValue q(0);
1591 IntegerValue previous_sum(0);
1592 std::sort(cover_weights.begin(), cover_weights.end());
1593 for (int i = 0; i < cover_size; ++i) {
1594 q = IntegerValue(cover_weights.size() - i);
1595 if (previous_sum + cover_weights[i] * q > rhs) {
1596 p = rhs - previous_sum;
1597 break;
1598 }
1599 previous_sum += cover_weights[i];
1600 }
1601 CHECK_GE(q, 1);
1602
1603 // Compute thresholds.
1604 // For the first q values, thresholds[i] is the smallest integer such that
1605 // q * threshold[i] > p * (i + 1).
1606 std::vector<IntegerValue> thresholds;
1607 for (int i = 0; i < q; ++i) {
1608 // TODO(user): compute this in an overflow-safe way.
1609 if (CapProd(p.value(), i + 1) >= std::numeric_limits<int64_t>::max() - 1) {
1610 ++ls_stats_.num_overflow_aborts;
1611 return false;
1612 }
1613 thresholds.push_back(CeilRatio(p * (i + 1) + 1, q));
1614 }
1615
1616 // For the other values, we just add the weights.
1617 std::reverse(cover_weights.begin(), cover_weights.end());
1618 for (int i = q.value(); i < cover_size; ++i) {
1619 thresholds.push_back(thresholds.back() + cover_weights[i]);
1620 }
1621 CHECK_EQ(thresholds.back(), rhs + 1);
1622
1623 // Generate the cut.
1624 //
1625 // Our algo is quadratic in worst case, but large coefficients should be
1626 // rare, and in practice we don't really see this.
1627 //
1628 // Note that this work for non-Boolean since we can just "theorically" split
1629 // them as a sum of Booleans :) Probably a cleaner proof exist by just using
1630 // the super-additivity of the lifting function on [0, rhs].
1631 temp_cut_.rhs = cover_size - 1;
1632 temp_cut_.terms.clear();
1633
1634 const int base_size = static_cast<int>(cut_.terms.size());
1635 for (int i = 0; i < base_size; ++i) {
1636 const CutTerm& term = cut_.terms[i];
1637 const IntegerValue coeff = term.coeff;
1638 IntegerValue cut_coeff(1);
1639 if (coeff < thresholds[0]) {
1640 if (i >= cover_size) continue;
1641 } else {
1642 // Find the largest index <= coeff.
1643 //
1644 // TODO(user): For exact multiple of p/q we can increase the coeff by 1/2.
1645 // See section in the paper on getting maximal super additive function.
1646 for (int i = 1; i < cover_size; ++i) {
1647 if (coeff < thresholds[i]) break;
1648 cut_coeff = IntegerValue(i + 1);
1649 }
1650 if (cut_coeff != 0 && i >= cover_size) ++ls_stats_.num_lifting;
1651 if (cut_coeff > 1 && i < cover_size) ++ls_stats_.num_lifting; // happen?
1652 }
1653
1654 temp_cut_.terms.push_back(term);
1655 temp_cut_.terms.back().coeff = cut_coeff;
1656 }
1657
1658 cut_ = temp_cut_;
1659 ++ls_stats_.num_cuts;
1660 return true;
1661}
1662
1664 if (!VLOG_IS_ON(1)) return;
1665 std::vector<std::pair<std::string, int64_t>> stats;
1666 stats.push_back({"bool_rlt/num_tried", num_tried_});
1667 stats.push_back({"bool_rlt/num_tried_factors", num_tried_factors_});
1668 shared_stats_->AddStats(stats);
1669}
1670
1671void BoolRLTCutHelper::Initialize(absl::Span<const IntegerVariable> lp_vars) {
1672 product_detector_->InitializeBooleanRLTCuts(lp_vars, *lp_values_);
1673 enabled_ = !product_detector_->BoolRLTCandidates().empty();
1674}
1675
1676// TODO(user): do less work, add more stats.
1678 if (!enabled_) return false;
1679
1680 ++num_tried_;
1681 DCHECK(input_ct.AllCoefficientsArePositive());
1682
1683 // We will list the interesting "factor" to try to multiply + linearize the
1684 // input constraint with.
1685 absl::flat_hash_set<IntegerVariable> to_try_set;
1686 std::vector<IntegerVariable> to_try;
1687
1688 // We can look at the linearized factor * term and bound the activity delta
1689 // rescaled by 1 / factor.
1690 //
1691 // CASE linearized_term delta = term/factor - previous
1692 //
1693 // DROP, 0 0 - X
1694 // MC_CORMICK, factor * ub - (ub - X) (ub - X) * (1 - 1/factor) <= 0
1695 // SQUARE, factor=X 1 - X
1696 // RLT, factor - P 1 - X - P/X <= 1 - X
1697 //
1698 // TODO(user): detect earlier that a factor is not worth checking because
1699 // we already loose too much with the DROP/MC_CORMICK cases ? Filter more ?
1700 // I think we can probably evaluate the factor efficiency during the first
1701 // loop which usually have a small complexity compared to num_factor_to_try
1702 // times num filtered terms.
1703 filtered_input_.terms.clear();
1704 filtered_input_.rhs = input_ct.rhs;
1705
1706 const auto& candidates = product_detector_->BoolRLTCandidates();
1707 for (const CutTerm& term : input_ct.terms) {
1708 // The only options are DROP or MC_CORMICK, but the later will unlikely win.
1709 //
1710 // TODO(user): we never use factor with lp value < 1e-4, but we could use a
1711 // factor equal to 1.0 I think. Double check.
1712 if (!term.IsBoolean() && term.lp_value <= 1e-6) {
1713 continue;
1714 }
1715
1716 // Here the MC_CORMICK will not loose much. And SQUARE or RLT cannot win
1717 // much, so we can assume there is no loss and just look for violated
1718 // subconstraint.
1719 if (term.LpDistToMaxValue() <= 1e-6) {
1720 filtered_input_.rhs -= absl::int128(term.coeff.value()) *
1721 absl::int128(term.bound_diff.value());
1722 continue;
1723 }
1724
1725 // Convert to var or -var (to mean 1 - var).
1726 //
1727 // TODO(user): We could keep for each factor the max gain, so that we
1728 // can decided if it is not even worth trying a factor.
1729 const IntegerVariable var = term.GetUnderlyingLiteralOrNone();
1730 if (var != kNoIntegerVariable && candidates.contains(NegationOf(var))) {
1731 for (const IntegerVariable factor : candidates.at(NegationOf(var))) {
1732 if (to_try_set.insert(factor).second) to_try.push_back(factor);
1733 }
1734 }
1735 filtered_input_.terms.push_back(term);
1736 }
1737
1738 // TODO(user): Avoid constructing the cut just to evaluate its efficacy.
1739 double best_efficacy = 1e-3;
1740 IntegerVariable best_factor = kNoIntegerVariable;
1741 for (const IntegerVariable factor : to_try) {
1742 ++num_tried_factors_;
1743 if (!TryProduct(factor, filtered_input_)) continue;
1744 const double efficacy = cut_.ComputeEfficacy();
1745 if (efficacy > best_efficacy) {
1746 best_efficacy = efficacy;
1747 best_factor = factor;
1748 }
1749 }
1750
1751 // If we found a good factor, applies it to the non-filtered base constraint.
1752 if (best_factor != kNoIntegerVariable) {
1753 return TryProduct(best_factor, input_ct);
1754 }
1755 return false;
1756}
1757
1758namespace {
1759
1760// Each bool * term can be linearized in a couple of way.
1761// We will choose the best one.
1762enum class LinearizationOption {
1763 DROP,
1764 MC_CORMICK,
1765 RLT,
1766 SQUARE,
1767};
1768
1769} // namespace
1770
1771double BoolRLTCutHelper::GetLiteralLpValue(IntegerVariable var) const {
1772 if (VariableIsPositive(var)) return (*lp_values_)[var];
1773 return 1.0 - (*lp_values_)[PositiveVariable(var)];
1774}
1775
1776bool BoolRLTCutHelper::TryProduct(IntegerVariable factor,
1777 const CutData& input) {
1778 cut_.terms.clear();
1779 cut_.rhs = 0;
1780 absl::int128 old_rhs = input.rhs;
1781
1782 const double factor_lp = GetLiteralLpValue(factor);
1783
1784 // Consider each term in sequence and linearize them.
1785 for (CutTerm term : input.terms) {
1786 LinearizationOption best_option = LinearizationOption::DROP;
1787
1788 // Recover the "IntegerVariable" literal if any.
1789 const IntegerVariable var = term.GetUnderlyingLiteralOrNone();
1790 const bool is_literal = var != kNoIntegerVariable;
1791
1792 // First option is if factor == var.
1793 if (factor == var) {
1794 // The term can be left unchanged.
1795 // Note that we "win" (factor_lp - factor_lp ^ 2) * coeff activity.
1796 best_option = LinearizationOption::SQUARE;
1797 cut_.terms.push_back(term);
1798 continue;
1799 }
1800
1801 // If factor == NegationOf(var) our best linearization is unfortunately
1802 // just product >= 0.
1803 if (NegationOf(factor) == var) {
1804 best_option = LinearizationOption::DROP;
1805 continue;
1806 }
1807
1808 // TODO(user): If l implies x and y, we have x * y >= l.
1809 // We have to choose l as high as possible if multiple choices.
1810
1811 // We start by the lp value for the drop option: simply dropping the term
1812 // since we know it is >= 0. We will choose the option with the highest
1813 // lp value, which is the one that "loose" the least activity.
1814 double best_lp = 0.0;
1815
1816 // Second option, is complement it and use x * (1 - y) <= (1 - y):
1817 // x * [1 - (1 - y)] = x - x * (1 - y) >= x - (1 - y)
1818 const double complement_lp =
1819 static_cast<double>(term.bound_diff.value()) - term.lp_value;
1820 const double mc_cormick_lp = factor_lp - complement_lp;
1821 if (mc_cormick_lp > best_lp) {
1822 best_option = LinearizationOption::MC_CORMICK;
1823 best_lp = mc_cormick_lp;
1824 }
1825
1826 // Last option is complement it and use a relation x * (1 - y) <= u.
1827 // so the lp is x - u. Note that this can be higher than x * y if the
1828 // bilinear relation is violated by the lp solution.
1829 if (is_literal) {
1830 // TODO(user): only consider variable within current lp.
1831 const IntegerVariable ub_lit =
1832 product_detector_->LiteralProductUpperBound(factor, NegationOf(var));
1833 if (ub_lit != kNoIntegerVariable) {
1834 const double lit_lp = GetLiteralLpValue(ub_lit);
1835 if (factor_lp - lit_lp > best_lp) {
1836 // We do it right away since we have all we need.
1837 best_option = LinearizationOption::RLT;
1838
1839 // First complement to update rhs.
1840 term.Complement(&old_rhs);
1841
1842 // Now we replace the term data.
1843 term.lp_value = lit_lp;
1844 term.ReplaceExpressionByLiteral(ub_lit);
1845 cut_.terms.push_back(term);
1846 continue;
1847 }
1848 }
1849 }
1850
1851 if (best_option == LinearizationOption::DROP) continue;
1852
1853 // We just keep the complemented term.
1854 CHECK(best_option == LinearizationOption::MC_CORMICK);
1855 term.Complement(&old_rhs);
1856 cut_.terms.push_back(term);
1857 }
1858
1859 // Finally we add the - factor * old_rhs term.
1860 // We can only do that if the old_rhs is not too big.
1861 //
1862 // TODO(user): Avoid right away large constraint coming from gomory...
1863 const absl::int128 limit(int64_t{1} << 50);
1864 if (old_rhs > limit || old_rhs < -limit) return false;
1865
1866 CutTerm term;
1867 term.coeff = -IntegerValue(static_cast<int64_t>(old_rhs));
1868 term.lp_value = factor_lp;
1869 term.bound_diff = 1;
1870 term.ReplaceExpressionByLiteral(factor);
1871 cut_.terms.push_back(term);
1872
1873 return true;
1874}
1875
1879 int linearization_level,
1880 Model* model) {
1881 CutGenerator result;
1882 if (z.var != kNoIntegerVariable) result.vars.push_back(z.var);
1883 if (x.var != kNoIntegerVariable) result.vars.push_back(x.var);
1884 if (y.var != kNoIntegerVariable) result.vars.push_back(y.var);
1885
1886 IntegerTrail* const integer_trail = model->GetOrCreate<IntegerTrail>();
1887 Trail* trail = model->GetOrCreate<Trail>();
1888
1889 result.generate_cuts = [z, x, y, linearization_level, model, trail,
1890 integer_trail](LinearConstraintManager* manager) {
1891 if (trail->CurrentDecisionLevel() > 0 && linearization_level == 1) {
1892 return true;
1893 }
1894 const int64_t x_lb = integer_trail->LevelZeroLowerBound(x).value();
1895 const int64_t x_ub = integer_trail->LevelZeroUpperBound(x).value();
1896 const int64_t y_lb = integer_trail->LevelZeroLowerBound(y).value();
1897 const int64_t y_ub = integer_trail->LevelZeroUpperBound(y).value();
1898
1899 // if x or y are fixed, the McCormick equations are exact.
1900 if (x_lb == x_ub || y_lb == y_ub) return true;
1901
1902 // Check for overflow with the product of expression bounds and the
1903 // product of one expression bound times the constant part of the other
1904 // expression.
1905 const int64_t x_max_amp = std::max(std::abs(x_lb), std::abs(x_ub));
1906 const int64_t y_max_amp = std::max(std::abs(y_lb), std::abs(y_ub));
1907 constexpr int64_t kMaxSafeInteger = (int64_t{1} << 53) - 1;
1908 if (CapProd(y_max_amp, x_max_amp) > kMaxSafeInteger) return true;
1909 if (CapProd(y_max_amp, std::abs(x.constant.value())) > kMaxSafeInteger) {
1910 return true;
1911 }
1912 if (CapProd(x_max_amp, std::abs(y.constant.value())) > kMaxSafeInteger) {
1913 return true;
1914 }
1915
1916 const auto& lp_values = manager->LpValues();
1917 const double x_lp_value = x.LpValue(lp_values);
1918 const double y_lp_value = y.LpValue(lp_values);
1919 const double z_lp_value = z.LpValue(lp_values);
1920
1921 // TODO(user): As the bounds change monotonically, these cuts
1922 // dominate any previous one. try to keep a reference to the cut and
1923 // replace it. Alternatively, add an API for a level-zero bound change
1924 // callback.
1925
1926 // Cut -z + x_coeff * x + y_coeff* y <= rhs
1927 auto try_add_above_cut = [&](int64_t x_coeff, int64_t y_coeff,
1928 int64_t rhs) {
1929 if (-z_lp_value + x_lp_value * x_coeff + y_lp_value * y_coeff >=
1930 rhs + kMinCutViolation) {
1931 LinearConstraintBuilder cut(model, /*lb=*/kMinIntegerValue,
1932 /*ub=*/IntegerValue(rhs));
1933 cut.AddTerm(z, IntegerValue(-1));
1934 if (x_coeff != 0) cut.AddTerm(x, IntegerValue(x_coeff));
1935 if (y_coeff != 0) cut.AddTerm(y, IntegerValue(y_coeff));
1936 manager->AddCut(cut.Build(), "PositiveProduct");
1937 }
1938 };
1939
1940 // Cut -z + x_coeff * x + y_coeff* y >= rhs
1941 auto try_add_below_cut = [&](int64_t x_coeff, int64_t y_coeff,
1942 int64_t rhs) {
1943 if (-z_lp_value + x_lp_value * x_coeff + y_lp_value * y_coeff <=
1944 rhs - kMinCutViolation) {
1945 LinearConstraintBuilder cut(model, /*lb=*/IntegerValue(rhs),
1946 /*ub=*/kMaxIntegerValue);
1947 cut.AddTerm(z, IntegerValue(-1));
1948 if (x_coeff != 0) cut.AddTerm(x, IntegerValue(x_coeff));
1949 if (y_coeff != 0) cut.AddTerm(y, IntegerValue(y_coeff));
1950 manager->AddCut(cut.Build(), "PositiveProduct");
1951 }
1952 };
1953
1954 // McCormick relaxation of bilinear constraints. These 4 cuts are the
1955 // exact facets of the x * y polyhedron for a bounded x and y.
1956 //
1957 // Each cut correspond to plane that contains two of the line
1958 // (x=x_lb), (x=x_ub), (y=y_lb), (y=y_ub). The easiest to
1959 // understand them is to draw the x*y curves and see the 4
1960 // planes that correspond to the convex hull of the graph.
1961 try_add_above_cut(y_lb, x_lb, x_lb * y_lb);
1962 try_add_above_cut(y_ub, x_ub, x_ub * y_ub);
1963 try_add_below_cut(y_ub, x_lb, x_lb * y_ub);
1964 try_add_below_cut(y_lb, x_ub, x_ub * y_lb);
1965 return true;
1966 };
1967
1968 return result;
1969}
1970
1972 AffineExpression square,
1973 IntegerValue x_lb,
1974 IntegerValue x_ub, Model* model) {
1975 const IntegerValue above_slope = x_ub + x_lb;
1976 LinearConstraintBuilder above_hyperplan(model, kMinIntegerValue,
1977 -x_lb * x_ub);
1978 above_hyperplan.AddTerm(square, 1);
1979 above_hyperplan.AddTerm(x, -above_slope);
1980 return above_hyperplan.Build();
1981}
1982
1984 AffineExpression square,
1985 IntegerValue x_value,
1986 Model* model) {
1987 const IntegerValue below_slope = 2 * x_value + 1;
1988 LinearConstraintBuilder below_hyperplan(model, -x_value - x_value * x_value,
1990 below_hyperplan.AddTerm(square, 1);
1991 below_hyperplan.AddTerm(x, -below_slope);
1992 return below_hyperplan.Build();
1993}
1994
1996 int linearization_level, Model* model) {
1997 CutGenerator result;
1998 if (x.var != kNoIntegerVariable) result.vars.push_back(x.var);
1999 if (y.var != kNoIntegerVariable) result.vars.push_back(y.var);
2000
2001 Trail* trail = model->GetOrCreate<Trail>();
2002 IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
2003 result.generate_cuts = [y, x, linearization_level, trail, integer_trail,
2004 model](LinearConstraintManager* manager) {
2005 if (trail->CurrentDecisionLevel() > 0 && linearization_level == 1) {
2006 return true;
2007 }
2008 const IntegerValue x_ub = integer_trail->LevelZeroUpperBound(x);
2009 const IntegerValue x_lb = integer_trail->LevelZeroLowerBound(x);
2010 DCHECK_GE(x_lb, 0);
2011
2012 if (x_lb == x_ub) return true;
2013
2014 // Check for potential overflows.
2015 if (x_ub > (int64_t{1} << 31)) return true;
2016 DCHECK_GE(x_lb, 0);
2017 manager->AddCut(ComputeHyperplanAboveSquare(x, y, x_lb, x_ub, model),
2018 "SquareUpper");
2019
2020 const IntegerValue x_floor =
2021 static_cast<int64_t>(std::floor(x.LpValue(manager->LpValues())));
2022 manager->AddCut(ComputeHyperplanBelowSquare(x, y, x_floor, model),
2023 "SquareLower");
2024 return true;
2025 };
2026
2027 return result;
2028}
2029
2030ImpliedBoundsProcessor::BestImpliedBoundInfo
2032 auto it = cache_.find(var);
2033 if (it != cache_.end()) {
2034 BestImpliedBoundInfo result = it->second;
2035 if (result.bool_var == kNoIntegerVariable) return BestImpliedBoundInfo();
2036 if (integer_trail_->IsFixed(result.bool_var)) return BestImpliedBoundInfo();
2037 return result;
2038 }
2039 return BestImpliedBoundInfo();
2040}
2041
2043ImpliedBoundsProcessor::ComputeBestImpliedBound(
2044 IntegerVariable var,
2046 auto it = cache_.find(var);
2047 if (it != cache_.end()) return it->second;
2048 BestImpliedBoundInfo result;
2049 double result_slack_lp_value = std::numeric_limits<double>::infinity();
2050 const IntegerValue lb = integer_trail_->LevelZeroLowerBound(var);
2051 for (const ImpliedBoundEntry& entry :
2052 implied_bounds_->GetImpliedBounds(var)) {
2053 // Only process entries with a Boolean variable currently part of the LP
2054 // we are considering for this cut.
2055 //
2056 // TODO(user): the more we use cuts, the less it make sense to have a
2057 // lot of small independent LPs.
2058 if (!lp_vars_.contains(PositiveVariable(entry.literal_view))) {
2059 continue;
2060 }
2061
2062 // The equation is X = lb + diff * Bool + Slack where Bool is in [0, 1]
2063 // and slack in [0, ub - lb].
2064 const IntegerValue diff = entry.lower_bound - lb;
2065 CHECK_GE(diff, 0);
2066 const double bool_lp_value =
2067 VariableIsPositive(entry.literal_view)
2068 ? lp_values[entry.literal_view]
2069 : 1.0 - lp_values[PositiveVariable(entry.literal_view)];
2070 const double slack_lp_value =
2071 lp_values[var] - ToDouble(lb) - bool_lp_value * ToDouble(diff);
2072
2073 // If the implied bound equation is not respected, we just add it
2074 // to implied_bound_cuts, and skip the entry for now.
2075 if (slack_lp_value < -1e-4) {
2076 LinearConstraint ib_cut;
2077 ib_cut.lb = kMinIntegerValue;
2078 std::vector<std::pair<IntegerVariable, IntegerValue>> terms;
2079 if (VariableIsPositive(entry.literal_view)) {
2080 // X >= Indicator * (bound - lb) + lb
2081 terms.push_back({entry.literal_view, diff});
2082 terms.push_back({var, IntegerValue(-1)});
2083 ib_cut.ub = -lb;
2084 } else {
2085 // X >= -Indicator * (bound - lb) + bound
2086 terms.push_back({PositiveVariable(entry.literal_view), -diff});
2087 terms.push_back({var, IntegerValue(-1)});
2088 ib_cut.ub = -entry.lower_bound;
2089 }
2090 CleanTermsAndFillConstraint(&terms, &ib_cut);
2091 ib_cut_pool_.AddCut(std::move(ib_cut), "IB", lp_values);
2092 continue;
2093 }
2094
2095 // We look for tight implied bounds, and amongst the tightest one, we
2096 // prefer larger coefficient in front of the Boolean.
2097 if (slack_lp_value + 1e-4 < result_slack_lp_value ||
2098 (slack_lp_value < result_slack_lp_value + 1e-4 &&
2099 entry.lower_bound > result.implied_bound)) {
2100 result_slack_lp_value = slack_lp_value;
2101 result.var_lp_value = lp_values[var];
2102 result.bool_lp_value = bool_lp_value;
2103 result.implied_bound = entry.lower_bound;
2104 result.bool_var = entry.literal_view;
2105 }
2106 }
2107 cache_[var] = result;
2108 return result;
2109}
2110
2113 cache_.clear();
2114 for (const IntegerVariable var :
2115 implied_bounds_->VariablesWithImpliedBounds()) {
2116 if (!lp_vars_.contains(PositiveVariable(var))) continue;
2117 ComputeBestImpliedBound(var, lp_values);
2118 }
2119}
2120
2122 const CutTerm& term, IntegerValue factor_t, CutTerm& bool_term,
2123 CutTerm& slack_term) {
2124 // We only want to expand non-Boolean and non-slack term!
2125 if (term.bound_diff <= 1) return false;
2126 if (!term.IsSimple()) return false;
2127 DCHECK_EQ(IntTypeAbs(term.expr_coeffs[0]), 1);
2128
2129 // Try lower bounded direction for implied bound.
2130 // This kind should always be beneficial if it exists:
2131 //
2132 // Because X = bound_diff * B + S
2133 // We can replace coeff * X by the expression before applying f:
2134 // = f(coeff * bound_diff) * B + f(coeff) * [X - bound_diff * B]
2135 // = f(coeff) * X + (f(coeff * bound_diff) - f(coeff) * bound_diff] * B
2136 // So we can "lift" B into the cut with a non-negative coefficient.
2137 //
2138 // Note that this lifting is really the same as if we used that implied
2139 // bound before since in f(coeff * bound_diff) * B + f(coeff) * S, if we
2140 // replace S by its value [X - bound_diff * B] we get the same result.
2141 //
2142 // TODO(user): Ignore if bound_diff == 1 ? But we can still merge B with
2143 // another entry if it exists, so it can still be good in this case.
2144 //
2145 // TODO(user): Only do it if coeff_b > 0 ? But again we could still merge
2146 // B with an existing Boolean for a better cut even if coeff_b == 0.
2147 if (term.cached_implied_lb < 0) return false;
2148 const BestImpliedBoundInfo info = cached_data_[term.cached_implied_lb];
2149 const IntegerValue lb = -term.expr_offset;
2150 const IntegerValue bound_diff = info.implied_bound - lb;
2151 if (bound_diff <= 0) return false;
2152 if (ProdOverflow(factor_t, CapProdI(term.coeff, bound_diff))) return false;
2153
2154 // We have X/-X = info.diff * Boolean + slack.
2155 bool_term.coeff = term.coeff * bound_diff;
2156 bool_term.expr_vars[0] = PositiveVariable(info.bool_var);
2157 bool_term.expr_coeffs[1] = 0;
2158 bool_term.bound_diff = IntegerValue(1);
2159 bool_term.lp_value = info.bool_lp_value;
2160 if (VariableIsPositive(info.bool_var)) {
2161 bool_term.expr_coeffs[0] = IntegerValue(1);
2162 bool_term.expr_offset = IntegerValue(0);
2163 } else {
2164 bool_term.expr_coeffs[0] = IntegerValue(-1);
2165 bool_term.expr_offset = IntegerValue(1);
2166 }
2167
2168 // Create slack.
2169 // The expression is term.exp - bound_diff * bool_term
2170 // The variable shouldn't be the same.
2171 DCHECK_NE(term.expr_vars[0], bool_term.expr_vars[0]);
2172 slack_term.expr_vars[0] = term.expr_vars[0];
2173 slack_term.expr_coeffs[0] = term.expr_coeffs[0];
2174 slack_term.expr_vars[1] = bool_term.expr_vars[0];
2175 slack_term.expr_coeffs[1] = -bound_diff * bool_term.expr_coeffs[0];
2176 slack_term.expr_offset =
2177 term.expr_offset - bound_diff * bool_term.expr_offset;
2178
2179 slack_term.lp_value = info.SlackLpValue(lb);
2180 slack_term.coeff = term.coeff;
2181 slack_term.bound_diff = term.bound_diff;
2182
2183 return true;
2184}
2185
2186// We use the fact that calling DecomposeWithImpliedLowerBound() with
2187// term.Complement() give us almost what we want. You have
2188// -complement(X) = -diff.B - slack
2189// - (diff - X) = -diff.(1 -(1- B)) - slack
2190// X = diff.(1 - B) - slack;
2192 const CutTerm& term, IntegerValue factor_t, CutTerm& bool_term,
2193 CutTerm& slack_term) {
2194 absl::int128 unused = 0;
2195 CutTerm complement = term;
2196 complement.Complement(&unused);
2197 if (!DecomposeWithImpliedLowerBound(complement, factor_t, bool_term,
2198 slack_term)) {
2199 return false;
2200 }
2201 // This is required not to have a constant term which might mess up our cut
2202 // heuristics.
2203 if (IntTypeAbs(bool_term.coeff) !=
2205 return false;
2206 }
2207 bool_term.Complement(&unused);
2208 CHECK_EQ(unused, absl::int128(0));
2209 return true;
2210}
2211
2213 const std::function<IntegerValue(IntegerValue)>& f, IntegerValue factor_t,
2214 CutData* cut) {
2215 int num_applied_lb = 0;
2216 int num_applied_ub = 0;
2217
2218 CutTerm bool_term;
2219 CutTerm slack_term;
2220 CutTerm ub_bool_term;
2221 CutTerm ub_slack_term;
2222
2223 tmp_terms_.clear();
2224 for (CutTerm& term : cut->terms) {
2225 if (term.bound_diff <= 1) continue;
2226 if (!term.IsSimple()) continue;
2227
2228 // Score is just the final lp value.
2229 // Higher is better since it is a <= constraint.
2230 double base_score;
2231 bool expand = false;
2232 if (DecomposeWithImpliedLowerBound(term, factor_t, bool_term, slack_term)) {
2233 // This side is always good.
2234 // c.X = c.d.B + c.S
2235 // applying f to the result we have f(c.d).B + f(c).[X - d.B]
2236 // which give f(c).X + [f(c.d) - f(c).d].B
2237 // and the second term is always positive by super-additivity.
2238 expand = true;
2239 base_score = AsDouble(f(bool_term.coeff)) * bool_term.lp_value +
2240 AsDouble(f(slack_term.coeff)) * slack_term.lp_value;
2241 } else {
2242 base_score = AsDouble(f(term.coeff)) * term.lp_value;
2243 }
2244
2245 // Test if it is better to use this "bad" side.
2246 //
2247 // Use the implied bound on (-X) if it is beneficial to do so.
2248 // Like complementing, this is not always good.
2249 //
2250 // We have comp(X) = diff - X = diff * B + S
2251 // X = diff * (1 - B) - S.
2252 // So if we applies f, we will get:
2253 // f(coeff * diff) * (1 - B) + f(-coeff) * S
2254 // and substituing S = diff * (1 - B) - X, we get:
2255 // -f(-coeff) * X + [f(coeff * diff) + f(-coeff) * diff] (1 - B).
2256 //
2257 // TODO(user): Note that while the violation might be higher, if the slack
2258 // becomes large this will result in a less powerfull cut. Shall we do
2259 // that? It is a bit the same problematic with complementing.
2260 //
2261 // TODO(user): If the slack is close to zero, then this transformation
2262 // will always increase the violation. So we could potentially do it in
2263 // Before our divisor selection heuristic. But the norm of the final cut
2264 // will increase too.
2265 if (DecomposeWithImpliedUpperBound(term, factor_t, ub_bool_term,
2266 ub_slack_term)) {
2267 const double score =
2268 AsDouble(f(ub_bool_term.coeff)) * ub_bool_term.lp_value +
2269 AsDouble(f(ub_slack_term.coeff)) * ub_slack_term.lp_value;
2270 // Note that because the slack is of the opposite sign, we might
2271 // loose more, so we prefer to be a bit defensive.
2272 if (score > base_score + 1e-2) {
2273 ++num_applied_ub;
2274 term = ub_slack_term;
2275 tmp_terms_.push_back(ub_bool_term);
2276 continue;
2277 }
2278 }
2279
2280 if (expand) {
2281 ++num_applied_lb;
2282 term = slack_term;
2283 tmp_terms_.push_back(bool_term);
2284 }
2285 }
2286
2287 const int num_merges = cut_builder_.AddOrMergeBooleanTerms(
2288 absl::MakeSpan(tmp_terms_), factor_t, cut);
2289
2290 return {num_applied_lb, num_applied_ub, num_merges};
2291}
2292
2294 IntegerValue factor_t, bool complement, CutTerm* term, absl::int128* rhs,
2295 std::vector<CutTerm>* new_bool_terms) {
2296 CutTerm bool_term;
2297 CutTerm slack_term;
2298 if (!DecomposeWithImpliedLowerBound(*term, factor_t, bool_term, slack_term)) {
2299 return false;
2300 }
2301
2302 // It should be good to use IB, but sometime we have things like
2303 // 7.3 = 2 * bool@1 + 5.3 and the expanded Boolean is at its upper bound.
2304 // It is always good to complement such variable.
2305 //
2306 // Note that here we do more and just complement anything closer to UB.
2307 if (complement) {
2308 if (bool_term.lp_value > 0.5) {
2309 bool_term.Complement(rhs);
2310 }
2311 if (slack_term.lp_value > 0.5 * AsDouble(slack_term.bound_diff)) {
2312 slack_term.Complement(rhs);
2313 }
2314 }
2315
2316 *term = slack_term;
2317 new_bool_terms->push_back(bool_term);
2318 return true;
2319}
2320
2321bool ImpliedBoundsProcessor::CacheDataForCut(IntegerVariable first_slack,
2322 CutData* cut) {
2323 cached_data_.clear();
2324
2325 const int size = cut->terms.size();
2326 for (int i = 0; i < size; ++i) {
2327 const CutTerm& term = cut->terms[i];
2328 if (!term.IsSimple()) continue;
2329 if (term.IsBoolean()) continue;
2330 if (term.expr_vars[0] >= first_slack) continue;
2331
2332 // Cache the BestImpliedBoundInfo if relevant.
2333 const IntegerVariable ib_var = term.expr_coeffs[0] > 0
2334 ? term.expr_vars[0]
2335 : NegationOf(term.expr_vars[0]);
2337 if (lb_info.bool_var != kNoIntegerVariable) {
2338 cut->terms[i].cached_implied_lb = cached_data_.size();
2339 cached_data_.emplace_back(std::move(lb_info));
2340 }
2341 BestImpliedBoundInfo ub_info =
2343 if (ub_info.bool_var != kNoIntegerVariable) {
2344 cut->terms[i].cached_implied_ub = cached_data_.size();
2345 cached_data_.emplace_back(std::move(ub_info));
2346 }
2347 }
2348
2349 return !cached_data_.empty();
2350}
2351
2353 min_values_.clear();
2354 expr_mins_.clear();
2355}
2356
2357void SumOfAllDiffLowerBounder::Add(const AffineExpression& expr, int num_exprs,
2358 const IntegerTrail& integer_trail) {
2359 expr_mins_.push_back(integer_trail.LevelZeroLowerBound(expr).value());
2360
2361 if (integer_trail.IsFixed(expr)) {
2362 min_values_.insert(integer_trail.FixedValue(expr));
2363 } else {
2364 if (expr.coeff > 0) {
2365 int count = 0;
2366 for (const IntegerValue value :
2367 integer_trail.InitialVariableDomain(expr.var).Values()) {
2368 min_values_.insert(expr.ValueAt(value));
2369 if (++count >= num_exprs) break;
2370 }
2371 } else {
2372 int count = 0;
2373 for (const IntegerValue value :
2374 integer_trail.InitialVariableDomain(expr.var).Negation().Values()) {
2375 min_values_.insert(-expr.ValueAt(value));
2376 if (++count >= num_exprs) break;
2377 }
2378 }
2379 }
2380}
2381
2383 int count = 0;
2384 IntegerValue sum = 0;
2385 for (const IntegerValue value : min_values_) {
2386 sum = CapAddI(sum, value);
2387 if (++count >= expr_mins_.size()) return sum;
2388 }
2389 return sum;
2390}
2391
2393 std::sort(expr_mins_.begin(), expr_mins_.end());
2394 IntegerValue tmp_value = kMinIntegerValue;
2395 IntegerValue result = 0;
2396 for (const IntegerValue value : expr_mins_) {
2397 // Make sure values are different.
2398 tmp_value = std::max(tmp_value + 1, value);
2399 result += tmp_value;
2400 }
2401 return result;
2402}
2403
2404IntegerValue SumOfAllDiffLowerBounder::GetBestLowerBound(std::string& suffix) {
2405 const IntegerValue domain_bound = SumOfMinDomainValues();
2406 const IntegerValue alldiff_bound = SumOfDifferentMins();
2407 if (domain_bound > alldiff_bound) {
2408 suffix = "d";
2409 return domain_bound;
2410 }
2411 suffix = alldiff_bound > domain_bound ? "a" : "e";
2412 return alldiff_bound;
2413}
2414
2415namespace {
2416
2417void TryToGenerateAllDiffCut(
2418 absl::Span<const std::pair<double, AffineExpression>> sorted_exprs_lp,
2419 const IntegerTrail& integer_trail,
2421 TopNCuts& top_n_cuts, Model* model) {
2422 const int num_exprs = sorted_exprs_lp.size();
2423
2424 std::vector<AffineExpression> current_set_exprs;
2425 SumOfAllDiffLowerBounder diff_mins;
2426 SumOfAllDiffLowerBounder negated_diff_maxes;
2427
2428 double sum = 0.0;
2429
2430 for (const auto& [expr_lp, expr] : sorted_exprs_lp) {
2431 sum += expr_lp;
2432 diff_mins.Add(expr, num_exprs, integer_trail);
2433 negated_diff_maxes.Add(expr.Negated(), num_exprs, integer_trail);
2434 current_set_exprs.push_back(expr);
2435 CHECK_EQ(current_set_exprs.size(), diff_mins.size());
2436 CHECK_EQ(current_set_exprs.size(), negated_diff_maxes.size());
2437 std::string min_suffix;
2438 const IntegerValue required_min_sum =
2439 diff_mins.GetBestLowerBound(min_suffix);
2440 std::string max_suffix;
2441 const IntegerValue required_max_sum =
2442 -negated_diff_maxes.GetBestLowerBound(max_suffix);
2443 if (required_max_sum == std::numeric_limits<IntegerValue>::max()) continue;
2444 DCHECK_LE(required_min_sum, required_max_sum);
2445 if (sum < ToDouble(required_min_sum) - kMinCutViolation ||
2446 sum > ToDouble(required_max_sum) + kMinCutViolation) {
2447 LinearConstraintBuilder cut(model, required_min_sum, required_max_sum);
2448 for (AffineExpression expr : current_set_exprs) {
2449 cut.AddTerm(expr, IntegerValue(1));
2450 }
2451 top_n_cuts.AddCut(cut.Build(),
2452 absl::StrCat("AllDiff_", min_suffix, max_suffix),
2453 lp_values);
2454
2455 // NOTE: We can extend the current set but it is more helpful to generate
2456 // the cut on a different set of variables so we reset the counters.
2457 sum = 0.0;
2458 current_set_exprs.clear();
2459 diff_mins.Clear();
2460 negated_diff_maxes.Clear();
2461 }
2462 }
2463}
2464
2465} // namespace
2466
2468 absl::Span<const AffineExpression> exprs, Model* model) {
2469 CutGenerator result;
2470 IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
2471
2472 for (const AffineExpression& expr : exprs) {
2473 if (!integer_trail->IsFixed(expr)) {
2474 result.vars.push_back(expr.var);
2475 }
2476 }
2478
2479 Trail* trail = model->GetOrCreate<Trail>();
2480 result.generate_cuts =
2481 [exprs = std::vector<AffineExpression>(exprs.begin(), exprs.end()),
2482 integer_trail, trail, model](LinearConstraintManager* manager) {
2483 // These cuts work at all levels but the generator adds too many cuts on
2484 // some instances and degrade the performance so we only use it at level
2485 // 0.
2486 if (trail->CurrentDecisionLevel() > 0) return true;
2487 const auto& lp_values = manager->LpValues();
2488 std::vector<std::pair<double, AffineExpression>> sorted_exprs;
2489 for (const AffineExpression expr : exprs) {
2490 if (integer_trail->LevelZeroLowerBound(expr) ==
2491 integer_trail->LevelZeroUpperBound(expr)) {
2492 continue;
2493 }
2494 sorted_exprs.push_back(std::make_pair(expr.LpValue(lp_values), expr));
2495 }
2496
2497 TopNCuts top_n_cuts(5);
2498 std::sort(sorted_exprs.begin(), sorted_exprs.end(),
2499 [](std::pair<double, AffineExpression>& a,
2500 const std::pair<double, AffineExpression>& b) {
2501 return a.first < b.first;
2502 });
2503 TryToGenerateAllDiffCut(sorted_exprs, *integer_trail, lp_values,
2504 top_n_cuts, model);
2505 // Other direction.
2506 std::reverse(sorted_exprs.begin(), sorted_exprs.end());
2507 TryToGenerateAllDiffCut(sorted_exprs, *integer_trail, lp_values,
2508 top_n_cuts, model);
2509 top_n_cuts.TransferToManager(manager);
2510 return true;
2511 };
2512 VLOG(2) << "Created all_diff cut generator of size: " << exprs.size();
2513 return result;
2514}
2515
2516namespace {
2517// Returns max((w2i - w1i)*Li, (w2i - w1i)*Ui).
2518IntegerValue MaxCornerDifference(const IntegerVariable var,
2519 const IntegerValue w1_i,
2520 const IntegerValue w2_i,
2521 const IntegerTrail& integer_trail) {
2522 const IntegerValue lb = integer_trail.LevelZeroLowerBound(var);
2523 const IntegerValue ub = integer_trail.LevelZeroUpperBound(var);
2524 return std::max((w2_i - w1_i) * lb, (w2_i - w1_i) * ub);
2525}
2526
2527// This is the coefficient of zk in the cut, where k = max_index.
2528// MPlusCoefficient_ki = max((wki - wI(i)i) * Li,
2529// (wki - wI(i)i) * Ui)
2530// = max corner difference for variable i,
2531// target expr I(i), max expr k.
2532// The coefficient of zk is Sum(i=1..n)(MPlusCoefficient_ki) + bk
2533IntegerValue MPlusCoefficient(
2534 absl::Span<const IntegerVariable> x_vars,
2535 absl::Span<const LinearExpression> exprs,
2536 const util_intops::StrongVector<IntegerVariable, int>& variable_partition,
2537 const int max_index, const IntegerTrail& integer_trail) {
2538 IntegerValue coeff = exprs[max_index].offset;
2539 // TODO(user): This algo is quadratic since GetCoefficientOfPositiveVar()
2540 // is linear. This can be optimized (better complexity) if needed.
2541 for (const IntegerVariable var : x_vars) {
2542 const int target_index = variable_partition[var];
2543 if (max_index != target_index) {
2544 coeff += MaxCornerDifference(
2545 var, GetCoefficientOfPositiveVar(var, exprs[target_index]),
2546 GetCoefficientOfPositiveVar(var, exprs[max_index]), integer_trail);
2547 }
2548 }
2549 return coeff;
2550}
2551
2552// Compute the value of
2553// rhs = wI(i)i * xi + Sum(k=1..d)(MPlusCoefficient_ki * zk)
2554// for variable xi for given target index I(i).
2555double ComputeContribution(
2556 const IntegerVariable xi_var, absl::Span<const IntegerVariable> z_vars,
2557 absl::Span<const LinearExpression> exprs,
2558 const util_intops::StrongVector<IntegerVariable, double>& lp_values,
2559 const IntegerTrail& integer_trail, const int target_index) {
2560 CHECK_GE(target_index, 0);
2561 CHECK_LT(target_index, exprs.size());
2562 const LinearExpression& target_expr = exprs[target_index];
2563 const double xi_value = lp_values[xi_var];
2564 const IntegerValue wt_i = GetCoefficientOfPositiveVar(xi_var, target_expr);
2565 double contrib = ToDouble(wt_i) * xi_value;
2566 for (int expr_index = 0; expr_index < exprs.size(); ++expr_index) {
2567 if (expr_index == target_index) continue;
2568 const LinearExpression& max_expr = exprs[expr_index];
2569 const double z_max_value = lp_values[z_vars[expr_index]];
2570 const IntegerValue corner_value = MaxCornerDifference(
2571 xi_var, wt_i, GetCoefficientOfPositiveVar(xi_var, max_expr),
2572 integer_trail);
2573 contrib += ToDouble(corner_value) * z_max_value;
2574 }
2575 return contrib;
2576}
2577} // namespace
2578
2579CutGenerator CreateLinMaxCutGenerator(const IntegerVariable target,
2580 absl::Span<const LinearExpression> exprs,
2581 absl::Span<const IntegerVariable> z_vars,
2582 Model* model) {
2583 CutGenerator result;
2584 std::vector<IntegerVariable> x_vars;
2585 result.vars = {target};
2586 const int num_exprs = exprs.size();
2587 for (int i = 0; i < num_exprs; ++i) {
2588 result.vars.push_back(z_vars[i]);
2589 x_vars.insert(x_vars.end(), exprs[i].vars.begin(), exprs[i].vars.end());
2590 }
2592 // All expressions should only contain positive variables.
2593 DCHECK(std::all_of(x_vars.begin(), x_vars.end(), [](IntegerVariable var) {
2594 return VariableIsPositive(var);
2595 }));
2596 result.vars.insert(result.vars.end(), x_vars.begin(), x_vars.end());
2597
2598 IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
2599 result.generate_cuts =
2600 [x_vars,
2601 z_vars = std::vector<IntegerVariable>(z_vars.begin(), z_vars.end()),
2602 target, num_exprs,
2603 exprs = std::vector<LinearExpression>(exprs.begin(), exprs.end()),
2604 integer_trail, model](LinearConstraintManager* manager) {
2605 const auto& lp_values = manager->LpValues();
2607 lp_values.size(), -1);
2609 variable_partition_contrib(lp_values.size(),
2610 std::numeric_limits<double>::infinity());
2611 for (int expr_index = 0; expr_index < num_exprs; ++expr_index) {
2612 for (const IntegerVariable var : x_vars) {
2613 const double contribution = ComputeContribution(
2614 var, z_vars, exprs, lp_values, *integer_trail, expr_index);
2615 const double prev_contribution = variable_partition_contrib[var];
2616 if (contribution < prev_contribution) {
2617 variable_partition[var] = expr_index;
2618 variable_partition_contrib[var] = contribution;
2619 }
2620 }
2621 }
2622
2623 LinearConstraintBuilder cut(model, /*lb=*/IntegerValue(0),
2624 /*ub=*/kMaxIntegerValue);
2625 double violation = lp_values[target];
2626 cut.AddTerm(target, IntegerValue(-1));
2627
2628 for (const IntegerVariable xi_var : x_vars) {
2629 const int input_index = variable_partition[xi_var];
2630 const LinearExpression& expr = exprs[input_index];
2631 const IntegerValue coeff = GetCoefficientOfPositiveVar(xi_var, expr);
2632 if (coeff != IntegerValue(0)) {
2633 cut.AddTerm(xi_var, coeff);
2634 }
2635 violation -= ToDouble(coeff) * lp_values[xi_var];
2636 }
2637 for (int expr_index = 0; expr_index < num_exprs; ++expr_index) {
2638 const IntegerVariable z_var = z_vars[expr_index];
2639 const IntegerValue z_coeff = MPlusCoefficient(
2640 x_vars, exprs, variable_partition, expr_index, *integer_trail);
2641 if (z_coeff != IntegerValue(0)) {
2642 cut.AddTerm(z_var, z_coeff);
2643 }
2644 violation -= ToDouble(z_coeff) * lp_values[z_var];
2645 }
2646 if (violation > 1e-2) {
2647 manager->AddCut(cut.Build(), "LinMax");
2648 }
2649 return true;
2650 };
2651 return result;
2652}
2653
2654namespace {
2655
2656IntegerValue EvaluateMaxAffine(
2657 absl::Span<const std::pair<IntegerValue, IntegerValue>> affines,
2658 IntegerValue x) {
2659 IntegerValue y = kMinIntegerValue;
2660 for (const auto& p : affines) {
2661 y = std::max(y, x * p.first + p.second);
2662 }
2663 return y;
2664}
2665
2666} // namespace
2667
2669 const LinearExpression& target, IntegerVariable var,
2670 absl::Span<const std::pair<IntegerValue, IntegerValue>> affines,
2671 Model* model, LinearConstraintBuilder* builder) {
2672 auto* integer_trail = model->GetOrCreate<IntegerTrail>();
2673 const IntegerValue x_min = integer_trail->LevelZeroLowerBound(var);
2674 const IntegerValue x_max = integer_trail->LevelZeroUpperBound(var);
2675
2676 const IntegerValue y_at_min = EvaluateMaxAffine(affines, x_min);
2677 const IntegerValue y_at_max = EvaluateMaxAffine(affines, x_max);
2678
2679 const IntegerValue delta_x = x_max - x_min;
2680 const IntegerValue delta_y = y_at_max - y_at_min;
2681
2682 // target <= y_at_min + (delta_y / delta_x) * (var - x_min)
2683 // delta_x * target <= delta_x * y_at_min + delta_y * (var - x_min)
2684 // -delta_y * var + delta_x * target <= delta_x * y_at_min - delta_y * x_min
2685 //
2686 // Checks the rhs for overflows.
2687 if (ProdOverflow(delta_x, y_at_min) || ProdOverflow(delta_x, y_at_max) ||
2688 ProdOverflow(delta_y, x_min) || ProdOverflow(delta_y, x_max)) {
2689 return false;
2690 }
2691
2692 // Checks target * delta_x for overflow.
2693 int64_t abs_magnitude = std::abs(target.offset.value());
2694 for (int i = 0; i < target.vars.size(); ++i) {
2695 const IntegerVariable var = target.vars[i];
2696 const IntegerValue var_min = integer_trail->LevelZeroLowerBound(var);
2697 const IntegerValue var_max = integer_trail->LevelZeroUpperBound(var);
2698 abs_magnitude = CapAdd(
2699 CapProd(std::max(std::abs(var_min.value()), std::abs(var_max.value())),
2700 std::abs(target.coeffs[i].value())),
2701 abs_magnitude);
2702 }
2703 if (AtMinOrMaxInt64(abs_magnitude) ||
2704 AtMinOrMaxInt64(CapProd(abs_magnitude, delta_x.value()))) {
2705 return false;
2706 }
2707
2708 builder->ResetBounds(kMinIntegerValue, delta_x * y_at_min - delta_y * x_min);
2709 builder->AddLinearExpression(target, delta_x);
2710 builder->AddTerm(var, -delta_y);
2711
2712 // Prevent to create constraints that can overflow.
2713 if (!ValidateLinearConstraintForOverflow(builder->Build(), *integer_trail)) {
2714 VLOG(2) << "Linear constraint can cause overflow: " << builder->Build();
2715
2716 return false;
2717 }
2718
2719 return true;
2720}
2721
2723 LinearExpression target, IntegerVariable var,
2724 std::vector<std::pair<IntegerValue, IntegerValue>> affines,
2725 const std::string cut_name, Model* model) {
2726 CutGenerator result;
2727 result.vars = target.vars;
2728 result.vars.push_back(var);
2730
2731 IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
2732 result.generate_cuts = [target, var, affines, cut_name, integer_trail,
2733 model](LinearConstraintManager* manager) {
2734 if (integer_trail->IsFixed(var)) return true;
2735 LinearConstraintBuilder builder(model);
2736 if (BuildMaxAffineUpConstraint(target, var, affines, model, &builder)) {
2737 manager->AddCut(builder.Build(), cut_name);
2738 }
2739 return true;
2740 };
2741 return result;
2742}
2743
2745 absl::Span<const IntegerVariable> base_variables, Model* model) {
2746 // Filter base_variables to only keep the one with a literal view, and
2747 // do the conversion.
2748 std::vector<IntegerVariable> variables;
2749 std::vector<Literal> literals;
2750 absl::flat_hash_map<LiteralIndex, IntegerVariable> positive_map;
2751 absl::flat_hash_map<LiteralIndex, IntegerVariable> negative_map;
2752 auto* integer_trail = model->GetOrCreate<IntegerTrail>();
2753 auto* encoder = model->GetOrCreate<IntegerEncoder>();
2754 for (const IntegerVariable var : base_variables) {
2755 if (integer_trail->LowerBound(var) != IntegerValue(0)) continue;
2756 if (integer_trail->UpperBound(var) != IntegerValue(1)) continue;
2757 const LiteralIndex literal_index = encoder->GetAssociatedLiteral(
2758 IntegerLiteral::GreaterOrEqual(var, IntegerValue(1)));
2759 if (literal_index != kNoLiteralIndex) {
2760 variables.push_back(var);
2761 literals.push_back(Literal(literal_index));
2762 positive_map[literal_index] = var;
2763 negative_map[Literal(literal_index).NegatedIndex()] = var;
2764 }
2765 }
2766 CutGenerator result;
2767 result.vars = variables;
2768 auto* implication_graph = model->GetOrCreate<BinaryImplicationGraph>();
2769 result.only_run_at_level_zero = true;
2770 result.generate_cuts = [variables, literals, implication_graph, positive_map,
2771 negative_map,
2772 model](LinearConstraintManager* manager) {
2773 std::vector<double> packed_values;
2774 std::vector<double> packed_reduced_costs;
2775 const auto& lp_values = manager->LpValues();
2776 const auto& reduced_costs = manager->ReducedCosts();
2777 for (int i = 0; i < literals.size(); ++i) {
2778 packed_values.push_back(lp_values[variables[i]]);
2779 packed_reduced_costs.push_back(reduced_costs[variables[i]]);
2780 }
2781 const std::vector<std::vector<Literal>> at_most_ones =
2782 implication_graph->GenerateAtMostOnesWithLargeWeight(
2783 literals, packed_values, packed_reduced_costs);
2784
2785 for (const std::vector<Literal>& at_most_one : at_most_ones) {
2786 // We need to express such "at most one" in term of the initial
2787 // variables, so we do not use the
2788 // LinearConstraintBuilder::AddLiteralTerm() here.
2790 model, IntegerValue(std::numeric_limits<int64_t>::min()),
2791 IntegerValue(1));
2792 for (const Literal l : at_most_one) {
2793 if (positive_map.contains(l.Index())) {
2794 builder.AddTerm(positive_map.at(l.Index()), IntegerValue(1));
2795 } else {
2796 // Add 1 - X to the linear constraint.
2797 builder.AddTerm(negative_map.at(l.Index()), IntegerValue(-1));
2798 builder.AddConstant(IntegerValue(1));
2799 }
2800 }
2801
2802 manager->AddCut(builder.Build(), "Clique");
2803 }
2804 return true;
2805 };
2806 return result;
2807}
2808
2809} // namespace sat
2810} // namespace operations_research
DomainIteratorBeginEnd Values() const &
bool TrySimpleSeparation(const CutData &input_ct)
Tries RLT separation of the input constraint. Returns true on success.
Definition cuts.cc:1677
void Initialize(absl::Span< const IntegerVariable > lp_vars)
Definition cuts.cc:1671
bool TrySimpleKnapsack(const CutData &input_ct, ImpliedBoundsProcessor *ib_processor=nullptr)
Definition cuts.cc:1304
bool TryWithLetchfordSouliLifting(const CutData &input_ct, ImpliedBoundsProcessor *ib_processor=nullptr)
Definition cuts.cc:1526
bool TrySingleNodeFlow(const CutData &input_ct, ImpliedBoundsProcessor *ib_processor=nullptr)
Definition cuts.cc:1422
Stores temporaries used to build or manipulate a CutData.
Definition cuts.h:160
bool ConvertToLinearConstraint(const CutData &cut, LinearConstraint *output)
Returns false if we encounter an integer overflow.
Definition cuts.cc:353
int AddOrMergeBooleanTerms(absl::Span< CutTerm > terms, IntegerValue t, CutData *cut)
Definition cuts.cc:300
std::vector< CutTerm > * ClearedMutableTempTerms()
Definition cuts.h:249
void RecomputeCacheAndSeparateSomeImpliedBoundCuts(const util_intops::StrongVector< IntegerVariable, double > &lp_values)
Definition cuts.cc:2111
bool CacheDataForCut(IntegerVariable first_slack, CutData *cut)
Definition cuts.cc:2321
bool TryToExpandWithLowerImpliedbound(IntegerValue factor_t, bool complement, CutTerm *term, absl::int128 *rhs, std::vector< CutTerm > *new_bool_terms)
Definition cuts.cc:2293
BestImpliedBoundInfo GetCachedImpliedBoundInfo(IntegerVariable var) const
Definition cuts.cc:2031
CutDataBuilder * MutableCutBuilder()
This can be used to share the hash-map memory.
Definition cuts.h:245
bool DecomposeWithImpliedLowerBound(const CutTerm &term, IntegerValue factor_t, CutTerm &bool_term, CutTerm &slack_term)
Definition cuts.cc:2121
std::tuple< int, int, int > PostprocessWithImpliedBound(const std::function< IntegerValue(IntegerValue)> &f, IntegerValue factor_t, CutData *cut)
Definition cuts.cc:2212
bool DecomposeWithImpliedUpperBound(const CutTerm &term, IntegerValue factor_t, CutTerm &bool_term, CutTerm &slack_term)
Definition cuts.cc:2191
bool ComputeCut(RoundingOptions options, const CutData &base_ct, ImpliedBoundsProcessor *ib_processor=nullptr)
Returns true on success. The cut can be accessed via cut().
Definition cuts.cc:774
IntegerValue FixedValue(IntegerVariable i) const
Checks that the variable is fixed and returns its value.
Definition integer.h:1329
bool IsFixed(IntegerVariable i) const
Checks if the variable is fixed.
Definition integer.h:1325
IntegerValue LevelZeroUpperBound(IntegerVariable var) const
Definition integer.h:1419
const Domain & InitialVariableDomain(IntegerVariable var) const
Definition integer.cc:869
IntegerValue LevelZeroLowerBound(IntegerVariable var) const
Returns globally valid lower/upper bound on the given integer variable.
Definition integer.h:1412
void ResetBounds(IntegerValue lb, IntegerValue ub)
Reset the bounds passed at construction time.
void AddTerm(IntegerVariable var, IntegerValue coeff)
void AddLinearExpression(const LinearExpression &expr)
void AddConstant(IntegerValue value)
Adds the corresponding term to the current linear expression.
LiteralIndex NegatedIndex() const
Definition sat_base.h:92
Utility class for the AllDiff cut generator.
Definition cuts.h:726
IntegerValue GetBestLowerBound(std::string &suffix)
Definition cuts.cc:2404
void Add(const AffineExpression &expr, int num_expr, const IntegerTrail &integer_trail)
Definition cuts.cc:2357
IntegerValue SumOfMinDomainValues()
Return int_max if the sum overflows.
Definition cuts.cc:2382
void TransferToManager(LinearConstraintManager *manager)
Empty the local pool and add all its content to the manager.
void AddCut(LinearConstraint ct, absl::string_view name, const util_intops::StrongVector< IntegerVariable, double > &lp_solution)
Adds a cut to the local pool.
void STLSortAndRemoveDuplicates(T *v, const LessFunc &less_func)
Definition stl_util.h:55
bool AddProductTo(IntegerValue a, IntegerValue b, IntegerValue *result)
Computes result += a * b, and return false iff there is an overflow.
void DivideByGCD(LinearConstraint *constraint)
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
bool BuildMaxAffineUpConstraint(const LinearExpression &target, IntegerVariable var, absl::Span< const std::pair< IntegerValue, IntegerValue > > affines, Model *model, LinearConstraintBuilder *builder)
Definition cuts.cc:2668
IntegerValue GetFactorT(IntegerValue rhs_remainder, IntegerValue divisor, IntegerValue max_magnitude)
Definition cuts.cc:471
IntType IntTypeAbs(IntType t)
CutGenerator CreatePositiveMultiplicationCutGenerator(AffineExpression z, AffineExpression x, AffineExpression y, int linearization_level, Model *model)
A cut generator for z = x * y (x and y >= 0).
Definition cuts.cc:1876
bool ProdOverflow(IntegerValue t, IntegerValue value)
const LiteralIndex kNoLiteralIndex(-1)
LinearConstraint ComputeHyperplanBelowSquare(AffineExpression x, AffineExpression square, IntegerValue x_value, Model *model)
Definition cuts.cc:1983
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)
CutGenerator CreateLinMaxCutGenerator(const IntegerVariable target, absl::Span< const LinearExpression > exprs, absl::Span< const IntegerVariable > z_vars, Model *model)
Definition cuts.cc:2579
void CleanTermsAndFillConstraint(std::vector< std::pair< IntegerVariable, IntegerValue > > *terms, LinearExpression *output)
std::function< IntegerValue(IntegerValue)> GetSuperAdditiveStrengtheningFunction(IntegerValue positive_rhs, IntegerValue min_magnitude)
Definition cuts.cc:570
CutGenerator CreateAllDifferentCutGenerator(absl::Span< const AffineExpression > exprs, Model *model)
Definition cuts.cc:2467
CutGenerator CreateSquareCutGenerator(AffineExpression y, AffineExpression x, int linearization_level, Model *model)
Definition cuts.cc:1995
CutGenerator CreateCliqueCutGenerator(absl::Span< const IntegerVariable > base_variables, Model *model)
Definition cuts.cc:2744
IntegerVariable PositiveVariable(IntegerVariable i)
IntegerValue PositiveRemainder(IntegerValue dividend, IntegerValue positive_divisor)
CutGenerator CreateMaxAffineCutGenerator(LinearExpression target, IntegerVariable var, std::vector< std::pair< IntegerValue, IntegerValue > > affines, const std::string cut_name, Model *model)
Definition cuts.cc:2722
IntegerValue CapAddI(IntegerValue a, IntegerValue b)
LinearConstraint ComputeHyperplanAboveSquare(AffineExpression x, AffineExpression square, IntegerValue x_lb, IntegerValue x_ub, Model *model)
Definition cuts.cc:1971
IntegerValue GetCoefficientOfPositiveVar(const IntegerVariable var, const LinearExpression &expr)
bool ValidateLinearConstraintForOverflow(const LinearConstraint &constraint, const IntegerTrail &integer_trail)
std::function< IntegerValue(IntegerValue)> ExtendNegativeFunction(std::function< IntegerValue(IntegerValue)> base_f, IntegerValue period)
Definition cuts.h:375
std::function< IntegerValue(IntegerValue)> GetSuperAdditiveStrengtheningMirFunction(IntegerValue positive_rhs, IntegerValue scaling)
Definition cuts.cc:605
bool VariableIsPositive(IntegerVariable i)
IntegerValue CapSubI(IntegerValue a, IntegerValue b)
bool AtMinOrMaxInt64I(IntegerValue t)
IntegerValue CapProdI(IntegerValue a, IntegerValue b)
Overflows and saturated arithmetic.
double ToDouble(IntegerValue value)
std::function< IntegerValue(IntegerValue)> GetSuperAdditiveRoundingFunction(IntegerValue rhs_remainder, IntegerValue divisor, IntegerValue t, IntegerValue max_scaling)
Definition cuts.cc:485
In SWIG mode, we don't want anything besides these top-level includes.
bool AtMinOrMaxInt64(int64_t x)
Checks if x is equal to the min or the max value of an int64_t.
int64_t CapAdd(int64_t x, int64_t y)
int64_t FloorRatio(int64_t value, int64_t positive_coeff)
int64_t CeilRatio(int64_t value, int64_t positive_coeff)
int64_t CapProd(int64_t x, int64_t y)
if(!yyg->yy_init)
Definition parser.yy.cc:966
static int input(yyscan_t yyscanner)
IntegerValue ValueAt(IntegerValue var_value) const
Returns the value of this affine expression given its variable value.
double LpValue(const util_intops::StrongVector< IntegerVariable, double > &lp_values) const
Returns the affine expression value under a given LP solution.
Our cut are always of the form linear_expression <= rhs.
Definition cuts.h:116
bool FillFromLinearConstraint(const LinearConstraint &base_ct, const util_intops::StrongVector< IntegerVariable, double > &lp_values, IntegerTrail *integer_trail)
Definition cuts.cc:174
bool AllCoefficientsArePositive() const
These functions transform the cut by complementation.
Definition cuts.cc:232
std::vector< CutTerm > terms
Definition cuts.h:152
bool FillFromParallelVectors(IntegerValue ub, absl::Span< const IntegerVariable > vars, absl::Span< const IntegerValue > coeffs, absl::Span< const double > lp_values, absl::Span< const IntegerValue > lower_bounds, absl::Span< const IntegerValue > upper_bounds)
Definition cuts.cc:192
double ComputeEfficacy() const
Definition cuts.cc:265
std::string DebugString() const
Definition cuts.cc:76
double ComputeViolation() const
Computes and returns the cut violation.
Definition cuts.cc:257
IntegerValue max_magnitude
Only filled after SortRelevantEntries().
Definition cuts.h:155
bool AppendOneTerm(IntegerVariable var, IntegerValue coeff, double lp_value, IntegerValue lb, IntegerValue ub)
Definition cuts.cc:137
absl::AnyInvocable< bool(LinearConstraintManager *manager)> generate_cuts
Definition cuts.h:59
std::vector< IntegerVariable > vars
Definition cuts.h:58
IntegerVariable GetUnderlyingLiteralOrNone() const
Definition cuts.cc:117
std::string DebugString() const
Definition cuts.cc:68
int cached_implied_lb
Refer to cached_data_ in ImpliedBoundsProcessor.
Definition cuts.h:111
double LpDistToMaxValue() const
Definition cuts.h:72
void ReplaceExpressionByLiteral(IntegerVariable var)
Definition cuts.cc:103
void Complement(absl::int128 *rhs)
Definition cuts.cc:84
std::array< IntegerVariable, 2 > expr_vars
Definition cuts.h:107
std::array< IntegerValue, 2 > expr_coeffs
Definition cuts.h:108
bool HasRelevantLpValue() const
Definition cuts.h:68
static IntegerLiteral GreaterOrEqual(IntegerVariable i, IntegerValue bound)
std::unique_ptr< IntegerValue[]> coeffs
std::unique_ptr< IntegerVariable[]> vars