Google OR-Tools v9.11
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-2024 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
134#ifndef OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
135#define OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
136
137#include <atomic>
138#include <cstdint>
139#include <functional>
140#include <limits>
141#include <map>
142#include <memory>
143#include <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"
161#include "ortools/base/logging.h"
163#include "ortools/linear_solver/linear_solver.pb.h"
167
168ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
169ABSL_DECLARE_FLAG(bool, log_verification_errors);
170ABSL_DECLARE_FLAG(bool, verify_solution);
171
172namespace operations_research {
173
174constexpr double kDefaultPrimalTolerance = 1e-07;
175
176class MPConstraint;
177class MPObjective;
180class MPVariable;
181
182// There is a homonymous version taking a MPSolver::OptimizationProblemType.
183bool SolverTypeIsMip(MPModelRequest::SolverType solver_type);
184
189class MPSolver {
190 public:
198 // Linear programming problems.
199 // ----------------------------
202 GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
203 // In-house linear programming solver based on the primal-dual hybrid
204 // gradient method. Sometimes faster than Glop for medium-size problems and
205 // scales to much larger problems than Glop.
209 // Integer programming problems.
210 // -----------------------------
211 // Recommended default value for MIP problems.
217 // Boolean optimization problem (requires only integer variables and works
218 // best with only Boolean variables).
220
221 // SAT based solver (requires only integer and Boolean variables).
222 // If you pass it mixed integer problems, it will scale coefficients to
223 // integer values, and solver continuous variables as integral variables.
224 //
225 // Recommended default value for pure integral problems problems.
227
228 // Dedicated knapsack solvers.
230
231 // Commercial software (need license).
240 };
244
245#ifndef SWIG
246 // This type is neither copyable nor movable.
247 MPSolver(const MPSolver&) = delete;
248 MPSolver& operator=(const MPSolver&) = delete;
249#endif
251 virtual ~MPSolver();
252
281 static MPSolver* CreateSolver(const std::string& solver_id);
282
288
294 static bool ParseSolverType(absl::string_view solver_id,
296
302 const std::string& solver_id);
303
304 bool IsMIP() const;
305
307 const std::string& Name() const {
308 return name_; // Set at construction.
310
312 virtual OptimizationProblemType ProblemType() const {
313 return problem_type_; // Set at construction.
315
321 void Clear();
322
324 int NumVariables() const { return variables_.size(); }
325
330 const std::vector<MPVariable*>& variables() const { return variables_; }
331
335 MPVariable* variable(int index) const { return variables_[index]; }
336
342 MPVariable* LookupVariableOrNull(const std::string& var_name) const;
343
351 MPVariable* MakeVar(double lb, double ub, bool integer,
352 const std::string& name);
353
355 MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
356
358 MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
359
361 MPVariable* MakeBoolVar(const std::string& name);
362
377 void MakeVarArray(int nb, double lb, double ub, bool integer,
378 const std::string& name_prefix,
379 std::vector<MPVariable*>* vars);
380
382 void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
383 std::vector<MPVariable*>* vars);
384
386 void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
387 std::vector<MPVariable*>* vars);
388
390 void MakeBoolVarArray(int nb, const std::string& name,
391 std::vector<MPVariable*>* vars);
392
394 int NumConstraints() const { return constraints_.size(); }
395
401 const std::vector<MPConstraint*>& constraints() const { return constraints_; }
402
404 MPConstraint* constraint(int index) const { return constraints_[index]; }
405
413 MPConstraint* LookupConstraintOrNull(
414 const std::string& constraint_name) const;
415
424 MPConstraint* MakeRowConstraint(double lb, double ub);
425
427 MPConstraint* MakeRowConstraint();
428
430 MPConstraint* MakeRowConstraint(double lb, double ub,
431 const std::string& name);
432
434 MPConstraint* MakeRowConstraint(const std::string& name);
435
440 MPConstraint* MakeRowConstraint(const LinearRange& range);
441
443 MPConstraint* MakeRowConstraint(const LinearRange& range,
444 const std::string& name);
445
452 const MPObjective& Objective() const { return *objective_; }
453
455 MPObjective* MutableObjective() { return objective_.get(); }
456
463 enum ResultStatus {
482
485
490 void Write(const std::string& file_name);
491
498 std::vector<double> ComputeConstraintActivities() const;
499
518 bool VerifySolution(double tolerance, bool log_errors) const;
519
528 void Reset();
529
539 bool InterruptSolve();
540
550 MPSolverResponseStatus LoadModelFromProto(const MPModelProto& input_model,
551 std::string* error_message,
552 bool clear_names = true);
560 MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(
561 const MPModelProto& input_model, std::string* error_message);
562
564 void FillSolutionResponseProto(MPSolutionResponse* response) const;
565
584 ABSL_DEPRECATED("Prefer SolveMPModel() from solve_mp_model.h.")
585 static void SolveWithProto(const MPModelRequest& model_request,
586 MPSolutionResponse* response,
587 std::atomic<bool>* interrupt = nullptr);
588
598 ABSL_DEPRECATED("Prefer SolveMPModel() from solve_mp_model.h.")
599 static void SolveLazyMutableRequest(LazyMutableCopy<MPModelRequest> request,
600 MPSolutionResponse* response,
601 std::atomic<bool>* interrupt = nullptr);
602
604 "Prefer SolverTypeSupportsInterruption() from solve_mp_model.h.")
606 const MPModelRequest::SolverType solver) {
607 // Interruption requires that MPSolver::InterruptSolve is supported for the
608 // underlying solver. Interrupting requests using SCIP is also not supported
609 // as of 2021/08/23, since InterruptSolve is not thread safe for SCIP.
610 return solver == MPModelRequest::GLOP_LINEAR_PROGRAMMING ||
611 solver == MPModelRequest::GUROBI_LINEAR_PROGRAMMING ||
612 solver == MPModelRequest::GUROBI_MIXED_INTEGER_PROGRAMMING ||
613 solver == MPModelRequest::SAT_INTEGER_PROGRAMMING ||
614 solver == MPModelRequest::PDLP_LINEAR_PROGRAMMING;
615 }
616
618 void ExportModelToProto(MPModelProto* output_model) const;
619
653 absl::Status LoadSolutionFromProto(
654 const MPSolutionResponse& response,
655 double tolerance = std::numeric_limits<double>::infinity());
656
661 absl::Status ClampSolutionWithinBounds();
662
669 bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
670 bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
671 std::string* model_str) const;
672
683 absl::Status SetNumThreads(int num_threads);
684
686 int GetNumThreads() const { return num_threads_; }
687
694 bool SetSolverSpecificParametersAsString(const std::string& parameters);
695 std::string GetSolverSpecificParametersAsString() const {
696 return solver_specific_parameter_string_;
698
714 void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
715
716 // Gives some brief (a few lines, at most) human-readable information about
717 // the given request, suitable for debug logging.
718 ABSL_DEPRECATED("Prefer MPModelRequestLoggingInfo() from solve_mp_model.h.")
719 static std::string GetMPModelRequestLoggingInfo(
720 const MPModelRequest& request);
721
726 enum BasisStatus {
727 FREE = 0,
746 const std::vector<MPSolver::BasisStatus>& variable_statuses,
747 const std::vector<MPSolver::BasisStatus>& constraint_statuses);
748
754 static double infinity() { return std::numeric_limits<double>::infinity(); }
755 double solver_infinity();
765 bool OutputIsEnabled() const;
766
768 void EnableOutput();
769
771 void SuppressOutput();
772
773 absl::Duration TimeLimit() const { return time_limit_; }
774 void SetTimeLimit(absl::Duration time_limit) {
775 DCHECK_GE(time_limit, absl::ZeroDuration());
776 time_limit_ = time_limit;
777 }
778
779 absl::Duration DurationSinceConstruction() const {
780 return absl::Now() - construction_time_;
782
784 int64_t iterations() const;
785
791 int64_t nodes() const;
792
794 std::string SolverVersion() const;
795
809 void* underlying_solver();
810
834 double ComputeExactConditionNumber() const;
835
850 ABSL_MUST_USE_RESULT bool NextSolution();
851
852 // Does not take ownership of "mp_callback".
853 //
854 // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
855 // SCIP does not support suggesting a heuristic solution in the callback.
856 void SetCallback(MPCallback* mp_callback);
857 bool SupportsCallbacks() const;
858
859 // Global counters of variables and constraints ever created across all
860 // MPSolver instances. Those are only updated after the destruction
861 // (or Clear()) of each MPSolver instance.
862 static int64_t global_num_variables();
863 static int64_t global_num_constraints();
864
865 // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
866 // NOTE: These deprecated functions used the convention time_limit = 0 to mean
867 // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
868 int64_t time_limit() const {
869 return time_limit_ == absl::InfiniteDuration()
870 ? 0
871 : absl::ToInt64Milliseconds(time_limit_);
872 }
873 void set_time_limit(int64_t time_limit_milliseconds) {
874 SetTimeLimit(time_limit_milliseconds == 0
875 ? absl::InfiniteDuration()
876 : absl::Milliseconds(time_limit_milliseconds));
877 }
878 double time_limit_in_secs() const {
879 return static_cast<double>(time_limit()) / 1000.0;
881
882 // DEPRECATED: Use DurationSinceConstruction() instead.
883 int64_t wall_time() const {
884 return absl::ToInt64Milliseconds(DurationSinceConstruction());
886
887 friend class GLPKInterface;
888 friend class CLPInterface;
889 friend class CBCInterface;
890 friend class SCIPInterface;
891 friend class GurobiInterface;
892 friend class CplexInterface;
893 friend class XpressInterface;
894 friend class SLMInterface;
895 friend class MPSolverInterface;
896 friend class GLOPInterface;
897 friend class BopInterface;
898 friend class SatInterface;
899 friend class PdlpInterface;
900 friend class HighsInterface;
901 friend class KnapsackInterface;
903 // Debugging: verify that the given MPVariable* belongs to this solver.
904 bool OwnsVariable(const MPVariable* var) const;
905
906 private:
907 // Computes the size of the constraint with the largest number of
908 // coefficients with index in [min_constraint_index,
909 // max_constraint_index)
910 int ComputeMaxConstraintSize(int min_constraint_index,
911 int max_constraint_index) const;
912
913 // Returns true if the model has constraints with lower bound > upper bound.
914 bool HasInfeasibleConstraints() const;
915
916 // Returns true if the model has at least 1 integer variable.
917 bool HasIntegerVariables() const;
918
919 // Generates the map from variable names to their indices.
920 void GenerateVariableNameIndex() const;
921
922 // Generates the map from constraint names to their indices.
923 void GenerateConstraintNameIndex() const;
924
925 // The name of the linear programming problem.
926 const std::string name_;
927
928 // The type of the linear programming problem.
929 const OptimizationProblemType problem_type_;
930
931 // The solver interface.
932 std::unique_ptr<MPSolverInterface> interface_;
933
934 // The vector of variables in the problem.
935 std::vector<MPVariable*> variables_;
936 // A map from a variable's name to its index in variables_.
937 mutable std::optional<absl::flat_hash_map<std::string, int> >
938 variable_name_to_index_;
939 // Whether variables have been extracted to the underlying interface.
940 std::vector<bool> variable_is_extracted_;
941
942 // The vector of constraints in the problem.
943 std::vector<MPConstraint*> constraints_;
944 // A map from a constraint's name to its index in constraints_.
945 mutable std::optional<absl::flat_hash_map<std::string, int> >
946 constraint_name_to_index_;
947 // Whether constraints have been extracted to the underlying interface.
948 std::vector<bool> constraint_is_extracted_;
949
950 // The linear objective function.
951 std::unique_ptr<MPObjective> objective_;
952
953 // Initial values for all or some of the problem variables that can be
954 // exploited as a starting hint by a solver.
955 //
956 // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
957 //
958 // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
959 // hint is provided and a std::vector<double> for the hint value.
960 std::vector<std::pair<const MPVariable*, double> > solution_hint_;
961
962 absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
963
964 const absl::Time construction_time_;
965
966 // Permanent storage for the number of threads.
967 int num_threads_ = 1;
968
969 // Permanent storage for SetSolverSpecificParametersAsString().
970 std::string solver_specific_parameter_string_;
971
972 static absl::Mutex global_count_mutex_;
973#ifndef SWIG
974 static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
975 static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
976#endif
977
978 enum ModelProtoNamesPolicy {
979 DEFAULT_CLEAR_NAMES = 0,
980 INVALID_MODEL_ON_DUPLICATE_NONEMPTY_NAMES = 1,
981 DIE_ON_DUPLICATE_NONEMPTY_NAMES = 2,
982 };
983 MPSolverResponseStatus LoadModelFromProtoInternal(
984 const MPModelProto& input_model, ModelProtoNamesPolicy name_policy,
985 bool check_model_validity, std::string* error_message);
986};
987
988inline bool SolverTypeIsMip(MPSolver::OptimizationProblemType solver_type) {
989 return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
991
992absl::string_view ToString(
993 MPSolver::OptimizationProblemType optimization_problem_type);
994
995inline std::ostream& operator<<(
996 std::ostream& os,
997 MPSolver::OptimizationProblemType optimization_problem_type) {
998 return os << ToString(optimization_problem_type);
999}
1000
1001inline std::ostream& operator<<(std::ostream& os,
1003 return os << ProtoEnumToString<MPSolverResponseStatus>(
1004 static_cast<MPSolverResponseStatus>(status));
1005}
1006
1007bool AbslParseFlag(absl::string_view text,
1009 std::string* error);
1010
1011inline std::string AbslUnparseFlag(
1013 return std::string(ToString(solver_type));
1014}
1015
1017class MPObjective {
1018 public:
1019#ifndef SWIG
1020 // This type is neither copyable nor movable.
1021 MPObjective(const MPObjective&) = delete;
1022 MPObjective& operator=(const MPObjective&) = delete;
1023#endif
1029 void Clear();
1030
1037 void SetCoefficient(const MPVariable* var, double coeff);
1038
1044 double GetCoefficient(const MPVariable* var) const;
1045
1051 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1052 return coefficients_;
1054
1056 void SetOffset(double value);
1057
1059 double offset() const { return offset_; }
1060
1065 void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1066
1068 void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1069 OptimizeLinearExpr(linear_expr, true);
1072 void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1073 OptimizeLinearExpr(linear_expr, false);
1075
1077 void AddLinearExpr(const LinearExpr& linear_expr);
1078
1080 void SetOptimizationDirection(bool maximize);
1081
1083 void SetMinimization() { SetOptimizationDirection(false); }
1084
1087
1089 bool maximization() const;
1090
1092 bool minimization() const;
1093
1105 double Value() const;
1106
1113 double BestBound() const;
1114
1115 private:
1116 friend class MPSolver;
1117 friend class MPSolverInterface;
1118 friend class CBCInterface;
1119 friend class CLPInterface;
1120 friend class GLPKInterface;
1121 friend class SCIPInterface;
1122 friend class SLMInterface;
1123 friend class GurobiInterface;
1124 friend class CplexInterface;
1125 friend class XpressInterface;
1126 friend class GLOPInterface;
1127 friend class BopInterface;
1128 friend class SatInterface;
1129 friend class PdlpInterface;
1130 friend class HighsInterface;
1131 friend class KnapsackInterface;
1133 // Constructor. An objective points to a single MPSolverInterface
1134 // that is specified in the constructor. An objective cannot belong
1135 // to several models.
1136 // At construction, an MPObjective has no terms (which is equivalent
1137 // on having a coefficient of 0 for all variables), and an offset of 0.
1138 explicit MPObjective(MPSolverInterface* const interface_in)
1139 : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1140
1141 MPSolverInterface* const interface_;
1142
1143 // Mapping var -> coefficient.
1144 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1145 // Constant term.
1146 double offset_;
1147};
1148
1150class MPVariable {
1151 public:
1152#ifndef SWIG
1153 // This type is neither copyable nor movable.
1154 MPVariable(const MPVariable&) = delete;
1155 MPVariable& operator=(const MPVariable&) = delete;
1156#endif
1159 const std::string& name() const { return name_; }
1160
1162 void SetInteger(bool integer);
1163
1165 bool integer() const { return integer_; }
1166
1174 double solution_value() const;
1175
1177 int index() const { return index_; }
1178
1180 double lb() const { return lb_; }
1181
1183 double ub() const { return ub_; }
1184
1186 void SetLB(double lb) { SetBounds(lb, ub_); }
1187
1189 void SetUB(double ub) { SetBounds(lb_, ub); }
1190
1192 void SetBounds(double lb, double ub);
1193
1200 double unrounded_solution_value() const;
1201
1206 double reduced_cost() const;
1207
1215
1226 int branching_priority() const { return branching_priority_; }
1227 void SetBranchingPriority(int priority);
1229 protected:
1230 friend class MPSolver;
1231 friend class MPSolverInterface;
1232 friend class CBCInterface;
1233 friend class CLPInterface;
1234 friend class GLPKInterface;
1235 friend class SCIPInterface;
1236 friend class SLMInterface;
1237 friend class GurobiInterface;
1238 friend class CplexInterface;
1239 friend class XpressInterface;
1240 friend class GLOPInterface;
1242 friend class BopInterface;
1243 friend class SatInterface;
1244 friend class PdlpInterface;
1245 friend class HighsInterface;
1246 friend class KnapsackInterface;
1248 // Constructor. A variable points to a single MPSolverInterface that
1249 // is specified in the constructor. A variable cannot belong to
1250 // several models.
1251 MPVariable(int index, double lb, double ub, bool integer,
1252 const std::string& name, MPSolverInterface* const interface_in)
1253 : index_(index),
1254 lb_(lb),
1255 ub_(ub),
1256 integer_(integer),
1257 name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1258 solution_value_(0.0),
1259 reduced_cost_(0.0),
1260 interface_(interface_in) {}
1261
1262 void set_solution_value(double value) { solution_value_ = value; }
1263 void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1265 private:
1266 const int index_;
1267 double lb_;
1268 double ub_;
1269 bool integer_;
1270 const std::string name_;
1271 double solution_value_;
1272 double reduced_cost_;
1273 int branching_priority_ = 0;
1274 MPSolverInterface* const interface_;
1275};
1276
1282class MPConstraint {
1283 public:
1284#ifndef SWIG
1285 // This type is neither copyable nor movable.
1286 MPConstraint(const MPConstraint&) = delete;
1287 MPConstraint& operator=(const MPConstraint&) = delete;
1288#endif
1291 const std::string& name() const { return name_; }
1292
1294 void Clear();
1295
1302 void SetCoefficient(const MPVariable* var, double coeff);
1303
1308 double GetCoefficient(const MPVariable* var) const;
1309
1315 const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1316 return coefficients_;
1318
1320 double lb() const { return lb_; }
1321
1323 double ub() const { return ub_; }
1324
1326 void SetLB(double lb) { SetBounds(lb, ub_); }
1327
1329 void SetUB(double ub) { SetBounds(lb_, ub); }
1330
1332 void SetBounds(double lb, double ub);
1333
1335 bool is_lazy() const { return is_lazy_; }
1336
1350 void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1351
1352 const MPVariable* indicator_variable() const { return indicator_variable_; }
1353 bool indicator_value() const { return indicator_value_; }
1356 int index() const { return index_; }
1357
1362 double dual_value() const;
1363
1377
1378 protected:
1379 friend class MPSolver;
1380 friend class MPSolverInterface;
1381 friend class CBCInterface;
1382 friend class CLPInterface;
1383 friend class GLPKInterface;
1384 friend class SCIPInterface;
1385 friend class SLMInterface;
1386 friend class GurobiInterface;
1387 friend class CplexInterface;
1388 friend class XpressInterface;
1389 friend class GLOPInterface;
1390 friend class BopInterface;
1391 friend class SatInterface;
1392 friend class PdlpInterface;
1393 friend class HighsInterface;
1394 friend class KnapsackInterface;
1396 // Constructor. A constraint points to a single MPSolverInterface
1397 // that is specified in the constructor. A constraint cannot belong
1398 // to several models.
1399 MPConstraint(int index, double lb, double ub, const std::string& name,
1400 MPSolverInterface* const interface_in)
1401 : coefficients_(1),
1402 index_(index),
1403 lb_(lb),
1404 ub_(ub),
1405 name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1406 is_lazy_(false),
1407 indicator_variable_(nullptr),
1408 dual_value_(0.0),
1409 interface_(interface_in) {}
1410
1411 void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1412
1413 private:
1414 // Returns true if the constraint contains variables that have not
1415 // been extracted yet.
1416 bool ContainsNewVariables();
1417
1418 // Mapping var -> coefficient.
1419 absl::flat_hash_map<const MPVariable*, double> coefficients_;
1420
1421 const int index_; // See index().
1422
1423 // The lower bound for the linear constraint.
1424 double lb_;
1425
1426 // The upper bound for the linear constraint.
1427 double ub_;
1428
1429 // Name.
1430 const std::string name_;
1431
1432 // True if the constraint is "lazy", i.e. the constraint is added to the
1433 // underlying Linear Programming solver only if it is violated.
1434 // By default this parameter is 'false'.
1435 bool is_lazy_;
1436
1437 // If given, this constraint is only active if `indicator_variable_`'s value
1438 // is equal to `indicator_value_`.
1439 const MPVariable* indicator_variable_;
1440 bool indicator_value_;
1441
1442 double dual_value_;
1443 MPSolverInterface* const interface_;
1444};
1445
1472class MPSolverParameters {
1473 public:
1475 enum DoubleParam {
1478
1485 PRIMAL_TOLERANCE = 1,
1488 };
1489
1491 enum IntegerParam {
1493 PRESOLVE = 1000,
1499 SCALING = 1003
1500 };
1501
1503 enum PresolveValues {
1508 };
1509
1511 enum LpAlgorithmValues {
1513 DUAL = 10,
1518 };
1519
1524
1530 };
1531
1533 enum ScalingValues {
1538 };
1539
1540 // Placeholder value to indicate that a parameter is set to
1541 // the default value defined in the wrapper.
1542 static const double kDefaultDoubleParamValue;
1543 static const int kDefaultIntegerParamValue;
1545 // Placeholder value to indicate that a parameter is unknown.
1546 static const double kUnknownDoubleParamValue;
1547 static const int kUnknownIntegerParamValue;
1549 // Default values for parameters. Only parameters that define the
1550 // properties of the solution returned need to have a default value
1551 // (that is the same for all solvers). You can also define a default
1552 // value for performance parameters when you are confident it is a
1553 // good choice (example: always turn presolve on).
1554 static const double kDefaultRelativeMipGap;
1555 static const double kDefaultPrimalTolerance;
1556 static const double kDefaultDualTolerance;
1562
1563#ifndef SWIG
1564 // This type is neither copyable nor movable.
1565 MPSolverParameters(const MPSolverParameters&) = delete;
1567#endif
1571
1574
1581
1588
1590 void Reset();
1591
1594
1597
1598 private:
1599 // Parameter value for each parameter.
1600 // @see DoubleParam
1601 // @see IntegerParam
1602 double relative_mip_gap_value_;
1603 double primal_tolerance_value_;
1604 double dual_tolerance_value_;
1605 int presolve_value_;
1606 int scaling_value_;
1607 int lp_algorithm_value_;
1608 int incrementality_value_;
1609
1610 // Boolean value indicating whether each parameter is set to the
1611 // solver's default value. Only parameters for which the wrapper
1612 // does not define a default value need such an indicator.
1613 bool lp_algorithm_is_default_;
1614};
1615
1616// Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1617// error when happening on the linear solver stubby server, see
1618// ./linear_solver_service.proto.
1619// Note that RPC errors forbid to carry a response to the client, who can only
1620// see the RPC error itself (error code + error message).
1621bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status);
1622
1623// This class wraps the actual mathematical programming solvers. Each
1624// solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1625// derives from this abstract class. This class is never directly
1626// accessed by the user.
1627// @see glop_interface.cc
1628// @see cbc_interface.cc
1629// @see clp_interface.cc
1630// @see glpk_interface.cc
1631// @see scip_interface.cc
1632class MPSolverInterface {
1633 public:
1635 // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1636 // sync for the model nor for the solution.
1638 // The underlying solver and MPSolver are in sync for the model
1639 // but not for the solution: the model has changed since the
1640 // solution was computed last.
1642 // The underlying solver and MPSolver are in sync for the model and
1643 // the solution.
1645 };
1646
1647 // When the underlying solver does not provide the number of simplex
1648 // iterations.
1649 static constexpr int64_t kUnknownNumberOfIterations = -1;
1650 // When the underlying solver does not provide the number of
1651 // branch-and-bound nodes.
1652 static constexpr int64_t kUnknownNumberOfNodes = -1;
1653
1654 // Constructor. The user will access the MPSolverInterface through the
1655 // MPSolver passed as argument.
1656 explicit MPSolverInterface(MPSolver* solver);
1657 virtual ~MPSolverInterface();
1658
1659 // ----- Solve -----
1660 // Solves problem with specified parameter values. Returns true if the
1661 // solution is optimal.
1662 virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1663
1664 // DirectlySolveProto() shall only be used if SupportsDirectlySolveProto() is
1665 // true.
1666 //
1667 // DirectlySolveProto() solves a MPModelRequest, bypassing the MPSolver data
1668 // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1669 // an 'interrupt' boolean.
1670 virtual bool SupportsDirectlySolveProto(
1671 std::atomic<bool>* /*interrupt*/) const {
1672 return false;
1673 }
1674 virtual MPSolutionResponse DirectlySolveProto(
1676 // `interrupt` is non-const because the internal
1677 // solver may set it to true itself, in some cases.
1678 std::atomic<bool>* /*interrupt*/) {
1679 LOG(DFATAL) << "Default implementation should never be called.";
1680 return MPSolutionResponse();
1681 }
1682
1683 // Writes the model using the solver internal write function. Currently only
1684 // available for GurobiInterface and XpressInterface.
1685 virtual void Write(const std::string& filename);
1686
1687 // ----- Model modifications and extraction -----
1688 // Resets extracted model.
1689 virtual void Reset() = 0;
1690
1691 // Sets the optimization direction (min/max).
1692 virtual void SetOptimizationDirection(bool maximize) = 0;
1693
1694 // Modifies bounds of an extracted variable.
1695 virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1696
1697 // Modifies integrality of an extracted variable.
1698 virtual void SetVariableInteger(int index, bool integer) = 0;
1699
1700 // Modify bounds of an extracted variable.
1701 virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1702
1703 // Adds a linear constraint.
1704 virtual void AddRowConstraint(MPConstraint* ct) = 0;
1705
1706 // Adds an indicator constraint. Returns true if the feature is supported by
1707 // the underlying solver.
1708 virtual bool AddIndicatorConstraint(MPConstraint* const /*ct*/) {
1709 LOG(ERROR) << "Solver doesn't support indicator constraints.";
1710 return false;
1711 }
1712
1713 // Add a variable.
1714 virtual void AddVariable(MPVariable* var) = 0;
1715
1716 // Changes a coefficient in a constraint.
1717 virtual void SetCoefficient(MPConstraint* constraint,
1718 const MPVariable* variable, double new_value,
1719 double old_value) = 0;
1720
1721 // Clears a constraint from all its terms.
1722 virtual void ClearConstraint(MPConstraint* constraint) = 0;
1723
1724 // Changes a coefficient in the linear objective.
1725 virtual void SetObjectiveCoefficient(const MPVariable* variable,
1726 double coefficient) = 0;
1728 // Changes the constant term in the linear objective.
1729 virtual void SetObjectiveOffset(double value) = 0;
1730
1731 // Clears the objective from all its terms.
1732 virtual void ClearObjective() = 0;
1733
1734 virtual void BranchingPriorityChangedForVariable(int /*var_index*/) {}
1735 // ------ Query statistics on the solution and the solve ------
1736 // Returns the number of simplex iterations. The problem must be discrete,
1737 // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1738 virtual int64_t iterations() const = 0;
1739 // Returns the number of branch-and-bound nodes. The problem must be discrete,
1740 // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1741 virtual int64_t nodes() const = 0;
1742 // Returns the best objective bound. The problem must be discrete, otherwise
1743 // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1744 double best_objective_bound() const;
1745 // Returns the objective value of the best solution found so far.
1746 double objective_value() const;
1747
1748 // Returns the basis status of a row.
1749 virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1750 // Returns the basis status of a constraint.
1751 virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1752
1753 // Checks whether the solution is synchronized with the model, i.e. whether
1754 // the model has changed since the solution was computed last.
1755 // If it isn't, it crashes in NDEBUG, and returns false otherwise.
1756 bool CheckSolutionIsSynchronized() const;
1757 // Checks whether a feasible solution exists. The behavior is similar to
1758 // CheckSolutionIsSynchronized() above.
1759 virtual bool CheckSolutionExists() const;
1760 // Handy shortcut to do both checks above (it is often used).
1764
1765 // ----- Misc -----
1766 // Queries problem type. For simplicity, the distinction between
1767 // continuous and discrete is based on the declaration of the user
1768 // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1769 // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1770 // the model.
1771 // Returns true if the problem is continuous.
1772 virtual bool IsContinuous() const = 0;
1773 // Returns true if the problem is continuous and linear.
1774 virtual bool IsLP() const = 0;
1775 // Returns true if the problem is discrete and linear.
1776 virtual bool IsMIP() const = 0;
1777
1778 // Returns the index of the last variable extracted.
1779 int last_variable_index() const { return last_variable_index_; }
1780
1782 return solver_->variable_is_extracted_[var_index];
1784 void set_variable_as_extracted(int var_index, bool extracted) {
1785 solver_->variable_is_extracted_[var_index] = extracted;
1787 bool constraint_is_extracted(int ct_index) const {
1788 return solver_->constraint_is_extracted_[ct_index];
1790 void set_constraint_as_extracted(int ct_index, bool extracted) {
1791 solver_->constraint_is_extracted_[ct_index] = extracted;
1793
1794 // Returns the boolean indicating the verbosity of the solver output.
1795 bool quiet() const { return quiet_; }
1796 // Sets the boolean indicating the verbosity of the solver output.
1797 void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1798
1799 // Returns the result status of the last solve.
1803 }
1804
1805 // Returns a string describing the underlying solver and its version.
1806 virtual std::string SolverVersion() const = 0;
1807
1808 // Returns the underlying solver.
1809 virtual void* underlying_solver() = 0;
1810
1811 // Computes exact condition number. Only available for continuous
1812 // problems and only implemented in GLPK.
1813 virtual double ComputeExactConditionNumber() const;
1814
1815 // See MPSolver::SetStartingLpBasis().
1816 virtual void SetStartingLpBasis(
1817 const std::vector<MPSolver::BasisStatus>& /*variable_statuses*/,
1818 const std::vector<MPSolver::BasisStatus>& /*constraint_statuses*/) {
1819 LOG(FATAL) << "Not supported by this solver.";
1820 }
1821
1822 virtual double infinity() { return std::numeric_limits<double>::infinity(); }
1823
1824 virtual bool InterruptSolve() { return false; }
1825
1826 // See MPSolver::NextSolution() for contract.
1827 virtual bool NextSolution() { return false; }
1828
1829 // See MPSolver::SetCallback() for details.
1830 virtual void SetCallback(MPCallback* /*mp_callback*/) {
1831 LOG(FATAL) << "Callbacks not supported for this solver.";
1833
1834 virtual bool SupportsCallbacks() const { return false; }
1835
1836 friend class MPSolver;
1837
1838 // To access the maximize_ bool and the MPSolver.
1839 friend class MPConstraint;
1840 friend class MPObjective;
1842 protected:
1843 MPSolver* const solver_;
1844 // Indicates whether the model and the solution are synchronized.
1846 // Indicates whether the solve has reached optimality,
1847 // infeasibility, a limit, etc.
1849 // Optimization direction.
1851
1852 // Index in MPSolver::variables_ of last constraint extracted.
1854 // Index in MPSolver::constraints_ of last variable extracted.
1856
1857 // The value of the objective function.
1858 double objective_value_;
1859
1860 // The value of the best objective bound. Used only for MIP solvers.
1861 double best_objective_bound_;
1862
1863 // Boolean indicator for the verbosity of the solver output.
1864 bool quiet_;
1865
1866 // Index of dummy variable created for empty constraints or the
1867 // objective offset.
1868 static const int kDummyVariableIndex;
1869
1870 // Extracts model stored in MPSolver.
1871 void ExtractModel();
1872 // Extracts the variables that have not been extracted yet.
1873 virtual void ExtractNewVariables() = 0;
1874 // Extracts the constraints that have not been extracted yet.
1875 virtual void ExtractNewConstraints() = 0;
1876 // Extracts the objective.
1877 virtual void ExtractObjective() = 0;
1878 // Resets the extraction information.
1880 // Change synchronization status from SOLUTION_SYNCHRONIZED to
1881 // MODEL_SYNCHRONIZED. To be used for model changes.
1883
1884 // Sets parameters common to LP and MIP in the underlying solver.
1885 void SetCommonParameters(const MPSolverParameters& param);
1886 // Sets MIP specific parameters in the underlying solver.
1887 void SetMIPParameters(const MPSolverParameters& param);
1888 // Sets all parameters in the underlying solver.
1889 virtual void SetParameters(const MPSolverParameters& param) = 0;
1890 // Sets an unsupported double parameter.
1892 // Sets an unsupported integer parameter.
1893 virtual void SetUnsupportedIntegerParam(
1895 // Sets a supported double parameter to an unsupported value.
1897 double value);
1898 // Sets a supported integer parameter to an unsupported value.
1901 // Sets each parameter in the underlying solver.
1902 virtual void SetRelativeMipGap(double value) = 0;
1903 virtual void SetPrimalTolerance(double value) = 0;
1904 virtual void SetDualTolerance(double value) = 0;
1905 virtual void SetPresolveMode(int value) = 0;
1907 // Sets the number of threads to be used by the solver.
1908 virtual absl::Status SetNumThreads(int num_threads);
1909
1910 // Pass solver specific parameters in text format. The format is
1911 // solver-specific and is the same as the corresponding solver configuration
1912 // file format. Returns true if the operation was successful.
1913 //
1914 // Default implementation returns true if the input is empty. It returns false
1915 // and logs a WARNING if the input is not empty.
1917 const std::string& parameters);
1918
1919 // Sets the scaling mode.
1920 virtual void SetScalingMode(int value) = 0;
1921 virtual void SetLpAlgorithm(int value) = 0;
1924} // namespace operations_research
1925
1926#endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
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.
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.
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_.
SatParameters parameters
const std::string name
A name for logging purposes.
const Constraint * ct
int64_t value
IntVar * var
absl::Status status
Definition g_gurobi.cc:44
int constraint_index
int ct_index
MPSolver::OptimizationProblemType problem_type
ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output)
int index
std::optional< ModelSolveParameters::SolutionHint > hint
In SWIG mode, we don't want anything besides these top-level includes.
constexpr double kDefaultPrimalTolerance
MPSolutionResponse SolveMPModel(LazyMutableCopy< MPModelRequest > request, const SolveInterrupter *interrupter)
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.
int64_t coefficient
int var_index
Definition search.cc:3268
const std::optional< Range > & range
Definition statistics.cc:37