forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cuts.cc
2174 lines (1973 loc) · 86.2 KB
/
cuts.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/cuts.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <functional>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/btree_set.h"
#include "ortools/algorithms/knapsack_solver_for_cuts.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/strong_vector.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/linear_constraint.h"
#include "ortools/sat/linear_constraint_manager.h"
#include "ortools/sat/sat_base.h"
#include "ortools/sat/util.h"
#include "ortools/util/time_limit.h"
namespace operations_research {
namespace sat {
namespace {
// Minimum amount of violation of the cut constraint by the solution. This
// is needed to avoid numerical issues and adding cuts with minor effect.
const double kMinCutViolation = 1e-4;
// Returns the lp value of a Literal.
double GetLiteralLpValue(
const Literal lit,
const absl::StrongVector<IntegerVariable, double>& lp_values,
const IntegerEncoder* encoder) {
const IntegerVariable direct_view = encoder->GetLiteralView(lit);
if (direct_view != kNoIntegerVariable) {
return lp_values[direct_view];
}
const IntegerVariable opposite_view = encoder->GetLiteralView(lit.Negated());
DCHECK_NE(opposite_view, kNoIntegerVariable);
return 1.0 - lp_values[opposite_view];
}
// Returns a constraint that disallow all given variables to be at their current
// upper bound. The arguments must form a non-trival constraint of the form
// sum terms (coeff * var) <= upper_bound.
LinearConstraint GenerateKnapsackCutForCover(
const std::vector<IntegerVariable>& vars,
const std::vector<IntegerValue>& coeffs, const IntegerValue upper_bound,
const IntegerTrail& integer_trail) {
CHECK_EQ(vars.size(), coeffs.size());
CHECK_GT(vars.size(), 0);
LinearConstraint cut;
IntegerValue cut_upper_bound = IntegerValue(0);
IntegerValue max_coeff = coeffs[0];
// slack = \sum_{i}(coeffs[i] * upper_bound[i]) - upper_bound.
IntegerValue slack = -upper_bound;
for (int i = 0; i < vars.size(); ++i) {
const IntegerValue var_upper_bound =
integer_trail.LevelZeroUpperBound(vars[i]);
cut_upper_bound += var_upper_bound;
cut.vars.push_back(vars[i]);
cut.coeffs.push_back(IntegerValue(1));
max_coeff = std::max(max_coeff, coeffs[i]);
slack += coeffs[i] * var_upper_bound;
}
CHECK_GT(slack, 0.0) << "Invalid cover for knapsack cut.";
cut_upper_bound -= CeilRatio(slack, max_coeff);
cut.lb = kMinIntegerValue;
cut.ub = cut_upper_bound;
VLOG(2) << "Generated Knapsack Constraint:" << cut.DebugString();
return cut;
}
bool SolutionSatisfiesConstraint(
const LinearConstraint& constraint,
const absl::StrongVector<IntegerVariable, double>& lp_values) {
const double activity = ComputeActivity(constraint, lp_values);
const double tolerance = 1e-6;
return (activity <= ToDouble(constraint.ub) + tolerance &&
activity >= ToDouble(constraint.lb) - tolerance)
? true
: false;
}
bool SmallRangeAndAllCoefficientsMagnitudeAreTheSame(
const LinearConstraint& constraint, IntegerTrail* integer_trail) {
if (constraint.vars.empty()) return true;
const int64_t magnitude = std::abs(constraint.coeffs[0].value());
for (int i = 1; i < constraint.coeffs.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
if (integer_trail->LevelZeroUpperBound(var) -
integer_trail->LevelZeroLowerBound(var) >
1) {
return false;
}
if (std::abs(constraint.coeffs[i].value()) != magnitude) {
return false;
}
}
return true;
}
bool AllVarsTakeIntegerValue(
const std::vector<IntegerVariable> vars,
const absl::StrongVector<IntegerVariable, double>& lp_values) {
for (IntegerVariable var : vars) {
if (std::abs(lp_values[var] - std::round(lp_values[var])) > 1e-6) {
return false;
}
}
return true;
}
// Returns smallest cover size for the given constraint taking into account
// level zero bounds. Smallest Cover size is computed as follows.
// 1. Compute the upper bound if all variables are shifted to have zero lower
// bound.
// 2. Sort all terms (coefficient * shifted upper bound) in non decreasing
// order.
// 3. Add terms in cover until term sum is smaller or equal to upper bound.
// 4. Add the last item which violates the upper bound. This forms the smallest
// cover. Return the size of this cover.
int GetSmallestCoverSize(const LinearConstraint& constraint,
const IntegerTrail& integer_trail) {
IntegerValue ub = constraint.ub;
std::vector<IntegerValue> sorted_terms;
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerValue coeff = constraint.coeffs[i];
const IntegerVariable var = constraint.vars[i];
const IntegerValue var_ub = integer_trail.LevelZeroUpperBound(var);
const IntegerValue var_lb = integer_trail.LevelZeroLowerBound(var);
ub -= var_lb * coeff;
sorted_terms.push_back(coeff * (var_ub - var_lb));
}
std::sort(sorted_terms.begin(), sorted_terms.end(),
std::greater<IntegerValue>());
int smallest_cover_size = 0;
IntegerValue sorted_term_sum = IntegerValue(0);
while (sorted_term_sum <= ub &&
smallest_cover_size < constraint.vars.size()) {
sorted_term_sum += sorted_terms[smallest_cover_size++];
}
return smallest_cover_size;
}
bool ConstraintIsEligibleForLifting(const LinearConstraint& constraint,
const IntegerTrail& integer_trail) {
for (const IntegerVariable var : constraint.vars) {
if (integer_trail.LevelZeroLowerBound(var) != IntegerValue(0) ||
integer_trail.LevelZeroUpperBound(var) != IntegerValue(1)) {
return false;
}
}
return true;
}
} // namespace
bool LiftKnapsackCut(
const LinearConstraint& constraint,
const absl::StrongVector<IntegerVariable, double>& lp_values,
const std::vector<IntegerValue>& cut_vars_original_coefficients,
const IntegerTrail& integer_trail, TimeLimit* time_limit,
LinearConstraint* cut) {
std::set<IntegerVariable> vars_in_cut;
for (IntegerVariable var : cut->vars) {
vars_in_cut.insert(var);
}
std::vector<std::pair<IntegerValue, IntegerVariable>> non_zero_vars;
std::vector<std::pair<IntegerValue, IntegerVariable>> zero_vars;
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
if (integer_trail.LevelZeroLowerBound(var) != IntegerValue(0) ||
integer_trail.LevelZeroUpperBound(var) != IntegerValue(1)) {
continue;
}
if (vars_in_cut.find(var) != vars_in_cut.end()) continue;
const IntegerValue coeff = constraint.coeffs[i];
if (lp_values[var] <= 1e-6) {
zero_vars.push_back({coeff, var});
} else {
non_zero_vars.push_back({coeff, var});
}
}
// Decide lifting sequence (nonzeros, zeros in nonincreasing order
// of coefficient ).
std::sort(non_zero_vars.rbegin(), non_zero_vars.rend());
std::sort(zero_vars.rbegin(), zero_vars.rend());
std::vector<std::pair<IntegerValue, IntegerVariable>> lifting_sequence(
std::move(non_zero_vars));
lifting_sequence.insert(lifting_sequence.end(), zero_vars.begin(),
zero_vars.end());
// Form Knapsack.
std::vector<double> lifting_profits;
std::vector<double> lifting_weights;
for (int i = 0; i < cut->vars.size(); ++i) {
lifting_profits.push_back(ToDouble(cut->coeffs[i]));
lifting_weights.push_back(ToDouble(cut_vars_original_coefficients[i]));
}
// Lift the cut.
bool is_lifted = false;
bool is_solution_optimal = false;
KnapsackSolverForCuts knapsack_solver("Knapsack cut lifter");
for (auto entry : lifting_sequence) {
is_solution_optimal = false;
const IntegerValue var_original_coeff = entry.first;
const IntegerVariable var = entry.second;
const IntegerValue lifting_capacity = constraint.ub - entry.first;
if (lifting_capacity <= IntegerValue(0)) continue;
knapsack_solver.Init(lifting_profits, lifting_weights,
ToDouble(lifting_capacity));
knapsack_solver.set_node_limit(100);
// NOTE: Since all profits and weights are integer, solution of
// knapsack is also integer.
// TODO(user): Use an integer solver or heuristic.
knapsack_solver.Solve(time_limit, &is_solution_optimal);
const double knapsack_upper_bound =
std::round(knapsack_solver.GetUpperBound());
const IntegerValue cut_coeff =
cut->ub - static_cast<int64_t>(knapsack_upper_bound);
if (cut_coeff > IntegerValue(0)) {
is_lifted = true;
cut->vars.push_back(var);
cut->coeffs.push_back(cut_coeff);
lifting_profits.push_back(ToDouble(cut_coeff));
lifting_weights.push_back(ToDouble(var_original_coeff));
}
}
return is_lifted;
}
LinearConstraint GetPreprocessedLinearConstraint(
const LinearConstraint& constraint,
const absl::StrongVector<IntegerVariable, double>& lp_values,
const IntegerTrail& integer_trail) {
IntegerValue ub = constraint.ub;
LinearConstraint constraint_with_left_vars;
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
const IntegerValue var_ub = integer_trail.LevelZeroUpperBound(var);
const IntegerValue coeff = constraint.coeffs[i];
if (ToDouble(var_ub) - lp_values[var] <= 1.0 - kMinCutViolation) {
constraint_with_left_vars.vars.push_back(var);
constraint_with_left_vars.coeffs.push_back(coeff);
} else {
// Variable not in cut
const IntegerValue var_lb = integer_trail.LevelZeroLowerBound(var);
ub -= coeff * var_lb;
}
}
constraint_with_left_vars.ub = ub;
constraint_with_left_vars.lb = constraint.lb;
return constraint_with_left_vars;
}
bool ConstraintIsTriviallyTrue(const LinearConstraint& constraint,
const IntegerTrail& integer_trail) {
IntegerValue term_sum = IntegerValue(0);
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
const IntegerValue var_ub = integer_trail.LevelZeroUpperBound(var);
const IntegerValue coeff = constraint.coeffs[i];
term_sum += coeff * var_ub;
}
if (term_sum <= constraint.ub) {
VLOG(2) << "Filtered by cover filter";
return true;
}
return false;
}
bool CanBeFilteredUsingCutLowerBound(
const LinearConstraint& preprocessed_constraint,
const absl::StrongVector<IntegerVariable, double>& lp_values,
const IntegerTrail& integer_trail) {
std::vector<double> variable_upper_bound_distances;
for (const IntegerVariable var : preprocessed_constraint.vars) {
const IntegerValue var_ub = integer_trail.LevelZeroUpperBound(var);
variable_upper_bound_distances.push_back(ToDouble(var_ub) - lp_values[var]);
}
// Compute the min cover size.
const int smallest_cover_size =
GetSmallestCoverSize(preprocessed_constraint, integer_trail);
std::nth_element(
variable_upper_bound_distances.begin(),
variable_upper_bound_distances.begin() + smallest_cover_size - 1,
variable_upper_bound_distances.end());
double cut_lower_bound = 0.0;
for (int i = 0; i < smallest_cover_size; ++i) {
cut_lower_bound += variable_upper_bound_distances[i];
}
if (cut_lower_bound >= 1.0 - kMinCutViolation) {
VLOG(2) << "Filtered by kappa heuristic";
return true;
}
return false;
}
double GetKnapsackUpperBound(std::vector<KnapsackItem> items,
const double capacity) {
// Sort items by value by weight ratio.
std::sort(items.begin(), items.end(), std::greater<KnapsackItem>());
double left_capacity = capacity;
double profit = 0.0;
for (const KnapsackItem item : items) {
if (item.weight <= left_capacity) {
profit += item.profit;
left_capacity -= item.weight;
} else {
profit += (left_capacity / item.weight) * item.profit;
break;
}
}
return profit;
}
bool CanBeFilteredUsingKnapsackUpperBound(
const LinearConstraint& constraint,
const absl::StrongVector<IntegerVariable, double>& lp_values,
const IntegerTrail& integer_trail) {
std::vector<KnapsackItem> items;
double capacity = -ToDouble(constraint.ub) - 1.0;
double sum_variable_profit = 0;
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
const IntegerValue var_ub = integer_trail.LevelZeroUpperBound(var);
const IntegerValue var_lb = integer_trail.LevelZeroLowerBound(var);
const IntegerValue coeff = constraint.coeffs[i];
KnapsackItem item;
item.profit = ToDouble(var_ub) - lp_values[var];
item.weight = ToDouble(coeff * (var_ub - var_lb));
items.push_back(item);
capacity += ToDouble(coeff * var_ub);
sum_variable_profit += item.profit;
}
// Return early if the required upper bound is negative since all the profits
// are non negative.
if (sum_variable_profit - 1.0 + kMinCutViolation < 0.0) return false;
// Get the knapsack upper bound.
const double knapsack_upper_bound =
GetKnapsackUpperBound(std::move(items), capacity);
if (knapsack_upper_bound < sum_variable_profit - 1.0 + kMinCutViolation) {
VLOG(2) << "Filtered by knapsack upper bound";
return true;
}
return false;
}
bool CanFormValidKnapsackCover(
const LinearConstraint& preprocessed_constraint,
const absl::StrongVector<IntegerVariable, double>& lp_values,
const IntegerTrail& integer_trail) {
if (ConstraintIsTriviallyTrue(preprocessed_constraint, integer_trail)) {
return false;
}
if (CanBeFilteredUsingCutLowerBound(preprocessed_constraint, lp_values,
integer_trail)) {
return false;
}
if (CanBeFilteredUsingKnapsackUpperBound(preprocessed_constraint, lp_values,
integer_trail)) {
return false;
}
return true;
}
void ConvertToKnapsackForm(const LinearConstraint& constraint,
std::vector<LinearConstraint>* knapsack_constraints,
IntegerTrail* integer_trail) {
// If all coefficient are the same, the generated knapsack cuts cannot be
// stronger than the constraint itself. However, when we substitute variables
// using the implication graph, this is not longer true. So we only skip
// constraints with same coeff and no substitutions.
if (SmallRangeAndAllCoefficientsMagnitudeAreTheSame(constraint,
integer_trail)) {
return;
}
if (constraint.ub < kMaxIntegerValue) {
LinearConstraint canonical_knapsack_form;
// Negate the variables with negative coefficients.
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
const IntegerValue coeff = constraint.coeffs[i];
if (coeff > IntegerValue(0)) {
canonical_knapsack_form.AddTerm(var, coeff);
} else {
canonical_knapsack_form.AddTerm(NegationOf(var), -coeff);
}
}
canonical_knapsack_form.ub = constraint.ub;
canonical_knapsack_form.lb = kMinIntegerValue;
knapsack_constraints->push_back(canonical_knapsack_form);
}
if (constraint.lb > kMinIntegerValue) {
LinearConstraint canonical_knapsack_form;
// Negate the variables with positive coefficients.
for (int i = 0; i < constraint.vars.size(); ++i) {
const IntegerVariable var = constraint.vars[i];
const IntegerValue coeff = constraint.coeffs[i];
if (coeff > IntegerValue(0)) {
canonical_knapsack_form.AddTerm(NegationOf(var), coeff);
} else {
canonical_knapsack_form.AddTerm(var, -coeff);
}
}
canonical_knapsack_form.ub = -constraint.lb;
canonical_knapsack_form.lb = kMinIntegerValue;
knapsack_constraints->push_back(canonical_knapsack_form);
}
}
// TODO(user): This is no longer used as we try to separate all cut with
// knapsack now, remove.
CutGenerator CreateKnapsackCoverCutGenerator(
const std::vector<LinearConstraint>& base_constraints,
const std::vector<IntegerVariable>& vars, Model* model) {
CutGenerator result;
result.vars = vars;
IntegerTrail* integer_trail = model->GetOrCreate<IntegerTrail>();
std::vector<LinearConstraint> knapsack_constraints;
for (const LinearConstraint& constraint : base_constraints) {
// There is often a lot of small linear base constraints and it doesn't seem
// super useful to generate cuts for constraints of size 2. Any valid cut
// of size 1 should be already infered by the propagation.
//
// TODO(user): The case of size 2 is a bit less clear. investigate more if
// it is useful.
if (constraint.vars.size() <= 2) continue;
ConvertToKnapsackForm(constraint, &knapsack_constraints, integer_trail);
}
VLOG(1) << "#knapsack constraints: " << knapsack_constraints.size();
// Note(user): for Knapsack cuts, it seems always advantageous to replace a
// variable X by a TIGHT lower bound of the form "coeff * binary + lb". This
// will not change "covers" but can only result in more violation by the
// current LP solution.
ImpliedBoundsProcessor implied_bounds_processor(
vars, integer_trail, model->GetOrCreate<ImpliedBounds>());
// TODO(user): do not add generator if there are no knapsack constraints.
result.generate_cuts = [implied_bounds_processor, knapsack_constraints, vars,
model, integer_trail](
const absl::StrongVector<IntegerVariable, double>&
lp_values,
LinearConstraintManager* manager) mutable {
// TODO(user): When we use implied-bound substitution, we might still infer
// an interesting cut even if all variables are integer. See if we still
// want to skip all such constraints.
if (AllVarsTakeIntegerValue(vars, lp_values)) return true;
KnapsackSolverForCuts knapsack_solver(
"Knapsack on demand cover cut generator");
int64_t skipped_constraints = 0;
LinearConstraint mutable_constraint;
// Iterate through all knapsack constraints.
implied_bounds_processor.RecomputeCacheAndSeparateSomeImpliedBoundCuts(
lp_values);
for (const LinearConstraint& constraint : knapsack_constraints) {
if (model->GetOrCreate<TimeLimit>()->LimitReached()) break;
VLOG(2) << "Processing constraint: " << constraint.DebugString();
mutable_constraint = constraint;
implied_bounds_processor.ProcessUpperBoundedConstraint(
lp_values, &mutable_constraint);
MakeAllCoefficientsPositive(&mutable_constraint);
const LinearConstraint preprocessed_constraint =
GetPreprocessedLinearConstraint(mutable_constraint, lp_values,
*integer_trail);
if (preprocessed_constraint.vars.empty()) continue;
if (!CanFormValidKnapsackCover(preprocessed_constraint, lp_values,
*integer_trail)) {
skipped_constraints++;
continue;
}
// Profits are (upper_bounds[i] - lp_values[i]) for knapsack variables.
std::vector<double> profits;
profits.reserve(preprocessed_constraint.vars.size());
// Weights are (coeffs[i] * (upper_bound[i] - lower_bound[i])).
std::vector<double> weights;
weights.reserve(preprocessed_constraint.vars.size());
double capacity = -ToDouble(preprocessed_constraint.ub) - 1.0;
// Compute and store the sum of variable profits. This is the constant
// part of the objective of the problem we are trying to solve. Hence
// this part is not supplied to the knapsack_solver and is subtracted
// when we receive the knapsack solution.
double sum_variable_profit = 0;
// Compute the profits, the weights and the capacity for the knapsack
// instance.
for (int i = 0; i < preprocessed_constraint.vars.size(); ++i) {
const IntegerVariable var = preprocessed_constraint.vars[i];
const double coefficient = ToDouble(preprocessed_constraint.coeffs[i]);
const double var_ub = ToDouble(integer_trail->LevelZeroUpperBound(var));
const double var_lb = ToDouble(integer_trail->LevelZeroLowerBound(var));
const double variable_profit = var_ub - lp_values[var];
profits.push_back(variable_profit);
sum_variable_profit += variable_profit;
const double weight = coefficient * (var_ub - var_lb);
weights.push_back(weight);
capacity += weight + coefficient * var_lb;
}
if (capacity < 0.0) continue;
std::vector<IntegerVariable> cut_vars;
std::vector<IntegerValue> cut_vars_original_coefficients;
VLOG(2) << "Knapsack size: " << profits.size();
knapsack_solver.Init(profits, weights, capacity);
// Set the time limit for the knapsack solver.
const double time_limit_for_knapsack_solver =
model->GetOrCreate<TimeLimit>()->GetTimeLeft();
// Solve the instance and subtract the constant part to compute the
// sum_of_distance_to_ub_for_vars_in_cover.
// TODO(user): Consider solving the instance approximately.
bool is_solution_optimal = false;
knapsack_solver.set_solution_upper_bound_threshold(
sum_variable_profit - 1.0 + kMinCutViolation);
// TODO(user): Consider providing lower bound threshold as
// sum_variable_profit - 1.0 + kMinCutViolation.
// TODO(user): Set node limit for knapsack solver.
auto time_limit_for_solver =
absl::make_unique<TimeLimit>(time_limit_for_knapsack_solver);
const double sum_of_distance_to_ub_for_vars_in_cover =
sum_variable_profit -
knapsack_solver.Solve(time_limit_for_solver.get(),
&is_solution_optimal);
if (is_solution_optimal) {
VLOG(2) << "Knapsack Optimal solution found yay !";
}
if (time_limit_for_solver->LimitReached()) {
VLOG(1) << "Knapsack Solver run out of time limit.";
}
if (sum_of_distance_to_ub_for_vars_in_cover < 1.0 - kMinCutViolation) {
// Constraint is eligible for the cover.
IntegerValue constraint_ub_for_cut = preprocessed_constraint.ub;
std::set<IntegerVariable> vars_in_cut;
for (int i = 0; i < preprocessed_constraint.vars.size(); ++i) {
const IntegerVariable var = preprocessed_constraint.vars[i];
const IntegerValue coefficient = preprocessed_constraint.coeffs[i];
if (!knapsack_solver.best_solution(i)) {
cut_vars.push_back(var);
cut_vars_original_coefficients.push_back(coefficient);
vars_in_cut.insert(var);
} else {
const IntegerValue var_lb = integer_trail->LevelZeroLowerBound(var);
constraint_ub_for_cut -= coefficient * var_lb;
}
}
LinearConstraint cut = GenerateKnapsackCutForCover(
cut_vars, cut_vars_original_coefficients, constraint_ub_for_cut,
*integer_trail);
// Check if the constraint has only binary variables.
bool is_lifted = false;
if (ConstraintIsEligibleForLifting(cut, *integer_trail)) {
if (LiftKnapsackCut(mutable_constraint, lp_values,
cut_vars_original_coefficients, *integer_trail,
model->GetOrCreate<TimeLimit>(), &cut)) {
is_lifted = true;
}
}
CHECK(!SolutionSatisfiesConstraint(cut, lp_values));
manager->AddCut(cut, is_lifted ? "LiftedKnapsack" : "Knapsack",
lp_values);
}
}
if (skipped_constraints > 0) {
VLOG(2) << "Skipped constraints: " << skipped_constraints;
}
return true;
};
return result;
}
// Compute the larger t <= max_t such that t * rhs_remainder >= divisor / 2.
//
// This is just a separate function as it is slightly faster to compute the
// result only once.
IntegerValue GetFactorT(IntegerValue rhs_remainder, IntegerValue divisor,
IntegerValue max_t) {
DCHECK_GE(max_t, 1);
return rhs_remainder == 0
? max_t
: std::min(max_t, CeilRatio(divisor / 2, rhs_remainder));
}
std::function<IntegerValue(IntegerValue)> GetSuperAdditiveRoundingFunction(
IntegerValue rhs_remainder, IntegerValue divisor, IntegerValue t,
IntegerValue max_scaling) {
DCHECK_GE(max_scaling, 1);
DCHECK_GE(t, 1);
// Adjust after the multiplication by t.
rhs_remainder *= t;
DCHECK_LT(rhs_remainder, divisor);
// Make sure we don't have an integer overflow below. Note that we assume that
// divisor and the maximum coeff magnitude are not too different (maybe a
// factor 1000 at most) so that the final result will never overflow.
max_scaling =
std::min(max_scaling, std::numeric_limits<int64_t>::max() / divisor);
const IntegerValue size = divisor - rhs_remainder;
if (max_scaling == 1 || size == 1) {
// TODO(user): Use everywhere a two step computation to avoid overflow?
// First divide by divisor, then multiply by t. For now, we limit t so that
// we never have an overflow instead.
return [t, divisor](IntegerValue coeff) {
return FloorRatio(t * coeff, divisor);
};
} else if (size <= max_scaling) {
return [size, rhs_remainder, t, divisor](IntegerValue coeff) {
const IntegerValue t_coeff = t * coeff;
const IntegerValue ratio = FloorRatio(t_coeff, divisor);
const IntegerValue remainder = PositiveRemainder(t_coeff, divisor);
const IntegerValue diff = remainder - rhs_remainder;
return size * ratio + std::max(IntegerValue(0), diff);
};
} else if (max_scaling.value() * rhs_remainder.value() < divisor) {
// Because of our max_t limitation, the rhs_remainder might stay small.
//
// If it is "too small" we cannot use the code below because it will not be
// valid. So we just divide divisor into max_scaling bucket. The
// rhs_remainder will be in the bucket 0.
//
// Note(user): This seems the same as just increasing t, modulo integer
// overflows. Maybe we should just always do the computation like this so
// that we can use larger t even if coeff is close to kint64max.
return [t, divisor, max_scaling](IntegerValue coeff) {
const IntegerValue t_coeff = t * coeff;
const IntegerValue ratio = FloorRatio(t_coeff, divisor);
const IntegerValue remainder = PositiveRemainder(t_coeff, divisor);
const IntegerValue bucket = FloorRatio(remainder * max_scaling, divisor);
return max_scaling * ratio + bucket;
};
} else {
// We divide (size = divisor - rhs_remainder) into (max_scaling - 1) buckets
// and increase the function by 1 / max_scaling for each of them.
//
// Note that for different values of max_scaling, we get a family of
// functions that do not dominate each others. So potentially, a max scaling
// as low as 2 could lead to the better cut (this is exactly the Letchford &
// Lodi function).
//
// Another interesting fact, is that if we want to compute the maximum alpha
// for a constraint with 2 terms like:
// divisor * Y + (ratio * divisor + remainder) * X
// <= rhs_ratio * divisor + rhs_remainder
// so that we have the cut:
// Y + (ratio + alpha) * X <= rhs_ratio
// This is the same as computing the maximum alpha such that for all integer
// X > 0 we have CeilRatio(alpha * divisor * X, divisor)
// <= CeilRatio(remainder * X - rhs_remainder, divisor).
// We can prove that this alpha is of the form (n - 1) / n, and it will
// be reached by such function for a max_scaling of n.
//
// TODO(user): This function is not always maximal when
// size % (max_scaling - 1) == 0. Improve?
return [size, rhs_remainder, t, divisor, max_scaling](IntegerValue coeff) {
const IntegerValue t_coeff = t * coeff;
const IntegerValue ratio = FloorRatio(t_coeff, divisor);
const IntegerValue remainder = PositiveRemainder(t_coeff, divisor);
const IntegerValue diff = remainder - rhs_remainder;
const IntegerValue bucket =
diff > 0 ? CeilRatio(diff * (max_scaling - 1), size)
: IntegerValue(0);
return max_scaling * ratio + bucket;
};
}
}
// TODO(user): This has been optimized a bit, but we can probably do even better
// as it still takes around 25% percent of the run time when all the cuts are on
// for the opm*mps.gz problems and others.
void IntegerRoundingCutHelper::ComputeCut(
RoundingOptions options, const std::vector<double>& lp_values,
const std::vector<IntegerValue>& lower_bounds,
const std::vector<IntegerValue>& upper_bounds,
ImpliedBoundsProcessor* ib_processor, LinearConstraint* cut) {
const int size = lp_values.size();
if (size == 0) return;
CHECK_EQ(lower_bounds.size(), size);
CHECK_EQ(upper_bounds.size(), size);
CHECK_EQ(cut->vars.size(), size);
CHECK_EQ(cut->coeffs.size(), size);
CHECK_EQ(cut->lb, kMinIntegerValue);
// To optimize the computation of the best divisor below, we only need to
// look at the indices with a shifted lp value that is not close to zero.
//
// TODO(user): sort by decreasing lp_values so that our early abort test in
// the critical loop below has more chance of returning early? I tried but it
// didn't seems to change much though.
relevant_indices_.clear();
relevant_lp_values_.clear();
relevant_coeffs_.clear();
relevant_bound_diffs_.clear();
divisors_.clear();
adjusted_coeffs_.clear();
// Compute the maximum magnitude for non-fixed variables.
IntegerValue max_magnitude(0);
for (int i = 0; i < size; ++i) {
if (lower_bounds[i] == upper_bounds[i]) continue;
const IntegerValue magnitude = IntTypeAbs(cut->coeffs[i]);
max_magnitude = std::max(max_magnitude, magnitude);
}
// Shift each variable using its lower/upper bound so that no variable can
// change sign. We eventually do a change of variable to its negation so
// that all variable are non-negative.
bool overflow = false;
change_sign_at_postprocessing_.assign(size, false);
for (int i = 0; i < size; ++i) {
if (cut->coeffs[i] == 0) continue;
const IntegerValue magnitude = IntTypeAbs(cut->coeffs[i]);
// We might change them below.
IntegerValue lb = lower_bounds[i];
double lp_value = lp_values[i];
const IntegerValue ub = upper_bounds[i];
const IntegerValue bound_diff =
IntegerValue(CapSub(ub.value(), lb.value()));
// Note that since we use ToDouble() this code works fine with lb/ub at
// min/max integer value.
//
// TODO(user): Experiments with different heuristics. Other solver also
// seems to try a bunch of possibilities in a "postprocess" phase once
// the divisor is chosen. Try that.
{
// when the magnitude of the entry become smaller and smaller we bias
// towards a positive coefficient. This is because after rounding this
// will likely become zero instead of -divisor and we need the lp value
// to be really close to its bound to compensate.
const double lb_dist = std::abs(lp_value - ToDouble(lb));
const double ub_dist = std::abs(lp_value - ToDouble(ub));
const double bias =
std::max(1.0, 0.1 * ToDouble(max_magnitude) / ToDouble(magnitude));
if ((bias * lb_dist > ub_dist && cut->coeffs[i] < 0) ||
(lb_dist > bias * ub_dist && cut->coeffs[i] > 0)) {
change_sign_at_postprocessing_[i] = true;
cut->coeffs[i] = -cut->coeffs[i];
lp_value = -lp_value;
lb = -ub;
}
}
// Always shift to lb.
// coeff * X = coeff * (X - shift) + coeff * shift.
lp_value -= ToDouble(lb);
if (!AddProductTo(-cut->coeffs[i], lb, &cut->ub)) {
overflow = true;
break;
}
// Deal with fixed variable, no need to shift back in this case, we can
// just remove the term.
if (bound_diff == 0) {
cut->coeffs[i] = IntegerValue(0);
lp_value = 0.0;
}
if (std::abs(lp_value) > 1e-2) {
relevant_coeffs_.push_back(cut->coeffs[i]);
relevant_indices_.push_back(i);
relevant_lp_values_.push_back(lp_value);
relevant_bound_diffs_.push_back(bound_diff);
divisors_.push_back(magnitude);
}
}
// TODO(user): Maybe this shouldn't be called on such constraint.
if (relevant_coeffs_.empty()) {
VLOG(2) << "Issue, nothing to cut.";
*cut = LinearConstraint(IntegerValue(0), IntegerValue(0));
return;
}
CHECK_NE(max_magnitude, 0);
// Our heuristic will try to generate a few different cuts, and we will keep
// the most violated one scaled by the l2 norm of the relevant position.
//
// TODO(user): Experiment for the best value of this initial violation
// threshold. Note also that we use the l2 norm on the restricted position
// here. Maybe we should change that? On that note, the L2 norm usage seems a
// bit weird to me since it grows with the number of term in the cut. And
// often, we already have a good cut, and we make it stronger by adding extra
// terms that do not change its activity.
//
// The discussion above only concern the best_scaled_violation initial value.
// The remainder_threshold allows to not consider cuts for which the final
// efficacity is clearly lower than 1e-3 (it is a bound, so we could generate
// cuts with a lower efficacity than this).
double best_scaled_violation = 0.01;
const IntegerValue remainder_threshold(max_magnitude / 1000);
// The cut->ub might have grown quite a bit with the bound substitution, so
// we need to include it too since we will apply the rounding function on it.
max_magnitude = std::max(max_magnitude, IntTypeAbs(cut->ub));
// Make sure that when we multiply the rhs or the coefficient by a factor t,
// we do not have an integer overflow. Actually, we need a bit more room
// because we might round down a value to the next multiple of
// max_magnitude.
const IntegerValue threshold = kMaxIntegerValue / 2;
if (overflow || max_magnitude >= threshold) {
VLOG(2) << "Issue, overflow.";
*cut = LinearConstraint(IntegerValue(0), IntegerValue(0));
return;
}
const IntegerValue max_t = threshold / max_magnitude;
// There is no point trying twice the same divisor or a divisor that is too
// small. Note that we use a higher threshold than the remainder_threshold
// because we can boost the remainder thanks to our adjusting heuristic below
// and also because this allows to have cuts with a small range of
// coefficients.
//
// TODO(user): Note that the std::sort() is visible in some cpu profile.
{
int new_size = 0;
const IntegerValue divisor_threshold = max_magnitude / 10;
for (int i = 0; i < divisors_.size(); ++i) {
if (divisors_[i] <= divisor_threshold) continue;
divisors_[new_size++] = divisors_[i];
}
divisors_.resize(new_size);
}
gtl::STLSortAndRemoveDuplicates(&divisors_, std::greater<IntegerValue>());
// TODO(user): Avoid quadratic algorithm? Note that we are quadratic in
// relevant_indices not the full cut->coeffs.size(), but this is still too
// much on some problems.
IntegerValue best_divisor(0);
for (const IntegerValue divisor : divisors_) {
// Skip if we don't have the potential to generate a good enough cut.
const IntegerValue initial_rhs_remainder =
cut->ub - FloorRatio(cut->ub, divisor) * divisor;
if (initial_rhs_remainder <= remainder_threshold) continue;
IntegerValue temp_ub = cut->ub;
adjusted_coeffs_.clear();
// We will adjust coefficient that are just under an exact multiple of
// divisor to an exact multiple. This is meant to get rid of small errors
// that appears due to rounding error in our exact computation of the
// initial constraint given to this class.
//
// Each adjustement will cause the initial_rhs_remainder to increase, and we
// do not want to increase it above divisor. Our threshold below guarantees
// this. Note that the higher the rhs_remainder becomes, the more the
// function f() has a chance to reduce the violation, so it is not always a
// good idea to use all the slack we have between initial_rhs_remainder and
// divisor.
//
// TODO(user): If possible, it might be better to complement these
// variables. Even if the adjusted lp_values end up larger, if we loose less
// when taking f(), then we will have a better violation.
const IntegerValue adjust_threshold =
(divisor - initial_rhs_remainder - 1) / IntegerValue(size);
if (adjust_threshold > 0) {
// Even before we finish the adjust, we can have a lower bound on the
// activily loss using this divisor, and so we can abort early. This is
// similar to what is done below in the function.
bool early_abort = false;
double loss_lb = 0.0;
const double threshold = ToDouble(initial_rhs_remainder);
for (int i = 0; i < relevant_coeffs_.size(); ++i) {
// Compute the difference of coeff with the next multiple of divisor.
const IntegerValue coeff = relevant_coeffs_[i];
const IntegerValue remainder =
CeilRatio(coeff, divisor) * divisor - coeff;
if (divisor - remainder <= initial_rhs_remainder) {
// We do not know exactly f() yet, but it will always round to the
// floor of the division by divisor in this case.
loss_lb += ToDouble(divisor - remainder) * relevant_lp_values_[i];
if (loss_lb >= threshold) {
early_abort = true;
break;
}
}
// Adjust coeff of the form k * divisor - epsilon.
const IntegerValue diff = relevant_bound_diffs_[i];
if (remainder > 0 && remainder <= adjust_threshold &&
CapProd(diff.value(), remainder.value()) <= adjust_threshold) {
temp_ub += remainder * diff;
adjusted_coeffs_.push_back({i, coeff + remainder});
}
}
if (early_abort) continue;
}
// Create the super-additive function f().
const IntegerValue rhs_remainder =
temp_ub - FloorRatio(temp_ub, divisor) * divisor;
if (rhs_remainder == 0) continue;
const auto f = GetSuperAdditiveRoundingFunction(
rhs_remainder, divisor, GetFactorT(rhs_remainder, divisor, max_t),
options.max_scaling);
// As we round coefficients, we will compute the loss compared to the
// current scaled constraint activity. As soon as this loss crosses the
// slack, then we known that there is no violation and we can abort early.
//
// TODO(user): modulo the scaling, we could compute the exact threshold
// using our current best cut. Note that we also have to account the change
// in slack due to the adjust code above.
const double scaling = ToDouble(f(divisor)) / ToDouble(divisor);
const double threshold = scaling * ToDouble(rhs_remainder);
double loss = 0.0;
// Apply f() to the cut and compute the cut violation. Note that it is
// okay to just look at the relevant indices since the other have a lp
// value which is almost zero. Doing it like this is faster, and even if
// the max_magnitude might be off it should still be relevant enough.
double violation = -ToDouble(f(temp_ub));
double l2_norm = 0.0;
bool early_abort = false;
int adjusted_coeffs_index = 0;
for (int i = 0; i < relevant_coeffs_.size(); ++i) {
IntegerValue coeff = relevant_coeffs_[i];
// Adjust coeff according to our previous computation if needed.
if (adjusted_coeffs_index < adjusted_coeffs_.size() &&
adjusted_coeffs_[adjusted_coeffs_index].first == i) {
coeff = adjusted_coeffs_[adjusted_coeffs_index].second;
adjusted_coeffs_index++;
}
if (coeff == 0) continue;
const IntegerValue new_coeff = f(coeff);
const double new_coeff_double = ToDouble(new_coeff);
const double lp_value = relevant_lp_values_[i];
l2_norm += new_coeff_double * new_coeff_double;
violation += new_coeff_double * lp_value;
loss += (scaling * ToDouble(coeff) - new_coeff_double) * lp_value;
if (loss >= threshold) {
early_abort = true;
break;
}
}
if (early_abort) continue;
// Here we scale by the L2 norm over the "relevant" positions. This seems
// to work slighly better in practice.
violation /= sqrt(l2_norm);
if (violation > best_scaled_violation) {