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/strings/match.h"
147 #include "absl/strings/str_format.h"
148 #include "absl/types/optional.h"
149 #include "ortools/base/commandlineflags.h"
150 #include "ortools/base/integral_types.h"
151 #include "ortools/base/logging.h"
152 #include "ortools/base/macros.h"
153 #include "ortools/base/status.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 
174 class MPSolver {
175  public:
183 #ifdef USE_CLP
184  CLP_LINEAR_PROGRAMMING = 0,
186 #endif
187 #ifdef USE_GLPK
188  GLPK_LINEAR_PROGRAMMING = 1,
190 #endif
193 #ifdef USE_GUROBI
194  GUROBI_LINEAR_PROGRAMMING = 6,
196 #endif
197 #ifdef USE_CPLEX
198  CPLEX_LINEAR_PROGRAMMING = 10,
200 #endif
201 
202 // Integer programming problems.
203 #ifdef USE_SCIP
204  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
206 #endif
207 #ifdef USE_GLPK
208  GLPK_MIXED_INTEGER_PROGRAMMING = 4,
210 #endif
211 #ifdef USE_CBC
214 #endif
215 #if defined(USE_GUROBI)
216  GUROBI_MIXED_INTEGER_PROGRAMMING = 7,
218 #endif
219 #if defined(USE_CPLEX)
220  CPLEX_MIXED_INTEGER_PROGRAMMING = 11,
222 #endif
229 #if defined(USE_XPRESS)
230  XPRESS_LINEAR_PROGRAMMING = 101,
231  XPRESS_MIXED_INTEGER_PROGRAMMING = 102,
232 #endif
233  };
234 
236  MPSolver(const std::string& name, OptimizationProblemType problem_type);
237  virtual ~MPSolver();
238 
243  static bool SupportsProblemType(OptimizationProblemType problem_type);
244 
249  static bool ParseSolverType(absl::string_view solver,
251 
252  bool IsMIP() const;
253 
255  const std::string& Name() const {
256  return name_; // Set at construction.
257  }
258 
261  return problem_type_; // Set at construction.
262  }
263 
269  void Clear();
270 
272  int NumVariables() const { return variables_.size(); }
273 
278  const std::vector<MPVariable*>& variables() const { return variables_; }
279 
285  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
286 
294  MPVariable* MakeVar(double lb, double ub, bool integer,
295  const std::string& name);
296 
298  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
299 
301  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
302 
304  MPVariable* MakeBoolVar(const std::string& name);
305 
320  void MakeVarArray(int nb, double lb, double ub, bool integer,
321  const std::string& name_prefix,
322  std::vector<MPVariable*>* vars);
323 
325  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
326  std::vector<MPVariable*>* vars);
327 
329  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
330  std::vector<MPVariable*>* vars);
331 
333  void MakeBoolVarArray(int nb, const std::string& name,
334  std::vector<MPVariable*>* vars);
335 
337  int NumConstraints() const { return constraints_.size(); }
338 
344  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
345 
354  const std::string& constraint_name) const;
355 
364  MPConstraint* MakeRowConstraint(double lb, double ub);
365 
368 
370  MPConstraint* MakeRowConstraint(double lb, double ub,
371  const std::string& name);
372 
374  MPConstraint* MakeRowConstraint(const std::string& name);
375 
381 
384  const std::string& name);
385 
392  const MPObjective& Objective() const { return *objective_; }
393 
395  MPObjective* MutableObjective() { return objective_.get(); }
396 
418  };
419 
422 
424  ResultStatus Solve(const MPSolverParameters& param);
425 
430  void Write(const std::string& file_name);
431 
438  std::vector<double> ComputeConstraintActivities() const;
439 
458  bool VerifySolution(double tolerance, bool log_errors) const;
459 
468  void Reset();
469 
477  bool InterruptSolve();
478 
487  std::string* error_message);
496  const MPModelProto& input_model, std::string* error_message);
497 
499  void FillSolutionResponseProto(MPSolutionResponse* response) const;
500 
510  static void SolveWithProto(const MPModelRequest& model_request,
511  MPSolutionResponse* response);
512 
514  void ExportModelToProto(MPModelProto* output_model) const;
515 
547  util::Status LoadSolutionFromProto(
548  const MPSolutionResponse& response,
549  double tolerance = kDefaultPrimalTolerance);
550 
555  util::Status ClampSolutionWithinBounds();
556 
563  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
564  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
565  std::string* model_str) const;
566 
577  util::Status SetNumThreads(int num_threads);
578 
580  int GetNumThreads() const { return num_threads_; }
581 
588  bool SetSolverSpecificParametersAsString(const std::string& parameters);
590  return solver_specific_parameter_string_;
591  }
592 
606  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
607 
612  enum BasisStatus {
613  FREE = 0,
618  };
619 
631  void SetStartingLpBasis(
632  const std::vector<MPSolver::BasisStatus>& variable_statuses,
633  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
634 
640  static double infinity() { return std::numeric_limits<double>::infinity(); }
641 
650  bool OutputIsEnabled() const;
651 
653  void EnableOutput();
654 
656  void SuppressOutput();
657 
658  absl::Duration TimeLimit() const { return time_limit_; }
659  void SetTimeLimit(absl::Duration time_limit) {
660  DCHECK_GE(time_limit, absl::ZeroDuration());
661  time_limit_ = time_limit;
662  }
663 
664  absl::Duration DurationSinceConstruction() const {
665  return absl::Now() - construction_time_;
666  }
667 
669  int64 iterations() const;
670 
676  int64 nodes() const;
677 
679  std::string SolverVersion() const;
680 
694  void* underlying_solver();
695 
719  double ComputeExactConditionNumber() const;
720 
735  ABSL_MUST_USE_RESULT bool NextSolution();
736 
737  // Does not take ownership of "mp_callback".
738  //
739  // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
740  // SCIP does not support suggesting a heuristic solution in the callback.
741  //
742  // See go/mpsolver-callbacks for additional documentation.
743  void SetCallback(MPCallback* mp_callback);
744  bool SupportsCallbacks() const;
745 
746  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
747  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
748  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
749  int64 time_limit() const {
750  return time_limit_ == absl::InfiniteDuration()
751  ? 0
752  : absl::ToInt64Milliseconds(time_limit_);
753  }
754  void set_time_limit(int64 time_limit_milliseconds) {
755  SetTimeLimit(time_limit_milliseconds == 0
756  ? absl::InfiniteDuration()
757  : absl::Milliseconds(time_limit_milliseconds));
758  }
759  double time_limit_in_secs() const {
760  return static_cast<double>(time_limit()) / 1000.0;
761  }
762 
763  // DEPRECATED: Use DurationSinceConstruction() instead.
764  int64 wall_time() const {
765  return absl::ToInt64Milliseconds(DurationSinceConstruction());
766  }
767 
768  friend class GLPKInterface;
769  friend class CLPInterface;
770  friend class CBCInterface;
771  friend class SCIPInterface;
772  friend class GurobiInterface;
773  friend class CplexInterface;
774  friend class XpressInterface;
775  friend class SLMInterface;
776  friend class MPSolverInterface;
777  friend class GLOPInterface;
778  friend class BopInterface;
779  friend class SatInterface;
780  friend class KnapsackInterface;
781 
782  // Debugging: verify that the given MPVariable* belongs to this solver.
783  bool OwnsVariable(const MPVariable* var) const;
784 
785  private:
786  // Computes the size of the constraint with the largest number of
787  // coefficients with index in [min_constraint_index,
788  // max_constraint_index)
789  int ComputeMaxConstraintSize(int min_constraint_index,
790  int max_constraint_index) const;
791 
792  // Returns true if the model has constraints with lower bound > upper bound.
793  bool HasInfeasibleConstraints() const;
794 
795  // Returns true if the model has at least 1 integer variable.
796  bool HasIntegerVariables() const;
797 
798  // Generates the map from variable names to their indices.
799  void GenerateVariableNameIndex() const;
800 
801  // Generates the map from constraint names to their indices.
802  void GenerateConstraintNameIndex() const;
803 
804  // The name of the linear programming problem.
805  const std::string name_;
806 
807  // The type of the linear programming problem.
808  const OptimizationProblemType problem_type_;
809 
810  // The solver interface.
811  std::unique_ptr<MPSolverInterface> interface_;
812 
813  // The vector of variables in the problem.
814  std::vector<MPVariable*> variables_;
815  // A map from a variable's name to its index in variables_.
816  mutable absl::optional<absl::flat_hash_map<std::string, int> >
817  variable_name_to_index_;
818  // Whether variables have been extracted to the underlying interface.
819  std::vector<bool> variable_is_extracted_;
820 
821  // The vector of constraints in the problem.
822  std::vector<MPConstraint*> constraints_;
823  // A map from a constraint's name to its index in constraints_.
824  mutable absl::optional<absl::flat_hash_map<std::string, int> >
825  constraint_name_to_index_;
826  // Whether constraints have been extracted to the underlying interface.
827  std::vector<bool> constraint_is_extracted_;
828 
829  // The linear objective function.
830  std::unique_ptr<MPObjective> objective_;
831 
832  // Initial values for all or some of the problem variables that can be
833  // exploited as a starting hint by a solver.
834  //
835  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
836  //
837  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
838  // hint is provided and a std::vector<double> for the hint value.
839  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
840 
841  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
842 
843  const absl::Time construction_time_;
844 
845  // Permanent storage for the number of threads.
846  int num_threads_ = 1;
847 
848  // Permanent storage for SetSolverSpecificParametersAsString().
849  std::string solver_specific_parameter_string_;
850 
851  MPSolverResponseStatus LoadModelFromProtoInternal(
852  const MPModelProto& input_model, bool clear_names,
853  bool check_model_validity, std::string* error_message);
854 
855  DISALLOW_COPY_AND_ASSIGN(MPSolver);
856 };
857 
858 const absl::string_view ToString(
859  MPSolver::OptimizationProblemType optimization_problem_type);
860 
861 inline std::ostream& operator<<(
862  std::ostream& os,
863  MPSolver::OptimizationProblemType optimization_problem_type) {
864  return os << ToString(optimization_problem_type);
865 }
866 
867 inline std::ostream& operator<<(std::ostream& os,
868  MPSolver::ResultStatus status) {
869  return os << ProtoEnumToString<MPSolverResponseStatus>(
870  static_cast<MPSolverResponseStatus>(status));
871 }
872 
873 bool AbslParseFlag(absl::string_view text,
875  std::string* error);
876 
877 inline std::string AbslUnparseFlag(
878  MPSolver::OptimizationProblemType solver_type) {
879  return std::string(ToString(solver_type));
880 }
881 
883 class MPObjective {
884  public:
889  void Clear();
890 
897  void SetCoefficient(const MPVariable* const var, double coeff);
898 
904  double GetCoefficient(const MPVariable* const var) const;
905 
911  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
912  return coefficients_;
913  }
914 
916  void SetOffset(double value);
917 
919  double offset() const { return offset_; }
920 
925  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
926 
928  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
929  OptimizeLinearExpr(linear_expr, true);
930  }
932  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
933  OptimizeLinearExpr(linear_expr, false);
934  }
935 
937  void AddLinearExpr(const LinearExpr& linear_expr);
938 
940  void SetOptimizationDirection(bool maximize);
941 
944 
947 
949  bool maximization() const;
950 
952  bool minimization() const;
953 
965  double Value() const;
966 
973  double BestBound() const;
974 
975  private:
976  friend class MPSolver;
977  friend class MPSolverInterface;
978  friend class CBCInterface;
979  friend class CLPInterface;
980  friend class GLPKInterface;
981  friend class SCIPInterface;
982  friend class SLMInterface;
983  friend class GurobiInterface;
984  friend class CplexInterface;
985  friend class XpressInterface;
986  friend class GLOPInterface;
987  friend class BopInterface;
988  friend class SatInterface;
989  friend class KnapsackInterface;
990 
991  // Constructor. An objective points to a single MPSolverInterface
992  // that is specified in the constructor. An objective cannot belong
993  // to several models.
994  // At construction, an MPObjective has no terms (which is equivalent
995  // on having a coefficient of 0 for all variables), and an offset of 0.
996  explicit MPObjective(MPSolverInterface* const interface_in)
997  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
998 
999  MPSolverInterface* const interface_;
1000 
1001  // Mapping var -> coefficient.
1002  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1003  // Constant term.
1004  double offset_;
1005 
1006  DISALLOW_COPY_AND_ASSIGN(MPObjective);
1007 };
1008 
1010 class MPVariable {
1011  public:
1013  const std::string& name() const { return name_; }
1014 
1016  void SetInteger(bool integer);
1017 
1019  bool integer() const { return integer_; }
1020 
1028  double solution_value() const;
1029 
1031  int index() const { return index_; }
1032 
1034  double lb() const { return lb_; }
1035 
1037  double ub() const { return ub_; }
1038 
1040  void SetLB(double lb) { SetBounds(lb, ub_); }
1041 
1043  void SetUB(double ub) { SetBounds(lb_, ub); }
1044 
1046  void SetBounds(double lb, double ub);
1047 
1054  double unrounded_solution_value() const;
1055 
1060  double reduced_cost() const;
1061 
1069 
1080  int branching_priority() const { return branching_priority_; }
1081  void SetBranchingPriority(int priority);
1082 
1083  protected:
1084  friend class MPSolver;
1085  friend class MPSolverInterface;
1086  friend class CBCInterface;
1087  friend class CLPInterface;
1088  friend class GLPKInterface;
1089  friend class SCIPInterface;
1090  friend class SLMInterface;
1091  friend class GurobiInterface;
1092  friend class CplexInterface;
1093  friend class XpressInterface;
1094  friend class GLOPInterface;
1096  friend class BopInterface;
1097  friend class SatInterface;
1098  friend class KnapsackInterface;
1099 
1100  // Constructor. A variable points to a single MPSolverInterface that
1101  // is specified in the constructor. A variable cannot belong to
1102  // several models.
1103  MPVariable(int index, double lb, double ub, bool integer,
1104  const std::string& name, MPSolverInterface* const interface_in)
1105  : index_(index),
1106  lb_(lb),
1107  ub_(ub),
1108  integer_(integer),
1109  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1110  solution_value_(0.0),
1111  reduced_cost_(0.0),
1112  interface_(interface_in) {}
1113 
1114  void set_solution_value(double value) { solution_value_ = value; }
1115  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1116 
1117  private:
1118  const int index_;
1119  double lb_;
1120  double ub_;
1121  bool integer_;
1122  const std::string name_;
1123  double solution_value_;
1124  double reduced_cost_;
1125  int branching_priority_ = 0;
1126  MPSolverInterface* const interface_;
1127  DISALLOW_COPY_AND_ASSIGN(MPVariable);
1128 };
1129 
1136  public:
1138  const std::string& name() const { return name_; }
1139 
1141  void Clear();
1142 
1149  void SetCoefficient(const MPVariable* const var, double coeff);
1150 
1155  double GetCoefficient(const MPVariable* const var) const;
1156 
1162  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1163  return coefficients_;
1164  }
1165 
1167  double lb() const { return lb_; }
1168 
1170  double ub() const { return ub_; }
1171 
1173  void SetLB(double lb) { SetBounds(lb, ub_); }
1174 
1176  void SetUB(double ub) { SetBounds(lb_, ub); }
1177 
1179  void SetBounds(double lb, double ub);
1180 
1182  bool is_lazy() const { return is_lazy_; }
1183 
1197  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1198 
1199  const MPVariable* indicator_variable() const { return indicator_variable_; }
1200  bool indicator_value() const { return indicator_value_; }
1201 
1203  int index() const { return index_; }
1204 
1209  double dual_value() const;
1210 
1224 
1225  protected:
1226  friend class MPSolver;
1227  friend class MPSolverInterface;
1228  friend class CBCInterface;
1229  friend class CLPInterface;
1230  friend class GLPKInterface;
1231  friend class SCIPInterface;
1232  friend class SLMInterface;
1233  friend class GurobiInterface;
1234  friend class CplexInterface;
1235  friend class XpressInterface;
1236  friend class GLOPInterface;
1237  friend class BopInterface;
1238  friend class SatInterface;
1239  friend class KnapsackInterface;
1240 
1241  // Constructor. A constraint points to a single MPSolverInterface
1242  // that is specified in the constructor. A constraint cannot belong
1243  // to several models.
1244  MPConstraint(int index, double lb, double ub, const std::string& name,
1245  MPSolverInterface* const interface_in)
1246  : coefficients_(1),
1247  index_(index),
1248  lb_(lb),
1249  ub_(ub),
1250  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1251  is_lazy_(false),
1252  indicator_variable_(nullptr),
1253  dual_value_(0.0),
1254  interface_(interface_in) {}
1255 
1256  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1257 
1258  private:
1259  // Returns true if the constraint contains variables that have not
1260  // been extracted yet.
1261  bool ContainsNewVariables();
1262 
1263  // Mapping var -> coefficient.
1264  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1265 
1266  const int index_; // See index().
1267 
1268  // The lower bound for the linear constraint.
1269  double lb_;
1270 
1271  // The upper bound for the linear constraint.
1272  double ub_;
1273 
1274  // Name.
1275  const std::string name_;
1276 
1277  // True if the constraint is "lazy", i.e. the constraint is added to the
1278  // underlying Linear Programming solver only if it is violated.
1279  // By default this parameter is 'false'.
1280  bool is_lazy_;
1281 
1282  // If given, this constraint is only active if `indicator_variable_`'s value
1283  // is equal to `indicator_value_`.
1284  const MPVariable* indicator_variable_;
1285  bool indicator_value_;
1286 
1287  double dual_value_;
1288  MPSolverInterface* const interface_;
1289  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1290 };
1291 
1319  public:
1324 
1334  };
1335 
1339  PRESOLVE = 1000,
1345  SCALING = 1003
1346  };
1347 
1354  };
1355 
1359  DUAL = 10,
1361  PRIMAL = 11,
1363  BARRIER = 12
1364  };
1365 
1370 
1376  };
1377 
1384  };
1385 
1386  // Placeholder value to indicate that a parameter is set to
1387  // the default value defined in the wrapper.
1388  static const double kDefaultDoubleParamValue;
1389  static const int kDefaultIntegerParamValue;
1390 
1391  // Placeholder value to indicate that a parameter is unknown.
1392  static const double kUnknownDoubleParamValue;
1393  static const int kUnknownIntegerParamValue;
1394 
1395  // Default values for parameters. Only parameters that define the
1396  // properties of the solution returned need to have a default value
1397  // (that is the same for all solvers). You can also define a default
1398  // value for performance parameters when you are confident it is a
1399  // good choice (example: always turn presolve on).
1400  static const double kDefaultRelativeMipGap;
1401  static const double kDefaultPrimalTolerance;
1402  static const double kDefaultDualTolerance;
1405 
1408 
1410  void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1411 
1413  void SetIntegerParam(MPSolverParameters::IntegerParam param, int value);
1414 
1421 
1428 
1430  void Reset();
1431 
1433  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1434 
1437 
1438  private:
1439  // Parameter value for each parameter.
1440  // @see DoubleParam
1441  // @see IntegerParam
1442  double relative_mip_gap_value_;
1443  double primal_tolerance_value_;
1444  double dual_tolerance_value_;
1445  int presolve_value_;
1446  int scaling_value_;
1447  int lp_algorithm_value_;
1448  int incrementality_value_;
1449 
1450  // Boolean value indicating whether each parameter is set to the
1451  // solver's default value. Only parameters for which the wrapper
1452  // does not define a default value need such an indicator.
1453  bool lp_algorithm_is_default_;
1454 
1455  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1456 };
1457 
1458 // Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1459 // error when happening on the linear solver stubby server, see
1460 // ./linear_solver_service.proto.
1461 // Note that RPC errors forbid to carry a response to the client, who can only
1462 // see the RPC error itself (error code + error message).
1464 
1465 // This class wraps the actual mathematical programming solvers. Each
1466 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1467 // derives from this abstract class. This class is never directly
1468 // accessed by the user.
1469 // @see glop_interface.cc
1470 // @see cbc_interface.cc
1471 // @see clp_interface.cc
1472 // @see glpk_interface.cc
1473 // @see scip_interface.cc
1475  public:
1477  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1478  // sync for the model nor for the solution.
1480  // The underlying solver and MPSolver are in sync for the model
1481  // but not for the solution: the model has changed since the
1482  // solution was computed last.
1484  // The underlying solver and MPSolver are in sync for the model and
1485  // the solution.
1487  };
1488 
1489  // When the underlying solver does not provide the number of simplex
1490  // iterations.
1491  static const int64 kUnknownNumberOfIterations = -1;
1492  // When the underlying solver does not provide the number of
1493  // branch-and-bound nodes.
1494  static const int64 kUnknownNumberOfNodes = -1;
1495 
1496  // Constructor. The user will access the MPSolverInterface through the
1497  // MPSolver passed as argument.
1498  explicit MPSolverInterface(MPSolver* const solver);
1499  virtual ~MPSolverInterface();
1500 
1501  // ----- Solve -----
1502  // Solves problem with specified parameter values. Returns true if the
1503  // solution is optimal.
1504  virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1505 
1506  // Directly solves a MPModelRequest, bypassing the MPSolver data structures
1507  // entirely. Returns {} (eg. absl::nullopt) if the feature is not supported by
1508  // the underlying solver.
1509  virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1510  const MPModelRequest& request) {
1511  return absl::nullopt;
1512  }
1513 
1514  // Writes the model using the solver internal write function. Currently only
1515  // available for GurobiInterface.
1516  virtual void Write(const std::string& filename);
1517 
1518  // ----- Model modifications and extraction -----
1519  // Resets extracted model.
1520  virtual void Reset() = 0;
1521 
1522  // Sets the optimization direction (min/max).
1523  virtual void SetOptimizationDirection(bool maximize) = 0;
1524 
1525  // Modifies bounds of an extracted variable.
1526  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1527 
1528  // Modifies integrality of an extracted variable.
1529  virtual void SetVariableInteger(int index, bool integer) = 0;
1530 
1531  // Modify bounds of an extracted variable.
1532  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1533 
1534  // Adds a linear constraint.
1535  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1536 
1537  // Adds an indicator constraint. Returns true if the feature is supported by
1538  // the underlying solver.
1539  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1540  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1541  return false;
1542  }
1543 
1544  // Add a variable.
1545  virtual void AddVariable(MPVariable* const var) = 0;
1546 
1547  // Changes a coefficient in a constraint.
1548  virtual void SetCoefficient(MPConstraint* const constraint,
1549  const MPVariable* const variable,
1550  double new_value, double old_value) = 0;
1551 
1552  // Clears a constraint from all its terms.
1553  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1554 
1555  // Changes a coefficient in the linear objective.
1556  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1557  double coefficient) = 0;
1558 
1559  // Changes the constant term in the linear objective.
1560  virtual void SetObjectiveOffset(double value) = 0;
1561 
1562  // Clears the objective from all its terms.
1563  virtual void ClearObjective() = 0;
1564 
1565  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1566  // ------ Query statistics on the solution and the solve ------
1567  // Returns the number of simplex iterations. The problem must be discrete,
1568  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1569  virtual int64 iterations() const = 0;
1570  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1571  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1572  virtual int64 nodes() const = 0;
1573  // Returns the best objective bound. The problem must be discrete, otherwise
1574  // it crashes, or returns trivial_worst_objective_bound() in NDEBUG mode.
1575  virtual double best_objective_bound() const = 0;
1576  // A trivial objective bound: the worst possible value of the objective,
1577  // which will be +infinity if minimizing and -infinity if maximing.
1578  double trivial_worst_objective_bound() const;
1579  // Returns the objective value of the best solution found so far.
1580  double objective_value() const;
1581 
1582  // Returns the basis status of a row.
1583  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1584  // Returns the basis status of a constraint.
1585  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1586 
1587  // Checks whether the solution is synchronized with the model, i.e. whether
1588  // the model has changed since the solution was computed last.
1589  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1590  bool CheckSolutionIsSynchronized() const;
1591  // Checks whether a feasible solution exists. The behavior is similar to
1592  // CheckSolutionIsSynchronized() above.
1593  virtual bool CheckSolutionExists() const;
1594  // Handy shortcut to do both checks above (it is often used).
1597  }
1598  // Checks whether information on the best objective bound exists. The behavior
1599  // is similar to CheckSolutionIsSynchronized() above.
1600  virtual bool CheckBestObjectiveBoundExists() const;
1601 
1602  // ----- Misc -----
1603  // Queries problem type. For simplicity, the distinction between
1604  // continuous and discrete is based on the declaration of the user
1605  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1606  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1607  // the model.
1608  // Returns true if the problem is continuous.
1609  virtual bool IsContinuous() const = 0;
1610  // Returns true if the problem is continuous and linear.
1611  virtual bool IsLP() const = 0;
1612  // Returns true if the problem is discrete and linear.
1613  virtual bool IsMIP() const = 0;
1614 
1615  // Returns the index of the last variable extracted.
1617 
1618  bool variable_is_extracted(int var_index) const {
1619  return solver_->variable_is_extracted_[var_index];
1620  }
1621  void set_variable_as_extracted(int var_index, bool extracted) {
1622  solver_->variable_is_extracted_[var_index] = extracted;
1623  }
1624  bool constraint_is_extracted(int ct_index) const {
1625  return solver_->constraint_is_extracted_[ct_index];
1626  }
1627  void set_constraint_as_extracted(int ct_index, bool extracted) {
1628  solver_->constraint_is_extracted_[ct_index] = extracted;
1629  }
1630 
1631  // Returns the boolean indicating the verbosity of the solver output.
1632  bool quiet() const { return quiet_; }
1633  // Sets the boolean indicating the verbosity of the solver output.
1634  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1635 
1636  // Returns the result status of the last solve.
1639  return result_status_;
1640  }
1641 
1642  // Returns a string describing the underlying solver and its version.
1643  virtual std::string SolverVersion() const = 0;
1644 
1645  // Returns the underlying solver.
1646  virtual void* underlying_solver() = 0;
1647 
1648  // Computes exact condition number. Only available for continuous
1649  // problems and only implemented in GLPK.
1650  virtual double ComputeExactConditionNumber() const;
1651 
1652  // See MPSolver::SetStartingLpBasis().
1653  virtual void SetStartingLpBasis(
1654  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1655  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1656  LOG(FATAL) << "Not supported by this solver.";
1657  }
1658 
1659  virtual bool InterruptSolve() { return false; }
1660 
1661  // See MPSolver::NextSolution() for contract.
1662  virtual bool NextSolution() { return false; }
1663 
1664  // See MPSolver::SetCallback() for details.
1665  virtual void SetCallback(MPCallback* mp_callback) {
1666  LOG(FATAL) << "Callbacks not supported for this solver.";
1667  }
1668 
1669  virtual bool SupportsCallbacks() const { return false; }
1670 
1671  friend class MPSolver;
1672 
1673  // To access the maximize_ bool and the MPSolver.
1674  friend class MPConstraint;
1675  friend class MPObjective;
1676 
1677  protected:
1679  // Indicates whether the model and the solution are synchronized.
1681  // Indicates whether the solve has reached optimality,
1682  // infeasibility, a limit, etc.
1684  // Optimization direction.
1686 
1687  // Index in MPSolver::variables_ of last constraint extracted.
1689  // Index in MPSolver::constraints_ of last variable extracted.
1691 
1692  // The value of the objective function.
1694 
1695  // Boolean indicator for the verbosity of the solver output.
1696  bool quiet_;
1697 
1698  // Index of dummy variable created for empty constraints or the
1699  // objective offset.
1700  static const int kDummyVariableIndex;
1701 
1702  // Extracts model stored in MPSolver.
1703  void ExtractModel();
1704  // Extracts the variables that have not been extracted yet.
1705  virtual void ExtractNewVariables() = 0;
1706  // Extracts the constraints that have not been extracted yet.
1707  virtual void ExtractNewConstraints() = 0;
1708  // Extracts the objective.
1709  virtual void ExtractObjective() = 0;
1710  // Resets the extraction information.
1712  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1713  // MODEL_SYNCHRONIZED. To be used for model changes.
1715 
1716  // Sets parameters common to LP and MIP in the underlying solver.
1717  void SetCommonParameters(const MPSolverParameters& param);
1718  // Sets MIP specific parameters in the underlying solver.
1719  void SetMIPParameters(const MPSolverParameters& param);
1720  // Sets all parameters in the underlying solver.
1721  virtual void SetParameters(const MPSolverParameters& param) = 0;
1722  // Sets an unsupported double parameter.
1724  // Sets an unsupported integer parameter.
1725  virtual void SetUnsupportedIntegerParam(
1727  // Sets a supported double parameter to an unsupported value.
1729  double value);
1730  // Sets a supported integer parameter to an unsupported value.
1731  virtual void SetIntegerParamToUnsupportedValue(
1732  MPSolverParameters::IntegerParam param, int value);
1733  // Sets each parameter in the underlying solver.
1734  virtual void SetRelativeMipGap(double value) = 0;
1735  virtual void SetPrimalTolerance(double value) = 0;
1736  virtual void SetDualTolerance(double value) = 0;
1737  virtual void SetPresolveMode(int value) = 0;
1738 
1739  // Sets the number of threads to be used by the solver.
1740  virtual util::Status SetNumThreads(int num_threads);
1741 
1742  // Pass solver specific parameters in text format. The format is
1743  // solver-specific and is the same as the corresponding solver configuration
1744  // file format. Returns true if the operation was successful.
1745  //
1746  // The default implementation of this method stores the parameters in a
1747  // temporary file and calls ReadParameterFile to import the parameter file
1748  // into the solver. Solvers that support passing the parameters directly can
1749  // override this method to skip the temporary file logic.
1751  const std::string& parameters);
1752 
1753  // Reads a solver-specific file of parameters and set them.
1754  // Returns true if there was no errors.
1755  virtual bool ReadParameterFile(const std::string& filename);
1756 
1757  // Returns a file extension like ".tmp", this is needed because some solvers
1758  // require a given extension for the ReadParameterFile() filename and we need
1759  // to know it to generate a temporary parameter file.
1760  virtual std::string ValidFileExtensionForParameterFile() const;
1761 
1762  // Sets the scaling mode.
1763  virtual void SetScalingMode(int value) = 0;
1764  virtual void SetLpAlgorithm(int value) = 0;
1765 };
1766 
1767 } // namespace operations_research
1768 
1769 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
int NumConstraints() const
Returns the number of constraints.
bool variable_is_extracted(int var_index) const
void SetMaximization()
Sets the optimization direction to maximize.
Linear Programming solver using GLOP (Recommended solver).
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
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.
friend class KnapsackInterface
MPSolverInterface(MPSolver *const solver)
Presolve is off.
bool indicator_value() const
MPSolver::ResultStatus result_status_
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
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.
static bool ParseSolverType(absl::string_view solver, OptimizationProblemType *type)
Parses the name of the solver.
MPSolverResponseStatus
friend class BopInterface
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
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
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.
virtual bool CheckSolutionExists() const
friend class XpressInterface
friend class CBCInterface
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.
Scaling is off.
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
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
void SetLB(double lb)
Sets the lower bound.
friend class KnapsackInterface
virtual util::Status SetNumThreads(int num_threads)
Dual simplex.
void set_variable_as_extracted(int var_index, bool extracted)
static const double kDefaultDualTolerance
util::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying solver.
void set_time_limit(int64 time_limit_milliseconds)
friend class XpressInterface
Definition: linear_expr.h:84
virtual bool InterruptSolve()
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.
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
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
Advanced usage: Certain MIP solvers (e.g.
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".
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
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
static const int64 kUnknownNumberOfIterations
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)
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
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 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 based solver (requires only integer and Boolean variables).
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, 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
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
Start solve from scratch.
friend class SLMInterface
bool maximize_
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
Mixed integer Programming Solver using SCIP.
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
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 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.
Mixed integer Programming Solver using Coin CBC.
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)
friend class GLPKInterface
MPObjective * MutableObjective()
Returns the mutable objective object.
virtual void SetScalingMode(int value)=0
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.
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
friend class CBCInterface
friend class SCIPInterface
ResultStatus
The status of solving the problem.
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.
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...
the model is trivially invalid (NaN coefficients, etc).
util::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...
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)
static const int64 kUnknownNumberOfNodes
friend class SLMInterface
int GetNumThreads() const
Returns the number of threads to be used during solve.
friend class GLPKInterface
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...
Linear Boolean Programming Solver.
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.
util::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
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.
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
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
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...
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::optional< MPSolutionResponse > DirectlySolveProto(const MPModelRequest &request)
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
void SetBranchingPriority(int priority)
void SetLB(double lb)
Sets the lower bound.
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 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.
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)
proven infeasible.
int last_variable_index() const
friend class CplexInterface
int64 iterations() const
Returns the number of simplex iterations.
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_
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
proven unbounded.
not been solved yet.
friend class GLPKInterface