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 #ifdef USE_CLP
187  CLP_LINEAR_PROGRAMMING = 0,
189 #endif
190 #ifdef USE_GLPK
191  GLPK_LINEAR_PROGRAMMING = 1,
193 #endif
196 #ifdef USE_GUROBI
197  GUROBI_LINEAR_PROGRAMMING = 6,
199 #endif
200 #ifdef USE_CPLEX
201  CPLEX_LINEAR_PROGRAMMING = 10,
203 #endif
204 
205 // Integer programming problems.
206 #ifdef USE_SCIP
207  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
209 #endif
210 #ifdef USE_GLPK
211  GLPK_MIXED_INTEGER_PROGRAMMING = 4,
213 #endif
214 #ifdef USE_CBC
217 #endif
218 #if defined(USE_GUROBI)
219  GUROBI_MIXED_INTEGER_PROGRAMMING = 7,
221 #endif
222 #if defined(USE_CPLEX)
223  CPLEX_MIXED_INTEGER_PROGRAMMING = 11,
225 #endif
232 #if defined(USE_XPRESS)
233  XPRESS_LINEAR_PROGRAMMING = 101,
234  XPRESS_MIXED_INTEGER_PROGRAMMING = 102,
235 #endif
236  };
237 
239  MPSolver(const std::string& name, OptimizationProblemType problem_type);
240  virtual ~MPSolver();
241 
246  static bool SupportsProblemType(OptimizationProblemType problem_type);
247 
252  static bool ParseSolverType(absl::string_view solver,
254 
255  bool IsMIP() const;
256 
258  const std::string& Name() const {
259  return name_; // Set at construction.
260  }
261 
264  return problem_type_; // Set at construction.
265  }
266 
272  void Clear();
273 
275  int NumVariables() const { return variables_.size(); }
276 
281  const std::vector<MPVariable*>& variables() const { return variables_; }
282 
288  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
289 
297  MPVariable* MakeVar(double lb, double ub, bool integer,
298  const std::string& name);
299 
301  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
302 
304  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
305 
307  MPVariable* MakeBoolVar(const std::string& name);
308 
323  void MakeVarArray(int nb, double lb, double ub, bool integer,
324  const std::string& name_prefix,
325  std::vector<MPVariable*>* vars);
326 
328  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
329  std::vector<MPVariable*>* vars);
330 
332  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
333  std::vector<MPVariable*>* vars);
334 
336  void MakeBoolVarArray(int nb, const std::string& name,
337  std::vector<MPVariable*>* vars);
338 
340  int NumConstraints() const { return constraints_.size(); }
341 
347  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
348 
357  const std::string& constraint_name) const;
358 
367  MPConstraint* MakeRowConstraint(double lb, double ub);
368 
371 
373  MPConstraint* MakeRowConstraint(double lb, double ub,
374  const std::string& name);
375 
377  MPConstraint* MakeRowConstraint(const std::string& name);
378 
384 
387  const std::string& name);
388 
395  const MPObjective& Objective() const { return *objective_; }
396 
398  MPObjective* MutableObjective() { return objective_.get(); }
399 
420  NOT_SOLVED = 6
421  };
422 
425 
428 
433  void Write(const std::string& file_name);
434 
441  std::vector<double> ComputeConstraintActivities() const;
442 
461  bool VerifySolution(double tolerance, bool log_errors) const;
462 
471  void Reset();
472 
481 
489  MPSolverResponseStatus LoadModelFromProto(const MPModelProto& input_model,
490  std::string* error_message);
499  const MPModelProto& input_model, std::string* error_message);
500 
502  void FillSolutionResponseProto(MPSolutionResponse* response) const;
503 
513  static void SolveWithProto(const MPModelRequest& model_request,
514  MPSolutionResponse* response);
515 
517  void ExportModelToProto(MPModelProto* output_model) const;
518 
550  absl::Status LoadSolutionFromProto(
551  const MPSolutionResponse& response,
552  double tolerance = kDefaultPrimalTolerance);
553 
559 
566  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
567  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
568  std::string* model_str) const;
569 
580  absl::Status SetNumThreads(int num_threads);
581 
583  int GetNumThreads() const { return num_threads_; }
584 
591  bool SetSolverSpecificParametersAsString(const std::string& parameters);
593  return solver_specific_parameter_string_;
594  }
595 
609  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
610 
615  enum BasisStatus {
616  FREE = 0,
620  BASIC
621  };
622 
635  const std::vector<MPSolver::BasisStatus>& variable_statuses,
636  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
637 
643  static double infinity() { return std::numeric_limits<double>::infinity(); }
644 
653  bool OutputIsEnabled() const;
654 
656  void EnableOutput();
657 
660 
661  absl::Duration TimeLimit() const { return time_limit_; }
662  void SetTimeLimit(absl::Duration time_limit) {
663  DCHECK_GE(time_limit, absl::ZeroDuration());
664  time_limit_ = time_limit;
665  }
666 
667  absl::Duration DurationSinceConstruction() const {
668  return absl::Now() - construction_time_;
669  }
670 
672  int64 iterations() const;
673 
679  int64 nodes() const;
680 
682  std::string SolverVersion() const;
683 
698 
723 
738  ABSL_MUST_USE_RESULT bool NextSolution();
739 
740  // Does not take ownership of "mp_callback".
741  //
742  // As of 2019-10-22, only SCIP and Gurobi support Callbacks.
743  // SCIP does not support suggesting a heuristic solution in the callback.
744  //
745  // See go/mpsolver-callbacks for additional documentation.
746  void SetCallback(MPCallback* mp_callback);
747  bool SupportsCallbacks() const;
748 
749  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
750  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
751  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
752  int64 time_limit() const {
753  return time_limit_ == absl::InfiniteDuration()
754  ? 0
755  : absl::ToInt64Milliseconds(time_limit_);
756  }
757  void set_time_limit(int64 time_limit_milliseconds) {
758  SetTimeLimit(time_limit_milliseconds == 0
759  ? absl::InfiniteDuration()
760  : absl::Milliseconds(time_limit_milliseconds));
761  }
762  double time_limit_in_secs() const {
763  return static_cast<double>(time_limit()) / 1000.0;
764  }
765 
766  // DEPRECATED: Use DurationSinceConstruction() instead.
767  int64 wall_time() const {
768  return absl::ToInt64Milliseconds(DurationSinceConstruction());
769  }
770 
771  friend class GLPKInterface;
772  friend class CLPInterface;
773  friend class CBCInterface;
774  friend class SCIPInterface;
775  friend class GurobiInterface;
776  friend class CplexInterface;
777  friend class XpressInterface;
778  friend class SLMInterface;
779  friend class MPSolverInterface;
780  friend class GLOPInterface;
781  friend class BopInterface;
782  friend class SatInterface;
783  friend class KnapsackInterface;
784 
785  // Debugging: verify that the given MPVariable* belongs to this solver.
786  bool OwnsVariable(const MPVariable* var) const;
787 
788  private:
789  // Computes the size of the constraint with the largest number of
790  // coefficients with index in [min_constraint_index,
791  // max_constraint_index)
792  int ComputeMaxConstraintSize(int min_constraint_index,
793  int max_constraint_index) const;
794 
795  // Returns true if the model has constraints with lower bound > upper bound.
796  bool HasInfeasibleConstraints() const;
797 
798  // Returns true if the model has at least 1 integer variable.
799  bool HasIntegerVariables() const;
800 
801  // Generates the map from variable names to their indices.
802  void GenerateVariableNameIndex() const;
803 
804  // Generates the map from constraint names to their indices.
805  void GenerateConstraintNameIndex() const;
806 
807  // The name of the linear programming problem.
808  const std::string name_;
809 
810  // The type of the linear programming problem.
811  const OptimizationProblemType problem_type_;
812 
813  // The solver interface.
814  std::unique_ptr<MPSolverInterface> interface_;
815 
816  // The vector of variables in the problem.
817  std::vector<MPVariable*> variables_;
818  // A map from a variable's name to its index in variables_.
819  mutable absl::optional<absl::flat_hash_map<std::string, int> >
820  variable_name_to_index_;
821  // Whether variables have been extracted to the underlying interface.
822  std::vector<bool> variable_is_extracted_;
823 
824  // The vector of constraints in the problem.
825  std::vector<MPConstraint*> constraints_;
826  // A map from a constraint's name to its index in constraints_.
827  mutable absl::optional<absl::flat_hash_map<std::string, int> >
828  constraint_name_to_index_;
829  // Whether constraints have been extracted to the underlying interface.
830  std::vector<bool> constraint_is_extracted_;
831 
832  // The linear objective function.
833  std::unique_ptr<MPObjective> objective_;
834 
835  // Initial values for all or some of the problem variables that can be
836  // exploited as a starting hint by a solver.
837  //
838  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
839  //
840  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
841  // hint is provided and a std::vector<double> for the hint value.
842  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
843 
844  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
845 
846  const absl::Time construction_time_;
847 
848  // Permanent storage for the number of threads.
849  int num_threads_ = 1;
850 
851  // Permanent storage for SetSolverSpecificParametersAsString().
852  std::string solver_specific_parameter_string_;
853 
854  MPSolverResponseStatus LoadModelFromProtoInternal(
855  const MPModelProto& input_model, bool clear_names,
856  bool check_model_validity, std::string* error_message);
857 
858  DISALLOW_COPY_AND_ASSIGN(MPSolver);
859 };
860 
862  return SolverTypeIsMip(static_cast<MPModelRequest::SolverType>(solver_type));
863 }
864 
865 const absl::string_view ToString(
866  MPSolver::OptimizationProblemType optimization_problem_type);
867 
868 inline std::ostream& operator<<(
869  std::ostream& os,
870  MPSolver::OptimizationProblemType optimization_problem_type) {
871  return os << ToString(optimization_problem_type);
872 }
873 
874 inline std::ostream& operator<<(std::ostream& os,
875  MPSolver::ResultStatus status) {
876  return os << ProtoEnumToString<MPSolverResponseStatus>(
877  static_cast<MPSolverResponseStatus>(status));
878 }
879 
880 bool AbslParseFlag(absl::string_view text,
882  std::string* error);
883 
884 inline std::string AbslUnparseFlag(
885  MPSolver::OptimizationProblemType solver_type) {
886  return std::string(ToString(solver_type));
887 }
888 
890 class MPObjective {
891  public:
896  void Clear();
897 
904  void SetCoefficient(const MPVariable* const var, double coeff);
905 
911  double GetCoefficient(const MPVariable* const var) const;
912 
918  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
919  return coefficients_;
920  }
921 
923  void SetOffset(double value);
924 
926  double offset() const { return offset_; }
927 
932  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
933 
935  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
936  OptimizeLinearExpr(linear_expr, true);
937  }
939  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
940  OptimizeLinearExpr(linear_expr, false);
941  }
942 
944  void AddLinearExpr(const LinearExpr& linear_expr);
945 
947  void SetOptimizationDirection(bool maximize);
948 
951 
954 
956  bool maximization() const;
957 
959  bool minimization() const;
960 
972  double Value() const;
973 
980  double BestBound() const;
981 
982  private:
983  friend class MPSolver;
984  friend class MPSolverInterface;
985  friend class CBCInterface;
986  friend class CLPInterface;
987  friend class GLPKInterface;
988  friend class SCIPInterface;
989  friend class SLMInterface;
990  friend class GurobiInterface;
991  friend class CplexInterface;
992  friend class XpressInterface;
993  friend class GLOPInterface;
994  friend class BopInterface;
995  friend class SatInterface;
996  friend class KnapsackInterface;
997 
998  // Constructor. An objective points to a single MPSolverInterface
999  // that is specified in the constructor. An objective cannot belong
1000  // to several models.
1001  // At construction, an MPObjective has no terms (which is equivalent
1002  // on having a coefficient of 0 for all variables), and an offset of 0.
1003  explicit MPObjective(MPSolverInterface* const interface_in)
1004  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1005 
1006  MPSolverInterface* const interface_;
1007 
1008  // Mapping var -> coefficient.
1009  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1010  // Constant term.
1011  double offset_;
1012 
1013  DISALLOW_COPY_AND_ASSIGN(MPObjective);
1014 };
1015 
1017 class MPVariable {
1018  public:
1020  const std::string& name() const { return name_; }
1021 
1023  void SetInteger(bool integer);
1024 
1026  bool integer() const { return integer_; }
1027 
1035  double solution_value() const;
1036 
1038  int index() const { return index_; }
1039 
1041  double lb() const { return lb_; }
1042 
1044  double ub() const { return ub_; }
1045 
1047  void SetLB(double lb) { SetBounds(lb, ub_); }
1048 
1050  void SetUB(double ub) { SetBounds(lb_, ub); }
1051 
1053  void SetBounds(double lb, double ub);
1054 
1062 
1067  double reduced_cost() const;
1068 
1074 
1085  int branching_priority() const { return branching_priority_; }
1086  void SetBranchingPriority(int priority);
1087 
1088  protected:
1089  friend class MPSolver;
1090  friend class MPSolverInterface;
1091  friend class CBCInterface;
1092  friend class CLPInterface;
1093  friend class GLPKInterface;
1094  friend class SCIPInterface;
1095  friend class SLMInterface;
1096  friend class GurobiInterface;
1097  friend class CplexInterface;
1098  friend class XpressInterface;
1099  friend class GLOPInterface;
1101  friend class BopInterface;
1102  friend class SatInterface;
1103  friend class KnapsackInterface;
1104 
1105  // Constructor. A variable points to a single MPSolverInterface that
1106  // is specified in the constructor. A variable cannot belong to
1107  // several models.
1108  MPVariable(int index, double lb, double ub, bool integer,
1109  const std::string& name, MPSolverInterface* const interface_in)
1110  : index_(index),
1111  lb_(lb),
1112  ub_(ub),
1113  integer_(integer),
1114  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1115  solution_value_(0.0),
1116  reduced_cost_(0.0),
1117  interface_(interface_in) {}
1118 
1119  void set_solution_value(double value) { solution_value_ = value; }
1120  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1121 
1122  private:
1123  const int index_;
1124  double lb_;
1125  double ub_;
1126  bool integer_;
1127  const std::string name_;
1128  double solution_value_;
1129  double reduced_cost_;
1130  int branching_priority_ = 0;
1131  MPSolverInterface* const interface_;
1132  DISALLOW_COPY_AND_ASSIGN(MPVariable);
1133 };
1134 
1141  public:
1143  const std::string& name() const { return name_; }
1144 
1146  void Clear();
1147 
1154  void SetCoefficient(const MPVariable* const var, double coeff);
1155 
1160  double GetCoefficient(const MPVariable* const var) const;
1161 
1167  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1168  return coefficients_;
1169  }
1170 
1172  double lb() const { return lb_; }
1173 
1175  double ub() const { return ub_; }
1176 
1178  void SetLB(double lb) { SetBounds(lb, ub_); }
1179 
1181  void SetUB(double ub) { SetBounds(lb_, ub); }
1182 
1184  void SetBounds(double lb, double ub);
1185 
1187  bool is_lazy() const { return is_lazy_; }
1188 
1202  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1203 
1204  const MPVariable* indicator_variable() const { return indicator_variable_; }
1205  bool indicator_value() const { return indicator_value_; }
1206 
1208  int index() const { return index_; }
1209 
1214  double dual_value() const;
1215 
1227 
1228  protected:
1229  friend class MPSolver;
1230  friend class MPSolverInterface;
1231  friend class CBCInterface;
1232  friend class CLPInterface;
1233  friend class GLPKInterface;
1234  friend class SCIPInterface;
1235  friend class SLMInterface;
1236  friend class GurobiInterface;
1237  friend class CplexInterface;
1238  friend class XpressInterface;
1239  friend class GLOPInterface;
1240  friend class BopInterface;
1241  friend class SatInterface;
1242  friend class KnapsackInterface;
1243 
1244  // Constructor. A constraint points to a single MPSolverInterface
1245  // that is specified in the constructor. A constraint cannot belong
1246  // to several models.
1247  MPConstraint(int index, double lb, double ub, const std::string& name,
1248  MPSolverInterface* const interface_in)
1249  : coefficients_(1),
1250  index_(index),
1251  lb_(lb),
1252  ub_(ub),
1253  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1254  is_lazy_(false),
1255  indicator_variable_(nullptr),
1256  dual_value_(0.0),
1257  interface_(interface_in) {}
1258 
1259  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1260 
1261  private:
1262  // Returns true if the constraint contains variables that have not
1263  // been extracted yet.
1264  bool ContainsNewVariables();
1265 
1266  // Mapping var -> coefficient.
1267  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1268 
1269  const int index_; // See index().
1270 
1271  // The lower bound for the linear constraint.
1272  double lb_;
1273 
1274  // The upper bound for the linear constraint.
1275  double ub_;
1276 
1277  // Name.
1278  const std::string name_;
1279 
1280  // True if the constraint is "lazy", i.e. the constraint is added to the
1281  // underlying Linear Programming solver only if it is violated.
1282  // By default this parameter is 'false'.
1283  bool is_lazy_;
1284 
1285  // If given, this constraint is only active if `indicator_variable_`'s value
1286  // is equal to `indicator_value_`.
1287  const MPVariable* indicator_variable_;
1288  bool indicator_value_;
1289 
1290  double dual_value_;
1291  MPSolverInterface* const interface_;
1292  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1293 };
1294 
1322  public:
1327 
1336  DUAL_TOLERANCE = 2
1337  };
1338 
1342  PRESOLVE = 1000,
1348  SCALING = 1003
1349  };
1350 
1356  PRESOLVE_ON = 1
1357  };
1358 
1362  DUAL = 10,
1364  PRIMAL = 11,
1366  BARRIER = 12
1367  };
1368 
1373 
1378  INCREMENTALITY_ON = 1
1379  };
1380 
1386  SCALING_ON = 1
1387  };
1388 
1389  // Placeholder value to indicate that a parameter is set to
1390  // the default value defined in the wrapper.
1391  static const double kDefaultDoubleParamValue;
1392  static const int kDefaultIntegerParamValue;
1393 
1394  // Placeholder value to indicate that a parameter is unknown.
1395  static const double kUnknownDoubleParamValue;
1396  static const int kUnknownIntegerParamValue;
1397 
1398  // Default values for parameters. Only parameters that define the
1399  // properties of the solution returned need to have a default value
1400  // (that is the same for all solvers). You can also define a default
1401  // value for performance parameters when you are confident it is a
1402  // good choice (example: always turn presolve on).
1403  static const double kDefaultRelativeMipGap;
1404  static const double kDefaultPrimalTolerance;
1405  static const double kDefaultDualTolerance;
1408 
1411 
1414 
1417 
1424 
1431 
1433  void Reset();
1434 
1437 
1440 
1441  private:
1442  // Parameter value for each parameter.
1443  // @see DoubleParam
1444  // @see IntegerParam
1445  double relative_mip_gap_value_;
1446  double primal_tolerance_value_;
1447  double dual_tolerance_value_;
1448  int presolve_value_;
1449  int scaling_value_;
1450  int lp_algorithm_value_;
1451  int incrementality_value_;
1452 
1453  // Boolean value indicating whether each parameter is set to the
1454  // solver's default value. Only parameters for which the wrapper
1455  // does not define a default value need such an indicator.
1456  bool lp_algorithm_is_default_;
1457 
1458  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1459 };
1460 
1461 // Whether the given MPSolverResponseStatus (of a solve) would yield an RPC
1462 // error when happening on the linear solver stubby server, see
1463 // ./linear_solver_service.proto.
1464 // Note that RPC errors forbid to carry a response to the client, who can only
1465 // see the RPC error itself (error code + error message).
1467 
1468 // This class wraps the actual mathematical programming solvers. Each
1469 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1470 // derives from this abstract class. This class is never directly
1471 // accessed by the user.
1472 // @see glop_interface.cc
1473 // @see cbc_interface.cc
1474 // @see clp_interface.cc
1475 // @see glpk_interface.cc
1476 // @see scip_interface.cc
1478  public:
1480  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1481  // sync for the model nor for the solution.
1483  // The underlying solver and MPSolver are in sync for the model
1484  // but not for the solution: the model has changed since the
1485  // solution was computed last.
1487  // The underlying solver and MPSolver are in sync for the model and
1488  // the solution.
1490  };
1491 
1492  // When the underlying solver does not provide the number of simplex
1493  // iterations.
1494  static constexpr int64 kUnknownNumberOfIterations = -1;
1495  // When the underlying solver does not provide the number of
1496  // branch-and-bound nodes.
1497  static constexpr int64 kUnknownNumberOfNodes = -1;
1498 
1499  // Constructor. The user will access the MPSolverInterface through the
1500  // MPSolver passed as argument.
1501  explicit MPSolverInterface(MPSolver* const solver);
1503 
1504  // ----- Solve -----
1505  // Solves problem with specified parameter values. Returns true if the
1506  // solution is optimal.
1508 
1509  // Directly solves a MPModelRequest, bypassing the MPSolver data structures
1510  // entirely. Returns {} (eg. absl::nullopt) if the feature is not supported by
1511  // the underlying solver.
1512  virtual absl::optional<MPSolutionResponse> DirectlySolveProto(
1513  const MPModelRequest& request) {
1514  return absl::nullopt;
1515  }
1516 
1517  // Writes the model using the solver internal write function. Currently only
1518  // available for GurobiInterface.
1519  virtual void Write(const std::string& filename);
1520 
1521  // ----- Model modifications and extraction -----
1522  // Resets extracted model.
1523  virtual void Reset() = 0;
1524 
1525  // Sets the optimization direction (min/max).
1526  virtual void SetOptimizationDirection(bool maximize) = 0;
1527 
1528  // Modifies bounds of an extracted variable.
1529  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1530 
1531  // Modifies integrality of an extracted variable.
1532  virtual void SetVariableInteger(int index, bool integer) = 0;
1533 
1534  // Modify bounds of an extracted variable.
1535  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1536 
1537  // Adds a linear constraint.
1538  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1539 
1540  // Adds an indicator constraint. Returns true if the feature is supported by
1541  // the underlying solver.
1542  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1543  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1544  return false;
1545  }
1546 
1547  // Add a variable.
1548  virtual void AddVariable(MPVariable* const var) = 0;
1549 
1550  // Changes a coefficient in a constraint.
1551  virtual void SetCoefficient(MPConstraint* const constraint,
1552  const MPVariable* const variable,
1553  double new_value, double old_value) = 0;
1554 
1555  // Clears a constraint from all its terms.
1556  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1557 
1558  // Changes a coefficient in the linear objective.
1559  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1560  double coefficient) = 0;
1561 
1562  // Changes the constant term in the linear objective.
1563  virtual void SetObjectiveOffset(double value) = 0;
1564 
1565  // Clears the objective from all its terms.
1566  virtual void ClearObjective() = 0;
1567 
1568  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1569  // ------ Query statistics on the solution and the solve ------
1570  // Returns the number of simplex iterations. The problem must be discrete,
1571  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1572  virtual int64 iterations() const = 0;
1573  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1574  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1575  virtual int64 nodes() const = 0;
1576  // Returns the best objective bound. The problem must be discrete, otherwise
1577  // it crashes, or returns trivial_worst_objective_bound() in NDEBUG mode.
1578  virtual double best_objective_bound() const = 0;
1579  // A trivial objective bound: the worst possible value of the objective,
1580  // which will be +infinity if minimizing and -infinity if maximing.
1582  // Returns the objective value of the best solution found so far.
1583  double objective_value() const;
1584 
1585  // Returns the basis status of a row.
1586  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1587  // Returns the basis status of a constraint.
1588  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1589 
1590  // Checks whether the solution is synchronized with the model, i.e. whether
1591  // the model has changed since the solution was computed last.
1592  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1594  // Checks whether a feasible solution exists. The behavior is similar to
1595  // CheckSolutionIsSynchronized() above.
1596  virtual bool CheckSolutionExists() const;
1597  // Handy shortcut to do both checks above (it is often used).
1600  }
1601  // Checks whether information on the best objective bound exists. The behavior
1602  // is similar to CheckSolutionIsSynchronized() above.
1603  virtual bool CheckBestObjectiveBoundExists() const;
1604 
1605  // ----- Misc -----
1606  // Queries problem type. For simplicity, the distinction between
1607  // continuous and discrete is based on the declaration of the user
1608  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1609  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1610  // the model.
1611  // Returns true if the problem is continuous.
1612  virtual bool IsContinuous() const = 0;
1613  // Returns true if the problem is continuous and linear.
1614  virtual bool IsLP() const = 0;
1615  // Returns true if the problem is discrete and linear.
1616  virtual bool IsMIP() const = 0;
1617 
1618  // Returns the index of the last variable extracted.
1620 
1621  bool variable_is_extracted(int var_index) const {
1622  return solver_->variable_is_extracted_[var_index];
1623  }
1624  void set_variable_as_extracted(int var_index, bool extracted) {
1625  solver_->variable_is_extracted_[var_index] = extracted;
1626  }
1627  bool constraint_is_extracted(int ct_index) const {
1628  return solver_->constraint_is_extracted_[ct_index];
1629  }
1630  void set_constraint_as_extracted(int ct_index, bool extracted) {
1631  solver_->constraint_is_extracted_[ct_index] = extracted;
1632  }
1633 
1634  // Returns the boolean indicating the verbosity of the solver output.
1635  bool quiet() const { return quiet_; }
1636  // Sets the boolean indicating the verbosity of the solver output.
1637  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1638 
1639  // Returns the result status of the last solve.
1642  return result_status_;
1643  }
1644 
1645  // Returns a string describing the underlying solver and its version.
1646  virtual std::string SolverVersion() const = 0;
1647 
1648  // Returns the underlying solver.
1649  virtual void* underlying_solver() = 0;
1650 
1651  // Computes exact condition number. Only available for continuous
1652  // problems and only implemented in GLPK.
1653  virtual double ComputeExactConditionNumber() const;
1654 
1655  // See MPSolver::SetStartingLpBasis().
1656  virtual void SetStartingLpBasis(
1657  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1658  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1659  LOG(FATAL) << "Not supported by this solver.";
1660  }
1661 
1662  virtual bool InterruptSolve() { return false; }
1663 
1664  // See MPSolver::NextSolution() for contract.
1665  virtual bool NextSolution() { return false; }
1666 
1667  // See MPSolver::SetCallback() for details.
1668  virtual void SetCallback(MPCallback* mp_callback) {
1669  LOG(FATAL) << "Callbacks not supported for this solver.";
1670  }
1671 
1672  virtual bool SupportsCallbacks() const { return false; }
1673 
1674  friend class MPSolver;
1675 
1676  // To access the maximize_ bool and the MPSolver.
1677  friend class MPConstraint;
1678  friend class MPObjective;
1679 
1680  protected:
1682  // Indicates whether the model and the solution are synchronized.
1684  // Indicates whether the solve has reached optimality,
1685  // infeasibility, a limit, etc.
1687  // Optimization direction.
1689 
1690  // Index in MPSolver::variables_ of last constraint extracted.
1692  // Index in MPSolver::constraints_ of last variable extracted.
1694 
1695  // The value of the objective function.
1697 
1698  // Boolean indicator for the verbosity of the solver output.
1699  bool quiet_;
1700 
1701  // Index of dummy variable created for empty constraints or the
1702  // objective offset.
1703  static const int kDummyVariableIndex;
1704 
1705  // Extracts model stored in MPSolver.
1707  // Extracts the variables that have not been extracted yet.
1708  virtual void ExtractNewVariables() = 0;
1709  // Extracts the constraints that have not been extracted yet.
1710  virtual void ExtractNewConstraints() = 0;
1711  // Extracts the objective.
1712  virtual void ExtractObjective() = 0;
1713  // Resets the extraction information.
1715  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1716  // MODEL_SYNCHRONIZED. To be used for model changes.
1718 
1719  // Sets parameters common to LP and MIP in the underlying solver.
1721  // Sets MIP specific parameters in the underlying solver.
1723  // Sets all parameters in the underlying solver.
1724  virtual void SetParameters(const MPSolverParameters& param) = 0;
1725  // Sets an unsupported double parameter.
1727  // Sets an unsupported integer parameter.
1730  // Sets a supported double parameter to an unsupported value.
1732  double value);
1733  // Sets a supported integer parameter to an unsupported value.
1735  MPSolverParameters::IntegerParam param, int value);
1736  // Sets each parameter in the underlying solver.
1737  virtual void SetRelativeMipGap(double value) = 0;
1738  virtual void SetPrimalTolerance(double value) = 0;
1739  virtual void SetDualTolerance(double value) = 0;
1740  virtual void SetPresolveMode(int value) = 0;
1741 
1742  // Sets the number of threads to be used by the solver.
1743  virtual absl::Status SetNumThreads(int num_threads);
1744 
1745  // Pass solver specific parameters in text format. The format is
1746  // solver-specific and is the same as the corresponding solver configuration
1747  // file format. Returns true if the operation was successful.
1748  //
1749  // The default implementation of this method stores the parameters in a
1750  // temporary file and calls ReadParameterFile to import the parameter file
1751  // into the solver. Solvers that support passing the parameters directly can
1752  // override this method to skip the temporary file logic.
1754  const std::string& parameters);
1755 
1756  // Reads a solver-specific file of parameters and set them.
1757  // Returns true if there was no errors.
1758  virtual bool ReadParameterFile(const std::string& filename);
1759 
1760  // Returns a file extension like ".tmp", this is needed because some solvers
1761  // require a given extension for the ReadParameterFile() filename and we need
1762  // to know it to generate a temporary parameter file.
1763  virtual std::string ValidFileExtensionForParameterFile() const;
1764 
1765  // Sets the scaling mode.
1766  virtual void SetScalingMode(int value) = 0;
1767  virtual void SetLpAlgorithm(int value) = 0;
1768 };
1769 
1770 } // namespace operations_research
1771 
1772 #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.
@ GLOP_LINEAR_PROGRAMMING
Linear Programming solver using GLOP (Recommended solver).
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
@ 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_
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)
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.
@ 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
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.
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.
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
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
@ 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
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
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
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 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
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_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
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)
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
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
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.
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
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_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.
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
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_
@ 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