C++ Reference

C++ Reference: Linear solver

linear_solver.h
Go to the documentation of this file.
1 // Copyright 2010-2018 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 <functional>
138 #include <limits>
139 #include <map>
140 #include <memory>
141 #include <string>
142 #include <utility>
143 #include <vector>
144 
145 #include "absl/container/flat_hash_map.h"
146 #include "absl/status/status.h"
147 #include "absl/strings/match.h"
148 #include "absl/strings/str_format.h"
149 #include "absl/types/optional.h"
150 #include "ortools/base/commandlineflags.h"
151 #include "ortools/base/integral_types.h"
152 #include "ortools/base/logging.h"
153 #include "ortools/base/macros.h"
154 #include "ortools/base/timer.h"
157 #include "ortools/linear_solver/linear_solver_callback.h"
158 #include "ortools/port/proto_utils.h"
159 
160 namespace operations_research {
161 
162 constexpr double kDefaultPrimalTolerance = 1e-07;
163 
164 class MPConstraint;
165 class MPObjective;
166 class MPSolverInterface;
167 class MPSolverParameters;
168 class MPVariable;
169 
170 // There is a homonymous version taking a MPSolver::OptimizationProblemType.
171 bool SolverTypeIsMip(MPModelRequest::SolverType solver_type);
172 
177 class MPSolver {
178  public:
186  // Linear programming problems.
187  // ----------------------------
190  GLOP_LINEAR_PROGRAMMING = 2, // Recommended default value. Made in Google.
191 
192  // Integer programming problems.
193  // -----------------------------
194  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
197 
198  // Commercial software (need license).
205 
206  // Boolean optimization problem (requires only integer variables and works
207  // best with only Boolean variables).
209 
210  // SAT based solver (requires only integer and Boolean variables).
211  // If you pass it mixed integer problems, it will scale coefficients to
212  // integer values, and solver continuous variables as integral variables.
214 
215  // Dedicated knapsack solvers.
217  };
218 
220  MPSolver(const std::string& name, OptimizationProblemType problem_type);
221  virtual ~MPSolver();
222 
251  static MPSolver* CreateSolver(const std::string& name,
252  const std::string& solver_id);
253 
258  static bool SupportsProblemType(OptimizationProblemType problem_type);
259 
264  static bool ParseSolverType(absl::string_view solver_id,
266 
272  const std::string& solver_id);
273 
278  static bool ParseAndCheckSupportForProblemType(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 
313  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
314 
322  MPVariable* MakeVar(double lb, double ub, bool integer,
323  const std::string& name);
324 
326  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
327 
329  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
330 
332  MPVariable* MakeBoolVar(const std::string& name);
333 
348  void MakeVarArray(int nb, double lb, double ub, bool integer,
349  const std::string& name_prefix,
350  std::vector<MPVariable*>* vars);
351 
353  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
354  std::vector<MPVariable*>* vars);
355 
357  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
358  std::vector<MPVariable*>* vars);
359 
361  void MakeBoolVarArray(int nb, const std::string& name,
362  std::vector<MPVariable*>* vars);
363 
365  int NumConstraints() const { return constraints_.size(); }
366 
372  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
373 
382  const std::string& constraint_name) const;
383 
392  MPConstraint* MakeRowConstraint(double lb, double ub);
393 
396 
398  MPConstraint* MakeRowConstraint(double lb, double ub,
399  const std::string& name);
400 
402  MPConstraint* MakeRowConstraint(const std::string& name);
403 
409 
412  const std::string& name);
413 
420  const MPObjective& Objective() const { return *objective_; }
421 
423  MPObjective* MutableObjective() { return objective_.get(); }
424 
445  NOT_SOLVED = 6
446  };
447 
450 
453 
458  void Write(const std::string& file_name);
459 
466  std::vector<double> ComputeConstraintActivities() const;
467 
486  bool VerifySolution(double tolerance, bool log_errors) const;
487 
496  void Reset();
497 
506 
514  MPSolverResponseStatus LoadModelFromProto(const MPModelProto& input_model,
515  std::string* error_message);
524  const MPModelProto& input_model, std::string* error_message);
525 
527  void FillSolutionResponseProto(MPSolutionResponse* response) const;
528 
538  static void SolveWithProto(const MPModelRequest& model_request,
539  MPSolutionResponse* response);
540 
542  void ExportModelToProto(MPModelProto* output_model) const;
543 
575  absl::Status LoadSolutionFromProto(
576  const MPSolutionResponse& response,
577  double tolerance = kDefaultPrimalTolerance);
578 
584 
591  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
592  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
593  std::string* model_str) const;
594 
605  absl::Status SetNumThreads(int num_threads);
606 
608  int GetNumThreads() const { return num_threads_; }
609 
616  bool SetSolverSpecificParametersAsString(const std::string& parameters);
618  return solver_specific_parameter_string_;
619  }
620 
634  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
635 
640  enum BasisStatus {
641  FREE = 0,
645  BASIC
646  };
647 
660  const std::vector<MPSolver::BasisStatus>& variable_statuses,
661  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
662 
668  static double infinity() { return std::numeric_limits<double>::infinity(); }
669 
678  bool OutputIsEnabled() const;
679 
681  void EnableOutput();
682 
685 
686  absl::Duration TimeLimit() const { return time_limit_; }
687  void SetTimeLimit(absl::Duration time_limit) {
688  DCHECK_GE(time_limit, absl::ZeroDuration());
689  time_limit_ = time_limit;
690  }
691 
692  absl::Duration DurationSinceConstruction() const {
693  return absl::Now() - construction_time_;
694  }
695 
697  int64 iterations() const;
698 
704  int64 nodes() const;
705 
707  std::string SolverVersion() const;
708 
723 
748 
763  ABSL_MUST_USE_RESULT bool NextSolution();
764 
765  // Does not take ownership of "mp_callback".
766  //
767  // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
768  // SCIP does not support suggesting a heuristic solution in the callback.
769  //
770  // See go/mpsolver-callbacks for additional documentation.
771  void SetCallback(MPCallback* mp_callback);
772  bool SupportsCallbacks() const;
773 
774  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
775  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
776  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
777  int64 time_limit() const {
778  return time_limit_ == absl::InfiniteDuration()
779  ? 0
780  : absl::ToInt64Milliseconds(time_limit_);
781  }
782  void set_time_limit(int64 time_limit_milliseconds) {
783  SetTimeLimit(time_limit_milliseconds == 0
784  ? absl::InfiniteDuration()
785  : absl::Milliseconds(time_limit_milliseconds));
786  }
787  double time_limit_in_secs() const {
788  return static_cast<double>(time_limit()) / 1000.0;
789  }
790 
791  // DEPRECATED: Use DurationSinceConstruction() instead.
792  int64 wall_time() const {
793  return absl::ToInt64Milliseconds(DurationSinceConstruction());
794  }
795 
796  // Supports search and loading Gurobi shared library.
797  static bool LoadGurobiSharedLibrary();
798  static void SetGurobiLibraryPath(const std::string &full_library_path);
799 
800  friend class GLPKInterface;
801  friend class CLPInterface;
802  friend class CBCInterface;
803  friend class SCIPInterface;
804  friend class GurobiInterface;
805  friend class CplexInterface;
806  friend class XpressInterface;
807  friend class SLMInterface;
808  friend class MPSolverInterface;
809  friend class GLOPInterface;
810  friend class BopInterface;
811  friend class SatInterface;
812  friend class KnapsackInterface;
813 
814  // Debugging: verify that the given MPVariable* belongs to this solver.
815  bool OwnsVariable(const MPVariable* var) const;
816 
817  private:
818  // Computes the size of the constraint with the largest number of
819  // coefficients with index in [min_constraint_index,
820  // max_constraint_index)
821  int ComputeMaxConstraintSize(int min_constraint_index,
822  int max_constraint_index) const;
823 
824  // Returns true if the model has constraints with lower bound > upper bound.
825  bool HasInfeasibleConstraints() const;
826 
827  // Returns true if the model has at least 1 integer variable.
828  bool HasIntegerVariables() const;
829 
830  // Generates the map from variable names to their indices.
831  void GenerateVariableNameIndex() const;
832 
833  // Generates the map from constraint names to their indices.
834  void GenerateConstraintNameIndex() const;
835 
836  // Checks licenses for commercial solver, and checks shared library loading
837  // for or-tools.
838  static bool GurobiIsCorrectlyInstalled();
839 
840  // The name of the linear programming problem.
841  const std::string name_;
842 
843  // The type of the linear programming problem.
844  const OptimizationProblemType problem_type_;
845 
846  // The solver interface.
847  std::unique_ptr<MPSolverInterface> interface_;
848 
849  // The vector of variables in the problem.
850  std::vector<MPVariable*> variables_;
851  // A map from a variable's name to its index in variables_.
852  mutable absl::optional<absl::flat_hash_map<std::string, int> >
853  variable_name_to_index_;
854  // Whether variables have been extracted to the underlying interface.
855  std::vector<bool> variable_is_extracted_;
856 
857  // The vector of constraints in the problem.
858  std::vector<MPConstraint*> constraints_;
859  // A map from a constraint's name to its index in constraints_.
860  mutable absl::optional<absl::flat_hash_map<std::string, int> >
861  constraint_name_to_index_;
862  // Whether constraints have been extracted to the underlying interface.
863  std::vector<bool> constraint_is_extracted_;
864 
865  // The linear objective function.
866  std::unique_ptr<MPObjective> objective_;
867 
868  // Initial values for all or some of the problem variables that can be
869  // exploited as a starting hint by a solver.
870  //
871  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
872  //
873  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
874  // hint is provided and a std::vector<double> for the hint value.
875  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
876 
877  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
878 
879  const absl::Time construction_time_;
880 
881  // Permanent storage for the number of threads.
882  int num_threads_ = 1;
883 
884  // Permanent storage for SetSolverSpecificParametersAsString().
885  std::string solver_specific_parameter_string_;
886 
887  MPSolverResponseStatus LoadModelFromProtoInternal(
888  const MPModelProto& input_model, bool clear_names,
889  bool check_model_validity, std::string* error_message);
890 
891  DISALLOW_COPY_AND_ASSIGN(MPSolver);
892 };
893 
895  return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
896 }
897 
898 const absl::string_view ToString(
899  MPSolver::OptimizationProblemType optimization_problem_type);
900 
901 inline std::ostream& operator<<(
902  std::ostream& os,
903  MPSolver::OptimizationProblemType optimization_problem_type) {
904  return os << ToString(optimization_problem_type);
905 }
906 
907 inline std::ostream& operator<<(std::ostream& os,
908  MPSolver::ResultStatus status) {
909  return os << ProtoEnumToString<MPSolverResponseStatus>(
910  static_cast<MPSolverResponseStatus>(status));
911 }
912 
913 bool AbslParseFlag(absl::string_view text,
915  std::string* error);
916 
917 inline std::string AbslUnparseFlag(
918  MPSolver::OptimizationProblemType solver_type) {
919  return std::string(ToString(solver_type));
920 }
921 
923 class MPObjective {
924  public:
929  void Clear();
930 
937  void SetCoefficient(const MPVariable* const var, double coeff);
938 
944  double GetCoefficient(const MPVariable* const var) const;
945 
951  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
952  return coefficients_;
953  }
954 
956  void SetOffset(double value);
957 
959  double offset() const { return offset_; }
960 
965  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
966 
968  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
969  OptimizeLinearExpr(linear_expr, true);
970  }
972  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
973  OptimizeLinearExpr(linear_expr, false);
974  }
975 
977  void AddLinearExpr(const LinearExpr& linear_expr);
978 
980  void SetOptimizationDirection(bool maximize);
981 
984 
987 
989  bool maximization() const;
990 
992  bool minimization() const;
993 
1005  double Value() const;
1006 
1013  double BestBound() const;
1014 
1015  private:
1016  friend class MPSolver;
1017  friend class MPSolverInterface;
1018  friend class CBCInterface;
1019  friend class CLPInterface;
1020  friend class GLPKInterface;
1021  friend class SCIPInterface;
1022  friend class SLMInterface;
1023  friend class GurobiInterface;
1024  friend class CplexInterface;
1025  friend class XpressInterface;
1026  friend class GLOPInterface;
1027  friend class BopInterface;
1028  friend class SatInterface;
1029  friend class KnapsackInterface;
1030 
1031  // Constructor. An objective points to a single MPSolverInterface
1032  // that is specified in the constructor. An objective cannot belong
1033  // to several models.
1034  // At construction, an MPObjective has no terms (which is equivalent
1035  // on having a coefficient of 0 for all variables), and an offset of 0.
1036  explicit MPObjective(MPSolverInterface* const interface_in)
1037  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1038 
1039  MPSolverInterface* const interface_;
1040 
1041  // Mapping var -> coefficient.
1042  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1043  // Constant term.
1044  double offset_;
1045 
1046  DISALLOW_COPY_AND_ASSIGN(MPObjective);
1047 };
1048 
1050 class MPVariable {
1051  public:
1053  const std::string& name() const { return name_; }
1054 
1056  void SetInteger(bool integer);
1057 
1059  bool integer() const { return integer_; }
1060 
1068  double solution_value() const;
1069 
1071  int index() const { return index_; }
1072 
1074  double lb() const { return lb_; }
1075 
1077  double ub() const { return ub_; }
1078 
1080  void SetLB(double lb) { SetBounds(lb, ub_); }
1081 
1083  void SetUB(double ub) { SetBounds(lb_, ub); }
1084 
1086  void SetBounds(double lb, double ub);
1087 
1095 
1100  double reduced_cost() const;
1101 
1109 
1111  int branching_priority() const { return branching_priority_; }
1122  void SetBranchingPriority(int priority);
1123 
1124  protected:
1125  friend class MPSolver;
1126  friend class MPSolverInterface;
1127  friend class CBCInterface;
1128  friend class CLPInterface;
1129  friend class GLPKInterface;
1130  friend class SCIPInterface;
1131  friend class SLMInterface;
1132  friend class GurobiInterface;
1133  friend class CplexInterface;
1134  friend class XpressInterface;
1135  friend class GLOPInterface;
1137  friend class BopInterface;
1138  friend class SatInterface;
1139  friend class KnapsackInterface;
1140 
1141  // Constructor. A variable points to a single MPSolverInterface that
1142  // is specified in the constructor. A variable cannot belong to
1143  // several models.
1144  MPVariable(int index, double lb, double ub, bool integer,
1145  const std::string& name, MPSolverInterface* const interface_in)
1146  : index_(index),
1147  lb_(lb),
1148  ub_(ub),
1149  integer_(integer),
1150  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1151  solution_value_(0.0),
1152  reduced_cost_(0.0),
1153  interface_(interface_in) {}
1154 
1155  void set_solution_value(double value) { solution_value_ = value; }
1156  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1157 
1158  private:
1159  const int index_;
1160  double lb_;
1161  double ub_;
1162  bool integer_;
1163  const std::string name_;
1164  double solution_value_;
1165  double reduced_cost_;
1166  int branching_priority_ = 0;
1167  MPSolverInterface* const interface_;
1168  DISALLOW_COPY_AND_ASSIGN(MPVariable);
1169 };
1170 
1177  public:
1179  const std::string& name() const { return name_; }
1180 
1182  void Clear();
1183 
1190  void SetCoefficient(const MPVariable* const var, double coeff);
1191 
1196  double GetCoefficient(const MPVariable* const var) const;
1197 
1203  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1204  return coefficients_;
1205  }
1206 
1208  double lb() const { return lb_; }
1209 
1211  double ub() const { return ub_; }
1212 
1214  void SetLB(double lb) { SetBounds(lb, ub_); }
1215 
1217  void SetUB(double ub) { SetBounds(lb_, ub); }
1218 
1220  void SetBounds(double lb, double ub);
1221 
1223  bool is_lazy() const { return is_lazy_; }
1224 
1238  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1239 
1240  const MPVariable* indicator_variable() const { return indicator_variable_; }
1241  bool indicator_value() const { return indicator_value_; }
1242 
1244  int index() const { return index_; }
1245 
1250  double dual_value() const;
1251 
1265 
1266  protected:
1267  friend class MPSolver;
1268  friend class MPSolverInterface;
1269  friend class CBCInterface;
1270  friend class CLPInterface;
1271  friend class GLPKInterface;
1272  friend class SCIPInterface;
1273  friend class SLMInterface;
1274  friend class GurobiInterface;
1275  friend class CplexInterface;
1276  friend class XpressInterface;
1277  friend class GLOPInterface;
1278  friend class BopInterface;
1279  friend class SatInterface;
1280  friend class KnapsackInterface;
1281 
1282  // Constructor. A constraint points to a single MPSolverInterface
1283  // that is specified in the constructor. A constraint cannot belong
1284  // to several models.
1285  MPConstraint(int index, double lb, double ub, const std::string& name,
1286  MPSolverInterface* const interface_in)
1287  : coefficients_(1),
1288  index_(index),
1289  lb_(lb),
1290  ub_(ub),
1291  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1292  is_lazy_(false),
1293  indicator_variable_(nullptr),
1294  dual_value_(0.0),
1295  interface_(interface_in) {}
1296 
1297  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1298 
1299  private:
1300  // Returns true if the constraint contains variables that have not
1301  // been extracted yet.
1302  bool ContainsNewVariables();
1303 
1304  // Mapping var -> coefficient.
1305  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1306 
1307  const int index_; // See index().
1308 
1309  // The lower bound for the linear constraint.
1310  double lb_;
1311 
1312  // The upper bound for the linear constraint.
1313  double ub_;
1314 
1315  // Name.
1316  const std::string name_;
1317 
1318  // True if the constraint is "lazy", i.e. the constraint is added to the
1319  // underlying Linear Programming solver only if it is violated.
1320  // By default this parameter is 'false'.
1321  bool is_lazy_;
1322 
1323  // If given, this constraint is only active if `indicator_variable_`'s value
1324  // is equal to `indicator_value_`.
1325  const MPVariable* indicator_variable_;
1326  bool indicator_value_;
1327 
1328  double dual_value_;
1329  MPSolverInterface* const interface_;
1330  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1331 };
1332 
1360  public:
1365 
1374  DUAL_TOLERANCE = 2
1375  };
1376 
1380  PRESOLVE = 1000,
1386  SCALING = 1003
1387  };
1388 
1394  PRESOLVE_ON = 1
1395  };
1396 
1400  DUAL = 10,
1402  PRIMAL = 11,
1404  BARRIER = 12
1405  };
1406 
1411 
1416  INCREMENTALITY_ON = 1
1417  };
1418 
1424  SCALING_ON = 1
1425  };
1426 
1427  // Placeholder value to indicate that a parameter is set to
1428  // the default value defined in the wrapper.
1429  static const double kDefaultDoubleParamValue;
1430  static const int kDefaultIntegerParamValue;
1431 
1432  // Placeholder value to indicate that a parameter is unknown.
1433  static const double kUnknownDoubleParamValue;
1434  static const int kUnknownIntegerParamValue;
1435 
1436  // Default values for parameters. Only parameters that define the
1437  // properties of the solution returned need to have a default value
1438  // (that is the same for all solvers). You can also define a default
1439  // value for performance parameters when you are confident it is a
1440  // good choice (example: always turn presolve on).
1441  static const double kDefaultRelativeMipGap;
1442  static const double kDefaultPrimalTolerance;
1443  static const double kDefaultDualTolerance;
1446 
1449 
1452 
1455 
1462 
1469 
1471  void Reset();
1472 
1475 
1478 
1479  private:
1480  // Parameter value for each parameter.
1481  // @see DoubleParam
1482  // @see IntegerParam
1483  double relative_mip_gap_value_;
1484  double primal_tolerance_value_;
1485  double dual_tolerance_value_;
1486  int presolve_value_;
1487  int scaling_value_;
1488  int lp_algorithm_value_;
1489  int incrementality_value_;
1490 
1491  // Boolean value indicating whether each parameter is set to the
1492  // solver's default value. Only parameters for which the wrapper
1493  // does not define a default value need such an indicator.
1494  bool lp_algorithm_is_default_;
1495 
1496  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1497 };
1498 
1499 // Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1500 // error when happening on the linear solver stubby server, see
1501 // ./linear_solver_service.proto.
1502 // Note that RPC errors forbid to carry a response to the client, who can only
1503 // see the RPC error itself (error code + error message).
1505 
1506 // This class wraps the actual mathematical programming solvers. Each
1507 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1508 // derives from this abstract class. This class is never directly
1509 // accessed by the user.
1510 // @see glop_interface.cc
1511 // @see cbc_interface.cc
1512 // @see clp_interface.cc
1513 // @see glpk_interface.cc
1514 // @see scip_interface.cc
1516  public:
1518  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1519  // sync for the model nor for the solution.
1521  // The underlying solver and MPSolver are in sync for the model
1522  // but not for the solution: the model has changed since the
1523  // solution was computed last.
1525  // The underlying solver and MPSolver are in sync for the model and
1526  // the solution.
1528  };
1529 
1530  // When the underlying solver does not provide the number of simplex
1531  // iterations.
1532  static constexpr int64 kUnknownNumberOfIterations = -1;
1533  // When the underlying solver does not provide the number of
1534  // branch-and-bound nodes.
1535  static constexpr int64 kUnknownNumberOfNodes = -1;
1536 
1537  // Constructor. The user will access the MPSolverInterface through the
1538  // MPSolver passed as argument.
1539  explicit MPSolverInterface(MPSolver* const solver);
1541 
1542  // ----- Solve -----
1543  // Solves problem with specified parameter values. Returns true if the
1544  // solution is optimal.
1546 
1547  // Directly solves a MPModelRequest, bypassing the MPSolver data structures
1548  // entirely. Returns {} (eg. absl::nullopt) if the feature is not supported by
1549  // the underlying solver.
1550  virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1551  const MPModelRequest& request) {
1552  return absl::nullopt;
1553  }
1554 
1555  // Writes the model using the solver internal write function. Currently only
1556  // available for GurobiInterface.
1557  virtual void Write(const std::string& filename);
1558 
1559  // ----- Model modifications and extraction -----
1560  // Resets extracted model.
1561  virtual void Reset() = 0;
1562 
1563  // Sets the optimization direction (min/max).
1564  virtual void SetOptimizationDirection(bool maximize) = 0;
1565 
1566  // Modifies bounds of an extracted variable.
1567  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1568 
1569  // Modifies integrality of an extracted variable.
1570  virtual void SetVariableInteger(int index, bool integer) = 0;
1571 
1572  // Modify bounds of an extracted variable.
1573  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1574 
1575  // Adds a linear constraint.
1576  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1577 
1578  // Adds an indicator constraint. Returns true if the feature is supported by
1579  // the underlying solver.
1580  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1581  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1582  return false;
1583  }
1584 
1585  // Add a variable.
1586  virtual void AddVariable(MPVariable* const var) = 0;
1587 
1588  // Changes a coefficient in a constraint.
1589  virtual void SetCoefficient(MPConstraint* const constraint,
1590  const MPVariable* const variable,
1591  double new_value, double old_value) = 0;
1592 
1593  // Clears a constraint from all its terms.
1594  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1595 
1596  // Changes a coefficient in the linear objective.
1597  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1598  double coefficient) = 0;
1599 
1600  // Changes the constant term in the linear objective.
1601  virtual void SetObjectiveOffset(double value) = 0;
1602 
1603  // Clears the objective from all its terms.
1604  virtual void ClearObjective() = 0;
1605 
1606  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1607  // ------ Query statistics on the solution and the solve ------
1608  // Returns the number of simplex iterations. The problem must be discrete,
1609  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1610  virtual int64 iterations() const = 0;
1611  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1612  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1613  virtual int64 nodes() const = 0;
1614  // Returns the best objective bound. The problem must be discrete, otherwise
1615  // it crashes, or returns trivial_worst_objective_bound() in NDEBUG mode.
1616  virtual double best_objective_bound() const = 0;
1617  // A trivial objective bound: the worst possible value of the objective,
1618  // which will be +infinity if minimizing and -infinity if maximing.
1620  // Returns the objective value of the best solution found so far.
1621  double objective_value() const;
1622 
1623  // Returns the basis status of a row.
1624  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1625  // Returns the basis status of a constraint.
1626  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1627 
1628  // Checks whether the solution is synchronized with the model, i.e. whether
1629  // the model has changed since the solution was computed last.
1630  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1632  // Checks whether a feasible solution exists. The behavior is similar to
1633  // CheckSolutionIsSynchronized() above.
1634  virtual bool CheckSolutionExists() const;
1635  // Handy shortcut to do both checks above (it is often used).
1638  }
1639  // Checks whether information on the best objective bound exists. The behavior
1640  // is similar to CheckSolutionIsSynchronized() above.
1641  virtual bool CheckBestObjectiveBoundExists() const;
1642 
1643  // ----- Misc -----
1644  // Queries problem type. For simplicity, the distinction between
1645  // continuous and discrete is based on the declaration of the user
1646  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1647  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1648  // the model.
1649  // Returns true if the problem is continuous.
1650  virtual bool IsContinuous() const = 0;
1651  // Returns true if the problem is continuous and linear.
1652  virtual bool IsLP() const = 0;
1653  // Returns true if the problem is discrete and linear.
1654  virtual bool IsMIP() const = 0;
1655 
1656  // Returns the index of the last variable extracted.
1658 
1659  bool variable_is_extracted(int var_index) const {
1660  return solver_->variable_is_extracted_[var_index];
1661  }
1662  void set_variable_as_extracted(int var_index, bool extracted) {
1663  solver_->variable_is_extracted_[var_index] = extracted;
1664  }
1665  bool constraint_is_extracted(int ct_index) const {
1666  return solver_->constraint_is_extracted_[ct_index];
1667  }
1668  void set_constraint_as_extracted(int ct_index, bool extracted) {
1669  solver_->constraint_is_extracted_[ct_index] = extracted;
1670  }
1671 
1672  // Returns the boolean indicating the verbosity of the solver output.
1673  bool quiet() const { return quiet_; }
1674  // Sets the boolean indicating the verbosity of the solver output.
1675  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1676 
1677  // Returns the result status of the last solve.
1680  return result_status_;
1681  }
1682 
1683  // Returns a string describing the underlying solver and its version.
1684  virtual std::string SolverVersion() const = 0;
1685 
1686  // Returns the underlying solver.
1687  virtual void* underlying_solver() = 0;
1688 
1689  // Computes exact condition number. Only available for continuous
1690  // problems and only implemented in GLPK.
1691  virtual double ComputeExactConditionNumber() const;
1692 
1693  // See MPSolver::SetStartingLpBasis().
1694  virtual void SetStartingLpBasis(
1695  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1696  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1697  LOG(FATAL) << "Not supported by this solver.";
1698  }
1699 
1700  virtual bool InterruptSolve() { return false; }
1701 
1702  // See MPSolver::NextSolution() for contract.
1703  virtual bool NextSolution() { return false; }
1704 
1705  // See MPSolver::SetCallback() for details.
1706  virtual void SetCallback(MPCallback* mp_callback) {
1707  LOG(FATAL) << "Callbacks not supported for this solver.";
1708  }
1709 
1710  virtual bool SupportsCallbacks() const { return false; }
1711 
1712  friend class MPSolver;
1713 
1714  // To access the maximize_ bool and the MPSolver.
1715  friend class MPConstraint;
1716  friend class MPObjective;
1717 
1718  protected:
1720  // Indicates whether the model and the solution are synchronized.
1722  // Indicates whether the solve has reached optimality,
1723  // infeasibility, a limit, etc.
1725  // Optimization direction.
1727 
1728  // Index in MPSolver::variables_ of last constraint extracted.
1730  // Index in MPSolver::constraints_ of last variable extracted.
1732 
1733  // The value of the objective function.
1735 
1736  // Boolean indicator for the verbosity of the solver output.
1737  bool quiet_;
1738 
1739  // Index of dummy variable created for empty constraints or the
1740  // objective offset.
1741  static const int kDummyVariableIndex;
1742 
1743  // Extracts model stored in MPSolver.
1745  // Extracts the variables that have not been extracted yet.
1746  virtual void ExtractNewVariables() = 0;
1747  // Extracts the constraints that have not been extracted yet.
1748  virtual void ExtractNewConstraints() = 0;
1749  // Extracts the objective.
1750  virtual void ExtractObjective() = 0;
1751  // Resets the extraction information.
1753  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1754  // MODEL_SYNCHRONIZED. To be used for model changes.
1756 
1757  // Sets parameters common to LP and MIP in the underlying solver.
1759  // Sets MIP specific parameters in the underlying solver.
1761  // Sets all parameters in the underlying solver.
1762  virtual void SetParameters(const MPSolverParameters& param) = 0;
1763  // Sets an unsupported double parameter.
1765  // Sets an unsupported integer parameter.
1768  // Sets a supported double parameter to an unsupported value.
1770  double value);
1771  // Sets a supported integer parameter to an unsupported value.
1773  MPSolverParameters::IntegerParam param, int value);
1774  // Sets each parameter in the underlying solver.
1775  virtual void SetRelativeMipGap(double value) = 0;
1776  virtual void SetPrimalTolerance(double value) = 0;
1777  virtual void SetDualTolerance(double value) = 0;
1778  virtual void SetPresolveMode(int value) = 0;
1779 
1780  // Sets the number of threads to be used by the solver.
1781  virtual absl::Status SetNumThreads(int num_threads);
1782 
1783  // Pass solver specific parameters in text format. The format is
1784  // solver-specific and is the same as the corresponding solver configuration
1785  // file format. Returns true if the operation was successful.
1786  //
1787  // The default implementation of this method stores the parameters in a
1788  // temporary file and calls ReadParameterFile to import the parameter file
1789  // into the solver. Solvers that support passing the parameters directly can
1790  // override this method to skip the temporary file logic.
1792  const std::string& parameters);
1793 
1794  // Reads a solver-specific file of parameters and set them.
1795  // Returns true if there was no errors.
1796  virtual bool ReadParameterFile(const std::string& filename);
1797 
1798  // Returns a file extension like ".tmp", this is needed because some solvers
1799  // require a given extension for the ReadParameterFile() filename and we need
1800  // to know it to generate a temporary parameter file.
1801  virtual std::string ValidFileExtensionForParameterFile() const;
1802 
1803  // Sets the scaling mode.
1804  virtual void SetScalingMode(int value) = 0;
1805  virtual void SetLpAlgorithm(int value) = 0;
1806 };
1807 
1808 } // namespace operations_research
1809 
1810 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
@ XPRESS_LINEAR_PROGRAMMING
int NumConstraints() const
Returns the number of constraints.
bool variable_is_extracted(int var_index) const
void SetMaximization()
Sets the optimization direction to maximize.
@ GLOP_LINEAR_PROGRAMMING
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
static bool LoadGurobiSharedLibrary()
@ LP_ALGORITHM
Algorithm to solve linear programs.
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable on the constraint.
void * underlying_solver()
Advanced usage: returns the underlying solver.
static bool SupportsProblemType(OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
virtual bool IsContinuous() const =0
void Reset()
Advanced usage: resets extracted model to solve from scratch.
virtual bool NextSolution()
friend class XpressInterface
The class for variables of a Mathematical Programming (MP) model.
This mathematical programming (MP) solver class is the main class though which users build and solve ...
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
Sets a double parameter to its default value (default value defined in MPSolverParameters if it exist...
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
Looks up a constraint by name, and returns nullptr if it does not exist.
@ MUST_RELOAD
friend class KnapsackInterface
MPSolverInterface(MPSolver *const solver)
@ PRESOLVE_OFF
Presolve is off.
bool indicator_value() const
MPSolver::ResultStatus result_status_
@ GLPK_MIXED_INTEGER_PROGRAMMING
friend class KnapsackInterface
std::vector< double > ComputeConstraintActivities() const
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms...
friend class CLPInterface
@ DUAL_TOLERANCE
Advanced usage: tolerance for dual feasibility of basic solutions.
int index() const
Returns the index of the variable in the MPSolver::variables_.
static const PresolveValues kDefaultPresolve
void Clear()
Clears all variables and coefficients. Does not clear the bounds.
virtual void SetVariableBounds(int index, double lb, double ub)=0
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
MPSolverResponseStatus
friend class BopInterface
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
@ FIXED_VALUE
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
friend class SatInterface
static bool ParseSolverType(absl::string_view solver_id, OptimizationProblemType *type)
Parses the name of the solver.
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
Shortcuts to the homonymous MPModelProtoExporter methods, via exporting to a MPModelProto with Export...
void SuppressOutput()
Suppresses solver logging.
friend class CplexInterface
The class for constraints of a Mathematical Programming (MP) model.
MPConstraint * MakeRowConstraint(const LinearRange &range, const std::string &name)
As above, but also names the constraint.
virtual bool CheckSolutionExists() const
friend class XpressInterface
friend class CBCInterface
@ FEASIBLE
feasible, or stopped by limit.
ABSL_MUST_USE_RESULT bool NextSolution()
Some solvers (MIP only, not LP) can produce multiple solutions to the problem.
virtual void ExtractNewVariables()=0
friend class CBCInterface
virtual void SetOptimizationDirection(bool maximize)=0
const absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)
double objective_value_
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
MPConstraint * MakeRowConstraint(const std::string &name)
Creates a named constraint with -infinity and +infinity bounds.
@ SCALING_OFF
Scaling is off.
@ CPLEX_MIXED_INTEGER_PROGRAMMING
virtual bool IsMIP() const =0
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable in the objective.
bool minimization() const
Is the optimization direction set to minimize?
int64 time_limit() const
static const double kDefaultRelativeMipGap
double offset() const
Gets the constant term in the objective.
virtual void ClearConstraint(MPConstraint *const constraint)=0
@ AT_LOWER_BOUND
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
MPConstraint * MakeRowConstraint(double lb, double ub)
Creates a linear constraint with given bounds.
void SetLB(double lb)
Sets the lower bound.
friend class KnapsackInterface
@ DUAL
Dual simplex.
void set_variable_as_extracted(int var_index, bool extracted)
@ MODEL_SYNCHRONIZED
static const double kDefaultDualTolerance
void set_time_limit(int64 time_limit_milliseconds)
friend class XpressInterface
Definition: linear_expr.h:84
virtual bool InterruptSolve()
@ SCALING
Advanced usage: enable or disable matrix scaling.
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the objective.
static double infinity()
Infinity.
@ GLPK_LINEAR_PROGRAMMING
friend class GurobiInterface
virtual void * underlying_solver()=0
PresolveValues
For each categorical parameter, enumeration of possible values.
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
static const int kDummyVariableIndex
void SetUB(double ub)
Sets the upper bound.
friend class GLOPInterface
LpAlgorithmValues
LP algorithm to use.
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
friend class SatInterface
const std::string & name() const
Returns the name of the variable.
static const IncrementalityValues kDefaultIncrementality
static const double kUnknownDoubleParamValue
@ RELATIVE_MIP_GAP
Limit for relative MIP gap.
void SetCallback(MPCallback *mp_callback)
virtual void ExtractNewConstraints()=0
double dual_value() const
Advanced usage: returns the dual value of the constraint in the current solution (only available for ...
int last_variable_index_
This class stores parameter settings for LP and MIP solvers.
double ub() const
Returns the upper bound.
virtual bool IsLP() const =0
bool IsMIP() const
An expression of the form:
Definition: linear_expr.h:192
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
bool CheckSolutionIsSynchronized() const
int branching_priority() const
Returns the branching priority, or 0 if it was not set.
virtual void Reset()=0
bool VerifySolution(double tolerance, bool log_errors) const
Advanced usage: Verifies the correctness of the solution.
ResultStatus Solve()
Solves the problem using the default parameter values.
virtual OptimizationProblemType ProblemType() const
Returns the optimization problem type set at construction.
void SetMinimization()
Sets the optimization direction to minimize.
std::string AbslUnparseFlag(MPSolver::OptimizationProblemType solver_type)
virtual bool SupportsCallbacks() const
void set_is_lazy(bool laziness)
Advanced usage: sets the constraint "laziness".
@ CPLEX_LINEAR_PROGRAMMING
SynchronizationStatus
friend class GurobiInterface
double unrounded_solution_value() const
Advanced usage: unrounded solution value.
static const double kDefaultPrimalTolerance
void SetTimeLimit(absl::Duration time_limit)
virtual int64 nodes() const =0
friend class MPVariableSolutionValueTest
std::string GetSolverSpecificParametersAsString() const
virtual void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value)=0
@ INCREMENTALITY
Advanced usage: incrementality from one solve to the next.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the variable in the current solution (only available for ...
const std::string & name() const
Returns the name of the constraint.
MPConstraint(int index, double lb, double ub, const std::string &name, MPSolverInterface *const interface_in)
void SetOffset(double value)
Sets the constant term in the objective.
friend class GLOPInterface
friend class BopInterface
friend class GLOPInterface
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
void SetCommonParameters(const MPSolverParameters &param)
ScalingValues
Advanced usage: Scaling options.
virtual void BranchingPriorityChangedForVariable(int var_index)
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
MPVariable(int index, double lb, double ub, bool integer, const std::string &name, MPSolverInterface *const interface_in)
ResultStatus Solve(const MPSolverParameters &param)
Solves the problem using the specified parameter values.
void Reset()
Sets all parameters to their default value.
void Clear()
Clears the objective (including the optimization direction), all variables and constraints.
void set_dual_value(double dual_value)
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
void ExtractModel()
IncrementalityValues
Advanced usage: Incrementality options.
void set_solution_value(double value)
virtual void SetPresolveMode(int value)=0
bool CheckSolutionIsSynchronizedAndExists() const
@ XPRESS_MIXED_INTEGER_PROGRAMMING
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...
double reduced_cost() const
Advanced usage: returns the reduced cost of the variable in the current solution (only available for ...
int64 nodes() const
Returns the number of branch-and-bound nodes evaluated during the solve.
virtual void AddRowConstraint(MPConstraint *const ct)=0
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the constraint.
friend class SatInterface
@ PRIMAL
Primal simplex.
virtual std::string SolverVersion() const =0
MPSolverParameters()
The constructor sets all parameters to their default value.
static const int kDefaultIntegerParamValue
bool AbslParseFlag(absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
@ SAT_INTEGER_PROGRAMMING
bool OwnsVariable(const MPVariable *var) const
void set_constraint_as_extracted(int ct_index, bool extracted)
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
@ ABNORMAL
abnormal, i.e., error of some kind.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
friend class CLPInterface
void ResetExtractionInformation()
double objective_value() const
static constexpr int64 kUnknownNumberOfNodes
absl::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying solver.
int64 wall_time() const
bool quiet_
LinearExpr models a quantity that is linear in the decision variables (MPVariable) of an optimization...
Definition: linear_expr.h:114
@ INCREMENTALITY_OFF
Start solve from scratch.
friend class SLMInterface
bool maximize_
static MPSolver * CreateSolver(const std::string &name, const std::string &solver_id)
Recommended factory method to create a MPSolver instance, especially in non C++ languages.
static const int kUnknownIntegerParamValue
MPVariable * LookupVariableOrNull(const std::string &var_name) const
Looks up a variable by name, and returns nullptr if it does not exist.
virtual void SetObjectiveOffset(double value)=0
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
virtual int64 iterations() const =0
virtual ~MPSolverInterface()
double lb() const
Returns the lower bound.
friend class CplexInterface
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
friend class SLMInterface
@ SCIP_MIXED_INTEGER_PROGRAMMING
virtual bool CheckBestObjectiveBoundExists() const
virtual void AddVariable(MPVariable *const var)=0
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
virtual void SetCallback(MPCallback *mp_callback)
bool integer() const
Returns the integrality requirement of the variable.
virtual void SetParameters(const MPSolverParameters &param)=0
virtual double best_objective_bound() const =0
absl::Duration TimeLimit() const
virtual double ComputeExactConditionNumber() const
@ GUROBI_MIXED_INTEGER_PROGRAMMING
IntegerParam
Enumeration of parameters that take integer or categorical values.
void MakeVarArray(int nb, double lb, double ub, bool integer, const std::string &name_prefix, std::vector< MPVariable * > *vars)
Creates an array of variables.
@ SCALING_ON
Scaling is on.
std::ostream & operator<<(std::ostream &stream, const LinearExpr &linear_expr)
virtual void SetRelativeMipGap(double value)=0
friend class SCIPInterface
bool SupportsCallbacks() const
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
@ CBC_MIXED_INTEGER_PROGRAMMING
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
friend class GurobiInterface
void SetMIPParameters(const MPSolverParameters &param)
virtual bool ReadParameterFile(const std::string &filename)
absl::Status LoadSolutionFromProto(const MPSolutionResponse &response, double tolerance=kDefaultPrimalTolerance)
Load a solution encoded in a protocol buffer onto this solver for easy access via the MPSolver interf...
friend class GLPKInterface
MPObjective * MutableObjective()
Returns the mutable objective object.
virtual void SetScalingMode(int value)=0
@ AT_UPPER_BOUND
absl::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
@ PRESOLVE
Advanced usage: presolve mode.
void EnableOutput()
Enables solver logging.
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
const MPObjective & Objective() const
Returns the objective object.
@ OPTIMAL
optimal.
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
friend class CBCInterface
static void SetGurobiLibraryPath(const std::string &full_library_path)
friend class SCIPInterface
ResultStatus
The status of solving the problem.
MPConstraint * MakeRowConstraint(const LinearRange &range)
Creates a constraint owned by MPSolver enforcing: range.lower_bound() <= range.linear_expr() <= range...
friend class XpressInterface
OptimizationProblemType
The type of problems (LP or MIP) that will be solved and the underlying solver (GLOP,...
double ub() const
Returns the upper bound.
virtual void ExtractObjective()=0
const std::string & Name() const
Returns the name of the model set at construction.
@ FREE
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
Sets an integer parameter to its default value (default value defined in MPSolverParameters if it exi...
@ MODEL_INVALID
the model is trivially invalid (NaN coefficients, etc).
void SetUB(double ub)
Sets the upper bound.
virtual std::string ValidFileExtensionForParameterFile() const
const std::vector< MPConstraint * > & constraints() const
Returns the array of constraints handled by the MPSolver.
virtual void SetDualTolerance(double value)=0
friend class CLPInterface
void Write(const std::string &file_name)
Writes the model using the solver internal write function.
virtual void SetConstraintBounds(int index, double lb, double ub)=0
bool maximization() const
Is the optimization direction set to maximize?
friend class SatInterface
bool MPSolverResponseStatusIsRpcError(MPSolverResponseStatus status)
friend class SLMInterface
int GetNumThreads() const
Returns the number of threads to be used during solve.
friend class GLPKInterface
@ BARRIER
Barrier algorithm.
double Value() const
Returns the objective value of the best solution found so far.
virtual void SetLpAlgorithm(int value)=0
friend class GurobiInterface
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the constraint.
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...
@ BOP_INTEGER_PROGRAMMING
MPVariable * MakeVar(double lb, double ub, bool integer, const std::string &name)
Creates a variable with the given bounds, integrality requirement and name.
virtual void SetPrimalTolerance(double value)=0
A class to express a linear objective.
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
int NumVariables() const
Returns the number of variables.
@ PRIMAL_TOLERANCE
Advanced usage: tolerance for primal feasibility of basic solutions.
absl::Duration DurationSinceConstruction() const
friend class CplexInterface
double time_limit_in_secs() const
friend class SCIPInterface
MPConstraint * MakeRowConstraint(double lb, double ub, const std::string &name)
Creates a named constraint with given bounds.
std::string SolverVersion() const
Returns a string describing the underlying solver and its version.
MPSolver *const solver_
friend class GLPKInterface
friend class BopInterface
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
static const double kDefaultDoubleParamValue
friend class SLMInterface
@ SOLUTION_SYNCHRONIZED
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
friend class CLPInterface
const MPVariable * indicator_variable() const
void set_quiet(bool quiet_value)
friend class SCIPInterface
bool constraint_is_extracted(int ct_index) const
double ComputeExactConditionNumber() const
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(i...
@ INCREMENTALITY_ON
Reuse results from previous solve as much as the underlying solver allows.
constexpr double kDefaultPrimalTolerance
virtual void ClearObjective()=0
DoubleParam
Enumeration of parameters that take continuous values.
double solution_value() const
Returns the value of the variable in the current solution.
bool OutputIsEnabled() const
Controls (or queries) the amount of output produced by the underlying solver.
const std::vector< MPVariable * > & variables() const
Returns the array of variables handled by the MPSolver.
virtual absl::Status SetNumThreads(int num_threads)
virtual absl::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request)
static constexpr int64 kUnknownNumberOfIterations
static bool ParseAndCheckSupportForProblemType(const std::string &solver_id)
Parses the name of the solver.
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
void SetBranchingPriority(int priority)
Advanced usage: Certain MIP solvers (e.g.
void SetLB(double lb)
Sets the lower bound.
@ KNAPSACK_MIXED_INTEGER_PROGRAMMING
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
Sets a hint for solution.
virtual void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient)=0
void set_reduced_cost(double reduced_cost)
friend class CBCInterface
MPSolver::ResultStatus result_status() const
int last_constraint_index_
@ PRESOLVE_ON
Presolve is on.
friend class KnapsackInterface
double BestBound() const
Returns the best objective bound.
double trivial_worst_objective_bound() const
void Clear()
Clears the offset, all variables and coefficients, and the optimization direction.
double lb() const
Returns the lower bound.
static OptimizationProblemType ParseSolverTypeOrDie(const std::string &solver_id)
Parses the name of the solver and returns the correct optimization type or dies.
bool quiet() const
friend class GLOPInterface
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
Advanced usage: Incrementality.
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
virtual ~MPSolver()
friend class BopInterface
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
virtual bool AddIndicatorConstraint(MPConstraint *const ct)
@ INFEASIBLE
proven infeasible.
int last_variable_index() const
friend class CplexInterface
@ GUROBI_LINEAR_PROGRAMMING
int64 iterations() const
Returns the number of simplex iterations.
@ CLP_LINEAR_PROGRAMMING
virtual void Write(const std::string &filename)
static void SolveWithProto(const MPModelRequest &model_request, MPSolutionResponse *response)
Solves the model encoded by a MPModelRequest protocol buffer and fills the solution encoded as a MPSo...
MPConstraint * MakeRowConstraint()
Creates a constraint with -infinity and +infinity bounds.
SynchronizationStatus sync_status_
@ BASIC
void InvalidateSolutionSynchronization()
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
virtual void SetVariableInteger(int index, bool integer)=0
@ UNBOUNDED
proven unbounded.
@ NOT_SOLVED
not been solved yet.
friend class GLPKInterface