C++ Reference

C++ Reference: Linear solver

linear_solver.h
Go to the documentation of this file.
1// Copyright 2010-2021 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
134#ifndef OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
135#define OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
136
137#include <atomic>
138#include <cstdint>
139#include <functional>
140#include <limits>
141#include <map>
142#include <memory>
143#include <string>
144#include <utility>
145#include <vector>
146
147#include "absl/base/port.h"
148#include "absl/container/flat_hash_map.h"
149#include "absl/flags/parse.h"
150#include "absl/flags/usage.h"
151#include "absl/status/status.h"
152#include "absl/strings/match.h"
153#include "absl/strings/str_format.h"
154#include "absl/types/optional.h"
155#include "ortools/base/integral_types.h"
156#include "ortools/base/logging.h"
157#include "ortools/base/macros.h"
158#include "ortools/base/timer.h"
161#include "ortools/linear_solver/linear_solver_callback.h"
162#include "ortools/port/proto_utils.h"
163
164ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
165
166namespace operations_research {
167
168constexpr double kDefaultPrimalTolerance = 1e-07;
169
170class MPConstraint;
171class MPObjective;
174class MPVariable;
175
176// There is a homonymous version taking a MPSolver::OptimizationProblemType.
178
183class MPSolver {
184 public:
192 // Linear programming problems.
193 // ----------------------------
196 GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
197
198 // Integer programming problems.
199 // -----------------------------
200 SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
203
204 // Commercial software (need license).
211
212 // Boolean optimization problem (requires only integer variables and works
213 // best with only Boolean variables).
215
216 // SAT based solver (requires only integer and Boolean variables).
217 // If you pass it mixed integer problems, it will scale coefficients to
218 // integer values, and solver continuous variables as integral variables.
220
221 // Dedicated knapsack solvers.
223 };
224
226 MPSolver(const std::string& name, OptimizationProblemType problem_type);
227 virtual ~MPSolver();
228
257 static MPSolver* CreateSolver(const std::string& solver_id);
258
264
270 static bool ParseSolverType(absl::string_view solver_id,
272
278 const std::string& solver_id);
279
280 bool IsMIP() const;
281
283 const std::string& Name() const {
284 return name_; // Set at construction.
285 }
286
289 return problem_type_; // Set at construction.
290 }
291
297 void Clear();
298
300 int NumVariables() const { return variables_.size(); }
301
306 const std::vector<MPVariable*>& variables() const { return variables_; }
307
311 MPVariable* variable(int index) const { return variables_[index]; }
312
318 MPVariable* LookupVariableOrNull(const std::string& var_name) const;
319
327 MPVariable* MakeVar(double lb, double ub, bool integer,
328 const std::string& name);
329
331 MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
332
334 MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
335
337 MPVariable* MakeBoolVar(const std::string& name);
338
353 void MakeVarArray(int nb, double lb, double ub, bool integer,
354 const std::string& name_prefix,
355 std::vector<MPVariable*>* vars);
356
358 void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
359 std::vector<MPVariable*>* vars);
360
362 void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
363 std::vector<MPVariable*>* vars);
364
366 void MakeBoolVarArray(int nb, const std::string& name,
367 std::vector<MPVariable*>* vars);
368
370 int NumConstraints() const { return constraints_.size(); }
371
377 const std::vector<MPConstraint*>& constraints() const { return constraints_; }
378
380 MPConstraint* constraint(int index) const { return constraints_[index]; }
381
390 const std::string& constraint_name) const;
391
400 MPConstraint* MakeRowConstraint(double lb, double ub);
401
404
406 MPConstraint* MakeRowConstraint(double lb, double ub,
407 const std::string& name);
408
410 MPConstraint* MakeRowConstraint(const std::string& name);
411
417
420 const std::string& name);
421
428 const MPObjective& Objective() const { return *objective_; }
429
431 MPObjective* MutableObjective() { return objective_.get(); }
432
453 NOT_SOLVED = 6
454 };
455
458
461
466 void Write(const std::string& file_name);
467
474 std::vector<double> ComputeConstraintActivities() const;
475
494 bool VerifySolution(double tolerance, bool log_errors) const;
495
504 void Reset();
505
516
525 std::string* error_message);
534 const MPModelProto& input_model, std::string* error_message);
535
538
554 static void SolveWithProto(const MPModelRequest& model_request,
555 MPSolutionResponse* response,
556 // `interrupt` is non-const because the internal
557 // solver may set it to true itself, in some cases.
558 std::atomic<bool>* interrupt = nullptr);
559
561 const MPModelRequest::SolverType solver) {
562 // Interruption requires that MPSolver::InterruptSolve is supported for the
563 // underlying solver. Interrupting requests using SCIP is also not supported
564 // as of 2021/08/23, since InterruptSolve is not go/thread-safe
565 // for SCIP (see e.g. cl/350545631 for details).
570 }
571
573 void ExportModelToProto(MPModelProto* output_model) const;
574
609 const MPSolutionResponse& response,
610 double tolerance = std::numeric_limits<double>::infinity());
611
617
624 bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
625 bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
626 std::string* model_str) const;
627
638 absl::Status SetNumThreads(int num_threads);
639
641 int GetNumThreads() const { return num_threads_; }
642
649 bool SetSolverSpecificParametersAsString(const std::string& parameters);
651 return solver_specific_parameter_string_;
652 }
653
667 void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
668
674 FREE = 0,
678 BASIC
679 };
680
693 const std::vector<MPSolver::BasisStatus>& variable_statuses,
694 const std::vector<MPSolver::BasisStatus>& constraint_statuses);
695
701 static double infinity() { return std::numeric_limits<double>::infinity(); }
702
711 bool OutputIsEnabled() const;
712
715
718
719 absl::Duration TimeLimit() const { return time_limit_; }
720 void SetTimeLimit(absl::Duration time_limit) {
721 DCHECK_GE(time_limit, absl::ZeroDuration());
722 time_limit_ = time_limit;
723 }
724
725 absl::Duration DurationSinceConstruction() const {
726 return absl::Now() - construction_time_;
727 }
728
730 int64_t iterations() const;
731
737 int64_t nodes() const;
738
740 std::string SolverVersion() const;
741
756
781
796 ABSL_MUST_USE_RESULT bool NextSolution();
797
798 // Does not take ownership of "mp_callback".
799 //
800 // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
801 // SCIP does not support suggesting a heuristic solution in the callback.
802 //
803 // See go/mpsolver-callbacks for additional documentation.
804 void SetCallback(MPCallback* mp_callback);
805 bool SupportsCallbacks() const;
806
807 // Global counters of variables and constraints ever created across all
808 // MPSolver instances. Those are only updated after the destruction
809 // (or Clear()) of each MPSolver instance.
810 static int64_t global_num_variables();
811 static int64_t global_num_constraints();
812
813 // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
814 // NOTE: These deprecated functions used the convention time_limit = 0 to mean
815 // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
816 int64_t time_limit() const {
817 return time_limit_ == absl::InfiniteDuration()
818 ? 0
819 : absl::ToInt64Milliseconds(time_limit_);
820 }
821 void set_time_limit(int64_t time_limit_milliseconds) {
822 SetTimeLimit(time_limit_milliseconds == 0
823 ? absl::InfiniteDuration()
824 : absl::Milliseconds(time_limit_milliseconds));
825 }
826 double time_limit_in_secs() const {
827 return static_cast<double>(time_limit()) / 1000.0;
828 }
829
830 // DEPRECATED: Use DurationSinceConstruction() instead.
831 int64_t wall_time() const {
832 return absl::ToInt64Milliseconds(DurationSinceConstruction());
833 }
834
835 friend class GLPKInterface;
836 friend class CLPInterface;
837 friend class CBCInterface;
838 friend class SCIPInterface;
839 friend class GurobiInterface;
840 friend class CplexInterface;
841 friend class XpressInterface;
842 friend class SLMInterface;
843 friend class MPSolverInterface;
844 friend class GLOPInterface;
845 friend class BopInterface;
846 friend class SatInterface;
847 friend class KnapsackInterface;
848
849 // Debugging: verify that the given MPVariable* belongs to this solver.
850 bool OwnsVariable(const MPVariable* var) const;
851
852 private:
853 // Computes the size of the constraint with the largest number of
854 // coefficients with index in [min_constraint_index,
855 // max_constraint_index)
856 int ComputeMaxConstraintSize(int min_constraint_index,
857 int max_constraint_index) const;
858
859 // Returns true if the model has constraints with lower bound > upper bound.
860 bool HasInfeasibleConstraints() const;
861
862 // Returns true if the model has at least 1 integer variable.
863 bool HasIntegerVariables() const;
864
865 // Generates the map from variable names to their indices.
866 void GenerateVariableNameIndex() const;
867
868 // Generates the map from constraint names to their indices.
869 void GenerateConstraintNameIndex() const;
870
871 // The name of the linear programming problem.
872 const std::string name_;
873
874 // The type of the linear programming problem.
875 const OptimizationProblemType problem_type_;
876
877 // The solver interface.
878 std::unique_ptr<MPSolverInterface> interface_;
879
880 // The vector of variables in the problem.
881 std::vector<MPVariable*> variables_;
882 // A map from a variable's name to its index in variables_.
883 mutable absl::optional<absl::flat_hash_map<std::string, int> >
884 variable_name_to_index_;
885 // Whether variables have been extracted to the underlying interface.
886 std::vector<bool> variable_is_extracted_;
887
888 // The vector of constraints in the problem.
889 std::vector<MPConstraint*> constraints_;
890 // A map from a constraint's name to its index in constraints_.
891 mutable absl::optional<absl::flat_hash_map<std::string, int> >
892 constraint_name_to_index_;
893 // Whether constraints have been extracted to the underlying interface.
894 std::vector<bool> constraint_is_extracted_;
895
896 // The linear objective function.
897 std::unique_ptr<MPObjective> objective_;
898
899 // Initial values for all or some of the problem variables that can be
900 // exploited as a starting hint by a solver.
901 //
902 // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
903 //
904 // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
905 // hint is provided and a std::vector<double> for the hint value.
906 std::vector<std::pair<const MPVariable*, double> > solution_hint_;
907
908 absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
909
910 const absl::Time construction_time_;
911
912 // Permanent storage for the number of threads.
913 int num_threads_ = 1;
914
915 // Permanent storage for SetSolverSpecificParametersAsString().
916 std::string solver_specific_parameter_string_;
917
918 static absl::Mutex global_count_mutex_;
919#ifndef SWIG
920 static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
921 static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
922#endif
923
924 MPSolverResponseStatus LoadModelFromProtoInternal(
925 const MPModelProto& input_model, bool clear_names,
926 bool check_model_validity, std::string* error_message);
927
928 DISALLOW_COPY_AND_ASSIGN(MPSolver);
929};
930
932 return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
933}
934
935const absl::string_view ToString(
936 MPSolver::OptimizationProblemType optimization_problem_type);
937
938inline std::ostream& operator<<(
939 std::ostream& os,
940 MPSolver::OptimizationProblemType optimization_problem_type) {
941 return os << ToString(optimization_problem_type);
942}
943
944inline std::ostream& operator<<(std::ostream& os,
945 MPSolver::ResultStatus status) {
946 return os << ProtoEnumToString<MPSolverResponseStatus>(
947 static_cast<MPSolverResponseStatus>(status));
948}
949
950bool AbslParseFlag(absl::string_view text,
952 std::string* error);
953
954inline std::string AbslUnparseFlag(
956 return std::string(ToString(solver_type));
957}
958
961 public:
966 void Clear();
967
974 void SetCoefficient(const MPVariable* const var, double coeff);
975
981 double GetCoefficient(const MPVariable* const var) const;
982
988 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
989 return coefficients_;
990 }
991
993 void SetOffset(double value);
994
996 double offset() const { return offset_; }
997
1002 void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1003
1005 void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1006 OptimizeLinearExpr(linear_expr, true);
1007 }
1009 void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1010 OptimizeLinearExpr(linear_expr, false);
1011 }
1012
1014 void AddLinearExpr(const LinearExpr& linear_expr);
1015
1017 void SetOptimizationDirection(bool maximize);
1018
1021
1024
1026 bool maximization() const;
1027
1029 bool minimization() const;
1030
1042 double Value() const;
1043
1050 double BestBound() const;
1051
1052 private:
1053 friend class MPSolver;
1054 friend class MPSolverInterface;
1055 friend class CBCInterface;
1056 friend class CLPInterface;
1057 friend class GLPKInterface;
1058 friend class SCIPInterface;
1059 friend class SLMInterface;
1060 friend class GurobiInterface;
1061 friend class CplexInterface;
1062 friend class XpressInterface;
1063 friend class GLOPInterface;
1064 friend class BopInterface;
1065 friend class SatInterface;
1066 friend class KnapsackInterface;
1067
1068 // Constructor. An objective points to a single MPSolverInterface
1069 // that is specified in the constructor. An objective cannot belong
1070 // to several models.
1071 // At construction, an MPObjective has no terms (which is equivalent
1072 // on having a coefficient of 0 for all variables), and an offset of 0.
1073 explicit MPObjective(MPSolverInterface* const interface_in)
1074 : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1075
1076 MPSolverInterface* const interface_;
1077
1078 // Mapping var -> coefficient.
1079 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1080 // Constant term.
1081 double offset_;
1082
1083 DISALLOW_COPY_AND_ASSIGN(MPObjective);
1084};
1085
1088 public:
1090 const std::string& name() const { return name_; }
1091
1094
1096 bool integer() const { return integer_; }
1097
1105 double solution_value() const;
1106
1108 int index() const { return index_; }
1109
1111 double lb() const { return lb_; }
1112
1114 double ub() const { return ub_; }
1115
1117 void SetLB(double lb) { SetBounds(lb, ub_); }
1118
1120 void SetUB(double ub) { SetBounds(lb_, ub); }
1121
1123 void SetBounds(double lb, double ub);
1124
1132
1137 double reduced_cost() const;
1138
1146
1157 int branching_priority() const { return branching_priority_; }
1158 void SetBranchingPriority(int priority);
1159
1160 protected:
1161 friend class MPSolver;
1162 friend class MPSolverInterface;
1163 friend class CBCInterface;
1164 friend class CLPInterface;
1165 friend class GLPKInterface;
1166 friend class SCIPInterface;
1167 friend class SLMInterface;
1168 friend class GurobiInterface;
1169 friend class CplexInterface;
1170 friend class XpressInterface;
1171 friend class GLOPInterface;
1173 friend class BopInterface;
1174 friend class SatInterface;
1175 friend class KnapsackInterface;
1176
1177 // Constructor. A variable points to a single MPSolverInterface that
1178 // is specified in the constructor. A variable cannot belong to
1179 // several models.
1180 MPVariable(int index, double lb, double ub, bool integer,
1181 const std::string& name, MPSolverInterface* const interface_in)
1182 : index_(index),
1183 lb_(lb),
1184 ub_(ub),
1185 integer_(integer),
1186 name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1187 solution_value_(0.0),
1188 reduced_cost_(0.0),
1189 interface_(interface_in) {}
1190
1191 void set_solution_value(double value) { solution_value_ = value; }
1192 void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1193
1194 private:
1195 const int index_;
1196 double lb_;
1197 double ub_;
1198 bool integer_;
1199 const std::string name_;
1200 double solution_value_;
1201 double reduced_cost_;
1202 int branching_priority_ = 0;
1203 MPSolverInterface* const interface_;
1204 DISALLOW_COPY_AND_ASSIGN(MPVariable);
1205};
1206
1213 public:
1215 const std::string& name() const { return name_; }
1216
1218 void Clear();
1219
1226 void SetCoefficient(const MPVariable* const var, double coeff);
1227
1232 double GetCoefficient(const MPVariable* const var) const;
1233
1239 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1240 return coefficients_;
1241 }
1242
1244 double lb() const { return lb_; }
1245
1247 double ub() const { return ub_; }
1248
1250 void SetLB(double lb) { SetBounds(lb, ub_); }
1251
1253 void SetUB(double ub) { SetBounds(lb_, ub); }
1254
1256 void SetBounds(double lb, double ub);
1257
1259 bool is_lazy() const { return is_lazy_; }
1260
1274 void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1275
1276 const MPVariable* indicator_variable() const { return indicator_variable_; }
1277 bool indicator_value() const { return indicator_value_; }
1278
1280 int index() const { return index_; }
1281
1286 double dual_value() const;
1287
1301
1302 protected:
1303 friend class MPSolver;
1304 friend class MPSolverInterface;
1305 friend class CBCInterface;
1306 friend class CLPInterface;
1307 friend class GLPKInterface;
1308 friend class SCIPInterface;
1309 friend class SLMInterface;
1310 friend class GurobiInterface;
1311 friend class CplexInterface;
1312 friend class XpressInterface;
1313 friend class GLOPInterface;
1314 friend class BopInterface;
1315 friend class SatInterface;
1316 friend class KnapsackInterface;
1317
1318 // Constructor. A constraint points to a single MPSolverInterface
1319 // that is specified in the constructor. A constraint cannot belong
1320 // to several models.
1321 MPConstraint(int index, double lb, double ub, const std::string& name,
1322 MPSolverInterface* const interface_in)
1323 : coefficients_(1),
1324 index_(index),
1325 lb_(lb),
1326 ub_(ub),
1327 name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1328 is_lazy_(false),
1329 indicator_variable_(nullptr),
1330 dual_value_(0.0),
1331 interface_(interface_in) {}
1332
1333 void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1334
1335 private:
1336 // Returns true if the constraint contains variables that have not
1337 // been extracted yet.
1338 bool ContainsNewVariables();
1339
1340 // Mapping var -> coefficient.
1341 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1342
1343 const int index_; // See index().
1344
1345 // The lower bound for the linear constraint.
1346 double lb_;
1347
1348 // The upper bound for the linear constraint.
1349 double ub_;
1350
1351 // Name.
1352 const std::string name_;
1353
1354 // True if the constraint is "lazy", i.e. the constraint is added to the
1355 // underlying Linear Programming solver only if it is violated.
1356 // By default this parameter is 'false'.
1357 bool is_lazy_;
1358
1359 // If given, this constraint is only active if `indicator_variable_`'s value
1360 // is equal to `indicator_value_`.
1361 const MPVariable* indicator_variable_;
1362 bool indicator_value_;
1363
1364 double dual_value_;
1365 MPSolverInterface* const interface_;
1366 DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1367};
1368
1396 public:
1401
1410 DUAL_TOLERANCE = 2
1412
1416 PRESOLVE = 1000,
1422 SCALING = 1003
1424
1430 PRESOLVE_ON = 1
1432
1436 DUAL = 10,
1440 BARRIER = 12
1442
1447
1454
1460 SCALING_ON = 1
1462
1463 // Placeholder value to indicate that a parameter is set to
1464 // the default value defined in the wrapper.
1465 static const double kDefaultDoubleParamValue;
1467
1468 // Placeholder value to indicate that a parameter is unknown.
1469 static const double kUnknownDoubleParamValue;
1471
1472 // Default values for parameters. Only parameters that define the
1473 // properties of the solution returned need to have a default value
1474 // (that is the same for all solvers). You can also define a default
1475 // value for performance parameters when you are confident it is a
1476 // good choice (example: always turn presolve on).
1477 static const double kDefaultRelativeMipGap;
1478 static const double kDefaultPrimalTolerance;
1479 static const double kDefaultDualTolerance;
1482
1485
1488
1491
1498
1505
1507 void Reset();
1508
1511
1514
1515 private:
1516 // Parameter value for each parameter.
1517 // @see DoubleParam
1518 // @see IntegerParam
1519 double relative_mip_gap_value_;
1520 double primal_tolerance_value_;
1521 double dual_tolerance_value_;
1522 int presolve_value_;
1523 int scaling_value_;
1524 int lp_algorithm_value_;
1525 int incrementality_value_;
1526
1527 // Boolean value indicating whether each parameter is set to the
1528 // solver's default value. Only parameters for which the wrapper
1529 // does not define a default value need such an indicator.
1530 bool lp_algorithm_is_default_;
1531
1532 DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1533};
1534
1535// Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1536// error when happening on the linear solver stubby server, see
1537// ./linear_solver_service.proto.
1538// Note that RPC errors forbid to carry a response to the client, who can only
1539// see the RPC error itself (error code + error message).
1541
1542// This class wraps the actual mathematical programming solvers. Each
1543// solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1544// derives from this abstract class. This class is never directly
1545// accessed by the user.
1546// @see glop_interface.cc
1547// @see cbc_interface.cc
1548// @see clp_interface.cc
1549// @see glpk_interface.cc
1550// @see scip_interface.cc
1552 public:
1554 // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1555 // sync for the model nor for the solution.
1557 // The underlying solver and MPSolver are in sync for the model
1558 // but not for the solution: the model has changed since the
1559 // solution was computed last.
1561 // The underlying solver and MPSolver are in sync for the model and
1562 // the solution.
1565
1566 // When the underlying solver does not provide the number of simplex
1567 // iterations.
1568 static constexpr int64_t kUnknownNumberOfIterations = -1;
1569 // When the underlying solver does not provide the number of
1570 // branch-and-bound nodes.
1571 static constexpr int64_t kUnknownNumberOfNodes = -1;
1572
1573 // Constructor. The user will access the MPSolverInterface through the
1574 // MPSolver passed as argument.
1575 explicit MPSolverInterface(MPSolver* const solver);
1577
1578 // ----- Solve -----
1579 // Solves problem with specified parameter values. Returns true if the
1580 // solution is optimal.
1582
1583 // Attempts to directly solve a MPModelRequest, bypassing the MPSolver data
1584 // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1585 // an 'interrupt' boolean.
1586 // Returns {} (eg. absl::nullopt) if direct-solve is not supported by the
1587 // underlying solver (possibly because interrupt != nullptr), in which case
1588 // the user should fall back to using MPSolver.
1589 virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1590 const MPModelRequest& request,
1591 // `interrupt` is non-const because the internal
1592 // solver may set it to true itself, in some cases.
1593 std::atomic<bool>* interrupt) {
1594 return absl::nullopt;
1595 }
1596
1597 // Writes the model using the solver internal write function. Currently only
1598 // available for GurobiInterface.
1599 virtual void Write(const std::string& filename);
1600
1601 // ----- Model modifications and extraction -----
1602 // Resets extracted model.
1603 virtual void Reset() = 0;
1604
1605 // Sets the optimization direction (min/max).
1606 virtual void SetOptimizationDirection(bool maximize) = 0;
1607
1608 // Modifies bounds of an extracted variable.
1609 virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1610
1611 // Modifies integrality of an extracted variable.
1612 virtual void SetVariableInteger(int index, bool integer) = 0;
1613
1614 // Modify bounds of an extracted variable.
1615 virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1616
1617 // Adds a linear constraint.
1618 virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1619
1620 // Adds an indicator constraint. Returns true if the feature is supported by
1621 // the underlying solver.
1622 virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1623 LOG(ERROR) << "Solver doesn't support indicator constraints.";
1624 return false;
1625 }
1626
1627 // Add a variable.
1628 virtual void AddVariable(MPVariable* const var) = 0;
1629
1630 // Changes a coefficient in a constraint.
1631 virtual void SetCoefficient(MPConstraint* const constraint,
1632 const MPVariable* const variable,
1633 double new_value, double old_value) = 0;
1634
1635 // Clears a constraint from all its terms.
1636 virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1637
1638 // Changes a coefficient in the linear objective.
1639 virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1640 double coefficient) = 0;
1641
1642 // Changes the constant term in the linear objective.
1643 virtual void SetObjectiveOffset(double value) = 0;
1644
1645 // Clears the objective from all its terms.
1646 virtual void ClearObjective() = 0;
1647
1648 virtual void BranchingPriorityChangedForVariable(int var_index) {}
1649 // ------ Query statistics on the solution and the solve ------
1650 // Returns the number of simplex iterations. The problem must be discrete,
1651 // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1652 virtual int64_t iterations() const = 0;
1653 // Returns the number of branch-and-bound nodes. The problem must be discrete,
1654 // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1655 virtual int64_t nodes() const = 0;
1656 // Returns the best objective bound. The problem must be discrete, otherwise
1657 // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1658 double best_objective_bound() const;
1659 // Returns the objective value of the best solution found so far.
1660 double objective_value() const;
1661
1662 // Returns the basis status of a row.
1663 virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1664 // Returns the basis status of a constraint.
1665 virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1666
1667 // Checks whether the solution is synchronized with the model, i.e. whether
1668 // the model has changed since the solution was computed last.
1669 // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1671 // Checks whether a feasible solution exists. The behavior is similar to
1672 // CheckSolutionIsSynchronized() above.
1673 virtual bool CheckSolutionExists() const;
1674 // Handy shortcut to do both checks above (it is often used).
1677 }
1678
1679 // ----- Misc -----
1680 // Queries problem type. For simplicity, the distinction between
1681 // continuous and discrete is based on the declaration of the user
1682 // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1683 // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1684 // the model.
1685 // Returns true if the problem is continuous.
1686 virtual bool IsContinuous() const = 0;
1687 // Returns true if the problem is continuous and linear.
1688 virtual bool IsLP() const = 0;
1689 // Returns true if the problem is discrete and linear.
1690 virtual bool IsMIP() const = 0;
1691
1692 // Returns the index of the last variable extracted.
1694
1695 bool variable_is_extracted(int var_index) const {
1696 return solver_->variable_is_extracted_[var_index];
1697 }
1698 void set_variable_as_extracted(int var_index, bool extracted) {
1699 solver_->variable_is_extracted_[var_index] = extracted;
1700 }
1701 bool constraint_is_extracted(int ct_index) const {
1702 return solver_->constraint_is_extracted_[ct_index];
1703 }
1704 void set_constraint_as_extracted(int ct_index, bool extracted) {
1705 solver_->constraint_is_extracted_[ct_index] = extracted;
1706 }
1707
1708 // Returns the boolean indicating the verbosity of the solver output.
1709 bool quiet() const { return quiet_; }
1710 // Sets the boolean indicating the verbosity of the solver output.
1711 void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1712
1713 // Returns the result status of the last solve.
1716 return result_status_;
1717 }
1718
1719 // Returns a string describing the underlying solver and its version.
1720 virtual std::string SolverVersion() const = 0;
1721
1722 // Returns the underlying solver.
1723 virtual void* underlying_solver() = 0;
1724
1725 // Computes exact condition number. Only available for continuous
1726 // problems and only implemented in GLPK.
1727 virtual double ComputeExactConditionNumber() const;
1728
1729 // See MPSolver::SetStartingLpBasis().
1731 const std::vector<MPSolver::BasisStatus>& variable_statuses,
1732 const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1733 LOG(FATAL) << "Not supported by this solver.";
1734 }
1735
1736 virtual bool InterruptSolve() { return false; }
1737
1738 // See MPSolver::NextSolution() for contract.
1739 virtual bool NextSolution() { return false; }
1740
1741 // See MPSolver::SetCallback() for details.
1742 virtual void SetCallback(MPCallback* mp_callback) {
1743 LOG(FATAL) << "Callbacks not supported for this solver.";
1744 }
1745
1746 virtual bool SupportsCallbacks() const { return false; }
1747
1748 friend class MPSolver;
1749
1750 // To access the maximize_ bool and the MPSolver.
1751 friend class MPConstraint;
1752 friend class MPObjective;
1753
1754 protected:
1756 // Indicates whether the model and the solution are synchronized.
1758 // Indicates whether the solve has reached optimality,
1759 // infeasibility, a limit, etc.
1761 // Optimization direction.
1763
1764 // Index in MPSolver::variables_ of last constraint extracted.
1766 // Index in MPSolver::constraints_ of last variable extracted.
1768
1769 // The value of the objective function.
1771
1772 // The value of the best objective bound. Used only for MIP solvers.
1774
1775 // Boolean indicator for the verbosity of the solver output.
1777
1778 // Index of dummy variable created for empty constraints or the
1779 // objective offset.
1780 static const int kDummyVariableIndex;
1781
1782 // Extracts model stored in MPSolver.
1784 // Extracts the variables that have not been extracted yet.
1785 virtual void ExtractNewVariables() = 0;
1786 // Extracts the constraints that have not been extracted yet.
1787 virtual void ExtractNewConstraints() = 0;
1788 // Extracts the objective.
1789 virtual void ExtractObjective() = 0;
1790 // Resets the extraction information.
1792 // Change synchronization status from SOLUTION_SYNCHRONIZED to
1793 // MODEL_SYNCHRONIZED. To be used for model changes.
1795
1796 // Sets parameters common to LP and MIP in the underlying solver.
1798 // Sets MIP specific parameters in the underlying solver.
1800 // Sets all parameters in the underlying solver.
1801 virtual void SetParameters(const MPSolverParameters& param) = 0;
1802 // Sets an unsupported double parameter.
1804 // Sets an unsupported integer parameter.
1807 // Sets a supported double parameter to an unsupported value.
1809 double value);
1810 // Sets a supported integer parameter to an unsupported value.
1812 MPSolverParameters::IntegerParam param, int value);
1813 // Sets each parameter in the underlying solver.
1814 virtual void SetRelativeMipGap(double value) = 0;
1815 virtual void SetPrimalTolerance(double value) = 0;
1816 virtual void SetDualTolerance(double value) = 0;
1817 virtual void SetPresolveMode(int value) = 0;
1818
1819 // Sets the number of threads to be used by the solver.
1820 virtual absl::Status SetNumThreads(int num_threads);
1821
1822 // Pass solver specific parameters in text format. The format is
1823 // solver-specific and is the same as the corresponding solver configuration
1824 // file format. Returns true if the operation was successful.
1825 //
1826 // Default implementation returns true if the input is empty. It returns false
1827 // and logs a WARNING if the input is not empty.
1829 const std::string& parameters);
1830
1831 // Sets the scaling mode.
1832 virtual void SetScalingMode(int value) = 0;
1833 virtual void SetLpAlgorithm(int value) = 0;
1834};
1835
1836} // namespace operations_research
1837
1838#endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
LinearExpr models a quantity that is linear in the decision variables (MPVariable) of an optimization...
Definition: linear_expr.h:114
An expression of the form:
Definition: linear_expr.h:192
The class for constraints of a Mathematical Programming (MP) model.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
const std::string & name() const
Returns the name of the constraint.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable on the constraint.
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable on the constraint (which is 0 if the variable does not appea...
void SetUB(double ub)
Sets the upper bound.
double ub() const
Returns the upper bound.
MPConstraint(int index, double lb, double ub, const std::string &name, MPSolverInterface *const interface_in)
const MPVariable * indicator_variable() const
void Clear()
Clears all variables and coefficients. Does not clear the bounds.
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
void set_is_lazy(bool laziness)
Advanced usage: sets the constraint "laziness".
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
double lb() const
Returns the lower bound.
void set_dual_value(double dual_value)
void SetLB(double lb)
Sets the lower bound.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the constraint.
double dual_value() const
Advanced usage: returns the dual value of the constraint in the current solution (only available for ...
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the constraint.
static constexpr SolverType GUROBI_LINEAR_PROGRAMMING
static constexpr SolverType GUROBI_MIXED_INTEGER_PROGRAMMING
static constexpr SolverType SAT_INTEGER_PROGRAMMING
static constexpr SolverType GLOP_LINEAR_PROGRAMMING
A class to express a linear objective.
void SetMaximization()
Sets the optimization direction to maximize.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable in the objective.
void SetOffset(double value)
Sets the constant term in the objective.
bool maximization() const
Is the optimization direction set to maximize?
void OptimizeLinearExpr(const LinearExpr &linear_expr, bool is_maximization)
Resets the current objective to take the value of linear_expr, and sets the objective direction to ma...
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
double Value() const
Returns the objective value of the best solution found so far.
double offset() const
Gets the constant term in the objective.
double BestBound() const
Returns the best objective bound.
bool minimization() const
Is the optimization direction set to minimize?
void Clear()
Clears the offset, all variables and coefficients, and the optimization direction.
void SetMinimization()
Sets the optimization direction to minimize.
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the objective.
This mathematical programming (MP) solver class is the main class though which users build and solve ...
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
int NumConstraints() const
Returns the number of constraints.
ABSL_MUST_USE_RESULT bool NextSolution()
Some solvers (MIP only, not LP) can produce multiple solutions to the problem.
MPConstraint * MakeRowConstraint(double lb, double ub, const std::string &name)
Creates a named constraint with given bounds.
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
bool VerifySolution(double tolerance, bool log_errors) const
Advanced usage: Verifies the correctness of the solution.
MPConstraint * MakeRowConstraint(const LinearRange &range, const std::string &name)
As above, but also names the constraint.
absl::Duration DurationSinceConstruction() const
void Reset()
Advanced usage: resets extracted model to solve from scratch.
MPConstraint * constraint(int index) const
Returns the constraint at the given index.
MPVariable * LookupVariableOrNull(const std::string &var_name) const
Looks up a variable by name, and returns nullptr if it does not exist.
static bool ParseSolverType(absl::string_view solver_id, OptimizationProblemType *type)
Parses the name of the solver.
static OptimizationProblemType ParseSolverTypeOrDie(const std::string &solver_id)
Parses the name of the solver and returns the correct optimization type or dies.
int64_t iterations() const
Returns the number of simplex iterations.
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
Advanced usage: Incrementality.
MPConstraint * MakeRowConstraint(double lb, double ub)
Creates a linear constraint with given bounds.
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
const std::vector< MPConstraint * > & constraints() const
Returns the array of constraints handled by the MPSolver.
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
Sets a hint for solution.
double ComputeExactConditionNumber() const
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(i...
ResultStatus
The status of solving the problem.
@ FEASIBLE
feasible, or stopped by limit.
@ NOT_SOLVED
not been solved yet.
@ INFEASIBLE
proven infeasible.
@ UNBOUNDED
proven unbounded.
@ ABNORMAL
abnormal, i.e., error of some kind.
@ MODEL_INVALID
the model is trivially invalid (NaN coefficients, etc).
const std::vector< MPVariable * > & variables() const
Returns the array of variables handled by the MPSolver.
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
void MakeVarArray(int nb, double lb, double ub, bool integer, const std::string &name_prefix, std::vector< MPVariable * > *vars)
Creates an array of variables.
static int64_t global_num_constraints()
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response, std::atomic< bool > *interrupt=nullptr)
Solves the model encoded by a MPModelRequest protocol buffer and fills the solution encoded as a MPSo...
void * underlying_solver()
Advanced usage: returns the underlying solver.
void set_time_limit(int64_t time_limit_milliseconds)
OptimizationProblemType
The type of problems (LP or MIP) that will be solved and the underlying solver (GLOP,...
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
absl::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=std::numeric_limits< double >::infinity())
Load a solution encoded in a protocol buffer onto this solver for easy access via the MPSolver interf...
static MPSolver * CreateSolver(const std::string &solver_id)
Recommended factory method to create a MPSolver instance, especially in non C++ languages.
absl::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying solver.
const std::string & Name() const
Returns the name of the model set at construction.
std::string SolverVersion() const
Returns a string describing the underlying solver and its version.
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
int GetNumThreads() const
Returns the number of threads to be used during solve.
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
std::vector< double > ComputeConstraintActivities() const
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms...
static double infinity()
Infinity.
std::string GetSolverSpecificParametersAsString() const
int NumVariables() const
Returns the number of variables.
absl::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
ResultStatus Solve()
Solves the problem using the default parameter values.
static int64_t global_num_variables()
bool OwnsVariable(const MPVariable *var) const
int64_t nodes() const
Returns the number of branch-and-bound nodes evaluated during the solve.
void Clear()
Clears the objective (including the optimization direction), all variables and constraints.
MPVariable * variable(int index) const
Returns the variable at position index.
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
Shortcuts to the homonymous MPModelProtoExporter methods, via exporting to a MPModelProto with Export...
ResultStatus Solve(const MPSolverParameters &param)
Solves the problem using the specified parameter values.
void Write(const std::string &file_name)
Writes the model using the solver internal write function.
MPConstraint * MakeRowConstraint(const LinearRange &range)
Creates a constraint owned by MPSolver enforcing: range.lower_bound() <= range.linear_expr() <= range...
MPConstraint * MakeRowConstraint()
Creates a constraint with -infinity and +infinity bounds.
void SetCallback(MPCallback *mp_callback)
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
bool OutputIsEnabled() const
Controls (or queries) the amount of output produced by the underlying solver.
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
MPVariable * MakeVar(double lb, double ub, bool integer, const std::string &name)
Creates a variable with the given bounds, integrality requirement and name.
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
Looks up a constraint by name, and returns nullptr if it does not exist.
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
const MPObjective & Objective() const
Returns the objective object.
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
void EnableOutput()
Enables solver logging.
void SuppressOutput()
Suppresses solver logging.
static bool SolverTypeSupportsInterruption(const MPModelRequest::SolverType solver)
MPConstraint * MakeRowConstraint(const std::string &name)
Creates a named constraint with -infinity and +infinity bounds.
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
MPObjective * MutableObjective()
Returns the mutable objective object.
virtual OptimizationProblemType ProblemType() const
Returns the optimization problem type set at construction.
absl::Duration TimeLimit() const
static bool SupportsProblemType(OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
void SetTimeLimit(absl::Duration time_limit)
virtual void SetLpAlgorithm(int value)=0
virtual absl::Status SetNumThreads(int num_threads)
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
virtual void Write(const std::string &filename)
void set_constraint_as_extracted(int ct_index, bool extracted)
virtual bool AddIndicatorConstraint(MPConstraint *const ct)
virtual void AddVariable(MPVariable *const var)=0
virtual absl::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request, std::atomic< bool > *interrupt)
void SetMIPParameters(const MPSolverParameters &param)
virtual bool IsContinuous() const =0
virtual int64_t iterations() const =0
virtual int64_t nodes() const =0
MPSolverInterface(MPSolver *const solver)
bool constraint_is_extracted(int ct_index) const
virtual void SetVariableBounds(int index, double lb, double ub)=0
virtual void SetPrimalTolerance(double value)=0
static constexpr int64_t kUnknownNumberOfNodes
virtual void BranchingPriorityChangedForVariable(int var_index)
virtual void SetParameters(const MPSolverParameters &param)=0
virtual void SetRelativeMipGap(double value)=0
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
virtual void SetOptimizationDirection(bool maximize)=0
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
virtual void SetScalingMode(int value)=0
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
virtual std::string SolverVersion() const =0
virtual void ClearConstraint(MPConstraint *const constraint)=0
virtual void SetObjectiveOffset(double value)=0
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
virtual void SetVariableInteger(int index, bool integer)=0
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
virtual void SetCallback(MPCallback *mp_callback)
bool variable_is_extracted(int var_index) const
virtual void SetDualTolerance(double value)=0
virtual bool CheckSolutionExists() const
virtual void SetPresolveMode(int value)=0
static constexpr int64_t kUnknownNumberOfIterations
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
MPSolver::ResultStatus result_status() const
virtual void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value)=0
virtual void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient)=0
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
void set_variable_as_extracted(int var_index, bool extracted)
virtual void SetConstraintBounds(int index, double lb, double ub)=0
virtual double ComputeExactConditionNumber() const
void SetCommonParameters(const MPSolverParameters &param)
virtual void AddRowConstraint(MPConstraint *const ct)=0
This class stores parameter settings for LP and MIP solvers.
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
Sets an integer parameter to its default value (default value defined in MPSolverParameters if it exi...
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
IncrementalityValues
Advanced usage: Incrementality options.
@ INCREMENTALITY_OFF
Start solve from scratch.
@ INCREMENTALITY_ON
Reuse results from previous solve as much as the underlying solver allows.
ScalingValues
Advanced usage: Scaling options.
void Reset()
Sets all parameters to their default value.
DoubleParam
Enumeration of parameters that take continuous values.
@ DUAL_TOLERANCE
Advanced usage: tolerance for dual feasibility of basic solutions.
@ PRIMAL_TOLERANCE
Advanced usage: tolerance for primal feasibility of basic solutions.
@ RELATIVE_MIP_GAP
Limit for relative MIP gap.
static const IncrementalityValues kDefaultIncrementality
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
IntegerParam
Enumeration of parameters that take integer or categorical values.
@ LP_ALGORITHM
Algorithm to solve linear programs.
@ SCALING
Advanced usage: enable or disable matrix scaling.
@ PRESOLVE
Advanced usage: presolve mode.
@ INCREMENTALITY
Advanced usage: incrementality from one solve to the next.
PresolveValues
For each categorical parameter, enumeration of possible values.
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
static const PresolveValues kDefaultPresolve
MPSolverParameters()
The constructor sets all parameters to their default value.
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
Sets a double parameter to its default value (default value defined in MPSolverParameters if it exist...
The class for variables of a Mathematical Programming (MP) model.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
double unrounded_solution_value() const
Advanced usage: unrounded solution value.
const std::string & name() const
Returns the name of the variable.
int branching_priority() const
Advanced usage: Certain MIP solvers (e.g.
void set_solution_value(double value)
void SetBranchingPriority(int priority)
void SetUB(double ub)
Sets the upper bound.
double ub() const
Returns the upper bound.
double reduced_cost() const
Advanced usage: returns the reduced cost of the variable in the current solution (only available for ...
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
MPVariable(int index, double lb, double ub, bool integer, const std::string &name, MPSolverInterface *const interface_in)
void set_reduced_cost(double reduced_cost)
bool integer() const
Returns the integrality requirement of the variable.
int index() const
Returns the index of the variable in the MPSolver::variables_.
double lb() const
Returns the lower bound.
void SetLB(double lb)
Sets the lower bound.
double solution_value() const
Returns the value of the variable in the current solution.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the variable in the current solution (only available for ...
This file allows you to write natural code (like a mathematical equation) to model optimization probl...
ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output)
constexpr double kDefaultPrimalTolerance
bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status)
bool AbslParseFlag(absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
std::ostream & operator<<(std::ostream &stream, const LinearExpr &linear_expr)
std::string AbslUnparseFlag(MPSolver::OptimizationProblemType solver_type)
const absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)