forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 9
/
cuts.cc
2801 lines (2517 loc) · 105 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-2024 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 <array>
#include <cmath>
#include <cstdint>
#include <functional>
#include <limits>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "absl/base/attributes.h"
#include "absl/container/btree_map.h"
#include "absl/container/btree_set.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/log/check.h"
#include "absl/meta/type_traits.h"
#include "absl/numeric/int128.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "ortools/base/logging.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/strong_vector.h"
#include "ortools/lp_data/lp_types.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/sat/synchronization.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/sorted_interval_list.h"
#include "ortools/util/strong_integers.h"
namespace operations_research {
namespace sat {
namespace {
// TODO(user): the function ToDouble() does some testing for min/max integer
// value and we don't need that here.
double AsDouble(IntegerValue v) { return static_cast<double>(v.value()); }
} // namespace
std::string CutTerm::DebugString() const {
return absl::StrCat("coeff=", coeff.value(), " lp=", lp_value,
" range=", bound_diff.value(), " expr=[",
expr_coeffs[0].value(), ",", expr_coeffs[1].value(), "]",
" * [V", expr_vars[0].value(), ",V", expr_vars[1].value(),
"]", " + ", expr_offset.value());
}
std::string CutData::DebugString() const {
std::string result = absl::StrCat("CutData rhs=", rhs, "\n");
for (const CutTerm& term : terms) {
absl::StrAppend(&result, term.DebugString(), "\n");
}
return result;
}
void CutTerm::Complement(absl::int128* rhs) {
// We replace coeff * X by coeff * (X - bound_diff + bound_diff)
// which gives -coeff * complement(X) + coeff * bound_diff;
*rhs -= absl::int128(coeff.value()) * absl::int128(bound_diff.value());
// 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 = static_cast<double>(bound_diff.value()) - lp_value;
coeff = -coeff;
// Swap the implied bound info.
std::swap(cached_implied_lb, cached_implied_ub);
}
void CutTerm::ReplaceExpressionByLiteral(IntegerVariable var) {
CHECK_EQ(bound_diff, 1);
expr_coeffs[1] = 0;
if (VariableIsPositive(var)) {
expr_vars[0] = var;
expr_coeffs[0] = 1;
expr_offset = 0;
} else {
expr_vars[0] = PositiveVariable(var);
expr_coeffs[0] = -1;
expr_offset = 1;
}
}
IntegerVariable CutTerm::GetUnderlyingLiteralOrNone() const {
if (expr_coeffs[1] != 0) return kNoIntegerVariable;
if (bound_diff != 1) return kNoIntegerVariable;
if (expr_coeffs[0] > 0) {
if (expr_coeffs[0] != 1) return kNoIntegerVariable;
if (expr_offset != 0) return kNoIntegerVariable;
CHECK(VariableIsPositive(expr_vars[0]));
return expr_vars[0];
}
if (expr_coeffs[0] != -1) return kNoIntegerVariable;
if (expr_offset != 1) return kNoIntegerVariable;
CHECK(VariableIsPositive(expr_vars[0]));
return NegationOf(expr_vars[0]);
}
// 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 has a positive coefficient.
const bool complement = coeff < 0;
// See formula below, the constant term is either coeff * lb or coeff * ub.
rhs -= absl::int128(coeff.value()) *
absl::int128(complement ? ub.value() : lb.value());
// 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 = static_cast<double>(ub.value()) - 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 - static_cast<double>(lb.value());
}
terms.push_back(entry);
return true;
}
bool CutData::FillFromLinearConstraint(
const LinearConstraint& base_ct,
const util_intops::StrongVector<IntegerVariable, double>& lp_values,
IntegerTrail* integer_trail) {
rhs = absl::int128(base_ct.ub.value());
terms.clear();
const int num_terms = base_ct.num_terms;
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(
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) {
rhs = absl::int128(ub.value());
terms.clear();
const int size = lp_values.size();
if (size == 0) return true;
CHECK_EQ(vars.size(), size);
CHECK_EQ(coeffs.size(), size);
CHECK_EQ(lower_bounds.size(), size);
CHECK_EQ(upper_bounds.size(), size);
for (int i = 0; i < size; ++i) {
if (!AppendOneTerm(vars[i], coeffs[i], lp_values[i], lower_bounds[i],
upper_bounds[i])) {
return false;
}
}
return true;
}
void CutData::ComplementForPositiveCoefficients() {
for (CutTerm& term : terms) {
if (term.coeff >= 0) continue;
term.Complement(&rhs);
}
}
void CutData::ComplementForSmallerLpValues() {
for (CutTerm& term : terms) {
if (term.lp_value <= term.LpDistToMaxValue()) continue;
term.Complement(&rhs);
}
}
bool CutData::AllCoefficientsArePositive() const {
for (const CutTerm& term : terms) {
if (term.coeff < 0) return false;
}
return true;
}
void CutData::SortRelevantEntries() {
num_relevant_entries = 0;
max_magnitude = 0;
for (CutTerm& entry : terms) {
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;
});
}
double CutData::ComputeViolation() const {
double violation = -static_cast<double>(rhs);
for (const CutTerm& term : terms) {
violation += term.lp_value * static_cast<double>(term.coeff.value());
}
return violation;
}
double CutData::ComputeEfficacy() const {
double violation = -static_cast<double>(rhs);
double norm = 0.0;
for (const CutTerm& term : terms) {
const double coeff = static_cast<double>(term.coeff.value());
violation += term.lp_value * coeff;
norm += coeff * coeff;
}
return violation / std::sqrt(norm);
}
// 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.
bool CutDataBuilder::MergeIfPossible(IntegerValue t, CutTerm& to_add,
CutTerm& target) {
DCHECK_EQ(to_add.expr_vars[0], target.expr_vars[0]);
DCHECK_EQ(to_add.expr_coeffs[0], target.expr_coeffs[0]);
const IntegerValue new_coeff = CapAddI(to_add.coeff, target.coeff);
if (AtMinOrMaxInt64I(new_coeff) || ProdOverflow(t, new_coeff)) {
return false;
}
to_add.coeff = 0; // Clear since we merge it.
target.coeff = new_coeff;
return true;
}
// We only deal with coeff * Bool or coeff * (1 - Bool)
//
// TODO(user): Because of merges, we might have entry with a coefficient of
// zero than are not useful. Remove them?
int CutDataBuilder::AddOrMergeBooleanTerms(absl::Span<CutTerm> new_terms,
IntegerValue t, CutData* cut) {
if (new_terms.empty()) return 0;
bool_index_.clear();
secondary_bool_index_.clear();
int num_merges = 0;
// Fill the maps.
int i = 0;
for (CutTerm& term : new_terms) {
const IntegerVariable var = term.expr_vars[0];
auto& map = term.expr_coeffs[0] > 0 ? bool_index_ : secondary_bool_index_;
const auto [it, inserted] = map.insert({var, i});
if (!inserted) {
if (MergeIfPossible(t, term, new_terms[it->second])) {
++num_merges;
}
}
++i;
}
// Loop over the cut now. Note that we loop with indices as we might add new
// terms in the middle of the loop.
for (CutTerm& term : cut->terms) {
if (term.bound_diff != 1) continue;
if (!term.IsSimple()) continue;
const IntegerVariable var = term.expr_vars[0];
auto& map = term.expr_coeffs[0] > 0 ? bool_index_ : secondary_bool_index_;
auto it = map.find(var);
if (it == map.end()) continue;
// We found a match, try to merge the map entry into the cut.
// Note that we don't waste time erasing this entry from the map since
// we should have no duplicates in the original cut.
if (MergeIfPossible(t, new_terms[it->second], term)) {
++num_merges;
}
}
// Finally add the terms we couldn't merge.
for (const CutTerm& term : new_terms) {
if (term.coeff == 0) continue;
cut->terms.push_back(term);
}
return num_merges;
}
// TODO(user): Divide by gcd first to avoid possible overflow in the
// conversion? it is however unlikely given that our coeffs should be small.
ABSL_DEPRECATED("Only used in tests, this will be removed.")
bool CutDataBuilder::ConvertToLinearConstraint(const CutData& cut,
LinearConstraint* output) {
tmp_map_.clear();
if (cut.rhs > absl::int128(std::numeric_limits<int64_t>::max()) ||
cut.rhs < absl::int128(std::numeric_limits<int64_t>::min())) {
return false;
}
IntegerValue new_rhs = static_cast<int64_t>(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->lb = kMinIntegerValue;
output->ub = new_rhs;
output->resize(tmp_map_.size());
int new_size = 0;
for (const auto [var, coeff] : tmp_map_) {
if (coeff == 0) continue;
output->vars[new_size] = var;
output->coeffs[new_size] = coeff;
++new_size;
}
output->resize(new_size);
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 PositiveRemainder(absl::int128 dividend,
IntegerValue positive_divisor) {
DCHECK_GT(positive_divisor, 0);
const IntegerValue m =
static_cast<int64_t>(dividend % absl::int128(positive_divisor.value()));
return m < 0 ? m + positive_divisor : m;
}
// We use the fact that f(k * divisor + rest) = k * f(divisor) + f(rest)
absl::int128 ApplyToInt128(const std::function<IntegerValue(IntegerValue)>& f,
IntegerValue divisor, absl::int128 value) {
const IntegerValue rest = PositiveRemainder(value, divisor);
const absl::int128 k =
(value - absl::int128(rest.value())) / absl::int128(divisor.value());
const absl::int128 result =
k * absl::int128(f(divisor).value()) + absl::int128(f(rest).value());
return result;
}
// Apply f() to the 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)
int ApplyWithPotentialBump(const std::function<IntegerValue(IntegerValue)>& f,
const IntegerValue divisor, CutData* cut) {
int bump_index = -1;
double bump_score = -1.0;
IntegerValue bump_coeff;
const IntegerValue remainder = PositiveRemainder(cut->rhs, divisor);
const IntegerValue f_remainder = f(remainder);
cut->rhs = ApplyToInt128(f, divisor, cut->rhs);
for (int i = 0; i < cut->terms.size(); ++i) {
CutTerm& entry = cut->terms[i];
const IntegerValue f_coeff = f(entry.coeff);
if (entry.bound_diff == 1) {
// TODO(user): we probably don't need int128 here, but we need
// t * (remainder - entry.coeff) not to overflow, and we can't really be
// sure.
const IntegerValue alternative =
entry.coeff > 0
? f_remainder - f(remainder - entry.coeff)
: f_remainder - IntegerValue(static_cast<int64_t>(ApplyToInt128(
f, divisor,
absl::int128(remainder.value()) -
absl::int128(entry.coeff.value()))));
DCHECK_GE(alternative, f_coeff);
if (alternative > f_coeff) {
const double score = ToDouble(alternative - f_coeff) * entry.lp_value;
if (score > bump_score) {
bump_index = i;
bump_score = score;
bump_coeff = alternative;
}
}
}
entry.coeff = f_coeff;
}
if (bump_index >= 0) {
cut->terms[bump_index].coeff = bump_coeff;
return 1;
}
return 0;
}
} // 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;
};
}
}
std::function<IntegerValue(IntegerValue)> GetSuperAdditiveStrengtheningFunction(
IntegerValue positive_rhs, IntegerValue min_magnitude) {
CHECK_GT(positive_rhs, 0);
CHECK_GT(min_magnitude, 0);
if (min_magnitude >= CeilRatio(positive_rhs, 2)) {
return [positive_rhs](IntegerValue v) {
if (v >= 0) return IntegerValue(0);
if (v > -positive_rhs) return IntegerValue(-1);
return IntegerValue(-2);
};
}
// The transformation only work if 2 * second_threshold >= positive_rhs.
//
// TODO(user): Limit the number of value used with scaling like above.
min_magnitude = std::min(min_magnitude, FloorRatio(positive_rhs, 2));
const IntegerValue second_threshold = positive_rhs - min_magnitude;
return [positive_rhs, min_magnitude, second_threshold](IntegerValue v) {
if (v >= 0) return IntegerValue(0);
if (v <= -positive_rhs) return -positive_rhs;
if (v <= -second_threshold) return -second_threshold;
// This should actually never happen by the definition of min_magnitude.
// But with it, the function is supper-additive even if min_magnitude is not
// correct.
if (v >= -min_magnitude) return -min_magnitude;
// TODO(user): we might want to intoduce some step to reduce the final
// magnitude of the cut.
return v;
};
}
std::function<IntegerValue(IntegerValue)>
GetSuperAdditiveStrengtheningMirFunction(IntegerValue positive_rhs,
IntegerValue scaling) {
if (scaling >= positive_rhs) {
// Simple case, no scaling required.
return [positive_rhs](IntegerValue v) {
if (v >= 0) return IntegerValue(0);
if (v <= -positive_rhs) return -positive_rhs;
return v;
};
}
// We need to scale.
scaling =
std::min(scaling, IntegerValue(std::numeric_limits<int64_t>::max()) /
positive_rhs);
if (scaling == 1) {
return [](IntegerValue v) {
if (v >= 0) return IntegerValue(0);
return IntegerValue(-1);
};
}
// We divide [-positive_rhs + 1, 0] into (scaling - 1) bucket.
return [positive_rhs, scaling](IntegerValue v) {
if (v >= 0) return IntegerValue(0);
if (v <= -positive_rhs) return -scaling;
return FloorRatio(v * (scaling - 1), (positive_rhs - 1));
};
}
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) {
absl::int128 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 = static_cast<double>(initial_rhs_remainder.value());
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 -=
static_cast<double>(remainder.value()) * 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 += absl::int128(prod.value());
const IntegerValue new_coeff = entry.coeff + adjust;
adjusted_coeffs_.push_back({i, new_coeff});
max_magnitude = std::max(max_magnitude, IntTypeAbs(new_coeff));
}
}
}
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 = -static_cast<double>(ApplyToInt128(f, divisor, 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);
}
// 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.
cut_ = base_ct;
if (options.use_ib_before_heuristic && ib_processor != nullptr) {
std::vector<CutTerm>* new_bool_terms =
ib_processor->ClearedMutableTempTerms();
for (CutTerm& term : cut_.terms) {
if (term.bound_diff <= 1) continue;
if (!term.HasRelevantLpValue()) continue;
if (options.prefer_positive_ib && term.coeff < 0) {
// We complement the term before trying the implied bound.
term.Complement(&cut_.rhs);
if (ib_processor->TryToExpandWithLowerImpliedbound(
IntegerValue(1),
/*complement=*/true, &term, &cut_.rhs, new_bool_terms)) {
++total_num_initial_ibs_;
continue;
}
term.Complement(&cut_.rhs);
}
if (ib_processor->TryToExpandWithLowerImpliedbound(
IntegerValue(1),
/*complement=*/true, &term, &cut_.rhs, new_bool_terms)) {
++total_num_initial_ibs_;
}
}
// 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 (new_bool_terms->empty()) return false;
total_num_initial_merges_ +=
ib_processor->MutableCutBuilder()->AddOrMergeBooleanTerms(
absl::MakeSpan(*new_bool_terms), IntegerValue(1), &cut_);
}
// 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.
cut_.SortRelevantEntries();
const IntegerValue remainder_threshold(
std::max(IntegerValue(1), cut_.max_magnitude / 1000));
if (cut_.rhs >= 0 && cut_.rhs < remainder_threshold.value()) {
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 : 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 we have too many divisor to try, restrict to the first ones which
// should correspond to the highest lp values.
if (divisors_.size() > 50) break;
}
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, 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, 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.
// TODO(user): This can be quadratic! we don't want to try too much of them.
// Or optimize the algo, we should be able to be more incremental here.
// see on g200x740.pb.gz for instance.
for (CutTerm& entry : cut_.terms) {
if (!entry.HasRelevantLpValue()) break;
if (entry.coeff % best_divisor == 0) continue;
// Temporary complement this variable.
entry.Complement(&cut_.rhs);
const double violation = GetScaledViolation(
best_divisor, options.max_scaling, remainder_threshold, 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(&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 = cut_.terms[index];
const IntegerValue remainder = new_coeff - entry.coeff;
CHECK_GT(remainder, 0);
entry.coeff = new_coeff;
cut_.rhs += absl::int128(remainder.value()) *
absl::int128(entry.bound_diff.value());
cut_.max_magnitude = std::max(cut_.max_magnitude, IntTypeAbs(new_coeff));
}
// Create the base super-additive function f().
const IntegerValue rhs_remainder = PositiveRemainder(cut_.rhs, best_divisor);
IntegerValue factor_t =
GetFactorT(rhs_remainder, best_divisor, 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 : 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, 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 might be worse.
num_ib_used_ = 0;
if (ib_processor != nullptr) {
const auto [num_lb, num_ub, num_merges] =
ib_processor->PostprocessWithImpliedBound(f, factor_t, &cut_);
total_num_pos_lifts_ += num_lb;
total_num_neg_lifts_ += num_ub;
total_num_merges_ += num_merges;
num_ib_used_ = num_lb + num_ub;
}
// 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 : cut_.terms) {
// Complementing an entry gives: