forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_programming_constraint.cc
2685 lines (2411 loc) · 104 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-2022 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/sat/linear_programming_constraint.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <functional>
#include <limits>
#include <memory>
#include <numeric>
#include <random>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.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/algorithms/binary_search.h"
#include "ortools/base/logging.h"
#include "ortools/base/mathutil.h"
#include "ortools/base/strong_vector.h"
#include "ortools/glop/parameters.pb.h"
#include "ortools/glop/revised_simplex.h"
#include "ortools/glop/status.h"
#include "ortools/glop/variables_info.h"
#include "ortools/lp_data/lp_data.h"
#include "ortools/lp_data/lp_data_utils.h"
#include "ortools/lp_data/lp_types.h"
#include "ortools/lp_data/scattered_vector.h"
#include "ortools/lp_data/sparse_column.h"
#include "ortools/sat/cuts.h"
#include "ortools/sat/implied_bounds.h"
#include "ortools/sat/integer.h"
#include "ortools/sat/integer_expr.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/sat_parameters.pb.h"
#include "ortools/sat/sat_solver.h"
#include "ortools/sat/synchronization.h"
#include "ortools/sat/util.h"
#include "ortools/sat/zero_half_cuts.h"
#include "ortools/util/bitset.h"
#include "ortools/util/rev.h"
#include "ortools/util/saturated_arithmetic.h"
#include "ortools/util/strong_integers.h"
#include "ortools/util/time_limit.h"
namespace operations_research {
namespace sat {
using glop::ColIndex;
using glop::Fractional;
using glop::RowIndex;
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_t add = CapAdd(value.value(), dense_vector_[col].value());
if (add == std::numeric_limits<int64_t>::min() ||
add == std::numeric_limits<int64_t>::max())
return false;
dense_vector_[col] = IntegerValue(add);
if (is_sparse_ && is_zeros_[col]) {
is_zeros_[col] = false;
non_zeros_.push_back(col);
}
return true;
}
template <bool check_overflow>
bool ScatteredIntegerVector::AddLinearExpressionMultiple(
const 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 (check_overflow) {
if (!AddProductTo(multiplier, term.second,
&dense_vector_[term.first])) {
return false;
}
} else {
dense_vector_[term.first] += multiplier * term.second;
}
}
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 (check_overflow) {
if (!AddProductTo(multiplier, term.second,
&dense_vector_[term.first])) {
return false;
}
} else {
dense_vector_[term.first] += multiplier * term.second;
}
}
}
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;
}
void ScatteredIntegerVector::ConvertToCutData(
absl::int128 rhs, const std::vector<IntegerVariable>& integer_variables,
const std::vector<double>& lp_solution, IntegerTrail* integer_trail,
CutData* result) {
result->terms.clear();
result->rhs = rhs;
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;
const IntegerVariable var = integer_variables[col.value()];
CHECK(result->AppendOneTerm(var, coeff, lp_solution[col.value()],
integer_trail->LevelZeroLowerBound(var),
integer_trail->LevelZeroUpperBound(var)));
}
} 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;
const IntegerVariable var = integer_variables[col.value()];
CHECK(result->AppendOneTerm(var, coeff, lp_solution[col.value()],
integer_trail->LevelZeroLowerBound(var),
integer_trail->LevelZeroUpperBound(var)));
}
}
}
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, absl::Span<const IntegerVariable> vars)
: constraint_manager_(model),
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<ModelLpValues>()) {
// Tweak the default parameters to make the solve incremental.
simplex_params_.set_use_dual_simplex(true);
simplex_params_.set_cost_scaling(glop::GlopParameters::MEAN_COST_SCALING);
simplex_params_.set_primal_feasibility_tolerance(
parameters_.lp_primal_tolerance());
simplex_params_.set_dual_feasibility_tolerance(
parameters_.lp_dual_tolerance());
if (parameters_.use_exact_lp_reason()) {
simplex_params_.set_change_status_to_imprecise(false);
}
simplex_.SetParameters(simplex_params_);
if (parameters_.use_branching_in_lp() ||
parameters_.search_branching() == SatParameters::LP_SEARCH) {
compute_reduced_cost_averages_ = true;
}
// Register our local rev int repository.
integer_trail_->RegisterReversibleClass(&rc_rev_int_repository_);
// Register SharedStatistics with the cut helpers.
auto* stats = model->GetOrCreate<SharedStatistics>();
integer_rounding_cut_helper_.SetSharedStatistics(stats);
flow_cover_cut_helper_.SetSharedStatistics(stats);
cover_cut_helper_.SetSharedStatistics(stats);
// Initialize the IntegerVariable -> ColIndex mapping.
CHECK(std::is_sorted(vars.begin(), vars.end()));
integer_variables_.assign(vars.begin(), vars.end());
ColIndex col{0};
for (const IntegerVariable positive_variable : vars) {
CHECK(VariableIsPositive(positive_variable));
implied_bounds_processor_.AddLpVariable(positive_variable);
(*dispatcher_)[positive_variable] = this;
mirror_lp_variable_[positive_variable] = col;
++col;
}
lp_solution_.assign(vars.size(), std::numeric_limits<double>::infinity());
lp_reduced_cost_.assign(vars.size(), 0.0);
if (!vars.empty()) {
const int max_index = NegationOf(vars.back()).value();
if (max_index >= expanded_lp_solution_.size()) {
expanded_lp_solution_.assign(max_index + 1, 0.0);
}
}
}
void LinearProgrammingConstraint::AddLinearConstraint(LinearConstraint ct) {
DCHECK(!lp_constraint_is_registered_);
constraint_manager_.Add(std::move(ct));
}
glop::ColIndex LinearProgrammingConstraint::GetMirrorVariable(
IntegerVariable positive_variable) {
DCHECK(VariableIsPositive(positive_variable));
return mirror_lp_variable_.at(positive_variable);
}
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 = GetMirrorVariable(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() {
simplex_.NotifyThatMatrixIsChangedForNextSolve();
// 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;
new_ct.lb_is_trivial = all_constraints[index].lb_is_trivial;
new_ct.ub_is_trivial = all_constraints[index].ub_is_trivial;
const int size = ct.vars.size();
if (ct.lb > ct.ub) {
VLOG(1) << "Trivial infeasible bound in an LP constraint";
return false;
}
IntegerValue infinity_norm = 0;
infinity_norm = std::max(infinity_norm, IntTypeAbs(ct.lb));
infinity_norm = std::max(infinity_norm, IntTypeAbs(ct.ub));
new_ct.terms.reserve(size);
for (int i = 0; i < size; ++i) {
// We only use positive variable inside this class.
const IntegerVariable var = ct.vars[i];
const IntegerValue coeff = ct.coeffs[i];
infinity_norm = std::max(infinity_norm, IntTypeAbs(coeff));
new_ct.terms.push_back({GetMirrorVariable(var), coeff});
}
infinity_norms_.push_back(infinity_norm);
// It is important to keep lp_data_ "clean".
DCHECK(std::is_sorted(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();
// TODO(user): Using trivial bound might be good for things like
// sum bool <= 1 since setting the slack in [0, 1] can lead to bound flip in
// the simplex. However if the bound is large, maybe it make more sense to
// use +/- infinity.
const double infinity = std::numeric_limits<double>::infinity();
lp_data_.SetConstraintBounds(
row, ct.lb_is_trivial ? -infinity : ToDouble(ct.lb),
ct.ub_is_trivial ? +infinity : 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.
scaler_.Scale(simplex_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 (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();
VLOG(3) << "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_t>(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 = GetMirrorVariable(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 (!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) {
// Get rid of all optimal constraint each time we go back to level zero.
if (level == 0) rev_optimal_constraints_size_ = 0;
optimal_constraints_.resize(rev_optimal_constraints_size_);
cumulative_optimal_constraint_sizes_.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) {
cut_generators_.push_back(std::move(generator));
}
bool LinearProgrammingConstraint::IncrementalPropagate(
const std::vector<int>& watch_indices) {
// If we have a really deep branch, with a lot of LP explanation constraint,
// we could take a quadratic amount of memory: O(num_var) per number of
// propagation in that branch. To avoid that, once the memory starts to be
// over a few GB, we only propagate from time to time. This way we do not need
// to keep that many constraints around.
//
// Note that 100 Millions int32_t variables, with the int128 coefficients and
// extra propagation vector is already a few GB.
if (!cumulative_optimal_constraint_sizes_.empty()) {
const double current_size =
static_cast<double>(cumulative_optimal_constraint_sizes_.back());
const double low_limit = 1e7;
if (current_size > low_limit) {
// We only propagate if we use less that 100 times the number of current
// integer literal enqueued.
const double num_enqueues = static_cast<double>(integer_trail_->Index());
if ((current_size - low_limit) > 100 * num_enqueues) return true;
}
}
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_[mirror_lp_variable_.at(variable).value()];
}
double LinearProgrammingConstraint::GetSolutionReducedCost(
IntegerVariable variable) const {
return lp_reduced_cost_[mirror_lp_variable_.at(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();
}
// By default we assume the matrix is unchanged.
// This will be reset by CreateLpFromConstraintManager().
simplex_.NotifyThatMatrixIsUnchangedForNextSolve();
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_++;
num_solves_by_status_[status_as_int]++;
VLOG(2) << lp_data_.GetDimensionString()
<< " 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::AnalyzeLp() {
// A dual-unbounded problem is infeasible. We use the dual ray reason.
if (simplex_.GetProblemStatus() == glop::ProblemStatus::DUAL_UNBOUNDED) {
if (parameters_.use_exact_lp_reason()) {
return PropagateExactDualRay();
}
FillReducedCostReasonIn(simplex_.GetDualRayRowCombination(),
&integer_reason_);
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)) {
// TODO(user): Maybe do a bit less computation when we cannot propagate
// anything.
if (parameters_.use_exact_lp_reason()) {
if (!PropagateExactLpReason()) return false;
// Display when the inexact bound would have propagated more.
if (VLOG_IS_ON(2)) {
const double relaxed_optimal_objective = simplex_.GetObjectiveValue();
const IntegerValue approximate_new_lb(static_cast<int64_t>(
std::ceil(relaxed_optimal_objective - kCpEpsilon)));
const IntegerValue propagated_lb =
integer_trail_->LowerBound(objective_cp_);
if (approximate_new_lb > propagated_lb) {
VLOG(2) << "LP objective [ " << ToDouble(propagated_lb) << ", "
<< ToDouble(integer_trail_->UpperBound(objective_cp_))
<< " ] approx_lb += "
<< ToDouble(approximate_new_lb - propagated_lb) << " gap: "
<< integer_trail_->UpperBound(objective_cp_) - propagated_lb;
}
}
} else {
// 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.
FillReducedCostReasonIn(simplex_.GetReducedCosts(), &integer_reason_);
const double objective_cp_ub =
ToDouble(integer_trail_->UpperBound(objective_cp_));
const double relaxed_optimal_objective = simplex_.GetObjectiveValue();
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.
const IntegerValue approximate_new_lb(static_cast<int64_t>(
std::ceil(relaxed_optimal_objective - kCpEpsilon)));
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();
for (int i = 0; i < num_vars; i++) {
lp_reduced_cost_[i] = scaler_.UnscaleReducedCost(
glop::ColIndex(i), simplex_.GetReducedCost(glop::ColIndex(i)));
if (std::abs(lp_solution_[i] - std::round(lp_solution_[i])) >
kCpEpsilon) {
lp_solution_is_integer_ = false;
}
}
if (compute_reduced_cost_averages_) {
UpdateAverageReducedCosts();
}
}
return true;
}
// Note that since we call this on the constraint with slack, we actually have
// linear expression == rhs, we can use this to propagate more!
//
// TODO(user): Also propagate on -cut ? in practice we already do that in many
// places were we try to generate the cut on -cut... But we coould do it sooner
// and more cleanly here.
bool LinearProgrammingConstraint::PreprocessCut(IntegerVariable first_slack,
CutData* cut) {
// Because of complement, all coeffs and all terms are positive after this.
cut->ComplementForPositiveCoefficients();
if (cut->rhs < 0) {
problem_proven_infeasible_by_cuts_ = true;
return false;
}
// Limited DP to compute first few reachable values.
// Note that all coeff are positive.
reachable_.Reset();
for (const CutTerm& term : cut->terms) {
reachable_.Add(term.coeff.value());
}
// Extra propag since we know it is actually an equality constraint.
if (cut->rhs < absl::int128(reachable_.LastValue()) &&
!reachable_.MightBeReachable(static_cast<int64_t>(cut->rhs))) {
problem_proven_infeasible_by_cuts_ = true;
return false;
}
bool some_fixed_terms = false;
bool some_relevant_positions = false;
for (CutTerm& term : cut->terms) {
const absl::int128 magnitude128 = term.coeff.value();
const absl::int128 range =
absl::int128(term.bound_diff.value()) * magnitude128;
IntegerValue new_diff = term.bound_diff;
if (range > cut->rhs) {
new_diff = static_cast<int64_t>(cut->rhs / magnitude128);
}
{
// Extra propag since we know it is actually an equality constraint.
absl::int128 rest128 =
cut->rhs - absl::int128(new_diff.value()) * magnitude128;
while (rest128 < absl::int128(reachable_.LastValue()) &&
!reachable_.MightBeReachable(static_cast<int64_t>(rest128))) {
++total_num_eq_propagations_;
CHECK_GT(new_diff, 0);
--new_diff;
rest128 += magnitude128;
}
}
if (new_diff < term.bound_diff) {
term.bound_diff = new_diff;
const IntegerVariable var = term.expr_vars[0];
if (var < first_slack) {
// Normal variable.
++total_num_cut_propagations_;
// Note that at this stage we only have X - lb or ub - X.
if (term.expr_coeffs[0] == 1) {
// X + offset <= bound_diff
if (!integer_trail_->Enqueue(
IntegerLiteral::LowerOrEqual(
var, term.bound_diff - term.expr_offset),
{}, {})) {
problem_proven_infeasible_by_cuts_ = true;
return false;
}
} else {
CHECK_EQ(term.expr_coeffs[0], -1);
// offset - X <= bound_diff
if (!integer_trail_->Enqueue(
IntegerLiteral::GreaterOrEqual(
var, term.expr_offset - term.bound_diff),
{}, {})) {
problem_proven_infeasible_by_cuts_ = true;
return false;
}
}
} else {
// This is a tighter bound on one of the constraint! like a cut. Note
// that in some corner case, new cut can be merged and update the bounds
// of the constraint before this code.
const int slack_index = (var.value() - first_slack.value()) / 2;
const glop::RowIndex row = tmp_slack_rows_[slack_index];
if (term.expr_coeffs[0] == 1) {
// slack = ct + offset <= bound_diff;
const IntegerValue new_ub = term.bound_diff - term.expr_offset;
if (constraint_manager_.UpdateConstraintUb(row, new_ub)) {
integer_lp_[row].ub = new_ub;
}
} else {
// slack = offset - ct <= bound_diff;
CHECK_EQ(term.expr_coeffs[0], -1);
const IntegerValue new_lb = term.expr_offset - term.bound_diff;
if (constraint_manager_.UpdateConstraintLb(row, new_lb)) {
integer_lp_[row].lb = new_lb;
}
}
}
}
if (term.bound_diff == 0) {
some_fixed_terms = true;
} else {
if (term.HasRelevantLpValue()) {
some_relevant_positions = true;
}
}
}