forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 3
/
linear_programming_constraint.cc
2809 lines (2526 loc) · 109 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 <algorithm>
#include <cmath>
#include <iterator>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/numeric/int128.h"
#include "ortools/base/commandlineflags.h"
#include "ortools/base/integral_types.h"
#include "ortools/base/logging.h"
#include "ortools/base/map_util.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/stl_util.h"
#include "ortools/base/strong_vector.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/sat/implied_bounds.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/zero_half_cuts.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;
void ScatteredIntegerVector::ClearAndResize(int size) {
if (is_sparse_) {
for (const glop::ColIndex col : non_zeros_) {
dense_vector_[col] = IntegerValue(0);
}
dense_vector_.resize(size, IntegerValue(0));
} else {
dense_vector_.assign(size, IntegerValue(0));
}
for (const glop::ColIndex col : non_zeros_) {
is_zeros_[col] = true;
}
is_zeros_.resize(size, true);
non_zeros_.clear();
is_sparse_ = true;
}
bool ScatteredIntegerVector::Add(glop::ColIndex col, IntegerValue value) {
const int64 add = CapAdd(value.value(), dense_vector_[col].value());
if (add == kint64min || add == kint64max) return false;
dense_vector_[col] = IntegerValue(add);
if (is_sparse_ && is_zeros_[col]) {
is_zeros_[col] = false;
non_zeros_.push_back(col);
}
return true;
}
bool ScatteredIntegerVector::AddLinearExpressionMultiple(
IntegerValue multiplier,
const std::vector<std::pair<glop::ColIndex, IntegerValue>>& terms) {
const double threshold = 0.1 * static_cast<double>(dense_vector_.size());
if (is_sparse_ && static_cast<double>(terms.size()) < threshold) {
for (const std::pair<glop::ColIndex, IntegerValue> term : terms) {
if (is_zeros_[term.first]) {
is_zeros_[term.first] = false;
non_zeros_.push_back(term.first);
}
if (!AddProductTo(multiplier, term.second, &dense_vector_[term.first])) {
return false;
}
}
if (static_cast<double>(non_zeros_.size()) < threshold) {
is_sparse_ = false;
}
} else {
is_sparse_ = false;
for (const std::pair<glop::ColIndex, IntegerValue> term : terms) {
if (!AddProductTo(multiplier, term.second, &dense_vector_[term.first])) {
return false;
}
}
}
return true;
}
void ScatteredIntegerVector::ConvertToLinearConstraint(
const std::vector<IntegerVariable>& integer_variables,
IntegerValue upper_bound, LinearConstraint* result) {
result->vars.clear();
result->coeffs.clear();
if (is_sparse_) {
std::sort(non_zeros_.begin(), non_zeros_.end());
for (const glop::ColIndex col : non_zeros_) {
const IntegerValue coeff = dense_vector_[col];
if (coeff == 0) continue;
result->vars.push_back(integer_variables[col.value()]);
result->coeffs.push_back(coeff);
}
} else {
const int size = dense_vector_.size();
for (glop::ColIndex col(0); col < size; ++col) {
const IntegerValue coeff = dense_vector_[col];
if (coeff == 0) continue;
result->vars.push_back(integer_variables[col.value()]);
result->coeffs.push_back(coeff);
}
}
result->lb = kMinIntegerValue;
result->ub = upper_bound;
}
std::vector<std::pair<glop::ColIndex, IntegerValue>>
ScatteredIntegerVector::GetTerms() {
std::vector<std::pair<glop::ColIndex, IntegerValue>> result;
if (is_sparse_) {
std::sort(non_zeros_.begin(), non_zeros_.end());
for (const glop::ColIndex col : non_zeros_) {
const IntegerValue coeff = dense_vector_[col];
if (coeff != 0) result.push_back({col, coeff});
}
} else {
const int size = dense_vector_.size();
for (glop::ColIndex col(0); col < size; ++col) {
const IntegerValue coeff = dense_vector_[col];
if (coeff != 0) result.push_back({col, coeff});
}
}
return result;
}
// 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>()),
integer_encoder_(model->GetOrCreate<IntegerEncoder>()),
random_(model->GetOrCreate<ModelRandomGenerator>()),
implied_bounds_processor_({}, integer_trail_,
model->GetOrCreate<ImpliedBounds>()),
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);
if (sat_parameters_.use_branching_in_lp() ||
sat_parameters_.search_branching() == SatParameters::LP_SEARCH) {
compute_reduced_cost_averages_ = true;
}
// Register our local rev int repository.
integer_trail_->RegisterReversibleClass(&rc_rev_int_repository_);
}
LinearProgrammingConstraint::~LinearProgrammingConstraint() {
VLOG(1) << "Total number of simplex iterations: "
<< total_num_simplex_iterations_;
for (int i = 0; i < num_solves_by_status_.size(); ++i) {
if (num_solves_by_status_[i] == 0) continue;
VLOG(1) << "#" << glop::ProblemStatus(i) << " : "
<< num_solves_by_status_[i];
}
}
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());
implied_bounds_processor_.AddLpVariable(positive_variable);
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;
constraint_manager_.SetObjectiveCoefficient(pos_var, 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.
//
// TODO(user): On TSP/VRP with a lot of cuts, this can take 20% of the overall
// running time. We should be able to almost remove most of this from the
// profile by being more incremental (modulo LP scaling).
//
// TODO(user): A longer term idea for LP with a lot of variables is to not
// add all variables to each LP solve and do some "sifting". That can be useful
// for TSP for instance where the number of edges is large, but only a small
// fraction will be used in the optimal solution.
bool 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].constraint;
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 > ct.ub) {
VLOG(1) << "Trivial infeasible bound in an LP constraint";
return false;
}
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());
}
// We remove fixed variables from the objective. This should help the LP
// scaling, but also our integer reason computation.
int new_size = 0;
objective_infinity_norm_ = 0;
for (const auto entry : integer_objective_) {
const IntegerVariable var = integer_variables_[entry.first.value()];
if (integer_trail_->IsFixedAtLevelZero(var)) {
integer_objective_offset_ +=
entry.second * integer_trail_->LevelZeroLowerBound(var);
continue;
}
objective_infinity_norm_ =
std::max(objective_infinity_norm_, IntTypeAbs(entry.second));
integer_objective_[new_size++] = entry;
lp_data_.SetObjectiveCoefficient(entry.first, ToDouble(entry.second));
}
objective_infinity_norm_ =
std::max(objective_infinity_norm_, IntTypeAbs(integer_objective_offset_));
integer_objective_.resize(new_size);
lp_data_.SetObjectiveOffset(ToDouble(integer_objective_offset_));
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));
}
}
lp_data_.NotifyThatColumnsAreClean();
// We scale the LP using the level zero bounds that we later override
// with the current ones.
//
// 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.
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_->LevelZeroLowerBound(cp_var));
const double ub = ToDouble(integer_trail_->LevelZeroUpperBound(cp_var));
lp_data_.SetVariableBounds(glop::ColIndex(i), lb, ub);
}
// TODO(user): As we have an idea of the LP optimal after the first solves,
// maybe we can adapt the scaling accordingly.
glop::GlopParameters params;
params.set_cost_scaling(glop::GlopParameters::MEAN_COST_SCALING);
scaler_.Scale(params, &lp_data_);
UpdateBoundsOfLpVariables();
// Set the information for the step to polish the LP basis. All our variables
// are integer, but for now, we just try to minimize the fractionality of the
// binary variables.
if (sat_parameters_.polish_lp_solution()) {
simplex_.ClearIntegralityScales();
for (int i = 0; i < num_vars; ++i) {
const IntegerVariable cp_var = integer_variables_[i];
const IntegerValue lb = integer_trail_->LevelZeroLowerBound(cp_var);
const IntegerValue ub = integer_trail_->LevelZeroUpperBound(cp_var);
if (lb != 0 || ub != 1) continue;
simplex_.SetIntegralityScale(
glop::ColIndex(i),
1.0 / scaler_.VariableScalingFactor(glop::ColIndex(i)));
}
}
lp_data_.NotifyThatColumnsAreClean();
lp_data_.AddSlackVariablesWhereNecessary(false);
VLOG(1) << "LP relaxation: " << lp_data_.GetDimensionString() << ". "
<< constraint_manager_.AllConstraints().size()
<< " Managed constraints.";
return true;
}
LPSolveInfo LinearProgrammingConstraint::SolveLpForBranching() {
LPSolveInfo info;
glop::BasisState basis_state = simplex_.GetState();
const glop::Status status = simplex_.Solve(lp_data_, time_limit_);
total_num_simplex_iterations_ += simplex_.GetNumberOfIterations();
simplex_.LoadStateForNextSolve(basis_state);
if (!status.ok()) {
VLOG(1) << "The LP solver encountered an error: " << status.error_message();
info.status = glop::ProblemStatus::ABNORMAL;
return info;
}
info.status = simplex_.GetProblemStatus();
if (info.status == glop::ProblemStatus::OPTIMAL ||
info.status == glop::ProblemStatus::DUAL_FEASIBLE) {
// Record the objective bound.
info.lp_objective = simplex_.GetObjectiveValue();
info.new_obj_bound = IntegerValue(
static_cast<int64>(std::ceil(info.lp_objective - kCpEpsilon)));
}
return info;
}
void LinearProgrammingConstraint::FillReducedCostReasonIn(
const glop::DenseRow& reduced_costs,
std::vector<IntegerLiteral>* integer_reason) {
integer_reason->clear();
const int num_vars = integer_variables_.size();
for (int i = 0; i < num_vars; i++) {
const double rc = reduced_costs[glop::ColIndex(i)];
if (rc > kLpEpsilon) {
integer_reason->push_back(
integer_trail_->LowerBoundAsLiteral(integer_variables_[i]));
} else if (rc < -kLpEpsilon) {
integer_reason->push_back(
integer_trail_->UpperBoundAsLiteral(integer_variables_[i]));
}
}
integer_trail_->RemoveLevelZeroBounds(integer_reason);
}
bool LinearProgrammingConstraint::BranchOnVar(IntegerVariable positive_var) {
// From the current LP solution, branch on the given var if fractional.
DCHECK(lp_solution_is_set_);
const double current_value = GetSolutionValue(positive_var);
DCHECK_GT(std::abs(current_value - std::round(current_value)), kCpEpsilon);
// Used as empty reason in this method.
integer_reason_.clear();
bool deductions_were_made = false;
UpdateBoundsOfLpVariables();
const IntegerValue current_obj_lb = integer_trail_->LowerBound(objective_cp_);
// This will try to branch in both direction around the LP value of the
// given variable and push any deduction done this way.
const glop::ColIndex lp_var = GetOrCreateMirrorVariable(positive_var);
const double current_lb = ToDouble(integer_trail_->LowerBound(positive_var));
const double current_ub = ToDouble(integer_trail_->UpperBound(positive_var));
const double factor = scaler_.VariableScalingFactor(lp_var);
if (current_value < current_lb || current_value > current_ub) {
return false;
}
// Form LP1 var <= floor(current_value)
const double new_ub = std::floor(current_value);
lp_data_.SetVariableBounds(lp_var, current_lb * factor, new_ub * factor);
LPSolveInfo lower_branch_info = SolveLpForBranching();
if (lower_branch_info.status != glop::ProblemStatus::OPTIMAL &&
lower_branch_info.status != glop::ProblemStatus::DUAL_FEASIBLE &&
lower_branch_info.status != glop::ProblemStatus::DUAL_UNBOUNDED) {
return false;
}
if (lower_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
// Push the other branch.
const IntegerLiteral deduction = IntegerLiteral::GreaterOrEqual(
positive_var, IntegerValue(std::ceil(current_value)));
if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
return false;
}
deductions_were_made = true;
} else if (lower_branch_info.new_obj_bound <= current_obj_lb) {
return false;
}
// Form LP2 var >= ceil(current_value)
const double new_lb = std::ceil(current_value);
lp_data_.SetVariableBounds(lp_var, new_lb * factor, current_ub * factor);
LPSolveInfo upper_branch_info = SolveLpForBranching();
if (upper_branch_info.status != glop::ProblemStatus::OPTIMAL &&
upper_branch_info.status != glop::ProblemStatus::DUAL_FEASIBLE &&
upper_branch_info.status != glop::ProblemStatus::DUAL_UNBOUNDED) {
return deductions_were_made;
}
if (upper_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
// Push the other branch if not infeasible.
if (lower_branch_info.status != glop::ProblemStatus::DUAL_UNBOUNDED) {
const IntegerLiteral deduction = IntegerLiteral::LowerOrEqual(
positive_var, IntegerValue(std::floor(current_value)));
if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
return deductions_were_made;
}
deductions_were_made = true;
}
} else if (upper_branch_info.new_obj_bound <= current_obj_lb) {
return deductions_were_made;
}
IntegerValue approximate_obj_lb = kMinIntegerValue;
if (lower_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED &&
upper_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
return integer_trail_->ReportConflict(integer_reason_);
} else if (lower_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
approximate_obj_lb = upper_branch_info.new_obj_bound;
} else if (upper_branch_info.status == glop::ProblemStatus::DUAL_UNBOUNDED) {
approximate_obj_lb = lower_branch_info.new_obj_bound;
} else {
approximate_obj_lb = std::min(lower_branch_info.new_obj_bound,
upper_branch_info.new_obj_bound);
}
// NOTE: On some problems, the approximate_obj_lb could be inexact which add
// some tolerance to CP-SAT where currently there is none.
if (approximate_obj_lb <= current_obj_lb) return deductions_were_made;
// Push the bound to the trail.
const IntegerLiteral deduction =
IntegerLiteral::GreaterOrEqual(objective_cp_, approximate_obj_lb);
if (!integer_trail_->Enqueue(deduction, {}, integer_reason_)) {
return deductions_were_made;
}
return true;
}
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();
}
if (!CreateLpFromConstraintManager()) {
model->GetOrCreate<SatSolver>()->NotifyThatModelIsUnsat();
return;
}
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);
// 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::GetVariableValueAtCpScale(
glop::ColIndex var) {
return scaler_.UnscaleVariableValue(var, simplex_.GetVariableValue(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 = scaler_.VariableScalingFactor(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_);
total_num_simplex_iterations_ += simplex_.GetNumberOfIterations();
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(2) << "High average degeneracy: "
<< average_degeneracy_.CurrentAverage();
}
const int status_as_int = static_cast<int>(simplex_.GetProblemStatus());
if (status_as_int >= num_solves_by_status_.size()) {
num_solves_by_status_.resize(status_as_int + 1);
}
num_solves_by_status_[status_as_int]++;
VLOG(2) << "lvl:" << trail_->CurrentDecisionLevel() << " "
<< simplex_.GetProblemStatus()
<< " iter:" << simplex_.GetNumberOfIterations()
<< " obj:" << simplex_.GetObjectiveValue();
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;
}
bool 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): For CG cuts, 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.
IntegerValue cut_ub;
if (!ComputeNewLinearConstraint(integer_multipliers, &tmp_scattered_vector_,
&cut_ub)) {
VLOG(1) << "Issue, overflow!";
return false;
}
// Important: because we use integer_multipliers below, we cannot just
// divide by GCD or call PreventOverflow() here.
//
// TODO(user): the conversion col_index -> IntegerVariable is slow and could
// in principle be removed. Easy for cuts, but not so much for
// implied_bounds_processor_. Note that in theory this could allow us to
// use Literal directly without the need to have an IntegerVariable for them.
tmp_scattered_vector_.ConvertToLinearConstraint(integer_variables_, cut_ub,
&cut_);
// Note that the base constraint we use are currently always tight.
// It is not a requirement though.
if (DEBUG_MODE) {
const double norm = ToDouble(ComputeInfinityNorm(cut_));
const double activity = ComputeActivity(cut_, expanded_lp_solution_);
if (std::abs(activity - ToDouble(cut_.ub)) / norm > 1e-4) {
VLOG(1) << "Cut not tight " << activity << " <= " << ToDouble(cut_.ub);
return false;
}
}
CHECK(constraint_manager_.DebugCheckConstraint(cut_));
// We will create "artificial" variables after this index that will be
// substitued back into LP variables afterwards. Also not that we only use
// positive variable indices for these new variables, so that algorithm that
// take their negation will not mess up the indexing.
const IntegerVariable first_new_var(expanded_lp_solution_.size());
CHECK_EQ(first_new_var.value() % 2, 0);
LinearConstraint copy_in_debug;
if (DEBUG_MODE) {
copy_in_debug = cut_;
}
// Unlike for the knapsack cuts, it might not be always beneficial to
// process the implied bounds even though it seems to be better in average.
//
// TODO(user): Perform more experiments, in particular with which bound we use
// and if we complement or not before the MIR rounding. Other solvers seems
// to try different complementation strategies in a "potprocessing" and we
// don't. Try this too.
std::vector<ImpliedBoundsProcessor::SlackInfo> ib_slack_infos;
implied_bounds_processor_.ProcessUpperBoundedConstraintWithSlackCreation(
/*substitute_only_inner_variables=*/false, first_new_var,
expanded_lp_solution_, &cut_, &ib_slack_infos);
DCHECK(implied_bounds_processor_.DebugSlack(first_new_var, copy_in_debug,
cut_, ib_slack_infos));
// 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. For now this is only called at level zero anyway.
tmp_lp_values_.clear();
tmp_var_lbs_.clear();
tmp_var_ubs_.clear();
for (const IntegerVariable var : cut_.vars) {
if (var >= first_new_var) {
CHECK(VariableIsPositive(var));
const auto& info =
ib_slack_infos[(var.value() - first_new_var.value()) / 2];
tmp_lp_values_.push_back(info.lp_value);
tmp_var_lbs_.push_back(info.lb);
tmp_var_ubs_.push_back(info.ub);
} else {
tmp_lp_values_.push_back(expanded_lp_solution_[var]);
tmp_var_lbs_.push_back(integer_trail_->LevelZeroLowerBound(var));
tmp_var_ubs_.push_back(integer_trail_->LevelZeroUpperBound(var));
}
}
// Add slack.
// definition: integer_lp_[row] + slack_row == bound;
const IntegerVariable first_slack(first_new_var +
IntegerVariable(2 * ib_slack_infos.size()));
tmp_slack_rows_.clear();
tmp_slack_bounds_.clear();
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;
tmp_lp_values_.push_back(0.0);
cut_.vars.push_back(first_slack +
2 * IntegerVariable(tmp_slack_rows_.size()));
tmp_slack_rows_.push_back(row);
cut_.coeffs.push_back(coeff);
const IntegerValue diff(
CapSub(integer_lp_[row].ub.value(), integer_lp_[row].lb.value()));
if (coeff > 0) {
tmp_slack_bounds_.push_back(integer_lp_[row].ub);
tmp_var_lbs_.push_back(IntegerValue(0));
tmp_var_ubs_.push_back(diff);
} else {
tmp_slack_bounds_.push_back(integer_lp_[row].lb);
tmp_var_lbs_.push_back(-diff);
tmp_var_ubs_.push_back(IntegerValue(0));
}
}
bool at_least_one_added = false;
// Try cover appraoch to find cut.
{
if (cover_cut_helper_.TrySimpleKnapsack(cut_, tmp_lp_values_, tmp_var_lbs_,
tmp_var_ubs_)) {
at_least_one_added |= PostprocessAndAddCut(
absl::StrCat(name, "_K"), cover_cut_helper_.Info(), first_new_var,
first_slack, ib_slack_infos, cover_cut_helper_.mutable_cut());
}
}
// Try integer rounding heuristic to find cut.
{
RoundingOptions options;
options.max_scaling = sat_parameters_.max_integer_rounding_scaling();
integer_rounding_cut_helper_.ComputeCut(options, tmp_lp_values_,
tmp_var_lbs_, tmp_var_ubs_,
&implied_bounds_processor_, &cut_);
at_least_one_added |= PostprocessAndAddCut(
name,
absl::StrCat("num_lifted_booleans=",
integer_rounding_cut_helper_.NumLiftedBooleans()),
first_new_var, first_slack, ib_slack_infos, &cut_);
}
return at_least_one_added;
}
bool LinearProgrammingConstraint::PostprocessAndAddCut(
const std::string& name, const std::string& info,
IntegerVariable first_new_var, IntegerVariable first_slack,
const std::vector<ImpliedBoundsProcessor::SlackInfo>& ib_slack_infos,
LinearConstraint* cut) {
// Compute the activity. Warning: the cut no longer have the same size so we
// cannot use tmp_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_new_var) {
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(3) << "Bad cut " << activity << " <= " << ToDouble(cut->ub);
return false;
}
// Substitute any slack left.
{
int num_slack = 0;
tmp_scattered_vector_.ClearAndResize(integer_variables_.size());
IntegerValue cut_ub = cut->ub;
bool overflow = false;
for (int i = 0; i < cut->vars.size(); ++i) {
const IntegerVariable var = cut->vars[i];
// Simple copy for non-slack variables.
if (var < first_new_var) {
const glop::ColIndex col =
gtl::FindOrDie(mirror_lp_variable_, PositiveVariable(var));
if (VariableIsPositive(var)) {
tmp_scattered_vector_.Add(col, cut->coeffs[i]);
} else {
tmp_scattered_vector_.Add(col, -cut->coeffs[i]);
}
continue;
}
// Replace slack from bound substitution.
if (var < first_slack) {
const IntegerValue multiplier = cut->coeffs[i];
const int index = (var.value() - first_new_var.value()) / 2;
CHECK_LT(index, ib_slack_infos.size());
std::vector<std::pair<ColIndex, IntegerValue>> terms;
for (const std::pair<IntegerVariable, IntegerValue>& term :
ib_slack_infos[index].terms) {
terms.push_back(
{gtl::FindOrDie(mirror_lp_variable_,
PositiveVariable(term.first)),
VariableIsPositive(term.first) ? term.second : -term.second});
}
if (!tmp_scattered_vector_.AddLinearExpressionMultiple(multiplier,
terms)) {
overflow = true;
break;
}
if (!AddProductTo(multiplier, -ib_slack_infos[index].offset, &cut_ub)) {
overflow = true;
break;
}
continue;
}
// Replace slack from LP constraints.
++num_slack;
const int slack_index = (var.value() - first_slack.value()) / 2;
const glop::RowIndex row = tmp_slack_rows_[slack_index];
const IntegerValue multiplier = -cut->coeffs[i];
if (!tmp_scattered_vector_.AddLinearExpressionMultiple(
multiplier, integer_lp_[row].terms)) {
overflow = true;
break;
}
// Update rhs.
if (!AddProductTo(multiplier, tmp_slack_bounds_[slack_index], &cut_ub)) {
overflow = true;
break;
}
}
if (overflow) {
VLOG(1) << "Overflow in slack removal.";
return false;
}
VLOG(3) << " num_slack: " << num_slack;
tmp_scattered_vector_.ConvertToLinearConstraint(integer_variables_, cut_ub,
cut);
}
// Display some stats used for investigation of cut generation.
const std::string extra_info =
absl::StrCat(info, " num_ib_substitutions=", ib_slack_infos.size());
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);
return constraint_manager_.AddCut(*cut, name, expanded_lp_solution_,
extra_info);
}
void LinearProgrammingConstraint::AddCGCuts() {
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;
// 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;
if (time_limit_->LimitReached()) break;
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 (std::abs(lp_multipliers[row]) < 1e-12) {
lp_multipliers[row] = 0.0;
continue;
}
// 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;
for (int i = 0; i < 2; ++i) {