Google OR-Tools v9.15
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
linear_solver.h
Go to the documentation of this file.
1// Copyright 2010-2025 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
133
134#ifndef ORTOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
135#define ORTOOLS_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 <optional>
144#include <ostream>
145#include <string>
146#include <utility>
147#include <vector>
148
149#include "absl/base/attributes.h"
150#include "absl/base/port.h"
151#include "absl/base/thread_annotations.h"
152#include "absl/container/flat_hash_map.h"
153#include "absl/flags/declare.h"
154#include "absl/log/check.h"
155#include "absl/log/log.h"
156#include "absl/status/status.h"
157#include "absl/strings/str_format.h"
158#include "absl/strings/string_view.h"
159#include "absl/time/clock.h"
160#include "absl/time/time.h"
162#include "ortools/base/logging.h"
168
169#ifndef SWIG
170OR_DLL ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
171OR_DLL ABSL_DECLARE_FLAG(bool, log_verification_errors);
172OR_DLL ABSL_DECLARE_FLAG(bool, verify_solution);
173#endif
174
175namespace operations_research {
176
177constexpr double kDefaultPrimalTolerance = 1e-07;
178
179class MPConstraint;
180class MPObjective;
183class MPVariable;
184
185// There is a homonymous version taking a MPSolver::OptimizationProblemType.
187
192class MPSolver {
193 public:
201 // Linear programming problems.
202 // ----------------------------
205 GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
206 // In-house linear programming solver based on the primal-dual hybrid
207 // gradient method. Sometimes faster than Glop for medium-size problems and
208 // scales to much larger problems than Glop.
212 // Integer programming problems.
213 // -----------------------------
214 // Recommended default value for MIP problems.
220 // Boolean optimization problem (requires only integer variables and works
221 // best with only Boolean variables).
223
224 // SAT based solver (requires only integer and Boolean variables).
225 // If you pass it mixed integer problems, it will scale coefficients to
226 // integer values, and solver continuous variables as integral variables.
227 //
228 // Recommended default value for pure integral problems problems.
230
231 // Dedicated knapsack solvers.
233
234 // Commercial software (need license).
243 };
246 MPSolver(const std::string& name, OptimizationProblemType problem_type);
247
248#ifndef SWIG
249 // This type is neither copyable nor movable.
250 MPSolver(const MPSolver&) = delete;
251 MPSolver& operator=(const MPSolver&) = delete;
252#endif
254 virtual ~MPSolver();
255
284 static MPSolver* CreateSolver(const std::string& solver_id);
285
290 static bool SupportsProblemType(OptimizationProblemType problem_type);
291
297 static bool ParseSolverType(absl::string_view solver_id,
299
305 const std::string& solver_id);
306
307 bool IsMIP() const;
308
310 const std::string& Name() const {
311 return name_; // Set at construction.
313
315 virtual OptimizationProblemType ProblemType() const {
316 return problem_type_; // Set at construction.
318
320
324 void Clear();
325
327 int NumVariables() const { return variables_.size(); }
328
333 const std::vector<MPVariable*>& variables() const { return variables_; }
334
338 MPVariable* variable(int index) const { return variables_[index]; }
339
345 MPVariable* LookupVariableOrNull(const std::string& var_name) const;
346
354 MPVariable* MakeVar(double lb, double ub, bool integer,
355 const std::string& name);
356
358 MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
359
361 MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
362
364 MPVariable* MakeBoolVar(const std::string& name);
365
380 void MakeVarArray(int nb, double lb, double ub, bool integer,
381 const std::string& name_prefix,
382 std::vector<MPVariable*>* vars);
383
385 void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
386 std::vector<MPVariable*>* vars);
387
389 void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
390 std::vector<MPVariable*>* vars);
391
393 void MakeBoolVarArray(int nb, const std::string& name,
394 std::vector<MPVariable*>* vars);
395
397 int NumConstraints() const { return constraints_.size(); }
398
404 const std::vector<MPConstraint*>& constraints() const { return constraints_; }
405
407 MPConstraint* constraint(int index) const { return constraints_[index]; }
408
417 const std::string& constraint_name) const;
418
427 MPConstraint* MakeRowConstraint(double lb, double ub);
428
431
433 MPConstraint* MakeRowConstraint(double lb, double ub,
434 const std::string& name);
435
437 MPConstraint* MakeRowConstraint(const std::string& name);
438
444
447 const std::string& name);
448
455 const MPObjective& Objective() const { return *objective_; }
456
458 MPObjective* MutableObjective() { return objective_.get(); }
459
466 enum ResultStatus {
485
488
493 void Write(const std::string& file_name);
494
501 std::vector<double> ComputeConstraintActivities() const;
502
521 bool VerifySolution(double tolerance, bool log_errors) const;
522
531 void Reset();
532
542 bool InterruptSolve();
543
554 std::string* error_message,
555 bool clear_names = true);
564 const MPModelProto& input_model, std::string* error_message);
565
567 void FillSolutionResponseProto(MPSolutionResponse* response) const;
568
587 ABSL_DEPRECATED("Prefer SolveMPModel() from solve_mp_model.h.")
588 static void SolveWithProto(const MPModelRequest& model_request,
589 MPSolutionResponse* response,
590 std::atomic<bool>* interrupt = nullptr);
591
601 ABSL_DEPRECATED("Prefer SolveMPModel() from solve_mp_model.h.")
603 MPSolutionResponse* response,
604 std::atomic<bool>* interrupt = nullptr);
605
607 "Prefer SolverTypeSupportsInterruption() from solve_mp_model.h.")
609 const MPModelRequest::SolverType solver) {
610 // Interruption requires that MPSolver::InterruptSolve is supported for the
611 // underlying solver. Interrupting requests using SCIP is also not supported
612 // as of 2021/08/23, since InterruptSolve is not thread safe for SCIP.
618 }
619
621 void ExportModelToProto(MPModelProto* output_model) const;
622
656 absl::Status LoadSolutionFromProto(
657 const MPSolutionResponse& response,
658 double tolerance = std::numeric_limits<double>::infinity());
659
664 absl::Status ClampSolutionWithinBounds();
665
672 bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
673 bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
674 std::string* model_str) const;
675
686 absl::Status SetNumThreads(int num_threads);
687
689 int GetNumThreads() const { return num_threads_; }
690
697 bool SetSolverSpecificParametersAsString(const std::string& parameters);
698 std::string GetSolverSpecificParametersAsString() const {
699 return solver_specific_parameter_string_;
701
703
717 void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
718
719 // Gives some brief (a few lines, at most) human-readable information about
720 // the given request, suitable for debug logging.
721 ABSL_DEPRECATED("Prefer MPModelRequestLoggingInfo() from solve_mp_model.h.")
722 static std::string GetMPModelRequestLoggingInfo(
723 const MPModelRequest& request);
724
729 enum BasisStatus {
730 FREE = 0,
738
749 const std::vector<MPSolver::BasisStatus>& variable_statuses,
750 const std::vector<MPSolver::BasisStatus>& constraint_statuses);
751
757 static double infinity() { return std::numeric_limits<double>::infinity(); }
758 double solver_infinity();
768 bool OutputIsEnabled() const;
769
771 void EnableOutput();
772
774 void SuppressOutput();
775
776 absl::Duration TimeLimit() const { return time_limit_; }
777 void SetTimeLimit(absl::Duration time_limit) {
778 DCHECK_GE(time_limit, absl::ZeroDuration());
779 time_limit_ = time_limit;
780 }
781
782 absl::Duration DurationSinceConstruction() const {
783 return absl::Now() - construction_time_;
785
787 int64_t iterations() const;
788
794 int64_t nodes() const;
795
797 std::string SolverVersion() const;
798
812 void* underlying_solver();
813
837 double ComputeExactConditionNumber() const;
838
853 ABSL_MUST_USE_RESULT bool NextSolution();
854
855 // Does not take ownership of "mp_callback".
856 //
857 // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
858 // SCIP does not support suggesting a heuristic solution in the callback.
859 void SetCallback(MPCallback* mp_callback);
860 bool SupportsCallbacks() const;
861
862 // Global counters of variables and constraints ever created across all
863 // MPSolver instances. Those are only updated after the destruction
864 // (or Clear()) of each MPSolver instance.
865 static int64_t global_num_variables();
866 static int64_t global_num_constraints();
867
872 int64_t time_limit() const {
873 return time_limit_ == absl::InfiniteDuration()
874 ? 0
875 : absl::ToInt64Milliseconds(time_limit_);
876 }
877 void set_time_limit(int64_t time_limit_milliseconds) {
878 SetTimeLimit(time_limit_milliseconds == 0
879 ? absl::InfiniteDuration()
880 : absl::Milliseconds(time_limit_milliseconds));
881 }
882 double time_limit_in_secs() const {
883 return static_cast<double>(time_limit()) / 1000.0;
885
887 int64_t wall_time() const {
888 return absl::ToInt64Milliseconds(DurationSinceConstruction());
890
891 friend class GLPKInterface;
892 friend class CLPInterface;
893 friend class CBCInterface;
894 friend class SCIPInterface;
895 friend class GurobiInterface;
896 friend class CplexInterface;
897 friend class XpressInterface;
898 friend class SLMInterface;
899 friend class MPSolverInterface;
900 friend class GLOPInterface;
901 friend class BopInterface;
902 friend class SatInterface;
903 friend class PdlpInterface;
904 friend class HighsInterface;
905 friend class KnapsackInterface;
907 // Debugging: verify that the given MPVariable* belongs to this solver.
908 bool OwnsVariable(const MPVariable* var) const;
909
910 private:
911 // Computes the size of the constraint with the largest number of
912 // coefficients with index in [min_constraint_index,
913 // max_constraint_index)
914 int ComputeMaxConstraintSize(int min_constraint_index,
915 int max_constraint_index) const;
916
917 // Returns true if the model has constraints with lower bound > upper bound.
918 bool HasInfeasibleConstraints() const;
919
920 // Returns true if the model has at least 1 integer variable.
921 bool HasIntegerVariables() const;
922
923 // Generates the map from variable names to their indices.
924 void GenerateVariableNameIndex() const;
925
926 // Generates the map from constraint names to their indices.
927 void GenerateConstraintNameIndex() const;
928
929 // The name of the linear programming problem.
930 const std::string name_;
931
932 // The type of the linear programming problem.
933 const OptimizationProblemType problem_type_;
934
935 // The solver interface.
936 std::unique_ptr<MPSolverInterface> interface_;
937
938 // The vector of variables in the problem.
939 std::vector<MPVariable*> variables_;
940 // A map from a variable's name to its index in variables_.
941 mutable std::optional<absl::flat_hash_map<std::string, int> >
942 variable_name_to_index_;
943 // Whether variables have been extracted to the underlying interface.
944 std::vector<bool> variable_is_extracted_;
945
946 // The vector of constraints in the problem.
947 std::vector<MPConstraint*> constraints_;
948 // A map from a constraint's name to its index in constraints_.
949 mutable std::optional<absl::flat_hash_map<std::string, int> >
950 constraint_name_to_index_;
951 // Whether constraints have been extracted to the underlying interface.
952 std::vector<bool> constraint_is_extracted_;
953
954 // The linear objective function.
955 std::unique_ptr<MPObjective> objective_;
956
957 // Initial values for all or some of the problem variables that can be
958 // exploited as a starting hint by a solver.
959 //
960 // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
961 //
962 // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
963 // hint is provided and a std::vector<double> for the hint value.
964 std::vector<std::pair<const MPVariable*, double> > solution_hint_;
965
966 absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
967
968 const absl::Time construction_time_;
969
970 // Permanent storage for the number of threads.
971 int num_threads_ = 1;
972
973 // Permanent storage for SetSolverSpecificParametersAsString().
974 std::string solver_specific_parameter_string_;
975
976 static absl::Mutex global_count_mutex_;
977#ifndef SWIG
978 static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
979 static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
980#endif
981
982 enum ModelProtoNamesPolicy {
983 DEFAULT_CLEAR_NAMES = 0,
984 INVALID_MODEL_ON_DUPLICATE_NONEMPTY_NAMES = 1,
985 DIE_ON_DUPLICATE_NONEMPTY_NAMES = 2,
986 };
987 MPSolverResponseStatus LoadModelFromProtoInternal(
988 const MPModelProto& input_model, ModelProtoNamesPolicy name_policy,
989 bool check_model_validity, std::string* error_message);
990};
991
992inline bool SolverTypeIsMip(MPSolver::OptimizationProblemType solver_type) {
993 return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
995
996absl::string_view ToString(
997 MPSolver::OptimizationProblemType optimization_problem_type);
998
999inline std::ostream& operator<<(
1000 std::ostream& os,
1001 MPSolver::OptimizationProblemType optimization_problem_type) {
1002 return os << ToString(optimization_problem_type);
1003}
1004
1005inline std::ostream& operator<<(std::ostream& os,
1006 MPSolver::ResultStatus status) {
1007 return os << ProtoEnumToString<MPSolverResponseStatus>(
1008 static_cast<MPSolverResponseStatus>(status));
1009}
1010
1011bool AbslParseFlag(absl::string_view text,
1013 std::string* error);
1014
1015inline std::string AbslUnparseFlag(
1017 return std::string(ToString(solver_type));
1018}
1019
1021class MPObjective {
1022 public:
1023#ifndef SWIG
1024 // This type is neither copyable nor movable.
1025 MPObjective(const MPObjective&) = delete;
1026 MPObjective& operator=(const MPObjective&) = delete;
1027#endif
1033 void Clear();
1034
1041 void SetCoefficient(const MPVariable* var, double coeff);
1042
1048 double GetCoefficient(const MPVariable* var) const;
1049
1055 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1056 return coefficients_;
1058
1060 void SetOffset(double value);
1061
1063 double offset() const { return offset_; }
1064
1069 void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1070
1072 void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1073 OptimizeLinearExpr(linear_expr, true);
1076 void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1077 OptimizeLinearExpr(linear_expr, false);
1079
1081 void AddLinearExpr(const LinearExpr& linear_expr);
1082
1084 void SetOptimizationDirection(bool maximize);
1085
1087 void SetMinimization() { SetOptimizationDirection(false); }
1088
1091
1093 bool maximization() const;
1094
1096 bool minimization() const;
1097
1109 double Value() const;
1110
1117 double BestBound() const;
1118
1119 private:
1120 friend class MPSolver;
1121 friend class MPSolverInterface;
1122 friend class CBCInterface;
1123 friend class CLPInterface;
1124 friend class GLPKInterface;
1125 friend class SCIPInterface;
1126 friend class SLMInterface;
1127 friend class GurobiInterface;
1128 friend class CplexInterface;
1129 friend class XpressInterface;
1130 friend class GLOPInterface;
1131 friend class BopInterface;
1132 friend class SatInterface;
1133 friend class PdlpInterface;
1134 friend class HighsInterface;
1135 friend class KnapsackInterface;
1137 // Constructor. An objective points to a single MPSolverInterface
1138 // that is specified in the constructor. An objective cannot belong
1139 // to several models.
1140 // At construction, an MPObjective has no terms (which is equivalent
1141 // on having a coefficient of 0 for all variables), and an offset of 0.
1142 explicit MPObjective(MPSolverInterface* const interface_in)
1143 : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1144
1145 MPSolverInterface* const interface_;
1146
1147 // Mapping var -> coefficient.
1148 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1149 // Constant term.
1150 double offset_;
1151};
1152
1154class MPVariable {
1155 public:
1156#ifndef SWIG
1157 // This type is neither copyable nor movable.
1158 MPVariable(const MPVariable&) = delete;
1159 MPVariable& operator=(const MPVariable&) = delete;
1160#endif
1163 const std::string& name() const { return name_; }
1164
1166 void SetInteger(bool integer);
1167
1169 bool integer() const { return integer_; }
1170
1178 double solution_value() const;
1179
1181 int index() const { return index_; }
1182
1184 double lb() const { return lb_; }
1185
1187 double ub() const { return ub_; }
1188
1190 void SetLB(double lb) { SetBounds(lb, ub_); }
1191
1193 void SetUB(double ub) { SetBounds(lb_, ub); }
1194
1196 void SetBounds(double lb, double ub);
1197
1204 double unrounded_solution_value() const;
1205
1210 double reduced_cost() const;
1211
1219
1230 int branching_priority() const { return branching_priority_; }
1231 void SetBranchingPriority(int priority);
1233 protected:
1234 friend class BopInterface;
1235 friend class CBCInterface;
1236 friend class CLPInterface;
1237 friend class CplexInterface;
1238 friend class GLOPInterface;
1239 friend class GLPKInterface;
1240 friend class GurobiInterface;
1241 friend class HighsInterface;
1242 friend class KnapsackInterface;
1243 friend class MPSolver;
1244 friend class MPSolverInterface;
1246 friend class PdlpInterface;
1247 friend class SatInterface;
1248 friend class SCIPInterface;
1249 friend class SLMInterface;
1250 friend class XpressInterface;
1252 // Constructor. A variable points to a single MPSolverInterface that
1253 // is specified in the constructor. A variable cannot belong to
1254 // several models.
1255 MPVariable(int index, double lb, double ub, bool integer,
1256 const std::string& name, MPSolverInterface* const interface_in)
1257 : index_(index),
1258 lb_(lb),
1259 ub_(ub),
1260 integer_(integer),
1261 name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1262 solution_value_(0.0),
1263 reduced_cost_(0.0),
1264 interface_(interface_in) {}
1265
1266 void set_solution_value(double value) { solution_value_ = value; }
1267 void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1269 private:
1270 const int index_;
1271 double lb_;
1272 double ub_;
1273 bool integer_;
1274 const std::string name_;
1275 double solution_value_;
1276 double reduced_cost_;
1277 int branching_priority_ = 0;
1278 MPSolverInterface* const interface_;
1279};
1280
1282
1286class MPConstraint {
1287 public:
1288#ifndef SWIG
1289 // This type is neither copyable nor movable.
1290 MPConstraint(const MPConstraint&) = delete;
1291 MPConstraint& operator=(const MPConstraint&) = delete;
1292#endif
1295 const std::string& name() const { return name_; }
1296
1298 void Clear();
1299
1306 void SetCoefficient(const MPVariable* var, double coeff);
1307
1312 double GetCoefficient(const MPVariable* var) const;
1313
1319 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1320 return coefficients_;
1322
1324 double lb() const { return lb_; }
1325
1327 double ub() const { return ub_; }
1328
1330 void SetLB(double lb) { SetBounds(lb, ub_); }
1331
1333 void SetUB(double ub) { SetBounds(lb_, ub); }
1334
1336 void SetBounds(double lb, double ub);
1337
1339 bool is_lazy() const { return is_lazy_; }
1340
1354 void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1355
1356 const MPVariable* indicator_variable() const { return indicator_variable_; }
1357 bool indicator_value() const { return indicator_value_; }
1360 int index() const { return index_; }
1361
1366 double dual_value() const;
1367
1381
1382 protected:
1383 friend class MPSolver;
1384 friend class MPSolverInterface;
1385 friend class CBCInterface;
1386 friend class CLPInterface;
1387 friend class GLPKInterface;
1388 friend class SCIPInterface;
1389 friend class SLMInterface;
1390 friend class GurobiInterface;
1391 friend class CplexInterface;
1392 friend class XpressInterface;
1393 friend class GLOPInterface;
1394 friend class BopInterface;
1395 friend class SatInterface;
1396 friend class PdlpInterface;
1397 friend class HighsInterface;
1398 friend class KnapsackInterface;
1400 // Constructor. A constraint points to a single MPSolverInterface
1401 // that is specified in the constructor. A constraint cannot belong
1402 // to several models.
1403 MPConstraint(int index, double lb, double ub, const std::string& name,
1404 MPSolverInterface* const interface_in)
1405 : coefficients_(1),
1406 index_(index),
1407 lb_(lb),
1408 ub_(ub),
1409 name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1410 is_lazy_(false),
1411 indicator_variable_(nullptr),
1412 dual_value_(0.0),
1413 interface_(interface_in) {}
1414
1415 void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1416
1417 private:
1418 // Returns true if the constraint contains variables that have not
1419 // been extracted yet.
1420 bool ContainsNewVariables();
1421
1422 // Mapping var -> coefficient.
1423 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1424
1425 const int index_; // See index().
1426
1427 // The lower bound for the linear constraint.
1428 double lb_;
1429
1430 // The upper bound for the linear constraint.
1431 double ub_;
1432
1433 // Name.
1434 const std::string name_;
1435
1436 // True if the constraint is "lazy", i.e. the constraint is added to the
1437 // underlying Linear Programming solver only if it is violated.
1438 // By default this parameter is 'false'.
1439 bool is_lazy_;
1440
1441 // If given, this constraint is only active if `indicator_variable_`'s value
1442 // is equal to `indicator_value_`.
1443 const MPVariable* indicator_variable_;
1444 bool indicator_value_;
1445
1446 double dual_value_;
1447 MPSolverInterface* const interface_;
1448};
1449
1451
1476class
1477#ifndef SWIG
1479#endif
1481 public:
1483 enum DoubleParam {
1499 enum IntegerParam {
1501 PRESOLVE = 1000,
1507 SCALING = 1003
1508 };
1511 enum PresolveValues {
1519 enum LpAlgorithmValues {
1521 DUAL = 10,
1526 };
1532
1538 };
1541 enum ScalingValues {
1546 };
1548 // Placeholder value to indicate that a parameter is set to
1549 // the default value defined in the wrapper.
1550 static const double kDefaultDoubleParamValue;
1551 static const int kDefaultIntegerParamValue;
1553 // Placeholder value to indicate that a parameter is unknown.
1554 static const double kUnknownDoubleParamValue;
1555 static const int kUnknownIntegerParamValue;
1557 // Default values for parameters. Only parameters that define the
1558 // properties of the solution returned need to have a default value
1559 // (that is the same for all solvers). You can also define a default
1560 // value for performance parameters when you are confident it is a
1561 // good choice (example: always turn presolve on).
1562 static const double kDefaultRelativeMipGap;
1563 static const double kDefaultPrimalTolerance;
1564 static const double kDefaultDualTolerance;
1570
1571#ifndef SWIG
1572 // This type is neither copyable nor movable.
1573 MPSolverParameters(const MPSolverParameters&) = delete;
1575#endif
1578 void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1579
1582
1589
1596
1598 void Reset();
1599
1602
1605
1606 private:
1607 // Parameter value for each parameter.
1608 // @see DoubleParam
1609 // @see IntegerParam
1610 double relative_mip_gap_value_;
1611 double primal_tolerance_value_;
1612 double dual_tolerance_value_;
1613 int presolve_value_;
1614 int scaling_value_;
1615 int lp_algorithm_value_;
1616 int incrementality_value_;
1617
1618 // Boolean value indicating whether each parameter is set to the
1619 // solver's default value. Only parameters for which the wrapper
1620 // does not define a default value need such an indicator.
1621 bool lp_algorithm_is_default_;
1622};
1623
1624// Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1625// error when happening on the linear solver stubby server, see
1626// ./linear_solver_service.proto.
1627// Note that RPC errors forbid to carry a response to the client, who can only
1628// see the RPC error itself (error code + error message).
1630
1631// This class wraps the actual mathematical programming solvers. Each
1632// solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1633// derives from this abstract class. This class is never directly
1634// accessed by the user.
1635// @see glop_interface.cc
1636// @see cbc_interface.cc
1637// @see clp_interface.cc
1638// @see glpk_interface.cc
1639// @see scip_interface.cc
1640class MPSolverInterface {
1641 public:
1643 // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1644 // sync for the model nor for the solution.
1646 // The underlying solver and MPSolver are in sync for the model
1647 // but not for the solution: the model has changed since the
1648 // solution was computed last.
1650 // The underlying solver and MPSolver are in sync for the model and
1651 // the solution.
1653 };
1655 // When the underlying solver does not provide the number of simplex
1656 // iterations.
1657 static constexpr int64_t kUnknownNumberOfIterations = -1;
1658 // When the underlying solver does not provide the number of
1659 // branch-and-bound nodes.
1660 static constexpr int64_t kUnknownNumberOfNodes = -1;
1661
1662 // Constructor. The user will access the MPSolverInterface through the
1663 // MPSolver passed as argument.
1664 explicit MPSolverInterface(MPSolver* solver);
1665 virtual ~MPSolverInterface();
1666
1667 // ----- Solve -----
1668 // Solves problem with specified parameter values. Returns true if the
1669 // solution is optimal.
1670 virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1671
1672 // DirectlySolveProto() shall only be used if SupportsDirectlySolveProto() is
1673 // true.
1674 //
1675 // DirectlySolveProto() solves a MPModelRequest, bypassing the MPSolver data
1676 // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1677 // an 'interrupt' boolean.
1678 virtual bool SupportsDirectlySolveProto(
1679 std::atomic<bool>* /*interrupt*/) const {
1680 return false;
1681 }
1684 // `interrupt` is non-const because the internal
1685 // solver may set it to true itself, in some cases.
1686 std::atomic<bool>* /*interrupt*/) {
1687 LOG(DFATAL) << "Default implementation should never be called.";
1688 return MPSolutionResponse();
1689 }
1690
1691 // Writes the model using the solver internal write function. Currently only
1692 // available for GurobiInterface and XpressInterface.
1693 virtual void Write(const std::string& filename);
1694
1695 // ----- Model modifications and extraction -----
1696 // Resets extracted model.
1697 virtual void Reset() = 0;
1698
1699 // Sets the optimization direction (min/max).
1700 virtual void SetOptimizationDirection(bool maximize) = 0;
1701
1702 // Modifies bounds of an extracted variable.
1703 virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1704
1705 // Modifies integrality of an extracted variable.
1706 virtual void SetVariableInteger(int index, bool integer) = 0;
1707
1708 // Modify bounds of an extracted variable.
1709 virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1710
1711 // Adds a linear constraint.
1712 virtual void AddRowConstraint(MPConstraint* ct) = 0;
1713
1714 // Adds an indicator constraint. Returns true if the feature is supported by
1715 // the underlying solver.
1716 virtual bool AddIndicatorConstraint(MPConstraint* const /*ct*/) {
1717 LOG(ERROR) << "Solver doesn't support indicator constraints.";
1718 return false;
1719 }
1720
1721 // Add a variable.
1722 virtual void AddVariable(MPVariable* var) = 0;
1723
1724 // Changes a coefficient in a constraint.
1725 virtual void SetCoefficient(MPConstraint* constraint,
1726 const MPVariable* variable, double new_value,
1727 double old_value) = 0;
1728
1729 // Clears a constraint from all its terms.
1730 virtual void ClearConstraint(MPConstraint* constraint) = 0;
1731
1732 // Changes a coefficient in the linear objective.
1733 virtual void SetObjectiveCoefficient(const MPVariable* variable,
1734 double coefficient) = 0;
1736 // Changes the constant term in the linear objective.
1737 virtual void SetObjectiveOffset(double value) = 0;
1738
1739 // Clears the objective from all its terms.
1740 virtual void ClearObjective() = 0;
1741
1742 virtual void BranchingPriorityChangedForVariable(int /*var_index*/) {}
1743 // ------ Query statistics on the solution and the solve ------
1744 // Returns the number of simplex iterations. The problem must be discrete,
1745 // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1746 virtual int64_t iterations() const = 0;
1747 // Returns the number of branch-and-bound nodes. The problem must be discrete,
1748 // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1749 virtual int64_t nodes() const = 0;
1750 // Returns the best objective bound. The problem must be discrete, otherwise
1751 // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1752 double best_objective_bound() const;
1753 // Returns the objective value of the best solution found so far.
1754 double objective_value() const;
1755
1756 // Returns the basis status of a row.
1757 virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1758 // Returns the basis status of a constraint.
1759 virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1760
1761 // Checks whether the solution is synchronized with the model, i.e. whether
1762 // the model has changed since the solution was computed last.
1763 // If it isn't, it crashes in NDEBUG, and returns false otherwise.
1764 bool CheckSolutionIsSynchronized() const;
1765 // Checks whether a feasible solution exists. The behavior is similar to
1766 // CheckSolutionIsSynchronized() above.
1767 virtual bool CheckSolutionExists() const;
1768 // Handy shortcut to do both checks above (it is often used).
1772
1773 // ----- Misc -----
1774 // Queries problem type. For simplicity, the distinction between
1775 // continuous and discrete is based on the declaration of the user
1776 // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1777 // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1778 // the model.
1779 // Returns true if the problem is continuous.
1780 virtual bool IsContinuous() const = 0;
1781 // Returns true if the problem is continuous and linear.
1782 virtual bool IsLP() const = 0;
1783 // Returns true if the problem is discrete and linear.
1784 virtual bool IsMIP() const = 0;
1785
1786 // Returns the index of the last variable extracted.
1787 int last_variable_index() const { return last_variable_index_; }
1788
1789 bool variable_is_extracted(int var_index) const {
1790 return solver_->variable_is_extracted_[var_index];
1792 void set_variable_as_extracted(int var_index, bool extracted) {
1793 solver_->variable_is_extracted_[var_index] = extracted;
1795 bool constraint_is_extracted(int ct_index) const {
1796 return solver_->constraint_is_extracted_[ct_index];
1798 void set_constraint_as_extracted(int ct_index, bool extracted) {
1799 solver_->constraint_is_extracted_[ct_index] = extracted;
1801
1802 // Returns the boolean indicating the verbosity of the solver output.
1803 bool quiet() const { return quiet_; }
1804 // Sets the boolean indicating the verbosity of the solver output.
1805 void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1806
1807 // Returns the result status of the last solve.
1811 }
1812
1813 // Returns a string describing the underlying solver and its version.
1814 virtual std::string SolverVersion() const = 0;
1815
1816 // Returns the underlying solver.
1817 virtual void* underlying_solver() = 0;
1818
1819 // Computes exact condition number. Only available for continuous
1820 // problems and only implemented in GLPK.
1821 virtual double ComputeExactConditionNumber() const;
1822
1823 // See MPSolver::SetStartingLpBasis().
1824 virtual void SetStartingLpBasis(
1825 const std::vector<MPSolver::BasisStatus>& /*variable_statuses*/,
1826 const std::vector<MPSolver::BasisStatus>& /*constraint_statuses*/) {
1827 LOG(FATAL) << "Not supported by this solver.";
1828 }
1829
1830 virtual double infinity() { return std::numeric_limits<double>::infinity(); }
1831
1832 virtual bool InterruptSolve() { return false; }
1833
1834 // See MPSolver::NextSolution() for contract.
1835 virtual bool NextSolution() { return false; }
1836
1837 // See MPSolver::SetCallback() for details.
1838 virtual void SetCallback(MPCallback* /*mp_callback*/) {
1839 LOG(FATAL) << "Callbacks not supported for this solver.";
1841
1842 virtual bool SupportsCallbacks() const { return false; }
1843
1844 friend class MPSolver;
1845
1846 // To access the maximize_ bool and the MPSolver.
1847 friend class MPConstraint;
1848 friend class MPObjective;
1850 protected:
1851 MPSolver* const solver_;
1852 // Indicates whether the model and the solution are synchronized.
1854 // Indicates whether the solve has reached optimality,
1855 // infeasibility, a limit, etc.
1857 // Optimization direction.
1859
1860 // Index in MPSolver::variables_ of last constraint extracted.
1862 // Index in MPSolver::constraints_ of last variable extracted.
1864
1865 // The value of the objective function.
1866 double objective_value_;
1867
1868 // The value of the best objective bound. Used only for MIP solvers.
1869 double best_objective_bound_;
1870
1871 // Boolean indicator for the verbosity of the solver output.
1872 bool quiet_;
1873
1874 // Index of dummy variable created for empty constraints or the
1875 // objective offset.
1876 static const int kDummyVariableIndex;
1877
1878 // Extracts model stored in MPSolver.
1879 void ExtractModel();
1880 // Extracts the variables that have not been extracted yet.
1881 virtual void ExtractNewVariables() = 0;
1882 // Extracts the constraints that have not been extracted yet.
1883 virtual void ExtractNewConstraints() = 0;
1884 // Extracts the objective.
1885 virtual void ExtractObjective() = 0;
1886 // Resets the extraction information.
1888 // Change synchronization status from SOLUTION_SYNCHRONIZED to
1889 // MODEL_SYNCHRONIZED. To be used for model changes.
1891
1892 // Sets parameters common to LP and MIP in the underlying solver.
1893 void SetCommonParameters(const MPSolverParameters& param);
1894 // Sets MIP specific parameters in the underlying solver.
1895 void SetMIPParameters(const MPSolverParameters& param);
1896 // Sets all parameters in the underlying solver.
1897 virtual void SetParameters(const MPSolverParameters& param) = 0;
1898 // Sets an unsupported double parameter.
1900 // Sets an unsupported integer parameter.
1901 virtual void SetUnsupportedIntegerParam(
1903 // Sets a supported double parameter to an unsupported value.
1905 double value);
1906 // Sets a supported integer parameter to an unsupported value.
1908 MPSolverParameters::IntegerParam param, int value);
1909 // Sets each parameter in the underlying solver.
1910 virtual void SetRelativeMipGap(double value) = 0;
1911 virtual void SetPrimalTolerance(double value) = 0;
1912 virtual void SetDualTolerance(double value) = 0;
1913 virtual void SetPresolveMode(int value) = 0;
1915 // Sets the number of threads to be used by the solver.
1916 virtual absl::Status SetNumThreads(int num_threads);
1917
1918 // Pass solver specific parameters in text format. The format is
1919 // solver-specific and is the same as the corresponding solver configuration
1920 // file format. Returns true if the operation was successful.
1921 //
1922 // Default implementation returns true if the input is empty. It returns false
1923 // and logs a WARNING if the input is not empty.
1925 const std::string& parameters);
1926
1927 // Sets the scaling mode.
1928 virtual void SetScalingMode(int value) = 0;
1929 virtual void SetLpAlgorithm(int value) = 0;
1932// Handy type name for callbacks that create a fresh MPSolverInterface tied
1933// to the given MPSolver. The underlying callback should *always* be permanent.
1934typedef std::function<MPSolverInterface*(MPSolver*)> MPSolverInterfaceFactory;
1935
1936// This class must be instantiated only once, through GetInstance(). It is
1937// thread-safe.
1938//
1939// - To register an existing MPSolverInterface in the global repository:
1940//
1941// MPSolverInterfaceFactory cbc_solver_interface_factory =
1942// CreateCBCInterface;
1943// MPSolverInterfaceFactoryRepository::GetInstance()->Register(
1944// cbc_solver_interface_factory, CBC_MIXED_INTEGER_PROGRAMMING);
1945//
1946// - To get the MPSolverInterfaceFactory associated to a given problem type:
1947//
1948// MPSolverInterface* my_solver_interface =
1949// MPSolverInterfaceFactoryRepository::GetInstance()->Create(
1950// CBC_MIXED_INTEGER_PROGRAMMING);
1951// CHECK(my_solver_interface != NULL) << "CBC not supported.";
1952//
1953// The implementations of MPSolverInterface defined here (e.g. ScipInterface)
1954// are registered at with the MPSolverInterfaceFactoryRepository Singleton
1955// automatically at link time, as long as the cc file where they are defined
1956// (e.g. scip_interface.cc) is included in your binary (i.e. you have a
1957// transitive dependency on the build rule ":linear_solver_scip", which sets
1958// alwayslink=1).
1960 public:
1961 static MPSolverInterfaceFactoryRepository* GetInstance();
1962
1963 // Maps the given factory to the given problem type. For solver needing
1964 // runtime checks an additional `is_runtime_ready` argument can be set. If
1965 // a factory was already assigned to this problem type, it will be replaced.
1968 std::function<bool()> is_runtime_ready = {});
1969
1970 // Invokes the factory associated to the given solver's problem type and fails
1971 // if no factory is registered or its runtime is not ready.
1972 // Use `Supports` below to check if `Create` succeeds.
1973 MPSolverInterface* Create(MPSolver* solver) const;
1974
1975 // Whether the implementation associated to the given problem type is
1976 // available and ready to use.
1977 bool Supports(MPSolver::OptimizationProblemType problem_type) const;
1978
1979 // List all the problem types.
1980 std::vector<MPSolver::OptimizationProblemType> ListAllRegisteredProblemTypes()
1981 const;
1982
1983 // Returns a human-readable list of supported OptimizationProblemType.
1984 std::string PrettyPrintAllRegisteredProblemTypes() const;
1985
1986 // FOR TESTING ONLY.
1988
1989 private:
1990 // The constructor / destructor are private to prevent this class from ever
1991 // being instantiated outside GetInstance().
1992 // TODO(user): consider adding the GLOP factory by default, and then expose
1993 // it via a CreateDefault() method.
1996
1997 mutable absl::Mutex mutex_;
1998 struct Entry {
2000 std::function<bool()> is_runtime_ready;
2001 };
2002 std::map<MPSolver::OptimizationProblemType, Entry> map_;
2003};
2004
2005} // namespace operations_research
2006
2007#endif // ORTOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
#define OR_DLL
Definition base_export.h:27
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
void set_dual_value(double dual_value)
void Clear()
Clears all variables and coefficients. Does not clear the bounds.
void SetCoefficient(const MPVariable *var, double coeff)
double lb() const
Returns the lower bound.
const absl::flat_hash_map< const MPVariable *, double > & terms() const
double ub() const
Returns the upper bound.
void SetUB(double ub)
Sets the upper bound.
void SetLB(double lb)
Sets the lower bound.
MPSolver::BasisStatus basis_status() const
MPConstraint(const MPConstraint &)=delete
const MPVariable * indicator_variable() const
MPConstraint & operator=(const MPConstraint &)=delete
double GetCoefficient(const MPVariable *var) const
const std::string & name() const
Returns the name of the constraint.
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
MPModelRequest_SolverType SolverType
static constexpr SolverType SAT_INTEGER_PROGRAMMING
static constexpr SolverType GUROBI_MIXED_INTEGER_PROGRAMMING
static constexpr SolverType PDLP_LINEAR_PROGRAMMING
static constexpr SolverType GUROBI_LINEAR_PROGRAMMING
static constexpr SolverType GLOP_LINEAR_PROGRAMMING
A class to express a linear objective.
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
void SetCoefficient(const MPVariable *var, double coeff)
double GetCoefficient(const MPVariable *var) const
void SetOffset(double value)
Sets the constant term in the objective.
MPObjective(const MPObjective &)=delete
const absl::flat_hash_map< const MPVariable *, double > & terms() const
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
bool minimization() const
Is the optimization direction set to minimize?
void SetMaximization()
Sets the optimization direction to maximize.
bool maximization() const
Is the optimization direction set to maximize?
double offset() const
Gets the constant term in the objective.
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
void OptimizeLinearExpr(const LinearExpr &linear_expr, bool is_maximization)
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
MPObjective & operator=(const MPObjective &)=delete
void SetMinimization()
Sets the optimization direction to minimize.
MPSolverInterface * Create(MPSolver *solver) const
std::vector< MPSolver::OptimizationProblemType > ListAllRegisteredProblemTypes() const
static MPSolverInterfaceFactoryRepository * GetInstance()
bool Unregister(MPSolver::OptimizationProblemType problem_type)
bool Supports(MPSolver::OptimizationProblemType problem_type) const
void Register(MPSolverInterfaceFactory factory, MPSolver::OptimizationProblemType problem_type, std::function< bool()> is_runtime_ready={})
void set_variable_as_extracted(int var_index, bool extracted)
virtual void AddVariable(MPVariable *var)=0
MPSolver::ResultStatus result_status() const
virtual void SetCallback(MPCallback *)
virtual void SetPrimalTolerance(double value)=0
static constexpr int64_t kUnknownNumberOfIterations
virtual void SetRelativeMipGap(double value)=0
virtual void SetObjectiveCoefficient(const MPVariable *variable, double coefficient)=0
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &, const std::vector< MPSolver::BasisStatus > &)
void set_constraint_as_extracted(int ct_index, bool extracted)
virtual int64_t nodes() const =0
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
virtual void SetPresolveMode(int value)=0
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
virtual void SetCoefficient(MPConstraint *constraint, const MPVariable *variable, double new_value, double old_value)=0
virtual std::string SolverVersion() const =0
virtual void SetVariableInteger(int index, bool integer)=0
virtual absl::Status SetNumThreads(int num_threads)
virtual int64_t iterations() const =0
virtual void BranchingPriorityChangedForVariable(int)
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
virtual void SetObjectiveOffset(double value)=0
virtual void SetParameters(const MPSolverParameters &param)=0
virtual bool IsContinuous() const =0
virtual void SetLpAlgorithm(int value)=0
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
bool variable_is_extracted(int var_index) const
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
virtual bool SupportsDirectlySolveProto(std::atomic< bool > *) const
bool constraint_is_extracted(int ct_index) const
static constexpr int64_t kUnknownNumberOfNodes
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
virtual void SetScalingMode(int value)=0
virtual double ComputeExactConditionNumber() const
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
virtual void AddRowConstraint(MPConstraint *ct)=0
virtual MPSolutionResponse DirectlySolveProto(LazyMutableCopy< MPModelRequest >, std::atomic< bool > *)
virtual void Write(const std::string &filename)
void SetMIPParameters(const MPSolverParameters &param)
virtual void SetDualTolerance(double value)=0
virtual bool AddIndicatorConstraint(MPConstraint *const)
virtual void SetOptimizationDirection(bool maximize)=0
void SetCommonParameters(const MPSolverParameters &param)
virtual void ClearConstraint(MPConstraint *constraint)=0
virtual void SetConstraintBounds(int index, double lb, double ub)=0
virtual void SetVariableBounds(int index, double lb, double ub)=0
static const PresolveValues kDefaultPresolve
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
MPSolverParameters & operator=(const MPSolverParameters &)=delete
DoubleParam
Enumeration of parameters that take continuous values.
@ DUAL_TOLERANCE
Advanced usage: tolerance for dual feasibility of basic solutions.
@ RELATIVE_MIP_GAP
Limit for relative MIP gap.
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
PresolveValues
For each categorical parameter, enumeration of possible values.
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
IntegerParam
Enumeration of parameters that take integer or categorical values.
@ INCREMENTALITY
Advanced usage: incrementality from one solve to the next.
@ PRESOLVE
Advanced usage: presolve mode.
@ LP_ALGORITHM
Algorithm to solve linear programs.
@ SCALING
Advanced usage: enable or disable matrix scaling.
MPSolverParameters()
The constructor sets all parameters to their default value.
static const IncrementalityValues kDefaultIncrementality
IncrementalityValues
Advanced usage: Incrementality options.
@ INCREMENTALITY_OFF
Start solve from scratch.
void Reset()
Sets all parameters to their default value.
ScalingValues
Advanced usage: Scaling options.
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
static void SolveLazyMutableRequest(LazyMutableCopy< MPModelRequest > request, MPSolutionResponse *response, std::atomic< bool > *interrupt=nullptr)
int64_t iterations() const
Returns the number of simplex iterations.
int NumVariables() const
Returns the number of variables.
static MPSolver * CreateSolver(const std::string &solver_id)
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
MPVariable * MakeVar(double lb, double ub, bool integer, const std::string &name)
const std::vector< MPVariable * > & variables() const
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
int NumConstraints() const
Returns the number of constraints.
@ MODEL_INVALID
the model is trivially invalid (NaN coefficients, etc).
@ FEASIBLE
feasible, or stopped by limit.
@ NOT_SOLVED
not been solved yet.
@ INFEASIBLE
proven infeasible.
@ ABNORMAL
abnormal, i.e., error of some kind.
ABSL_DEPRECATED("Prefer SolverTypeSupportsInterruption() from solve_mp_model.h.") static bool SolverTypeSupportsInterruption(const MPModelRequest
ResultStatus Solve()
Solves the problem using the default parameter values.
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message, bool clear_names=true)
bool VerifySolution(double tolerance, bool log_errors) const
void MakeVarArray(int nb, double lb, double ub, bool integer, const std::string &name_prefix, std::vector< MPVariable * > *vars)
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
const MPObjective & Objective() const
void SetCallback(MPCallback *mp_callback)
void SetTimeLimit(absl::Duration time_limit)
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
bool SetSolverSpecificParametersAsString(const std::string &parameters)
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
virtual OptimizationProblemType ProblemType() const
Returns the optimization problem type set at construction.
ABSL_MUST_USE_RESULT bool NextSolution()
static bool SupportsProblemType(OptimizationProblemType problem_type)
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
double ComputeExactConditionNumber() const
std::string GetSolverSpecificParametersAsString() const
absl::Duration DurationSinceConstruction() const
absl::Status SetNumThreads(int num_threads)
MPVariable * variable(int index) const
bool OwnsVariable(const MPVariable *var) const
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
std::vector< double > ComputeConstraintActivities() const
int GetNumThreads() const
Returns the number of threads to be used during solve.
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
static std::string GetMPModelRequestLoggingInfo(const MPModelRequest &request)
MPConstraint * MakeRowConstraint()
Creates a constraint with -infinity and +infinity bounds.
const std::vector< MPConstraint * > & constraints() const
MPObjective * MutableObjective()
Returns the mutable objective object.
static OptimizationProblemType ParseSolverTypeOrDie(const std::string &solver_id)
absl::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=std::numeric_limits< double >::infinity())
absl::Duration TimeLimit() const
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
MPConstraint * constraint(int index) const
void EnableOutput()
Enables solver logging.
static int64_t global_num_variables()
MPSolver & operator=(const MPSolver &)=delete
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
void SuppressOutput()
Suppresses solver logging.
MPVariable * LookupVariableOrNull(const std::string &var_name) const
void Write(const std::string &file_name)
static int64_t global_num_constraints()
const std::string & Name() const
Returns the name of the model set at construction.
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
static bool ParseSolverType(absl::string_view solver_id, OptimizationProblemType *type)
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response, std::atomic< bool > *interrupt=nullptr)
std::string SolverVersion() const
Returns a string describing the underlying solver and its version.
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
void set_time_limit(int64_t time_limit_milliseconds)
The class for variables of a Mathematical Programming (MP) model.
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
bool integer() const
Returns the integrality requirement of the variable.
void SetBranchingPriority(int priority)
void SetLB(double lb)
Sets the lower bound.
double lb() const
Returns the lower bound.
double ub() const
Returns the upper bound.
MPVariable(const MPVariable &)=delete
void SetUB(double ub)
Sets the upper bound.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
const std::string & name() const
Returns the name of the variable.
MPVariable & operator=(const MPVariable &)=delete
void set_reduced_cost(double reduced_cost)
void set_solution_value(double value)
MPSolver::BasisStatus basis_status() const
int index() const
Returns the index of the variable in the MPSolver::variables_.
OR_DLL ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output)
OR-Tools root namespace.
constexpr double kDefaultPrimalTolerance
std::function< MPSolverInterface *(MPSolver *)> MPSolverInterfaceFactory
bool SolverTypeSupportsInterruption(const MPModelRequest::SolverType solver)
bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status)
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
bool AbslParseFlag(const absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)
std::string AbslUnparseFlag(MPSolver::OptimizationProblemType solver_type)
STL namespace.