Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cuts.h
Go to the documentation of this file.
1// Copyright 2010-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14#ifndef OR_TOOLS_SAT_CUTS_H_
15#define OR_TOOLS_SAT_CUTS_H_
16
17#include <stdint.h>
18
19#include <algorithm>
20#include <array>
21#include <functional>
22#include <limits>
23#include <string>
24#include <utility>
25#include <vector>
26
27#include "absl/container/btree_map.h"
28#include "absl/container/btree_set.h"
29#include "absl/container/flat_hash_map.h"
30#include "absl/container/flat_hash_set.h"
31#include "absl/numeric/int128.h"
32#include "absl/strings/str_cat.h"
33#include "absl/types/span.h"
36#include "ortools/sat/integer.h"
39#include "ortools/sat/model.h"
42
43namespace operations_research {
44namespace sat {
45
46// A "cut" generator on a set of IntegerVariable.
47//
48// The generate_cuts() function can get the current LP solution with
49// manager->LpValues(). Note that a CutGenerator should:
50// - Only look at the lp_values positions that corresponds to its 'vars' or
51// their negation.
52// - Only add cuts in term of the same variables or their negation.
55 std::vector<IntegerVariable> vars;
56 std::function<bool(LinearConstraintManager* manager)> generate_cuts;
57};
58
59// To simplify cut generation code, we use a more complex data structure than
60// just a LinearConstraint to represent a cut with shifted/complemented variable
61// and implied bound substitution.
62struct CutTerm {
63 bool IsBoolean() const { return bound_diff == 1; }
64 bool IsSimple() const { return expr_coeffs[1] == 0; }
65 bool HasRelevantLpValue() const { return lp_value > 1e-2; }
66 double LpDistToMaxValue() const {
67 return static_cast<double>(bound_diff.value()) - lp_value;
68 }
69
70 std::string DebugString() const;
71
72 // Do the subtitution X -> (1 - X') and update the rhs.
73 //
74 // Our precondition on the sum of variable domains fitting an int64_t should
75 // ensure that this can never overflow.
76 void Complement(absl::int128* rhs);
77
78 // This assumes bound_diff == 1. It replaces the inner expression by either
79 // var or 1 - var depending on the positiveness of var.
80 void ReplaceExpressionByLiteral(IntegerVariable var);
81
82 // If the term correspond to literal_view or (1 - literal_view) return the
83 // integer variable representation of that literal. Returns kNoIntegerVariable
84 // if this is not the case.
85 IntegerVariable GetUnderlyingLiteralOrNone() const;
86
87 // Each term is of the form coeff * X where X is a variable with given
88 // lp_value and with a domain in [0, bound_diff]. Note X is always >= 0.
89 double lp_value = 0.0;
90 IntegerValue coeff = IntegerValue(0);
91 IntegerValue bound_diff = IntegerValue(0);
92
93 // X = the given LinearExpression.
94 // We only support size 1 or 2 here which allow to inline the memory.
95 // When a coefficient is zero, we don't care about the variable.
96 //
97 // TODO(user): We might want to store that elsewhere, as sorting CutTerm is a
98 // bit slow and we don't need to look at that in most places. Same for the
99 // cached_implied_lb/ub below.
100 IntegerValue expr_offset = IntegerValue(0);
101 std::array<IntegerVariable, 2> expr_vars;
102 std::array<IntegerValue, 2> expr_coeffs;
103
104 // Refer to cached_data_ in ImpliedBoundsProcessor.
107};
108
109// Our cut are always of the form linear_expression <= rhs.
110struct CutData {
111 // We need level zero bounds and LP relaxation values to fill a CutData.
112 // Returns false if we encounter any integer overflow.
114 const LinearConstraint& base_ct,
116 IntegerTrail* integer_trail);
117
118 bool FillFromParallelVectors(IntegerValue ub,
119 absl::Span<const IntegerVariable> vars,
120 absl::Span<const IntegerValue> coeffs,
121 absl::Span<const double> lp_values,
122 absl::Span<const IntegerValue> lower_bounds,
123 absl::Span<const IntegerValue> upper_bounds);
124
125 bool AppendOneTerm(IntegerVariable var, IntegerValue coeff, double lp_value,
126 IntegerValue lb, IntegerValue ub);
127
128 // These functions transform the cut by complementation.
129 bool AllCoefficientsArePositive() const;
132
133 // Computes and returns the cut violation.
134 double ComputeViolation() const;
135 double ComputeEfficacy() const;
136
137 std::string DebugString() const;
138
139 // Note that we use a 128 bit rhs so we can freely complement variable without
140 // running into overflow.
141 absl::int128 rhs;
142 std::vector<CutTerm> terms;
143
144 // This sorts terms and fill both num_relevant_entries and max_magnitude.
145 void Canonicalize();
146 IntegerValue max_magnitude;
148};
149
150// Stores temporaries used to build or manipulate a CutData.
152 public:
153 // These function allow to merges entries corresponding to the same variable
154 // and complementation. That is (X - lb) and (ub - X) are NOT merged and kept
155 // as separate terms. Note that we currently only merge Booleans since this
156 // is the only case we need.
157 void ClearIndices();
158 void AddOrMergeTerm(const CutTerm& term, IntegerValue t, CutData* cut);
159
160 void ClearNumMerges() { num_merges_ = 0; }
161 int NumMergesSinceLastClear() const { return num_merges_; }
162
163 // Returns false if we encounter an integer overflow.
164 bool ConvertToLinearConstraint(const CutData& cut, LinearConstraint* output);
165
166 private:
167 void RegisterAllBooleanTerms(const CutData& cut);
168
169 int num_merges_ = 0;
170 bool constraint_is_indexed_ = false;
171 absl::flat_hash_map<IntegerVariable, int> bool_index_;
172 absl::flat_hash_map<IntegerVariable, int> secondary_bool_index_;
173 absl::btree_map<IntegerVariable, IntegerValue> tmp_map_;
174};
175
176// Given an upper-bounded linear relation (sum terms <= ub), this algorithm
177// inspects the integer variable appearing in the sum and try to replace each of
178// them by a tight lower bound (>= coeff * binary + lb) using the implied bound
179// repository. By tight, we mean that it will take the same value under the
180// current LP solution.
181//
182// We use a class to reuse memory of the tmp terms.
184 public:
185 // We will only replace IntegerVariable appearing in lp_vars_.
186 ImpliedBoundsProcessor(absl::Span<const IntegerVariable> lp_vars_,
187 IntegerTrail* integer_trail,
188 ImpliedBounds* implied_bounds)
189 : lp_vars_(lp_vars_.begin(), lp_vars_.end()),
190 integer_trail_(integer_trail),
191 implied_bounds_(implied_bounds) {}
192
193 // See if some of the implied bounds equation are violated and add them to
194 // the IB cut pool if it is the case.
195 //
196 // Important: This must be called before we process any constraints with a
197 // different lp_values or level zero bounds.
200
201 // This assumes the term is simple: expr[0] = var - LB / UB - var. We use an
202 // implied lower bound on this expr, independently of the term.coeff sign.
203 //
204 // If possible, returns true and express X = bool_term + slack_term.
205 // If coeff of X is positive, then all coeff will be positive here.
207 IntegerValue factor_t, CutTerm& bool_term,
208 CutTerm& slack_term);
209
210 // This assumes the term is simple: expr[0] = var - LB / UB - var. We use
211 // an implied upper bound on this expr, independently of term.coeff sign.
212 //
213 // If possible, returns true and express X = bool_term + slack_term.
214 // If coeff of X is positive, then bool_term will have a positive coeff but
215 // slack_term will have a negative one.
217 IntegerValue factor_t, CutTerm& bool_term,
218 CutTerm& slack_term);
219
220 // We are about to apply the super-additive function f() to the CutData. Use
221 // implied bound information to eventually substitute and make the cut
222 // stronger. Returns the number of {lb_ib, ub_ib} applied.
223 //
224 // This should lead to stronger cuts even if the norms migth be worse.
225 std::pair<int, int> PostprocessWithImpliedBound(
226 const std::function<IntegerValue(IntegerValue)>& f, IntegerValue factor_t,
227 CutData* cut, CutDataBuilder* builder);
228
229 // Precomputes quantities used by all cut generation.
230 // This allows to do that once rather than 6 times.
231 // Return false if there are no exploitable implied bounds.
232 bool CacheDataForCut(IntegerVariable first_slack, CutData* cut);
233
234 // All our cut code use the same base cut (modulo complement), so we reuse the
235 // hash-map of where boolean are in the cut. Note that even if we add new
236 // entry that are no longer there for another cut algo, we can still reuse the
237 // same hash-map.
238 CutDataBuilder* BaseCutBuilder() { return &base_cut_builder_; }
239
240 bool TryToExpandWithLowerImpliedbound(IntegerValue factor_t, int i,
241 bool complement, CutData* cut,
242 CutDataBuilder* builder);
243
244 // Add a new variable that could be used in the new cuts.
245 // Note that the cache must be computed to take this into account.
246 void AddLpVariable(IntegerVariable var) { lp_vars_.insert(var); }
247
248 // Once RecomputeCacheAndSeparateSomeImpliedBoundCuts() has been called,
249 // we can get the best implied bound for each variables.
250 //
251 // Note that because the variable level zero lower bound might change since
252 // the time this was cached, we just store the implied bound here.
254 double var_lp_value = 0.0;
255 double bool_lp_value = 0.0;
257 IntegerValue implied_bound;
258 IntegerVariable bool_var = kNoIntegerVariable;
259
260 double SlackLpValue(IntegerValue lb) const {
261 const double bool_term =
262 static_cast<double>((implied_bound - lb).value()) * bool_lp_value;
263 return var_lp_value - static_cast<double>(lb.value()) - bool_term;
264 }
265
266 std::string DebugString() const {
267 return absl::StrCat("var - lb == (", implied_bound.value(),
268 " - lb) * bool(", bool_lp_value, ") + slack.");
269 }
270 };
271 BestImpliedBoundInfo GetCachedImpliedBoundInfo(IntegerVariable var) const;
272
273 // As we compute the best implied bounds for each variable, we add violated
274 // cuts here.
275 TopNCuts& IbCutPool() { return ib_cut_pool_; }
276
277 private:
278 BestImpliedBoundInfo ComputeBestImpliedBound(
279 IntegerVariable var,
281
282 absl::flat_hash_set<IntegerVariable> lp_vars_;
283 mutable absl::flat_hash_map<IntegerVariable, BestImpliedBoundInfo> cache_;
284
285 // Temporary data used by CacheDataForCut().
286 CutDataBuilder base_cut_builder_;
287 std::vector<BestImpliedBoundInfo> cached_data_;
288
289 TopNCuts ib_cut_pool_ = TopNCuts(50);
290
291 // Data from the constructor.
292 IntegerTrail* integer_trail_;
293 ImpliedBounds* implied_bounds_;
294};
295
296// Visible for testing. Returns a function f on integers such that:
297// - f is non-decreasing.
298// - f is super-additive: f(a) + f(b) <= f(a + b)
299// - 1 <= f(divisor) <= max_scaling
300// - For all x, f(x * divisor) = x * f(divisor)
301// - For all x, f(x * divisor + remainder) = x * f(divisor)
302//
303// Preconditions:
304// - 0 <= remainder < divisor.
305// - 1 <= max_scaling.
306//
307// This is used in IntegerRoundingCut() and is responsible for "strengthening"
308// the cut. Just taking f(x) = x / divisor result in the non-strengthened cut
309// and using any function that stricly dominate this one is better.
310//
311// Algorithm:
312// - We first scale by a factor t so that rhs_remainder >= divisor / 2.
313// - Then, if max_scaling == 2, we use the function described
314// in "Strenghtening Chvatal-Gomory cuts and Gomory fractional cuts", Adam N.
315// Letchfrod, Andrea Lodi.
316// - Otherwise, we use a generalization of this which is a discretized version
317// of the classical MIR rounding function that only take the value of the
318// form "an_integer / max_scaling". As max_scaling goes to infinity, this
319// converge to the real-valued MIR function.
320//
321// Note that for each value of max_scaling we will get a different function.
322// And that there is no dominance relation between any of these functions. So
323// it could be nice to try to generate a cut using different values of
324// max_scaling.
325IntegerValue GetFactorT(IntegerValue rhs_remainder, IntegerValue divisor,
326 IntegerValue max_magnitude);
327std::function<IntegerValue(IntegerValue)> GetSuperAdditiveRoundingFunction(
328 IntegerValue rhs_remainder, IntegerValue divisor, IntegerValue t,
329 IntegerValue max_scaling);
330
331// If we have an equation sum ci.Xi >= rhs with everything positive, and all
332// ci are >= min_magnitude then any ci >= rhs can be set to rhs. Also if
333// some ci are in [rhs - min, rhs) then they can be strenghtened to rhs - min.
334//
335// If we apply this to the negated equation (sum -ci.Xi + sum cj.Xj <= -rhs)
336// with potentially positive terms, this reduce to apply a super-additive
337// function:
338//
339// Plot look like:
340// x=-rhs x=0
341// | |
342// y=0 : | ---------------------------------
343// | ---
344// | /
345// |---
346// y=-rhs -------
347//
348// TODO(user): Extend it for ci >= max_magnitude, we can probaly "lift" such
349// coefficient.
350std::function<IntegerValue(IntegerValue)> GetSuperAdditiveStrengtheningFunction(
351 IntegerValue positive_rhs, IntegerValue min_magnitude);
352
353// Similar to above but with scaling of the linear part to just have at most
354// scaling values.
355std::function<IntegerValue(IntegerValue)>
356GetSuperAdditiveStrengtheningMirFunction(IntegerValue positive_rhs,
357 IntegerValue scaling);
358
359// Given a super-additive non-decreasing function f(), we periodically extend
360// its restriction from [-period, 0] to Z. Such extension is not always
361// super-additive and it is up to the caller to know when this is true or not.
362inline std::function<IntegerValue(IntegerValue)> ExtendNegativeFunction(
363 std::function<IntegerValue(IntegerValue)> base_f, IntegerValue period) {
364 const IntegerValue m = -base_f(-period);
365 return [m, period, base_f](IntegerValue v) {
366 const IntegerValue r = PositiveRemainder(v, period);
367 const IntegerValue output_r = m + base_f(r - period);
368 return FloorRatio(v, period) * m + output_r;
369 };
370}
371
372// Given an upper bounded linear constraint, this function tries to transform it
373// to a valid cut that violate the given LP solution using integer rounding.
374// Note that the returned cut might not always violate the LP solution, in which
375// case it can be discarded.
376//
377// What this does is basically take the integer division of the constraint by an
378// integer. If the coefficients where doubles, this would be the same as scaling
379// the constraint and then rounding. We choose the coefficient of the most
380// fractional variable (rescaled by its coefficient) as the divisor, but there
381// are other possible alternatives.
382//
383// Note that if the constraint is tight under the given lp solution, and if
384// there is a unique variable not at one of its bounds and fractional, then we
385// are guaranteed to generate a cut that violate the current LP solution. This
386// should be the case for Chvatal-Gomory base constraints modulo our loss of
387// precision while doing exact integer computations.
388//
389// Precondition:
390// - We assumes that the given initial constraint is tight using the given lp
391// values. This could be relaxed, but for now it should always be the case, so
392// we log a message and abort if not, to ease debugging.
393// - The IntegerVariable of the cuts are not used here. We assumes that the
394// first three vectors are in one to one correspondence with the initial order
395// of the variable in the cut.
396//
397// TODO(user): There is a bunch of heuristic involved here, and we could spend
398// more effort tuning them. In particular, one can try many heuristics and keep
399// the best looking cut (or more than one). This is not on the critical code
400// path, so we can spend more effort in finding good cuts.
402 IntegerValue max_scaling = IntegerValue(60);
405};
407 public:
409
410 // Returns true on success. The cut can be accessed via cut().
411 bool ComputeCut(RoundingOptions options, const CutData& base_ct,
412 ImpliedBoundsProcessor* ib_processor = nullptr);
413
414 // If successful, info about the last generated cut.
415 const CutData& cut() const { return cut_; }
416
417 void SetSharedStatistics(SharedStatistics* stats) { shared_stats_ = stats; }
418
419 // Single line of text that we append to the cut log line.
420 std::string Info() const { return absl::StrCat("ib_lift=", num_ib_used_); }
421
422 private:
423 double GetScaledViolation(IntegerValue divisor, IntegerValue max_scaling,
424 IntegerValue remainder_threshold,
425 const CutData& cut);
426
427 // The helper is just here to reuse the memory for these vectors.
428 std::vector<IntegerValue> divisors_;
429 std::vector<IntegerValue> remainders_;
430 std::vector<IntegerValue> rs_;
431 std::vector<IntegerValue> best_rs_;
432
433 int64_t num_ib_used_ = 0;
434 CutDataBuilder cut_builder_;
435 CutData cut_;
436
437 std::vector<std::pair<int, IntegerValue>> adjusted_coeffs_;
438 std::vector<std::pair<int, IntegerValue>> best_adjusted_coeffs_;
439
440 // Overall stats.
441 SharedStatistics* shared_stats_ = nullptr;
442 int64_t total_num_dominating_f_ = 0;
443 int64_t total_num_pos_lifts_ = 0;
444 int64_t total_num_neg_lifts_ = 0;
445 int64_t total_num_post_complements_ = 0;
446 int64_t total_num_overflow_abort_ = 0;
447 int64_t total_num_coeff_adjust_ = 0;
448 int64_t total_num_merges_ = 0;
449 int64_t total_num_bumps_ = 0;
450 int64_t total_num_final_complements_ = 0;
451
452 int64_t total_num_initial_ibs_ = 0;
453 int64_t total_num_initial_merges_ = 0;
454};
455
456// Helper to find knapsack cover cuts.
458 public:
460
461 // Try to find a cut with a knapsack heuristic. This assumes an input with all
462 // coefficients positive. If this returns true, you can get the cut via cut().
463 //
464 // This uses a lifting procedure similar to what is described in "Lifting the
465 // Knapsack Cover Inequalities for the Knapsack Polytope", Adam N. Letchfod,
466 // Georgia Souli. In particular the section "Lifting via mixed-integer
467 // rounding".
468 bool TrySimpleKnapsack(const CutData& input_ct,
469 ImpliedBoundsProcessor* ib_processor = nullptr);
470
471 // Applies the lifting procedure described in "On Lifted Cover Inequalities: A
472 // New Lifting Procedure with Unusual Properties", Adam N. Letchford, Georgia
473 // Souli. This assumes an input with all coefficients positive.
474 //
475 // The algo is pretty simple, given a cover C for a given rhs. We compute
476 // a rational weight p/q so that sum_C min(w_i, p/q) = rhs. Note that q is
477 // pretty small (lower or equal to the size of C). The generated cut is then
478 // of the form
479 // sum X_i in C for which w_i <= p / q
480 // + sum gamma_i X_i for the other variable <= |C| - 1.
481 //
482 // gamma_i being the smallest k such that w_i <= sum of the k + 1 largest
483 // min(w_i, p/q) for i in C. In particular, it is zero if w_i <= p/q.
484 //
485 // Note that this accept a general constraint that has been canonicalized to
486 // sum coeff_i * X_i <= base_rhs. Each coeff_i >= 0 and each X_i >= 0.
487 //
488 // TODO(user): Generalize to non-Boolean, or use a different cover heuristic
489 // for this:
490 // - We want a Boolean only cover currently.
491 // - We can always use implied bound for this, since there is more chance
492 // for a Bool only cover.
493 // - Also, f() should be super additive on the value <= rhs, i.e. f(a + b) >=
494 // f(a) + f(b), so it is always good to use implied bounds of the form X =
495 // bound * B + Slack.
497 const CutData& input_ct, ImpliedBoundsProcessor* ib_processor = nullptr);
498
499 // It turns out that what FlowCoverCutHelper is doing is really just finding a
500 // cover and generating a cut via coefficient strenghtening instead of MIR
501 // rounding. This more generic version should just always outperform our old
502 // code.
503 bool TrySingleNodeFlow(const CutData& input_ct,
504 ImpliedBoundsProcessor* ib_processor = nullptr);
505
506 // If successful, info about the last generated cut.
507 const CutData& cut() const { return cut_; }
508
509 // Single line of text that we append to the cut log line.
510 std::string Info() const { return absl::StrCat("lift=", num_lifting_); }
511
512 void SetSharedStatistics(SharedStatistics* stats) { shared_stats_ = stats; }
513
514 void ClearCache() { has_bool_base_ct_ = false; }
515
516 private:
517 void InitializeCut(const CutData& input_ct);
518
519 // This looks at base_ct_ and reoder the terms so that the first ones are in
520 // the cover. return zero if no interesting cover was found.
521 template <class CompareAdd, class CompareRemove>
522 int GetCoverSize(int relevant_size);
523
524 // Same as GetCoverSize() but only look at Booleans, and use a different
525 // heuristic.
526 int GetCoverSizeForBooleans();
527
528 template <class Compare>
529 int MinimizeCover(int cover_size, absl::int128 slack);
530
531 // Here to reuse memory, cut_ is both the input and the output.
532 CutData cut_;
533 CutData temp_cut_;
534 CutDataBuilder cut_builder_;
535
536 // Hack to not sort twice.
537 bool has_bool_base_ct_ = false;
538 CutData bool_base_ct_;
539 int bool_cover_size_ = 0;
540
541 // Stats.
542 SharedStatistics* shared_stats_ = nullptr;
543 int64_t num_lifting_ = 0;
544
545 // Stats for the various type of cuts generated here.
546 struct CutStats {
547 int64_t num_cuts = 0;
548 int64_t num_initial_ibs = 0;
549 int64_t num_lb_ibs = 0;
550 int64_t num_ub_ibs = 0;
551 int64_t num_merges = 0;
552 int64_t num_bumps = 0;
553 int64_t num_lifting = 0;
554 int64_t num_overflow_aborts = 0;
555 };
556 CutStats flow_stats_;
557 CutStats cover_stats_;
558 CutStats ls_stats_;
559};
560
561// Separate RLT cuts.
562//
563// See for instance "Efficient Separation of RLT Cuts for Implicit and Explicit
564// Bilinear Products", Ksenia Bestuzheva, Ambros Gleixner, Tobias Achterberg,
565// https://arxiv.org/abs/2211.13545
567 public:
569 : product_detector_(model->GetOrCreate<ProductDetector>()),
570 shared_stats_(model->GetOrCreate<SharedStatistics>()),
571 lp_values_(model->GetOrCreate<ModelLpValues>()) {};
573
574 // Precompute data according to the current lp relaxation.
575 // This also restrict any Boolean to be currently appearing in the LP.
576 void Initialize(
577 const absl::flat_hash_map<IntegerVariable, glop::ColIndex>& lp_vars);
578
579 // Tries RLT separation of the input constraint. Returns true on success.
580 bool TrySimpleSeparation(const CutData& input_ct);
581
582 // If successful, this contains the last generated cut.
583 const CutData& cut() const { return cut_; }
584
585 // Single line of text that we append to the cut log line.
586 std::string Info() const { return ""; }
587
588 private:
589 // LP value of a literal encoded as an IntegerVariable.
590 // That is lit(X) = X if X positive or 1 - X otherwise.
591 double GetLiteralLpValue(IntegerVariable var) const;
592
593 // Multiplies input by lit(factor) and linearize in the best possible way.
594 // The result will be stored in cut_.
595 bool TryProduct(IntegerVariable factor, const CutData& input);
596
597 bool enabled_ = false;
598 CutData filtered_input_;
599 CutData cut_;
600
601 ProductDetector* product_detector_;
602 SharedStatistics* shared_stats_;
603 ModelLpValues* lp_values_;
604
605 int64_t num_tried_ = 0;
606 int64_t num_tried_factors_ = 0;
607};
608
609// A cut generator for z = x * y (x and y >= 0).
610CutGenerator CreatePositiveMultiplicationCutGenerator(AffineExpression z,
611 AffineExpression x,
612 AffineExpression y,
613 int linearization_level,
614 Model* model);
615
616// Above hyperplan for square = x * x: square should be below the line
617// (x_lb, x_lb ^ 2) to (x_ub, x_ub ^ 2).
618// The slope of that line is (ub^2 - lb^2) / (ub - lb) = ub + lb.
619// square <= (x_lb + x_ub) * x - x_lb * x_ub
620// This only works for positive x.
621LinearConstraint ComputeHyperplanAboveSquare(AffineExpression x,
622 AffineExpression square,
623 IntegerValue x_lb,
624 IntegerValue x_ub, Model* model);
625
626// Below hyperplan for square = x * x: y should be above the line
627// (x_value, x_value ^ 2) to (x_value + 1, (x_value + 1) ^ 2)
628// The slope of that line is 2 * x_value + 1
629// square >= below_slope * (x - x_value) + x_value ^ 2
630// square >= below_slope * x - x_value ^ 2 - x_value
631LinearConstraint ComputeHyperplanBelowSquare(AffineExpression x,
632 AffineExpression square,
633 IntegerValue x_value,
634 Model* model);
635
636// A cut generator for y = x ^ 2 (x >= 0).
637// It will dynamically add a linear inequality to push y closer to the parabola.
638CutGenerator CreateSquareCutGenerator(AffineExpression y, AffineExpression x,
639 int linearization_level, Model* model);
640
641// A cut generator for all_diff(xi). Let the united domain of all xi be D. Sum
642// of any k-sized subset of xi need to be greater or equal to the sum of
643// smallest k values in D and lesser or equal to the sum of largest k values in
644// D. The cut generator first sorts the variables based on LP values and adds
645// cuts of the form described above if they are violated by lp solution. Note
646// that all the fixed variables are ignored while generating cuts.
648 const std::vector<AffineExpression>& exprs, Model* model);
649
650// Consider the Lin Max constraint with d expressions and n variables in the
651// form: target = max {exprs[k] = Sum (wki * xi + bk)}. k in {1,..,d}.
652// Li = lower bound of xi
653// Ui = upper bound of xi.
654// Let zk be in {0,1} for all k in {1,..,d}.
655// The target = exprs[k] when zk = 1.
656//
657// The following is a valid linearization for Lin Max.
658// target >= exprs[k], for all k in {1,..,d}
659// target <= Sum (wli * xi) + Sum((Nlk + bk) * zk), for all l in {1,..,d}
660// Where Nlk is a large number defined as:
661// Nlk = Sum (max((wki - wli)*Li, (wki - wli)*Ui))
662// = Sum (max corner difference for variable i, target expr l, max expr k)
663//
664// Consider a partition of variables xi into set {1,..,d} as I.
665// i.e. I(i) = j means xi is mapped to jth index.
666// The following inequality is valid and sharp cut for the lin max constraint
667// described above.
668//
669// target <= Sum(i=1..n)(wI(i)i * xi + Sum(k=1..d)(MPlusCoefficient_ki * zk))
670// + Sum(k=1..d)(bk * zk) ,
671// Where MPlusCoefficient_ki = max((wki - wI(i)i) * Li,
672// (wki - wI(i)i) * Ui)
673// = max corner difference for variable i,
674// target expr I(i), max expr k.
675//
676// For detailed proof of validity, refer
677// Reference: "Strong mixed-integer programming formulations for trained neural
678// networks" by Ross Anderson et. (https://arxiv.org/pdf/1811.01988.pdf).
679//
680// In the cut generator, we compute the most violated partition I by computing
681// the rhs value (wI(i)i * lp_value(xi) + Sum(k=1..d)(MPlusCoefficient_ki * zk))
682// for each variable for each partition index. We choose the partition index
683// that gives lowest rhs value for a given variable.
684//
685// Note: This cut generator requires all expressions to contain only positive
686// vars.
687CutGenerator CreateLinMaxCutGenerator(
688 IntegerVariable target, const std::vector<LinearExpression>& exprs,
689 const std::vector<IntegerVariable>& z_vars, Model* model);
690
691// Helper for the affine max constraint.
692//
693// This function will reset the bounds of the builder.
695 const LinearExpression& target, IntegerVariable var,
696 const std::vector<std::pair<IntegerValue, IntegerValue>>& affines,
697 Model* model, LinearConstraintBuilder* builder);
698
699// By definition, the Max of affine functions is convex. The linear polytope is
700// bounded by all affine functions on the bottom, and by a single hyperplane
701// that join the two points at the extreme of the var domain, and their y-values
702// of the max of the affine functions.
703CutGenerator CreateMaxAffineCutGenerator(
704 LinearExpression target, IntegerVariable var,
705 std::vector<std::pair<IntegerValue, IntegerValue>> affines,
706 std::string cut_name, Model* model);
707
708// Extracts the variables that have a Literal view from base variables and
709// create a generator that will returns constraint of the form "at_most_one"
710// between such literals.
711CutGenerator CreateCliqueCutGenerator(
712 const std::vector<IntegerVariable>& base_variables, Model* model);
713
714// Utility class for the AllDiff cut generator.
716 public:
717 void Clear();
718 void Add(const AffineExpression& expr, int num_expr,
719 const IntegerTrail& integer_trail);
720
721 IntegerValue SumOfMinDomainValues();
722 IntegerValue SumOfDifferentMins();
723 IntegerValue GetBestLowerBound(std::string& suffix);
724
725 int size() const { return expr_mins_.size(); }
726
727 private:
728 absl::btree_set<IntegerValue> min_values_;
729 std::vector<IntegerValue> expr_mins_;
730};
731
732} // namespace sat
733} // namespace operations_research
734
735#endif // OR_TOOLS_SAT_CUTS_H_
IntegerValue y
bool TrySimpleSeparation(const CutData &input_ct)
Tries RLT separation of the input constraint. Returns true on success.
Definition cuts.cc:1660
void Initialize(const absl::flat_hash_map< IntegerVariable, glop::ColIndex > &lp_vars)
Definition cuts.cc:1653
std::string Info() const
Single line of text that we append to the cut log line.
Definition cuts.h:586
const CutData & cut() const
If successful, this contains the last generated cut.
Definition cuts.h:583
Helper to find knapsack cover cuts.
Definition cuts.h:457
const CutData & cut() const
If successful, info about the last generated cut.
Definition cuts.h:507
bool TrySimpleKnapsack(const CutData &input_ct, ImpliedBoundsProcessor *ib_processor=nullptr)
Definition cuts.cc:1293
std::string Info() const
Single line of text that we append to the cut log line.
Definition cuts.h:510
bool TryWithLetchfordSouliLifting(const CutData &input_ct, ImpliedBoundsProcessor *ib_processor=nullptr)
Definition cuts.cc:1512
void SetSharedStatistics(SharedStatistics *stats)
Definition cuts.h:512
bool TrySingleNodeFlow(const CutData &input_ct, ImpliedBoundsProcessor *ib_processor=nullptr)
Definition cuts.cc:1408
Stores temporaries used to build or manipulate a CutData.
Definition cuts.h:151
bool ConvertToLinearConstraint(const CutData &cut, LinearConstraint *output)
Returns false if we encounter an integer overflow.
Definition cuts.cc:364
void AddOrMergeTerm(const CutTerm &term, IntegerValue t, CutData *cut)
Definition cuts.cc:294
void RecomputeCacheAndSeparateSomeImpliedBoundCuts(const util_intops::StrongVector< IntegerVariable, double > &lp_values)
Definition cuts.cc:2094
bool CacheDataForCut(IntegerVariable first_slack, CutData *cut)
Definition cuts.cc:2307
ImpliedBoundsProcessor(absl::Span< const IntegerVariable > lp_vars_, IntegerTrail *integer_trail, ImpliedBounds *implied_bounds)
We will only replace IntegerVariable appearing in lp_vars_.
Definition cuts.h:186
void AddLpVariable(IntegerVariable var)
Definition cuts.h:246
BestImpliedBoundInfo GetCachedImpliedBoundInfo(IntegerVariable var) const
Definition cuts.cc:2014
bool DecomposeWithImpliedLowerBound(const CutTerm &term, IntegerValue factor_t, CutTerm &bool_term, CutTerm &slack_term)
Definition cuts.cc:2104
bool TryToExpandWithLowerImpliedbound(IntegerValue factor_t, int i, bool complement, CutData *cut, CutDataBuilder *builder)
Important: The cut_builder_ must have been reset.
Definition cuts.cc:2274
std::pair< int, int > PostprocessWithImpliedBound(const std::function< IntegerValue(IntegerValue)> &f, IntegerValue factor_t, CutData *cut, CutDataBuilder *builder)
Definition cuts.cc:2195
bool DecomposeWithImpliedUpperBound(const CutTerm &term, IntegerValue factor_t, CutTerm &bool_term, CutTerm &slack_term)
Definition cuts.cc:2174
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:785
const CutData & cut() const
If successful, info about the last generated cut.
Definition cuts.h:415
std::string Info() const
Single line of text that we append to the cut log line.
Definition cuts.h:420
void SetSharedStatistics(SharedStatistics *stats)
Definition cuts.h:417
Simple class to add statistics by name and print them at the end.
Utility class for the AllDiff cut generator.
Definition cuts.h:715
IntegerValue GetBestLowerBound(std::string &suffix)
Definition cuts.cc:2391
void Add(const AffineExpression &expr, int num_expr, const IntegerTrail &integer_trail)
Definition cuts.cc:2344
IntVar * var
GRBmodel * model
IntegerValue FloorRatio(IntegerValue dividend, IntegerValue positive_divisor)
Definition integer.h:94
CutGenerator CreateCliqueCutGenerator(const std::vector< IntegerVariable > &base_variables, Model *model)
Definition cuts.cc:2724
IntegerValue GetFactorT(IntegerValue rhs_remainder, IntegerValue divisor, IntegerValue max_magnitude)
Definition cuts.cc:482
bool BuildMaxAffineUpConstraint(const LinearExpression &target, IntegerVariable var, const std::vector< std::pair< IntegerValue, IntegerValue > > &affines, Model *model, LinearConstraintBuilder *builder)
Definition cuts.cc:2648
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:1859
LinearConstraint ComputeHyperplanBelowSquare(AffineExpression x, AffineExpression square, IntegerValue x_value, Model *model)
Definition cuts.cc:1966
CutGenerator CreateLinMaxCutGenerator(const IntegerVariable target, const std::vector< LinearExpression > &exprs, const std::vector< IntegerVariable > &z_vars, Model *model)
Definition cuts.cc:2563
const IntegerVariable kNoIntegerVariable(-1)
std::function< IntegerValue(IntegerValue)> GetSuperAdditiveStrengtheningFunction(IntegerValue positive_rhs, IntegerValue min_magnitude)
Definition cuts.cc:581
CutGenerator CreateSquareCutGenerator(AffineExpression y, AffineExpression x, int linearization_level, Model *model)
Definition cuts.cc:1978
IntegerValue PositiveRemainder(IntegerValue dividend, IntegerValue positive_divisor)
Definition integer.h:153
CutGenerator CreateMaxAffineCutGenerator(LinearExpression target, IntegerVariable var, std::vector< std::pair< IntegerValue, IntegerValue > > affines, const std::string cut_name, Model *model)
Definition cuts.cc:2702
LinearConstraint ComputeHyperplanAboveSquare(AffineExpression x, AffineExpression square, IntegerValue x_lb, IntegerValue x_ub, Model *model)
Definition cuts.cc:1954
CutGenerator CreateAllDifferentCutGenerator(const std::vector< AffineExpression > &exprs, Model *model)
Definition cuts.cc:2452
std::function< IntegerValue(IntegerValue)> ExtendNegativeFunction(std::function< IntegerValue(IntegerValue)> base_f, IntegerValue period)
Definition cuts.h:362
std::function< IntegerValue(IntegerValue)> GetSuperAdditiveStrengtheningMirFunction(IntegerValue positive_rhs, IntegerValue scaling)
Definition cuts.cc:616
std::function< IntegerValue(IntegerValue)> GetSuperAdditiveRoundingFunction(IntegerValue rhs_remainder, IntegerValue divisor, IntegerValue t, IntegerValue max_scaling)
Definition cuts.cc:496
In SWIG mode, we don't want anything besides these top-level includes.
static int input(yyscan_t yyscanner)
const Variable x
Definition qp_tests.cc:127
std::vector< double > lower_bounds
Definition lp_utils.cc:746
std::vector< double > upper_bounds
Definition lp_utils.cc:747
std::optional< int64_t > end
Our cut are always of the form linear_expression <= rhs.
Definition cuts.h:110
void Canonicalize()
This sorts terms and fill both num_relevant_entries and max_magnitude.
Definition cuts.cc:235
bool FillFromLinearConstraint(const LinearConstraint &base_ct, const util_intops::StrongVector< IntegerVariable, double > &lp_values, IntegerTrail *integer_trail)
Definition cuts.cc:170
bool AllCoefficientsArePositive() const
These functions transform the cut by complementation.
Definition cuts.cc:228
std::vector< CutTerm > terms
Definition cuts.h:142
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:188
double ComputeEfficacy() const
Definition cuts.cc:262
std::string DebugString() const
Definition cuts.cc:72
double ComputeViolation() const
Computes and returns the cut violation.
Definition cuts.cc:254
bool AppendOneTerm(IntegerVariable var, IntegerValue coeff, double lp_value, IntegerValue lb, IntegerValue ub)
Definition cuts.cc:133
std::vector< IntegerVariable > vars
Definition cuts.h:55
std::function< bool(LinearConstraintManager *manager)> generate_cuts
Definition cuts.h:56
IntegerVariable GetUnderlyingLiteralOrNone() const
Definition cuts.cc:113
std::string DebugString() const
Definition cuts.cc:64
int cached_implied_lb
Refer to cached_data_ in ImpliedBoundsProcessor.
Definition cuts.h:105
double LpDistToMaxValue() const
Definition cuts.h:66
void ReplaceExpressionByLiteral(IntegerVariable var)
Definition cuts.cc:99
void Complement(absl::int128 *rhs)
Definition cuts.cc:80
std::array< IntegerVariable, 2 > expr_vars
Definition cuts.h:101
std::array< IntegerValue, 2 > expr_coeffs
Definition cuts.h:102
bool HasRelevantLpValue() const
Definition cuts.h:65