forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lp_data.cc
1571 lines (1419 loc) · 59 KB
/
lp_data.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/lp_data/lp_data.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <string>
#include <utility>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "ortools/base/logging.h"
#include "ortools/base/strong_vector.h"
#include "ortools/lp_data/lp_print_utils.h"
#include "ortools/lp_data/lp_utils.h"
#include "ortools/lp_data/matrix_utils.h"
#include "ortools/lp_data/permutation.h"
namespace operations_research {
namespace glop {
namespace {
// This should be the same as DCHECK(AreBoundsValid()), but the DCHECK() are
// split to give more meaningful information to the user in case of failure.
void DebugCheckBoundsValid(Fractional lower_bound, Fractional upper_bound) {
DCHECK(!std::isnan(lower_bound));
DCHECK(!std::isnan(upper_bound));
DCHECK(!(lower_bound == kInfinity && upper_bound == kInfinity));
DCHECK(!(lower_bound == -kInfinity && upper_bound == -kInfinity));
DCHECK_LE(lower_bound, upper_bound);
DCHECK(AreBoundsValid(lower_bound, upper_bound));
}
// Returns true if the bounds are the ones of a free or boxed row. Note that
// a fixed row is not counted as boxed.
bool AreBoundsFreeOrBoxed(Fractional lower_bound, Fractional upper_bound) {
if (lower_bound == -kInfinity && upper_bound == kInfinity) return true;
if (lower_bound != -kInfinity && upper_bound != kInfinity &&
lower_bound != upper_bound) {
return true;
}
return false;
}
template <class I, class T>
double Average(const absl::StrongVector<I, T>& v) {
const size_t size = v.size();
DCHECK_LT(0, size);
double sum = 0.0;
double n = 0.0; // n is used in a calculation involving doubles.
for (I i(0); i < size; ++i) {
if (v[i] == 0.0) continue;
++n;
sum += static_cast<double>(v[i].value());
}
return n == 0.0 ? 0.0 : sum / n;
}
template <class I, class T>
double StandardDeviation(const absl::StrongVector<I, T>& v) {
const size_t size = v.size();
double n = 0.0; // n is used in a calculation involving doubles.
double sigma_square = 0.0;
double sigma = 0.0;
for (I i(0); i < size; ++i) {
double sample = static_cast<double>(v[i].value());
if (sample == 0.0) continue;
sigma_square += sample * sample;
sigma += sample;
++n;
}
return n == 0.0 ? 0.0 : sqrt((sigma_square - sigma * sigma / n) / n);
}
// Returns 0 when the vector is empty.
template <class I, class T>
T GetMaxElement(const absl::StrongVector<I, T>& v) {
const size_t size = v.size();
if (size == 0) {
return T(0);
}
T max_index = v[I(0)];
for (I i(1); i < size; ++i) {
if (max_index < v[i]) {
max_index = v[i];
}
}
return max_index;
}
} // anonymous namespace
// --------------------------------------------------------
// LinearProgram
// --------------------------------------------------------
LinearProgram::LinearProgram()
: matrix_(),
transpose_matrix_(),
constraint_lower_bounds_(),
constraint_upper_bounds_(),
constraint_names_(),
objective_coefficients_(),
variable_lower_bounds_(),
variable_upper_bounds_(),
variable_names_(),
variable_types_(),
integer_variables_list_(),
variable_table_(),
constraint_table_(),
objective_offset_(0.0),
objective_scaling_factor_(1.0),
maximize_(false),
columns_are_known_to_be_clean_(true),
transpose_matrix_is_consistent_(true),
integer_variables_list_is_consistent_(true),
name_(),
first_slack_variable_(kInvalidCol) {}
void LinearProgram::Clear() {
matrix_.Clear();
transpose_matrix_.Clear();
constraint_lower_bounds_.clear();
constraint_upper_bounds_.clear();
constraint_names_.clear();
objective_coefficients_.clear();
variable_lower_bounds_.clear();
variable_upper_bounds_.clear();
variable_types_.clear();
integer_variables_list_.clear();
variable_names_.clear();
constraint_table_.clear();
variable_table_.clear();
maximize_ = false;
objective_offset_ = 0.0;
objective_scaling_factor_ = 1.0;
columns_are_known_to_be_clean_ = true;
transpose_matrix_is_consistent_ = true;
integer_variables_list_is_consistent_ = true;
name_.clear();
first_slack_variable_ = kInvalidCol;
}
ColIndex LinearProgram::CreateNewVariable() {
DCHECK_EQ(kInvalidCol, first_slack_variable_)
<< "New variables can't be added to programs that already have slack "
"variables. Consider calling LinearProgram::DeleteSlackVariables() "
"before adding new variables to the problem.";
objective_coefficients_.push_back(0.0);
variable_lower_bounds_.push_back(0);
variable_upper_bounds_.push_back(kInfinity);
variable_types_.push_back(VariableType::CONTINUOUS);
variable_names_.push_back("");
transpose_matrix_is_consistent_ = false;
return matrix_.AppendEmptyColumn();
}
ColIndex LinearProgram::CreateNewSlackVariable(bool is_integer_slack_variable,
Fractional lower_bound,
Fractional upper_bound,
const std::string& name) {
objective_coefficients_.push_back(0.0);
variable_lower_bounds_.push_back(lower_bound);
variable_upper_bounds_.push_back(upper_bound);
variable_types_.push_back(is_integer_slack_variable
? (VariableType::IMPLIED_INTEGER)
: (VariableType::CONTINUOUS));
variable_names_.push_back(name);
transpose_matrix_is_consistent_ = false;
return matrix_.AppendEmptyColumn();
}
RowIndex LinearProgram::CreateNewConstraint() {
DCHECK_EQ(kInvalidCol, first_slack_variable_)
<< "New constraints can't be added to programs that already have slack "
"variables. Consider calling LinearProgram::DeleteSlackVariables() "
"before adding new variables to the problem.";
const RowIndex row(constraint_names_.size());
matrix_.SetNumRows(row + 1);
constraint_lower_bounds_.push_back(Fractional(0.0));
constraint_upper_bounds_.push_back(Fractional(0.0));
constraint_names_.push_back("");
transpose_matrix_is_consistent_ = false;
return row;
}
ColIndex LinearProgram::FindOrCreateVariable(const std::string& variable_id) {
const absl::flat_hash_map<std::string, ColIndex>::iterator it =
variable_table_.find(variable_id);
if (it != variable_table_.end()) {
return it->second;
} else {
const ColIndex col = CreateNewVariable();
variable_names_[col] = variable_id;
variable_table_[variable_id] = col;
return col;
}
}
RowIndex LinearProgram::FindOrCreateConstraint(
const std::string& constraint_id) {
const absl::flat_hash_map<std::string, RowIndex>::iterator it =
constraint_table_.find(constraint_id);
if (it != constraint_table_.end()) {
return it->second;
} else {
const RowIndex row = CreateNewConstraint();
constraint_names_[row] = constraint_id;
constraint_table_[constraint_id] = row;
return row;
}
}
void LinearProgram::SetVariableName(ColIndex col, absl::string_view name) {
variable_names_[col] = std::string(name);
}
void LinearProgram::SetVariableType(ColIndex col, VariableType type) {
const bool var_was_integer = IsVariableInteger(col);
variable_types_[col] = type;
const bool var_is_integer = IsVariableInteger(col);
if (var_is_integer != var_was_integer) {
integer_variables_list_is_consistent_ = false;
}
}
void LinearProgram::SetConstraintName(RowIndex row, absl::string_view name) {
constraint_names_[row] = std::string(name);
}
void LinearProgram::SetVariableBounds(ColIndex col, Fractional lower_bound,
Fractional upper_bound) {
if (dcheck_bounds_) DebugCheckBoundsValid(lower_bound, upper_bound);
const bool var_was_binary = IsVariableBinary(col);
variable_lower_bounds_[col] = lower_bound;
variable_upper_bounds_[col] = upper_bound;
const bool var_is_binary = IsVariableBinary(col);
if (var_is_binary != var_was_binary) {
integer_variables_list_is_consistent_ = false;
}
}
void LinearProgram::UpdateAllIntegerVariableLists() const {
if (integer_variables_list_is_consistent_) return;
integer_variables_list_.clear();
binary_variables_list_.clear();
non_binary_variables_list_.clear();
const ColIndex num_cols = num_variables();
for (ColIndex col(0); col < num_cols; ++col) {
if (IsVariableInteger(col)) {
integer_variables_list_.push_back(col);
if (IsVariableBinary(col)) {
binary_variables_list_.push_back(col);
} else {
non_binary_variables_list_.push_back(col);
}
}
}
integer_variables_list_is_consistent_ = true;
}
const std::vector<ColIndex>& LinearProgram::IntegerVariablesList() const {
UpdateAllIntegerVariableLists();
return integer_variables_list_;
}
const std::vector<ColIndex>& LinearProgram::BinaryVariablesList() const {
UpdateAllIntegerVariableLists();
return binary_variables_list_;
}
const std::vector<ColIndex>& LinearProgram::NonBinaryVariablesList() const {
UpdateAllIntegerVariableLists();
return non_binary_variables_list_;
}
bool LinearProgram::IsVariableInteger(ColIndex col) const {
return variable_types_[col] == VariableType::INTEGER ||
variable_types_[col] == VariableType::IMPLIED_INTEGER;
}
bool LinearProgram::IsVariableBinary(ColIndex col) const {
// TODO(user): bounds of binary variables (and of integer ones) should
// be integer. Add a preprocessor for that.
return IsVariableInteger(col) && (variable_lower_bounds_[col] < kEpsilon) &&
(variable_lower_bounds_[col] > Fractional(-1)) &&
(variable_upper_bounds_[col] > Fractional(1) - kEpsilon) &&
(variable_upper_bounds_[col] < 2);
}
void LinearProgram::SetConstraintBounds(RowIndex row, Fractional lower_bound,
Fractional upper_bound) {
if (dcheck_bounds_) DebugCheckBoundsValid(lower_bound, upper_bound);
ResizeRowsIfNeeded(row);
constraint_lower_bounds_[row] = lower_bound;
constraint_upper_bounds_[row] = upper_bound;
}
void LinearProgram::SetCoefficient(RowIndex row, ColIndex col,
Fractional value) {
DCHECK(IsFinite(value));
ResizeRowsIfNeeded(row);
columns_are_known_to_be_clean_ = false;
transpose_matrix_is_consistent_ = false;
matrix_.mutable_column(col)->SetCoefficient(row, value);
}
void LinearProgram::SetObjectiveCoefficient(ColIndex col, Fractional value) {
DCHECK(IsFinite(value));
objective_coefficients_[col] = value;
}
void LinearProgram::SetObjectiveOffset(Fractional objective_offset) {
DCHECK(IsFinite(objective_offset));
objective_offset_ = objective_offset;
}
void LinearProgram::SetObjectiveScalingFactor(
Fractional objective_scaling_factor) {
DCHECK(IsFinite(objective_scaling_factor));
DCHECK_NE(0.0, objective_scaling_factor);
objective_scaling_factor_ = objective_scaling_factor;
}
void LinearProgram::SetMaximizationProblem(bool maximize) {
maximize_ = maximize;
}
void LinearProgram::CleanUp() {
if (columns_are_known_to_be_clean_) return;
matrix_.CleanUp();
columns_are_known_to_be_clean_ = true;
transpose_matrix_is_consistent_ = false;
}
bool LinearProgram::IsCleanedUp() const {
if (columns_are_known_to_be_clean_) return true;
columns_are_known_to_be_clean_ = matrix_.IsCleanedUp();
return columns_are_known_to_be_clean_;
}
std::string LinearProgram::GetVariableName(ColIndex col) const {
return col >= variable_names_.size() || variable_names_[col].empty()
? absl::StrFormat("c%d", col.value())
: variable_names_[col];
}
std::string LinearProgram::GetConstraintName(RowIndex row) const {
return row >= constraint_names_.size() || constraint_names_[row].empty()
? absl::StrFormat("r%d", row.value())
: constraint_names_[row];
}
LinearProgram::VariableType LinearProgram::GetVariableType(ColIndex col) const {
return variable_types_[col];
}
const SparseMatrix& LinearProgram::GetTransposeSparseMatrix() const {
if (!transpose_matrix_is_consistent_) {
transpose_matrix_.PopulateFromTranspose(matrix_);
transpose_matrix_is_consistent_ = true;
}
DCHECK_EQ(transpose_matrix_.num_rows().value(), matrix_.num_cols().value());
DCHECK_EQ(transpose_matrix_.num_cols().value(), matrix_.num_rows().value());
return transpose_matrix_;
}
SparseMatrix* LinearProgram::GetMutableTransposeSparseMatrix() {
if (!transpose_matrix_is_consistent_) {
transpose_matrix_.PopulateFromTranspose(matrix_);
}
// This enables a client to start modifying the matrix and then abort and not
// call UseTransposeMatrixAsReference(). Then, the other client of
// GetTransposeSparseMatrix() will still see the correct matrix.
transpose_matrix_is_consistent_ = false;
return &transpose_matrix_;
}
void LinearProgram::UseTransposeMatrixAsReference() {
DCHECK_EQ(transpose_matrix_.num_rows().value(), matrix_.num_cols().value());
DCHECK_EQ(transpose_matrix_.num_cols().value(), matrix_.num_rows().value());
matrix_.PopulateFromTranspose(transpose_matrix_);
transpose_matrix_is_consistent_ = true;
}
void LinearProgram::ClearTransposeMatrix() {
transpose_matrix_.Clear();
transpose_matrix_is_consistent_ = false;
}
const SparseColumn& LinearProgram::GetSparseColumn(ColIndex col) const {
return matrix_.column(col);
}
SparseColumn* LinearProgram::GetMutableSparseColumn(ColIndex col) {
columns_are_known_to_be_clean_ = false;
transpose_matrix_is_consistent_ = false;
return matrix_.mutable_column(col);
}
Fractional LinearProgram::GetObjectiveCoefficientForMinimizationVersion(
ColIndex col) const {
return maximize_ ? -objective_coefficients()[col]
: objective_coefficients()[col];
}
std::string LinearProgram::GetDimensionString() const {
Fractional min_magnitude = 0.0;
Fractional max_magnitude = 0.0;
matrix_.ComputeMinAndMaxMagnitudes(&min_magnitude, &max_magnitude);
return absl::StrFormat(
"%d rows, %d columns, %d entries with magnitude in [%e, %e]",
num_constraints().value(), num_variables().value(),
// static_cast<int64_t> is needed because the Android port uses int32_t.
static_cast<int64_t>(num_entries().value()), min_magnitude,
max_magnitude);
}
namespace {
template <typename FractionalValues>
void UpdateStats(const FractionalValues& values, int64_t* num_non_zeros,
Fractional* min_value, Fractional* max_value) {
for (const Fractional v : values) {
if (v == 0 || v == kInfinity || v == -kInfinity) continue;
*min_value = std::min(*min_value, v);
*max_value = std::max(*max_value, v);
++(*num_non_zeros);
}
}
} // namespace
std::string LinearProgram::GetObjectiveStatsString() const {
int64_t num_non_zeros = 0;
Fractional min_value = +kInfinity;
Fractional max_value = -kInfinity;
UpdateStats(objective_coefficients_, &num_non_zeros, &min_value, &max_value);
if (num_non_zeros == 0) {
return "No objective term. This is a pure feasibility problem.";
} else {
return absl::StrFormat("%d non-zeros, range [%e, %e]", num_non_zeros,
min_value, max_value);
}
}
std::string LinearProgram::GetBoundsStatsString() const {
int64_t num_non_zeros = 0;
Fractional min_value = +kInfinity;
Fractional max_value = -kInfinity;
UpdateStats(variable_lower_bounds_, &num_non_zeros, &min_value, &max_value);
UpdateStats(variable_upper_bounds_, &num_non_zeros, &min_value, &max_value);
UpdateStats(constraint_lower_bounds_, &num_non_zeros, &min_value, &max_value);
UpdateStats(constraint_upper_bounds_, &num_non_zeros, &min_value, &max_value);
if (num_non_zeros == 0) {
return "All variables/constraints bounds are zero or +/- infinity.";
} else {
return absl::StrFormat("%d non-zeros, range [%e, %e]", num_non_zeros,
min_value, max_value);
}
}
bool LinearProgram::SolutionIsWithinVariableBounds(
const DenseRow& solution, Fractional absolute_tolerance) const {
DCHECK_EQ(solution.size(), num_variables());
if (solution.size() != num_variables()) return false;
const ColIndex num_cols = num_variables();
for (ColIndex col = ColIndex(0); col < num_cols; ++col) {
if (!IsFinite(solution[col])) return false;
const Fractional lb_error = variable_lower_bounds()[col] - solution[col];
const Fractional ub_error = solution[col] - variable_upper_bounds()[col];
if (lb_error > absolute_tolerance || ub_error > absolute_tolerance) {
return false;
}
}
return true;
}
bool LinearProgram::SolutionIsLPFeasible(const DenseRow& solution,
Fractional absolute_tolerance) const {
if (!SolutionIsWithinVariableBounds(solution, absolute_tolerance)) {
return false;
}
const SparseMatrix& transpose = GetTransposeSparseMatrix();
const RowIndex num_rows = num_constraints();
for (RowIndex row = RowIndex(0); row < num_rows; ++row) {
const Fractional sum =
ScalarProduct(solution, transpose.column(RowToColIndex(row)));
if (!IsFinite(sum)) return false;
const Fractional lb_error = constraint_lower_bounds()[row] - sum;
const Fractional ub_error = sum - constraint_upper_bounds()[row];
if (lb_error > absolute_tolerance || ub_error > absolute_tolerance) {
return false;
}
}
return true;
}
bool LinearProgram::SolutionIsInteger(const DenseRow& solution,
Fractional absolute_tolerance) const {
DCHECK_EQ(solution.size(), num_variables());
if (solution.size() != num_variables()) return false;
for (ColIndex col : IntegerVariablesList()) {
if (!IsFinite(solution[col])) return false;
const Fractional fractionality = fabs(solution[col] - round(solution[col]));
if (fractionality > absolute_tolerance) return false;
}
return true;
}
bool LinearProgram::SolutionIsMIPFeasible(const DenseRow& solution,
Fractional absolute_tolerance) const {
return SolutionIsLPFeasible(solution, absolute_tolerance) &&
SolutionIsInteger(solution, absolute_tolerance);
}
void LinearProgram::ComputeSlackVariableValues(DenseRow* solution) const {
CHECK(solution != nullptr);
const ColIndex num_cols = GetFirstSlackVariable();
const SparseMatrix& transpose = GetTransposeSparseMatrix();
const RowIndex num_rows = num_constraints();
CHECK_EQ(solution->size(), num_variables());
for (RowIndex row = RowIndex(0); row < num_rows; ++row) {
const Fractional sum = PartialScalarProduct(
*solution, transpose.column(RowToColIndex(row)), num_cols.value());
const ColIndex slack_variable = GetSlackVariable(row);
CHECK_NE(slack_variable, kInvalidCol);
(*solution)[slack_variable] = -sum;
}
}
Fractional LinearProgram::ApplyObjectiveScalingAndOffset(
Fractional value) const {
return objective_scaling_factor() * (value + objective_offset());
}
Fractional LinearProgram::RemoveObjectiveScalingAndOffset(
Fractional value) const {
return value / objective_scaling_factor() - objective_offset();
}
std::string LinearProgram::Dump() const {
// Objective line.
std::string output = maximize_ ? "max:" : "min:";
if (objective_offset_ != 0.0) {
output += Stringify(objective_offset_);
}
const ColIndex num_cols = num_variables();
for (ColIndex col(0); col < num_cols; ++col) {
const Fractional coeff = objective_coefficients()[col];
if (coeff != 0.0) {
output += StringifyMonomial(coeff, GetVariableName(col), false);
}
}
output.append(";\n");
// Constraints.
const RowIndex num_rows = num_constraints();
for (RowIndex row(0); row < num_rows; ++row) {
const Fractional lower_bound = constraint_lower_bounds()[row];
const Fractional upper_bound = constraint_upper_bounds()[row];
output += GetConstraintName(row);
output += ":";
if (AreBoundsFreeOrBoxed(lower_bound, upper_bound)) {
output += " ";
output += Stringify(lower_bound);
output += " <=";
}
for (ColIndex col(0); col < num_cols; ++col) {
const Fractional coeff = matrix_.LookUpValue(row, col);
output += StringifyMonomial(coeff, GetVariableName(col), false);
}
if (AreBoundsFreeOrBoxed(lower_bound, upper_bound)) {
output += " <= ";
output += Stringify(upper_bound);
} else if (lower_bound == upper_bound) {
output += " = ";
output += Stringify(upper_bound);
} else if (lower_bound != -kInfinity) {
output += " >= ";
output += Stringify(lower_bound);
} else if (lower_bound != kInfinity) {
output += " <= ";
output += Stringify(upper_bound);
}
output += ";\n";
}
// Variables.
for (ColIndex col(0); col < num_cols; ++col) {
const Fractional lower_bound = variable_lower_bounds()[col];
const Fractional upper_bound = variable_upper_bounds()[col];
if (AreBoundsFreeOrBoxed(lower_bound, upper_bound)) {
output += Stringify(lower_bound);
output += " <= ";
}
output += GetVariableName(col);
if (AreBoundsFreeOrBoxed(lower_bound, upper_bound)) {
output += " <= ";
output += Stringify(upper_bound);
} else if (lower_bound == upper_bound) {
output += " = ";
output += Stringify(upper_bound);
} else if (lower_bound != -kInfinity) {
output += " >= ";
output += Stringify(lower_bound);
} else if (lower_bound != kInfinity) {
output += " <= ";
output += Stringify(upper_bound);
}
output += ";\n";
}
// Integer variables.
// TODO(user): if needed provide similar output for binary variables.
const std::vector<ColIndex>& integer_variables = IntegerVariablesList();
if (!integer_variables.empty()) {
output += "int";
for (ColIndex col : integer_variables) {
output += " ";
output += GetVariableName(col);
}
output += ";\n";
}
return output;
}
std::string LinearProgram::DumpSolution(const DenseRow& variable_values) const {
DCHECK_EQ(variable_values.size(), num_variables());
std::string output;
for (ColIndex col(0); col < variable_values.size(); ++col) {
if (!output.empty()) absl::StrAppend(&output, ", ");
absl::StrAppend(&output, GetVariableName(col), " = ",
(variable_values[col]));
}
return output;
}
std::string LinearProgram::GetProblemStats() const {
return ProblemStatFormatter(
"%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,"
"%d,%d,%d,%d");
}
std::string LinearProgram::GetPrettyProblemStats() const {
return ProblemStatFormatter(
"Number of rows : %d\n"
"Number of variables in file : %d\n"
"Number of entries (non-zeros) : %d\n"
"Number of entries in the objective : %d\n"
"Number of entries in the right-hand side : %d\n"
"Number of <= constraints : %d\n"
"Number of >= constraints : %d\n"
"Number of = constraints : %d\n"
"Number of range constraints : %d\n"
"Number of non-negative variables : %d\n"
"Number of boxed variables : %d\n"
"Number of free variables : %d\n"
"Number of fixed variables : %d\n"
"Number of other variables : %d\n"
"Number of integer variables : %d\n"
"Number of binary variables : %d\n"
"Number of non-binary integer variables : %d\n"
"Number of continuous variables : %d\n");
}
std::string LinearProgram::GetNonZeroStats() const {
return NonZeroStatFormatter("%.2f%%,%d,%.2f,%.2f,%d,%.2f,%.2f");
}
std::string LinearProgram::GetPrettyNonZeroStats() const {
return NonZeroStatFormatter(
"Fill rate : %.2f%%\n"
"Entries in row (Max / average / std. dev.) : %d / %.2f / %.2f\n"
"Entries in column (Max / average / std. dev.): %d / %.2f / %.2f\n");
}
void LinearProgram::AddSlackVariablesWhereNecessary(
bool detect_integer_constraints) {
// Clean up the matrix. We're going to add entries, but we'll only be adding
// them to new columns, and only one entry per column, which does not
// invalidate the "cleanness" of the matrix.
CleanUp();
// Detect which constraints produce an integer slack variable. A constraint
// has an integer slack variable, if it contains only integer variables with
// integer coefficients. We do not check the bounds of the constraints,
// because in such case, they will be tightened to integer values by the
// preprocessors.
//
// We don't use the transpose, because it might not be valid and it would be
// inefficient to update it and invalidate it again at the end of this
// preprocessor.
DenseBooleanColumn has_integer_slack_variable(num_constraints(),
detect_integer_constraints);
if (detect_integer_constraints) {
for (ColIndex col(0); col < num_variables(); ++col) {
const SparseColumn& column = matrix_.column(col);
const bool is_integer_variable = IsVariableInteger(col);
for (const SparseColumn::Entry& entry : column) {
const RowIndex row = entry.row();
has_integer_slack_variable[row] =
has_integer_slack_variable[row] && is_integer_variable &&
round(entry.coefficient()) == entry.coefficient();
}
}
}
// Extend the matrix of the problem with an identity matrix.
const ColIndex original_num_variables = num_variables();
for (RowIndex row(0); row < num_constraints(); ++row) {
ColIndex slack_variable_index = GetSlackVariable(row);
if (slack_variable_index != kInvalidCol &&
slack_variable_index < original_num_variables) {
// Slack variable is already present in this constraint.
continue;
}
const ColIndex slack_col = CreateNewSlackVariable(
has_integer_slack_variable[row], -constraint_upper_bounds_[row],
-constraint_lower_bounds_[row], absl::StrCat("s", row.value()));
SetCoefficient(row, slack_col, 1.0);
SetConstraintBounds(row, 0.0, 0.0);
}
columns_are_known_to_be_clean_ = true;
transpose_matrix_is_consistent_ = false;
if (first_slack_variable_ == kInvalidCol) {
first_slack_variable_ = original_num_variables;
}
}
ColIndex LinearProgram::GetFirstSlackVariable() const {
return first_slack_variable_;
}
ColIndex LinearProgram::GetSlackVariable(RowIndex row) const {
DCHECK_GE(row, RowIndex(0));
DCHECK_LT(row, num_constraints());
if (first_slack_variable_ == kInvalidCol) {
return kInvalidCol;
}
return first_slack_variable_ + RowToColIndex(row);
}
void LinearProgram::PopulateFromDual(const LinearProgram& dual,
RowToColMapping* duplicated_rows) {
const ColIndex dual_num_variables = dual.num_variables();
const RowIndex dual_num_constraints = dual.num_constraints();
Clear();
// We always take the dual in its minimization form thanks to the
// GetObjectiveCoefficientForMinimizationVersion() below, so this will always
// be a maximization problem.
SetMaximizationProblem(true);
// Taking the dual does not change the offset nor the objective scaling
// factor.
SetObjectiveOffset(dual.objective_offset());
SetObjectiveScalingFactor(dual.objective_scaling_factor());
// Create the dual variables y, with bounds depending on the type
// of constraints in the primal.
for (RowIndex dual_row(0); dual_row < dual_num_constraints; ++dual_row) {
CreateNewVariable();
const ColIndex col = RowToColIndex(dual_row);
const Fractional lower_bound = dual.constraint_lower_bounds()[dual_row];
const Fractional upper_bound = dual.constraint_upper_bounds()[dual_row];
if (lower_bound == upper_bound) {
SetVariableBounds(col, -kInfinity, kInfinity);
SetObjectiveCoefficient(col, lower_bound);
} else if (upper_bound != kInfinity) {
// Note that for a ranged constraint, the loop will be continued here.
// This is wanted because we want to deal with the lower_bound afterwards.
SetVariableBounds(col, -kInfinity, 0.0);
SetObjectiveCoefficient(col, upper_bound);
} else if (lower_bound != -kInfinity) {
SetVariableBounds(col, 0.0, kInfinity);
SetObjectiveCoefficient(col, lower_bound);
} else {
// This code does not support free rows in linear_program.
LOG(DFATAL) << "PopulateFromDual() was called with a program "
<< "containing free constraints.";
}
}
// Create the dual slack variables v.
for (ColIndex dual_col(0); dual_col < dual_num_variables; ++dual_col) {
const Fractional lower_bound = dual.variable_lower_bounds()[dual_col];
if (lower_bound != -kInfinity) {
const ColIndex col = CreateNewVariable();
SetObjectiveCoefficient(col, lower_bound);
SetVariableBounds(col, 0.0, kInfinity);
const RowIndex row = ColToRowIndex(dual_col);
SetCoefficient(row, col, Fractional(1.0));
}
}
// Create the dual surplus variables w.
for (ColIndex dual_col(0); dual_col < dual_num_variables; ++dual_col) {
const Fractional upper_bound = dual.variable_upper_bounds()[dual_col];
if (upper_bound != kInfinity) {
const ColIndex col = CreateNewVariable();
SetObjectiveCoefficient(col, upper_bound);
SetVariableBounds(col, -kInfinity, 0.0);
const RowIndex row = ColToRowIndex(dual_col);
SetCoefficient(row, col, Fractional(1.0));
}
}
// Store the transpose of the matrix.
for (ColIndex dual_col(0); dual_col < dual_num_variables; ++dual_col) {
const RowIndex row = ColToRowIndex(dual_col);
const Fractional row_bound =
dual.GetObjectiveCoefficientForMinimizationVersion(dual_col);
SetConstraintBounds(row, row_bound, row_bound);
for (const SparseColumn::Entry e : dual.GetSparseColumn(dual_col)) {
const RowIndex dual_row = e.row();
const ColIndex col = RowToColIndex(dual_row);
SetCoefficient(row, col, e.coefficient());
}
}
// Take care of ranged constraints.
duplicated_rows->assign(dual_num_constraints, kInvalidCol);
for (RowIndex dual_row(0); dual_row < dual_num_constraints; ++dual_row) {
const Fractional lower_bound = dual.constraint_lower_bounds()[dual_row];
const Fractional upper_bound = dual.constraint_upper_bounds()[dual_row];
if (AreBoundsFreeOrBoxed(lower_bound, upper_bound)) {
DCHECK(upper_bound != kInfinity || lower_bound != -kInfinity);
// upper_bound was done in a loop above, now do the lower_bound.
const ColIndex col = CreateNewVariable();
SetVariableBounds(col, 0.0, kInfinity);
SetObjectiveCoefficient(col, lower_bound);
matrix_.mutable_column(col)->PopulateFromSparseVector(
matrix_.column(RowToColIndex(dual_row)));
(*duplicated_rows)[dual_row] = col;
}
}
// We know that the columns are ordered by rows.
columns_are_known_to_be_clean_ = true;
transpose_matrix_is_consistent_ = false;
}
void LinearProgram::PopulateFromLinearProgram(
const LinearProgram& linear_program) {
matrix_.PopulateFromSparseMatrix(linear_program.matrix_);
if (linear_program.transpose_matrix_is_consistent_) {
transpose_matrix_is_consistent_ = true;
transpose_matrix_.PopulateFromSparseMatrix(
linear_program.transpose_matrix_);
} else {
transpose_matrix_is_consistent_ = false;
transpose_matrix_.Clear();
}
constraint_lower_bounds_ = linear_program.constraint_lower_bounds_;
constraint_upper_bounds_ = linear_program.constraint_upper_bounds_;
constraint_names_ = linear_program.constraint_names_;
constraint_table_.clear();
PopulateNameObjectiveAndVariablesFromLinearProgram(linear_program);
first_slack_variable_ = linear_program.first_slack_variable_;
}
void LinearProgram::PopulateFromPermutedLinearProgram(
const LinearProgram& lp, const RowPermutation& row_permutation,
const ColumnPermutation& col_permutation) {
DCHECK(lp.IsCleanedUp());
DCHECK_EQ(row_permutation.size(), lp.num_constraints());
DCHECK_EQ(col_permutation.size(), lp.num_variables());
DCHECK_EQ(lp.GetFirstSlackVariable(), kInvalidCol);
Clear();
// Populate matrix coefficients.
ColumnPermutation inverse_col_permutation;
inverse_col_permutation.PopulateFromInverse(col_permutation);
matrix_.PopulateFromPermutedMatrix(lp.matrix_, row_permutation,
inverse_col_permutation);
ClearTransposeMatrix();
// Populate constraints.
ApplyPermutation(row_permutation, lp.constraint_lower_bounds(),
&constraint_lower_bounds_);
ApplyPermutation(row_permutation, lp.constraint_upper_bounds(),
&constraint_upper_bounds_);
// Populate variables.
ApplyPermutation(col_permutation, lp.objective_coefficients(),
&objective_coefficients_);
ApplyPermutation(col_permutation, lp.variable_lower_bounds(),
&variable_lower_bounds_);
ApplyPermutation(col_permutation, lp.variable_upper_bounds(),
&variable_upper_bounds_);
ApplyPermutation(col_permutation, lp.variable_types(), &variable_types_);
integer_variables_list_is_consistent_ = false;
// There is no vector based accessor to names, because they may be created
// on the fly.
constraint_names_.resize(lp.num_constraints());
for (RowIndex old_row(0); old_row < lp.num_constraints(); ++old_row) {
const RowIndex new_row = row_permutation[old_row];
constraint_names_[new_row] = lp.constraint_names_[old_row];
}
variable_names_.resize(lp.num_variables());
for (ColIndex old_col(0); old_col < lp.num_variables(); ++old_col) {
const ColIndex new_col = col_permutation[old_col];
variable_names_[new_col] = lp.variable_names_[old_col];
}
// Populate singular fields.
maximize_ = lp.maximize_;
objective_offset_ = lp.objective_offset_;
objective_scaling_factor_ = lp.objective_scaling_factor_;
name_ = lp.name_;
}
void LinearProgram::PopulateFromLinearProgramVariables(
const LinearProgram& linear_program) {
matrix_.PopulateFromZero(RowIndex(0), linear_program.num_variables());
first_slack_variable_ = kInvalidCol;
transpose_matrix_is_consistent_ = false;
transpose_matrix_.Clear();
constraint_lower_bounds_.clear();
constraint_upper_bounds_.clear();
constraint_names_.clear();
constraint_table_.clear();
PopulateNameObjectiveAndVariablesFromLinearProgram(linear_program);
}
void LinearProgram::PopulateNameObjectiveAndVariablesFromLinearProgram(
const LinearProgram& linear_program) {
objective_coefficients_ = linear_program.objective_coefficients_;
variable_lower_bounds_ = linear_program.variable_lower_bounds_;
variable_upper_bounds_ = linear_program.variable_upper_bounds_;
variable_names_ = linear_program.variable_names_;
variable_types_ = linear_program.variable_types_;
integer_variables_list_is_consistent_ =
linear_program.integer_variables_list_is_consistent_;
integer_variables_list_ = linear_program.integer_variables_list_;
binary_variables_list_ = linear_program.binary_variables_list_;
non_binary_variables_list_ = linear_program.non_binary_variables_list_;
variable_table_.clear();
maximize_ = linear_program.maximize_;
objective_offset_ = linear_program.objective_offset_;
objective_scaling_factor_ = linear_program.objective_scaling_factor_;
columns_are_known_to_be_clean_ =
linear_program.columns_are_known_to_be_clean_;
name_ = linear_program.name_;
}
void LinearProgram::AddConstraints(
const SparseMatrix& coefficients, const DenseColumn& left_hand_sides,
const DenseColumn& right_hand_sides,
const StrictITIVector<RowIndex, std::string>& names) {
const RowIndex num_new_constraints = coefficients.num_rows();
DCHECK_EQ(num_variables(), coefficients.num_cols());
DCHECK_EQ(num_new_constraints, left_hand_sides.size());
DCHECK_EQ(num_new_constraints, right_hand_sides.size());
DCHECK_EQ(num_new_constraints, names.size());
matrix_.AppendRowsFromSparseMatrix(coefficients);
transpose_matrix_is_consistent_ = false;
transpose_matrix_.Clear();
columns_are_known_to_be_clean_ = false;
// Copy constraint bounds and names from linear_program.
constraint_lower_bounds_.insert(constraint_lower_bounds_.end(),
left_hand_sides.begin(),
left_hand_sides.end());
constraint_upper_bounds_.insert(constraint_upper_bounds_.end(),
right_hand_sides.begin(),
right_hand_sides.end());
constraint_names_.insert(constraint_names_.end(), names.begin(), names.end());
}
void LinearProgram::AddConstraintsWithSlackVariables(
const SparseMatrix& coefficients, const DenseColumn& left_hand_sides,
const DenseColumn& right_hand_sides,