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/flags/parse.h"
149#include "absl/flags/usage.h"
150#include "absl/status/status.h"
151#include "absl/strings/match.h"
152#include "absl/strings/str_format.h"
153#include "absl/types/optional.h"
154#include "ortools/base/integral_types.h"
155#include "ortools/base/logging.h"
156#include "ortools/base/macros.h"
157#include "ortools/base/timer.h"
160#include "ortools/linear_solver/linear_solver_callback.h"
161#include "ortools/port/proto_utils.h"
162
163ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
164
165namespace operations_research {
166
167constexpr double kDefaultPrimalTolerance = 1e-07;
168
169class MPConstraint;
170class MPObjective;
173class MPVariable;
174
175// There is a homonymous version taking a MPSolver::OptimizationProblemType.
177
182class MPSolver {
183 public:
191 // Linear programming problems.
192 // ----------------------------
195 GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
196
197 // Integer programming problems.
198 // -----------------------------
199 SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
202
203 // Commercial software (need license).
210
211 // Boolean optimization problem (requires only integer variables and works
212 // best with only Boolean variables).
214
215 // SAT based solver (requires only integer and Boolean variables).
216 // If you pass it mixed integer problems, it will scale coefficients to
217 // integer values, and solver continuous variables as integral variables.
219
220 // Dedicated knapsack solvers.
222 };
223
225 MPSolver(const std::string& name, OptimizationProblemType problem_type);
226 virtual ~MPSolver();
227
256 static MPSolver* CreateSolver(const std::string& solver_id);
257
263
269 static bool ParseSolverType(absl::string_view solver_id,
271
277 const std::string& solver_id);
278
279 bool IsMIP() const;
280
282 const std::string& Name() const {
283 return name_; // Set at construction.
284 }
285
288 return problem_type_; // Set at construction.
289 }
290
296 void Clear();
297
299 int NumVariables() const { return variables_.size(); }
300
305 const std::vector<MPVariable*>& variables() const { return variables_; }
306
310 MPVariable* variable(int index) const { return variables_[index]; }
311
317 MPVariable* LookupVariableOrNull(const std::string& var_name) const;
318
326 MPVariable* MakeVar(double lb, double ub, bool integer,
327 const std::string& name);
328
330 MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
331
333 MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
334
336 MPVariable* MakeBoolVar(const std::string& name);
337
352 void MakeVarArray(int nb, double lb, double ub, bool integer,
353 const std::string& name_prefix,
354 std::vector<MPVariable*>* vars);
355
357 void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
358 std::vector<MPVariable*>* vars);
359
361 void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
362 std::vector<MPVariable*>* vars);
363
365 void MakeBoolVarArray(int nb, const std::string& name,
366 std::vector<MPVariable*>* vars);
367
369 int NumConstraints() const { return constraints_.size(); }
370
376 const std::vector<MPConstraint*>& constraints() const { return constraints_; }
377
379 MPConstraint* constraint(int index) const { return constraints_[index]; }
380
389 const std::string& constraint_name) const;
390
399 MPConstraint* MakeRowConstraint(double lb, double ub);
400
403
405 MPConstraint* MakeRowConstraint(double lb, double ub,
406 const std::string& name);
407
409 MPConstraint* MakeRowConstraint(const std::string& name);
410
416
419 const std::string& name);
420
427 const MPObjective& Objective() const { return *objective_; }
428
430 MPObjective* MutableObjective() { return objective_.get(); }
431
452 NOT_SOLVED = 6
453 };
454
457
460
465 void Write(const std::string& file_name);
466
473 std::vector<double> ComputeConstraintActivities() const;
474
493 bool VerifySolution(double tolerance, bool log_errors) const;
494
503 void Reset();
504
515
524 std::string* error_message);
533 const MPModelProto& input_model, std::string* error_message);
534
537
553 static void SolveWithProto(const MPModelRequest& model_request,
554 MPSolutionResponse* response,
555 // `interrupt` is non-const because the internal
556 // solver may set it to true itself, in some cases.
557 std::atomic<bool>* interrupt = nullptr);
558
560 const MPModelRequest::SolverType solver) {
561 // Interruption requires that MPSolver::InterruptSolve is supported for the
562 // underlying solver. Interrupting requests using SCIP is also not supported
563 // as of 2021/08/23, since InterruptSolve is not go/thread-safe
564 // for SCIP (see e.g. cl/350545631 for details).
569 }
570
572 void ExportModelToProto(MPModelProto* output_model) const;
573
608 const MPSolutionResponse& response,
609 double tolerance = std::numeric_limits<double>::infinity());
610
616
623 bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
624 bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
625 std::string* model_str) const;
626
637 absl::Status SetNumThreads(int num_threads);
638
640 int GetNumThreads() const { return num_threads_; }
641
648 bool SetSolverSpecificParametersAsString(const std::string& parameters);
650 return solver_specific_parameter_string_;
651 }
652
666 void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
667
673 FREE = 0,
677 BASIC
678 };
679
692 const std::vector<MPSolver::BasisStatus>& variable_statuses,
693 const std::vector<MPSolver::BasisStatus>& constraint_statuses);
694
700 static double infinity() { return std::numeric_limits<double>::infinity(); }
701
710 bool OutputIsEnabled() const;
711
714
717
718 absl::Duration TimeLimit() const { return time_limit_; }
719 void SetTimeLimit(absl::Duration time_limit) {
720 DCHECK_GE(time_limit, absl::ZeroDuration());
721 time_limit_ = time_limit;
722 }
723
724 absl::Duration DurationSinceConstruction() const {
725 return absl::Now() - construction_time_;
726 }
727
729 int64_t iterations() const;
730
736 int64_t nodes() const;
737
739 std::string SolverVersion() const;
740
755
780
795 ABSL_MUST_USE_RESULT bool NextSolution();
796
797 // Does not take ownership of "mp_callback".
798 //
799 // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
800 // SCIP does not support suggesting a heuristic solution in the callback.
801 //
802 // See go/mpsolver-callbacks for additional documentation.
803 void SetCallback(MPCallback* mp_callback);
804 bool SupportsCallbacks() const;
805
806 // Global counters of variables and constraints ever created across all
807 // MPSolver instances. Those are only updated after the destruction
808 // (or Clear()) of each MPSolver instance.
809 static int64_t global_num_variables();
810 static int64_t global_num_constraints();
811
812 // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
813 // NOTE: These deprecated functions used the convention time_limit = 0 to mean
814 // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
815 int64_t time_limit() const {
816 return time_limit_ == absl::InfiniteDuration()
817 ? 0
818 : absl::ToInt64Milliseconds(time_limit_);
819 }
820 void set_time_limit(int64_t time_limit_milliseconds) {
821 SetTimeLimit(time_limit_milliseconds == 0
822 ? absl::InfiniteDuration()
823 : absl::Milliseconds(time_limit_milliseconds));
824 }
825 double time_limit_in_secs() const {
826 return static_cast<double>(time_limit()) / 1000.0;
827 }
828
829 // DEPRECATED: Use DurationSinceConstruction() instead.
830 int64_t wall_time() const {
831 return absl::ToInt64Milliseconds(DurationSinceConstruction());
832 }
833
834 friend class GLPKInterface;
835 friend class CLPInterface;
836 friend class CBCInterface;
837 friend class SCIPInterface;
838 friend class GurobiInterface;
839 friend class CplexInterface;
840 friend class XpressInterface;
841 friend class SLMInterface;
842 friend class MPSolverInterface;
843 friend class GLOPInterface;
844 friend class BopInterface;
845 friend class SatInterface;
846 friend class KnapsackInterface;
847
848 // Debugging: verify that the given MPVariable* belongs to this solver.
849 bool OwnsVariable(const MPVariable* var) const;
850
851 private:
852 // Computes the size of the constraint with the largest number of
853 // coefficients with index in [min_constraint_index,
854 // max_constraint_index)
855 int ComputeMaxConstraintSize(int min_constraint_index,
856 int max_constraint_index) const;
857
858 // Returns true if the model has constraints with lower bound > upper bound.
859 bool HasInfeasibleConstraints() const;
860
861 // Returns true if the model has at least 1 integer variable.
862 bool HasIntegerVariables() const;
863
864 // Generates the map from variable names to their indices.
865 void GenerateVariableNameIndex() const;
866
867 // Generates the map from constraint names to their indices.
868 void GenerateConstraintNameIndex() const;
869
870 // The name of the linear programming problem.
871 const std::string name_;
872
873 // The type of the linear programming problem.
874 const OptimizationProblemType problem_type_;
875
876 // The solver interface.
877 std::unique_ptr<MPSolverInterface> interface_;
878
879 // The vector of variables in the problem.
880 std::vector<MPVariable*> variables_;
881 // A map from a variable's name to its index in variables_.
882 mutable absl::optional<absl::flat_hash_map<std::string, int> >
883 variable_name_to_index_;
884 // Whether variables have been extracted to the underlying interface.
885 std::vector<bool> variable_is_extracted_;
886
887 // The vector of constraints in the problem.
888 std::vector<MPConstraint*> constraints_;
889 // A map from a constraint's name to its index in constraints_.
890 mutable absl::optional<absl::flat_hash_map<std::string, int> >
891 constraint_name_to_index_;
892 // Whether constraints have been extracted to the underlying interface.
893 std::vector<bool> constraint_is_extracted_;
894
895 // The linear objective function.
896 std::unique_ptr<MPObjective> objective_;
897
898 // Initial values for all or some of the problem variables that can be
899 // exploited as a starting hint by a solver.
900 //
901 // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
902 //
903 // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
904 // hint is provided and a std::vector<double> for the hint value.
905 std::vector<std::pair<const MPVariable*, double> > solution_hint_;
906
907 absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
908
909 const absl::Time construction_time_;
910
911 // Permanent storage for the number of threads.
912 int num_threads_ = 1;
913
914 // Permanent storage for SetSolverSpecificParametersAsString().
915 std::string solver_specific_parameter_string_;
916
917 static absl::Mutex global_count_mutex_;
918#ifndef SWIG
919 static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
920 static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
921#endif
922
923 MPSolverResponseStatus LoadModelFromProtoInternal(
924 const MPModelProto& input_model, bool clear_names,
925 bool check_model_validity, std::string* error_message);
926
927 DISALLOW_COPY_AND_ASSIGN(MPSolver);
928};
929
931 return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
932}
933
934const absl::string_view ToString(
935 MPSolver::OptimizationProblemType optimization_problem_type);
936
937inline std::ostream& operator<<(
938 std::ostream& os,
939 MPSolver::OptimizationProblemType optimization_problem_type) {
940 return os << ToString(optimization_problem_type);
941}
942
943inline std::ostream& operator<<(std::ostream& os,
944 MPSolver::ResultStatus status) {
945 return os << ProtoEnumToString<MPSolverResponseStatus>(
946 static_cast<MPSolverResponseStatus>(status));
947}
948
949bool AbslParseFlag(absl::string_view text,
951 std::string* error);
952
953inline std::string AbslUnparseFlag(
955 return std::string(ToString(solver_type));
956}
957
960 public:
965 void Clear();
966
973 void SetCoefficient(const MPVariable* const var, double coeff);
974
980 double GetCoefficient(const MPVariable* const var) const;
981
987 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
988 return coefficients_;
989 }
990
992 void SetOffset(double value);
993
995 double offset() const { return offset_; }
996
1001 void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1002
1004 void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1005 OptimizeLinearExpr(linear_expr, true);
1006 }
1008 void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1009 OptimizeLinearExpr(linear_expr, false);
1010 }
1011
1013 void AddLinearExpr(const LinearExpr& linear_expr);
1014
1016 void SetOptimizationDirection(bool maximize);
1017
1020
1023
1025 bool maximization() const;
1026
1028 bool minimization() const;
1029
1041 double Value() const;
1042
1049 double BestBound() const;
1050
1051 private:
1052 friend class MPSolver;
1053 friend class MPSolverInterface;
1054 friend class CBCInterface;
1055 friend class CLPInterface;
1056 friend class GLPKInterface;
1057 friend class SCIPInterface;
1058 friend class SLMInterface;
1059 friend class GurobiInterface;
1060 friend class CplexInterface;
1061 friend class XpressInterface;
1062 friend class GLOPInterface;
1063 friend class BopInterface;
1064 friend class SatInterface;
1065 friend class KnapsackInterface;
1066
1067 // Constructor. An objective points to a single MPSolverInterface
1068 // that is specified in the constructor. An objective cannot belong
1069 // to several models.
1070 // At construction, an MPObjective has no terms (which is equivalent
1071 // on having a coefficient of 0 for all variables), and an offset of 0.
1072 explicit MPObjective(MPSolverInterface* const interface_in)
1073 : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1074
1075 MPSolverInterface* const interface_;
1076
1077 // Mapping var -> coefficient.
1078 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1079 // Constant term.
1080 double offset_;
1081
1082 DISALLOW_COPY_AND_ASSIGN(MPObjective);
1083};
1084
1087 public:
1089 const std::string& name() const { return name_; }
1090
1093
1095 bool integer() const { return integer_; }
1096
1104 double solution_value() const;
1105
1107 int index() const { return index_; }
1108
1110 double lb() const { return lb_; }
1111
1113 double ub() const { return ub_; }
1114
1116 void SetLB(double lb) { SetBounds(lb, ub_); }
1117
1119 void SetUB(double ub) { SetBounds(lb_, ub); }
1120
1122 void SetBounds(double lb, double ub);
1123
1131
1136 double reduced_cost() const;
1137
1145
1156 int branching_priority() const { return branching_priority_; }
1157 void SetBranchingPriority(int priority);
1158
1159 protected:
1160 friend class MPSolver;
1161 friend class MPSolverInterface;
1162 friend class CBCInterface;
1163 friend class CLPInterface;
1164 friend class GLPKInterface;
1165 friend class SCIPInterface;
1166 friend class SLMInterface;
1167 friend class GurobiInterface;
1168 friend class CplexInterface;
1169 friend class XpressInterface;
1170 friend class GLOPInterface;
1172 friend class BopInterface;
1173 friend class SatInterface;
1174 friend class KnapsackInterface;
1175
1176 // Constructor. A variable points to a single MPSolverInterface that
1177 // is specified in the constructor. A variable cannot belong to
1178 // several models.
1179 MPVariable(int index, double lb, double ub, bool integer,
1180 const std::string& name, MPSolverInterface* const interface_in)
1181 : index_(index),
1182 lb_(lb),
1183 ub_(ub),
1184 integer_(integer),
1185 name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1186 solution_value_(0.0),
1187 reduced_cost_(0.0),
1188 interface_(interface_in) {}
1189
1190 void set_solution_value(double value) { solution_value_ = value; }
1191 void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1192
1193 private:
1194 const int index_;
1195 double lb_;
1196 double ub_;
1197 bool integer_;
1198 const std::string name_;
1199 double solution_value_;
1200 double reduced_cost_;
1201 int branching_priority_ = 0;
1202 MPSolverInterface* const interface_;
1203 DISALLOW_COPY_AND_ASSIGN(MPVariable);
1204};
1205
1212 public:
1214 const std::string& name() const { return name_; }
1215
1217 void Clear();
1218
1225 void SetCoefficient(const MPVariable* const var, double coeff);
1226
1231 double GetCoefficient(const MPVariable* const var) const;
1232
1238 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1239 return coefficients_;
1240 }
1241
1243 double lb() const { return lb_; }
1244
1246 double ub() const { return ub_; }
1247
1249 void SetLB(double lb) { SetBounds(lb, ub_); }
1250
1252 void SetUB(double ub) { SetBounds(lb_, ub); }
1253
1255 void SetBounds(double lb, double ub);
1256
1258 bool is_lazy() const { return is_lazy_; }
1259
1273 void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1274
1275 const MPVariable* indicator_variable() const { return indicator_variable_; }
1276 bool indicator_value() const { return indicator_value_; }
1277
1279 int index() const { return index_; }
1280
1285 double dual_value() const;
1286
1300
1301 protected:
1302 friend class MPSolver;
1303 friend class MPSolverInterface;
1304 friend class CBCInterface;
1305 friend class CLPInterface;
1306 friend class GLPKInterface;
1307 friend class SCIPInterface;
1308 friend class SLMInterface;
1309 friend class GurobiInterface;
1310 friend class CplexInterface;
1311 friend class XpressInterface;
1312 friend class GLOPInterface;
1313 friend class BopInterface;
1314 friend class SatInterface;
1315 friend class KnapsackInterface;
1316
1317 // Constructor. A constraint points to a single MPSolverInterface
1318 // that is specified in the constructor. A constraint cannot belong
1319 // to several models.
1320 MPConstraint(int index, double lb, double ub, const std::string& name,
1321 MPSolverInterface* const interface_in)
1322 : coefficients_(1),
1323 index_(index),
1324 lb_(lb),
1325 ub_(ub),
1326 name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1327 is_lazy_(false),
1328 indicator_variable_(nullptr),
1329 dual_value_(0.0),
1330 interface_(interface_in) {}
1331
1332 void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1333
1334 private:
1335 // Returns true if the constraint contains variables that have not
1336 // been extracted yet.
1337 bool ContainsNewVariables();
1338
1339 // Mapping var -> coefficient.
1340 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1341
1342 const int index_; // See index().
1343
1344 // The lower bound for the linear constraint.
1345 double lb_;
1346
1347 // The upper bound for the linear constraint.
1348 double ub_;
1349
1350 // Name.
1351 const std::string name_;
1352
1353 // True if the constraint is "lazy", i.e. the constraint is added to the
1354 // underlying Linear Programming solver only if it is violated.
1355 // By default this parameter is 'false'.
1356 bool is_lazy_;
1357
1358 // If given, this constraint is only active if `indicator_variable_`'s value
1359 // is equal to `indicator_value_`.
1360 const MPVariable* indicator_variable_;
1361 bool indicator_value_;
1362
1363 double dual_value_;
1364 MPSolverInterface* const interface_;
1365 DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1366};
1367
1395 public:
1400
1409 DUAL_TOLERANCE = 2
1411
1415 PRESOLVE = 1000,
1421 SCALING = 1003
1423
1429 PRESOLVE_ON = 1
1431
1435 DUAL = 10,
1439 BARRIER = 12
1441
1446
1453
1459 SCALING_ON = 1
1461
1462 // Placeholder value to indicate that a parameter is set to
1463 // the default value defined in the wrapper.
1464 static const double kDefaultDoubleParamValue;
1466
1467 // Placeholder value to indicate that a parameter is unknown.
1468 static const double kUnknownDoubleParamValue;
1470
1471 // Default values for parameters. Only parameters that define the
1472 // properties of the solution returned need to have a default value
1473 // (that is the same for all solvers). You can also define a default
1474 // value for performance parameters when you are confident it is a
1475 // good choice (example: always turn presolve on).
1476 static const double kDefaultRelativeMipGap;
1477 static const double kDefaultPrimalTolerance;
1478 static const double kDefaultDualTolerance;
1481
1484
1487
1490
1497
1504
1506 void Reset();
1507
1510
1513
1514 private:
1515 // Parameter value for each parameter.
1516 // @see DoubleParam
1517 // @see IntegerParam
1518 double relative_mip_gap_value_;
1519 double primal_tolerance_value_;
1520 double dual_tolerance_value_;
1521 int presolve_value_;
1522 int scaling_value_;
1523 int lp_algorithm_value_;
1524 int incrementality_value_;
1525
1526 // Boolean value indicating whether each parameter is set to the
1527 // solver's default value. Only parameters for which the wrapper
1528 // does not define a default value need such an indicator.
1529 bool lp_algorithm_is_default_;
1530
1531 DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1532};
1533
1534// Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1535// error when happening on the linear solver stubby server, see
1536// ./linear_solver_service.proto.
1537// Note that RPC errors forbid to carry a response to the client, who can only
1538// see the RPC error itself (error code + error message).
1540
1541// This class wraps the actual mathematical programming solvers. Each
1542// solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1543// derives from this abstract class. This class is never directly
1544// accessed by the user.
1545// @see glop_interface.cc
1546// @see cbc_interface.cc
1547// @see clp_interface.cc
1548// @see glpk_interface.cc
1549// @see scip_interface.cc
1551 public:
1553 // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1554 // sync for the model nor for the solution.
1556 // The underlying solver and MPSolver are in sync for the model
1557 // but not for the solution: the model has changed since the
1558 // solution was computed last.
1560 // The underlying solver and MPSolver are in sync for the model and
1561 // the solution.
1564
1565 // When the underlying solver does not provide the number of simplex
1566 // iterations.
1567 static constexpr int64_t kUnknownNumberOfIterations = -1;
1568 // When the underlying solver does not provide the number of
1569 // branch-and-bound nodes.
1570 static constexpr int64_t kUnknownNumberOfNodes = -1;
1571
1572 // Constructor. The user will access the MPSolverInterface through the
1573 // MPSolver passed as argument.
1574 explicit MPSolverInterface(MPSolver* const solver);
1576
1577 // ----- Solve -----
1578 // Solves problem with specified parameter values. Returns true if the
1579 // solution is optimal.
1581
1582 // Attempts to directly solve a MPModelRequest, bypassing the MPSolver data
1583 // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1584 // an 'interrupt' boolean.
1585 // Returns {} (eg. absl::nullopt) if direct-solve is not supported by the
1586 // underlying solver (possibly because interrupt != nullptr), in which case
1587 // the user should fall back to using MPSolver.
1588 virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1589 const MPModelRequest& request,
1590 // `interrupt` is non-const because the internal
1591 // solver may set it to true itself, in some cases.
1592 std::atomic<bool>* interrupt) {
1593 return absl::nullopt;
1594 }
1595
1596 // Writes the model using the solver internal write function. Currently only
1597 // available for GurobiInterface.
1598 virtual void Write(const std::string& filename);
1599
1600 // ----- Model modifications and extraction -----
1601 // Resets extracted model.
1602 virtual void Reset() = 0;
1603
1604 // Sets the optimization direction (min/max).
1605 virtual void SetOptimizationDirection(bool maximize) = 0;
1606
1607 // Modifies bounds of an extracted variable.
1608 virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1609
1610 // Modifies integrality of an extracted variable.
1611 virtual void SetVariableInteger(int index, bool integer) = 0;
1612
1613 // Modify bounds of an extracted variable.
1614 virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1615
1616 // Adds a linear constraint.
1617 virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1618
1619 // Adds an indicator constraint. Returns true if the feature is supported by
1620 // the underlying solver.
1621 virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1622 LOG(ERROR) << "Solver doesn't support indicator constraints.";
1623 return false;
1624 }
1625
1626 // Add a variable.
1627 virtual void AddVariable(MPVariable* const var) = 0;
1628
1629 // Changes a coefficient in a constraint.
1630 virtual void SetCoefficient(MPConstraint* const constraint,
1631 const MPVariable* const variable,
1632 double new_value, double old_value) = 0;
1633
1634 // Clears a constraint from all its terms.
1635 virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1636
1637 // Changes a coefficient in the linear objective.
1638 virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1639 double coefficient) = 0;
1640
1641 // Changes the constant term in the linear objective.
1642 virtual void SetObjectiveOffset(double value) = 0;
1643
1644 // Clears the objective from all its terms.
1645 virtual void ClearObjective() = 0;
1646
1647 virtual void BranchingPriorityChangedForVariable(int var_index) {}
1648 // ------ Query statistics on the solution and the solve ------
1649 // Returns the number of simplex iterations. The problem must be discrete,
1650 // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1651 virtual int64_t iterations() const = 0;
1652 // Returns the number of branch-and-bound nodes. The problem must be discrete,
1653 // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1654 virtual int64_t nodes() const = 0;
1655 // Returns the best objective bound. The problem must be discrete, otherwise
1656 // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1657 double best_objective_bound() const;
1658 // Returns the objective value of the best solution found so far.
1659 double objective_value() const;
1660
1661 // Returns the basis status of a row.
1662 virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1663 // Returns the basis status of a constraint.
1664 virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1665
1666 // Checks whether the solution is synchronized with the model, i.e. whether
1667 // the model has changed since the solution was computed last.
1668 // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1670 // Checks whether a feasible solution exists. The behavior is similar to
1671 // CheckSolutionIsSynchronized() above.
1672 virtual bool CheckSolutionExists() const;
1673 // Handy shortcut to do both checks above (it is often used).
1676 }
1677
1678 // ----- Misc -----
1679 // Queries problem type. For simplicity, the distinction between
1680 // continuous and discrete is based on the declaration of the user
1681 // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1682 // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1683 // the model.
1684 // Returns true if the problem is continuous.
1685 virtual bool IsContinuous() const = 0;
1686 // Returns true if the problem is continuous and linear.
1687 virtual bool IsLP() const = 0;
1688 // Returns true if the problem is discrete and linear.
1689 virtual bool IsMIP() const = 0;
1690
1691 // Returns the index of the last variable extracted.
1693
1694 bool variable_is_extracted(int var_index) const {
1695 return solver_->variable_is_extracted_[var_index];
1696 }
1697 void set_variable_as_extracted(int var_index, bool extracted) {
1698 solver_->variable_is_extracted_[var_index] = extracted;
1699 }
1700 bool constraint_is_extracted(int ct_index) const {
1701 return solver_->constraint_is_extracted_[ct_index];
1702 }
1703 void set_constraint_as_extracted(int ct_index, bool extracted) {
1704 solver_->constraint_is_extracted_[ct_index] = extracted;
1705 }
1706
1707 // Returns the boolean indicating the verbosity of the solver output.
1708 bool quiet() const { return quiet_; }
1709 // Sets the boolean indicating the verbosity of the solver output.
1710 void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1711
1712 // Returns the result status of the last solve.
1715 return result_status_;
1716 }
1717
1718 // Returns a string describing the underlying solver and its version.
1719 virtual std::string SolverVersion() const = 0;
1720
1721 // Returns the underlying solver.
1722 virtual void* underlying_solver() = 0;
1723
1724 // Computes exact condition number. Only available for continuous
1725 // problems and only implemented in GLPK.
1726 virtual double ComputeExactConditionNumber() const;
1727
1728 // See MPSolver::SetStartingLpBasis().
1730 const std::vector<MPSolver::BasisStatus>& variable_statuses,
1731 const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1732 LOG(FATAL) << "Not supported by this solver.";
1733 }
1734
1735 virtual bool InterruptSolve() { return false; }
1736
1737 // See MPSolver::NextSolution() for contract.
1738 virtual bool NextSolution() { return false; }
1739
1740 // See MPSolver::SetCallback() for details.
1741 virtual void SetCallback(MPCallback* mp_callback) {
1742 LOG(FATAL) << "Callbacks not supported for this solver.";
1743 }
1744
1745 virtual bool SupportsCallbacks() const { return false; }
1746
1747 friend class MPSolver;
1748
1749 // To access the maximize_ bool and the MPSolver.
1750 friend class MPConstraint;
1751 friend class MPObjective;
1752
1753 protected:
1755 // Indicates whether the model and the solution are synchronized.
1757 // Indicates whether the solve has reached optimality,
1758 // infeasibility, a limit, etc.
1760 // Optimization direction.
1762
1763 // Index in MPSolver::variables_ of last constraint extracted.
1765 // Index in MPSolver::constraints_ of last variable extracted.
1767
1768 // The value of the objective function.
1770
1771 // The value of the best objective bound. Used only for MIP solvers.
1773
1774 // Boolean indicator for the verbosity of the solver output.
1776
1777 // Index of dummy variable created for empty constraints or the
1778 // objective offset.
1779 static const int kDummyVariableIndex;
1780
1781 // Extracts model stored in MPSolver.
1783 // Extracts the variables that have not been extracted yet.
1784 virtual void ExtractNewVariables() = 0;
1785 // Extracts the constraints that have not been extracted yet.
1786 virtual void ExtractNewConstraints() = 0;
1787 // Extracts the objective.
1788 virtual void ExtractObjective() = 0;
1789 // Resets the extraction information.
1791 // Change synchronization status from SOLUTION_SYNCHRONIZED to
1792 // MODEL_SYNCHRONIZED. To be used for model changes.
1794
1795 // Sets parameters common to LP and MIP in the underlying solver.
1797 // Sets MIP specific parameters in the underlying solver.
1799 // Sets all parameters in the underlying solver.
1800 virtual void SetParameters(const MPSolverParameters& param) = 0;
1801 // Sets an unsupported double parameter.
1803 // Sets an unsupported integer parameter.
1806 // Sets a supported double parameter to an unsupported value.
1808 double value);
1809 // Sets a supported integer parameter to an unsupported value.
1811 MPSolverParameters::IntegerParam param, int value);
1812 // Sets each parameter in the underlying solver.
1813 virtual void SetRelativeMipGap(double value) = 0;
1814 virtual void SetPrimalTolerance(double value) = 0;
1815 virtual void SetDualTolerance(double value) = 0;
1816 virtual void SetPresolveMode(int value) = 0;
1817
1818 // Sets the number of threads to be used by the solver.
1819 virtual absl::Status SetNumThreads(int num_threads);
1820
1821 // Pass solver specific parameters in text format. The format is
1822 // solver-specific and is the same as the corresponding solver configuration
1823 // file format. Returns true if the operation was successful.
1824 //
1825 // Default implementation returns true if the input is empty. It returns false
1826 // and logs a WARNING if the input is not empty.
1828 const std::string& parameters);
1829
1830 // Sets the scaling mode.
1831 virtual void SetScalingMode(int value) = 0;
1832 virtual void SetLpAlgorithm(int value) = 0;
1833};
1834
1835} // namespace operations_research
1836
1837#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)