OR-Tools  9.2
linear_solver.h
Go to the documentation of this file.
1 // Copyright 2010-2021 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
134 #ifndef OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
135 #define OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
136 
137 #include <atomic>
138 #include <cstdint>
139 #include <functional>
140 #include <limits>
141 #include <map>
142 #include <memory>
143 #include <string>
144 #include <utility>
145 #include <vector>
146 
147 #include "absl/base/port.h"
148 #include "absl/container/flat_hash_map.h"
149 #include "absl/flags/parse.h"
150 #include "absl/flags/usage.h"
151 #include "absl/status/status.h"
152 #include "absl/strings/match.h"
153 #include "absl/strings/str_format.h"
154 #include "absl/types/optional.h"
156 #include "ortools/base/logging.h"
157 #include "ortools/base/macros.h"
158 #include "ortools/base/timer.h"
163 
164 ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output);
165 
166 namespace operations_research {
167 
168 constexpr double kDefaultPrimalTolerance = 1e-07;
169 
170 class MPConstraint;
171 class MPObjective;
172 class MPSolverInterface;
173 class MPSolverParameters;
174 class MPVariable;
175 
176 // There is a homonymous version taking a MPSolver::OptimizationProblemType.
178 
183 class MPSolver {
184  public:
192  // Linear programming problems.
193  // ----------------------------
196  GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
197 
198  // Integer programming problems.
199  // -----------------------------
200  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
203 
204  // Commercial software (need license).
211 
212  // Boolean optimization problem (requires only integer variables and works
213  // best with only Boolean variables).
215 
216  // SAT based solver (requires only integer and Boolean variables).
217  // If you pass it mixed integer problems, it will scale coefficients to
218  // integer values, and solver continuous variables as integral variables.
220 
221  // Dedicated knapsack solvers.
223  };
224 
226  MPSolver(const std::string& name, OptimizationProblemType problem_type);
227  virtual ~MPSolver();
228 
257  static MPSolver* CreateSolver(const std::string& solver_id);
258 
264 
270  static bool ParseSolverType(absl::string_view solver_id,
272 
278  const std::string& solver_id);
279 
280  bool IsMIP() const;
281 
283  const std::string& Name() const {
284  return name_; // Set at construction.
285  }
286 
289  return problem_type_; // Set at construction.
290  }
291 
297  void Clear();
298 
300  int NumVariables() const { return variables_.size(); }
301 
306  const std::vector<MPVariable*>& variables() const { return variables_; }
307 
311  MPVariable* variable(int index) const { return variables_[index]; }
312 
318  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
319 
327  MPVariable* MakeVar(double lb, double ub, bool integer,
328  const std::string& name);
329 
331  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
332 
334  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
335 
337  MPVariable* MakeBoolVar(const std::string& name);
338 
353  void MakeVarArray(int nb, double lb, double ub, bool integer,
354  const std::string& name_prefix,
355  std::vector<MPVariable*>* vars);
356 
358  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
359  std::vector<MPVariable*>* vars);
360 
362  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
363  std::vector<MPVariable*>* vars);
364 
366  void MakeBoolVarArray(int nb, const std::string& name,
367  std::vector<MPVariable*>* vars);
368 
370  int NumConstraints() const { return constraints_.size(); }
371 
377  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
378 
380  MPConstraint* constraint(int index) const { return constraints_[index]; }
381 
390  const std::string& constraint_name) const;
391 
400  MPConstraint* MakeRowConstraint(double lb, double ub);
401 
404 
406  MPConstraint* MakeRowConstraint(double lb, double ub,
407  const std::string& name);
408 
410  MPConstraint* MakeRowConstraint(const std::string& name);
411 
417 
420  const std::string& name);
421 
428  const MPObjective& Objective() const { return *objective_; }
429 
431  MPObjective* MutableObjective() { return objective_.get(); }
432 
454  };
455 
458 
460  ResultStatus Solve(const MPSolverParameters& param);
461 
466  void Write(const std::string& file_name);
467 
474  std::vector<double> ComputeConstraintActivities() const;
475 
494  bool VerifySolution(double tolerance, bool log_errors) const;
495 
504  void Reset();
505 
515  bool InterruptSolve();
516 
525  std::string* error_message);
534  const MPModelProto& input_model, std::string* error_message);
535 
538 
554  static void SolveWithProto(const MPModelRequest& model_request,
556  // `interrupt` is non-const because the internal
557  // solver may set it to true itself, in some cases.
558  std::atomic<bool>* interrupt = nullptr);
559 
561  const MPModelRequest::SolverType solver) {
562  // Interruption requires that MPSolver::InterruptSolve is supported for the
563  // underlying solver. Interrupting requests using SCIP is also not supported
564  // as of 2021/08/23, since InterruptSolve is not go/thread-safe
565  // for SCIP (see e.g. cl/350545631 for details).
566  return solver == MPModelRequest::GLOP_LINEAR_PROGRAMMING ||
570  }
571 
573  void ExportModelToProto(MPModelProto* output_model) const;
574 
608  absl::Status LoadSolutionFromProto(
610  double tolerance = std::numeric_limits<double>::infinity());
611 
616  absl::Status ClampSolutionWithinBounds();
617 
624  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
625  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
626  std::string* model_str) const;
627 
638  absl::Status SetNumThreads(int num_threads);
639 
641  int GetNumThreads() const { return num_threads_; }
642 
649  bool SetSolverSpecificParametersAsString(const std::string& parameters);
651  return solver_specific_parameter_string_;
652  }
653 
667  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
668 
673  enum BasisStatus {
674  FREE = 0,
679  };
680 
692  void SetStartingLpBasis(
693  const std::vector<MPSolver::BasisStatus>& variable_statuses,
694  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
695 
701  static double infinity() { return std::numeric_limits<double>::infinity(); }
702 
711  bool OutputIsEnabled() const;
712 
714  void EnableOutput();
715 
717  void SuppressOutput();
718 
719  absl::Duration TimeLimit() const { return time_limit_; }
720  void SetTimeLimit(absl::Duration time_limit) {
721  DCHECK_GE(time_limit, absl::ZeroDuration());
722  time_limit_ = time_limit;
723  }
724 
725  absl::Duration DurationSinceConstruction() const {
726  return absl::Now() - construction_time_;
727  }
728 
730  int64_t iterations() const;
731 
737  int64_t nodes() const;
738 
740  std::string SolverVersion() const;
741 
755  void* underlying_solver();
756 
780  double ComputeExactConditionNumber() const;
781 
796  ABSL_MUST_USE_RESULT bool NextSolution();
797 
798  // Does not take ownership of "mp_callback".
799  //
800  // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
801  // SCIP does not support suggesting a heuristic solution in the callback.
802  //
803  // See go/mpsolver-callbacks for additional documentation.
804  void SetCallback(MPCallback* mp_callback);
805  bool SupportsCallbacks() const;
806 
807  // Global counters of variables and constraints ever created across all
808  // MPSolver instances. Those are only updated after the destruction
809  // (or Clear()) of each MPSolver instance.
810  static int64_t global_num_variables();
811  static int64_t global_num_constraints();
812 
813  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
814  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
815  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
816  int64_t time_limit() const {
817  return time_limit_ == absl::InfiniteDuration()
818  ? 0
819  : absl::ToInt64Milliseconds(time_limit_);
820  }
821  void set_time_limit(int64_t time_limit_milliseconds) {
822  SetTimeLimit(time_limit_milliseconds == 0
823  ? absl::InfiniteDuration()
824  : absl::Milliseconds(time_limit_milliseconds));
825  }
826  double time_limit_in_secs() const {
827  return static_cast<double>(time_limit()) / 1000.0;
828  }
829 
830  // DEPRECATED: Use DurationSinceConstruction() instead.
831  int64_t wall_time() const {
832  return absl::ToInt64Milliseconds(DurationSinceConstruction());
833  }
834 
835  friend class GLPKInterface;
836  friend class CLPInterface;
837  friend class CBCInterface;
838  friend class SCIPInterface;
839  friend class GurobiInterface;
840  friend class CplexInterface;
841  friend class XpressInterface;
842  friend class SLMInterface;
843  friend class MPSolverInterface;
844  friend class GLOPInterface;
845  friend class BopInterface;
846  friend class SatInterface;
847  friend class KnapsackInterface;
848 
849  // Debugging: verify that the given MPVariable* belongs to this solver.
850  bool OwnsVariable(const MPVariable* var) const;
851 
852  private:
853  // Computes the size of the constraint with the largest number of
854  // coefficients with index in [min_constraint_index,
855  // max_constraint_index)
856  int ComputeMaxConstraintSize(int min_constraint_index,
857  int max_constraint_index) const;
858 
859  // Returns true if the model has constraints with lower bound > upper bound.
860  bool HasInfeasibleConstraints() const;
861 
862  // Returns true if the model has at least 1 integer variable.
863  bool HasIntegerVariables() const;
864 
865  // Generates the map from variable names to their indices.
866  void GenerateVariableNameIndex() const;
867 
868  // Generates the map from constraint names to their indices.
869  void GenerateConstraintNameIndex() const;
870 
871  // The name of the linear programming problem.
872  const std::string name_;
873 
874  // The type of the linear programming problem.
875  const OptimizationProblemType problem_type_;
876 
877  // The solver interface.
878  std::unique_ptr<MPSolverInterface> interface_;
879 
880  // The vector of variables in the problem.
881  std::vector<MPVariable*> variables_;
882  // A map from a variable's name to its index in variables_.
883  mutable absl::optional<absl::flat_hash_map<std::string, int> >
884  variable_name_to_index_;
885  // Whether variables have been extracted to the underlying interface.
886  std::vector<bool> variable_is_extracted_;
887 
888  // The vector of constraints in the problem.
889  std::vector<MPConstraint*> constraints_;
890  // A map from a constraint's name to its index in constraints_.
891  mutable absl::optional<absl::flat_hash_map<std::string, int> >
892  constraint_name_to_index_;
893  // Whether constraints have been extracted to the underlying interface.
894  std::vector<bool> constraint_is_extracted_;
895 
896  // The linear objective function.
897  std::unique_ptr<MPObjective> objective_;
898 
899  // Initial values for all or some of the problem variables that can be
900  // exploited as a starting hint by a solver.
901  //
902  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
903  //
904  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
905  // hint is provided and a std::vector<double> for the hint value.
906  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
907 
908  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
909 
910  const absl::Time construction_time_;
911 
912  // Permanent storage for the number of threads.
913  int num_threads_ = 1;
914 
915  // Permanent storage for SetSolverSpecificParametersAsString().
916  std::string solver_specific_parameter_string_;
917 
918  static absl::Mutex global_count_mutex_;
919 #ifndef SWIG
920  static int64_t global_num_variables_ ABSL_GUARDED_BY(global_count_mutex_);
921  static int64_t global_num_constraints_ ABSL_GUARDED_BY(global_count_mutex_);
922 #endif
923 
924  MPSolverResponseStatus LoadModelFromProtoInternal(
925  const MPModelProto& input_model, bool clear_names,
926  bool check_model_validity, std::string* error_message);
927 
929 };
930 
932  return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
933 }
934 
935 const absl::string_view ToString(
936  MPSolver::OptimizationProblemType optimization_problem_type);
937 
938 inline std::ostream& operator<<(
939  std::ostream& os,
940  MPSolver::OptimizationProblemType optimization_problem_type) {
941  return os << ToString(optimization_problem_type);
942 }
943 
944 inline std::ostream& operator<<(std::ostream& os,
945  MPSolver::ResultStatus status) {
946  return os << ProtoEnumToString<MPSolverResponseStatus>(
947  static_cast<MPSolverResponseStatus>(status));
948 }
949 
950 bool AbslParseFlag(absl::string_view text,
952  std::string* error);
953 
954 inline std::string AbslUnparseFlag(
955  MPSolver::OptimizationProblemType solver_type) {
956  return std::string(ToString(solver_type));
957 }
958 
960 class MPObjective {
961  public:
966  void Clear();
967 
974  void SetCoefficient(const MPVariable* const var, double coeff);
975 
981  double GetCoefficient(const MPVariable* const var) const;
982 
988  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
989  return coefficients_;
990  }
991 
993  void SetOffset(double value);
994 
996  double offset() const { return offset_; }
997 
1002  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
1003 
1005  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
1006  OptimizeLinearExpr(linear_expr, true);
1007  }
1009  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
1010  OptimizeLinearExpr(linear_expr, false);
1011  }
1012 
1014  void AddLinearExpr(const LinearExpr& linear_expr);
1015 
1017  void SetOptimizationDirection(bool maximize);
1018 
1021 
1024 
1026  bool maximization() const;
1027 
1029  bool minimization() const;
1030 
1042  double Value() const;
1043 
1050  double BestBound() const;
1051 
1052  private:
1053  friend class MPSolver;
1054  friend class MPSolverInterface;
1055  friend class CBCInterface;
1056  friend class CLPInterface;
1057  friend class GLPKInterface;
1058  friend class SCIPInterface;
1059  friend class SLMInterface;
1060  friend class GurobiInterface;
1061  friend class CplexInterface;
1062  friend class XpressInterface;
1063  friend class GLOPInterface;
1064  friend class BopInterface;
1065  friend class SatInterface;
1066  friend class KnapsackInterface;
1067 
1068  // Constructor. An objective points to a single MPSolverInterface
1069  // that is specified in the constructor. An objective cannot belong
1070  // to several models.
1071  // At construction, an MPObjective has no terms (which is equivalent
1072  // on having a coefficient of 0 for all variables), and an offset of 0.
1073  explicit MPObjective(MPSolverInterface* const interface_in)
1074  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1075 
1076  MPSolverInterface* const interface_;
1077 
1078  // Mapping var -> coefficient.
1079  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1080  // Constant term.
1081  double offset_;
1082 
1084 };
1085 
1087 class MPVariable {
1088  public:
1090  const std::string& name() const { return name_; }
1091 
1093  void SetInteger(bool integer);
1094 
1096  bool integer() const { return integer_; }
1097 
1105  double solution_value() const;
1106 
1108  int index() const { return index_; }
1109 
1111  double lb() const { return lb_; }
1112 
1114  double ub() const { return ub_; }
1115 
1117  void SetLB(double lb) { SetBounds(lb, ub_); }
1118 
1120  void SetUB(double ub) { SetBounds(lb_, ub); }
1121 
1123  void SetBounds(double lb, double ub);
1124 
1131  double unrounded_solution_value() const;
1132 
1137  double reduced_cost() const;
1138 
1146 
1157  int branching_priority() const { return branching_priority_; }
1158  void SetBranchingPriority(int priority);
1159 
1160  protected:
1161  friend class MPSolver;
1162  friend class MPSolverInterface;
1163  friend class CBCInterface;
1164  friend class CLPInterface;
1165  friend class GLPKInterface;
1166  friend class SCIPInterface;
1167  friend class SLMInterface;
1168  friend class GurobiInterface;
1169  friend class CplexInterface;
1170  friend class XpressInterface;
1171  friend class GLOPInterface;
1173  friend class BopInterface;
1174  friend class SatInterface;
1175  friend class KnapsackInterface;
1176 
1177  // Constructor. A variable points to a single MPSolverInterface that
1178  // is specified in the constructor. A variable cannot belong to
1179  // several models.
1180  MPVariable(int index, double lb, double ub, bool integer,
1181  const std::string& name, MPSolverInterface* const interface_in)
1182  : index_(index),
1183  lb_(lb),
1184  ub_(ub),
1185  integer_(integer),
1186  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1187  solution_value_(0.0),
1188  reduced_cost_(0.0),
1189  interface_(interface_in) {}
1190 
1191  void set_solution_value(double value) { solution_value_ = value; }
1192  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1193 
1194  private:
1195  const int index_;
1196  double lb_;
1197  double ub_;
1198  bool integer_;
1199  const std::string name_;
1200  double solution_value_;
1201  double reduced_cost_;
1202  int branching_priority_ = 0;
1203  MPSolverInterface* const interface_;
1205 };
1206 
1213  public:
1215  const std::string& name() const { return name_; }
1216 
1218  void Clear();
1219 
1226  void SetCoefficient(const MPVariable* const var, double coeff);
1227 
1232  double GetCoefficient(const MPVariable* const var) const;
1233 
1239  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1240  return coefficients_;
1241  }
1242 
1244  double lb() const { return lb_; }
1245 
1247  double ub() const { return ub_; }
1248 
1250  void SetLB(double lb) { SetBounds(lb, ub_); }
1251 
1253  void SetUB(double ub) { SetBounds(lb_, ub); }
1254 
1256  void SetBounds(double lb, double ub);
1257 
1259  bool is_lazy() const { return is_lazy_; }
1260 
1274  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1275 
1276  const MPVariable* indicator_variable() const { return indicator_variable_; }
1277  bool indicator_value() const { return indicator_value_; }
1278 
1280  int index() const { return index_; }
1281 
1286  double dual_value() const;
1287 
1301 
1302  protected:
1303  friend class MPSolver;
1304  friend class MPSolverInterface;
1305  friend class CBCInterface;
1306  friend class CLPInterface;
1307  friend class GLPKInterface;
1308  friend class SCIPInterface;
1309  friend class SLMInterface;
1310  friend class GurobiInterface;
1311  friend class CplexInterface;
1312  friend class XpressInterface;
1313  friend class GLOPInterface;
1314  friend class BopInterface;
1315  friend class SatInterface;
1316  friend class KnapsackInterface;
1317 
1318  // Constructor. A constraint points to a single MPSolverInterface
1319  // that is specified in the constructor. A constraint cannot belong
1320  // to several models.
1321  MPConstraint(int index, double lb, double ub, const std::string& name,
1322  MPSolverInterface* const interface_in)
1323  : coefficients_(1),
1324  index_(index),
1325  lb_(lb),
1326  ub_(ub),
1327  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1328  is_lazy_(false),
1329  indicator_variable_(nullptr),
1330  dual_value_(0.0),
1331  interface_(interface_in) {}
1332 
1333  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1334 
1335  private:
1336  // Returns true if the constraint contains variables that have not
1337  // been extracted yet.
1338  bool ContainsNewVariables();
1339 
1340  // Mapping var -> coefficient.
1341  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1342 
1343  const int index_; // See index().
1344 
1345  // The lower bound for the linear constraint.
1346  double lb_;
1347 
1348  // The upper bound for the linear constraint.
1349  double ub_;
1350 
1351  // Name.
1352  const std::string name_;
1353 
1354  // True if the constraint is "lazy", i.e. the constraint is added to the
1355  // underlying Linear Programming solver only if it is violated.
1356  // By default this parameter is 'false'.
1357  bool is_lazy_;
1358 
1359  // If given, this constraint is only active if `indicator_variable_`'s value
1360  // is equal to `indicator_value_`.
1361  const MPVariable* indicator_variable_;
1362  bool indicator_value_;
1363 
1364  double dual_value_;
1365  MPSolverInterface* const interface_;
1367 };
1368 
1396  public:
1401 
1411  };
1412 
1416  PRESOLVE = 1000,
1422  SCALING = 1003
1423  };
1424 
1431  };
1432 
1436  DUAL = 10,
1438  PRIMAL = 11,
1440  BARRIER = 12
1441  };
1442 
1447 
1453  };
1454 
1461  };
1462 
1463  // Placeholder value to indicate that a parameter is set to
1464  // the default value defined in the wrapper.
1465  static const double kDefaultDoubleParamValue;
1466  static const int kDefaultIntegerParamValue;
1467 
1468  // Placeholder value to indicate that a parameter is unknown.
1469  static const double kUnknownDoubleParamValue;
1470  static const int kUnknownIntegerParamValue;
1471 
1472  // Default values for parameters. Only parameters that define the
1473  // properties of the solution returned need to have a default value
1474  // (that is the same for all solvers). You can also define a default
1475  // value for performance parameters when you are confident it is a
1476  // good choice (example: always turn presolve on).
1477  static const double kDefaultRelativeMipGap;
1478  static const double kDefaultPrimalTolerance;
1479  static const double kDefaultDualTolerance;
1482 
1485 
1488 
1491 
1498 
1505 
1507  void Reset();
1508 
1510  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1511 
1514 
1515  private:
1516  // Parameter value for each parameter.
1517  // @see DoubleParam
1518  // @see IntegerParam
1519  double relative_mip_gap_value_;
1520  double primal_tolerance_value_;
1521  double dual_tolerance_value_;
1522  int presolve_value_;
1523  int scaling_value_;
1524  int lp_algorithm_value_;
1525  int incrementality_value_;
1526 
1527  // Boolean value indicating whether each parameter is set to the
1528  // solver's default value. Only parameters for which the wrapper
1529  // does not define a default value need such an indicator.
1530  bool lp_algorithm_is_default_;
1531 
1532  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1533 };
1534 
1535 // Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1536 // error when happening on the linear solver stubby server, see
1537 // ./linear_solver_service.proto.
1538 // Note that RPC errors forbid to carry a response to the client, who can only
1539 // see the RPC error itself (error code + error message).
1541 
1542 // This class wraps the actual mathematical programming solvers. Each
1543 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1544 // derives from this abstract class. This class is never directly
1545 // accessed by the user.
1546 // @see glop_interface.cc
1547 // @see cbc_interface.cc
1548 // @see clp_interface.cc
1549 // @see glpk_interface.cc
1550 // @see scip_interface.cc
1552  public:
1554  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1555  // sync for the model nor for the solution.
1557  // The underlying solver and MPSolver are in sync for the model
1558  // but not for the solution: the model has changed since the
1559  // solution was computed last.
1561  // The underlying solver and MPSolver are in sync for the model and
1562  // the solution.
1564  };
1565 
1566  // When the underlying solver does not provide the number of simplex
1567  // iterations.
1568  static constexpr int64_t kUnknownNumberOfIterations = -1;
1569  // When the underlying solver does not provide the number of
1570  // branch-and-bound nodes.
1571  static constexpr int64_t kUnknownNumberOfNodes = -1;
1572 
1573  // Constructor. The user will access the MPSolverInterface through the
1574  // MPSolver passed as argument.
1575  explicit MPSolverInterface(MPSolver* const solver);
1576  virtual ~MPSolverInterface();
1577 
1578  // ----- Solve -----
1579  // Solves problem with specified parameter values. Returns true if the
1580  // solution is optimal.
1581  virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1582 
1583  // Attempts to directly solve a MPModelRequest, bypassing the MPSolver data
1584  // structures entirely. Like MPSolver::SolveWithProto(), optionally takes in
1585  // an 'interrupt' boolean.
1586  // Returns {} (eg. absl::nullopt) if direct-solve is not supported by the
1587  // underlying solver (possibly because interrupt != nullptr), in which case
1588  // the user should fall back to using MPSolver.
1589  virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1590  const MPModelRequest& request,
1591  // `interrupt` is non-const because the internal
1592  // solver may set it to true itself, in some cases.
1593  std::atomic<bool>* interrupt) {
1594  return absl::nullopt;
1595  }
1596 
1597  // Writes the model using the solver internal write function. Currently only
1598  // available for GurobiInterface.
1599  virtual void Write(const std::string& filename);
1600 
1601  // ----- Model modifications and extraction -----
1602  // Resets extracted model.
1603  virtual void Reset() = 0;
1604 
1605  // Sets the optimization direction (min/max).
1606  virtual void SetOptimizationDirection(bool maximize) = 0;
1607 
1608  // Modifies bounds of an extracted variable.
1609  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1610 
1611  // Modifies integrality of an extracted variable.
1612  virtual void SetVariableInteger(int index, bool integer) = 0;
1613 
1614  // Modify bounds of an extracted variable.
1615  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1616 
1617  // Adds a linear constraint.
1618  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1619 
1620  // Adds an indicator constraint. Returns true if the feature is supported by
1621  // the underlying solver.
1622  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1623  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1624  return false;
1625  }
1626 
1627  // Add a variable.
1628  virtual void AddVariable(MPVariable* const var) = 0;
1629 
1630  // Changes a coefficient in a constraint.
1631  virtual void SetCoefficient(MPConstraint* const constraint,
1632  const MPVariable* const variable,
1633  double new_value, double old_value) = 0;
1634 
1635  // Clears a constraint from all its terms.
1636  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1637 
1638  // Changes a coefficient in the linear objective.
1639  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1640  double coefficient) = 0;
1641 
1642  // Changes the constant term in the linear objective.
1643  virtual void SetObjectiveOffset(double value) = 0;
1644 
1645  // Clears the objective from all its terms.
1646  virtual void ClearObjective() = 0;
1647 
1648  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1649  // ------ Query statistics on the solution and the solve ------
1650  // Returns the number of simplex iterations. The problem must be discrete,
1651  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1652  virtual int64_t iterations() const = 0;
1653  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1654  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1655  virtual int64_t nodes() const = 0;
1656  // Returns the best objective bound. The problem must be discrete, otherwise
1657  // it crashes, or returns trivial bound (+/- inf) in NDEBUG mode.
1658  double best_objective_bound() const;
1659  // Returns the objective value of the best solution found so far.
1660  double objective_value() const;
1661 
1662  // Returns the basis status of a row.
1663  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1664  // Returns the basis status of a constraint.
1665  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1666 
1667  // Checks whether the solution is synchronized with the model, i.e. whether
1668  // the model has changed since the solution was computed last.
1669  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1670  bool CheckSolutionIsSynchronized() const;
1671  // Checks whether a feasible solution exists. The behavior is similar to
1672  // CheckSolutionIsSynchronized() above.
1673  virtual bool CheckSolutionExists() const;
1674  // Handy shortcut to do both checks above (it is often used).
1677  }
1678 
1679  // ----- Misc -----
1680  // Queries problem type. For simplicity, the distinction between
1681  // continuous and discrete is based on the declaration of the user
1682  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1683  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1684  // the model.
1685  // Returns true if the problem is continuous.
1686  virtual bool IsContinuous() const = 0;
1687  // Returns true if the problem is continuous and linear.
1688  virtual bool IsLP() const = 0;
1689  // Returns true if the problem is discrete and linear.
1690  virtual bool IsMIP() const = 0;
1691 
1692  // Returns the index of the last variable extracted.
1694 
1695  bool variable_is_extracted(int var_index) const {
1696  return solver_->variable_is_extracted_[var_index];
1697  }
1698  void set_variable_as_extracted(int var_index, bool extracted) {
1699  solver_->variable_is_extracted_[var_index] = extracted;
1700  }
1701  bool constraint_is_extracted(int ct_index) const {
1702  return solver_->constraint_is_extracted_[ct_index];
1703  }
1704  void set_constraint_as_extracted(int ct_index, bool extracted) {
1705  solver_->constraint_is_extracted_[ct_index] = extracted;
1706  }
1707 
1708  // Returns the boolean indicating the verbosity of the solver output.
1709  bool quiet() const { return quiet_; }
1710  // Sets the boolean indicating the verbosity of the solver output.
1711  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1712 
1713  // Returns the result status of the last solve.
1716  return result_status_;
1717  }
1718 
1719  // Returns a string describing the underlying solver and its version.
1720  virtual std::string SolverVersion() const = 0;
1721 
1722  // Returns the underlying solver.
1723  virtual void* underlying_solver() = 0;
1724 
1725  // Computes exact condition number. Only available for continuous
1726  // problems and only implemented in GLPK.
1727  virtual double ComputeExactConditionNumber() const;
1728 
1729  // See MPSolver::SetStartingLpBasis().
1730  virtual void SetStartingLpBasis(
1731  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1732  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1733  LOG(FATAL) << "Not supported by this solver.";
1734  }
1735 
1736  virtual bool InterruptSolve() { return false; }
1737 
1738  // See MPSolver::NextSolution() for contract.
1739  virtual bool NextSolution() { return false; }
1740 
1741  // See MPSolver::SetCallback() for details.
1742  virtual void SetCallback(MPCallback* mp_callback) {
1743  LOG(FATAL) << "Callbacks not supported for this solver.";
1744  }
1745 
1746  virtual bool SupportsCallbacks() const { return false; }
1747 
1748  friend class MPSolver;
1749 
1750  // To access the maximize_ bool and the MPSolver.
1751  friend class MPConstraint;
1752  friend class MPObjective;
1753 
1754  protected:
1756  // Indicates whether the model and the solution are synchronized.
1758  // Indicates whether the solve has reached optimality,
1759  // infeasibility, a limit, etc.
1761  // Optimization direction.
1763 
1764  // Index in MPSolver::variables_ of last constraint extracted.
1766  // Index in MPSolver::constraints_ of last variable extracted.
1768 
1769  // The value of the objective function.
1771 
1772  // The value of the best objective bound. Used only for MIP solvers.
1774 
1775  // Boolean indicator for the verbosity of the solver output.
1776  bool quiet_;
1777 
1778  // Index of dummy variable created for empty constraints or the
1779  // objective offset.
1780  static const int kDummyVariableIndex;
1781 
1782  // Extracts model stored in MPSolver.
1783  void ExtractModel();
1784  // Extracts the variables that have not been extracted yet.
1785  virtual void ExtractNewVariables() = 0;
1786  // Extracts the constraints that have not been extracted yet.
1787  virtual void ExtractNewConstraints() = 0;
1788  // Extracts the objective.
1789  virtual void ExtractObjective() = 0;
1790  // Resets the extraction information.
1792  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1793  // MODEL_SYNCHRONIZED. To be used for model changes.
1795 
1796  // Sets parameters common to LP and MIP in the underlying solver.
1797  void SetCommonParameters(const MPSolverParameters& param);
1798  // Sets MIP specific parameters in the underlying solver.
1799  void SetMIPParameters(const MPSolverParameters& param);
1800  // Sets all parameters in the underlying solver.
1801  virtual void SetParameters(const MPSolverParameters& param) = 0;
1802  // Sets an unsupported double parameter.
1804  // Sets an unsupported integer parameter.
1805  virtual void SetUnsupportedIntegerParam(
1807  // Sets a supported double parameter to an unsupported value.
1809  double value);
1810  // Sets a supported integer parameter to an unsupported value.
1811  virtual void SetIntegerParamToUnsupportedValue(
1813  // Sets each parameter in the underlying solver.
1814  virtual void SetRelativeMipGap(double value) = 0;
1815  virtual void SetPrimalTolerance(double value) = 0;
1816  virtual void SetDualTolerance(double value) = 0;
1817  virtual void SetPresolveMode(int value) = 0;
1818 
1819  // Sets the number of threads to be used by the solver.
1820  virtual absl::Status SetNumThreads(int num_threads);
1821 
1822  // Pass solver specific parameters in text format. The format is
1823  // solver-specific and is the same as the corresponding solver configuration
1824  // file format. Returns true if the operation was successful.
1825  //
1826  // Default implementation returns true if the input is empty. It returns false
1827  // and logs a WARNING if the input is not empty.
1829  const std::string& parameters);
1830 
1831  // Sets the scaling mode.
1832  virtual void SetScalingMode(int value) = 0;
1833  virtual void SetLpAlgorithm(int value) = 0;
1834 };
1835 
1836 } // namespace operations_research
1837 
1838 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
ResultStatus
The status of solving the problem.
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the constraint.
virtual absl::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request, std::atomic< bool > *interrupt)
static const IncrementalityValues kDefaultIncrementality
virtual OptimizationProblemType ProblemType() const
Returns the optimization problem type set at construction.
MPVariable * LookupVariableOrNull(const std::string &var_name) const
Looks up a variable by name, and returns nullptr if it does not exist.
void set_variable_as_extracted(int var_index, bool extracted)
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
Advanced usage: incrementality from one solve to the next.
virtual absl::Status SetNumThreads(int num_threads)
static MPSolver * CreateSolver(const std::string &solver_id)
Recommended factory method to create a MPSolver instance, especially in non C++ languages.
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
virtual void SetLpAlgorithm(int value)=0
static constexpr SolverType GUROBI_LINEAR_PROGRAMMING
ScalingValues
Advanced usage: Scaling options.
double Value() const
Returns the objective value of the best solution found so far.
virtual void SetOptimizationDirection(bool maximize)=0
const int FATAL
Definition: log_severity.h:32
virtual void SetPresolveMode(int value)=0
const std::vector< MPConstraint * > & constraints() const
Returns the array of constraints handled by the MPSolver.
MPSolver::ResultStatus result_status() const
void set_constraint_as_extracted(int ct_index, bool extracted)
static OptimizationProblemType ParseSolverTypeOrDie(const std::string &solver_id)
Parses the name of the solver and returns the correct optimization type or dies.
void Clear()
Clears the objective (including the optimization direction), all variables and constraints.
void SetOffset(double value)
Sets the constant term in the objective.
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
Advanced usage: Incrementality.
virtual double ComputeExactConditionNumber() const
const std::string & name() const
Returns the name of the constraint.
const std::string name
const MPObjective & Objective() const
Returns the objective object.
MPSolverParameters()
The constructor sets all parameters to their default value.
double ub() const
Returns the upper bound.
static double infinity()
Infinity.
const int ERROR
Definition: log_severity.h:32
virtual bool AddIndicatorConstraint(MPConstraint *const ct)
virtual void ClearConstraint(MPConstraint *const constraint)=0
virtual void SetCallback(MPCallback *mp_callback)
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
Sets a double parameter to its default value (default value defined in MPSolverParameters if it exist...
void Clear()
Clears all variables and coefficients. Does not clear the bounds.
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
double BestBound() const
Returns the best objective bound.
int NumVariables() const
Returns the number of variables.
static bool SupportsProblemType(OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
const absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)
bool integer() const
Returns the integrality requirement of the variable.
#define LOG(severity)
Definition: base/logging.h:420
bool minimization() const
Is the optimization direction set to minimize?
OptimizationProblemType
The type of problems (LP or MIP) that will be solved and the underlying solver (GLOP,...
void SetMinimization()
Sets the optimization direction to minimize.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
A class to express a linear objective.
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
const MPVariable * indicator_variable() const
ABSL_DECLARE_FLAG(bool, linear_solver_enable_verbose_output)
IntegerParam
Enumeration of parameters that take integer or categorical values.
virtual void Write(const std::string &filename)
int64_t coefficient
virtual bool IsContinuous() const =0
MPObjective * MutableObjective()
Returns the mutable objective object.
void Reset()
Advanced usage: resets extracted model to solve from scratch.
virtual int64_t nodes() const =0
static int64_t global_num_constraints()
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable on the constraint (which is 0 if the variable does not appea...
void set_dual_value(double dual_value)
MPSolverInterface(MPSolver *const solver)
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
Sets an integer parameter to its default value (default value defined in MPSolverParameters if it exi...
virtual int64_t iterations() const =0
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
virtual void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient)=0
virtual void SetRelativeMipGap(double value)=0
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
MPConstraint(int index, double lb, double ub, const std::string &name, MPSolverInterface *const interface_in)
absl::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
void set_solution_value(double value)
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
Sets a hint for solution.
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
The class for variables of a Mathematical Programming (MP) model.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the variable in the current solution (only available for ...
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
Definition: cleanup.h:22
void OptimizeLinearExpr(const LinearExpr &linear_expr, bool is_maximization)
Resets the current objective to take the value of linear_expr, and sets the objective direction to ma...
virtual void SetObjectiveOffset(double value)=0
the model is trivially invalid (NaN coefficients, etc).
DoubleParam
Enumeration of parameters that take continuous values.
virtual void SetDualTolerance(double value)=0
static int64_t global_num_variables()
virtual void SetScalingMode(int value)=0
MPVariable(int index, double lb, double ub, bool integer, const std::string &name, MPSolverInterface *const interface_in)
double ub() const
Returns the upper bound.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
absl::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying solver.
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
Looks up a constraint by name, and returns nullptr if it does not exist.
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
std::vector< double > ComputeConstraintActivities() const
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms...
double ComputeExactConditionNumber() const
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(i...
bool VerifySolution(double tolerance, bool log_errors) const
Advanced usage: Verifies the correctness of the solution.
int64_t iterations() const
Returns the number of simplex iterations.
MPVariable * MakeVar(double lb, double ub, bool integer, const std::string &name)
Creates a variable with the given bounds, integrality requirement and name.
void MakeVarArray(int nb, double lb, double ub, bool integer, const std::string &name_prefix, std::vector< MPVariable * > *vars)
Creates an array of variables.
IntVar *const objective_
Definition: search.cc:3017
virtual void SetConstraintBounds(int index, double lb, double ub)=0
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
void Write(const std::string &file_name)
Writes the model using the solver internal write function.
void SetCommonParameters(const MPSolverParameters &param)
static constexpr int64_t kUnknownNumberOfIterations
virtual std::string SolverVersion() const =0
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
const std::string & name() const
Returns the name of the variable.
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
void SuppressOutput()
Suppresses solver logging.
void Reset()
Sets all parameters to their default value.
int index
Definition: pack.cc:509
double solution_value() const
Returns the value of the variable in the current solution.
virtual void SetVariableBounds(int index, double lb, double ub)=0
void SetLB(double lb)
Sets the lower bound.
The class for constraints of a Mathematical Programming (MP) model.
static const PresolveValues kDefaultPresolve
feasible, or stopped by limit.
#define DCHECK_GE(val1, val2)
Definition: base/logging.h:894
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable in the objective.
void SetMIPParameters(const MPSolverParameters &param)
SharedResponseManager * response
static bool SolverTypeSupportsInterruption(const MPModelRequest::SolverType solver)
void EnableOutput()
Enables solver logging.
bool constraint_is_extracted(int ct_index) const
Advanced usage: tolerance for primal feasibility of basic solutions.
virtual void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value)=0
absl::Duration DurationSinceConstruction() const
void SetLB(double lb)
Sets the lower bound.
This file allows you to write natural code (like a mathematical equation) to model optimization probl...
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
double dual_value() const
Advanced usage: returns the dual value of the constraint in the current solution (only available for ...
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
bool OutputIsEnabled() const
Controls (or queries) the amount of output produced by the underlying solver.
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
virtual void BranchingPriorityChangedForVariable(int var_index)
int NumConstraints() const
Returns the number of constraints.
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
int index() const
Returns the index of the variable in the MPSolver::variables_.
Advanced usage: enable or disable matrix scaling.
void SetCallback(MPCallback *mp_callback)
void SetBranchingPriority(int priority)
double unrounded_solution_value() const
Advanced usage: unrounded solution value.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the constraint.
bool AbslParseFlag(const absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
std::string GetSolverSpecificParametersAsString() const
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
virtual void AddRowConstraint(MPConstraint *const ct)=0
static constexpr int64_t kUnknownNumberOfNodes
std::string AbslUnparseFlag(MPSolver::OptimizationProblemType solver_type)
Advanced usage: tolerance for dual feasibility of basic solutions.
absl::Duration TimeLimit() const
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
bool maximization() const
Is the optimization direction set to maximize?
double lb() const
Returns the lower bound.
void SetTimeLimit(absl::Duration time_limit)
MPVariable * variable(int index) const
Returns the variable at position index.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable on the constraint.
int64_t nodes() const
Returns the number of branch-and-bound nodes evaluated during the solve.
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the objective.
double lb() const
Returns the lower bound.
Reuse results from previous solve as much as the underlying solver allows.
ResultStatus Solve()
Solves the problem using the default parameter values.
const std::vector< MPVariable * > & variables() const
Returns the array of variables handled by the MPSolver.
This mathematical programming (MP) solver class is the main class though which users build and solve ...
IncrementalityValues
Advanced usage: Incrementality options.
LinearExpr models a quantity that is linear in the decision variables (MPVariable) of an optimization...
Definition: linear_expr.h:114
bool OwnsVariable(const MPVariable *var) const
virtual void SetVariableInteger(int index, bool integer)=0
Collection of objects used to extend the Constraint Solver library.
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
abnormal, i.e., error of some kind.
void SetUB(double ub)
Sets the upper bound.
void SetUB(double ub)
Sets the upper bound.
const int64_t offset_
Definition: interval.cc:2108
MPConstraint * MakeRowConstraint()
Creates a constraint with -infinity and +infinity bounds.
static constexpr SolverType SAT_INTEGER_PROGRAMMING
MPSolver::OptimizationProblemType problem_type
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
SatParameters parameters
std::string SolverVersion() const
Returns a string describing the underlying solver and its version.
const std::string & Name() const
Returns the name of the model set at construction.
This class stores parameter settings for LP and MIP solvers.
void Clear()
Clears the offset, all variables and coefficients, and the optimization direction.
absl::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=std::numeric_limits< double >::infinity())
Load a solution encoded in a protocol buffer onto this solver for easy access via the MPSolver interf...
IntVar * var
Definition: expr_array.cc:1874
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
Shortcuts to the homonymous MPModelProtoExporter methods, via exporting to a MPModelProto with Export...
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status)
PresolveValues
For each categorical parameter, enumeration of possible values.
An expression of the form:
Definition: linear_expr.h:192
virtual void SetPrimalTolerance(double value)=0
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
static constexpr SolverType GLOP_LINEAR_PROGRAMMING
void * underlying_solver()
Advanced usage: returns the underlying solver.
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
int GetNumThreads() const
Returns the number of threads to be used during solve.
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
MPConstraint * constraint(int index) const
Returns the constraint at the given index.
constexpr double kDefaultPrimalTolerance
void set_time_limit(int64_t time_limit_milliseconds)
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response, std::atomic< bool > *interrupt=nullptr)
Solves the model encoded by a MPModelRequest protocol buffer and fills the solution encoded as a MPSo...
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
virtual void AddVariable(MPVariable *const var)=0
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
double offset() const
Gets the constant term in the objective.
double reduced_cost() const
Advanced usage: returns the reduced cost of the variable in the current solution (only available for ...
int64_t value
void set_reduced_cost(double reduced_cost)
static constexpr SolverType GUROBI_MIXED_INTEGER_PROGRAMMING
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
const Constraint * ct
bool variable_is_extracted(int var_index) const
ABSL_MUST_USE_RESULT bool NextSolution()
Some solvers (MIP only, not LP) can produce multiple solutions to the problem.
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
Definition: macros.h:29
virtual void SetParameters(const MPSolverParameters &param)=0
static bool ParseSolverType(absl::string_view solver_id, OptimizationProblemType *type)
Parses the name of the solver.
void SetMaximization()
Sets the optimization direction to maximize.
int branching_priority() const
Advanced usage: Certain MIP solvers (e.g.
void set_is_lazy(bool laziness)
Advanced usage: sets the constraint "laziness".