This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
forked from rte-france/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_programming_constraint.cc
1890 lines (1690 loc) · 73 KB
/
linear_programming_constraint.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-2018 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/linear_programming_constraint.h"
#include <cmath>
#include <limits>
#include <string>
#include "absl/container/flat_hash_map.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/int128.h"
#include "ortools/base/int_type_indexed_vector.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/glop/parameters.pb.h"
#include "ortools/glop/preprocessor.h"
#include "ortools/glop/status.h"
#include "ortools/graph/strongly_connected_components.h"
#include "ortools/lp_data/lp_types.h"
#include "ortools/util/saturated_arithmetic.h"
namespace operations_research {
namespace sat {
using glop::ColIndex;
using glop::Fractional;
using glop::RowIndex;
const double LinearProgrammingConstraint::kCpEpsilon = 1e-4;
const double LinearProgrammingConstraint::kLpEpsilon = 1e-6;
// TODO(user): make SatParameters singleton too, otherwise changing them after
// a constraint was added will have no effect on this class.
LinearProgrammingConstraint::LinearProgrammingConstraint(Model* model)
: constraint_manager_(model),
sat_parameters_(*(model->GetOrCreate<SatParameters>())),
model_(model),
time_limit_(model->GetOrCreate<TimeLimit>()),
integer_trail_(model->GetOrCreate<IntegerTrail>()),
trail_(model->GetOrCreate<Trail>()),
model_heuristics_(model->GetOrCreate<SearchHeuristicsVector>()),
integer_encoder_(model->GetOrCreate<IntegerEncoder>()),
dispatcher_(model->GetOrCreate<LinearProgrammingDispatcher>()),
expanded_lp_solution_(
*model->GetOrCreate<LinearProgrammingConstraintLpSolution>()) {
// Tweak the default parameters to make the solve incremental.
glop::GlopParameters parameters;
parameters.set_use_dual_simplex(true);
simplex_.SetParameters(parameters);
}
void LinearProgrammingConstraint::AddLinearConstraint(
const LinearConstraint& ct) {
DCHECK(!lp_constraint_is_registered_);
constraint_manager_.Add(ct);
// We still create the mirror variable right away though.
//
// TODO(user): clean this up? Note that it is important that the variable
// in lp_data_ never changes though, so we can restart from the current
// lp solution and be incremental (even if the constraints changed).
for (const IntegerVariable var : ct.vars) {
GetOrCreateMirrorVariable(PositiveVariable(var));
}
}
glop::ColIndex LinearProgrammingConstraint::GetOrCreateMirrorVariable(
IntegerVariable positive_variable) {
DCHECK(VariableIsPositive(positive_variable));
const auto it = mirror_lp_variable_.find(positive_variable);
if (it == mirror_lp_variable_.end()) {
const glop::ColIndex col(integer_variables_.size());
mirror_lp_variable_[positive_variable] = col;
integer_variables_.push_back(positive_variable);
lp_solution_.push_back(std::numeric_limits<double>::infinity());
lp_reduced_cost_.push_back(0.0);
(*dispatcher_)[positive_variable] = this;
const int index = std::max(positive_variable.value(),
NegationOf(positive_variable).value());
if (index >= expanded_lp_solution_.size()) {
expanded_lp_solution_.resize(index + 1, 0.0);
}
return col;
}
return it->second;
}
void LinearProgrammingConstraint::SetObjectiveCoefficient(IntegerVariable ivar,
IntegerValue coeff) {
CHECK(!lp_constraint_is_registered_);
objective_is_defined_ = true;
IntegerVariable pos_var = VariableIsPositive(ivar) ? ivar : NegationOf(ivar);
if (ivar != pos_var) coeff = -coeff;
const glop::ColIndex col = GetOrCreateMirrorVariable(pos_var);
integer_objective_.push_back({col, coeff});
objective_infinity_norm_ =
std::max(objective_infinity_norm_, IntTypeAbs(coeff));
}
// TODO(user): As the search progress, some variables might get fixed. Exploit
// this to reduce the number of variables in the LP and in the
// ConstraintManager? We might also detect during the search that two variable
// are equivalent.
void LinearProgrammingConstraint::CreateLpFromConstraintManager() {
// Fill integer_lp_.
integer_lp_.clear();
infinity_norms_.clear();
const auto& all_constraints = constraint_manager_.AllConstraints();
for (const auto index : constraint_manager_.LpConstraints()) {
const LinearConstraint& ct = all_constraints[index];
integer_lp_.push_back(LinearConstraintInternal());
LinearConstraintInternal& new_ct = integer_lp_.back();
new_ct.lb = ct.lb;
new_ct.ub = ct.ub;
const int size = ct.vars.size();
IntegerValue infinity_norm(0);
if (ct.lb > kMinIntegerValue) {
infinity_norm = std::max(infinity_norm, IntTypeAbs(ct.lb));
}
if (ct.ub < kMaxIntegerValue) {
infinity_norm = std::max(infinity_norm, IntTypeAbs(ct.ub));
}
for (int i = 0; i < size; ++i) {
// We only use positive variable inside this class.
IntegerVariable var = ct.vars[i];
IntegerValue coeff = ct.coeffs[i];
if (!VariableIsPositive(var)) {
var = NegationOf(var);
coeff = -coeff;
}
infinity_norm = std::max(infinity_norm, IntTypeAbs(coeff));
new_ct.terms.push_back({GetOrCreateMirrorVariable(var), coeff});
}
infinity_norms_.push_back(infinity_norm);
// Important to keep lp_data_ "clean".
std::sort(new_ct.terms.begin(), new_ct.terms.end());
}
// Copy the integer_lp_ into lp_data_.
lp_data_.Clear();
for (int i = 0; i < integer_variables_.size(); ++i) {
CHECK_EQ(glop::ColIndex(i), lp_data_.CreateNewVariable());
}
for (const auto entry : integer_objective_) {
lp_data_.SetObjectiveCoefficient(entry.first, ToDouble(entry.second));
}
for (const LinearConstraintInternal& ct : integer_lp_) {
const ConstraintIndex row = lp_data_.CreateNewConstraint();
lp_data_.SetConstraintBounds(row, ToDouble(ct.lb), ToDouble(ct.ub));
for (const auto& term : ct.terms) {
lp_data_.SetCoefficient(row, term.first, ToDouble(term.second));
}
}
// Scale lp_data_.
scaler_.Clear();
Scale(&lp_data_, &scaler_, glop::GlopParameters::DEFAULT);
lp_data_.ScaleObjective();
// ScaleBounds() looks at both the constraints and variable bounds, so we
// initialize the LP variable bounds before scaling them.
//
// TODO(user): As part of the scaling, we may also want to shift the initial
// variable bounds so that each variable contain the value zero in their
// domain. Maybe just once and for all at the beginning.
bound_scaling_factor_ = 1.0;
UpdateBoundsOfLpVariables();
bound_scaling_factor_ = lp_data_.ScaleBounds();
lp_data_.NotifyThatColumnsAreClean();
lp_data_.AddSlackVariablesWhereNecessary(false);
VLOG(1) << "LP relaxation: " << lp_data_.GetDimensionString() << ". "
<< constraint_manager_.AllConstraints().size()
<< " Managed constraints.";
}
void LinearProgrammingConstraint::RegisterWith(Model* model) {
DCHECK(!lp_constraint_is_registered_);
lp_constraint_is_registered_ = true;
model->GetOrCreate<LinearProgrammingConstraintCollection>()->push_back(this);
// Note fdid, this is not really needed by should lead to better cache
// locality.
std::sort(integer_objective_.begin(), integer_objective_.end());
// Set the LP to its initial content.
if (!sat_parameters_.add_lp_constraints_lazily()) {
constraint_manager_.AddAllConstraintsToLp();
}
CreateLpFromConstraintManager();
GenericLiteralWatcher* watcher = model->GetOrCreate<GenericLiteralWatcher>();
const int watcher_id = watcher->Register(this);
const int num_vars = integer_variables_.size();
for (int i = 0; i < num_vars; i++) {
watcher->WatchIntegerVariable(integer_variables_[i], watcher_id, i);
}
if (objective_is_defined_) {
watcher->WatchUpperBound(objective_cp_, watcher_id);
}
watcher->SetPropagatorPriority(watcher_id, 2);
watcher->AlwaysCallAtLevelZero(watcher_id);
if (integer_variables_.size() >= 20) { // Do not use on small subparts.
auto* container = model->GetOrCreate<SearchHeuristicsVector>();
container->push_back(HeuristicLPPseudoCostBinary(model));
container->push_back(HeuristicLPMostInfeasibleBinary(model));
}
// Registering it with the trail make sure this class is always in sync when
// it is used in the decision heuristics.
integer_trail_->RegisterReversibleClass(this);
watcher->RegisterReversibleInt(watcher_id, &rev_optimal_constraints_size_);
}
void LinearProgrammingConstraint::SetLevel(int level) {
optimal_constraints_.resize(rev_optimal_constraints_size_);
if (lp_solution_is_set_ && level < lp_solution_level_) {
lp_solution_is_set_ = false;
}
// Special case for level zero, we "reload" any previously known optimal
// solution from that level.
//
// TODO(user): Keep all optimal solution in the current branch?
// TODO(user): Still try to add cuts/constraints though!
if (level == 0 && !level_zero_lp_solution_.empty()) {
lp_solution_is_set_ = true;
lp_solution_ = level_zero_lp_solution_;
lp_solution_level_ = 0;
for (int i = 0; i < lp_solution_.size(); i++) {
expanded_lp_solution_[integer_variables_[i]] = lp_solution_[i];
expanded_lp_solution_[NegationOf(integer_variables_[i])] =
-lp_solution_[i];
}
}
}
void LinearProgrammingConstraint::AddCutGenerator(CutGenerator generator) {
for (const IntegerVariable var : generator.vars) {
GetOrCreateMirrorVariable(VariableIsPositive(var) ? var : NegationOf(var));
}
cut_generators_.push_back(std::move(generator));
}
bool LinearProgrammingConstraint::IncrementalPropagate(
const std::vector<int>& watch_indices) {
if (!lp_solution_is_set_) return Propagate();
// At level zero, if there is still a chance to add cuts or lazy constraints,
// we re-run the LP.
if (trail_->CurrentDecisionLevel() == 0 && !lp_at_level_zero_is_final_) {
return Propagate();
}
// Check whether the change breaks the current LP solution. If it does, call
// Propagate() on the current LP.
for (const int index : watch_indices) {
const double lb =
ToDouble(integer_trail_->LowerBound(integer_variables_[index]));
const double ub =
ToDouble(integer_trail_->UpperBound(integer_variables_[index]));
const double value = lp_solution_[index];
if (value < lb - kCpEpsilon || value > ub + kCpEpsilon) return Propagate();
}
// TODO(user): The saved lp solution is still valid given the current variable
// bounds, so the LP optimal didn't change. However we might still want to add
// new cuts or new lazy constraints?
//
// TODO(user): Propagate the last optimal_constraint? Note that we need
// to be careful since the reversible int in IntegerSumLE are not registered.
// However, because we delete "optimalconstraints" on backtrack, we might not
// care.
return true;
}
glop::Fractional LinearProgrammingConstraint::CpToLpScalingFactor(
glop::ColIndex col) const {
return scaler_.col_scale(col) / bound_scaling_factor_;
}
glop::Fractional LinearProgrammingConstraint::LpToCpScalingFactor(
glop::ColIndex col) const {
return bound_scaling_factor_ / scaler_.col_scale(col);
}
glop::Fractional LinearProgrammingConstraint::GetVariableValueAtCpScale(
glop::ColIndex var) {
return simplex_.GetVariableValue(var) * LpToCpScalingFactor(var);
}
double LinearProgrammingConstraint::GetSolutionValue(
IntegerVariable variable) const {
return lp_solution_[gtl::FindOrDie(mirror_lp_variable_, variable).value()];
}
double LinearProgrammingConstraint::GetSolutionReducedCost(
IntegerVariable variable) const {
return lp_reduced_cost_[gtl::FindOrDie(mirror_lp_variable_, variable)
.value()];
}
void LinearProgrammingConstraint::UpdateBoundsOfLpVariables() {
const int num_vars = integer_variables_.size();
for (int i = 0; i < num_vars; i++) {
const IntegerVariable cp_var = integer_variables_[i];
const double lb = ToDouble(integer_trail_->LowerBound(cp_var));
const double ub = ToDouble(integer_trail_->UpperBound(cp_var));
const double factor = CpToLpScalingFactor(glop::ColIndex(i));
lp_data_.SetVariableBounds(glop::ColIndex(i), lb * factor, ub * factor);
}
}
bool LinearProgrammingConstraint::SolveLp() {
if (trail_->CurrentDecisionLevel() == 0) {
lp_at_level_zero_is_final_ = false;
}
const auto status = simplex_.Solve(lp_data_, time_limit_);
if (!status.ok()) {
VLOG(1) << "The LP solver encountered an error: " << status.error_message();
simplex_.ClearStateForNextSolve();
return false;
}
average_degeneracy_.AddData(CalculateDegeneracy());
if (average_degeneracy_.CurrentAverage() >= 1000.0) {
VLOG(1) << "High average degeneracy: "
<< average_degeneracy_.CurrentAverage();
}
if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
lp_solution_is_set_ = true;
lp_solution_level_ = trail_->CurrentDecisionLevel();
const int num_vars = integer_variables_.size();
for (int i = 0; i < num_vars; i++) {
const glop::Fractional value =
GetVariableValueAtCpScale(glop::ColIndex(i));
lp_solution_[i] = value;
expanded_lp_solution_[integer_variables_[i]] = value;
expanded_lp_solution_[NegationOf(integer_variables_[i])] = -value;
}
if (lp_solution_level_ == 0) {
level_zero_lp_solution_ = lp_solution_;
}
}
return true;
}
LinearConstraint LinearProgrammingConstraint::ConvertToLinearConstraint(
const gtl::ITIVector<ColIndex, IntegerValue>& dense_vector,
IntegerValue upper_bound) {
LinearConstraint result;
for (ColIndex col(0); col < dense_vector.size(); ++col) {
const IntegerValue coeff = dense_vector[col];
if (coeff == 0) continue;
const IntegerVariable var = integer_variables_[col.value()];
result.vars.push_back(var);
result.coeffs.push_back(coeff);
}
result.lb = kMinIntegerValue;
result.ub = upper_bound;
return result;
}
namespace {
// Returns false in case of overflow
bool AddLinearExpressionMultiple(
IntegerValue multiplier,
const std::vector<std::pair<ColIndex, IntegerValue>>& terms,
gtl::ITIVector<ColIndex, IntegerValue>* dense_vector) {
for (const std::pair<ColIndex, IntegerValue> term : terms) {
if (!AddProductTo(multiplier, term.second, &(*dense_vector)[term.first])) {
return false;
}
}
return true;
}
} // namespace
void LinearProgrammingConstraint::AddCutFromConstraints(
const std::string& name,
const std::vector<std::pair<RowIndex, IntegerValue>>& integer_multipliers) {
// This is initialized to a valid linear contraint (by taking linear
// combination of the LP rows) and will be transformed into a cut if
// possible.
//
// TODO(user): Ideally this linear combination should have only one
// fractional variable (basis_col). But because of imprecision, we get a
// bunch of fractional entry with small coefficient (relative to the one of
// basis_col). We try to handle that in IntegerRoundingCut(), but it might
// be better to add small multiple of the involved rows to get rid of them.
LinearConstraint cut;
{
gtl::ITIVector<ColIndex, IntegerValue> dense_cut;
IntegerValue cut_ub;
if (!ComputeNewLinearConstraint(
/*use_constraint_status=*/true, integer_multipliers, &dense_cut,
&cut_ub)) {
VLOG(1) << "Issue, overflow!";
return;
}
// Important: because we use integer_multipliers below, we cannot just
// divide by GCD or call PreventOverflow() here.
cut = ConvertToLinearConstraint(dense_cut, cut_ub);
}
// This should be tight!
if (std::abs(ComputeActivity(cut, expanded_lp_solution_) - ToDouble(cut.ub)) /
std::max(1.0, std::abs(ToDouble(cut.ub))) >
1e-2) {
VLOG(1) << "Cut not tight " << ComputeActivity(cut, expanded_lp_solution_)
<< " " << ToDouble(cut.ub);
return;
}
// Fills data for IntegerRoundingCut().
//
// Note(user): we use the current bound here, so the reasonement will only
// produce locally valid cut if we call this at a non-root node. We could
// use the level zero bounds if we wanted to generate a globally valid cut
// at another level, but we will likely not genereate a constraint violating
// the current lp solution in that case.
std::vector<double> lp_values;
std::vector<IntegerValue> var_lbs;
std::vector<IntegerValue> var_ubs;
for (const IntegerVariable var : cut.vars) {
lp_values.push_back(expanded_lp_solution_[var]);
var_lbs.push_back(integer_trail_->LowerBound(var));
var_ubs.push_back(integer_trail_->UpperBound(var));
}
// Add slack.
// definition: integer_lp_[row] + slack_row == bound;
const IntegerVariable first_slack(expanded_lp_solution_.size());
for (const auto pair : integer_multipliers) {
const RowIndex row = pair.first;
const IntegerValue coeff = pair.second;
const auto status = simplex_.GetConstraintStatus(row);
if (status == glop::ConstraintStatus::FIXED_VALUE) continue;
lp_values.push_back(0.0);
cut.vars.push_back(first_slack + IntegerVariable(row.value()));
cut.coeffs.push_back(coeff);
const IntegerValue diff(CapSub(integer_lp_[row.value()].ub.value(),
integer_lp_[row.value()].lb.value()));
if (status == glop::ConstraintStatus::AT_UPPER_BOUND) {
var_lbs.push_back(IntegerValue(0));
var_ubs.push_back(diff);
} else {
CHECK_EQ(status, glop::ConstraintStatus::AT_LOWER_BOUND);
var_lbs.push_back(-diff);
var_ubs.push_back(IntegerValue(0));
}
}
// Get the cut using some integer rounding heuristic.
RoundingOptions options;
options.use_mir = sat_parameters_.use_mir_rounding();
options.max_scaling = sat_parameters_.max_integer_rounding_scaling();
IntegerRoundingCut(options, lp_values, var_lbs, var_ubs, &cut);
// Compute the activity. Warning: the cut no longer have the same size so we
// cannot use lp_values. Note that the substitution below shouldn't change
// the activity by definition.
double activity = 0.0;
for (int i = 0; i < cut.vars.size(); ++i) {
if (cut.vars[i] < first_slack) {
activity += ToDouble(cut.coeffs[i]) * expanded_lp_solution_[cut.vars[i]];
}
}
const double kMinViolation = 1e-4;
const double violation = activity - ToDouble(cut.ub);
if (violation < kMinViolation) {
VLOG(2) << "Bad cut " << activity << " <= " << ToDouble(cut.ub);
return;
}
// Substitute any slack left.
{
int num_slack = 0;
gtl::ITIVector<ColIndex, IntegerValue> dense_cut(integer_variables_.size(),
IntegerValue(0));
IntegerValue cut_ub = cut.ub;
bool overflow = false;
for (int i = 0; i < cut.vars.size(); ++i) {
if (cut.vars[i] < first_slack) {
CHECK(VariableIsPositive(cut.vars[i]));
const glop::ColIndex col =
gtl::FindOrDie(mirror_lp_variable_, cut.vars[i]);
dense_cut[col] = cut.coeffs[i];
} else {
++num_slack;
// Update the constraint.
const glop::RowIndex row(cut.vars[i].value() - first_slack.value());
const IntegerValue multiplier = -cut.coeffs[i];
if (!AddLinearExpressionMultiple(
multiplier, integer_lp_[row.value()].terms, &dense_cut)) {
overflow = true;
break;
}
// Update rhs.
const auto status = simplex_.GetConstraintStatus(row);
if (status == glop::ConstraintStatus::AT_LOWER_BOUND) {
if (!AddProductTo(multiplier, integer_lp_[row.value()].lb, &cut_ub)) {
overflow = true;
break;
}
} else {
CHECK_EQ(status, glop::ConstraintStatus::AT_UPPER_BOUND);
if (!AddProductTo(multiplier, integer_lp_[row.value()].ub, &cut_ub)) {
overflow = true;
break;
}
}
}
}
if (overflow) {
VLOG(1) << "Overflow in slack removal.";
return;
}
VLOG(3) << " num_slack: " << num_slack;
cut = ConvertToLinearConstraint(dense_cut, cut_ub);
}
const double new_violation =
ComputeActivity(cut, expanded_lp_solution_) - ToDouble(cut.ub);
if (std::abs(violation - new_violation) >= 1e-4) {
VLOG(1) << "Violation discrepancy after slack removal. "
<< " before = " << violation << " after = " << new_violation;
}
DivideByGCD(&cut);
constraint_manager_.AddCut(cut, name, expanded_lp_solution_);
}
void LinearProgrammingConstraint::AddCGCuts() {
CHECK_EQ(trail_->CurrentDecisionLevel(), 0);
const RowIndex num_rows = lp_data_.num_constraints();
for (RowIndex row(0); row < num_rows; ++row) {
ColIndex basis_col = simplex_.GetBasis(row);
const Fractional lp_value = GetVariableValueAtCpScale(basis_col);
// TODO(user): We could just look at the diff with std::floor() in the hope
// that when we are just under an integer, the exact computation below will
// also be just under it.
if (std::abs(lp_value - std::round(lp_value)) < 0.01) continue;
// This is optional, but taking the negation allow to change the
// fractionality to 1 - fractionality. And having a fractionality close
// to 1.0 result in smaller coefficients in IntegerRoundingCut().
//
// TODO(user): Perform more experiments. Provide an option?
const bool take_negation = lp_value - std::floor(lp_value) < 0.5;
// If this variable is a slack, we ignore it. This is because the
// corresponding row is not tight under the given lp values.
if (basis_col >= integer_variables_.size()) continue;
const glop::ScatteredRow& lambda = simplex_.GetUnitRowLeftInverse(row);
glop::DenseColumn lp_multipliers(num_rows, 0.0);
double magnitude = 0.0;
int num_non_zeros = 0;
for (RowIndex row(0); row < num_rows; ++row) {
lp_multipliers[row] = lambda.values[glop::RowToColIndex(row)];
if (lp_multipliers[row] == 0.0) continue;
if (take_negation) lp_multipliers[row] = -lp_multipliers[row];
// There should be no BASIC status, but they could be imprecision
// in the GetUnitRowLeftInverse() code? not sure, so better be safe.
const auto status = simplex_.GetConstraintStatus(row);
if (status == glop::ConstraintStatus::BASIC) {
VLOG(1) << "BASIC row not expected! " << lp_multipliers[row];
lp_multipliers[row] = 0.0;
}
magnitude = std::max(magnitude, std::abs(lp_multipliers[row]));
if (lp_multipliers[row] != 0.0) ++num_non_zeros;
}
if (num_non_zeros == 0) continue;
Fractional scaling;
// TODO(user): We use a lower value here otherwise we might run into
// overflow while computing the cut. This should be fixable.
const std::vector<std::pair<RowIndex, IntegerValue>> integer_multipliers =
ScaleLpMultiplier(/*take_objective_into_account=*/false,
/*use_constraint_status=*/true, lp_multipliers,
&scaling, /*max_pow=*/52);
AddCutFromConstraints("CG", integer_multipliers);
}
}
void LinearProgrammingConstraint::AddMirCuts() {
CHECK_EQ(trail_->CurrentDecisionLevel(), 0);
const RowIndex num_rows = lp_data_.num_constraints();
for (RowIndex row(0); row < num_rows; ++row) {
const auto status = simplex_.GetConstraintStatus(row);
if (status == glop::ConstraintStatus::BASIC) continue;
if (status == glop::ConstraintStatus::FREE) continue;
// TODO(user): Do not consider just one constraint, but take linear
// combination of a small number of constraints. There is a lot of
// literature on the possible heuristics here.
std::vector<std::pair<RowIndex, IntegerValue>> integer_multipliers;
integer_multipliers.push_back({row, IntegerValue(1)});
AddCutFromConstraints("MIR1", integer_multipliers);
}
}
void LinearProgrammingConstraint::UpdateSimplexIterationLimit(
const int64 min_iter, const int64 max_iter) {
if (sat_parameters_.linearization_level() < 2) return;
const int64 num_degenerate_columns = CalculateDegeneracy();
const int64 num_cols = simplex_.GetProblemNumCols().value();
if (num_cols <= 0) {
return;
}
CHECK_GT(num_cols, 0);
const bool is_degenerate = num_degenerate_columns >= 0.3 * num_cols;
const int64 decrease_factor = (10 * num_degenerate_columns) / num_cols;
if (simplex_.GetProblemStatus() == glop::ProblemStatus::DUAL_FEASIBLE) {
// We reached here probably because we predicted wrong. We use this as a
// signal to increase the iterations or punish less for degeneracy compare
// to the other part.
if (is_degenerate) {
next_simplex_iter_ /= std::max(int64{1}, decrease_factor);
} else {
next_simplex_iter_ *= 2;
}
} else if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
if (is_degenerate) {
next_simplex_iter_ /= std::max(int64{1}, 2 * decrease_factor);
} else {
// This is the most common case. We use the size of the problem to
// determine the limit and ignore the previous limit.
next_simplex_iter_ = num_cols / 40;
}
}
next_simplex_iter_ =
std::max(min_iter, std::min(max_iter, next_simplex_iter_));
}
bool LinearProgrammingConstraint::Propagate() {
UpdateBoundsOfLpVariables();
// TODO(user): It seems the time we loose by not stopping early might be worth
// it because we end up with a better explanation at optimality.
glop::GlopParameters parameters = simplex_.GetParameters();
if (/* DISABLES CODE */ (false) && objective_is_defined_) {
// We put a limit on the dual objective since there is no point increasing
// it past our current objective upper-bound (we will already fail as soon
// as we pass it). Note that this limit is properly transformed using the
// objective scaling factor and offset stored in lp_data_.
//
// Note that we use a bigger epsilon here to be sure that if we abort
// because of this, we will report a conflict.
parameters.set_objective_upper_limit(
static_cast<double>(integer_trail_->UpperBound(objective_cp_).value() +
100.0 * kCpEpsilon));
}
// Put an iteration limit on the work we do in the simplex for this call. Note
// that because we are "incremental", even if we don't solve it this time we
// will make progress towards a solve in the lower node of the tree search.
if (trail_->CurrentDecisionLevel() == 0) {
// TODO(user): Dynamically change the iteration limit for root node as
// well.
parameters.set_max_number_of_iterations(2000);
} else {
parameters.set_max_number_of_iterations(next_simplex_iter_);
}
if (sat_parameters_.use_exact_lp_reason()) {
parameters.set_change_status_to_imprecise(false);
parameters.set_primal_feasibility_tolerance(1e-7);
parameters.set_dual_feasibility_tolerance(1e-7);
}
simplex_.SetParameters(parameters);
simplex_.NotifyThatMatrixIsUnchangedForNextSolve();
if (!SolveLp()) return true;
// Add new constraints to the LP and resolve?
//
// TODO(user): We might want to do that more than once. Currently we rely on
// this beeing called again on the next IncrementalPropagate() call, but that
// might not always happen at level zero.
if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
// First add any new lazy constraints or cuts that where previsouly
// generated and are now cutting the current solution.
if (constraint_manager_.ChangeLp(expanded_lp_solution_)) {
CreateLpFromConstraintManager();
if (!SolveLp()) return true;
} else if (constraint_manager_.num_cuts() <
sat_parameters_.max_num_cuts()) {
const int old_num_cuts = constraint_manager_.num_cuts();
// The "generic" cuts are currently part of this class as they are using
// data from the current LP.
//
// TODO(user): Refactor so that they are just normal cut generators?
if (trail_->CurrentDecisionLevel() == 0) {
if (sat_parameters_.add_mir_cuts()) AddMirCuts();
if (sat_parameters_.add_cg_cuts()) AddCGCuts();
}
// Try to add cuts.
if (!cut_generators_.empty() &&
(trail_->CurrentDecisionLevel() == 0 ||
!sat_parameters_.only_add_cuts_at_level_zero())) {
for (const CutGenerator& generator : cut_generators_) {
generator.generate_cuts(expanded_lp_solution_, &constraint_manager_);
}
}
if (constraint_manager_.num_cuts() > old_num_cuts &&
constraint_manager_.ChangeLp(expanded_lp_solution_)) {
CreateLpFromConstraintManager();
const double old_obj = simplex_.GetObjectiveValue();
if (!SolveLp()) return true;
if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
VLOG(1) << "Cuts relaxation improvement " << old_obj << " -> "
<< simplex_.GetObjectiveValue()
<< " diff: " << simplex_.GetObjectiveValue() - old_obj;
}
} else {
if (trail_->CurrentDecisionLevel() == 0) {
lp_at_level_zero_is_final_ = true;
}
}
}
}
// A dual-unbounded problem is infeasible. We use the dual ray reason.
if (simplex_.GetProblemStatus() == glop::ProblemStatus::DUAL_UNBOUNDED) {
if (sat_parameters_.use_exact_lp_reason()) {
if (!FillExactDualRayReason()) return true;
} else {
FillDualRayReason();
}
return integer_trail_->ReportConflict(integer_reason_);
}
// TODO(user): Update limits for DUAL_UNBOUNDED status as well.
UpdateSimplexIterationLimit(/*min_iter=*/10, /*max_iter=*/1000);
// Optimality deductions if problem has an objective.
if (objective_is_defined_ &&
(simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL ||
simplex_.GetProblemStatus() == glop::ProblemStatus::DUAL_FEASIBLE)) {
// Try to filter optimal objective value. Note that GetObjectiveValue()
// already take care of the scaling so that it returns an objective in the
// CP world.
const double relaxed_optimal_objective = simplex_.GetObjectiveValue();
const IntegerValue approximate_new_lb(
static_cast<int64>(std::ceil(relaxed_optimal_objective - kCpEpsilon)));
// TODO(user): Maybe do a bit less computation when we cannot propagate
// anything.
if (sat_parameters_.use_exact_lp_reason()) {
if (!ExactLpReasonning()) return false;
// Display when the inexact bound would have propagated more.
const IntegerValue propagated_lb =
integer_trail_->LowerBound(objective_cp_);
if (approximate_new_lb > propagated_lb) {
VLOG(1) << "LP objective [ " << ToDouble(propagated_lb) << ", "
<< ToDouble(integer_trail_->UpperBound(objective_cp_))
<< " ] approx_lb += "
<< ToDouble(approximate_new_lb - propagated_lb);
}
} else {
FillReducedCostsReason();
const double objective_cp_ub =
ToDouble(integer_trail_->UpperBound(objective_cp_));
ReducedCostStrengtheningDeductions(objective_cp_ub -
relaxed_optimal_objective);
if (!deductions_.empty()) {
deductions_reason_ = integer_reason_;
deductions_reason_.push_back(
integer_trail_->UpperBoundAsLiteral(objective_cp_));
}
// Push new objective lb.
if (approximate_new_lb > integer_trail_->LowerBound(objective_cp_)) {
const IntegerLiteral deduction =
IntegerLiteral::GreaterOrEqual(objective_cp_, approximate_new_lb);
if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
return false;
}
}
// Push reduced cost strengthening bounds.
if (!deductions_.empty()) {
const int trail_index_with_same_reason = integer_trail_->Index();
for (const IntegerLiteral deduction : deductions_) {
if (!integer_trail_->Enqueue(deduction, {}, deductions_reason_,
trail_index_with_same_reason)) {
return false;
}
}
}
}
}
// Copy more info about the current solution.
if (simplex_.GetProblemStatus() == glop::ProblemStatus::OPTIMAL) {
CHECK(lp_solution_is_set_);
lp_objective_ = simplex_.GetObjectiveValue();
lp_solution_is_integer_ = true;
const int num_vars = integer_variables_.size();
const double objective_scale = lp_data_.objective_scaling_factor();
for (int i = 0; i < num_vars; i++) {
// The reduced cost need to be divided by LpToCpScalingFactor().
lp_reduced_cost_[i] = simplex_.GetReducedCost(glop::ColIndex(i)) *
CpToLpScalingFactor(glop::ColIndex(i)) *
objective_scale;
if (std::abs(lp_solution_[i] - std::round(lp_solution_[i])) >
kCpEpsilon) {
lp_solution_is_integer_ = false;
}
}
if (compute_reduced_cost_averages_) {
// Decay averages.
num_calls_since_reduced_cost_averages_reset_++;
if (num_calls_since_reduced_cost_averages_reset_ == 10000) {
for (int i = 0; i < num_vars; i++) {
sum_cost_up_[i] /= 2;
num_cost_up_[i] /= 2;
sum_cost_down_[i] /= 2;
num_cost_down_[i] /= 2;
}
num_calls_since_reduced_cost_averages_reset_ = 0;
}
// Accumulate pseudo-costs of all unassigned variables.
for (int i = 0; i < num_vars; i++) {
const IntegerVariable var = this->integer_variables_[i];
// Skip ignored and fixed variables.
if (integer_trail_->IsCurrentlyIgnored(var)) continue;
const IntegerValue lb = integer_trail_->LowerBound(var);
const IntegerValue ub = integer_trail_->UpperBound(var);
if (lb == ub) continue;
// Skip reduced costs that are zero or close.
const double rc = this->GetSolutionReducedCost(var);
if (std::abs(rc) < kCpEpsilon) continue;
if (rc < 0.0) {
sum_cost_down_[i] -= rc;
num_cost_down_[i]++;
} else {
sum_cost_up_[i] += rc;
num_cost_up_[i]++;
}
}
}
}
return true;
}
// Returns kMinIntegerValue in case of overflow.
//
// TODO(user): Because of PreventOverflow(), this should actually never happen.
IntegerValue LinearProgrammingConstraint::GetImpliedLowerBound(
const LinearConstraint& terms) const {
IntegerValue lower_bound(0);
const int size = terms.vars.size();
for (int i = 0; i < size; ++i) {
const IntegerVariable var = terms.vars[i];
const IntegerValue coeff = terms.coeffs[i];
CHECK_NE(coeff, 0);
const IntegerValue bound = coeff > 0 ? integer_trail_->LowerBound(var)
: integer_trail_->UpperBound(var);
if (!AddProductTo(bound, coeff, &lower_bound)) return kMinIntegerValue;
}
return lower_bound;
}
bool LinearProgrammingConstraint::PossibleOverflow(
const LinearConstraint& constraint) {
IntegerValue lower_bound(0);
const int size = constraint.vars.size();
for (int i = 0; i < size; ++i) {
const IntegerVariable var = constraint.vars[i];
const IntegerValue coeff = constraint.coeffs[i];
CHECK_NE(coeff, 0);
const IntegerValue bound = coeff > 0 ? integer_trail_->LowerBound(var)
: integer_trail_->UpperBound(var);
if (!AddProductTo(bound, coeff, &lower_bound)) {
return true;
}
}
const int64 slack = CapAdd(lower_bound.value(), -constraint.ub.value());
if (slack == kint64min || slack == kint64max) {
return true;
}
return false;
}
namespace {
absl::int128 FloorRatio128(absl::int128 x, IntegerValue positive_div) {
absl::int128 div128(positive_div.value());
absl::int128 result = x / div128;
if (result * div128 > x) return result - 1;
return result;
}
} // namespace
void LinearProgrammingConstraint::PreventOverflow(LinearConstraint* constraint,
int max_pow) {
// Compute the min/max possible partial sum.
double sum_min = std::min(0.0, ToDouble(-constraint->ub));
double sum_max = std::max(0.0, ToDouble(-constraint->ub));
const int size = constraint->vars.size();
for (int i = 0; i < size; ++i) {
const IntegerVariable var = constraint->vars[i];
const double coeff = ToDouble(constraint->coeffs[i]);
const double prod1 = coeff * ToDouble(integer_trail_->LowerBound(var));
const double prod2 = coeff * ToDouble(integer_trail_->UpperBound(var));
sum_min += std::min(0.0, std::min(prod1, prod2));
sum_max += std::max(0.0, std::max(prod1, prod2));
}
const double max_value = std::max(sum_max, -sum_min);
const IntegerValue divisor(std::ceil(std::ldexp(max_value, -max_pow)));
if (divisor <= 1) return;
// To be correct, we need to shift all variable so that they are positive.
//
// TODO(user): This code is tricky and similar to the one to generate cuts.
// Test and may reduce the duplication? note however that here we use int128
// to deal with potential overflow.
int new_size = 0;
absl::int128 adjust = 0;
for (int i = 0; i < size; ++i) {
const IntegerValue old_coeff = constraint->coeffs[i];
const IntegerValue new_coeff = FloorRatio(old_coeff, divisor);
// Compute the rhs adjustement.
const absl::int128 remainder =
absl::int128(old_coeff.value()) -
absl::int128(new_coeff.value()) * absl::int128(divisor.value());
adjust +=
remainder *
absl::int128(integer_trail_->LowerBound(constraint->vars[i]).value());
if (new_coeff == 0) continue;
constraint->vars[new_size] = constraint->vars[i];
constraint->coeffs[new_size] = new_coeff;
++new_size;
}
constraint->vars.resize(new_size);
constraint->coeffs.resize(new_size);
constraint->ub = IntegerValue(static_cast<int64>(
FloorRatio128(absl::int128(constraint->ub.value()) - adjust, divisor)));
}
// TODO(user): combine this with RelaxLinearReason() to avoid the extra
// magnitude vector and the weird precondition of RelaxLinearReason().
void LinearProgrammingConstraint::SetImpliedLowerBoundReason(
const LinearConstraint& terms, IntegerValue slack) {
integer_reason_.clear();
std::vector<IntegerValue> magnitudes;
const int size = terms.vars.size();
for (int i = 0; i < size; ++i) {
const IntegerVariable var = terms.vars[i];
const IntegerValue coeff = terms.coeffs[i];
CHECK_NE(coeff, 0);
if (coeff > 0) {