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"
159#include "ortools/linear_solver/linear_solver.pb.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.
176bool SolverTypeIsMip(MPModelRequest::SolverType solver_type);
177
182class MPSolver {
183 public:
191 // Linear programming problems.
192 // ----------------------------
195 GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
196 // In-house linear programming solver based on the primal-dual hybrid
197 // gradient method. Sometimes faster than Glop for medium-size problems and
198 // scales to much larger problems than Glop.
200
201 // Integer programming problems.
202 // -----------------------------
203 SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
206
207 // Commercial software (need license).
214
215 // Boolean optimization problem (requires only integer variables and works
216 // best with only Boolean variables).
218
219 // SAT based solver (requires only integer and Boolean variables).
220 // If you pass it mixed integer problems, it will scale coefficients to
221 // integer values, and solver continuous variables as integral variables.
223
224 // Dedicated knapsack solvers.
226 };
227
229 MPSolver(const std::string& name, OptimizationProblemType problem_type);
230 virtual ~MPSolver();
231
260 static MPSolver* CreateSolver(const std::string& solver_id);
261
267
273 static bool ParseSolverType(absl::string_view solver_id,
275
281 const std::string& solver_id);
282
283 bool IsMIP() const;
284
286 const std::string& Name() const {
287 return name_; // Set at construction.
288 }
289
292 return problem_type_; // Set at construction.
293 }
294
300 void Clear();
301
303 int NumVariables() const { return variables_.size(); }
304
309 const std::vector<MPVariable*>& variables() const { return variables_; }
310
314 MPVariable* variable(int index) const { return variables_[index]; }
315
321 MPVariable* LookupVariableOrNull(const std::string& var_name) const;
322
330 MPVariable* MakeVar(double lb, double ub, bool integer,
331 const std::string& name);
332
334 MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
335
337 MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
338
340 MPVariable* MakeBoolVar(const std::string& name);
341
356 void MakeVarArray(int nb, double lb, double ub, bool integer,
357 const std::string& name_prefix,
358 std::vector<MPVariable*>* vars);
359
361 void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
362 std::vector<MPVariable*>* vars);
363
365 void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
366 std::vector<MPVariable*>* vars);
367
369 void MakeBoolVarArray(int nb, const std::string& name,
370 std::vector<MPVariable*>* vars);
371
373 int NumConstraints() const { return constraints_.size(); }
374
380 const std::vector<MPConstraint*>& constraints() const { return constraints_; }
381
383 MPConstraint* constraint(int index) const { return constraints_[index]; }
384
393 const std::string& constraint_name) const;
394
403 MPConstraint* MakeRowConstraint(double lb, double ub);
404
407
409 MPConstraint* MakeRowConstraint(double lb, double ub,
410 const std::string& name);
411
413 MPConstraint* MakeRowConstraint(const std::string& name);
414
420
423 const std::string& name);
424
431 const MPObjective& Objective() const { return *objective_; }
432
434 MPObjective* MutableObjective() { return objective_.get(); }
435
456 NOT_SOLVED = 6
457 };
458
461
464
469 void Write(const std::string& file_name);
470
477 std::vector<double> ComputeConstraintActivities() const;
478
497 bool VerifySolution(double tolerance, bool log_errors) const;
498
507 void Reset();
508
519
527 MPSolverResponseStatus LoadModelFromProto(const MPModelProto& input_model,
528 std::string* error_message);
537 const MPModelProto& input_model, std::string* error_message);
538
540 void FillSolutionResponseProto(MPSolutionResponse* response) const;
541
557 static void SolveWithProto(const MPModelRequest& model_request,
558 MPSolutionResponse* response,
559 // `interrupt` is non-const because the internal
560 // solver may set it to true itself, in some cases.
561 std::atomic<bool>* interrupt = nullptr);
562
564 const MPModelRequest::SolverType solver) {
565 // Interruption requires that MPSolver::InterruptSolve is supported for the
566 // underlying solver. Interrupting requests using SCIP is also not supported
567 // as of 2021/08/23, since InterruptSolve is not go/thread-safe
568 // for SCIP (see e.g. cl/350545631 for details).
569 return solver == MPModelRequest::GLOP_LINEAR_PROGRAMMING ||
570 solver == MPModelRequest::GUROBI_LINEAR_PROGRAMMING ||
571 solver == MPModelRequest::GUROBI_MIXED_INTEGER_PROGRAMMING ||
572 solver == MPModelRequest::SAT_INTEGER_PROGRAMMING ||
573 solver == MPModelRequest::PDLP_LINEAR_PROGRAMMING;
574 }
575
577 void ExportModelToProto(MPModelProto* output_model) const;
578
613 const MPSolutionResponse& response,
614 double tolerance = std::numeric_limits<double>::infinity());
615
621
628 bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
629 bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
630 std::string* model_str) const;
631
642 absl::Status SetNumThreads(int num_threads);
643
645 int GetNumThreads() const { return num_threads_; }
646
653 bool SetSolverSpecificParametersAsString(const std::string& parameters);
655 return solver_specific_parameter_string_;
656 }
657
671 void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
672
678 FREE = 0,
682 BASIC
683 };
684
697 const std::vector<MPSolver::BasisStatus>& variable_statuses,
698 const std::vector<MPSolver::BasisStatus>& constraint_statuses);
699
705 static double infinity() { return std::numeric_limits<double>::infinity(); }
706
715 bool OutputIsEnabled() const;
716
719
722
723 absl::Duration TimeLimit() const { return time_limit_; }
724 void SetTimeLimit(absl::Duration time_limit) {
725 DCHECK_GE(time_limit, absl::ZeroDuration());
726 time_limit_ = time_limit;
727 }
728
729 absl::Duration DurationSinceConstruction() const {
730 return absl::Now() - construction_time_;
731 }
732
734 int64_t iterations() const;
735
741 int64_t nodes() const;
742
744 std::string SolverVersion() const;
745
760
785
800 ABSL_MUST_USE_RESULT bool NextSolution();
801
802 // Does not take ownership of "mp_callback".
803 //
804 // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
805 // SCIP does not support suggesting a heuristic solution in the callback.
806 //
807 // See go/mpsolver-callbacks for additional documentation.
808 void SetCallback(MPCallback* mp_callback);
809 bool SupportsCallbacks() const;
810
811 // Global counters of variables and constraints ever created across all
812 // MPSolver instances. Those are only updated after the destruction
813 // (or Clear()) of each MPSolver instance.
814 static int64_t global_num_variables();
815 static int64_t global_num_constraints();
816
817 // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
818 // NOTE: These deprecated functions used the convention time_limit = 0 to mean
819 // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
820 int64_t time_limit() const {
821 return time_limit_ == absl::InfiniteDuration()
822 ? 0
823 : absl::ToInt64Milliseconds(time_limit_);
824 }
825 void set_time_limit(int64_t time_limit_milliseconds) {
826 SetTimeLimit(time_limit_milliseconds == 0
827 ? absl::InfiniteDuration()
828 : absl::Milliseconds(time_limit_milliseconds));
829 }
830 double time_limit_in_secs() const {
831 return static_cast<double>(time_limit()) / 1000.0;
832 }
833
834 // DEPRECATED: Use DurationSinceConstruction() instead.
835 int64_t wall_time() const {
836 return absl::ToInt64Milliseconds(DurationSinceConstruction());
837 }
838
839 friend class GLPKInterface;
840 friend class CLPInterface;
841 friend class CBCInterface;
842 friend class SCIPInterface;
843 friend class GurobiInterface;
844 friend class CplexInterface;
845 friend class XpressInterface;
846 friend class SLMInterface;
847 friend class MPSolverInterface;
848 friend class GLOPInterface;
849 friend class BopInterface;
850 friend class SatInterface;
851 friend class PdlpInterface;
852 friend class KnapsackInterface;
853
854 // Debugging: verify that the given MPVariable* belongs to this solver.
855 bool OwnsVariable(const MPVariable* var) const;
856
857 private:
858 // Computes the size of the constraint with the largest number of
859 // coefficients with index in [min_constraint_index,
860 // max_constraint_index)
861 int ComputeMaxConstraintSize(int min_constraint_index,
862 int max_constraint_index) const;
863
864 // Returns true if the model has constraints with lower bound > upper bound.
865 bool HasInfeasibleConstraints() const;
866
867 // Returns true if the model has at least 1 integer variable.
868 bool HasIntegerVariables() const;
869
870 // Generates the map from variable names to their indices.
871 void GenerateVariableNameIndex() const;
872
873 // Generates the map from constraint names to their indices.
874 void GenerateConstraintNameIndex() const;
875
876 // The name of the linear programming problem.
877 const std::string name_;
878
879 // The type of the linear programming problem.
880 const OptimizationProblemType problem_type_;
881
882 // The solver interface.
883 std::unique_ptr<MPSolverInterface> interface_;
884
885 // The vector of variables in the problem.
886 std::vector<MPVariable*> variables_;
887 // A map from a variable's name to its index in variables_.
888 mutable absl::optional<absl::flat_hash_map<std::string, int> >
889 variable_name_to_index_;
890 // Whether variables have been extracted to the underlying interface.
891 std::vector<bool> variable_is_extracted_;
892
893 // The vector of constraints in the problem.
894 std::vector<MPConstraint*> constraints_;
895 // A map from a constraint's name to its index in constraints_.
896 mutable absl::optional<absl::flat_hash_map<std::string, int> >
897 constraint_name_to_index_;
898 // Whether constraints have been extracted to the underlying interface.
899 std::vector<bool> constraint_is_extracted_;
900
901 // The linear objective function.
902 std::unique_ptr<MPObjective> objective_;
903
904 // Initial values for all or some of the problem variables that can be
905 // exploited as a starting hint by a solver.
906 //
907 // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
908 //
909 // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
910 // hint is provided and a std::vector<double> for the hint value.
911 std::vector<std::pair<const MPVariable*, double> > solution_hint_;
912
913 absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
914
915 const absl::Time construction_time_;
916
917 // Permanent storage for the number of threads.
918 int num_threads_ = 1;
919
920 // Permanent storage for SetSolverSpecificParametersAsString().
921 std::string solver_specific_parameter_string_;
922
923 static absl::Mutex global_count_mutex_;
924#ifndef SWIG
925 static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
926 static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
927#endif
928
929 MPSolverResponseStatus LoadModelFromProtoInternal(
930 const MPModelProto& input_model, bool clear_names,
931 bool check_model_validity, std::string* error_message);
932
933 DISALLOW_COPY_AND_ASSIGN(MPSolver);
934};
935
937 return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
938}
939
940const absl::string_view ToString(
941 MPSolver::OptimizationProblemType optimization_problem_type);
942
943inline std::ostream& operator<<(
944 std::ostream& os,
945 MPSolver::OptimizationProblemType optimization_problem_type) {
946 return os << ToString(optimization_problem_type);
947}
948
949inline std::ostream& operator<<(std::ostream& os,
950 MPSolver::ResultStatus status) {
951 return os << ProtoEnumToString<MPSolverResponseStatus>(
952 static_cast<MPSolverResponseStatus>(status));
953}
954
955bool AbslParseFlag(absl::string_view text,
957 std::string* error);
958
959inline std::string AbslUnparseFlag(
961 return std::string(ToString(solver_type));
962}
963
966 public:
971 void Clear();
972
979 void SetCoefficient(const MPVariable* const var, double coeff);
980
986 double GetCoefficient(const MPVariable* const var) const;
987
993 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
994 return coefficients_;
995 }
996
998 void SetOffset(double value);
999
1001 double offset() const { return offset_; }
1002
1007 void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1008
1010 void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1011 OptimizeLinearExpr(linear_expr, true);
1012 }
1014 void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1015 OptimizeLinearExpr(linear_expr, false);
1016 }
1017
1019 void AddLinearExpr(const LinearExpr& linear_expr);
1020
1022 void SetOptimizationDirection(bool maximize);
1023
1026
1029
1031 bool maximization() const;
1032
1034 bool minimization() const;
1035
1047 double Value() const;
1048
1055 double BestBound() const;
1056
1057 private:
1058 friend class MPSolver;
1059 friend class MPSolverInterface;
1060 friend class CBCInterface;
1061 friend class CLPInterface;
1062 friend class GLPKInterface;
1063 friend class SCIPInterface;
1064 friend class SLMInterface;
1065 friend class GurobiInterface;
1066 friend class CplexInterface;
1067 friend class XpressInterface;
1068 friend class GLOPInterface;
1069 friend class BopInterface;
1070 friend class SatInterface;
1071 friend class PdlpInterface;
1072 friend class KnapsackInterface;
1073
1074 // Constructor. An objective points to a single MPSolverInterface
1075 // that is specified in the constructor. An objective cannot belong
1076 // to several models.
1077 // At construction, an MPObjective has no terms (which is equivalent
1078 // on having a coefficient of 0 for all variables), and an offset of 0.
1079 explicit MPObjective(MPSolverInterface* const interface_in)
1080 : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1081
1082 MPSolverInterface* const interface_;
1083
1084 // Mapping var -> coefficient.
1085 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1086 // Constant term.
1087 double offset_;
1088
1089 DISALLOW_COPY_AND_ASSIGN(MPObjective);
1090};
1091
1094 public:
1096 const std::string& name() const { return name_; }
1097
1100
1102 bool integer() const { return integer_; }
1103
1111 double solution_value() const;
1112
1114 int index() const { return index_; }
1115
1117 double lb() const { return lb_; }
1118
1120 double ub() const { return ub_; }
1121
1123 void SetLB(double lb) { SetBounds(lb, ub_); }
1124
1126 void SetUB(double ub) { SetBounds(lb_, ub); }
1127
1129 void SetBounds(double lb, double ub);
1130
1138
1143 double reduced_cost() const;
1144
1152
1163 int branching_priority() const { return branching_priority_; }
1164 void SetBranchingPriority(int priority);
1165
1166 protected:
1167 friend class MPSolver;
1168 friend class MPSolverInterface;
1169 friend class CBCInterface;
1170 friend class CLPInterface;
1171 friend class GLPKInterface;
1172 friend class SCIPInterface;
1173 friend class SLMInterface;
1174 friend class GurobiInterface;
1175 friend class CplexInterface;
1176 friend class XpressInterface;
1177 friend class GLOPInterface;
1179 friend class BopInterface;
1180 friend class SatInterface;
1181 friend class PdlpInterface;
1182 friend class KnapsackInterface;
1183
1184 // Constructor. A variable points to a single MPSolverInterface that
1185 // is specified in the constructor. A variable cannot belong to
1186 // several models.
1187 MPVariable(int index, double lb, double ub, bool integer,
1188 const std::string& name, MPSolverInterface* const interface_in)
1189 : index_(index),
1190 lb_(lb),
1191 ub_(ub),
1192 integer_(integer),
1193 name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1194 solution_value_(0.0),
1195 reduced_cost_(0.0),
1196 interface_(interface_in) {}
1197
1198 void set_solution_value(double value) { solution_value_ = value; }
1199 void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1200
1201 private:
1202 const int index_;
1203 double lb_;
1204 double ub_;
1205 bool integer_;
1206 const std::string name_;
1207 double solution_value_;
1208 double reduced_cost_;
1209 int branching_priority_ = 0;
1210 MPSolverInterface* const interface_;
1211 DISALLOW_COPY_AND_ASSIGN(MPVariable);
1212};
1213
1220 public:
1222 const std::string& name() const { return name_; }
1223
1225 void Clear();
1226
1233 void SetCoefficient(const MPVariable* const var, double coeff);
1234
1239 double GetCoefficient(const MPVariable* const var) const;
1240
1246 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1247 return coefficients_;
1248 }
1249
1251 double lb() const { return lb_; }
1252
1254 double ub() const { return ub_; }
1255
1257 void SetLB(double lb) { SetBounds(lb, ub_); }
1258
1260 void SetUB(double ub) { SetBounds(lb_, ub); }
1261
1263 void SetBounds(double lb, double ub);
1264
1266 bool is_lazy() const { return is_lazy_; }
1267
1281 void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1282
1283 const MPVariable* indicator_variable() const { return indicator_variable_; }
1284 bool indicator_value() const { return indicator_value_; }
1285
1287 int index() const { return index_; }
1288
1293 double dual_value() const;
1294
1308
1309 protected:
1310 friend class MPSolver;
1311 friend class MPSolverInterface;
1312 friend class CBCInterface;
1313 friend class CLPInterface;
1314 friend class GLPKInterface;
1315 friend class SCIPInterface;
1316 friend class SLMInterface;
1317 friend class GurobiInterface;
1318 friend class CplexInterface;
1319 friend class XpressInterface;
1320 friend class GLOPInterface;
1321 friend class BopInterface;
1322 friend class SatInterface;
1323 friend class PdlpInterface;
1324 friend class KnapsackInterface;
1325
1326 // Constructor. A constraint points to a single MPSolverInterface
1327 // that is specified in the constructor. A constraint cannot belong
1328 // to several models.
1329 MPConstraint(int index, double lb, double ub, const std::string& name,
1330 MPSolverInterface* const interface_in)
1331 : coefficients_(1),
1332 index_(index),
1333 lb_(lb),
1334 ub_(ub),
1335 name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1336 is_lazy_(false),
1337 indicator_variable_(nullptr),
1338 dual_value_(0.0),
1339 interface_(interface_in) {}
1340
1341 void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1342
1343 private:
1344 // Returns true if the constraint contains variables that have not
1345 // been extracted yet.
1346 bool ContainsNewVariables();
1347
1348 // Mapping var -> coefficient.
1349 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1350
1351 const int index_; // See index().
1352
1353 // The lower bound for the linear constraint.
1354 double lb_;
1355
1356 // The upper bound for the linear constraint.
1357 double ub_;
1358
1359 // Name.
1360 const std::string name_;
1361
1362 // True if the constraint is "lazy", i.e. the constraint is added to the
1363 // underlying Linear Programming solver only if it is violated.
1364 // By default this parameter is 'false'.
1365 bool is_lazy_;
1366
1367 // If given, this constraint is only active if `indicator_variable_`'s value
1368 // is equal to `indicator_value_`.
1369 const MPVariable* indicator_variable_;
1370 bool indicator_value_;
1371
1372 double dual_value_;
1373 MPSolverInterface* const interface_;
1374 DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1375};
1376
1404 public:
1409
1418 DUAL_TOLERANCE = 2
1420
1424 PRESOLVE = 1000,
1430 SCALING = 1003
1432
1438 PRESOLVE_ON = 1
1440
1444 DUAL = 10,
1448 BARRIER = 12
1450
1455
1462
1468 SCALING_ON = 1
1470
1471 // Placeholder value to indicate that a parameter is set to
1472 // the default value defined in the wrapper.
1473 static const double kDefaultDoubleParamValue;
1475
1476 // Placeholder value to indicate that a parameter is unknown.
1477 static const double kUnknownDoubleParamValue;
1479
1480 // Default values for parameters. Only parameters that define the
1481 // properties of the solution returned need to have a default value
1482 // (that is the same for all solvers). You can also define a default
1483 // value for performance parameters when you are confident it is a
1484 // good choice (example: always turn presolve on).
1485 static const double kDefaultRelativeMipGap;
1486 static const double kDefaultPrimalTolerance;
1487 static const double kDefaultDualTolerance;
1490
1493
1496
1499
1506
1513
1515 void Reset();
1516
1519
1522
1523 private:
1524 // Parameter value for each parameter.
1525 // @see DoubleParam
1526 // @see IntegerParam
1527 double relative_mip_gap_value_;
1528 double primal_tolerance_value_;
1529 double dual_tolerance_value_;
1530 int presolve_value_;
1531 int scaling_value_;
1532 int lp_algorithm_value_;
1533 int incrementality_value_;
1534
1535 // Boolean value indicating whether each parameter is set to the
1536 // solver's default value. Only parameters for which the wrapper
1537 // does not define a default value need such an indicator.
1538 bool lp_algorithm_is_default_;
1539
1540 DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1541};
1542
1543// Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1544// error when happening on the linear solver stubby server, see
1545// ./linear_solver_service.proto.
1546// Note that RPC errors forbid to carry a response to the client, who can only
1547// see the RPC error itself (error code + error message).
1548bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status);
1549
1550// This class wraps the actual mathematical programming solvers. Each
1551// solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1552// derives from this abstract class. This class is never directly
1553// accessed by the user.
1554// @see glop_interface.cc
1555// @see cbc_interface.cc
1556// @see clp_interface.cc
1557// @see glpk_interface.cc
1558// @see scip_interface.cc
1560 public:
1562 // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1563 // sync for the model nor for the solution.
1565 // The underlying solver and MPSolver are in sync for the model
1566 // but not for the solution: the model has changed since the
1567 // solution was computed last.
1569 // The underlying solver and MPSolver are in sync for the model and
1570 // the solution.
1573
1574 // When the underlying solver does not provide the number of simplex
1575 // iterations.
1576 static constexpr int64_t kUnknownNumberOfIterations = -1;
1577 // When the underlying solver does not provide the number of
1578 // branch-and-bound nodes.
1579 static constexpr int64_t kUnknownNumberOfNodes = -1;
1580
1581 // Constructor. The user will access the MPSolverInterface through the
1582 // MPSolver passed as argument.
1583 explicit MPSolverInterface(MPSolver* const solver);
1585
1586 // ----- Solve -----
1587 // Solves problem with specified parameter values. Returns true if the
1588 // solution is optimal.
1590
1591 // Attempts to directly solve a MPModelRequest, bypassing the MPSolver data
1592 // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1593 // an 'interrupt' boolean.
1594 // Returns {} (eg. absl::nullopt) if direct-solve is not supported by the
1595 // underlying solver (possibly because interrupt != nullptr), in which case
1596 // the user should fall back to using MPSolver.
1597 virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1598 const MPModelRequest& request,
1599 // `interrupt` is non-const because the internal
1600 // solver may set it to true itself, in some cases.
1601 std::atomic<bool>* interrupt) {
1602 return absl::nullopt;
1603 }
1604
1605 // Writes the model using the solver internal write function. Currently only
1606 // available for GurobiInterface.
1607 virtual void Write(const std::string& filename);
1608
1609 // ----- Model modifications and extraction -----
1610 // Resets extracted model.
1611 virtual void Reset() = 0;
1612
1613 // Sets the optimization direction (min/max).
1614 virtual void SetOptimizationDirection(bool maximize) = 0;
1615
1616 // Modifies bounds of an extracted variable.
1617 virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1618
1619 // Modifies integrality of an extracted variable.
1620 virtual void SetVariableInteger(int index, bool integer) = 0;
1621
1622 // Modify bounds of an extracted variable.
1623 virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1624
1625 // Adds a linear constraint.
1626 virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1627
1628 // Adds an indicator constraint. Returns true if the feature is supported by
1629 // the underlying solver.
1630 virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1631 LOG(ERROR) << "Solver doesn't support indicator constraints.";
1632 return false;
1633 }
1634
1635 // Add a variable.
1636 virtual void AddVariable(MPVariable* const var) = 0;
1637
1638 // Changes a coefficient in a constraint.
1639 virtual void SetCoefficient(MPConstraint* const constraint,
1640 const MPVariable* const variable,
1641 double new_value, double old_value) = 0;
1642
1643 // Clears a constraint from all its terms.
1644 virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1645
1646 // Changes a coefficient in the linear objective.
1647 virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1648 double coefficient) = 0;
1649
1650 // Changes the constant term in the linear objective.
1651 virtual void SetObjectiveOffset(double value) = 0;
1652
1653 // Clears the objective from all its terms.
1654 virtual void ClearObjective() = 0;
1655
1656 virtual void BranchingPriorityChangedForVariable(int var_index) {}
1657 // ------ Query statistics on the solution and the solve ------
1658 // Returns the number of simplex iterations. The problem must be discrete,
1659 // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1660 virtual int64_t iterations() const = 0;
1661 // Returns the number of branch-and-bound nodes. The problem must be discrete,
1662 // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1663 virtual int64_t nodes() const = 0;
1664 // Returns the best objective bound. The problem must be discrete, otherwise
1665 // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1666 double best_objective_bound() const;
1667 // Returns the objective value of the best solution found so far.
1668 double objective_value() const;
1669
1670 // Returns the basis status of a row.
1671 virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1672 // Returns the basis status of a constraint.
1673 virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1674
1675 // Checks whether the solution is synchronized with the model, i.e. whether
1676 // the model has changed since the solution was computed last.
1677 // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1679 // Checks whether a feasible solution exists. The behavior is similar to
1680 // CheckSolutionIsSynchronized() above.
1681 virtual bool CheckSolutionExists() const;
1682 // Handy shortcut to do both checks above (it is often used).
1685 }
1686
1687 // ----- Misc -----
1688 // Queries problem type. For simplicity, the distinction between
1689 // continuous and discrete is based on the declaration of the user
1690 // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1691 // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1692 // the model.
1693 // Returns true if the problem is continuous.
1694 virtual bool IsContinuous() const = 0;
1695 // Returns true if the problem is continuous and linear.
1696 virtual bool IsLP() const = 0;
1697 // Returns true if the problem is discrete and linear.
1698 virtual bool IsMIP() const = 0;
1699
1700 // Returns the index of the last variable extracted.
1702
1703 bool variable_is_extracted(int var_index) const {
1704 return solver_->variable_is_extracted_[var_index];
1705 }
1706 void set_variable_as_extracted(int var_index, bool extracted) {
1707 solver_->variable_is_extracted_[var_index] = extracted;
1708 }
1709 bool constraint_is_extracted(int ct_index) const {
1710 return solver_->constraint_is_extracted_[ct_index];
1711 }
1712 void set_constraint_as_extracted(int ct_index, bool extracted) {
1713 solver_->constraint_is_extracted_[ct_index] = extracted;
1714 }
1715
1716 // Returns the boolean indicating the verbosity of the solver output.
1717 bool quiet() const { return quiet_; }
1718 // Sets the boolean indicating the verbosity of the solver output.
1719 void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1720
1721 // Returns the result status of the last solve.
1724 return result_status_;
1725 }
1726
1727 // Returns a string describing the underlying solver and its version.
1728 virtual std::string SolverVersion() const = 0;
1729
1730 // Returns the underlying solver.
1731 virtual void* underlying_solver() = 0;
1732
1733 // Computes exact condition number. Only available for continuous
1734 // problems and only implemented in GLPK.
1735 virtual double ComputeExactConditionNumber() const;
1736
1737 // See MPSolver::SetStartingLpBasis().
1739 const std::vector<MPSolver::BasisStatus>& variable_statuses,
1740 const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1741 LOG(FATAL) << "Not supported by this solver.";
1742 }
1743
1744 virtual bool InterruptSolve() { return false; }
1745
1746 // See MPSolver::NextSolution() for contract.
1747 virtual bool NextSolution() { return false; }
1748
1749 // See MPSolver::SetCallback() for details.
1750 virtual void SetCallback(MPCallback* mp_callback) {
1751 LOG(FATAL) << "Callbacks not supported for this solver.";
1752 }
1753
1754 virtual bool SupportsCallbacks() const { return false; }
1755
1756 friend class MPSolver;
1757
1758 // To access the maximize_ bool and the MPSolver.
1759 friend class MPConstraint;
1760 friend class MPObjective;
1761
1762 protected:
1764 // Indicates whether the model and the solution are synchronized.
1766 // Indicates whether the solve has reached optimality,
1767 // infeasibility, a limit, etc.
1769 // Optimization direction.
1771
1772 // Index in MPSolver::variables_ of last constraint extracted.
1774 // Index in MPSolver::constraints_ of last variable extracted.
1776
1777 // The value of the objective function.
1779
1780 // The value of the best objective bound. Used only for MIP solvers.
1782
1783 // Boolean indicator for the verbosity of the solver output.
1785
1786 // Index of dummy variable created for empty constraints or the
1787 // objective offset.
1788 static const int kDummyVariableIndex;
1789
1790 // Extracts model stored in MPSolver.
1792 // Extracts the variables that have not been extracted yet.
1793 virtual void ExtractNewVariables() = 0;
1794 // Extracts the constraints that have not been extracted yet.
1795 virtual void ExtractNewConstraints() = 0;
1796 // Extracts the objective.
1797 virtual void ExtractObjective() = 0;
1798 // Resets the extraction information.
1800 // Change synchronization status from SOLUTION_SYNCHRONIZED to
1801 // MODEL_SYNCHRONIZED. To be used for model changes.
1803
1804 // Sets parameters common to LP and MIP in the underlying solver.
1806 // Sets MIP specific parameters in the underlying solver.
1808 // Sets all parameters in the underlying solver.
1809 virtual void SetParameters(const MPSolverParameters& param) = 0;
1810 // Sets an unsupported double parameter.
1812 // Sets an unsupported integer parameter.
1815 // Sets a supported double parameter to an unsupported value.
1817 double value);
1818 // Sets a supported integer parameter to an unsupported value.
1820 MPSolverParameters::IntegerParam param, int value);
1821 // Sets each parameter in the underlying solver.
1822 virtual void SetRelativeMipGap(double value) = 0;
1823 virtual void SetPrimalTolerance(double value) = 0;
1824 virtual void SetDualTolerance(double value) = 0;
1825 virtual void SetPresolveMode(int value) = 0;
1826
1827 // Sets the number of threads to be used by the solver.
1828 virtual absl::Status SetNumThreads(int num_threads);
1829
1830 // Pass solver specific parameters in text format. The format is
1831 // solver-specific and is the same as the corresponding solver configuration
1832 // file format. Returns true if the operation was successful.
1833 //
1834 // Default implementation returns true if the input is empty. It returns false
1835 // and logs a WARNING if the input is not empty.
1837 const std::string& parameters);
1838
1839 // Sets the scaling mode.
1840 virtual void SetScalingMode(int value) = 0;
1841 virtual void SetLpAlgorithm(int value) = 0;
1842};
1843
1844} // namespace operations_research
1845
1846#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.
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)