forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 3
/
linear_solver.cc
2022 lines (1839 loc) · 71.9 KB
/
linear_solver.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/linear_solver/linear_solver.h"
#if !defined(_MSC_VER)
#include <unistd.h>
#endif
#include <cmath>
#include <cstddef>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_replace.h"
#include "absl/synchronization/mutex.h"
#include "ortools/base/accurate_sum.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/status_macros.h"
#include "ortools/base/stl_util.h"
#include "ortools/linear_solver/linear_solver.pb.h"
#include "ortools/linear_solver/model_exporter.h"
#include "ortools/linear_solver/model_validator.h"
#include "ortools/port/file.h"
#include "ortools/util/fp_utils.h"
ABSL_FLAG(bool, verify_solution, false,
"Systematically verify the solution when calling Solve()"
", and change the return value of Solve() to ABNORMAL if"
" an error was detected.");
ABSL_FLAG(bool, log_verification_errors, true,
"If --verify_solution is set: LOG(ERROR) all errors detected"
" during the verification of the solution.");
ABSL_FLAG(bool, linear_solver_enable_verbose_output, false,
"If set, enables verbose output for the solver. Setting this flag"
" is the same as calling MPSolver::EnableOutput().");
ABSL_FLAG(bool, mpsolver_bypass_model_validation, false,
"If set, the user-provided Model won't be verified before Solve()."
" Invalid models will typically trigger various error responses"
" from the underlying solvers; sometimes crashes.");
namespace operations_research {
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type) {
switch (solver_type) {
case MPModelRequest::GLOP_LINEAR_PROGRAMMING:
case MPModelRequest::CLP_LINEAR_PROGRAMMING:
case MPModelRequest::GLPK_LINEAR_PROGRAMMING:
case MPModelRequest::GUROBI_LINEAR_PROGRAMMING:
case MPModelRequest::XPRESS_LINEAR_PROGRAMMING:
case MPModelRequest::CPLEX_LINEAR_PROGRAMMING:
return false;
case MPModelRequest::SCIP_MIXED_INTEGER_PROGRAMMING:
case MPModelRequest::GLPK_MIXED_INTEGER_PROGRAMMING:
case MPModelRequest::CBC_MIXED_INTEGER_PROGRAMMING:
case MPModelRequest::GUROBI_MIXED_INTEGER_PROGRAMMING:
case MPModelRequest::KNAPSACK_MIXED_INTEGER_PROGRAMMING:
case MPModelRequest::BOP_INTEGER_PROGRAMMING:
case MPModelRequest::SAT_INTEGER_PROGRAMMING:
case MPModelRequest::XPRESS_MIXED_INTEGER_PROGRAMMING:
case MPModelRequest::CPLEX_MIXED_INTEGER_PROGRAMMING:
return true;
}
LOG(DFATAL) << "Invalid SolverType: " << solver_type;
return false;
}
double MPConstraint::GetCoefficient(const MPVariable* const var) const {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == nullptr) return 0.0;
return gtl::FindWithDefault(coefficients_, var, 0.0);
}
void MPConstraint::SetCoefficient(const MPVariable* const var, double coeff) {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == nullptr) return;
if (coeff == 0.0) {
auto it = coefficients_.find(var);
// If setting a coefficient to 0 when this coefficient did not
// exist or was already 0, do nothing: skip
// interface_->SetCoefficient() and do not store a coefficient in
// the map. Note that if the coefficient being set to 0 did exist
// and was not 0, we do have to keep a 0 in the coefficients_ map,
// because the extraction of the constraint might rely on it,
// depending on the underlying solver.
if (it != coefficients_.end() && it->second != 0.0) {
const double old_value = it->second;
it->second = 0.0;
interface_->SetCoefficient(this, var, 0.0, old_value);
}
return;
}
auto insertion_result = coefficients_.insert(std::make_pair(var, coeff));
const double old_value =
insertion_result.second ? 0.0 : insertion_result.first->second;
insertion_result.first->second = coeff;
interface_->SetCoefficient(this, var, coeff, old_value);
}
void MPConstraint::Clear() {
interface_->ClearConstraint(this);
coefficients_.clear();
}
void MPConstraint::SetBounds(double lb, double ub) {
const bool change = lb != lb_ || ub != ub_;
lb_ = lb;
ub_ = ub;
if (change && interface_->constraint_is_extracted(index_)) {
interface_->SetConstraintBounds(index_, lb_, ub_);
}
}
double MPConstraint::dual_value() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Dual value only available for continuous problems";
return 0.0;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
return dual_value_;
}
MPSolver::BasisStatus MPConstraint::basis_status() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Basis status only available for continuous problems";
return MPSolver::FREE;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) {
return MPSolver::FREE;
}
// This is done lazily as this method is expected to be rarely used.
return interface_->row_status(index_);
}
bool MPConstraint::ContainsNewVariables() {
const int last_variable_index = interface_->last_variable_index();
for (const auto& entry : coefficients_) {
const int variable_index = entry.first->index();
if (variable_index >= last_variable_index ||
!interface_->variable_is_extracted(variable_index)) {
return true;
}
}
return false;
}
// ----- MPObjective -----
double MPObjective::GetCoefficient(const MPVariable* const var) const {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == nullptr) return 0.0;
return gtl::FindWithDefault(coefficients_, var, 0.0);
}
void MPObjective::SetCoefficient(const MPVariable* const var, double coeff) {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == nullptr) return;
if (coeff == 0.0) {
auto it = coefficients_.find(var);
// See the discussion on MPConstraint::SetCoefficient() for 0 coefficients,
// the same reasoning applies here.
if (it == coefficients_.end() || it->second == 0.0) return;
it->second = 0.0;
} else {
coefficients_[var] = coeff;
}
interface_->SetObjectiveCoefficient(var, coeff);
}
void MPObjective::SetOffset(double value) {
offset_ = value;
interface_->SetObjectiveOffset(offset_);
}
namespace {
void CheckLinearExpr(const MPSolver& solver, const LinearExpr& linear_expr) {
for (auto var_value_pair : linear_expr.terms()) {
CHECK(solver.OwnsVariable(var_value_pair.first))
<< "Bad MPVariable* in LinearExpr, did you try adding an integer to an "
"MPVariable* directly?";
}
}
} // namespace
void MPObjective::OptimizeLinearExpr(const LinearExpr& linear_expr,
bool is_maximization) {
CheckLinearExpr(*interface_->solver_, linear_expr);
interface_->ClearObjective();
coefficients_.clear();
SetOffset(linear_expr.offset());
for (const auto& kv : linear_expr.terms()) {
SetCoefficient(kv.first, kv.second);
}
SetOptimizationDirection(is_maximization);
}
void MPObjective::AddLinearExpr(const LinearExpr& linear_expr) {
CheckLinearExpr(*interface_->solver_, linear_expr);
SetOffset(offset_ + linear_expr.offset());
for (const auto& kv : linear_expr.terms()) {
SetCoefficient(kv.first, GetCoefficient(kv.first) + kv.second);
}
}
void MPObjective::Clear() {
interface_->ClearObjective();
coefficients_.clear();
offset_ = 0.0;
SetMinimization();
}
void MPObjective::SetOptimizationDirection(bool maximize) {
// Note(user): The maximize_ bool would more naturally belong to the
// MPObjective, but it actually has to be a member of MPSolverInterface,
// because some implementations (such as GLPK) need that bool for the
// MPSolverInterface constructor, i.e at a time when the MPObjective is not
// constructed yet (MPSolverInterface is always built before MPObjective
// when a new MPSolver is constructed).
interface_->maximize_ = maximize;
interface_->SetOptimizationDirection(maximize);
}
bool MPObjective::maximization() const { return interface_->maximize_; }
bool MPObjective::minimization() const { return !interface_->maximize_; }
double MPObjective::Value() const {
// Note(user): implementation-wise, the objective value belongs more
// naturally to the MPSolverInterface, since all of its implementations write
// to it directly.
return interface_->objective_value();
}
double MPObjective::BestBound() const {
// Note(user): the best objective bound belongs to the interface for the
// same reasons as the objective value does.
return interface_->best_objective_bound();
}
// ----- MPVariable -----
double MPVariable::solution_value() const {
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
// If the underlying solver supports integer variables, and this is an integer
// variable, we round the solution value (i.e., clients usually expect precise
// integer values for integer variables).
return (integer_ && interface_->IsMIP()) ? round(solution_value_)
: solution_value_;
}
double MPVariable::unrounded_solution_value() const {
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
return solution_value_;
}
double MPVariable::reduced_cost() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Reduced cost only available for continuous problems";
return 0.0;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
return reduced_cost_;
}
MPSolver::BasisStatus MPVariable::basis_status() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Basis status only available for continuous problems";
return MPSolver::FREE;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) {
return MPSolver::FREE;
}
// This is done lazily as this method is expected to be rarely used.
return interface_->column_status(index_);
}
void MPVariable::SetBounds(double lb, double ub) {
const bool change = lb != lb_ || ub != ub_;
lb_ = lb;
ub_ = ub;
if (change && interface_->variable_is_extracted(index_)) {
interface_->SetVariableBounds(index_, lb_, ub_);
}
}
void MPVariable::SetInteger(bool integer) {
if (integer_ != integer) {
integer_ = integer;
if (interface_->variable_is_extracted(index_)) {
interface_->SetVariableInteger(index_, integer);
}
}
}
void MPVariable::SetBranchingPriority(int priority) {
if (priority == branching_priority_) return;
branching_priority_ = priority;
interface_->BranchingPriorityChangedForVariable(index_);
}
// ----- Interface shortcuts -----
bool MPSolver::IsMIP() const { return interface_->IsMIP(); }
std::string MPSolver::SolverVersion() const {
return interface_->SolverVersion();
}
void* MPSolver::underlying_solver() { return interface_->underlying_solver(); }
// ---- Solver-specific parameters ----
absl::Status MPSolver::SetNumThreads(int num_threads) {
if (num_threads < 1) {
return absl::InvalidArgumentError("num_threads must be a positive number.");
}
const absl::Status status = interface_->SetNumThreads(num_threads);
if (status.ok()) {
num_threads_ = num_threads;
}
return status;
}
bool MPSolver::SetSolverSpecificParametersAsString(
const std::string& parameters) {
solver_specific_parameter_string_ = parameters;
return interface_->SetSolverSpecificParametersAsString(parameters);
}
// ----- Solver -----
#if defined(USE_CLP) || defined(USE_CBC)
extern MPSolverInterface* BuildCLPInterface(MPSolver* const solver);
#endif
#if defined(USE_CBC)
extern MPSolverInterface* BuildCBCInterface(MPSolver* const solver);
#endif
#if defined(USE_GLPK)
extern MPSolverInterface* BuildGLPKInterface(bool mip, MPSolver* const solver);
#endif
extern MPSolverInterface* BuildBopInterface(MPSolver* const solver);
extern MPSolverInterface* BuildGLOPInterface(MPSolver* const solver);
extern MPSolverInterface* BuildSatInterface(MPSolver* const solver);
#if defined(USE_SCIP)
extern MPSolverInterface* BuildSCIPInterface(MPSolver* const solver);
#endif
extern MPSolverInterface* BuildGurobiInterface(bool mip,
MPSolver* const solver);
#if defined(USE_CPLEX)
extern MPSolverInterface* BuildCplexInterface(bool mip, MPSolver* const solver);
extern MPSolverInterface* BuildGLOPInterface(MPSolver* const solver);
#endif
#if defined(USE_XPRESS)
extern MPSolverInterface* BuildXpressInterface(bool mip,
MPSolver* const solver);
#endif
namespace {
MPSolverInterface* BuildSolverInterface(MPSolver* const solver) {
DCHECK(solver != nullptr);
switch (solver->ProblemType()) {
case MPSolver::BOP_INTEGER_PROGRAMMING:
return BuildBopInterface(solver);
case MPSolver::SAT_INTEGER_PROGRAMMING:
return BuildSatInterface(solver);
case MPSolver::GLOP_LINEAR_PROGRAMMING:
return BuildGLOPInterface(solver);
#if defined(USE_GLPK)
case MPSolver::GLPK_LINEAR_PROGRAMMING:
return BuildGLPKInterface(false, solver);
case MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING:
return BuildGLPKInterface(true, solver);
#endif
#if defined(USE_CLP) || defined(USE_CBC)
case MPSolver::CLP_LINEAR_PROGRAMMING:
return BuildCLPInterface(solver);
#endif
#if defined(USE_CBC)
case MPSolver::CBC_MIXED_INTEGER_PROGRAMMING:
return BuildCBCInterface(solver);
#endif
#if defined(USE_SCIP)
case MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING:
return BuildSCIPInterface(solver);
#endif
case MPSolver::GUROBI_LINEAR_PROGRAMMING:
return BuildGurobiInterface(false, solver);
case MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING:
return BuildGurobiInterface(true, solver);
#if defined(USE_CPLEX)
case MPSolver::CPLEX_LINEAR_PROGRAMMING:
return BuildCplexInterface(false, solver);
case MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING:
return BuildCplexInterface(true, solver);
#endif
#if defined(USE_XPRESS)
case MPSolver::XPRESS_MIXED_INTEGER_PROGRAMMING:
return BuildXpressInterface(true, solver);
case MPSolver::XPRESS_LINEAR_PROGRAMMING:
return BuildXpressInterface(false, solver);
#endif
default:
// TODO(user): Revert to the best *available* interface.
LOG(FATAL) << "Linear solver not recognized.";
}
return nullptr;
}
} // namespace
namespace {
int NumDigits(int n) {
// Number of digits needed to write a non-negative integer in base 10.
// Note(user): max(1, log(0) + 1) == max(1, -inf) == 1.
#if defined(_MSC_VER)
return static_cast<int>(std::max(1.0L, log(1.0L * n) / log(10.0L) + 1.0));
#else
return static_cast<int>(std::max(1.0, log10(static_cast<double>(n)) + 1.0));
#endif
}
} // namespace
MPSolver::MPSolver(const std::string& name,
OptimizationProblemType problem_type)
: name_(name),
problem_type_(problem_type),
construction_time_(absl::Now()) {
interface_.reset(BuildSolverInterface(this));
if (absl::GetFlag(FLAGS_linear_solver_enable_verbose_output)) {
EnableOutput();
}
objective_.reset(new MPObjective(interface_.get()));
}
MPSolver::~MPSolver() { Clear(); }
// static
bool MPSolver::SupportsProblemType(OptimizationProblemType problem_type) {
#ifdef USE_CLP
if (problem_type == CLP_LINEAR_PROGRAMMING) return true;
#endif
#ifdef USE_GLPK
if (problem_type == GLPK_LINEAR_PROGRAMMING ||
problem_type == GLPK_MIXED_INTEGER_PROGRAMMING) {
return true;
}
#endif
if (problem_type == BOP_INTEGER_PROGRAMMING) return true;
if (problem_type == SAT_INTEGER_PROGRAMMING) return true;
if (problem_type == GLOP_LINEAR_PROGRAMMING) return true;
if (problem_type == GUROBI_LINEAR_PROGRAMMING ||
problem_type == GUROBI_MIXED_INTEGER_PROGRAMMING) {
return MPSolver::GurobiIsCorrectlyInstalled();
}
#ifdef USE_SCIP
if (problem_type == SCIP_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_CBC
if (problem_type == CBC_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_XPRESS
if (problem_type == XPRESS_MIXED_INTEGER_PROGRAMMING ||
problem_type == XPRESS_LINEAR_PROGRAMMING) {
return true;
}
#endif
#ifdef USE_CPLEX
if (problem_type == CPLEX_LINEAR_PROGRAMMING ||
problem_type == CPLEX_MIXED_INTEGER_PROGRAMMING) {
return true;
}
#endif
return false;
}
// TODO(user): post c++ 14, instead use
// std::pair<MPSolver::OptimizationProblemType, const absl::string_view>
// once pair gets a constexpr constructor.
namespace {
struct NamedOptimizationProblemType {
MPSolver::OptimizationProblemType problem_type;
absl::string_view name;
};
} // namespace
#if defined(_MSC_VER)
const
#else
constexpr
#endif
NamedOptimizationProblemType kOptimizationProblemTypeNames[] = {
{MPSolver::GLOP_LINEAR_PROGRAMMING, "glop"},
{MPSolver::CLP_LINEAR_PROGRAMMING, "clp"},
{MPSolver::GUROBI_LINEAR_PROGRAMMING, "gurobi_lp"},
{MPSolver::GLPK_LINEAR_PROGRAMMING, "glpk_lp"},
{MPSolver::CPLEX_LINEAR_PROGRAMMING, "cplex_lp"},
{MPSolver::XPRESS_LINEAR_PROGRAMMING, "xpress_lp"},
{MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING, "scip"},
{MPSolver::CBC_MIXED_INTEGER_PROGRAMMING, "cbc"},
{MPSolver::SAT_INTEGER_PROGRAMMING, "sat"},
{MPSolver::BOP_INTEGER_PROGRAMMING, "bop"},
{MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING, "gurobi"},
{MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING, "glpk"},
{MPSolver::KNAPSACK_MIXED_INTEGER_PROGRAMMING, "knapsack"},
{MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING, "cplex"},
{MPSolver::XPRESS_MIXED_INTEGER_PROGRAMMING, "xpress"},
};
// static
bool MPSolver::ParseSolverType(absl::string_view solver_id,
MPSolver::OptimizationProblemType* type) {
// Normalize the solver id.
const std::string id =
absl::StrReplaceAll(absl::AsciiStrToUpper(solver_id), {{"-", "_"}});
// Support the full enum name
MPModelRequest::SolverType solver_type;
if (MPModelRequest::SolverType_Parse(id, &solver_type)) {
*type = static_cast<MPSolver::OptimizationProblemType>(solver_type);
return true;
}
// Names are stored in lower case.
std::string lower_id = absl::AsciiStrToLower(id);
// Remove any "_mip" suffix, since they are optional.
if (absl::EndsWith(lower_id, "_mip")) {
lower_id = lower_id.substr(0, lower_id.size() - 4);
}
// Rewrite CP-SAT into SAT.
if (lower_id == "cp_sat") {
lower_id = "sat";
}
// Reverse lookup in the kOptimizationProblemTypeNames[] array.
for (auto& named_solver : kOptimizationProblemTypeNames) {
if (named_solver.name == lower_id) {
*type = named_solver.problem_type;
return true;
}
}
return false;
}
const absl::string_view ToString(
MPSolver::OptimizationProblemType optimization_problem_type) {
for (const auto& named_solver : kOptimizationProblemTypeNames) {
if (named_solver.problem_type == optimization_problem_type) {
return named_solver.name;
}
}
LOG(FATAL) << "Unrecognized solver type: "
<< static_cast<int>(optimization_problem_type);
return "";
}
bool AbslParseFlag(const absl::string_view text,
MPSolver::OptimizationProblemType* solver_type,
std::string* error) {
DCHECK(solver_type != nullptr);
DCHECK(error != nullptr);
const bool result = MPSolver::ParseSolverType(text, solver_type);
if (!result) {
*error = absl::StrCat("Solver type: ", text, " does not exist.");
}
return result;
}
/* static */
MPSolver::OptimizationProblemType MPSolver::ParseSolverTypeOrDie(
const std::string& solver_id) {
MPSolver::OptimizationProblemType problem_type;
CHECK(MPSolver::ParseSolverType(solver_id, &problem_type)) << solver_id;
return problem_type;
}
/* static */
MPSolver* MPSolver::CreateSolver(const std::string& solver_id) {
MPSolver::OptimizationProblemType problem_type;
if (!MPSolver::ParseSolverType(solver_id, &problem_type)) {
LOG(WARNING) << "Unrecognized solver type: " << solver_id;
return nullptr;
}
if (!MPSolver::SupportsProblemType(problem_type)) {
LOG(WARNING) << "Support for " << solver_id
<< " not linked in, or the license was not found.";
return nullptr;
}
return new MPSolver("", problem_type);
}
MPVariable* MPSolver::LookupVariableOrNull(const std::string& var_name) const {
if (!variable_name_to_index_) GenerateVariableNameIndex();
absl::flat_hash_map<std::string, int>::const_iterator it =
variable_name_to_index_->find(var_name);
if (it == variable_name_to_index_->end()) return nullptr;
return variables_[it->second];
}
MPConstraint* MPSolver::LookupConstraintOrNull(
const std::string& constraint_name) const {
if (!constraint_name_to_index_) GenerateConstraintNameIndex();
const auto it = constraint_name_to_index_->find(constraint_name);
if (it == constraint_name_to_index_->end()) return nullptr;
return constraints_[it->second];
}
// ----- Methods using protocol buffers -----
MPSolverResponseStatus MPSolver::LoadModelFromProto(
const MPModelProto& input_model, std::string* error_message) {
// The variable and constraint names are dropped, because we allow
// duplicate names in the proto (they're not considered as 'ids'),
// unlike the MPSolver C++ API which crashes if there are duplicate names.
// Clearing the names makes the MPSolver generate unique names.
return LoadModelFromProtoInternal(input_model, /*clear_names=*/true,
/*check_model_validity=*/true,
error_message);
}
MPSolverResponseStatus MPSolver::LoadModelFromProtoWithUniqueNamesOrDie(
const MPModelProto& input_model, std::string* error_message) {
// Force variable and constraint name indexing (which CHECKs name uniqueness).
GenerateVariableNameIndex();
GenerateConstraintNameIndex();
return LoadModelFromProtoInternal(input_model, /*clear_names=*/false,
/*check_model_validity=*/true,
error_message);
}
MPSolverResponseStatus MPSolver::LoadModelFromProtoInternal(
const MPModelProto& input_model, bool clear_names,
bool check_model_validity, std::string* error_message) {
CHECK(error_message != nullptr);
if (check_model_validity) {
const std::string error = FindErrorInMPModelProto(input_model);
if (!error.empty()) {
*error_message = error;
LOG_IF(INFO, OutputIsEnabled())
<< "Invalid model given to LoadModelFromProto(): " << error;
if (absl::GetFlag(FLAGS_mpsolver_bypass_model_validation)) {
LOG_IF(INFO, OutputIsEnabled())
<< "Ignoring the model error(s) because of"
<< " --mpsolver_bypass_model_validation.";
} else {
return absl::StrContains(error, "Infeasible") ? MPSOLVER_INFEASIBLE
: MPSOLVER_MODEL_INVALID;
}
}
}
if (input_model.has_quadratic_objective()) {
*error_message =
"Optimizing a quadratic objective is only supported through direct "
"proto solves. Please use MPSolver::SolveWithProto, or the solver's "
"direct proto solve function.";
return MPSOLVER_MODEL_INVALID;
}
MPObjective* const objective = MutableObjective();
// Passing empty names makes the MPSolver generate unique names.
const std::string empty;
for (int i = 0; i < input_model.variable_size(); ++i) {
const MPVariableProto& var_proto = input_model.variable(i);
MPVariable* variable =
MakeNumVar(var_proto.lower_bound(), var_proto.upper_bound(),
clear_names ? empty : var_proto.name());
variable->SetInteger(var_proto.is_integer());
if (var_proto.branching_priority() != 0) {
variable->SetBranchingPriority(var_proto.branching_priority());
}
objective->SetCoefficient(variable, var_proto.objective_coefficient());
}
for (const MPConstraintProto& ct_proto : input_model.constraint()) {
if (ct_proto.lower_bound() == -infinity() &&
ct_proto.upper_bound() == infinity()) {
continue;
}
MPConstraint* const ct =
MakeRowConstraint(ct_proto.lower_bound(), ct_proto.upper_bound(),
clear_names ? empty : ct_proto.name());
ct->set_is_lazy(ct_proto.is_lazy());
for (int j = 0; j < ct_proto.var_index_size(); ++j) {
ct->SetCoefficient(variables_[ct_proto.var_index(j)],
ct_proto.coefficient(j));
}
}
for (const MPGeneralConstraintProto& general_constraint :
input_model.general_constraint()) {
switch (general_constraint.general_constraint_case()) {
case MPGeneralConstraintProto::kIndicatorConstraint: {
const auto& proto =
general_constraint.indicator_constraint().constraint();
if (proto.lower_bound() == -infinity() &&
proto.upper_bound() == infinity()) {
continue;
}
const int constraint_index = NumConstraints();
MPConstraint* const constraint = new MPConstraint(
constraint_index, proto.lower_bound(), proto.upper_bound(),
clear_names ? "" : proto.name(), interface_.get());
if (constraint_name_to_index_) {
gtl::InsertOrDie(&*constraint_name_to_index_, constraint->name(),
constraint_index);
}
constraints_.push_back(constraint);
constraint_is_extracted_.push_back(false);
constraint->set_is_lazy(proto.is_lazy());
for (int j = 0; j < proto.var_index_size(); ++j) {
constraint->SetCoefficient(variables_[proto.var_index(j)],
proto.coefficient(j));
}
MPVariable* const variable =
variables_[general_constraint.indicator_constraint().var_index()];
constraint->indicator_variable_ = variable;
constraint->indicator_value_ =
general_constraint.indicator_constraint().var_value();
if (!interface_->AddIndicatorConstraint(constraint)) {
*error_message = "Solver doesn't support indicator constraints";
return MPSOLVER_MODEL_INVALID;
}
break;
}
default:
*error_message = absl::StrFormat(
"Optimizing general constraints of type %i is only supported "
"through direct proto solves. Please use MPSolver::SolveWithProto, "
"or the solver's direct proto solve function.",
general_constraint.general_constraint_case());
return MPSOLVER_MODEL_INVALID;
}
}
objective->SetOptimizationDirection(input_model.maximize());
if (input_model.has_objective_offset()) {
objective->SetOffset(input_model.objective_offset());
}
// Stores any hints about where to start the solve.
solution_hint_.clear();
for (int i = 0; i < input_model.solution_hint().var_index_size(); ++i) {
solution_hint_.push_back(
std::make_pair(variables_[input_model.solution_hint().var_index(i)],
input_model.solution_hint().var_value(i)));
}
return MPSOLVER_MODEL_IS_VALID;
}
namespace {
MPSolverResponseStatus ResultStatusToMPSolverResponseStatus(
MPSolver::ResultStatus status) {
switch (status) {
case MPSolver::OPTIMAL:
return MPSOLVER_OPTIMAL;
case MPSolver::FEASIBLE:
return MPSOLVER_FEASIBLE;
case MPSolver::INFEASIBLE:
return MPSOLVER_INFEASIBLE;
case MPSolver::UNBOUNDED:
return MPSOLVER_UNBOUNDED;
case MPSolver::ABNORMAL:
return MPSOLVER_ABNORMAL;
case MPSolver::MODEL_INVALID:
return MPSOLVER_MODEL_INVALID;
case MPSolver::NOT_SOLVED:
return MPSOLVER_NOT_SOLVED;
}
return MPSOLVER_UNKNOWN_STATUS;
}
} // namespace
void MPSolver::FillSolutionResponseProto(MPSolutionResponse* response) const {
CHECK(response != nullptr);
response->Clear();
response->set_status(
ResultStatusToMPSolverResponseStatus(interface_->result_status_));
if (interface_->result_status_ == MPSolver::OPTIMAL ||
interface_->result_status_ == MPSolver::FEASIBLE) {
response->set_objective_value(Objective().Value());
for (int i = 0; i < variables_.size(); ++i) {
response->add_variable_value(variables_[i]->solution_value());
}
if (interface_->IsMIP()) {
response->set_best_objective_bound(interface_->best_objective_bound());
} else {
// Dual values have no meaning in MIP.
for (int j = 0; j < constraints_.size(); ++j) {
response->add_dual_value(constraints_[j]->dual_value());
}
// Reduced cost have no meaning in MIP.
for (int i = 0; i < variables_.size(); ++i) {
response->add_reduced_cost(variables_[i]->reduced_cost());
}
}
}
}
// static
void MPSolver::SolveWithProto(const MPModelRequest& model_request,
MPSolutionResponse* response) {
CHECK(response != nullptr);
MPSolver solver(model_request.model().name(),
static_cast<MPSolver::OptimizationProblemType>(
model_request.solver_type()));
if (model_request.enable_internal_solver_output()) {
solver.EnableOutput();
}
auto optional_response = solver.interface_->DirectlySolveProto(model_request);
if (optional_response) {
*response = std::move(optional_response).value();
return;
}
const absl::optional<LazyMutableCopy<MPModelProto>> optional_model =
ExtractValidMPModelOrPopulateResponseStatus(model_request, response);
if (!optional_model) {
LOG_IF(WARNING, model_request.enable_internal_solver_output())
<< "Failed to extract a valid model from protocol buffer. Status: "
<< ProtoEnumToString<MPSolverResponseStatus>(response->status()) << " ("
<< response->status() << "): " << response->status_str();
return;
}
std::string error_message;
response->set_status(solver.LoadModelFromProtoInternal(
optional_model->get(), /*clear_names=*/true,
/*check_model_validity=*/false, &error_message));
// Even though we don't re-check model validity here, there can be some
// problems found by LoadModelFromProto, eg. unsupported features.
if (response->status() != MPSOLVER_MODEL_IS_VALID) {
response->set_status_str(error_message);
LOG_IF(WARNING, model_request.enable_internal_solver_output())
<< "LoadModelFromProtoInternal() failed even though the model was "
<< "valid! Status: "
<< ProtoEnumToString<MPSolverResponseStatus>(response->status()) << " ("
<< response->status() << "); Error: " << error_message;
return;
}
if (model_request.has_solver_time_limit_seconds()) {
solver.SetTimeLimit(
absl::Seconds(model_request.solver_time_limit_seconds()));
}
std::string warning_message;
if (model_request.has_solver_specific_parameters()) {
if (!solver.SetSolverSpecificParametersAsString(
model_request.solver_specific_parameters())) {
if (model_request.ignore_solver_specific_parameters_failure()) {
// We'll add a warning message in status_str after the solve.
warning_message =
"Warning: the solver specific parameters were not successfully "
"applied";
} else {
response->set_status(MPSOLVER_MODEL_INVALID_SOLVER_PARAMETERS);
return;
}
}
}
solver.Solve();
solver.FillSolutionResponseProto(response);
if (!warning_message.empty()) {
response->set_status_str(absl::StrCat(
response->status_str(), (response->status_str().empty() ? "" : "\n"),
warning_message));
}
}
void MPSolver::ExportModelToProto(MPModelProto* output_model) const {
DCHECK(output_model != nullptr);
output_model->Clear();
// Name
output_model->set_name(Name());
// Variables
for (int j = 0; j < variables_.size(); ++j) {
const MPVariable* const var = variables_[j];
MPVariableProto* const variable_proto = output_model->add_variable();
// TODO(user): Add option to avoid filling the var name to avoid overly
// large protocol buffers.
variable_proto->set_name(var->name());
variable_proto->set_lower_bound(var->lb());
variable_proto->set_upper_bound(var->ub());
variable_proto->set_is_integer(var->integer());
if (objective_->GetCoefficient(var) != 0.0) {
variable_proto->set_objective_coefficient(
objective_->GetCoefficient(var));
}
if (var->branching_priority() != 0) {
variable_proto->set_branching_priority(var->branching_priority());
}
}
// Map the variables to their indices. This is needed to output the
// variables in the order they were created, which in turn is needed to have
// repeatable results with ExportModelAsLpFormat and ExportModelAsMpsFormat.
// This step is needed as long as the variable indices are given by the
// underlying solver at the time of model extraction.
// TODO(user): remove this step.
absl::flat_hash_map<const MPVariable*, int> var_to_index;
for (int j = 0; j < variables_.size(); ++j) {
var_to_index[variables_[j]] = j;
}
// Constraints
for (int i = 0; i < constraints_.size(); ++i) {
MPConstraint* const constraint = constraints_[i];
MPConstraintProto* constraint_proto;
if (constraint->indicator_variable() != nullptr) {
MPGeneralConstraintProto* const general_constraint_proto =
output_model->add_general_constraint();
general_constraint_proto->set_name(constraint->name());
MPIndicatorConstraint* const indicator_constraint_proto =
general_constraint_proto->mutable_indicator_constraint();
indicator_constraint_proto->set_var_index(
constraint->indicator_variable()->index());
indicator_constraint_proto->set_var_value(constraint->indicator_value());
constraint_proto = indicator_constraint_proto->mutable_constraint();
} else {
constraint_proto = output_model->add_constraint();
}
constraint_proto->set_name(constraint->name());
constraint_proto->set_lower_bound(constraint->lb());
constraint_proto->set_upper_bound(constraint->ub());
constraint_proto->set_is_lazy(constraint->is_lazy());
// Vector linear_term will contain pairs (variable index, coeff), that will
// be sorted by variable index.
std::vector<std::pair<int, double>> linear_term;
for (const auto& entry : constraint->coefficients_) {
const MPVariable* const var = entry.first;
const int var_index = gtl::FindWithDefault(var_to_index, var, -1);
DCHECK_NE(-1, var_index);
const double coeff = entry.second;
linear_term.push_back(std::pair<int, double>(var_index, coeff));
}
// The cost of sort is expected to be low as constraints usually have very
// few terms.
std::sort(linear_term.begin(), linear_term.end());
// Now use linear term.
for (const std::pair<int, double>& var_and_coeff : linear_term) {
constraint_proto->add_var_index(var_and_coeff.first);
constraint_proto->add_coefficient(var_and_coeff.second);
}
}
output_model->set_maximize(Objective().maximization());
output_model->set_objective_offset(Objective().offset());
if (!solution_hint_.empty()) {
PartialVariableAssignment* const hint =
output_model->mutable_solution_hint();
for (const auto& var_value_pair : solution_hint_) {
hint->add_var_index(var_value_pair.first->index());
hint->add_var_value(var_value_pair.second);
}
}
}
absl::Status MPSolver::LoadSolutionFromProto(const MPSolutionResponse& response,
double tolerance) {
interface_->result_status_ = static_cast<ResultStatus>(response.status());
if (response.status() != MPSOLVER_OPTIMAL &&
response.status() != MPSOLVER_FEASIBLE) {
return absl::InvalidArgumentError(absl::StrCat(
"Cannot load a solution unless its status is OPTIMAL or FEASIBLE"
" (status was: ",
ProtoEnumToString<MPSolverResponseStatus>(response.status()), ")"));
}