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 
14 // A C++ wrapper that provides a simple and unified interface to
15 // several linear programming and mixed integer programming solvers:
16 // GLOP, GLPK, CLP, CBC, and SCIP. The wrapper can also be used in Java, C#,
17 // and Python via SWIG.
18 //
19 //
20 // -----------------------------------
21 //
22 // What is Linear Programming?
23 //
24 // In mathematics, linear programming (LP) is a technique for optimization of
25 // a linear objective function, subject to linear equality and linear
26 // inequality constraints. Informally, linear programming determines the way
27 // to achieve the best outcome (such as maximum profit or lowest cost) in a
28 // given mathematical model and given some list of requirements represented
29 // as linear equations.
30 //
31 // The most widely used technique for solving a linear program is the Simplex
32 // algorithm, devised by George Dantzig in 1947. It performs very well on
33 // most instances, for which its running time is polynomial. A lot of effort
34 // has been put into improving the algorithm and its implementation. As a
35 // byproduct, it has however been shown that one can always construct
36 // problems that take exponential time for the Simplex algorithm to solve.
37 // Research has thus focused on trying to find a polynomial algorithm for
38 // linear programming, or to prove that linear programming is indeed
39 // polynomial.
40 //
41 // Leonid Khachiyan first exhibited in 1979 a weakly polynomial algorithm for
42 // linear programming. "Weakly polynomial" means that the running time of the
43 // algorithm is in O(P(n) * 2^p) where P(n) is a polynomial of the size of the
44 // problem, and p is the precision of computations expressed in number of
45 // bits. With a fixed-precision, floating-point-based implementation, a weakly
46 // polynomial algorithm will thus run in polynomial time. No implementation
47 // of Khachiyan's algorithm has proved efficient, but a larger breakthrough in
48 // the field came in 1984 when Narendra Karmarkar introduced a new interior
49 // point method for solving linear programming problems. Interior point
50 // algorithms have proved efficient on very large linear programs.
51 //
52 // Check Wikipedia for more detail:
53 // http://en.wikipedia.org/wiki/Linear_programming
54 //
55 // -----------------------------------
56 //
57 // Example of a Linear Program
58 //
59 // maximize:
60 // 3x + y
61 // subject to:
62 // 1.5 x + 2 y <= 12
63 // 0 <= x <= 3
64 // 0 <= y <= 5
65 //
66 // A linear program has:
67 // 1) a linear objective function
68 // 2) linear constraints that can be equalities or inequalities
69 // 3) bounds on variables that can be positive, negative, finite or
70 // infinite.
71 //
72 // -----------------------------------
73 //
74 // What is Mixed Integer Programming?
75 //
76 // Here, the constraints and the objective are still linear but
77 // there are additional integrality requirements for variables. If
78 // all variables are required to take integer values, then the
79 // problem is called an integer program (IP). In most cases, only
80 // some variables are required to be integer and the rest of the
81 // variables are continuous: this is called a mixed integer program
82 // (MIP). IPs and MIPs are generally NP-hard.
83 //
84 // Integer variables can be used to model discrete decisions (build a
85 // datacenter in city A or city B), logical relationships (only
86 // place machines in datacenter A if we have decided to build
87 // datacenter A) and approximate non-linear functions with piecewise
88 // linear functions (for example, the cost of machines as a function
89 // of how many machines are bought, or the latency of a server as a
90 // function of its load).
91 //
92 // -----------------------------------
93 //
94 // How to use the wrapper
95 //
96 // The user builds the model and solves it through the MPSolver class,
97 // then queries the solution through the MPSolver, MPVariable and
98 // MPConstraint classes. To be able to query a solution, you need the
99 // following:
100 // - A solution exists: MPSolver::Solve has been called and a solution
101 // has been found.
102 // - The model has not been modified since the last time
103 // MPSolver::Solve was called. Otherwise, the solution obtained
104 // before the model modification may not longer be feasible or
105 // optimal.
106 //
107 // @see ../examples/linear_programming.cc for a simple LP example.
108 //
109 // @see ../examples/integer_programming.cc for a simple MIP example.
110 //
111 // All methods cannot be called successfully in all cases. For
112 // example: you cannot query a solution when no solution exists, you
113 // cannot query a reduced cost value (which makes sense only on
114 // continuous problems) on a discrete problem. When a method is
115 // called in an unsuitable context, it aborts with a
116 // LOG(FATAL).
117 // TODO(user): handle failures gracefully.
118 //
119 // -----------------------------------
120 //
121 // For developers: How the wrapper works
122 //
123 // MPSolver stores a representation of the model (variables,
124 // constraints and objective) in its own data structures and a
125 // pointer to a MPSolverInterface that wraps the underlying solver
126 // (GLOP, CBC, CLP, GLPK, or SCIP) that does the actual work. The
127 // underlying solver also keeps a representation of the model in its
128 // own data structures. The model representations in MPSolver and in
129 // the underlying solver are kept in sync by the 'extraction'
130 // mechanism: synchronously for some changes and asynchronously
131 // (when MPSolver::Solve is called) for others. Synchronicity
132 // depends on the modification applied and on the underlying solver.
133 
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"
155 #include "ortools/glop/parameters.pb.h"
156 #include "ortools/linear_solver/linear_expr.h"
158 #include "ortools/port/proto_utils.h"
159 
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 
186 #endif
187 #ifdef USE_GLPK
188 
189  GLPK_LINEAR_PROGRAMMING = 1,
190 #endif
191 #ifdef USE_GLOP
192 
194 #endif
195 #ifdef USE_GUROBI
196 
197  GUROBI_LINEAR_PROGRAMMING = 6,
198 #endif
199 #ifdef USE_CPLEX
200 
201  CPLEX_LINEAR_PROGRAMMING = 10,
202 #endif
203 
204 // Integer programming problems.
205 #ifdef USE_SCIP
206 
208  SCIP_MIXED_INTEGER_PROGRAMMING = 3, // Recommended default value.
209 #endif
210 #ifdef USE_GLPK
211 
212  GLPK_MIXED_INTEGER_PROGRAMMING = 4,
213 #endif
214 #ifdef USE_CBC
215 
217 #endif
218 #if defined(USE_GUROBI)
219 
220  GUROBI_MIXED_INTEGER_PROGRAMMING = 7,
221 #endif
222 #if defined(USE_CPLEX)
223 
224  CPLEX_MIXED_INTEGER_PROGRAMMING = 11,
225 #endif
226 #if defined(USE_BOP)
227 
229 #endif
230  };
231 
235  MPSolver(const std::string& name, OptimizationProblemType problem_type);
236  virtual ~MPSolver();
237 
242  static bool SupportsProblemType(OptimizationProblemType problem_type);
243 
248  static bool ParseSolverType(absl::string_view solver,
250 
251  bool IsMIP() const;
252 
256  const std::string& Name() const {
257  return name_; // Set at construction.
258  }
259 
264  return problem_type_; // Set at construction.
265  }
266 
272  void Clear();
273 
277  int NumVariables() const { return variables_.size(); }
278 
283  const std::vector<MPVariable*>& variables() const { return variables_; }
284 
290  MPVariable* LookupVariableOrNull(const std::string& var_name) const;
291 
299  MPVariable* MakeVar(double lb, double ub, bool integer,
300  const std::string& name);
301 
305  MPVariable* MakeNumVar(double lb, double ub, const std::string& name);
306 
310  MPVariable* MakeIntVar(double lb, double ub, const std::string& name);
311 
315  MPVariable* MakeBoolVar(const std::string& name);
316 
331  void MakeVarArray(int nb, double lb, double ub, bool integer,
332  const std::string& name_prefix,
333  std::vector<MPVariable*>* vars);
334 
338  void MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
339  std::vector<MPVariable*>* vars);
340 
344  void MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
345  std::vector<MPVariable*>* vars);
346 
350  void MakeBoolVarArray(int nb, const std::string& name,
351  std::vector<MPVariable*>* vars);
352 
356  int NumConstraints() const { return constraints_.size(); }
357 
363  const std::vector<MPConstraint*>& constraints() const { return constraints_; }
364 
373  const std::string& constraint_name) const;
374 
383  MPConstraint* MakeRowConstraint(double lb, double ub);
384 
389 
393  MPConstraint* MakeRowConstraint(double lb, double ub,
394  const std::string& name);
398  MPConstraint* MakeRowConstraint(const std::string& name);
399 
404  MPConstraint* MakeRowConstraint(const LinearRange& range);
405 
409  MPConstraint* MakeRowConstraint(const LinearRange& range,
410  const std::string& name);
411 
418  const MPObjective& Objective() const { return *objective_; }
419 
423  MPObjective* MutableObjective() { return objective_.get(); }
424 
446  };
447 
452 
456  ResultStatus Solve(const MPSolverParameters& param);
457 
462  void Write(const std::string& file_name);
463 
470  std::vector<double> ComputeConstraintActivities() const;
471 
490  bool VerifySolution(double tolerance, bool log_errors) const;
491 
500  void Reset();
501 
509  bool InterruptSolve();
510 
519  std::string* error_message);
528  const MPModelProto& input_model, std::string* error_message);
529 
533  void FillSolutionResponseProto(MPSolutionResponse* response) const;
534 
544  static void SolveWithProto(const MPModelRequest& model_request,
545  MPSolutionResponse* response);
546 
550  void ExportModelToProto(MPModelProto* output_model) const;
551 
584  util::Status LoadSolutionFromProto(
585  const MPSolutionResponse& response,
586  double tolerance = kDefaultPrimalTolerance);
587 
592  util::Status ClampSolutionWithinBounds();
593 
600  bool ExportModelAsLpFormat(bool obfuscate, std::string* model_str) const;
601  bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
602  std::string* model_str) const;
603 
614  util::Status SetNumThreads(int num_threads);
618  int GetNumThreads() const { return num_threads_; }
619 
630  bool SetSolverSpecificParametersAsString(const std::string& parameters);
632  return solver_specific_parameter_string_;
633  }
634 
648  void SetHint(std::vector<std::pair<const MPVariable*, double> > hint);
649 
654  enum BasisStatus {
655  FREE = 0,
660  };
661 
673  void SetStartingLpBasis(
674  const std::vector<MPSolver::BasisStatus>& variable_statuses,
675  const std::vector<MPSolver::BasisStatus>& constraint_statuses);
676 
682  static double infinity() { return std::numeric_limits<double>::infinity(); }
683 
692  bool OutputIsEnabled() const;
694  void EnableOutput();
696  void SuppressOutput();
697 
698  absl::Duration TimeLimit() const { return time_limit_; }
699  void SetTimeLimit(absl::Duration time_limit) {
700  DCHECK_GE(time_limit, absl::ZeroDuration());
701  time_limit_ = time_limit;
702  }
703 
704  absl::Duration DurationSinceConstruction() const {
705  return absl::Now() - construction_time_;
706  }
707 
711  int64 iterations() const;
712 
718  int64 nodes() const;
719 
723  std::string SolverVersion() const;
724 
738  void* underlying_solver();
739 
763  double ComputeExactConditionNumber() const;
764 
779  ABSL_MUST_USE_RESULT bool NextSolution();
780 
781  // DEPRECATED: Use TimeLimit() and SetTimeLimit(absl::Duration) instead.
782  // NOTE: These deprecated functions used the convention time_limit = 0 to mean
783  // "no limit", which now corresponds to time_limit_ = InfiniteDuration().
784  int64 time_limit() const {
785  return time_limit_ == absl::InfiniteDuration()
786  ? 0
787  : absl::ToInt64Milliseconds(time_limit_);
788  }
789  void set_time_limit(int64 time_limit_milliseconds) {
790  SetTimeLimit(time_limit_milliseconds == 0
791  ? absl::InfiniteDuration()
792  : absl::Milliseconds(time_limit_milliseconds));
793  }
794  double time_limit_in_secs() const {
795  return static_cast<double>(time_limit()) / 1000.0;
796  }
797 
798  // DEPRECATED: Use DurationSinceConstruction() instead.
799  int64 wall_time() const {
800  return absl::ToInt64Milliseconds(DurationSinceConstruction());
801  }
802 
803  friend class GLPKInterface;
804  friend class CLPInterface;
805  friend class CBCInterface;
806  friend class SCIPInterface;
807  friend class GurobiInterface;
808  friend class CplexInterface;
809  friend class SLMInterface;
810  friend class MPSolverInterface;
811  friend class GLOPInterface;
812  friend class BopInterface;
813  friend class SatInterface;
814  friend class KnapsackInterface;
815 
816  // Debugging: verify that the given MPVariable* belongs to this solver.
817  bool OwnsVariable(const MPVariable* var) const;
818 
819  private:
820  // Computes the size of the constraint with the largest number of
821  // coefficients with index in [min_constraint_index,
822  // max_constraint_index)
823  int ComputeMaxConstraintSize(int min_constraint_index,
824  int max_constraint_index) const;
825 
826  // Returns true if the model has constraints with lower bound > upper bound.
827  bool HasInfeasibleConstraints() const;
828 
829  // Returns true if the model has at least 1 integer variable.
830  bool HasIntegerVariables() const;
831 
832  // Generates the map from variable names to their indices.
833  void GenerateVariableNameIndex() const;
834 
835  // Generates the map from constraint names to their indices.
836  void GenerateConstraintNameIndex() const;
837 
838  // The name of the linear programming problem.
839  const std::string name_;
840 
841  // The type of the linear programming problem.
842  const OptimizationProblemType problem_type_;
843 
844  // The solver interface.
845  std::unique_ptr<MPSolverInterface> interface_;
846 
847  // The vector of variables in the problem.
848  std::vector<MPVariable*> variables_;
849  // A map from a variable's name to its index in variables_.
850  mutable absl::optional<absl::flat_hash_map<std::string, int> >
851  variable_name_to_index_;
852  // Whether variables have been extracted to the underlying interface.
853  std::vector<bool> variable_is_extracted_;
854 
855  // The vector of constraints in the problem.
856  std::vector<MPConstraint*> constraints_;
857  // A map from a constraint's name to its index in constraints_.
858  mutable absl::optional<absl::flat_hash_map<std::string, int> >
859  constraint_name_to_index_;
860  // Whether constraints have been extracted to the underlying interface.
861  std::vector<bool> constraint_is_extracted_;
862 
863  // The linear objective function.
864  std::unique_ptr<MPObjective> objective_;
865 
866  // Initial values for all or some of the problem variables that can be
867  // exploited as a starting hint by a solver.
868  //
869  // Note(user): as of 05/05/2015, we can't use >> because of some SWIG errors.
870  //
871  // TODO(user): replace by two vectors, a std::vector<bool> to indicate if a
872  // hint is provided and a std::vector<double> for the hint value.
873  std::vector<std::pair<const MPVariable*, double> > solution_hint_;
874 
875  absl::Duration time_limit_ = absl::InfiniteDuration(); // Default = No limit.
876 
877  const absl::Time construction_time_;
878 
879  // Permanent storage for the number of threads.
880  int num_threads_ = 1;
881 
882  // Permanent storage for SetSolverSpecificParametersAsString().
883  std::string solver_specific_parameter_string_;
884 
885  MPSolverResponseStatus LoadModelFromProtoInternal(
886  const MPModelProto& input_model, bool clear_names,
887  std::string* error_message);
888 
889  DISALLOW_COPY_AND_ASSIGN(MPSolver);
890 };
891 
892 const absl::string_view ToString(
893  MPSolver::OptimizationProblemType optimization_problem_type);
894 
895 inline std::ostream& operator<<(
896  std::ostream& os,
897  MPSolver::OptimizationProblemType optimization_problem_type) {
898  return os << ToString(optimization_problem_type);
899 }
900 
901 inline std::ostream& operator<<(std::ostream& os,
902  MPSolver::ResultStatus status) {
903  return os << ProtoEnumToString<MPSolverResponseStatus>(
904  static_cast<MPSolverResponseStatus>(status));
905 }
906 
907 bool AbslParseFlag(absl::string_view text,
909  std::string* error);
910 
911 inline std::string AbslUnparseFlag(
912  MPSolver::OptimizationProblemType solver_type) {
913  return std::string(ToString(solver_type));
914 }
915 
919 class MPObjective {
920  public:
925  void Clear();
926 
933  void SetCoefficient(const MPVariable *const var, double coeff);
934 
940  double GetCoefficient(const MPVariable *const var) const;
941 
947  const absl::flat_hash_map<const MPVariable *, double> &terms() const {
948  return coefficients_;
949  }
950 
954  void SetOffset(double value);
955 
959  double offset() const { return offset_; }
960 
965  void OptimizeLinearExpr(const LinearExpr& linear_expr, bool is_maximization);
966 
970  void MaximizeLinearExpr(const LinearExpr& linear_expr) {
971  OptimizeLinearExpr(linear_expr, true);
972  }
976  void MinimizeLinearExpr(const LinearExpr& linear_expr) {
977  OptimizeLinearExpr(linear_expr, false);
978  }
979 
983  void AddLinearExpr(const LinearExpr& linear_expr);
984 
988  void SetOptimizationDirection(bool maximize);
989 
994 
999 
1003  bool maximization() const;
1007  bool minimization() const;
1008 
1020  double Value() const;
1021 
1028  double BestBound() const;
1029 
1030  private:
1031  friend class MPSolver;
1032  friend class MPSolverInterface;
1033  friend class CBCInterface;
1034  friend class CLPInterface;
1035  friend class GLPKInterface;
1036  friend class SCIPInterface;
1037  friend class SLMInterface;
1038  friend class GurobiInterface;
1039  friend class CplexInterface;
1040  friend class GLOPInterface;
1041  friend class BopInterface;
1042  friend class SatInterface;
1043  friend class KnapsackInterface;
1044 
1045  // Constructor. An objective points to a single MPSolverInterface
1046  // that is specified in the constructor. An objective cannot belong
1047  // to several models.
1048  // At construction, an MPObjective has no terms (which is equivalent
1049  // on having a coefficient of 0 for all variables), and an offset of 0.
1050  explicit MPObjective(MPSolverInterface* const interface_in)
1051  : interface_(interface_in), coefficients_(1), offset_(0.0) {}
1052 
1053  MPSolverInterface* const interface_;
1054 
1055  // Mapping var -> coefficient.
1056  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1057  // Constant term.
1058  double offset_;
1059 
1060  DISALLOW_COPY_AND_ASSIGN(MPObjective);
1061 };
1062 
1066 class MPVariable {
1067  public:
1071  const std::string& name() const { return name_; }
1072 
1076  void SetInteger(bool integer);
1077 
1081  bool integer() const { return integer_; }
1082 
1090  double solution_value() const;
1091 
1095  int index() const { return index_; }
1096 
1100  double lb() const { return lb_; }
1101 
1105  double ub() const { return ub_; }
1106 
1110  void SetLB(double lb) { SetBounds(lb, ub_); }
1114  void SetUB(double ub) { SetBounds(lb_, ub); }
1115 
1119  void SetBounds(double lb, double ub);
1120 
1127  double unrounded_solution_value() const;
1128 
1133  double reduced_cost() const;
1134 
1141 
1152  int branching_priority() const { return branching_priority_; }
1153  void SetBranchingPriority(int priority);
1154 
1155  protected:
1156  friend class MPSolver;
1157  friend class MPSolverInterface;
1158  friend class CBCInterface;
1159  friend class CLPInterface;
1160  friend class GLPKInterface;
1161  friend class SCIPInterface;
1162  friend class SLMInterface;
1163  friend class GurobiInterface;
1164  friend class CplexInterface;
1165  friend class GLOPInterface;
1167  friend class BopInterface;
1168  friend class SatInterface;
1169  friend class KnapsackInterface;
1170 
1171  // Constructor. A variable points to a single MPSolverInterface that
1172  // is specified in the constructor. A variable cannot belong to
1173  // several models.
1174  MPVariable(int index, double lb, double ub, bool integer,
1175  const std::string& name, MPSolverInterface* const interface_in)
1176  : index_(index),
1177  lb_(lb),
1178  ub_(ub),
1179  integer_(integer),
1180  name_(name.empty() ? absl::StrFormat("auto_v_%09d", index) : name),
1181  solution_value_(0.0),
1182  reduced_cost_(0.0),
1183  interface_(interface_in) {}
1184 
1185  void set_solution_value(double value) { solution_value_ = value; }
1186  void set_reduced_cost(double reduced_cost) { reduced_cost_ = reduced_cost; }
1187 
1188  private:
1189  const int index_;
1190  double lb_;
1191  double ub_;
1192  bool integer_;
1193  const std::string name_;
1194  double solution_value_;
1195  double reduced_cost_;
1196  int branching_priority_ = 0;
1197  MPSolverInterface* const interface_;
1198  DISALLOW_COPY_AND_ASSIGN(MPVariable);
1199 };
1200 
1207  public:
1211  const std::string& name() const { return name_; }
1212 
1216  void Clear();
1217 
1224  void SetCoefficient(const MPVariable* const var, double coeff);
1225 
1230  double GetCoefficient(const MPVariable* const var) const;
1231 
1237  const absl::flat_hash_map<const MPVariable*, double>& terms() const {
1238  return coefficients_;
1239  }
1240 
1244  double lb() const { return lb_; }
1245 
1249  double ub() const { return ub_; }
1250 
1254  void SetLB(double lb) { SetBounds(lb, ub_); }
1255 
1259  void SetUB(double ub) { SetBounds(lb_, ub); }
1260 
1264  void SetBounds(double lb, double ub);
1265 
1269  bool is_lazy() const { return is_lazy_; }
1270 
1283  void set_is_lazy(bool laziness) { is_lazy_ = laziness; }
1284 
1285  const MPVariable* indicator_variable() const { return indicator_variable_; }
1286  bool indicator_value() const { return indicator_value_; }
1287 
1291  int index() const { return index_; }
1292 
1297  double dual_value() const;
1298 
1312 
1313  protected:
1314  friend class MPSolver;
1315  friend class MPSolverInterface;
1316  friend class CBCInterface;
1317  friend class CLPInterface;
1318  friend class GLPKInterface;
1319  friend class SCIPInterface;
1320  friend class SLMInterface;
1321  friend class GurobiInterface;
1322  friend class CplexInterface;
1323  friend class GLOPInterface;
1324  friend class BopInterface;
1325  friend class SatInterface;
1326  friend class KnapsackInterface;
1327 
1328  // Constructor. A constraint points to a single MPSolverInterface
1329  // that is specified in the constructor. A constraint cannot belong
1330  // to several models.
1331  MPConstraint(int index, double lb, double ub, const std::string& name,
1332  MPSolverInterface* const interface_in)
1333  : coefficients_(1),
1334  index_(index),
1335  lb_(lb),
1336  ub_(ub),
1337  name_(name.empty() ? absl::StrFormat("auto_c_%09d", index) : name),
1338  is_lazy_(false),
1339  indicator_variable_(nullptr),
1340  dual_value_(0.0),
1341  interface_(interface_in) {}
1342 
1343  void set_dual_value(double dual_value) { dual_value_ = dual_value; }
1344 
1345  private:
1346  // Returns true if the constraint contains variables that have not
1347  // been extracted yet.
1348  bool ContainsNewVariables();
1349 
1350  // Mapping var -> coefficient.
1351  absl::flat_hash_map<const MPVariable*, double> coefficients_;
1352 
1353  const int index_; // See index().
1354 
1355  // The lower bound for the linear constraint.
1356  double lb_;
1357 
1358  // The upper bound for the linear constraint.
1359  double ub_;
1360 
1361  // Name.
1362  const std::string name_;
1363 
1364  // True if the constraint is "lazy", i.e. the constraint is added to the
1365  // underlying Linear Programming solver only if it is violated.
1366  // By default this parameter is 'false'.
1367  bool is_lazy_;
1368 
1369  // If given, this constraint is only active if `indicator_variable_`'s value
1370  // is equal to `indicator_value_`.
1371  const MPVariable* indicator_variable_;
1372  bool indicator_value_;
1373 
1374  double dual_value_;
1375  MPSolverInterface* const interface_;
1376  DISALLOW_COPY_AND_ASSIGN(MPConstraint);
1377 };
1378 
1406  public:
1415 
1426  };
1427 
1435  PRESOLVE = 1000,
1447  SCALING = 1003
1448  };
1449 
1454  PRESOLVE_OFF = 0, // Presolve is off.
1455  PRESOLVE_ON = 1 // Presolve is on.
1456  };
1457 
1462  DUAL = 10, // Dual simplex.
1463  PRIMAL = 11, // Primal simplex.
1464  BARRIER = 12 // Barrier algorithm.
1465  };
1466 
1475 
1481  };
1482 
1491  };
1492 
1493  // @{
1494  // Placeholder value to indicate that a parameter is set to
1495  // the default value defined in the wrapper.
1496  static const double kDefaultDoubleParamValue;
1497  static const int kDefaultIntegerParamValue;
1498  // @}
1499 
1500  // @{
1501  // Placeholder value to indicate that a parameter is unknown.
1502  static const double kUnknownDoubleParamValue;
1503  static const int kUnknownIntegerParamValue;
1504  // @}
1505 
1506  // @{
1507  // Default values for parameters. Only parameters that define the
1508  // properties of the solution returned need to have a default value
1509  // (that is the same for all solvers). You can also define a default
1510  // value for performance parameters when you are confident it is a
1511  // good choice (example: always turn presolve on).
1512  static const double kDefaultRelativeMipGap;
1513  static const double kDefaultPrimalTolerance;
1514  static const double kDefaultDualTolerance;
1517  // @}
1518 
1523 
1527  void SetDoubleParam(MPSolverParameters::DoubleParam param, double value);
1531  void SetIntegerParam(MPSolverParameters::IntegerParam param, int value);
1532 
1549  void Reset();
1550 
1554  double GetDoubleParam(MPSolverParameters::DoubleParam param) const;
1555 
1560 
1561  private:
1562  // @{
1563  // Parameter value for each parameter.
1564  // @see DoubleParam
1565  // @see IntegerParam
1566  double relative_mip_gap_value_;
1567  double primal_tolerance_value_;
1568  double dual_tolerance_value_;
1569  int presolve_value_;
1570  int scaling_value_;
1571  int lp_algorithm_value_;
1572  int incrementality_value_;
1573  // @}
1574 
1575  // Boolean value indicating whether each parameter is set to the
1576  // solver's default value. Only parameters for which the wrapper
1577  // does not define a default value need such an indicator.
1578  bool lp_algorithm_is_default_;
1579 
1580  DISALLOW_COPY_AND_ASSIGN(MPSolverParameters);
1581 };
1582 
1583 // This class wraps the actual mathematical programming solvers. Each
1584 // solver (GLOP, CLP, CBC, GLPK, SCIP) has its own interface class that
1585 // derives from this abstract class. This class is never directly
1586 // accessed by the user.
1587 // @see glop_interface.cc
1588 // @see cbc_interface.cc
1589 // @see clp_interface.cc
1590 // @see glpk_interface.cc
1591 // @see scip_interface.cc
1593  public:
1595  // The underlying solver (CLP, GLPK, ...) and MPSolver are not in
1596  // sync for the model nor for the solution.
1598  // The underlying solver and MPSolver are in sync for the model
1599  // but not for the solution: the model has changed since the
1600  // solution was computed last.
1602  // The underlying solver and MPSolver are in sync for the model and
1603  // the solution.
1605  };
1606 
1607  // When the underlying solver does not provide the number of simplex
1608  // iterations.
1609  static const int64 kUnknownNumberOfIterations = -1;
1610  // When the underlying solver does not provide the number of
1611  // branch-and-bound nodes.
1612  static const int64 kUnknownNumberOfNodes = -1;
1613 
1614  // Constructor. The user will access the MPSolverInterface through the
1615  // MPSolver passed as argument.
1616  explicit MPSolverInterface(MPSolver* const solver);
1617  virtual ~MPSolverInterface();
1618 
1619  // ----- Solve -----
1620  // Solves problem with specified parameter values. Returns true if the
1621  // solution is optimal.
1622  virtual MPSolver::ResultStatus Solve(const MPSolverParameters& param) = 0;
1623 
1624  // Writes the model using the solver internal write function. Currently only
1625  // available for GurobiInterface.
1626  virtual void Write(const std::string& filename);
1627 
1628  // ----- Model modifications and extraction -----
1629  // Resets extracted model.
1630  virtual void Reset() = 0;
1631 
1632  // Sets the optimization direction (min/max).
1633  virtual void SetOptimizationDirection(bool maximize) = 0;
1634 
1635  // Modifies bounds of an extracted variable.
1636  virtual void SetVariableBounds(int index, double lb, double ub) = 0;
1637 
1638  // Modifies integrality of an extracted variable.
1639  virtual void SetVariableInteger(int index, bool integer) = 0;
1640 
1641  // Modify bounds of an extracted variable.
1642  virtual void SetConstraintBounds(int index, double lb, double ub) = 0;
1643 
1644  // Adds a linear constraint.
1645  virtual void AddRowConstraint(MPConstraint* const ct) = 0;
1646 
1647  // Adds an indicator constraint. Returns true if the feature is supported by
1648  // the underlying solver.
1649  virtual bool AddIndicatorConstraint(MPConstraint* const ct) {
1650  LOG(ERROR) << "Solver doesn't support indicator constraints.";
1651  return false;
1652  }
1653 
1654  // Add a variable.
1655  virtual void AddVariable(MPVariable* const var) = 0;
1656 
1657  // Changes a coefficient in a constraint.
1658  virtual void SetCoefficient(MPConstraint* const constraint,
1659  const MPVariable* const variable,
1660  double new_value, double old_value) = 0;
1661 
1662  // Clears a constraint from all its terms.
1663  virtual void ClearConstraint(MPConstraint* const constraint) = 0;
1664 
1665  // Changes a coefficient in the linear objective.
1666  virtual void SetObjectiveCoefficient(const MPVariable* const variable,
1667  double coefficient) = 0;
1668 
1669  // Changes the constant term in the linear objective.
1670  virtual void SetObjectiveOffset(double value) = 0;
1671 
1672  // Clears the objective from all its terms.
1673  virtual void ClearObjective() = 0;
1674 
1675  virtual void BranchingPriorityChangedForVariable(int var_index) {}
1676  // ------ Query statistics on the solution and the solve ------
1677  // Returns the number of simplex iterations. The problem must be discrete,
1678  // otherwise it crashes, or returns kUnknownNumberOfIterations in NDEBUG mode.
1679  virtual int64 iterations() const = 0;
1680  // Returns the number of branch-and-bound nodes. The problem must be discrete,
1681  // otherwise it crashes, or returns kUnknownNumberOfNodes in NDEBUG mode.
1682  virtual int64 nodes() const = 0;
1683  // Returns the best objective bound. The problem must be discrete, otherwise
1684  // it crashes, or returns trivial_worst_objective_bound() in NDEBUG mode.
1685  virtual double best_objective_bound() const = 0;
1686  // A trivial objective bound: the worst possible value of the objective,
1687  // which will be +infinity if minimizing and -infinity if maximing.
1688  double trivial_worst_objective_bound() const;
1689  // Returns the objective value of the best solution found so far.
1690  double objective_value() const;
1691 
1692  // Returns the basis status of a row.
1693  virtual MPSolver::BasisStatus row_status(int constraint_index) const = 0;
1694  // Returns the basis status of a constraint.
1695  virtual MPSolver::BasisStatus column_status(int variable_index) const = 0;
1696 
1697  // Checks whether the solution is synchronized with the model, i.e. whether
1698  // the model has changed since the solution was computed last.
1699  // If it isn't, it crashes in NDEBUG, and returns false othwerwise.
1700  bool CheckSolutionIsSynchronized() const;
1701  // Checks whether a feasible solution exists. The behavior is similar to
1702  // CheckSolutionIsSynchronized() above.
1703  virtual bool CheckSolutionExists() const;
1704  // Handy shortcut to do both checks above (it is often used).
1707  }
1708  // Checks whether information on the best objective bound exists. The behavior
1709  // is similar to CheckSolutionIsSynchronized() above.
1710  virtual bool CheckBestObjectiveBoundExists() const;
1711 
1712  // ----- Misc -----
1713  // Queries problem type. For simplicity, the distinction between
1714  // continuous and discrete is based on the declaration of the user
1715  // when the solver is created (example: GLPK_LINEAR_PROGRAMMING
1716  // vs. GLPK_MIXED_INTEGER_PROGRAMMING), not on the actual content of
1717  // the model.
1718  // Returns true if the problem is continuous.
1719  virtual bool IsContinuous() const = 0;
1720  // Returns true if the problem is continuous and linear.
1721  virtual bool IsLP() const = 0;
1722  // Returns true if the problem is discrete and linear.
1723  virtual bool IsMIP() const = 0;
1724 
1725  // Returns the index of the last variable extracted.
1727 
1728  bool variable_is_extracted(int var_index) const {
1729  return solver_->variable_is_extracted_[var_index];
1730  }
1731  void set_variable_as_extracted(int var_index, bool extracted) {
1732  solver_->variable_is_extracted_[var_index] = extracted;
1733  }
1734  bool constraint_is_extracted(int ct_index) const {
1735  return solver_->constraint_is_extracted_[ct_index];
1736  }
1737  void set_constraint_as_extracted(int ct_index, bool extracted) {
1738  solver_->constraint_is_extracted_[ct_index] = extracted;
1739  }
1740 
1741  // Returns the boolean indicating the verbosity of the solver output.
1742  bool quiet() const { return quiet_; }
1743  // Sets the boolean indicating the verbosity of the solver output.
1744  void set_quiet(bool quiet_value) { quiet_ = quiet_value; }
1745 
1746  // Returns the result status of the last solve.
1749  return result_status_;
1750  }
1751 
1752  // Returns a std::string describing the underlying solver and its version.
1753  virtual std::string SolverVersion() const = 0;
1754 
1755  // Returns the underlying solver.
1756  virtual void* underlying_solver() = 0;
1757 
1758  // Computes exact condition number. Only available for continuous
1759  // problems and only implemented in GLPK.
1760  virtual double ComputeExactConditionNumber() const;
1761 
1762  // See MPSolver::SetStartingLpBasis().
1763  virtual void SetStartingLpBasis(
1764  const std::vector<MPSolver::BasisStatus>& variable_statuses,
1765  const std::vector<MPSolver::BasisStatus>& constraint_statuses) {
1766  LOG(FATAL) << "Not supported by this solver.";
1767  }
1768 
1769  virtual bool InterruptSolve() { return false; }
1770 
1771  // See MPSolver::NextSolution() for contract.
1772  virtual bool NextSolution() { return false; }
1773 
1774  friend class MPSolver;
1775 
1776  // To access the maximize_ bool and the MPSolver.
1777  friend class MPConstraint;
1778  friend class MPObjective;
1779 
1780  protected:
1782  // Indicates whether the model and the solution are synchronized.
1784  // Indicates whether the solve has reached optimality,
1785  // infeasibility, a limit, etc.
1787  // Optimization direction.
1789 
1790  // Index in MPSolver::variables_ of last constraint extracted.
1792  // Index in MPSolver::constraints_ of last variable extracted.
1794 
1795  // The value of the objective function.
1797 
1798  // Boolean indicator for the verbosity of the solver output.
1799  bool quiet_;
1800 
1801  // Index of dummy variable created for empty constraints or the
1802  // objective offset.
1803  static const int kDummyVariableIndex;
1804 
1805  // Extracts model stored in MPSolver.
1806  void ExtractModel();
1807  // Extracts the variables that have not been extracted yet.
1808  virtual void ExtractNewVariables() = 0;
1809  // Extracts the constraints that have not been extracted yet.
1810  virtual void ExtractNewConstraints() = 0;
1811  // Extracts the objective.
1812  virtual void ExtractObjective() = 0;
1813  // Resets the extraction information.
1815  // Change synchronization status from SOLUTION_SYNCHRONIZED to
1816  // MODEL_SYNCHRONIZED. To be used for model changes.
1818 
1819  // Sets parameters common to LP and MIP in the underlying solver.
1820  void SetCommonParameters(const MPSolverParameters& param);
1821  // Sets MIP specific parameters in the underlying solver.
1822  void SetMIPParameters(const MPSolverParameters& param);
1823  // Sets all parameters in the underlying solver.
1824  virtual void SetParameters(const MPSolverParameters& param) = 0;
1825  // Sets an unsupported double parameter.
1827  // Sets an unsupported integer parameter.
1828  virtual void SetUnsupportedIntegerParam(
1830  // Sets a supported double parameter to an unsupported value.
1832  double value);
1833  // Sets a supported integer parameter to an unsupported value.
1834  virtual void SetIntegerParamToUnsupportedValue(
1835  MPSolverParameters::IntegerParam param, int value);
1836  // Sets each parameter in the underlying solver.
1837  virtual void SetRelativeMipGap(double value) = 0;
1838  virtual void SetPrimalTolerance(double value) = 0;
1839  virtual void SetDualTolerance(double value) = 0;
1840  virtual void SetPresolveMode(int value) = 0;
1841 
1842  // Sets the number of threads to be used by the solver.
1843  virtual util::Status SetNumThreads(int num_threads);
1844 
1845  // Pass solver specific parameters in text format. The format is
1846  // solver-specific and is the same as the corresponding solver configuration
1847  // file format. Returns true if the operation was successful.
1848  //
1849  // The default implementation of this method stores the parameters in a
1850  // temporary file and calls ReadParameterFile to import the parameter file
1851  // into the solver. Solvers that support passing the parameters directly can
1852  // override this method to skip the temporary file logic.
1854  const std::string& parameters);
1855 
1856  // Reads a solver-specific file of parameters and set them.
1857  // Returns true if there was no errors.
1858  virtual bool ReadParameterFile(const std::string& filename);
1859 
1860  // Returns a file extension like ".tmp", this is needed because some solvers
1861  // require a given extension for the ReadParameterFile() filename and we need
1862  // to know it to generate a temporary parameter file.
1863  virtual std::string ValidFileExtensionForParameterFile() const;
1864 
1865  // Sets the scaling mode.
1866  virtual void SetScalingMode(int value) = 0;
1867  virtual void SetLpAlgorithm(int value) = 0;
1868 };
1869 
1870 } // namespace operations_research
1871 
1872 #endif // OR_TOOLS_LINEAR_SOLVER_LINEAR_SOLVER_H_
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...
Advanced usage: incrementality from one solve to the next.
virtual util::Status SetNumThreads(int num_threads)
double GetCoefficient(const MPVariable *const var) const
Gets the coefficient of a given variable in the objective.
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...
virtual MPSolver::BasisStatus column_status(int variable_index) const =0
bool integer() const
Returns the integrality requirement of the variable.
void SetIntegerParam(MPSolverParameters::IntegerParam param, int value)
Sets a integer parameter to a specific value.
void set_variable_as_extracted(int var_index, bool extracted)
void * underlying_solver()
Advanced usage: returns the underlying solver.
virtual void SetIntegerParamToUnsupportedValue(MPSolverParameters::IntegerParam param, int value)
int branching_priority() const
Advanced usage: Certain MIP solvers (e.g.
void Clear()
Clears the offset, all variables and coefficients, and the optimization direction.
IntegerParam
Enumeration of parameters that take integer or categorical values.
This mathematical programming (MP) solver class is the main class though which users build and solve ...
void SetCommonParameters(const MPSolverParameters &param)
const std::vector< MPVariable * > & variables() const
Returns the array of variables handled by the MPSolver.
void SetLB(double lb)
Sets the lower bound.
double reduced_cost() const
Advanced usage: returns the reduced cost of the variable in the current solution (only available for ...
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
int64 iterations() const
Returns the number of simplex iterations.
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the constraint.
MPVariable * LookupVariableOrNull(const std::string &var_name) const
Looks up a variable by name, and returns nullptr if it does not exist.
virtual void Write(const std::string &filename)
void SetHint(std::vector< std::pair< const MPVariable *, double > > hint)
Set a hint for solution.
the model is trivially invalid (NaN coefficients, etc).
void MakeBoolVarArray(int nb, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of boolean variables.
MPSolver(const std::string &name, OptimizationProblemType problem_type)
Create a solver with the given name and underlying solver backend.
virtual double best_objective_bound() const =0
void set_is_lazy(bool laziness)
Advanced usage: sets the constraint "laziness".
virtual void SetUnsupportedIntegerParam(MPSolverParameters::IntegerParam param)
Mixed integer Programming Solver using Coin CBC.
virtual MPSolver::ResultStatus Solve(const MPSolverParameters &param)=0
const std::string & name() const
Returns the name of the variable.
bool is_lazy() const
Advanced usage: returns true if the constraint is "lazy" (see below).
static bool ParseSolverType(absl::string_view solver, OptimizationProblemType *type)
Parses the name of the solver.
double offset() const
Gets the constant term in the objective.
const MPObjective & Objective() const
Returns the objective object.
void set_solution_value(double value)
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable in the objective.
void SetOptimizationDirection(bool maximize)
Sets the optimization direction (maximize: true or minimize: false).
bool variable_is_extracted(int var_index) const
virtual bool AddIndicatorConstraint(MPConstraint *const ct)
bool constraint_is_extracted(int ct_index) const
IncrementalityValues
Advanced usage: Incrementality options.
int index() const
Returns the index of the constraint in the MPSolver::constraints_.
void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
Advanced usage: Incrementality.
Reuse results from previous solve as much as the underlying solver allows.
bool ExportModelAsMpsFormat(bool fixed_format, bool obfuscate, std::string *model_str) const
void SetBranchingPriority(int priority)
MPVariable * MakeIntVar(double lb, double ub, const std::string &name)
Creates an integer variable.
virtual void SetCoefficient(MPConstraint *const constraint, const MPVariable *const variable, double new_value, double old_value)=0
void Clear()
Clears the objective (including the optimization direction), all variables and constraints.
virtual void SetScalingMode(int value)=0
constexpr double kDefaultPrimalTolerance
int NumVariables() const
Returns the number of variables.
double dual_value() const
Advanced usage: returns the dual value of the constraint in the current solution (only available for ...
virtual void SetDualTolerance(double value)=0
void SetCoefficient(const MPVariable *const var, double coeff)
Sets the coefficient of the variable on the constraint.
virtual std::string SolverVersion() const =0
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...
MPSolver::ResultStatus result_status() const
virtual std::string ValidFileExtensionForParameterFile() const
PresolveValues
For each categorical parameter, enumeration of possible values.
const MPVariable * indicator_variable() const
MPObjective * MutableObjective()
Returns the mutable objective object.
void ExportModelToProto(MPModelProto *output_model) const
Exports model to protocol buffer.
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...
void EnableOutput()
Enable output.
virtual void SetObjectiveCoefficient(const MPVariable *const variable, double coefficient)=0
int GetIntegerParam(MPSolverParameters::IntegerParam param) const
Returns the value of an integer parameter.
void SetMaximization()
Sets the optimization direction to maximize.
void SetDoubleParamToUnsupportedValue(MPSolverParameters::DoubleParam param, double value)
const absl::flat_hash_map< const MPVariable *, double > & terms() const
Returns a map from variables to their coefficients in the objective.
bool SetSolverSpecificParametersAsString(const std::string &parameters)
Advanced usage: pass solver specific parameters in text format.
Mixed integer Programming Solver using SCIP.
static const IncrementalityValues kDefaultIncrementality
virtual int64 nodes() const =0
ABSL_MUST_USE_RESULT bool NextSolution()
Some solvers (MIP only, not LP) can produce multiple solutions to the problem.
void MakeIntVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of integer variables.
virtual void ClearConstraint(MPConstraint *const constraint)=0
void Write(const std::string &file_name)
Writes the model using the solver internal write function.
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the variable in the current solution (only available for ...
virtual OptimizationProblemType ProblemType() const
Returns the optimization problem type set at construction.
void SuppressOutput()
Suppress output.
void Clear()
Clears all variables and coefficients.
void set_constraint_as_extracted(int ct_index, bool extracted)
void SetTimeLimit(absl::Duration time_limit)
MPSolverResponseStatus LoadModelFromProtoWithUniqueNamesOrDie(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
static bool SupportsProblemType(OptimizationProblemType problem_type)
Whether the given problem type is supported (this will depend on the targets that you linked).
double ComputeExactConditionNumber() const
Advanced usage: computes the exact condition number of the current scaled basis: L1norm(B) * L1norm(i...
bool minimization() const
Is the optimization direction set to minimize?
virtual void SetOptimizationDirection(bool maximize)=0
void AddLinearExpr(const LinearExpr &linear_expr)
Adds linear_expr to the current objective, does not change the direction.
void SetMinimization()
Sets the optimization direction to minimize.
void MinimizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to minimize linear_expr.
std::ostream & operator<<(std::ostream &os, MPSolver::OptimizationProblemType optimization_problem_type)
void MakeNumVarArray(int nb, double lb, double ub, const std::string &name, std::vector< MPVariable * > *vars)
Creates an array of continuous variables.
virtual bool CheckBestObjectiveBoundExists() const
bool VerifySolution(double tolerance, bool log_errors) const
Advanced usage: Verifies the correctness of the solution.
void ResetIntegerParam(MPSolverParameters::IntegerParam param)
Sets an integer parameter to its default value (default value defined in MPSolverParameters if it exi...
virtual bool SetSolverSpecificParametersAsString(const std::string &parameters)
int64 nodes() const
Returns the number of branch-and-bound nodes evaluated during the solve.
Linear Programming solver using GLOP (Recommended solver).
static double infinity()
Infinity.
bool OwnsVariable(const MPVariable *var) const
virtual void AddVariable(MPVariable *const var)=0
void MakeVarArray(int nb, double lb, double ub, bool integer, const std::string &name_prefix, std::vector< MPVariable * > *vars)
Creates an array of variables.
virtual void SetVariableBounds(int index, double lb, double ub)=0
void SetLB(double lb)
Sets the lower bound.
void SetMIPParameters(const MPSolverParameters &param)
void SetInteger(bool integer)
Sets the integrality requirement of the variable.
virtual void SetPrimalTolerance(double value)=0
void set_time_limit(int64 time_limit_milliseconds)
ResultStatus Solve()
Solves the problem using default parameter values.
MPConstraint * MakeRowConstraint()
Creates a constraint with -infinity and +infinity bounds.
void SetDoubleParam(MPSolverParameters::DoubleParam param, double value)
Sets a double parameter to a specific value.
OptimizationProblemType
The type of problems (LP or MIP) that will be solved and the underlying solver (GLOP,...
const std::string & Name() const
Returns the name of the model set at construction.
MPSolverParameters()
The constructor sets all parameters to their default value.
const absl::string_view ToString(MPSolver::OptimizationProblemType optimization_problem_type)
BasisStatus
Advanced usage: possible basis status values for a variable and the slack variable of a linear constr...
MPSolver::BasisStatus basis_status() const
Advanced usage: returns the basis status of the constraint.
ResultStatus
The status of solving the problem.
Advanced usage: tolerance for primal feasibility of basic solutions.
virtual void SetVariableInteger(int index, bool integer)=0
double BestBound() const
Returns the best objective bound.
virtual MPSolver::BasisStatus row_status(int constraint_index) const =0
double ub() const
Returns the upper bound.
This class stores parameter settings for LP and MIP solvers.
const std::string & name() const
Returns the name of the constraint.
The class for constraints of a Mathematical Programming (MP) model.
virtual void BranchingPriorityChangedForVariable(int var_index)
int NumConstraints() const
Returns the number of constraints.
void set_dual_value(double dual_value)
double unrounded_solution_value() const
Advanced usage: unrounded solution value.
std::vector< double > ComputeConstraintActivities() const
Advanced usage: compute the "activities" of all constraints, which are the sums of their linear terms...
util::Status SetNumThreads(int num_threads)
Sets the number of threads to use by the underlying solver.
ScalingValues
Advanced usage: Scaling options.
std::string AbslUnparseFlag(MPSolver::OptimizationProblemType solver_type)
bool AbslParseFlag(absl::string_view text, MPSolver::OptimizationProblemType *solver_type, std::string *error)
abnormal, i.e., error of some kind.
MPVariable(int index, double lb, double ub, bool integer, const std::string &name, MPSolverInterface *const interface_in)
void SetUB(double ub)
Sets the upper bound.
bool ExportModelAsLpFormat(bool obfuscate, std::string *model_str) const
Shortcuts to the homonymous MPModelProtoExporter methods, via exporting to a MPModelProto with Export...
void Reset()
Sets all parameters to their default value.
absl::Duration DurationSinceConstruction() const
void ResetDoubleParam(MPSolverParameters::DoubleParam param)
Sets a double parameter to its default value (default value defined in MPSolverParameters if it exist...
MPSolverResponseStatus LoadModelFromProto(const MPModelProto &input_model, std::string *error_message)
Loads model from protocol buffer.
virtual void AddRowConstraint(MPConstraint *const ct)=0
Linear Programming solver using Coin CBC.
std::string SolverVersion() const
Returns a std::string describing the underlying solver and its version.
virtual double ComputeExactConditionNumber() const
MPVariable * MakeNumVar(double lb, double ub, const std::string &name)
Creates a continuous variable.
MPConstraint(int index, double lb, double ub, const std::string &name, MPSolverInterface *const interface_in)
MPSolverInterface(MPSolver *const solver)
void SetUnsupportedDoubleParam(MPSolverParameters::DoubleParam param)
MPVariable * MakeBoolVar(const std::string &name)
Creates a boolean variable.
bool maximization() const
Is the optimization direction set to maximize?
int GetNumThreads() const
Returns the number of threads to be used during solve.
MPConstraint * LookupConstraintOrNull(const std::string &constraint_name) const
Looks up a constraint by name, and returns nullptr if it does not exist.
virtual void SetObjectiveOffset(double value)=0
The class for variables of a Mathematical Programming (MP) model.
virtual bool ReadParameterFile(const std::string &filename)
void SetBounds(double lb, double ub)
Sets both the lower and upper bounds.
Advanced usage: tolerance for dual feasibility of basic solutions.
virtual void SetPresolveMode(int value)=0
virtual void SetParameters(const MPSolverParameters &param)=0
double ub() const
Returns the upper bound.
MPVariable * MakeVar(double lb, double ub, bool integer, const std::string &name)
Creates a variable with the given bounds, integrality requirement and name.
void MaximizeLinearExpr(const LinearExpr &linear_expr)
Resets the current objective to maximize linear_expr.
util::Status ClampSolutionWithinBounds()
Resets values of out of bound variables to the corresponding bound and returns an error if any of the...
feasible, or stopped by limit.
static const PresolveValues kDefaultPresolve
bool InterruptSolve()
Interrupts the Solve() execution to terminate processing if possible.
Advanced usage: enable or disable matrix scaling.
double GetDoubleParam(MPSolverParameters::DoubleParam param) const
Returns the value of a double parameter.
void SetUB(double ub)
Sets the upper bound.
virtual bool CheckSolutionExists() const
double lb() const
Returns the lower bound.
std::string GetSolverSpecificParametersAsString() const
void FillSolutionResponseProto(MPSolutionResponse *response) const
Encodes the current solution in a solution response protocol buffer.
const std::vector< MPConstraint * > & constraints() const
Returns the array of constraints handled by the MPSolver.
DoubleParam
Enumeration of parameters that take continuous values.
virtual int64 iterations() const =0
bool OutputIsEnabled() const
Controls (or queries) the amount of output produced by the underlying solver.
double lb() const
Returns the lower bound.
double solution_value() const
Returns the value of the variable in the current solution.
void set_reduced_cost(double reduced_cost)
void SetOffset(double value)
Sets the constant term in the objective.
absl::Duration TimeLimit() const
virtual void SetRelativeMipGap(double value)=0
int index() const
Returns the index of the variable in the MPSolver::variables_.
A class to express a linear objective.
virtual void SetConstraintBounds(int index, double lb, double ub)=0
virtual bool IsContinuous() const =0
virtual void SetLpAlgorithm(int value)=0
virtual void SetStartingLpBasis(const std::vector< MPSolver::BasisStatus > &variable_statuses, const std::vector< MPSolver::BasisStatus > &constraint_statuses)
void Reset()
Advanced usage: resets extracted model to solve from scratch.
double Value() const
Returns the objective value of the best solution found so far.