forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cuts.cc
2395 lines (2182 loc) · 92 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-2022 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 <cstdlib>
#include <functional>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/btree_set.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "ortools/base/logging.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/strong_vector.h"
#include "ortools/sat/clause.h"
#include "ortools/sat/implied_bounds.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/linear_constraint.h"
#include "ortools/sat/linear_constraint_manager.h"
#include "ortools/sat/model.h"
#include "ortools/sat/sat_base.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
#include "ortools/util/strong_integers.h"
#include "ortools/util/time_limit.h"
namespace operations_research {
namespace sat {
std::string CutTerm::DebugString() const {
return absl::StrCat("coeff=", coeff.value(), " lp=", lp_value,
" range=", bound_diff.value());
}
bool CutTerm::Complement(IntegerValue* rhs) {
// We replace coeff * X by coeff * (X - bound_diff + bound_diff)
// which gives -coeff * complement(X) + coeff * bound_diff;
if (!AddProductTo(-coeff, bound_diff, rhs)) return false;
// We keep the same expression variable.
for (int i = 0; i < 2; ++i) {
expr_coeffs[i] = -expr_coeffs[i];
}
expr_offset = bound_diff - expr_offset;
// Note that this is not involutive because of floating point error. Fix?
lp_value = ToDouble(bound_diff) - lp_value;
coeff = -coeff;
return true;
}
// To try to minimize the risk of overflow, we switch to the bound closer
// to the lp_value. Since most of our base constraint for cut are tight,
// hopefully this is not too bad.
bool CutData::AppendOneTerm(IntegerVariable var, IntegerValue coeff,
double lp_value, IntegerValue lb, IntegerValue ub) {
if (coeff == 0) return true;
const IntegerValue bound_diff = ub - lb;
// Complement the variable so that it is always closer to its lb.
bool complement = false;
const double lb_dist = std::abs(lp_value - ToDouble(lb));
const double ub_dist = std::abs(lp_value - ToDouble(ub));
if (ub_dist < lb_dist) {
complement = true;
}
// See formula below, the constant term is either coeff * lb or coeff * ub.
if (!AddProductTo(-coeff, complement ? ub : lb, &rhs)) {
return false;
}
// Deal with fixed variable, no need to shift back in this case, we can
// just remove the term.
if (bound_diff == 0) return true;
CutTerm entry;
entry.expr_vars[0] = var;
entry.expr_coeffs[1] = 0;
entry.bound_diff = bound_diff;
if (complement) {
// X = -(UB - X) + UB
entry.expr_coeffs[0] = -IntegerValue(1);
entry.expr_offset = ub;
entry.coeff = -coeff;
entry.lp_value = ToDouble(ub) - lp_value;
} else {
// C = (X - LB) + LB
entry.expr_coeffs[0] = IntegerValue(1);
entry.expr_offset = -lb;
entry.coeff = coeff;
entry.lp_value = lp_value - ToDouble(lb);
}
terms.push_back(entry);
return true;
}
bool CutData::FillFromLinearConstraint(
const LinearConstraint& base_ct,
const absl::StrongVector<IntegerVariable, double>& lp_values,
IntegerTrail* integer_trail) {
rhs = base_ct.ub;
terms.clear();
const int num_terms = base_ct.vars.size();
for (int i = 0; i < num_terms; ++i) {
const IntegerVariable var = base_ct.vars[i];
if (!AppendOneTerm(var, base_ct.coeffs[i], lp_values[base_ct.vars[i]],
integer_trail->LevelZeroLowerBound(var),
integer_trail->LevelZeroUpperBound(var))) {
return false;
}
}
return true;
}
bool CutData::FillFromParallelVectors(
const LinearConstraint& base_ct, const std::vector<double>& lp_values,
const std::vector<IntegerValue>& lower_bounds,
const std::vector<IntegerValue>& upper_bounds) {
rhs = base_ct.ub;
terms.clear();
const int size = lp_values.size();
if (size == 0) return true;
CHECK_EQ(lower_bounds.size(), size);
CHECK_EQ(upper_bounds.size(), size);
CHECK_EQ(base_ct.vars.size(), size);
CHECK_EQ(base_ct.coeffs.size(), size);
CHECK_EQ(base_ct.lb, kMinIntegerValue);
for (int i = 0; i < size; ++i) {
if (!AppendOneTerm(base_ct.vars[i], base_ct.coeffs[i], lp_values[i],
lower_bounds[i], upper_bounds[i])) {
return false;
}
}
return true;
}
void CutData::Canonicalize() {
num_relevant_entries = 0;
max_magnitude = IntTypeAbs(rhs);
for (int i = 0; i < terms.size(); ++i) {
CutTerm& entry = terms[i];
max_magnitude = std::max(max_magnitude, IntTypeAbs(entry.coeff));
if (entry.HasRelevantLpValue()) {
std::swap(terms[num_relevant_entries], entry);
++num_relevant_entries;
}
}
// Sort by larger lp_value first.
std::sort(terms.begin(), terms.begin() + num_relevant_entries,
[](const CutTerm& a, const CutTerm& b) {
return a.lp_value > b.lp_value;
});
}
void CutDataBuilder::ClearIndices() {
num_merges_ = 0;
constraint_is_indexed_ = false;
direct_index_.clear();
complemented_index_.clear();
}
void CutDataBuilder::RegisterAllBooleansTerms(const CutData& cut) {
constraint_is_indexed_ = true;
const int size = cut.terms.size();
for (int i = 0; i < size; ++i) {
const CutTerm& term = cut.terms[i];
if (term.bound_diff != 1) continue;
if (!term.IsSimple()) continue;
if (term.expr_coeffs[0] > 0) {
direct_index_[term.expr_vars[0]] = i;
} else {
complemented_index_[term.expr_vars[0]] = i;
}
}
}
void CutDataBuilder::AddOrMergeTerm(const CutTerm& term, IntegerValue t,
CutData* cut) {
if (!constraint_is_indexed_) {
RegisterAllBooleansTerms(*cut);
}
DCHECK(term.IsSimple());
const IntegerVariable var = term.expr_vars[0];
const int new_index = cut->terms.size();
const auto [it, inserted] =
term.expr_coeffs[0] > 0 ? direct_index_.insert({var, new_index})
: complemented_index_.insert({var, new_index});
const int entry_index = it->second;
if (inserted) {
cut->terms.push_back(term);
} else {
// We can only merge the term if term.coeff + old_coeff do not overflow and
// if t * new_coeff do not overflow.
//
// If we cannot merge the term, we will keep them separate. The produced cut
// will be less strong, but can still be used.
const int64_t new_coeff =
CapAdd(cut->terms[entry_index].coeff.value(), term.coeff.value());
const int64_t overflow_check = CapProd(t.value(), new_coeff);
if (AtMinOrMaxInt64(new_coeff) || AtMinOrMaxInt64(overflow_check)) {
// If we cannot merge the term, we keep them separate.
cut->terms.push_back(term);
} else {
++num_merges_;
cut->terms[entry_index].coeff = IntegerValue(new_coeff);
}
}
}
bool CutDataBuilder::ConvertToLinearConstraint(const CutData& cut,
LinearConstraint* output) {
tmp_map_.clear();
IntegerValue new_rhs = cut.rhs;
for (const CutTerm& term : cut.terms) {
for (int i = 0; i < 2; ++i) {
if (term.expr_coeffs[i] == 0) continue;
if (!AddProductTo(term.coeff, term.expr_coeffs[i],
&tmp_map_[term.expr_vars[i]])) {
return false;
}
}
if (!AddProductTo(-term.coeff, term.expr_offset, &new_rhs)) {
return false;
}
}
output->ClearTerms();
output->lb = kMinIntegerValue;
output->ub = new_rhs;
for (const auto [var, coeff] : tmp_map_) {
if (coeff == 0) continue;
output->vars.push_back(var);
output->coeffs.push_back(coeff);
}
DivideByGCD(output);
return true;
}
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;
IntegerValue CapProdI(IntegerValue a, IntegerValue b) {
return IntegerValue(CapProd(a.value(), b.value()));
}
IntegerValue CapSubI(IntegerValue a, IntegerValue b) {
return IntegerValue(CapSub(a.value(), b.value()));
}
IntegerValue CapAddI(IntegerValue a, IntegerValue b) {
return IntegerValue(CapAdd(a.value(), b.value()));
}
bool ProdOverflow(IntegerValue t, IntegerValue value) {
return AtMinOrMaxInt64(CapProd(t.value(), value.value()));
}
} // namespace
// 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_magnitude) {
// Make sure that when we multiply the rhs or the coefficient by a factor t,
// we do not have an integer overflow. Note that the rhs should be counted
// in max_magnitude since we will apply f() on it.
IntegerValue max_t(std::numeric_limits<int64_t>::max());
if (max_magnitude != 0) {
max_t = max_t / max_magnitude;
}
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;
};
}
}
IntegerRoundingCutHelper::~IntegerRoundingCutHelper() {
if (!VLOG_IS_ON(1)) return;
if (shared_stats_ == nullptr) return;
std::vector<std::pair<std::string, int64_t>> stats;
stats.push_back({"rounding_cut/num_initial_ibs_", total_num_initial_ibs_});
stats.push_back(
{"rounding_cut/num_initial_merges_", total_num_initial_merges_});
stats.push_back({"rounding_cut/num_pos_lifts", total_num_pos_lifts_});
stats.push_back({"rounding_cut/num_neg_lifts", total_num_neg_lifts_});
stats.push_back(
{"rounding_cut/num_post_complements", total_num_post_complements_});
stats.push_back({"rounding_cut/num_overflows", total_num_overflow_abort_});
stats.push_back({"rounding_cut/num_adjusts", total_num_coeff_adjust_});
stats.push_back({"rounding_cut/num_merges", total_num_merges_});
stats.push_back({"rounding_cut/num_bumps", total_num_bumps_});
stats.push_back(
{"rounding_cut/num_final_complements", total_num_final_complements_});
stats.push_back({"rounding_cut/num_dominating_f", total_num_dominating_f_});
shared_stats_->AddStats(stats);
}
double IntegerRoundingCutHelper::GetScaledViolation(
IntegerValue divisor, IntegerValue max_scaling,
IntegerValue remainder_threshold, const CutData& cut) {
IntegerValue rhs = cut.rhs;
IntegerValue max_magnitude = cut.max_magnitude;
const IntegerValue initial_rhs_remainder = PositiveRemainder(rhs, divisor);
if (initial_rhs_remainder < remainder_threshold) return 0.0;
// 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): We could see if for a fixed function f, the increase is
// interesting?
// before: f(rhs) - f(coeff) * lp_value
// after: f(rhs + increase * bound_diff) - f(coeff + increase) * lp_value.
adjusted_coeffs_.clear();
const IntegerValue adjust_threshold =
(divisor - initial_rhs_remainder - 1) /
IntegerValue(std::max(1000, cut.num_relevant_entries));
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.
double max_violation = ToDouble(initial_rhs_remainder);
for (int i = 0; i < cut.num_relevant_entries; ++i) {
const CutTerm& entry = cut.terms[i];
const IntegerValue remainder = PositiveRemainder(entry.coeff, divisor);
if (remainder == 0) continue;
if (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.
max_violation -= ToDouble(remainder) * entry.lp_value;
if (max_violation <= 1e-3) return 0.0;
continue;
}
// Adjust coeff of the form k * divisor - epsilon.
const IntegerValue adjust = divisor - remainder;
const IntegerValue prod = CapProdI(adjust, entry.bound_diff);
if (prod <= adjust_threshold) {
rhs += prod;
const IntegerValue new_coeff = entry.coeff + adjust;
adjusted_coeffs_.push_back({i, new_coeff});
max_magnitude = std::max(max_magnitude, IntTypeAbs(new_coeff));
}
}
}
max_magnitude = std::max(max_magnitude, IntTypeAbs(rhs));
const IntegerValue rhs_remainder = PositiveRemainder(rhs, divisor);
const IntegerValue t = GetFactorT(rhs_remainder, divisor, max_magnitude);
const auto f =
GetSuperAdditiveRoundingFunction(rhs_remainder, divisor, t, 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);
double max_violation = scaling * ToDouble(rhs_remainder);
// 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(rhs));
double l2_norm = 0.0;
int adjusted_coeffs_index = 0;
for (int i = 0; i < cut.num_relevant_entries; ++i) {
const CutTerm& entry = cut.terms[i];
// Adjust coeff according to our previous computation if needed.
IntegerValue coeff = entry.coeff;
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 = entry.lp_value;
// TODO(user): Shall we compute the norm after slack are substituted back?
// it might be widely different. Another reason why this might not be
// the best measure.
l2_norm += new_coeff_double * new_coeff_double;
violation += new_coeff_double * lp_value;
max_violation -= (scaling * ToDouble(coeff) - new_coeff_double) * lp_value;
if (max_violation <= 1e-3) return 0.0;
}
if (l2_norm == 0.0) return 0.0;
// Here we scale by the L2 norm over the "relevant" positions. This seems
// to work slighly better in practice.
//
// Note(user): The non-relevant position have an LP value of zero. If their
// coefficient is positive, it seems good not to take it into account in the
// norm since the larger this coeff is, the stronger the cut. If the coeff
// is negative though, a large coeff means a small increase from zero of the
// lp value will make the cut satisfied, so we might want to look at them.
return violation / sqrt(l2_norm);
}
bool IntegerRoundingCutHelper::HasComplementedImpliedBound(
const CutTerm& entry, ImpliedBoundsProcessor* ib_processor) {
if (ib_processor == nullptr) return false;
if (!entry.IsSimple()) return false;
if (entry.bound_diff == 1) return false;
const ImpliedBoundsProcessor::BestImpliedBoundInfo info =
ib_processor->GetCachedImpliedBoundInfo(
entry.expr_coeffs[0] > 0 ? NegationOf(entry.expr_vars[0])
: entry.expr_vars[0]);
return info.bool_var != kNoIntegerVariable;
}
// TODO(user): This is slow, 50% of run time on a2c1s1.pb.gz. Optimize!
bool IntegerRoundingCutHelper::ComputeCut(
RoundingOptions options, const CutData& base_ct,
ImpliedBoundsProcessor* ib_processor) {
// Try IB before heuristic?
// This should be better except it can mess up the norm and the divisors.
best_cut_ = base_ct;
if (options.use_ib_before_heuristic && ib_processor != nullptr) {
cut_builder_.ClearIndices();
const int old_size = static_cast<int>(best_cut_.terms.size());
bool abort = true;
for (int i = 0; i < old_size; ++i) {
if (best_cut_.terms[i].bound_diff <= 1) continue;
if (!best_cut_.terms[i].HasRelevantLpValue()) continue;
if (options.prefer_positive_ib && best_cut_.terms[i].coeff < 0) {
// We complement the term before trying the implied bound.
if (best_cut_.terms[i].Complement(&best_cut_.rhs)) {
if (ib_processor->TryToExpandWithLowerImpliedbound(
IntegerValue(1), i,
/*complement=*/true, &best_cut_, &cut_builder_)) {
++total_num_initial_ibs_;
abort = false;
continue;
}
best_cut_.terms[i].Complement(&best_cut_.rhs);
}
}
if (ib_processor->TryToExpandWithLowerImpliedbound(
IntegerValue(1), i,
/*complement=*/true, &best_cut_, &cut_builder_)) {
abort = false;
++total_num_initial_ibs_;
}
}
total_num_initial_merges_ += cut_builder_.NumMergesSinceLastClear();
// TODO(user): We assume that this is called with and without the option
// use_ib_before_heuristic, so that we can abort if no IB has been applied
// since then we will redo the computation. This is not really clean.
if (abort) return false;
}
// 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).
//
// TODO(user): If the rhs is small and close to zero, we might want to
// consider different way of complementing the variables.
best_cut_.Canonicalize();
const IntegerValue remainder_threshold(
std::max(IntegerValue(1), best_cut_.max_magnitude / 1000));
if (best_cut_.rhs >= 0 && best_cut_.rhs < remainder_threshold) {
return false;
}
// 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.
divisors_.clear();
for (const CutTerm& entry : best_cut_.terms) {
// Note that because of the slacks, initial coeff are here too.
const IntegerValue magnitude = IntTypeAbs(entry.coeff);
if (magnitude <= remainder_threshold) continue;
divisors_.push_back(magnitude);
}
if (divisors_.empty()) return false;
gtl::STLSortAndRemoveDuplicates(&divisors_, std::greater<IntegerValue>());
// Note that most of the time is spend here since we call this function on
// many linear equation, and just a few of them have a good enough scaled
// violation. We can spend more time afterwards to tune the cut.
//
// TODO(user): Avoid quadratic algorithm? Note that we are quadratic in
// relevant positions not the full cut size, but this is still too much on
// some problems.
IntegerValue best_divisor(0);
double best_scaled_violation = 1e-3;
for (const IntegerValue divisor : divisors_) {
// Note that the function will abort right away if PositiveRemainder() is
// not good enough, so it is quick for bad divisor.
const double violation = GetScaledViolation(divisor, options.max_scaling,
remainder_threshold, best_cut_);
if (violation > best_scaled_violation) {
best_scaled_violation = violation;
best_adjusted_coeffs_ = adjusted_coeffs_;
best_divisor = divisor;
}
}
if (best_divisor == 0) return false;
// Try best_divisor divided by small number.
for (int div = 2; div < 9; ++div) {
const IntegerValue divisor = best_divisor / IntegerValue(div);
if (divisor <= 1) continue;
const double violation = GetScaledViolation(divisor, options.max_scaling,
remainder_threshold, best_cut_);
if (violation > best_scaled_violation) {
best_scaled_violation = violation;
best_adjusted_coeffs_ = adjusted_coeffs_;
best_divisor = divisor;
}
}
// Re try complementation on the transformed cut.
for (CutTerm& entry : best_cut_.terms) {
if (!entry.HasRelevantLpValue()) break;
if (entry.coeff % best_divisor == 0) continue;
// Temporary try to complement this variable.
if (!entry.Complement(&best_cut_.rhs)) continue;
const double violation = GetScaledViolation(
best_divisor, options.max_scaling, remainder_threshold, best_cut_);
if (violation > best_scaled_violation) {
// keep the change.
++total_num_post_complements_;
best_scaled_violation = violation;
best_adjusted_coeffs_ = adjusted_coeffs_;
} else {
// Restore.
entry.Complement(&best_cut_.rhs);
}
}
// Adjust coefficients as computed by the best GetScaledViolation().
for (const auto [index, new_coeff] : best_adjusted_coeffs_) {
++total_num_coeff_adjust_;
CutTerm& entry = best_cut_.terms[index];
const IntegerValue remainder = new_coeff - entry.coeff;
CHECK_GT(remainder, 0);
entry.coeff = new_coeff;
best_cut_.rhs += remainder * entry.bound_diff;
best_cut_.max_magnitude =
std::max(best_cut_.max_magnitude, IntTypeAbs(new_coeff));
}
best_cut_.max_magnitude =
std::max(best_cut_.max_magnitude, IntTypeAbs(best_cut_.rhs));
// Create the base super-additive function f().
const IntegerValue rhs_remainder =
PositiveRemainder(best_cut_.rhs, best_divisor);
IntegerValue factor_t =
GetFactorT(rhs_remainder, best_divisor, best_cut_.max_magnitude);
auto f = GetSuperAdditiveRoundingFunction(rhs_remainder, best_divisor,
factor_t, options.max_scaling);
// Look amongst all our possible function f() for one that dominate greedily
// our current best one. Note that we prefer lower scaling factor since that
// result in a cut with lower coefficients.
//
// We only look at relevant position and ignore the other. Not sure this is
// the best approach.
remainders_.clear();
for (const CutTerm& entry : best_cut_.terms) {
if (!entry.HasRelevantLpValue()) break;
const IntegerValue coeff = entry.coeff;
const IntegerValue r = PositiveRemainder(coeff, best_divisor);
if (r > rhs_remainder) remainders_.push_back(r);
}
gtl::STLSortAndRemoveDuplicates(&remainders_);
if (remainders_.size() <= 100) {
best_rs_.clear();
for (const IntegerValue r : remainders_) {
best_rs_.push_back(f(r));
}
IntegerValue best_d = f(best_divisor);
// Note that the complexity seems high 100 * 2 * options.max_scaling, but
// this only run on cuts that are already efficient and the inner loop tend
// to abort quickly. I didn't see this code in the cpu profile so far.
for (const IntegerValue t :
{IntegerValue(1),
GetFactorT(rhs_remainder, best_divisor, best_cut_.max_magnitude)}) {
for (IntegerValue s(2); s <= options.max_scaling; ++s) {
const auto g =
GetSuperAdditiveRoundingFunction(rhs_remainder, best_divisor, t, s);
int num_strictly_better = 0;
rs_.clear();
const IntegerValue d = g(best_divisor);
for (int i = 0; i < best_rs_.size(); ++i) {
const IntegerValue temp = g(remainders_[i]);
if (temp * best_d < best_rs_[i] * d) break;
if (temp * best_d > best_rs_[i] * d) num_strictly_better++;
rs_.push_back(temp);
}
if (rs_.size() == best_rs_.size() && num_strictly_better > 0) {
++total_num_dominating_f_;
f = g;
factor_t = t;
best_rs_ = rs_;
best_d = d;
}
}
}
}
// Use implied bounds to "lift" Booleans into the cut.
// This should lead to stronger cuts even if the norms migth be worse.
num_ib_used_ = 0;
if (ib_processor != nullptr) {
cut_builder_.ClearIndices();
const int old_size = best_cut_.terms.size();
for (int i = 0; i < old_size; ++i) {
CutTerm& term = best_cut_.terms[i];
// We only want to expand non-Boolean and non-slack term!
if (term.bound_diff <= 1) continue;
if (!term.IsSimple()) continue;
if (ib_processor->TryToExpandWithLowerImpliedbound(
factor_t, i, /*complement=*/false, &best_cut_, &cut_builder_)) {
++num_ib_used_;
++total_num_pos_lifts_;
continue;
}
// Use the implied bound on (-X) if it is beneficial to do so.
// Like complementing, this is not always good.
//
// We have comp(X) = diff - X = diff * B + S
// X = diff * (1 - B) - S.
// So if we applies f, we will get:
// f(coeff * diff) * (1 - B) + f(-coeff) * S
// and substituing S = diff * (1 - B) - X, we get:
// -f(-coeff) * X + [f(coeff * diff) + f(-coeff) * diff] (1 - B).
//
// TODO(user): Note that while the violation might be higher, if the slack
// becomes large this will result in a less powerfull cut. Shall we do
// that? It is a bit the same problematic with complementing.
//
// TODO(user): If the slack is close to zero, then this transformation
// will always increase the violation. So we could potentially do it in
// Before our divisor selection heuristic. But the norm of the final cut
// will increase too.
if (!HasComplementedImpliedBound(term, ib_processor)) continue;
const ImpliedBoundsProcessor::BestImpliedBoundInfo info =
ib_processor->GetCachedImpliedBoundInfo(
term.expr_coeffs[0] > 0 ? NegationOf(term.expr_vars[0])
: term.expr_vars[0]);
const IntegerValue lb = -term.expr_offset;
const IntegerValue bound_diff = info.implied_bound - lb;
// We do not want overflow when computing f().
if (ProdOverflow(factor_t, CapProdI(term.coeff, bound_diff))) {
continue;
}
// We only consider IB that span the full range here.
if (bound_diff != term.bound_diff) continue;
// Note that -f(-coeff) >= f(coeff) but coeff_b <= 0.
const IntegerValue coeff_b =
f(term.coeff * bound_diff) + f(-term.coeff) * bound_diff;
CHECK_LE(coeff_b, 0);
const double lp1 = ToDouble(f(term.coeff)) * term.lp_value;
const double lp2 = -ToDouble(f(-term.coeff)) * term.lp_value +
ToDouble(coeff_b) * (1 - info.bool_lp_value);
if (lp2 > lp1 + 1e-2) {
// Create the Boolean term for (1 - B) in X = diff * (1 - B) - S
// We reverse the is_positive meaning here since we have (1 - B).
CutTerm bool_term;
bool_term.coeff = bound_diff * term.coeff;
bool_term.expr_vars[0] = info.bool_var;
bool_term.expr_coeffs[1] = 0;
bool_term.bound_diff = IntegerValue(1);
bool_term.lp_value = 1.0 - info.bool_lp_value;
if (!info.is_positive) {
bool_term.expr_coeffs[0] = IntegerValue(1);
bool_term.expr_offset = IntegerValue(0);
} else {
bool_term.expr_coeffs[0] = IntegerValue(-1);
bool_term.expr_offset = IntegerValue(1);
}
// Create the slack term in X = diff * (1 - B) - S
CutTerm slack_term;
slack_term.coeff = -term.coeff;
slack_term.expr_vars[0] = term.expr_vars[0];
slack_term.expr_coeffs[0] = -term.expr_coeffs[0];
slack_term.expr_vars[1] = bool_term.expr_vars[0];
slack_term.expr_coeffs[1] = bound_diff * bool_term.expr_coeffs[0];
slack_term.expr_offset =
bound_diff * bool_term.expr_offset - term.expr_offset;
slack_term.lp_value = info.SlackLpValue(lb);
slack_term.bound_diff = term.bound_diff;
// Commit the change.
++num_ib_used_;
++total_num_neg_lifts_;
term = slack_term;
cut_builder_.AddOrMergeTerm(bool_term, factor_t, &best_cut_);
}
}
total_num_merges_ += cut_builder_.NumMergesSinceLastClear();
}
// More complementation, but for the same f.
// If we can do that, it probably means our heuristics above are not great.
for (int i = 0; i < 3; ++i) {
const int64_t saved = total_num_final_complements_;
for (CutTerm& entry : best_cut_.terms) {
// Complementing an entry gives:
// [a * X <= b] -> [-a * (diff - X) <= b - a * diff]
//
// We will compare what happen when we apply f:
// [f(b) - f(a) * lp(X)] -> [f(b - a * diff) - f(-a) * (diff - lp(X))].
//
// If lp(X) is zero, then the transformation is always worse.
// Because f(b - a * diff) >= f(b) + f(-a) * diff by super-additivity.
//
// However the larger is X, the better it gets since at diff, we have
// f(b) >= f(b - a * diff) + f(a * diff) >= f(b - a * diff) + f(a) * diff.
//
// TODO(user): It is still unclear if we have a * X + b * (1 - X) <= rhs
// for a Boolean X, what is the best way to apply f and if we should merge
// the terms. If there is no other terms, best is probably
// f(rhs - a) * X + f(rhs - b) * (1 - X).
if (entry.coeff % best_divisor == 0) continue;
if (!entry.HasRelevantLpValue()) continue;
// Avoid potential overflow here.
const IntegerValue prod(CapProdI(entry.bound_diff, entry.coeff));
if (ProdOverflow(factor_t, prod)) continue;
if (ProdOverflow(factor_t, CapSubI(best_cut_.rhs, prod))) continue;
const double lp1 = ToDouble(f(best_cut_.rhs)) -
ToDouble(f(entry.coeff)) * entry.lp_value;
const double lp2 = ToDouble(f(best_cut_.rhs - prod)) -
ToDouble(f(-entry.coeff)) *
(ToDouble(entry.bound_diff) - entry.lp_value);
if (lp2 + 1e-2 < lp1) {
if (!entry.Complement(&best_cut_.rhs)) continue;
++total_num_final_complements_;
}
}
if (total_num_final_complements_ == saved) break;
}
// Apply f() to the best_cut_ with a potential improvement for one Boolean:
//
// If we have a Boolean X, and a cut: terms + a * X <= b;
// By setting X to true or false, we have two inequalities:
// terms <= b if X == 0
// terms <= b - a if X == 1
// We can apply f to both inequalities and recombine:
// f(terms) <= f(b) * (1 - X) + f(b - a) * X
// Which change the final coeff of X from f(a) to [f(b) - f(b - a)].
// This can only improve the cut since f(b) >= f(b - a) + f(a)
//
// Note that we re-Canonicalize after our possible complementation so that the
// "improvement" is applied to larger lp_value first.
best_cut_.Canonicalize();
bool improved = false;
const IntegerValue rhs = best_cut_.rhs;
const IntegerValue f_rhs = f(best_cut_.rhs);
best_cut_.rhs = f_rhs;
for (CutTerm& entry : best_cut_.terms) {
const IntegerValue f_coeff = f(entry.coeff);
if (!improved && entry.bound_diff == 1 &&
!ProdOverflow(factor_t, CapSubI(rhs, entry.coeff))) {
const IntegerValue alternative = f_rhs - f(rhs - entry.coeff);
DCHECK_GE(alternative, f_coeff);
if (alternative > f_coeff) {
++total_num_bumps_;
improved = true;
entry.coeff = alternative;
continue;
}
}
entry.coeff = f_coeff;
}
if (!cut_builder_.ConvertToLinearConstraint(best_cut_, &cut_)) {
++total_num_overflow_abort_;
return false;
}
return true;
}
CoverCutHelper::~CoverCutHelper() {
if (!VLOG_IS_ON(1)) return;
if (shared_stats_ == nullptr) return;
std::vector<std::pair<std::string, int64_t>> stats;
stats.push_back({"cover_cut/num_overflows", total_num_overflow_abort_});
stats.push_back({"cover_cut/num_lifting", total_num_lifting_});
stats.push_back({"cover_cut/num_implied_bounds", total_num_ibs_});
shared_stats_->AddStats(stats);
}
// Try a simple cover heuristic.
// Look for violated CUT of the form: sum (UB - X) or (X - LB) >= 1.
int CoverCutHelper::GetCoverSize(int relevant_size, IntegerValue* rhs) {
if (relevant_size == 0) return 0;
// Sorting can be slow, so we start by splitting the vector in 3 parts
// [can always be in cover, candidates, can never be in cover].
int part1 = 0;
const double threshold = 1.0 / static_cast<double>(relevant_size);
for (int i = 0; i < relevant_size;) {
const double dist = base_ct_.terms[i].LpDistToMaxValue();
if (dist < threshold) {
// Move to part 1.
std::swap(base_ct_.terms[i], base_ct_.terms[part1]);
++i;
++part1;
} else if (dist < 0.9999) {
// Keep in part 2.
++i;
} else {
// Exclude entirely (part 3).
--relevant_size;
std::swap(base_ct_.terms[i], base_ct_.terms[relevant_size]);
}
}
std::sort(base_ct_.terms.begin() + part1,
base_ct_.terms.begin() + relevant_size,
[](const CutTerm& a, const CutTerm& b) {
const double dist_a = a.LpDistToMaxValue();
const double dist_b = b.LpDistToMaxValue();
if (dist_a == dist_b) {
// Prefer low coefficients if the distance is the same.
return a.coeff < b.coeff;
}
return dist_a < dist_b;
});
double activity = 0.0;
int cover_size = relevant_size;
*rhs = base_ct_.rhs;
for (int i = 0; i < relevant_size; ++i) {
const CutTerm& term = base_ct_.terms[i];
activity += term.LpDistToMaxValue();
// As an heuristic we select all the term so that the sum of distance
// to the upper bound is <= 1.0. If the corresponding rhs is negative, then
// we will have a cut of violation at least 0.0. Note that this violation
// can be improved by the lifting.
//
// TODO(user): experiment with different threshold (even greater than one).
// Or come up with an algo that incorporate the lifting into the heuristic.
if (activity > 0.9999) {
cover_size = i; // before this entry.
break;
}
if (!AddProductTo(-term.coeff, term.bound_diff, rhs)) {