Google OR-Tools v9.14
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 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 <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/status/status.h"
156#include "absl/strings/str_format.h"
157#include "absl/strings/string_view.h"
158#include "absl/time/clock.h"
159#include "absl/time/time.h"
160#include "absl/types/optional.h"
162#include "ortools/base/logging.h"
168
169OR_DLL ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
170OR_DLL ABSL_DECLARE_FLAG(bool, log_verification_errors);
171OR_DLL ABSL_DECLARE_FLAG(bool, verify_solution);
172
173namespace operations_research {
174
175constexpr double kDefaultPrimalTolerance = 1e-07;
176
177class MPConstraint;
178class MPObjective;
181class MPVariable;
182
183// There is a homonymous version taking a MPSolver::OptimizationProblemType.
185
190class MPSolver {
191 public:
199 // Linear programming problems.
200 // ----------------------------
203 GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
204 // In-house linear programming solver based on the primal-dual hybrid
205 // gradient method. Sometimes faster than Glop for medium-size problems and
206 // scales to much larger problems than Glop.
210 // Integer programming problems.
211 // -----------------------------
212 // Recommended default value for MIP problems.
218 // Boolean optimization problem (requires only integer variables and works
219 // best with only Boolean variables).
221
222 // SAT based solver (requires only integer and Boolean variables).
223 // If you pass it mixed integer problems, it will scale coefficients to
224 // integer values, and solver continuous variables as integral variables.
225 //
226 // Recommended default value for pure integral problems problems.
228
229 // Dedicated knapsack solvers.
231
232 // Commercial software (need license).
241 };
244 MPSolver(const std::string& name, OptimizationProblemType problem_type);
245
246#ifndef SWIG
247 // This type is neither copyable nor movable.
248 MPSolver(const MPSolver&) = delete;
249 MPSolver& operator=(const MPSolver&) = delete;
250#endif
252 virtual ~MPSolver();
253
282 static MPSolver* CreateSolver(const std::string& solver_id);
283
288 static bool SupportsProblemType(OptimizationProblemType problem_type);
289
295 static bool ParseSolverType(absl::string_view solver_id,
297
303 const std::string& solver_id);
304
305 bool IsMIP() const;
306
308 const std::string& Name() const {
309 return name_; // Set at construction.
311
313 virtual OptimizationProblemType ProblemType() const {
314 return problem_type_; // Set at construction.
316
318
322 void Clear();
323
325 int NumVariables() const { return variables_.size(); }
326
331 const std::vector<MPVariable*>& variables() const { return variables_; }
332
336 MPVariable* variable(int index) const { return variables_[index]; }
337
343 MPVariable* LookupVariableOrNull(const std::string& var_name) const;
344
352 MPVariable* MakeVar(double lb, double ub, bool integer,
353 const std::string& name);
354
356 MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
357
359 MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
360
362 MPVariable* MakeBoolVar(const std::string& name);
363
378 void MakeVarArray(int nb, double lb, double ub, bool integer,
379 const std::string& name_prefix,
380 std::vector<MPVariable*>* vars);
381
383 void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
384 std::vector<MPVariable*>* vars);
385
387 void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
388 std::vector<MPVariable*>* vars);
389
391 void MakeBoolVarArray(int nb, const std::string& name,
392 std::vector<MPVariable*>* vars);
393
395 int NumConstraints() const { return constraints_.size(); }
396
402 const std::vector<MPConstraint*>& constraints() const { return constraints_; }
403
405 MPConstraint* constraint(int index) const { return constraints_[index]; }
406
415 const std::string& constraint_name) const;
416
425 MPConstraint* MakeRowConstraint(double lb, double ub);
426
429
431 MPConstraint* MakeRowConstraint(double lb, double ub,
432 const std::string& name);
433
435 MPConstraint* MakeRowConstraint(const std::string& name);
436
442
445 const std::string& name);
446
453 const MPObjective& Objective() const { return *objective_; }
454
456 MPObjective* MutableObjective() { return objective_.get(); }
457
464 enum ResultStatus {
483
486
491 void Write(const std::string& file_name);
492
499 std::vector<double> ComputeConstraintActivities() const;
500
519 bool VerifySolution(double tolerance, bool log_errors) const;
520
529 void Reset();
530
540 bool InterruptSolve();
541
552 std::string* error_message,
553 bool clear_names = true);
562 const MPModelProto& input_model, std::string* error_message);
563
565 void FillSolutionResponseProto(MPSolutionResponse* response) const;
566
585 ABSL_DEPRECATED("Prefer SolveMPModel() from solve_mp_model.h.")
586 static void SolveWithProto(const MPModelRequest& model_request,
587 MPSolutionResponse* response,
588 std::atomic<bool>* interrupt = nullptr);
589
599 ABSL_DEPRECATED("Prefer SolveMPModel() from solve_mp_model.h.")
601 MPSolutionResponse* response,
602 std::atomic<bool>* interrupt = nullptr);
603
605 "Prefer SolverTypeSupportsInterruption() from solve_mp_model.h.")
607 const MPModelRequest::SolverType solver) {
608 // Interruption requires that MPSolver::InterruptSolve is supported for the
609 // underlying solver. Interrupting requests using SCIP is also not supported
610 // as of 2021/08/23, since InterruptSolve is not thread safe for SCIP.
616 }
617
619 void ExportModelToProto(MPModelProto* output_model) const;
620
654 absl::Status LoadSolutionFromProto(
655 const MPSolutionResponse& response,
656 double tolerance = std::numeric_limits<double>::infinity());
657
662 absl::Status ClampSolutionWithinBounds();
663
670 bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
671 bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
672 std::string* model_str) const;
673
684 absl::Status SetNumThreads(int num_threads);
685
687 int GetNumThreads() const { return num_threads_; }
688
695 bool SetSolverSpecificParametersAsString(const std::string& parameters);
696 std::string GetSolverSpecificParametersAsString() const {
697 return solver_specific_parameter_string_;
699
701
715 void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
716
717 // Gives some brief (a few lines, at most) human-readable information about
718 // the given request, suitable for debug logging.
719 ABSL_DEPRECATED("Prefer MPModelRequestLoggingInfo() from solve_mp_model.h.")
720 static std::string GetMPModelRequestLoggingInfo(
721 const MPModelRequest& request);
722
727 enum BasisStatus {
728 FREE = 0,
736
747 const std::vector<MPSolver::BasisStatus>& variable_statuses,
748 const std::vector<MPSolver::BasisStatus>& constraint_statuses);
749
755 static double infinity() { return std::numeric_limits<double>::infinity(); }
756 double solver_infinity();
766 bool OutputIsEnabled() const;
767
769 void EnableOutput();
770
772 void SuppressOutput();
773
774 absl::Duration TimeLimit() const { return time_limit_; }
775 void SetTimeLimit(absl::Duration time_limit) {
776 DCHECK_GE(time_limit, absl::ZeroDuration());
777 time_limit_ = time_limit;
778 }
779
780 absl::Duration DurationSinceConstruction() const {
781 return absl::Now() - construction_time_;
783
785 int64_t iterations() const;
786
792 int64_t nodes() const;
793
795 std::string SolverVersion() const;
796
810 void* underlying_solver();
811
835 double ComputeExactConditionNumber() const;
836
851 ABSL_MUST_USE_RESULT bool NextSolution();
852
853 // Does not take ownership of "mp_callback".
854 //
855 // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
856 // SCIP does not support suggesting a heuristic solution in the callback.
857 void SetCallback(MPCallback* mp_callback);
858 bool SupportsCallbacks() const;
859
860 // Global counters of variables and constraints ever created across all
861 // MPSolver instances. Those are only updated after the destruction
862 // (or Clear()) of each MPSolver instance.
863 static int64_t global_num_variables();
864 static int64_t global_num_constraints();
865
866 // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
867 // NOTE: These deprecated functions used the convention time_limit = 0 to mean
868 // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
869 int64_t time_limit() const {
870 return time_limit_ == absl::InfiniteDuration()
871 ? 0
872 : absl::ToInt64Milliseconds(time_limit_);
873 }
874 void set_time_limit(int64_t time_limit_milliseconds) {
875 SetTimeLimit(time_limit_milliseconds == 0
876 ? absl::InfiniteDuration()
877 : absl::Milliseconds(time_limit_milliseconds));
878 }
879 double time_limit_in_secs() const {
880 return static_cast<double>(time_limit()) / 1000.0;
882
883 // DEPRECATED: Use DurationSinceConstruction() instead.
884 int64_t wall_time() const {
885 return absl::ToInt64Milliseconds(DurationSinceConstruction());
887
888 friend class GLPKInterface;
889 friend class CLPInterface;
890 friend class CBCInterface;
891 friend class SCIPInterface;
892 friend class GurobiInterface;
893 friend class CplexInterface;
894 friend class XpressInterface;
895 friend class SLMInterface;
896 friend class MPSolverInterface;
897 friend class GLOPInterface;
898 friend class BopInterface;
899 friend class SatInterface;
900 friend class PdlpInterface;
901 friend class HighsInterface;
902 friend class KnapsackInterface;
904 // Debugging: verify that the given MPVariable* belongs to this solver.
905 bool OwnsVariable(const MPVariable* var) const;
906
907 private:
908 // Computes the size of the constraint with the largest number of
909 // coefficients with index in [min_constraint_index,
910 // max_constraint_index)
911 int ComputeMaxConstraintSize(int min_constraint_index,
912 int max_constraint_index) const;
913
914 // Returns true if the model has constraints with lower bound > upper bound.
915 bool HasInfeasibleConstraints() const;
916
917 // Returns true if the model has at least 1 integer variable.
918 bool HasIntegerVariables() const;
919
920 // Generates the map from variable names to their indices.
921 void GenerateVariableNameIndex() const;
922
923 // Generates the map from constraint names to their indices.
924 void GenerateConstraintNameIndex() const;
925
926 // The name of the linear programming problem.
927 const std::string name_;
928
929 // The type of the linear programming problem.
930 const OptimizationProblemType problem_type_;
931
932 // The solver interface.
933 std::unique_ptr<MPSolverInterface> interface_;
934
935 // The vector of variables in the problem.
936 std::vector<MPVariable*> variables_;
937 // A map from a variable's name to its index in variables_.
938 mutable std::optional<absl::flat_hash_map<std::string, int> >
939 variable_name_to_index_;
940 // Whether variables have been extracted to the underlying interface.
941 std::vector<bool> variable_is_extracted_;
942
943 // The vector of constraints in the problem.
944 std::vector<MPConstraint*> constraints_;
945 // A map from a constraint's name to its index in constraints_.
946 mutable std::optional<absl::flat_hash_map<std::string, int> >
947 constraint_name_to_index_;
948 // Whether constraints have been extracted to the underlying interface.
949 std::vector<bool> constraint_is_extracted_;
950
951 // The linear objective function.
952 std::unique_ptr<MPObjective> objective_;
953
954 // Initial values for all or some of the problem variables that can be
955 // exploited as a starting hint by a solver.
956 //
957 // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
958 //
959 // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
960 // hint is provided and a std::vector<double> for the hint value.
961 std::vector<std::pair<const MPVariable*, double> > solution_hint_;
962
963 absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
964
965 const absl::Time construction_time_;
966
967 // Permanent storage for the number of threads.
968 int num_threads_ = 1;
969
970 // Permanent storage for SetSolverSpecificParametersAsString().
971 std::string solver_specific_parameter_string_;
972
973 static absl::Mutex global_count_mutex_;
974#ifndef SWIG
975 static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
976 static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
977#endif
978
979 enum ModelProtoNamesPolicy {
980 DEFAULT_CLEAR_NAMES = 0,
981 INVALID_MODEL_ON_DUPLICATE_NONEMPTY_NAMES = 1,
982 DIE_ON_DUPLICATE_NONEMPTY_NAMES = 2,
983 };
984 MPSolverResponseStatus LoadModelFromProtoInternal(
985 const MPModelProto& input_model, ModelProtoNamesPolicy name_policy,
986 bool check_model_validity, std::string* error_message);
987};
988
989inline bool SolverTypeIsMip(MPSolver::OptimizationProblemType solver_type) {
990 return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
992
993absl::string_view ToString(
994 MPSolver::OptimizationProblemType optimization_problem_type);
995
996inline std::ostream& operator<<(
997 std::ostream& os,
998 MPSolver::OptimizationProblemType optimization_problem_type) {
999 return os << ToString(optimization_problem_type);
1000}
1001
1002inline std::ostream& operator<<(std::ostream& os,
1003 MPSolver::ResultStatus status) {
1004 return os << ProtoEnumToString<MPSolverResponseStatus>(
1005 static_cast<MPSolverResponseStatus>(status));
1006}
1007
1008bool AbslParseFlag(absl::string_view text,
1010 std::string* error);
1011
1012inline std::string AbslUnparseFlag(
1014 return std::string(ToString(solver_type));
1015}
1016
1018class MPObjective {
1019 public:
1020#ifndef SWIG
1021 // This type is neither copyable nor movable.
1022 MPObjective(const MPObjective&) = delete;
1023 MPObjective& operator=(const MPObjective&) = delete;
1024#endif
1030 void Clear();
1031
1038 void SetCoefficient(const MPVariable* var, double coeff);
1039
1045 double GetCoefficient(const MPVariable* var) const;
1046
1052 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1053 return coefficients_;
1055
1057 void SetOffset(double value);
1058
1060 double offset() const { return offset_; }
1061
1066 void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1067
1069 void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1070 OptimizeLinearExpr(linear_expr, true);
1073 void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1074 OptimizeLinearExpr(linear_expr, false);
1076
1078 void AddLinearExpr(const LinearExpr& linear_expr);
1079
1081 void SetOptimizationDirection(bool maximize);
1082
1084 void SetMinimization() { SetOptimizationDirection(false); }
1085
1088
1090 bool maximization() const;
1091
1093 bool minimization() const;
1094
1106 double Value() const;
1107
1114 double BestBound() const;
1115
1116 private:
1117 friend class MPSolver;
1118 friend class MPSolverInterface;
1119 friend class CBCInterface;
1120 friend class CLPInterface;
1121 friend class GLPKInterface;
1122 friend class SCIPInterface;
1123 friend class SLMInterface;
1124 friend class GurobiInterface;
1125 friend class CplexInterface;
1126 friend class XpressInterface;
1127 friend class GLOPInterface;
1128 friend class BopInterface;
1129 friend class SatInterface;
1130 friend class PdlpInterface;
1131 friend class HighsInterface;
1132 friend class KnapsackInterface;
1134 // Constructor. An objective points to a single MPSolverInterface
1135 // that is specified in the constructor. An objective cannot belong
1136 // to several models.
1137 // At construction, an MPObjective has no terms (which is equivalent
1138 // on having a coefficient of 0 for all variables), and an offset of 0.
1139 explicit MPObjective(MPSolverInterface* const interface_in)
1140 : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1141
1142 MPSolverInterface* const interface_;
1143
1144 // Mapping var -> coefficient.
1145 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1146 // Constant term.
1147 double offset_;
1148};
1149
1151class MPVariable {
1152 public:
1153#ifndef SWIG
1154 // This type is neither copyable nor movable.
1155 MPVariable(const MPVariable&) = delete;
1156 MPVariable& operator=(const MPVariable&) = delete;
1157#endif
1160 const std::string& name() const { return name_; }
1161
1163 void SetInteger(bool integer);
1164
1166 bool integer() const { return integer_; }
1167
1175 double solution_value() const;
1176
1178 int index() const { return index_; }
1179
1181 double lb() const { return lb_; }
1182
1184 double ub() const { return ub_; }
1185
1187 void SetLB(double lb) { SetBounds(lb, ub_); }
1188
1190 void SetUB(double ub) { SetBounds(lb_, ub); }
1191
1193 void SetBounds(double lb, double ub);
1194
1201 double unrounded_solution_value() const;
1202
1207 double reduced_cost() const;
1208
1216
1227 int branching_priority() const { return branching_priority_; }
1228 void SetBranchingPriority(int priority);
1230 protected:
1231 friend class MPSolver;
1232 friend class MPSolverInterface;
1233 friend class CBCInterface;
1234 friend class CLPInterface;
1235 friend class GLPKInterface;
1236 friend class SCIPInterface;
1237 friend class SLMInterface;
1238 friend class GurobiInterface;
1239 friend class CplexInterface;
1240 friend class XpressInterface;
1241 friend class GLOPInterface;
1243 friend class BopInterface;
1244 friend class SatInterface;
1245 friend class PdlpInterface;
1246 friend class HighsInterface;
1247 friend class KnapsackInterface;
1249 // Constructor. A variable points to a single MPSolverInterface that
1250 // is specified in the constructor. A variable cannot belong to
1251 // several models.
1252 MPVariable(int index, double lb, double ub, bool integer,
1253 const std::string& name, MPSolverInterface* const interface_in)
1254 : index_(index),
1255 lb_(lb),
1256 ub_(ub),
1257 integer_(integer),
1258 name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1259 solution_value_(0.0),
1260 reduced_cost_(0.0),
1261 interface_(interface_in) {}
1262
1263 void set_solution_value(double value) { solution_value_ = value; }
1264 void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1266 private:
1267 const int index_;
1268 double lb_;
1269 double ub_;
1270 bool integer_;
1271 const std::string name_;
1272 double solution_value_;
1273 double reduced_cost_;
1274 int branching_priority_ = 0;
1275 MPSolverInterface* const interface_;
1276};
1277
1279
1283class MPConstraint {
1284 public:
1285#ifndef SWIG
1286 // This type is neither copyable nor movable.
1287 MPConstraint(const MPConstraint&) = delete;
1288 MPConstraint& operator=(const MPConstraint&) = delete;
1289#endif
1292 const std::string& name() const { return name_; }
1293
1295 void Clear();
1296
1303 void SetCoefficient(const MPVariable* var, double coeff);
1304
1309 double GetCoefficient(const MPVariable* var) const;
1310
1316 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1317 return coefficients_;
1319
1321 double lb() const { return lb_; }
1322
1324 double ub() const { return ub_; }
1325
1327 void SetLB(double lb) { SetBounds(lb, ub_); }
1328
1330 void SetUB(double ub) { SetBounds(lb_, ub); }
1331
1333 void SetBounds(double lb, double ub);
1334
1336 bool is_lazy() const { return is_lazy_; }
1337
1351 void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1352
1353 const MPVariable* indicator_variable() const { return indicator_variable_; }
1354 bool indicator_value() const { return indicator_value_; }
1357 int index() const { return index_; }
1358
1363 double dual_value() const;
1364
1378
1379 protected:
1380 friend class MPSolver;
1381 friend class MPSolverInterface;
1382 friend class CBCInterface;
1383 friend class CLPInterface;
1384 friend class GLPKInterface;
1385 friend class SCIPInterface;
1386 friend class SLMInterface;
1387 friend class GurobiInterface;
1388 friend class CplexInterface;
1389 friend class XpressInterface;
1390 friend class GLOPInterface;
1391 friend class BopInterface;
1392 friend class SatInterface;
1393 friend class PdlpInterface;
1394 friend class HighsInterface;
1395 friend class KnapsackInterface;
1397 // Constructor. A constraint points to a single MPSolverInterface
1398 // that is specified in the constructor. A constraint cannot belong
1399 // to several models.
1400 MPConstraint(int index, double lb, double ub, const std::string& name,
1401 MPSolverInterface* const interface_in)
1402 : coefficients_(1),
1403 index_(index),
1404 lb_(lb),
1405 ub_(ub),
1406 name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1407 is_lazy_(false),
1408 indicator_variable_(nullptr),
1409 dual_value_(0.0),
1410 interface_(interface_in) {}
1411
1412 void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1413
1414 private:
1415 // Returns true if the constraint contains variables that have not
1416 // been extracted yet.
1417 bool ContainsNewVariables();
1418
1419 // Mapping var -> coefficient.
1420 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1421
1422 const int index_; // See index().
1423
1424 // The lower bound for the linear constraint.
1425 double lb_;
1426
1427 // The upper bound for the linear constraint.
1428 double ub_;
1429
1430 // Name.
1431 const std::string name_;
1432
1433 // True if the constraint is "lazy", i.e. the constraint is added to the
1434 // underlying Linear Programming solver only if it is violated.
1435 // By default this parameter is 'false'.
1436 bool is_lazy_;
1437
1438 // If given, this constraint is only active if `indicator_variable_`'s value
1439 // is equal to `indicator_value_`.
1440 const MPVariable* indicator_variable_;
1441 bool indicator_value_;
1442
1443 double dual_value_;
1444 MPSolverInterface* const interface_;
1445};
1446
1448
1474 public:
1475 /// Enumeration of parameters that take continuous values.
1476 enum DoubleParam {
1492 enum IntegerParam {
1494 PRESOLVE = 1000,
1500 SCALING = 1003
1501 };
1504 enum PresolveValues {
1512 enum LpAlgorithmValues {
1514 DUAL = 10,
1519 };
1525
1531 };
1534 enum ScalingValues {
1539 };
1541 // Placeholder value to indicate that a parameter is set to
1542 // the default value defined in the wrapper.
1543 static const double kDefaultDoubleParamValue;
1544 static const int kDefaultIntegerParamValue;
1546 // Placeholder value to indicate that a parameter is unknown.
1547 static const double kUnknownDoubleParamValue;
1548 static const int kUnknownIntegerParamValue;
1550 // Default values for parameters. Only parameters that define the
1551 // properties of the solution returned need to have a default value
1552 // (that is the same for all solvers). You can also define a default
1553 // value for performance parameters when you are confident it is a
1554 // good choice (example: always turn presolve on).
1555 static const double kDefaultRelativeMipGap;
1556 static const double kDefaultPrimalTolerance;
1557 static const double kDefaultDualTolerance;
1563
1564#ifndef SWIG
1565 // This type is neither copyable nor movable.
1566 MPSolverParameters(const MPSolverParameters&) = delete;
1568#endif
1571 void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1572
1575
1582
1589
1591 void Reset();
1592
1595
1598
1599 private:
1600 // Parameter value for each parameter.
1601 // @see DoubleParam
1602 // @see IntegerParam
1603 double relative_mip_gap_value_;
1604 double primal_tolerance_value_;
1605 double dual_tolerance_value_;
1606 int presolve_value_;
1607 int scaling_value_;
1608 int lp_algorithm_value_;
1609 int incrementality_value_;
1610
1611 // Boolean value indicating whether each parameter is set to the
1612 // solver's default value. Only parameters for which the wrapper
1613 // does not define a default value need such an indicator.
1614 bool lp_algorithm_is_default_;
1615};
1616
1617// Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1618// error when happening on the linear solver stubby server, see
1619// ./linear_solver_service.proto.
1620// Note that RPC errors forbid to carry a response to the client, who can only
1621// see the RPC error itself (error code + error message).
1623
1624// This class wraps the actual mathematical programming solvers. Each
1625// solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1626// derives from this abstract class. This class is never directly
1627// accessed by the user.
1628// @see glop_interface.cc
1629// @see cbc_interface.cc
1630// @see clp_interface.cc
1631// @see glpk_interface.cc
1632// @see scip_interface.cc
1633class MPSolverInterface {
1634 public:
1636 // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1637 // sync for the model nor for the solution.
1639 // The underlying solver and MPSolver are in sync for the model
1640 // but not for the solution: the model has changed since the
1641 // solution was computed last.
1643 // The underlying solver and MPSolver are in sync for the model and
1644 // the solution.
1646 };
1648 // When the underlying solver does not provide the number of simplex
1649 // iterations.
1650 static constexpr int64_t kUnknownNumberOfIterations = -1;
1651 // When the underlying solver does not provide the number of
1652 // branch-and-bound nodes.
1653 static constexpr int64_t kUnknownNumberOfNodes = -1;
1654
1655 // Constructor. The user will access the MPSolverInterface through the
1656 // MPSolver passed as argument.
1657 explicit MPSolverInterface(MPSolver* solver);
1658 virtual ~MPSolverInterface();
1659
1660 // ----- Solve -----
1661 // Solves problem with specified parameter values. Returns true if the
1662 // solution is optimal.
1663 virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1664
1665 // DirectlySolveProto() shall only be used if SupportsDirectlySolveProto() is
1666 // true.
1667 //
1668 // DirectlySolveProto() solves a MPModelRequest, bypassing the MPSolver data
1669 // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1670 // an 'interrupt' boolean.
1671 virtual bool SupportsDirectlySolveProto(
1672 std::atomic<bool>* /*interrupt*/) const {
1673 return false;
1674 }
1677 // `interrupt` is non-const because the internal
1678 // solver may set it to true itself, in some cases.
1679 std::atomic<bool>* /*interrupt*/) {
1680 LOG(DFATAL) << "Default implementation should never be called.";
1681 return MPSolutionResponse();
1682 }
1683
1684 // Writes the model using the solver internal write function. Currently only
1685 // available for GurobiInterface and XpressInterface.
1686 virtual void Write(const std::string& filename);
1687
1688 // ----- Model modifications and extraction -----
1689 // Resets extracted model.
1690 virtual void Reset() = 0;
1691
1692 // Sets the optimization direction (min/max).
1693 virtual void SetOptimizationDirection(bool maximize) = 0;
1694
1695 // Modifies bounds of an extracted variable.
1696 virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1697
1698 // Modifies integrality of an extracted variable.
1699 virtual void SetVariableInteger(int index, bool integer) = 0;
1700
1701 // Modify bounds of an extracted variable.
1702 virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1703
1704 // Adds a linear constraint.
1705 virtual void AddRowConstraint(MPConstraint* ct) = 0;
1706
1707 // Adds an indicator constraint. Returns true if the feature is supported by
1708 // the underlying solver.
1709 virtual bool AddIndicatorConstraint(MPConstraint* const /*ct*/) {
1710 LOG(ERROR) << "Solver doesn't support indicator constraints.";
1711 return false;
1712 }
1713
1714 // Add a variable.
1715 virtual void AddVariable(MPVariable* var) = 0;
1716
1717 // Changes a coefficient in a constraint.
1718 virtual void SetCoefficient(MPConstraint* constraint,
1719 const MPVariable* variable, double new_value,
1720 double old_value) = 0;
1721
1722 // Clears a constraint from all its terms.
1723 virtual void ClearConstraint(MPConstraint* constraint) = 0;
1724
1725 // Changes a coefficient in the linear objective.
1726 virtual void SetObjectiveCoefficient(const MPVariable* variable,
1727 double coefficient) = 0;
1729 // Changes the constant term in the linear objective.
1730 virtual void SetObjectiveOffset(double value) = 0;
1731
1732 // Clears the objective from all its terms.
1733 virtual void ClearObjective() = 0;
1734
1735 virtual void BranchingPriorityChangedForVariable(int /*var_index*/) {}
1736 // ------ Query statistics on the solution and the solve ------
1737 // Returns the number of simplex iterations. The problem must be discrete,
1738 // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1739 virtual int64_t iterations() const = 0;
1740 // Returns the number of branch-and-bound nodes. The problem must be discrete,
1741 // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1742 virtual int64_t nodes() const = 0;
1743 // Returns the best objective bound. The problem must be discrete, otherwise
1744 // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1745 double best_objective_bound() const;
1746 // Returns the objective value of the best solution found so far.
1747 double objective_value() const;
1748
1749 // Returns the basis status of a row.
1750 virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1751 // Returns the basis status of a constraint.
1752 virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1753
1754 // Checks whether the solution is synchronized with the model, i.e. whether
1755 // the model has changed since the solution was computed last.
1756 // If it isn't, it crashes in NDEBUG, and returns false otherwise.
1757 bool CheckSolutionIsSynchronized() const;
1758 // Checks whether a feasible solution exists. The behavior is similar to
1759 // CheckSolutionIsSynchronized() above.
1760 virtual bool CheckSolutionExists() const;
1761 // Handy shortcut to do both checks above (it is often used).
1765
1766 // ----- Misc -----
1767 // Queries problem type. For simplicity, the distinction between
1768 // continuous and discrete is based on the declaration of the user
1769 // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1770 // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1771 // the model.
1772 // Returns true if the problem is continuous.
1773 virtual bool IsContinuous() const = 0;
1774 // Returns true if the problem is continuous and linear.
1775 virtual bool IsLP() const = 0;
1776 // Returns true if the problem is discrete and linear.
1777 virtual bool IsMIP() const = 0;
1778
1779 // Returns the index of the last variable extracted.
1780 int last_variable_index() const { return last_variable_index_; }
1781
1782 bool variable_is_extracted(int var_index) const {
1783 return solver_->variable_is_extracted_[var_index];
1785 void set_variable_as_extracted(int var_index, bool extracted) {
1786 solver_->variable_is_extracted_[var_index] = extracted;
1788 bool constraint_is_extracted(int ct_index) const {
1789 return solver_->constraint_is_extracted_[ct_index];
1791 void set_constraint_as_extracted(int ct_index, bool extracted) {
1792 solver_->constraint_is_extracted_[ct_index] = extracted;
1794
1795 // Returns the boolean indicating the verbosity of the solver output.
1796 bool quiet() const { return quiet_; }
1797 // Sets the boolean indicating the verbosity of the solver output.
1798 void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1799
1800 // Returns the result status of the last solve.
1804 }
1805
1806 // Returns a string describing the underlying solver and its version.
1807 virtual std::string SolverVersion() const = 0;
1808
1809 // Returns the underlying solver.
1810 virtual void* underlying_solver() = 0;
1811
1812 // Computes exact condition number. Only available for continuous
1813 // problems and only implemented in GLPK.
1814 virtual double ComputeExactConditionNumber() const;
1815
1816 // See MPSolver::SetStartingLpBasis().
1817 virtual void SetStartingLpBasis(
1818 const std::vector<MPSolver::BasisStatus>& /*variable_statuses*/,
1819 const std::vector<MPSolver::BasisStatus>& /*constraint_statuses*/) {
1820 LOG(FATAL) << "Not supported by this solver.";
1821 }
1822
1823 virtual double infinity() { return std::numeric_limits<double>::infinity(); }
1824
1825 virtual bool InterruptSolve() { return false; }
1826
1827 // See MPSolver::NextSolution() for contract.
1828 virtual bool NextSolution() { return false; }
1829
1830 // See MPSolver::SetCallback() for details.
1831 virtual void SetCallback(MPCallback* /*mp_callback*/) {
1832 LOG(FATAL) << "Callbacks not supported for this solver.";
1834
1835 virtual bool SupportsCallbacks() const { return false; }
1836
1837 friend class MPSolver;
1838
1839 // To access the maximize_ bool and the MPSolver.
1840 friend class MPConstraint;
1841 friend class MPObjective;
1843 protected:
1844 MPSolver* const solver_;
1845 // Indicates whether the model and the solution are synchronized.
1847 // Indicates whether the solve has reached optimality,
1848 // infeasibility, a limit, etc.
1850 // Optimization direction.
1852
1853 // Index in MPSolver::variables_ of last constraint extracted.
1855 // Index in MPSolver::constraints_ of last variable extracted.
1857
1858 // The value of the objective function.
1859 double objective_value_;
1860
1861 // The value of the best objective bound. Used only for MIP solvers.
1862 double best_objective_bound_;
1863
1864 // Boolean indicator for the verbosity of the solver output.
1865 bool quiet_;
1866
1867 // Index of dummy variable created for empty constraints or the
1868 // objective offset.
1869 static const int kDummyVariableIndex;
1870
1871 // Extracts model stored in MPSolver.
1872 void ExtractModel();
1873 // Extracts the variables that have not been extracted yet.
1874 virtual void ExtractNewVariables() = 0;
1875 // Extracts the constraints that have not been extracted yet.
1876 virtual void ExtractNewConstraints() = 0;
1877 // Extracts the objective.
1878 virtual void ExtractObjective() = 0;
1879 // Resets the extraction information.
1881 // Change synchronization status from SOLUTION_SYNCHRONIZED to
1882 // MODEL_SYNCHRONIZED. To be used for model changes.
1884
1885 // Sets parameters common to LP and MIP in the underlying solver.
1886 void SetCommonParameters(const MPSolverParameters& param);
1887 // Sets MIP specific parameters in the underlying solver.
1888 void SetMIPParameters(const MPSolverParameters& param);
1889 // Sets all parameters in the underlying solver.
1890 virtual void SetParameters(const MPSolverParameters& param) = 0;
1891 // Sets an unsupported double parameter.
1893 // Sets an unsupported integer parameter.
1894 virtual void SetUnsupportedIntegerParam(
1896 // Sets a supported double parameter to an unsupported value.
1898 double value);
1899 // Sets a supported integer parameter to an unsupported value.
1901 MPSolverParameters::IntegerParam param, int value);
1902 // Sets each parameter in the underlying solver.
1903 virtual void SetRelativeMipGap(double value) = 0;
1904 virtual void SetPrimalTolerance(double value) = 0;
1905 virtual void SetDualTolerance(double value) = 0;
1906 virtual void SetPresolveMode(int value) = 0;
1908 // Sets the number of threads to be used by the solver.
1909 virtual absl::Status SetNumThreads(int num_threads);
1910
1911 // Pass solver specific parameters in text format. The format is
1912 // solver-specific and is the same as the corresponding solver configuration
1913 // file format. Returns true if the operation was successful.
1914 //
1915 // Default implementation returns true if the input is empty. It returns false
1916 // and logs a WARNING if the input is not empty.
1918 const std::string& parameters);
1919
1920 // Sets the scaling mode.
1921 virtual void SetScalingMode(int value) = 0;
1922 virtual void SetLpAlgorithm(int value) = 0;
1925} // namespace operations_research
1926
1927#endif // OR_TOOLS_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
This type is neither copyable nor movable.
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
nested types -------------------------------------------------—
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
--— MPObjective --—
void SetOffset(double value)
Sets the constant term in the objective.
MPObjective(const MPObjective &)=delete
This type is neither copyable nor movable.
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.
void set_variable_as_extracted(int var_index, bool extracted)
virtual void AddVariable(MPVariable *var)=0
Add a variable.
MPSolver::ResultStatus result_status() const
Returns the result status of the last solve.
virtual void SetCallback(MPCallback *)
See MPSolver::SetCallback() for details.
virtual void SetPrimalTolerance(double value)=0
virtual void ExtractNewConstraints()=0
Extracts the constraints that have not been extracted yet.
virtual void ClearObjective()=0
Clears the objective from all its terms.
static constexpr int64_t kUnknownNumberOfIterations
virtual void ExtractObjective()=0
Extracts the objective.
friend class MPConstraint
To access the maximize_ bool and the MPSolver.
virtual void SetRelativeMipGap(double value)=0
Sets each parameter in the underlying solver.
virtual void SetObjectiveCoefficient(const MPVariable *variable, double coefficient)=0
Changes a coefficient in the linear objective.
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &, const std::vector< MPSolver::BasisStatus > &)
See MPSolver::SetStartingLpBasis().
void set_constraint_as_extracted(int ct_index, bool extracted)
virtual bool IsMIP() const =0
Returns true if the problem is discrete and linear.
virtual int64_t nodes() const =0
void ResetExtractionInformation()
Resets the extraction information.
int last_variable_index_
Index in MPSolver::constraints_ of last variable extracted.
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
Sets a supported integer parameter to an unsupported value.
int last_variable_index() const
Returns the index of the last variable extracted.
virtual void SetPresolveMode(int value)=0
int last_constraint_index_
Index in MPSolver::variables_ of last constraint extracted.
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
Returns the basis status of a constraint.
virtual void SetCoefficient(MPConstraint *constraint, const MPVariable *variable, double new_value, double old_value)=0
Changes a coefficient in a constraint.
virtual std::string SolverVersion() const =0
Returns a string describing the underlying solver and its version.
virtual void SetVariableInteger(int index, bool integer)=0
Modifies integrality of an extracted variable.
virtual absl::Status SetNumThreads(int num_threads)
Sets the number of threads to be used by the solver.
virtual int64_t iterations() const =0
virtual void BranchingPriorityChangedForVariable(int)
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
static const int kDummyVariableIndex
-------— MPSolverInterface -------—
virtual void SetObjectiveOffset(double value)=0
Changes the constant term in the linear objective.
virtual void SetParameters(const MPSolverParameters &param)=0
Sets all parameters in the underlying solver.
virtual bool IsContinuous() const =0
virtual void SetLpAlgorithm(int value)=0
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
Sets an unsupported integer parameter.
virtual bool NextSolution()
See MPSolver::NextSolution() for contract.
bool variable_is_extracted(int var_index) const
virtual bool IsLP() const =0
Returns true if the problem is continuous and linear.
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
Sets an unsupported double parameter.
bool quiet() const
Returns the boolean indicating the verbosity of the solver output.
virtual void * underlying_solver()=0
Returns the underlying solver.
virtual bool SupportsDirectlySolveProto(std::atomic< bool > *) const
bool constraint_is_extracted(int ct_index) const
static constexpr int64_t kUnknownNumberOfNodes
virtual void ExtractNewVariables()=0
Extracts the variables that have not been extracted yet.
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
double objective_value() const
Returns the objective value of the best solution found so far.
void ExtractModel()
Extracts model stored in MPSolver.
double objective_value_
The value of the objective function.
double best_objective_bound_
The value of the best objective bound. Used only for MIP solvers.
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
Sets a supported double parameter to an unsupported value.
virtual void SetScalingMode(int value)=0
Sets the scaling mode.
bool maximize_
Optimization direction.
virtual double ComputeExactConditionNumber() const
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
Returns the basis status of a row.
virtual void AddRowConstraint(MPConstraint *ct)=0
Adds a linear constraint.
virtual MPSolutionResponse DirectlySolveProto(LazyMutableCopy< MPModelRequest >, std::atomic< bool > *)
virtual void Write(const std::string &filename)
void SetMIPParameters(const MPSolverParameters &param)
Sets MIP specific parameters in the underlying solver.
virtual void SetDualTolerance(double value)=0
virtual bool AddIndicatorConstraint(MPConstraint *const)
virtual void SetOptimizationDirection(bool maximize)=0
Sets the optimization direction (min/max).
bool quiet_
Boolean indicator for the verbosity of the solver output.
void SetCommonParameters(const MPSolverParameters &param)
Sets parameters common to LP and MIP in the underlying solver.
virtual void ClearConstraint(MPConstraint *constraint)=0
Clears a constraint from all its terms.
bool CheckSolutionIsSynchronizedAndExists() const
Handy shortcut to do both checks above (it is often used).
void set_quiet(bool quiet_value)
Sets the boolean indicating the verbosity of the solver output.
virtual void SetConstraintBounds(int index, double lb, double ub)=0
Modify bounds of an extracted variable.
SynchronizationStatus sync_status_
Indicates whether the model and the solution are synchronized.
virtual void SetVariableBounds(int index, double lb, double ub)=0
Modifies bounds of an extracted variable.
static const PresolveValues kDefaultPresolve
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
MPSolverParameters & operator=(const MPSolverParameters &)=delete
static const double kDefaultPrimalTolerance
For the primal and dual tolerances, choose the same default as CLP and GLPK.
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.
static const double kUnknownDoubleParamValue
Placeholder value to indicate that a parameter is unknown.
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.
static const double kDefaultRelativeMipGap
-------— MPSolverParameters -------—
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)
static
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)
--— Methods using protocol buffers --—
bool IsMIP() const
--— Interface shortcuts --—
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)
@ SCIP_MIXED_INTEGER_PROGRAMMING
Recommended default value for MIP problems.
@ KNAPSACK_MIXED_INTEGER_PROGRAMMING
Dedicated knapsack solvers.
@ GUROBI_LINEAR_PROGRAMMING
Commercial software (need license).
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)
static
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)
-— Solver-specific parameters -—
MPVariable * variable(int index) const
bool OwnsVariable(const MPVariable *var) const
Debugging: verify that the given MPVariable* belongs to this solver.
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)
static
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()
static
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()
static
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
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response, std::atomic< bool > *interrupt=nullptr)
static
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
This type is neither copyable nor movable.
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)
double solution_value() const
--— MPVariable --—
MPSolver::BasisStatus basis_status() const
int index() const
Returns the index of the variable in the MPSolver::variables_.
time_limit
Definition solve.cc:22
OR_DLL ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output)
In SWIG mode, we don't want anything besides these top-level includes.
constexpr double kDefaultPrimalTolerance
bool SolverTypeSupportsInterruption(const MPModelRequest::SolverType solver)
bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status)
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
There is a homonymous version taking a MPSolver::OptimizationProblemType.
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.