This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
forked from rte-france/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_solver.cc
1864 lines (1694 loc) · 65 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/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/synchronization/mutex.h"
#include "ortools/base/accurate_sum.h"
#include "ortools/base/canonical_errors.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"
DEFINE_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.");
DEFINE_bool(log_verification_errors, true,
"If --verify_solution is set: LOG(ERROR) all errors detected"
" during the verification of the solution.");
DEFINE_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().");
DEFINE_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 {
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();
offset_ = 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);
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 ----
util::Status MPSolver::SetNumThreads(int num_threads) {
if (num_threads < 1) {
return util::InvalidArgumentError("num_threads must be a positive number.");
}
const util::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
#if defined(USE_BOP)
extern MPSolverInterface* BuildBopInterface(MPSolver* const solver);
#endif
#if defined(USE_GLOP)
extern MPSolverInterface* BuildGLOPInterface(MPSolver* const solver);
#endif
#if defined(USE_SCIP)
extern MPSolverInterface* BuildSCIPInterface(MPSolver* const solver);
#endif
#if defined(USE_GUROBI)
extern MPSolverInterface* BuildGurobiInterface(bool mip,
MPSolver* const solver);
#endif
#if defined(USE_CPLEX)
extern MPSolverInterface* BuildCplexInterface(bool mip, MPSolver* const solver);
extern MPSolverInterface* BuildGLOPInterface(MPSolver* const solver);
#endif
namespace {
MPSolverInterface* BuildSolverInterface(MPSolver* const solver) {
DCHECK(solver != nullptr);
switch (solver->ProblemType()) {
#if defined(USE_BOP)
case MPSolver::BOP_INTEGER_PROGRAMMING:
return BuildBopInterface(solver);
#endif
#if defined(USE_GLOP)
case MPSolver::GLOP_LINEAR_PROGRAMMING:
return BuildGLOPInterface(solver);
#endif
#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
#if defined(USE_GUROBI)
case MPSolver::GUROBI_LINEAR_PROGRAMMING:
return BuildGurobiInterface(false, solver);
case MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING:
return BuildGurobiInterface(true, solver);
#endif
#if defined(USE_CPLEX)
case MPSolver::CPLEX_LINEAR_PROGRAMMING:
return BuildCplexInterface(false, solver);
case MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING:
return BuildCplexInterface(true, 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
}
MPSolver::OptimizationProblemType DetourProblemType(
MPSolver::OptimizationProblemType problem_type) {
return problem_type;
}
} // namespace
MPSolver::MPSolver(const std::string& name,
OptimizationProblemType problem_type)
: name_(name),
problem_type_(DetourProblemType(problem_type)),
construction_time_(absl::Now()) {
interface_.reset(BuildSolverInterface(this));
if (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) return true;
if (problem_type == GLPK_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_BOP
if (problem_type == BOP_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_GLOP
if (problem_type == GLOP_LINEAR_PROGRAMMING) return true;
#endif
#ifdef USE_GUROBI
if (problem_type == GUROBI_LINEAR_PROGRAMMING) return true;
if (problem_type == GUROBI_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#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
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"},
#if defined(USE_GLPK)
{MPSolver::GLPK_LINEAR_PROGRAMMING, "glpk_lp"},
#endif
#if defined(USE_CLP)
{MPSolver::CLP_LINEAR_PROGRAMMING, "clp"},
#endif
#if defined(USE_GUROBI)
{MPSolver::GUROBI_LINEAR_PROGRAMMING, "gurobi_lp"},
#endif
#if defined(USE_SCIP)
{MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING, "scip"},
#endif
#if defined(USE_CBC)
{MPSolver::CBC_MIXED_INTEGER_PROGRAMMING, "cbc"},
#endif
#if defined(USE_GLPK)
{MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING, "glpk_mip"},
#endif
#if defined(USE_BOP)
{MPSolver::BOP_INTEGER_PROGRAMMING, "bop"},
#endif
#if defined(USE_GUROBI)
{MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING, "gurobi_mip"},
#endif
};
// static
bool MPSolver::ParseSolverType(absl::string_view solver,
MPSolver::OptimizationProblemType* type) {
for (const auto& named_solver : kOptimizationProblemTypeNames) {
if (named_solver.name == solver) {
*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;
}
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,
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,
error_message);
}
MPSolverResponseStatus MPSolver::LoadModelFromProtoInternal(
const MPModelProto& input_model, bool clear_names,
std::string* error_message) {
CHECK(error_message != nullptr);
const std::string error = FindErrorInMPModelProto(input_model);
if (!error.empty()) {
*error_message = error;
LOG_IF(INFO, OutputIsEnabled())
<< "Invalid model given to LoadModelFromProto(): " << error;
if (FLAGS_mpsolver_bypass_model_validation) {
LOG_IF(INFO, OutputIsEnabled())
<< "Ignoring the model error(s) because of"
<< " --mpsolver_bypass_model_validation.";
} else {
return error.find("Infeasible") == std::string::npos
? MPSOLVER_MODEL_INVALID
: MPSOLVER_INFEASIBLE;
}
}
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()) {
if (general_constraint.has_indicator_constraint()) {
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;
}
}
}
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);
const MPModelProto& model = model_request.model();
MPSolver solver(model.name(), static_cast<MPSolver::OptimizationProblemType>(
model_request.solver_type()));
if (model_request.enable_internal_solver_output()) {
solver.EnableOutput();
}
std::string error_message;
response->set_status(solver.LoadModelFromProto(model, &error_message));
if (response->status() != MPSOLVER_MODEL_IS_VALID) {
LOG(WARNING) << "Loading model from protocol buffer failed, load 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()));
}
solver.SetSolverSpecificParametersAsString(
model_request.solver_specific_parameters());
solver.Solve();
solver.FillSolutionResponseProto(response);
}
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);
}
}
}
util::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 util::InvalidArgumentError(absl::StrCat(
"Cannot load a solution unless its status is OPTIMAL or FEASIBLE"
" (status was: ",
ProtoEnumToString<MPSolverResponseStatus>(response.status()), ")"));
}
// Before touching the variables, verify that the solution looks legit:
// each variable of the MPSolver must have its value listed exactly once, and
// each listed solution should correspond to a known variable.
if (response.variable_value_size() != variables_.size()) {
return util::InvalidArgumentError(absl::StrCat(
"Trying to load a solution whose number of variables (",
response.variable_value_size(),
") does not correspond to the Solver's (", variables_.size(), ")"));
}
interface_->ExtractModel();
if (tolerance != infinity()) {
// Look further: verify that the variable values are within the bounds.
double largest_error = 0;
int num_vars_out_of_bounds = 0;
int last_offending_var = -1;
for (int i = 0; i < response.variable_value_size(); ++i) {
const double var_value = response.variable_value(i);
MPVariable* var = variables_[i];
// TODO(user): Use parameter when they become available in this class.
const double lb_error = var->lb() - var_value;
const double ub_error = var_value - var->ub();
if (lb_error > tolerance || ub_error > tolerance) {
++num_vars_out_of_bounds;
largest_error = std::max(largest_error, std::max(lb_error, ub_error));
last_offending_var = i;
}
}
if (num_vars_out_of_bounds > 0) {
return util::InvalidArgumentError(absl::StrCat(
"Loaded a solution whose variables matched the solver's, but ",
num_vars_out_of_bounds, " of ", variables_.size(),
" variables were out of their bounds, by more than the primal"
" tolerance which is: ",
tolerance, ". Max error: ", largest_error, ", last offender var is #",
last_offending_var, ": '", variables_[last_offending_var]->name(),
"'"));
}
}
for (int i = 0; i < response.variable_value_size(); ++i) {
variables_[i]->set_solution_value(response.variable_value(i));
}
// Set the objective value, if is known.
// NOTE(user): We do not verify the objective, even though we could!
if (response.has_objective_value()) {
interface_->objective_value_ = response.objective_value();
}
// Mark the status as SOLUTION_SYNCHRONIZED, so that users may inspect the
// solution normally.
interface_->sync_status_ = MPSolverInterface::SOLUTION_SYNCHRONIZED;
return util::OkStatus();
}
void MPSolver::Clear() {
MutableObjective()->Clear();
gtl::STLDeleteElements(&variables_);
gtl::STLDeleteElements(&constraints_);
variables_.clear();
if (variable_name_to_index_) {
variable_name_to_index_->clear();
}
variable_is_extracted_.clear();
constraints_.clear();
if (constraint_name_to_index_) {
constraint_name_to_index_->clear();
}
constraint_is_extracted_.clear();
interface_->Reset();
solution_hint_.clear();
}
void MPSolver::Reset() { interface_->Reset(); }
bool MPSolver::InterruptSolve() { return interface_->InterruptSolve(); }
void MPSolver::SetStartingLpBasis(
const std::vector<BasisStatus>& variable_statuses,
const std::vector<BasisStatus>& constraint_statuses) {
interface_->SetStartingLpBasis(variable_statuses, constraint_statuses);
}
MPVariable* MPSolver::MakeVar(double lb, double ub, bool integer,
const std::string& name) {
const int var_index = NumVariables();
MPVariable* v =
new MPVariable(var_index, lb, ub, integer, name, interface_.get());
if (variable_name_to_index_) {
gtl::InsertOrDie(&*variable_name_to_index_, v->name(), var_index);
}
variables_.push_back(v);
variable_is_extracted_.push_back(false);
interface_->AddVariable(v);
return v;
}
MPVariable* MPSolver::MakeNumVar(double lb, double ub,
const std::string& name) {
return MakeVar(lb, ub, false, name);
}
MPVariable* MPSolver::MakeIntVar(double lb, double ub,
const std::string& name) {
return MakeVar(lb, ub, true, name);
}
MPVariable* MPSolver::MakeBoolVar(const std::string& name) {
return MakeVar(0.0, 1.0, true, name);
}
void MPSolver::MakeVarArray(int nb, double lb, double ub, bool integer,
const std::string& name,
std::vector<MPVariable*>* vars) {
DCHECK_GE(nb, 0);
if (nb <= 0) return;
const int num_digits = NumDigits(nb);
for (int i = 0; i < nb; ++i) {
if (name.empty()) {
vars->push_back(MakeVar(lb, ub, integer, name));
} else {
std::string vname =
absl::StrFormat("%s%0*d", name.c_str(), num_digits, i);
vars->push_back(MakeVar(lb, ub, integer, vname));
}
}
}
void MPSolver::MakeNumVarArray(int nb, double lb, double ub,
const std::string& name,
std::vector<MPVariable*>* vars) {
MakeVarArray(nb, lb, ub, false, name, vars);
}
void MPSolver::MakeIntVarArray(int nb, double lb, double ub,
const std::string& name,
std::vector<MPVariable*>* vars) {